package webtest import ( "encoding/base64" "encoding/json" "net/http" "net/url" "strings" "sync" "testing" "time" "amadan.net/oficina/base/internal/equipo/equipotest" ) // Ask set up with Oficina ID (docs/api/base-native-v1.md): the native app // posts an assertion addressed to Equipo, and Base completes Equipo's own // native sign-in for the person, keeping the key where the code flow does. // connectWithOficina posts what the native app posts for subject. func (a *testApp) connectWithOficina(f *equipotest.Fake, subject string) Resp { a.t.Helper() assertion, verifier := f.OficinaAssertion(subject) body, _ := json.Marshal(map[string]string{"assertion": assertion, "verifier": verifier}) return a.nativePost("/api/v1/ask/oficina", string(body)) } type askReadyAnswer struct { State string `json:"state"` RenewAfter string `json:"renew_after"` } // equipoLinks is how many Equipo links Base holds. func (a *testApp) equipoLinks() int { a.t.Helper() var n int if err := a.DB.QueryRow(`SELECT count(*) FROM equipo_links`).Scan(&n); err != nil { a.t.Fatal(err) } return n } // liveDevice is the one device the fake holds that is not revoked. func liveDevice(t *testing.T, f *equipotest.Fake) string { t.Helper() var live []string for _, id := range f.Devices() { if !f.Revoked(id) { live = append(live, id) } } if len(live) != 1 { t.Fatalf("live devices: %v", live) } return live[0] } func TestAskOficinaConnect(t *testing.T) { _, app, f := newNativeAskApp(t) f.LinkOficinaID("subject-owner", ownerAddress) r := app.connectWithOficina(f, "subject-owner") if r.Code != 200 || r.Header.Get("Cache-Control") != "no-store" { t.Fatalf("connect: %d %s", r.Code, r.Body) } wantKeys(t, "connect", r.Body, "state", "renew_after") out := decode[askReadyAnswer](t, r) renew, err := time.Parse(time.RFC3339, out.RenewAfter) if out.State != "ready" || err != nil || renew.Sub(time.Now().Add(5*24*time.Hour)).Abs() > time.Minute { t.Fatalf("connect: %s", r.Body) } // Equipo's exchange: what a native app sends, no Origin, no cookie. ex := f.Calls("/native/oficina-id") if len(ex) != 1 || ex[0].Header.Get("Origin") != "" || ex[0].Header.Get("Cookie") != "" || ex[0].Header.Get("Authorization") != "" || ex[0].Header.Get("Content-Type") != "application/json" || len(keysOf(t, ex[0].Body)) != 2 { t.Fatalf("exchange: %+v", ex) } // Then the device, with that session's cookie (and nothing of Base's), // Equipo's own Origin, a fresh key and Base's label. dev := f.Calls("/api/v1/auth/devices/native") if len(dev) != 1 { t.Fatalf("device calls: %d", len(dev)) } h := dev[0].Header if !strings.HasPrefix(h.Get("Cookie"), equipotest.SessionCookie+"=") || strings.Contains(h.Get("Cookie"), sessionCookie) || strings.Contains(h.Get("Cookie"), ";") || h.Get("Origin") != f.URL || h.Get("Authorization") != "" { t.Fatalf("device headers: %v", h) } var in struct { PublicKey string `json:"public_key"` Label string `json:"label"` } _ = json.Unmarshal([]byte(dev[0].Body), &in) if pub, err := base64.RawURLEncoding.DecodeString(in.PublicKey); err != nil || len(pub) != 32 || in.Label != "Base (Acme)" { t.Fatalf("device body: %s", dev[0].Body) } device := liveDevice(t, f) if f.DeviceSession(device) == "" { t.Fatal("the key is not the native session's") } // The Assistant's host is registered with the new key, as Connect does. hosts := f.Hosts() if len(hosts) != 1 || !strings.HasPrefix(hosts[0].Header.Get("Authorization"), "Bearer equipo.person.v1.") { t.Fatalf("hosts: %+v", hosts) } // Ask is ready, and the relay uses the key. s, raw := app.askState() if s.State != "ready" || !strings.Contains(raw.Body, `"renew_after":"`+out.RenewAfter+`"`) { t.Fatalf("state: %s", raw.Body) } if sent := app.nativeForm("/ask/messages", url.Values{"text": {"Hello"}, "key": {"o-1"}}); sent.Code != 200 { t.Fatalf("send: %d %s", sent.Code, sent.Body) } if c := f.Calls("/api/v1/assistant/messages"); len(c) != 1 || c[0].Header.Get("Authorization") != hosts[0].Header.Get("Authorization") { t.Fatalf("relayed with: %+v", c) } // Neither the key nor Equipo's session ever reaches the app. app.noLeak(strings.TrimPrefix(hosts[0].Header.Get("Authorization"), "Bearer ")) app.noLeak(f.DeviceSession(device)) // Base never signs Equipo's session out. for _, c := range f.Calls("") { if strings.Contains(c.Path, "signout") { t.Errorf("Base called %s", c.Path) } } } // A person Equipo has not linked to their Oficina ID: not_linked, and // nothing is stored. func TestAskOficinaUnknown(t *testing.T) { _, app, f := newNativeAskApp(t) wantBody(t, "unlinked", app.connectWithOficina(f, "subject-owner"), 409, `{"state":"not_linked"}`) if n := app.equipoLinks(); n != 0 || len(f.Devices()) != 0 || len(f.Calls("/api/v1/auth/devices/native")) != 0 { t.Fatalf("stored %d links, %d devices", n, len(f.Devices())) } if s, _ := app.askState(); s.State != "connect" { t.Errorf("state: %s", s.State) } } // Equipo's other refusals store nothing either, and never answer 401, // which the app would read as Base's own session ending. func TestAskOficinaEquipoRefusals(t *testing.T) { _, app, f := newNativeAskApp(t) f.LinkOficinaID("subject-owner", ownerAddress) f.FailNextNativeExchange(503) wantBody(t, "Equipo down", app.connectWithOficina(f, "subject-owner"), 502, `{"state":"unavailable"}`) // An assertion Equipo refuses (here, one already used). assertion, verifier := f.OficinaAssertion("subject-owner") body, _ := json.Marshal(map[string]string{"assertion": assertion, "verifier": verifier}) if r := app.nativePost("/api/v1/ask/oficina", string(body)); r.Code != 200 { t.Fatalf("first use: %d %s", r.Code, r.Body) } wantBody(t, "replayed", app.nativePost("/api/v1/ask/oficina", string(body)), 422, `{"state":"failed"}`) if len(f.Devices()) != 1 { t.Errorf("devices: %d", len(f.Devices())) } // What Base can't read. for _, bad := range []string{``, `{}`, `{"assertion":"x"}`, `{"assertion":"x","verifier":"y","extra":1}`, `[1]`} { wantBody(t, "body "+bad, app.nativePost("/api/v1/ask/oficina", bad), 400, `{"state":"invalid"}`) } } // A second post replaces the key and Equipo session, and revokes the old // device in Equipo. func TestAskOficinaRenew(t *testing.T) { _, app, f := newNativeAskApp(t) f.LinkOficinaID("subject-owner", ownerAddress) if r := app.connectWithOficina(f, "subject-owner"); r.Code != 200 { t.Fatalf("first: %d %s", r.Code, r.Body) } first := liveDevice(t, f) if r := app.connectWithOficina(f, "subject-owner"); r.Code != 200 { t.Fatalf("renew: %d %s", r.Code, r.Body) } second := liveDevice(t, f) if second == first || !f.Revoked(first) || f.DeviceSession(second) == f.DeviceSession(first) || f.NativeSessions() != 2 { t.Fatalf("renew: first %s (revoked %v), second %s", first, f.Revoked(first), second) } if n := app.equipoLinks(); n != 1 { t.Errorf("links: %d", n) } if hosts := f.Hosts(); len(hosts) != 2 { t.Errorf("hosts registered: %d", len(hosts)) } if s, _ := app.askState(); s.State != "ready" { t.Errorf("state: %s", s.State) } // Two at once run one at a time: one device is left. var wg sync.WaitGroup for range 2 { wg.Add(1) go func() { defer wg.Done() if r := app.connectWithOficina(f, "subject-owner"); r.Code != 200 { t.Errorf("concurrent: %d %s", r.Code, r.Body) } }() } wg.Wait() liveDevice(t, f) } // The web keeps its code flow: only a native session may post here. func TestAskOficinaRefusesWeb(t *testing.T) { web, _, f := newNativeAskApp(t) f.LinkOficinaID("subject-owner", ownerAddress) browser := web.newBrowser() browser.signInWithOficina("subject-owner") for name, b := range map[string]*testApp{"local": web, "Oficina in a browser": browser} { wantBody(t, name, b.connectWithOficina(f, "subject-owner"), 403, `{"state":"forbidden"}`) } if len(f.Calls("/native/oficina-id")) != 0 { t.Fatal("a browser session reached Equipo") } // From another site it never gets that far. req, _ := http.NewRequest(http.MethodPost, homeOrigin+"/api/v1/ask/oficina", strings.NewReader(`{}`)) req.Header.Set("Content-Type", "application/json") req.Header.Set("Origin", "https://evil.test") if r := web.do(req); r.Code != http.StatusForbidden { t.Errorf("cross-site: %d", r.Code) } } func TestAskStateSaysWhenToRenew(t *testing.T) { web, app, f := newNativeAskApp(t) // A key from the code flow: no renew_after. web.approveEquipo(f) _, r := app.askState() if !strings.Contains(r.Body, `"renew_after":""`) || !strings.Contains(r.Body, `"equipo_origin":"`+f.URL+`"`) { t.Fatalf("code flow: %s", r.Body) } // With Oficina ID: five days after Equipo's session began. f.LinkOficinaID("subject-owner", ownerAddress) out := decode[askReadyAnswer](t, app.connectWithOficina(f, "subject-owner")) _, r = app.askState() if out.RenewAfter == "" || !strings.Contains(r.Body, `"renew_after":"`+out.RenewAfter+`"`) { t.Fatalf("oficina: %s (answered %+v)", r.Body, out) } // It replaced the code flow's key, which is revoked: one key is live. // Equipo ending its session ends the key: Ask asks to reconnect. f.EndNativeSession(f.DeviceSession(liveDevice(t, f))) if s, _ := app.askState(); s.State != "reconnect" { t.Errorf("after Equipo's session ended: %s", s.State) } } func TestDisconnectRevokesOficinaKey(t *testing.T) { _, app, f := newNativeAskApp(t) f.LinkOficinaID("subject-owner", ownerAddress) if r := app.connectWithOficina(f, "subject-owner"); r.Code != 200 { t.Fatalf("connect: %d %s", r.Code, r.Body) } device := liveDevice(t, f) if r := app.post("/ask/disconnect", nil); r.Code != 303 || r.Location() != "/settings" { t.Fatalf("disconnect: %d %q", r.Code, r.Location()) } if !f.Revoked(device) || app.equipoLinks() != 0 { t.Fatalf("revoked %v, links %d", f.Revoked(device), app.equipoLinks()) } if s, _ := app.askState(); s.State != "connect" { t.Errorf("state: %s", s.State) } } // startHeldSetup starts a native set-up that waits at Equipo's exchange, // and returns where its answer will come. func startHeldSetup(t *testing.T, app *testApp, f *equipotest.Fake) (done <-chan Resp, release func()) { t.Helper() entered, release := f.HoldNextNativeExchange() out := make(chan Resp, 1) go func() { out <- app.connectWithOficina(f, "subject-owner") }() select { case <-entered: case r := <-out: t.Fatalf("the set-up never reached Equipo: %d %s", r.Code, r.Body) case <-time.After(5 * time.Second): t.Fatal("the set-up never reached Equipo") } return out, release } // newDevice is the one device the fake holds that is not in before. func newDevice(t *testing.T, f *equipotest.Fake, before []string) string { t.Helper() old := map[string]bool{} for _, id := range before { old[id] = true } var made []string for _, id := range f.Devices() { if !old[id] { made = append(made, id) } } if len(made) != 1 { t.Fatalf("new devices: %v", made) } return made[0] } // A renewal that Disconnect overtakes saves nothing, and revokes the // device it made: Disconnect stays done. func TestAskOficinaSetupOvertakenByDisconnect(t *testing.T) { _, app, f := newNativeAskApp(t) f.LinkOficinaID("subject-owner", ownerAddress) if r := app.connectWithOficina(f, "subject-owner"); r.Code != 200 { t.Fatalf("connect: %d %s", r.Code, r.Body) } first := liveDevice(t, f) done, release := startHeldSetup(t, app, f) if r := app.post("/ask/disconnect", nil); r.Code != 303 { t.Fatalf("disconnect: %d", r.Code) } release() wantBody(t, "overtaken set-up", <-done, 409, `{"state":"superseded"}`) made := newDevice(t, f, []string{first}) if n := app.equipoLinks(); n != 0 || !f.Revoked(first) || !f.Revoked(made) { t.Fatalf("links %d, first revoked %v, new revoked %v", n, f.Revoked(first), f.Revoked(made)) } if hosts := f.Hosts(); len(hosts) != 1 { t.Errorf("hosts registered: %d", len(hosts)) } if s, _ := app.askState(); s.State != "connect" { t.Errorf("state: %s", s.State) } } // A set-up that the web's code flow overtakes saves nothing and revokes // its device; the web's connection stays, the one live device. func TestAskOficinaSetupOvertakenByWebConnect(t *testing.T) { web, app, f := newNativeAskApp(t) f.LinkOficinaID("subject-owner", ownerAddress) done, release := startHeldSetup(t, app, f) web.approveEquipo(f) webDevice := liveDevice(t, f) release() wantBody(t, "overtaken set-up", <-done, 409, `{"state":"superseded"}`) made := newDevice(t, f, []string{webDevice}) if live := liveDevice(t, f); live != webDevice || !f.Revoked(made) { t.Fatalf("live %s (web %s), new revoked %v", live, webDevice, f.Revoked(made)) } if n := app.equipoLinks(); n != 1 { t.Errorf("links: %d", n) } s, r := app.askState() if s.State != "ready" || !strings.Contains(r.Body, `"renew_after":""`) { t.Errorf("state: %s", r.Body) } if sent := app.nativeForm("/ask/messages", url.Values{"text": {"Hi"}, "key": {"w-1"}}); sent.Code != 200 { t.Errorf("send on the web's key: %d %s", sent.Code, sent.Body) } } // A renewal revokes the device it replaces, read as it saves, ready or // not: here a key Base no longer uses (it expired here first) but Equipo // would still take. func TestAskOficinaRenewRevokesWhatItReplaces(t *testing.T) { _, app, f := newNativeAskApp(t) f.LinkOficinaID("subject-owner", ownerAddress) if r := app.connectWithOficina(f, "subject-owner"); r.Code != 200 { t.Fatalf("connect: %d %s", r.Code, r.Body) } first := liveDevice(t, f) if _, err := app.DB.Exec(`UPDATE equipo_links SET expires_at = ?`, time.Now().Add(-time.Minute).UTC()); err != nil { t.Fatal(err) } if s, _ := app.askState(); s.State != "reconnect" { t.Fatalf("state: %s", s.State) } if r := app.connectWithOficina(f, "subject-owner"); r.Code != 200 { t.Fatalf("renew: %d %s", r.Code, r.Body) } if !f.Revoked(first) { t.Fatal("the replaced device is still live in Equipo") } liveDevice(t, f) }