From 3e8a0b6a9988e8eb58a0385bd7e3481a1dba3856 Mon Sep 17 00:00:00 2001 From: Anya Tokugawa Date: Tue, 1 Dec 2026 07:48:55 +0900 Subject: [PATCH] feat(mysql): port atomic CLI authentication handoff persistence --- cmd/pageswiki/mysql_ml_schema_test.go | 4 +- docs/design/ja/database-portability.md | 28 ++++-- docs/design/ja/implementation-backlog.md | 5 +- internal/store/auth_accounts_backend_test.go | 2 +- internal/store/auth_cli.go | 63 +++++++++++--- internal/store/auth_cli_backend_test.go | 91 ++++++++++++++++++++ internal/store/auth_cli_mysql.go | 33 +++++++ internal/store/auth_mysql.go | 2 +- internal/store/auth_mysql_schema.go | 11 +++ internal/store/auth_mysql_test.go | 23 +++-- internal/store/namespace_mysql.go | 2 +- 11 files changed, 234 insertions(+), 30 deletions(-) create mode 100644 internal/store/auth_cli_backend_test.go create mode 100644 internal/store/auth_cli_mysql.go diff --git a/cmd/pageswiki/mysql_ml_schema_test.go b/cmd/pageswiki/mysql_ml_schema_test.go index a29e514..cbd4295 100644 --- a/cmd/pageswiki/mysql_ml_schema_test.go +++ b/cmd/pageswiki/mysql_ml_schema_test.go @@ -68,7 +68,7 @@ func testMySQLSchemaCommand(t *testing.T, component string) { if component == "namespace" { pending = `"pending":3` } else if component == "identity" { - pending = `"pending":5` + pending = `"pending":6` } if e = run("status"); e != nil || !strings.Contains(out.String(), pending) { t.Fatal(out.String(), e) @@ -95,7 +95,7 @@ func testMySQLSchemaCommand(t *testing.T, component string) { if component == "namespace" { ledger, version = "store-namespaces", 1 } else if component == "identity" { - ledger, version = "store-auth-core", 2 + ledger, version = "store-auth-core", 3 } if _, e = admin.ExecContext(ctx, "UPDATE "+name+".schema_mysql_migrations SET state='running',next_operation=1 WHERE component=? AND version=?", ledger, version); e != nil { t.Fatal(e) diff --git a/docs/design/ja/database-portability.md b/docs/design/ja/database-portability.md index 25dabbf..8df3fe0 100644 --- a/docs/design/ja/database-portability.md +++ b/docs/design/ja/database-portability.md @@ -1,6 +1,6 @@ # SQLite依存の縮小とPostgreSQL/MySQL対応 -2026-11-30更新。既存PostgreSQL対応を維持し、新規ML機能からMySQL対応を検証する。 +2026-12-01更新。既存PostgreSQL対応を維持し、新規ML機能からMySQL対応を検証する。 SQL文字列をdriverで置換する方式や、未対応時のSQLite自動fallbackは採用しない。 既存本番DBの切替・実データ移行は本作業と分離する。 @@ -13,7 +13,7 @@ SQL文字列をdriverで置換する方式や、未対応時のSQLite自動fallb | ML予算schema | 明示migration | 明示migration | native migration、版/checksum台帳、検査・明示再開CLI。実DB試験済み、本番未適用 | | Campus/Domain/設定 | 既存 | 既存 | DB-COREa+b:Campus作成・更新、ホスト解決、設定、standalone Campus内のlocal Domain作成・更新。Domain/Campus削除は未対応 | | ユーザー/グループ | 既存 | 既存 | パスワードアカウント、所属、group/permission、管理者継承・失効の限定保存API。HTTP認証・完全な認可境界は未接続 | -| 認証設定/管理 | 既存 | 既存 | provider設定・暗号化secret保持、外部ID、challenge、TOTP、profile/avatarの保存処理。Domain別session一覧・失効を限定APIへ接続。CLI認証handoff・監査は未対応 | +| 認証設定/管理 | 既存 | 既存 | provider設定・暗号化secret保持、外部ID、challenge、TOTP、profile/avatar、CLI認証handoffの保存処理。Domain別session一覧・失効を限定APIへ接続。監査・HTTP接続は未対応 | | DBバックアップ/DR | 既存SQLite方式 | native backup、現行DR起動は拒否 | 設計・実装未着手 | MySQL接続を`internal/db/mysql.go`に追加。既定は検証付きTLSのみ、秘密情報を含むdriverエラーや @@ -34,7 +34,7 @@ Domain変更は`MySQLIdentityRepository`で、built-in group/管理者継承 `MySQLIdentityRepository`は保存APIであり、呼出元が認証・認可する必要がある。 権限評価の下位primitiveを完全なAuthorizeの代用として公開しない。 OIDC/LDAP/SMTP設定とsecret保持、外部ID紐付け、challenge、TOTP、profile/avatarの保存処理は -MySQLにも移植したが、HTTPサーバーや実providerとは未接続。CLI認証handoff、監査、 +MySQLにも移植したが、HTTPサーバーや実providerとは未接続。CLI認証handoffの保存処理も移植済み。監査、 locality/publication policyまで含む完全な認可境界は未移植。 パスワード照合・session purpose/Domain分離・失効のprimitiveは実DB試験済みだが、 MySQLで本体ログイン画面が使えることを意味しない。 @@ -80,7 +80,7 @@ MySQLで本体ログイン画面が使えることを意味しない。 **DB-COREb基盤実装済み**:principal/membership/built-in group、管理者継承、local Domain書込。 次はDB-COREcで文書metadata・Revision・Pathを移植する。 COREbの認証保存処理(外部ID/provider・MFA・profile)とsession管理は移植済み。 - 残件(CLI認証handoff・完全な認可snapshot・監査・group編集・認証/管理UI接続)も本体接続前に消化する。 + 残件(完全な認可snapshot・監査・group編集・認証/管理UI接続)も本体接続前に消化する。 部分対応を本体対応と混同しない。 4. **DB-JOBS**:activity outbox/イベントキュー/claim/lease/ログ保持を移植。 ワーカーの再起動・同時claim・timeout・receipt保持を確認してからML workerを接続する。 @@ -102,8 +102,7 @@ MySQL enumを増やしただけで全体対応を宣言せず、各repositoryの 2026-11-30コミット整理時にも、使い捨てのMySQL 8.4/PostgreSQL 17とSQLiteで 下記のnamespace・identity・ML・migration契約を`-race -count=1`で再検証した。 -`TestAccountBackend*`のCLI handoffは引き続きSQLite/PostgreSQLのみであり、 -MySQL対応済みの範囲には含めない。Goクライアント/設定APIの回帰と +この時点では`TestAccountBackend*`のCLI handoffはSQLite/PostgreSQLのみ(12月1日の追加は下記)。Goクライアント/設定APIの回帰と `go vet ./internal/db ./internal/machinelearning ./internal/store ./cmd/pageswiki`も成功。 全パッケージの全テスト、本番切替、MySQLでのHTTPサーバー起動確認を意味しない。 @@ -204,7 +203,7 @@ Domain別session一覧・失効。session操作はcontext取消・read-only失 寸法:UUID 36、identity issuer/subject・credential identifier 255、permission scope Path/grant target 512文字。 既存データのimportは未対応で、上限を超える値を切り詰めて取り込まない。 COREcで文書Pathの最大長とpermission scope/grant targetの上限を整合させる。 -groupの編集/archive、profile/avatar・provider/MFA等の管理UI接続、CLI認証handoff、監査、 +groupの編集/archive、profile/avatar・provider/MFA等の管理UI接続、監査、 完全な認可snapshot、Domain削除・federation・backupは後続。 Domain削除は文書・拡張機能の関連データ移植後に扱い、未対応tableを残した部分削除はしない。 公開前にこれらと文書metadataを接続する。 @@ -217,3 +216,18 @@ session Domain分離を検証する。実OIDC/LDAP/SMTPへの接続や既存ユ 2026-11-30の追加試験:上記4本と`TestMySQLIdentity*`/schema CLIを、SQLite・PostgreSQL 17・ MySQL 8.4で`-race -count=3`実行し成功。既存HTTPログイン・LDAP/OIDC設定・trusted session・ CLI OIDCの回帰試験も成功。本体MySQL受入や外部サービス接続の成功を意味しない。 + +### CLI認証handoffのMySQL移植(2026-12-01) + +v0.19.0候補とは分離した次段階。`store-auth-core`版3で`auth_cli_requests`を追加し、 +版1/2のchecksum・データを保持する。版3の検査は旧版の検査も引き継ぐ。 +MySQLでは`UPDATE ... RETURNING`に頼らず管理用行ロックと`SELECT ... FOR UPDATE`を使う。 +承認の消費とsession作成は同一transaction、誤コードの試行回数は拒否時にも保存する。 +poll間隔・発行上限・Domain/origin/verifierの照合・browser失効を既存契約に合わせる。 +CLI handoffは内部Store保存処理の移植であり、MySQL HTTPログインはまだ公開しない。 + +受入試験:`TestAccountBackendCLI*`、`TestMySQLIdentity*`、`TestMySQLMLSchemaCommand*`。 +3DBで単回交換・同時発行制限・失敗時rollback・期限切れ・誤コード上限・所属取消・ +read-only/context取消を検証する。実providerや本番ユーザーデータは使わない。 +SQLite/PostgreSQL 17/MySQL 8.4で上記と`TestAccountBackend*`/`TestCLIAuth*`を +`-race -count=1`実行して成功。`go vet ./internal/store ./cmd/pageswiki`も成功。 diff --git a/docs/design/ja/implementation-backlog.md b/docs/design/ja/implementation-backlog.md index aa6efaa..a89c02c 100644 --- a/docs/design/ja/implementation-backlog.md +++ b/docs/design/ja/implementation-backlog.md @@ -61,7 +61,10 @@ DB-MIGの基盤(版/checksum台帳、operation journal、専用connection lo 続いてCOREbのprovider設定・暗号化secret保持・外部ID紐付け・challenge・TOTP・profile/avatar保存を移植。 Domain別session一覧・失効を限定APIへ接続。auth schema版2を追加し、版1の履歴とデータを保持する。 MySQLのUPDATE代入順によるTOTP失敗回数の差も修正し、3DB共通の5回制限を試験する。 -次はCOREbのCLI認証handoff/監査/group編集と完全な認可snapshot、DB-COREcの文書metadata/Revision/Path。 +2026-12-01:CLI認証handoffの保存処理を移植。auth schema版3を追加し、版1/2の履歴・既存アカウントを保持。 +SQLite/PostgreSQL 17/MySQL 8.4で認証関連共通試験をrace付きで成功。単回交換、試行制限、 +session発行失敗時rollback、失効・分離境界を検証した。v0.19.0候補から分離した次段階の変更。 +次はCOREbの監査/group編集と完全な認可snapshot、DB-COREcの文書metadata/Revision/Path。 管理UI接続、Domain削除・federationも残る。Domain削除は関連文書・拡張データを含めた移植後に行う。 保存pilotをHTTP認証サーバーとして公開しない。 ML後続はこの境界と整合させ、MySQL本体対応を宣言するのはDB-APP通過後とする。 diff --git a/internal/store/auth_accounts_backend_test.go b/internal/store/auth_accounts_backend_test.go index a3aeaf6..4ec7150 100644 --- a/internal/store/auth_accounts_backend_test.go +++ b/internal/store/auth_accounts_backend_test.go @@ -13,7 +13,7 @@ import ( ) func TestAccountBackendCLIHandoff(t *testing.T) { - for _, b := range []storeSQLBackend{storeSQLite, storePostgreSQL} { + for _, b := range []storeSQLBackend{storeSQLite, storePostgreSQL, storeMySQL} { t.Run(fmt.Sprint(b), func(t *testing.T) { s, d := accountBackendStore(t, b) p, err := s.BootstrapOwner(d, "owner", "synthetic password for backend tests", "", "") diff --git a/internal/store/auth_cli.go b/internal/store/auth_cli.go index 44c90b6..17c28a9 100644 --- a/internal/store/auth_cli.go +++ b/internal/store/auth_cli.go @@ -44,7 +44,7 @@ type CLIAuthRequest struct { Remember bool } -// Admission is serialized on both backends so concurrent unauthenticated +// Admission is serialized on all backends so concurrent unauthenticated // requests cannot race the caps. Retain requests for issuance accounting. func (s *Store) StartCLIAuth(ctx context.Context, domain, origin, challenge string) (id, device, code string, err error) { return s.StartCLIAuthForLogin(ctx, domain, origin, challenge, false) @@ -76,6 +76,19 @@ func (s *Store) StartCLIAuthForLogin(ctx context.Context, domain, origin, challe if _, err := tx.ExecContext(ctx, `DELETE FROM auth_cli_requests WHERE expires_ms<`+s.sqlParam(1), now-5*60*1000); err != nil { return err } + if s.sqlBackend == storeMySQL { + // Read limits under the administrative write lock, avoiding a + // target-table subquery in MySQL's INSERT. Admission remains atomic. + var total, recent int + if err := tx.QueryRowContext(ctx, `SELECT COUNT(*),COALESCE(SUM(domain_uuid=? AND created_ms>?),0) FROM auth_cli_requests`, domain, now-300000).Scan(&total, &recent); err != nil { + return err + } + if total >= 4096 || recent >= 64 { + return ErrCLILimit + } + _, err := tx.ExecContext(ctx, `INSERT INTO auth_cli_requests(id,domain_uuid,origin,device_hash,challenge,code_hash,created_ms,expires_ms,remember) VALUES(?,?,?,?,?,?,?,?,?)`, id, domain, origin, hashAuthToken(device), challenge, hashAuthToken(code), now, now+300000, rememberValue) + return err + } result, err := tx.ExecContext(ctx, `INSERT INTO auth_cli_requests(id,domain_uuid,origin,device_hash,challenge,code_hash,created_ms,expires_ms,remember) SELECT `+s.sqlParam(1)+`,`+s.sqlParam(2)+`,`+s.sqlParam(3)+`,`+s.sqlParam(4)+`,`+s.sqlParam(5)+`,`+s.sqlParam(6)+`,`+s.sqlParam(7)+`,`+s.sqlParam(8)+`,`+s.sqlParam(9)+` WHERE (SELECT count(*) FROM auth_cli_requests)<4096 AND (SELECT count(*) FROM auth_cli_requests WHERE domain_uuid=`+s.sqlParam(10)+` AND created_ms>`+s.sqlParam(11)+`)<64`, @@ -148,9 +161,14 @@ func (s *Store) DecideCLIAuth(ctx context.Context, domain, origin, id, browser, } now := time.Now().UnixMilli() var expectedCode string - err := s.DB.QueryRowContext(ctx, `UPDATE auth_cli_requests SET attempts=attempts+1 + var err error + if s.sqlBackend == storeMySQL { + expectedCode, err = s.consumeCLIAuthAttemptMySQL(ctx, domain, origin, id, browser, now) + } else { + err = s.DB.QueryRowContext(ctx, `UPDATE auth_cli_requests SET attempts=attempts+1 WHERE id=`+s.sqlParam(1)+` AND domain_uuid=`+s.sqlParam(2)+` AND origin=`+s.sqlParam(3)+` AND state='pending' AND browser_hash=`+s.sqlParam(4)+` AND attempts<5 AND expires_ms>`+s.sqlParam(5)+` RETURNING code_hash`, id, domain, origin, hashAuthToken(browser), now).Scan(&expectedCode) + } if err != nil { return ErrAccessDenied } @@ -192,7 +210,11 @@ func (s *Store) ExchangeCLIAuth(ctx context.Context, domain, origin, device, ver now := time.Now().UnixMilli() lifetime := s.AuthSessionLifetime(domain).Milliseconds() trustedLifetime := s.LoginSessionLifetime(domain, true).Milliseconds() - tx, err := s.DB.BeginTx(ctx, nil) + var options *sql.TxOptions + if s.sqlBackend == storeMySQL { + options = &sql.TxOptions{Isolation: sql.LevelReadCommitted} + } + tx, err := s.DB.BeginTx(ctx, options) if err != nil { return } @@ -202,12 +224,21 @@ func (s *Store) ExchangeCLIAuth(ctx context.Context, domain, origin, device, ver if _, err = tx.ExecContext(ctx, `SELECT pg_advisory_xact_lock(1885431653, 1853058931)`); err != nil { return } + } else if s.sqlBackend == storeMySQL { + // Same lock order as account suspension and membership revocation. + if _, err = tx.ExecContext(ctx, `INSERT INTO namespace_write_lock(id) VALUES(1) ON DUPLICATE KEY UPDATE id=1`); err != nil { + return + } } var id, state, browser string var remember bool - err = tx.QueryRowContext(ctx, `UPDATE auth_cli_requests SET next_poll_ms=`+s.sqlParam(1)+`,state=CASE WHEN state='approved' THEN 'consumed' ELSE state END + if s.sqlBackend == storeMySQL { + id, state, browser, remember, err = s.pollCLIAuthMySQL(ctx, tx, domain, origin, device, verifier, now) + } else { + err = tx.QueryRowContext(ctx, `UPDATE auth_cli_requests SET next_poll_ms=`+s.sqlParam(1)+`,state=CASE WHEN state='approved' THEN 'consumed' ELSE state END WHERE device_hash=`+s.sqlParam(2)+` AND challenge=`+s.sqlParam(3)+` AND domain_uuid=`+s.sqlParam(4)+` AND origin=`+s.sqlParam(5)+` AND expires_ms>`+s.sqlParam(6)+` AND next_poll_ms<=`+s.sqlParam(7)+` AND state IN ('pending','approved','denied') RETURNING id,state,browser_hash,remember`, now+5000, hashAuthToken(device), hashAuthToken(verifier), domain, origin, now, now).Scan(&id, &state, &browser, &remember) + } if errors.Is(err, sql.ErrNoRows) { var exists int e := tx.QueryRowContext(ctx, `SELECT count(*) FROM auth_cli_requests WHERE device_hash=`+s.sqlParam(1)+` AND challenge=`+s.sqlParam(2)+` AND domain_uuid=`+s.sqlParam(3)+` AND origin=`+s.sqlParam(4)+` AND expires_ms>`+s.sqlParam(5)+` AND state IN ('pending','approved','denied')`, hashAuthToken(device), hashAuthToken(verifier), domain, origin, now).Scan(&exists) @@ -244,16 +275,28 @@ func (s *Store) ExchangeCLIAuth(ctx context.Context, domain, origin, device, ver } token = "pw_api_" + raw minimum, maximum := "min", "max" - if s.sqlBackend == storePostgreSQL { + if s.sqlBackend != storeSQLite { minimum, maximum = "LEAST", "GREATEST" } // A disabled user, removed membership or revoked browser cannot delegate. - err = tx.QueryRowContext(ctx, `INSERT INTO auth_sessions(uuid,token_hash,principal_uuid,domain_uuid,auth_time_ms,expires_at_ms,last_seen_at_ms,mfa_level) - SELECT `+s.sqlParam(1)+`,`+s.sqlParam(2)+`,p.uuid,a.domain_uuid,a.auth_time_ms,`+minimum+`(`+s.sqlParam(3)+`,a.expires_at_ms),`+s.sqlParam(4)+`,`+maximum+`(a.mfa_level,g.mfa_level) + insert := `INSERT INTO auth_sessions(uuid,token_hash,principal_uuid,domain_uuid,auth_time_ms,expires_at_ms,last_seen_at_ms,mfa_level) + SELECT ` + s.sqlParam(1) + `,` + s.sqlParam(2) + `,p.uuid,a.domain_uuid,a.auth_time_ms,` + minimum + `(` + s.sqlParam(3) + `,a.expires_at_ms),` + s.sqlParam(4) + `,` + maximum + `(a.mfa_level,g.mfa_level) FROM auth_cli_requests g JOIN auth_sessions a ON a.token_hash=g.browser_hash JOIN principals p ON p.uuid=a.principal_uuid JOIN domain_memberships m ON m.principal_uuid=p.uuid AND m.domain_uuid=a.domain_uuid - WHERE a.token_hash=`+s.sqlParam(5)+` AND a.domain_uuid=`+s.sqlParam(6)+` AND a.revoked_at_ms=0 AND a.expires_at_ms>`+s.sqlParam(7)+` AND p.state IN ('active','readonly') AND m.state='active' - AND g.id=`+s.sqlParam(8)+` - RETURNING principal_uuid,expires_at_ms`, uuid.NewString(), hashAuthToken(token), now+lifetime, now, browser, domain, now, id).Scan(&username, &expires) + WHERE a.token_hash=` + s.sqlParam(5) + ` AND a.domain_uuid=` + s.sqlParam(6) + ` AND a.revoked_at_ms=0 AND a.expires_at_ms>` + s.sqlParam(7) + ` AND p.state IN ('active','readonly') AND m.state='active' + AND g.id=` + s.sqlParam(8) + args := []any{uuid.NewString(), hashAuthToken(token), now + lifetime, now, browser, domain, now, id} + if s.sqlBackend == storeMySQL { + var result sql.Result + result, err = tx.ExecContext(ctx, insert, args...) + if err == nil { + err = cliChanged(result, nil) + } + if err == nil { + err = tx.QueryRowContext(ctx, `SELECT principal_uuid,expires_at_ms FROM auth_sessions WHERE uuid=?`, args[0]).Scan(&username, &expires) + } + } else { + err = tx.QueryRowContext(ctx, insert+` RETURNING principal_uuid,expires_at_ms`, args...).Scan(&username, &expires) + } if errors.Is(err, sql.ErrNoRows) { err = ErrAccessDenied } diff --git a/internal/store/auth_cli_backend_test.go b/internal/store/auth_cli_backend_test.go new file mode 100644 index 0000000..7be803c --- /dev/null +++ b/internal/store/auth_cli_backend_test.go @@ -0,0 +1,91 @@ +package store + +import ( + "context" + "errors" + "fmt" + "strings" + "testing" +) + +func TestAccountBackendCLIBoundaries(t *testing.T) { + for _, backend := range []storeSQLBackend{storeSQLite, storePostgreSQL, storeMySQL} { + t.Run(fmt.Sprint(backend), func(t *testing.T) { + for _, mode := range []string{"domain", "origin", "verifier", "device", "expired", "denied", "suspended", "membership", "browser-revoked", "attempts", "read-only", "cancelled"} { + t.Run(mode, func(t *testing.T) { + s, domain := accountBackendStore(t, backend) + ctx := context.Background() + p, err := s.BootstrapOwner(domain, "owner", "synthetic CLI boundary password", "", "") + if err != nil { + t.Fatal(err) + } + browser, err := s.CreateBrowserAuthSession(domain, p.UUID, 1) + if err != nil { + t.Fatal(err) + } + verifier := strings.Repeat("b", 43) + id, device, code, err := s.StartCLIAuth(ctx, domain, cliTestOrigin, hashAuthToken(verifier)) + if err != nil { + t.Fatal(err) + } + if err = s.BindCLIAuth(ctx, domain, cliTestOrigin, id, browser); err != nil { + t.Fatal(err) + } + if mode == "attempts" { + for i := 0; i < 5; i++ { + if e := s.DecideCLIAuth(ctx, domain, cliTestOrigin, id, browser, "wrong", "", true); !errors.Is(e, ErrAccessDenied) { + t.Fatal(e) + } + } + if e := s.DecideCLIAuth(ctx, domain, cliTestOrigin, id, browser, code, "", true); !errors.Is(e, ErrAccessDenied) { + t.Fatal("attempt limit bypassed", e) + } + var attempts int + if e := s.DB.QueryRow(`SELECT attempts FROM auth_cli_requests`).Scan(&attempts); e != nil || attempts != 5 { + t.Fatal("failed attempts not retained", attempts, e) + } + } else if err = s.DecideCLIAuth(ctx, domain, cliTestOrigin, id, browser, code, "", mode != "denied"); err != nil { + t.Fatal(err) + } + origin, query := cliTestOrigin, "" + switch mode { + case "domain": + domain = "outside" + case "origin": + origin = "https://alias.example.test" + case "verifier": + verifier = strings.Repeat("c", 43) + case "device": + device = strings.Repeat("d", 43) + case "expired": + query = `UPDATE auth_cli_requests SET expires_ms=1` + case "suspended": + query = `UPDATE principals SET state='suspended'` + case "membership": + query = `UPDATE domain_memberships SET state='suspended'` + case "browser-revoked": + query = `UPDATE auth_sessions SET revoked_at_ms=1` + case "read-only": + s.ReadOnly = true + case "cancelled": + var cancel context.CancelFunc + ctx, cancel = context.WithCancel(ctx) + cancel() + } + if query != "" { + if _, err = s.DB.Exec(query); err != nil { + t.Fatal(err) + } + } + if token, _, _, e := s.ExchangeCLIAuth(ctx, domain, origin, device, verifier); e == nil || token != "" { + t.Fatal("invalid grant issued session", e) + } + var sessions int + if e := s.DB.QueryRow(`SELECT COUNT(*) FROM auth_sessions`).Scan(&sessions); e != nil || sessions != 1 { + t.Fatal("session leaked", sessions, e) + } + }) + } + }) + } +} diff --git a/internal/store/auth_cli_mysql.go b/internal/store/auth_cli_mysql.go new file mode 100644 index 0000000..2c139b6 --- /dev/null +++ b/internal/store/auth_cli_mysql.go @@ -0,0 +1,33 @@ +package store + +import ( + "context" + "database/sql" +) + +// Commit the attempt before checking the approval code. A wrong code must not +// roll back its attempt counter. The row lock replaces UPDATE ... RETURNING. +func (s *Store) consumeCLIAuthAttemptMySQL(ctx context.Context, domain, origin, id, browser string, now int64) (code string, err error) { + err = s.groupWrite(ctx, func(ctx context.Context, tx *sql.Tx) error { + if e := tx.QueryRowContext(ctx, `SELECT code_hash FROM auth_cli_requests WHERE id=? AND domain_uuid=? AND origin=? AND state='pending' AND browser_hash=? AND attempts<5 AND expires_ms>? FOR UPDATE`, id, domain, origin, hashAuthToken(browser), now).Scan(&code); e != nil { + return e + } + _, e := tx.ExecContext(ctx, `UPDATE auth_cli_requests SET attempts=attempts+1 WHERE id=?`, id) + return e + }) + return +} + +// The caller holds the administrative lock and commits polling/consumption +// together with session creation. Failed issuance rolls back consumption. +func (s *Store) pollCLIAuthMySQL(ctx context.Context, tx *sql.Tx, domain, origin, device, verifier string, now int64) (id, state, browser string, remember bool, err error) { + err = tx.QueryRowContext(ctx, `SELECT id,state,browser_hash,remember FROM auth_cli_requests WHERE device_hash=? AND challenge=? AND domain_uuid=? AND origin=? AND expires_ms>? AND next_poll_ms<=? AND state IN ('pending','approved','denied') FOR UPDATE`, hashAuthToken(device), hashAuthToken(verifier), domain, origin, now, now).Scan(&id, &state, &browser, &remember) + if err != nil { + return + } + if state == "approved" { + state = "consumed" + } + _, err = tx.ExecContext(ctx, `UPDATE auth_cli_requests SET next_poll_ms=?,state=? WHERE id=?`, now+5000, state, id) + return +} diff --git a/internal/store/auth_mysql.go b/internal/store/auth_mysql.go index 6264172..f890d4f 100644 --- a/internal/store/auth_mysql.go +++ b/internal/store/auth_mysql.go @@ -11,7 +11,7 @@ import ( // MUST authenticate and authorize every administrator mutation. It intentionally // exposes neither *Store nor grant-only checks as a complete authorization API. // MFA/provider persistence is internally tested but not exposed as a login API. -// Audit/locality policy, CLI handoff and Domain deletion remain unported. +// Audit/locality policy and Domain deletion remain unported. type MySQLIdentityRepository struct{ store *Store } func NewMySQLIdentityRepository(database *sql.DB) *MySQLIdentityRepository { diff --git a/internal/store/auth_mysql_schema.go b/internal/store/auth_mysql_schema.go index 21b9b63..078f80e 100644 --- a/internal/store/auth_mysql_schema.go +++ b/internal/store/auth_mysql_schema.go @@ -49,6 +49,17 @@ func mysqlAuthMigrations() []db.MySQLMigration { // Inspect validates the latest contract only, since later versions may // replace older columns. This additive version must retain all v1 checks. steps[1].Assertions = append(append([]string{}, steps[0].Assertions...), steps[1].Assertions...) + cli := mysqlAuthTableMigration(3, "CLI authentication handoff", []mysqlAuthTable{ + {"auth_cli_requests", []mysqlAuthColumn{ + {"id", "varchar(128)", ""}, {"domain_uuid", id, ""}, {"origin", "varchar(2048)", ""}, + {"device_hash", "varchar(128)", ""}, {"challenge", "varchar(128)", ""}, {"code_hash", "varchar(128)", ""}, + {"state", state, "'pending'"}, {"browser_hash", "varchar(128)", "''"}, {"principal_uuid", id, "''"}, + {"mfa_level", "int", "0"}, {"attempts", "int", "0"}, {"oidc_attempts", "int", "0"}, + {"created_ms", number, ""}, {"expires_ms", number, ""}, {"next_poll_ms", number, "0"}, {"remember", "int", "0"}, + }, []string{"id", "device_hash"}, []string{"domain_uuid,created_ms", "expires_ms"}}, + }) + cli.Assertions = append(append([]string{}, steps[1].Assertions...), cli.Assertions...) + steps = append(steps, cli) return steps } diff --git a/internal/store/auth_mysql_test.go b/internal/store/auth_mysql_test.go index 1a5b795..319164d 100644 --- a/internal/store/auth_mysql_test.go +++ b/internal/store/auth_mysql_test.go @@ -4,6 +4,7 @@ import ( "context" "database/sql" "errors" + "fmt" "strings" "testing" @@ -206,7 +207,7 @@ func TestMySQLIdentitySchemaAndCancellation(t *testing.T) { database := mysqlTestDatabase(t) r := NewMySQLIdentityRepository(database) ctx := context.Background() - if status, e := r.InspectSchema(ctx); e != nil || status.Pending != 5 { + if status, e := r.InspectSchema(ctx); e != nil || status.Pending != 6 { t.Fatal(status, e) } if e := r.PrepareSchema(ctx); e != nil { @@ -215,7 +216,7 @@ func TestMySQLIdentitySchemaAndCancellation(t *testing.T) { if e := r.PrepareSchema(ctx); e != nil { t.Fatal("repeat prepare", e) } - if _, e := database.Exec(`UPDATE schema_mysql_migrations SET state='running',next_operation=1 WHERE component='store-auth-core' AND version=2`); e != nil { + if _, e := database.Exec(`UPDATE schema_mysql_migrations SET state='running',next_operation=1 WHERE component='store-auth-core' AND version=3`); e != nil { t.Fatal(e) } if e := r.PrepareSchema(ctx); !errors.Is(e, db.ErrMySQLMigrationDirty) { @@ -256,37 +257,45 @@ func TestMySQLIdentitySchemaAndCancellation(t *testing.T) { } func TestMySQLIdentitySchemaUpgradePreservesAccounts(t *testing.T) { + for _, version := range []int{1, 2} { + t.Run(fmt.Sprint(version), func(t *testing.T) { + testMySQLIdentitySchemaUpgrade(t, version) + }) + } +} + +func testMySQLIdentitySchemaUpgrade(t *testing.T, version int) { database := mysqlTestDatabase(t) ctx := context.Background() if err := NewMySQLNamespaceRepository(database).PrepareSchema(ctx); err != nil { t.Fatal(err) } plan := mysqlAuthMigrations() - if err := db.ApplyMySQLMigrations(ctx, database, "store-auth-core", plan[:1]); err != nil { + if err := db.ApplyMySQLMigrations(ctx, database, "store-auth-core", plan[:version]); err != nil { t.Fatal(err) } var before string - if err := database.QueryRow(`SELECT checksum FROM schema_mysql_migrations WHERE component='store-auth-core' AND version=1`).Scan(&before); err != nil { + if err := database.QueryRow(`SELECT GROUP_CONCAT(checksum ORDER BY version) FROM schema_mysql_migrations WHERE component='store-auth-core' AND version<=?`, version).Scan(&before); err != nil { t.Fatal(err) } if _, err := database.Exec(`INSERT INTO principals(uuid,display_name,created_at_ms,updated_at_ms) VALUES('upgrade-user','既存の利用者',1,1)`); err != nil { t.Fatal(err) } r := NewMySQLIdentityRepository(database) - if status, err := r.InspectSchema(ctx); err != nil || status.Pending != 1 || status.Applied != 4 { + if status, err := r.InspectSchema(ctx); err != nil || status.Pending != 3-version || status.Applied != 3+version { t.Fatal(status, err) } if err := r.PrepareSchema(ctx); err != nil { t.Fatal(err) } var after, title string - if err := database.QueryRow(`SELECT checksum FROM schema_mysql_migrations WHERE component='store-auth-core' AND version=1`).Scan(&after); err != nil || after != before { + if err := database.QueryRow(`SELECT GROUP_CONCAT(checksum ORDER BY version) FROM schema_mysql_migrations WHERE component='store-auth-core' AND version<=?`, version).Scan(&after); err != nil || after != before { t.Fatal("historical checksum changed", err) } if err := database.QueryRow(`SELECT display_name FROM principals WHERE uuid='upgrade-user'`).Scan(&title); err != nil || title != "既存の利用者" { t.Fatal("existing principal changed", err) } - if status, err := r.InspectSchema(ctx); err != nil || status.Pending != 0 || status.Applied != 5 { + if status, err := r.InspectSchema(ctx); err != nil || status.Pending != 0 || status.Applied != 6 { t.Fatal(status, err) } if _, err := database.Exec(`ALTER TABLE auth_providers DROP INDEX uq_0`); err != nil { diff --git a/internal/store/namespace_mysql.go b/internal/store/namespace_mysql.go index 55d06cd..efcad3b 100644 --- a/internal/store/namespace_mysql.go +++ b/internal/store/namespace_mysql.go @@ -23,7 +23,7 @@ func mysqlStoreError(operation string, err error) error { if err == nil { return nil } - for _, known := range []error{sql.ErrNoRows, context.Canceled, context.DeadlineExceeded, ErrReadOnly, ErrBackendFeatureUnavailable, ErrAccessDenied} { + for _, known := range []error{sql.ErrNoRows, context.Canceled, context.DeadlineExceeded, ErrReadOnly, ErrBackendFeatureUnavailable, ErrAccessDenied, ErrCLIPending, ErrCLISlowDown, ErrCLIExpired, ErrCLILimit} { if errors.Is(err, known) { return known }