| 1 | package web |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "context" |
| 6 | "encoding/json" |
| 7 | "io" |
| 8 | "log/slog" |
| 9 | "net/http" |
| 10 | "net/http/httptest" |
| 11 | "net/url" |
| 12 | "path/filepath" |
| 13 | "regexp" |
| 14 | "strings" |
| 15 | "testing" |
| 16 | "time" |
| 17 | |
| 18 | "amadan.net/oficina/alta/console" |
| 19 | "amadan.net/oficina/alta/console/fakeconsole" |
| 20 | "amadan.net/oficina/alta/homeop" |
| 21 | "amadan.net/oficina/alta/homeop/fakehome" |
| 22 | "amadan.net/oficina/alta/provision" |
| 23 | "amadan.net/oficina/home/connect" |
| 24 | "amadan.net/rastrillo/rastrillo/assertion" |
| 25 | family "amadan.net/rastrillo/rastrillo/crypto" |
| 26 | ) |
| 27 | |
| 28 | const ( |
| 29 | origin = "https://alta.example.test" |
| 30 | issuer = "https://id.oficina.works" |
| 31 | dirO = "https://oficina.works" |
| 32 | operator = "pr_" + "bbbbbbbbbbbbbbbbbbbbbbbbbb" |
| 33 | stranger = "pr_" + "cccccccccccccccccccccccccc" |
| 34 | owner = "owner-canary@lagged.test" |
| 35 | ) |
| 36 | |
| 37 | type fixture struct { |
| 38 | t *testing.T |
| 39 | now time.Time |
| 40 | app *App |
| 41 | signer *family.Keypair |
| 42 | home *fakehome.Home |
| 43 | engine *provision.Engine |
| 44 | store *provision.Store |
| 45 | jar map[string]*http.Cookie |
| 46 | } |
| 47 | |
| 48 | func newFixture(t *testing.T) *fixture { |
| 49 | f := &fixture{t: t, now: time.Unix(2_000_000_000, 0), jar: map[string]*http.Cookie{}} |
| 50 | clock := func() time.Time { return f.now } |
| 51 | key, _ := family.Generate() |
| 52 | pre := homeop.Token() |
| 53 | f.home = fakehome.New(key.SignPub(), pre, issuer, dirO, clock) |
| 54 | f.home.AddPerson(owner) |
| 55 | dir := httptest.NewServer(f.home.Handler(homeop.Directory)) |
| 56 | cred := httptest.NewServer(f.home.Handler(homeop.Credential)) |
| 57 | t.Cleanup(dir.Close) |
| 58 | t.Cleanup(cred.Close) |
| 59 | con := fakeconsole.New("bds", "alta") |
| 60 | t.Cleanup(con.Close) |
| 61 | tokens := map[string]string{} |
| 62 | for _, a := range provision.Apps { |
| 63 | tokens[a.Slug] = con.Mint(a.Slug) |
| 64 | } |
| 65 | db, err := provision.OpenDB(filepath.Join(t.TempDir(), "alta.db")) |
| 66 | if err != nil { |
| 67 | t.Fatal(err) |
| 68 | } |
| 69 | t.Cleanup(func() { db.Close() }) |
| 70 | f.store, err = provision.NewStore(context.Background(), db, bytes.Repeat([]byte{3}, 32), clock, Extra...) |
| 71 | if err != nil { |
| 72 | t.Fatal(err) |
| 73 | } |
| 74 | roles := map[string]homeop.Role{} |
| 75 | for name, url := range map[string]string{homeop.Credential: cred.URL, homeop.Directory: dir.URL} { |
| 76 | p := f.home.Pins(name) |
| 77 | o := issuer |
| 78 | if name == homeop.Directory { |
| 79 | o = dirO |
| 80 | } |
| 81 | roles[name] = homeop.Role{Name: name, Origin: o, URL: url, Installation: p.Installation, Registry: p.Registry, Device: p.Device} |
| 82 | } |
| 83 | f.engine = provision.New(provision.Config{Store: f.store, Home: &homeop.Client{Key: key, Prefilter: pre, Roles: roles, Now: clock}, |
| 84 | Console: &console.Client{Base: con.URL(), Account: "bds", Tokens: tokens, Guard: provision.Guard{Store: f.store, Account: "bds"}}, |
| 85 | HomeCfg: provision.HomeConfig{Issuer: issuer, Directory: dirO, Provisioner: f.home.ProvisioningPublic()}, Account: "bds", Now: clock, Logger: slog.New(slog.NewTextHandler(io.Discard, nil))}) |
| 86 | f.signer, _ = family.Generate() |
| 87 | app, err := New(Config{Origin: origin, OperatorSubject: operator, Engine: f.engine, Store: f.store, HomeDirectory: dirO, HomeCredential: issuer, Account: "bds", Now: clock, |
| 88 | Home: &connect.DecodedCredentials{Issuer: issuer, ConsumerID: "alta", Keys: map[string][]byte{"k1": f.signer.SignPub()}, DEK: bytes.Repeat([]byte{5}, 32), Directory: dirO}}) |
| 89 | if err != nil { |
| 90 | t.Fatal(err) |
| 91 | } |
| 92 | f.app = app |
| 93 | return f |
| 94 | } |
| 95 | |
| 96 | func (f *fixture) do(method, path string, form url.Values, headers map[string]string) *httptest.ResponseRecorder { |
| 97 | f.t.Helper() |
| 98 | var body io.Reader |
| 99 | if form != nil { |
| 100 | body = strings.NewReader(form.Encode()) |
| 101 | } |
| 102 | r := httptest.NewRequest(method, origin+path, body) |
| 103 | if form != nil { |
| 104 | r.Header.Set("Content-Type", "application/x-www-form-urlencoded") |
| 105 | } |
| 106 | for k, v := range headers { |
| 107 | r.Header.Set(k, v) |
| 108 | } |
| 109 | for _, c := range f.jar { |
| 110 | r.AddCookie(c) |
| 111 | } |
| 112 | w := httptest.NewRecorder() |
| 113 | f.app.ServeHTTP(w, r) |
| 114 | for _, c := range w.Result().Cookies() { |
| 115 | if c.MaxAge < 0 { |
| 116 | delete(f.jar, c.Name) |
| 117 | } else { |
| 118 | f.jar[c.Name] = c |
| 119 | } |
| 120 | } |
| 121 | return w |
| 122 | } |
| 123 | |
| 124 | var sameOrigin = map[string]string{"Origin": origin, "Sec-Fetch-Site": "same-origin"} |
| 125 | |
| 126 | // signIn is the Home hand-off, with Home's assertion minted here. |
| 127 | func (f *fixture) signIn(subject string) { |
| 128 | f.t.Helper() |
| 129 | start := f.do("GET", "/auth/start?return_to=%2F", nil, nil) |
| 130 | if start.Code != 303 { |
| 131 | f.t.Fatalf("start %d", start.Code) |
| 132 | } |
| 133 | target, _ := url.Parse(start.Header().Get("Location")) |
| 134 | if target.Host != "id.oficina.works" || target.Query().Get("consumer") != "alta" { |
| 135 | f.t.Fatalf("issuer target %s", target) |
| 136 | } |
| 137 | id, _ := assertion.RandomID() |
| 138 | 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()}) |
| 139 | if err != nil { |
| 140 | f.t.Fatal(err) |
| 141 | } |
| 142 | cb := f.do("POST", "/auth/assertion", url.Values{"assertion": {token}}, map[string]string{"Origin": issuer}) |
| 143 | if cb.Code != 303 { |
| 144 | f.t.Fatalf("callback %d", cb.Code) |
| 145 | } |
| 146 | fin := f.do("GET", "/auth/finish", nil, nil) |
| 147 | if fin.Code != 303 || fin.Header().Get("Location") != "/" { |
| 148 | f.t.Fatalf("finish %d %s", fin.Code, fin.Header().Get("Location")) |
| 149 | } |
| 150 | } |
| 151 | |
| 152 | func TestSignInIsHomeOnlyAndOperatorOnly(t *testing.T) { |
| 153 | f := newFixture(t) |
| 154 | if w := f.do("GET", "/", nil, nil); w.Code != 303 || !strings.HasPrefix(w.Header().Get("Location"), "/auth/start?return_to=") { |
| 155 | t.Fatalf("anonymous: %d %s", w.Code, w.Header().Get("Location")) |
| 156 | } |
| 157 | f.signIn(stranger) |
| 158 | for _, p := range []string{"/", "/teams/new", "/runs/1", "/initialize"} { |
| 159 | if w := f.do("GET", p, nil, nil); w.Code != 404 { |
| 160 | t.Fatalf("stranger %s: %d", p, w.Code) |
| 161 | } |
| 162 | } |
| 163 | unknown := f.do("GET", "/no-such-page", nil, nil) |
| 164 | stranger := f.do("GET", "/teams/new", nil, nil) |
| 165 | if unknown.Body.String() != stranger.Body.String() { |
| 166 | t.Fatal("a stranger's 404 differs from an unknown page's") |
| 167 | } |
| 168 | f.jar = map[string]*http.Cookie{} |
| 169 | f.signIn(operator) |
| 170 | w := f.do("GET", "/", nil, nil) |
| 171 | if w.Code != 200 || !strings.Contains(w.Body.String(), "Initialize") { |
| 172 | t.Fatalf("operator: %d", w.Code) |
| 173 | } |
| 174 | scriptless(t, w.Body.String()) |
| 175 | } |
| 176 | |
| 177 | func scriptless(t *testing.T, html string) { |
| 178 | t.Helper() |
| 179 | scripts := regexp.MustCompile(`<script[^>]*>`).FindAllString(html, -1) |
| 180 | if len(scripts) != 1 || !strings.Contains(scripts[0], "busy.js") { |
| 181 | t.Fatalf("scripts %v: Alta is scriptless but for estilo's busy.js", scripts) |
| 182 | } |
| 183 | if strings.Contains(html, " style=") || strings.Contains(html, "<style") || strings.Contains(html, " onclick") { |
| 184 | t.Fatal("inline style or handler") |
| 185 | } |
| 186 | } |
| 187 | |
| 188 | func TestIdleSessionEnds(t *testing.T) { |
| 189 | f := newFixture(t) |
| 190 | f.signIn(operator) |
| 191 | if w := f.do("GET", "/", nil, nil); w.Code != 200 { |
| 192 | t.Fatal(w.Code) |
| 193 | } |
| 194 | f.now = f.now.Add(IdleLifetime + time.Minute) |
| 195 | if w := f.do("GET", "/", nil, nil); w.Code != 303 { |
| 196 | t.Fatalf("idle session still served: %d", w.Code) |
| 197 | } |
| 198 | } |
| 199 | |
| 200 | func TestCrossOriginPostRefused(t *testing.T) { |
| 201 | f := newFixture(t) |
| 202 | f.signIn(operator) |
| 203 | w := f.do("POST", "/teams", url.Values{"label": {"alpha"}}, map[string]string{"Origin": "https://evil.example"}) |
| 204 | if w.Code != 403 { |
| 205 | t.Fatalf("cross-origin POST: %d", w.Code) |
| 206 | } |
| 207 | } |
| 208 | |
| 209 | func TestInitializeThenNewTeamShowsTheConfirmCeremony(t *testing.T) { |
| 210 | f := newFixture(t) |
| 211 | f.signIn(operator) |
| 212 | if w := f.do("POST", "/initialize", url.Values{"attestation": {"yes"}}, sameOrigin); w.Code != 422 || !strings.Contains(w.Body.String(), "Type the sentence exactly") { |
| 213 | t.Fatalf("bad attestation: %d", w.Code) |
| 214 | } |
| 215 | w := f.do("POST", "/initialize", url.Values{"attestation": {provision.InitializeAttestation}}, sameOrigin) |
| 216 | if w.Code != 303 { |
| 217 | t.Fatalf("initialize: %d %s", w.Code, w.Body.String()) |
| 218 | } |
| 219 | if err := f.home.Confirm(homeop.Directory, ""); err != nil { |
| 220 | t.Fatal(err) |
| 221 | } |
| 222 | id := strings.TrimPrefix(w.Header().Get("Location"), "/runs/") |
| 223 | runID := mustInt(t, id) |
| 224 | if err := f.engine.Advance(context.Background(), runID); err != nil { |
| 225 | t.Fatal(err) |
| 226 | } |
| 227 | f.now = f.now.Add(homeop.WindowLifetime * time.Second) |
| 228 | page := f.do("GET", "/teams/new", nil, nil) |
| 229 | if page.Code != 200 { |
| 230 | t.Fatal(page.Code) |
| 231 | } |
| 232 | scriptless(t, page.Body.String()) |
| 233 | // The profile is chosen per run: outside is the default; samples off. |
| 234 | if b := page.Body.String(); !strings.Contains(b, `name="profile" value="outside" checked`) || strings.Contains(b, `value="own" checked`) || strings.Contains(b, `name="samples" value="1" checked`) { |
| 235 | t.Fatal("the new team form does not default to outside without samples") |
| 236 | } |
| 237 | for label, want := range map[string]string{"docs": "reserved", "xn--lagged": "two hyphens"} { |
| 238 | w = f.do("POST", "/teams", url.Values{"label": {label}, "name": {"X"}, "owner": {owner}, "app": {"docs"}, "profile": {"outside"}}, sameOrigin) |
| 239 | if w.Code != 422 || !strings.Contains(w.Body.String(), want) { |
| 240 | t.Fatalf("label %q: %d", label, w.Code) |
| 241 | } |
| 242 | } |
| 243 | w = f.do("POST", "/teams", url.Values{"label": {"lagged"}, "name": {"X"}, "owner": {owner}, "app": {"docs"}, "profile": {"mine"}}, sameOrigin) |
| 244 | if w.Code != 422 || !strings.Contains(w.Body.String(), "Choose a profile") { |
| 245 | t.Fatalf("unknown profile: %d", w.Code) |
| 246 | } |
| 247 | // A label used before is refused on the form, and the address is |
| 248 | // echoed into the form only. |
| 249 | w = f.do("POST", "/teams", url.Values{"label": {"Bad Label"}, "name": {"Lagged"}, "owner": {owner}, "app": {"docs", "calls"}}, sameOrigin) |
| 250 | if w.Code != 422 || !strings.Contains(w.Body.String(), "lower-case") { |
| 251 | t.Fatalf("bad label: %d", w.Code) |
| 252 | } |
| 253 | w = f.do("POST", "/teams", url.Values{"label": {"lagged"}, "name": {"Lagged"}, "owner": {owner}, "app": {"docs", "calls", "memoria"}, "profile": {"own"}, "samples": {"1"}}, sameOrigin) |
| 254 | if w.Code != 303 { |
| 255 | t.Fatalf("create: %d %s", w.Code, w.Body.String()) |
| 256 | } |
| 257 | run := f.do("GET", w.Header().Get("Location"), nil, nil) |
| 258 | body := run.Body.String() |
| 259 | r, _ := f.store.Run(context.Background(), mustInt(t, strings.TrimPrefix(w.Header().Get("Location"), "/runs/"))) |
| 260 | if r.Options != (provision.RunOptions{Profile: provision.ProfileOwn, Samples: true}) { |
| 261 | t.Fatalf("run options %+v", r.Options) |
| 262 | } |
| 263 | for _, want := range []string{"https://oficina.works/operator/confirm", "https://id.oficina.works/operator/confirm", homeop.PlanPrefix(r.PlanID), "lagged.docs.oficina.works", "Resume", |
| 264 | "Profile <strong>Own</strong>", "Docs sample documents <strong>on</strong>", "After the run: Memoria AI"} { |
| 265 | if !strings.Contains(body, want) { |
| 266 | t.Fatalf("run page lacks %q", want) |
| 267 | } |
| 268 | } |
| 269 | if strings.Contains(body, owner) { |
| 270 | t.Fatal("the run page shows the owner's address") |
| 271 | } |
| 272 | scriptless(t, body) |
| 273 | team := f.do("GET", "/teams/lagged", nil, nil) |
| 274 | if team.Code != 200 || strings.Contains(team.Body.String(), owner) { |
| 275 | t.Fatalf("team page: %d", team.Code) |
| 276 | } |
| 277 | 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") { |
| 278 | t.Fatal("the team page does not show the run's profile") |
| 279 | } |
| 280 | retire := f.do("GET", "/teams/lagged/retire", nil, nil) |
| 281 | if retire.Code != 200 || !strings.Contains(retire.Body.String(), "Type lagged to confirm") { |
| 282 | t.Fatalf("retire page: %d", retire.Code) |
| 283 | } |
| 284 | } |
| 285 | |
| 286 | func mustInt(t *testing.T, s string) int64 { |
| 287 | var n int64 |
| 288 | if err := json.Unmarshal([]byte(s), &n); err != nil { |
| 289 | t.Fatalf("not a run id: %q", s) |
| 290 | } |
| 291 | return n |
| 292 | } |
| 293 | |
| 294 | // Fable's review, blocker 3: an owner Home refuses leaves the label |
| 295 | // recorded; the team page offers the owner form while the team is not |
| 296 | // yet at Home, even though Alta still holds the (wrong) address. |
| 297 | func TestRefusedOwnerLeadsToTheOwnerForm(t *testing.T) { |
| 298 | f := newFixture(t) |
| 299 | f.signIn(operator) |
| 300 | w := f.do("POST", "/initialize", url.Values{"attestation": {provision.InitializeAttestation}}, sameOrigin) |
| 301 | _ = f.home.Confirm(homeop.Directory, "") |
| 302 | _ = f.engine.Advance(context.Background(), mustInt(t, strings.TrimPrefix(w.Header().Get("Location"), "/runs/"))) |
| 303 | f.now = f.now.Add(homeop.WindowLifetime * time.Second) |
| 304 | w = f.do("POST", "/teams", url.Values{"label": {"lagged"}, "name": {"Lagged"}, "owner": {"typo@lagged.test"}, "app": {"sheets"}}, sameOrigin) |
| 305 | if w.Code != 303 || !strings.HasPrefix(w.Header().Get("Location"), "/teams/lagged?audit=plan-refused-credential") { |
| 306 | t.Fatalf("refused owner: %d %s", w.Code, w.Header().Get("Location")) |
| 307 | } |
| 308 | page := f.do("GET", w.Header().Get("Location"), nil, nil).Body.String() |
| 309 | if !strings.Contains(page, `action="/teams/lagged/owner"`) || !strings.Contains(page, "Has the owner signed in") { |
| 310 | t.Fatal("no owner form for an unseeded team") |
| 311 | } |
| 312 | if strings.Contains(page, "typo@lagged.test") { |
| 313 | t.Fatal("the held address is shown") |
| 314 | } |
| 315 | if w := f.do("POST", "/teams/lagged/owner", url.Values{"owner": {owner}}, sameOrigin); w.Code != 303 { |
| 316 | t.Fatalf("retype: %d", w.Code) |
| 317 | } |
| 318 | if got, _, _ := f.store.Owner(context.Background(), "lagged"); got != owner { |
| 319 | t.Fatal("retyped owner not held") |
| 320 | } |
| 321 | // Once the team is seeded at Home, no app takes a retyped owner: a |
| 322 | // seeded app's owner is only ever the address Home confirmed. |
| 323 | if err := f.store.SetSeeded(context.Background(), "lagged", 1, "Uk", 1, "g", "pr_x", nil); err != nil { |
| 324 | t.Fatal(err) |
| 325 | } else { |
| 326 | 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") { |
| 327 | t.Fatalf("retype after the seed: %d %s", w.Code, w.Header().Get("Location")) |
| 328 | } |
| 329 | if got, _, _ := f.store.Owner(context.Background(), "lagged"); got != owner { |
| 330 | t.Fatal("a retype after the seed replaced the owner") |
| 331 | } |
| 332 | } |
| 333 | // A code Alta never produced is not shown as if Alta said it. |
| 334 | if page := f.do("GET", "/teams/lagged?audit=Your+account+is+suspended", nil, nil).Body.String(); strings.Contains(page, "suspended") { |
| 335 | t.Fatal("an arbitrary audit code was reflected") |
| 336 | } |
| 337 | } |
| 338 | |