oficina / sheets Public

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

Plain git — no account needed to clone.

Download

Download this file

1package sheets
2
3import (
4 "bytes"
5 "crypto/rand"
6 "encoding/base64"
7 "encoding/json"
8 "html"
9 "net/http"
10 "net/http/httptest"
11 "net/url"
12 "regexp"
13 "strings"
14 "testing"
15 "time"
16
17 "amadan.net/oficina/home/connect"
18 "amadan.net/oficina/home/handoff"
19 "amadan.net/rastrillo/rastrillo/assertion"
20 "amadan.net/rastrillo/rastrillo/sessions"
21)
22
23// The native app's Oficina ID sign-in (Home spec
24// 2026-11-14-oficina-id-native.md §7, §8): POST /native/oficina-id trades
25// an assertion Home made for the app's verifier for a Sheets session, with
26// no browser and no cookie. Driven through the router, as main mounts it.
27
28type nativeAnswer struct {
29 State string `json:"state"`
30 Name string `json:"name"`
31 Value string `json:"value"`
32 ExpiresAt int64 `json:"expires_at"`
33}
34
35// nativeExchange posts what the native app posts: JSON, no Origin, no
36// Sec-Fetch-Site, no cookies.
37func (f *homeFixture) nativeExchange(t *testing.T, subject string, extra map[string]string) (*httptest.ResponseRecorder, nativeAnswer) {
38 t.Helper()
39 raw := make([]byte, 32)
40 if _, err := rand.Read(raw); err != nil {
41 t.Fatal(err)
42 }
43 verifier := base64.RawURLEncoding.EncodeToString(raw)
44 challenge, _ := handoff.NativeChallenge(verifier)
45 nonce, _ := handoff.NativeNonce(challenge)
46 now := time.Now().Unix()
47 id, _ := assertion.RandomID()
48 token, err := assertion.Sign(f.key, assertion.Claims{Version: 1, Issuer: homeTestIssuer, Audience: testOrigin, Subject: subject, KeyID: "key", ID: id, Nonce: nonce, IssuedAt: now, ExpiresAt: now + 120, AuthTime: now - 60})
49 if err != nil {
50 t.Fatal(err)
51 }
52 body := map[string]string{"assertion": token, "verifier": verifier}
53 for k, v := range extra {
54 body[k] = v
55 }
56 encoded, _ := json.Marshal(body)
57 r := httptest.NewRequest("POST", testOrigin+connect.NativeExchangePath, bytes.NewReader(encoded))
58 r.Header.Set("Content-Type", "application/json")
59 rec := httptest.NewRecorder()
60 f.app.Router().ServeHTTP(rec, r)
61 if len(rec.Result().Cookies()) != 0 {
62 t.Fatal("the native exchange set a cookie")
63 }
64 var answer nativeAnswer
65 if err := json.Unmarshal(rec.Body.Bytes(), &answer); err != nil {
66 t.Fatalf("answer %d %q: %v", rec.Code, rec.Body.String(), err)
67 }
68 return rec, answer
69}
70
71// nativeList is the native app's sheet list (SheetsWorkspace's GET
72// /sheets as JSON), with the minted session.
73func (f *homeFixture) nativeList(t *testing.T, a nativeAnswer) *httptest.ResponseRecorder {
74 t.Helper()
75 r := httptest.NewRequest("GET", testOrigin+"/sheets", nil)
76 r.Header.Set("Accept", "application/json")
77 r.AddCookie(&http.Cookie{Name: a.Name, Value: a.Value})
78 rec := httptest.NewRecorder()
79 f.app.Router().ServeHTTP(rec, r)
80 return rec
81}
82
83// age backdates the minted session's creation, as seven days would.
84func (f *homeFixture) age(t *testing.T, a nativeAnswer, by time.Duration) {
85 t.Helper()
86 old := time.Now().Add(-by).UTC().Format(time.RFC3339)
87 if err := f.app.db.Exec("UPDATE sessions SET created_at=? WHERE token_hash=?", old, sessions.HashToken(a.Value)).Error; err != nil {
88 t.Fatal(err)
89 }
90}
91
92func TestNativeOficinaIDOpensALinkedAccount(t *testing.T) {
93 f := newHomeFixture(t)
94 member := f.local(t, signedInAddress)
95 if _, err := f.app.createSheet(nil, "Linked workbook", member); err != nil {
96 t.Fatal(err)
97 }
98 f.link(t, "pr_linked")
99 f.jar = map[string]*http.Cookie{}
100
101 rec, answer := f.nativeExchange(t, "pr_linked", nil)
102 if rec.Code != http.StatusOK || answer.State != "ok" || answer.Name != f.app.homeSessions.CookieName() || answer.Value == "" {
103 t.Fatalf("exchange = %d %s", rec.Code, rec.Body.String())
104 }
105 r := httptest.NewRequest("GET", testOrigin+"/", nil)
106 r.AddCookie(&http.Cookie{Name: answer.Name, Value: answer.Value})
107 if s, ok := f.app.homeSessions.From(r); !ok || s.Method != connect.NativeMethod || s.Subject != "pr_linked" {
108 t.Fatalf("minted %+v", s)
109 }
110 if list := f.nativeList(t, answer); list.Code != http.StatusOK || !strings.Contains(list.Body.String(), "Linked workbook") {
111 t.Fatalf("native list = %d %s", list.Code, list.Body.String())
112 }
113
114 // Outside team mode a subject with no account here is unknown, and the
115 // same whatever it sends.
116 for _, extra := range []map[string]string{nil, {"choice": "new"}} {
117 if rec, _ := f.nativeExchange(t, "pr_stranger", extra); rec.Code != http.StatusForbidden || rec.Body.String() != `{"state":"unknown"}` {
118 t.Fatalf("stranger = %d %s", rec.Code, rec.Body.String())
119 }
120 }
121}
122
123// Seven days after it was minted, however recently used, the native
124// session opens nothing: the app re-mints long before (§7).
125func TestNativeSessionEndsAfterSevenDays(t *testing.T) {
126 f := newHomeFixture(t)
127 f.local(t, signedInAddress)
128 f.link(t, "pr_linked")
129 _, answer := f.nativeExchange(t, "pr_linked", nil)
130 if f.nativeList(t, answer).Code != http.StatusOK {
131 t.Fatal("a fresh native session was refused")
132 }
133 f.age(t, answer, connect.NativeLifetime+time.Hour)
134 if r := f.nativeList(t, answer); r.Code == http.StatusOK {
135 t.Fatalf("a native session older than seven days opened the list: %s", r.Body.String())
136 }
137}
138
139// The exchange is not a browser route: a browser's Origin, or a form, is
140// refused by the exchange itself, not waved through the CSRF check.
141func TestNativeExchangeRefusesABrowser(t *testing.T) {
142 f := newHomeFixture(t)
143 serve := func(r *http.Request) *httptest.ResponseRecorder {
144 rec := httptest.NewRecorder()
145 f.app.Router().ServeHTTP(rec, r)
146 return rec
147 }
148 r := httptest.NewRequest("POST", testOrigin+connect.NativeExchangePath, strings.NewReader(`{"assertion":"x","verifier":"y"}`))
149 r.Header.Set("Content-Type", "application/json")
150 r.Header.Set("Origin", testOrigin)
151 if rec := serve(r); rec.Code != http.StatusBadRequest || rec.Body.String() != `{"state":"invalid"}` {
152 t.Fatalf("browser POST = %d %s", rec.Code, rec.Body.String())
153 }
154 r = httptest.NewRequest("POST", testOrigin+connect.NativeExchangePath, strings.NewReader(url.Values{"assertion": {"x"}}.Encode()))
155 r.Header.Set("Content-Type", "application/x-www-form-urlencoded")
156 if rec := serve(r); rec.Code != http.StatusBadRequest {
157 t.Fatalf("form POST = %d", rec.Code)
158 }
159}
160
161// In team mode a roster member with no member here chooses: 409 and
162// nothing made, then choice "new" makes the Home-only member and signs in.
163// Non-members get the identical unknown; an undecidable roster is a 503.
164func TestTeamNativeMemberChooses(t *testing.T) {
165 f := newTeamFixture(t)
166 teamSheet(t, f, "Team plan")
167 b := teamSubject('b')
168 f.dir.Set(b, "member")
169 rec, answer := f.nativeExchange(t, b, nil)
170 if rec.Code != http.StatusConflict || answer.State != "choose" {
171 t.Fatalf("member with no member here = %d %s", rec.Code, rec.Body.String())
172 }
173 var addressless int64
174 f.app.db.Model(&Member{}).Where("address IS NULL").Count(&addressless)
175 if addressless != 0 {
176 t.Fatal("409 made a member")
177 }
178 rec, answer = f.nativeExchange(t, b, map[string]string{"choice": "new"})
179 if rec.Code != http.StatusOK || answer.State != "ok" {
180 t.Fatalf("choice new = %d %s", rec.Code, rec.Body.String())
181 }
182 if list := f.nativeList(t, answer); list.Code != http.StatusOK || !strings.Contains(list.Body.String(), "Team plan") {
183 t.Fatalf("native list = %d %s", list.Code, list.Body.String())
184 }
185 // Now linked: no choice asked again.
186 if rec, again := f.nativeExchange(t, b, nil); rec.Code != http.StatusOK || again.State != "ok" {
187 t.Fatalf("second exchange = %d %s", rec.Code, rec.Body.String())
188 }
189 for _, extra := range []map[string]string{nil, {"choice": "new"}} {
190 if rec, _ := f.nativeExchange(t, teamSubject('z'), extra); rec.Code != http.StatusForbidden || rec.Body.String() != `{"state":"unknown"}` {
191 t.Fatalf("non-member = %d %s", rec.Code, rec.Body.String())
192 }
193 }
194 f.dir.Set(teamSubject('c'), "member")
195 f.expired(t)
196 if rec, _ := f.nativeExchange(t, teamSubject('c'), map[string]string{"choice": "new"}); rec.Code != http.StatusServiceUnavailable {
197 t.Fatalf("undecidable roster = %d %s", rec.Code, rec.Body.String())
198 }
199}
200
201// Team mode resolves a session by its subject (teamIdentify), not through
202// ResolveSession, so it must refuse a native session past seven days too.
203func TestTeamNativeSessionEndsAfterSevenDays(t *testing.T) {
204 f := newTeamFixture(t)
205 b := teamSubject('b')
206 f.dir.Set(b, "member")
207 _, answer := f.nativeExchange(t, b, map[string]string{"choice": "new"})
208 if f.nativeList(t, answer).Code != http.StatusOK {
209 t.Fatal("a fresh native session was refused")
210 }
211 f.age(t, answer, connect.NativeLifetime+time.Hour)
212 if r := f.nativeList(t, answer); r.Code == http.StatusOK {
213 t.Fatalf("a native session older than seven days opened the list: %s", r.Body.String())
214 }
215}
216
217// The browser half of the member choice: "Connect my existing account"
218// resumes local sign-in and linking; "I'm new here" is refused while any
219// app session is present; a cross-origin POST is stopped.
220func TestTeamMemberChoicePage(t *testing.T) {
221 f := newTeamFixture(t)
222 a := teamSubject('a')
223 f.dir.Set(a, "member")
224 if fin := f.signInHomeChoosing(t, a); fin.Code != http.StatusSeeOther || fin.Header().Get("Location") != connect.ChoosePath {
225 t.Fatalf("member sign-in = %d %q", fin.Code, fin.Header().Get("Location"))
226 }
227 page := f.get(t, connect.ChoosePath)
228 body := page.Body.String()
229 for _, want := range []string{homeCopy["choose_title"], "Connect my existing account", `value="connect"`, `value="new"`} {
230 if !strings.Contains(body, want) && !strings.Contains(body, strings.ReplaceAll(want, "’", "’")) {
231 t.Fatalf("choose page lacks %q: %s", want, body)
232 }
233 }
234 if connected := f.choose(t, "connect"); connected.Code != http.StatusSeeOther || !strings.HasPrefix(connected.Header().Get("Location"), "/signin/local") {
235 t.Fatalf("connect = %d %q", connected.Code, connected.Header().Get("Location"))
236 }
237
238 // "I'm new here" with an app session present is refused.
239 if fin := f.signInHomeChoosing(t, a); fin.Header().Get("Location") != connect.ChoosePath {
240 t.Fatalf("member sign-in again = %q", fin.Header().Get("Location"))
241 }
242 f.local(t, "local@example.com")
243 if rec := f.choose(t, "new"); rec.Code != http.StatusForbidden {
244 t.Fatalf("I'm new here over a live app session = %d %q, want 403", rec.Code, rec.Header().Get("Location"))
245 }
246 var made int64
247 f.app.db.Model(&Member{}).Where("address IS NULL").Count(&made)
248 if made != 0 {
249 t.Fatalf("Home-only members = %d after a refused choice, want 0", made)
250 }
251
252 // A POST from another origin never reaches the choice, even carrying
253 // the page's real form token and the proof cookie.
254 f.jar = map[string]*http.Cookie{}
255 f.signInHomeChoosing(t, a)
256 token := regexp.MustCompile(`name="token" value="([^"]+)"`).FindStringSubmatch(f.get(t, connect.ChoosePath).Body.String())
257 if token == nil {
258 t.Fatal("no form token on the choose page")
259 }
260 r := httptest.NewRequest("POST", testOrigin+connect.ChoosePath, strings.NewReader(url.Values{"choice": {"new"}, "token": {html.UnescapeString(token[1])}}.Encode()))
261 r.Header.Set("Content-Type", "application/x-www-form-urlencoded")
262 r.Header.Set("Origin", "https://evil.example")
263 for _, c := range f.jar {
264 r.AddCookie(c)
265 }
266 rec := httptest.NewRecorder()
267 f.app.Router().ServeHTTP(rec, r)
268 if rec.Code != http.StatusForbidden {
269 t.Fatalf("cross-origin choose POST = %d", rec.Code)
270 }
271 var addressless int64
272 f.app.db.Model(&Member{}).Where("address IS NULL").Count(&addressless)
273 if addressless != 0 {
274 t.Fatalf("Home-only members = %d, want 0: no choice of new went through", addressless)
275 }
276}
277