oficina / memoria Public

Clone
git clone https://amadan.net/oficina/memoria

Plain git — no account needed to clone.

Download

Download this file

1package memoria
2
3import (
4 "bytes"
5 "html"
6 "net/http"
7 "net/http/httptest"
8 "strings"
9 "testing"
10 "time"
11
12 "amadan.net/oficina/home/connect"
13 assertioncrypto "amadan.net/rastrillo/rastrillo/crypto"
14)
15
16// The account menu's "Connect your Oficina account" follows the STORED
17// link, not how this session signed in (Paul hit it on 2026-10-24: linked,
18// signed in with Memoria's own email link, and still offered the item).
19//
20// Each test below was seen to fail with the fix reverted; the comment on
21// each says what was reverted and what went red.
22
23const unlinkedSubject = "opaque-unlinked-alice"
24
25// offersConnect is whether a page's account menu offers the connection.
26func offersConnect(body string) bool {
27 return strings.Contains(body, `href="/account/home"`) && strings.Contains(body, "Connect your Oficina account")
28}
29
30// signedInPage is GET / for a signed-in viewer, or the test fails.
31func (f *homeRouterFixture) signedInPage(t *testing.T) string {
32 t.Helper()
33 w := f.do("GET", "/", "")
34 b := w.Body.String()
35 if w.Code != http.StatusOK || !strings.Contains(b, "estilo-account") {
36 t.Fatalf("GET / = %d, not signed in:\n%s", w.Code, b)
37 }
38 return b
39}
40
41// linkFromMenu runs the menu's link flow for the signed-in local session
42// against subject, up to and including the confirm POST, and returns the
43// POST's answer.
44func (f *homeRouterFixture) linkFromMenu(t *testing.T, subject string) *httptest.ResponseRecorder {
45 t.Helper()
46 if w := f.do("GET", "/account/home", ""); w.Code != http.StatusOK {
47 t.Fatal("link page", w.Code, w.Body.String())
48 }
49 start := homeRedirect(t, f.do("POST", "/account/home", ""))
50 if got := homeRedirect(t, f.exchange(t, start, subject)); got != "/account/home/confirm" {
51 t.Fatal("wrong proof landing", got)
52 }
53 if w := f.do("GET", "/account/home/confirm", ""); w.Code != http.StatusOK {
54 t.Fatal("confirm page", w.Code, w.Body.String())
55 }
56 return f.do("POST", "/account/home/confirm", "")
57}
58
59// linkRows counts home_identity_links rows for subject.
60func (f *homeRouterFixture) linkRows(t *testing.T, subject string) int {
61 t.Helper()
62 var n int
63 if err := f.app.db.Writer().QueryRow("SELECT COUNT(*) FROM home_identity_links WHERE subject=?", subject).Scan(&n); err != nil {
64 t.Fatal(err)
65 }
66 return n
67}
68
69// formFoot is the one rst-form-foot row of a connect page, or the test
70// fails. The row holds a form and a link, never a div, so it ends at the
71// first </div>.
72func formFoot(t *testing.T, page string) string {
73 t.Helper()
74 if n := strings.Count(page, "<div rst-form-foot>"); n != 1 {
75 t.Fatalf("%d rst-form-foot rows, want one:\n%s", n, page)
76 }
77 i := strings.Index(page, "<div rst-form-foot>")
78 j := strings.Index(page[i:], "</div>")
79 return page[i : i+j]
80}
81
82// The presence half. Never linked: offered, before /account/home has
83// allocated the local identity row (an ordinary local sign-in allocates
84// none) and after. Seen red with offersHomeLink answering false when no
85// identity row exists, and again when it answered false for a row with no
86// link (mutations of the fix, since the bug was an absence, not a
87// presence).
88func TestConnectItemOfferedToAnUnlinkedLocalSession(t *testing.T) {
89 f := newHomeRouterFixture(t)
90 f.local(t)
91 rows := func() int {
92 var n int
93 if err := f.app.db.Writer().QueryRow("SELECT COUNT(*) FROM memoria_home_local_identities").Scan(&n); err != nil {
94 t.Fatal(err)
95 }
96 return n
97 }
98 if rows() != 0 {
99 t.Fatal("an ordinary local sign-in allocated a local identity")
100 }
101 if !offersConnect(f.signedInPage(t)) {
102 t.Error("no identity row: a local session is not offered the connection")
103 }
104 if w := f.do("GET", "/account/home", ""); w.Code != http.StatusOK {
105 t.Fatal("link page", w.Code)
106 }
107 if rows() != 1 {
108 t.Fatal("the link page did not allocate the local identity")
109 }
110 if !offersConnect(f.signedInPage(t)) {
111 t.Error("identity row, no link: a local session is not offered the connection")
112 }
113}
114
115// The bug. Linked, then signed in again with Memoria's own email link: no
116// item. Seen red with offersHomeLink restored to the session-method test:
117// "a linked account signed in locally is still offered the connection".
118func TestConnectItemNotOfferedOnceLinkedToALocalSession(t *testing.T) {
119 f := newHomeRouterFixture(t)
120 f.local(t)
121 homeRedirect(t, f.linkFromMenu(t, "opaque-home-alice"))
122 if f.linkRows(t, "opaque-home-alice") != 1 {
123 t.Fatal("the link was not stored")
124 }
125 f.cookies = map[string]*http.Cookie{}
126 f.local(t)
127 if offersConnect(f.signedInPage(t)) {
128 t.Error("a linked account signed in locally is still offered the connection")
129 }
130}
131
132// Unknown is not "not linked": when either lookup fails, nothing is
133// offered (a count that fails is not a count of zero). Each table is
134// dropped in turn to make its lookup fail. Seen red with offersHomeLink
135// offering on a Linked error, and on a homeLocalID error.
136func TestConnectItemNotOfferedWhenTheLinkIsUnknown(t *testing.T) {
137 for _, table := range []string{"home_identity_links", "memoria_home_local_identities"} {
138 f := newHomeRouterFixture(t)
139 f.local(t)
140 // The identity row, so the Linked lookup is the one reached.
141 if w := f.do("GET", "/account/home", ""); w.Code != http.StatusOK {
142 t.Fatal("link page", w.Code)
143 }
144 if !offersConnect(f.signedInPage(t)) {
145 t.Fatal("not offered before the lookup broke")
146 }
147 if _, err := f.app.db.Writer().Exec("DROP TABLE " + table); err != nil {
148 t.Fatal(err)
149 }
150 if offersConnect(f.signedInPage(t)) {
151 t.Errorf("%s unreadable: still offered the connection", table)
152 }
153 }
154}
155
156// A Home session is the link itself. Seen red with offersHomeLink answering
157// true for any signed-in viewer.
158func TestConnectItemNotOfferedToAHomeSession(t *testing.T) {
159 f := newHomeRouterFixture(t)
160 f.local(t)
161 homeRedirect(t, f.linkFromMenu(t, "opaque-home-alice"))
162 f.cookies = map[string]*http.Cookie{}
163 start := f.oficina(t, "/signin")
164 homeRedirect(t, f.exchange(t, start, "opaque-home-alice"))
165 if offersConnect(f.signedInPage(t)) {
166 t.Error("a Home session is offered to connect the account it signed in with")
167 }
168}
169
170// Right after the confirm POST, in the same (local) session: "Accounts
171// connected", the row is stored, and the very next page's menu has no
172// item. Seen red with the session-method test restored: the last check.
173func TestConfirmSaysConnectedAndTheItemGoesInTheSameSession(t *testing.T) {
174 f := newHomeRouterFixture(t)
175 f.local(t)
176 if !offersConnect(f.signedInPage(t)) {
177 t.Fatal("not offered before linking")
178 }
179 res := f.linkFromMenu(t, "opaque-home-alice").Result()
180 loc := res.Header.Get("Location")
181 if res.StatusCode != http.StatusSeeOther || !strings.HasPrefix(loc, "/account/home/confirm?connected=1") {
182 t.Fatalf("confirm POST = %d to %q, want the connected page", res.StatusCode, loc)
183 }
184 w := f.do("GET", loc, "")
185 b := html.UnescapeString(w.Body.String())
186 if w.Code != http.StatusOK || !strings.Contains(b, "Accounts connected") {
187 t.Fatalf("connected page = %d:\n%s", w.Code, b)
188 }
189 if f.linkRows(t, "opaque-home-alice") != 1 {
190 t.Fatal("the confirm POST did not store the link")
191 }
192 if offersConnect(f.signedInPage(t)) {
193 t.Error("the same session is still offered the connection right after connecting")
194 }
195}
196
197// An Oficina sign-in this app has no link for shows the unknown page; a
198// local sign-in in the same browser then goes straight to Home's
199// freshness check, the confirm step, and on to a stored link, landing back
200// where the person was headed. Seen red without the ensureHomeLocalIdentity
201// call on /auth/local/complete (localComplete): a person who had never
202// opened /account/home has no local identity row, so the resume could not
203// bind, and the sign-in fell back to the Connect page, /account/home.
204func TestUnknownOficinaAccountResumesTheLinkAfterLocalSignin(t *testing.T) {
205 f := newHomeRouterFixture(t)
206 start := f.oficina(t, "/signin?return_to=%2Fsearch%3Fq%3Dnebula")
207 w := f.exchange(t, start, unlinkedSubject)
208 b := html.UnescapeString(w.Body.String())
209 if w.Code != http.StatusForbidden || !strings.Contains(b, "Sign in to your Memoria account once to connect it to your Oficina account.") {
210 t.Fatalf("unknown page = %d:\n%s", w.Code, b)
211 }
212 if foot := formFoot(t, b); !strings.Contains(foot, `<a rst-btn="primary" href="/signin/local">`) {
213 t.Errorf("the unknown page's button does not go to /signin/local:\n%s", foot)
214 }
215
216 landing := f.localAs(t, "alice@example.test")
217 if landing != "/auth/start?return_to=%2Faccount%2Fhome%2Fconfirm" {
218 t.Fatalf("local sign-in after an unknown assertion landed on %q, want Home's freshness start", landing)
219 }
220 if f.cookies["__Host-oficina-home-init"] == nil {
221 t.Fatal("no link initiation cookie")
222 }
223 if got := homeRedirect(t, f.exchange(t, landing, unlinkedSubject)); got != "/account/home/confirm" {
224 t.Fatal("fresh assertion landed on", got)
225 }
226 w = f.do("GET", "/account/home/confirm", "")
227 b = html.UnescapeString(w.Body.String())
228 for _, want := range []string{
229 "Connect these two accounts?",
230 "Your Oficina account is confirmed. Connect it to the Memoria account below, and you can sign in to Memoria with Oficina from now on.",
231 "alice@example.test",
232 } {
233 if w.Code != http.StatusOK || !strings.Contains(b, want) {
234 t.Errorf("confirm page (%d) lacks %q", w.Code, want)
235 }
236 }
237 foot := formFoot(t, b)
238 p, g := strings.Index(foot, `<button rst-btn="primary" type="submit">`), strings.Index(foot, `<a rst-btn="ghost" href="/">`)
239 if p < 0 || g < 0 || p > g {
240 t.Errorf("confirm buttons are not one row, primary first:\n%s", foot)
241 }
242 if f.linkRows(t, unlinkedSubject) != 0 {
243 t.Fatal("linked before the confirm click")
244 }
245 res := f.do("POST", "/account/home/confirm", "").Result()
246 loc := res.Header.Get("Location")
247 if res.StatusCode != http.StatusSeeOther || !strings.HasPrefix(loc, "/account/home/confirm?connected=1") {
248 t.Fatalf("confirm POST = %d to %q", res.StatusCode, loc)
249 }
250 if f.linkRows(t, unlinkedSubject) != 1 {
251 t.Fatal("the confirm POST did not store the link")
252 }
253 w = f.do("GET", loc, "")
254 b = w.Body.String()
255 if w.Code != http.StatusOK || !strings.Contains(b, "Accounts connected") {
256 t.Fatalf("connected page = %d:\n%s", w.Code, b)
257 }
258 // PageFor: the way back is the page the sign-in was headed for.
259 if !strings.Contains(formFoot(t, b), `<a rst-btn="primary" href="/search?q=nebula">`) {
260 t.Errorf("the connected page does not lead back to /search?q=nebula:\n%s", formFoot(t, b))
261 }
262 if offersConnect(f.signedInPage(t)) {
263 t.Error("still offered the connection after connecting")
264 }
265 // And the Oficina account now signs in as alice.
266 f.cookies = map[string]*http.Cookie{}
267 start = f.oficina(t, "/signin")
268 homeRedirect(t, f.exchange(t, start, unlinkedSubject))
269 if !strings.Contains(f.signedInPage(t), "alice@example.test") {
270 t.Error("the linked Oficina account does not sign in as alice")
271 }
272}
273
274// The unknown marker lives ten minutes. Inside them the local sign-in
275// resumes the link; past them it lands as before (on "/", nothing begun).
276// The app's clock is the bridge's (WireHome passes a.now), so the
277// assertion is issued at the shifted time; the nine-minute row is the
278// proof the shifted clock reaches the marker at all (were it not, the
279// eleven-minute row would resume too). Seen red: the nine-minute row,
280// without localComplete's allocation. The expiry check itself is home's
281// (navigation.marker), and tested there.
282func TestUnknownMarkerExpiresAfterTenMinutes(t *testing.T) {
283 for _, tc := range []struct {
284 ago time.Duration
285 resume bool
286 }{{9 * time.Minute, true}, {11 * time.Minute, false}} {
287 // The link store keeps a high-water clock and refuses to go back,
288 // so the app starts on the shifted clock and only moves forward.
289 at := time.Now().Add(-tc.ago)
290 key, err := assertioncrypto.Generate()
291 if err != nil {
292 t.Fatal(err)
293 }
294 f := newHomeRouterFixtureWith(t, key, Config{Origin: homeTestOrigin, Home: &connect.DecodedCredentials{Issuer: homeTestIssuer, ConsumerID: "memoria-test", Keys: map[string][]byte{"key": key.SignPub()}, DEK: bytes.Repeat([]byte{7}, 32)}},
295 func(a *app) { a.clock = func() time.Time { return at } })
296 start := f.oficina(t, "/signin")
297 if w := f.exchangeAt(t, start, unlinkedSubject, at); w.Code != http.StatusForbidden {
298 t.Fatalf("%v ago: unknown page = %d", tc.ago, w.Code)
299 }
300 f.app.clock = nil
301 landing := f.localAs(t, "alice@example.test")
302 resumed := landing == "/auth/start?return_to=%2Faccount%2Fhome%2Fconfirm"
303 if resumed != tc.resume || (!tc.resume && landing != "/") {
304 t.Errorf("marker %v old: local sign-in landed on %q, resume want %v", tc.ago, landing, tc.resume)
305 }
306 if !tc.resume && f.cookies["__Host-oficina-home-init"] != nil {
307 t.Errorf("marker %v old: a link was begun", tc.ago)
308 }
309 }
310}
311
312// The connect page's two buttons are one rst-form-foot row, primary first
313// (estilo 0b375d5). Seen red with estilo pinned back to 530cb93, whose
314// template stacked them with no row.
315func TestConnectPageButtonsAreOneRowPrimaryFirst(t *testing.T) {
316 f := newHomeRouterFixture(t)
317 f.local(t)
318 w := f.do("GET", "/account/home", "")
319 if w.Code != http.StatusOK {
320 t.Fatal(w.Code)
321 }
322 foot := formFoot(t, w.Body.String())
323 p := strings.Index(foot, `<form method="post" action="/account/home"><button rst-btn="primary" type="submit">Connect</button></form>`)
324 g := strings.Index(foot, `<a rst-btn="ghost" href="/">`)
325 if p < 0 || g < 0 || p > g {
326 t.Errorf("the Connect and Cancel buttons are not one row, primary first:\n%s", foot)
327 }
328}
329