package web import ( "bytes" "context" "encoding/json" "io" "log/slog" "net/http" "net/http/httptest" "net/url" "path/filepath" "regexp" "strings" "testing" "time" "amadan.net/oficina/alta/console" "amadan.net/oficina/alta/console/fakeconsole" "amadan.net/oficina/alta/homeop" "amadan.net/oficina/alta/homeop/fakehome" "amadan.net/oficina/alta/provision" "amadan.net/oficina/home/connect" "amadan.net/rastrillo/rastrillo/assertion" family "amadan.net/rastrillo/rastrillo/crypto" ) const ( origin = "https://alta.example.test" issuer = "https://id.oficina.works" dirO = "https://oficina.works" operator = "pr_" + "bbbbbbbbbbbbbbbbbbbbbbbbbb" stranger = "pr_" + "cccccccccccccccccccccccccc" owner = "owner-canary@lagged.test" ) type fixture struct { t *testing.T now time.Time app *App signer *family.Keypair home *fakehome.Home engine *provision.Engine store *provision.Store jar map[string]*http.Cookie } func newFixture(t *testing.T) *fixture { f := &fixture{t: t, now: time.Unix(2_000_000_000, 0), jar: map[string]*http.Cookie{}} clock := func() time.Time { return f.now } key, _ := family.Generate() pre := homeop.Token() f.home = fakehome.New(key.SignPub(), pre, issuer, dirO, clock) f.home.AddPerson(owner) dir := httptest.NewServer(f.home.Handler(homeop.Directory)) cred := httptest.NewServer(f.home.Handler(homeop.Credential)) t.Cleanup(dir.Close) t.Cleanup(cred.Close) con := fakeconsole.New("bds", "alta") t.Cleanup(con.Close) tokens := map[string]string{} for _, a := range provision.Apps { tokens[a.Slug] = con.Mint(a.Slug) } db, err := provision.OpenDB(filepath.Join(t.TempDir(), "alta.db")) if err != nil { t.Fatal(err) } t.Cleanup(func() { db.Close() }) f.store, err = provision.NewStore(context.Background(), db, bytes.Repeat([]byte{3}, 32), clock, Extra...) if err != nil { t.Fatal(err) } roles := map[string]homeop.Role{} for name, url := range map[string]string{homeop.Credential: cred.URL, homeop.Directory: dir.URL} { p := f.home.Pins(name) o := issuer if name == homeop.Directory { o = dirO } roles[name] = homeop.Role{Name: name, Origin: o, URL: url, Installation: p.Installation, Registry: p.Registry, Device: p.Device} } f.engine = provision.New(provision.Config{Store: f.store, Home: &homeop.Client{Key: key, Prefilter: pre, Roles: roles, Now: clock}, Console: &console.Client{Base: con.URL(), Account: "bds", Tokens: tokens, Guard: provision.Guard{Store: f.store, Account: "bds"}}, HomeCfg: provision.HomeConfig{Issuer: issuer, Directory: dirO, Provisioner: f.home.ProvisioningPublic()}, Account: "bds", Now: clock, Logger: slog.New(slog.NewTextHandler(io.Discard, nil))}) f.signer, _ = family.Generate() app, err := New(Config{Origin: origin, OperatorSubject: operator, Engine: f.engine, Store: f.store, HomeDirectory: dirO, HomeCredential: issuer, Account: "bds", Now: clock, Home: &connect.DecodedCredentials{Issuer: issuer, ConsumerID: "alta", Keys: map[string][]byte{"k1": f.signer.SignPub()}, DEK: bytes.Repeat([]byte{5}, 32), Directory: dirO}}) if err != nil { t.Fatal(err) } f.app = app return f } func (f *fixture) do(method, path string, form url.Values, headers map[string]string) *httptest.ResponseRecorder { f.t.Helper() var body io.Reader if form != nil { body = strings.NewReader(form.Encode()) } r := httptest.NewRequest(method, origin+path, body) if form != nil { r.Header.Set("Content-Type", "application/x-www-form-urlencoded") } for k, v := range headers { r.Header.Set(k, v) } for _, c := range f.jar { r.AddCookie(c) } w := httptest.NewRecorder() f.app.ServeHTTP(w, r) for _, c := range w.Result().Cookies() { if c.MaxAge < 0 { delete(f.jar, c.Name) } else { f.jar[c.Name] = c } } return w } var sameOrigin = map[string]string{"Origin": origin, "Sec-Fetch-Site": "same-origin"} // signIn is the Home hand-off, with Home's assertion minted here. func (f *fixture) signIn(subject string) { f.t.Helper() start := f.do("GET", "/auth/start?return_to=%2F", nil, nil) if start.Code != 303 { f.t.Fatalf("start %d", start.Code) } target, _ := url.Parse(start.Header().Get("Location")) if target.Host != "id.oficina.works" || target.Query().Get("consumer") != "alta" { f.t.Fatalf("issuer target %s", target) } id, _ := assertion.RandomID() token, err := assertion.Sign(f.signer, assertion.Claims{Version: 1, Issuer: issuer, Audience: origin, Subject: subject, KeyID: "k1", ID: id, Nonce: target.Query().Get("nonce"), IssuedAt: f.now.Unix(), ExpiresAt: f.now.Unix() + 120, AuthTime: f.now.Unix()}) if err != nil { f.t.Fatal(err) } cb := f.do("POST", "/auth/assertion", url.Values{"assertion": {token}}, map[string]string{"Origin": issuer}) if cb.Code != 303 { f.t.Fatalf("callback %d", cb.Code) } fin := f.do("GET", "/auth/finish", nil, nil) if fin.Code != 303 || fin.Header().Get("Location") != "/" { f.t.Fatalf("finish %d %s", fin.Code, fin.Header().Get("Location")) } } func TestSignInIsHomeOnlyAndOperatorOnly(t *testing.T) { f := newFixture(t) if w := f.do("GET", "/", nil, nil); w.Code != 303 || !strings.HasPrefix(w.Header().Get("Location"), "/auth/start?return_to=") { t.Fatalf("anonymous: %d %s", w.Code, w.Header().Get("Location")) } f.signIn(stranger) for _, p := range []string{"/", "/teams/new", "/runs/1", "/initialize"} { if w := f.do("GET", p, nil, nil); w.Code != 404 { t.Fatalf("stranger %s: %d", p, w.Code) } } unknown := f.do("GET", "/no-such-page", nil, nil) stranger := f.do("GET", "/teams/new", nil, nil) if unknown.Body.String() != stranger.Body.String() { t.Fatal("a stranger's 404 differs from an unknown page's") } f.jar = map[string]*http.Cookie{} f.signIn(operator) w := f.do("GET", "/", nil, nil) if w.Code != 200 || !strings.Contains(w.Body.String(), "Initialize") { t.Fatalf("operator: %d", w.Code) } scriptless(t, w.Body.String()) } func scriptless(t *testing.T, html string) { t.Helper() scripts := regexp.MustCompile(`]*>`).FindAllString(html, -1) if len(scripts) != 1 || !strings.Contains(scripts[0], "busy.js") { t.Fatalf("scripts %v: Alta is scriptless but for estilo's busy.js", scripts) } if strings.Contains(html, " style=") || strings.Contains(html, "Own", "Docs sample documents on", "After the run: Memoria AI"} { if !strings.Contains(body, want) { t.Fatalf("run page lacks %q", want) } } if strings.Contains(body, owner) { t.Fatal("the run page shows the owner's address") } scriptless(t, body) team := f.do("GET", "/teams/lagged", nil, nil) if team.Code != 200 || strings.Contains(team.Body.String(), owner) { t.Fatalf("team page: %d", team.Code) } if b := team.Body.String(); !strings.Contains(b, "Continues Docs, Calls, Memoria.") || !strings.Contains(b, `id="continue"`) || !strings.Contains(b, `name="profile" value="own" checked`) || !strings.Contains(b, `name="samples" value="1" checked`) || !strings.Contains(b, "create-team ยท own, samples") { t.Fatal("the team page does not show the run's profile") } retire := f.do("GET", "/teams/lagged/retire", nil, nil) if retire.Code != 200 || !strings.Contains(retire.Body.String(), "Type lagged to confirm") { t.Fatalf("retire page: %d", retire.Code) } } func mustInt(t *testing.T, s string) int64 { var n int64 if err := json.Unmarshal([]byte(s), &n); err != nil { t.Fatalf("not a run id: %q", s) } return n } // Fable's review, blocker 3: an owner Home refuses leaves the label // recorded; the team page offers the owner form while the team is not // yet at Home, even though Alta still holds the (wrong) address. func TestRefusedOwnerLeadsToTheOwnerForm(t *testing.T) { f := newFixture(t) f.signIn(operator) w := f.do("POST", "/initialize", url.Values{"attestation": {provision.InitializeAttestation}}, sameOrigin) _ = f.home.Confirm(homeop.Directory, "") _ = f.engine.Advance(context.Background(), mustInt(t, strings.TrimPrefix(w.Header().Get("Location"), "/runs/"))) f.now = f.now.Add(homeop.WindowLifetime * time.Second) w = f.do("POST", "/teams", url.Values{"label": {"lagged"}, "name": {"Lagged"}, "owner": {"typo@lagged.test"}, "app": {"sheets"}}, sameOrigin) if w.Code != 303 || !strings.HasPrefix(w.Header().Get("Location"), "/teams/lagged?audit=plan-refused-credential") { t.Fatalf("refused owner: %d %s", w.Code, w.Header().Get("Location")) } page := f.do("GET", w.Header().Get("Location"), nil, nil).Body.String() if !strings.Contains(page, `action="/teams/lagged/owner"`) || !strings.Contains(page, "Has the owner signed in") { t.Fatal("no owner form for an unseeded team") } if strings.Contains(page, "typo@lagged.test") { t.Fatal("the held address is shown") } if w := f.do("POST", "/teams/lagged/owner", url.Values{"owner": {owner}}, sameOrigin); w.Code != 303 { t.Fatalf("retype: %d", w.Code) } if got, _, _ := f.store.Owner(context.Background(), "lagged"); got != owner { t.Fatal("retyped owner not held") } // Once the team is seeded at Home, no app takes a retyped owner: a // seeded app's owner is only ever the address Home confirmed. if err := f.store.SetSeeded(context.Background(), "lagged", 1, "Uk", 1, "g", "pr_x", nil); err != nil { t.Fatal(err) } else { if w := f.do("POST", "/teams/lagged/owner", url.Values{"owner": {"someone-else@lagged.test"}}, sameOrigin); w.Code != 303 || !strings.Contains(w.Header().Get("Location"), "audit=owner-retype-refused") { t.Fatalf("retype after the seed: %d %s", w.Code, w.Header().Get("Location")) } if got, _, _ := f.store.Owner(context.Background(), "lagged"); got != owner { t.Fatal("a retype after the seed replaced the owner") } } // A code Alta never produced is not shown as if Alta said it. if page := f.do("GET", "/teams/lagged?audit=Your+account+is+suspended", nil, nil).Body.String(); strings.Contains(page, "suspended") { t.Fatal("an arbitrary audit code was reflected") } }