Enable CLI language-aware editing and reuse OIDC authentication
This commit is contained in:
1 parent
5821254535
commit
2f7a20f6de
11 files changed
+264
-84
No files matched your search
@@ -2,6 +2,8 @@
|
|||||||
|
|
||||||
2026-11-01。合成データで検証済み。同日、本番サーバのCity更新と合わせてクライアントをホストの `/home/anya/.local/bin/pages` に配置した。実ユーザの資格情報取得・ログイン・本番Page編集は未実施。接続設定とログインは利用者が行う。[反映記録](../../operations/deployments/2026-11-01-city-pages-cli.md)。
|
2026-11-01。合成データで検証済み。同日、本番サーバのCity更新と合わせてクライアントをホストの `/home/anya/.local/bin/pages` に配置した。実ユーザの資格情報取得・ログイン・本番Page編集は未実施。接続設定とログインは利用者が行う。[反映記録](../../operations/deployments/2026-11-01-city-pages-cli.md)。
|
||||||
|
|
||||||
|
v0.3.0のOIDCログインは利用者の動作確認済み。後続変更として、OIDC承認時の追加ローカルTOTPを廃止し、CLIの `auto` 言語選択と既存Pageの新規言語版編集を実装した。この後続変更はソース段階であり、本番サーバー/PATH上のCLIには未反映。
|
||||||
|
|
||||||
## 原設計との整合
|
## 原設計との整合
|
||||||
|
|
||||||
原設計の [Address Model](../address-model.md)、[URI](../uri.md)、[認証バックエンド](../auth-backend.md)、[エディタの保存契約](editor-resilience.md)を使用する。
|
原設計の [Address Model](../address-model.md)、[URI](../uri.md)、[認証バックエンド](../auth-backend.md)、[エディタの保存契約](editor-resilience.md)を使用する。
|
||||||
@@ -24,7 +26,7 @@ pages login
|
|||||||
pages status
|
pages status
|
||||||
pages
|
pages
|
||||||
|
|
||||||
# ワンショット。--lang はコマンドより前に指定する。
|
# ワンショット。editでは --lang をコマンドの後にも指定可能。
|
||||||
pages ls /manual
|
pages ls /manual
|
||||||
pages edit /manual/start
|
pages edit /manual/start
|
||||||
pages get /manual/start ./start.html
|
pages get /manual/start ./start.html
|
||||||
@@ -32,7 +34,7 @@ pages put ./start.html /manual/start --base REVISION_UUID
|
|||||||
pages logout
|
pages logout
|
||||||
```
|
```
|
||||||
|
|
||||||
配置方法と詳しい設定例は [pages-cli README](../../../pages-cli/README.md)。既定プロファイル名は `default`、編集言語は `und`。`pages configure --lang ja` で変更し、`configure set --profile work --origin ... --username ... --lang en` で接続先を追加する。`configure use work` で既定を切り替え、通常操作ではprofile/langの引数を省略する。一時的な `--profile`/`--lang` 上書きも残す。
|
配置方法と詳しい設定例は [pages-cli README](../../../pages-cli/README.md)。既定プロファイル名は `default`、新規プロファイルの編集言語は `auto`。既存の明示設定は保持する。`pages configure --lang auto` で表示対象の言語に追従し、`--lang ja` なら日本語版を指定する。`configure set --profile work --origin ... --username ... --lang en` で接続先を追加し、`configure use work` で既定を切り替える。一時的な `--profile`/`--lang` 上書きも残す。
|
||||||
|
|
||||||
設定は `config.json` の version/default_profile/profiles と、各接続のorigin/username/langに限定。パスワード・Bearerは設定表示へ含めない。configureはネットワーク通信をせず、ログイン中のorigin/username変更を拒否する。mainは設定ロック→セッションロックの順で取得し、起動時の接続先すり替えを防ぐ。手編集時も保存したセッションの接続先・アカウントとの一致を確認してから使用する。logoutは設定を手編集した場合でも、保存済みの元接続先に対して失効する。
|
設定は `config.json` の version/default_profile/profiles と、各接続のorigin/username/langに限定。パスワード・Bearerは設定表示へ含めない。configureはネットワーク通信をせず、ログイン中のorigin/username変更を拒否する。mainは設定ロック→セッションロックの順で取得し、起動時の接続先すり替えを防ぐ。手編集時も保存したセッションの接続先・アカウントとの一致を確認してから使用する。logoutは設定を手編集した場合でも、保存済みの元接続先に対して失効する。
|
||||||
|
|
||||||
@@ -47,11 +49,13 @@ TabはPath候補を取得し、上下キーは当該プロセス内の履歴を
|
|||||||
- `get ADDRESS LOCAL` は最大64 MiBの正本を取得し、SHA-256を照合する。ローカル出力は0600で新規作成し、既存ファイルを上書きしない。Revision UUIDを表示する。
|
- `get ADDRESS LOCAL` は最大64 MiBの正本を取得し、SHA-256を照合する。ローカル出力は0600で新規作成し、既存ファイルを上書きしない。Revision UUIDを表示する。
|
||||||
- `cat` はpipe時に正本バイト列を出力。TTY時には制御文字を除去する。`view` はテキストを `$PAGER`(既定less)に渡し、HTMLを端末上で実行しない。
|
- `cat` はpipe時に正本バイト列を出力。TTY時には制御文字を除去する。`view` はテキストを `$PAGER`(既定less)に渡し、HTMLを端末上で実行しない。
|
||||||
- `edit` は `$EDITOR`(既定vi)をshellを介さず起動。HTMLはauthoring Markdownが既定、その他の対応テキストは原文。`--format raw` でHTMLを直接編集できる。`--format markdown` はHTML文書専用。
|
- `edit` は `$EDITOR`(既定vi)をshellを介さず起動。HTMLはauthoring Markdownが既定、その他の対応テキストは原文。`--format raw` でHTMLを直接編集できる。`--format markdown` はHTML文書専用。
|
||||||
|
- `auto` はRaw HEADのRevision UUIDから言語を確認し、その言語の現在headを再取得する。以降の保存・競合比較はその言語に固定し、途中で通常表示の言語が変わっても追従しない。
|
||||||
|
- 明示言語のheadがなければ表示対象のRevisionを下書きとして読み込む。保存先言語と空の `base_revision_uuid` を保持し、保存時点でもheadがないことをCASで確認する。元の言語版は変更しない。これは内容の分岐であり自動翻訳ではない。無変更で閉じれば新規Revisionは作らない。
|
||||||
- ローカル作業ファイルは0700の一時ディレクトリ内に0600で保存。成功・無変更時は削除、失敗/409/通信断時は原稿とrecovery.jsonを保持して場所を表示する。recovery.jsonにはorigin、UUID、基点Revision、言語、形式を記録し、Bearerは含めない。
|
- ローカル作業ファイルは0700の一時ディレクトリ内に0600で保存。成功・無変更時は削除、失敗/409/通信断時は原稿とrecovery.jsonを保持して場所を表示する。recovery.jsonにはorigin、UUID、基点Revision、言語、形式を記録し、Bearerは含めない。
|
||||||
- 409では最新内容とローカル原稿の差分を表示し、保存は停止する。自動マージ、強制上書き、自動再送はしない。応答喪失時は取得してサーバの状態を確認してから再試行する。
|
- 409では最新内容とローカル原稿の差分を表示し、保存は停止する。自動マージ、強制上書き、自動再送はしない。応答喪失時は取得してサーバの状態を確認してから再試行する。
|
||||||
- `put` は既存Pageの既存言語のみ。`--base` が必須で、現在headと不一致なら送信しない。サーバ保存も同じbaseでCASを行う。編集を保持したい場合は最新を取得して差分を確認し、調整済み原稿とその最新Revisionを明示して保存する。
|
- `put` は既存Pageの既存言語のみ。`--base` が必須で、現在headと不一致なら送信しない。サーバ保存も同じbaseでCASを行う。編集を保持したい場合は最新を取得して差分を確認し、調整済み原稿とその最新Revisionを明示して保存する。
|
||||||
- `put --format markdown` はauthoring変換を使用。rawは正本形式を保持する。ローカル拡張子で保存MIMEを勝手に変更しない。テキスト編集は1 MiB、JSON送信は2 MiBまで。
|
- `put --format markdown` はauthoring変換を使用。rawは正本形式を保持する。ローカル拡張子で保存MIMEを勝手に変更しない。テキスト編集は1 MiB、JSON送信は2 MiBまで。
|
||||||
- `rev:` は取得専用。新規Page、未作成の言語head、バイナリ編集、Asset更新は拒否する。新規作成のためにエディタGETの副作用を利用しない。
|
- `rev:` は取得専用。新規Path/Page、バイナリ編集、Asset更新は拒否する。新規作成のためにエディタGETの副作用を利用しない。新規言語版も保存APIで既存Pageの書込権限を検査する。
|
||||||
- `open` は同一originのPath/UUID/Revisionビューアをブラウザで開く。BearerはURLに含めず、ブラウザ側のログインが必要。共有リンクは自動発行しない。
|
- `open` は同一originのPath/UUID/Revisionビューアをブラウザで開く。BearerはURLに含めず、ブラウザ側のログインが必要。共有リンクは自動発行しない。
|
||||||
|
|
||||||
## HTTP契約
|
## HTTP契約
|
||||||
@@ -67,9 +71,9 @@ TabはPath候補を取得し、上下キーは当該プロセス内の履歴を
|
|||||||
| HTMLへの復帰 | POST `/_/api/v1/render/markdown`、authoring=true、projection=false |
|
| HTMLへの復帰 | POST `/_/api/v1/render/markdown`、authoring=true、projection=false |
|
||||||
| CAS保存 | POST `/_/api/v1/revisions/save` |
|
| CAS保存 | POST `/_/api/v1/revisions/save` |
|
||||||
|
|
||||||
一覧は既存の件数制限を維持し、truncatedを表示する。巨大な全階層を再帰取得しない。読み取りのRaw言語選択は既存サーバの候補選択に従うが、編集は指定言語のheadを必須とし、存在しない場合は拒否する。
|
一覧は既存の件数制限を維持し、truncatedを表示する。巨大な全階層を再帰取得しない。読み取りのRaw言語選択は既存サーバの候補選択に従う。`auto` はRawのlang指定を省略し、実際に選択されたRevisionの言語をeditor/stateのmetadataで確認する。明示言語のheadがない場合だけ、同APIのrevision指定で元の内容を読み込む。元のRevision UUIDを保存の基点に流用せず、空の基点で新規言語版を作る。
|
||||||
|
|
||||||
## OIDCブラウザ引き継ぎ(v0.3.0本番反映済み)
|
## OIDCブラウザ引き継ぎ
|
||||||
|
|
||||||
`pages login --oidc` はブラウザを開き、`--no-browser` はURLだけを表示する。
|
`pages login --oidc` はブラウザを開き、`--no-browser` はURLだけを表示する。
|
||||||
CLI側に受信ポートは不要で、SSH先から開始して別のPC/スマホで承認できる。
|
CLI側に受信ポートは不要で、SSH先から開始して別のPC/スマホで承認できる。
|
||||||
@@ -90,7 +94,7 @@ discovery/grant_type/client registrationへの完全準拠を標榜しない
|
|||||||
| POST `/_/auth/cli/start` | formの`code_challenge`、`code_challenge_method=S256`で開始 |
|
| POST `/_/auth/cli/start` | formの`code_challenge`、`code_challenge_method=S256`で開始 |
|
||||||
| GET `/_/auth/cli/verify?request=...` | OIDCへの入口と、認証後の本人・接続先確認/承認フォーム |
|
| GET `/_/auth/cli/verify?request=...` | OIDCへの入口と、認証後の本人・接続先確認/承認フォーム |
|
||||||
| GET `/_/auth/oidc?cli=...` | 既存のnonce・state・PKCE・署名検証を使うOIDCフロー |
|
| GET `/_/auth/oidc?cli=...` | 既存のnonce・state・PKCE・署名検証を使うOIDCフロー |
|
||||||
| POST `/_/auth/cli/verify` | browser session、CSRF、request、確認コード、必要ならTOTPで承認/拒否 |
|
| POST `/_/auth/cli/verify` | browser session、CSRF、request、確認コードで承認/拒否 |
|
||||||
| POST `/_/auth/cli/token` | formの`device_code`、`code_verifier`を照合して単回交換 |
|
| POST `/_/auth/cli/token` | formの`device_code`、`code_verifier`を照合して単回交換 |
|
||||||
|
|
||||||
1. CLIは暗号学的乱数のverifierを生成し、そのSHA-256を送る。サーバは独立した256bitの
|
1. CLIは暗号学的乱数のverifierを生成し、そのSHA-256を送る。サーバは独立した256bitの
|
||||||
@@ -101,8 +105,9 @@ discovery/grant_type/client registrationへの完全準拠を標榜しない
|
|||||||
3. callbackだけではCLIへ認証情報を渡さない。承認画面はterminalの確認コード入力を要求し、
|
3. callbackだけではCLIへ認証情報を渡さない。承認画面はterminalの確認コード入力を要求し、
|
||||||
フォーム内にコードを埋め込まない。本人が開始した操作だけ承認するよう警告する。
|
フォーム内にコードを埋め込まない。本人が開始した操作だけ承認するよう警告する。
|
||||||
同一origin検査+browser tokenとrequestに束縛したCSRFを使用する。
|
同一origin検査+browser tokenとrequestに束縛したCSRFを使用する。
|
||||||
4. 登録済みローカルTOTPを検査し、使用済みTOTPの再利用も既存処理で拒否する。
|
4. OIDC認証後の承認で追加のローカルTOTPは要求しない。プロバイダーの認証ポリシーを使用する。
|
||||||
承認後に新たにTOTPが有効になった場合、未検証grantの交換を拒否する。
|
OIDC成功だけをMFA成功とは扱わず、未検証のMFA levelを加算しない。
|
||||||
|
ローカルパスワードログイン時のTOTP要件は変更しない。
|
||||||
5. CLIは5秒間隔でpoll。pendingのみ継続し、slow_downで間隔を5秒ずつ最大30秒へ増やす。
|
5. CLIは5秒間隔でpoll。pendingのみ継続し、slow_downで間隔を5秒ずつ最大30秒へ増やす。
|
||||||
拒否・失効・ネットワーク障害・交換応答の喪失では自動再送しない。
|
拒否・失効・ネットワーク障害・交換応答の喪失では自動再送しない。
|
||||||
6. grantの消費と専用`pw_api_`セッション発行を同じtransactionで確定する。
|
6. grantの消費と専用`pw_api_`セッション発行を同じtransactionで確定する。
|
||||||
@@ -141,18 +146,18 @@ Ctrl+C時は未交換grantを即時サーバ削除せず、5分の期限で失
|
|||||||
|
|
||||||
Python unittest:origin制限、端末制御文字、別origin redirect遮断、非JSON/403/サイズ上限、TOTP、資格情報権限・symlink・並行実行拒否、authoring/CAS payload、ダウンロード上書き拒否、409時の原稿保全。
|
Python unittest:origin制限、端末制御文字、別origin redirect遮断、非JSON/403/サイズ上限、TOTP、資格情報権限・symlink・並行実行拒否、authoring/CAS payload、ダウンロード上書き拒否、409時の原稿保全。
|
||||||
|
|
||||||
Python単体試験18件:既定値/複数接続切替/言語保存、一時上書き、設定表示からのトークン除外、接続先変更拒否、PKCE、poll間隔、URL検査、アカウント不一致、取消、通信断、username未指定でのsession保持、開始API未対応/OIDC無効時の診断を検査する。
|
Python単体試験22件:既定値/複数接続切替/言語保存、一時上書き、設定表示からのトークン除外、接続先変更拒否、PKCE、poll間隔、URL検査、アカウント不一致、取消、通信断、username未指定でのsession保持、開始API未対応/OIDC無効時の診断、autoの言語とhead固定、新規言語版の空CAS、無変更終了、競合時の言語固定を検査する。
|
||||||
|
|
||||||
Goの `TestRemoteCLIHTTPIntegration`:一時DBと本物のHTTPハンドラでログイン、一覧、編集状態、authoring変換、保存、古いRevision拒否、Rawハッシュ、immutable拒否、存在しない言語拒否、put、ログアウト後の拒否を検査。Pythonがないビルド環境ではこの統合試験をskipする。外部カレンダーや本番資格情報は使わない。
|
Goの `TestRemoteCLIHTTPIntegration`:一時DBと本物のHTTPハンドラでログイン、一覧、編集状態、authoring変換、保存、古いRevision拒否、Rawハッシュ、immutable拒否、新規言語版作成と並行作成の409、元言語の保持、日本語版のみ存在するPageのauto編集、put、ログアウト後の拒否を検査。Pythonがないビルド環境ではこの統合試験をskipする。外部カレンダーや本番資格情報は使わない。
|
||||||
|
|
||||||
OIDCは署名付き模擬providerによるcallback→承認→交換のHTTP試験、12並行交換で1sessionのみ、
|
OIDCは署名付き模擬providerによるcallback→承認→交換のHTTP試験、12並行交換で1sessionのみ、
|
||||||
越境・別origin・期限・失効・MFA・不正コード・発行上限・途中失敗rollbackを検査する。
|
越境・別origin・期限・失効・MFA・不正コード・発行上限・途中失敗rollbackを検査する。
|
||||||
`TestRemoteCLIOIDCIntegration`ではPython CLIから実際のHTTP経由でconfigure→OIDC待機/交換→一覧→authoring保存→logoutを実行する。
|
`TestRemoteCLIOIDCIntegration`ではPython CLIから実際のHTTP経由でconfigure→OIDC待機/交換→一覧→authoring保存→logoutを実行する。
|
||||||
この試験のブラウザ操作だけはfixtureの承認ブリッジを使い、実OIDC callbackは別のHTTP試験で検証する。
|
この試験のブラウザ操作だけはfixtureの承認ブリッジを使い、実OIDC callbackは別のHTTP試験で検証する。
|
||||||
承認画面のChromium試験は1440px/390pxで実フォームとCookieによる承認を確認する。
|
承認画面のChromium試験は1440px/390pxで実フォームとCookieによる承認を確認する。
|
||||||
本番OIDC providerでの実ログインは未実施。
|
v0.3.0の本番OIDCログインは利用者確認済み。追加TOTP省略はローカルTOTP有効の合成アカウントでも検証し、MFA levelを不当に上げないことと既存の検証済みlevelの継承を確認する。
|
||||||
|
|
||||||
2026-11-01の実行結果:全Goテスト(キャッシュなし)、全Go vet、関連store/serverのrace検査、
|
2026-11-01のv0.3.0公開時の実行結果:全Goテスト(キャッシュなし)、全Go vet、関連store/serverのrace検査、
|
||||||
Python 18件、OIDCとパスワードのCLI HTTP統合試験、承認画面と既存CookieログインのChromium試験が成功。
|
Python 18件、OIDCとパスワードのCLI HTTP統合試験、承認画面と既存CookieログインのChromium試験が成功。
|
||||||
CLI承認画面のモバイルスクリーンショットも確認した。実機Safariは未確認。
|
CLI承認画面のモバイルスクリーンショットも確認した。実機Safariは未確認。
|
||||||
前段のイベントログ修正を保持し、OIDCは機能追加としてv0.3.0で公開した。
|
前段のイベントログ修正を保持し、OIDCは機能追加としてv0.3.0で公開した。
|
||||||
@@ -161,6 +166,11 @@ CLI承認画面のモバイルスクリーンショットも確認した。実
|
|||||||
サーバーとCLIの両方が必要。開始APIの404/405/501は未対応または接続先の誤りとして明示し、
|
サーバーとCLIの両方が必要。開始APIの404/405/501は未対応または接続先の誤りとして明示し、
|
||||||
OIDC無効の403と区別する。エラー時のログイン要求は自動再送せず、資格情報も保存しない。
|
OIDC無効の403と区別する。エラー時のログイン要求は自動再送せず、資格情報も保存しない。
|
||||||
|
|
||||||
|
同日の後続変更でも全Goテスト(キャッシュなし)、全Go vet、CLI関連store/serverのrace検査、
|
||||||
|
Python 22件、承認画面と既存CookieログインのChromium試験が成功した。
|
||||||
|
`TestRemoteCLILanguageForkRequiresWritePermission`で、有効なreadonlyセッションからの言語版作成が403になり、Revisionが残らないことも確認した。
|
||||||
|
この後続変更は未リリース・未デプロイであり、上記v0.3.0の反映記録とは区別する。
|
||||||
|
|
||||||
ソースのチェックポイント:`.deployment-backups/dev-cli-oidc-20261101/source-after.tar.gz`
|
ソースのチェックポイント:`.deployment-backups/dev-cli-oidc-20261101/source-after.tar.gz`
|
||||||
(SHA-256 `3e4228cd53b4220dffe43a80b4ed02c0bd757a8b3845829b7d3a77a64b0e9c4b`)。
|
(SHA-256 `3e4228cd53b4220dffe43a80b4ed02c0bd757a8b3845829b7d3a77a64b0e9c4b`)。
|
||||||
OIDC関連18ファイルのみで、本番DB・鍵・セッション・前段のログ保存修正は含まない。
|
OIDC関連18ファイルのみで、本番DB・鍵・セッション・前段のログ保存修正は含まない。
|
||||||
@@ -169,7 +179,7 @@ OIDC関連18ファイルのみで、本番DB・鍵・セッション・前段の
|
|||||||
次段階の順序:
|
次段階の順序:
|
||||||
|
|
||||||
1. Ctrl+Pによる検索選択、補完の引用文字/途中カーソル対応、永続履歴の明示opt-in。
|
1. Ctrl+Pによる検索選択、補完の引用文字/途中カーソル対応、永続履歴の明示opt-in。
|
||||||
2. 新規Page+Path+初回Revisionの原子的な作成API、create/upload-only権限、並行作成の衝突、言語分岐。
|
2. 新規Page+Path+初回Revisionの原子的な作成API、create/upload-only権限、並行作成の衝突。既存Pageの言語分岐は実装済み。
|
||||||
3. 競合の対話選択・復旧コマンド、巨大転送のstreamingとキャンセル、mget/mput(globのlocal/remoteを明示)。
|
3. 競合の対話選択・復旧コマンド、巨大転送のstreamingとキャンセル、mget/mput(globのlocal/remoteを明示)。
|
||||||
4. OIDC引き継ぎの本番schema適用・サーバ/CLI配布はv0.3.0で完了。実providerでの本人ログイン・承認は利用者確認が残る。
|
4. OIDC引き継ぎの本番schema適用・サーバ/CLI配布と利用者確認はv0.3.0で完了。追加TOTP省略と言語編集改善の配布は未実施。schema v1の定義は変更しない。
|
||||||
5. OS keyring、Windows対応、非公開の短縮リンク引き継ぎ。自動的な公開shareは行わない。
|
5. OS keyring、Windows対応、非公開の短縮リンク引き継ぎ。自動的な公開shareは行わない。
|
||||||
@@ -164,7 +164,6 @@ func (s *Server) verifyCLIAuth(w http.ResponseWriter, r *http.Request) {
|
|||||||
}
|
}
|
||||||
data["CLIUsername"] = principal.Username
|
data["CLIUsername"] = principal.Username
|
||||||
data["CLICSRF"] = cliConsentCSRF(token, id)
|
data["CLICSRF"] = cliConsentCSRF(token, id)
|
||||||
data["CLITOTP"] = s.store.HasTOTP(principal.UUID)
|
|
||||||
if r.Method == http.MethodPost {
|
if r.Method == http.MethodPost {
|
||||||
if !validBrowserMutationOrigin(r) || subtle.ConstantTimeCompare([]byte(r.PostForm.Get("csrf")), []byte(cliConsentCSRF(token, id))) != 1 {
|
if !validBrowserMutationOrigin(r) || subtle.ConstantTimeCompare([]byte(r.PostForm.Get("csrf")), []byte(cliConsentCSRF(token, id))) != 1 {
|
||||||
http.Error(w, "invalid approval origin or token", 403)
|
http.Error(w, "invalid approval origin or token", 403)
|
||||||
|
|||||||
@@ -11,7 +11,7 @@ func init() {
|
|||||||
"auth.cli_approve": "このCLIを承認する",
|
"auth.cli_approve": "このCLIを承認する",
|
||||||
"auth.cli_deny": "拒否する",
|
"auth.cli_deny": "拒否する",
|
||||||
"auth.cli_done": "リクエストは処理済みです。ターミナルに戻って結果を確認してください。この画面は閉じられます。",
|
"auth.cli_done": "リクエストは処理済みです。ターミナルに戻って結果を確認してください。この画面は閉じられます。",
|
||||||
"auth.cli_invalid": "確認コードまたはTOTPが正しくないか、リクエストが失効しました。5回失敗した場合はCLIでログインをやり直してください。",
|
"auth.cli_invalid": "確認コードが正しくないか、リクエストが失効しました。5回失敗した場合はCLIでログインをやり直してください。",
|
||||||
},
|
},
|
||||||
"en": {
|
"en": {
|
||||||
"auth.cli_title": "Approve terminal access",
|
"auth.cli_title": "Approve terminal access",
|
||||||
@@ -22,7 +22,7 @@ func init() {
|
|||||||
"auth.cli_approve": "Approve this CLI",
|
"auth.cli_approve": "Approve this CLI",
|
||||||
"auth.cli_deny": "Deny",
|
"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_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.",
|
"auth.cli_invalid": "Incorrect confirmation code or expired request. After five failed attempts, restart login from the CLI.",
|
||||||
},
|
},
|
||||||
} {
|
} {
|
||||||
for key, value := range entries {
|
for key, value := range entries {
|
||||||
|
|||||||
@@ -28,7 +28,12 @@ func cliForm(s *Server, path string, form url.Values, cookie, origin string) *ht
|
|||||||
}
|
}
|
||||||
|
|
||||||
func TestCLIAuthOIDCFlow(t *testing.T) {
|
func TestCLIAuthOIDCFlow(t *testing.T) {
|
||||||
s, _, domain := configFixture(t)
|
s, api, domain := configFixture(t)
|
||||||
|
principal := s.mustCLIPrincipal(t, domain, api)
|
||||||
|
// An enrolled local factor must not add a second challenge to OIDC consent.
|
||||||
|
if _, err := s.store.DB.Exec(`INSERT INTO auth_credentials(uuid,principal_uuid,kind,identifier,secret_hash,created_at_ms,updated_at_ms,enabled) VALUES('cli-test-totp',?,'totp',?,'synthetic-invalid',1,1,1)`, principal, principal); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
p := newOIDCTestProvider(t)
|
p := newOIDCTestProvider(t)
|
||||||
previous := oidcVerifier
|
previous := oidcVerifier
|
||||||
oidcVerifier = p.verifier
|
oidcVerifier = p.verifier
|
||||||
@@ -93,6 +98,9 @@ func TestCLIAuthOIDCFlow(t *testing.T) {
|
|||||||
if w.Code != 200 || !strings.Contains(w.Body.String(), `name="user_code"`) || !strings.Contains(w.Body.String(), cliConsentCSRF(browser, id)) {
|
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())
|
t.Fatalf("consent %d %s", w.Code, w.Body.String())
|
||||||
}
|
}
|
||||||
|
if strings.Contains(w.Body.String(), `name="totp"`) {
|
||||||
|
t.Fatal("OIDC consent repeated local TOTP")
|
||||||
|
}
|
||||||
form := url.Values{"request": {id}, "csrf": {cliConsentCSRF(browser, id)}, "user_code": {grant.Code}, "decision": {"approve"}}
|
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 {
|
if w := cliForm(s, "/_/auth/cli/verify", form, browser, "https://evil.example"); w.Code != 403 {
|
||||||
t.Fatal("cross-origin approval accepted")
|
t.Fatal("cross-origin approval accepted")
|
||||||
|
|||||||
@@ -17,7 +17,14 @@ func TestRemoteCLIHTTPIntegration(t *testing.T) {
|
|||||||
if _, err := exec.LookPath("python3"); err != nil {
|
if _, err := exec.LookPath("python3"); err != nil {
|
||||||
t.Skip("python3 not installed")
|
t.Skip("python3 not installed")
|
||||||
}
|
}
|
||||||
s, _, _, _ := editorFixture(t)
|
s, _, domain, _ := editorFixture(t)
|
||||||
|
object, err := s.store.CreatePageAtPathInDomain(domain, "/ja-only")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if _, err := s.store.SaveRevisionForLanguage(object, "<h1>日本語のページ</h1><p>{{children}}</p>", "", "ja"); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
s.mux.HandleFunc("/_/auth/", s.handleAuth)
|
s.mux.HandleFunc("/_/auth/", s.handleAuth)
|
||||||
s.mux.HandleFunc("/v/raw/", s.handleRawView)
|
s.mux.HandleFunc("/v/raw/", s.handleRawView)
|
||||||
s.mux.HandleFunc("/_/api/v1/path-picker", s.handlePathPickerAPI)
|
s.mux.HandleFunc("/_/api/v1/path-picker", s.handlePathPickerAPI)
|
||||||
@@ -36,6 +43,39 @@ func TestRemoteCLIHTTPIntegration(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestRemoteCLILanguageForkRequiresWritePermission(t *testing.T) {
|
||||||
|
s, token, domain, object := editorFixture(t)
|
||||||
|
principal := s.mustCLIPrincipal(t, domain, token)
|
||||||
|
if err := s.store.SetPrincipalState(domain, principal, "readonly"); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
// Changing account state revokes old sessions. Use a newly authenticated
|
||||||
|
// readonly session so this exercises write authorization, not expiration.
|
||||||
|
token, err := s.store.CreateAuthSession(domain, principal)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
body, err := json.Marshal(map[string]any{
|
||||||
|
"object_uuid": object, "body": "<h1>New language</h1>", "lang": "ja",
|
||||||
|
"content_type": "text/html", "base_revision_uuid": "", "editor_principal_uuid": principal,
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
r := httptest.NewRequest("POST", "http://localhost/_/api/v1/revisions/save", bytes.NewReader(body))
|
||||||
|
r.Header.Set("Authorization", "Bearer "+token)
|
||||||
|
r.Header.Set("Content-Type", "application/json")
|
||||||
|
w := httptest.NewRecorder()
|
||||||
|
s.withAuthorization(s.mux).ServeHTTP(w, r)
|
||||||
|
if w.Code != http.StatusForbidden {
|
||||||
|
t.Fatalf("readonly language fork: %d %s", w.Code, w.Body.String())
|
||||||
|
}
|
||||||
|
revision, err := s.store.GetRevisionMetadataForExactLanguage(object, "ja")
|
||||||
|
if err != nil || revision.UUID != "" {
|
||||||
|
t.Fatalf("denied language fork persisted: %s %v", revision.UUID, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func TestRemoteCLIOIDCIntegration(t *testing.T) {
|
func TestRemoteCLIOIDCIntegration(t *testing.T) {
|
||||||
if _, err := exec.LookPath("python3"); err != nil {
|
if _, err := exec.LookPath("python3"); err != nil {
|
||||||
t.Skip("python3 not installed")
|
t.Skip("python3 not installed")
|
||||||
|
|||||||
@@ -124,17 +124,18 @@ func cliChanged(result sql.Result, err error) error {
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// The browser token, confirmation code and current membership are all checked
|
// The verified OIDC callback is the only production caller of BindCLIAuth.
|
||||||
// at mutation time. Attempts are spent before checking TOTP to bound guessing.
|
// Authenticate at the provider, then require explicit local consent, not a
|
||||||
func (s *Store) DecideCLIAuth(ctx context.Context, domain, origin, id, browser, code, totp string, approve bool) error {
|
// second local TOTP challenge. This does not claim the provider performed MFA.
|
||||||
|
func (s *Store) DecideCLIAuth(ctx context.Context, domain, origin, id, browser, code, _ string, approve bool) error {
|
||||||
if s.ReadOnly || !strings.HasPrefix(browser, "pw_browser_") {
|
if s.ReadOnly || !strings.HasPrefix(browser, "pw_browser_") {
|
||||||
return ErrAccessDenied
|
return ErrAccessDenied
|
||||||
}
|
}
|
||||||
now := time.Now().UnixMilli()
|
now := time.Now().UnixMilli()
|
||||||
var principal, expectedCode string
|
var expectedCode string
|
||||||
err := s.DB.QueryRowContext(ctx, `UPDATE auth_cli_requests SET attempts=attempts+1
|
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>?
|
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)
|
RETURNING code_hash`, id, domain, origin, hashAuthToken(browser), now).Scan(&expectedCode)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return ErrAccessDenied
|
return ErrAccessDenied
|
||||||
}
|
}
|
||||||
@@ -143,17 +144,6 @@ func (s *Store) DecideCLIAuth(ctx context.Context, domain, origin, id, browser,
|
|||||||
if hashAuthToken(strings.ToUpper(strings.ReplaceAll(strings.TrimSpace(code), "-", ""))) != expectedCode {
|
if hashAuthToken(strings.ToUpper(strings.ReplaceAll(strings.TrimSpace(code), "-", ""))) != expectedCode {
|
||||||
return ErrAccessDenied
|
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"
|
state := "denied"
|
||||||
if approve {
|
if approve {
|
||||||
@@ -224,7 +214,7 @@ func (s *Store) ExchangeCLIAuth(ctx context.Context, domain, origin, device, ver
|
|||||||
SELECT ?,?,p.uuid,a.domain_uuid,a.auth_time_ms,min(?,a.expires_at_ms),?,max(a.mfa_level,g.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
|
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'
|
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))
|
AND g.id=?
|
||||||
RETURNING principal_uuid,expires_at_ms`, uuid.NewString(), hashAuthToken(token), now+lifetime, now, browser, domain, now, id).Scan(&username, &expires)
|
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) {
|
if errors.Is(err, sql.ErrNoRows) {
|
||||||
err = ErrAccessDenied
|
err = ErrAccessDenied
|
||||||
|
|||||||
@@ -88,9 +88,9 @@ func TestCLIAuthExchangeIsAtomicAndSingleUse(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func TestCLIAuthBoundariesAndRevocation(t *testing.T) {
|
func TestCLIAuthBoundariesAndRevocation(t *testing.T) {
|
||||||
for _, mode := range []string{"domain", "origin", "verifier", "device", "expired", "denied", "suspended", "membership", "browser revoked", "new totp"} {
|
for _, mode := range []string{"domain", "origin", "verifier", "device", "expired", "denied", "suspended", "membership", "browser revoked"} {
|
||||||
t.Run(mode, func(t *testing.T) {
|
t.Run(mode, func(t *testing.T) {
|
||||||
s, principal, browser := cliAuthFixture(t)
|
s, _, browser := cliAuthFixture(t)
|
||||||
ctx := context.Background()
|
ctx := context.Background()
|
||||||
verifier := strings.Repeat("b", 43)
|
verifier := strings.Repeat("b", 43)
|
||||||
id, device, code, err := s.StartCLIAuth(ctx, "domain", cliTestOrigin, hashAuthToken(verifier))
|
id, device, code, err := s.StartCLIAuth(ctx, "domain", cliTestOrigin, hashAuthToken(verifier))
|
||||||
@@ -122,11 +122,6 @@ func TestCLIAuthBoundariesAndRevocation(t *testing.T) {
|
|||||||
query = `UPDATE domain_memberships SET state='suspended'`
|
query = `UPDATE domain_memberships SET state='suspended'`
|
||||||
case "browser revoked":
|
case "browser revoked":
|
||||||
query = `UPDATE auth_sessions SET revoked_at_ms=1`
|
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 query != "" {
|
||||||
if _, err := s.DB.Exec(query); err != nil {
|
if _, err := s.DB.Exec(query); err != nil {
|
||||||
@@ -202,7 +197,7 @@ func TestCLIAuthSessionFailureRollsBackConsumption(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestCLIAuthRequiresTOTPAndPreservesLevel(t *testing.T) {
|
func TestCLIAuthOIDCDoesNotRepeatLocalTOTPOrInventMFA(t *testing.T) {
|
||||||
s, principal, browser := cliAuthFixture(t)
|
s, principal, browser := cliAuthFixture(t)
|
||||||
ctx := context.Background()
|
ctx := context.Background()
|
||||||
verifier := strings.Repeat("t", 43)
|
verifier := strings.Repeat("t", 43)
|
||||||
@@ -232,14 +227,7 @@ func TestCLIAuthRequiresTOTPAndPreservesLevel(t *testing.T) {
|
|||||||
if err := s.BindCLIAuth(ctx, "domain", cliTestOrigin, id, browser); err != nil {
|
if err := s.BindCLIAuth(ctx, "domain", cliTestOrigin, id, browser); err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
if err := s.DecideCLIAuth(ctx, "domain", cliTestOrigin, id, browser, userCode, "", true); err == nil {
|
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)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
token, _, _, err := s.ExchangeCLIAuth(ctx, "domain", cliTestOrigin, device, verifier)
|
token, _, _, err := s.ExchangeCLIAuth(ctx, "domain", cliTestOrigin, device, verifier)
|
||||||
@@ -247,7 +235,29 @@ func TestCLIAuthRequiresTOTPAndPreservesLevel(t *testing.T) {
|
|||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
var level int
|
var level int
|
||||||
|
if err := s.DB.QueryRow(`SELECT mfa_level FROM auth_sessions WHERE token_hash=?`, hashAuthToken(token)).Scan(&level); err != nil || level != 0 {
|
||||||
|
t.Fatalf("OIDC must not invent local MFA: %d %v", level, err)
|
||||||
|
}
|
||||||
|
// Preserve an actually verified level from the bound browser session.
|
||||||
|
strongBrowser, err := s.CreateBrowserAuthSession("domain", principal, 1)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
id, device, userCode, err = s.StartCLIAuth(ctx, "domain", cliTestOrigin, hashAuthToken(verifier))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := s.BindCLIAuth(ctx, "domain", cliTestOrigin, id, strongBrowser); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := s.DecideCLIAuth(ctx, "domain", cliTestOrigin, id, strongBrowser, userCode, "", true); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
token, _, _, err = s.ExchangeCLIAuth(ctx, "domain", cliTestOrigin, device, verifier)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
if err := s.DB.QueryRow(`SELECT mfa_level FROM auth_sessions WHERE token_hash=?`, hashAuthToken(token)).Scan(&level); err != nil || level != 1 {
|
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)
|
t.Fatalf("verified MFA level lost: %d %v", level, err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
+25
-8
@@ -48,8 +48,10 @@ pages login --oidc --no-browser
|
|||||||
|
|
||||||
CLIに表示されたURLを手元のPC/スマホで開き、OIDCでログインします。
|
CLIに表示されたURLを手元のPC/スマホで開き、OIDCでログインします。
|
||||||
続いてアカウント・接続先を確認し、ターミナルの確認コードを入力して承認します。
|
続いてアカウント・接続先を確認し、ターミナルの確認コードを入力して承認します。
|
||||||
ローカルTOTPを設定済みならTOTPも必要です。承認後はCLIが専用セッションを受け取ります。
|
OIDCで認証した場合は、追加のローカルTOTPを要求しません。承認後はCLIが専用セッションを受け取ります。
|
||||||
OIDCプロバイダーのパスワードやトークンをターミナルに入力する必要はありません。
|
OIDCプロバイダーのパスワードやトークンをターミナルに入力する必要はありません。
|
||||||
|
プロバイダー側のMFAポリシーはそのまま適用されます。パスワードログイン時のローカルTOTPも変更しません。
|
||||||
|
この追加TOTP省略はv0.3.0より後の変更です。v0.3.0のサーバーでは従来どおりTOTPを要求します。
|
||||||
|
|
||||||
ユーザー名の指定は省略できます。指定済みならブラウザで認証したユーザーとの一致を確認し、
|
ユーザー名の指定は省略できます。指定済みならブラウザで認証したユーザーとの一致を確認し、
|
||||||
不一致時は発行セッションの失効を試みて保存しません。`pages logout` 後に設定を変更できます。
|
不一致時は発行セッションの失効を試みて保存しません。`pages logout` 後に設定を変更できます。
|
||||||
@@ -66,7 +68,7 @@ configureの接続先URLを確認し、サーバーも対応版へ更新して
|
|||||||
|
|
||||||
```sh
|
```sh
|
||||||
pages configure # 設定を表示(トークンは表示しない)
|
pages configure # 設定を表示(トークンは表示しない)
|
||||||
pages configure --lang ja # 現在の既定接続の編集言語
|
pages configure --lang auto # 表示対象の言語版を編集
|
||||||
pages configure list # 接続先一覧、★が既定
|
pages configure list # 接続先一覧、★が既定
|
||||||
pages configure set --profile work --origin https://work.example.test --username anya --lang en
|
pages configure set --profile work --origin https://work.example.test --username anya --lang en
|
||||||
pages configure use work # 以後はworkを指定不要
|
pages configure use work # 以後はworkを指定不要
|
||||||
@@ -74,11 +76,13 @@ pages status
|
|||||||
pages edit /guide
|
pages edit /guide
|
||||||
```
|
```
|
||||||
|
|
||||||
既定プロファイル名は `default`、既定言語は `und`(言語未指定)です。OSや表示言語から
|
既定プロファイル名は `default`、新しいプロファイルの既定言語は `auto` です。
|
||||||
書き込み先の言語を推測しません。最初に名前付きプロファイルを作った場合はそれを既定とします。
|
`auto` はサーバーが通常表示するRevisionの言語を取得し、その言語の最新版を編集します。
|
||||||
言語は接続先ごとに保持し、編集時はその言語の既存Revisionを使用します。
|
OSの言語からは推測しません。最初に名前付きプロファイルを作った場合はそれを既定とします。
|
||||||
|
言語は接続先ごとに保持します。既存設定の `und`(言語未指定)や `ja` は自動変更しません。
|
||||||
|
以前のCLIで設定済みの場合は `pages configure --lang auto` で切り替えられます。
|
||||||
|
|
||||||
一度だけ変更したいときは `pages --profile personal --lang ja edit /guide` も使えます。
|
一度だけ変更したいときは `pages edit /guide --lang auto`、`pages --profile personal --lang ja edit /guide` も使えます。
|
||||||
プロファイル自体は先にconfigureで登録します。引数の上書きは設定ファイルを書き換えません。
|
プロファイル自体は先にconfigureで登録します。引数の上書きは設定ファイルを書き換えません。
|
||||||
|
|
||||||
設定ファイルは `~/.config/pages-cli/config.json`(`XDG_CONFIG_HOME`対応)。
|
設定ファイルは `~/.config/pages-cli/config.json`(`XDG_CONFIG_HOME`対応)。
|
||||||
@@ -91,7 +95,7 @@ pages edit /guide
|
|||||||
"default": {
|
"default": {
|
||||||
"origin": "https://pages.example.test",
|
"origin": "https://pages.example.test",
|
||||||
"username": "anya",
|
"username": "anya",
|
||||||
"lang": "und"
|
"lang": "auto"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -122,7 +126,20 @@ pages edit /guide
|
|||||||
`pages --help`、`pages configure --help`、`pages edit --help` で引数を確認できます。
|
`pages --help`、`pages configure --help`、`pages edit --help` で引数を確認できます。
|
||||||
Tab補完、上下キーのプロセス内履歴に対応。複雑な引用位置の補完、Ctrl+Pのfuzzy UIは後続です。
|
Tab補完、上下キーのプロセス内履歴に対応。複雑な引用位置の補完、Ctrl+Pのfuzzy UIは後続です。
|
||||||
|
|
||||||
初期版は既存Page・既存言語の更新まで。新規作成、バイナリ更新は未実装です。
|
### 言語を指定して編集する
|
||||||
|
|
||||||
|
```sh
|
||||||
|
pages edit /guide --lang auto # 表示される言語の最新版を編集
|
||||||
|
pages edit /guide --lang ja # 日本語版。未作成なら既存内容から開始
|
||||||
|
pages edit /guide --lang en # 英語版。未作成なら既存内容から開始
|
||||||
|
```
|
||||||
|
|
||||||
|
編集開始時に対象言語を表示します。指定言語のRevisionがない場合は、表示中の版の内容を
|
||||||
|
下書きとして `$EDITOR` を開き、変更を保存するとその言語の最初のRevisionを作ります。
|
||||||
|
自動翻訳ではありません。元の言語版は変更せず、編集せずに閉じた場合は何も作成しません。
|
||||||
|
同じ言語版が先に作成された場合も、競合として保存を止めます。
|
||||||
|
|
||||||
|
対応範囲は既存Pageの更新と新規言語版の作成です。新規Path/Page作成、バイナリ更新は未実装です。
|
||||||
競合や通信断で自動上書きせず、ローカル原稿を保持します。HTTPS必須(開発用loopbackのみHTTP可)。
|
競合や通信断で自動上書きせず、ローカル原稿を保持します。HTTPS必須(開発用loopbackのみHTTP可)。
|
||||||
詳しいURI・保存・安全性の契約は[設計書](../docs/design/ja/remote-cli.md)を参照してください。
|
詳しいURI・保存・安全性の契約は[設計書](../docs/design/ja/remote-cli.md)を参照してください。
|
||||||
|
|
||||||
|
|||||||
+45
-16
@@ -71,7 +71,7 @@ class NoRedirect(http.HTTPRedirectHandler):
|
|||||||
|
|
||||||
|
|
||||||
class Client:
|
class Client:
|
||||||
def __init__(self, base, token='', lang='und'):
|
def __init__(self, base, token='', lang='auto'):
|
||||||
self.base, self.token, self.lang = origin(base), token, lang
|
self.base, self.token, self.lang = origin(base), token, lang
|
||||||
self.opener = http.build_opener(NoRedirect())
|
self.opener = http.build_opener(NoRedirect())
|
||||||
|
|
||||||
@@ -200,24 +200,45 @@ class Client:
|
|||||||
return self.json('/_/api/v1/path-picker?' + url.urlencode({'path': path, 'mode': 'children', 'prefix': prefix}))
|
return self.json('/_/api/v1/path-picker?' + url.urlencode({'path': path, 'mode': 'children', 'prefix': prefix}))
|
||||||
|
|
||||||
def raw(self, addr, method='GET'):
|
def raw(self, addr, method='GET'):
|
||||||
raw, headers = self.request('/v/raw/' + url.quote(addr, safe='/:') + '?' + url.urlencode({'lang': self.lang}), method=method, limit=64 << 20)
|
query = '' if self.lang == 'auto' else '?' + url.urlencode({'lang': self.lang})
|
||||||
|
raw, headers = self.request('/v/raw/' + url.quote(addr, safe='/:') + query, method=method, limit=64 << 20)
|
||||||
digest = headers.get('X-PagesWiki-Document-SHA256')
|
digest = headers.get('X-PagesWiki-Document-SHA256')
|
||||||
if method == 'GET' and (not digest or hashlib.sha256(raw).hexdigest() != digest):
|
if method == 'GET' and (not digest or hashlib.sha256(raw).hexdigest() != digest):
|
||||||
raise Failure('Document SHA-256 mismatch.')
|
raise Failure('Document SHA-256 mismatch.')
|
||||||
return raw, headers
|
return raw, headers
|
||||||
|
|
||||||
def snapshot(self, addr):
|
def snapshot(self, addr, lang=None):
|
||||||
if addr.startswith('rev:'):
|
if addr.startswith('rev:'):
|
||||||
raise Failure('Revision addresses are immutable; edit a path: or uuid: address.')
|
raise Failure('Revision addresses are immutable; edit a path: or uuid: address.')
|
||||||
_, headers = self.raw(addr, 'HEAD')
|
_, headers = self.raw(addr, 'HEAD')
|
||||||
ident = headers.get('X-PagesWiki-Object-UUID')
|
ident = headers.get('X-PagesWiki-Object-UUID')
|
||||||
if not ident:
|
if not ident:
|
||||||
raise Failure('Missing Object UUID metadata.')
|
raise Failure('Missing Object UUID metadata.')
|
||||||
state = self.json('/_/api/v1/editor/state?' + url.urlencode({'uuid': ident, 'lang': self.lang}))
|
target = self.lang if lang is None else lang
|
||||||
|
visible = headers.get('X-PagesWiki-Revision-UUID', '')
|
||||||
|
def load(language, **extra):
|
||||||
|
return self.json('/_/api/v1/editor/state?' + url.urlencode({'uuid': ident, 'lang': language, **extra}))
|
||||||
|
if target == 'auto':
|
||||||
|
# Resolve the viewer's language, then obtain that exact language's
|
||||||
|
# current head. Never save against a head from a different language.
|
||||||
|
target = load('und', revision=visible, metadata=1)['lang'] if visible else 'und'
|
||||||
|
state = load(target)
|
||||||
if not state.get('editable') or not state.get('principal_uuid'):
|
if not state.get('editable') or not state.get('principal_uuid'):
|
||||||
raise Failure('Not an authenticated editable text document; use the browser.')
|
raise Failure('Not an authenticated editable text document; use the browser.')
|
||||||
if not state.get('head_revision_uuid') or not state.get('content_type'):
|
if not state.get('head_revision_uuid'):
|
||||||
raise Failure('No saved revision in this exact language; creation/translation is not supported yet.')
|
# An empty CAS base asserts absence of this language. Seed from the
|
||||||
|
# visible source without changing it or pretending it is the base.
|
||||||
|
if visible:
|
||||||
|
source = load(state['lang'], revision=visible)
|
||||||
|
if not source.get('editable') or source.get('principal_uuid') != state['principal_uuid']:
|
||||||
|
raise Failure('Cannot fork this document or the editing account changed.')
|
||||||
|
for key in ('body', 'markdown', 'content_type', 'filename'):
|
||||||
|
state[key] = source[key]
|
||||||
|
state['source_revision_uuid'] = visible
|
||||||
|
state['source_language'] = source['lang']
|
||||||
|
state['new_language'] = True
|
||||||
|
if not state.get('content_type'):
|
||||||
|
raise Failure('Missing document format; use the browser.')
|
||||||
state['object_uuid'] = ident
|
state['object_uuid'] = ident
|
||||||
return state
|
return state
|
||||||
|
|
||||||
@@ -229,7 +250,7 @@ class Client:
|
|||||||
raise Failure('Markdown authoring is supported only for HTML Wiki documents.')
|
raise Failure('Markdown authoring is supported only for HTML Wiki documents.')
|
||||||
text = self.json('/_/api/v1/render/markdown', method='POST', data={
|
text = self.json('/_/api/v1/render/markdown', method='POST', data={
|
||||||
'markdown': text, 'authoring': True, 'projection': False})['html']
|
'markdown': text, 'authoring': True, 'projection': False})['html']
|
||||||
if text == state['body']:
|
if state['head_revision_uuid'] and text == state['body']:
|
||||||
return {'status': 'unchanged', 'revision_uuid': state['head_revision_uuid']}
|
return {'status': 'unchanged', 'revision_uuid': state['head_revision_uuid']}
|
||||||
return self.json('/_/api/v1/revisions/save', method='POST', data={
|
return self.json('/_/api/v1/revisions/save', method='POST', data={
|
||||||
'object_uuid': state['object_uuid'], 'body': text, 'lang': state['lang'],
|
'object_uuid': state['object_uuid'], 'body': text, 'lang': state['lang'],
|
||||||
@@ -294,7 +315,7 @@ def profile_name(name):
|
|||||||
|
|
||||||
def language(value):
|
def language(value):
|
||||||
if not isinstance(value, str) or not re.fullmatch(r'[A-Za-z]{1,8}(?:-[A-Za-z0-9]{1,8})*', value):
|
if not isinstance(value, str) or not re.fullmatch(r'[A-Za-z]{1,8}(?:-[A-Za-z0-9]{1,8})*', value):
|
||||||
raise Failure('Use a language tag such as und, ja or en-US; the server validates the exact tag.')
|
raise Failure('Use auto or a language tag such as und, ja or en-US; the server validates the exact tag.')
|
||||||
return value
|
return value
|
||||||
|
|
||||||
|
|
||||||
@@ -325,7 +346,7 @@ class Configuration(PrivateJSON):
|
|||||||
raise Failure('Profiles accept only origin, username and lang; never store a password here.')
|
raise Failure('Profiles accept only origin, username and lang; never store a password here.')
|
||||||
if not isinstance(spec.get('username', ''), str) or any(unicodedata.category(c).startswith('C') for c in spec.get('username', '')):
|
if not isinstance(spec.get('username', ''), str) or any(unicodedata.category(c).startswith('C') for c in spec.get('username', '')):
|
||||||
raise Failure('Invalid configured username.')
|
raise Failure('Invalid configured username.')
|
||||||
normalized[name] = dict(spec, origin=origin(spec.get('origin', '')), lang=language(spec.get('lang', 'und')))
|
normalized[name] = dict(spec, origin=origin(spec.get('origin', '')), lang=language(spec.get('lang', 'auto')))
|
||||||
if profiles and default not in profiles: raise Failure('Default profile does not exist.')
|
if profiles and default not in profiles: raise Failure('Default profile does not exist.')
|
||||||
return {'version': 1, 'default_profile': default, 'profiles': normalized}
|
return {'version': 1, 'default_profile': default, 'profiles': normalized}
|
||||||
|
|
||||||
@@ -347,7 +368,7 @@ def configure(words, root=None):
|
|||||||
print(json.dumps(data, ensure_ascii=False, indent=2)); return
|
print(json.dumps(data, ensure_ascii=False, indent=2)); return
|
||||||
if args.action == 'list':
|
if args.action == 'list':
|
||||||
for name, spec in data['profiles'].items():
|
for name, spec in data['profiles'].items():
|
||||||
print(safe_text(('★ ' if name == data['default_profile'] else ' ') + name + ' ' + spec['origin'] + ' ' + spec.get('username', '') + ' [' + spec.get('lang', 'und') + ']'))
|
print(safe_text(('★ ' if name == data['default_profile'] else ' ') + name + ' ' + spec['origin'] + ' ' + spec.get('username', '') + ' [' + spec.get('lang', 'auto') + ']'))
|
||||||
if not data['profiles']: print('No connections. Use: pages configure --origin https://wiki.example --username NAME')
|
if not data['profiles']: print('No connections. Use: pages configure --origin https://wiki.example --username NAME')
|
||||||
return
|
return
|
||||||
if args.action == 'use':
|
if args.action == 'use':
|
||||||
@@ -356,7 +377,7 @@ def configure(words, root=None):
|
|||||||
data['default_profile'] = name
|
data['default_profile'] = name
|
||||||
else:
|
else:
|
||||||
name = profile_name(args.profile or data['default_profile'])
|
name = profile_name(args.profile or data['default_profile'])
|
||||||
spec = dict(data['profiles'].get(name, {'lang': 'und'}))
|
spec = dict(data['profiles'].get(name, {'lang': 'auto'}))
|
||||||
if args.origin is not None: spec['origin'] = origin(args.origin)
|
if args.origin is not None: spec['origin'] = origin(args.origin)
|
||||||
if args.username is not None: spec['username'] = args.username.strip()
|
if args.username is not None: spec['username'] = args.username.strip()
|
||||||
if args.lang is not None: spec['lang'] = language(args.lang)
|
if args.lang is not None: spec['lang'] = language(args.lang)
|
||||||
@@ -378,6 +399,9 @@ def configure(words, root=None):
|
|||||||
|
|
||||||
def editor(client, addr, mode):
|
def editor(client, addr, mode):
|
||||||
state = client.snapshot(addr)
|
state = client.snapshot(addr)
|
||||||
|
print('Editing language:', safe_text(state['lang']))
|
||||||
|
if state.get('new_language'):
|
||||||
|
print('Creating a new language revision; source remains unchanged:', safe_text(state.get('source_language', '(empty)')))
|
||||||
markdown = mode == 'markdown' or (mode == 'auto' and state['content_type'].startswith('text/html'))
|
markdown = mode == 'markdown' or (mode == 'auto' and state['content_type'].startswith('text/html'))
|
||||||
initial = state['markdown'] if markdown else state['body']
|
initial = state['markdown'] if markdown else state['body']
|
||||||
directory = Path(tempfile.mkdtemp(prefix='pageswiki-edit-'))
|
directory = Path(tempfile.mkdtemp(prefix='pageswiki-edit-'))
|
||||||
@@ -397,7 +421,7 @@ def editor(client, addr, mode):
|
|||||||
result = client.save(state, text, markdown)
|
result = client.save(state, text, markdown)
|
||||||
except Failure as error:
|
except Failure as error:
|
||||||
if error.status == 409:
|
if error.status == 409:
|
||||||
latest = client.snapshot('uuid:' + state['object_uuid'])
|
latest = client.snapshot('uuid:' + state['object_uuid'], lang=state['lang'])
|
||||||
remote = latest['markdown'] if markdown else latest['body']
|
remote = latest['markdown'] if markdown else latest['body']
|
||||||
print(safe_text(''.join(difflib.unified_diff(remote.splitlines(True), text.splitlines(True), fromfile='remote', tofile='local'))))
|
print(safe_text(''.join(difflib.unified_diff(remote.splitlines(True), text.splitlines(True), fromfile='remote', tofile='local'))))
|
||||||
raise
|
raise
|
||||||
@@ -411,7 +435,8 @@ def editor(client, addr, mode):
|
|||||||
metadata = directory / 'recovery.json'
|
metadata = directory / 'recovery.json'
|
||||||
metadata.touch(mode=0o600)
|
metadata.touch(mode=0o600)
|
||||||
metadata.write_text(json.dumps({'origin': client.base, 'address': 'uuid:' + state['object_uuid'],
|
metadata.write_text(json.dumps({'origin': client.base, 'address': 'uuid:' + state['object_uuid'],
|
||||||
'base_revision_uuid': state['head_revision_uuid'], 'lang': state['lang'], 'format': 'markdown' if markdown else 'raw'}))
|
'base_revision_uuid': state['head_revision_uuid'], 'source_revision_uuid': state.get('source_revision_uuid', ''),
|
||||||
|
'lang': state['lang'], 'format': 'markdown' if markdown else 'raw'}))
|
||||||
print('Local edit retained:', safe_text(file), file=sys.stderr)
|
print('Local edit retained:', safe_text(file), file=sys.stderr)
|
||||||
|
|
||||||
|
|
||||||
@@ -423,6 +448,7 @@ def execute(client, profile, words):
|
|||||||
p.add_argument('path', nargs='?', default='.')
|
p.add_argument('path', nargs='?', default='.')
|
||||||
if command == 'edit':
|
if command == 'edit':
|
||||||
p.add_argument('--format', choices=['auto', 'raw', 'markdown'], default='auto')
|
p.add_argument('--format', choices=['auto', 'raw', 'markdown'], default='auto')
|
||||||
|
p.add_argument('--lang', help='auto edits the visible language; an explicit tag can create a language revision')
|
||||||
p = sub.add_parser('get'); p.add_argument('path'); p.add_argument('local')
|
p = sub.add_parser('get'); p.add_argument('path'); p.add_argument('local')
|
||||||
p = sub.add_parser('put'); p.add_argument('local'); p.add_argument('path'); p.add_argument('--base', required=True)
|
p = sub.add_parser('put'); p.add_argument('local'); p.add_argument('path'); p.add_argument('--base', required=True)
|
||||||
p.add_argument('--format', choices=['raw', 'markdown'], default='raw')
|
p.add_argument('--format', choices=['raw', 'markdown'], default='raw')
|
||||||
@@ -462,9 +488,12 @@ def execute(client, profile, words):
|
|||||||
route = addr[5:] if addr.startswith('path:') else '/o/' + addr if addr.startswith('uuid:') else '/r/view/' + addr[4:]
|
route = addr[5:] if addr.startswith('path:') else '/o/' + addr if addr.startswith('uuid:') else '/r/view/' + addr[4:]
|
||||||
webbrowser.open(client.base + url.quote(route, safe='/:'), new=2)
|
webbrowser.open(client.base + url.quote(route, safe='/:'), new=2)
|
||||||
elif cmd == 'edit':
|
elif cmd == 'edit':
|
||||||
editor(client, addr, args.format)
|
editing = Client(client.base, client.token, language(args.lang)) if args.lang else client
|
||||||
|
editor(editing, addr, args.format)
|
||||||
elif cmd == 'put':
|
elif cmd == 'put':
|
||||||
state = client.snapshot(addr)
|
state = client.snapshot(addr)
|
||||||
|
if not state['head_revision_uuid']:
|
||||||
|
raise Failure('No revision in the target language; use edit --lang to create a language revision.')
|
||||||
if state['head_revision_uuid'] != args.base: raise Failure('Conflict: supplied base is not the current language head.', 409)
|
if state['head_revision_uuid'] != args.base: raise Failure('Conflict: supplied base is not the current language head.', 409)
|
||||||
text = Path(args.local).read_text(encoding='utf-8')
|
text = Path(args.local).read_text(encoding='utf-8')
|
||||||
print('Revision:', safe_text(client.save(state, text, args.format == 'markdown')['revision_uuid']))
|
print('Revision:', safe_text(client.save(state, text, args.format == 'markdown')['revision_uuid']))
|
||||||
@@ -529,7 +558,7 @@ def shell(client, profile):
|
|||||||
def main(argv=None):
|
def main(argv=None):
|
||||||
parser = argparse.ArgumentParser(prog='pages', description=__doc__, epilog='Commands: configure, login, logout, status, shell, ls, cd, pwd, cat, view, get, put, edit, search, open. Use pages COMMAND --help.')
|
parser = argparse.ArgumentParser(prog='pages', description=__doc__, epilog='Commands: configure, login, logout, status, shell, ls, cd, pwd, cat, view, get, put, edit, search, open. Use pages COMMAND --help.')
|
||||||
parser.add_argument('--profile', help='Use another configured connection for this invocation')
|
parser.add_argument('--profile', help='Use another configured connection for this invocation')
|
||||||
parser.add_argument('--lang', help='Override the configured exact language for this invocation')
|
parser.add_argument('--lang', help='auto or an exact language tag for this invocation')
|
||||||
parser.add_argument('command', nargs='?', default='shell')
|
parser.add_argument('command', nargs='?', default='shell')
|
||||||
parser.add_argument('args', nargs=argparse.REMAINDER)
|
parser.add_argument('args', nargs=argparse.REMAINDER)
|
||||||
args = parser.parse_args(argv)
|
args = parser.parse_args(argv)
|
||||||
@@ -553,7 +582,7 @@ def main(argv=None):
|
|||||||
spec = settings['profiles'].get(name)
|
spec = settings['profiles'].get(name)
|
||||||
if spec is None:
|
if spec is None:
|
||||||
raise Failure('No connection configured. Run: pages configure --origin https://HOST --username NAME')
|
raise Failure('No connection configured. Run: pages configure --origin https://HOST --username NAME')
|
||||||
lang = language(args.lang or spec.get('lang', 'und'))
|
lang = language(args.lang or spec.get('lang', 'auto'))
|
||||||
# Hold the profile lock before releasing the configuration lock.
|
# Hold the profile lock before releasing the configuration lock.
|
||||||
profile = stack.enter_context(Profile(name).locked())
|
profile = stack.enter_context(Profile(name).locked())
|
||||||
if args.command == 'login':
|
if args.command == 'login':
|
||||||
|
|||||||
+84
-6
@@ -139,11 +139,14 @@ class RemoteTests(unittest.TestCase):
|
|||||||
self.configure(root,'use','work')
|
self.configure(root,'use','work')
|
||||||
settings=json.loads(self.configure(root,'show'))
|
settings=json.loads(self.configure(root,'show'))
|
||||||
self.assertEqual(settings['default_profile'],'work')
|
self.assertEqual(settings['default_profile'],'work')
|
||||||
self.assertEqual(settings['profiles']['default']['lang'],'und')
|
self.assertEqual(settings['profiles']['default']['lang'],'auto')
|
||||||
self.assertEqual(settings['profiles']['work']['lang'],'ja')
|
self.assertEqual(settings['profiles']['work']['lang'],'ja')
|
||||||
self.configure(root,'--lang','en-US')
|
self.configure(root,'--lang','en-US')
|
||||||
settings=json.loads(self.configure(root,'show'))
|
settings=json.loads(self.configure(root,'show'))
|
||||||
self.assertEqual(settings['profiles']['work']['lang'],'en-US')
|
self.assertEqual(settings['profiles']['work']['lang'],'en-US')
|
||||||
|
self.configure(root,'--lang','und')
|
||||||
|
settings=json.loads(self.configure(root,'show'))
|
||||||
|
self.assertEqual(settings['profiles']['work']['lang'],'und')
|
||||||
with m['Configuration'](root).locked() as cfg:
|
with m['Configuration'](root).locked() as cfg:
|
||||||
self.assertEqual(stat.S_IMODE(cfg.path.stat().st_mode),0o600)
|
self.assertEqual(stat.S_IMODE(cfg.path.stat().st_mode),0o600)
|
||||||
with self.assertRaises(Failure): self.configure(root,'use','missing')
|
with self.assertRaises(Failure): self.configure(root,'use','missing')
|
||||||
@@ -274,6 +277,62 @@ class RemoteTests(unittest.TestCase):
|
|||||||
self.assertEqual(stat.S_IMODE(Path(file).stat().st_mode),0o600)
|
self.assertEqual(stat.S_IMODE(Path(file).stat().st_mode),0o600)
|
||||||
with self.assertRaises(FileExistsError): m['execute'](client,profile,['get','/path',file])
|
with self.assertRaises(FileExistsError): m['execute'](client,profile,['get','/path',file])
|
||||||
|
|
||||||
|
def test_auto_snapshot_pins_visible_language_and_head(self):
|
||||||
|
client=Client('https://example.test','token')
|
||||||
|
state={'lang':'ja','head_revision_uuid':'current-ja','content_type':'text/plain','filename':'x.txt','body':'new','markdown':'new','editable':True,'principal_uuid':'owner'}
|
||||||
|
headers={'X-PagesWiki-Object-UUID':'object','X-PagesWiki-Revision-UUID':'visible-ja'}
|
||||||
|
with patch.object(client,'raw',return_value=(b'',headers)),patch.object(client,'json',side_effect=[{'lang':'ja'},state]) as api:
|
||||||
|
result=client.snapshot('path:/x')
|
||||||
|
self.assertEqual(result['lang'],'ja')
|
||||||
|
self.assertEqual(result['head_revision_uuid'],'current-ja')
|
||||||
|
self.assertIn('revision=visible-ja',api.call_args_list[0].args[0])
|
||||||
|
self.assertIn('lang=ja',api.call_args_list[1].args[0])
|
||||||
|
self.assertNotIn('revision=',api.call_args_list[1].args[0])
|
||||||
|
|
||||||
|
def test_fork_uses_empty_base_and_preserves_source(self):
|
||||||
|
client=Client('https://example.test','token','en')
|
||||||
|
target={'lang':'en','head_revision_uuid':'','content_type':'text/html','filename':'','body':'','markdown':'','editable':True,'principal_uuid':'owner'}
|
||||||
|
source=dict(target,lang='ja',body='<h1>Source</h1>',markdown='# Source',revision_uuid='ja-base')
|
||||||
|
headers={'X-PagesWiki-Object-UUID':'object','X-PagesWiki-Revision-UUID':'ja-base'}
|
||||||
|
with patch.object(client,'raw',return_value=(b'',headers)),patch.object(client,'json',side_effect=[target,source]):
|
||||||
|
result=client.snapshot('path:/x')
|
||||||
|
self.assertEqual(result['lang'],'en'); self.assertEqual(result['head_revision_uuid'],'')
|
||||||
|
self.assertEqual(result['source_language'],'ja'); self.assertEqual(result['body'],source['body'])
|
||||||
|
with patch.object(client,'json',return_value={'revision_uuid':'en-new'}) as api:
|
||||||
|
client.save(result,result['body'])
|
||||||
|
self.assertEqual(api.call_args.kwargs['data']['base_revision_uuid'],'')
|
||||||
|
self.assertEqual(api.call_args.kwargs['data']['lang'],'en')
|
||||||
|
for changes in ({'editable':False},{'principal_uuid':'someone-else'}):
|
||||||
|
with patch.object(client,'raw',return_value=(b'',headers)),patch.object(client,'json',side_effect=[dict(target,head_revision_uuid=''),dict(source,**changes)]):
|
||||||
|
with self.assertRaises(Failure): client.snapshot('path:/x')
|
||||||
|
|
||||||
|
def test_editor_unchanged_fork_does_not_save(self):
|
||||||
|
client=Client('https://example.test','token','ja')
|
||||||
|
state={'object_uuid':'object','head_revision_uuid':'','principal_uuid':'owner','lang':'ja',
|
||||||
|
'content_type':'text/plain','filename':'x.txt','body':'source','markdown':'source','new_language':True,'source_language':'und'}
|
||||||
|
with patch.object(client,'snapshot',return_value=state),patch.object(client,'save') as save,patch('subprocess.run') as command,contextlib.redirect_stdout(io.StringIO()):
|
||||||
|
command.return_value.returncode=0
|
||||||
|
m['editor'](client,'path:/x','auto')
|
||||||
|
save.assert_not_called()
|
||||||
|
self.assertFalse(Path(command.call_args.args[0][-1]).exists())
|
||||||
|
|
||||||
|
def test_edit_language_override_does_not_change_profile(self):
|
||||||
|
client=Client('https://example.test','token','und')
|
||||||
|
with tempfile.TemporaryDirectory() as root:
|
||||||
|
profile=Profile('test',root)
|
||||||
|
profile.data={'cwd':'/notes'}
|
||||||
|
def editor_override(editing,addr,mode):
|
||||||
|
self.assertEqual((editing.base,editing.token,editing.lang),(client.base,client.token,'auto'))
|
||||||
|
self.assertEqual((addr,mode),('path:/notes/page','auto'))
|
||||||
|
with patch.dict(m['execute'].__globals__,{'editor':editor_override}):
|
||||||
|
m['execute'](client,profile,['edit','page','--lang','auto'])
|
||||||
|
self.assertEqual(client.lang,'und')
|
||||||
|
self.assertEqual(profile.data,{'cwd':'/notes'})
|
||||||
|
with patch.object(client,'snapshot',return_value={'head_revision_uuid':''}),patch.object(client,'save') as save:
|
||||||
|
with self.assertRaisesRegex(Failure,'use edit --lang'):
|
||||||
|
m['execute'](client,profile,['put','unused','page','--base',''])
|
||||||
|
save.assert_not_called()
|
||||||
|
|
||||||
def test_editor_conflict_retains_private_recovery(self):
|
def test_editor_conflict_retains_private_recovery(self):
|
||||||
state={'object_uuid':'object','head_revision_uuid':'base','principal_uuid':'person','lang':'und',
|
state={'object_uuid':'object','head_revision_uuid':'base','principal_uuid':'person','lang':'und',
|
||||||
'content_type':'text/plain','filename':'x.txt','body':'old','markdown':'old'}
|
'content_type':'text/plain','filename':'x.txt','body':'old','markdown':'old'}
|
||||||
@@ -284,8 +343,9 @@ class RemoteTests(unittest.TestCase):
|
|||||||
Path(args[-1]).write_text('my edit')
|
Path(args[-1]).write_text('my edit')
|
||||||
class Result: returncode=0
|
class Result: returncode=0
|
||||||
return Result()
|
return Result()
|
||||||
with patch('tempfile.mkdtemp',return_value=str(directory)), patch('subprocess.run',side_effect=edit), patch.object(client,'snapshot',return_value=state), patch.object(client,'save',side_effect=Failure('conflict',409)), contextlib.redirect_stdout(io.StringIO()), contextlib.redirect_stderr(io.StringIO()):
|
with patch('tempfile.mkdtemp',return_value=str(directory)), patch('subprocess.run',side_effect=edit), patch.object(client,'snapshot',return_value=state) as snapshot, patch.object(client,'save',side_effect=Failure('conflict',409)), contextlib.redirect_stdout(io.StringIO()), contextlib.redirect_stderr(io.StringIO()):
|
||||||
with self.assertRaises(Failure): m['editor'](client,'path:/x','auto')
|
with self.assertRaises(Failure): m['editor'](client,'path:/x','auto')
|
||||||
|
snapshot.assert_called_with('uuid:object',lang='und')
|
||||||
self.assertEqual((directory/'document.txt').read_text(),'my edit')
|
self.assertEqual((directory/'document.txt').read_text(),'my edit')
|
||||||
recovery=(directory/'recovery.json').read_text()
|
recovery=(directory/'recovery.json').read_text()
|
||||||
self.assertNotIn('secret-token',recovery)
|
self.assertNotIn('secret-token',recovery)
|
||||||
@@ -342,15 +402,33 @@ def integration():
|
|||||||
m['main'](['logout'])
|
m['main'](['logout'])
|
||||||
assert session_token not in output.getvalue()
|
assert session_token not in output.getvalue()
|
||||||
with Profile('default',root).locked() as session: assert 'token' not in session.data
|
with Profile('default',root).locked() as session: assert 'token' not in session.data
|
||||||
client=Client(fixture['origin'])
|
client=Client(fixture['origin'], lang='und')
|
||||||
client.login('admin','a long test password')
|
client.login('admin','a long test password')
|
||||||
addr='path:/editor-fixture'
|
addr='path:/editor-fixture'
|
||||||
state=client.snapshot(addr)
|
state=client.snapshot(addr)
|
||||||
assert state['lang']=='und' and state['principal_uuid']
|
assert state['lang']=='und' and state['principal_uuid']
|
||||||
missing=Client(fixture['origin'], client.token, 'ja')
|
missing=Client(fixture['origin'], client.token, 'ja')
|
||||||
try: missing.snapshot(addr)
|
fork=missing.snapshot(addr)
|
||||||
except Failure: pass
|
assert fork['lang']=='ja' and fork['head_revision_uuid']=='' and fork['new_language']
|
||||||
else: raise AssertionError('missing language silently fell back')
|
assert fork['body']==state['body'] and fork['source_language']=='und'
|
||||||
|
missing.save(fork,'# Japanese draft\n\n{{children}}\n',True)
|
||||||
|
assert missing.snapshot(addr)['lang']=='ja'
|
||||||
|
assert client.snapshot(addr)['head_revision_uuid']==state['head_revision_uuid']
|
||||||
|
try: missing.save(fork,'competing first revision')
|
||||||
|
except Failure as e: assert e.status==409
|
||||||
|
else: raise AssertionError('concurrent language creation overwrote the head')
|
||||||
|
auto=Client(fixture['origin'],client.token)
|
||||||
|
auto_state=auto.snapshot('path:/ja-only')
|
||||||
|
assert auto_state['lang']=='ja' and auto_state['head_revision_uuid']
|
||||||
|
def edit_japanese(args, **kwargs):
|
||||||
|
path=Path(args[-1]); path.write_text(path.read_text()+'\nJapanese edit\n')
|
||||||
|
class Result: returncode=0
|
||||||
|
return Result()
|
||||||
|
with patch('subprocess.run',side_effect=edit_japanese),contextlib.redirect_stdout(io.StringIO()):
|
||||||
|
m['editor'](auto,'path:/ja-only','auto')
|
||||||
|
assert 'Japanese edit' in auto.snapshot('path:/ja-only')['body']
|
||||||
|
pending=Client(fixture['origin'],client.token,'und').snapshot('path:/ja-only')
|
||||||
|
assert pending['head_revision_uuid']==''
|
||||||
assert client.listing('/')['entries']
|
assert client.listing('/')['entries']
|
||||||
assert client.save(state,'# Remote\n\n{{children}}\n',True)['revision_uuid'] != state['head_revision_uuid']
|
assert client.save(state,'# Remote\n\n{{children}}\n',True)['revision_uuid'] != state['head_revision_uuid']
|
||||||
latest=client.snapshot(addr)
|
latest=client.snapshot(addr)
|
||||||
|
|||||||
@@ -13,7 +13,6 @@
|
|||||||
<input type="hidden" name="request" value="{{ .CLIRequest }}">
|
<input type="hidden" name="request" value="{{ .CLIRequest }}">
|
||||||
<input type="hidden" name="csrf" value="{{ .CLICSRF }}">
|
<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>
|
<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-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>
|
<button class="auth-secondary" type="submit" name="decision" value="deny" formnovalidate>{{ T "auth.cli_deny" }}</button>
|
||||||
</form>
|
</form>
|
||||||
|
|||||||
Reference in new issue
Block a user