Add OIDC browser approval and PKCE session handoff for pages CLI
This commit is contained in:
1 parent
2af87b4f58
commit
d02116577a
18 files changed
+1397
-23
No files matched your search
@@ -26,7 +26,7 @@
|
||||
- [x] 共通ナビの◐からプリセットを選択、リロードせず切替。host限定Cookieに保持し、Domain既定に戻せる。登録済みテーマのみ許可。Domain設定/アカウントの全端末設定ではなくブラウザ上書き。失敗時は現在テーマを保持する。
|
||||
- [x] 絶対セッション期限:設定→セッション、5〜43200分、既定1440分。Domain単位で新規ブラウザ/APIログイン(OIDC/LDAPを含む)に適用。発行時にDBの期限を固定し、Cookie/APIのexpires_inにも反映。既存セッションの期限とCalDAVアプリパスワードは変更しない。管理者認可とサーバ側失効をfixture検証。
|
||||
- [ ] 無操作タイムアウトとアカウント別の短縮上書き:background pollingを人間の操作とみなさないactivity契約、再認証、既存セッションへの即時適用を別途設計する。
|
||||
- [x] 電話連絡先の初期実装(2026-11-01ローカル検証済み、本番未反映):本人編集、独立した公開範囲、表示用文字列と正規化した `tel:` リンク。公開は明示確認とプロフィール/ドメイン上限に従う。クリックなしで発信しない。
|
||||
- [x] 電話連絡先の初期実装(2026-11-01 v0.2.0本番反映済み):本人編集、独立した公開範囲、表示用文字列と正規化した `tel:` リンク。公開は明示確認とプロフィール/ドメイン上限に従う。クリックなしで発信しない。
|
||||
|
||||
### 4. Cityの表示名
|
||||
|
||||
@@ -37,9 +37,9 @@
|
||||
### 5. セッション付きCLI/TUI
|
||||
|
||||
- [x] HTTPクライアント初期版 `pages-cli`/コマンド `pages`(2026-11-01ホストのユーザーPATHへ配置済み。実ユーザログインは未実施):configureによる接続先・既定プロファイル・言語管理、パスワード/TOTP、Bearer保持・失効、ls/cd/cat/view/get、既存Page edit/put、Path補完、メモリ内履歴、検索候補、ブラウザ引き継ぎ。詳細と原設計整合は [遠隔CLI](remote-cli.md)。既存DB直アクセスCLIは変更しない。
|
||||
- [ ] 既存 `data/pageswiki-cli` を拡張する専用起動コマンドとセッション保持。履歴や資格情報に0600相当の保護と失効/ログアウトを設ける。
|
||||
- [x] 専用起動コマンドとセッション保持は独立HTTPクライアント `pages` として実装。既存 `data/pageswiki-cli` のDB直接操作とは分離し、資格情報に0600の保護と失効/ログアウトを設ける。
|
||||
- [ ] `Ctrl+P` のfuzzy検索と、ローカル `$EDITOR` 編集。現在版/ETagを保持してアップロード時の競合を検出し、上書き・差分・キャンセルを選べるようにする。
|
||||
- [ ] パスワード認証に加え、ターミナルにURLを表示するブラウザ認証(OIDC)。既存Web認証と同じ本人性/MFA制約を適用し、短命・単回の認可コード+PKCEやdevice-flow相当の仕様を検討する。URLや履歴に長期トークンを含めない。
|
||||
- [x] ターミナルにURLを表示するブラウザ認証(OIDC)。`pages login --oidc [--no-browser]`、S256、5分の単回grant、確認コード/CSRF/TOTP、失効再確認、poll・発行上限を実装。2026-11-01ソース検証済み、本番未反映。契約は[遠隔CLI](remote-cli.md)を参照。
|
||||
- [ ] ターミナル表示が難しい内容はブラウザに引き継ぐ。short linkは認証を迂回しない内部リンクとし、公開share link発行とは分離する。自動公開しない。
|
||||
|
||||
## チェックポイントと進捗
|
||||
@@ -93,9 +93,9 @@
|
||||
- 電話番号は3〜15桁、先頭の+、表示用の空白・ハイフン・括弧に限定。内線、URIパラメータ、サービスコード、制御文字、任意スキームを拒否。空欄保存は番号を消去してprivateに戻す。
|
||||
- JA/ENの説明・フォーム・保存後アンカーを追加。デスクトップ1440px/375pxで実ブラウザの入力・保存・telリンク・フォーム幅を検証。iPhoneの電話アプリ起動そのものは未検証。
|
||||
- store/HTTPで本人・匿名・他メンバー・管理者・越境・公開確認・公開撤回・競合・不正番号を検証。個人情報の本文を監査ログへ追加しない。CardDAV、住所録、複数番号、内線は後続。
|
||||
- **本番反映済みfix2にはこの機能を含めない。** 次回リリースでは追加componentの適用と、旧版への切り戻し条件を別途検証する。
|
||||
- fix2時点では未反映だったが、v0.2.0で追加componentの適用と切り戻し条件を検証し本番反映した。[リリース記録](../../operations/deployments/2026-11-01-v0.2.0.md)を参照。
|
||||
|
||||
### 新規DBの初期接続競合(後続修正、本番未反映)
|
||||
### 新規DBの初期接続競合(v0.2.0本番反映済み)
|
||||
|
||||
全体回帰で `TestSQLMigrationLedgerConcurrencyAndChecksum` がまれにSQLITE_BUSYとなることを確認。診断メッセージをmigration connection取得/BEGINに分け、2,000回の反復で接続取得段階の失敗を再現した。`sql.Open` がlazyのため、最初の並行接続でWALへの切替が競合していた。
|
||||
|
||||
@@ -123,7 +123,7 @@
|
||||
|
||||
現行 `data/pageswiki-cli` はSQLite/Document Storeへ直接アクセスする運用CLI。shell、補完、履歴、`$PAGER`/`$EDITOR` は既にあるが、Web認証を受けるリモートクライアントではない。Webユーザの認可をSQLite直アクセスへ継ぎ足さず、HTTP transportを持つ別コマンド(仮称 `pageswiki remote`)として段階導入する。
|
||||
|
||||
2026-11-01:試作名 `data/pageswiki-remote` から、ユーザ指定によりサブプロジェクト `pages-cli`/実行名 `pages` へ整理。`pages configure` と既定値により通常操作のprofile/lang引数を不要とした。以下は全体計画であり、Ctrl+P、OIDCハンドオフ、新規作成、強制上書きの対話選択、short linkは未実装。[初期版の範囲・制限・検証](remote-cli.md)を参照。
|
||||
2026-11-01:試作名 `data/pageswiki-remote` から、ユーザ指定によりサブプロジェクト `pages-cli`/実行名 `pages` へ整理。`pages configure` と既定値により通常操作のprofile/lang引数を不要とした。OIDCハンドオフは後続ソース実装・検証まで完了。本番反映、Ctrl+P、新規作成、強制上書きの対話選択、short linkは残件。[範囲・制限・検証](remote-cli.md)を参照。
|
||||
|
||||
1. パスワード+TOTPの既存JSONログイン、失効/logout、接続先・Principal・Domain別セッション保存。秘密情報はコマンド引数/履歴/ログへ出さず、保存先0700・資格情報0600相当、TLS検証必須。
|
||||
2. `ls/cd/view/get/edit` と現在Pathの保持。検索は認可付き・件数制限・キャンセル可能なAPIを使用し、`Ctrl+P` のfuzzy選択へ接続。端末の制御シーケンスは本文/タイトルから除去する。
|
||||
|
||||
@@ -13,7 +13,7 @@
|
||||
- 旧認証設計にはCookie中心の記載が残るが、実装済みのJSONログインはBearerセッションを発行する。CLIはこのフローを使用し、Web Cookieを抽出しない。
|
||||
- `data/pageswiki-cli` は信頼されたローカル運用ツールとして維持。遠隔版はサブプロジェクト `pages-cli`、実行名 `pages`(`pages-cli/pages`)とし、DB・Document Storeを直接開かない。
|
||||
|
||||
サーバAPI/DBスキーマの追加・変更はない。初期実装はPython 3.9以降の標準ライブラリで動作するUnix系クライアント(fcntl、readline使用)。Windowsネイティブ版は未対応。
|
||||
初期のパスワード版にはサーバAPI/DBスキーマの追加・変更はない。後続のOIDC引き継ぎでは下記のauthエンドポイントとmanaged component `cli-auth` v1を追加する。Python 3.9以降の標準ライブラリで動作するUnix系クライアント(fcntl、readline使用)。Windowsネイティブ版は未対応。
|
||||
|
||||
## 利用方法
|
||||
|
||||
@@ -69,6 +69,65 @@ TabはPath候補を取得し、上下キーは当該プロセス内の履歴を
|
||||
|
||||
一覧は既存の件数制限を維持し、truncatedを表示する。巨大な全階層を再帰取得しない。読み取りのRaw言語選択は既存サーバの候補選択に従うが、編集は指定言語のheadを必須とし、存在しない場合は拒否する。
|
||||
|
||||
## OIDCブラウザ引き継ぎ(2026-11-01実装、本番未反映)
|
||||
|
||||
`pages login --oidc` はブラウザを開き、`--no-browser` はURLだけを表示する。
|
||||
CLI側に受信ポートは不要で、SSH先から開始して別のPC/スマホで承認できる。
|
||||
接続先のOIDC設定・既存アカウントとの対応を再利用し、新たなprovider登録は不要。
|
||||
ユーザー名未指定なら認証結果をセッションに保存する。指定済みなら一致を検査し、
|
||||
不一致時は新セッションを失効させるリクエストを送って保存を止める。
|
||||
設定上のusernameと認証結果のusernameは別々に保持し、接続先・アカウントの手編集対策を維持する。
|
||||
|
||||
### プロトコル
|
||||
|
||||
[RFC 8628](https://datatracker.ietf.org/doc/html/rfc8628)の別端末承認・ポーリングの考え方と、
|
||||
[RFC 7636](https://www.rfc-editor.org/rfc/rfc7636)のS256照合を参照する。
|
||||
これはPagesWiki専用のsession handoffであり、汎用OAuth Device Authorization Serverの
|
||||
discovery/grant_type/client registrationへの完全準拠を標榜しない。
|
||||
|
||||
| 入口 | 用途 |
|
||||
| --- | --- |
|
||||
| POST `/_/auth/cli/start` | formの`code_challenge`、`code_challenge_method=S256`で開始 |
|
||||
| GET `/_/auth/cli/verify?request=...` | OIDCへの入口と、認証後の本人・接続先確認/承認フォーム |
|
||||
| GET `/_/auth/oidc?cli=...` | 既存のnonce・state・PKCE・署名検証を使うOIDCフロー |
|
||||
| POST `/_/auth/cli/verify` | browser session、CSRF、request、確認コード、必要ならTOTPで承認/拒否 |
|
||||
| POST `/_/auth/cli/token` | formの`device_code`、`code_verifier`を照合して単回交換 |
|
||||
|
||||
1. CLIは暗号学的乱数のverifierを生成し、そのSHA-256を送る。サーバは独立した256bitの
|
||||
public request ID/device codeと32bit確認コードを生成する。
|
||||
返却するverification URIは同一origin内の固定Path。CLIもPath形式を厳密に検査する。
|
||||
2. ブラウザは既存CookieがあってもOIDCフローを通る。新しいOIDC callbackで作られた
|
||||
browser sessionにリクエストを一度だけ束縛する。他ブラウザによる再束縛を拒否。
|
||||
3. callbackだけではCLIへ認証情報を渡さない。承認画面はterminalの確認コード入力を要求し、
|
||||
フォーム内にコードを埋め込まない。本人が開始した操作だけ承認するよう警告する。
|
||||
同一origin検査+browser tokenとrequestに束縛したCSRFを使用する。
|
||||
4. 登録済みローカルTOTPを検査し、使用済みTOTPの再利用も既存処理で拒否する。
|
||||
承認後に新たにTOTPが有効になった場合、未検証grantの交換を拒否する。
|
||||
5. CLIは5秒間隔でpoll。pendingのみ継続し、slow_downで間隔を5秒ずつ最大30秒へ増やす。
|
||||
拒否・失効・ネットワーク障害・交換応答の喪失では自動再送しない。
|
||||
6. grantの消費と専用`pw_api_`セッション発行を同じtransactionで確定する。
|
||||
Principal/Domain membership/承認元browser sessionの失効・期限を再検査する。
|
||||
セッションは既存の権限評価に従い、期限はDomain設定と承認元session期限の短い方。
|
||||
MFA levelを保持する。ブラウザCookieや外部provider tokenをCLIへ流用しない。
|
||||
|
||||
### 永続化・上限
|
||||
|
||||
- managed component `cli-auth` v1に短期状態を保存。既存authテーブルやURIは改名しない。
|
||||
- grantは5分で失効。確認失敗は最大5回、OIDC開始は1grantあたり3回まで。
|
||||
- 同一Domainで5分間に64件まで、全体の保持件数は4096件まで。発行前に作成10分超の行を削除する。
|
||||
上限判定は単一INSERT内で行い、並行発行で超過しない。長期履歴にはしない。
|
||||
- device code/確認コード/browser tokenはハッシュだけを保存。verifierはCLIのメモリだけ。
|
||||
新しいAPI Bearerの平文は既存0600セッションファイルだけに保存する。
|
||||
- 外向け応答はno-store、承認ページはno-referrer・frame禁止。Bearer・verifier・確認コードを
|
||||
URLに含めない。リクエスト本文をアクセスログへ記録しない運用を前提とする。
|
||||
- read-onlyインスタンスは発行・承認・交換しない。初期化は通常のmanaged schema手順に従う。
|
||||
v0.2.0へ戻す前には追加componentを含む互換性を確認し、schema履歴を削除して回避しない。
|
||||
|
||||
HTTP応答が失われた場合にセッションが発行済みの可能性は残る。平文BearerをDBへ保持して
|
||||
再配布する方式は採らず、利用者が設定画面で不要なセッションを失効する。
|
||||
Ctrl+C時は未交換grantを即時サーバ削除せず、5分の期限で失効させる。
|
||||
この上限は入口全体のDDoS対策ではない。reverse proxyでの一般的なリクエスト制限は別途必要。
|
||||
|
||||
## セキュリティと運用上の制限
|
||||
|
||||
- 遠隔はHTTPS必須、証明書検証を無効化するオプションなし。HTTPはlocalhost/127.0.0.1/::1の開発専用。
|
||||
@@ -82,14 +141,34 @@ TabはPath候補を取得し、上下キーは当該プロセス内の履歴を
|
||||
|
||||
Python unittest:origin制限、端末制御文字、別origin redirect遮断、非JSON/403/サイズ上限、TOTP、資格情報権限・symlink・並行実行拒否、authoring/CAS payload、ダウンロード上書き拒否、409時の原稿保全。
|
||||
|
||||
設定追加後は12件:既定値/複数接続切替/言語保存、一時上書き、設定表示からのトークン除外、セッション保持中の再接続先変更拒否、手編集での接続先不一致拒否も検査。HTTP統合試験では公開エントリーポイントのconfigure→login→引数省略のls/status/edit→logoutを通す。
|
||||
Python単体試験18件:既定値/複数接続切替/言語保存、一時上書き、設定表示からのトークン除外、接続先変更拒否、PKCE、poll間隔、URL検査、アカウント不一致、取消、通信断、username未指定でのsession保持、開始API未対応/OIDC無効時の診断を検査する。
|
||||
|
||||
Goの `TestRemoteCLIHTTPIntegration`:一時DBと本物のHTTPハンドラでログイン、一覧、編集状態、authoring変換、保存、古いRevision拒否、Rawハッシュ、immutable拒否、存在しない言語拒否、put、ログアウト後の拒否を検査。Pythonがないビルド環境ではこの統合試験をskipする。外部カレンダーや本番資格情報は使わない。
|
||||
|
||||
OIDCは署名付き模擬providerによるcallback→承認→交換のHTTP試験、12並行交換で1sessionのみ、
|
||||
越境・別origin・期限・失効・MFA・不正コード・発行上限・途中失敗rollbackを検査する。
|
||||
`TestRemoteCLIOIDCIntegration`ではPython CLIから実際のHTTP経由でconfigure→OIDC待機/交換→一覧→authoring保存→logoutを実行する。
|
||||
この試験のブラウザ操作だけはfixtureの承認ブリッジを使い、実OIDC callbackは別のHTTP試験で検証する。
|
||||
承認画面のChromium試験は1440px/390pxで実フォームとCookieによる承認を確認する。
|
||||
本番OIDC providerでの実ログインは未実施。
|
||||
|
||||
2026-11-01の実行結果:全Goテスト(キャッシュなし)、全Go vet、関連store/serverのrace検査、
|
||||
Python 18件、OIDCとパスワードのCLI HTTP統合試験、承認画面と既存CookieログインのChromium試験が成功。
|
||||
CLI承認画面のモバイルスクリーンショットも確認した。実機Safariは未確認。
|
||||
前段のイベントログ修正を保持し、本番のv0.2.0・ユーザーPATH上の旧CLIは変更していない。
|
||||
OIDCは機能追加なので、ログ修正単独のPATCHと区別しv0.3.0で公開する。
|
||||
サーバーとCLIの両方が必要。開始APIの404/405/501は未対応または接続先の誤りとして明示し、
|
||||
OIDC無効の403と区別する。エラー時のログイン要求は自動再送せず、資格情報も保存しない。
|
||||
|
||||
ソースのチェックポイント:`.deployment-backups/dev-cli-oidc-20261101/source-after.tar.gz`
|
||||
(SHA-256 `3e4228cd53b4220dffe43a80b4ed02c0bd757a8b3845829b7d3a77a64b0e9c4b`)。
|
||||
OIDC関連18ファイルのみで、本番DB・鍵・セッション・前段のログ保存修正は含まない。
|
||||
変更前はGitの`0f686aa`と比較し、対象ファイル単位で復元する。作業ツリー全体をresetしない。
|
||||
|
||||
次段階の順序:
|
||||
|
||||
1. Ctrl+Pによる検索選択、補完の引用文字/途中カーソル対応、永続履歴の明示opt-in。
|
||||
2. 新規Page+Path+初回Revisionの原子的な作成API、create/upload-only権限、並行作成の衝突、言語分岐。
|
||||
3. 競合の対話選択・復旧コマンド、巨大転送のstreamingとキャンセル、mget/mput(globのlocal/remoteを明示)。
|
||||
4. OIDCブラウザ認証の短命・単回・PKCE相当ハンドオフ。既存device approvalをそのまま転用せず、本人確認・Domain・CLIリクエストを束縛する。
|
||||
4. OIDC引き継ぎの本番schema適用・サーバ/CLI配布・実providerログイン確認。初期実装は上記のとおり完了、v0.2.0環境への反映は未実施。
|
||||
5. OS keyring、Windows対応、非公開の短縮リンク引き継ぎ。自動的な公開shareは行わない。
|
||||
@@ -0,0 +1,186 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"crypto/subtle"
|
||||
"encoding/base64"
|
||||
"errors"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"regexp"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"pageswiki/internal/store"
|
||||
)
|
||||
|
||||
var cliProofPattern = regexp.MustCompile(`^[A-Za-z0-9_-]{43}$`)
|
||||
var cliVerifierPattern = regexp.MustCompile(`^[A-Za-z0-9._~-]{43,128}$`)
|
||||
|
||||
func cliOrigin(r *http.Request) string { return strings.ToLower(externalURL(r, "")) }
|
||||
func cliSecureTransport(r *http.Request) bool {
|
||||
if requestIsHTTPS(r) {
|
||||
return true
|
||||
}
|
||||
host := r.Host
|
||||
if h, _, err := net.SplitHostPort(host); err == nil {
|
||||
host = h
|
||||
}
|
||||
return host == "localhost" || host == "127.0.0.1" || host == "::1" || host == "[::1]"
|
||||
}
|
||||
func cliVerifyPath(id string) string { return "/_/auth/cli/verify?request=" + url.QueryEscape(id) }
|
||||
func cliConsentCSRF(token, id string) string {
|
||||
sum := sha256.Sum256([]byte("pages-cli-consent:" + token + ":" + id))
|
||||
return base64.RawURLEncoding.EncodeToString(sum[:])
|
||||
}
|
||||
|
||||
func (s *Server) handleCLIAuth(w http.ResponseWriter, r *http.Request, action string) {
|
||||
w.Header().Set("Cache-Control", "private, no-store")
|
||||
w.Header().Set("Referrer-Policy", "no-referrer")
|
||||
w.Header().Set("X-Frame-Options", "DENY")
|
||||
if !cliSecureTransport(r) {
|
||||
writeEventJSON(w, 400, map[string]string{"error": "https_required"})
|
||||
return
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(r.Context(), 5*time.Second)
|
||||
defer cancel()
|
||||
r = r.WithContext(ctx)
|
||||
domain := s.domainUUIDForRequest(r)
|
||||
config, err := s.store.AuthProviderConfig(domain, "oidc")
|
||||
if err != nil || !config.Enabled {
|
||||
writeEventJSON(w, 403, map[string]string{"error": "oidc_disabled"})
|
||||
return
|
||||
}
|
||||
if action == "cli/verify" {
|
||||
s.verifyCLIAuth(w, r)
|
||||
return
|
||||
}
|
||||
if r.Method != http.MethodPost {
|
||||
w.Header().Set("Allow", "POST")
|
||||
http.Error(w, "method not allowed", 405)
|
||||
return
|
||||
}
|
||||
r.Body = http.MaxBytesReader(w, r.Body, 4096)
|
||||
if err := r.ParseForm(); err != nil {
|
||||
writeEventJSON(w, 400, map[string]string{"error": "invalid_request"})
|
||||
return
|
||||
}
|
||||
switch action {
|
||||
case "cli/start":
|
||||
challenge := r.PostForm.Get("code_challenge")
|
||||
if !cliProofPattern.MatchString(challenge) || r.PostForm.Get("code_challenge_method") != "S256" {
|
||||
writeEventJSON(w, 400, map[string]string{"error": "invalid_request"})
|
||||
return
|
||||
}
|
||||
id, device, code, err := s.store.StartCLIAuth(ctx, domain, cliOrigin(r), challenge)
|
||||
if err != nil {
|
||||
cliAuthError(w, err)
|
||||
return
|
||||
}
|
||||
writeEventJSON(w, 200, map[string]any{"device_code": device, "verification_uri": cliVerifyPath(id), "user_code": code[:4] + "-" + code[4:], "expires_in": 300, "interval": 5})
|
||||
case "cli/token":
|
||||
device, verifier := r.PostForm.Get("device_code"), r.PostForm.Get("code_verifier")
|
||||
if !cliProofPattern.MatchString(device) || !cliVerifierPattern.MatchString(verifier) {
|
||||
writeEventJSON(w, 400, map[string]string{"error": "invalid_request"})
|
||||
return
|
||||
}
|
||||
token, name, expires, err := s.store.ExchangeCLIAuth(ctx, domain, cliOrigin(r), device, verifier)
|
||||
if err != nil {
|
||||
cliAuthError(w, err)
|
||||
return
|
||||
}
|
||||
writeEventJSON(w, 200, map[string]any{"access_token": token, "token_type": "Bearer", "username": name, "expires_in": max(1, (expires-time.Now().UnixMilli())/1000)})
|
||||
default:
|
||||
http.NotFound(w, r)
|
||||
}
|
||||
}
|
||||
|
||||
func cliAuthError(w http.ResponseWriter, err error) {
|
||||
code, status := "temporarily_unavailable", 503
|
||||
switch {
|
||||
case errors.Is(err, store.ErrCLIPending):
|
||||
code, status = "authorization_pending", 400
|
||||
case errors.Is(err, store.ErrCLISlowDown):
|
||||
code, status = "slow_down", 400
|
||||
case errors.Is(err, store.ErrCLIExpired):
|
||||
code, status = "expired_token", 400
|
||||
case errors.Is(err, store.ErrAccessDenied):
|
||||
code, status = "access_denied", 403
|
||||
case errors.Is(err, store.ErrCLILimit):
|
||||
code, status = "too_many_requests", 429
|
||||
}
|
||||
writeEventJSON(w, status, map[string]string{"error": code})
|
||||
}
|
||||
|
||||
func (s *Server) verifyCLIAuth(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodGet && r.Method != http.MethodPost {
|
||||
w.Header().Set("Allow", "GET, POST")
|
||||
http.Error(w, "method not allowed", 405)
|
||||
return
|
||||
}
|
||||
r.Body = http.MaxBytesReader(w, r.Body, 4096)
|
||||
if err := r.ParseForm(); err != nil {
|
||||
http.Error(w, "invalid request", 400)
|
||||
return
|
||||
}
|
||||
id := r.URL.Query().Get("request")
|
||||
if r.Method == http.MethodPost {
|
||||
id = r.PostForm.Get("request")
|
||||
}
|
||||
if !cliProofPattern.MatchString(id) {
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
domain := s.domainUUIDForRequest(r)
|
||||
grant, err := s.store.CLIAuthRequest(r.Context(), domain, cliOrigin(r), id)
|
||||
if err != nil {
|
||||
http.Error(w, "CLI request expired; restart pages login --oidc", 410)
|
||||
return
|
||||
}
|
||||
data := map[string]any{"CLIAuth": true, "CLIOrigin": grant.Origin, "CLIRequest": id}
|
||||
if grant.State != "pending" {
|
||||
data["CLIDone"] = true
|
||||
s.renderAuthPage(w, r, data)
|
||||
return
|
||||
}
|
||||
if grant.BrowserHash == "" {
|
||||
if r.Method != http.MethodGet {
|
||||
http.Error(w, "OIDC login required", 403)
|
||||
return
|
||||
}
|
||||
data["CLILogin"] = "/_/auth/oidc?cli=" + url.QueryEscape(id)
|
||||
s.renderAuthPage(w, r, data)
|
||||
return
|
||||
}
|
||||
token := s.authTokenFromRequest(r)
|
||||
sum := sha256.Sum256([]byte(token))
|
||||
hash := base64.RawURLEncoding.EncodeToString(sum[:])
|
||||
principal, err := s.store.PrincipalForSession(domain, token)
|
||||
if !strings.HasPrefix(token, "pw_browser_") || hash != grant.BrowserHash || err != nil {
|
||||
http.Error(w, "This request belongs to another browser. Restart CLI login.", 403)
|
||||
return
|
||||
}
|
||||
data["CLIUsername"] = principal.Username
|
||||
data["CLICSRF"] = cliConsentCSRF(token, id)
|
||||
data["CLITOTP"] = s.store.HasTOTP(principal.UUID)
|
||||
if r.Method == http.MethodPost {
|
||||
if !validBrowserMutationOrigin(r) || subtle.ConstantTimeCompare([]byte(r.PostForm.Get("csrf")), []byte(cliConsentCSRF(token, id))) != 1 {
|
||||
http.Error(w, "invalid approval origin or token", 403)
|
||||
return
|
||||
}
|
||||
decision := r.PostForm.Get("decision")
|
||||
if decision != "approve" && decision != "deny" {
|
||||
http.Error(w, "invalid decision", 400)
|
||||
return
|
||||
}
|
||||
err = s.store.DecideCLIAuth(r.Context(), domain, cliOrigin(r), id, token, r.PostForm.Get("user_code"), r.PostForm.Get("totp"), decision == "approve")
|
||||
if err != nil {
|
||||
data["Error"] = translate(s.getLocale(domain), "auth.cli_invalid")
|
||||
} else {
|
||||
data["CLIDone"] = true
|
||||
}
|
||||
}
|
||||
s.renderAuthPage(w, r, data)
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"pageswiki/internal/store"
|
||||
)
|
||||
|
||||
func TestCLIConsentChromium(t *testing.T) {
|
||||
if os.Getenv("PAGESWIKI_BROWSER_TEST") != "1" {
|
||||
t.Skip("opt-in Chromium")
|
||||
}
|
||||
for _, width := range []string{"1440", "390"} {
|
||||
t.Run(width, func(t *testing.T) {
|
||||
s, api, domain := configFixture(t)
|
||||
if err := s.store.SetAuthProviderConfig(domain, store.AuthProviderConfig{Kind: "oidc", Enabled: true, Issuer: "https://id.example", ClientID: "client"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
browser, err := s.store.CreateBrowserAuthSession(domain, s.mustCLIPrincipal(t, domain, api), 0)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var code string
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method == "GET" && r.URL.Path == "/_/auth/cli/verify" {
|
||||
r.AddCookie(&http.Cookie{Name: authCookieName, Value: browser})
|
||||
rec := httptest.NewRecorder()
|
||||
s.handleAuth(rec, r)
|
||||
for k, values := range rec.Header() {
|
||||
w.Header()[k] = values
|
||||
}
|
||||
s.setAuthCookie(w, r, browser)
|
||||
encoded, _ := json.Marshal(code)
|
||||
script := `<script>(async()=>{try{
|
||||
const form=document.querySelector('.auth-form'); if(!form)throw Error('missing consent form');
|
||||
if(document.documentElement.scrollWidth>innerWidth+2)throw Error('horizontal overflow');
|
||||
const field=form.elements.user_code; if(getComputedStyle(field).backgroundColor==='rgba(0, 0, 0, 0)')throw Error('input theme missing');
|
||||
field.value=` + string(encoded) + `; const data=new URLSearchParams(new FormData(form)); data.set('decision','approve');
|
||||
const response=await fetch(form.action,{method:'POST',body:data}); const html=await response.text();
|
||||
if(!response.ok||html.includes('name="user_code"'))throw Error('approval failed');
|
||||
document.body.dataset.vimReady='true';
|
||||
}catch(e){const p=document.createElement('pre');p.id='error';p.textContent=e.message;document.body.append(p)}})();</script>`
|
||||
w.WriteHeader(rec.Code)
|
||||
_, _ = w.Write([]byte(strings.Replace(rec.Body.String(), "</body>", script+"</body>", 1)))
|
||||
return
|
||||
}
|
||||
if strings.HasPrefix(r.URL.Path, "/_/auth/") {
|
||||
s.withAuthorization(http.HandlerFunc(s.handleAuth)).ServeHTTP(w, r)
|
||||
return
|
||||
}
|
||||
s.withAuthorization(s.mux).ServeHTTP(w, r)
|
||||
}))
|
||||
defer server.Close()
|
||||
origin := strings.Replace(server.URL, "127.0.0.1", "localhost", 1)
|
||||
id, _, c, err := s.store.StartCLIAuth(context.Background(), domain, origin, strings.Repeat("c", 43))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
code = c
|
||||
if err := s.store.BindCLIAuth(context.Background(), domain, origin, id, browser); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 40*time.Second)
|
||||
defer cancel()
|
||||
screenshot := ""
|
||||
if dir := os.Getenv("PAGESWIKI_BROWSER_ARTIFACTS"); dir != "" {
|
||||
if err := os.MkdirAll(dir, 0755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
screenshot = filepath.Join(dir, "cli-consent-"+width+".png")
|
||||
}
|
||||
command := exec.CommandContext(ctx, "node", "internal/server/testdata/vim-browser-smoke.mjs", origin+cliVerifyPath(id), t.TempDir(), screenshot, width, "900")
|
||||
if out, err := command.CombinedOutput(); err != nil {
|
||||
t.Fatalf("consent browser: %v %s", err, out)
|
||||
}
|
||||
grant, err := s.store.CLIAuthRequest(context.Background(), domain, origin, id)
|
||||
if err != nil || grant.State != "approved" {
|
||||
t.Fatalf("not persisted: %+v %v", grant, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package server
|
||||
|
||||
func init() {
|
||||
for lang, entries := range map[string]map[string]string{
|
||||
"ja": {
|
||||
"auth.cli_title": "ターミナルからのアクセスを承認",
|
||||
"auth.cli_warning": "自分で pages login --oidc を開始した場合のみ続行してください。他人から送られたURLや確認コードを使って承認しないでください。有効期限は開始から5分です。",
|
||||
"auth.cli_account": "ログインするアカウント",
|
||||
"auth.cli_access": "このCLIはあなたの現在の権限で閲覧・編集できます。専用セッションは設定画面から失効できます。",
|
||||
"auth.cli_code": "ターミナルに表示された確認コード",
|
||||
"auth.cli_approve": "このCLIを承認する",
|
||||
"auth.cli_deny": "拒否する",
|
||||
"auth.cli_done": "リクエストは処理済みです。ターミナルに戻って結果を確認してください。この画面は閉じられます。",
|
||||
"auth.cli_invalid": "確認コードまたはTOTPが正しくないか、リクエストが失効しました。5回失敗した場合はCLIでログインをやり直してください。",
|
||||
},
|
||||
"en": {
|
||||
"auth.cli_title": "Approve terminal access",
|
||||
"auth.cli_warning": "Continue only if you started pages login --oidc yourself. Never approve a URL or code sent by someone else. This request expires five minutes after creation.",
|
||||
"auth.cli_account": "Account",
|
||||
"auth.cli_access": "This CLI can read and edit using your current permissions. Its separate session can be revoked in Settings.",
|
||||
"auth.cli_code": "Confirmation code shown in your terminal",
|
||||
"auth.cli_approve": "Approve this CLI",
|
||||
"auth.cli_deny": "Deny",
|
||||
"auth.cli_done": "This request has been processed. Return to your terminal to check the result. You may close this page.",
|
||||
"auth.cli_invalid": "Incorrect confirmation code or TOTP, or the request expired. After five failed attempts, restart login from the CLI.",
|
||||
},
|
||||
} {
|
||||
for key, value := range entries {
|
||||
translations[lang][key] = value
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,174 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"pageswiki/internal/store"
|
||||
)
|
||||
|
||||
func cliForm(s *Server, path string, form url.Values, cookie, origin string) *httptest.ResponseRecorder {
|
||||
r := httptest.NewRequest("POST", "https://localhost"+path, strings.NewReader(form.Encode()))
|
||||
r.Header.Set("Content-Type", "application/x-www-form-urlencoded")
|
||||
if origin != "" {
|
||||
r.Header.Set("Origin", origin)
|
||||
}
|
||||
if cookie != "" {
|
||||
r.AddCookie(&http.Cookie{Name: authCookieName, Value: cookie})
|
||||
}
|
||||
w := httptest.NewRecorder()
|
||||
s.withAuthorization(http.HandlerFunc(s.handleAuth)).ServeHTTP(w, r)
|
||||
return w
|
||||
}
|
||||
|
||||
func TestCLIAuthOIDCFlow(t *testing.T) {
|
||||
s, _, domain := configFixture(t)
|
||||
p := newOIDCTestProvider(t)
|
||||
previous := oidcVerifier
|
||||
oidcVerifier = p.verifier
|
||||
t.Cleanup(func() { oidcVerifier = previous })
|
||||
if err := s.store.SetAuthProviderConfig(domain, store.AuthProviderConfig{Kind: "oidc", Enabled: true, Issuer: p.server.URL, ClientID: "client", ClientSecret: "secret", OIDCMatchBy: "preferred_username"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
verifier := strings.Repeat("x", 43)
|
||||
sum := sha256.Sum256([]byte(verifier))
|
||||
start := cliForm(s, "/_/auth/cli/start", url.Values{"code_challenge": {base64.RawURLEncoding.EncodeToString(sum[:])}, "code_challenge_method": {"S256"}}, "", "")
|
||||
if start.Code != 200 {
|
||||
t.Fatalf("start %d %s", start.Code, start.Body.String())
|
||||
}
|
||||
var grant struct {
|
||||
Device string `json:"device_code"`
|
||||
URI string `json:"verification_uri"`
|
||||
Code string `json:"user_code"`
|
||||
}
|
||||
if err := json.Unmarshal(start.Body.Bytes(), &grant); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
u, _ := url.Parse(grant.URI)
|
||||
id := u.Query().Get("request")
|
||||
verify := httptest.NewRecorder()
|
||||
s.handleAuth(verify, httptest.NewRequest("GET", "https://localhost"+grant.URI, nil))
|
||||
if verify.Code != 200 || !strings.Contains(verify.Body.String(), "/_/auth/oidc?cli=") || strings.Contains(verify.Body.String(), grant.Device) {
|
||||
t.Fatalf("verify landing: %d %s", verify.Code, verify.Body.String())
|
||||
}
|
||||
begin := httptest.NewRecorder()
|
||||
s.beginOIDC(begin, httptest.NewRequest("GET", "https://localhost/_/auth/oidc?cli="+id, nil))
|
||||
if begin.Code != 302 {
|
||||
t.Fatalf("oidc begin %d %s", begin.Code, begin.Body.String())
|
||||
}
|
||||
location, _ := url.Parse(begin.Header().Get("Location"))
|
||||
claims := oidcTestClaims(p.server.URL)
|
||||
claims["nonce"] = location.Query().Get("nonce")
|
||||
p.mu.Lock()
|
||||
p.idToken = oidcTestToken(t, p.key, map[string]string{"alg": "RS256", "kid": "one"}, claims)
|
||||
p.mu.Unlock()
|
||||
callback := httptest.NewRequest("GET", "https://localhost/_/auth/callback/oidc?code=code&state="+url.QueryEscape(location.Query().Get("state")), nil)
|
||||
for _, cookie := range begin.Result().Cookies() {
|
||||
callback.AddCookie(cookie)
|
||||
}
|
||||
complete := httptest.NewRecorder()
|
||||
s.completeOIDC(complete, callback)
|
||||
if complete.Code != 303 || complete.Header().Get("Location") != grant.URI {
|
||||
t.Fatalf("oidc callback %d %s", complete.Code, complete.Body.String())
|
||||
}
|
||||
var browser string
|
||||
for _, cookie := range complete.Result().Cookies() {
|
||||
if cookie.Name == authCookieName {
|
||||
browser = cookie.Value
|
||||
}
|
||||
}
|
||||
if browser == "" {
|
||||
t.Fatal("missing browser session")
|
||||
}
|
||||
consent := httptest.NewRequest("GET", "https://localhost"+grant.URI, nil)
|
||||
consent.AddCookie(&http.Cookie{Name: authCookieName, Value: browser})
|
||||
w := httptest.NewRecorder()
|
||||
s.handleAuth(w, consent)
|
||||
if w.Code != 200 || !strings.Contains(w.Body.String(), `name="user_code"`) || !strings.Contains(w.Body.String(), cliConsentCSRF(browser, id)) {
|
||||
t.Fatalf("consent %d %s", w.Code, w.Body.String())
|
||||
}
|
||||
form := url.Values{"request": {id}, "csrf": {cliConsentCSRF(browser, id)}, "user_code": {grant.Code}, "decision": {"approve"}}
|
||||
if w := cliForm(s, "/_/auth/cli/verify", form, browser, "https://evil.example"); w.Code != 403 {
|
||||
t.Fatal("cross-origin approval accepted")
|
||||
}
|
||||
bad := url.Values{"request": {id}, "csrf": {"bad"}, "user_code": {grant.Code}, "decision": {"approve"}}
|
||||
if w := cliForm(s, "/_/auth/cli/verify", bad, browser, "https://localhost"); w.Code != 403 {
|
||||
t.Fatal("CSRF accepted")
|
||||
}
|
||||
other, err := s.store.CreateBrowserAuthSession(domain, s.mustCLIPrincipal(t, domain, browser), 0)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if w := cliForm(s, "/_/auth/cli/verify", form, other, "https://localhost"); w.Code != 403 {
|
||||
t.Fatal("other browser accepted")
|
||||
}
|
||||
approved := cliForm(s, "/_/auth/cli/verify", form, browser, "https://localhost")
|
||||
if approved.Code != 200 || strings.Contains(approved.Body.String(), `name="user_code"`) {
|
||||
t.Fatalf("approve: %d %s", approved.Code, approved.Body.String())
|
||||
}
|
||||
poll := url.Values{"device_code": {grant.Device}, "code_verifier": {verifier}}
|
||||
exchange := cliForm(s, "/_/auth/cli/token", poll, "", "")
|
||||
if exchange.Code != 200 {
|
||||
t.Fatalf("exchange %d %s", exchange.Code, exchange.Body.String())
|
||||
}
|
||||
var result struct {
|
||||
Token string `json:"access_token"`
|
||||
Username string `json:"username"`
|
||||
}
|
||||
if err := json.Unmarshal(exchange.Body.Bytes(), &result); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !strings.HasPrefix(result.Token, "pw_api_") || result.Username != "admin" || result.Token == browser {
|
||||
t.Fatal("invalid delegated credential")
|
||||
}
|
||||
if _, err := s.store.PrincipalForSession(domain, result.Token); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if w := cliForm(s, "/_/auth/cli/token", poll, "", ""); w.Code == 200 {
|
||||
t.Fatal("replay accepted")
|
||||
}
|
||||
if err := s.store.RevokeAuthSession(result.Token); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := s.store.PrincipalForSession(domain, result.Token); err == nil {
|
||||
t.Fatal("CLI session not revocable")
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Server) mustCLIPrincipal(t *testing.T, domain, token string) string {
|
||||
t.Helper()
|
||||
p, err := s.store.PrincipalForSession(domain, token)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return p.UUID
|
||||
}
|
||||
|
||||
func TestCLITransportAndMethods(t *testing.T) {
|
||||
for _, host := range []string{"localhost.attacker.test", "127.0.0.10", "wiki.example"} {
|
||||
if cliSecureTransport(httptest.NewRequest("POST", "http://"+host+"/_/auth/cli/start", nil)) {
|
||||
t.Fatal("insecure remote", host)
|
||||
}
|
||||
}
|
||||
s, _, domain := configFixture(t)
|
||||
if err := s.store.SetAuthProviderConfig(domain, store.AuthProviderConfig{Kind: "oidc", Enabled: true, Issuer: "https://id.example", ClientID: "client"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, path := range []string{"start", "token"} {
|
||||
w := httptest.NewRecorder()
|
||||
s.handleAuth(w, httptest.NewRequest("GET", "https://localhost/_/auth/cli/"+path, nil))
|
||||
if w.Code != 405 {
|
||||
t.Fatalf("GET %s %d", path, w.Code)
|
||||
}
|
||||
}
|
||||
w := cliForm(s, "/_/auth/cli/start", url.Values{"code_challenge": {strings.Repeat("x", 43)}, "code_challenge_method": {"plain"}}, "", "")
|
||||
if w.Code != 400 {
|
||||
t.Fatal("plain challenge accepted")
|
||||
}
|
||||
}
|
||||
@@ -14,7 +14,7 @@ import (
|
||||
"time"
|
||||
)
|
||||
|
||||
type oidcChallenge struct{ Verifier, Nonce, Return, Issuer, ClientID, BrowserHash string }
|
||||
type oidcChallenge struct{ Verifier, Nonce, Return, Issuer, ClientID, BrowserHash, CLIRequest string }
|
||||
|
||||
func logOIDCFailure(stage, domainUUID, issuer string, err error) {
|
||||
host := "invalid"
|
||||
@@ -56,6 +56,19 @@ func (s *Server) beginOIDC(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(r.Context(), 8*time.Second)
|
||||
defer cancel()
|
||||
cliRequest := r.URL.Query().Get("cli")
|
||||
returnPath := safeReturnPath(r.URL.Query().Get("return"))
|
||||
if cliRequest != "" {
|
||||
if !cliSecureTransport(r) || !cliProofPattern.MatchString(cliRequest) {
|
||||
http.Error(w, "invalid CLI request", 400)
|
||||
return
|
||||
}
|
||||
if err := s.store.BeginCLIAuth(ctx, domainUUID, cliOrigin(r), cliRequest); err != nil {
|
||||
http.Error(w, "invalid CLI request", 400)
|
||||
return
|
||||
}
|
||||
returnPath = cliVerifyPath(cliRequest)
|
||||
}
|
||||
metadata, err := fetchOIDCMetadata(ctx, config.Issuer)
|
||||
if err != nil {
|
||||
logOIDCFailure("discovery", domainUUID, config.Issuer, err)
|
||||
@@ -64,7 +77,7 @@ func (s *Server) beginOIDC(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
verifier, nonce, browser := randomURLToken(32), randomURLToken(24), randomURLToken(32)
|
||||
browserDigest := sha256.Sum256([]byte(browser))
|
||||
state, err := s.store.CreateAuthChallenge(domainUUID, "", "oidc", oidcChallenge{Verifier: verifier, Nonce: nonce, Return: safeReturnPath(r.URL.Query().Get("return")), Issuer: config.Issuer, ClientID: config.ClientID, BrowserHash: base64.RawURLEncoding.EncodeToString(browserDigest[:])}, 5*time.Minute)
|
||||
state, err := s.store.CreateAuthChallenge(domainUUID, "", "oidc", oidcChallenge{Verifier: verifier, Nonce: nonce, Return: returnPath, Issuer: config.Issuer, ClientID: config.ClientID, BrowserHash: base64.RawURLEncoding.EncodeToString(browserDigest[:]), CLIRequest: cliRequest}, 5*time.Minute)
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), 500)
|
||||
return
|
||||
@@ -197,6 +210,13 @@ func (s *Server) completeOIDC(w http.ResponseWriter, r *http.Request) {
|
||||
http.Error(w, err.Error(), 500)
|
||||
return
|
||||
}
|
||||
if challenge.CLIRequest != "" {
|
||||
if err := s.store.BindCLIAuth(r.Context(), domainUUID, cliOrigin(r), challenge.CLIRequest, token); err != nil {
|
||||
_ = s.store.RevokeAuthSession(token)
|
||||
http.Error(w, "CLI request expired or already used; restart login", 400)
|
||||
return
|
||||
}
|
||||
}
|
||||
s.setAuthCookie(w, r, token)
|
||||
http.Redirect(w, r, challenge.Return, http.StatusSeeOther)
|
||||
}
|
||||
|
||||
@@ -101,6 +101,10 @@ func (s *Server) authTokenFromRequest(r *http.Request) string {
|
||||
func (s *Server) handleAuth(w http.ResponseWriter, r *http.Request) {
|
||||
action := strings.Trim(strings.TrimPrefix(r.URL.Path, "/_/auth"), "/")
|
||||
domainUUID := s.domainUUIDForRequest(r)
|
||||
if strings.HasPrefix(action, "cli/") {
|
||||
s.handleCLIAuth(w, r, action)
|
||||
return
|
||||
}
|
||||
switch action {
|
||||
case "wallpaper":
|
||||
s.handleAuthWallpaper(w, r)
|
||||
|
||||
@@ -9,6 +9,8 @@ import (
|
||||
"os/exec"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"pageswiki/internal/store"
|
||||
)
|
||||
|
||||
func TestRemoteCLIHTTPIntegration(t *testing.T) {
|
||||
@@ -33,3 +35,48 @@ func TestRemoteCLIHTTPIntegration(t *testing.T) {
|
||||
t.Fatalf("remote CLI: %v\n%s", err, out)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRemoteCLIOIDCIntegration(t *testing.T) {
|
||||
if _, err := exec.LookPath("python3"); err != nil {
|
||||
t.Skip("python3 not installed")
|
||||
}
|
||||
s, api, domain, _ := editorFixture(t)
|
||||
if err := s.store.SetAuthProviderConfig(domain, store.AuthProviderConfig{Kind: "oidc", Enabled: true, Issuer: "https://id.example", ClientID: "client"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
s.mux.HandleFunc("/_/auth/", s.handleAuth)
|
||||
s.mux.HandleFunc("/v/raw/", s.handleRawView)
|
||||
s.mux.HandleFunc("/_/api/v1/path-picker", s.handlePathPickerAPI)
|
||||
principal := s.mustCLIPrincipal(t, domain, api)
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
r.Host = "localhost"
|
||||
// Test-only bridge in this httptest server. The real signed OIDC callback,
|
||||
// browser binding and CSRF flow are covered by TestCLIAuthOIDCFlow.
|
||||
if r.URL.Path == "/__test/cli-approve" {
|
||||
_ = r.ParseForm()
|
||||
browser, err := s.store.CreateBrowserAuthSession(domain, principal, 0)
|
||||
if err == nil {
|
||||
err = s.store.BindCLIAuth(r.Context(), domain, "http://localhost", r.Form.Get("request"), browser)
|
||||
}
|
||||
if err == nil {
|
||||
err = s.store.DecideCLIAuth(r.Context(), domain, "http://localhost", r.Form.Get("request"), browser, r.Form.Get("code"), "", true)
|
||||
}
|
||||
if err != nil {
|
||||
http.Error(w, "synthetic approval failed", 500)
|
||||
return
|
||||
}
|
||||
writeEventJSON(w, 200, map[string]bool{"approved": true})
|
||||
return
|
||||
}
|
||||
s.withAuthorization(s.mux).ServeHTTP(w, r)
|
||||
}))
|
||||
defer server.Close()
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
defer cancel()
|
||||
cmd := exec.CommandContext(ctx, "python3", "pages-cli/test_pages.py", "--oidc-integration")
|
||||
input, _ := json.Marshal(map[string]string{"origin": server.URL})
|
||||
cmd.Stdin = bytes.NewReader(input)
|
||||
if out, err := cmd.CombinedOutput(); err != nil {
|
||||
t.Fatalf("CLI OIDC integration: %v %s", err, out)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,248 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"database/sql"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"pageswiki/internal/db"
|
||||
)
|
||||
|
||||
var cliAuthMigrations = []db.SQLMigration{{Version: 1, Name: "cli_oidc_handoff", Statements: []string{
|
||||
`CREATE TABLE auth_cli_requests (
|
||||
id TEXT PRIMARY KEY, domain_uuid TEXT NOT NULL, origin TEXT NOT NULL,
|
||||
device_hash TEXT NOT NULL UNIQUE, challenge TEXT NOT NULL, code_hash TEXT NOT NULL,
|
||||
state TEXT NOT NULL DEFAULT 'pending', browser_hash TEXT NOT NULL DEFAULT '',
|
||||
principal_uuid TEXT NOT NULL DEFAULT '', mfa_level INTEGER NOT NULL DEFAULT 0, attempts INTEGER NOT NULL DEFAULT 0, oidc_attempts INTEGER NOT NULL DEFAULT 0,
|
||||
created_ms INTEGER NOT NULL, expires_ms INTEGER NOT NULL, next_poll_ms INTEGER NOT NULL DEFAULT 0)`,
|
||||
`CREATE INDEX auth_cli_domain_created ON auth_cli_requests(domain_uuid,created_ms)`,
|
||||
`CREATE INDEX auth_cli_expiry ON auth_cli_requests(expires_ms)`,
|
||||
}, Assertions: []string{
|
||||
schemaColumns("auth_cli_requests", "id,domain_uuid,origin,device_hash,challenge,code_hash,state,browser_hash,principal_uuid,mfa_level,attempts,oidc_attempts,created_ms,expires_ms,next_poll_ms"),
|
||||
schemaUnique("auth_cli_requests", "id"), schemaUnique("auth_cli_requests", "device_hash"),
|
||||
schemaIndex("auth_cli_requests", "auth_cli_domain_created", "domain_uuid,created_ms"),
|
||||
schemaIndex("auth_cli_requests", "auth_cli_expiry", "expires_ms"),
|
||||
}}}
|
||||
|
||||
var (
|
||||
ErrCLIPending = errors.New("authorization_pending")
|
||||
ErrCLISlowDown = errors.New("slow_down")
|
||||
ErrCLIExpired = errors.New("expired_token")
|
||||
ErrCLILimit = errors.New("too_many_requests")
|
||||
)
|
||||
|
||||
type CLIAuthRequest struct {
|
||||
ID, Origin, State, BrowserHash, PrincipalUUID string
|
||||
ExpiresMS int64
|
||||
}
|
||||
|
||||
// Admission is one write statement; concurrent unauthenticated requests cannot
|
||||
// race the caps. Requests are retained for ten minutes for issuance accounting.
|
||||
func (s *Store) StartCLIAuth(ctx context.Context, domain, origin, challenge string) (id, device, code string, err error) {
|
||||
if s.ReadOnly {
|
||||
return "", "", "", ErrReadOnly
|
||||
}
|
||||
id, _, err = authToken()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
device, _, err = authToken()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
var raw [4]byte
|
||||
if _, err = rand.Read(raw[:]); err != nil {
|
||||
return
|
||||
}
|
||||
code = strings.ToUpper(hex.EncodeToString(raw[:]))
|
||||
now := time.Now().UnixMilli()
|
||||
_, err = s.DB.ExecContext(ctx, `DELETE FROM auth_cli_requests WHERE expires_ms<?`, now-5*60*1000)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
var result sql.Result
|
||||
result, err = s.DB.ExecContext(ctx, `INSERT INTO auth_cli_requests(id,domain_uuid,origin,device_hash,challenge,code_hash,created_ms,expires_ms)
|
||||
SELECT ?,?,?,?,?,?,?,? WHERE (SELECT count(*) FROM auth_cli_requests)<4096
|
||||
AND (SELECT count(*) FROM auth_cli_requests WHERE domain_uuid=? AND created_ms>?)<64`,
|
||||
id, domain, origin, hashAuthToken(device), challenge, hashAuthToken(code), now, now+300000, domain, now-300000)
|
||||
if err == nil {
|
||||
if n, e := result.RowsAffected(); e != nil {
|
||||
err = e
|
||||
} else if n != 1 {
|
||||
err = ErrCLILimit
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func (s *Store) CLIAuthRequest(ctx context.Context, domain, origin, id string) (*CLIAuthRequest, error) {
|
||||
var grant CLIAuthRequest
|
||||
err := s.DB.QueryRowContext(ctx, `SELECT id,origin,state,browser_hash,principal_uuid,expires_ms FROM auth_cli_requests WHERE id=? AND domain_uuid=? AND origin=? AND expires_ms>?`, id, domain, origin, time.Now().UnixMilli()).Scan(&grant.ID, &grant.Origin, &grant.State, &grant.BrowserHash, &grant.PrincipalUUID, &grant.ExpiresMS)
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return nil, ErrCLIExpired
|
||||
}
|
||||
return &grant, err
|
||||
}
|
||||
|
||||
func (s *Store) BeginCLIAuth(ctx context.Context, domain, origin, id string) error {
|
||||
if s.ReadOnly {
|
||||
return ErrReadOnly
|
||||
}
|
||||
result, err := s.DB.ExecContext(ctx, `UPDATE auth_cli_requests SET oidc_attempts=oidc_attempts+1 WHERE id=? AND domain_uuid=? AND origin=? AND state='pending' AND browser_hash='' AND expires_ms>? AND oidc_attempts<3`, id, domain, origin, time.Now().UnixMilli())
|
||||
return cliChanged(result, err)
|
||||
}
|
||||
|
||||
// Only the verified OIDC callback calls this method. The first successful
|
||||
// browser wins; another browser cannot rebind an in-flight approval.
|
||||
func (s *Store) BindCLIAuth(ctx context.Context, domain, origin, id, browser string) error {
|
||||
if s.ReadOnly || !strings.HasPrefix(browser, "pw_browser_") {
|
||||
return ErrAccessDenied
|
||||
}
|
||||
now := time.Now().UnixMilli()
|
||||
result, err := s.DB.ExecContext(ctx, `UPDATE auth_cli_requests SET browser_hash=?,principal_uuid=(SELECT principal_uuid FROM auth_sessions WHERE token_hash=?)
|
||||
WHERE id=? AND domain_uuid=? AND origin=? AND state='pending' AND browser_hash='' AND expires_ms>?
|
||||
AND EXISTS(SELECT 1 FROM auth_sessions WHERE token_hash=? AND domain_uuid=? AND revoked_at_ms=0 AND expires_at_ms>?)`, hashAuthToken(browser), hashAuthToken(browser), id, domain, origin, now, hashAuthToken(browser), domain, now)
|
||||
return cliChanged(result, err)
|
||||
}
|
||||
|
||||
func cliChanged(result sql.Result, err error) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
n, err := result.RowsAffected()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if n != 1 {
|
||||
return ErrAccessDenied
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// The browser token, confirmation code and current membership are all checked
|
||||
// at mutation time. Attempts are spent before checking TOTP to bound guessing.
|
||||
func (s *Store) DecideCLIAuth(ctx context.Context, domain, origin, id, browser, code, totp string, approve bool) error {
|
||||
if s.ReadOnly || !strings.HasPrefix(browser, "pw_browser_") {
|
||||
return ErrAccessDenied
|
||||
}
|
||||
now := time.Now().UnixMilli()
|
||||
var principal, expectedCode string
|
||||
err := s.DB.QueryRowContext(ctx, `UPDATE auth_cli_requests SET attempts=attempts+1
|
||||
WHERE id=? AND domain_uuid=? AND origin=? AND state='pending' AND browser_hash=? AND attempts<5 AND expires_ms>?
|
||||
RETURNING principal_uuid,code_hash`, id, domain, origin, hashAuthToken(browser), now).Scan(&principal, &expectedCode)
|
||||
if err != nil {
|
||||
return ErrAccessDenied
|
||||
}
|
||||
level := 0
|
||||
if approve {
|
||||
if hashAuthToken(strings.ToUpper(strings.ReplaceAll(strings.TrimSpace(code), "-", ""))) != expectedCode {
|
||||
return ErrAccessDenied
|
||||
}
|
||||
// Query errors must not silently bypass enrolled MFA.
|
||||
var has int
|
||||
if err := s.DB.QueryRowContext(ctx, `SELECT count(*) FROM auth_credentials WHERE principal_uuid=? AND kind='totp' AND enabled=1`, principal).Scan(&has); err != nil {
|
||||
return err
|
||||
}
|
||||
if has > 0 {
|
||||
if err := s.VerifyTOTP(principal, totp); err != nil {
|
||||
return ErrAccessDenied
|
||||
}
|
||||
level = 1
|
||||
}
|
||||
}
|
||||
state := "denied"
|
||||
if approve {
|
||||
state = "approved"
|
||||
}
|
||||
result, err := s.DB.ExecContext(ctx, `UPDATE auth_cli_requests SET state=?,mfa_level=? WHERE id=? AND domain_uuid=? AND state='pending' AND browser_hash=? AND expires_ms>?
|
||||
AND EXISTS(SELECT 1 FROM auth_sessions a 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=? AND a.domain_uuid=? AND a.revoked_at_ms=0 AND a.expires_at_ms>? AND p.state IN ('active','readonly') AND m.state='active')`, state, level, id, domain, hashAuthToken(browser), now, hashAuthToken(browser), domain, now)
|
||||
if err = cliChanged(result, err); err != nil {
|
||||
return err
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
// Poll and exchange start with a write, avoiding a WAL read-to-write upgrade.
|
||||
// Grant consumption and API-session creation commit together. No replay on a
|
||||
// lost HTTP response: a new login is required (no credential stored in grant).
|
||||
func (s *Store) ExchangeCLIAuth(ctx context.Context, domain, origin, device, verifier string) (token, username string, expires int64, err error) {
|
||||
if s.ReadOnly {
|
||||
err = ErrReadOnly
|
||||
return
|
||||
}
|
||||
now := time.Now().UnixMilli()
|
||||
lifetime := s.AuthSessionLifetime(domain).Milliseconds()
|
||||
tx, err := s.DB.BeginTx(ctx, nil)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
defer tx.Rollback()
|
||||
var id, state, browser string
|
||||
err = tx.QueryRowContext(ctx, `UPDATE auth_cli_requests SET next_poll_ms=?,state=CASE WHEN state='approved' THEN 'consumed' ELSE state END
|
||||
WHERE device_hash=? AND challenge=? AND domain_uuid=? AND origin=? AND expires_ms>? AND next_poll_ms<=? AND state IN ('pending','approved','denied')
|
||||
RETURNING id,state,browser_hash`, now+5000, hashAuthToken(device), hashAuthToken(verifier), domain, origin, now, now).Scan(&id, &state, &browser)
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
var exists int
|
||||
e := tx.QueryRowContext(ctx, `SELECT count(*) FROM auth_cli_requests WHERE device_hash=? AND challenge=? AND domain_uuid=? AND origin=? AND expires_ms>? AND state IN ('pending','approved','denied')`, hashAuthToken(device), hashAuthToken(verifier), domain, origin, now).Scan(&exists)
|
||||
if e != nil {
|
||||
err = e
|
||||
} else if exists > 0 {
|
||||
err = ErrCLISlowDown
|
||||
} else {
|
||||
err = ErrCLIExpired
|
||||
}
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
if state != "consumed" {
|
||||
err = tx.Commit()
|
||||
if err == nil {
|
||||
if state == "denied" {
|
||||
err = ErrAccessDenied
|
||||
} else {
|
||||
err = ErrCLIPending
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
var raw string
|
||||
raw, _, err = authToken()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
token = "pw_api_" + raw
|
||||
// A disabled user, removed membership or revoked browser cannot delegate.
|
||||
err = tx.QueryRowContext(ctx, `INSERT INTO auth_sessions(uuid,token_hash,principal_uuid,domain_uuid,auth_time_ms,expires_at_ms,last_seen_at_ms,mfa_level)
|
||||
SELECT ?,?,p.uuid,a.domain_uuid,a.auth_time_ms,min(?,a.expires_at_ms),?,max(a.mfa_level,g.mfa_level)
|
||||
FROM auth_cli_requests g JOIN auth_sessions a ON a.token_hash=g.browser_hash JOIN principals p ON p.uuid=a.principal_uuid JOIN domain_memberships m ON m.principal_uuid=p.uuid AND m.domain_uuid=a.domain_uuid
|
||||
WHERE a.token_hash=? AND a.domain_uuid=? AND a.revoked_at_ms=0 AND a.expires_at_ms>? AND p.state IN ('active','readonly') AND m.state='active'
|
||||
AND g.id=? AND (g.mfa_level>0 OR NOT EXISTS(SELECT 1 FROM auth_credentials WHERE principal_uuid=p.uuid AND kind='totp' AND enabled=1))
|
||||
RETURNING principal_uuid,expires_at_ms`, uuid.NewString(), hashAuthToken(token), now+lifetime, now, browser, domain, now, id).Scan(&username, &expires)
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
err = ErrAccessDenied
|
||||
}
|
||||
if err != nil {
|
||||
token = ""
|
||||
return
|
||||
}
|
||||
var name string
|
||||
err = tx.QueryRowContext(ctx, `SELECT COALESCE((SELECT subject FROM principal_identities WHERE principal_uuid=? AND provider_type='password' LIMIT 1),?)`, username, username).Scan(&name)
|
||||
if err != nil {
|
||||
token = ""
|
||||
return
|
||||
}
|
||||
username = name
|
||||
err = tx.Commit()
|
||||
if err != nil {
|
||||
token = ""
|
||||
}
|
||||
return
|
||||
}
|
||||
@@ -0,0 +1,253 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
const cliTestOrigin = "https://wiki.example"
|
||||
|
||||
func cliAuthFixture(t *testing.T) (*Store, string, string) {
|
||||
t.Helper()
|
||||
s := newSchemaTestStore(t)
|
||||
s.authKey = make([]byte, 32) // synthetic key; no on-disk or production secrets
|
||||
if err := s.EnsureAuthSchema(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := s.ensureSchemaComponent("cli-auth"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
p, err := s.BootstrapOwner("domain", "owner", "correct horse battery staple", "Owner", "")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
browser, err := s.CreateBrowserAuthSession("domain", p.UUID, 0)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return s, p.UUID, browser
|
||||
}
|
||||
|
||||
func TestCLIAuthExchangeIsAtomicAndSingleUse(t *testing.T) {
|
||||
s, _, browser := cliAuthFixture(t)
|
||||
ctx := context.Background()
|
||||
verifier := strings.Repeat("a", 43)
|
||||
id, device, code, err := s.StartCLIAuth(ctx, "domain", cliTestOrigin, hashAuthToken(verifier))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, _, _, err := s.ExchangeCLIAuth(ctx, "domain", cliTestOrigin, device, verifier); !errors.Is(err, ErrCLIPending) {
|
||||
t.Fatalf("pending: %v", err)
|
||||
}
|
||||
if _, _, _, err := s.ExchangeCLIAuth(ctx, "domain", cliTestOrigin, device, verifier); !errors.Is(err, ErrCLISlowDown) {
|
||||
t.Fatalf("poll rate: %v", err)
|
||||
}
|
||||
if err := s.BindCLIAuth(ctx, "domain", cliTestOrigin, id, browser); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := s.BindCLIAuth(ctx, "domain", cliTestOrigin, id, browser); err == nil {
|
||||
t.Fatal("request rebound")
|
||||
}
|
||||
if err := s.DecideCLIAuth(ctx, "domain", cliTestOrigin, id, browser, code, "", true); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := s.DB.Exec(`UPDATE auth_cli_requests SET next_poll_ms=0`); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var wg sync.WaitGroup
|
||||
var successes atomic.Int32
|
||||
for range 12 {
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
token, name, expires, err := s.ExchangeCLIAuth(ctx, "domain", cliTestOrigin, device, verifier)
|
||||
if err == nil {
|
||||
if !strings.HasPrefix(token, "pw_api_") || name != "owner" || expires <= time.Now().UnixMilli() {
|
||||
t.Errorf("bad issued session")
|
||||
}
|
||||
if _, err := s.PrincipalForSession("domain", token); err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
successes.Add(1)
|
||||
}
|
||||
}()
|
||||
}
|
||||
wg.Wait()
|
||||
if successes.Load() != 1 {
|
||||
t.Fatalf("issued %d sessions", successes.Load())
|
||||
}
|
||||
var count int
|
||||
if err := s.DB.QueryRow(`SELECT count(*) FROM auth_sessions`).Scan(&count); err != nil || count != 2 {
|
||||
t.Fatalf("sessions=%d %v", count, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCLIAuthBoundariesAndRevocation(t *testing.T) {
|
||||
for _, mode := range []string{"domain", "origin", "verifier", "device", "expired", "denied", "suspended", "membership", "browser revoked", "new totp"} {
|
||||
t.Run(mode, func(t *testing.T) {
|
||||
s, principal, browser := cliAuthFixture(t)
|
||||
ctx := context.Background()
|
||||
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 err := s.DecideCLIAuth(ctx, "domain", cliTestOrigin, id, browser, code, "", mode != "denied"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
domain, origin := "domain", cliTestOrigin
|
||||
var query string
|
||||
switch mode {
|
||||
case "domain":
|
||||
domain = "other"
|
||||
case "origin":
|
||||
origin = "https://alias.example"
|
||||
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 "new totp":
|
||||
_, err = s.DB.Exec(`INSERT INTO auth_credentials(uuid,principal_uuid,kind,identifier,secret_hash,created_at_ms,updated_at_ms,enabled) VALUES('totp',?,'totp',?,'invalid',1,1,1)`, principal, principal)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if query != "" {
|
||||
if _, err := s.DB.Exec(query); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if token, _, _, err := s.ExchangeCLIAuth(ctx, domain, origin, device, verifier); err == nil || token != "" {
|
||||
t.Fatalf("bypass %s", mode)
|
||||
}
|
||||
var count int
|
||||
if err := s.DB.QueryRow(`SELECT count(*) FROM auth_sessions`).Scan(&count); err != nil || count != 1 {
|
||||
t.Fatalf("session leaked %d %v", count, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestCLIAuthApprovalAttemptsAndIssuanceCap(t *testing.T) {
|
||||
s, _, browser := cliAuthFixture(t)
|
||||
ctx := context.Background()
|
||||
id, _, code, err := s.StartCLIAuth(ctx, "domain", cliTestOrigin, strings.Repeat("c", 43))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := s.BindCLIAuth(ctx, "domain", cliTestOrigin, id, browser); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for range 5 {
|
||||
if err := s.DecideCLIAuth(ctx, "domain", cliTestOrigin, id, browser, "wrong", "", true); err == nil {
|
||||
t.Fatal("wrong code accepted")
|
||||
}
|
||||
}
|
||||
if err := s.DecideCLIAuth(ctx, "domain", cliTestOrigin, id, browser, code, "", true); err == nil {
|
||||
t.Fatal("attempt limit bypassed")
|
||||
}
|
||||
for range 63 {
|
||||
if _, _, _, err := s.StartCLIAuth(ctx, "domain", cliTestOrigin, strings.Repeat("c", 43)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if _, _, _, err := s.StartCLIAuth(ctx, "domain", cliTestOrigin, strings.Repeat("c", 43)); !errors.Is(err, ErrCLILimit) {
|
||||
t.Fatalf("cap: %v", err)
|
||||
}
|
||||
s.ReadOnly = true
|
||||
if _, _, _, err := s.StartCLIAuth(ctx, "domain", cliTestOrigin, strings.Repeat("c", 43)); !errors.Is(err, ErrReadOnly) {
|
||||
t.Fatalf("readonly: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCLIAuthSessionFailureRollsBackConsumption(t *testing.T) {
|
||||
s, _, browser := cliAuthFixture(t)
|
||||
ctx := context.Background()
|
||||
verifier := strings.Repeat("e", 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 err := s.DecideCLIAuth(ctx, "domain", cliTestOrigin, id, browser, code, "", true); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := s.DB.Exec(`CREATE TRIGGER reject_cli_session BEFORE INSERT ON auth_sessions BEGIN SELECT RAISE(ABORT,'synthetic failure'); END`); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if token, _, _, err := s.ExchangeCLIAuth(ctx, "domain", cliTestOrigin, device, verifier); err == nil || token != "" {
|
||||
t.Fatal("failed write accepted")
|
||||
}
|
||||
grant, err := s.CLIAuthRequest(ctx, "domain", cliTestOrigin, id)
|
||||
if err != nil || grant.State != "approved" {
|
||||
t.Fatalf("consumed without session: %+v %v", grant, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCLIAuthRequiresTOTPAndPreservesLevel(t *testing.T) {
|
||||
s, principal, browser := cliAuthFixture(t)
|
||||
ctx := context.Background()
|
||||
verifier := strings.Repeat("t", 43)
|
||||
secret, err := s.BeginTOTPEnrollment(principal)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
code, err := totpCode(secret, time.Now().Unix()/30)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := s.ConfirmTOTPEnrollment(principal, code); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
id, device, userCode, err := s.StartCLIAuth(ctx, "domain", cliTestOrigin, hashAuthToken(verifier))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for range 3 {
|
||||
if err := s.BeginCLIAuth(ctx, "domain", cliTestOrigin, id); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if err := s.BeginCLIAuth(ctx, "domain", cliTestOrigin, id); err == nil {
|
||||
t.Fatal("OIDC challenge amplification allowed")
|
||||
}
|
||||
if err := s.BindCLIAuth(ctx, "domain", cliTestOrigin, id, browser); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := s.DecideCLIAuth(ctx, "domain", cliTestOrigin, id, browser, userCode, "", true); err == nil {
|
||||
t.Fatal("TOTP bypass")
|
||||
}
|
||||
code, err = totpCode(secret, time.Now().Unix()/30+1)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := s.DecideCLIAuth(ctx, "domain", cliTestOrigin, id, browser, userCode, code, true); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
token, _, _, err := s.ExchangeCLIAuth(ctx, "domain", cliTestOrigin, device, verifier)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var level int
|
||||
if err := s.DB.QueryRow(`SELECT mfa_level FROM auth_sessions WHERE token_hash=?`, hashAuthToken(token)).Scan(&level); err != nil || level != 1 {
|
||||
t.Fatalf("MFA not preserved: %d %v", level, err)
|
||||
}
|
||||
}
|
||||
@@ -12,6 +12,7 @@ import (
|
||||
// Once released, add a new version; never edit an applied definition.
|
||||
// Auth, City, tasks and calendars remain in their existing migration paths.
|
||||
var managedStoreSchemas = map[string][]db.SQLMigration{
|
||||
"cli-auth": cliAuthMigrations,
|
||||
"profile-contacts": profileContactMigrations,
|
||||
"event-jobs": eventJobMigrations,
|
||||
"projection-metadata": {{Version: 1, Name: "adopt_projection_metadata", Statements: []string{
|
||||
|
||||
@@ -102,6 +102,9 @@ func NewWithDocumentRoot(
|
||||
if err := st.EnsureAuthSchema(); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
if err := st.ensureSchemaComponent("cli-auth"); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
if err := st.EnsureTasksSchema(); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
+29
-1
@@ -34,6 +34,34 @@ pages[default]:/manual> exit
|
||||
|
||||
`exit` はシェルを閉じるだけです。セッションを失効させる場合は `pages logout`。
|
||||
|
||||
### OIDCでログインする
|
||||
|
||||
OIDC連携を有効にしたDomainで利用します。サーバーとCLIの両方に **v0.3.0以降** が必要です。
|
||||
CLIのファイルだけを更新しても、v0.2.xのサーバーでは利用できません。
|
||||
|
||||
```sh
|
||||
pages configure --origin https://pages.example.test
|
||||
pages login --oidc
|
||||
# SSH先など、ブラウザを自動で開かない場合
|
||||
pages login --oidc --no-browser
|
||||
```
|
||||
|
||||
CLIに表示されたURLを手元のPC/スマホで開き、OIDCでログインします。
|
||||
続いてアカウント・接続先を確認し、ターミナルの確認コードを入力して承認します。
|
||||
ローカルTOTPを設定済みならTOTPも必要です。承認後はCLIが専用セッションを受け取ります。
|
||||
OIDCプロバイダーのパスワードやトークンをターミナルに入力する必要はありません。
|
||||
|
||||
ユーザー名の指定は省略できます。指定済みならブラウザで認証したユーザーとの一致を確認し、
|
||||
不一致時は発行セッションの失効を試みて保存しません。`pages logout` 後に設定を変更できます。
|
||||
リクエストは5分で失効します。Ctrl+Cはローカルの待機を終了し、未交換リクエストは期限で失効します。
|
||||
他人から送られたURL・コードでは承認しないでください。通信断で交換結果が不明な場合は自動再送せず、
|
||||
サーバのセッション管理で不要なセッションを確認・失効してからログインし直します。
|
||||
|
||||
`CLI OIDC login is unavailable on this server` は開始APIが利用できない場合の表示です。
|
||||
configureの接続先URLを確認し、サーバーも対応版へ更新してください。
|
||||
`OIDC login is not enabled for this domain` の場合は、対象DomainのOIDC設定を確認してください。
|
||||
`--no-browser` はブラウザーの自動起動だけを抑止し、承認待ちとセッション取得は通常どおり行います。
|
||||
|
||||
## 設定する
|
||||
|
||||
```sh
|
||||
@@ -94,7 +122,7 @@ pages edit /guide
|
||||
`pages --help`、`pages configure --help`、`pages edit --help` で引数を確認できます。
|
||||
Tab補完、上下キーのプロセス内履歴に対応。複雑な引用位置の補完、Ctrl+Pのfuzzy UIは後続です。
|
||||
|
||||
初期版は既存Page・既存言語の更新まで。新規作成、OIDC引き継ぎ、バイナリ更新は未実装です。
|
||||
初期版は既存Page・既存言語の更新まで。新規作成、バイナリ更新は未実装です。
|
||||
競合や通信断で自動上書きせず、ローカル原稿を保持します。HTTPS必須(開発用loopbackのみHTTP可)。
|
||||
詳しいURI・保存・安全性の契約は[設計書](../docs/design/ja/remote-cli.md)を参照してください。
|
||||
|
||||
|
||||
+75
-8
@@ -1,6 +1,7 @@
|
||||
#!/usr/bin/env python3
|
||||
"""pages — navigate and edit PagesWiki from your terminal (pages-cli)."""
|
||||
import argparse
|
||||
import base64
|
||||
import contextlib
|
||||
import difflib
|
||||
import fcntl
|
||||
@@ -11,6 +12,7 @@ import os
|
||||
from pathlib import Path
|
||||
import posixpath
|
||||
import re
|
||||
import secrets
|
||||
import shlex
|
||||
import stat
|
||||
import subprocess
|
||||
@@ -130,11 +132,69 @@ class Client:
|
||||
raise
|
||||
result = self.json('/_/auth/totp', method='POST', form={
|
||||
'challenge_token': e.payload['challenge_token'], 'code': otp('TOTP: ')})
|
||||
return self.accept_session(result)
|
||||
|
||||
def accept_session(self, result):
|
||||
token = result.get('access_token')
|
||||
if not isinstance(token, str) or not re.fullmatch(r'[A-Za-z0-9_.~-]{16,1024}', token) or result.get('token_type') != 'Bearer':
|
||||
raise Failure('Server did not issue a Bearer session.')
|
||||
duration = result.get('expires_in')
|
||||
if not isinstance(duration, int) or isinstance(duration, bool) or not 1 <= duration <= 30*24*60*60:
|
||||
raise Failure('Invalid session lifetime.')
|
||||
self.token = token
|
||||
return time.time() + int(result['expires_in'])
|
||||
return time.time() + duration
|
||||
|
||||
def login_oidc(self, no_browser=False, expected_username='', *, sleep=time.sleep, clock=time.monotonic):
|
||||
verifier = secrets.token_urlsafe(32)
|
||||
challenge = base64.urlsafe_b64encode(hashlib.sha256(verifier.encode()).digest()).decode().rstrip('=')
|
||||
try:
|
||||
started = self.json('/_/auth/cli/start', method='POST', form={
|
||||
'code_challenge': challenge, 'code_challenge_method': 'S256'})
|
||||
except Failure as e:
|
||||
if e.status in (404, 405, 501):
|
||||
raise Failure('CLI OIDC login is unavailable on this server. Check the configured server URL and deploy a server version supporting /_/auth/cli/start.', e.status) from None
|
||||
if e.status == 403 and e.payload.get('error') == 'oidc_disabled':
|
||||
raise Failure('OIDC login is not enabled for this domain. Ask your administrator to enable it.', e.status) from None
|
||||
raise
|
||||
device, route, code = (started.get(k) for k in ('device_code', 'verification_uri', 'user_code'))
|
||||
if (not isinstance(device, str) or not re.fullmatch(r'[A-Za-z0-9_-]{43}', device)
|
||||
or not isinstance(route, str) or not re.fullmatch(r'/_/auth/cli/verify\?request=[A-Za-z0-9_-]{43}', route)
|
||||
or not isinstance(code, str) or not re.fullmatch(r'[A-F0-9]{4}-[A-F0-9]{4}', code)):
|
||||
raise Failure('Invalid browser login response; no browser was opened.')
|
||||
lifetime, interval = int(started.get('expires_in', 0)), int(started.get('interval', 0))
|
||||
if not 1 <= lifetime <= 300 or not 5 <= interval <= 30:
|
||||
raise Failure('Invalid browser login lifetime or polling interval.')
|
||||
deadline = clock() + lifetime
|
||||
print('Open this URL and approve only the request you started:')
|
||||
print(self.base + route)
|
||||
print('Confirmation code:', code)
|
||||
print('Waiting for approval (up to 5 minutes). Ctrl+C cancels locally.', flush=True)
|
||||
if not no_browser:
|
||||
try: webbrowser.open(self.base + route, new=2)
|
||||
except (webbrowser.Error, OSError): pass # URL remains usable on another device.
|
||||
while clock() + interval < deadline:
|
||||
sleep(interval)
|
||||
try:
|
||||
result = self.json('/_/auth/cli/token', method='POST', form={
|
||||
'device_code': device, 'code_verifier': verifier})
|
||||
except Failure as e:
|
||||
reason = e.payload.get('error')
|
||||
if e.status == 400 and reason == 'authorization_pending': continue
|
||||
if e.status == 400 and reason == 'slow_down':
|
||||
interval = min(30, interval + 5); continue
|
||||
if reason in ('access_denied', 'expired_token', 'oidc_disabled'):
|
||||
raise Failure('Browser login denied, expired or disabled. Restart pages login --oidc.') from None
|
||||
raise # Never retry an ambiguous token exchange or a network failure.
|
||||
name = result.get('username')
|
||||
expires = self.accept_session(result)
|
||||
if (not isinstance(name, str) or not name or any(unicodedata.category(c).startswith('C') for c in name)
|
||||
or (expected_username and name.lower() != expected_username.lower())):
|
||||
try: self.json('/_/auth/logout', method='POST')
|
||||
except Failure: pass
|
||||
self.token = ''
|
||||
raise Failure('The browser account differs from the configured username; attempted to revoke the new session.')
|
||||
return expires, name
|
||||
raise Failure('Browser login expired. Restart pages login --oidc.')
|
||||
|
||||
def listing(self, path, prefix=''):
|
||||
return self.json('/_/api/v1/path-picker?' + url.urlencode({'path': path, 'mode': 'children', 'prefix': prefix}))
|
||||
@@ -304,7 +364,7 @@ def configure(words, root=None):
|
||||
# Configuration and session locks use this order. Never retarget an
|
||||
# active credential to a different Domain or account.
|
||||
with Profile(name, root).locked() as session:
|
||||
if session.data.get('token') and (spec['origin'] != session.data.get('origin') or spec.get('username', '') != session.data.get('username')):
|
||||
if session.data.get('token') and (spec['origin'] != session.data.get('origin') or spec.get('username', '') != session.data.get('configured_username', session.data.get('username'))):
|
||||
raise Failure('Log out this profile before changing its origin or username.')
|
||||
data['profiles'][name] = spec
|
||||
if len(data['profiles']) == 1: data['default_profile'] = name
|
||||
@@ -480,7 +540,10 @@ def main(argv=None):
|
||||
parser.print_help(); return
|
||||
if args.command == 'login':
|
||||
login = argparse.ArgumentParser(prog='pages login', description='Log into the configured connection. Password and TOTP are prompted privately.')
|
||||
login.parse_args(args.args)
|
||||
login.add_argument('--oidc', action='store_true', help='Authenticate and approve in a browser; no local password required')
|
||||
login.add_argument('--no-browser', action='store_true', help='Print the browser login URL without opening it (requires --oidc)')
|
||||
login_args = login.parse_args(args.args)
|
||||
if login_args.no_browser and not login_args.oidc: login.error('--no-browser requires --oidc')
|
||||
elif '--help' in args.args:
|
||||
execute(None, None, [args.command] + args.args); return
|
||||
with contextlib.ExitStack() as stack:
|
||||
@@ -494,13 +557,17 @@ def main(argv=None):
|
||||
# Hold the profile lock before releasing the configuration lock.
|
||||
profile = stack.enter_context(Profile(name).locked())
|
||||
if args.command == 'login':
|
||||
if not spec.get('username'): raise Failure('Set your account with pages configure --username NAME.')
|
||||
if not login_args.oidc and not spec.get('username'): raise Failure('Set your account with pages configure --username NAME, or use pages login --oidc.')
|
||||
if profile.data.get('token'): raise Failure('Log out this profile before replacing its session.')
|
||||
client = Client(spec['origin'], lang=lang)
|
||||
expires = client.login(spec['username'], getpass.getpass('Password: '))
|
||||
same_identity = profile.data.get('origin') == client.base and profile.data.get('username') == spec['username']
|
||||
if login_args.oidc:
|
||||
expires, username = client.login_oidc(login_args.no_browser, spec.get('username', ''))
|
||||
else:
|
||||
username = spec['username']
|
||||
expires = client.login(username, getpass.getpass('Password: '))
|
||||
same_identity = profile.data.get('origin') == client.base and profile.data.get('username') == username
|
||||
cwd = profile.data.get('cwd', '/') if same_identity else '/'
|
||||
profile.data = {'origin': client.base, 'username': spec['username'], 'token': client.token, 'expires': expires, 'cwd': cwd}
|
||||
profile.data = {'origin': client.base, 'username': username, 'configured_username': spec.get('username', ''), 'token': client.token, 'expires': expires, 'cwd': cwd}
|
||||
try:
|
||||
profile.save()
|
||||
except OSError:
|
||||
@@ -512,7 +579,7 @@ def main(argv=None):
|
||||
raise Failure('Could not save credentials; attempted to revoke the new session.') from None
|
||||
print('Logged in. Session saved privately.'); return
|
||||
if not profile.data.get('token'): raise Failure('Log in first.')
|
||||
if args.command != 'logout' and (profile.data.get('origin') != spec['origin'] or profile.data.get('username') != spec.get('username')):
|
||||
if args.command != 'logout' and (profile.data.get('origin') != spec['origin'] or profile.data.get('configured_username', profile.data.get('username')) != spec.get('username', '')):
|
||||
raise Failure('Session and configured identity differ. Log out before reconnecting.')
|
||||
if args.command not in ('logout', 'status') and profile.data.get('expires', 0) <= time.time(): raise Failure('Session expired; log out and log in again.')
|
||||
client = Client(profile.data['origin'], profile.data['token'], lang)
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import contextlib
|
||||
import base64
|
||||
from email.message import Message
|
||||
import hashlib
|
||||
import io
|
||||
@@ -38,6 +39,94 @@ def reply(h, status, body, mime='application/json'):
|
||||
|
||||
|
||||
class RemoteTests(unittest.TestCase):
|
||||
def test_oidc_polling_pkce_and_no_secret_output(self):
|
||||
now = [0]
|
||||
waits, calls = [], []
|
||||
started = {'device_code': 'D'*43, 'verification_uri': '/_/auth/cli/verify?request='+'R'*43,
|
||||
'user_code': 'ABCD-1234', 'expires_in': 300, 'interval': 5}
|
||||
client = Client('https://wiki.example')
|
||||
def sleep(seconds): waits.append(seconds); now[0] += seconds
|
||||
def request(route, **kwargs):
|
||||
calls.append((route, kwargs))
|
||||
if route.endswith('/start'): return started
|
||||
polls = len(calls)-1
|
||||
if polls == 1: raise Failure('pending',400,{'error':'authorization_pending'})
|
||||
if polls == 2: raise Failure('slow',400,{'error':'slow_down'})
|
||||
return {'access_token':'pw_api_'+'S'*43,'token_type':'Bearer','expires_in':3600,'username':'anya'}
|
||||
with patch.object(client,'json',side_effect=request), patch.object(m['webbrowser'],'open') as browser, contextlib.redirect_stdout(io.StringIO()) as out:
|
||||
expires, name = client.login_oidc(True,sleep=sleep,clock=lambda:now[0])
|
||||
self.assertEqual(name,'anya'); self.assertGreater(expires,time.time())
|
||||
self.assertEqual(waits,[5,5,10]); browser.assert_not_called()
|
||||
proof = calls[1][1]['form']['code_verifier']
|
||||
expected=base64.urlsafe_b64encode(hashlib.sha256(proof.encode()).digest()).decode().rstrip('=')
|
||||
self.assertEqual(calls[0][1]['form']['code_challenge'],expected)
|
||||
self.assertNotIn(proof,out.getvalue()); self.assertNotIn(started['device_code'],out.getvalue()); self.assertNotIn(client.token,out.getvalue())
|
||||
self.assertIn('ABCD-1234',out.getvalue())
|
||||
|
||||
def test_oidc_unavailable_server_explained_without_retry(self):
|
||||
for status in (404, 405, 501):
|
||||
with self.subTest(status=status):
|
||||
client = Client('https://wiki.example')
|
||||
with patch.object(client, 'json', side_effect=Failure('Not found or not readable.', status)) as api, patch.object(m['webbrowser'], 'open') as browser, contextlib.redirect_stdout(io.StringIO()) as out:
|
||||
with self.assertRaisesRegex(Failure, 'CLI OIDC login is unavailable') as caught:
|
||||
client.login_oidc(True)
|
||||
self.assertEqual(caught.exception.status, status)
|
||||
api.assert_called_once()
|
||||
browser.assert_not_called()
|
||||
self.assertEqual(out.getvalue(), '')
|
||||
self.assertEqual(client.token, '')
|
||||
|
||||
def test_oidc_disabled_and_other_start_errors(self):
|
||||
client = Client('https://wiki.example')
|
||||
with patch.object(client, 'json', side_effect=Failure('Access denied.', 403, {'error': 'oidc_disabled'})):
|
||||
with self.assertRaisesRegex(Failure, 'not enabled for this domain'):
|
||||
client.login_oidc(True)
|
||||
for error in (Failure('Connection/TLS failure.'), Failure('Access denied.', 403), Failure('Unavailable.', 503)):
|
||||
with patch.object(client, 'json', side_effect=error) as api:
|
||||
with self.assertRaises(Failure) as caught:
|
||||
client.login_oidc(True)
|
||||
self.assertIs(caught.exception, error)
|
||||
api.assert_called_once()
|
||||
|
||||
def test_oidc_rejects_external_url_and_wrong_account(self):
|
||||
client=Client('https://wiki.example')
|
||||
started={'device_code':'D'*43,'verification_uri':'https://evil.example/','user_code':'ABCD-1234','expires_in':300,'interval':5}
|
||||
with patch.object(client,'json',return_value=started),patch.object(m['webbrowser'],'open') as browser:
|
||||
with self.assertRaises(Failure): client.login_oidc()
|
||||
browser.assert_not_called()
|
||||
started['verification_uri']='/_/auth/cli/verify?request='+'R'*43
|
||||
token={'access_token':'pw_api_'+'S'*43,'token_type':'Bearer','expires_in':3600,'username':'other'}
|
||||
with patch.object(client,'json',side_effect=[started,token,{}]) as api, contextlib.redirect_stdout(io.StringIO()):
|
||||
with self.assertRaises(Failure): client.login_oidc(True,'anya',sleep=lambda _:None,clock=lambda:0)
|
||||
self.assertEqual(api.call_args.args[0],'/_/auth/logout')
|
||||
self.assertEqual(client.token,'')
|
||||
|
||||
def test_oidc_cancellation_denial_and_ambiguous_exchange(self):
|
||||
started={'device_code':'D'*43,'verification_uri':'/_/auth/cli/verify?request='+'R'*43,'user_code':'ABCD-1234','expires_in':300,'interval':5}
|
||||
for error in [Failure('denied',403,{'error':'access_denied'}),Failure('expired',400,{'error':'expired_token'}),Failure('network failure')]:
|
||||
client=Client('https://wiki.example')
|
||||
with patch.object(client,'json',side_effect=[started,error]) as api,contextlib.redirect_stdout(io.StringIO()):
|
||||
with self.assertRaises(Failure): client.login_oidc(True,sleep=lambda _:None,clock=lambda:0)
|
||||
self.assertEqual(api.call_count,2)
|
||||
client=Client('https://wiki.example')
|
||||
with patch.object(client,'json',return_value=started) as api,contextlib.redirect_stdout(io.StringIO()):
|
||||
def interrupt(_): raise KeyboardInterrupt()
|
||||
with self.assertRaises(KeyboardInterrupt): client.login_oidc(True,sleep=interrupt,clock=lambda:0)
|
||||
self.assertEqual(api.call_count,1)
|
||||
|
||||
def test_oidc_main_without_configured_username(self):
|
||||
with tempfile.TemporaryDirectory() as root, patch.dict(os.environ,{'XDG_CONFIG_HOME':root}):
|
||||
self.configure(None,'--origin','https://wiki.example')
|
||||
def login(client,*args,**kwargs): client.token='pw_api_'+'s'*43; return time.time()+600,'anya'
|
||||
with patch.object(Client,'login_oidc',login),contextlib.redirect_stdout(io.StringIO()):
|
||||
m['main'](['login','--oidc','--no-browser'])
|
||||
m['main'](['status'])
|
||||
self.configure(None,'--lang','ja')
|
||||
with Profile('default').locked() as profile:
|
||||
self.assertEqual(profile.data['username'],'anya')
|
||||
self.assertEqual(profile.data['configured_username'],'')
|
||||
with self.assertRaises(Failure): self.configure(None,'--username','other')
|
||||
|
||||
def configure(self, root, *args):
|
||||
with contextlib.redirect_stdout(io.StringIO()) as output:
|
||||
m['configure'](list(args), root)
|
||||
@@ -204,6 +293,36 @@ class RemoteTests(unittest.TestCase):
|
||||
self.assertEqual(stat.S_IMODE((directory/'recovery.json').stat().st_mode),0o600)
|
||||
|
||||
|
||||
def oidc_integration():
|
||||
fixture=json.load(sys.stdin)
|
||||
original=Client.json
|
||||
grant={}
|
||||
def capture(client,route,**kwargs):
|
||||
result=original(client,route,**kwargs)
|
||||
if route=='/_/auth/cli/start': grant.update(result)
|
||||
return result
|
||||
def browser(target,**kwargs):
|
||||
ident=m['url'].parse_qs(m['url'].urlsplit(target).query)['request'][0]
|
||||
original(Client(fixture['origin']),'/__test/cli-approve',method='POST',form={'request':ident,'code':grant['user_code']})
|
||||
return True
|
||||
with tempfile.TemporaryDirectory() as root,patch.dict(os.environ,{'XDG_CONFIG_HOME':root}),contextlib.redirect_stdout(io.StringIO()) as output:
|
||||
m['main'](['configure','--origin',fixture['origin']])
|
||||
with patch.object(Client,'json',capture),patch.object(m['webbrowser'],'open',browser): m['main'](['login','--oidc'])
|
||||
with Profile('default',root).locked() as session:
|
||||
token=session.data['token']; assert session.data['username']=='admin'
|
||||
m['main'](['ls']); m['main'](['status'])
|
||||
client=Client(fixture['origin'],token)
|
||||
state=client.snapshot('path:/editor-fixture')
|
||||
client.save(state,'# OIDC edit\n\n{{children}}\n',True)
|
||||
assert '{{children}}' in client.snapshot('path:/editor-fixture')['markdown']
|
||||
m['main'](['logout'])
|
||||
assert token not in output.getvalue()
|
||||
try: client.snapshot('path:/editor-fixture')
|
||||
except Failure as e: assert e.status in (401,403,303)
|
||||
else: raise AssertionError('revoked CLI session accepted')
|
||||
print('OIDC CLI configure/login/list/authoring/logout integration passed')
|
||||
|
||||
|
||||
def integration():
|
||||
fixture=json.load(sys.stdin)
|
||||
# Exercise the public entry point with persisted defaults, not only Client.
|
||||
@@ -261,4 +380,5 @@ def integration():
|
||||
|
||||
if __name__=='__main__':
|
||||
if sys.argv[1:] == ['--integration']: integration()
|
||||
elif sys.argv[1:] == ['--oidc-integration']: oidc_integration()
|
||||
else: unittest.main()
|
||||
@@ -1,13 +1,13 @@
|
||||
{{ define "auth.gohtml" }}<!doctype html>
|
||||
<html lang="{{ .Locale }}"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
|
||||
<title>{{ if .Logout }}{{ T "auth.logout" }}{{ else if .MFA }}{{ T "auth.totp" }}{{ else if .Setup }}{{ T "auth.setup" }}{{ else }}{{ T "auth.login" }}{{ end }} · {{ .WikiName }}</title>
|
||||
<title>{{ if .CLIAuth }}{{ T "auth.cli_title" }}{{ else if .Logout }}{{ T "auth.logout" }}{{ else if .MFA }}{{ T "auth.totp" }}{{ else if .Setup }}{{ T "auth.setup" }}{{ else }}{{ T "auth.login" }}{{ end }} · {{ .WikiName }}</title>
|
||||
<link rel="stylesheet" href="/static/css/theme/base.css"><link rel="stylesheet" href="/static/css/main.css"><link rel="stylesheet" href="/static/css/home.css?v=12"><link rel="stylesheet" href="/static/css/auth.css?v=1"><link rel="stylesheet" href="{{ .ThemeCSS }}"></head>
|
||||
<body class="auth-page" style="--home-glass-opacity:{{ .HomeGlassOpacity }}%">
|
||||
{{ if .HomeWallpaperURL }}<img class="home-wallpaper" src="{{ .HomeWallpaperURL }}" alt="" aria-hidden="true" decoding="async" fetchpriority="high" style="opacity:{{ .HomeWallpaperOpacity }}">{{ end }}
|
||||
<a class="auth-brand" href="/">{{ .WikiName }}</a>
|
||||
<main class="auth-shell"><section class="auth-card"><header class="auth-heading"><h1>{{ if .Logout }}{{ T "auth.logout" }}{{ else if .MFA }}{{ T "auth.totp" }}{{ else if .Setup }}{{ T "auth.setup" }}{{ else }}{{ T "auth.login" }}{{ end }}</h1></header>
|
||||
<main class="auth-shell"><section class="auth-card"><header class="auth-heading"><h1>{{ if .CLIAuth }}{{ T "auth.cli_title" }}{{ else if .Logout }}{{ T "auth.logout" }}{{ else if .MFA }}{{ T "auth.totp" }}{{ else if .Setup }}{{ T "auth.setup" }}{{ else }}{{ T "auth.login" }}{{ end }}</h1></header>
|
||||
{{ if .Setup }}<p>{{ T "auth.setup_help" }}</p>{{ end }}{{ if .Error }}<p class="auth-error">{{ .Error }}</p>{{ end }}
|
||||
{{ if .Logout }}<form class="auth-form" method="post" action="/_/auth/logout"><button class="auth-primary" type="submit">{{ T "auth.logout" }}</button><a class="auth-secondary" href="/">{{ .WikiName }}</a></form>{{ else if .MFA }}<form class="auth-form" method="post" action="/_/auth/totp"><input type="hidden" name="return" value="{{ .Return }}"><label>{{ T "auth.totp_code" }}<input name="code" inputmode="numeric" pattern="[0-9]{6}" autocomplete="one-time-code" required autofocus></label><button class="auth-primary">{{ T "auth.verify" }}</button></form>{{ else }}<form class="auth-form" method="post" action="/_/auth/{{ if .Setup }}setup{{ else }}login{{ end }}"><input type="hidden" name="return" value="{{ .Return }}">
|
||||
{{ if .CLIAuth }}{{ template "auth-cli" . }}{{ else if .Logout }}<form class="auth-form" method="post" action="/_/auth/logout"><button class="auth-primary" type="submit">{{ T "auth.logout" }}</button><a class="auth-secondary" href="/">{{ .WikiName }}</a></form>{{ else if .MFA }}<form class="auth-form" method="post" action="/_/auth/totp"><input type="hidden" name="return" value="{{ .Return }}"><label>{{ T "auth.totp_code" }}<input name="code" inputmode="numeric" pattern="[0-9]{6}" autocomplete="one-time-code" required autofocus></label><button class="auth-primary">{{ T "auth.verify" }}</button></form>{{ else }}<form class="auth-form" method="post" action="/_/auth/{{ if .Setup }}setup{{ else }}login{{ end }}"><input type="hidden" name="return" value="{{ .Return }}">
|
||||
{{ if .Setup }}<label>{{ T "auth.bootstrap_token" }}<input name="bootstrap_token" autocomplete="off" required></label><label>{{ T "auth.display_name" }}<input name="display_name" autocomplete="name"></label><label>{{ T "auth.email" }}<input name="email" type="email" autocomplete="email"></label>{{ end }}
|
||||
<label>{{ T "auth.username" }}<input name="username" autocomplete="username" required autofocus></label>
|
||||
<label>{{ T "auth.password" }}<input name="password" type="password" autocomplete="{{ if .Setup }}new-password{{ else }}current-password{{ end }}" minlength="12" required></label>
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
{{ define "auth-cli" }}
|
||||
{{ if .CLIDone }}
|
||||
<p role="status">{{ T "auth.cli_done" }}</p>
|
||||
{{ else }}
|
||||
<p>{{ T "auth.cli_warning" }}</p>
|
||||
<p><strong>{{ .CLIOrigin }}</strong></p>
|
||||
{{ if .CLILogin }}
|
||||
<a class="auth-provider-button" href="{{ .CLILogin }}">{{ T "auth.login_oidc" }}</a>
|
||||
{{ else }}
|
||||
<p>{{ T "auth.cli_account" }}: <strong>{{ .CLIUsername }}</strong></p>
|
||||
<p>{{ T "auth.cli_access" }}</p>
|
||||
<form class="auth-form" method="post" action="/_/auth/cli/verify">
|
||||
<input type="hidden" name="request" value="{{ .CLIRequest }}">
|
||||
<input type="hidden" name="csrf" value="{{ .CLICSRF }}">
|
||||
<label>{{ T "auth.cli_code" }}<input name="user_code" autocomplete="off" autocapitalize="characters" spellcheck="false" maxlength="9" required autofocus placeholder="ABCD-1234"></label>
|
||||
{{ if .CLITOTP }}<label>{{ T "auth.totp_code" }}<input name="totp" inputmode="numeric" pattern="[0-9]{6}" autocomplete="one-time-code" required></label>{{ end }}
|
||||
<button class="auth-primary" type="submit" name="decision" value="approve">{{ T "auth.cli_approve" }}</button>
|
||||
<button class="auth-secondary" type="submit" name="decision" value="deny" formnovalidate>{{ T "auth.cli_deny" }}</button>
|
||||
</form>
|
||||
{{ end }}{{ end }}
|
||||
{{ end }}
|
||||
Reference in new issue
Block a user