| 1 | package webtest |
| 2 | |
| 3 | import ( |
| 4 | "encoding/base64" |
| 5 | "encoding/json" |
| 6 | "net/http" |
| 7 | "net/url" |
| 8 | "strings" |
| 9 | "sync" |
| 10 | "testing" |
| 11 | "time" |
| 12 | |
| 13 | "amadan.net/oficina/base/internal/equipo/equipotest" |
| 14 | ) |
| 15 | |
| 16 | // Ask set up with Oficina ID (docs/api/base-native-v1.md): the native app |
| 17 | // posts an assertion addressed to Equipo, and Base completes Equipo's own |
| 18 | // native sign-in for the person, keeping the key where the code flow does. |
| 19 | |
| 20 | // connectWithOficina posts what the native app posts for subject. |
| 21 | func (a *testApp) connectWithOficina(f *equipotest.Fake, subject string) Resp { |
| 22 | a.t.Helper() |
| 23 | assertion, verifier := f.OficinaAssertion(subject) |
| 24 | body, _ := json.Marshal(map[string]string{"assertion": assertion, "verifier": verifier}) |
| 25 | return a.nativePost("/api/v1/ask/oficina", string(body)) |
| 26 | } |
| 27 | |
| 28 | type askReadyAnswer struct { |
| 29 | State string `json:"state"` |
| 30 | RenewAfter string `json:"renew_after"` |
| 31 | } |
| 32 | |
| 33 | // equipoLinks is how many Equipo links Base holds. |
| 34 | func (a *testApp) equipoLinks() int { |
| 35 | a.t.Helper() |
| 36 | var n int |
| 37 | if err := a.DB.QueryRow(`SELECT count(*) FROM equipo_links`).Scan(&n); err != nil { |
| 38 | a.t.Fatal(err) |
| 39 | } |
| 40 | return n |
| 41 | } |
| 42 | |
| 43 | // liveDevice is the one device the fake holds that is not revoked. |
| 44 | func liveDevice(t *testing.T, f *equipotest.Fake) string { |
| 45 | t.Helper() |
| 46 | var live []string |
| 47 | for _, id := range f.Devices() { |
| 48 | if !f.Revoked(id) { |
| 49 | live = append(live, id) |
| 50 | } |
| 51 | } |
| 52 | if len(live) != 1 { |
| 53 | t.Fatalf("live devices: %v", live) |
| 54 | } |
| 55 | return live[0] |
| 56 | } |
| 57 | |
| 58 | func TestAskOficinaConnect(t *testing.T) { |
| 59 | _, app, f := newNativeAskApp(t) |
| 60 | f.LinkOficinaID("subject-owner", ownerAddress) |
| 61 | r := app.connectWithOficina(f, "subject-owner") |
| 62 | if r.Code != 200 || r.Header.Get("Cache-Control") != "no-store" { |
| 63 | t.Fatalf("connect: %d %s", r.Code, r.Body) |
| 64 | } |
| 65 | wantKeys(t, "connect", r.Body, "state", "renew_after") |
| 66 | out := decode[askReadyAnswer](t, r) |
| 67 | renew, err := time.Parse(time.RFC3339, out.RenewAfter) |
| 68 | if out.State != "ready" || err != nil || renew.Sub(time.Now().Add(5*24*time.Hour)).Abs() > time.Minute { |
| 69 | t.Fatalf("connect: %s", r.Body) |
| 70 | } |
| 71 | |
| 72 | // Equipo's exchange: what a native app sends, no Origin, no cookie. |
| 73 | ex := f.Calls("/native/oficina-id") |
| 74 | if len(ex) != 1 || ex[0].Header.Get("Origin") != "" || ex[0].Header.Get("Cookie") != "" || ex[0].Header.Get("Authorization") != "" || |
| 75 | ex[0].Header.Get("Content-Type") != "application/json" || len(keysOf(t, ex[0].Body)) != 2 { |
| 76 | t.Fatalf("exchange: %+v", ex) |
| 77 | } |
| 78 | // Then the device, with that session's cookie (and nothing of Base's), |
| 79 | // Equipo's own Origin, a fresh key and Base's label. |
| 80 | dev := f.Calls("/api/v1/auth/devices/native") |
| 81 | if len(dev) != 1 { |
| 82 | t.Fatalf("device calls: %d", len(dev)) |
| 83 | } |
| 84 | h := dev[0].Header |
| 85 | if !strings.HasPrefix(h.Get("Cookie"), equipotest.SessionCookie+"=") || strings.Contains(h.Get("Cookie"), sessionCookie) || |
| 86 | strings.Contains(h.Get("Cookie"), ";") || h.Get("Origin") != f.URL || h.Get("Authorization") != "" { |
| 87 | t.Fatalf("device headers: %v", h) |
| 88 | } |
| 89 | var in struct { |
| 90 | PublicKey string `json:"public_key"` |
| 91 | Label string `json:"label"` |
| 92 | } |
| 93 | _ = json.Unmarshal([]byte(dev[0].Body), &in) |
| 94 | if pub, err := base64.RawURLEncoding.DecodeString(in.PublicKey); err != nil || len(pub) != 32 || in.Label != "Base (Acme)" { |
| 95 | t.Fatalf("device body: %s", dev[0].Body) |
| 96 | } |
| 97 | device := liveDevice(t, f) |
| 98 | if f.DeviceSession(device) == "" { |
| 99 | t.Fatal("the key is not the native session's") |
| 100 | } |
| 101 | // The Assistant's host is registered with the new key, as Connect does. |
| 102 | hosts := f.Hosts() |
| 103 | if len(hosts) != 1 || !strings.HasPrefix(hosts[0].Header.Get("Authorization"), "Bearer equipo.person.v1.") { |
| 104 | t.Fatalf("hosts: %+v", hosts) |
| 105 | } |
| 106 | // Ask is ready, and the relay uses the key. |
| 107 | s, raw := app.askState() |
| 108 | if s.State != "ready" || !strings.Contains(raw.Body, `"renew_after":"`+out.RenewAfter+`"`) { |
| 109 | t.Fatalf("state: %s", raw.Body) |
| 110 | } |
| 111 | if sent := app.nativeForm("/ask/messages", url.Values{"text": {"Hello"}, "key": {"o-1"}}); sent.Code != 200 { |
| 112 | t.Fatalf("send: %d %s", sent.Code, sent.Body) |
| 113 | } |
| 114 | if c := f.Calls("/api/v1/assistant/messages"); len(c) != 1 || c[0].Header.Get("Authorization") != hosts[0].Header.Get("Authorization") { |
| 115 | t.Fatalf("relayed with: %+v", c) |
| 116 | } |
| 117 | // Neither the key nor Equipo's session ever reaches the app. |
| 118 | app.noLeak(strings.TrimPrefix(hosts[0].Header.Get("Authorization"), "Bearer ")) |
| 119 | app.noLeak(f.DeviceSession(device)) |
| 120 | // Base never signs Equipo's session out. |
| 121 | for _, c := range f.Calls("") { |
| 122 | if strings.Contains(c.Path, "signout") { |
| 123 | t.Errorf("Base called %s", c.Path) |
| 124 | } |
| 125 | } |
| 126 | } |
| 127 | |
| 128 | // A person Equipo has not linked to their Oficina ID: not_linked, and |
| 129 | // nothing is stored. |
| 130 | func TestAskOficinaUnknown(t *testing.T) { |
| 131 | _, app, f := newNativeAskApp(t) |
| 132 | wantBody(t, "unlinked", app.connectWithOficina(f, "subject-owner"), 409, `{"state":"not_linked"}`) |
| 133 | if n := app.equipoLinks(); n != 0 || len(f.Devices()) != 0 || len(f.Calls("/api/v1/auth/devices/native")) != 0 { |
| 134 | t.Fatalf("stored %d links, %d devices", n, len(f.Devices())) |
| 135 | } |
| 136 | if s, _ := app.askState(); s.State != "connect" { |
| 137 | t.Errorf("state: %s", s.State) |
| 138 | } |
| 139 | } |
| 140 | |
| 141 | // Equipo's other refusals store nothing either, and never answer 401, |
| 142 | // which the app would read as Base's own session ending. |
| 143 | func TestAskOficinaEquipoRefusals(t *testing.T) { |
| 144 | _, app, f := newNativeAskApp(t) |
| 145 | f.LinkOficinaID("subject-owner", ownerAddress) |
| 146 | f.FailNextNativeExchange(503) |
| 147 | wantBody(t, "Equipo down", app.connectWithOficina(f, "subject-owner"), 502, `{"state":"unavailable"}`) |
| 148 | // An assertion Equipo refuses (here, one already used). |
| 149 | assertion, verifier := f.OficinaAssertion("subject-owner") |
| 150 | body, _ := json.Marshal(map[string]string{"assertion": assertion, "verifier": verifier}) |
| 151 | if r := app.nativePost("/api/v1/ask/oficina", string(body)); r.Code != 200 { |
| 152 | t.Fatalf("first use: %d %s", r.Code, r.Body) |
| 153 | } |
| 154 | wantBody(t, "replayed", app.nativePost("/api/v1/ask/oficina", string(body)), 422, `{"state":"failed"}`) |
| 155 | if len(f.Devices()) != 1 { |
| 156 | t.Errorf("devices: %d", len(f.Devices())) |
| 157 | } |
| 158 | // What Base can't read. |
| 159 | for _, bad := range []string{``, `{}`, `{"assertion":"x"}`, `{"assertion":"x","verifier":"y","extra":1}`, `[1]`} { |
| 160 | wantBody(t, "body "+bad, app.nativePost("/api/v1/ask/oficina", bad), 400, `{"state":"invalid"}`) |
| 161 | } |
| 162 | } |
| 163 | |
| 164 | // A second post replaces the key and Equipo session, and revokes the old |
| 165 | // device in Equipo. |
| 166 | func TestAskOficinaRenew(t *testing.T) { |
| 167 | _, app, f := newNativeAskApp(t) |
| 168 | f.LinkOficinaID("subject-owner", ownerAddress) |
| 169 | if r := app.connectWithOficina(f, "subject-owner"); r.Code != 200 { |
| 170 | t.Fatalf("first: %d %s", r.Code, r.Body) |
| 171 | } |
| 172 | first := liveDevice(t, f) |
| 173 | if r := app.connectWithOficina(f, "subject-owner"); r.Code != 200 { |
| 174 | t.Fatalf("renew: %d %s", r.Code, r.Body) |
| 175 | } |
| 176 | second := liveDevice(t, f) |
| 177 | if second == first || !f.Revoked(first) || f.DeviceSession(second) == f.DeviceSession(first) || f.NativeSessions() != 2 { |
| 178 | t.Fatalf("renew: first %s (revoked %v), second %s", first, f.Revoked(first), second) |
| 179 | } |
| 180 | if n := app.equipoLinks(); n != 1 { |
| 181 | t.Errorf("links: %d", n) |
| 182 | } |
| 183 | if hosts := f.Hosts(); len(hosts) != 2 { |
| 184 | t.Errorf("hosts registered: %d", len(hosts)) |
| 185 | } |
| 186 | if s, _ := app.askState(); s.State != "ready" { |
| 187 | t.Errorf("state: %s", s.State) |
| 188 | } |
| 189 | // Two at once run one at a time: one device is left. |
| 190 | var wg sync.WaitGroup |
| 191 | for range 2 { |
| 192 | wg.Add(1) |
| 193 | go func() { |
| 194 | defer wg.Done() |
| 195 | if r := app.connectWithOficina(f, "subject-owner"); r.Code != 200 { |
| 196 | t.Errorf("concurrent: %d %s", r.Code, r.Body) |
| 197 | } |
| 198 | }() |
| 199 | } |
| 200 | wg.Wait() |
| 201 | liveDevice(t, f) |
| 202 | } |
| 203 | |
| 204 | // The web keeps its code flow: only a native session may post here. |
| 205 | func TestAskOficinaRefusesWeb(t *testing.T) { |
| 206 | web, _, f := newNativeAskApp(t) |
| 207 | f.LinkOficinaID("subject-owner", ownerAddress) |
| 208 | browser := web.newBrowser() |
| 209 | browser.signInWithOficina("subject-owner") |
| 210 | for name, b := range map[string]*testApp{"local": web, "Oficina in a browser": browser} { |
| 211 | wantBody(t, name, b.connectWithOficina(f, "subject-owner"), 403, `{"state":"forbidden"}`) |
| 212 | } |
| 213 | if len(f.Calls("/native/oficina-id")) != 0 { |
| 214 | t.Fatal("a browser session reached Equipo") |
| 215 | } |
| 216 | // From another site it never gets that far. |
| 217 | req, _ := http.NewRequest(http.MethodPost, homeOrigin+"/api/v1/ask/oficina", strings.NewReader(`{}`)) |
| 218 | req.Header.Set("Content-Type", "application/json") |
| 219 | req.Header.Set("Origin", "https://evil.test") |
| 220 | if r := web.do(req); r.Code != http.StatusForbidden { |
| 221 | t.Errorf("cross-site: %d", r.Code) |
| 222 | } |
| 223 | } |
| 224 | |
| 225 | func TestAskStateSaysWhenToRenew(t *testing.T) { |
| 226 | web, app, f := newNativeAskApp(t) |
| 227 | // A key from the code flow: no renew_after. |
| 228 | web.approveEquipo(f) |
| 229 | _, r := app.askState() |
| 230 | if !strings.Contains(r.Body, `"renew_after":""`) || !strings.Contains(r.Body, `"equipo_origin":"`+f.URL+`"`) { |
| 231 | t.Fatalf("code flow: %s", r.Body) |
| 232 | } |
| 233 | // With Oficina ID: five days after Equipo's session began. |
| 234 | f.LinkOficinaID("subject-owner", ownerAddress) |
| 235 | out := decode[askReadyAnswer](t, app.connectWithOficina(f, "subject-owner")) |
| 236 | _, r = app.askState() |
| 237 | if out.RenewAfter == "" || !strings.Contains(r.Body, `"renew_after":"`+out.RenewAfter+`"`) { |
| 238 | t.Fatalf("oficina: %s (answered %+v)", r.Body, out) |
| 239 | } |
| 240 | // It replaced the code flow's key, which is revoked: one key is live. |
| 241 | // Equipo ending its session ends the key: Ask asks to reconnect. |
| 242 | f.EndNativeSession(f.DeviceSession(liveDevice(t, f))) |
| 243 | if s, _ := app.askState(); s.State != "reconnect" { |
| 244 | t.Errorf("after Equipo's session ended: %s", s.State) |
| 245 | } |
| 246 | } |
| 247 | |
| 248 | func TestDisconnectRevokesOficinaKey(t *testing.T) { |
| 249 | _, app, f := newNativeAskApp(t) |
| 250 | f.LinkOficinaID("subject-owner", ownerAddress) |
| 251 | if r := app.connectWithOficina(f, "subject-owner"); r.Code != 200 { |
| 252 | t.Fatalf("connect: %d %s", r.Code, r.Body) |
| 253 | } |
| 254 | device := liveDevice(t, f) |
| 255 | if r := app.post("/ask/disconnect", nil); r.Code != 303 || r.Location() != "/settings" { |
| 256 | t.Fatalf("disconnect: %d %q", r.Code, r.Location()) |
| 257 | } |
| 258 | if !f.Revoked(device) || app.equipoLinks() != 0 { |
| 259 | t.Fatalf("revoked %v, links %d", f.Revoked(device), app.equipoLinks()) |
| 260 | } |
| 261 | if s, _ := app.askState(); s.State != "connect" { |
| 262 | t.Errorf("state: %s", s.State) |
| 263 | } |
| 264 | } |
| 265 | |
| 266 | // startHeldSetup starts a native set-up that waits at Equipo's exchange, |
| 267 | // and returns where its answer will come. |
| 268 | func startHeldSetup(t *testing.T, app *testApp, f *equipotest.Fake) (done <-chan Resp, release func()) { |
| 269 | t.Helper() |
| 270 | entered, release := f.HoldNextNativeExchange() |
| 271 | out := make(chan Resp, 1) |
| 272 | go func() { out <- app.connectWithOficina(f, "subject-owner") }() |
| 273 | select { |
| 274 | case <-entered: |
| 275 | case r := <-out: |
| 276 | t.Fatalf("the set-up never reached Equipo: %d %s", r.Code, r.Body) |
| 277 | case <-time.After(5 * time.Second): |
| 278 | t.Fatal("the set-up never reached Equipo") |
| 279 | } |
| 280 | return out, release |
| 281 | } |
| 282 | |
| 283 | // newDevice is the one device the fake holds that is not in before. |
| 284 | func newDevice(t *testing.T, f *equipotest.Fake, before []string) string { |
| 285 | t.Helper() |
| 286 | old := map[string]bool{} |
| 287 | for _, id := range before { |
| 288 | old[id] = true |
| 289 | } |
| 290 | var made []string |
| 291 | for _, id := range f.Devices() { |
| 292 | if !old[id] { |
| 293 | made = append(made, id) |
| 294 | } |
| 295 | } |
| 296 | if len(made) != 1 { |
| 297 | t.Fatalf("new devices: %v", made) |
| 298 | } |
| 299 | return made[0] |
| 300 | } |
| 301 | |
| 302 | // A renewal that Disconnect overtakes saves nothing, and revokes the |
| 303 | // device it made: Disconnect stays done. |
| 304 | func TestAskOficinaSetupOvertakenByDisconnect(t *testing.T) { |
| 305 | _, app, f := newNativeAskApp(t) |
| 306 | f.LinkOficinaID("subject-owner", ownerAddress) |
| 307 | if r := app.connectWithOficina(f, "subject-owner"); r.Code != 200 { |
| 308 | t.Fatalf("connect: %d %s", r.Code, r.Body) |
| 309 | } |
| 310 | first := liveDevice(t, f) |
| 311 | done, release := startHeldSetup(t, app, f) |
| 312 | if r := app.post("/ask/disconnect", nil); r.Code != 303 { |
| 313 | t.Fatalf("disconnect: %d", r.Code) |
| 314 | } |
| 315 | release() |
| 316 | wantBody(t, "overtaken set-up", <-done, 409, `{"state":"superseded"}`) |
| 317 | made := newDevice(t, f, []string{first}) |
| 318 | if n := app.equipoLinks(); n != 0 || !f.Revoked(first) || !f.Revoked(made) { |
| 319 | t.Fatalf("links %d, first revoked %v, new revoked %v", n, f.Revoked(first), f.Revoked(made)) |
| 320 | } |
| 321 | if hosts := f.Hosts(); len(hosts) != 1 { |
| 322 | t.Errorf("hosts registered: %d", len(hosts)) |
| 323 | } |
| 324 | if s, _ := app.askState(); s.State != "connect" { |
| 325 | t.Errorf("state: %s", s.State) |
| 326 | } |
| 327 | } |
| 328 | |
| 329 | // A set-up that the web's code flow overtakes saves nothing and revokes |
| 330 | // its device; the web's connection stays, the one live device. |
| 331 | func TestAskOficinaSetupOvertakenByWebConnect(t *testing.T) { |
| 332 | web, app, f := newNativeAskApp(t) |
| 333 | f.LinkOficinaID("subject-owner", ownerAddress) |
| 334 | done, release := startHeldSetup(t, app, f) |
| 335 | web.approveEquipo(f) |
| 336 | webDevice := liveDevice(t, f) |
| 337 | release() |
| 338 | wantBody(t, "overtaken set-up", <-done, 409, `{"state":"superseded"}`) |
| 339 | made := newDevice(t, f, []string{webDevice}) |
| 340 | if live := liveDevice(t, f); live != webDevice || !f.Revoked(made) { |
| 341 | t.Fatalf("live %s (web %s), new revoked %v", live, webDevice, f.Revoked(made)) |
| 342 | } |
| 343 | if n := app.equipoLinks(); n != 1 { |
| 344 | t.Errorf("links: %d", n) |
| 345 | } |
| 346 | s, r := app.askState() |
| 347 | if s.State != "ready" || !strings.Contains(r.Body, `"renew_after":""`) { |
| 348 | t.Errorf("state: %s", r.Body) |
| 349 | } |
| 350 | if sent := app.nativeForm("/ask/messages", url.Values{"text": {"Hi"}, "key": {"w-1"}}); sent.Code != 200 { |
| 351 | t.Errorf("send on the web's key: %d %s", sent.Code, sent.Body) |
| 352 | } |
| 353 | } |
| 354 | |
| 355 | // A renewal revokes the device it replaces, read as it saves, ready or |
| 356 | // not: here a key Base no longer uses (it expired here first) but Equipo |
| 357 | // would still take. |
| 358 | func TestAskOficinaRenewRevokesWhatItReplaces(t *testing.T) { |
| 359 | _, app, f := newNativeAskApp(t) |
| 360 | f.LinkOficinaID("subject-owner", ownerAddress) |
| 361 | if r := app.connectWithOficina(f, "subject-owner"); r.Code != 200 { |
| 362 | t.Fatalf("connect: %d %s", r.Code, r.Body) |
| 363 | } |
| 364 | first := liveDevice(t, f) |
| 365 | if _, err := app.DB.Exec(`UPDATE equipo_links SET expires_at = ?`, time.Now().Add(-time.Minute).UTC()); err != nil { |
| 366 | t.Fatal(err) |
| 367 | } |
| 368 | if s, _ := app.askState(); s.State != "reconnect" { |
| 369 | t.Fatalf("state: %s", s.State) |
| 370 | } |
| 371 | if r := app.connectWithOficina(f, "subject-owner"); r.Code != 200 { |
| 372 | t.Fatalf("renew: %d %s", r.Code, r.Body) |
| 373 | } |
| 374 | if !f.Revoked(first) { |
| 375 | t.Fatal("the replaced device is still live in Equipo") |
| 376 | } |
| 377 | liveDevice(t, f) |
| 378 | } |
| 379 | |