oficina / home Public

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

Plain git — no account needed to clone.

Download

Download this file

1package home
2
3import (
4 "crypto/rand"
5 "crypto/sha256"
6 "encoding/base64"
7 "encoding/hex"
8 "encoding/json"
9 "net/http"
10 "net/http/httptest"
11 "regexp"
12 "strings"
13 "testing"
14 "time"
15
16 "amadan.net/rastrillo/rastrillo/assertion"
17 assertioncrypto "amadan.net/rastrillo/rastrillo/crypto"
18)
19
20// newNativeApp is a credential-role app: the native endpoints mount only
21// there. Its consumers are the directory and one team's Docs.
22func newNativeApp(t *testing.T) *testApp {
23 t.Helper()
24 app := newTestApp(t)
25 key, err := assertioncrypto.Generate()
26 if err != nil {
27 t.Fatal(err)
28 }
29 sum := sha256.Sum256(key.SignPub())
30 kid := hex.EncodeToString(sum[:])
31 app.runtime = &Runtime{role: "credential", origins: app.origins, secrets: app.secrets, signer: key, keyID: kid, keys: map[string][]byte{kid: key.SignPub()}, consumers: map[string]string{"directory": directoryOrigin, "team_docs": "https://blue.docs.oficina.works"}}
32 return app
33}
34
35// restart builds a fresh App on the same database and keys: every in-memory
36// budget is new, everything persistent is not.
37func (app *testApp) restart(t *testing.T) *testApp {
38 t.Helper()
39 next, err := NewWithOrigins(app.secrets, app.db, quietLogger(), app.origins)
40 if err != nil {
41 t.Fatal(err)
42 }
43 next.flow.Classifier.LookupTXT = app.flow.Classifier.LookupTXT
44 next.runtime = app.runtime
45 return &testApp{App: next, mailer: app.mailer, db: app.db, dbPath: app.dbPath}
46}
47
48// device is a native app's device key.
49type device struct {
50 key *assertioncrypto.Keypair
51 platform string
52}
53
54func newDevice(t *testing.T) *device {
55 t.Helper()
56 k, err := assertioncrypto.Generate()
57 if err != nil {
58 t.Fatal(err)
59 }
60 return &device{key: k, platform: "macos"}
61}
62func (d *device) public() string { return base64.RawURLEncoding.EncodeToString(d.key.SignPub()) }
63
64// proofOpts tampers with one part of a proof.
65type proofOpts struct {
66 iat int64
67 htu, jti string
68 signedBody []byte // sign over this body instead of the one sent
69 signer *device
70 headers map[string]string
71 ip string
72}
73
74func (d *device) proof(t *testing.T, path string, body []byte, o proofOpts) string {
75 t.Helper()
76 signed := body
77 if o.signedBody != nil {
78 signed = o.signedBody
79 }
80 bh := sha256.Sum256(signed)
81 iat := time.Now().Unix()
82 if o.iat != 0 {
83 iat = o.iat
84 }
85 htu := Origin + path
86 if o.htu != "" {
87 htu = o.htu
88 }
89 jti := o.jti
90 if jti == "" {
91 r := make([]byte, 16)
92 if _, err := rand.Read(r); err != nil {
93 t.Fatal(err)
94 }
95 jti = base64.RawURLEncoding.EncodeToString(r)
96 }
97 payload, err := json.Marshal(map[string]any{"v": 1, "htm": "POST", "htu": htu, "iat": iat, "jti": jti, "bh": base64.RawURLEncoding.EncodeToString(bh[:])})
98 if err != nil {
99 t.Fatal(err)
100 }
101 signer := d
102 if o.signer != nil {
103 signer = o.signer
104 }
105 sig, err := assertioncrypto.Sign(signer.key, nativeProofContext, payload)
106 if err != nil {
107 t.Fatal(err)
108 }
109 return base64.RawURLEncoding.EncodeToString(payload) + "." + base64.RawURLEncoding.EncodeToString(sig)
110}
111
112// call drives one native endpoint as the app would.
113func (d *device) call(t *testing.T, app *testApp, path string, body any, grant string, o ...proofOpts) *httptest.ResponseRecorder {
114 t.Helper()
115 var opts proofOpts
116 if len(o) > 0 {
117 opts = o[0]
118 }
119 b, err := json.Marshal(body)
120 if err != nil {
121 t.Fatal(err)
122 }
123 req := httptest.NewRequest("POST", Origin+path, strings.NewReader(string(b)))
124 req.Header.Set("Content-Type", "application/json")
125 req.Header.Set("Oficina-Proof", d.proof(t, path, b, opts))
126 if grant != "" {
127 req.Header.Set("Authorization", "OficinaID "+grant)
128 }
129 req.RemoteAddr = "192.0.2.10:4444"
130 if opts.ip != "" {
131 req.RemoteAddr = opts.ip
132 }
133 for k, v := range opts.headers {
134 req.Header.Set(k, v)
135 }
136 w := httptest.NewRecorder()
137 app.Router().ServeHTTP(w, req)
138 return w
139}
140
141func decodeReply(t *testing.T, w *httptest.ResponseRecorder) map[string]any {
142 t.Helper()
143 var out map[string]any
144 if err := json.Unmarshal(w.Body.Bytes(), &out); err != nil {
145 t.Fatalf("not JSON (%d): %s", w.Code, w.Body.String())
146 }
147 return out
148}
149
150func (d *device) start(t *testing.T, app *testApp, email string) string {
151 t.Helper()
152 w := d.call(t, app, nativePrefix+"/code/start", map[string]string{"email": email, "device_key": d.public(), "platform": d.platform}, "")
153 if w.Code != http.StatusAccepted {
154 t.Fatalf("start: %d %s", w.Code, w.Body.String())
155 }
156 return decodeReply(t, w)["start"].(string)
157}
158
159var codeLine = regexp.MustCompile(`Your Oficina ID code is (\d{6})`)
160
161func lastCode(t *testing.T, app *testApp) string {
162 t.Helper()
163 m, ok := app.mailer.last()
164 if !ok {
165 t.Fatal("no mail")
166 }
167 got := codeLine.FindStringSubmatch(m.Body)
168 if got == nil {
169 t.Fatal("no code in mail")
170 }
171 return got[1]
172}
173
174func (d *device) verify(t *testing.T, app *testApp, start, code string) *httptest.ResponseRecorder {
175 t.Helper()
176 return d.call(t, app, nativePrefix+"/code/verify", map[string]string{"start": start, "code": code}, "")
177}
178
179// signInByCode runs the whole code sign-in and returns the grant token.
180func (d *device) signInByCode(t *testing.T, app *testApp, email string) (grant, identityID string) {
181 t.Helper()
182 start := d.start(t, app, email)
183 w := d.verify(t, app, start, lastCode(t, app))
184 out := decodeReply(t, w)
185 if w.Code != 200 || out["grant"] == nil {
186 t.Fatalf("verify: %d %s", w.Code, w.Body.String())
187 }
188 return out["grant"].(string), out["identity_id"].(string)
189}
190
191func (d *device) assert(t *testing.T, app *testApp, grant, aud string, challenge []byte, o ...proofOpts) *httptest.ResponseRecorder {
192 t.Helper()
193 return d.call(t, app, nativePrefix+"/assert", map[string]string{"aud": aud, "challenge": base64.RawURLEncoding.EncodeToString(challenge)}, grant, o...)
194}
195
196func grantState(t *testing.T, app *testApp, grant string) (ended bool, reason string) {
197 t.Helper()
198 var e *int64
199 var why *string
200 if err := app.db.Writer().QueryRow("SELECT ended_at,end_reason FROM home_id_grants WHERE grant_hash=?", nativeHash(grant)).Scan(&e, &why); err != nil {
201 t.Fatal(err)
202 }
203 if why != nil {
204 reason = *why
205 }
206 return e != nil, reason
207}
208
209func count(t *testing.T, app *testApp, query string, args ...any) int {
210 t.Helper()
211 var n int
212 if err := app.db.Writer().QueryRow(query, args...).Scan(&n); err != nil {
213 t.Fatal(err)
214 }
215 return n
216}
217
218// verifierFor is a native client's verifier and challenge: SHA-256 of the
219// verifier's base64url string.
220func verifierFor(seed byte) (verifier string, challenge []byte) {
221 raw := make([]byte, 32)
222 for i := range raw {
223 raw[i] = seed + byte(i)
224 }
225 verifier = base64.RawURLEncoding.EncodeToString(raw)
226 sum := sha256.Sum256([]byte(verifier))
227 return verifier, sum[:]
228}
229
230func verifyAssertion(t *testing.T, app *testApp, token, aud string) assertion.Claims {
231 t.Helper()
232 v, err := assertion.NewVerifier(Origin, aud, app.runtime.keys)
233 if err != nil {
234 t.Fatal(err)
235 }
236 c, err := v.Verify(token, time.Now())
237 if err != nil {
238 t.Fatal(err)
239 }
240 return c
241}
242