package podapi import ( "bytes" "encoding/json" "io" "log/slog" "maps" "net/http" "net/http/httptest" "slices" "strings" "testing" "tangled.org/guid.foo/lanyard/api/v1alpha1" "tangled.org/guid.foo/lanyard/atproto" "tangled.org/guid.foo/lanyard/atproto/atprototest" "tangled.org/guid.foo/lanyard/cluster" "tangled.org/guid.foo/lanyard/cluster/clustertest" "tangled.org/guid.foo/lanyard/gitea" "tangled.org/guid.foo/lanyard/gitea/giteatest" "tangled.org/guid.foo/lanyard/github" "tangled.org/guid.foo/lanyard/github/githubtest" "tangled.org/guid.foo/lanyard/metrics" ) const ( clientID = "Iv23liEXAMPLE" forgePassword = "correct horse battery staple" giteaPassword = "tr0ub4dor&3" atprotoPassword = "abcd-efgh-ijkl-mnop" claudeDID = "did:plc:abcdefghijklmnopqrstuvwx" knot = "did:web:knot.example.com" receivePack = "org.tangled.git.receivePack" ) // world is a cluster, a GitHub, a Gitea, and a PDS with one of // everything. The App example-app is installed on example-org, which has // the repository widgets and the fork borrowed, and lanyard's namespace // holds its key. The GiteaAccount forge is the user claude on the Gitea, // and lanyard's namespace holds claude's password. The AtprotoAccount // claude is claude.example.com on the PDS, and lanyard's namespace holds // its app password. In the namespace agents, the pod fixer-1 runs as // fixer with the token "fixer-token". fixer holds the Badge reads, which // reads example-org's contents and issues, reads forge's repositories // and issues, gives claude's push tokens for the knot, and gives the // secret forge, and the Badge writes, which writes example-org's // contents and forge's repositories and gives claude's session. reader // holds reads alone. type world struct { cluster *clustertest.Fake github *githubtest.Fake gitea *giteatest.Fake pds *atprototest.Fake url string log *bytes.Buffer metrics *metrics.Metrics } func newWorld(t *testing.T) *world { t.Helper() fake, c := clustertest.Start(t) hub := githubtest.Start(t) hub.AddApp(clientID, "example-app", map[string]string{"contents": "write", "issues": "read"}) hub.Install(clientID, "example-org") hub.AddRepository("example-org", "widgets", false) hub.AddRepository("example-org", "borrowed", true) forge := giteatest.Start(t) forge.AddUser("claude", giteaPassword) pds := atprototest.Start(t) pds.AddAccount("claude.example.com", claudeDID, atprotoPassword) fake.AddSecret("lanyard-system", "gitea-forge", map[string]string{"password": giteaPassword}) fake.AddGiteaAccount(v1alpha1.GiteaAccount{ Metadata: v1alpha1.ObjectMeta{Name: "forge"}, Spec: v1alpha1.GiteaAccountSpec{URL: forge.URL, Username: "claude", Password: v1alpha1.Password{ SecretKeyRef: v1alpha1.SecretKeySelector{Name: "gitea-forge", Key: "password"}}}, }) fake.AddSecret("lanyard-system", "atproto-claude", map[string]string{"password": atprotoPassword}) fake.AddAtprotoAccount(v1alpha1.AtprotoAccount{ Metadata: v1alpha1.ObjectMeta{Name: "claude"}, Spec: v1alpha1.AtprotoAccountSpec{PDS: pds.URL, Identifier: "claude.example.com", AppPassword: v1alpha1.Password{ SecretKeyRef: v1alpha1.SecretKeySelector{Name: "atproto-claude", Key: "password"}}}, }) fake.AddSecret("lanyard-system", "github-app-example-org", map[string]string{"private-key": string(githubtest.KeyPEM())}) fake.AddGitHubApp(v1alpha1.GitHubApp{ Metadata: v1alpha1.ObjectMeta{Name: "example-org"}, Spec: v1alpha1.GitHubAppSpec{ClientID: clientID, PrivateKey: v1alpha1.PrivateKey{ SecretKeyRef: v1alpha1.SecretKeySelector{Name: "github-app-example-org", Key: "private-key"}}}, }) fake.AddBadge(v1alpha1.Badge{ Metadata: v1alpha1.ObjectMeta{Namespace: "agents", Name: "reads"}, Spec: v1alpha1.BadgeSpec{ ServiceAccounts: []string{"fixer", "reader"}, GitHub: []v1alpha1.GitHubEntry{{Owners: []string{"example-org"}, Permissions: map[string]string{"contents": "read", "issues": "read"}}}, Gitea: []v1alpha1.GiteaEntry{{Accounts: []string{"forge"}, Scopes: []string{"read:repository", "read:issue"}}}, Atproto: []v1alpha1.AtprotoEntry{{Accounts: []string{"claude"}, Services: []v1alpha1.AtprotoService{{Audience: knot, Methods: []string{receivePack}}}}}, Secrets: []v1alpha1.SecretEntry{{Name: "forge", SecretRef: v1alpha1.LocalSecretReference{Name: "forge-login"}}}, }, }) fake.AddBadge(v1alpha1.Badge{ Metadata: v1alpha1.ObjectMeta{Namespace: "agents", Name: "writes"}, Spec: v1alpha1.BadgeSpec{ ServiceAccounts: []string{"fixer"}, GitHub: []v1alpha1.GitHubEntry{{Owners: []string{"example-org"}, Permissions: map[string]string{"contents": "write"}}}, Gitea: []v1alpha1.GiteaEntry{{Accounts: []string{"forge"}, Scopes: []string{"write:repository"}}}, Atproto: []v1alpha1.AtprotoEntry{{Accounts: []string{"claude"}, Session: true}}, }, }) fake.AddSecret("agents", "forge-login", map[string]string{"username": "fixer", "password": forgePassword}) addPod(fake, "agents", "fixer-1", "fixer", "Running") addToken(fake, "fixer-token", "agents", "fixer-1", "fixer") log := &bytes.Buffer{} m := metrics.New("test") tokens := github.NewTokens(github.New(hub.URL, m.Registry), m.TokenMinted) giteaTokens := gitea.NewTokens(gitea.New(m.Registry), m.GiteaTokenMinted) atprotoTokens := atproto.NewTokens(atproto.New(m.Registry), m.AtprotoTokenMinted) issuers := Issuers{GitHub: tokens, Gitea: giteaTokens, Atproto: atprotoTokens} api := New("lanyard-system", c, issuers, slog.New(slog.NewJSONHandler(log, &slog.HandlerOptions{Level: slog.LevelDebug})), m) server := httptest.NewServer(api.Handler()) t.Cleanup(server.Close) return &world{cluster: fake, github: hub, gitea: forge, pds: pds, url: server.URL, log: log, metrics: m} } func addPod(fake *clustertest.Fake, namespace, name, account, phase string) { fake.AddPod(cluster.Pod{Namespace: namespace, Name: name, UID: name + "-uid", Phase: phase, ServiceAccount: account}) } func addToken(fake *clustertest.Fake, token, namespace, pod, account string) { fake.AddToken(token, clustertest.Token{Namespace: namespace, ServiceAccount: account, Pod: pod, PodUID: pod + "-uid", Audiences: []string{"lanyard"}}) } // get sends one request with a token, and answers the status and the // body. func (w *world) get(t *testing.T, path, token string) (int, string) { t.Helper() request, _ := http.NewRequest(http.MethodGet, w.url+path, nil) if token != "" { request.Header.Set("Authorization", "Bearer "+token) } response, err := http.DefaultClient.Do(request) if err != nil { t.Fatal(err) } defer response.Body.Close() body, _ := io.ReadAll(response.Body) return response.StatusCode, string(body) } func TestAPodGetsATokenWithItsBadgesCombined(t *testing.T) { w := newWorld(t) status, body := w.get(t, "/v1/github/example-org/widgets", "fixer-token") if status != http.StatusOK { t.Fatalf("status %d: %s", status, body) } var answered Token json.Unmarshal([]byte(body), &answered) issued := w.github.Tokens() if len(issued) != 1 || issued[0].Token != answered.Token || issued[0].Repository != "example-org/widgets" { t.Fatalf("GitHub gave %+v, and lanyard answered %q", issued, answered.Token) } want := map[string]string{"contents": "write", "issues": "read"} if !maps.Equal(issued[0].Permissions, want) { t.Errorf("the token's permissions are %v, want %v", issued[0].Permissions, want) } if answered.ExpiresAt.IsZero() { t.Error("the answer has no expiresAt") } } func TestAPodThatHoldsOneBadgeGetsOnlyThatBadge(t *testing.T) { w := newWorld(t) addPod(w.cluster, "agents", "reader-1", "reader", "Running") addToken(w.cluster, "reader-token", "agents", "reader-1", "reader") if status, body := w.get(t, "/v1/github/example-org/widgets", "reader-token"); status != http.StatusOK { t.Fatalf("status %d: %s", status, body) } want := map[string]string{"contents": "read", "issues": "read"} if got := w.github.Tokens()[0].Permissions; !maps.Equal(got, want) { t.Errorf("the token's permissions are %v, want %v", got, want) } } func TestWhoGetsNothing(t *testing.T) { cases := []struct { name string setup func(*world) token string status int }{ {name: "a request with no token", token: "", status: http.StatusUnauthorized}, {name: "a token nobody issued", token: "made-up", status: http.StatusUnauthorized}, { name: "a token for another audience", setup: func(w *world) { w.cluster.AddToken("api-token", clustertest.Token{Namespace: "agents", ServiceAccount: "fixer", Pod: "fixer-1", PodUID: "fixer-1-uid", Audiences: []string{"https://kubernetes.default.svc"}}) }, token: "api-token", status: http.StatusUnauthorized, }, { name: "a token that is not bound to a pod", setup: func(w *world) { w.cluster.AddToken("loose-token", clustertest.Token{Namespace: "agents", ServiceAccount: "fixer", Audiences: []string{"lanyard"}}) }, token: "loose-token", status: http.StatusUnauthorized, }, { name: "a pod that has finished", setup: func(w *world) { addPod(w.cluster, "agents", "fixer-1", "fixer", "Succeeded") }, token: "fixer-token", status: http.StatusForbidden, }, { name: "a pod that is gone", setup: func(w *world) { w.cluster.Delete("/api/v1/namespaces/agents/pods/fixer-1") }, token: "fixer-token", status: http.StatusForbidden, }, { name: "a newer pod of the same name", setup: func(w *world) { w.cluster.AddPod(cluster.Pod{Namespace: "agents", Name: "fixer-1", UID: "another-uid", Phase: "Running", ServiceAccount: "fixer"}) }, token: "fixer-token", status: http.StatusForbidden, }, { name: "a pod that runs as another ServiceAccount", setup: func(w *world) { addPod(w.cluster, "agents", "fixer-1", "other", "Running") }, token: "fixer-token", status: http.StatusForbidden, }, { name: "a ServiceAccount that no Badge names", setup: func(w *world) { addPod(w.cluster, "agents", "stranger-1", "stranger", "Running") addToken(w.cluster, "stranger-token", "agents", "stranger-1", "stranger") }, token: "stranger-token", status: http.StatusForbidden, }, { name: "a ServiceAccount of the same name in another namespace", setup: func(w *world) { addPod(w.cluster, "elsewhere", "fixer-1", "fixer", "Running") addToken(w.cluster, "elsewhere-token", "elsewhere", "fixer-1", "fixer") }, token: "elsewhere-token", status: http.StatusForbidden, }, } for _, c := range cases { t.Run(c.name, func(t *testing.T) { w := newWorld(t) if c.setup != nil { c.setup(w) } for _, path := range []string{"/v1/github/example-org/widgets", "/v1/gitea/forge", "/v1/secrets/reads/forge"} { if status, body := w.get(t, path, c.token); status != c.status { t.Errorf("%s answered %d, want %d: %s", path, status, c.status, body) } } if issued := w.github.Tokens(); len(issued) != 0 { t.Errorf("GitHub gave %d tokens, want none", len(issued)) } if made := w.gitea.Tokens("claude"); len(made) != 0 { t.Errorf("Gitea made %d tokens, want none", len(made)) } }) } } func TestWhatAPodIsRefused(t *testing.T) { cases := []struct { name string setup func(*world) path string status int reason string }{ {name: "an owner no Badge names", path: "/v1/github/elsewhere/widgets", status: http.StatusForbidden, reason: "names the owner elsewhere"}, { name: "an owner with no GitHubApp", setup: func(w *world) { w.cluster.Delete(v1alpha1.GitHubAppPath("example-org")) }, path: "/v1/github/example-org/widgets", status: http.StatusNotFound, reason: "no GitHubApp", }, { name: "an owner whose App's key Secret is gone", setup: func(w *world) { w.cluster.Delete("/api/v1/namespaces/lanyard-system/secrets/github-app-example-org") }, path: "/v1/github/example-org/widgets", status: http.StatusNotFound, reason: "has no private key", }, { name: "an owner whose App's key Secret lacks the key", setup: func(w *world) { w.cluster.AddSecret("lanyard-system", "github-app-example-org", map[string]string{"other": "x"}) }, path: "/v1/github/example-org/widgets", status: http.StatusNotFound, reason: "has no private key", }, {name: "a repository that does not exist", path: "/v1/github/example-org/nothing", status: http.StatusNotFound, reason: "not installed"}, {name: "a fork", path: "/v1/github/example-org/borrowed", status: http.StatusForbidden, reason: "is a fork"}, {name: "a name that is not a repository's", path: "/v1/github/example-org/wid%20gets", status: http.StatusBadRequest, reason: "not the name"}, { name: "a permission the App lacks", setup: func(w *world) { w.cluster.AddBadge(v1alpha1.Badge{ Metadata: v1alpha1.ObjectMeta{Namespace: "agents", Name: "workflows"}, Spec: v1alpha1.BadgeSpec{ServiceAccounts: []string{"fixer"}, GitHub: []v1alpha1.GitHubEntry{{Owners: []string{"example-org"}, Permissions: map[string]string{"workflows": "write"}}}}, }) }, path: "/v1/github/example-org/widgets", status: http.StatusForbidden, reason: "does not hold every permission", }, {name: "a secret no Badge of its own gives", path: "/v1/secrets/reads/other", status: http.StatusForbidden, reason: "holds no secret reads/other"}, {name: "a secret of a Badge it does not hold", path: "/v1/secrets/elsewhere/forge", status: http.StatusForbidden, reason: "holds no secret"}, { name: "a secret whose Secret is gone", setup: func(w *world) { w.cluster.Delete("/api/v1/namespaces/agents/secrets/forge-login") }, path: "/v1/secrets/reads/forge", status: http.StatusNotFound, reason: "does not exist", }, } for _, c := range cases { t.Run(c.name, func(t *testing.T) { w := newWorld(t) if c.setup != nil { c.setup(w) } status, body := w.get(t, c.path, "fixer-token") if status != c.status || !strings.Contains(body, c.reason) { t.Errorf("answered %d %q, want %d with %q", status, body, c.status, c.reason) } }) } } func TestAForkGetsATokenFromABadgeThatAllowsForks(t *testing.T) { w := newWorld(t) w.cluster.AddBadge(v1alpha1.Badge{ Metadata: v1alpha1.ObjectMeta{Namespace: "agents", Name: "forks"}, Spec: v1alpha1.BadgeSpec{ServiceAccounts: []string{"fixer"}, GitHub: []v1alpha1.GitHubEntry{{Owners: []string{"example-org"}, Permissions: map[string]string{"contents": "read"}, Forks: true}}}, }) status, body := w.get(t, "/v1/github/example-org/borrowed", "fixer-token") if status != http.StatusOK { t.Fatalf("status %d: %s", status, body) } var answered Token json.Unmarshal([]byte(body), &answered) issued := w.github.Tokens() last := issued[len(issued)-1] if last.Token != answered.Token || last.Revoked || !maps.Equal(last.Permissions, map[string]string{"contents": "read"}) { t.Errorf("lanyard answered %q, and GitHub's last token is %+v, want one that reads contents", answered.Token, last) } } func TestAServiceAccountTakenOffABadgeLosesItAtTheNextRequest(t *testing.T) { w := newWorld(t) if status, body := w.get(t, "/v1/secrets/reads/forge", "fixer-token"); status != http.StatusOK { t.Fatalf("status %d: %s", status, body) } reads := w.cluster.Badge("agents", "reads") reads.Spec.ServiceAccounts = []string{"reader"} w.cluster.AddBadge(reads) if status, body := w.get(t, "/v1/secrets/reads/forge", "fixer-token"); status != http.StatusForbidden { t.Errorf("after the edit, status %d, want 403: %s", status, body) } } func TestAPodGetsEveryKeyOfASecret(t *testing.T) { w := newWorld(t) status, body := w.get(t, "/v1/secrets/reads/forge", "fixer-token") if status != http.StatusOK { t.Fatalf("status %d: %s", status, body) } var answered Secret json.Unmarshal([]byte(body), &answered) if string(answered.Data["username"]) != "fixer" || string(answered.Data["password"]) != forgePassword { t.Errorf("the secret is %q", answered.Data) } } func TestAPodReadsItsLanyard(t *testing.T) { w := newWorld(t) status, body := w.get(t, "/v1/lanyard", "fixer-token") if status != http.StatusOK { t.Fatalf("status %d: %s", status, body) } var answered Lanyard json.Unmarshal([]byte(body), &answered) if answered.Namespace != "agents" || answered.ServiceAccount != "fixer" || len(answered.Badges) != 2 { t.Fatalf("the lanyard is %+v", answered) } reads := answered.Badges[0] if reads.Name != "reads" || len(reads.GitHub) != 1 || len(reads.Gitea) != 1 || len(reads.Secrets) != 1 || reads.Secrets[0] != "forge" { t.Errorf("the Badge reads is %+v", reads) } want := []GiteaAccount{{Name: "forge", URL: w.gitea.URL, Username: "claude"}} if !slices.Equal(answered.GiteaAccounts, want) { t.Errorf("the Gitea accounts are %+v, want %+v", answered.GiteaAccounts, want) } if len(reads.Atproto) != 1 || len(answered.Badges[1].Atproto) != 1 || !answered.Badges[1].Atproto[0].Session { t.Errorf("the atproto entries are %+v and %+v", reads.Atproto, answered.Badges[1].Atproto) } wantAtproto := []AtprotoAccount{{Name: "claude", PDS: w.pds.URL, Identifier: "claude.example.com"}} if !slices.Equal(answered.AtprotoAccounts, wantAtproto) { t.Errorf("the atproto accounts are %+v, want %+v", answered.AtprotoAccounts, wantAtproto) } for name, value := range map[string]string{"a secret's value": forgePassword, "a Gitea password": giteaPassword, "an app password": atprotoPassword} { if strings.Contains(body, value) { t.Errorf("the lanyard holds %s", name) } } } func TestNoAnswerMayBeStored(t *testing.T) { w := newWorld(t) request, _ := http.NewRequest(http.MethodGet, w.url+"/v1/github/example-org/widgets", nil) request.Header.Set("Authorization", "Bearer fixer-token") response, err := http.DefaultClient.Do(request) if err != nil { t.Fatal(err) } response.Body.Close() if got := response.Header.Get("Cache-Control"); got != "no-store" { t.Errorf("Cache-Control = %q, want no-store", got) } } func TestTheLogHoldsNoCredential(t *testing.T) { w := newWorld(t) _, body := w.get(t, "/v1/github/example-org/widgets", "fixer-token") var answered Token json.Unmarshal([]byte(body), &answered) w.get(t, "/v1/secrets/reads/forge", "fixer-token") w.get(t, "/v1/github/example-org/borrowed", "fixer-token") w.get(t, "/v1/github/example-org/widgets", "made-up") w.get(t, "/v1/gitea/forge", "fixer-token") w.cluster.AddSecret("lanyard-system", "gitea-forge", map[string]string{"password": "a wrong password"}) w.cluster.AddBadge(v1alpha1.Badge{ Metadata: v1alpha1.ObjectMeta{Namespace: "agents", Name: "users"}, Spec: v1alpha1.BadgeSpec{ServiceAccounts: []string{"fixer"}, Gitea: []v1alpha1.GiteaEntry{{Accounts: []string{"forge"}, Scopes: []string{"read:user"}}}}, }) w.get(t, "/v1/gitea/forge", "fixer-token") w.get(t, "/v1/atproto/claude/service?aud="+knot+"&lxm="+receivePack, "fixer-token") _, session := w.get(t, "/v1/atproto/claude/session", "fixer-token") var answeredSession AtprotoSession json.Unmarshal([]byte(session), &answeredSession) w.cluster.AddSecret("lanyard-system", "atproto-claude", map[string]string{"password": "a wrong app password"}) w.get(t, "/v1/atproto/claude/session", "fixer-token") log := w.log.String() for _, gave := range []string{"gave a GitHub token", "gave a secret", "gave a Gitea token", "gave an atproto service token", "gave an atproto session"} { if !strings.Contains(log, gave) { t.Fatalf("the log does not record %q: %s", gave, log) } } for _, issued := range w.github.Tokens() { if strings.Contains(log, issued.Token) { t.Errorf("the log holds the GitHub token %s", issued.Token) } } for _, made := range w.gitea.Tokens("claude") { if strings.Contains(log, made.Value) { t.Errorf("the log holds the Gitea token %s", made.Name) } } for _, made := range w.pds.ServiceTokens() { if strings.Contains(log, made.Token) { t.Errorf("the log holds the service token for %s", made.Method) } } for name, secret := range map[string]string{ "the secret's value": forgePassword, "the pod's token": "fixer-token", "a refused token": "made-up", "the App's key": "PRIVATE KEY", "the Gitea password": giteaPassword, "a refused Gitea password": "a wrong password", "the app password": atprotoPassword, "a refused app password": "a wrong app password", "the access token": answeredSession.AccessJWT, } { if strings.Contains(log, secret) { t.Errorf("the log holds %s", name) } } }