| 1 | package idtest |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "context" |
| 6 | "html" |
| 7 | "log/slog" |
| 8 | "net" |
| 9 | "net/http" |
| 10 | "net/http/httptest" |
| 11 | "net/url" |
| 12 | "os" |
| 13 | "path/filepath" |
| 14 | "regexp" |
| 15 | "strings" |
| 16 | "sync" |
| 17 | "testing" |
| 18 | "time" |
| 19 | |
| 20 | "amadan.net/oficina/equipo/internal/equipo" |
| 21 | "amadan.net/oficina/equipo/internal/equipo/oficinaid" |
| 22 | "amadan.net/oficina/home/connect" |
| 23 | "amadan.net/rastrillo/rastrillo/assertion" |
| 24 | "amadan.net/rastrillo/rastrillo/crypto" |
| 25 | "amadan.net/rastrillo/rastrillo/db" |
| 26 | "amadan.net/rastrillo/rastrillo/pow" |
| 27 | "amadan.net/rastrillo/rastrillo/sessions" |
| 28 | ) |
| 29 | |
| 30 | const appOrigin = "https://equipo.example" |
| 31 | const issuer = "https://id.example" |
| 32 | const person = "pr_aaaaaaaaaaaaaaaaaaaaaaaaaa" |
| 33 | const address = "local-canary@example.invalid" |
| 34 | const homeAddress = "home-private-canary@example.invalid" |
| 35 | |
| 36 | type mailer struct { |
| 37 | mu sync.Mutex |
| 38 | body string |
| 39 | } |
| 40 | |
| 41 | func (m *mailer) Send(_ context.Context, _, _, body string) error { |
| 42 | m.mu.Lock() |
| 43 | defer m.mu.Unlock() |
| 44 | m.body = body |
| 45 | return nil |
| 46 | } |
| 47 | |
| 48 | type fixture struct { |
| 49 | db *db.DB |
| 50 | h http.Handler |
| 51 | k *crypto.Keypair |
| 52 | mail *mailer |
| 53 | logs *bytes.Buffer |
| 54 | path string |
| 55 | origin, issuer string |
| 56 | } |
| 57 | |
| 58 | func newFixture(t *testing.T, enabled bool) *fixture { return fixtureAt(t, enabled, appOrigin, issuer) } |
| 59 | func fixtureAt(t *testing.T, enabled bool, origin, home string) *fixture { |
| 60 | t.Helper() |
| 61 | path := filepath.Join(t.TempDir(), "equipo.db") |
| 62 | logs := new(bytes.Buffer) |
| 63 | logger := slog.New(slog.NewTextHandler(logs, nil)) |
| 64 | d, e := db.Open(path, logger) |
| 65 | if e != nil { |
| 66 | t.Fatal(e) |
| 67 | } |
| 68 | t.Cleanup(func() { d.Close() }) |
| 69 | k, e := crypto.Generate() |
| 70 | if e != nil { |
| 71 | t.Fatal(e) |
| 72 | } |
| 73 | m := new(mailer) |
| 74 | cfg := equipo.Config{Origin: origin, InstanceKey: "id-test-key", Owners: []string{address}} |
| 75 | if enabled { |
| 76 | cfg.Home = &connect.DecodedCredentials{Issuer: home, ConsumerID: "equipo", Keys: map[string][]byte{"k": k.SignPub()}, DEK: bytes.Repeat([]byte{7}, 32)} |
| 77 | } |
| 78 | h, e := equipo.App(d, cfg, m, logger) |
| 79 | if e != nil { |
| 80 | t.Fatal(e) |
| 81 | } |
| 82 | return &fixture{d, h, k, m, logs, path, origin, home} |
| 83 | } |
| 84 | func (f *fixture) request(method, path, origin string, form url.Values, cookies ...*http.Cookie) *httptest.ResponseRecorder { |
| 85 | req := httptest.NewRequest(method, f.origin+path, strings.NewReader(form.Encode())) |
| 86 | if method == "POST" { |
| 87 | req.Header.Set("Content-Type", "application/x-www-form-urlencoded") |
| 88 | } |
| 89 | if origin != "" { |
| 90 | req.Header.Set("Origin", origin) |
| 91 | } |
| 92 | for _, c := range cookies { |
| 93 | if c != nil { |
| 94 | req.AddCookie(c) |
| 95 | } |
| 96 | } |
| 97 | out := httptest.NewRecorder() |
| 98 | f.h.ServeHTTP(out, req) |
| 99 | return out |
| 100 | } |
| 101 | func cookie(t *testing.T, w *httptest.ResponseRecorder, name string) *http.Cookie { |
| 102 | t.Helper() |
| 103 | for _, c := range w.Result().Cookies() { |
| 104 | if c.Name == name && c.Value != "" && c.MaxAge >= 0 { |
| 105 | return c |
| 106 | } |
| 107 | } |
| 108 | t.Fatalf("no cookie %s, status %d body %.200s", name, w.Code, w.Body.String()) |
| 109 | return nil |
| 110 | } |
| 111 | func (f *fixture) local(t *testing.T, who string) *http.Cookie { |
| 112 | t.Helper() |
| 113 | now := time.Now().UTC() |
| 114 | token, hash, e := sessions.NewToken() |
| 115 | if e != nil { |
| 116 | t.Fatal(e) |
| 117 | } |
| 118 | if _, e = f.db.Writer().Exec("INSERT INTO sessions(token_hash,subject,method,auth_time,created_at,expires_at) VALUES(?,?,?,?,?,?)", hash, who, "magiclink", "", now.Format(time.RFC3339), now.Add(time.Hour).Format(time.RFC3339)); e != nil { |
| 119 | t.Fatal(e) |
| 120 | } |
| 121 | return &http.Cookie{Name: "__Host-rastrillo_session", Value: token, Path: "/", Secure: true, HttpOnly: true, SameSite: http.SameSiteLaxMode} |
| 122 | } |
| 123 | func (f *fixture) signed(t *testing.T, nonce, subject string, at time.Time) string { |
| 124 | t.Helper() |
| 125 | now := time.Now() |
| 126 | jti, _ := assertion.RandomID() |
| 127 | token, e := assertion.Sign(f.k, assertion.Claims{Version: 1, KeyID: "k", Issuer: f.issuer, Audience: f.origin, Subject: subject, ID: jti, Nonce: nonce, IssuedAt: now.Unix(), ExpiresAt: now.Unix() + 120, AuthTime: at.Unix()}) |
| 128 | if e != nil { |
| 129 | t.Fatal(e) |
| 130 | } |
| 131 | return token |
| 132 | } |
| 133 | func (f *fixture) exchange(t *testing.T, init, local *http.Cookie, subject string) (*httptest.ResponseRecorder, []*http.Cookie) { |
| 134 | t.Helper() |
| 135 | start := f.request("GET", "/auth/home?return_to=%2Fwork", "", nil, init, local) |
| 136 | if start.Code != 303 { |
| 137 | t.Fatalf("start %d %s", start.Code, start.Body.String()) |
| 138 | } |
| 139 | u, e := url.Parse(start.Header().Get("Location")) |
| 140 | if e != nil { |
| 141 | t.Fatal(e) |
| 142 | } |
| 143 | q := u.Query() |
| 144 | if q.Get("consumer") != "equipo" || len(q) != 2+btoi(init != nil) { |
| 145 | t.Fatal("authorize query", q) |
| 146 | } |
| 147 | if init != nil && q.Get("max_age") != "300" { |
| 148 | t.Fatal("link omitted fresh prompt") |
| 149 | } |
| 150 | receipt := f.request("POST", "/auth/assertion", f.issuer, url.Values{"assertion": {f.signed(t, q.Get("nonce"), subject, time.Now())}}) |
| 151 | if receipt.Code != 303 { |
| 152 | t.Fatalf("callback %d %s", receipt.Code, receipt.Body.String()) |
| 153 | } |
| 154 | cookies := []*http.Cookie{cookie(t, start, "__Host-equipo-id-pending"), cookie(t, receipt, "__Host-equipo-id-inbox"), init, local} |
| 155 | done := f.request("GET", "/auth/finish", "", nil, cookies...) |
| 156 | return done, cookies |
| 157 | } |
| 158 | func btoi(b bool) int { |
| 159 | if b { |
| 160 | return 1 |
| 161 | } |
| 162 | return 0 |
| 163 | } |
| 164 | func (f *fixture) link(t *testing.T) *http.Cookie { |
| 165 | t.Helper() |
| 166 | old := f.local(t, address) |
| 167 | start := f.request("POST", "/account/home/reauth", f.origin, url.Values{"purpose": {"link"}}, old) |
| 168 | if start.Code != 303 { |
| 169 | t.Fatalf("reauth begin %d %s", start.Code, start.Body.String()) |
| 170 | } |
| 171 | fresh := f.local(t, address) |
| 172 | end := f.request("GET", "/account/home/reauth-complete", "", nil, fresh, cookie(t, start, "__Host-equipo-id-reauth")) |
| 173 | if end.Code != 303 { |
| 174 | t.Fatalf("reauth end %d %s", end.Code, end.Body.String()) |
| 175 | } |
| 176 | done, _ := f.exchange(t, cookie(t, end, "__Host-equipo-id-init"), fresh, person) |
| 177 | if done.Code != 303 { |
| 178 | t.Fatalf("link finish %d %s", done.Code, done.Body.String()) |
| 179 | } |
| 180 | proof := cookie(t, done, "__Host-equipo-id-proof") |
| 181 | page := f.request("GET", "/account/home/confirm", "", nil, fresh, proof) |
| 182 | if page.Code != 200 { |
| 183 | t.Fatalf("confirm page %d %.200s", page.Code, page.Body.String()) |
| 184 | } |
| 185 | confirm := f.request("POST", "/account/home/confirm", f.origin, nil, fresh, proof) |
| 186 | if confirm.Code != 303 { |
| 187 | t.Fatalf("confirm %d %s", confirm.Code, confirm.Body.String()) |
| 188 | } |
| 189 | return fresh |
| 190 | } |
| 191 | func TestIDDoorOffAndUnlinked(t *testing.T) { |
| 192 | off := newFixture(t, false) |
| 193 | if body := off.request("GET", "/signin", "", nil).Body.String(); strings.Contains(body, "Oficina ID") || strings.Contains(body, "/signin/oficina") { |
| 194 | t.Fatal("door enabled without config") |
| 195 | } |
| 196 | f := newFixture(t, true) |
| 197 | if body := f.request("GET", "/signin", "", nil).Body.String(); !strings.Contains(body, "Continue with Oficina ID") || !strings.Contains(body, `href="/signin/oficina"`) { |
| 198 | t.Fatal("missing door", body) |
| 199 | } |
| 200 | done, _ := f.exchange(t, nil, nil, person) |
| 201 | if done.Code != 403 || !strings.Contains(done.Body.String(), "No Equipo account is linked to this Oficina ID.") || !strings.Contains(done.Body.String(), "Sign in by email") { |
| 202 | t.Fatal("unlinked path", done.Code, done.Body.String()) |
| 203 | } |
| 204 | var n int |
| 205 | if e := f.db.Writer().QueryRow("SELECT count(*) FROM members").Scan(&n); e != nil || n != 1 { |
| 206 | t.Fatal("created account", n, e) |
| 207 | } |
| 208 | } |
| 209 | func TestIDFullLinkSigninUnlink(t *testing.T) { |
| 210 | f := newFixture(t, true) |
| 211 | local := f.link(t) |
| 212 | settings := f.request("GET", "/conversation/settings/oficina-id", "", nil, local) |
| 213 | if settings.Code != 200 || !strings.Contains(settings.Body.String(), person) || !strings.Contains(settings.Body.String(), "Linked on") { |
| 214 | t.Fatal("linked settings", settings.Code, settings.Body.String()) |
| 215 | } |
| 216 | done, _ := f.exchange(t, nil, nil, person) |
| 217 | if done.Code != 303 { |
| 218 | t.Fatal("signin", done.Code, done.Body.String()) |
| 219 | } |
| 220 | home := cookie(t, done, "__Host-rastrillo_session") |
| 221 | if r := f.request("GET", "/work", "", nil, home); r.Code != 200 { |
| 222 | t.Fatal("home session admission", r.Code) |
| 223 | } |
| 224 | start := f.request("POST", "/account/home/reauth", f.origin, url.Values{"purpose": {"unlink"}}, home) |
| 225 | reauth := cookie(t, start, "__Host-equipo-id-reauth") |
| 226 | fresh := f.local(t, address) |
| 227 | if r := f.request("GET", "/account/home/reauth-complete", "", nil, fresh, reauth); r.Code != 303 { |
| 228 | t.Fatal("unlink reauth", r.Code) |
| 229 | } |
| 230 | if r := f.request("POST", "/account/home/unlink", f.origin, nil, fresh, reauth); r.Code != 303 { |
| 231 | t.Fatal("unlink", r.Code, r.Body.String()) |
| 232 | } |
| 233 | if r := f.request("GET", "/work", "", nil, home); r.Code == 200 { |
| 234 | t.Fatal("Home session survived unlink") |
| 235 | } |
| 236 | if r := f.request("GET", "/work", "", nil, local); r.Code != 200 { |
| 237 | t.Fatal("local session lost", r.Code) |
| 238 | } |
| 239 | if r, _ := f.exchange(t, nil, nil, person); r.Code != 403 { |
| 240 | t.Fatal("unlinked subject signed in") |
| 241 | } |
| 242 | } |
| 243 | func TestIDLeakage(t *testing.T) { |
| 244 | f := newFixture(t, true) |
| 245 | f.link(t) |
| 246 | done, _ := f.exchange(t, nil, nil, person) |
| 247 | if done.Code != 303 { |
| 248 | t.Fatal(done.Code) |
| 249 | } |
| 250 | for _, table := range []string{"equipo_id_accounts", "equipo_id_reauth", "home_identity_links", "home_link_flows", "oficina_handoff_pending", "oficina_handoff_inbox", "audit_events"} { |
| 251 | rows, e := f.db.Writer().Query("SELECT * FROM " + table) |
| 252 | if e != nil { |
| 253 | t.Fatal(e) |
| 254 | } |
| 255 | cols, _ := rows.Columns() |
| 256 | for rows.Next() { |
| 257 | v := make([]any, len(cols)) |
| 258 | ptr := make([]any, len(v)) |
| 259 | for i := range v { |
| 260 | ptr[i] = &v[i] |
| 261 | } |
| 262 | if e = rows.Scan(ptr...); e != nil { |
| 263 | t.Fatal(e) |
| 264 | } |
| 265 | for _, value := range v { |
| 266 | var raw []byte |
| 267 | switch value := value.(type) { |
| 268 | case []byte: |
| 269 | raw = value |
| 270 | case string: |
| 271 | raw = []byte(value) |
| 272 | } |
| 273 | if bytes.Contains(raw, []byte(address)) || bytes.Contains(raw, []byte(homeAddress)) { |
| 274 | t.Fatal("address in identity storage", table) |
| 275 | } |
| 276 | } |
| 277 | } |
| 278 | rows.Close() |
| 279 | } |
| 280 | var n int |
| 281 | if e := f.db.Writer().QueryRow("SELECT count(*) FROM sessions WHERE method=? AND subject LIKE '%@%'", oficinaid.Method).Scan(&n); e != nil || n != 0 { |
| 282 | t.Fatal("address in Home session") |
| 283 | } |
| 284 | for _, suffix := range []string{"", "-wal", "-shm"} { |
| 285 | raw, e := os.ReadFile(f.path + suffix) |
| 286 | if e != nil && !os.IsNotExist(e) { |
| 287 | t.Fatal(e) |
| 288 | } |
| 289 | if bytes.Contains(raw, []byte(homeAddress)) { |
| 290 | t.Fatal("Home address at rest") |
| 291 | } |
| 292 | } |
| 293 | if strings.Contains(f.logs.String(), address) || strings.Contains(f.logs.String(), homeAddress) { |
| 294 | t.Fatal("address in logs") |
| 295 | } |
| 296 | } |
| 297 | func fields(body, action string) url.Values { |
| 298 | v := url.Values{} |
| 299 | for _, form := range regexp.MustCompile(`(?s)<form\b[^>]*>.*?</form>`).FindAllString(body, -1) { |
| 300 | if !strings.Contains(form, `action="`+action+`"`) { |
| 301 | continue |
| 302 | } |
| 303 | for _, in := range regexp.MustCompile(`<input\b[^>]*>`).FindAllString(form, -1) { |
| 304 | attrs := map[string]string{} |
| 305 | for _, m := range regexp.MustCompile(`([a-z_-]+)="([^"]*)"`).FindAllStringSubmatch(in, -1) { |
| 306 | attrs[m[1]] = html.UnescapeString(m[2]) |
| 307 | } |
| 308 | if attrs["name"] != "" { |
| 309 | v.Set(attrs["name"], attrs["value"]) |
| 310 | } |
| 311 | } |
| 312 | } |
| 313 | return v |
| 314 | } |
| 315 | func (f *fixture) email(t *testing.T) { f.emailWith(t, "/signin?force=1", nil) } |
| 316 | func (f *fixture) emailWith(t *testing.T, start string, original ...*http.Cookie) *http.Cookie { |
| 317 | t.Helper() |
| 318 | page := f.request("GET", start, "", nil, original...) |
| 319 | form := fields(page.Body.String(), "/auth/begin") |
| 320 | form.Set("address", address) |
| 321 | time.Sleep(pow.DefaultMinAge + 20*time.Millisecond) |
| 322 | begin := f.request("POST", "/auth/begin", f.origin, form, original...) |
| 323 | if begin.Code != 303 { |
| 324 | t.Fatal("email begin", begin.Code, begin.Body.String()) |
| 325 | } |
| 326 | f.mail.mu.Lock() |
| 327 | body := f.mail.body |
| 328 | f.mail.mu.Unlock() |
| 329 | var target string |
| 330 | for _, word := range strings.Fields(body) { |
| 331 | if strings.Contains(word, "/auth/verify?") { |
| 332 | u, e := url.Parse(word) |
| 333 | if e != nil { |
| 334 | t.Fatal(e) |
| 335 | } |
| 336 | target = u.RequestURI() |
| 337 | break |
| 338 | } |
| 339 | } |
| 340 | if target == "" { |
| 341 | t.Fatal("no emailed link") |
| 342 | } |
| 343 | jar := mergeCookies(original, page.Result().Cookies(), begin.Result().Cookies()) |
| 344 | confirm := f.request("GET", target, "", nil, jar...) |
| 345 | if confirm.Code != 200 { |
| 346 | t.Fatal("email confirmation", confirm.Code) |
| 347 | } |
| 348 | values := fields(confirm.Body.String(), "/auth/verify") |
| 349 | done := f.request("POST", "/auth/verify", f.origin, values, mergeCookies(jar, confirm.Result().Cookies())...) |
| 350 | if done.Code != 303 { |
| 351 | t.Fatal("email verify", done.Code, done.Body.String()) |
| 352 | } |
| 353 | startURL, _ := url.Parse(start) |
| 354 | if back := startURL.Query().Get("return_to"); back != "" && done.Header().Get("Location") != back { |
| 355 | t.Fatal("email lost return target", done.Header().Get("Location")) |
| 356 | } |
| 357 | local := cookie(t, done, "__Host-rastrillo_session") |
| 358 | if r := f.request("GET", "/work", "", nil, local); r.Code != 200 { |
| 359 | t.Fatal("local admission", r.Code) |
| 360 | } |
| 361 | return local |
| 362 | } |
| 363 | func TestIDHangingHomeLocalSignoutAndEmail(t *testing.T) { |
| 364 | entered := make(chan struct{}, 1) |
| 365 | stop := make(chan struct{}) |
| 366 | home := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { entered <- struct{}{}; <-stop })) |
| 367 | defer home.Close() |
| 368 | defer close(stop) |
| 369 | // Establish a real connection which remains unanswered during local operations. |
| 370 | go func() { |
| 371 | resp, e := home.Client().Get(home.URL) |
| 372 | if e == nil { |
| 373 | resp.Body.Close() |
| 374 | } |
| 375 | }() |
| 376 | <-entered |
| 377 | u, _ := url.Parse(home.URL) |
| 378 | _, port, _ := net.SplitHostPort(u.Host) |
| 379 | transport := home.Client().Transport.(*http.Transport).Clone() |
| 380 | transport.TLSClientConfig = transport.TLSClientConfig.Clone() |
| 381 | transport.TLSClientConfig.InsecureSkipVerify = true // The test issuer is served only on loopback. |
| 382 | transport.DialContext = func(ctx context.Context, network, _ string) (net.Conn, error) { |
| 383 | return (&net.Dialer{}).DialContext(ctx, network, u.Host) |
| 384 | } |
| 385 | previous := http.DefaultClient |
| 386 | http.DefaultClient = &http.Client{Transport: transport, Timeout: 2 * time.Second} |
| 387 | defer func() { http.DefaultClient = previous; transport.CloseIdleConnections() }() |
| 388 | f := fixtureAt(t, true, appOrigin, "https://id.example:"+port) |
| 389 | f.link(t) |
| 390 | done, _ := f.exchange(t, nil, nil, person) |
| 391 | session := cookie(t, done, "__Host-rastrillo_session") |
| 392 | before := time.Now() |
| 393 | out := f.request("POST", "/signout", f.origin, nil, session) |
| 394 | if out.Code != 303 || out.Header().Get("Location") != "/signed-out" || time.Since(before) > time.Second { |
| 395 | t.Fatal("signout waited for Home") |
| 396 | } |
| 397 | landing := f.request("GET", "/signed-out", "", nil, cookie(t, out, "__Host-equipo-id-logout")) |
| 398 | if landing.Code != 200 || !strings.Contains(landing.Body.String(), "Sign out of Oficina ID too") { |
| 399 | t.Fatal("local landing", landing.Code) |
| 400 | } |
| 401 | if r := f.request("GET", "/work", "", nil, session); r.Code == 200 { |
| 402 | t.Fatal("session not revoked") |
| 403 | } |
| 404 | f.email(t) |
| 405 | localForUnlink := f.local(t, address) |
| 406 | reauth := f.request("POST", "/account/home/reauth", f.origin, url.Values{"purpose": {"unlink"}}, localForUnlink) |
| 407 | fresh := f.local(t, address) |
| 408 | proof := cookie(t, reauth, "__Host-equipo-id-reauth") |
| 409 | if r := f.request("GET", "/account/home/reauth-complete", "", nil, fresh, proof); r.Code != 303 { |
| 410 | t.Fatal("outage reauth", r.Code) |
| 411 | } |
| 412 | before = time.Now() |
| 413 | if r := f.request("POST", "/account/home/unlink", f.origin, nil, fresh, proof); r.Code != 303 || time.Since(before) > time.Second { |
| 414 | t.Fatal("unlink depends on Home", r.Code) |
| 415 | } |
| 416 | local := f.local(t, address) |
| 417 | out = f.request("POST", "/signout", f.origin, nil, local) |
| 418 | landing = f.request("GET", "/signed-out", "", nil, out.Result().Cookies()...) |
| 419 | if strings.Contains(landing.Body.String(), "Sign out of Oficina ID too") { |
| 420 | t.Fatal("local session offered Home hop") |
| 421 | } |
| 422 | } |
| 423 | |
| 424 | func mergeCookies(groups ...[]*http.Cookie) []*http.Cookie { |
| 425 | jar := map[string]*http.Cookie{} |
| 426 | for _, group := range groups { |
| 427 | for _, c := range group { |
| 428 | if c == nil { |
| 429 | continue |
| 430 | } |
| 431 | if c.MaxAge < 0 { |
| 432 | delete(jar, c.Name) |
| 433 | } else { |
| 434 | jar[c.Name] = c |
| 435 | } |
| 436 | } |
| 437 | } |
| 438 | var out []*http.Cookie |
| 439 | for _, c := range jar { |
| 440 | out = append(out, c) |
| 441 | } |
| 442 | return out |
| 443 | } |
| 444 | |