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
3// Every route and state of the smart door (Home spec 2026-11-19-smart-door.md,
4// "Routes, and every state the door must answer"), with Home and without.
5
6import (
7 "fmt"
8 "net/http"
9 "net/url"
10 "strings"
11 "testing"
12 "time"
13
14 "amadan.net/oficina/home/connect"
15 "amadan.net/rastrillo/rastrillo/lastsignin"
16)
17
18func TestDoorStatesWithHome(t *testing.T) {
19 f := newHomeRouterFixture(t)
20 oficina := &lastsignin.Record{Method: lastsignin.MethodFederated, Provider: lastsignin.ProviderOficina, Address: "alice@example.test"}
21 email := &lastsignin.Record{Method: lastsignin.MethodMagicLink, Address: "alice@example.test"}
22 keymail := &lastsignin.Record{Method: lastsignin.MethodKeymail, Address: "alice@example.test"}
23 for _, c := range []struct {
24 name, path string
25 record *lastsignin.Record
26 title string
27 want, never []string
28 }{
29 {"first visit", "/signin", nil, "Sign in to Memoria", []string{oficinaButton, otherWays, `href="/signin/oficina"`}, []string{emailField}},
30 {"Oficina ID remembered", "/signin", oficina, "Sign in to Memoria", []string{oficinaButton, otherWays}, []string{"Continue as", emailField}},
31 {"email remembered", "/signin", email, "Sign in to Memoria", []string{"Continue as alice@example.test", otherWays}, []string{oficinaButton}},
32 {"Keymail remembered", "/signin", keymail, "Sign in to Memoria", []string{"Continue as alice@example.test", `name="expect" value="keymail"`, otherWays}, []string{oficinaButton, "Keymail"}},
33 {"the chooser", "/signin?ways=1", email, "Other ways to sign in to Memoria", []string{"Oficina ID", "Back", "Use a different email"}, []string{emailField}},
34 {"the email way", "/signin?way=email", nil, "Sign in to Memoria", []string{emailField, "Continue"}, []string{oficinaButton}},
35 {"the Oficina way", "/signin?way=oficina", email, "Sign in to Memoria", []string{oficinaButton}, []string{"Continue as"}},
36 {"page carried", "/signin?return_to=%2Fconnectors", nil, "Sign in to Memoria", []string{`href="/signin/oficina?return_to=%2Fconnectors"`}, nil},
37 {"email only", "/signin/local", oficina, "Sign in to Memoria", []string{"Continue as alice@example.test"}, []string{oficinaButton}},
38 {"email only, nothing remembered", "/signin/local", nil, "Sign in to Memoria", []string{emailField}, []string{oficinaButton, otherWays}},
39 {"a step-up", "/signin?reauth=1", oficina, "Sign in to Memoria", []string{"Continue as alice@example.test", `name="reauth" value="1"`}, []string{oficinaButton}},
40 {"a problem", "/signin?err=expired", email, "Problem signing in to Memoria", []string{"That link has expired or was already used.", emailField}, []string{oficinaButton}},
41 {"rate", "/signin?err=rate", nil, "Problem signing in to Memoria", []string{"Too many tries."}, nil},
42 {"a bad address", "/signin?err=address", nil, "Problem signing in to Memoria", []string{"That doesn't look like an email address."}, nil},
43 {"Keymail failed", "/signin?force=1&err=keymail", nil, "Problem signing in to Memoria", []string{`name="force" value="1"`, "We couldn't confirm it's you."}, []string{"Keymail"}},
44 {"sent", "/signin?sent=1", email, "Check your email to sign in to Memoria", []string{"Check your email", "Use a different email"}, []string{oficinaButton, emailField}},
45 {"the removal", "/signin?err=removed", nil, "Problem signing in to Memoria", []string{signinRemoved, appProblem, emailField}, []string{"Something went wrong"}},
46 } {
47 t.Run(c.name, func(t *testing.T) {
48 br := f.fresh()
49 if c.record != nil {
50 br.remember(t, *c.record)
51 }
52 rec := br.get(c.path)
53 if rec.Code != http.StatusOK || rec.Header().Get("Cache-Control") != "no-store" {
54 t.Fatalf("GET %s: %d %q", c.path, rec.Code, rec.Header().Get("Cache-Control"))
55 }
56 if got := titleOf(t, rec.Body.String()); got != c.title {
57 t.Errorf("title %q, want %q", got, c.title)
58 }
59 card := door(t, rec.Body.String())
60 for _, want := range c.want {
61 if !strings.Contains(card, want) {
62 t.Errorf("the door lacks %q:\n%s", want, card)
63 }
64 }
65 for _, never := range c.never {
66 if strings.Contains(card, never) {
67 t.Errorf("the door has %q:\n%s", never, card)
68 }
69 }
70 // The card is the door's alone: no Colophon, no account, no
71 // footer (the door is drawn signed out).
72 if body := rec.Body.String(); strings.Contains(body, "/help/open-source") || strings.Contains(body, "estilo-account") || strings.Contains(body, "<footer") {
73 t.Error("the door draws more than the door")
74 }
75 })
76 }
77 // Continue with Oficina ID starts the exchange, with the page.
78 br := f.fresh()
79 redirectsTo(t, br.get("/signin/oficina"), "/auth/start?return_to=%2F")
80 redirectsTo(t, br.get("/signin/oficina?return_to=%2Fconnectors"), "/auth/start?return_to=%2Fconnectors")
81 // A step-up never reaches Home.
82 redirectsTo(t, br.get("/signin/oficina?reauth=1&return_to=%2Faccount%2Fhome"), "/signin/local?reauth=1&return_to=%2Faccount%2Fhome")
83 // The member choice is mounted (outside team mode connect answers
84 // without the team hooks, never a 405).
85 if rec := br.get(connect.ChoosePath); rec.Code == http.StatusMethodNotAllowed || rec.Code == http.StatusOK {
86 t.Errorf("GET %s outside team mode = %d", connect.ChoosePath, rec.Code)
87 }
88}
89
90func TestDoorStatesStandalone(t *testing.T) {
91 f := newStandaloneDoor(t)
92 email := lastsignin.Record{Method: lastsignin.MethodMagicLink, Address: "alice@example.test"}
93 for _, path := range []string{"/signin", "/signin?ways=1", "/signin?way=oficina", "/signin?err=expired", "/signin?reauth=1"} {
94 br := f.fresh()
95 br.remember(t, email)
96 rec := br.get(path)
97 if rec.Code != http.StatusOK {
98 t.Fatalf("GET %s: %d", path, rec.Code)
99 }
100 if body := rec.Body.String(); strings.Contains(body, "Oficina ID") || strings.Contains(body, "/signin/oficina") {
101 t.Errorf("standalone %s offers Oficina ID:\n%s", path, door(t, body))
102 }
103 }
104 br := f.fresh()
105 if got := titleOf(t, br.get("/signin").Body.String()); got != "Sign in to Memoria" {
106 t.Errorf("title %q", got)
107 }
108 if card := door(t, br.get("/signin").Body.String()); !strings.Contains(card, emailField) {
109 t.Errorf("standalone first visit is not the email field:\n%s", card)
110 }
111 // With one way in there is no chooser: "Use a different email" stands in
112 // for Other ways.
113 br.remember(t, email)
114 if card := door(t, br.get("/signin").Body.String()); !strings.Contains(card, "Continue as alice@example.test") || !strings.Contains(card, "Use a different email") || strings.Contains(card, otherWays) {
115 t.Errorf("standalone remembered door:\n%s", card)
116 }
117 for _, path := range []string{"/signin/local", "/signin/oficina", connect.ChoosePath} {
118 if rec := f.fresh().get(path); rec.Code != http.StatusNotFound {
119 t.Errorf("standalone GET %s = %d, want 404", path, rec.Code)
120 }
121 }
122 if rec := f.fresh().do(http.MethodPost, connect.ChoosePath, "choice=new"); rec.Code != http.StatusNotFound {
123 t.Errorf("standalone POST %s = %d, want 404", connect.ChoosePath, rec.Code)
124 }
125}
126
127// app.go mounts the door's routes at literals (the route gate reads
128// literals); this keeps each equal to the constant it stands for.
129func TestDoorRoutesAreConnects(t *testing.T) {
130 for literal, constant := range map[string]string{
131 "/signin": connect.SigninPath,
132 "/signin/local": connect.SigninLocalPath,
133 "/signin/oficina": connect.SigninOficinaPath,
134 "/account/home/choose": connect.ChoosePath,
135 "/signin/forget": signinForgetPath,
136 "/auth/begin": beginPath,
137 } {
138 if literal != constant {
139 t.Errorf("app.go mounts %s, but the constant is %s", literal, constant)
140 }
141 }
142 if signinPath != connect.SigninPath {
143 t.Errorf("auth's SigninPath %s is not connect's %s", signinPath, connect.SigninPath)
144 }
145}
146
147// Somebody signed in and admitted never sees the door unless the query
148// names one of its states, and goes to a safe return_to or "/".
149func TestASignedInOwnerSkipsTheDoor(t *testing.T) {
150 doorModes(t, func(t *testing.T, f *homeRouterFixture) {
151 f.session(t, "alice@example.test", "magiclink", time.Now())
152 redirectsTo(t, f.get("/signin"), "/")
153 redirectsTo(t, f.get("/signin?return_to=%2Fconnectors"), "/connectors")
154 redirectsTo(t, f.get("/signin?return_to=%2F%2Fevil.example"), "/")
155 for _, state := range []string{"/signin?sent=1", "/signin?err=expired", "/signin?reauth=1"} {
156 if rec := f.get(state); rec.Code != http.StatusOK {
157 t.Errorf("signed in, GET %s = %d, want the door's state", state, rec.Code)
158 }
159 }
160 if f.sessionCookie() == nil {
161 t.Fatal("the door ended an admitted session")
162 }
163 })
164}
165
166// A whole email sign-in through the door, both modes, lands on the index,
167// and rastrillo remembers the emailed link.
168func TestAnEmailSigninThroughTheDoor(t *testing.T) {
169 doorModes(t, func(t *testing.T, f *homeRouterFixture) {
170 if got := f.emailSignin(t, url.Values{"address": {"alice@example.test"}}); got != "/" {
171 t.Fatalf("landed on %q", got)
172 }
173 f.signedInPage(t)
174 if rec, res := f.remembered(); res != lastsignin.Valid || rec.Method != lastsignin.MethodMagicLink || rec.Address != "alice@example.test" {
175 t.Fatalf("remembered %+v (%v), want the emailed link for alice", rec, res)
176 }
177 })
178}
179
180// A stranger's post is answered exactly as an owner's is (beginGuard's
181// AnswerAsSent, gate 33): for addresses of the same length, the same
182// status, the same Sent (attempt id aside, of the same length), the same
183// cookies with the same Max-Age, flags and value lengths, and nothing
184// mailed. Plain, as a step-up, as the remembered-Keymail one-tap
185// (expect=keymail), and from a browser that already holds an attempt.
186func TestAStrangersBeginIsAnOwnersSent(t *testing.T) {
187 type cookieShape struct {
188 Name, Path string
189 MaxAge, ValueLen int
190 Secure, HTTPOnly bool
191 SameSite http.SameSite
192 }
193 type answer struct {
194 Code int
195 Location string
196 Cookies []cookieShape
197 }
198 const owner, stranger = "alice@example.test", "zzzzz@example.test"
199 for _, c := range []struct {
200 name string
201 extra url.Values
202 before bool
203 }{
204 {"plain", nil, false},
205 {"a step-up", url.Values{"reauth": {"1"}}, false},
206 {"expect=keymail", url.Values{"expect": {"keymail"}}, false},
207 {"an attempt already held", nil, true},
208 } {
209 t.Run(c.name, func(t *testing.T) {
210 doorModes(t, func(t *testing.T, f *homeRouterFixture) {
211 post := func(address string) answer {
212 br := f.fresh()
213 form := url.Values{"address": {address}, "force": {"1"}, "return_to": {"/connectors"}}
214 for k, v := range c.extra {
215 form[k] = v
216 }
217 if c.before {
218 br.do(http.MethodPost, "/auth/begin", form.Encode())
219 }
220 rec := br.do(http.MethodPost, "/auth/begin", form.Encode())
221 u, _ := url.Parse(rec.Header().Get("Location"))
222 q := u.Query()
223 if q.Get("attempt") == "" {
224 t.Errorf("%s: Sent carries no attempt: %q", address, rec.Header().Get("Location"))
225 }
226 q.Set("attempt", strings.Repeat("x", len(q.Get("attempt"))))
227 u.RawQuery = q.Encode()
228 a := answer{Code: rec.Code, Location: u.String()}
229 for _, ck := range rec.Result().Cookies() {
230 a.Cookies = append(a.Cookies, cookieShape{ck.Name, ck.Path, ck.MaxAge, len(ck.Value), ck.Secure, ck.HttpOnly, ck.SameSite})
231 }
232 return a
233 }
234 f.mail.body = ""
235 s := post(stranger)
236 if f.mail.body != "" {
237 t.Fatal("a link was mailed to a stranger")
238 }
239 o := post(owner)
240 if f.mail.body == "" {
241 t.Fatal("no link was mailed to the owner, so the comparison proves nothing")
242 }
243 if fmt.Sprint(s) != fmt.Sprint(o) {
244 t.Fatalf("a stranger is answered\n%+v\nan owner\n%+v", s, o)
245 }
246 if u, _ := url.Parse(o.Location); u.Path != "/signin" || u.Query().Get("sent") != "1" || u.Query().Get("return_to") != "/connectors" {
247 t.Fatalf("Sent = %q, want the door's Sent with the page", o.Location)
248 }
249 })
250 })
251 }
252}
253
254// The guard's own answer to a malformed address is Begin's shape: err,
255// with a failed Keymail's force and a step-up's reauth kept, and the page.
256func TestTheGuardsAddressProblemKeepsForceReauthAndThePage(t *testing.T) {
257 doorModes(t, func(t *testing.T, f *homeRouterFixture) {
258 rec := f.do(http.MethodPost, "/auth/begin", url.Values{"address": {"paul@"}, "force": {"1"}, "reauth": {"1"}, "return_to": {"/connectors"}}.Encode())
259 redirectsTo(t, rec, "/signin?err=address&force=1&reauth=1&return_to=%2Fconnectors")
260 if card := door(t, f.get(rec.Header().Get("Location")).Body.String()); !strings.Contains(card, "That doesn't look like an email address.") || !strings.Contains(card, `name="force" value="1"`) {
261 t.Fatalf("the address problem's door:\n%s", card)
262 }
263 if f.mail.body != "" {
264 t.Fatal("a malformed address was mailed")
265 }
266 })
267}
268