package idtest import ( "bytes" "context" "html" "log/slog" "net" "net/http" "net/http/httptest" "net/url" "os" "path/filepath" "regexp" "strings" "sync" "testing" "time" "amadan.net/oficina/equipo/internal/equipo" "amadan.net/oficina/equipo/internal/equipo/oficinaid" "amadan.net/oficina/home/connect" "amadan.net/rastrillo/rastrillo/assertion" "amadan.net/rastrillo/rastrillo/crypto" "amadan.net/rastrillo/rastrillo/db" "amadan.net/rastrillo/rastrillo/pow" "amadan.net/rastrillo/rastrillo/sessions" ) const appOrigin = "https://equipo.example" const issuer = "https://id.example" const person = "pr_aaaaaaaaaaaaaaaaaaaaaaaaaa" const address = "local-canary@example.invalid" const homeAddress = "home-private-canary@example.invalid" type mailer struct { mu sync.Mutex body string } func (m *mailer) Send(_ context.Context, _, _, body string) error { m.mu.Lock() defer m.mu.Unlock() m.body = body return nil } type fixture struct { db *db.DB h http.Handler k *crypto.Keypair mail *mailer logs *bytes.Buffer path string origin, issuer string } func newFixture(t *testing.T, enabled bool) *fixture { return fixtureAt(t, enabled, appOrigin, issuer) } func fixtureAt(t *testing.T, enabled bool, origin, home string) *fixture { t.Helper() path := filepath.Join(t.TempDir(), "equipo.db") logs := new(bytes.Buffer) logger := slog.New(slog.NewTextHandler(logs, nil)) d, e := db.Open(path, logger) if e != nil { t.Fatal(e) } t.Cleanup(func() { d.Close() }) k, e := crypto.Generate() if e != nil { t.Fatal(e) } m := new(mailer) cfg := equipo.Config{Origin: origin, InstanceKey: "id-test-key", Owners: []string{address}} if enabled { cfg.Home = &connect.DecodedCredentials{Issuer: home, ConsumerID: "equipo", Keys: map[string][]byte{"k": k.SignPub()}, DEK: bytes.Repeat([]byte{7}, 32)} } h, e := equipo.App(d, cfg, m, logger) if e != nil { t.Fatal(e) } return &fixture{d, h, k, m, logs, path, origin, home} } func (f *fixture) request(method, path, origin string, form url.Values, cookies ...*http.Cookie) *httptest.ResponseRecorder { req := httptest.NewRequest(method, f.origin+path, strings.NewReader(form.Encode())) if method == "POST" { req.Header.Set("Content-Type", "application/x-www-form-urlencoded") } if origin != "" { req.Header.Set("Origin", origin) } for _, c := range cookies { if c != nil { req.AddCookie(c) } } out := httptest.NewRecorder() f.h.ServeHTTP(out, req) return out } func cookie(t *testing.T, w *httptest.ResponseRecorder, name string) *http.Cookie { t.Helper() for _, c := range w.Result().Cookies() { if c.Name == name && c.Value != "" && c.MaxAge >= 0 { return c } } t.Fatalf("no cookie %s, status %d body %.200s", name, w.Code, w.Body.String()) return nil } func (f *fixture) local(t *testing.T, who string) *http.Cookie { t.Helper() now := time.Now().UTC() token, hash, e := sessions.NewToken() if e != nil { t.Fatal(e) } 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 { t.Fatal(e) } return &http.Cookie{Name: "__Host-rastrillo_session", Value: token, Path: "/", Secure: true, HttpOnly: true, SameSite: http.SameSiteLaxMode} } func (f *fixture) signed(t *testing.T, nonce, subject string, at time.Time) string { t.Helper() now := time.Now() jti, _ := assertion.RandomID() 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()}) if e != nil { t.Fatal(e) } return token } func (f *fixture) exchange(t *testing.T, init, local *http.Cookie, subject string) (*httptest.ResponseRecorder, []*http.Cookie) { t.Helper() start := f.request("GET", "/auth/home?return_to=%2Fwork", "", nil, init, local) if start.Code != 303 { t.Fatalf("start %d %s", start.Code, start.Body.String()) } u, e := url.Parse(start.Header().Get("Location")) if e != nil { t.Fatal(e) } q := u.Query() if q.Get("consumer") != "equipo" || len(q) != 2+btoi(init != nil) { t.Fatal("authorize query", q) } if init != nil && q.Get("max_age") != "300" { t.Fatal("link omitted fresh prompt") } receipt := f.request("POST", "/auth/assertion", f.issuer, url.Values{"assertion": {f.signed(t, q.Get("nonce"), subject, time.Now())}}) if receipt.Code != 303 { t.Fatalf("callback %d %s", receipt.Code, receipt.Body.String()) } cookies := []*http.Cookie{cookie(t, start, "__Host-equipo-id-pending"), cookie(t, receipt, "__Host-equipo-id-inbox"), init, local} done := f.request("GET", "/auth/finish", "", nil, cookies...) return done, cookies } func btoi(b bool) int { if b { return 1 } return 0 } func (f *fixture) link(t *testing.T) *http.Cookie { t.Helper() old := f.local(t, address) start := f.request("POST", "/account/home/reauth", f.origin, url.Values{"purpose": {"link"}}, old) if start.Code != 303 { t.Fatalf("reauth begin %d %s", start.Code, start.Body.String()) } fresh := f.local(t, address) end := f.request("GET", "/account/home/reauth-complete", "", nil, fresh, cookie(t, start, "__Host-equipo-id-reauth")) if end.Code != 303 { t.Fatalf("reauth end %d %s", end.Code, end.Body.String()) } done, _ := f.exchange(t, cookie(t, end, "__Host-equipo-id-init"), fresh, person) if done.Code != 303 { t.Fatalf("link finish %d %s", done.Code, done.Body.String()) } proof := cookie(t, done, "__Host-equipo-id-proof") page := f.request("GET", "/account/home/confirm", "", nil, fresh, proof) if page.Code != 200 { t.Fatalf("confirm page %d %.200s", page.Code, page.Body.String()) } confirm := f.request("POST", "/account/home/confirm", f.origin, nil, fresh, proof) if confirm.Code != 303 { t.Fatalf("confirm %d %s", confirm.Code, confirm.Body.String()) } return fresh } func TestIDDoorOffAndUnlinked(t *testing.T) { off := newFixture(t, false) if body := off.request("GET", "/signin", "", nil).Body.String(); strings.Contains(body, "Oficina ID") || strings.Contains(body, "/signin/oficina") { t.Fatal("door enabled without config") } f := newFixture(t, true) if body := f.request("GET", "/signin", "", nil).Body.String(); !strings.Contains(body, "Continue with Oficina ID") || !strings.Contains(body, `href="/signin/oficina"`) { t.Fatal("missing door", body) } done, _ := f.exchange(t, nil, nil, person) 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") { t.Fatal("unlinked path", done.Code, done.Body.String()) } var n int if e := f.db.Writer().QueryRow("SELECT count(*) FROM members").Scan(&n); e != nil || n != 1 { t.Fatal("created account", n, e) } } func TestIDFullLinkSigninUnlink(t *testing.T) { f := newFixture(t, true) local := f.link(t) settings := f.request("GET", "/conversation/settings/oficina-id", "", nil, local) if settings.Code != 200 || !strings.Contains(settings.Body.String(), person) || !strings.Contains(settings.Body.String(), "Linked on") { t.Fatal("linked settings", settings.Code, settings.Body.String()) } done, _ := f.exchange(t, nil, nil, person) if done.Code != 303 { t.Fatal("signin", done.Code, done.Body.String()) } home := cookie(t, done, "__Host-rastrillo_session") if r := f.request("GET", "/work", "", nil, home); r.Code != 200 { t.Fatal("home session admission", r.Code) } start := f.request("POST", "/account/home/reauth", f.origin, url.Values{"purpose": {"unlink"}}, home) reauth := cookie(t, start, "__Host-equipo-id-reauth") fresh := f.local(t, address) if r := f.request("GET", "/account/home/reauth-complete", "", nil, fresh, reauth); r.Code != 303 { t.Fatal("unlink reauth", r.Code) } if r := f.request("POST", "/account/home/unlink", f.origin, nil, fresh, reauth); r.Code != 303 { t.Fatal("unlink", r.Code, r.Body.String()) } if r := f.request("GET", "/work", "", nil, home); r.Code == 200 { t.Fatal("Home session survived unlink") } if r := f.request("GET", "/work", "", nil, local); r.Code != 200 { t.Fatal("local session lost", r.Code) } if r, _ := f.exchange(t, nil, nil, person); r.Code != 403 { t.Fatal("unlinked subject signed in") } } func TestIDLeakage(t *testing.T) { f := newFixture(t, true) f.link(t) done, _ := f.exchange(t, nil, nil, person) if done.Code != 303 { t.Fatal(done.Code) } for _, table := range []string{"equipo_id_accounts", "equipo_id_reauth", "home_identity_links", "home_link_flows", "oficina_handoff_pending", "oficina_handoff_inbox", "audit_events"} { rows, e := f.db.Writer().Query("SELECT * FROM " + table) if e != nil { t.Fatal(e) } cols, _ := rows.Columns() for rows.Next() { v := make([]any, len(cols)) ptr := make([]any, len(v)) for i := range v { ptr[i] = &v[i] } if e = rows.Scan(ptr...); e != nil { t.Fatal(e) } for _, value := range v { var raw []byte switch value := value.(type) { case []byte: raw = value case string: raw = []byte(value) } if bytes.Contains(raw, []byte(address)) || bytes.Contains(raw, []byte(homeAddress)) { t.Fatal("address in identity storage", table) } } } rows.Close() } var n int if e := f.db.Writer().QueryRow("SELECT count(*) FROM sessions WHERE method=? AND subject LIKE '%@%'", oficinaid.Method).Scan(&n); e != nil || n != 0 { t.Fatal("address in Home session") } for _, suffix := range []string{"", "-wal", "-shm"} { raw, e := os.ReadFile(f.path + suffix) if e != nil && !os.IsNotExist(e) { t.Fatal(e) } if bytes.Contains(raw, []byte(homeAddress)) { t.Fatal("Home address at rest") } } if strings.Contains(f.logs.String(), address) || strings.Contains(f.logs.String(), homeAddress) { t.Fatal("address in logs") } } func fields(body, action string) url.Values { v := url.Values{} for _, form := range regexp.MustCompile(`(?s)
`).FindAllString(body, -1) { if !strings.Contains(form, `action="`+action+`"`) { continue } for _, in := range regexp.MustCompile(`]*>`).FindAllString(form, -1) { attrs := map[string]string{} for _, m := range regexp.MustCompile(`([a-z_-]+)="([^"]*)"`).FindAllStringSubmatch(in, -1) { attrs[m[1]] = html.UnescapeString(m[2]) } if attrs["name"] != "" { v.Set(attrs["name"], attrs["value"]) } } } return v } func (f *fixture) email(t *testing.T) { f.emailWith(t, "/signin?force=1", nil) } func (f *fixture) emailWith(t *testing.T, start string, original ...*http.Cookie) *http.Cookie { t.Helper() page := f.request("GET", start, "", nil, original...) form := fields(page.Body.String(), "/auth/begin") form.Set("address", address) time.Sleep(pow.DefaultMinAge + 20*time.Millisecond) begin := f.request("POST", "/auth/begin", f.origin, form, original...) if begin.Code != 303 { t.Fatal("email begin", begin.Code, begin.Body.String()) } f.mail.mu.Lock() body := f.mail.body f.mail.mu.Unlock() var target string for _, word := range strings.Fields(body) { if strings.Contains(word, "/auth/verify?") { u, e := url.Parse(word) if e != nil { t.Fatal(e) } target = u.RequestURI() break } } if target == "" { t.Fatal("no emailed link") } jar := mergeCookies(original, page.Result().Cookies(), begin.Result().Cookies()) confirm := f.request("GET", target, "", nil, jar...) if confirm.Code != 200 { t.Fatal("email confirmation", confirm.Code) } values := fields(confirm.Body.String(), "/auth/verify") done := f.request("POST", "/auth/verify", f.origin, values, mergeCookies(jar, confirm.Result().Cookies())...) if done.Code != 303 { t.Fatal("email verify", done.Code, done.Body.String()) } startURL, _ := url.Parse(start) if back := startURL.Query().Get("return_to"); back != "" && done.Header().Get("Location") != back { t.Fatal("email lost return target", done.Header().Get("Location")) } local := cookie(t, done, "__Host-rastrillo_session") if r := f.request("GET", "/work", "", nil, local); r.Code != 200 { t.Fatal("local admission", r.Code) } return local } func TestIDHangingHomeLocalSignoutAndEmail(t *testing.T) { entered := make(chan struct{}, 1) stop := make(chan struct{}) home := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { entered <- struct{}{}; <-stop })) defer home.Close() defer close(stop) // Establish a real connection which remains unanswered during local operations. go func() { resp, e := home.Client().Get(home.URL) if e == nil { resp.Body.Close() } }() <-entered u, _ := url.Parse(home.URL) _, port, _ := net.SplitHostPort(u.Host) transport := home.Client().Transport.(*http.Transport).Clone() transport.TLSClientConfig = transport.TLSClientConfig.Clone() transport.TLSClientConfig.InsecureSkipVerify = true // The test issuer is served only on loopback. transport.DialContext = func(ctx context.Context, network, _ string) (net.Conn, error) { return (&net.Dialer{}).DialContext(ctx, network, u.Host) } previous := http.DefaultClient http.DefaultClient = &http.Client{Transport: transport, Timeout: 2 * time.Second} defer func() { http.DefaultClient = previous; transport.CloseIdleConnections() }() f := fixtureAt(t, true, appOrigin, "https://id.example:"+port) f.link(t) done, _ := f.exchange(t, nil, nil, person) session := cookie(t, done, "__Host-rastrillo_session") before := time.Now() out := f.request("POST", "/signout", f.origin, nil, session) if out.Code != 303 || out.Header().Get("Location") != "/signed-out" || time.Since(before) > time.Second { t.Fatal("signout waited for Home") } landing := f.request("GET", "/signed-out", "", nil, cookie(t, out, "__Host-equipo-id-logout")) if landing.Code != 200 || !strings.Contains(landing.Body.String(), "Sign out of Oficina ID too") { t.Fatal("local landing", landing.Code) } if r := f.request("GET", "/work", "", nil, session); r.Code == 200 { t.Fatal("session not revoked") } f.email(t) localForUnlink := f.local(t, address) reauth := f.request("POST", "/account/home/reauth", f.origin, url.Values{"purpose": {"unlink"}}, localForUnlink) fresh := f.local(t, address) proof := cookie(t, reauth, "__Host-equipo-id-reauth") if r := f.request("GET", "/account/home/reauth-complete", "", nil, fresh, proof); r.Code != 303 { t.Fatal("outage reauth", r.Code) } before = time.Now() if r := f.request("POST", "/account/home/unlink", f.origin, nil, fresh, proof); r.Code != 303 || time.Since(before) > time.Second { t.Fatal("unlink depends on Home", r.Code) } local := f.local(t, address) out = f.request("POST", "/signout", f.origin, nil, local) landing = f.request("GET", "/signed-out", "", nil, out.Result().Cookies()...) if strings.Contains(landing.Body.String(), "Sign out of Oficina ID too") { t.Fatal("local session offered Home hop") } } func mergeCookies(groups ...[]*http.Cookie) []*http.Cookie { jar := map[string]*http.Cookie{} for _, group := range groups { for _, c := range group { if c == nil { continue } if c.MaxAge < 0 { delete(jar, c.Name) } else { jar[c.Name] = c } } } var out []*http.Cookie for _, c := range jar { out = append(out, c) } return out }