oficina / calendar Public

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

Plain git — no account needed to clone.

Download

Download this file

1package calendar
2
3import (
4 "crypto/rand"
5 "crypto/sha256"
6 "encoding/base64"
7 "encoding/json"
8 "io"
9 "log/slog"
10 "net/http"
11 "net/http/httptest"
12 "path/filepath"
13 "strings"
14 "testing"
15 "time"
16
17 "amadan.net/oficina/home/connect"
18 "amadan.net/rastrillo/rastrillo/sessions"
19)
20
21// The native sign-in crosses two rastrillo module paths. The app's
22// sessions are amadan.net/rastrillo/rastrillo's; rastrillo/native's
23// server only takes github.com/carlosframework/rastrillo's, which
24// native.go builds over the same database (the one import
25// TestNoPreMoveRastrillo allows). These tests drive the whole exchange
26// through the router, so a change to either package's sessions table,
27// cookie name, token hash or time layout fails here rather than in the
28// Mac or iPhone app: approval of a browser session, the exchange minting
29// a new one, that one being an ordinary session to the app, and expiry
30// and revocation holding on both sides.
31//
32// Three shapes, because the app reads a session three ways: a local
33// sign-in with no Home (auth's RequireSession), a local sign-in with
34// Home configured, and a Home sign-in (both through the Home
35// connection's own sessions, the second resolving an opaque subject).
36
37// nativeRig is one signed-in browser against one app.
38type nativeRig struct {
39 app *App
40 origin string
41 browser *http.Cookie
42}
43
44func nativeRigs(t *testing.T) map[string]func(*testing.T) *nativeRig {
45 return map[string]func(*testing.T) *nativeRig{
46 "local, no Home": func(t *testing.T) *nativeRig {
47 a, err := New(Config{DBPath: filepath.Join(t.TempDir(), "calendar.db"), Env: "development", Origin: TestOrigin, Logger: slog.New(slog.NewTextHandler(io.Discard, nil))})
48 if err != nil {
49 t.Fatal(err)
50 }
51 t.Cleanup(func() { a.Close() })
52 return &nativeRig{a, TestOrigin, a.SignInForTest(t, "alice@example.test")}
53 },
54 "local, Home configured": func(t *testing.T) *nativeRig {
55 f := newHomeRouterFixture(t)
56 f.local(t)
57 return &nativeRig{f.app, homeTestOrigin, f.cookies[f.app.home.sessions.CookieName()]}
58 },
59 "Home sign-in": func(t *testing.T) *nativeRig {
60 f := newHomeRouterFixture(t)
61 f.local(t)
62 // The first signed-in page sets the person up; linking needs one.
63 if w := f.do("GET", "/day/2026-09-10", ""); w.Code != 200 {
64 t.Fatalf("first page = %d", w.Code)
65 }
66 if w := f.do("GET", "/account/home", ""); w.Code != 200 {
67 t.Fatalf("link page = %d %s", w.Code, w.Body.String())
68 }
69 start := homeRedirect(t, f.do("POST", "/account/home", ""))
70 homeRedirect(t, f.exchange(t, start, "opaque-home-alice"))
71 homeRedirect(t, f.do("POST", "/account/home/confirm", ""))
72 f.do("POST", "/signout", "")
73 start = homeRedirect(t, f.do("GET", connect.SigninOficinaPath, ""))
74 if got := homeRedirect(t, f.exchange(t, start, "opaque-home-alice")); got != "/" {
75 t.Fatalf("Home sign-in landed on %q", got)
76 }
77 c := f.cookies[f.app.home.sessions.CookieName()]
78 var method string
79 if err := f.app.db.G.Raw(`SELECT method FROM sessions WHERE token_hash = ?`, sessions.HashToken(c.Value)).Scan(&method).Error; err != nil || method == "magiclink" || method == "" {
80 t.Fatalf("the fixture's session is not a Home session: method %q, %v", method, err)
81 }
82 return &nativeRig{f.app, homeTestOrigin, c}
83 },
84 }
85}
86
87func (n *nativeRig) do(t *testing.T, method, path, body string, cookies ...*http.Cookie) *httptest.ResponseRecorder {
88 t.Helper()
89 r := httptest.NewRequest(method, n.origin+path, strings.NewReader(body))
90 r.Header.Set("Content-Type", "application/json")
91 r.Header.Set("Origin", n.origin)
92 for _, c := range cookies {
93 r.AddCookie(c)
94 }
95 w := httptest.NewRecorder()
96 n.app.mux.ServeHTTP(w, r)
97 return w
98}
99
100// request starts a native sign-in and returns its id and verifier.
101func (n *nativeRig) request(t *testing.T) (id, verifier string) {
102 t.Helper()
103 b := make([]byte, 32)
104 if _, err := rand.Read(b); err != nil {
105 t.Fatal(err)
106 }
107 verifier = base64.RawURLEncoding.EncodeToString(b)
108 sum := sha256.Sum256([]byte(verifier))
109 w := n.do(t, "POST", "/native/request", `{"challenge":"`+base64.RawURLEncoding.EncodeToString(sum[:])+`"}`)
110 var out struct{ ID string }
111 if w.Code != 200 || json.Unmarshal(w.Body.Bytes(), &out) != nil || out.ID == "" {
112 t.Fatalf("POST /native/request = %d %q", w.Code, w.Body.String())
113 }
114 return out.ID, verifier
115}
116
117// approve is the signed-in browser pressing "Sign in to Calendar app".
118func (n *nativeRig) approve(t *testing.T, id string) *httptest.ResponseRecorder {
119 t.Helper()
120 return n.do(t, "POST", "/native/authorize?id="+id, "", n.browser)
121}
122
123func (n *nativeRig) exchange(t *testing.T, id, verifier string) *httptest.ResponseRecorder {
124 t.Helper()
125 return n.do(t, "POST", "/native/exchange", `{"id":"`+id+`","verifier":"`+verifier+`"}`)
126}
127
128// mint runs a whole approved exchange and returns the minted cookie.
129func (n *nativeRig) mint(t *testing.T) *http.Cookie {
130 t.Helper()
131 id, verifier := n.request(t)
132 if w := n.approve(t, id); w.Code != 200 {
133 t.Fatalf("approval = %d", w.Code)
134 }
135 w := n.exchange(t, id, verifier)
136 var minted struct{ Name, Value string }
137 if w.Code != 200 || json.Unmarshal(w.Body.Bytes(), &minted) != nil {
138 t.Fatalf("exchange = %d %q", w.Code, w.Body.String())
139 }
140 return &http.Cookie{Name: minted.Name, Value: minted.Value}
141}
142
143// defaultCalendar is GET /api/native/session with one cookie: the
144// status, and whose default calendar it answered with.
145func (n *nativeRig) defaultCalendar(t *testing.T, c *http.Cookie) (int, int64) {
146 t.Helper()
147 w := n.do(t, "GET", "/api/native/session", "", c)
148 var s struct {
149 Default int64 `json:"default_calendar_id"`
150 }
151 _ = json.Unmarshal(w.Body.Bytes(), &s)
152 return w.Code, s.Default
153}
154
155func (n *nativeRig) setExpiry(t *testing.T, token string, at time.Time) {
156 t.Helper()
157 res := n.app.db.G.Exec(`UPDATE sessions SET expires_at = ? WHERE token_hash = ?`, at.UTC().Format(time.RFC3339), sessions.HashToken(token))
158 if res.Error != nil || res.RowsAffected != 1 {
159 t.Fatalf("expire session: %v, %d rows", res.Error, res.RowsAffected)
160 }
161}
162
163func TestNativeExchangeMintsASessionTheAppAccepts(t *testing.T) {
164 for name, build := range nativeRigs(t) {
165 t.Run(name, func(t *testing.T) {
166 n := build(t)
167 code, want := n.defaultCalendar(t, n.browser)
168 if code != 200 || want == 0 {
169 t.Fatalf("the browser's own session: GET /api/native/session = %d", code)
170 }
171 id, verifier := n.request(t)
172 if w := n.exchange(t, id, verifier); w.Code != http.StatusAccepted {
173 t.Fatalf("exchange before approval = %d, want 202", w.Code)
174 }
175 if w := n.approve(t, id); w.Code != 200 || !strings.Contains(w.Body.String(), "is signed in") {
176 t.Fatalf("approval = %d: %s", w.Code, w.Body.String())
177 }
178 wrong := make([]byte, 32)
179 _, _ = rand.Read(wrong)
180 if w := n.exchange(t, id, base64.RawURLEncoding.EncodeToString(wrong)); w.Code != http.StatusNotFound {
181 t.Fatalf("exchange with the wrong verifier = %d, want 404", w.Code)
182 }
183 w := n.exchange(t, id, verifier)
184 var minted struct{ Name, Value string }
185 if w.Code != 200 || json.Unmarshal(w.Body.Bytes(), &minted) != nil {
186 t.Fatalf("exchange = %d %q", w.Code, w.Body.String())
187 }
188 // The pre-move package names the cookie the app reads, and
189 // mints a new token rather than handing back the browser's.
190 if minted.Name != n.browser.Name {
191 t.Fatalf("exchange minted cookie %q; the app reads %q", minted.Name, n.browser.Name)
192 }
193 if minted.Value == "" || minted.Value == n.browser.Value {
194 t.Fatal("exchange did not mint a session of its own")
195 }
196 // And the app takes it as the same person.
197 code, got := n.defaultCalendar(t, &http.Cookie{Name: minted.Name, Value: minted.Value})
198 if code != 200 {
199 t.Fatalf("the app refuses the session native minted: GET /api/native/session = %d", code)
200 }
201 if got != want {
202 t.Fatalf("the minted session is somebody else: default calendar %d, the browser's is %d", got, want)
203 }
204 // Spent: the same id never exchanges twice.
205 if w := n.exchange(t, id, verifier); w.Code != http.StatusNotFound {
206 t.Fatalf("second exchange = %d, want 404", w.Code)
207 }
208 })
209 }
210}
211
212func TestNativeSessionExpiryHolds(t *testing.T) {
213 for name, build := range nativeRigs(t) {
214 t.Run(name, func(t *testing.T) {
215 n := build(t)
216
217 // An expired browser session signs nothing in. (The approval
218 // page records whatever cookie it is shown; the exchange is
219 // where the session is authenticated, from scratch.)
220 n.setExpiry(t, n.browser.Value, time.Now().Add(-time.Minute))
221 id, verifier := n.request(t)
222 n.approve(t, id)
223 if w := n.exchange(t, id, verifier); w.Code == 200 {
224 t.Fatal("an expired browser session signed a native app in")
225 }
226
227 // Approved while live, expired before the exchange: refused.
228 n.setExpiry(t, n.browser.Value, time.Now().Add(time.Hour))
229 id, verifier = n.request(t)
230 n.approve(t, id)
231 n.setExpiry(t, n.browser.Value, time.Now().Add(-time.Minute))
232 if w := n.exchange(t, id, verifier); w.Code != http.StatusUnauthorized {
233 t.Fatalf("exchange of an expired approval = %d, want 401", w.Code)
234 }
235
236 // A minted session expires like any other.
237 n.setExpiry(t, n.browser.Value, time.Now().Add(time.Hour))
238 native := n.mint(t)
239 if code, _ := n.defaultCalendar(t, native); code != 200 {
240 t.Fatalf("live minted session: GET /api/native/session = %d", code)
241 }
242 n.setExpiry(t, native.Value, time.Now().Add(-time.Minute))
243 if code, _ := n.defaultCalendar(t, native); code == 200 {
244 t.Fatal("the app still accepts a minted session past its expiry")
245 }
246 })
247 }
248}
249
250func TestNativeSessionRevocationHolds(t *testing.T) {
251 for name, build := range nativeRigs(t) {
252 t.Run(name, func(t *testing.T) {
253 // Signing the browser out between approval and exchange
254 // refuses the exchange.
255 n := build(t)
256 id, verifier := n.request(t)
257 n.approve(t, id)
258 if res := n.app.db.G.Exec(`DELETE FROM sessions WHERE token_hash = ?`, sessions.HashToken(n.browser.Value)); res.Error != nil || res.RowsAffected != 1 {
259 t.Fatalf("revoke the browser's session: %v", res.Error)
260 }
261 if w := n.exchange(t, id, verifier); w.Code != http.StatusUnauthorized {
262 t.Fatalf("exchange after the browser signed out = %d, want 401", w.Code)
263 }
264
265 // The app signing out a minted session (the app's own
266 // sessions package, deleting a row the pre-move package
267 // wrote) ends it, and leaves the browser's alone.
268 n = build(t)
269 native := n.mint(t)
270 if w := n.do(t, "POST", "/signout", "", native); w.Code >= 400 {
271 t.Fatalf("POST /signout with the minted session = %d", w.Code)
272 }
273 if code, _ := n.defaultCalendar(t, native); code == 200 {
274 t.Fatal("a signed-out minted session still reaches the native API")
275 }
276 if code, _ := n.defaultCalendar(t, n.browser); code != 200 {
277 t.Fatalf("signing native out ended the browser's session too: GET /api/native/session = %d", code)
278 }
279 })
280 }
281}
282