feat(auth): add scoped JSON account and session queries for CLI clients
Build and publish container images / images (push) Successful in 18m18s
Build and publish container images / images (push) Successful in 18m18s
This commit is contained in:
1 parent
6f9752ea3a
commit
b650fe50d7
10 files changed
+640
No files matched your search
@@ -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しない。
|
||||||
@@ -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・配布バイナリも今回の照合対象外。
|
||||||
|
|||||||
@@ -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バイパスなし等の記述と末尾の
|
||||||
|
|||||||
@@ -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
|
||||||
|
|||||||
@@ -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
|
||||||
|
|||||||
@@ -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})
|
||||||
|
}
|
||||||
@@ -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)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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)
|
||||||
|
|||||||
@@ -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
|
||||||
|
}
|
||||||
@@ -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)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in new issue
Block a user