package stateapi import ( "encoding/json" "fmt" "io" "log/slog" "net/http" "net/http/httptest" "strings" "testing" "github.com/liken-sh/liken/kubernetes/events" "github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus/testutil" corev1 "k8s.io/api/core/v1" "tangled.org/guid.foo/gofer/api/v1alpha1" "tangled.org/guid.foo/gofer/cluster" "tangled.org/guid.foo/gofer/cluster/clustertest" "tangled.org/guid.foo/gofer/inject" "tangled.org/guid.foo/gofer/seal" "tangled.org/guid.foo/gofer/store" ) const statePath = "/v1/namespaces/errands/browserprofiles/shopping/state" // world is an API server holding the shopping profile, its card, and one // pod that uses it with the token "agent-token", and a state API in // front of an empty store. type world struct { fake *clustertest.Fake url string server *Server store *store.Store dir string registry *prometheus.Registry recorder *events.Recorder } func newWorld(t *testing.T) *world { t.Helper() fake, c := clustertest.Start(t) fake.AddProfile(v1alpha1.BrowserProfile{ Metadata: v1alpha1.ObjectMeta{Namespace: "errands", Name: "shopping", UID: "profile-uid"}, Spec: v1alpha1.BrowserProfileSpec{ ServiceAccounts: []string{"agent"}, Egress: v1alpha1.Egress{Hosts: []string{"*.stripe.com"}}, Secrets: []v1alpha1.Secret{{ Name: "card", SecretKeyRef: v1alpha1.SecretKeySelector{Name: "test-card", Key: "number"}, Origins: []string{"https://js.stripe.com"}, }}, }, }) fake.AddSecret("errands", "test-card", map[string]string{"number": "4242424242424242"}) addPod(fake, "agent-1", "pod-uid-1", "agent", "shopping", "Running") fake.AddToken("agent-token", clustertest.Token{Namespace: "errands", ServiceAccount: "agent", Pod: "agent-1", PodUID: "pod-uid-1", Audiences: []string{"gofer"}}) keyring, _ := seal.NewKeyring(seal.NewKey()) dir := t.TempDir() states := store.New(dir, keyring) recorder := fake.Recorder(t) registry := prometheus.NewRegistry() api := New(sidecarImage, c, states, slog.New(slog.DiscardHandler), registry, recorder) server := httptest.NewServer(api.Handler()) t.Cleanup(server.Close) return &world{fake: fake, url: server.URL, server: api, store: states, dir: dir, registry: registry, recorder: recorder} } const sidecarImage = "registry.example:5000/gofer/sidecar:main-2-bbb" // injected is the spec the webhook leaves on a pod. func injected() corev1.PodSpec { return injectedWith(sidecarImage) } // injectedWith is the spec a webhook that injects image leaves on a pod. func injectedWith(image string) corev1.PodSpec { always := corev1.ContainerRestartPolicyAlways return corev1.PodSpec{ InitContainers: []corev1.Container{{Name: inject.SidecarName, Image: image, RestartPolicy: &always, VolumeMounts: []corev1.VolumeMount{{Name: inject.TokenVolume, MountPath: "/t"}}}}, Containers: []corev1.Container{{Name: "agent", Image: "agent:1"}}, } } func addPod(fake *clustertest.Fake, name, uid, account, profile, phase string) { addPodWithSpec(fake, name, uid, account, profile, phase, injected()) } func addPodWithSpec(fake *clustertest.Fake, name, uid, account, profile, phase string, spec corev1.PodSpec) { fake.AddPod(cluster.Pod{ Namespace: "errands", Name: name, UID: uid, Phase: phase, ServiceAccount: account, Labels: map[string]string{v1alpha1.LabelProfile: profile}, Spec: spec, }) } func (w *world) send(t *testing.T, method, path, token string, headers map[string]string, body string) *http.Response { t.Helper() req, _ := http.NewRequest(method, w.url+path, strings.NewReader(body)) if token != "" { req.Header.Set("Authorization", "Bearer "+token) } for k, v := range headers { req.Header.Set(k, v) } res, err := http.DefaultClient.Do(req) if err != nil { t.Fatal(err) } t.Cleanup(func() { res.Body.Close() }) return res } func TestStateRoundTripsWithVersions(t *testing.T) { w := newWorld(t) if res := w.send(t, "GET", statePath, "agent-token", nil, ""); res.StatusCode != http.StatusNotFound { t.Fatalf("GET before any save = %d, want 404", res.StatusCode) } res := w.send(t, "PUT", statePath, "agent-token", map[string]string{"If-None-Match": "*"}, `{"cookies":[1]}`) if res.StatusCode != http.StatusNoContent || res.Header.Get("ETag") != `"1"` { t.Fatalf("first PUT = %d %s, want 204 \"1\"", res.StatusCode, res.Header.Get("ETag")) } res = w.send(t, "PUT", statePath, "agent-token", map[string]string{"If-Match": `"1"`}, `{"cookies":[2]}`) if res.StatusCode != http.StatusNoContent || res.Header.Get("ETag") != `"2"` { t.Fatalf("second PUT = %d %s, want 204 \"2\"", res.StatusCode, res.Header.Get("ETag")) } res = w.send(t, "GET", statePath, "agent-token", nil, "") body, _ := io.ReadAll(res.Body) if res.StatusCode != http.StatusOK || res.Header.Get("ETag") != `"2"` || string(body) != `{"cookies":[2]}` { t.Errorf("GET = %d %s %s", res.StatusCode, res.Header.Get("ETag"), body) } state := w.fake.Profile("errands", "shopping").Status.State if state == nil || state.Version != 2 || state.Size == 0 { t.Errorf("status.state = %+v, want version 2", state) } } func TestAWriteOnAStaleVersionIsRefused(t *testing.T) { w := newWorld(t) w.send(t, "PUT", statePath, "agent-token", map[string]string{"If-None-Match": "*"}, `{}`) w.send(t, "PUT", statePath, "agent-token", map[string]string{"If-Match": `"1"`}, `{}`) cases := []struct { name string headers map[string]string want int }{ {"a write on the version before", map[string]string{"If-Match": `"1"`}, http.StatusPreconditionFailed}, {"a create when the state exists", map[string]string{"If-None-Match": "*"}, http.StatusPreconditionFailed}, {"a write that names no version", nil, http.StatusPreconditionRequired}, } for _, c := range cases { t.Run(c.name, func(t *testing.T) { if res := w.send(t, "PUT", statePath, "agent-token", c.headers, `{}`); res.StatusCode != c.want { t.Errorf("PUT = %d, want %d", res.StatusCode, c.want) } }) } } func TestSecretsReachOnlyThePodsTheProfileAllows(t *testing.T) { w := newWorld(t) addPod(w.fake, "other-sa", "pod-uid-2", "intruder", "shopping", "Running") w.fake.AddToken("other-sa-token", clustertest.Token{Namespace: "errands", ServiceAccount: "intruder", Pod: "other-sa", PodUID: "pod-uid-2", Audiences: []string{"gofer"}}) addPod(w.fake, "unlabeled", "pod-uid-3", "agent", "", "Running") w.fake.AddToken("unlabeled-token", clustertest.Token{Namespace: "errands", ServiceAccount: "agent", Pod: "unlabeled", PodUID: "pod-uid-3", Audiences: []string{"gofer"}}) addPod(w.fake, "done", "pod-uid-4", "agent", "shopping", "Succeeded") w.fake.AddToken("done-token", clustertest.Token{Namespace: "errands", ServiceAccount: "agent", Pod: "done", PodUID: "pod-uid-4", Audiences: []string{"gofer"}}) w.fake.AddToken("old-pod-token", clustertest.Token{Namespace: "errands", ServiceAccount: "agent", Pod: "agent-1", PodUID: "pod-uid-old", Audiences: []string{"gofer"}}) w.fake.AddToken("api-server-token", clustertest.Token{Namespace: "errands", ServiceAccount: "agent", Pod: "agent-1", PodUID: "pod-uid-1", Audiences: []string{"https://kubernetes.default.svc"}}) addPod(w.fake, "pending", "pod-uid-5", "agent", "shopping", "Pending") addPodWithSpec(w.fake, "no-sidecar", "pod-uid-6", "agent", "shopping", "Running", corev1.PodSpec{Containers: []corev1.Container{{Name: "agent"}}}) w.fake.AddToken("no-sidecar-token", clustertest.Token{Namespace: "errands", ServiceAccount: "agent", Pod: "no-sidecar", PodUID: "pod-uid-6", Audiences: []string{"gofer"}}) w.fake.AddToken("pending-token", clustertest.Token{Namespace: "errands", ServiceAccount: "agent", Pod: "pending", PodUID: "pod-uid-5", Audiences: []string{"gofer"}}) sidecars := map[string]string{ "earlier-release": "registry.example:5000/gofer/sidecar:main-1-aaa", "by-digest": "registry.example:5000/gofer/sidecar@sha256:0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef", "foreign": "registry.example:5000/gofer/other:main-2-bbb", "lookalike": "registry.example:5000/gofer/sidecar-two:main-2-bbb", "other-registry": "elsewhere.example/gofer/sidecar:main-2-bbb", } for name, image := range sidecars { addPodWithSpec(w.fake, name, "uid-"+name, "agent", "shopping", "Running", injectedWith(image)) w.fake.AddToken(name+"-token", clustertest.Token{Namespace: "errands", ServiceAccount: "agent", Pod: name, PodUID: "uid-" + name, Audiences: []string{"gofer"}}) } cases := []struct { name string token string want int }{ {"the profile's pod", "agent-token", http.StatusOK}, {"the profile's pod while its sidecar starts", "pending-token", http.StatusOK}, {"no token", "", http.StatusUnauthorized}, {"the API server's token for the same pod", "api-server-token", http.StatusUnauthorized}, {"a pod whose ServiceAccount the profile does not allow", "other-sa-token", http.StatusForbidden}, {"a pod without the profile's label", "unlabeled-token", http.StatusForbidden}, {"a pod that has finished", "done-token", http.StatusForbidden}, {"a token of an earlier pod of the same name", "old-pod-token", http.StatusForbidden}, {"a labeled pod the webhook never saw", "no-sidecar-token", http.StatusForbidden}, {"a pod an earlier release injected", "earlier-release-token", http.StatusOK}, {"a pod whose sidecar names its image by digest", "by-digest-token", http.StatusOK}, {"a pod whose sidecar is another image", "foreign-token", http.StatusForbidden}, {"a pod whose sidecar's repository only starts the same", "lookalike-token", http.StatusForbidden}, {"a pod whose sidecar comes from another registry", "other-registry-token", http.StatusForbidden}, } for _, c := range cases { t.Run(c.name, func(t *testing.T) { res := w.send(t, "GET", "/v1/namespaces/errands/browserprofiles/shopping/secrets", c.token, nil, "") body, _ := io.ReadAll(res.Body) if res.StatusCode != c.want { t.Fatalf("GET secrets = %d %s, want %d", res.StatusCode, body, c.want) } if c.want != http.StatusOK { if strings.Contains(string(body), "4242") { t.Error("a refusal holds the card number") } return } var secrets map[string]Secret json.Unmarshal(body, &secrets) if secrets["card"].Value != "4242424242424242" || secrets["card"].Origins[0] != "https://js.stripe.com" { t.Errorf("secrets = %+v", secrets) } }) } } func TestAPodCannotReachAnotherProfile(t *testing.T) { w := newWorld(t) w.fake.AddProfile(v1alpha1.BrowserProfile{ Metadata: v1alpha1.ObjectMeta{Namespace: "errands", Name: "banking", UID: "other-uid"}, Spec: v1alpha1.BrowserProfileSpec{ServiceAccounts: []string{"agent"}}, }) res := w.send(t, "GET", "/v1/namespaces/errands/browserprofiles/banking/state", "agent-token", nil, "") if res.StatusCode != http.StatusForbidden { t.Errorf("GET another profile's state = %d, want 403", res.StatusCode) } } func TestEachRequestIsCountedByRouteAndCode(t *testing.T) { w := newWorld(t) secretsPath := "/v1/namespaces/errands/browserprofiles/shopping/secrets" w.send(t, "GET", statePath, "agent-token", nil, "") w.send(t, "PUT", statePath, "agent-token", map[string]string{"If-None-Match": "*"}, `{}`) w.send(t, "PUT", statePath, "agent-token", map[string]string{"If-None-Match": "*"}, `{}`) w.send(t, "GET", secretsPath, "", nil, "") cases := []struct { route, code string want float64 }{ {"get_state", "404", 1}, {"put_state", "204", 1}, {"put_state", "412", 1}, {"get_secrets", "401", 1}, {"get_secrets", "200", 0}, } for _, c := range cases { t.Run(c.route+" "+c.code, func(t *testing.T) { if got := testutil.ToFloat64(w.server.requests.WithLabelValues(c.route, c.code)); got != c.want { t.Errorf("gofer_state_requests_total{route=%q,code=%q} = %v, want %v", c.route, c.code, got, c.want) } }) } if got := testutil.ToFloat64(w.server.saves); got != 1 { t.Errorf("gofer_state_saves_total = %v, want 1", got) } if got := testutil.ToFloat64(w.server.conflicts); got != 1 { t.Errorf("gofer_state_conflicts_total = %v, want 1", got) } } func TestAStoredStateOlderThanTheStatusIsRefusedWithAWarning(t *testing.T) { w := newWorld(t) if _, _, err := w.store.Save(store.Profile{Namespace: "errands", Name: "shopping", UID: "profile-uid"}, 0, []byte(`{}`)); err != nil { t.Fatal(err) } profile := w.fake.Profile("errands", "shopping") profile.Status.State = &v1alpha1.StateStatus{Version: 2} w.fake.AddProfile(profile) if res := w.send(t, "GET", statePath, "agent-token", nil, ""); res.StatusCode != http.StatusInternalServerError { t.Errorf("GET of a rolled-back state = %d, want 500", res.StatusCode) } if got := testutil.ToFloat64(w.server.rollbacks); got != 1 { t.Errorf("gofer_state_rollbacks_refused_total = %v, want 1", got) } posted := w.fake.EventsAbout(t, w.recorder, v1alpha1.Kind, "shopping") if len(posted) != 1 || posted[0].Type != "Warning" || posted[0].Reason != v1alpha1.ReasonStateRolledBack { t.Errorf("Events = %+v, want one Warning %s", posted, v1alpha1.ReasonStateRolledBack) } } // underAnotherKey answers a world whose volume holds a saved state that // the state API cannot open, because the key-encryption key it was given // is not the one that sealed the state, as after a restore that brought // back the volume but not the Secret gofer-kek. func underAnotherKey(t *testing.T) *world { t.Helper() w := newWorld(t) if _, _, err := w.store.Save(store.Profile{Namespace: "errands", Name: "shopping", UID: "profile-uid"}, 0, []byte(`{}`)); err != nil { t.Fatal(err) } other, _ := seal.NewKeyring(seal.NewKey()) w.server.store = store.New(w.dir, other) return w } func TestAStateThatDoesNotOpenIsCountedByRoute(t *testing.T) { cases := []struct { name string method string headers map[string]string get, put int }{ {"a load", "GET", nil, 1, 0}, {"a save", "PUT", map[string]string{"If-Match": `"1"`}, 0, 1}, } for _, c := range cases { t.Run(c.name, func(t *testing.T) { w := underAnotherKey(t) if res := w.send(t, c.method, statePath, "agent-token", c.headers, `{}`); res.StatusCode != http.StatusInternalServerError { t.Errorf("%s of a state that does not open = %d, want 500", c.method, res.StatusCode) } want := fmt.Sprintf(` # HELP gofer_state_unseal_failures_total Requests that failed because a profile's stored state or its data key did not open, by route. # TYPE gofer_state_unseal_failures_total counter gofer_state_unseal_failures_total{route="get_state"} %d gofer_state_unseal_failures_total{route="put_state"} %d `, c.get, c.put) if err := testutil.GatherAndCompare(w.registry, strings.NewReader(want), "gofer_state_unseal_failures_total"); err != nil { t.Error(err) } }) } }