feat: opt-in OIDC browser open, atomic page creation, and conflict recovery

- Default pages login --oidc to not auto-open a browser and replace --no-browser with --with-open-browser
- Add atomic new Path/Page creation (PUT /_/api/v1/pages/path:... with If-None-Match: *) in pages edit with confirmation and und warning
- Add interactive 409/412 conflict resolution and pages recover (--list, --edit, --discard)
- Update tests, docs (README.md, DISTRIBUTION.md, docs/client-contract.md, docs/neomutt.md), and macOS CI unittest list
This commit is contained in:
Anya Tokugawa committed 2026-11-30 21:26:57 +09:00
1 parent bee03094f3
commit 9b685b72da
9 files changed
+907 -75

No files matched your search

+1 -1
View File
@@ -45,7 +45,7 @@ jobs:
python3 -m venv .venv python3 -m venv .venv
. .venv/bin/activate . .venv/bin/activate
python -m pip install -r requirements-build.txt python -m pip install -r requirements-build.txt
python -m unittest test_pages test_productivity test_distribution test_tls python -m unittest test_pages test_productivity test_distribution test_tls test_remember
python tools/build.py python tools/build.py
python tools/smoke_binary.py dist/pages python tools/smoke_binary.py dist/pages
PAGES_CLI_TEST_BINARY="$PWD/dist/pages" python -m unittest test_tls PAGES_CLI_TEST_BINARY="$PWD/dist/pages" python -m unittest test_tls
+2 -2
View File
@@ -18,8 +18,8 @@ rpm/debは初期配布の必須条件にせず、LinuxはELFを提供する。Py
```sh ```sh
# ダウンロード先で実行。手元にあるファイルをチェックする。 # ダウンロード先で実行。手元にあるファイルをチェックする。
sha256sum --ignore-missing -c pages-cli-v0.4.2-linux-amd64-SHA256SUMS sha256sum --ignore-missing -c pages-cli-v0.5.0-linux-amd64-SHA256SUMS
tar -xzf pages-cli-v0.4.2-linux-amd64.tar.gz tar -xzf pages-cli-v0.5.0-linux-amd64.tar.gz
mkdir -p ~/.local/bin mkdir -p ~/.local/bin
install -m 755 pages ~/.local/bin/pages install -m 755 pages ~/.local/bin/pages
pages --version pages --version
+14 -13
View File
@@ -53,15 +53,15 @@ pages -k logout
**自己署名証明書だけでなく、期限切れやホスト名不一致も許容します。通信は暗号化されますが、相手の真正性を確認できず、中間者攻撃でパスワード・Bearer・文書等を盗み見られる危険があります。** 信頼できる検証環境でのみ明示指定し、常用する環境では信頼するCAをOSへ登録して通常の検証を使ってください。遠隔HTTP、リダイレクト追従、TLS失敗時の自動再送は引き続き許可しません。 **自己署名証明書だけでなく、期限切れやホスト名不一致も許容します。通信は暗号化されますが、相手の真正性を確認できず、中間者攻撃でパスワード・Bearer・文書等を盗み見られる危険があります。** 信頼できる検証環境でのみ明示指定し、常用する環境では信頼するCAをOSへ登録して通常の検証を使ってください。遠隔HTTP、リダイレクト追従、TLS失敗時の自動再送は引き続き許可しません。
OIDCでは `pages -k login --oidc --no-browser` のように指定できます。ただし、スキップするのはCLIのHTTPS要求のみです。開いたブラウザやOIDCプロバイダーの証明書検証は変更しません。 OIDCでは `pages -k login --oidc`(または `pages -k login --oidc --with-open-browser`)のように指定できます。ただし、スキップするのはCLIのHTTPS要求のみです。開いたブラウザやOIDCプロバイダーの証明書検証は変更しません。
### 信頼できる端末でログインを維持する ### 信頼できる端末でログインを維持する
開発版(未リリース)では、対応サーバーと組み合わせて最長30日のログインを選択できます。 v0.5.0以降では、対応サーバーと組み合わせて最長30日のログインを選択できます。
```sh ```sh
pages login --remember pages login --remember
pages login --oidc --no-browser --remember pages login --oidc --remember
``` ```
実際の期限はサーバー管理者の設定に従います。旧サーバーでは通常の期限になる場合があります。 実際の期限はサーバー管理者の設定に従います。旧サーバーでは通常の期限になる場合があります。
@@ -77,8 +77,8 @@ CLIのファイルだけを更新しても、v0.2.xのサーバーでは利用
```sh ```sh
pages configure --origin https://pages.example.test pages configure --origin https://pages.example.test
pages login --oidc pages login --oidc
# SSH先など、ブラウザを自動で開かない場合 # ブラウザを自動で開く場合
pages login --oidc --no-browser pages login --oidc --with-open-browser
``` ```
CLIに表示されたURLを手元のPC/スマホで開き、OIDCでログインします。 CLIに表示されたURLを手元のPC/スマホで開き、OIDCでログインします。
@@ -97,7 +97,7 @@ OIDCプロバイダーのパスワードやトークンをターミナルに入
`CLI OIDC login is unavailable on this server` は開始APIが利用できない場合の表示です。 `CLI OIDC login is unavailable on this server` は開始APIが利用できない場合の表示です。
configureの接続先URLを確認し、サーバーも対応版へ更新してください。 configureの接続先URLを確認し、サーバーも対応版へ更新してください。
`OIDC login is not enabled for this domain` の場合は、対象DomainのOIDC設定を確認してください。 `OIDC login is not enabled for this domain` の場合は、対象DomainのOIDC設定を確認してください。
`--no-browser` はブラウザーの自動起動だけを抑止し、承認待ちとセッション取得は通常どおり行います。 既定では `pages login --oidc` はURLを表示するだけでブラウザを自動起動しません。`--with-open-browser` を指定するとブラウザの自動起動を試み、失敗した場合も表示されたURLからそのまま承認できます。
## 設定する ## 設定する
@@ -152,8 +152,9 @@ OSの言語からは推測しません。最初に名前付きプロファイル
| `ls` / `cd` / `pwd` | Semantic Pathをたどる。仮想フォルダにも移動可能 | | `ls` / `cd` / `pwd` | Semantic Pathをたどる。仮想フォルダにも移動可能 |
| `cat` / `view` | 正本の出力/`$PAGER`で閲覧 | | `cat` / `view` | 正本の出力/`$PAGER`で閲覧 |
| `get ADDRESS LOCAL` | 正本をダウンロード。既存のローカルファイルは上書きしない | | `get ADDRESS LOCAL` | 正本をダウンロード。既存のローカルファイルは上書きしない |
| `edit ADDRESS` | `$EDITOR`で編集。Wikiはauthoring Markdown、他のテキストは原文 | | `edit ADDRESS` | `$EDITOR`で編集。未存在Pathは確認後に新規作成。Wikiはauthoring Markdown、他のテキストは原文 |
| `put LOCAL ADDRESS --base REVISION_UUID` | 明示した基点RevisionとのCASで更新 | | `put LOCAL ADDRESS --base REVISION_UUID` | 明示した基点RevisionとのCASで更新 |
| `recover [PATH]` | 退避された原稿の一覧表示・再開・破棄(`--list` / `--edit` / `--discard`) |
| `search QUERY` | 権限付きの検索候補 | | `search QUERY` | 権限付きの検索候補 |
| `open ADDRESS` | ブラウザで閲覧。ブラウザ側ログインを使用 | | `open ADDRESS` | ブラウザで閲覧。ブラウザ側ログインを使用 |
| `status` / `logout` | 接続状態表示/セッション失効 | | `status` / `logout` | 接続状態表示/セッション失効 |
@@ -166,9 +167,9 @@ Tab補完、上下キーのプロセス内履歴に対応。複雑な引用位
`auto` 言語選択と未作成言語版の編集は、独立版CLI v0.1.0で利用できます(分離前はサーバー同梱版v0.4.0以降)。 `auto` 言語選択と未作成言語版の編集は、独立版CLI v0.1.0で利用できます(分離前はサーバー同梱版v0.4.0以降)。
```sh ```sh
pages edit /guide --lang auto # 表示される言語の最新版を編集 pages edit /guide --lang auto # 表示される言語の最新版を編集(未存在時は確認後にundで新規作成)
pages edit /guide --lang ja # 日本語版。未作成なら既存内容から開始 pages edit /guide --lang ja # 日本語版。既存Pageなら既存内容から開始、未存在なら新規作成
pages edit /guide --lang en # 英語版。未作成なら既存内容から開始 pages edit /guide --lang en # 英語版。既存Pageなら既存内容から開始、未存在なら新規作成
``` ```
編集開始時に対象言語を表示します。指定言語のRevisionがない場合は、表示中の版の内容を 編集開始時に対象言語を表示します。指定言語のRevisionがない場合は、表示中の版の内容を
@@ -176,14 +177,14 @@ pages edit /guide --lang en # 英語版。未作成なら既存内容から
自動翻訳ではありません。元の言語版は変更せず、編集せずに閉じた場合は何も作成しません。 自動翻訳ではありません。元の言語版は変更せず、編集せずに閉じた場合は何も作成しません。
同じ言語版が先に作成された場合も、競合として保存を止めます。 同じ言語版が先に作成された場合も、競合として保存を止めます。
対応範囲は既存Pageの更新と新規言語版の作成です。新規Path/Page作成、バイナリ更新は未実装です。 指定したPathが存在しない場合(または `create`-only 権限で読取不可の場合)は、新規Pageとして作成するか確認プロンプトを表示してから `$EDITOR` を開きます(`--lang auto` のまま作成する場合は `und` になる旨の警告を表示します)。空のまま閉じた場合は作成しません。新規Path/Page作成には `PUT /_/api/v1/pages/path:...` に対応したサーバーが必要です。バイナリ更新は未実装です。
競合や通信断で自動上書きせず、ローカル原稿を保持します。HTTPS必須(開発用loopbackのみHTTP可)。 保存時に競合(更新時 `409`、新規作成時 `412`)が起きた場合は差分を表示し、対話環境ではマージ編集・最新headへの保存・別Path選択・ローカル保持を選択できます(非対話時は保持して停止)。通信断等で保持された原稿は `pages recover --list` で確認し、`pages recover PATH` で再開または `--discard` で破棄できます。HTTPS必須(開発用loopbackのみHTTP可)。
詳しいURI・保存・安全性の契約は[クライアント契約](docs/client-contract.md)を参照してください。 詳しいURI・保存・安全性の契約は[クライアント契約](docs/client-contract.md)を参照してください。
## テスト ## テスト
```sh ```sh
python3 -m unittest test_pages test_productivity test_distribution test_tls python3 -m unittest test_pages test_productivity test_distribution test_tls test_remember
``` ```
合成サーバーと一時ディレクトリのみを使用します。TLS試験には一時証明書を生成するOpenSSLコマンドが必要です。本番資格情報や外部カレンダーは不要です。Goサーバーとの結合テストはサーバーリポジトリ側で実行します。 合成サーバーと一時ディレクトリのみを使用します。TLS試験には一時証明書を生成するOpenSSLコマンドが必要です。本番資格情報や外部カレンダーは不要です。Goサーバーとの結合テストはサーバーリポジトリ側で実行します。
+25 -5
View File
@@ -8,7 +8,7 @@ pages-cliはPagesWikiのHTTPクライアントであり、DBやDocument Storeを
`-k` 使用時もHTTPはloopbackでの開発専用。originにuserinfo、Path、query、fragmentを含めず、リダイレクトには追従しない。ログイン画面のHTMLや302/303をAPIの成功として扱わない。 `-k` 使用時もHTTPはloopbackでの開発専用。originにuserinfo、Path、query、fragmentを含めず、リダイレクトには追従しない。ログイン画面のHTMLや302/303をAPIの成功として扱わない。
パスワードログインでは必要に応じてTOTPを入力する。`login --oidc [--no-browser]` ではブラウザのOIDCログイン後に、ターミナルの確認コードを入力して承認する。S256でCLIのverifierに束縛し、短期リクエストを一度だけBearerセッションへ交換する。SSH先から開始し、別端末で承認できる。ブラウザCookie、外部OIDC token、Campus用PSKをCLIのBearerとして流用しない。 パスワードログインでは必要に応じてTOTPを入力する。`login --oidc [--with-open-browser]` ではブラウザのOIDCログイン後に、ターミナルの確認コードを入力して承認する(既定ではブラウザを自動起動せず、`--with-open-browser` 指定時のみ開く)。S256でCLIのverifierに束縛し、短期リクエストを一度だけBearerセッションへ交換する。SSH先から開始し、別端末で承認できる。ブラウザCookie、外部OIDC token、Campus用PSKをCLIのBearerとして流用しない。
OIDC入口はサーバーv0.3.0以降。OIDCで認証した利用者への追加ローカルTOTP省略と新規言語版の編集はサーバーv0.4.0以降。タスク・連絡先を含む独立CLIの利用基準はサーバーv0.6.0以降。独立CLIとサーバーのバージョン番号は連動しない。 OIDC入口はサーバーv0.3.0以降。OIDCで認証した利用者への追加ローカルTOTP省略と新規言語版の編集はサーバーv0.4.0以降。タスク・連絡先を含む独立CLIの利用基準はサーバーv0.6.0以降。独立CLIとサーバーのバージョン番号は連動しない。
@@ -24,9 +24,13 @@ Pathは到達経路、UUIDはPageの識別子、Revisionは履歴。正本は `/
編集開始時にObject UUIDと保存先言語、基点Revisionを確定する。`auto` は表示されたRevisionの言語を採用する。明示した言語のheadがなければ既存言語の内容を下書きとして開き、空の基点で新規言語版をCAS保存する。自動翻訳はしない。無変更なら作成しない。編集途中でPathが変わっても別Pageへ保存しない。 編集開始時にObject UUIDと保存先言語、基点Revisionを確定する。`auto` は表示されたRevisionの言語を採用する。明示した言語のheadがなければ既存言語の内容を下書きとして開き、空の基点で新規言語版をCAS保存する。自動翻訳はしない。無変更なら作成しない。編集途中でPathが変わっても別Pageへ保存しない。
`$EDITOR` はshellを介さず起動する。作業ファイルは0700の一時ディレクトリ内へ0600で保存し、成功・無変更時は削除する。通信断や競合時は原稿と復旧メタデータを保持して場所を表示する。復旧メタデータにBearerを入れない。競合時は差分を示して停止し、自動マージ・強制上書き・保存要求の自動再送は行わない。 `path:/...`(ルート `/` を除く)を `edit` で開いた際、対象Pathが未存在(`404`)または読取不可(`403`:create-only権限の可能性)の場合は、新規Pageとして作成するか確認プロンプトを出してから `$EDITOR` を開く(非対話標準入力では安全のため中止する)。プロファイル言語が `auto` のまま新規作成する場合は `WARNING` を標準エラーへ出して `und` で作成する。`--lang TAG` を指定した場合はその言語で作成する。空のまま編集を終えた場合は送信しない。
`put` は既存言語の基点を `--base` で指定する。新規Path/Page、バイナリ編集、Asset更新は未対応。Revisionアドレスは取得専用。ブラウザで `open` する際はブラウザ自身のログインを使い、共有リンクを自動発行しない。 `$EDITOR` はshellを介さず起動する。作業ファイルは0700の一時ディレクトリ内へ0600で保存し、成功・無変更時は削除する。通信断や競合(更新時 `409`、新規作成時 `412`)時は原稿と復旧メタデータを保持して場所を表示する。復旧メタデータにBearerを入れない。競合時は差分を示し、対話端末では `[e]` 競合マーカー付き編集(マーカー残存時は保存を拒否)・`[f]` 最新headへの明示保存(更新時)・`[p]` 別Path選択(`412` 時)・`[k]` ローカル保持のいずれかを選べる(非対話時は常にローカル保持で停止)。自動マージ・無断強制上書き・保存要求の自動再送は行わない。
保持された原稿は `pages recover` で一覧(`--list`)・再編集(`--edit`)・再開・破棄(`--discard`)できる。`recover` はディレクトリ0700/ファイル0600・所有者・シンボリックリンク非使用・`origin` 一致・CAS基点(`base_revision_uuid`)の再照合を検査する。
`put` は既存言語の基点を `--base` で指定する。`uuid:`・`rev:`・`/` からの新規作成、バイナリ編集、Asset更新は未対応。Revisionアドレスは取得専用。ブラウザで `open` する際はブラウザ自身のログインを使い、共有リンクを自動発行しない。
## HTTP API ## HTTP API
@@ -40,14 +44,30 @@ Pathは到達経路、UUIDはPageの識別子、Revisionは履歴。正本は `/
| 正本・識別子 | GET/HEAD `/v/raw/{explicit-address}` | | 正本・識別子 | GET/HEAD `/v/raw/{explicit-address}` |
| 編集状態 | GET `/_/api/v1/editor/state` | | 編集状態 | GET `/_/api/v1/editor/state` |
| 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保存(既存Page) | POST `/_/api/v1/revisions/save` |
| 原子的作成(新規Path+Page) | PUT `/_/api/v1/pages/path:{semantic-path}` |
| タスク | `/_/api/v1/extension/organizer.tasks/`配下のcapture・items・preferences・work・report | | タスク | `/_/api/v1/extension/organizer.tasks/`配下のcapture・items・preferences・work・report |
| 個人アドレス帳 | `/_/api/v1/extension/organizer.contacts/`配下のitems・import | | 個人アドレス帳 | `/_/api/v1/extension/organizer.contacts/`配下のitems・import |
### 新規Path/Page作成API契約(`PUT /_/api/v1/pages/path:...`)
Viewer面(`/...`)や非正規Projection面(`/v/raw/...`)と分離されたAPI面で、正式なHTTP `PUT` により住所(Path)・Page UUID・初回Revision・不変Documentを原子的に作成する。
- **URI**: `PUT /_/api/v1/pages/path:<UTF-8 percent-encoded semantic path>`(ルート `/`、予約プレフィックス、`..`、`uuid:`/`rev:` は不可)
- **リクエストヘッダ**:
- `Authorization: Bearer <token>`
- `If-None-Match: *`(必須。未指定時は `428 Precondition Required`、既存在/並行作成競合時は `412 Precondition Failed`)
- `Content-Type`: 保存する正本のMIME型(Markdown編集時は先に `POST /_/api/v1/render/markdown` でHTML正本化し `text/html; charset=utf-8` を送信、`--format raw` 時は `text/plain; charset=utf-8`)
- `Content-Language`: BCP 47言語タグ(`auto` 時は `und`)
- `X-PagesWiki-Commit-Message` / `X-PagesWiki-Filename`: 任意(UTF-8 RFC 3986 percent-encoding、空白は `%20`)
- **リクエストボディ**: 正本バイト列そのもの(JSONで包まない。テキスト上限1 MiB)
- **成功応答(`201 Created`)**: `X-PagesWiki-Object-UUID`、`X-PagesWiki-Revision-UUID`、`X-PagesWiki-Document-SHA256`(64桁小文字hex)、`Content-Language`、`ETag`、`Location`、`Cache-Control: private, no-store`
- **エラー応答**: `400`(不正Path・不正言語・非対応MIME)、`401`(未認証)、`403`(存在チェックより先に評価する `create` 権限不足)、`404`/`405`/`501`(未対応サーバー)、`412`(Path既存・並行衝突)、`413`(サイズ上限超過)、`428`(`If-None-Match: *` 欠落)
## 上限と検証 ## 上限と検証
ネットワークには20秒のsocket timeoutと応答サイズ上限がある。総転送時間の厳密なdeadlineや巨大転送のstreamingは未対応。`get` は最大64 MiB、SHA-256を照合し、新規0600ファイルへ出力する。既存ファイルは上書きしない。編集テキストは1 MiB、JSON送信は2 MiBまで。 ネットワークには20秒のsocket timeoutと応答サイズ上限がある。総転送時間の厳密なdeadlineや巨大転送のstreamingは未対応。`get` は最大64 MiB、SHA-256を照合し、新規0600ファイルへ出力する。既存ファイルは上書きしない。編集テキストは1 MiB、JSON送信は2 MiBまで。
メール取り込みは1通2 MiB、本文は明示指定時のみ、保持するメモは16 KiBまで。再送用要求は最大20件。連絡先importは1枚のUTF-8 vCard、64 KiBまで。NeoMutt検索は本人・Domain内の個人アドレス帳を対象とし、最大100件を返す。 メール取り込みは1通2 MiB、本文は明示指定時のみ、保持するメモは16 KiBまで。再送用要求は最大20件。連絡先importは1枚のUTF-8 vCard、64 KiBまで。NeoMutt検索は本人・Domain内の個人アドレス帳を対象とし、最大100件を返す。
CLIの単体・実バイナリ試験は合成データのみを使用する。サーバー側の権限・CAS・OIDC署名検証とGoのHTTP結合テストはPagesWikiリポジトリで管理する。Windowsの資格情報保護とロック移植、新規Page作成、競合の対話的復旧、巨大ファイル転送は後続タスク。 CLIの単体・実バイナリ試験は合成データのみを使用する。サーバー側の権限・CAS・OIDC署名検証とGoのHTTP結合テストはPagesWikiリポジトリで管理する。新規Page作成には `PUT /_/api/v1/pages/path:...` に対応したサーバーが必要。Windowsの資格情報保護とロック移植、巨大ファイル転送は後続タスク。
+1 -1
View File
@@ -4,7 +4,7 @@
```sh ```sh
pages configure --origin https://pages.example.test --username YOUR_USERNAME pages configure --origin https://pages.example.test --username YOUR_USERNAME
pages login --oidc --no-browser pages login --oidc
pages task preferences --wiki-prefix /private/mail pages task preferences --wiki-prefix /private/mail
pages task --help pages task --help
``` ```
+379 -39
View File
@@ -92,26 +92,30 @@ class Client:
handlers.append(http.HTTPSHandler(context=context)) handlers.append(http.HTTPSHandler(context=context))
self.opener = http.build_opener(*handlers) self.opener = http.build_opener(*handlers)
def request(self, route, method='GET', data=None, form=None, limit=4 << 20, etag=None, content_type=None): def request(self, route, method='GET', data=None, form=None, limit=4 << 20, etag=None, content_type=None, headers=None, expect_status=None):
if not route.startswith('/') or route.startswith('//'): if not route.startswith('/') or route.startswith('//'):
raise Failure('Invalid API route.') raise Failure('Invalid API route.')
headers = {'Accept': 'application/json', 'User-Agent': 'pages-cli/' + VERSION} req_headers = {'Accept': 'application/json', 'User-Agent': 'pages-cli/' + VERSION}
if headers:
req_headers.update(headers)
if etag is not None: if etag is not None:
headers['If-Match'] = etag req_headers['If-Match'] = etag
if self.token: if self.token:
headers['Authorization'] = 'Bearer ' + self.token req_headers['Authorization'] = 'Bearer ' + self.token
body = None body = None
if data is not None: if data is not None:
body = data if isinstance(data, bytes) else json.dumps(data, ensure_ascii=False).encode() body = data if isinstance(data, bytes) else json.dumps(data, ensure_ascii=False).encode()
headers['Content-Type'] = content_type or 'application/json' req_headers['Content-Type'] = content_type or 'application/json'
if form is not None: if form is not None:
body = url.urlencode(form).encode() body = url.urlencode(form).encode()
headers['Content-Type'] = 'application/x-www-form-urlencoded' req_headers['Content-Type'] = 'application/x-www-form-urlencoded'
if body is not None and len(body) > 2 << 20: if body is not None and len(body) > 2 << 20:
raise Failure('Request exceeds the 2 MiB client limit.') raise Failure('Request exceeds the 2 MiB client limit.')
req = http.Request(self.base + route, body, headers, method=method) req = http.Request(self.base + route, body, req_headers, method=method)
try: try:
with self.opener.open(req, timeout=20) as response: with self.opener.open(req, timeout=20) as response:
if expect_status is not None and response.status != expect_status:
raise Failure('Unexpected HTTP status (%d).' % response.status, response.status)
raw = response.read(limit + 1) raw = response.read(limit + 1)
if len(raw) > limit: if len(raw) > limit:
raise Failure('Response exceeds client limit; use the browser for large files.') raise Failure('Response exceeds client limit; use the browser for large files.')
@@ -127,7 +131,8 @@ class Client:
payload = {} payload = {}
messages = {303: 'Login redirect refused; log in again.', 401: 'Session expired or authentication required.', 403: 'Access denied.', messages = {303: 'Login redirect refused; log in again.', 401: 'Session expired or authentication required.', 403: 'Access denied.',
404: 'Not found or not readable.', 409: 'Conflict: remote revision changed.', 404: 'Not found or not readable.', 409: 'Conflict: remote revision changed.',
412: 'Conflict: remote item changed; reload before saving.', 422: 'Invalid fields; check dates, project and required settings.'} 412: 'Conflict: remote item changed; reload before saving.', 422: 'Invalid fields; check dates, project and required settings.',
428: 'Precondition required by server.'}
raise Failure(messages.get(e.code, 'HTTP request failed (%d); redirects are not followed.' % e.code), e.code, payload) from None raise Failure(messages.get(e.code, 'HTTP request failed (%d); redirects are not followed.' % e.code), e.code, payload) from None
except (urllib.error.URLError, TimeoutError, OSError): except (urllib.error.URLError, TimeoutError, OSError):
raise Failure('Connection/TLS failure; no automatic write retry was attempted.') from None raise Failure('Connection/TLS failure; no automatic write retry was attempted.') from None
@@ -166,7 +171,7 @@ class Client:
self.token = token self.token = token
return time.time() + duration return time.time() + duration
def login_oidc(self, no_browser=False, expected_username='', *, remember=False, sleep=time.sleep, clock=time.monotonic): def login_oidc(self, open_browser=False, expected_username='', *, remember=False, sleep=time.sleep, clock=time.monotonic):
verifier = secrets.token_urlsafe(32) verifier = secrets.token_urlsafe(32)
challenge = base64.urlsafe_b64encode(hashlib.sha256(verifier.encode()).digest()).decode().rstrip('=') challenge = base64.urlsafe_b64encode(hashlib.sha256(verifier.encode()).digest()).decode().rstrip('=')
try: try:
@@ -192,7 +197,7 @@ class Client:
print(self.base + route) print(self.base + route)
print('Confirmation code:', code) print('Confirmation code:', code)
print('Waiting for approval (up to 5 minutes). Ctrl+C cancels locally.', flush=True) print('Waiting for approval (up to 5 minutes). Ctrl+C cancels locally.', flush=True)
if not no_browser: if open_browser:
try: webbrowser.open(self.base + route, new=2) try: webbrowser.open(self.base + route, new=2)
except (webbrowser.Error, OSError): pass # URL remains usable on another device. except (webbrowser.Error, OSError): pass # URL remains usable on another device.
while clock() + interval < deadline: while clock() + interval < deadline:
@@ -281,6 +286,45 @@ class Client:
'base_revision_uuid': state['head_revision_uuid'], 'base_revision_uuid': state['head_revision_uuid'],
'editor_principal_uuid': state['principal_uuid'], 'message': 'Remote CLI edit'}) 'editor_principal_uuid': state['principal_uuid'], 'message': 'Remote CLI edit'})
def create_page(self, addr, text, markdown=False, *, lang=None, content_type=None, filename='', message='Remote CLI create'):
if not addr.startswith('path:') or addr == 'path:/':
raise Failure('New page creation requires a non-root Path.')
if len(text.encode('utf-8')) > 1 << 20:
raise Failure('Text edit exceeds the 1 MiB client limit.')
chosen = self.lang if lang is None else language(lang)
target_lang = 'und' if chosen == 'auto' else chosen
if markdown:
ctype = 'text/html; charset=utf-8'
body_text = self.json('/_/api/v1/render/markdown', method='POST', data={
'markdown': text, 'authoring': True, 'projection': False})['html']
else:
ctype = content_type or 'text/plain; charset=utf-8'
body_text = text
payload = body_text.encode('utf-8')
extra = {'If-None-Match': '*', 'Content-Language': target_lang}
if message:
extra['X-PagesWiki-Commit-Message'] = url.quote(message, safe='-_.,~')
if filename:
extra['X-PagesWiki-Filename'] = url.quote(filename, safe='-_.,~')
route = '/_/api/v1/pages/' + url.quote(addr, safe='/:')
try:
_, resp_headers = self.request(route, method='PUT', data=payload, content_type=ctype, headers=extra, expect_status=201)
except Failure as e:
if e.status in (404, 405, 501):
raise Failure('Atomic page creation (PUT /_/api/v1/pages/path:...) is unavailable on this server. Update the server to a version supporting this endpoint.', e.status, e.payload) from None
if e.status == 412:
raise Failure('Conflict: a page already exists at this Path; reload with pages edit.', 412, e.payload) from None
if e.status == 428:
raise Failure('Server requires a create precondition (If-None-Match: *).', 428, e.payload) from None
raise
object_uuid = resp_headers.get('X-PagesWiki-Object-UUID', '').strip()
revision_uuid = resp_headers.get('X-PagesWiki-Revision-UUID', '').strip()
doc_hash = resp_headers.get('X-PagesWiki-Document-SHA256', '').strip()
saved_lang = resp_headers.get('Content-Language', target_lang).strip() or target_lang
if not object_uuid or not revision_uuid or not re.fullmatch(r'[0-9a-f]{64}', doc_hash):
raise Failure('Invalid page creation response; missing document identity headers.')
return {'status': 'created', 'path': addr[5:], 'object_uuid': object_uuid, 'revision_uuid': revision_uuid, 'document_hash': doc_hash, 'lang': saved_lang}
def private_file(path): def private_file(path):
info = path.lstat() info = path.lstat()
@@ -420,47 +464,336 @@ def configure(words, root=None):
print('Default profile:', data['default_profile']) print('Default profile:', data['default_profile'])
def private_dir(path):
info = path.lstat()
if not stat.S_ISDIR(info.st_mode) or info.st_uid != os.getuid() or info.st_mode & 0o077:
raise Failure('Recovery directory must be owned by you with mode 0700; symlinks are not accepted.')
def run_editor(file):
command = shlex.split(os.environ.get('EDITOR', 'vi'))
if not command or subprocess.run(command + [str(file)], check=False).returncode:
raise Failure('Editor exited unsuccessfully.')
def conflict_buffer(local, remote, head_rev=''):
l = local if (not local or local.endswith('\n')) else local + '\n'
r = remote if (not remote or remote.endswith('\n')) else remote + '\n'
label = 'remote (rev: ' + head_rev + ')' if head_rev else 'remote'
return '<<<<<<< local\n' + l + '=======\n' + r + '>>>>>>> ' + label + '\n'
def has_conflict_markers(text):
return any(line.startswith('<<<<<<< ') or line == '=======' or line.startswith('>>>>>>> ') for line in text.splitlines())
def choose_conflict_action(kind, has_remote=True):
if not sys.stdin.isatty():
return 'k'
if kind == 'update':
prompt = 'Conflict detected. [e]dit with markers, [f]orce-save local on new head, [k]eep local draft and exit [e/f/K]: '
allowed = ('e', 'f', 'k')
elif has_remote:
prompt = 'Path already exists. [e]dit with existing page, [p]ick another path, [k]eep local draft and exit [e/p/K]: '
allowed = ('e', 'p', 'k')
else:
prompt = 'Path already exists (not readable). [p]ick another path, [k]eep local draft and exit [p/K]: '
allowed = ('p', 'k')
try:
choice = input(prompt).strip().lower()
except EOFError:
return 'k'
return choice if choice in allowed else 'k'
def prompt_new_path(cwd='/'):
if not sys.stdin.isatty():
return None
try:
raw = input('New Path (blank to keep draft and exit): ').strip()
except EOFError:
return None
if not raw:
return None
try:
addr = address(raw, cwd)
except Failure as e:
print(safe_text(str(e)), file=sys.stderr)
return None
if not addr.startswith('path:') or addr == 'path:/':
print('Enter a non-root Path.', file=sys.stderr)
return None
return addr
def write_recovery(directory, client, ctx):
metadata = directory / 'recovery.json'
metadata.touch(mode=0o600)
if ctx['creating']:
recovery = {'origin': client.base, 'mode': 'create', 'address': ctx['addr'],
'lang': ctx['lang'], 'format': 'markdown' if ctx['markdown'] else 'raw'}
else:
recovery = {'origin': client.base, 'address': 'uuid:' + ctx['state']['object_uuid'],
'base_revision_uuid': ctx['state']['head_revision_uuid'],
'source_revision_uuid': ctx['state'].get('source_revision_uuid', ''),
'lang': ctx['state']['lang'], 'format': 'markdown' if ctx['markdown'] else 'raw'}
metadata.write_text(json.dumps(recovery))
def commit_edit(client, file, text, ctx, cwd='/'):
while True:
if ctx['creating']:
try:
result = client.create_page(ctx['addr'], text, ctx['markdown'], lang=ctx['lang'])
except Failure as error:
if error.status != 412:
raise
try:
latest = client.snapshot(ctx['addr'], lang=ctx['lang'])
except Failure:
latest = None
remote = ''
if latest is not None:
remote = latest['markdown'] if ctx['markdown'] else latest['body']
print(safe_text(''.join(difflib.unified_diff(remote.splitlines(True), text.splitlines(True), fromfile='remote', tofile='local'))))
action = choose_conflict_action('create', has_remote=latest is not None)
if action == 'p':
new_addr = prompt_new_path(cwd)
if not new_addr:
raise
ctx['addr'] = new_addr
continue
if action == 'e' and latest is not None:
ctx['creating'] = False
ctx['state'] = latest
ctx['lang'] = latest['lang']
file.write_text(conflict_buffer(text, remote, latest.get('head_revision_uuid', '')), encoding='utf-8')
run_editor(file)
text = file.read_text(encoding='utf-8')
if has_conflict_markers(text):
print('Conflict markers remain; remove them before saving.', file=sys.stderr)
raise Failure('Conflict markers remain in edited document.', 409) from None
continue
raise
print('Created page:', safe_text(result['path']))
print('Object UUID:', safe_text(result['object_uuid']))
print('Saved revision:', safe_text(result['revision_uuid']))
return result
try:
result = client.save(ctx['state'], text, ctx['markdown'])
except Failure as error:
if error.status != 409:
raise
latest = client.snapshot('uuid:' + ctx['state']['object_uuid'], lang=ctx['state']['lang'])
remote = latest['markdown'] if ctx['markdown'] else latest['body']
print(safe_text(''.join(difflib.unified_diff(remote.splitlines(True), text.splitlines(True), fromfile='remote', tofile='local'))))
action = choose_conflict_action('update', has_remote=True)
if action == 'k':
raise
ctx['state'] = latest
if action == 'f':
continue
if action == 'e':
file.write_text(conflict_buffer(text, remote, latest.get('head_revision_uuid', '')), encoding='utf-8')
run_editor(file)
text = file.read_text(encoding='utf-8')
if has_conflict_markers(text):
print('Conflict markers remain; remove them before saving.', file=sys.stderr)
raise Failure('Conflict markers remain in edited document.', 409) from None
continue
raise
print('Saved revision:', safe_text(result['revision_uuid']))
return result
def confirm_create(addr, status):
if not sys.stdin.isatty():
if status == 404:
raise Failure('Not found or not readable (interactive confirmation is required to create a new page).', 404)
raise Failure('Access denied.', 403)
path = safe_text(addr[5:])
if status == 404:
prompt = f'Path {path} does not exist. Create a new page? [y/N]: '
else:
prompt = f'Cannot read {path} (access denied). If you have create-only permission, attempt to create a new page? [y/N]: '
try:
answer = input(prompt)
except EOFError:
return False
return answer.strip().lower() in ('y', 'yes')
def editor(client, addr, mode): def editor(client, addr, mode):
state = client.snapshot(addr) creating = False
print('Editing language:', safe_text(state['lang'])) state = None
if state.get('new_language'): try:
print('Creating a new language revision; source remains unchanged:', safe_text(state.get('source_language', '(empty)'))) state = client.snapshot(addr)
markdown = mode == 'markdown' or (mode == 'auto' and state['content_type'].startswith('text/html')) except Failure as error:
initial = state['markdown'] if markdown else state['body'] if error.status in (404, 403) and addr.startswith('path:') and addr != 'path:/':
if not confirm_create(addr, error.status):
print('Aborted.')
return
creating = True
if client.lang == 'auto':
lang = 'und'
print("WARNING: Creating a new page with language 'und' (profile language is 'auto'). Use --lang TAG to specify an explicit language.", file=sys.stderr)
else:
lang = client.lang
print('Creating new page:', safe_text(addr[5:]))
print('Editing language:', safe_text(lang))
markdown = mode in ('auto', 'markdown')
initial = ''
else:
raise
if not creating:
lang = state['lang']
print('Editing language:', safe_text(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'))
initial = state['markdown'] if markdown else state['body']
directory = Path(tempfile.mkdtemp(prefix='pageswiki-edit-')) directory = Path(tempfile.mkdtemp(prefix='pageswiki-edit-'))
file = directory / ('document.md' if markdown else 'document.txt') file = directory / ('document.md' if markdown else 'document.txt')
file.touch(mode=0o600) file.touch(mode=0o600)
file.write_text(initial, encoding='utf-8') file.write_text(initial, encoding='utf-8')
ctx = {'creating': creating, 'addr': addr, 'state': state, 'lang': lang, 'markdown': markdown}
success = False success = False
try: try:
command = shlex.split(os.environ.get('EDITOR', 'vi')) run_editor(file)
if not command or subprocess.run(command + [str(file)], check=False).returncode:
raise Failure('Editor exited unsuccessfully.')
text = file.read_text(encoding='utf-8') text = file.read_text(encoding='utf-8')
if text == initial: if text == initial:
print('Unchanged.') print('Unchanged; page was not created.' if creating else 'Unchanged.')
else: else:
try: commit_edit(client, file, text, ctx)
result = client.save(state, text, markdown)
except Failure as error:
if error.status == 409:
latest = client.snapshot('uuid:' + state['object_uuid'], lang=state['lang'])
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'))))
raise
print('Saved revision:', safe_text(result['revision_uuid']))
success = True success = True
finally: finally:
if success: if success:
file.unlink() file.unlink()
directory.rmdir() directory.rmdir()
else: else:
metadata = directory / 'recovery.json' write_recovery(directory, client, ctx)
metadata.touch(mode=0o600)
metadata.write_text(json.dumps({'origin': client.base, 'address': 'uuid:' + state['object_uuid'],
'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)
print('Recover later with: pages recover', safe_text(file), file=sys.stderr)
def resolve_recovery(target):
p = Path(target)
if p.is_symlink():
raise Failure('Recovery path must not be a symlink.')
if p.is_dir():
directory = p
elif p.name in ('recovery.json', 'document.md', 'document.txt'):
directory = p.parent
else:
raise Failure('Specify a pageswiki-edit recovery directory, recovery.json, or retained document file.')
if not directory.exists() or directory.is_symlink():
raise Failure('Recovery directory not found or invalid.')
private_dir(directory)
meta_path = directory / 'recovery.json'
if not meta_path.exists() and not meta_path.is_symlink():
raise Failure('Missing recovery.json metadata.')
private_file(meta_path)
try:
data = json.loads(meta_path.read_text(encoding='utf-8'))
except (ValueError, UnicodeError) as e:
raise Failure('Corrupt recovery.json metadata.') from e
if not isinstance(data, dict):
raise Failure('Corrupt recovery.json metadata.')
req_origin = data.get('origin')
addr = data.get('address')
lang = data.get('lang')
fmt = data.get('format')
rec_mode = data.get('mode', 'update')
if (not isinstance(req_origin, str) or not req_origin
or not isinstance(addr, str) or not addr
or not isinstance(lang, str) or not lang
or fmt not in ('markdown', 'raw')
or rec_mode not in ('update', 'create')):
raise Failure('Invalid recovery.json metadata.')
doc_path = directory / ('document.md' if fmt == 'markdown' else 'document.txt')
if not doc_path.exists() and not doc_path.is_symlink():
raise Failure('Missing retained document file.')
private_file(doc_path)
return directory, meta_path, doc_path, data
def list_recoveries(temp_root=None):
root = Path(temp_root or tempfile.gettempdir())
found = []
for entry in sorted(root.glob('pageswiki-edit-*')):
try:
directory, _, doc_path, data = resolve_recovery(entry)
found.append((directory, doc_path, data, doc_path.stat().st_mtime))
except (Failure, OSError, ValueError):
continue
return found
def cleanup_recovery(directory, meta_path, doc_path):
for p in (doc_path, meta_path):
if p.exists():
p.unlink()
if directory.exists() and not any(directory.iterdir()):
directory.rmdir()
def recover(client, profile, target=None, *, edit_first=False, discard=False, list_only=False, temp_root=None):
if list_only or (target is None and not discard):
items = list_recoveries(temp_root)
if not items:
print('No local recovery drafts found.')
return
for directory, _, data, mtime in items:
stamp = time.strftime('%Y-%m-%dT%H:%M:%S', time.localtime(mtime))
print(safe_text('\t'.join((str(directory), data.get('mode', 'update'), data['address'], data['lang'], data['origin'], stamp))))
return
if target is None:
raise Failure('Specify a recovery path or use --list.')
directory, meta_path, doc_path, meta = resolve_recovery(target)
if discard:
if not directory.name.startswith('pageswiki-edit-'):
raise Failure('Refusing to discard outside a pageswiki-edit-* directory.')
cleanup_recovery(directory, meta_path, doc_path)
print('Discarded recovery draft:', safe_text(directory))
return
if meta['origin'] != client.base:
raise Failure('Recovery draft belongs to a different server origin (%s); switch profile before recovering.' % safe_text(meta['origin']))
rec_mode = meta.get('mode', 'update')
markdown = meta['format'] == 'markdown'
lang = language(meta['lang'])
addr = meta['address']
if edit_first:
run_editor(doc_path)
text = doc_path.read_text(encoding='utf-8')
if has_conflict_markers(text):
raise Failure('Conflict markers remain in draft; run with --edit to resolve them.', 409)
if rec_mode == 'create':
if not text:
raise Failure('Recovery draft is empty; edit with --edit or remove with --discard.')
ctx = {'creating': True, 'addr': addr, 'state': None, 'lang': lang, 'markdown': markdown}
else:
state = client.snapshot(addr, lang=lang)
expected_base = meta.get('base_revision_uuid', '')
if state['head_revision_uuid'] != expected_base:
remote = state['markdown'] if markdown else state['body']
print(safe_text(''.join(difflib.unified_diff(remote.splitlines(True), text.splitlines(True), fromfile='remote', tofile='local'))))
action = choose_conflict_action('update', has_remote=True)
if action == 'k':
raise Failure('Conflict: remote revision changed since draft was saved.', 409)
if action == 'e':
doc_path.write_text(conflict_buffer(text, remote, state.get('head_revision_uuid', '')), encoding='utf-8')
run_editor(doc_path)
text = doc_path.read_text(encoding='utf-8')
if has_conflict_markers(text):
raise Failure('Conflict markers remain in edited document.', 409)
ctx = {'creating': False, 'addr': addr, 'state': state, 'lang': state['lang'], 'markdown': markdown}
cwd = profile.data.get('cwd', '/') if profile else '/'
try:
commit_edit(client, doc_path, text, ctx, cwd=cwd)
except BaseException:
write_recovery(directory, client, ctx)
raise
cleanup_recovery(directory, meta_path, doc_path)
TASK_API = '/_/api/v1/extension/organizer.tasks/' TASK_API = '/_/api/v1/extension/organizer.tasks/'
@@ -733,15 +1066,22 @@ 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.add_argument('--lang', help='auto edits the visible language (or creates as und with warning); an explicit tag selects or creates 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')
p = sub.add_parser('recover', help='List, resume, or discard retained local edit drafts')
p.add_argument('target', nargs='?', help='Recovery directory, recovery.json, or retained document file')
p.add_argument('--list', action='store_true', dest='list_only', help='List retained local drafts')
p.add_argument('--edit', action='store_true', dest='edit_first', help='Open the draft in $EDITOR before saving')
p.add_argument('--discard', action='store_true', help='Delete the retained draft without saving')
p = sub.add_parser('search'); p.add_argument('query') p = sub.add_parser('search'); p.add_argument('query')
sub.add_parser('pwd'); sub.add_parser('logout'); sub.add_parser('status') sub.add_parser('pwd'); sub.add_parser('logout'); sub.add_parser('status')
args = parser.parse_args(words) args = parser.parse_args(words)
cwd = profile.data.get('cwd', '/') cwd = profile.data.get('cwd', '/')
cmd = args.command cmd = args.command
if cmd == 'recover':
recover(client, profile, args.target, edit_first=args.edit_first, discard=args.discard, list_only=args.list_only); return
if cmd == 'logout': if cmd == 'logout':
client.json('/_/auth/logout', method='POST') client.json('/_/auth/logout', method='POST')
profile.data.pop('token', None); profile.data.pop('expires', None); profile.save() profile.data.pop('token', None); profile.data.pop('expires', None); profile.save()
@@ -841,7 +1181,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, task, contacts. 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, recover, search, open, task, contacts. Use pages COMMAND --help.')
parser.add_argument('--version', action='version', version='pages-cli ' + VERSION) parser.add_argument('--version', action='version', version='pages-cli ' + VERSION)
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='auto or an exact language tag for this invocation') parser.add_argument('--lang', help='auto or an exact language tag for this invocation')
@@ -858,10 +1198,10 @@ def main(argv=None):
if args.command == 'login': if args.command == 'login':
login = argparse.ArgumentParser(prog='pages login', description='Log into the configured connection. Password and TOTP are prompted privately.') login = argparse.ArgumentParser(prog='pages login', description='Log into the configured connection. Password and TOTP are prompted privately.')
login.add_argument('--oidc', action='store_true', help='Authenticate and approve in a browser; no local password required') 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.add_argument('--with-open-browser', action='store_true', help='Open the browser login URL automatically (requires --oidc)')
login.add_argument('--remember', action='store_true', help='Keep this trusted device signed in for up to 30 days, subject to server policy') login.add_argument('--remember', action='store_true', help='Keep this trusted device signed in for up to 30 days, subject to server policy')
login_args = login.parse_args(args.args) login_args = login.parse_args(args.args)
if login_args.no_browser and not login_args.oidc: login.error('--no-browser requires --oidc') if login_args.with_open_browser and not login_args.oidc: login.error('--with-open-browser requires --oidc')
elif '--help' in args.args: elif '--help' in args.args:
execute(None, None, [args.command] + args.args); return execute(None, None, [args.command] + args.args); return
with contextlib.ExitStack() as stack: with contextlib.ExitStack() as stack:
@@ -881,7 +1221,7 @@ def main(argv=None):
if profile.data.get('token') and profile.data.get('expires',0)>time.time(): raise Failure('Log out this profile before replacing its active session.') if profile.data.get('token') and profile.data.get('expires',0)>time.time(): raise Failure('Log out this profile before replacing its active session.')
client = Client(spec['origin'], lang=lang, insecure=args.insecure) client = Client(spec['origin'], lang=lang, insecure=args.insecure)
if login_args.oidc: if login_args.oidc:
expires, username = client.login_oidc(login_args.no_browser, spec.get('username', ''), remember=login_args.remember) expires, username = client.login_oidc(login_args.with_open_browser, spec.get('username', ''), remember=login_args.remember)
else: else:
username = spec['username'] username = spec['username']
expires = client.login(username, getpass.getpass('Password: '), remember=login_args.remember) expires = client.login(username, getpass.getpass('Password: '), remember=login_args.remember)
+483 -12
View File
@@ -25,6 +25,7 @@ def server(callback):
class Handler(BaseHTTPRequestHandler): class Handler(BaseHTTPRequestHandler):
def do_GET(self): callback(self) def do_GET(self): callback(self)
def do_POST(self): callback(self) def do_POST(self): callback(self)
def do_PUT(self): callback(self)
def log_message(self, *args): pass def log_message(self, *args): pass
instance = ThreadingHTTPServer(('127.0.0.1', 0), Handler) instance = ThreadingHTTPServer(('127.0.0.1', 0), Handler)
thread = threading.Thread(target=instance.serve_forever, daemon=True) thread = threading.Thread(target=instance.serve_forever, daemon=True)
@@ -54,7 +55,7 @@ class RemoteTests(unittest.TestCase):
if polls == 2: raise Failure('slow',400,{'error':'slow_down'}) 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'} 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: 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]) expires, name = client.login_oidc(sleep=sleep,clock=lambda:now[0])
self.assertEqual(name,'anya'); self.assertGreater(expires,time.time()) self.assertEqual(name,'anya'); self.assertGreater(expires,time.time())
self.assertEqual(waits,[5,5,10]); browser.assert_not_called() self.assertEqual(waits,[5,5,10]); browser.assert_not_called()
proof = calls[1][1]['form']['code_verifier'] proof = calls[1][1]['form']['code_verifier']
@@ -69,7 +70,7 @@ class RemoteTests(unittest.TestCase):
client = Client('https://wiki.example') 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 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: with self.assertRaisesRegex(Failure, 'CLI OIDC login is unavailable') as caught:
client.login_oidc(True) client.login_oidc(open_browser=True)
self.assertEqual(caught.exception.status, status) self.assertEqual(caught.exception.status, status)
api.assert_called_once() api.assert_called_once()
browser.assert_not_called() browser.assert_not_called()
@@ -80,11 +81,11 @@ class RemoteTests(unittest.TestCase):
client = Client('https://wiki.example') client = Client('https://wiki.example')
with patch.object(client, 'json', side_effect=Failure('Access denied.', 403, {'error': 'oidc_disabled'})): with patch.object(client, 'json', side_effect=Failure('Access denied.', 403, {'error': 'oidc_disabled'})):
with self.assertRaisesRegex(Failure, 'not enabled for this domain'): with self.assertRaisesRegex(Failure, 'not enabled for this domain'):
client.login_oidc(True) client.login_oidc()
for error in (Failure('Connection/TLS failure.'), Failure('Access denied.', 403), Failure('Unavailable.', 503)): 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 patch.object(client, 'json', side_effect=error) as api:
with self.assertRaises(Failure) as caught: with self.assertRaises(Failure) as caught:
client.login_oidc(True) client.login_oidc()
self.assertIs(caught.exception, error) self.assertIs(caught.exception, error)
api.assert_called_once() api.assert_called_once()
@@ -92,12 +93,12 @@ class RemoteTests(unittest.TestCase):
client=Client('https://wiki.example') client=Client('https://wiki.example')
started={'device_code':'D'*43,'verification_uri':'https://evil.example/','user_code':'ABCD-1234','expires_in':300,'interval':5} 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 patch.object(client,'json',return_value=started),patch.object(m['webbrowser'],'open') as browser:
with self.assertRaises(Failure): client.login_oidc() with self.assertRaises(Failure): client.login_oidc(open_browser=True)
browser.assert_not_called() browser.assert_not_called()
started['verification_uri']='/_/auth/cli/verify?request='+'R'*43 started['verification_uri']='/_/auth/cli/verify?request='+'R'*43
token={'access_token':'pw_api_'+'S'*43,'token_type':'Bearer','expires_in':3600,'username':'other'} 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 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) with self.assertRaises(Failure): client.login_oidc(expected_username='anya',sleep=lambda _:None,clock=lambda:0)
self.assertEqual(api.call_args.args[0],'/_/auth/logout') self.assertEqual(api.call_args.args[0],'/_/auth/logout')
self.assertEqual(client.token,'') self.assertEqual(client.token,'')
@@ -106,27 +107,60 @@ class RemoteTests(unittest.TestCase):
for error in [Failure('denied',403,{'error':'access_denied'}),Failure('expired',400,{'error':'expired_token'}),Failure('network failure')]: for error in [Failure('denied',403,{'error':'access_denied'}),Failure('expired',400,{'error':'expired_token'}),Failure('network failure')]:
client=Client('https://wiki.example') client=Client('https://wiki.example')
with patch.object(client,'json',side_effect=[started,error]) as api,contextlib.redirect_stdout(io.StringIO()): 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) with self.assertRaises(Failure): client.login_oidc(sleep=lambda _:None,clock=lambda:0)
self.assertEqual(api.call_count,2) self.assertEqual(api.call_count,2)
client=Client('https://wiki.example') client=Client('https://wiki.example')
with patch.object(client,'json',return_value=started) as api,contextlib.redirect_stdout(io.StringIO()): with patch.object(client,'json',return_value=started) as api,contextlib.redirect_stdout(io.StringIO()):
def interrupt(_): raise KeyboardInterrupt() def interrupt(_): raise KeyboardInterrupt()
with self.assertRaises(KeyboardInterrupt): client.login_oidc(True,sleep=interrupt,clock=lambda:0) with self.assertRaises(KeyboardInterrupt): client.login_oidc(sleep=interrupt,clock=lambda:0)
self.assertEqual(api.call_count,1) self.assertEqual(api.call_count,1)
def test_oidc_main_without_configured_username(self): def test_oidc_main_without_configured_username(self):
with tempfile.TemporaryDirectory() as root, patch.dict(os.environ,{'XDG_CONFIG_HOME':root}): with tempfile.TemporaryDirectory() as root, patch.dict(os.environ,{'XDG_CONFIG_HOME':root}):
self.configure(None,'--origin','https://wiki.example') self.configure(None,'--origin','https://wiki.example')
def login(client,*args,**kwargs): client.token='pw_api_'+'s'*43; return time.time()+600,'anya' calls=[]
def login(client,*args,**kwargs):
calls.append((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()): with patch.object(Client,'login_oidc',login),contextlib.redirect_stdout(io.StringIO()):
m['main'](['login','--oidc','--no-browser']) m['main'](['login','--oidc'])
m['main'](['status']) m['main'](['status'])
self.configure(None,'--lang','ja') self.configure(None,'--lang','ja')
self.assertIs(calls[-1][0][0],False)
with Profile('default').locked() as profile: with Profile('default').locked() as profile:
self.assertEqual(profile.data['username'],'anya') self.assertEqual(profile.data['username'],'anya')
self.assertEqual(profile.data['configured_username'],'') self.assertEqual(profile.data['configured_username'],'')
with self.assertRaises(Failure): self.configure(None,'--username','other') with self.assertRaises(Failure): self.configure(None,'--username','other')
def test_oidc_browser_opening_is_opt_in(self):
started = {'device_code': 'D'*43, 'verification_uri': '/_/auth/cli/verify?request='+'R'*43,
'user_code': 'ABCD-1234', 'expires_in': 300, 'interval': 5}
result = {'access_token': 'pw_api_'+'S'*43, 'token_type': 'Bearer', 'expires_in': 3600, 'username': 'anya'}
client = Client('https://wiki.example')
with patch.object(client, 'json', side_effect=[started, result]), patch.object(m['webbrowser'], 'open') as browser, contextlib.redirect_stdout(io.StringIO()):
client.login_oidc(sleep=lambda _: None, clock=lambda: 0)
browser.assert_not_called()
client = Client('https://wiki.example')
with patch.object(client, 'json', side_effect=[started, result]), patch.object(m['webbrowser'], 'open') as browser, contextlib.redirect_stdout(io.StringIO()):
client.login_oidc(open_browser=True, sleep=lambda _: None, clock=lambda: 0)
browser.assert_called_once_with('https://wiki.example/_/auth/cli/verify?request='+'R'*43, new=2)
with tempfile.TemporaryDirectory() as root, patch.dict(os.environ, {'XDG_CONFIG_HOME': root}):
self.configure(None, '--origin', 'https://wiki.example')
calls = []
def login(client_arg, *args, **kwargs):
calls.append((args, kwargs))
client_arg.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', '--with-open-browser'])
self.assertIs(calls[-1][0][0], True)
with patch.object(Client, 'login_oidc') as login_mock, contextlib.redirect_stderr(io.StringIO()):
for bad_args in (['login', '--with-open-browser'], ['login', '--oidc', '--no-browser']):
with self.assertRaises(SystemExit) as exited:
m['main'](bad_args)
self.assertNotEqual(exited.exception.code, 0)
login_mock.assert_not_called()
def configure(self, root, *args): def configure(self, root, *args):
with contextlib.redirect_stdout(io.StringIO()) as output: with contextlib.redirect_stdout(io.StringIO()) as output:
m['configure'](list(args), root) m['configure'](list(args), root)
@@ -343,7 +377,7 @@ 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) as snapshot, 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)), patch.object(m['sys'],'stdin',io.StringIO('')), 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') 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')
@@ -352,6 +386,443 @@ class RemoteTests(unittest.TestCase):
self.assertIn('base',recovery) self.assertIn('base',recovery)
self.assertEqual(stat.S_IMODE((directory/'recovery.json').stat().st_mode),0o600) self.assertEqual(stat.S_IMODE((directory/'recovery.json').stat().st_mode),0o600)
def test_create_page_put_contract_and_errors(self):
recorded = []
mode = {'status': 201, 'headers': None}
def handle(h):
length = int(h.headers.get('Content-Length', 0))
body = h.rfile.read(length)
recorded.append((h.command, h.path, h.headers, body))
if h.path == '/_/api/v1/render/markdown':
req = json.loads(body)
self.assertTrue(req['authoring'])
self.assertFalse(req['projection'])
reply(h, 200, {'html': '<p>' + req['markdown'].strip() + '</p>'})
return
if mode['status'] != 201:
reply(h, mode['status'], {'error': 'rejected'})
return
digest = hashlib.sha256(body).hexdigest()
headers = {
'Content-Type': 'application/json; charset=utf-8',
'Location': '/o/uuid:00000000-0000-4000-8000-000000000001',
'ETag': '"' + digest + '"',
'Content-Language': h.headers.get('Content-Language', 'und'),
'X-PagesWiki-Object-UUID': '00000000-0000-4000-8000-000000000001',
'X-PagesWiki-Revision-UUID': '00000000-0000-4000-8000-000000000002',
'X-PagesWiki-Document-SHA256': digest,
}
if mode['headers'] is not None:
headers = mode['headers'](digest)
h.send_response(201)
for k, v in headers.items():
h.send_header(k, v)
h.end_headers()
with server(handle) as base:
client = Client(base, 'secret-token', 'auto')
created = client.create_page('path:/docs/新規 ガイド', '# Title\n', markdown=True)
self.assertEqual(created['path'], '/docs/新規 ガイド')
self.assertEqual(created['lang'], 'und')
self.assertEqual(created['object_uuid'], '00000000-0000-4000-8000-000000000001')
self.assertEqual(created['revision_uuid'], '00000000-0000-4000-8000-000000000002')
self.assertEqual(recorded[0][0], 'POST')
self.assertEqual(recorded[0][1], '/_/api/v1/render/markdown')
method, path, hdrs, raw = recorded[1]
self.assertEqual(method, 'PUT')
self.assertEqual(path, '/_/api/v1/pages/path:/docs/%E6%96%B0%E8%A6%8F%20%E3%82%AC%E3%82%A4%E3%83%89')
self.assertEqual(hdrs.get('Authorization'), 'Bearer secret-token')
self.assertEqual(hdrs.get('If-None-Match'), '*')
self.assertEqual(hdrs.get('Content-Language'), 'und')
self.assertEqual(hdrs.get('Content-Type'), 'text/html; charset=utf-8')
self.assertEqual(hdrs.get('X-PagesWiki-Commit-Message'), 'Remote%20CLI%20create')
self.assertEqual(raw, b'<p># Title</p>')
recorded.clear()
raw_created = client.create_page('path:/notes/memo.txt', 'hello', markdown=False, lang='ja', filename='メモ.txt')
self.assertEqual(raw_created['lang'], 'ja')
self.assertEqual(len(recorded), 1)
self.assertEqual(recorded[0][0], 'PUT')
self.assertEqual(recorded[0][2].get('Content-Type'), 'text/plain; charset=utf-8')
self.assertEqual(recorded[0][2].get('Content-Language'), 'ja')
self.assertEqual(recorded[0][2].get('X-PagesWiki-Filename'), '%E3%83%A1%E3%83%A2.txt')
self.assertEqual(recorded[0][3], b'hello')
before = len(recorded)
for bad in ('path:/', 'uuid:00000000-0000-0000-0000-000000000000', 'rev:00000000-0000-0000-0000-000000000000'):
with self.assertRaises(Failure):
client.create_page(bad, 'x')
with self.assertRaises(Failure):
client.create_page('path:/too-big', 'a' * ((1 << 20) + 1))
self.assertEqual(len(recorded), before)
mode['headers'] = lambda d: {'X-PagesWiki-Object-UUID': '00000000-0000-4000-8000-000000000001'}
with self.assertRaisesRegex(Failure, 'missing document identity'):
client.create_page('path:/bad-headers', 'x')
mode['headers'] = None
for status, pattern in ((200, 'Unexpected HTTP status'), (412, 'already exists'), (428, 'If-None-Match'), (404, 'unavailable'), (405, 'unavailable'), (501, 'unavailable'), (403, 'Access denied')):
recorded.clear()
mode['status'] = status
with self.assertRaisesRegex(Failure, pattern) as caught:
client.create_page('path:/err', 'x')
self.assertEqual(caught.exception.status, status)
self.assertEqual(len(recorded), 1)
def test_editor_creates_new_page_with_confirmation_and_und_warning(self):
client = Client('https://example.test', 'token', 'auto')
with patch.object(client, 'snapshot', side_effect=Failure('Not found', 404)), \
patch.dict(m['editor'].__globals__, {'confirm_create': lambda addr, st: False}), \
patch.object(client, 'create_page') as create_mock, \
patch('subprocess.run') as run_mock, \
contextlib.redirect_stdout(io.StringIO()) as out:
m['editor'](client, 'path:/docs/new', 'auto')
self.assertIn('Aborted.', out.getvalue())
run_mock.assert_not_called()
create_mock.assert_not_called()
def edit_ok(args, **kwargs):
Path(args[-1]).write_text('# Hello\n', encoding='utf-8')
return type('R', (), {'returncode': 0})()
with patch.object(client, 'snapshot', side_effect=Failure('Not found', 404)), \
patch.dict(m['editor'].__globals__, {'confirm_create': lambda addr, st: True}), \
patch.object(client, 'create_page', return_value={'path': '/docs/new', 'object_uuid': 'obj-1', 'revision_uuid': 'rev-1'}) as create_mock, \
patch('subprocess.run', side_effect=edit_ok) as run_mock, \
contextlib.redirect_stdout(io.StringIO()) as out, \
contextlib.redirect_stderr(io.StringIO()) as err:
m['editor'](client, 'path:/docs/new', 'auto')
self.assertIn("WARNING: Creating a new page with language 'und'", err.getvalue())
self.assertIn('Created page: /docs/new', out.getvalue())
self.assertTrue(run_mock.call_args.args[0][-1].endswith('document.md'))
self.assertFalse(Path(run_mock.call_args.args[0][-1]).exists())
create_mock.assert_called_once_with('path:/docs/new', '# Hello\n', True, lang='und')
client_ja = Client('https://example.test', 'token', 'ja')
with patch.object(client_ja, 'snapshot', side_effect=Failure('Not found', 404)), \
patch.dict(m['editor'].__globals__, {'confirm_create': lambda addr, st: True}), \
patch.object(client_ja, 'create_page', return_value={'path': '/docs/new', 'object_uuid': 'obj-1', 'revision_uuid': 'rev-1'}) as create_mock, \
patch('subprocess.run', side_effect=edit_ok), \
contextlib.redirect_stdout(io.StringIO()), \
contextlib.redirect_stderr(io.StringIO()) as err:
m['editor'](client_ja, 'path:/docs/new', 'raw')
self.assertEqual(err.getvalue(), '')
create_mock.assert_called_once_with('path:/docs/new', '# Hello\n', False, lang='ja')
confirm_calls = []
def record_confirm(addr, status):
confirm_calls.append((addr, status))
return True
with patch.object(client_ja, 'snapshot', side_effect=Failure('Access denied', 403)), \
patch.dict(m['editor'].__globals__, {'confirm_create': record_confirm}), \
patch.object(client_ja, 'create_page', return_value={'path': '/docs/create-only', 'object_uuid': 'obj-2', 'revision_uuid': 'rev-2'}), \
patch('subprocess.run', side_effect=edit_ok), \
contextlib.redirect_stdout(io.StringIO()):
m['editor'](client_ja, 'path:/docs/create-only', 'auto')
self.assertEqual(confirm_calls, [('path:/docs/create-only', 403)])
for non_creatable in ('uuid:00000000-0000-0000-0000-000000000000', 'rev:00000000-0000-0000-0000-000000000000', 'path:/'):
with patch.object(client, 'snapshot', side_effect=Failure('Not found', 404)), \
patch.dict(m['editor'].__globals__, {'confirm_create': lambda *_: self.fail('should not prompt')}):
with self.assertRaises(Failure):
m['editor'](client, non_creatable, 'auto')
non_tty = io.StringIO('y\n')
with patch.object(m['sys'], 'stdin', non_tty), \
patch.object(client, 'snapshot', side_effect=Failure('Not found', 404)):
with self.assertRaises(Failure) as caught:
m['editor'](client, 'path:/docs/new', 'auto')
self.assertEqual(caught.exception.status, 404)
def test_editor_new_page_empty_aborts_and_failure_retains_private_recovery(self):
client = Client('https://example.test', 'secret-token', 'auto')
with tempfile.TemporaryDirectory() as root:
directory = Path(root) / 'empty'; directory.mkdir(mode=0o700)
with patch('tempfile.mkdtemp', return_value=str(directory)), \
patch.object(client, 'snapshot', side_effect=Failure('Not found', 404)), \
patch.dict(m['editor'].__globals__, {'confirm_create': lambda addr, st: True}), \
patch.object(client, 'create_page') as create_mock, \
patch('subprocess.run', return_value=type('R', (), {'returncode': 0})()), \
contextlib.redirect_stdout(io.StringIO()) as out, \
contextlib.redirect_stderr(io.StringIO()):
m['editor'](client, 'path:/docs/empty', 'auto')
create_mock.assert_not_called()
self.assertIn('was not created', out.getvalue())
self.assertFalse(directory.exists())
working = Path(root) / 'race'; working.mkdir(mode=0o700)
def edit_write(args, **kwargs):
Path(args[-1]).write_text('draft body', encoding='utf-8')
return type('R', (), {'returncode': 0})()
with patch('tempfile.mkdtemp', return_value=str(working)), \
patch.object(client, 'snapshot', side_effect=Failure('Not found', 404)), \
patch.dict(m['editor'].__globals__, {'confirm_create': lambda addr, st: True}), \
patch.object(client, 'create_page', side_effect=Failure('Conflict', 412)), \
patch('subprocess.run', side_effect=edit_write), \
patch.object(m['sys'], 'stdin', io.StringIO('')), \
contextlib.redirect_stdout(io.StringIO()), \
contextlib.redirect_stderr(io.StringIO()) as err:
with self.assertRaises(Failure) as caught:
m['editor'](client, 'path:/docs/race', 'auto')
self.assertEqual(caught.exception.status, 412)
self.assertNotIn('secret-token', err.getvalue())
self.assertEqual((working / 'document.md').read_text(encoding='utf-8'), 'draft body')
self.assertEqual(stat.S_IMODE((working / 'document.md').stat().st_mode), 0o600)
recovery_text = (working / 'recovery.json').read_text(encoding='utf-8')
self.assertNotIn('secret-token', recovery_text)
recovery = json.loads(recovery_text)
self.assertEqual(recovery['mode'], 'create')
self.assertEqual(recovery['address'], 'path:/docs/race')
self.assertEqual(recovery['lang'], 'und')
self.assertEqual(recovery['format'], 'markdown')
self.assertEqual(stat.S_IMODE((working / 'recovery.json').stat().st_mode), 0o600)
def test_editor_409_interactive_edit_and_force_save(self):
state = {'object_uuid': 'object', 'head_revision_uuid': 'base-rev', 'principal_uuid': 'person', 'lang': 'und',
'content_type': 'text/plain', 'filename': 'x.txt', 'body': 'base\n', 'markdown': 'base\n'}
latest = {'object_uuid': 'object', 'head_revision_uuid': 'latest-rev', 'principal_uuid': 'person', 'lang': 'und',
'content_type': 'text/plain', 'filename': 'x.txt', 'body': 'remote line\n', 'markdown': 'remote line\n'}
client = Client('https://example.test', 'token')
with tempfile.TemporaryDirectory() as root:
working = Path(root) / 'merge'; working.mkdir(mode=0o700)
seen_buffers = []
call_count = [0]
def run_ed(args, **kwargs):
call_count[0] += 1
p = Path(args[-1])
if call_count[0] == 1:
p.write_text('local line\n', encoding='utf-8')
else:
seen_buffers.append(p.read_text(encoding='utf-8'))
p.write_text('merged line\n', encoding='utf-8')
return type('R', (), {'returncode': 0})()
with patch('tempfile.mkdtemp', return_value=str(working)), \
patch('subprocess.run', side_effect=run_ed), \
patch.object(client, 'snapshot', side_effect=[state, latest]), \
patch.object(client, 'save', side_effect=[Failure('conflict', 409), {'revision_uuid': 'merged-rev'}]) as save_mock, \
patch.dict(m['editor'].__globals__, {'choose_conflict_action': lambda kind, has_remote=True: 'e'}), \
contextlib.redirect_stdout(io.StringIO()) as out:
m['editor'](client, 'path:/x', 'auto')
self.assertIn('<<<<<<< local\nlocal line\n=======\nremote line\n>>>>>>> remote (rev: latest-rev)\n', seen_buffers[0])
self.assertEqual(save_mock.call_args_list[1].args, (latest, 'merged line\n', False))
self.assertIn('Saved revision: merged-rev', out.getvalue())
self.assertFalse(working.exists())
markers = Path(root) / 'markers'; markers.mkdir(mode=0o700)
call_count[0] = 0
def leave_markers(args, **kwargs):
call_count[0] += 1
if call_count[0] == 1:
Path(args[-1]).write_text('local line\n', encoding='utf-8')
return type('R', (), {'returncode': 0})()
with patch('tempfile.mkdtemp', return_value=str(markers)), \
patch('subprocess.run', side_effect=leave_markers), \
patch.object(client, 'snapshot', side_effect=[state, latest]), \
patch.object(client, 'save', side_effect=Failure('conflict', 409)) as save_mock, \
patch.dict(m['editor'].__globals__, {'choose_conflict_action': lambda kind, has_remote=True: 'e'}), \
contextlib.redirect_stdout(io.StringIO()), \
contextlib.redirect_stderr(io.StringIO()) as err:
with self.assertRaises(Failure) as caught:
m['editor'](client, 'path:/x', 'auto')
self.assertEqual(caught.exception.status, 409)
self.assertEqual(save_mock.call_count, 1)
self.assertIn('Conflict markers remain', err.getvalue())
self.assertTrue((markers / 'recovery.json').exists())
force_dir = Path(root) / 'force'; force_dir.mkdir(mode=0o700)
def edit_local(args, **kwargs):
Path(args[-1]).write_text('forced body\n', encoding='utf-8')
return type('R', (), {'returncode': 0})()
with patch('tempfile.mkdtemp', return_value=str(force_dir)), \
patch('subprocess.run', side_effect=edit_local) as run_mock, \
patch.object(client, 'snapshot', side_effect=[state, latest]), \
patch.object(client, 'save', side_effect=[Failure('conflict', 409), {'revision_uuid': 'forced-rev'}]) as save_mock, \
patch.dict(m['editor'].__globals__, {'choose_conflict_action': lambda kind, has_remote=True: 'f'}), \
contextlib.redirect_stdout(io.StringIO()) as out:
m['editor'](client, 'path:/x', 'auto')
self.assertEqual(run_mock.call_count, 1)
self.assertEqual(save_mock.call_args_list[1].args, (latest, 'forced body\n', False))
self.assertIn('Saved revision: forced-rev', out.getvalue())
self.assertFalse(force_dir.exists())
def test_editor_412_interactive_pick_path_and_merge(self):
client = Client('https://example.test', 'token', 'auto')
with tempfile.TemporaryDirectory() as root:
pick_dir = Path(root) / 'pick'; pick_dir.mkdir(mode=0o700)
def edit_new(args, **kwargs):
Path(args[-1]).write_text('# New Draft\n', encoding='utf-8')
return type('R', (), {'returncode': 0})()
with patch('tempfile.mkdtemp', return_value=str(pick_dir)), \
patch('subprocess.run', side_effect=edit_new), \
patch.object(client, 'snapshot', side_effect=[Failure('Not found', 404), Failure('Forbidden', 403)]), \
patch.object(client, 'create_page', side_effect=[Failure('Exists', 412), {'path': '/docs/alt', 'object_uuid': 'obj-2', 'revision_uuid': 'rev-2'}]) as create_mock, \
patch.dict(m['editor'].__globals__, {
'confirm_create': lambda addr, st: True,
'choose_conflict_action': lambda kind, has_remote=True: 'p',
'prompt_new_path': lambda cwd='/': 'path:/docs/alt',
}), \
contextlib.redirect_stdout(io.StringIO()) as out, \
contextlib.redirect_stderr(io.StringIO()):
m['editor'](client, 'path:/docs/orig', 'auto')
self.assertEqual(create_mock.call_args_list[1].args[0], 'path:/docs/alt')
self.assertIn('Created page: /docs/alt', out.getvalue())
self.assertFalse(pick_dir.exists())
merge_dir = Path(root) / 'merge-create'; merge_dir.mkdir(mode=0o700)
existing = {'object_uuid': 'obj-existing', 'head_revision_uuid': 'rev-existing', 'principal_uuid': 'person',
'lang': 'ja', 'content_type': 'text/html', 'filename': '', 'body': '<p>Existing</p>', 'markdown': 'Existing\n'}
call_count = [0]
seen_buffers = []
def edit_merge(args, **kwargs):
call_count[0] += 1
p = Path(args[-1])
if call_count[0] == 1:
p.write_text('My new page\n', encoding='utf-8')
else:
seen_buffers.append(p.read_text(encoding='utf-8'))
p.write_text('Combined page\n', encoding='utf-8')
return type('R', (), {'returncode': 0})()
with patch('tempfile.mkdtemp', return_value=str(merge_dir)), \
patch('subprocess.run', side_effect=edit_merge), \
patch.object(client, 'snapshot', side_effect=[Failure('Not found', 404), existing]), \
patch.object(client, 'create_page', side_effect=Failure('Exists', 412)), \
patch.object(client, 'save', return_value={'revision_uuid': 'rev-combined'}) as save_mock, \
patch.dict(m['editor'].__globals__, {
'confirm_create': lambda addr, st: True,
'choose_conflict_action': lambda kind, has_remote=True: 'e',
}), \
contextlib.redirect_stdout(io.StringIO()) as out, \
contextlib.redirect_stderr(io.StringIO()):
m['editor'](client, 'path:/docs/race', 'auto')
self.assertIn('<<<<<<< local\nMy new page\n=======\nExisting\n>>>>>>> remote (rev: rev-existing)\n', seen_buffers[0])
save_mock.assert_called_once_with(existing, 'Combined page\n', True)
self.assertIn('Saved revision: rev-combined', out.getvalue())
self.assertFalse(merge_dir.exists())
def test_recover_list_resume_conflict_discard_and_security(self):
client = Client('https://example.test', 'token', 'auto')
profile = type('P', (), {'data': {'cwd': '/notes'}})()
def make_draft(base_dir, name, meta, doc_text, *, dir_mode=0o700, file_mode=0o600):
d = Path(base_dir) / name
d.mkdir(mode=0o700)
doc_name = 'document.md' if meta['format'] == 'markdown' else 'document.txt'
doc = d / doc_name
doc.touch(mode=0o600); doc.write_text(doc_text, encoding='utf-8'); doc.chmod(file_mode)
meta_file = d / 'recovery.json'
meta_file.touch(mode=0o600); meta_file.write_text(json.dumps(meta), encoding='utf-8'); meta_file.chmod(file_mode)
d.chmod(dir_mode)
return d, doc, meta_file
with tempfile.TemporaryDirectory() as root:
good_dir, good_doc, _ = make_draft(root, 'pageswiki-edit-good', {
'origin': 'https://example.test', 'address': 'uuid:obj-1',
'base_revision_uuid': 'rev-1', 'lang': 'ja', 'format': 'raw',
}, 'recovered text\n')
make_draft(root, 'pageswiki-edit-badperm', {
'origin': 'https://example.test', 'address': 'uuid:obj-2',
'base_revision_uuid': 'rev-2', 'lang': 'ja', 'format': 'raw',
}, 'ignored\n', dir_mode=0o755)
bad_link = Path(root) / 'pageswiki-edit-symlink'
bad_link.symlink_to(good_dir)
out = io.StringIO()
with contextlib.redirect_stdout(out):
m['recover'](client, profile, list_only=True, temp_root=root)
lines = out.getvalue().strip().splitlines()
self.assertEqual(len(lines), 1)
self.assertIn(str(good_dir), lines[0])
self.assertNotIn('badperm', out.getvalue())
self.assertNotIn('symlink', out.getvalue())
bad_link.unlink()
# Resume update when head still matches.
state = {'object_uuid': 'obj-1', 'head_revision_uuid': 'rev-1', 'principal_uuid': 'person',
'lang': 'ja', 'content_type': 'text/plain', 'filename': 'a.txt', 'body': 'old', 'markdown': 'old'}
with patch.object(client, 'snapshot', return_value=state), \
patch.object(client, 'save', return_value={'revision_uuid': 'rev-2'}) as save_mock, \
contextlib.redirect_stdout(io.StringIO()) as out:
m['recover'](client, profile, str(good_doc))
save_mock.assert_called_once_with(state, 'recovered text\n', False)
self.assertIn('Saved revision: rev-2', out.getvalue())
self.assertFalse(good_dir.exists())
# Resume update when remote head changed: non-interactive keeps draft; interactive 'e' merges.
moved_dir, moved_doc, _ = make_draft(root, 'pageswiki-edit-moved', {
'origin': 'https://example.test', 'address': 'uuid:obj-1',
'base_revision_uuid': 'rev-1', 'lang': 'ja', 'format': 'raw',
}, 'draft edit\n')
newer = {'object_uuid': 'obj-1', 'head_revision_uuid': 'rev-9', 'principal_uuid': 'person',
'lang': 'ja', 'content_type': 'text/plain', 'filename': 'a.txt', 'body': 'newer remote\n', 'markdown': 'newer remote\n'}
with patch.object(client, 'snapshot', return_value=newer), \
patch.object(client, 'save') as save_mock, \
patch.object(m['sys'], 'stdin', io.StringIO('')), \
contextlib.redirect_stdout(io.StringIO()):
with self.assertRaises(Failure) as caught:
m['recover'](client, profile, str(moved_dir))
self.assertEqual(caught.exception.status, 409)
save_mock.assert_not_called()
self.assertTrue(moved_doc.exists())
def resolve_in_ed(args, **kwargs):
p = Path(args[-1])
self.assertIn('<<<<<<< local\ndraft edit\n=======\nnewer remote\n>>>>>>> remote (rev: rev-9)\n', p.read_text(encoding='utf-8'))
p.write_text('resolved draft\n', encoding='utf-8')
return type('R', (), {'returncode': 0})()
with patch.object(client, 'snapshot', return_value=newer), \
patch.object(client, 'save', return_value={'revision_uuid': 'rev-10'}) as save_mock, \
patch('subprocess.run', side_effect=resolve_in_ed), \
patch.dict(m['recover'].__globals__, {'choose_conflict_action': lambda kind, has_remote=True: 'e'}), \
contextlib.redirect_stdout(io.StringIO()):
m['recover'](client, profile, str(moved_dir))
save_mock.assert_called_once_with(newer, 'resolved draft\n', False)
self.assertFalse(moved_dir.exists())
# Resume create draft.
create_dir, _, _ = make_draft(root, 'pageswiki-edit-create', {
'origin': 'https://example.test', 'mode': 'create', 'address': 'path:/docs/new',
'lang': 'und', 'format': 'markdown',
}, '# Created from recovery\n')
with patch.object(client, 'create_page', return_value={'path': '/docs/new', 'object_uuid': 'obj-new', 'revision_uuid': 'rev-new'}) as create_mock, \
contextlib.redirect_stdout(io.StringIO()) as out:
m['recover'](client, profile, str(create_dir))
create_mock.assert_called_once_with('path:/docs/new', '# Created from recovery\n', True, lang='und')
self.assertIn('Created page: /docs/new', out.getvalue())
self.assertFalse(create_dir.exists())
# Reject wrong origin with zero network calls.
other_dir, _, _ = make_draft(root, 'pageswiki-edit-other', {
'origin': 'https://other.example', 'address': 'uuid:obj-1',
'base_revision_uuid': 'rev-1', 'lang': 'und', 'format': 'raw',
}, 'other\n')
with patch.object(client, 'snapshot') as snap_mock, patch.object(client, 'save') as save_mock:
with self.assertRaisesRegex(Failure, 'different server origin'):
m['recover'](client, profile, str(other_dir))
snap_mock.assert_not_called(); save_mock.assert_not_called()
# Reject insecure permissions and discard safety check.
_, insecure_doc, _ = make_draft(root, 'pageswiki-edit-insecure', {
'origin': 'https://example.test', 'address': 'uuid:obj-1',
'base_revision_uuid': 'rev-1', 'lang': 'und', 'format': 'raw',
}, 'x\n', file_mode=0o644)
with self.assertRaisesRegex(Failure, '0600'):
m['recover'](client, profile, str(insecure_doc))
outside_dir, _, _ = make_draft(root, 'custom-dir', {
'origin': 'https://example.test', 'address': 'uuid:obj-1',
'base_revision_uuid': 'rev-1', 'lang': 'und', 'format': 'raw',
}, 'x\n')
with self.assertRaisesRegex(Failure, 'Refusing to discard'):
m['recover'](client, profile, str(outside_dir), discard=True)
self.assertTrue(outside_dir.exists())
discard_dir, _, _ = make_draft(root, 'pageswiki-edit-discard', {
'origin': 'https://example.test', 'address': 'uuid:obj-1',
'base_revision_uuid': 'rev-1', 'lang': 'und', 'format': 'raw',
}, 'x\n')
with contextlib.redirect_stdout(io.StringIO()) as out:
m['recover'](client, profile, str(discard_dir), discard=True)
self.assertIn('Discarded recovery draft', out.getvalue())
self.assertFalse(discard_dir.exists())
def oidc_integration(): def oidc_integration():
fixture=json.load(sys.stdin) fixture=json.load(sys.stdin)
@@ -367,7 +838,7 @@ def oidc_integration():
return True return True
with tempfile.TemporaryDirectory() as root,patch.dict(os.environ,{'XDG_CONFIG_HOME':root}),contextlib.redirect_stdout(io.StringIO()) as output: 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']]) m['main'](['configure','--origin',fixture['origin']])
with patch.object(Client,'json',capture),patch.object(m['webbrowser'],'open',browser): m['main'](['login','--oidc']) with patch.object(Client,'json',capture),patch.object(m['webbrowser'],'open',browser): m['main'](['login','--oidc','--with-open-browser'])
with Profile('default',root).locked() as session: with Profile('default',root).locked() as session:
token=session.data['token']; assert session.data['username']=='admin' token=session.data['token']; assert session.data['username']=='admin'
m['main'](['ls']); m['main'](['status']) m['main'](['ls']); m['main'](['status'])
+1 -1
View File
@@ -50,6 +50,6 @@ class RememberTests(unittest.TestCase):
'user_code': 'ABCD-1234', 'expires_in': 300, 'interval': 5} 'user_code': 'ABCD-1234', 'expires_in': 300, 'interval': 5}
result = {'access_token': 'pw_api_'+'x'*43, 'token_type': 'Bearer', 'expires_in': 2592000, 'username': 'anya'} result = {'access_token': 'pw_api_'+'x'*43, 'token_type': 'Bearer', 'expires_in': 2592000, 'username': 'anya'}
with patch.object(client, 'json', side_effect=[start, result]) as api, contextlib.redirect_stdout(io.StringIO()): with patch.object(client, 'json', side_effect=[start, result]) as api, contextlib.redirect_stdout(io.StringIO()):
client.login_oidc(True, remember=remember, sleep=lambda _: None, clock=lambda: 0) client.login_oidc(remember=remember, sleep=lambda _: None, clock=lambda: 0)
self.assertEqual(api.call_args_list[0].kwargs['form'].get('remember'), '1' if remember else None) self.assertEqual(api.call_args_list[0].kwargs['form'].get('remember'), '1' if remember else None)
self.assertNotIn('remember', api.call_args_list[1].kwargs['form']) self.assertNotIn('remember', api.call_args_list[1].kwargs['form'])
+1 -1
View File
@@ -142,7 +142,7 @@ class TLSTests(unittest.TestCase):
def test_oidc_client_uses_explicit_tls_context(self): def test_oidc_client_uses_explicit_tls_context(self):
client=Client(self.base,insecure=True) client=Client(self.base,insecure=True)
with patch.object(m['webbrowser'],'open') as browser,contextlib.redirect_stdout(io.StringIO()) as out: with patch.object(m['webbrowser'],'open') as browser,contextlib.redirect_stdout(io.StringIO()) as out:
_,username=client.login_oidc(no_browser=True,sleep=lambda _:None) _,username=client.login_oidc(sleep=lambda _:None)
browser.assert_not_called() browser.assert_not_called()
self.assertEqual(username,'synthetic') self.assertEqual(username,'synthetic')
self.assertEqual(client.token,self.token) self.assertEqual(client.token,self.token)