4 Commits
Author SHA1 Message Date
Anya Tokugawa b650fe50d7 feat(auth): add scoped JSON account and session queries for CLI clients
Build and publish container images / images (push) Successful in 18m18s
2026-12-01 08:17:56 +09:00
Anya Tokugawa 6f9752ea3a docs(release): record verified v0.19.0 production deployment
Build and publish container images / images (push) Successful in 18m36s
2026-12-01 08:03:49 +09:00
Anya Tokugawa 8f771b2ce6 ci(mysql): verify native pilot contracts before publishing images 2026-12-01 07:54:08 +09:00
Anya Tokugawa 3e8a0b6a99 feat(mysql): port atomic CLI authentication handoff persistence 2026-12-01 07:48:55 +09:00
25 changed files with 971 additions and 30 deletions

No files matched your search

+4
View File
@@ -51,6 +51,10 @@ jobs:
shell: bash shell: bash
run: bash tools/ci/test-postgres.sh run: bash tools/ci/test-postgres.sh
- name: Test native MySQL 8.4 pilot contracts before publishing
shell: bash
run: bash tools/ci/test-mysql.sh
- name: Log in to registry - name: Log in to registry
uses: https://github.com/docker/login-action@184bdaa0721073962dff0199f1fb9940f07167d1 # v3.5.0 uses: https://github.com/docker/login-action@184bdaa0721073962dff0199f1fb9940f07167d1 # v3.5.0
with: with:
+1
View File
@@ -21,6 +21,7 @@ data/*
.deployment-backups/ .deployment-backups/
*.sh *.sh
!tools/ci/test-postgres.sh !tools/ci/test-postgres.sh
!tools/ci/test-mysql.sh
assets/editor/node_modules/ assets/editor/node_modules/
assets/city-generator/node_modules/ assets/city-generator/node_modules/
assets/excalidraw-viewer/node_modules/ assets/excalidraw-viewer/node_modules/
+2 -2
View File
@@ -68,7 +68,7 @@ func testMySQLSchemaCommand(t *testing.T, component string) {
if component == "namespace" { if component == "namespace" {
pending = `"pending":3` pending = `"pending":3`
} else if component == "identity" { } else if component == "identity" {
pending = `"pending":5` pending = `"pending":6`
} }
if e = run("status"); e != nil || !strings.Contains(out.String(), pending) { if e = run("status"); e != nil || !strings.Contains(out.String(), pending) {
t.Fatal(out.String(), e) t.Fatal(out.String(), e)
@@ -95,7 +95,7 @@ func testMySQLSchemaCommand(t *testing.T, component string) {
if component == "namespace" { if component == "namespace" {
ledger, version = "store-namespaces", 1 ledger, version = "store-namespaces", 1
} else if component == "identity" { } 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 { 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) t.Fatal(e)
+179
View File
@@ -0,0 +1,179 @@
# pages-cli:アカウント照会・明示的空フォルダの契約
2026-12-01。pages-cli 0.7.0(申告commit `c92531a`)からの相談に対するサーバー側回答。
独立CLIのコードは本作業では変更しない。旧APIや管理HTMLへの自動fallbackは不要・禁止。
## 状態
| 項目 | 状態 |
| --- | --- |
| `GET /_/api/v1/auth/whoami` | サーバー実装・隔離試験済み。本番未反映 |
| `GET /_/api/v1/auth/sessions` | 同上 |
| `GET /_/api/v1/auth/sessions/history` | 同上 |
| 任意ユーザーの`whois?username=` | 未実装。自己照会APIへusernameを付けて代用しない |
| 明示的フォルダAPI/一覧統合 | 下記の設計案。まだ利用可能なAPIではない |
## 認証照会API(実装契約)
3本ともGETのみ。Bearerまたは既存ブラウザーsessionを要求し、Domainの認可モードが
legacyでも未認証は401。失効・期限切れ・停止されたアカウントは認証できない。
Domainは接続先Hostから決まり、クエリで他Domainへ切り替えない。
全応答はJSON、`Cache-Control: private, no-store`。token、token_hash、password hash、
provider secret、認証challengeは返さない。ログイン画面へのリダイレクトも行わない。
### whoami
クエリ指定は受け付けない。自己のemailは返す。`roles`と`groups`は名前の文字列配列。
groupsは「閲覧できるグループ一覧」ではなく、現在のDomainでの有効な所属グループだけ。
role/grantの完全な権限一覧ではなく、クライアント側で操作の可否を断定する材料にしない。
各配列は100件を上限とし、超過時は`memberships_truncated: true`。
```json
{
"principal_uuid": "...",
"username": "anya",
"display_name": "Anya",
"email": "anya@example.test",
"state": "active",
"roles": ["owner"],
"groups": ["campus_admin", "domain_admin"],
"memberships_truncated": false,
"session": {
"uuid": "...",
"auth_time_ms": 1796080000000,
"last_seen_at_ms": 1796080000000,
"expires_at_ms": 1796166400000,
"mfa_level": 1
}
}
```
usernameは既存のローカルidentity解決と同じ。該当identityがなければprincipal UUIDへfallbackする。
任意ユーザー照会は、非公開所属・emailの開示方針を分離して後続実装する。
### sessions / sessions/history
両者とも`scope=self`が既定。`scope=domain`は接続Domainのbuilt-in `domain_admin`判定が
通る場合のみ。既存のアカウント管理UIと同じ境界とし、単に`manage`というPath権限を
持つだけでは全員のセッションを列挙できない。Campus管理者も有効な継承結果に従う。
- `sessions`:未失効かつ期限内の行。既定limit=100。
- `sessions/history`:保持されている全状態の行。既定limit=20。
- 両方とも`limit=1..100`。101件目までDBから読み、超過を`truncated`で通知する。
- 順序は`auth_time_ms DESC, uuid DESC`。同時刻でも順序を安定させる。
- 現版は最近の上限件数を返すAPIであり、カーソル/全履歴exportは未実装。
- 空結果は`"sessions": []`。`truncated`は両方のAPIで必ず返す。
- 不明なクエリ、重複したscope/limit、不正なlimitは400。
```json
{
"sessions": [{
"uuid": "...",
"principal_uuid": "...",
"username": "anya",
"display_name": "Anya",
"auth_time_ms": 1796080000000,
"last_seen_at_ms": 1796080000000,
"expires_at_ms": 1796166400000,
"revoked_at_ms": 0,
"mfa_level": 1,
"status": "active",
"is_current": true
}],
"truncated": false
}
```
応答項目は共通。statusは`revoked_at_ms != 0`なら`revoked`、それ以外で期限切れなら
`expired`、残りが`active`。`is_current`はこのHTTPリクエストで認証されたセッションUUIDとの比較。
emailはsession一覧には含めない。
### 履歴・オンライン表示の限界
これは**auth_sessionsの保持行の照会であり、追記型の監査ログではない**。
失効は同じ行の状態更新。行が削除された後の履歴を復元しない。
`auth_time_ms`は既存sessionの認証時刻で、CLI委譲時にブラウザー側の時刻を引き継ぐこともある。
`last_seen_at_ms`は保存されている値を返すだけで、API呼び出しによるheartbeat更新はしない。
CLIはこれを「今オンライン」「実際の最終操作時刻」と断定しない。
### エラーと受入
JSONの`error`は固定コード:401 `authentication_required`、403 `domain_admin_required`、
400 `invalid_query` / `invalid_scope` / `invalid_limit`、405 `method_not_allowed`、
照会失敗は503 `auth_query_unavailable`。DBエラーの詳細を返さない。
404/405/501は未対応サーバーとして扱い、HTML解析や旧エンドポイント探索をしない。
401は未対応ではなく、再認証が必要な状態として区別する。
`TestAuthQueryAPI`はHTTP認証、legacy/enforcing、秘密値非出力、method閉鎖、scope、上限を検証。
`TestAccountBackendAuthQueries`はSQLite/PostgreSQL 17/MySQL 8.4で状態分類、Domain分離、
現在session、所属とtruncatedを検証。MySQL本体起動を提供するものではない。
両試験を3DBで`-race -count=3`実行して成功。全Goテストとstore/serverのvetも成功。
全体試験はhttptestのlocalhost待受が必要なため、その権限を許可して実行した。
## 明示的空フォルダ(設計案・未実装)
### モデルと共存
Pageや空のHTML文書を作るのではなく、Domain内のPathにフォルダ予約を保持する。
仮の論理schemaは`path_folders(domain_uuid, path, uuid, version, created_at_ms)`。
`(domain_uuid,path)`はunique。UUID/versionは予約の識別と強いETagに使う。
Page/Object/RevisionのUUIDとして解決しない。migrationはDB別に管理する。
- `/a`の明示フォルダとPage `/a`は排他。既存Pageをフォルダへ変換しない。
- `/a`の明示フォルダとPage `/a/b`は共存。最初の子Page作成で予約を消さない。
- 最後の子を消しても明示フォルダは残る。仮想フォルダだけなら現在どおり消える。
- 既存の仮想フォルダに予約を追加することは許す。同一PathのPageがある場合は許さない。
- 親Pathを逐次明示登録することは必須にしない。省略された親は仮想フォルダとして見える。
CLIの`--parents`は、親も空になった後に残したい場合の明示予約に使える。
- 同じ名前のPageと予約の二重作成を防ぐため、別tableのunique制約だけでは不十分。
Page作成・bind・import・rename・folder作成を同一のDomain Path排他で直列化する。
### HTTP案
`PUT /_/api/v1/folders/path:/parent/name`、本文なし、`If-None-Match: *`必須。
先に認証・Pathの構文を検査し、対象Pathへのcreate権限を存在照会前に評価する。
未認証401、構文不正400、権限不足403、条件欠落428、既存Page/予約との競合412。
成功は201、`{"path":"/parent/name","kind":"folder","explicit":true}`、強いETagとLocation。
権限不足の応答から既存Pathの有無を区別しない。権限は既存の上位Path継承を維持する。
追加提案:`GET/HEAD`で明示予約のmetadataとETagを取得可能にする。
`DELETE`はdelete権限を先に確認し、**単一の強い`If-Match`を必須**にする。
欠落428、世代不一致412、配下にPageまたは予約があれば409、成功204。
これにより、削除・再作成された同名フォルダを古い操作で消す事故を防ぐ。
DELETEは再帰削除に拡張せず、再帰操作は既存のsnapshot確認経路へ統合する。
この条件付き削除/metadata取得はCLI側へ申し送りする追加提案で、まだ確定実装ではない。
PathはHTTPで一度だけpercent decodeしたUTF-8 semantic pathを検査する。
ルート、`.` / `..` segment、制御文字、不正UTF-8、二重slashや末尾slashなどの
非canonical入力、制御用予約namespace、`uuid:` / `rev:`等の別アドレス形式は400。
不正入力を`path.Clean`や二度目のunescapeで別Pathへ変換しない。
予約範囲は既存ルーターの表と共有し、`/u/{username}`等の専用namespaceはその専用権限契約に従う。
### 一覧と非開示
`path-picker`の通常一覧と`mode=children`の両方でPathと予約をSQL段階で統合・重複排除する。
`kind: "folder"`に`explicit: true`を追加。通常の仮想フォルダとの混在を許す。
可視性はrequestのread権限を通し、子の名前・件数から非公開Pageを漏らさない。
`empty`の厳密値は不可視の子の存在を漏らすため初版では一覧に返さない。
空かどうかの最終判断はdelete権限を確認したrmdir transaction内で行う。
ETagはGET/HEADから取得し、閲覧者一覧に変更用metadataを過剰付与しない。
### 公開前に必須の接続作業
1. SQLite/PostgreSQLで予約schema・版管理・backup/importを追加。MySQLはmetadata移植と統合する。
2. `store/paths.go`と`metadata.Repository.CreatePage/BindPath`の全書込を予約競合と同じ排他へ統合。
3. `path_mutation.go` / `path_snapshot.go`へ予約を含め、再帰rename・削除・競合previewを原子的にする。
Folderだけの階層も対象とし、旧snapshotは新しい予約の追加を検出して拒否する。
4. browser、path completion、tree、children、仮想フォルダviewer、Cityへの扱いを整合。
予約だけでPage数を増やさず、Pathキャッシュ無効化とoutboxを同時に接続する。
5. create-vs-Page、rmdir-vs-child作成、rename-vs-予約の同時実行、ABA、Domain分離、
不可視子、Unicode/`%`/`_`/大文字小文字、rollback、移行・復旧を実DBで検証。
6. 上記の後にHTTP APIを有効化。骨子だけの段階で成功201を返さない。
現状はPage作成のSQLite/PostgreSQL経路と、snapshot付きPath操作が別れているため、
フォルダAPIだけを先行公開しない。フォルダの設計・実装状態は`CLI-FOLDER-01`で追跡する。
なお、提案中の子Page作成先`PUT /_/api/v1/pages/path:...`も、この時点のサーバーには
登録されていない。既存のcreate/save/bind実装がこのURIの対応を意味するわけではない。
以前の新規作成PUT契約への接続を別途完了し、予約競合を同じtransactionで検査する必要がある。
CLIはこの入口も未対応扱いを維持し、エディタGETやHTML解析へfallbackしない。
+24 -7
View File
@@ -1,6 +1,6 @@
# SQLite依存の縮小とPostgreSQL/MySQL対応 # SQLite依存の縮小とPostgreSQL/MySQL対応
2026-11-30更新。既存PostgreSQL対応を維持し、新規ML機能からMySQL対応を検証する。 2026-12-01更新。既存PostgreSQL対応を維持し、新規ML機能からMySQL対応を検証する。
SQL文字列をdriverで置換する方式や、未対応時のSQLite自動fallbackは採用しない。 SQL文字列をdriverで置換する方式や、未対応時のSQLite自動fallbackは採用しない。
既存本番DBの切替・実データ移行は本作業と分離する。 既存本番DBの切替・実データ移行は本作業と分離する。
@@ -13,7 +13,7 @@ SQL文字列をdriverで置換する方式や、未対応時のSQLite自動fallb
| ML予算schema | 明示migration | 明示migration | native migration、版/checksum台帳、検査・明示再開CLI。実DB試験済み、本番未適用 | | ML予算schema | 明示migration | 明示migration | native migration、版/checksum台帳、検査・明示再開CLI。実DB試験済み、本番未適用 |
| Campus/Domain/設定 | 既存 | 既存 | DB-COREa+b:Campus作成・更新、ホスト解決、設定、standalone Campus内のlocal Domain作成・更新。Domain/Campus削除は未対応 | | Campus/Domain/設定 | 既存 | 既存 | DB-COREa+b:Campus作成・更新、ホスト解決、設定、standalone Campus内のlocal Domain作成・更新。Domain/Campus削除は未対応 |
| ユーザー/グループ | 既存 | 既存 | パスワードアカウント、所属、group/permission、管理者継承・失効の限定保存API。HTTP認証・完全な認可境界は未接続 | | ユーザー/グループ | 既存 | 既存 | パスワードアカウント、所属、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起動は拒否 | 設計・実装未着手 | | DBバックアップ/DR | 既存SQLite方式 | native backup、現行DR起動は拒否 | 設計・実装未着手 |
MySQL接続を`internal/db/mysql.go`に追加。既定は検証付きTLSのみ、秘密情報を含むdriverエラーや MySQL接続を`internal/db/mysql.go`に追加。既定は検証付きTLSのみ、秘密情報を含むdriverエラーや
@@ -34,7 +34,7 @@ Domain変更は`MySQLIdentityRepository`で、built-in group/管理者継承
`MySQLIdentityRepository`は保存APIであり、呼出元が認証・認可する必要がある。 `MySQLIdentityRepository`は保存APIであり、呼出元が認証・認可する必要がある。
権限評価の下位primitiveを完全なAuthorizeの代用として公開しない。 権限評価の下位primitiveを完全なAuthorizeの代用として公開しない。
OIDC/LDAP/SMTP設定とsecret保持、外部ID紐付け、challenge、TOTP、profile/avatarの保存処理は OIDC/LDAP/SMTP設定とsecret保持、外部ID紐付け、challenge、TOTP、profile/avatarの保存処理は
MySQLにも移植したが、HTTPサーバーや実providerとは未接続。CLI認証handoff、監査、 MySQLにも移植したが、HTTPサーバーや実providerとは未接続。CLI認証handoffの保存処理も移植済み。監査、
locality/publication policyまで含む完全な認可境界は未移植。 locality/publication policyまで含む完全な認可境界は未移植。
パスワード照合・session purpose/Domain分離・失効のprimitiveは実DB試験済みだが、 パスワード照合・session purpose/Domain分離・失効のprimitiveは実DB試験済みだが、
MySQLで本体ログイン画面が使えることを意味しない。 MySQLで本体ログイン画面が使えることを意味しない。
@@ -80,7 +80,7 @@ MySQLで本体ログイン画面が使えることを意味しない。
**DB-COREb基盤実装済み**:principal/membership/built-in group、管理者継承、local Domain書込。 **DB-COREb基盤実装済み**:principal/membership/built-in group、管理者継承、local Domain書込。
次はDB-COREcで文書metadata・Revision・Pathを移植する。 次はDB-COREcで文書metadata・Revision・Pathを移植する。
COREbの認証保存処理(外部ID/provider・MFA・profile)とsession管理は移植済み。 COREbの認証保存処理(外部ID/provider・MFA・profile)とsession管理は移植済み。
残件(CLI認証handoff・完全な認可snapshot・監査・group編集・認証/管理UI接続)も本体接続前に消化する。 残件(完全な認可snapshot・監査・group編集・認証/管理UI接続)も本体接続前に消化する。
部分対応を本体対応と混同しない。 部分対応を本体対応と混同しない。
4. **DB-JOBS**:activity outbox/イベントキュー/claim/lease/ログ保持を移植。 4. **DB-JOBS**:activity outbox/イベントキュー/claim/lease/ログ保持を移植。
ワーカーの再起動・同時claim・timeout・receipt保持を確認してからML workerを接続する。 ワーカーの再起動・同時claim・timeout・receipt保持を確認してからML workerを接続する。
@@ -102,8 +102,7 @@ MySQL enumを増やしただけで全体対応を宣言せず、各repositoryの
2026-11-30コミット整理時にも、使い捨てのMySQL 8.4/PostgreSQL 17とSQLiteで 2026-11-30コミット整理時にも、使い捨てのMySQL 8.4/PostgreSQL 17とSQLiteで
下記のnamespace・identity・ML・migration契約を`-race -count=1`で再検証した。 下記のnamespace・identity・ML・migration契約を`-race -count=1`で再検証した。
`TestAccountBackend*`のCLI handoffは引き続きSQLite/PostgreSQLのみであり、 この時点では`TestAccountBackend*`のCLI handoffはSQLite/PostgreSQLのみ(12月1日の追加は下記)。Goクライアント/設定APIの回帰と
MySQL対応済みの範囲には含めない。Goクライアント/設定APIの回帰と
`go vet ./internal/db ./internal/machinelearning ./internal/store ./cmd/pageswiki`も成功。 `go vet ./internal/db ./internal/machinelearning ./internal/store ./cmd/pageswiki`も成功。
全パッケージの全テスト、本番切替、MySQLでのHTTPサーバー起動確認を意味しない。 全パッケージの全テスト、本番切替、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文字。 寸法:UUID 36、identity issuer/subject・credential identifier 255、permission scope Path/grant target 512文字。
既存データのimportは未対応で、上限を超える値を切り詰めて取り込まない。 既存データのimportは未対応で、上限を超える値を切り詰めて取り込まない。
COREcで文書Pathの最大長とpermission scope/grant targetの上限を整合させる。 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は後続。 完全な認可snapshot、Domain削除・federation・backupは後続。
Domain削除は文書・拡張機能の関連データ移植後に扱い、未対応tableを残した部分削除はしない。 Domain削除は文書・拡張機能の関連データ移植後に扱い、未対応tableを残した部分削除はしない。
公開前にこれらと文書metadataを接続する。 公開前にこれらと文書metadataを接続する。
@@ -217,3 +216,21 @@ session Domain分離を検証する。実OIDC/LDAP/SMTPへの接続や既存ユ
2026-11-30の追加試験:上記4本と`TestMySQLIdentity*`/schema CLIを、SQLite・PostgreSQL 17・ 2026-11-30の追加試験:上記4本と`TestMySQLIdentity*`/schema CLIを、SQLite・PostgreSQL 17・
MySQL 8.4で`-race -count=3`実行し成功。既存HTTPログイン・LDAP/OIDC設定・trusted session・ MySQL 8.4で`-race -count=3`実行し成功。既存HTTPログイン・LDAP/OIDC設定・trusted session・
CLI OIDCの回帰試験も成功。本体MySQL受入や外部サービス接続の成功を意味しない。 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`も成功。
以後の退行検出用に`tools/ci/test-mysql.sh`をイメージ公開前のCIへ追加。
同スクリプトも隔離MySQL 8.4で実行成功。PostgreSQLは既存の別ゲートで全体試験し、
MySQLゲートでは実装済みpilot契約だけを対象にする。
+9 -1
View File
@@ -8,6 +8,11 @@ RSS-01はその後の内蔵reader・FreshRSS読取・共通UI実装まで個別
## 調査範囲と状態の読み方 ## 調査範囲と状態の読み方
2026-12-01 CLI連携追加:`CLI-AUTH-01`はwhoami/sessions/historyのJSON APIを実装・隔離試験済み、
本番未反映。`CLI-FOLDER-01`は明示予約モデルの設計段階。Page作成との共通排他、
再帰rename/削除snapshot、一覧/キャッシュ、DB移行を接続してから公開する。
[契約とCLIへの申し送り](cli-account-and-folders.md)を参照。
日本語設計書、原ロードマップ、実装記録と、対応するstore/HTTP handler/テストを静的照合した。 日本語設計書、原ロードマップ、実装記録と、対応するstore/HTTP handler/テストを静的照合した。
全エンドポイントの再監査や本番の再試験ではない。実データ、外部カレンダー、メールボックスには 全エンドポイントの再監査や本番の再試験ではない。実データ、外部カレンダー、メールボックスには
アクセスしていない。独立した `anya/pages-cli` の現行HEAD・配布バイナリも今回の照合対象外。 アクセスしていない。独立した `anya/pages-cli` の現行HEAD・配布バイナリも今回の照合対象外。
@@ -61,7 +66,10 @@ DB-MIGの基盤(版/checksum台帳、operation journal、専用connection lo
続いてCOREbのprovider設定・暗号化secret保持・外部ID紐付け・challenge・TOTP・profile/avatar保存を移植。 続いてCOREbのprovider設定・暗号化secret保持・外部ID紐付け・challenge・TOTP・profile/avatar保存を移植。
Domain別session一覧・失効を限定APIへ接続。auth schema版2を追加し、版1の履歴とデータを保持する。 Domain別session一覧・失効を限定APIへ接続。auth schema版2を追加し、版1の履歴とデータを保持する。
MySQLのUPDATE代入順によるTOTP失敗回数の差も修正し、3DB共通の5回制限を試験する。 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削除は関連文書・拡張データを含めた移植後に行う。 管理UI接続、Domain削除・federationも残る。Domain削除は関連文書・拡張データを含めた移植後に行う。
保存pilotをHTTP認証サーバーとして公開しない。 保存pilotをHTTP認証サーバーとして公開しない。
ML後続はこの境界と整合させ、MySQL本体対応を宣言するのはDB-APP通過後とする。 ML後続はこの境界と整合させ、MySQL本体対応を宣言するのはDB-APP通過後とする。
+4
View File
@@ -1,5 +1,9 @@
# pages-cli:`pages` HTTPクライアント # pages-cli:`pages` HTTPクライアント
2026-12-01:独立CLI 0.7.0からの`whois / w / last / mkdir`相談への
[照会API・明示的フォルダ契約](cli-account-and-folders.md)を追加。
自己・session照会の3 APIは実装試験済み、本番未反映。明示的フォルダは設計段階。
2026-11-06:利用者向けの[クライアント契約](https://git.anya.jp/anya/pages-cli/src/branch/main/docs/client-contract.md)と[NeoMutt連携](https://git.anya.jp/anya/pages-cli/src/branch/main/docs/neomutt.md)は独立した公開pages-cliリポジトリへ移転した。本書はサーバー側のHTTP・OIDC認証契約、結合テストと導入履歴を保持する。下記のv0.3.0/v0.4.0は分離前のサーバー同梱版の番号であり、独立CLIはv0.1.0から採番する。 2026-11-06:利用者向けの[クライアント契約](https://git.anya.jp/anya/pages-cli/src/branch/main/docs/client-contract.md)と[NeoMutt連携](https://git.anya.jp/anya/pages-cli/src/branch/main/docs/neomutt.md)は独立した公開pages-cliリポジトリへ移転した。本書はサーバー側のHTTP・OIDC認証契約、結合テストと導入履歴を保持する。下記のv0.3.0/v0.4.0は分離前のサーバー同梱版の番号であり、独立CLIはv0.1.0から採番する。
2026-11-08整理:以下のPython実装・Windows未対応・TLSバイパスなし等の記述と末尾の 2026-11-08整理:以下のPython実装・Windows未対応・TLSバイパスなし等の記述と末尾の
+6
View File
@@ -31,6 +31,12 @@ Page UUIDs, Revisions, and projections remain separate.
## Rules ## Rules
Read-only account/session JSON is exposed at `/_/api/v1/auth/whoami`,
`/_/api/v1/auth/sessions`, and `/_/api/v1/auth/sessions/history`.
Explicit folder reservations under `/_/api/v1/folders/path:...` are designed,
not implemented. See the [CLI account and folder contract](ja/cli-account-and-folders.md)
for scope, privacy, and activation gates.
Task CalDAV uses `/_/api/v1/caldav/tasks/` (private home/principal), Task CalDAV uses `/_/api/v1/caldav/tasks/` (private home/principal),
`/_/api/v1/caldav/tasks/default/` (fixed VTODO collection) and `/_/api/v1/caldav/tasks/default/` (fixed VTODO collection) and
`/_/api/v1/caldav/tasks/default/{name}.ics` (resource). These are not Wiki Paths `/_/api/v1/caldav/tasks/default/{name}.ics` (resource). These are not Wiki Paths
+6
View File
@@ -23,6 +23,12 @@ Kroki、Mermaid、code-server は upstream の配布イメージを使用する
3 回の push は原子的ではないため、**ワークフロー全体の成功を確認してから利用**する。 3 回の push は原子的ではないため、**ワークフロー全体の成功を確認してから利用**する。
最後に当該ジョブのローカル CI タグと専用 builder を後処理する。 最後に当該ジョブのローカル CI タグと専用 builder を後処理する。
v0.19.0後のmainでは、PostgreSQL 17の全体試験に加え、`tools/ci/test-mysql.sh`で
MySQL 8.4の移植済みpilot契約を公開前に検証する。合成データ専用コンテナを使い、
ポート公開・新規サブネット・本番DSNは使わない。接続に失敗した場合はSKIPせず失敗する。
MySQLの全機能対応や本体起動の受入を示すゲートではなく、ML予算・migration・名前空間・
identity/CLI認証の移植済み範囲の退行を防ぐためのもの。
## runner 環境(初回・環境変更時のみ) ## runner 環境(初回・環境変更時のみ)
`ubuntu-latest` は runner を選ぶラベルであり、ツールの存在を保証するものではない。 `ubuntu-latest` は runner を選ぶラベルであり、ツールの存在を保証するものではない。
+43 -1
View File
@@ -1,6 +1,8 @@
# PagesWiki v0.19.0 # PagesWiki v0.19.0
リリース対象:v0.18.0以降の実装整理。ビルド・タグ昇格・本番配備の結果は別途記録する。 2026-12-01 08:02 JST、本番配備完了。対象はv0.18.0以降の実装整理。
タグ対象は`cbcb8a24b43a15a6386b00fdbef70e3e6f5aa4f5`。
[Giteaリリース](https://git.anya.jp/anya/pages/releases/tag/v0.19.0)。
## 利用者向け変更 ## 利用者向け変更
@@ -30,3 +32,43 @@
RSSとスライドはPC・モバイルのChromium試験、MLは隔離環境の合成データ試験を実施。 RSSとスライドはPC・モバイルのChromium試験、MLは隔離環境の合成データ試験を実施。
リリース判定はGiteaの全Goテスト・PostgreSQL試験・4イメージ公開の成功後に行う。 リリース判定はGiteaの全Goテスト・PostgreSQL試験・4イメージ公開の成功後に行う。
任意のMLサービスとGecko relayは本番更新で起動しない。 任意のMLサービスとGecko relayは本番更新で起動しない。
## 配備結果
- 初回CI #99は`TestSchemaCommandCurrentApplicationDatabase`で失敗。未導入ML schemaの必須扱いを修正した。
- [CI #100](https://git.anya.jp/anya/pages/actions/runs/100):全Goテスト、PostgreSQL 17実DB全体試験、4イメージ公開まで成功。
- [リリース #101](https://git.anya.jp/anya/pages/actions/runs/101):SHAイメージを再ビルドせずv0.19.0へ昇格、成功。
- 本番のapp/adaptor-gateway/excalidraw-viewerを更新。全てOCI revisionがタグのcommitと一致。
- 本体とExcalidrawはhealthy、gatewayは稼働中(専用Docker healthcheckは未設定)。再起動回数0。
- ローカルと公開HTTPSの`/health`、公開トップ・ログイン画面が200。
配信された`slides.js`、`slides-frame.js`、`feeds.js`、`slides.css`はタグ内ファイルとバイト一致。
- 起動後の観測範囲でpanic/fatal、DB/schemaエラー、イベントジョブ失敗は0件。
認証済みユーザー本文・外部取り込みカレンダー要素は検証時に取得しない。
- 本番DBは既存SQLiteを維持。停止状態のapp2は起動せず、展示クラスタ・CLIリポジトリも変更しない。
- ローカルの`.env.release`をv0.19.0へ更新。以後の通常配備もregistry overlayを指定する。
| 配備イメージ | registry digest(sha256) |
| --- | --- |
| pageswiki-app | `52a7b89ba8b3e10a8bc4b095abe32aa15a8d8a4bc03bcfccde6b3eb8f0750baa` |
| pageswiki-adaptor-gateway | `353b39eb9ada98f3772587ad67ba7c86a3ef49c159cbb0b3fb2336268e6d7ac4` |
| pageswiki-excalidraw-viewer | `14d5a8b17736e0a466d9714332fd108b478398555380d8b16c6f188b292fadc3` |
## 保全と切戻し
ホストの`.deployment-backups/release-v0.19.0-20261201/`に設定、切替スクリプト、
旧イメージ用`rollback.yml`と`cutover/data/`を保全。リポジトリやイメージには含めない。
appとgatewayの停止後に最終rsyncを行い、checksum付き比較で差分なし、コピーDBの
`PRAGMA quick_check`で`ok`を確認してから起動した。旧バックアップの削除は行っていない。
旧稼働イメージ3個はそれぞれ`rollback-before-v0.19.0-20261201`タグで保持。
切戻しは同ディレクトリの`rollback.yml`を最後のCompose overlayとして使い、
app/adaptor-gateway/excalidraw-viewerだけを`--no-deps --no-build`で再作成する。
切替後に保存されたデータを失わないため、バックアップの上書き復元は自動実行しない。
## 本番リリースと分離した後続変更
`3e8a0b6`:MySQLのCLI認証handoff保存処理、失効・単回交換・発行上限の3DB試験。
`8f771b2`:MySQL 8.4 pilot契約のCIゲート追加。隔離環境でスクリプト実行も成功。
これらはv0.19.0タグには含めず、mainの次段階として保持する。
残件の優先順は[DB移植計画](../../design/ja/database-portability.md)と
[実装バックログ](../../design/ja/implementation-backlog.md)を参照。
+6
View File
@@ -284,6 +284,12 @@ func (s *Server) withAuthorization(next http.Handler) http.Handler {
// No process-wide principal/policy cache: revocation is observed by the // No process-wide principal/policy cache: revocation is observed by the
// next request. Read snapshots never authorize mutating store operations. // next request. Read snapshots never authorize mutating store operations.
r = cacheRequestDomain(withReadPolicyContext(r)) r = cacheRequestDomain(withReadPolicyContext(r))
// These read-only JSON handlers require a live session even in legacy
// mode; they also own method and domain-admin checks, without HTML redirects.
if authQueryRoute(r.URL.Path) {
next.ServeHTTP(w, r)
return
}
if r.URL.Path == "/g" || strings.HasPrefix(r.URL.Path, "/g/") { if r.URL.Path == "/g" || strings.HasPrefix(r.URL.Path, "/g/") {
next.ServeHTTP(w, r) next.ServeHTTP(w, r)
return return
+120
View File
@@ -0,0 +1,120 @@
package server
import (
"context"
"database/sql"
"encoding/json"
"errors"
"net/http"
"net/url"
"strconv"
"time"
)
func writeAuthQueryJSON(w http.ResponseWriter, status int, value any) {
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.Header().Set("Cache-Control", "private, no-store")
w.WriteHeader(status)
_ = json.NewEncoder(w).Encode(value)
}
func authQueryRoute(path string) bool {
switch path {
case "/_/api/v1/auth/whoami", "/_/api/v1/auth/sessions", "/_/api/v1/auth/sessions/history":
return true
}
return false
}
func (s *Server) registerAuthQueryRoutes() {
for _, path := range []string{"/_/api/v1/auth/whoami", "/_/api/v1/auth/sessions", "/_/api/v1/auth/sessions/history"} {
s.mux.HandleFunc(path, s.handleAuthQuery)
}
}
func (s *Server) handleAuthQuery(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Cache-Control", "private, no-store")
w.Header().Set("X-Content-Type-Options", "nosniff")
if r.Method != http.MethodGet {
w.Header().Set("Allow", "GET")
writeAuthQueryJSON(w, 405, map[string]string{"error": "method_not_allowed"})
return
}
p := s.requestPrincipal(r)
if p == nil {
writeAuthQueryJSON(w, 401, map[string]string{"error": "authentication_required"})
return
}
domain := s.domainUUIDForRequest(r)
ctx, cancel := context.WithTimeout(r.Context(), 3*time.Second)
defer cancel()
current, err := s.store.CurrentAuthSession(ctx, domain, p.UUID, s.authTokenFromRequest(r))
if err != nil {
if errors.Is(err, sql.ErrNoRows) {
writeAuthQueryJSON(w, 401, map[string]string{"error": "authentication_required"})
} else {
writeAuthQueryJSON(w, 503, map[string]string{"error": "auth_query_unavailable"})
}
return
}
query, err := url.ParseQuery(r.URL.RawQuery)
if err != nil {
writeAuthQueryJSON(w, 400, map[string]string{"error": "invalid_query"})
return
}
if r.URL.Path == "/_/api/v1/auth/whoami" {
if len(query) != 0 {
writeAuthQueryJSON(w, 400, map[string]string{"error": "invalid_query"})
return
}
roles, groups, truncated, e := s.store.AuthMembershipNames(ctx, domain, p.UUID)
if e != nil {
writeAuthQueryJSON(w, 503, map[string]string{"error": "auth_query_unavailable"})
return
}
writeAuthQueryJSON(w, 200, map[string]any{
"principal_uuid": p.UUID, "username": p.Username, "display_name": p.DisplayName, "email": p.Email, "state": p.State,
"roles": roles, "groups": groups, "memberships_truncated": truncated,
"session": map[string]any{"uuid": current.UUID, "auth_time_ms": current.AuthTimeMS, "last_seen_at_ms": current.LastSeenAtMS, "expires_at_ms": current.ExpiresAtMS, "mfa_level": current.MFALevel},
})
return
}
for key, values := range query {
if (key != "scope" && key != "limit") || len(values) != 1 {
writeAuthQueryJSON(w, 400, map[string]string{"error": "invalid_query"})
return
}
}
scope := query.Get("scope")
principal := p.UUID
switch scope {
case "", "self":
case "domain":
if !s.store.IsBuiltinGroupAdmin(domain, p.UUID, "domain_admin") {
writeAuthQueryJSON(w, 403, map[string]string{"error": "domain_admin_required"})
return
}
principal = ""
default:
writeAuthQueryJSON(w, 400, map[string]string{"error": "invalid_scope"})
return
}
history := r.URL.Path == "/_/api/v1/auth/sessions/history"
limit := 100
if history {
limit = 20
}
if values, ok := query["limit"]; ok {
limit, err = strconv.Atoi(values[0])
if err != nil || limit < 1 || limit > 100 {
writeAuthQueryJSON(w, 400, map[string]string{"error": "invalid_limit"})
return
}
}
sessions, truncated, err := s.store.QueryAuthSessions(ctx, domain, principal, current.UUID, history, limit)
if err != nil {
writeAuthQueryJSON(w, 503, map[string]string{"error": "auth_query_unavailable"})
return
}
writeAuthQueryJSON(w, 200, map[string]any{"sessions": sessions, "truncated": truncated})
}
+112
View File
@@ -0,0 +1,112 @@
package server
import (
"encoding/json"
"net/http"
"strings"
"testing"
"pageswiki/internal/store"
)
func TestAuthQueryAPI(t *testing.T) {
s, owner, domain := configFixture(t)
s.registerAuthQueryRoutes()
member, err := s.store.CreatePasswordAccount(domain, "reader", "synthetic auth query password", "Reader", "reader@example.test")
if err != nil {
t.Fatal(err)
}
token, err := s.store.CreateAuthSession(domain, member.UUID)
if err != nil {
t.Fatal(err)
}
for _, mode := range []string{"enforcing", "legacy"} {
if err = s.store.SetConfigInDomain(domain, "authorization_mode", mode); err != nil {
t.Fatal(err)
}
for _, path := range []string{"whoami", "sessions", "sessions/history"} {
url := "/_/api/v1/auth/" + path
for _, bad := range []string{"", "invalid"} {
w := configRequest(s, bad, "GET", url, nil)
if w.Code != 401 || !strings.Contains(w.Body.String(), "authentication_required") {
t.Fatalf("%s %s: %d %s", mode, path, w.Code, w.Body.String())
}
}
w := configRequest(s, token, "GET", url, nil)
if w.Code != 200 || w.Header().Get("Cache-Control") != "private, no-store" || !strings.Contains(w.Header().Get("Content-Type"), "application/json") {
t.Fatalf("%s %s: %d %s", mode, path, w.Code, w.Body.String())
}
for _, secret := range []string{token, "token_hash", "secret_hash", "browser_hash", "password"} {
if strings.Contains(w.Body.String(), secret) {
t.Fatalf("secret field leaked: %s", secret)
}
}
w = configRequest(s, token, "POST", url, nil)
if w.Code != 405 || w.Header().Get("Allow") != "GET" {
t.Fatal("method not closed", w.Code)
}
}
}
w := configRequest(s, token, "GET", "/_/api/v1/auth/whoami", nil)
var self struct {
Principal string `json:"principal_uuid"`
Username string `json:"username"`
Email string `json:"email"`
Roles []string `json:"roles"`
Groups []string `json:"groups"`
Session struct {
UUID string `json:"uuid"`
} `json:"session"`
}
if err = json.Unmarshal(w.Body.Bytes(), &self); err != nil || self.Principal != member.UUID || self.Username != "reader" || self.Email != "reader@example.test" || self.Session.UUID == "" || self.Roles == nil || self.Groups == nil {
t.Fatal("invalid self", w.Body.String(), err)
}
for _, path := range []string{"sessions", "sessions/history"} {
url := "/_/api/v1/auth/" + path
w = configRequest(s, token, "GET", url+"?scope=domain", nil)
if w.Code != 403 {
t.Fatal("ordinary member domain enumeration", w.Code)
}
w = configRequest(s, owner, "GET", url+"?scope=domain", nil)
if w.Code != 200 || !strings.Contains(w.Body.String(), member.UUID) {
t.Fatal("admin list", w.Code, w.Body.String())
}
w = configRequest(s, token, "GET", url, nil)
var list struct {
Sessions []store.AuthSessionView `json:"sessions"`
}
if err = json.Unmarshal(w.Body.Bytes(), &list); err != nil || len(list.Sessions) != 1 || list.Sessions[0].PrincipalUUID != member.UUID || !list.Sessions[0].IsCurrent {
t.Fatal("self scope", w.Body.String(), err)
}
for _, query := range []string{"limit=0", "limit=101", "limit=-1", "limit=", "limit=wat", "limit=1&limit=2", "scope=outside", "username=reader", "scope=domain;limit=1"} {
w = configRequest(s, owner, "GET", url+"?"+query, nil)
if w.Code != 400 {
t.Fatal("invalid query accepted", query, w.Code)
}
}
}
s.store.ReadOnly = true
w = configRequest(s, token, "GET", "/_/api/v1/auth/whoami", nil)
if w.Code != 200 {
t.Fatal("read-only store must permit self inquiry", w.Code)
}
s.store.ReadOnly = false
if err = s.store.RevokeAuthSession(token); err != nil {
t.Fatal(err)
}
w = configRequest(s, token, "GET", "/_/api/v1/auth/whoami", nil)
if w.Code != http.StatusUnauthorized {
t.Fatal("revoked token accepted", w.Code)
}
token, err = s.store.CreateAuthSession(domain, member.UUID)
if err != nil {
t.Fatal(err)
}
if err = s.store.SetPrincipalState(domain, member.UUID, "suspended"); err != nil {
t.Fatal(err)
}
w = configRequest(s, token, "GET", "/_/api/v1/auth/sessions", nil)
if w.Code != 401 {
t.Fatal("suspended user admitted", w.Code)
}
}
+1
View File
@@ -245,6 +245,7 @@ func (s *Server) mustLoadTemplates() {
} }
func (s *Server) registerRoutes() { func (s *Server) registerRoutes() {
s.registerAuthQueryRoutes()
s.registerCalendarRoutes() s.registerCalendarRoutes()
s.registerTaskRoutes() s.registerTaskRoutes()
s.mux.HandleFunc("/_/auth/", s.handleAuth) s.mux.HandleFunc("/_/auth/", s.handleAuth)
+1 -1
View File
@@ -13,7 +13,7 @@ import (
) )
func TestAccountBackendCLIHandoff(t *testing.T) { 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) { t.Run(fmt.Sprint(b), func(t *testing.T) {
s, d := accountBackendStore(t, b) s, d := accountBackendStore(t, b)
p, err := s.BootstrapOwner(d, "owner", "synthetic password for backend tests", "", "") p, err := s.BootstrapOwner(d, "owner", "synthetic password for backend tests", "", "")
+52 -9
View File
@@ -44,7 +44,7 @@ type CLIAuthRequest struct {
Remember bool 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. // 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) { 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) 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 { if _, err := tx.ExecContext(ctx, `DELETE FROM auth_cli_requests WHERE expires_ms<`+s.sqlParam(1), now-5*60*1000); err != nil {
return err 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) 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 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`, 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() now := time.Now().UnixMilli()
var expectedCode string 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)+` 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) RETURNING code_hash`, id, domain, origin, hashAuthToken(browser), now).Scan(&expectedCode)
}
if err != nil { if err != nil {
return ErrAccessDenied return ErrAccessDenied
} }
@@ -192,7 +210,11 @@ func (s *Store) ExchangeCLIAuth(ctx context.Context, domain, origin, device, ver
now := time.Now().UnixMilli() now := time.Now().UnixMilli()
lifetime := s.AuthSessionLifetime(domain).Milliseconds() lifetime := s.AuthSessionLifetime(domain).Milliseconds()
trustedLifetime := s.LoginSessionLifetime(domain, true).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 { if err != nil {
return 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 { if _, err = tx.ExecContext(ctx, `SELECT pg_advisory_xact_lock(1885431653, 1853058931)`); err != nil {
return 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 id, state, browser string
var remember bool var remember bool
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 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') 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) 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) { if errors.Is(err, sql.ErrNoRows) {
var exists int 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) 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 token = "pw_api_" + raw
minimum, maximum := "min", "max" minimum, maximum := "min", "max"
if s.sqlBackend == storePostgreSQL { if s.sqlBackend != storeSQLite {
minimum, maximum = "LEAST", "GREATEST" minimum, maximum = "LEAST", "GREATEST"
} }
// A disabled user, removed membership or revoked browser cannot delegate. // 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) 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) 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 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' 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)+` 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) 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) { if errors.Is(err, sql.ErrNoRows) {
err = ErrAccessDenied err = ErrAccessDenied
} }
+91
View File
@@ -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)
}
})
}
})
}
}
+33
View File
@@ -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
}
+1 -1
View File
@@ -11,7 +11,7 @@ import (
// MUST authenticate and authorize every administrator mutation. It intentionally // MUST authenticate and authorize every administrator mutation. It intentionally
// exposes neither *Store nor grant-only checks as a complete authorization API. // 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. // 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 } type MySQLIdentityRepository struct{ store *Store }
func NewMySQLIdentityRepository(database *sql.DB) *MySQLIdentityRepository { func NewMySQLIdentityRepository(database *sql.DB) *MySQLIdentityRepository {
+11
View File
@@ -49,6 +49,17 @@ func mysqlAuthMigrations() []db.MySQLMigration {
// Inspect validates the latest contract only, since later versions may // Inspect validates the latest contract only, since later versions may
// replace older columns. This additive version must retain all v1 checks. // replace older columns. This additive version must retain all v1 checks.
steps[1].Assertions = append(append([]string{}, steps[0].Assertions...), steps[1].Assertions...) 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 return steps
} }
+16 -7
View File
@@ -4,6 +4,7 @@ import (
"context" "context"
"database/sql" "database/sql"
"errors" "errors"
"fmt"
"strings" "strings"
"testing" "testing"
@@ -206,7 +207,7 @@ func TestMySQLIdentitySchemaAndCancellation(t *testing.T) {
database := mysqlTestDatabase(t) database := mysqlTestDatabase(t)
r := NewMySQLIdentityRepository(database) r := NewMySQLIdentityRepository(database)
ctx := context.Background() 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) t.Fatal(status, e)
} }
if e := r.PrepareSchema(ctx); e != nil { if e := r.PrepareSchema(ctx); e != nil {
@@ -215,7 +216,7 @@ func TestMySQLIdentitySchemaAndCancellation(t *testing.T) {
if e := r.PrepareSchema(ctx); e != nil { if e := r.PrepareSchema(ctx); e != nil {
t.Fatal("repeat prepare", e) 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) t.Fatal(e)
} }
if e := r.PrepareSchema(ctx); !errors.Is(e, db.ErrMySQLMigrationDirty) { if e := r.PrepareSchema(ctx); !errors.Is(e, db.ErrMySQLMigrationDirty) {
@@ -256,37 +257,45 @@ func TestMySQLIdentitySchemaAndCancellation(t *testing.T) {
} }
func TestMySQLIdentitySchemaUpgradePreservesAccounts(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) database := mysqlTestDatabase(t)
ctx := context.Background() ctx := context.Background()
if err := NewMySQLNamespaceRepository(database).PrepareSchema(ctx); err != nil { if err := NewMySQLNamespaceRepository(database).PrepareSchema(ctx); err != nil {
t.Fatal(err) t.Fatal(err)
} }
plan := mysqlAuthMigrations() 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) t.Fatal(err)
} }
var before string 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) 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 { 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) t.Fatal(err)
} }
r := NewMySQLIdentityRepository(database) 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) t.Fatal(status, err)
} }
if err := r.PrepareSchema(ctx); err != nil { if err := r.PrepareSchema(ctx); err != nil {
t.Fatal(err) t.Fatal(err)
} }
var after, title string 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) t.Fatal("historical checksum changed", err)
} }
if err := database.QueryRow(`SELECT display_name FROM principals WHERE uuid='upgrade-user'`).Scan(&title); err != nil || title != "既存の利用者" { if err := database.QueryRow(`SELECT display_name FROM principals WHERE uuid='upgrade-user'`).Scan(&title); err != nil || title != "既存の利用者" {
t.Fatal("existing principal changed", err) 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) t.Fatal(status, err)
} }
if _, err := database.Exec(`ALTER TABLE auth_providers DROP INDEX uq_0`); err != nil { if _, err := database.Exec(`ALTER TABLE auth_providers DROP INDEX uq_0`); err != nil {
+123
View File
@@ -0,0 +1,123 @@
package store
import (
"context"
"fmt"
"time"
)
// AuthSessionView deliberately contains no credential or credential hash.
type AuthSessionView struct {
UUID string `json:"uuid"`
PrincipalUUID string `json:"principal_uuid"`
Username string `json:"username"`
DisplayName string `json:"display_name"`
AuthTimeMS int64 `json:"auth_time_ms"`
LastSeenAtMS int64 `json:"last_seen_at_ms"`
ExpiresAtMS int64 `json:"expires_at_ms"`
RevokedAtMS int64 `json:"revoked_at_ms"`
MFALevel int `json:"mfa_level"`
Status string `json:"status"`
IsCurrent bool `json:"is_current"`
}
func (s *Store) CurrentAuthSession(ctx context.Context, domain, principal, token string) (AuthSessionView, error) {
var v AuthSessionView
err := s.DB.QueryRowContext(ctx, `SELECT a.uuid,a.auth_time_ms,a.last_seen_at_ms,a.expires_at_ms,a.mfa_level
FROM auth_sessions a JOIN principals p ON p.uuid=a.principal_uuid
JOIN domain_memberships m ON m.domain_uuid=a.domain_uuid AND m.principal_uuid=p.uuid
WHERE a.domain_uuid=`+s.sqlParam(1)+` AND a.principal_uuid=`+s.sqlParam(2)+` AND a.token_hash=`+s.sqlParam(3)+`
AND a.revoked_at_ms=0 AND a.expires_at_ms>`+s.sqlParam(4)+` AND m.state='active' AND p.state IN ('active','readonly')`, domain, principal, hashAuthToken(token), time.Now().UnixMilli()).Scan(&v.UUID, &v.AuthTimeMS, &v.LastSeenAtMS, &v.ExpiresAtMS, &v.MFALevel)
return v, s.sqlError("current auth session", err)
}
// Callers must authorize domain-wide access before passing an empty principal.
// LIMIT + 1 bounds both the response and the database result, not just JSON.
func (s *Store) QueryAuthSessions(ctx context.Context, domain, principal, current string, history bool, limit int) ([]AuthSessionView, bool, error) {
if limit < 1 || limit > 100 {
return nil, false, ErrAccessDenied
}
args := []any{domain}
where := `a.domain_uuid=` + s.sqlParam(1)
if principal != "" {
args = append(args, principal)
where += ` AND a.principal_uuid=` + s.sqlParam(len(args))
}
now := time.Now().UnixMilli()
if !history {
args = append(args, now)
where += ` AND a.revoked_at_ms=0 AND a.expires_at_ms>` + s.sqlParam(len(args))
}
args = append(args, limit+1)
query := `SELECT a.uuid,a.principal_uuid,COALESCE((SELECT subject FROM principal_identities i WHERE i.principal_uuid=p.uuid AND i.provider_type='password' ORDER BY i.subject,i.uuid LIMIT 1),p.uuid),p.display_name,a.auth_time_ms,a.last_seen_at_ms,a.expires_at_ms,a.revoked_at_ms,a.mfa_level
FROM auth_sessions a JOIN principals p ON p.uuid=a.principal_uuid WHERE ` + where + ` ORDER BY a.auth_time_ms DESC,a.uuid DESC LIMIT ` + s.sqlParam(len(args))
rows, err := s.DB.QueryContext(ctx, query, args...)
if err != nil {
return nil, false, s.sqlError("query auth sessions", err)
}
defer rows.Close()
out := make([]AuthSessionView, 0, limit+1)
for rows.Next() {
var v AuthSessionView
if err = rows.Scan(&v.UUID, &v.PrincipalUUID, &v.Username, &v.DisplayName, &v.AuthTimeMS, &v.LastSeenAtMS, &v.ExpiresAtMS, &v.RevokedAtMS, &v.MFALevel); err != nil {
return nil, false, s.sqlError("scan auth sessions", err)
}
v.Status = "active"
if v.RevokedAtMS != 0 {
v.Status = "revoked"
} else if v.ExpiresAtMS <= now {
v.Status = "expired"
}
v.IsCurrent = v.UUID == current
out = append(out, v)
}
if err = rows.Err(); err != nil {
return nil, false, s.sqlError("query auth sessions", err)
}
truncated := len(out) > limit
if truncated {
out = out[:limit]
}
return out, truncated, nil
}
// Membership names, not a list of all groups visible to this principal.
// Results are bounded and truncation is explicit for unusually large accounts.
func (s *Store) AuthMembershipNames(ctx context.Context, domain, principal string) (roles, groups []string, truncated bool, err error) {
roles, groups = make([]string, 0), make([]string, 0)
queries := []string{
`SELECT DISTINCT r.name FROM auth_roles r JOIN auth_role_bindings b ON b.role_uuid=r.uuid JOIN domain_memberships m ON m.uuid=b.membership_uuid WHERE r.domain_uuid=%s AND m.domain_uuid=r.domain_uuid AND m.principal_uuid=%s AND m.state='active' ORDER BY r.name LIMIT 101`,
`SELECT DISTINCT g.name FROM ` + s.sqlGroupTable() + ` g JOIN group_members gm ON gm.group_uuid=g.uuid JOIN domain_memberships m ON m.uuid=gm.membership_uuid WHERE g.domain_uuid=%s AND m.domain_uuid=g.domain_uuid AND m.principal_uuid=%s AND m.state='active' AND g.state='active' ORDER BY g.name LIMIT 101`,
}
for i, query := range queries {
rows, e := s.DB.QueryContext(ctx, fmt.Sprintf(query, s.sqlParam(1), s.sqlParam(2)), domain, principal)
if e != nil {
return nil, nil, false, s.sqlError("auth memberships", e)
}
items := make([]string, 0)
for rows.Next() {
var name string
if e = rows.Scan(&name); e != nil {
break
}
items = append(items, name)
}
if e == nil {
e = rows.Err()
}
rows.Close()
if e != nil {
return nil, nil, false, s.sqlError("auth memberships", e)
}
if len(items) > 100 {
truncated = true
items = items[:100]
}
if i == 0 {
roles = items
} else {
groups = items
}
}
return
}
+84
View File
@@ -0,0 +1,84 @@
package store
import (
"context"
"fmt"
"testing"
"time"
)
func TestAccountBackendAuthQueries(t *testing.T) {
for _, backend := range []storeSQLBackend{storeSQLite, storePostgreSQL, storeMySQL} {
t.Run(fmt.Sprint(backend), func(t *testing.T) {
s, d := accountBackendStore(t, backend)
ctx := context.Background()
p, err := s.BootstrapOwner(d, "owner", "synthetic auth query password", "Owner", "")
if err != nil {
t.Fatal(err)
}
token, err := s.CreateAuthSession(d, p.UUID)
if err != nil {
t.Fatal(err)
}
current, err := s.CurrentAuthSession(ctx, d, p.UUID, token)
if err != nil || current.UUID == "" {
t.Fatal(current, err)
}
for _, kind := range []string{"expired", "revoked"} {
extra, e := s.CreateAuthSession(d, p.UUID)
if e != nil {
t.Fatal(e)
}
v, e := s.CurrentAuthSession(ctx, d, p.UUID, extra)
if e != nil {
t.Fatal(e)
}
if kind == "expired" {
_, e = s.DB.Exec(`UPDATE auth_sessions SET expires_at_ms=1 WHERE uuid=`+s.sqlParam(1), v.UUID)
} else {
e = s.RevokeAuthSession(extra)
}
if e != nil {
t.Fatal(e)
}
}
// A retained session in another domain must never appear in either scope.
_, err = s.DB.Exec(`INSERT INTO auth_sessions(uuid,token_hash,principal_uuid,domain_uuid,auth_time_ms,expires_at_ms,last_seen_at_ms,mfa_level) VALUES(`+s.sqlParam(1)+`,`+s.sqlParam(2)+`,`+s.sqlParam(3)+`,`+s.sqlParam(4)+`,1,`+s.sqlParam(5)+`,1,0)`, "foreign-session", "synthetic-foreign-hash", p.UUID, "foreign-domain", time.Now().Add(time.Hour).UnixMilli())
if err != nil {
t.Fatal(err)
}
for _, principal := range []string{p.UUID, ""} {
items, truncated, e := s.QueryAuthSessions(ctx, d, principal, current.UUID, false, 100)
if e != nil || truncated || len(items) != 1 || !items[0].IsCurrent || items[0].Status != "active" {
t.Fatal(items, truncated, e)
}
items, truncated, e = s.QueryAuthSessions(ctx, d, principal, current.UUID, true, 100)
if e != nil || truncated || len(items) != 3 {
t.Fatal(items, truncated, e)
}
statuses := map[string]int{}
for _, v := range items {
statuses[v.Status]++
}
if statuses["active"] != 1 || statuses["revoked"] != 1 || statuses["expired"] != 1 {
t.Fatal(statuses)
}
items, truncated, e = s.QueryAuthSessions(ctx, d, principal, current.UUID, true, 1)
if e != nil || !truncated || len(items) != 1 {
t.Fatal(items, truncated, e)
}
}
if _, e := s.CurrentAuthSession(ctx, "foreign-domain", p.UUID, token); e == nil {
t.Fatal("cross-domain current session")
}
roles, groups, truncated, e := s.AuthMembershipNames(ctx, d, p.UUID)
if e != nil || roles == nil || truncated || len(groups) < 2 {
t.Fatal(roles, groups, truncated, e)
}
roles, groups, _, e = s.AuthMembershipNames(ctx, "foreign-domain", p.UUID)
if e != nil || len(roles) != 0 || len(groups) != 0 {
t.Fatal("cross-domain memberships", e)
}
})
}
}
+1 -1
View File
@@ -23,7 +23,7 @@ func mysqlStoreError(operation string, err error) error {
if err == nil { if err == nil {
return 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) { if errors.Is(err, known) {
return known return known
} }
+41
View File
@@ -0,0 +1,41 @@
#!/usr/bin/env bash
set -euo pipefail
# Native MySQL pilot contracts only, never production data. Reuse a private
# network namespace rather than publishing a port or allocating a new subnet.
suffix="${GITHUB_RUN_ID:-local}-$$-${RANDOM}"
mysql="pageswiki-mysql-test-${suffix}"
tests="pageswiki-mysql-go-${suffix}"
test_image="pageswiki-mysql-test:${suffix}"
cleanup() {
docker rm -fv "$tests" "$mysql" >/dev/null 2>&1 || true
docker image rm "$test_image" >/dev/null 2>&1 || true
}
trap cleanup EXIT
docker build --target source --tag "$test_image" .
docker run --detach --name "$mysql" --network none \
--env MYSQL_ROOT_PASSWORD=pageswiki-synthetic-ci-only \
--env MYSQL_ROOT_HOST=127.0.0.1 \
"${PAGESWIKI_CI_MYSQL_IMAGE:-mysql:8.4}"
ready=false
for ((attempt=0; attempt<60; attempt++)); do
if docker exec --env MYSQL_PWD=pageswiki-synthetic-ci-only "$mysql" \
mysql --protocol=TCP --host=127.0.0.1 --user=root --execute='SELECT 1' >/dev/null 2>&1; then
ready=true
break
fi
sleep 1
done
if [[ "$ready" != true ]]; then
echo 'Synthetic MySQL did not become ready' >&2
exit 1
fi
docker run --rm --name "$tests" --network "container:$mysql" \
--tmpfs /test-tmp:rw,exec,size=2147483648 \
--env TMPDIR=/test-tmp --env GOTMPDIR=/tmp \
--env GOPROXY=off --env GOSUMDB=off \
--env PAGESWIKI_TEST_MYSQL_DSN='root:pageswiki-synthetic-ci-only@tcp(127.0.0.1:3306)/mysql' \
"$test_image" go test -p 1 ./internal/db ./internal/store ./cmd/pageswiki \
-run 'TestMySQL|TestMLBudget|TestMachineLearningPolicyPersistence|TestNamespaceCoreThreeBackendContract|TestStoreNamespaceBackendContract|TestDomainWriteBackend|TestAdminInheritanceBackend|TestGeneralGroupBackend|TestGroupPermissionBackend|TestRoleGrantBackend|TestPrincipalStateBackend|TestAccountBackend' \
-count=1 -v