oficina / equipo Public

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

Plain git — no account needed to clone.

Download

Download this file

1package plan3test
2
3import (
4 "context"
5 "crypto/ed25519"
6 "crypto/rand"
7 "encoding/base64"
8 "encoding/json"
9 "fmt"
10 "gorm.io/gorm"
11 "net/http/httptest"
12 "strings"
13 "testing"
14 "time"
15
16 "amadan.net/oficina/equipo/internal/equipo"
17 "amadan.net/oficina/equipo/internal/equipo/personapi"
18)
19
20func deviceRequest(t *testing.T, f *fixture, token, method, path, body, key, rev string) *httptest.ResponseRecorder {
21 t.Helper()
22 r := httptest.NewRequest(method, path, strings.NewReader(body))
23 r.RemoteAddr = "127.0.0.1:1234"
24 r.Header.Set("Content-Type", "application/json")
25 r.Header.Set("Idempotency-Key", key)
26 if rev != "" {
27 r.Header.Set("If-Match", rev)
28 }
29 if token != "" {
30 r.Header.Set("Authorization", "Bearer "+token)
31 }
32 w := httptest.NewRecorder()
33 f.Handler.ServeHTTP(w, r)
34 return w
35}
36func deviceChallenge(t *testing.T, f *fixture) (personapi.PersonDeviceChallenge, ed25519.PrivateKey) {
37 t.Helper()
38 pub, key, err := ed25519.GenerateKey(rand.Reader)
39 must(t, err)
40 body := fmt.Sprintf(`{"public_key":%q,"label":"My phone"}`, base64.RawURLEncoding.EncodeToString(pub))
41 w := deviceRequest(t, f, "", "POST", "/api/v1/auth/devices", body, rand.Text(), "")
42 expectHTTP(t, w, 200)
43 c := apiValue[personapi.PersonDeviceChallenge](t, w)
44 if c.ID == "" || c.DeviceSecret == "" || c.UserCode == "" || c.Challenge == "" || c.PollIntervalSeconds != 5 {
45 t.Fatal("incomplete device challenge", c)
46 }
47 return c, key
48}
49func signedDevice(t *testing.T, f *fixture, c personapi.PersonDeviceChallenge, key ed25519.PrivateKey) string {
50 t.Helper()
51 p := personapi.PersonDeviceProof{ID: c.ID, DeviceSecret: c.DeviceSecret, Challenge: c.Challenge, Nonce: rand.Text()}
52 p.Signature = base64.RawURLEncoding.EncodeToString(ed25519.Sign(key, personapi.DeviceProofMessage(f.TeamID, p)))
53 b, err := json.Marshal(p)
54 must(t, err)
55 return string(b)
56}
57func approvedDevice(t *testing.T, f *fixture) personapi.PersonCredential {
58 t.Helper()
59 c, key := deviceChallenge(t, f)
60 w := apiRequest(t, f, owner, "POST", "/api/v1/auth/devices/"+c.ID+"/approve", fmt.Sprintf(`{"typed_code":%q}`, c.UserCode), "approve", `"1"`)
61 expectHTTP(t, w, 200)
62 w = deviceRequest(t, f, "", "POST", "/api/v1/auth/devices/exchange", signedDevice(t, f, c, key), "exchange", "")
63 expectHTTP(t, w, 200)
64 return apiValue[personapi.PersonCredential](t, w)
65}
66func TestPersonAPIDeviceApproval(t *testing.T) {
67 f := newFixture(t)
68 c, key := deviceChallenge(t, f)
69 page := f.get(t, owner, "/auth/devices/"+c.ID)
70 expectHTTP(t, page, 200)
71 if !strings.Contains(page.Body.String(), "My phone") || !strings.Contains(page.Body.String(), c.ExpiresAt.Add(-10*time.Minute).Format(time.RFC3339)) {
72 t.Fatal("approval omits label or server creation time", page.Body.String())
73 }
74 if strings.Contains(page.Body.String(), c.UserCode) || strings.Contains(page.Body.String(), c.DeviceSecret) {
75 t.Fatal("approval prefills secret or code")
76 }
77 path := "/api/v1/auth/devices/" + c.ID + "/approve"
78 expectHTTP(t, apiRequest(t, f, owner, "POST", path, `{}`, "missing", `"1"`), 422)
79 expectHTTP(t, apiRequest(t, f, owner, "POST", path+"?typed_code="+c.UserCode, `{}`, "link", `"1"`), 422)
80 expectHTTP(t, apiRequest(t, f, owner, "POST", path, fmt.Sprintf(`{"typed_code":%q}`, c.UserCode), "approve", `"1"`), 200)
81 proof := signedDevice(t, f, c, key)
82 w := deviceRequest(t, f, "", "POST", "/api/v1/auth/devices/exchange", proof, "exchange", "")
83 expectHTTP(t, w, 200)
84 cred := apiValue[personapi.PersonCredential](t, w)
85 if cred.Audience != "equipo.person.v1" || cred.InstanceID != f.TeamID {
86 t.Fatal("wrong credential binding", cred)
87 }
88 replay := deviceRequest(t, f, "", "POST", "/api/v1/auth/devices/exchange", proof, "exchange", "")
89 expectHTTP(t, replay, 200)
90 if replay.Body.String() != w.Body.String() {
91 t.Fatal("lost response replay minted a new credential")
92 }
93 expectHTTP(t, deviceRequest(t, f, cred.Token, "GET", "/api/v1/me", "", "", ""), 200)
94 list := deviceRequest(t, f, cred.Token, "GET", "/api/v1/auth/devices", "", "", "")
95 expectHTTP(t, list, 200)
96 for _, secret := range []string{cred.Token, c.DeviceSecret, c.UserCode, c.Challenge, "token_hash", "public_key", "result_cipher"} {
97 if strings.Contains(list.Body.String(), secret) {
98 t.Fatal("private device field leaked", secret)
99 }
100 }
101 expectHTTP(t, deviceRequest(t, f, cred.Token, "POST", path, fmt.Sprintf(`{"typed_code":%q}`, c.UserCode), "bearer-approval", `"1"`), 401)
102 expectHTTP(t, deviceRequest(t, f, "", "POST", "/api/v1/auth/devices/exchange", signedDevice(t, f, c, key), "new-nonce", ""), 403)
103 expectHTTP(t, deviceRequest(t, f, cred.Token, "DELETE", "/api/v1/auth/devices/"+cred.ID, `{}`, "revoke", `"3"`), 200)
104 expectHTTP(t, deviceRequest(t, f, cred.Token, "GET", "/api/v1/me", "", "", ""), 401)
105}
106func TestPersonAPIDeviceGuards(t *testing.T) {
107 for _, kind := range []string{"key", "challenge", "expiry", "epoch", "removed", "audience"} {
108 t.Run(kind, func(t *testing.T) {
109 f := newFixture(t)
110 c, key := deviceChallenge(t, f)
111 expectHTTP(t, apiRequest(t, f, owner, "POST", "/api/v1/auth/devices/"+c.ID+"/approve", fmt.Sprintf(`{"typed_code":%q}`, c.UserCode), "approve", `"1"`), 200)
112 switch kind {
113 case "key":
114 _, key, _ = ed25519.GenerateKey(rand.Reader)
115 case "challenge":
116 c.Challenge = "wrong"
117 case "expiry":
118 f.exec(t, "UPDATE person_devices SET expires_at=? WHERE id=?", time.Now().Add(-time.Hour), c.ID)
119 case "epoch":
120 f.exec(t, "UPDATE members SET session_epoch=? WHERE address=?", time.Now().Add(time.Hour).Unix(), owner.Address)
121 case "removed":
122 f.exec(t, "UPDATE members SET active=0 WHERE address=?", owner.Address)
123 case "audience":
124 c.DeviceSecret = "equipo.runner.v2.secret"
125 }
126 w := deviceRequest(t, f, "", "POST", "/api/v1/auth/devices/exchange", signedDevice(t, f, c, key), "exchange", "")
127 if w.Code < 400 {
128 t.Fatal("device guard bypassed", kind, w.Body.String())
129 }
130 })
131 }
132}
133func TestPersonAPIBrowserCSRFRealDevice(t *testing.T) {
134 f := newFixture(t)
135 c := approvedDevice(t, f)
136 expectHTTP(t, deviceRequest(t, f, c.Token, "POST", "/api/v1/conversation/messages", `{"body":"native"}`, "native", ""), 200)
137 r := httptest.NewRequest("POST", "/api/v1/conversation/messages", strings.NewReader(`{"body":"cross"}`))
138 r.Header.Set("Authorization", "Bearer "+c.Token)
139 r.Header.Set("Origin", "https://evil.example")
140 r.Header.Set("Content-Type", "application/json")
141 r.Header.Set("Idempotency-Key", "cross")
142 w := httptest.NewRecorder()
143 f.Handler.ServeHTTP(w, r)
144 expectHTTP(t, w, 403)
145 r.Header.Set("Origin", origin)
146 r.AddCookie(f.Cookies[owner.Address])
147 w = httptest.NewRecorder()
148 f.Handler.ServeHTTP(w, r)
149 expectHTTP(t, w, 401)
150 f.exec(t, "UPDATE members SET session_epoch=? WHERE address=?", time.Now().Add(time.Hour).Unix(), owner.Address)
151 expectHTTP(t, deviceRequest(t, f, c.Token, "GET", "/api/v1/me", "", "", ""), 401)
152}
153
154var _ = equipo.Mutation{}
155
156func TestPersonAPIDeviceThrottleAndExpiry(t *testing.T) {
157 f := newFixture(t)
158 c, key := deviceChallenge(t, f)
159 path := "/api/v1/auth/devices/" + c.ID + "/approve"
160 expectHTTP(t, apiRequest(t, f, owner, "POST", path, `{"typed_code":"WRONG123"}`, "wrong", `"1"`), 403)
161 proof := signedDevice(t, f, c, key)
162 expectHTTP(t, deviceRequest(t, f, "", "POST", "/api/v1/auth/devices/exchange", proof, "poll", ""), 409)
163 expectHTTP(t, deviceRequest(t, f, "", "POST", "/api/v1/auth/devices/exchange", proof, "poll", ""), 429)
164 expectHTTP(t, apiRequest(t, f, owner, "POST", path, fmt.Sprintf(`{"typed_code":%q}`, c.UserCode), "approve", `"1"`), 200)
165 f.exec(t, "UPDATE person_devices SET last_poll=? WHERE id=?", time.Now().Add(-6*time.Second), c.ID)
166 w := deviceRequest(t, f, "", "POST", "/api/v1/auth/devices/exchange", proof, "poll", "")
167 expectHTTP(t, w, 200)
168 cred := apiValue[personapi.PersonCredential](t, w)
169 var saved string
170 must(t, f.DB.Writer().QueryRow("SELECT token_hash||secret_hash||code_hash||result_cipher||begin_cipher FROM person_devices WHERE id=?", c.ID).Scan(&saved))
171 for _, secret := range []string{cred.Token, c.DeviceSecret, c.UserCode} {
172 if strings.Contains(saved, secret) {
173 t.Fatal("credential stored in plaintext")
174 }
175 }
176 f.exec(t, "UPDATE person_devices SET result_expires_at=? WHERE id=?", time.Now().Add(-time.Second), c.ID)
177 expectHTTP(t, deviceRequest(t, f, "", "POST", "/api/v1/auth/devices/exchange", proof, "poll", ""), 410)
178 if f.count(t, "SELECT count(*) FROM person_devices WHERE id=? AND result_cipher<>''", c.ID) != 0 {
179 t.Fatal("expired replay result retained")
180 }
181 f.exec(t, "UPDATE person_devices SET token_expires_at=? WHERE id=?", time.Now().Add(-time.Second), c.ID)
182 expectHTTP(t, deviceRequest(t, f, cred.Token, "GET", "/api/v1/me", "", "", ""), 401)
183 for i := 0; i < 9; i++ {
184 deviceChallenge(t, f)
185 }
186 pub, _, err := ed25519.GenerateKey(rand.Reader)
187 must(t, err)
188 expectHTTP(t, deviceRequest(t, f, "", "POST", "/api/v1/auth/devices", fmt.Sprintf(`{"public_key":%q,"label":"extra"}`, base64.RawURLEncoding.EncodeToString(pub)), "extra", ""), 429)
189}
190
191func TestPersonAPIDeviceIdleExpiry(t *testing.T) {
192 f := newFixture(t)
193 cred := approvedDevice(t, f)
194 f.exec(t, "UPDATE person_devices SET result_expires_at=? WHERE id=?", time.Now().Add(-time.Second), cred.ID)
195 maintenance := personapi.DeviceStore{Now: time.Now, Write: func(ctx context.Context, fn func(*gorm.DB) error) error {
196 return f.DB.G.WithContext(ctx).Transaction(fn)
197 }}
198 must(t, maintenance.Sweep(ctx))
199 if f.count(t, "SELECT count(*) FROM person_devices WHERE id=? AND result_cipher<>''", cred.ID) != 0 {
200 t.Fatal("idle expired replay result retained")
201 }
202 expectHTTP(t, deviceRequest(t, f, cred.Token, "GET", "/api/v1/me", "", "", ""), 200)
203}
204