oficina / equipo Public

Require fresh Keymail gestures and bound Oficina ID sign-in starts

codex agent, operated by paul@keymail.dev pushed by paul@keymail.dev de8177bc27ce93dba314491ca74de752c51ea63b parent a20309a
8 files changed, +223 −42
  • internal/equipo/migrations/0082_oficina_id.sql +1 −1
  • internal/equipo/migrations/schema.sql +1 −1
  • internal/equipo/oficinaid/http.go +19 −3
  • internal/equipo/oficinaid/link.go +4 −1
  • internal/equipo/oficinaid/migrations/0001_lifecycle.sql +2 −2
  • internal/equipo/oficinaid/review_test.go +175 −0
  • internal/equipo/oficinaid/store.go +12 −28
  • internal/idtest/deletion_test.go +9 −6

CI passed — run details

diff --git a/internal/equipo/migrations/0082_oficina_id.sql b/internal/equipo/migrations/0082_oficina_id.sql
index cd47e40c..cee08c72 100644
--- a/internal/equipo/migrations/0082_oficina_id.sql
+++ b/internal/equipo/migrations/0082_oficina_id.sql
@@ -4,5 +4,5 @@ CREATE UNIQUE INDEX members_identity_key ON members(identity_key);
CREATE TRIGGER equipo_member_identity AFTER INSERT ON members WHEN NEW.identity_key='' BEGIN
UPDATE members SET identity_key=lower(hex(randomblob(16))) WHERE address=NEW.address;
END;
-CREATE TABLE equipo_id_accounts (id INTEGER PRIMARY KEY AUTOINCREMENT, binding TEXT NOT NULL UNIQUE, member_key TEXT NOT NULL UNIQUE, sealed_address BLOB NOT NULL, linked_at INTEGER NOT NULL DEFAULT 0);
+CREATE TABLE equipo_id_accounts (id INTEGER PRIMARY KEY AUTOINCREMENT, binding TEXT NOT NULL UNIQUE, member_key TEXT NOT NULL UNIQUE, linked_at INTEGER NOT NULL DEFAULT 0);
CREATE TABLE equipo_id_reauth (id_hash TEXT PRIMARY KEY, account_id INTEGER NOT NULL, session_hash TEXT NOT NULL, started INTEGER NOT NULL, expires INTEGER NOT NULL, purpose TEXT NOT NULL, ready INTEGER NOT NULL DEFAULT 0);
diff --git a/internal/equipo/migrations/schema.sql b/internal/equipo/migrations/schema.sql
index 42881be9..f97d2145 100644
--- a/internal/equipo/migrations/schema.sql
+++ b/internal/equipo/migrations/schema.sql
@@ -684,5 +684,5 @@ CREATE UNIQUE INDEX members_identity_key ON members(identity_key);
CREATE TRIGGER equipo_member_identity AFTER INSERT ON members WHEN NEW.identity_key='' BEGIN
UPDATE members SET identity_key=lower(hex(randomblob(16))) WHERE address=NEW.address;
END;
-CREATE TABLE equipo_id_accounts (id INTEGER PRIMARY KEY AUTOINCREMENT, binding TEXT NOT NULL UNIQUE, member_key TEXT NOT NULL UNIQUE, sealed_address BLOB NOT NULL, linked_at INTEGER NOT NULL DEFAULT 0);
+CREATE TABLE equipo_id_accounts (id INTEGER PRIMARY KEY AUTOINCREMENT, binding TEXT NOT NULL UNIQUE, member_key TEXT NOT NULL UNIQUE, linked_at INTEGER NOT NULL DEFAULT 0);
CREATE TABLE equipo_id_reauth (id_hash TEXT PRIMARY KEY, account_id INTEGER NOT NULL, session_hash TEXT NOT NULL, started INTEGER NOT NULL, expires INTEGER NOT NULL, purpose TEXT NOT NULL, ready INTEGER NOT NULL DEFAULT 0);
diff --git a/internal/equipo/oficinaid/http.go b/internal/equipo/oficinaid/http.go
index 74e28bdd..a09d029d 100644
--- a/internal/equipo/oficinaid/http.go
+++ b/internal/equipo/oficinaid/http.go
@@ -1,6 +1,8 @@
package oficinaid
import (
+ "amadan.net/rastrillo/rastrillo/carlos"
+ "amadan.net/rastrillo/rastrillo/clientip"
"encoding/base64"
"errors"
"io"
@@ -8,6 +10,7 @@ import (
"net/http"
"net/url"
"strings"
+ "sync"
"time"
"amadan.net/oficina/equipo/internal/equipo/identity"
@@ -33,9 +36,11 @@ type View struct {
HomeSignout string
}
type HTTP struct {
- Store *Store
- Auth *auth.Auth
- Render func(http.ResponseWriter, *http.Request, View, int)
+ startOnce sync.Once
+ startLimiter *signin.MemoryLimiter
+ Store *Store
+ Auth *auth.Auth
+ Render func(http.ResponseWriter, *http.Request, View, int)
}
func cookie(r *http.Request, name string) string {
@@ -139,6 +144,17 @@ func (h *HTTP) Start(w http.ResponseWriter, r *http.Request) {
h.fail(w, r, ErrRefused)
return
}
+ h.startOnce.Do(func() { h.startLimiter = signin.NewMemoryLimiter(10 * time.Minute) })
+ hops := 0
+ if carlos.Running() {
+ hops = clientip.DefaultHops
+ }
+ allowed, err := h.startLimiter.Allow(r.Context(), clientip.From(r, hops), time.Now(), 20)
+ if err != nil || !allowed {
+ w.Header().Set("Retry-After", "600")
+ h.Render(w, r, View{State: "failed"}, http.StatusTooManyRequests)
+ return
+ }
secret, nonce, e := start(r.Context(), path, cookie(r, pendingCookie), time.Now())
if e != nil {
h.fail(w, r, e)
diff --git a/internal/equipo/oficinaid/link.go b/internal/equipo/oficinaid/link.go
index 3842ea56..be2b8179 100644
--- a/internal/equipo/oficinaid/link.go
+++ b/internal/equipo/oficinaid/link.go
@@ -173,7 +173,10 @@ func (s *Store) Unlink(ctx context.Context, proof, token string, now time.Time)
if _, e = tx.ExecContext(ctx, "DELETE FROM home_identity_links WHERE issuer=? AND person_id=?", s.Config.Issuer, local.PersonID); e != nil {
return e
}
- for _, table := range []string{"home_link_flows", "oficina_handoff_pending", "oficina_handoff_inbox", "equipo_id_reauth"} {
+ if _, e = tx.ExecContext(ctx, "DELETE FROM equipo_id_reauth WHERE account_id=?", local.PersonID); e != nil {
+ return e
+ }
+ for _, table := range []string{"home_link_flows", "oficina_handoff_pending", "oficina_handoff_inbox"} {
if _, e = tx.ExecContext(ctx, "DELETE FROM "+table); e != nil {
return e
}
diff --git a/internal/equipo/oficinaid/migrations/0001_lifecycle.sql b/internal/equipo/oficinaid/migrations/0001_lifecycle.sql
index 33e7eba7..214f0575 100644
--- a/internal/equipo/oficinaid/migrations/0001_lifecycle.sql
+++ b/internal/equipo/oficinaid/migrations/0001_lifecycle.sql
@@ -1,8 +1,8 @@
CREATE TRIGGER equipo_id_member_delete AFTER DELETE ON members BEGIN
DELETE FROM sessions WHERE method='oficina-id' AND subject IN (SELECT subject FROM home_identity_links WHERE person_id IN (SELECT id FROM equipo_id_accounts WHERE member_key=OLD.identity_key));
DELETE FROM home_identity_links WHERE person_id IN (SELECT id FROM equipo_id_accounts WHERE member_key=OLD.identity_key);
+ DELETE FROM equipo_id_reauth WHERE account_id IN (SELECT id FROM equipo_id_accounts WHERE member_key=OLD.identity_key);
DELETE FROM equipo_id_accounts WHERE member_key=OLD.identity_key;
- DELETE FROM equipo_id_reauth;
DELETE FROM home_link_flows;
DELETE FROM oficina_handoff_pending;
DELETE FROM oficina_handoff_inbox;
@@ -10,8 +10,8 @@ END;
CREATE TRIGGER equipo_id_member_change AFTER UPDATE OF address ON members WHEN OLD.address<>NEW.address BEGIN
DELETE FROM sessions WHERE method='oficina-id' AND subject IN (SELECT subject FROM home_identity_links WHERE person_id IN (SELECT id FROM equipo_id_accounts WHERE member_key=OLD.identity_key));
DELETE FROM home_identity_links WHERE person_id IN (SELECT id FROM equipo_id_accounts WHERE member_key=OLD.identity_key);
+ DELETE FROM equipo_id_reauth WHERE account_id IN (SELECT id FROM equipo_id_accounts WHERE member_key=OLD.identity_key);
DELETE FROM equipo_id_accounts WHERE member_key=OLD.identity_key;
- DELETE FROM equipo_id_reauth;
DELETE FROM home_link_flows;
DELETE FROM oficina_handoff_pending;
DELETE FROM oficina_handoff_inbox;
diff --git a/internal/equipo/oficinaid/review_test.go b/internal/equipo/oficinaid/review_test.go
new file mode 100644
index 00000000..0da66830
--- /dev/null
+++ b/internal/equipo/oficinaid/review_test.go
@@ -0,0 +1,175 @@
+package oficinaid
+
+import (
+ "context"
+ "net/http"
+ "net/http/httptest"
+ "strconv"
+ "testing"
+ "time"
+
+ "amadan.net/rastrillo/rastrillo/sessions"
+)
+
+func TestIDLocalGesture(t *testing.T) {
+ for _, purpose := range []string{"link", "unlink"} {
+ for _, method := range []string{"magiclink", "keymail"} {
+ for _, gesture := range []string{"missing", "old", "fresh", "future"} {
+ t.Run(purpose+"/"+method+"/"+gesture, func(t *testing.T) {
+ s, _ := fixture(t)
+ ctx := context.Background()
+ now := time.Now().Truncate(time.Second)
+ old := seedLocal(t, s, "local@example.invalid", now)
+ proof, e := s.BeginReauth(ctx, old, purpose, now)
+ if e != nil {
+ t.Fatal(e)
+ }
+ fresh := seedLocal(t, s, "local@example.invalid", now.Add(time.Second))
+ at := ""
+ switch gesture {
+ case "old":
+ at = now.Add(-time.Second).Format(time.RFC3339)
+ case "fresh":
+ at = now.Format(time.RFC3339)
+ case "future":
+ at = now.Add(time.Minute).Format(time.RFC3339)
+ }
+ if _, e = s.DB.Exec("UPDATE sessions SET method=?,auth_time=? WHERE token_hash=?", method, at, sessions.HashToken(fresh)); e != nil {
+ t.Fatal(e)
+ }
+ _, _, e = s.CompleteReauth(ctx, proof, fresh, now.Add(time.Second))
+ want := gesture == "fresh" || (method == "magiclink" && gesture == "missing")
+ if (e == nil) != want {
+ t.Fatalf("gesture accepted=%v want=%v: %v", e == nil, want, e)
+ }
+ if e == nil && purpose == "unlink" {
+ if e = s.Unlink(ctx, proof, fresh, now.Add(time.Second)); e != nil {
+ t.Fatal(e)
+ }
+ }
+ })
+ }
+ }
+ }
+}
+
+func TestIDReauthCleanupScope(t *testing.T) {
+ for _, action := range []string{"unlink", "delete", "address"} {
+ t.Run(action, func(t *testing.T) {
+ s, k := fixture(t)
+ ctx := context.Background()
+ now := time.Now().Truncate(time.Second)
+ local, _ := establish(t, s, k, now)
+ migration, e := migrations.ReadFile("migrations/0001_lifecycle.sql")
+ if e != nil {
+ t.Fatal(e)
+ }
+ if _, e = s.DB.Exec(string(migration)); e != nil {
+ t.Fatal(e)
+ }
+ other := seedLocal(t, s, "other@example.invalid", now)
+ otherProof, e := s.BeginReauth(ctx, other, "link", now)
+ if e != nil {
+ t.Fatal(e)
+ }
+ proof, e := s.BeginReauth(ctx, local, "unlink", now)
+ if e != nil {
+ t.Fatal(e)
+ }
+ switch action {
+ case "unlink":
+ fresh := seedLocal(t, s, "local-canary@example.invalid", now)
+ if _, _, e = s.CompleteReauth(ctx, proof, fresh, now); e != nil {
+ t.Fatal(e)
+ }
+ e = s.Unlink(ctx, proof, fresh, now)
+ case "delete":
+ _, e = s.DB.Exec("DELETE FROM members WHERE address='local-canary@example.invalid'")
+ case "address":
+ _, e = s.DB.Exec("UPDATE members SET address='changed@example.invalid' WHERE address='local-canary@example.invalid'")
+ }
+ if e != nil {
+ t.Fatal(e)
+ }
+ var n int
+ if e = s.DB.QueryRow("SELECT count(*) FROM equipo_id_reauth WHERE id_hash=?", sessions.HashToken(proof)).Scan(&n); e != nil || n != 0 {
+ t.Fatal("affected proof survived", n, e)
+ }
+ fresh := seedLocal(t, s, "other@example.invalid", now)
+ if _, _, e = s.CompleteReauth(ctx, otherProof, fresh, now); e != nil {
+ t.Fatal("other account reauthentication lost", e)
+ }
+ })
+ }
+}
+
+func TestIDStartIPLimit(t *testing.T) {
+ for _, platform := range []bool{false, true} {
+ t.Run(strconv.FormatBool(platform), func(t *testing.T) {
+ socket := ""
+ if platform {
+ socket = "/not-opened"
+ }
+ t.Setenv("CARLOS_CONTROL_SOCKET", socket)
+ testStartIPLimit(t, platform)
+ })
+ }
+}
+func testStartIPLimit(t *testing.T, platform bool) {
+ t.Helper()
+ s, _ := fixture(t)
+ h := &HTTP{Store: s, Render: func(w http.ResponseWriter, _ *http.Request, _ View, status int) { w.WriteHeader(status) }}
+ start := func(ip, port string, i int) int {
+ r := httptest.NewRequest("GET", s.Origin+"/auth/home", nil)
+ r.RemoteAddr = ip + ":" + port
+ r.Header.Set("X-Forwarded-For", "198.51.100."+strconv.Itoa(i))
+ if platform {
+ r.RemoteAddr = "127.0.0.1:" + port
+ r.Header.Add("X-Forwarded-For", ip)
+ }
+ w := httptest.NewRecorder()
+ h.Start(w, r)
+ return w.Code
+ }
+ for i := 0; i < 20; i++ {
+ if got := start("192.0.2.1", strconv.Itoa(1000+i), i); got != 303 {
+ t.Fatal("allowance", i, got)
+ }
+ }
+ for i := 0; i < 3; i++ {
+ if got := start("192.0.2.1", strconv.Itoa(2000+i), i+20); got != 429 {
+ t.Fatal("IP budget bypassed", got)
+ }
+ }
+ var n int
+ if e := s.DB.QueryRow("SELECT count(*) FROM oficina_handoff_pending").Scan(&n); e != nil || n != 20 {
+ t.Fatal("limited request inserted pending", n, e)
+ }
+ if got := start("192.0.2.2", "3000", 40); got != 303 {
+ t.Fatal("other IP blocked", got)
+ }
+}
+
+func TestIDUnlinkRechecksKeymailGesture(t *testing.T) {
+ s, k := fixture(t)
+ now := time.Now().Truncate(time.Second)
+ local, _ := establish(t, s, k, now)
+ ctx := context.Background()
+ proof, e := s.BeginReauth(ctx, local, "unlink", now)
+ if e != nil {
+ t.Fatal(e)
+ }
+ fresh := seedLocal(t, s, "local-canary@example.invalid", now)
+ if _, e = s.DB.Exec("UPDATE sessions SET method='keymail',auth_time=? WHERE token_hash=?", now.Format(time.RFC3339), sessions.HashToken(fresh)); e != nil {
+ t.Fatal(e)
+ }
+ if _, _, e = s.CompleteReauth(ctx, proof, fresh, now); e != nil {
+ t.Fatal(e)
+ }
+ if _, e = s.DB.Exec("UPDATE sessions SET auth_time='' WHERE token_hash=?", sessions.HashToken(fresh)); e != nil {
+ t.Fatal(e)
+ }
+ if e = s.Unlink(ctx, proof, fresh, now); e == nil {
+ t.Fatal("unlink accepted Keymail without gesture")
+ }
+}
diff --git a/internal/equipo/oficinaid/store.go b/internal/equipo/oficinaid/store.go
index 14e76d2f..ab133daa 100644
--- a/internal/equipo/oficinaid/store.go
+++ b/internal/equipo/oficinaid/store.go
@@ -23,15 +23,14 @@ const Method = "oficina-id"
var ErrRefused = errors.New("oficina identity refused")
var ErrUnlinked = errors.New("oficina identity unlinked")
-const SchemaSQL = `CREATE TABLE equipo_id_accounts (id INTEGER PRIMARY KEY AUTOINCREMENT, binding TEXT NOT NULL UNIQUE, member_key TEXT NOT NULL UNIQUE, sealed_address BLOB NOT NULL, linked_at INTEGER NOT NULL DEFAULT 0);
+const SchemaSQL = `CREATE TABLE equipo_id_accounts (id INTEGER PRIMARY KEY AUTOINCREMENT, binding TEXT NOT NULL UNIQUE, member_key TEXT NOT NULL UNIQUE, linked_at INTEGER NOT NULL DEFAULT 0);
CREATE TABLE equipo_id_reauth (id_hash TEXT PRIMARY KEY, account_id INTEGER NOT NULL, session_hash TEXT NOT NULL, started INTEGER NOT NULL, expires INTEGER NOT NULL, purpose TEXT NOT NULL, ready INTEGER NOT NULL DEFAULT 0);`
type Account struct {
- MemberKey string `gorm:"not null;unique"`
- ID int64
- Binding string `gorm:"not null;unique"`
- SealedAddress []byte `gorm:"not null"`
- LinkedAt int64 `gorm:"not null;default:0"`
+ MemberKey string `gorm:"not null;unique"`
+ ID int64
+ Binding string `gorm:"not null;unique"`
+ LinkedAt int64 `gorm:"not null;default:0"`
}
func (Account) TableName() string { return "equipo_id_accounts" }
@@ -84,18 +83,9 @@ func (s *Store) binding(address string) string {
return hex.EncodeToString(m.Sum(nil))
}
func (s *Store) lookup(ctx context.Context, q linkstore.Queryer, id int64) (string, error) {
- var sealed []byte
- var memberKey string
- if e := q.QueryRowContext(ctx, "SELECT sealed_address,member_key FROM equipo_id_accounts WHERE id=?", id).Scan(&sealed, &memberKey); e != nil {
- return "", e
- }
- plain, e := s.seal.Open("account."+strconv.FormatInt(id, 10), sealed)
- if e != nil {
- return "", ErrRefused
- }
- address := string(plain)
+ var address string
var active bool
- if e = q.QueryRowContext(ctx, "SELECT active FROM members WHERE address=? AND identity_key=?", address, memberKey).Scan(&active); e != nil {
+ if e := q.QueryRowContext(ctx, "SELECT m.address,m.active FROM equipo_id_accounts a JOIN members m ON m.identity_key=a.member_key WHERE a.id=?", id).Scan(&address, &active); e != nil {
return "", e
}
if !active {
@@ -118,20 +108,11 @@ func (s *Store) account(ctx context.Context, tx *sql.Tx, address string) (int64,
if !errors.Is(e, sql.ErrNoRows) {
return 0, e
}
- result, e := tx.ExecContext(ctx, "INSERT INTO equipo_id_accounts(binding,member_key,sealed_address) VALUES(?,?,?)", binding, memberKey, []byte{})
- if e != nil {
- return 0, e
- }
- id, e = result.LastInsertId()
- if e != nil {
- return 0, e
- }
- sealed, e := s.seal.Seal("account."+strconv.FormatInt(id, 10), []byte(address))
+ result, e := tx.ExecContext(ctx, "INSERT INTO equipo_id_accounts(binding,member_key) VALUES(?,?)", binding, memberKey)
if e != nil {
return 0, e
}
- _, e = tx.ExecContext(ctx, "UPDATE equipo_id_accounts SET sealed_address=? WHERE id=?", sealed, id)
- return id, e
+ return result.LastInsertId()
}
func (s *Store) begin(ctx context.Context, now time.Time) (*sql.Tx, error) {
tx, e := s.DB.BeginTx(ctx, nil)
@@ -217,6 +198,9 @@ func (s *Store) local(ctx context.Context, tx *sql.Tx, token string, now time.Ti
}
at := sess.AuthTime
if at.IsZero() {
+ if sess.Method == "keymail" {
+ return linkstore.Local{}, ErrRefused
+ }
at = sess.At
}
if at.After(now) || high-at.Unix() > 300 {
diff --git a/internal/idtest/deletion_test.go b/internal/idtest/deletion_test.go
index 17d4ec05..131bc1bc 100644
--- a/internal/idtest/deletion_test.go
+++ b/internal/idtest/deletion_test.go
@@ -2,7 +2,6 @@ package idtest
import (
"amadan.net/rastrillo/rastrillo/sessions"
- "bytes"
"net/url"
"testing"
"time"
@@ -63,18 +62,22 @@ func TestIDLocalReauthenticationUsesRealEmail(t *testing.T) {
}
}
-func TestIDReauthSealsLocalAddressBeforeWrite(t *testing.T) {
+func TestIDReauthHasNoAddressBridge(t *testing.T) {
f := newFixture(t, true)
local := f.local(t, address)
out := f.request("POST", "/account/home/reauth", f.origin, url.Values{"purpose": {"link"}}, local)
if out.Code != 303 {
t.Fatal("reauth start", out.Code)
}
- var sealed []byte
- if e := f.db.Writer().QueryRow("SELECT sealed_address FROM equipo_id_accounts").Scan(&sealed); e != nil {
+ var n int
+ if e := f.db.Writer().QueryRow("SELECT count(*) FROM pragma_table_info('equipo_id_accounts') WHERE name LIKE '%address%'").Scan(&n); e != nil || n != 0 {
+ t.Fatal("redundant address bridge remains", n, e)
+ }
+ var key, memberKey string
+ if e := f.db.Writer().QueryRow("SELECT member_key FROM equipo_id_accounts").Scan(&key); e != nil {
t.Fatal(e)
}
- if len(sealed) == 0 || bytes.Contains(sealed, []byte(address)) {
- t.Fatal("readable local address persisted before sealing")
+ if e := f.db.Writer().QueryRow("SELECT identity_key FROM members WHERE address=?", address).Scan(&memberKey); e != nil || key != memberKey {
+ t.Fatal("immutable member binding missing", e)
}
}