package github import ( "crypto/rsa" "crypto/x509" "encoding/pem" "errors" "maps" "strings" "testing" "time" "github.com/prometheus/client_golang/prometheus" "tangled.org/guid.foo/lanyard/github/githubtest" ) const clientID = "Iv23liEXAMPLE" // world is a GitHub where the App example-app is installed on // example-org, which has the repository widgets and the fork borrowed. type world struct { fake *githubtest.Fake registry *prometheus.Registry client *Client tokens *Tokens minted []string } func newWorld(t *testing.T) *world { t.Helper() fake := githubtest.Start(t) fake.AddApp(clientID, "example-app", map[string]string{"contents": "write", "issues": "read", "metadata": "read"}) fake.Install(clientID, "example-org") fake.AddRepository("example-org", "widgets", false) fake.AddRepository("example-org", "borrowed", true) registry := prometheus.NewRegistry() w := &world{fake: fake, registry: registry, client: New(fake.URL, registry)} w.tokens = NewTokens(w.client, func(owner string) { w.minted = append(w.minted, owner) }) return w } func (w *world) request(repository string, permissions, forkPermissions map[string]string) Request { return Request{ ClientID: clientID, Key: func() (*rsa.PrivateKey, error) { return githubtest.Key(), nil }, Owner: "example-org", Repository: repository, Permissions: permissions, ForkPermissions: forkPermissions, } } var ( write = map[string]string{"contents": "write"} read = map[string]string{"contents": "read"} ) func TestGitHubNamesAnAppWhoseKeyItAccepts(t *testing.T) { w := newWorld(t) slug, err := w.client.Slug(t.Context(), App{ClientID: clientID, Key: githubtest.Key()}) if err != nil || slug != "example-app" { t.Errorf("Slug = %q, %v, want example-app", slug, err) } } func TestGitHubRefusesAnAppItCannotIdentify(t *testing.T) { other, err := ParseKey(githubtest.OtherKeyPEM()) if err != nil { t.Fatal(err) } cases := []struct { name string app App want error }{ {"a client ID it does not know", App{ClientID: "Iv23liOTHER", Key: githubtest.Key()}, ErrUnknownApp}, {"a key that is not the App's", App{ClientID: clientID, Key: other}, ErrRefused}, } for _, c := range cases { t.Run(c.name, func(t *testing.T) { w := newWorld(t) if _, err := w.client.Slug(t.Context(), c.app); !errors.Is(err, c.want) { t.Errorf("Slug answered %v, want %v", err, c.want) } if _, _, err := w.client.Mint(t.Context(), c.app, "example-org", "widgets", write); !errors.Is(err, c.want) { t.Errorf("Mint answered %v, want %v", err, c.want) } }) } } func TestATokenIsForOneRepositoryAndItsPermissions(t *testing.T) { w := newWorld(t) token, err := w.tokens.Get(t.Context(), w.request("widgets", write, nil)) if err != nil { t.Fatal(err) } issued := w.fake.Tokens() if len(issued) != 1 { t.Fatalf("GitHub gave %d tokens, want 1", len(issued)) } if issued[0].Token != token.Value || issued[0].Repository != "example-org/widgets" || !maps.Equal(issued[0].Permissions, write) { t.Errorf("GitHub gave %+v, and lanyard answered %q", issued[0], token.Value) } if left := time.Until(token.ExpiresAt); left < 50*time.Minute { t.Errorf("the token has %s left, want most of an hour", left) } if len(w.minted) != 1 || w.minted[0] != "example-org" { t.Errorf("minted = %v, want one for example-org", w.minted) } } func TestASecondRequestGetsTheSameTokenUntilItIsNearItsEnd(t *testing.T) { w := newWorld(t) first, _ := w.tokens.Get(t.Context(), w.request("widgets", write, nil)) second, _ := w.tokens.Get(t.Context(), w.request("Widgets", write, nil)) if first.Value != second.Value { t.Errorf("the second request got %q, want the first token %q", second.Value, first.Value) } w.client.now = func() time.Time { return time.Now().Add(55 * time.Minute) } third, err := w.tokens.Get(t.Context(), w.request("widgets", write, nil)) if err != nil { t.Fatal(err) } if third.Value == first.Value { t.Error("a request near the token's end got the old token, want a new one") } } func TestOtherPermissionsGetAnotherToken(t *testing.T) { w := newWorld(t) writing, _ := w.tokens.Get(t.Context(), w.request("widgets", write, nil)) reading, err := w.tokens.Get(t.Context(), w.request("widgets", read, nil)) if err != nil { t.Fatal(err) } if reading.Value == writing.Value { t.Error("a request for read got the token that writes") } } func TestRefusals(t *testing.T) { cases := []struct { name string repository string permissions map[string]string want error }{ {"a repository that does not exist", "nothing", write, ErrNotInstalled}, {"a permission the App lacks", "widgets", map[string]string{"issues": "write"}, ErrPermissions}, {"a permission the App has never heard of", "widgets", map[string]string{"workflows": "write"}, ErrPermissions}, } for _, c := range cases { t.Run(c.name, func(t *testing.T) { w := newWorld(t) _, err := w.tokens.Get(t.Context(), w.request(c.repository, c.permissions, nil)) if !errors.Is(err, c.want) { t.Errorf("Get answered %v, want %v", err, c.want) } }) } } func TestAnOwnerWithNoInstallationGetsNothing(t *testing.T) { w := newWorld(t) w.fake.AddRepository("elsewhere", "widgets", false) request := w.request("widgets", write, nil) request.Owner = "elsewhere" if _, err := w.tokens.Get(t.Context(), request); !errors.Is(err, ErrNotInstalled) { t.Errorf("Get answered %v, want ErrNotInstalled", err) } } func TestAForkWithNoForkPermissionsGetsNothing(t *testing.T) { w := newWorld(t) _, err := w.tokens.Get(t.Context(), w.request("borrowed", write, nil)) if !errors.Is(err, ErrFork) { t.Fatalf("Get answered %v, want ErrFork", err) } issued := w.fake.Tokens() if len(issued) != 1 || !issued[0].Revoked { t.Errorf("GitHub's tokens are %+v, want the one token revoked", issued) } // The second request knows the repository is a fork, and asks // GitHub for nothing. if _, err := w.tokens.Get(t.Context(), w.request("borrowed", write, nil)); !errors.Is(err, ErrFork) { t.Errorf("the second Get answered %v, want ErrFork", err) } if len(w.fake.Tokens()) != 1 { t.Errorf("GitHub gave %d tokens, want still 1", len(w.fake.Tokens())) } } func TestAForkGetsOnlyTheForkPermissions(t *testing.T) { w := newWorld(t) token, err := w.tokens.Get(t.Context(), w.request("borrowed", write, read)) if err != nil { t.Fatal(err) } issued := w.fake.Tokens() if len(issued) != 2 { t.Fatalf("GitHub gave %d tokens, want the wide one and the narrow one", len(issued)) } if !issued[0].Revoked || !maps.Equal(issued[0].Permissions, write) { t.Errorf("the first token is %+v, want the writing token revoked", issued[0]) } if issued[1].Revoked || issued[1].Token != token.Value || !maps.Equal(issued[1].Permissions, read) { t.Errorf("the second token is %+v, want the reading token that lanyard answered", issued[1]) } } func TestAForkWhoseEntriesAllAllowForksKeepsItsFirstToken(t *testing.T) { w := newWorld(t) token, err := w.tokens.Get(t.Context(), w.request("borrowed", write, write)) if err != nil { t.Fatal(err) } issued := w.fake.Tokens() if len(issued) != 1 || issued[0].Revoked || issued[0].Token != token.Value { t.Errorf("GitHub's tokens are %+v, want the one token, in use", issued) } } func TestParseKey(t *testing.T) { key := githubtest.Key() pkcs8, _ := x509.MarshalPKCS8PrivateKey(key) joined := strings.ReplaceAll(strings.TrimSpace(string(githubtest.KeyPEM())), "\n", " ") cases := []struct { name string text []byte ok bool }{ {"PKCS #1, as GitHub gives it", githubtest.KeyPEM(), true}, {"PKCS #8", pem.EncodeToMemory(&pem.Block{Type: "PRIVATE KEY", Bytes: pkcs8}), true}, {"line breaks turned into spaces", []byte(joined), true}, {"not PEM", []byte("a password"), false}, {"PEM of something else", pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: []byte("no")}), false}, } for _, c := range cases { t.Run(c.name, func(t *testing.T) { parsed, err := ParseKey(c.text) if c.ok != (err == nil) { t.Fatalf("ParseKey answered %v", err) } if c.ok && !parsed.Equal(key) { t.Error("ParseKey answered another key") } }) } }