oficina / base Public

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

Plain git — no account needed to clone.

Download

Download this file

1package equipotest
2
3import (
4 "crypto/ed25519"
5 "crypto/rand"
6 "encoding/base64"
7 "mime"
8 "net/http"
9 "net/url"
10 "strings"
11 "sync"
12 "time"
13 "unicode/utf8"
14)
15
16// Equipo's own native sign-in with Oficina ID, as Base completes it for a
17// person (Equipo's internal/equipo/oficinaid/native.go and
18// personapi/native_device.go):
19//
20// - POST /native/oficina-id trades an assertion Oficina ID made for
21// Equipo, and its verifier, for a seven-day native session, only for a
22// subject Equipo has linked to a roster member. It refuses anything a
23// browser sends (Origin, Sec-Fetch-Site), and answers
24// {name, value, expires_at}, or {"state": …} with 400, 401 failed,
25// 403 unknown or 503.
26// - POST /api/v1/auth/devices/native, with that session's cookie and
27// Equipo's own Origin, registers a device key and answers its person
28// credential, which ends with the session.
29//
30// The fake does not verify signatures: OficinaAssertion hands out an opaque
31// assertion and its verifier, as Oficina ID would for Equipo, and the
32// exchange accepts each once.
33
34// SessionCookie is the name of the fake's session cookie.
35const SessionCookie = "__Host-equipo_session"
36
37// nativeLifetime is how long Equipo's native session, and every device
38// registered with it, lasts.
39const nativeLifetime = 7 * 24 * time.Hour
40
41type nativeSession struct {
42 subject, address string
43 at time.Time
44 ended bool
45}
46
47type assertionGrant struct {
48 subject, verifier string
49 used bool
50}
51
52type nativeState struct {
53 nmu sync.Mutex
54 links map[string]string // Oficina subject → roster address
55 assertions map[string]*assertionGrant
56 sessions map[string]*nativeSession // cookie value → session
57 failNative int // the next exchange's status, once
58 // nativeHold, when set, stops the next exchange until it is closed;
59 // nativeEntered is closed when that exchange arrives.
60 nativeHold, nativeEntered chan struct{}
61}
62
63func (n *nativeState) init() {
64 n.links, n.assertions, n.sessions = map[string]string{}, map[string]*assertionGrant{}, map[string]*nativeSession{}
65}
66
67// LinkOficinaID links the Oficina ID subject to the roster member address,
68// as signing in to Equipo with Oficina ID once does.
69func (f *Fake) LinkOficinaID(subject, address string) {
70 f.nmu.Lock()
71 defer f.nmu.Unlock()
72 f.links[subject] = address
73}
74
75// OficinaAssertion is an assertion Oficina ID made for Equipo about
76// subject, and its verifier, as the native app fetches them.
77func (f *Fake) OficinaAssertion(subject string) (assertion, verifier string) {
78 f.nmu.Lock()
79 defer f.nmu.Unlock()
80 assertion, verifier = "oficina."+rand.Text()+rand.Text(), rand.Text()+rand.Text()
81 f.assertions[assertion] = &assertionGrant{subject: subject, verifier: verifier}
82 return assertion, verifier
83}
84
85// FailNextNativeExchange makes the next native exchange answer status
86// (with its state), as Equipo does when it is down (503).
87func (f *Fake) FailNextNativeExchange(status int) {
88 f.nmu.Lock()
89 defer f.nmu.Unlock()
90 f.failNative = status
91}
92
93// HoldNextNativeExchange makes the next native exchange wait, once it has
94// arrived and before it answers, until release is called: a test can act
95// in between. entered is closed when it arrives.
96func (f *Fake) HoldNextNativeExchange() (entered <-chan struct{}, release func()) {
97 f.nmu.Lock()
98 defer f.nmu.Unlock()
99 f.nativeHold, f.nativeEntered = make(chan struct{}), make(chan struct{})
100 hold := f.nativeHold
101 return f.nativeEntered, func() { close(hold) }
102}
103
104// NativeSessions is how many native sessions the fake has minted.
105func (f *Fake) NativeSessions() int {
106 f.nmu.Lock()
107 defer f.nmu.Unlock()
108 return len(f.sessions)
109}
110
111// EndNativeSession ends the native session whose cookie is value, as
112// signing out of Equipo does, and revokes every device registered with it.
113func (f *Fake) EndNativeSession(value string) {
114 f.nmu.Lock()
115 if s := f.sessions[value]; s != nil {
116 s.ended = true
117 }
118 f.nmu.Unlock()
119 f.mu.Lock()
120 defer f.mu.Unlock()
121 for _, d := range f.devices {
122 if d.session == value {
123 d.revoked = true
124 }
125 }
126}
127
128// DeviceSession is the native session cookie the device with id was
129// registered with ("" for a device from the code flow).
130func (f *Fake) DeviceSession(id string) string {
131 f.mu.Lock()
132 defer f.mu.Unlock()
133 if d := f.devices[id]; d != nil {
134 return d.session
135 }
136 return ""
137}
138
139// LiveCredentials are the ids of the devices holding a credential Equipo
140// still takes: exchanged or registered, and not revoked.
141func (f *Fake) LiveCredentials() []string {
142 f.mu.Lock()
143 defer f.mu.Unlock()
144 var out []string
145 for id, d := range f.devices {
146 if d.token != "" && !d.revoked {
147 out = append(out, id)
148 }
149 }
150 return out
151}
152
153// Devices are the ids of every device the fake knows.
154func (f *Fake) Devices() []string {
155 f.mu.Lock()
156 defer f.mu.Unlock()
157 var out []string
158 for id := range f.devices {
159 out = append(out, id)
160 }
161 return out
162}
163
164func nativeAnswer(w http.ResponseWriter, status int, state string) {
165 writeJSON(w, status, map[string]string{"state": state})
166}
167
168// serveNative answers the two native routes, and reports whether r was
169// one of them.
170func (f *Fake) serveNative(w http.ResponseWriter, r *http.Request) bool {
171 switch {
172 case r.Method == http.MethodPost && r.URL.Path == "/native/oficina-id":
173 f.nativeExchange(w, r)
174 case r.Method == http.MethodPost && r.URL.Path == "/api/v1/auth/devices/native":
175 f.nativeDevice(w, r)
176 default:
177 return false
178 }
179 return true
180}
181
182func (f *Fake) nativeExchange(w http.ResponseWriter, r *http.Request) {
183 u, _ := url.Parse(f.URL)
184 media, _, err := mime.ParseMediaType(r.Header.Get("Content-Type"))
185 if r.Host != u.Host || r.URL.RawQuery != "" || len(r.Header.Values("Origin")) != 0 || len(r.Header.Values("Sec-Fetch-Site")) != 0 ||
186 len(r.Header.Values("Cookie")) != 0 || len(r.Header.Values("Authorization")) != 0 || err != nil || media != "application/json" {
187 nativeAnswer(w, 400, "invalid")
188 return
189 }
190 var in struct {
191 Assertion string `json:"assertion"`
192 Verifier string `json:"verifier"`
193 }
194 if strict(r, &in) != nil || in.Assertion == "" || in.Verifier == "" {
195 nativeAnswer(w, 400, "invalid")
196 return
197 }
198 f.nmu.Lock()
199 hold, entered := f.nativeHold, f.nativeEntered
200 f.nativeHold, f.nativeEntered = nil, nil
201 f.nmu.Unlock()
202 if hold != nil {
203 close(entered)
204 select {
205 case <-hold:
206 case <-f.closing:
207 return
208 }
209 }
210 f.nmu.Lock()
211 defer f.nmu.Unlock()
212 if status := f.failNative; status != 0 {
213 f.failNative = 0
214 state, ok := map[int]string{400: "invalid", 401: "failed", 403: "unknown"}[status]
215 if !ok {
216 state = "unavailable"
217 }
218 nativeAnswer(w, status, state)
219 return
220 }
221 g := f.assertions[in.Assertion]
222 if g == nil || g.used || g.verifier != in.Verifier {
223 nativeAnswer(w, 401, "failed")
224 return
225 }
226 address, linked := f.links[g.subject]
227 if !linked {
228 nativeAnswer(w, 403, "unknown")
229 return
230 }
231 g.used = true
232 value := rand.Text() + rand.Text()
233 now := time.Now().UTC().Truncate(time.Second)
234 f.sessions[value] = &nativeSession{subject: g.subject, address: address, at: now}
235 writeJSON(w, 200, map[string]any{"name": SessionCookie, "value": value, "expires_at": now.Add(nativeLifetime).Unix()})
236}
237
238func (f *Fake) nativeDevice(w http.ResponseWriter, r *http.Request) {
239 // A browser-style request: the session cookie, and Equipo's own
240 // Origin, which its CSRF check wants on a cookie mutation.
241 if r.Header.Get("Origin") != f.URL || len(r.Header.Values("Authorization")) != 0 || len(r.Header.Values("Idempotency-Key")) > 1 {
242 writeError(w, r, 403, "forbidden")
243 return
244 }
245 c, err := r.Cookie(SessionCookie)
246 if err != nil || len(r.Cookies()) != 1 {
247 writeError(w, r, 401, "unauthenticated")
248 return
249 }
250 var in struct {
251 PublicKey string `json:"public_key"`
252 Label string `json:"label"`
253 }
254 if strict(r, &in) != nil {
255 writeError(w, r, 422, "invalid_input")
256 return
257 }
258 raw, err := base64.RawURLEncoding.Strict().DecodeString(in.PublicKey)
259 if err != nil || len(raw) != ed25519.PublicKeySize || in.Label == "" || len(in.Label) > 128 || !utf8.ValidString(in.Label) || strings.ContainsAny(in.Label, "\x00\r\n") {
260 writeError(w, r, 422, "invalid_input")
261 return
262 }
263 f.nmu.Lock()
264 s := f.sessions[c.Value]
265 live := s != nil && !s.ended && time.Now().Before(s.at.Add(nativeLifetime))
266 var at time.Time
267 if live {
268 at = s.at
269 }
270 f.nmu.Unlock()
271 if !live {
272 writeError(w, r, 401, "unauthenticated")
273 return
274 }
275 d := &device{id: rand.Text(), publicKey: in.PublicKey, label: in.Label, approved: true, revision: 1,
276 token: personAudience + "." + rand.Text(), expires: at.Add(nativeLifetime), session: c.Value}
277 f.mu.Lock()
278 f.devices[d.id] = d
279 f.mu.Unlock()
280 w.Header().Set("ETag", `"1"`)
281 writeJSON(w, 200, map[string]any{"id": d.id, "token": d.token, "audience": personAudience,
282 "instance_id": f.Instance, "expires_at": d.expires})
283}
284