oficina / equipo Public

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

Plain git — no account needed to clone.

Download

Download this file

1package door
2
3// The door's own rules, around a stand-in guard: what the admission probe
4// judges and how it reads the guard's answer, what Oficina ID is
5// remembered as, and the paths a sign-in may land on. The routes through
6// Equipo's real guard are tested in internal/idtest (door_*_test.go).
7
8import (
9 "bytes"
10 "context"
11 "errors"
12 "io"
13 "log/slog"
14 "net/http"
15 "net/http/httptest"
16 "os"
17 "path/filepath"
18 "strings"
19 "testing"
20 "time"
21
22 "amadan.net/oficina/equipo/internal/equipo/identity"
23 "amadan.net/oficina/estilo.git/chrome"
24 "amadan.net/oficina/estilo.git/sky"
25 "amadan.net/rastrillo/rastrillo/auth"
26 "amadan.net/rastrillo/rastrillo/db"
27 "amadan.net/rastrillo/rastrillo/lastsignin"
28 "amadan.net/rastrillo/rastrillo/migrate"
29 "amadan.net/rastrillo/rastrillo/sessions"
30)
31
32const origin = "https://equipo.example"
33
34type stand struct {
35 rt *Routes
36 status int // what the stand-in guard answers; 0 lets the page through
37 invited bool // what Invited answers
38 err error
39}
40
41func newStand(t *testing.T) *stand {
42 t.Helper()
43 logger := slog.New(slog.NewTextHandler(io.Discard, nil))
44 d, err := db.Open(filepath.Join(t.TempDir(), "door.db"), logger)
45 if err != nil {
46 t.Fatal(err)
47 }
48 t.Cleanup(func() { d.Close() })
49 if _, err := migrate.Apply(context.Background(), d, migrate.Merge(sessions.Schema, auth.Schema)); err != nil {
50 t.Fatal(err)
51 }
52 a, err := auth.New(auth.Config{DB: d.Writer(), Origin: origin, InstanceKey: "test-identity-cookie-key", ProofOff: true, SigninScreen: true, SigninOneWay: true, Logger: logger})
53 if err != nil {
54 t.Fatal(err)
55 }
56 s := &stand{}
57 s.rt = &Routes{Auth: a, DB: d.Writer(), Origin: origin, Issuer: "https://id.example",
58 Look: Look{Brand: "Equipo", Oficina: "Oficina ID", Refusal: "refused", Forget: "/auth/forget"},
59 Invited: func(context.Context, string) (bool, error) { return s.invited, s.err },
60 Signout: func(w http.ResponseWriter, r *http.Request) { http.Redirect(w, r, "/signed-out", http.StatusSeeOther) },
61 }
62 s.rt.Guard = func(next http.Handler) http.Handler {
63 return s.rt.Auth.RequireSession(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
64 if s.status != 0 {
65 w.WriteHeader(s.status)
66 return
67 }
68 id, _ := auth.From(r)
69 next.ServeHTTP(w, identity.With(r, id))
70 }))
71 }
72 return s
73}
74
75// session stores a session row for subject by method and returns its cookie.
76func (s *stand) session(t *testing.T, subject, method string) *http.Cookie {
77 t.Helper()
78 token, hash, err := sessions.NewToken()
79 if err != nil {
80 t.Fatal(err)
81 }
82 now := time.Now().UTC()
83 if _, err := s.rt.DB.Exec("INSERT INTO sessions(token_hash,subject,method,auth_time,created_at,expires_at) VALUES(?,?,?,?,?,?)", hash, subject, method, "", now.Format(time.RFC3339), now.Add(time.Hour).Format(time.RFC3339)); err != nil {
84 t.Fatal(err)
85 }
86 return &http.Cookie{Name: s.rt.Auth.SessionCookie(), Value: token}
87}
88
89func request(cookies ...*http.Cookie) *http.Request {
90 r := httptest.NewRequest(http.MethodGet, origin+"/signin", nil)
91 for _, c := range cookies {
92 r.AddCookie(c)
93 }
94 return r
95}
96
97func TestTheProbeJudgesWebSessionsOnly(t *testing.T) {
98 for _, c := range []struct {
99 method string
100 judged bool
101 }{{"magiclink", true}, {"keymail", true}, {"oficina-id", true}, {"home-assertion-native", false}, {"passkey", false}, {"guest", false}} {
102 s := newStand(t)
103 s.status = http.StatusForbidden
104 ad := s.rt.admission(request(s.session(t, "someone@example.test", c.method)))
105 if ad.refused != c.judged || ad.admitted || ad.undecided {
106 t.Errorf("%s: %+v, want refused=%v", c.method, ad, c.judged)
107 }
108 }
109}
110
111func TestTheProbeReadsTheGuard(t *testing.T) {
112 for _, c := range []struct {
113 name string
114 status int
115 invited bool
116 err error
117 want admission
118 }{
119 {"admitted", 0, false, nil, admission{admitted: true, address: "someone@example.test"}},
120 {"refused", http.StatusForbidden, false, nil, admission{refused: true}},
121 {"a refused Oficina ID session (oficinaid's failed page)", http.StatusBadRequest, false, nil, admission{refused: true}},
122 {"storage failed", http.StatusServiceUnavailable, false, nil, admission{undecided: true}},
123 {"any 5xx", http.StatusInternalServerError, false, nil, admission{undecided: true}},
124 {"sent to sign in", http.StatusSeeOther, false, nil, admission{}},
125 {"invited, not yet a member", http.StatusForbidden, true, nil, admission{}},
126 {"invitations unreadable", http.StatusForbidden, false, errors.New("disk"), admission{undecided: true}},
127 } {
128 s := newStand(t)
129 s.status, s.invited, s.err = c.status, c.invited, c.err
130 if got := s.rt.admission(request(s.session(t, "someone@example.test", "magiclink"))); got != c.want {
131 t.Errorf("%s: %+v, want %+v", c.name, got, c.want)
132 }
133 }
134 s := newStand(t)
135 if got := s.rt.admission(request()); got != (admission{}) {
136 t.Errorf("no session: %+v", got)
137 }
138}
139
140// What a 4xx means depends on who the session is: an active member's is
141// only stale (signed out, never refused), an Oficina ID session is judged
142// by the account it is linked to, and any lookup that fails is undecided.
143func TestTheProbeReadsAStaleSessionAsSignedOut(t *testing.T) {
144 disk := errors.New("disk")
145 for _, c := range []struct {
146 name, method, linked string
147 active bool
148 activeErr, linkErr error
149 want admission
150 }{
151 {"an active member's stale session", "magiclink", "", true, nil, nil, admission{stale: true}},
152 {"a removed member", "magiclink", "", false, nil, nil, admission{refused: true}},
153 {"the roster unreadable", "magiclink", "", false, disk, nil, admission{undecided: true}},
154 {"a stale Oficina ID session", "oficina-id", "member@example.test", true, nil, nil, admission{stale: true}},
155 {"an Oficina ID session linked to nobody", "oficina-id", "", true, nil, nil, admission{refused: true}},
156 {"the link unreadable", "oficina-id", "", true, nil, disk, admission{undecided: true}},
157 } {
158 s := newStand(t)
159 s.status = http.StatusForbidden
160 var asked string
161 s.rt.Active = func(_ context.Context, address string) (bool, error) { asked = address; return c.active, c.activeErr }
162 s.rt.Address = func(context.Context, string) (string, error) { return c.linked, c.linkErr }
163 subject := "someone@example.test"
164 if c.method == "oficina-id" {
165 subject = "pr_home_subject"
166 }
167 got := s.rt.admission(request(s.session(t, subject, c.method)))
168 if got != c.want {
169 t.Errorf("%s: %+v, want %+v", c.name, got, c.want)
170 }
171 if c.method == "oficina-id" && c.linked != "" && asked != c.linked {
172 t.Errorf("%s: asked about %q, want the linked address", c.name, asked)
173 }
174 }
175}
176
177// The probe ends nothing: the door does, for a session it refuses.
178func TestTheProbeEndsNothing(t *testing.T) {
179 s := newStand(t)
180 s.status = http.StatusForbidden
181 c := s.session(t, "someone@example.test", "magiclink")
182 if !s.rt.admission(request(c)).refused {
183 t.Fatal("not refused")
184 }
185 if _, ok := s.rt.Auth.SessionFrom(request(c)); !ok {
186 t.Fatal("the probe ended the session")
187 }
188}
189
190func TestOficinaIDIsRememberedOnlyForAnAdmittedSession(t *testing.T) {
191 for _, c := range []struct {
192 name string
193 status int
194 remember bool
195 }{{"admitted", 0, true}, {"refused", http.StatusForbidden, false}, {"undecided", http.StatusServiceUnavailable, false}} {
196 s := newStand(t)
197 s.status = c.status
198 minted := s.session(t, "member@example.test", "oficina-id")
199 // The browser still remembers somebody else's email way.
200 w := httptest.NewRecorder()
201 s.rt.Auth.RememberJar().Remember(w, lastsignin.Record{Method: lastsignin.MethodMagicLink, Address: "earlier@example.test"})
202 old := w.Result().Cookies()[0]
203 w = httptest.NewRecorder()
204 s.rt.SignedIn(w, request(old), minted)
205 rec, res := s.rt.Auth.RememberJar().Read(request(w.Result().Cookies()...))
206 if !c.remember {
207 if res == lastsignin.Valid {
208 t.Errorf("%s: remembered %+v", c.name, rec)
209 }
210 continue
211 }
212 want := lastsignin.Record{Method: lastsignin.MethodFederated, Provider: lastsignin.ProviderOficina, Address: "member@example.test"}
213 if res != lastsignin.Valid || rec != want {
214 t.Errorf("%s: %+v %v, want %+v (the minted session's address, nothing carried over)", c.name, rec, res, want)
215 }
216 }
217}
218
219func TestEveryLandingSpendsTheKeptPage(t *testing.T) {
220 s := newStand(t)
221 kept := &http.Cookie{Name: "__Host-rastrillo_return_to", Value: "%2Fwork"}
222 w := httptest.NewRecorder()
223 s.rt.SignedIn(w, request(kept), s.session(t, "member@example.test", "oficina-id"))
224 if !cleared(w.Result().Cookies(), kept.Name) {
225 t.Fatal("an Oficina ID landing kept the page an email sign-in kept")
226 }
227 w = httptest.NewRecorder()
228 s.rt.homeSignout(w, request(kept))
229 if !cleared(w.Result().Cookies(), kept.Name) {
230 t.Fatal("sign-out kept the page")
231 }
232}
233
234func cleared(cookies []*http.Cookie, name string) bool {
235 for _, c := range cookies {
236 if c.Name == name && c.MaxAge < 0 {
237 return true
238 }
239 }
240 return false
241}
242
243func TestOficinaHrefFollowsTheRoute(t *testing.T) {
244 for _, c := range []struct {
245 target string
246 offer bool
247 want string
248 }{
249 {"/signin", true, "/signin/oficina"},
250 {"/signin?return_to=%2Fwork%3Fa%3D1", true, "/signin/oficina?return_to=%2Fwork%3Fa%3D1"},
251 {"/signin?return_to=%2Fsigned-out", true, "/signin/oficina"},
252 {"/signin?return_to=%2F%2Fevil.example", true, "/signin/oficina"},
253 {"/signin?return_to=%2Faccount%2Fhome%2Fconfirm", true, "/signin/oficina"},
254 {"/signin?reauth=1", true, ""},
255 {"/signin/local", false, ""},
256 {"/signin", false, ""},
257 } {
258 r := httptest.NewRequest(http.MethodGet, origin+c.target, nil)
259 if c.offer {
260 r = withOffer(r)
261 }
262 if got := oficinaHref(r); got != c.want {
263 t.Errorf("%s offer=%v: %q, want %q", c.target, c.offer, got, c.want)
264 }
265 }
266}
267
268func TestSignedOutPageIsCleaned(t *testing.T) {
269 for p, want := range map[string]bool{"/signed-out": true, "/./signed-out": true, "/work/../signed-out": true, "/work/..\\signed-out": true, "/signed-out/": true, "/signed-outs": false, "/work": false} {
270 if got := signedOutPage(p); got != want {
271 t.Errorf("signedOutPage(%q) = %v, want %v", p, got, want)
272 }
273 }
274}
275
276func TestReturnPaths(t *testing.T) {
277 for p, want := range map[string]bool{"/work": true, "/tasks/1?x=2": true, "/signed-out": false, "/signed-out?x=1": false,
278 "//evil.example/x": false, "https://evil.example/": false, "/\\evil.example": false, "/signin": false, "/auth/home": false, "/account/home/confirm": false} {
279 if got := returnPath(p); got != want {
280 t.Errorf("returnPath(%q) = %v, want %v", p, got, want)
281 }
282 }
283}
284
285func TestTheChainedForgetReturnsToTheSignedOutPage(t *testing.T) {
286 if got := OficinaForget("https://id.oficina.works/", "https://equipo.oficina.works"); got != "https://id.oficina.works/forget?return=https%3A%2F%2Fequipo.oficina.works%2Fsigned-out" {
287 t.Fatal(got)
288 }
289}
290
291// The door's stylesheets are estilo's, byte for byte.
292func TestTheDoorsStylesheetsAreEstilos(t *testing.T) {
293 for name, want := range map[string][]byte{"chrome.css": chrome.CSS(), "sky.css": sky.CSS()} {
294 got, err := os.ReadFile(filepath.Join("..", "static", "estilo", name))
295 if err != nil || !bytes.Equal(got, want) {
296 t.Errorf("static/estilo/%s differs from estilo's (re-copy it from the pinned estilo): %v", name, err)
297 }
298 }
299}
300
301func TestStaticServesTheSkyAndTheMark(t *testing.T) {
302 mux := http.NewServeMux()
303 Static(mux)
304 for _, path := range []string{Icon(), sky.For("equipo.example").Layers[2].Src} {
305 w := httptest.NewRecorder()
306 mux.ServeHTTP(w, httptest.NewRequest(http.MethodGet, path, nil))
307 if w.Code != http.StatusOK || !strings.Contains(w.Header().Get("Content-Type"), "svg") {
308 t.Errorf("%s: %d %s", path, w.Code, w.Header().Get("Content-Type"))
309 }
310 }
311}
312