package webtest import ( "context" "encoding/json" "net/http" "net/url" "strconv" "strings" "testing" "time" "amadan.net/oficina/base/internal/equipo" "amadan.net/oficina/base/internal/equipo/equipotest" "amadan.net/oficina/base/internal/store" ) // capsOfLast is the Base-Capabilities header of the newest call to path, // and whether the header was there at all. func capsOfLast(t *testing.T, f *equipotest.Fake, path string) (string, bool) { t.Helper() calls := f.Calls(path) if len(calls) == 0 { t.Fatalf("no call to %s", path) } v, ok := calls[len(calls)-1].Header["Base-Capabilities"] if !ok { return "", false } return strings.Join(v, ","), true } const snapshotPath = "/api/v1/assistant/snapshot" // wantCaps fails unless the newest call to path carried // Base-Capabilities: lookup_answers (have) or none at all (!have). func wantCaps(t *testing.T, f *equipotest.Fake, path, where string, have bool) { t.Helper() caps, ok := capsOfLast(t, f, path) if have && (!ok || caps != equipo.CapLookupAnswers) || !have && ok { t.Errorf("%s: Base-Capabilities %q (%v), want it %v", where, caps, ok, have) } } // A member who uses only the web is told, on Equipo's every call, that // Base draws lookup answers. func TestAskCapsWebOnly(t *testing.T) { a, f := newAskApp(t) a.approveEquipo(f) if r := a.get("/ask"); r.Code != 200 { t.Fatalf("/ask: %d", r.Code) } wantCaps(t, f, snapshotPath, "the web", true) } // One native app that called without saying it draws lookups withholds // the capability for the member, on the web too, until it calls with it, // or until it was last seen more than 30 days ago. func TestAskCapsWithheldForOldNative(t *testing.T) { web, app, f := newNativeAskApp(t) web.approveEquipo(f) want := func(where string, have bool) { t.Helper(); wantCaps(t, f, snapshotPath, where, have) } app.askState() want("an old app's own read", false) if r := web.get("/ask"); r.Code != 200 { t.Fatalf("/ask: %d", r.Code) } want("the web, while the old app is in use", false) app.header = http.Header{"Base-Client-Capabilities": {"job_actions, " + equipo.CapLookupAnswers}} app.askState() want("the app, upgraded", true) web.get("/ask") want("the web, once the app is upgraded", true) // A write says nothing of what the app draws: it changes nothing. bare := *app bare.header = nil if r := bare.nativeForm("/ask/messages", url.Values{"text": {"Hi"}, "key": {"caps-w"}}); r.Code != 200 { t.Fatalf("send: %d %s", r.Code, r.Body) } web.get("/ask") want("the web, after the upgraded app wrote", true) app.header = nil app.askState() want("the app, downgraded", false) // The app's kit sets no header of its own: the same list as a query // parameter counts alike. if r := app.nativeGet("/ask/state?client_caps=" + equipo.CapLookupAnswers); r.Code != 200 { t.Fatalf("/ask/state: %d", r.Code) } want("the app, saying so in the query", true) app.askState() want("the app, downgraded again", false) if _, err := web.DB.Exec(`UPDATE ask_clients SET seen_at = ?`, time.Now().Add(-31*24*time.Hour).UTC()); err != nil { t.Fatal(err) } web.get("/ask") want("the web, the old app unseen for 31 days", true) } // Every relayed call carries the header: the snapshot, the event stream, // a message, a card's answer, Carry on now and the time zone. The host's // registration carries it too, with its body as it always was. func TestCapabilityHeaderOnEveryCall(t *testing.T) { web, app, f := newNativeAskApp(t) // The member's app says what it draws before they connect. app.header = http.Header{"Base-Client-Capabilities": {equipo.CapLookupAnswers}} app.askState() web.approveEquipo(f) web.get("/ask") for i := 0; i < 200 && len(f.Calls("/api/v1/assistant/time-zone")) == 0; i++ { time.Sleep(10 * time.Millisecond) } card := f.AskQuestion("Which colour?", "Blue", "Green") job := f.AskJob("A form") f.PauseJob(job, "Paused until 21:00", "It has reached the limit on its plan for now.", true) if r := web.post("/ask/messages", url.Values{"text": {"Hello"}, "key": {"caps-1"}}); r.Code != 303 { t.Fatalf("send: %d %s", r.Code, r.Body) } if r := web.post("/ask/cards/"+card+"/answer", url.Values{"choice": {"Blue"}, "revision": {"1"}, "key": {"caps-2"}}); r.Code != 303 { t.Fatalf("answer: %d %s", r.Code, r.Body) } rev := int64(3) // asked, paused, carry_on offered: the fake's revisions if r := web.post("/ask/cards/"+job+"/carry_on", url.Values{"revision": {strconv.FormatInt(rev, 10)}, "key": {"caps-3"}}); r.Code != 303 { t.Fatalf("carry on: %d %s", r.Code, r.Body) } web.events(t, "0", func(got []sseFrame) bool { return len(got) >= 2 }) for _, p := range []string{snapshotPath, "/api/v1/assistant/events", "/api/v1/assistant/messages", "/api/v1/assistant/cards/" + card + "/answer", "/api/v1/assistant/cards/" + job + "/carry_on", "/api/v1/assistant/time-zone", "/api/v1/assistant/host"} { wantCaps(t, f, p, p, true) } hosts := f.Hosts() var body map[string]string if err := json.Unmarshal([]byte(hosts[len(hosts)-1].Body), &body); err != nil || len(body) != 2 || body["origin"] == "" || body["token"] == "" { t.Errorf("host body %q: %v", hosts[len(hosts)-1].Body, err) } n, err := store.MemberNumber(context.Background(), web.DB, web.ownerID()) if err != nil { t.Fatal(err) } // The web is never recorded as a client: only the app is. if got, err := store.AskClients(context.Background(), web.DB, n, time.Time{}); err != nil || len(got) != 1 { t.Errorf("clients recorded: %+v %v", got, err) } } // A native session Base has never heard from on /ask (an app opened // before this Base, or one whose record failed before a restart) holds // the member back (Astra round 2); one whose first request is a write is // recorded as drawing nothing (round 1), and a write keeps an old app's // 30-day window open. func TestAskCapsNativeWriteFirst(t *testing.T) { web, app, f := newNativeAskApp(t) web.approveEquipo(f) web.get("/ask") wantCaps(t, f, snapshotPath, "an app never heard from", false) if r := app.nativeForm("/ask/messages", url.Values{"text": {"Hi"}, "key": {"first-w"}}); r.Code != 200 { t.Fatalf("send: %d %s", r.Code, r.Body) } web.get("/ask") wantCaps(t, f, snapshotPath, "an app seen only writing", false) old := time.Now().Add(-29 * 24 * time.Hour).UTC() if _, err := web.DB.Exec(`UPDATE ask_clients SET seen_at = ?`, old); err != nil { t.Fatal(err) } if r := app.nativeForm("/ask/messages", url.Values{"text": {"Again"}, "key": {"first-w2"}}); r.Code != 200 { t.Fatalf("send: %d %s", r.Code, r.Body) } var seen time.Time if err := web.DB.QueryRow(`SELECT seen_at FROM ask_clients`).Scan(&seen); err != nil || !seen.After(old.Add(time.Hour)) { t.Errorf("a write didn't keep the app's window open: %v %v", seen, err) } app.header = http.Header{"Base-Client-Capabilities": {equipo.CapLookupAnswers}} app.askState() web.get("/ask") wantCaps(t, f, snapshotPath, "once the app said so", true) } // When Base can't record what an app said, the member is told to draw // nothing until it can, on every request, not just that one (Astra // round 1, P1-3). func TestAskCapsRecordFailureHoldsBack(t *testing.T) { web, app, f := newNativeAskApp(t) web.approveEquipo(f) want := func(where string, have bool) { t.Helper(); web.get("/ask"); wantCaps(t, f, snapshotPath, where, have) } app.header = http.Header{"Base-Client-Capabilities": {equipo.CapLookupAnswers}} app.askState() want("the app says it draws them", true) for _, q := range []string{ `CREATE TRIGGER no_insert BEFORE INSERT ON ask_clients BEGIN SELECT RAISE(ABORT, 'refused'); END`, `CREATE TRIGGER no_update BEFORE UPDATE ON ask_clients BEGIN SELECT RAISE(ABORT, 'refused'); END`, } { if _, err := web.DB.Exec(q); err != nil { t.Fatal(err) } } // Downgraded, its read can't be recorded: held back from then on, // and not only in this process (the app's row is gone, and its // session is one Base knows nothing of). app.header = nil app.askState() want("the app's downgrade went unrecorded", false) var rows int if err := web.DB.QueryRow(`SELECT count(*) FROM ask_clients`).Scan(&rows); err != nil || rows != 0 { t.Errorf("%d rows left for a client Base couldn't record: %v", rows, err) } // A write that can't be recorded either holds it back too, and one // that can doesn't undo that. if r := app.nativeForm("/ask/messages", url.Values{"text": {"Hi"}, "key": {"held-w"}}); r.Code != 200 { t.Fatalf("send: %d", r.Code) } want("after a write", false) for _, q := range []string{`DROP TRIGGER no_insert`, `DROP TRIGGER no_update`} { if _, err := web.DB.Exec(q); err != nil { t.Fatal(err) } } if r := app.nativeForm("/ask/messages", url.Values{"text": {"Again"}, "key": {"held-w2"}}); r.Code != 200 { t.Fatalf("send: %d", r.Code) } want("after a recorded write", false) app.header = http.Header{"Base-Client-Capabilities": {equipo.CapLookupAnswers}} app.askState() want("once recorded", true) }