package adopt import ( "context" "fmt" "net/http" "net/http/httptest" "strings" "testing" "amadan.net/oficina/alta/carlosop" "amadan.net/oficina/alta/provision" ) const signInNonce = "NONCE-MUST-NOT-TRAVEL" // redirectTo answers status with one Location. func redirectTo(status int, location string) func(http.ResponseWriter) { return func(w http.ResponseWriter) { w.Header().Set("Location", location) w.WriteHeader(status) } } // signInFor is the redirect production answers for slug. func signInFor(slug string) func(http.ResponseWriter) { return redirectTo(http.StatusSeeOther, HomeIssuerOrigin+"/authorize?consumer="+slug+"&nonce="+signInNonce) } // secretHome stores the fixture's Home issuer and consumer as production // does, as secrets in the default layer, and serves the live sign-in. func secretHome(x *carlosFixture) { x.f.SetSecret(x.app.Slug, "", x.app.Prefix+"_HOME_ISSUER") x.f.SetSecret(x.app.Slug, "", x.app.Prefix+"_HOME_CONSUMER_ID") x.site.signIn = signInFor(x.app.Slug) } // The adoption tuple's consumer is the bare slug for each of the six apps. func TestAdoptionConsumerIsTheBareSlug(t *testing.T) { want := []string{"docs", "sheets", "slides", "calendar", "calls", "memoria", "equipo", "base"} if len(provision.Apps) != len(want) { t.Fatalf("%d apps", len(provision.Apps)) } for _, slug := range want { if _, ok := provision.AppBySlug(slug); !ok { t.Fatalf("no app %s", slug) } if got := provision.ConsumerID(provision.AdoptionLabel, slug); got != slug { t.Fatalf("ConsumerID(%s) = %q", slug, got) } } } // Production's shape passes for every app: both values secret, both read // from the sign-in redirect, which is never followed. func TestPreflightReadsSecretHomeIdentityFromSignIn(t *testing.T) { for _, a := range provision.Apps { t.Run(a.Slug, func(t *testing.T) { x := newCarlosFixture(t, a.Slug) secretHome(x) snap, codes := x.preflight(t, nil) wantCodes(t, codes) if snap.HomeIssuer != HomeIssuerOrigin || snap.HomeConsumer != a.Slug { t.Fatalf("issuer %q consumer %q", snap.HomeIssuer, snap.HomeConsumer) } if x.site.signIns.Load() != 1 || x.site.followed.Load() != 0 { t.Fatalf("sign-in read %d times, followed %d times", x.site.signIns.Load(), x.site.followed.Load()) } if strings.Contains(fmt.Sprintf("%+v", snap), signInNonce) { t.Fatal("the snapshot carries the nonce") } }) } } func TestPreflightAcceptsAFoundRedirect(t *testing.T) { x := newCarlosFixture(t, "docs") secretHome(x) x.site.signIn = redirectTo(http.StatusFound, HomeIssuerOrigin+"/authorize?nonce=n&consumer=docs") _, codes := x.preflight(t, nil) wantCodes(t, codes) } // Everything short of the exact redirect leaves both values empty. func TestPreflightRefusesSignInLookalikes(t *testing.T) { const good = "/authorize?consumer=docs&nonce=n" both := []string{"home-consumer-mismatch", "home-issuer-mismatch"} cases := map[string]struct { answer func(http.ResponseWriter) want []string }{ "other origin": {redirectTo(303, "https://id.example"+good), both}, "issuer subdomain": {redirectTo(303, "https://x.id.oficina.works"+good), both}, "issuer as a prefix": {redirectTo(303, "https://id.oficina.works.example"+good), both}, "explicit port": {redirectTo(303, "https://id.oficina.works:443"+good), both}, "http scheme": {redirectTo(303, "http://id.oficina.works"+good), both}, "userinfo": {redirectTo(303, "https://user@id.oficina.works"+good), both}, "userinfo lookalike": {redirectTo(303, "https://id.oficina.works@evil.example"+good), both}, "wrong path": {redirectTo(303, HomeIssuerOrigin+"/login?consumer=docs"), both}, "trailing slash": {redirectTo(303, HomeIssuerOrigin+"/authorize/?consumer=docs"), both}, "encoded path": {redirectTo(303, HomeIssuerOrigin+"/%61uthorize?consumer=docs"), both}, "fragment": {redirectTo(303, HomeIssuerOrigin+good+"#consumer=docs"), both}, "empty fragment": {redirectTo(303, HomeIssuerOrigin+good+"#"), both}, "backslash in host": {redirectTo(303, "https://id.oficina.works\\@evil.example"+good), both}, "backslash for path": {redirectTo(303, "https://id.oficina.works\\authorize?consumer=docs"), both}, "backslash in path": {redirectTo(303, HomeIssuerOrigin+"/authorize\\?consumer=docs"), both}, "backslash in query": {redirectTo(303, HomeIssuerOrigin+good+"\\"), both}, "backslash consumer": {redirectTo(303, HomeIssuerOrigin+"/authorize?consumer=docs\\"), both}, "repeated consumer": {redirectTo(303, HomeIssuerOrigin+"/authorize?consumer=docs&consumer=docs"), both}, "empty consumer": {redirectTo(303, HomeIssuerOrigin+"/authorize?consumer=&nonce=n"), both}, "no consumer": {redirectTo(303, HomeIssuerOrigin+"/authorize?nonce=n"), both}, "malformed query": {redirectTo(303, HomeIssuerOrigin+"/authorize?consumer=docs&x=%zz"), both}, "semicolon query": {redirectTo(303, HomeIssuerOrigin+"/authorize?consumer=docs;consumer=x"), both}, "relative location": {redirectTo(303, good), both}, "scheme-relative": {redirectTo(303, "//id.oficina.works"+good), both}, "no location": {func(w http.ResponseWriter) { w.WriteHeader(303) }, both}, "two locations": {func(w http.ResponseWriter) { w.Header().Add("Location", HomeIssuerOrigin+good) w.Header().Add("Location", HomeIssuerOrigin+good) w.WriteHeader(303) }, both}, "200 with a location": {redirectTo(200, HomeIssuerOrigin+good), both}, "301": {redirectTo(301, HomeIssuerOrigin+good), both}, "307": {redirectTo(307, HomeIssuerOrigin+good), both}, "oversized body": {func(w http.ResponseWriter) { w.Header().Set("Location", HomeIssuerOrigin+good) w.WriteHeader(303) _, _ = w.Write(make([]byte, bodyLimit+1)) }, both}, "connection dropped": {func(w http.ResponseWriter) { panic(http.ErrAbortHandler) }, both}, "wrong consumer": {signInFor("sheets"), []string{"home-consumer-mismatch"}}, } for name, c := range cases { t.Run(name, func(t *testing.T) { x := newCarlosFixture(t, "docs") secretHome(x) x.site.signIn = c.answer _, codes := x.preflight(t, nil) wantCodes(t, codes, c.want...) if x.site.followed.Load() != 0 { t.Fatal("the redirect was followed") } }) } t.Run("no sign-in door", func(t *testing.T) { x := newCarlosFixture(t, "docs") secretHome(x) x.site.signIn = nil _, codes := x.preflight(t, nil) wantCodes(t, codes, both...) }) } // A plain var is compared as it is: the redirect never rescues it. func TestPreflightNeverFallsBackFromAPlainVar(t *testing.T) { t.Run("issuer", func(t *testing.T) { x := newCarlosFixture(t, "docs") secretHome(x) x.f.SetVar("docs", "", "DOCS_HOME_ISSUER", "https://id.example") _, codes := x.preflight(t, nil) wantCodes(t, codes, "home-issuer-mismatch") }) t.Run("consumer", func(t *testing.T) { x := newCarlosFixture(t, "docs") secretHome(x) x.f.SetVar("docs", "", "DOCS_HOME_CONSUMER_ID", "oficina-docs") _, codes := x.preflight(t, nil) wantCodes(t, codes, "home-consumer-mismatch") }) t.Run("consumer absent", func(t *testing.T) { x := newCarlosFixture(t, "docs") secretHome(x) x.f.Unset("docs", "", "DOCS_HOME_CONSUMER_ID") _, codes := x.preflight(t, nil) wantCodes(t, codes, "home-consumer-mismatch") }) t.Run("both plain makes no sign-in read", func(t *testing.T) { x := newCarlosFixture(t, "docs") x.site.signIn = signInFor("docs") _, codes := x.preflight(t, nil) wantCodes(t, codes) if x.site.signIns.Load() != 0 { t.Fatal("plain vars read the sign-in door") } }) } // A secret in the overlay is not the app's own stored identity. func TestPreflightRefusesASecretConsumerInTheOverlay(t *testing.T) { x := newCarlosFixture(t, "docs") secretHome(x) x.f.SetOverlay("docs", docsRoute, "DOCS_HOME_CONSUMER_ID", "docs") _, codes := x.preflight(t, nil) wantCodes(t, codes, "home-consumer-mismatch") } // A secret is only believed when the stored layer agrees with the // effective view about it. func TestStoredSecretNeedsTheSameKindAndDigest(t *testing.T) { l := carlosop.Layer{Vars: []carlosop.Var{{Key: "K", Kind: "secret", Digest: "d1"}, {Key: "P", Kind: "env", Digest: "d1"}}} cases := map[string]struct { ev *carlosop.EffectiveVar want bool }{ "held": {&carlosop.EffectiveVar{Key: "K", Kind: "secret", Digest: "d1"}, true}, "absent": {nil, false}, "other digest": {&carlosop.EffectiveVar{Key: "K", Kind: "secret", Digest: "d2"}, false}, "effective plain": {&carlosop.EffectiveVar{Key: "K", Kind: "env", Digest: "d1"}, false}, "stored plain": {&carlosop.EffectiveVar{Key: "P", Kind: "secret", Digest: "d1"}, false}, "not stored": {&carlosop.EffectiveVar{Key: "X", Kind: "secret", Digest: "d1"}, false}, } for name, c := range cases { if got := storedSecret(l, c.ev); got != c.want { t.Errorf("%s: %v", name, got) } } } // The sign-in is only believed from an https origin. func TestSignInIdentityRefusesAPlainHTTPOrigin(t *testing.T) { srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { signInFor("docs")(w) })) t.Cleanup(srv.Close) if iss, cons := signInIdentity(context.Background(), srv.Client(), srv.URL); iss != "" || cons != "" { t.Fatalf("issuer %q consumer %q", iss, cons) } } // configure runs Preflight again before writing: a sign-in that has moved // sends nothing. func TestConfigureRefusesAMovedSignInBeforeWriting(t *testing.T) { w := newWriteFixture(t, "docs") secretHome(w.carlosFixture) w.site.signIn = signInFor("sheets") if _, err := w.configure(true); err == nil || !strings.Contains(err.Error(), "home-consumer-mismatch") { t.Fatalf("configure: %v", err) } if w.puts() != 0 { t.Fatal("configure wrote past a moved sign-in") } } func secretHomeBefore(w *writeFixture) { secretHome(w.carlosFixture) } // The activation gate holds the live sign-in to the same rule. func TestObserverRefusesAMovedSignIn(t *testing.T) { x := newObserverFixture(t, "calendar", secretHomeBefore) if _, err := x.observe(); err != nil { t.Fatalf("Observe with production's shape: %v", err) } x.site.signIn = signInFor("sheets") if _, err := x.observe(); err == nil || !strings.Contains(err.Error(), "home-consumer-mismatch") { t.Fatalf("Observe: %v", err) } } // The secrets themselves stay under digest preservation: a reseal is // drift even though the sign-in still answers the same. func TestObserverRefusesResealedHomeSecrets(t *testing.T) { for _, key := range []string{"CALENDAR_HOME_ISSUER", "CALENDAR_HOME_CONSUMER_ID"} { t.Run(key, func(t *testing.T) { x := newObserverFixture(t, "calendar", secretHomeBefore) x.f.SetSecret("calendar", "", key) if _, err := x.observe(); err == nil || !strings.Contains(err.Error(), "drift-changed:"+key) { t.Fatalf("Observe: %v", err) } }) } } // A rollback has to reach an app that is down, so it never asks the // sign-in door, and a broken one does not stop it. func TestRollbackDoesNotNeedTheSignIn(t *testing.T) { w := newWriteFixture(t, "docs") secretHome(w.carlosFixture) w.configured(t) w.site.signIn = nil before := w.site.signIns.Load() if err := w.rollback(true); err != nil { t.Fatalf("RollbackAgentKeys: %v", err) } if w.site.signIns.Load() != before { t.Fatal("the rollback read the sign-in door") } }