| 1 | package plan3test |
| 2 | |
| 3 | import ( |
| 4 | "amadan.net/oficina/equipo/internal/equipo/kernel" |
| 5 | "bytes" |
| 6 | "context" |
| 7 | "crypto/sha256" |
| 8 | "encoding/base64" |
| 9 | "encoding/json" |
| 10 | "errors" |
| 11 | "gorm.io/gorm" |
| 12 | "io" |
| 13 | "log/slog" |
| 14 | "net/http" |
| 15 | "net/http/httptest" |
| 16 | "strings" |
| 17 | "testing" |
| 18 | "time" |
| 19 | |
| 20 | "amadan.net/oficina/equipo/internal/equipo" |
| 21 | "amadan.net/oficina/equipo/internal/equipo/oficinaid" |
| 22 | "amadan.net/oficina/equipo/internal/equipo/personapi" |
| 23 | "amadan.net/oficina/home/connect" |
| 24 | "amadan.net/oficina/home/handoff" |
| 25 | "amadan.net/rastrillo/rastrillo/assertion" |
| 26 | "amadan.net/rastrillo/rastrillo/crypto" |
| 27 | "amadan.net/rastrillo/rastrillo/mail" |
| 28 | "amadan.net/rastrillo/rastrillo/sessions" |
| 29 | ) |
| 30 | |
| 31 | const nativeOrigin = "https://equipo-staging.bds.oncarlos.com" |
| 32 | const nativeSubject = "pr_aaaaaaaaaaaaaaaaaaaaaaaaaa" |
| 33 | |
| 34 | func nativeIDFixture(t *testing.T) (*fixture, *oficinaid.Store, string, *crypto.Keypair) { |
| 35 | t.Helper() |
| 36 | f := newFixture(t) |
| 37 | key, e := crypto.Generate() |
| 38 | must(t, e) |
| 39 | cfg := &connect.DecodedCredentials{Issuer: "https://id.example", ConsumerID: "equipo", Keys: map[string][]byte{"k": key.SignPub()}, DEK: bytes.Repeat([]byte{7}, 32)} |
| 40 | s, e := oficinaid.New(f.DB.Writer(), nativeOrigin, cfg) |
| 41 | must(t, e) |
| 42 | now := time.Now().UTC().Truncate(time.Second) |
| 43 | old := f.Cookies[owner.Address].Value |
| 44 | proof, e := s.BeginReauth(ctx, old, "link", now) |
| 45 | must(t, e) |
| 46 | fresh, hash, e := sessions.NewToken() |
| 47 | must(t, e) |
| 48 | f.exec(t, "INSERT INTO sessions(token_hash,subject,method,auth_time,created_at,expires_at) VALUES(?,?,?,?,?,?)", hash, owner.Address, "magiclink", now.Format(time.RFC3339), now.Format(time.RFC3339), now.Add(time.Hour).Format(time.RFC3339)) |
| 49 | init, _, e := s.CompleteReauth(ctx, proof, fresh, now) |
| 50 | must(t, e) |
| 51 | secret, nonce, e := s.Exchange.StartFresh(ctx, "/account/home/confirm", "", now) |
| 52 | must(t, e) |
| 53 | must(t, s.Bind(ctx, init, fresh, nonce, now)) |
| 54 | sign := func(nonce string) string { |
| 55 | id, e := assertion.RandomID() |
| 56 | must(t, e) |
| 57 | v, e := assertion.Sign(key, assertion.Claims{Version: 1, KeyID: "k", Issuer: cfg.Issuer, Audience: nativeOrigin, Subject: nativeSubject, ID: id, Nonce: nonce, IssuedAt: now.Unix(), ExpiresAt: now.Unix() + 120, AuthTime: now.Unix()}) |
| 58 | must(t, e) |
| 59 | return v |
| 60 | } |
| 61 | receipt, e := s.Exchange.ReceivePending(ctx, sign(nonce), now) |
| 62 | must(t, e) |
| 63 | confirmation, _, e := s.Finish(ctx, secret, receipt, fresh, init, now) |
| 64 | must(t, e) |
| 65 | must(t, s.Confirm(ctx, confirmation, fresh, now)) |
| 66 | logger := slog.New(slog.NewTextHandler(io.Discard, nil)) |
| 67 | router, e := equipo.RouterWithStore(f.DB, equipo.Config{Origin: nativeOrigin, InstanceKey: "plan3-fixture", Home: cfg, AllowLoggedMail: true, Owners: []string{owner.Address}}, mail.Logged(logger), logger, f.Store) |
| 68 | must(t, e) |
| 69 | f.Handler = equipo.Mux(router) |
| 70 | verifier := base64.RawURLEncoding.EncodeToString(bytes.Repeat([]byte{4}, 32)) |
| 71 | challenge := sha256.Sum256([]byte(verifier)) |
| 72 | nonce, _ = handoff.NativeNonce(base64.RawURLEncoding.EncodeToString(challenge[:])) |
| 73 | body, _ := json.Marshal(map[string]string{"assertion": sign(nonce), "verifier": verifier}) |
| 74 | r := httptest.NewRequest("POST", nativeOrigin+oficinaid.NativePath, bytes.NewReader(body)) |
| 75 | r.Header.Set("Content-Type", "application/json") |
| 76 | w := httptest.NewRecorder() |
| 77 | f.Handler.ServeHTTP(w, r) |
| 78 | expectNativeHTTP(t, w, 200) |
| 79 | minted := apiValue[oficinaid.NativeSession](t, w) |
| 80 | f.Cookies[owner.Address] = &http.Cookie{Name: minted.Name, Value: minted.Value} |
| 81 | return f, s, fresh, key |
| 82 | } |
| 83 | func nativeDevicePost(f *fixture, body string, edit func(*http.Request)) *httptest.ResponseRecorder { |
| 84 | r := httptest.NewRequest("POST", nativeOrigin+"/api/v1/auth/devices/native", strings.NewReader(body)) |
| 85 | r.Header.Set("Content-Type", "application/json") |
| 86 | r.Header.Set("Origin", nativeOrigin) |
| 87 | r.AddCookie(f.Cookies[owner.Address]) |
| 88 | if edit != nil { |
| 89 | edit(r) |
| 90 | } |
| 91 | w := httptest.NewRecorder() |
| 92 | f.Handler.ServeHTTP(w, r) |
| 93 | return w |
| 94 | } |
| 95 | func nativeDeviceBody() string { |
| 96 | return `{"public_key":"` + base64.RawURLEncoding.EncodeToString(bytes.Repeat([]byte{3}, 32)) + `","label":"private-device-label"}` |
| 97 | } |
| 98 | func TestPersonAPINativeDevice(t *testing.T) { |
| 99 | f, s, fresh, _ := nativeIDFixture(t) |
| 100 | sourceAt := time.Now().UTC().Truncate(time.Second).Add(-2 * 24 * time.Hour) |
| 101 | f.exec(t, "UPDATE sessions SET created_at=?,expires_at=? WHERE token_hash=?", sourceAt.Format(time.RFC3339), sourceAt.Add(7*24*time.Hour).Format(time.RFC3339), sessions.HashToken(f.Cookies[owner.Address].Value)) |
| 102 | w := nativeDevicePost(f, nativeDeviceBody(), nil) |
| 103 | expectNativeHTTP(t, w, 200) |
| 104 | credential := apiValue[personapi.PersonCredential](t, w) |
| 105 | var person, source, created string |
| 106 | must(t, f.DB.Writer().QueryRow("SELECT person,native_session_hash FROM person_devices WHERE id=?", credential.ID).Scan(&person, &source)) |
| 107 | must(t, f.DB.Writer().QueryRow("SELECT created_at FROM sessions WHERE token_hash=?", source).Scan(&created)) |
| 108 | at, e := time.Parse(time.RFC3339, created) |
| 109 | must(t, e) |
| 110 | if person != owner.Address || source != sessions.HashToken(f.Cookies[owner.Address].Value) || !credential.ExpiresAt.Equal(at.Add(7*24*time.Hour)) { |
| 111 | t.Fatal("wrong owner, source, or expiry") |
| 112 | } |
| 113 | if !strings.HasPrefix(credential.Token, personapi.PersonAudience+".") || credential.Audience != personapi.PersonAudience || credential.InstanceID == "" { |
| 114 | t.Fatal("credential contract") |
| 115 | } |
| 116 | var audit string |
| 117 | must(t, f.DB.Writer().QueryRow("SELECT group_concat(actor || kind || record_id) FROM audit_events").Scan(&audit)) |
| 118 | for _, secret := range []string{credential.Token, source, f.Cookies[owner.Address].Value, "private-device-label"} { |
| 119 | if strings.Contains(audit, secret) { |
| 120 | t.Fatal("credential or label in audit") |
| 121 | } |
| 122 | } |
| 123 | if !strings.Contains(audit, "person_device.native") { |
| 124 | t.Fatal("missing native audit") |
| 125 | } |
| 126 | // Unlink uses the existing fresh local ceremony and cascades session deletion. |
| 127 | proof, e := s.BeginReauth(ctx, fresh, "unlink", time.Now()) |
| 128 | must(t, e) |
| 129 | next, hash, e := sessions.NewToken() |
| 130 | must(t, e) |
| 131 | now := time.Now().UTC() |
| 132 | f.exec(t, "INSERT INTO sessions(token_hash,subject,method,auth_time,created_at,expires_at) VALUES(?,?,?,?,?,?)", hash, owner.Address, "magiclink", now.Format(time.RFC3339), now.Format(time.RFC3339), now.Add(time.Hour).Format(time.RFC3339)) |
| 133 | _, _, e = s.CompleteReauth(ctx, proof, next, now) |
| 134 | must(t, e) |
| 135 | must(t, s.Unlink(ctx, proof, next, now)) |
| 136 | if f.count(t, "SELECT count(*) FROM person_devices WHERE id=? AND revoked_at IS NOT NULL", credential.ID) != 1 { |
| 137 | t.Fatal("device survived unlink") |
| 138 | } |
| 139 | if f.count(t, "SELECT count(*) FROM sessions WHERE token_hash=?", source) != 0 { |
| 140 | t.Fatal("session survived unlink") |
| 141 | } |
| 142 | } |
| 143 | func TestPersonAPINativeDeviceGates(t *testing.T) { |
| 144 | f, _, _, _ := nativeIDFixture(t) |
| 145 | for _, gate := range []string{"own-person", "local-session", "web-session", "bearer", "no-origin", "cross-origin", "json", "key", "duplicate-cookie", "unknown-field", "removed", "expired", "revoked"} { |
| 146 | t.Run(gate, func(t *testing.T) { |
| 147 | token := f.Cookies[owner.Address].Value |
| 148 | hash := sessions.HashToken(token) |
| 149 | body := nativeDeviceBody() |
| 150 | want := 401 |
| 151 | switch gate { |
| 152 | case "own-person", "unknown-field": |
| 153 | body = body[:len(body)-1] + `,"person":"peer@example.com"}` |
| 154 | want = 422 |
| 155 | case "json", "key": |
| 156 | want = 422 |
| 157 | case "no-origin", "cross-origin", "local-session": |
| 158 | want = 403 |
| 159 | } |
| 160 | if gate == "key" { |
| 161 | body = `{"public_key":"` + base64.RawURLEncoding.EncodeToString(make([]byte, 31)) + `","label":"phone"}` |
| 162 | } |
| 163 | if gate == "local-session" || gate == "web-session" { |
| 164 | method := "magiclink" |
| 165 | if gate == "web-session" { |
| 166 | method = oficinaid.Method |
| 167 | } |
| 168 | f.exec(t, "UPDATE sessions SET method=? WHERE token_hash=?", method, hash) |
| 169 | defer f.exec(t, "UPDATE sessions SET method=? WHERE token_hash=?", oficinaid.NativeMethod, hash) |
| 170 | } |
| 171 | if gate == "removed" { |
| 172 | f.exec(t, "UPDATE members SET active=0 WHERE address=?", owner.Address) |
| 173 | defer f.exec(t, "UPDATE members SET active=1 WHERE address=?", owner.Address) |
| 174 | } |
| 175 | if gate == "expired" { |
| 176 | f.exec(t, "UPDATE sessions SET created_at=? WHERE token_hash=?", time.Now().Add(-8*24*time.Hour).Format(time.RFC3339), hash) |
| 177 | defer f.exec(t, "UPDATE sessions SET created_at=? WHERE token_hash=?", time.Now().Format(time.RFC3339), hash) |
| 178 | } |
| 179 | if gate == "revoked" { |
| 180 | f.exec(t, "DELETE FROM sessions WHERE token_hash=?", hash) |
| 181 | } |
| 182 | w := nativeDevicePost(f, body, func(r *http.Request) { |
| 183 | switch gate { |
| 184 | case "bearer": |
| 185 | r.Header.Set("Authorization", "Bearer device") |
| 186 | case "no-origin": |
| 187 | r.Header.Del("Origin") |
| 188 | case "cross-origin": |
| 189 | r.Header.Set("Origin", "https://other.example") |
| 190 | case "json": |
| 191 | r.Header.Set("Content-Type", "text/plain") |
| 192 | case "duplicate-cookie": |
| 193 | r.AddCookie(f.Cookies[owner.Address]) |
| 194 | } |
| 195 | }) |
| 196 | expectNativeHTTP(t, w, want) |
| 197 | if f.count(t, "SELECT count(*) FROM person_devices") != 0 { |
| 198 | t.Fatal("refused request allocated a device") |
| 199 | } |
| 200 | }) |
| 201 | } |
| 202 | } |
| 203 | |
| 204 | func TestPersonAPINativeDeviceTransactionGuards(t *testing.T) { |
| 205 | for _, gate := range []string{"actor", "session-person", "session-method", "session-expiry", "roster", "audit"} { |
| 206 | t.Run(gate, func(t *testing.T) { |
| 207 | f := newFixture(t) |
| 208 | now := time.Now().UTC() |
| 209 | p := personapi.PersonPrincipal{Address: owner.Address, SessionHash: "verified-hash", SessionEpoch: now.Unix()} |
| 210 | actor := owner |
| 211 | if gate == "actor" { |
| 212 | actor = peer |
| 213 | } |
| 214 | ds := &personapi.DeviceStore{Key: "fixture-native-device-key", Now: func() time.Time { return now }, Invalid: equipo.ErrInvalid, Forbidden: equipo.ErrForbidden, |
| 215 | Write: func(c context.Context, fn func(*gorm.DB) error) error { |
| 216 | return f.DB.G.WithContext(c).Transaction(func(tx *gorm.DB) error { |
| 217 | if gate == "roster" { |
| 218 | if e := tx.Exec("UPDATE members SET active=0 WHERE address=?", owner.Address).Error; e != nil { |
| 219 | return e |
| 220 | } |
| 221 | } |
| 222 | return fn(tx) |
| 223 | }) |
| 224 | }, |
| 225 | NativeSession: func(tx *gorm.DB, hash string) (sessions.Session, error) { |
| 226 | sess := sessions.Session{Subject: owner.Address, Method: oficinaid.NativeMethod, At: now} |
| 227 | if gate == "session-person" { |
| 228 | sess.Subject = peer.Address |
| 229 | } |
| 230 | if gate == "session-method" { |
| 231 | sess.Method = "magiclink" |
| 232 | } |
| 233 | if gate == "session-expiry" { |
| 234 | sess.At = now.Add(-8 * 24 * time.Hour) |
| 235 | } |
| 236 | return sess, nil |
| 237 | }, |
| 238 | Member: func(tx *gorm.DB, person string) (kernel.Member, error) { |
| 239 | var m kernel.Member |
| 240 | e := tx.Where("address=?", person).Take(&m).Error |
| 241 | return m, e |
| 242 | }, |
| 243 | Instance: func(*gorm.DB) (string, error) { return "instance", nil }, Audit: func(*gorm.DB, kernel.Actor, string, string) error { |
| 244 | if gate == "audit" { |
| 245 | return errors.New("audit unavailable") |
| 246 | } |
| 247 | return nil |
| 248 | }} |
| 249 | _, err := ds.RegisterNative(personapi.WithVerifiedPrincipal(ctx, p), actor, base64.RawURLEncoding.EncodeToString(make([]byte, 32)), "phone") |
| 250 | if err == nil { |
| 251 | t.Fatal("native device guard accepted", gate) |
| 252 | } |
| 253 | if f.count(t, "SELECT count(*) FROM person_devices") != 0 { |
| 254 | t.Fatal("failed transaction retained credential") |
| 255 | } |
| 256 | }) |
| 257 | } |
| 258 | } |
| 259 | func TestPersonAPINativeSessionRevocation(t *testing.T) { |
| 260 | for _, action := range []string{"session", "link", "member", "address"} { |
| 261 | t.Run(action, func(t *testing.T) { |
| 262 | f, _, _, _ := nativeIDFixture(t) |
| 263 | w := nativeDevicePost(f, nativeDeviceBody(), nil) |
| 264 | expectNativeHTTP(t, w, 200) |
| 265 | credential := apiValue[personapi.PersonCredential](t, w) |
| 266 | // Pending pushes and tokens go away in the same transaction. |
| 267 | f.exec(t, "INSERT INTO push_registrations(credential,person,token) VALUES(?,?,?)", credential.ID, owner.Address, "sealed-canary") |
| 268 | f.exec(t, "INSERT INTO push_activities(credential,task_id,person,token) VALUES(?,?,?,?)", credential.ID, "task", owner.Address, "sealed-canary") |
| 269 | f.exec(t, "INSERT INTO push_outbox(id,credential,person,state) VALUES(?,?,?,?)", "native-push", credential.ID, owner.Address, "pending") |
| 270 | switch action { |
| 271 | case "session": |
| 272 | f.exec(t, "DELETE FROM sessions WHERE token_hash=?", sessions.HashToken(f.Cookies[owner.Address].Value)) |
| 273 | case "link": |
| 274 | f.exec(t, "DELETE FROM home_identity_links WHERE subject=?", nativeSubject) |
| 275 | case "member": |
| 276 | f.exec(t, "DELETE FROM members WHERE address=?", owner.Address) |
| 277 | case "address": |
| 278 | f.exec(t, "UPDATE members SET address=? WHERE address=?", "renamed@example.invalid", owner.Address) |
| 279 | } |
| 280 | if f.count(t, "SELECT count(*) FROM person_devices WHERE id=? AND revoked_at IS NOT NULL", credential.ID) != 1 { |
| 281 | t.Fatal("native device remained live", action) |
| 282 | } |
| 283 | for _, table := range []string{"push_registrations", "push_activities"} { |
| 284 | if f.count(t, "SELECT count(*) FROM "+table+" WHERE credential=?", credential.ID) != 0 { |
| 285 | t.Fatal("push secret survived", table) |
| 286 | } |
| 287 | } |
| 288 | if f.count(t, "SELECT count(*) FROM push_outbox WHERE id='native-push' AND state='dropped'") != 1 { |
| 289 | t.Fatal("pending push survived") |
| 290 | } |
| 291 | }) |
| 292 | } |
| 293 | } |
| 294 | |
| 295 | func expectNativeHTTP(t *testing.T, w *httptest.ResponseRecorder, status int) { |
| 296 | t.Helper() |
| 297 | if w.Code != status { |
| 298 | t.Fatalf("native HTTP %d, want %d", w.Code, status) |
| 299 | } |
| 300 | } |
| 301 | |
| 302 | func TestPersonAPINativeLiveExchange(t *testing.T) { |
| 303 | f, s, _, key := nativeIDFixture(t) |
| 304 | // Both listeners bind to loopback. Home is a signing fixture; the instance |
| 305 | // runs the production router and database over a real TLS connection. |
| 306 | fakeHome := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 307 | var in struct { |
| 308 | Aud string `json:"aud"` |
| 309 | Challenge string `json:"challenge"` |
| 310 | } |
| 311 | if json.NewDecoder(r.Body).Decode(&in) != nil || in.Aud != nativeOrigin { |
| 312 | w.WriteHeader(400) |
| 313 | return |
| 314 | } |
| 315 | nonce, ok := handoff.NativeNonce(in.Challenge) |
| 316 | if !ok { |
| 317 | w.WriteHeader(400) |
| 318 | return |
| 319 | } |
| 320 | id, err := assertion.RandomID() |
| 321 | if err != nil { |
| 322 | w.WriteHeader(500) |
| 323 | return |
| 324 | } |
| 325 | now := time.Now().Unix() |
| 326 | signed, err := assertion.Sign(key, assertion.Claims{Version: 1, KeyID: "k", Issuer: s.Config.Issuer, Audience: in.Aud, Subject: nativeSubject, ID: id, Nonce: nonce, IssuedAt: now, ExpiresAt: now + 120, AuthTime: now}) |
| 327 | if err != nil { |
| 328 | w.WriteHeader(500) |
| 329 | return |
| 330 | } |
| 331 | w.Header().Set("Content-Type", "application/json") |
| 332 | _ = json.NewEncoder(w).Encode(map[string]string{"assertion": signed}) |
| 333 | })) |
| 334 | defer fakeHome.Close() |
| 335 | instance := httptest.NewTLSServer(f.Handler) |
| 336 | defer instance.Close() |
| 337 | verifier := base64.RawURLEncoding.EncodeToString(bytes.Repeat([]byte{12}, 32)) |
| 338 | challenge := sha256.Sum256([]byte(verifier)) |
| 339 | input, _ := json.Marshal(map[string]string{"aud": nativeOrigin, "challenge": base64.RawURLEncoding.EncodeToString(challenge[:])}) |
| 340 | response, err := http.Post(fakeHome.URL+"/native/v1/assert", "application/json", bytes.NewReader(input)) |
| 341 | must(t, err) |
| 342 | var asserted struct { |
| 343 | Assertion string `json:"assertion"` |
| 344 | } |
| 345 | must(t, json.NewDecoder(response.Body).Decode(&asserted)) |
| 346 | response.Body.Close() |
| 347 | if response.StatusCode != 200 { |
| 348 | t.Fatal("fake Home status", response.StatusCode) |
| 349 | } |
| 350 | exchange, _ := json.Marshal(oficinaid.NativeRequest{Assertion: asserted.Assertion, Verifier: verifier}) |
| 351 | req, err := http.NewRequest("POST", instance.URL+oficinaid.NativePath, bytes.NewReader(exchange)) |
| 352 | must(t, err) |
| 353 | req.Host = strings.TrimPrefix(nativeOrigin, "https://") |
| 354 | req.Header.Set("Content-Type", "application/json") |
| 355 | response, err = instance.Client().Do(req) |
| 356 | must(t, err) |
| 357 | defer response.Body.Close() |
| 358 | if response.StatusCode != 200 || len(response.Cookies()) != 0 { |
| 359 | t.Fatal("live exchange status or cookie", response.StatusCode) |
| 360 | } |
| 361 | var minted oficinaid.NativeSession |
| 362 | must(t, json.NewDecoder(response.Body).Decode(&minted)) |
| 363 | req, err = http.NewRequest("POST", instance.URL+"/api/v1/auth/devices/native", strings.NewReader(nativeDeviceBody())) |
| 364 | must(t, err) |
| 365 | req.Host = strings.TrimPrefix(nativeOrigin, "https://") |
| 366 | req.Header.Set("Content-Type", "application/json") |
| 367 | req.Header.Set("Origin", nativeOrigin) |
| 368 | req.AddCookie(&http.Cookie{Name: minted.Name, Value: minted.Value}) |
| 369 | response, err = instance.Client().Do(req) |
| 370 | must(t, err) |
| 371 | defer response.Body.Close() |
| 372 | if response.StatusCode != 200 { |
| 373 | t.Fatal("live device status", response.StatusCode) |
| 374 | } |
| 375 | var credential personapi.PersonCredential |
| 376 | must(t, json.NewDecoder(response.Body).Decode(&credential)) |
| 377 | if credential.Token == "" || credential.ExpiresAt.Unix() != minted.ExpiresAt { |
| 378 | t.Fatal("live native credential expiry") |
| 379 | } |
| 380 | req, err = http.NewRequest("GET", instance.URL+"/api/v1/snapshot", nil) |
| 381 | must(t, err) |
| 382 | req.Host = strings.TrimPrefix(nativeOrigin, "https://") |
| 383 | req.Header.Set("Authorization", "Bearer "+credential.Token) |
| 384 | response, err = instance.Client().Do(req) |
| 385 | must(t, err) |
| 386 | defer response.Body.Close() |
| 387 | if response.StatusCode != 200 { |
| 388 | t.Fatal("device engine status", response.StatusCode) |
| 389 | } |
| 390 | } |
| 391 | |
| 392 | // A native session's devices expire with it (7 days). Approving a paired |
| 393 | // device from it would mint a 30-day credential that outlives the session, so |
| 394 | // both approval routes refuse it; the person's web session still approves. |
| 395 | func TestPersonAPINativeSessionNeverApprovesPairing(t *testing.T) { |
| 396 | f, _, fresh, _ := nativeIDFixture(t) |
| 397 | pub := base64.RawURLEncoding.EncodeToString(bytes.Repeat([]byte{5}, 32)) |
| 398 | c, e := f.Store.BeginPersonDevice(ctx, pub, "paired phone", "native-approve-begin") |
| 399 | must(t, e) |
| 400 | native := f.Cookies[owner.Address] |
| 401 | web := &http.Cookie{Name: native.Name, Value: fresh} |
| 402 | approve := func(cookie *http.Cookie, form bool, key string) *httptest.ResponseRecorder { |
| 403 | var r *http.Request |
| 404 | if form { |
| 405 | r = httptest.NewRequest("POST", nativeOrigin+"/auth/devices/"+c.ID+"/approve", strings.NewReader("typed_code="+c.UserCode+"&request_id="+key+"&revision=1")) |
| 406 | r.Header.Set("Content-Type", "application/x-www-form-urlencoded") |
| 407 | } else { |
| 408 | r = httptest.NewRequest("POST", nativeOrigin+"/api/v1/auth/devices/"+c.ID+"/approve", strings.NewReader(`{"typed_code":"`+c.UserCode+`"}`)) |
| 409 | r.Header.Set("Content-Type", "application/json") |
| 410 | r.Header.Set("Idempotency-Key", key) |
| 411 | r.Header.Set("If-Match", `"1"`) |
| 412 | } |
| 413 | r.Header.Set("Origin", nativeOrigin) |
| 414 | r.AddCookie(cookie) |
| 415 | w := httptest.NewRecorder() |
| 416 | f.Handler.ServeHTTP(w, r) |
| 417 | return w |
| 418 | } |
| 419 | expectNativeHTTP(t, approve(native, false, "native-api"), 403) |
| 420 | expectNativeHTTP(t, approve(native, true, "native-form"), 403) |
| 421 | if f.count(t, "SELECT count(*) FROM person_devices WHERE id=? AND approved_at IS NOT NULL", c.ID) != 0 { |
| 422 | t.Fatal("native session approved a paired device") |
| 423 | } |
| 424 | expectNativeHTTP(t, approve(web, false, "web-api"), 200) |
| 425 | } |
| 426 | |