Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
bee03094f3 | ||
|
|
e27c023d66 | ||
|
|
bd54b5f06a | ||
|
|
e22af6a0ec | ||
|
|
541c2bd069 | ||
|
|
cde94ed936 | ||
|
|
59ab4c5b26 |
No files matched your search
@@ -45,9 +45,10 @@ 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
|
python -m unittest test_pages test_productivity test_distribution test_tls
|
||||||
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
|
||||||
- name: Publish release assets
|
- name: Publish release assets
|
||||||
if: startsWith(github.ref, 'refs/tags/v')
|
if: startsWith(github.ref, 'refs/tags/v')
|
||||||
env:
|
env:
|
||||||
|
|||||||
+3
-3
@@ -18,8 +18,8 @@ rpm/debは初期配布の必須条件にせず、LinuxはELFを提供する。Py
|
|||||||
|
|
||||||
```sh
|
```sh
|
||||||
# ダウンロード先で実行。手元にあるファイルをチェックする。
|
# ダウンロード先で実行。手元にあるファイルをチェックする。
|
||||||
sha256sum --ignore-missing -c pages-cli-v0.1.0-linux-amd64-SHA256SUMS
|
sha256sum --ignore-missing -c pages-cli-v0.4.2-linux-amd64-SHA256SUMS
|
||||||
tar -xzf pages-cli-v0.1.0-linux-amd64.tar.gz
|
tar -xzf pages-cli-v0.4.2-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
|
||||||
@@ -35,6 +35,6 @@ mainへのpushはテスト・ビルドのみ。`vX.Y.Z` タグのpushは同じ
|
|||||||
|
|
||||||
既存runnerにはdocker/buildxとGiteaへのHTTPS接続が必要。公開にはジョブのtokenを使用し、権限不足の場合だけこのリポジトリに限定した `CLI_RELEASE_TOKEN` を設定する。サーバーリポジトリのPATやDocker資格情報をコピーしない。
|
既存runnerにはdocker/buildxとGiteaへのHTTPS接続が必要。公開にはジョブのtokenを使用し、権限不足の場合だけこのリポジトリに限定した `CLI_RELEASE_TOKEN` を設定する。サーバーリポジトリのPATやDocker資格情報をコピーしない。
|
||||||
|
|
||||||
macOSは `CLI_MACOS_ENABLED=true` と `CLI_MACOS_RUNNER_LABEL` を設定した場合のみ起動する。runnerにはPython 3とgitが必要で、タグcheckout後に同じbuild.pyを実行する。Macの最低OS、CPU、署名・公証は実際のrunnerと検証結果に合わせて公開時に明記する。Windowsは安全な資格情報保存の移植が済むまでジョブを有効化しない。
|
macOSは `CLI_MACOS_ENABLED=true` と `CLI_MACOS_RUNNER_LABEL` を設定した場合のみ起動する。runnerにはPython 3、git、一時テスト証明書を生成するOpenSSLコマンドが必要で、タグcheckout後に同じbuild.pyを実行する。Macの最低OS、CPU、署名・公証は実際のrunnerと検証結果に合わせて公開時に明記する。Windowsは安全な資格情報保存の移植が済むまでジョブを有効化しない。
|
||||||
|
|
||||||
サーバーリポジトリ側の旧pages-cliは結合テスト用スナップショット。CLIの新規実装・配布はこのリポジトリで行い、サーバーの結合テスト用コピーはレビューしたリビジョンに明示的に更新する。
|
サーバーリポジトリ側の旧pages-cliは結合テスト用スナップショット。CLIの新規実装・配布はこのリポジトリで行い、サーバーの結合テスト用コピーはレビューしたリビジョンに明示的に更新する。
|
||||||
+1
-1
@@ -6,6 +6,6 @@ ENV SOURCE_REVISION=$SOURCE_REVISION
|
|||||||
COPY requirements-build.txt .
|
COPY requirements-build.txt .
|
||||||
RUN pip install --no-cache-dir -r requirements-build.txt
|
RUN pip install --no-cache-dir -r requirements-build.txt
|
||||||
COPY . .
|
COPY . .
|
||||||
RUN python -m unittest test_pages test_productivity test_distribution && python tools/build.py && python tools/smoke_binary.py dist/pages
|
RUN python -m unittest test_pages test_productivity test_distribution test_tls test_remember && python tools/build.py && python tools/smoke_binary.py dist/pages && PAGES_CLI_TEST_BINARY=/src/dist/pages python -m unittest test_tls
|
||||||
FROM scratch AS artifacts
|
FROM scratch AS artifacts
|
||||||
COPY --from=build /src/release/ /
|
COPY --from=build /src/release/ /
|
||||||
@@ -36,7 +36,40 @@ pages[default]:/manual> exit
|
|||||||
|
|
||||||
`exit` はシェルを閉じるだけです。セッションを失効させる場合は `pages logout`。
|
`exit` はシェルを閉じるだけです。セッションを失効させる場合は `pages logout`。
|
||||||
|
|
||||||
### OIDCでログインする
|
### 自己署名証明書の環境に接続する
|
||||||
|
|
||||||
|
v0.2.0以降では、グローバルオプション `--insecure`(`-k`)を**コマンドの前**に指定すると、その実行中だけTLS証明書とホスト名の検証をスキップできます。既定では必ず検証し、設定・セッションにはスキップ状態を保存しません。
|
||||||
|
|
||||||
|
```sh
|
||||||
|
pages configure --origin https://wiki.example.test --username YOUR_USERNAME
|
||||||
|
pages --insecure login
|
||||||
|
pages -k task list
|
||||||
|
pages -k edit /guide --lang ja
|
||||||
|
pages -k # この対話シェルの終了まで適用
|
||||||
|
pages -k logout
|
||||||
|
```
|
||||||
|
|
||||||
|
指定のたびに標準エラーへ警告を表示します。標準出力のJSONやNeoMutt宛先候補には混ぜません。次のコマンドでは、必要なら改めて `-k` を付けます。`configure` は通信しないため `-k configure` は拒否します。
|
||||||
|
|
||||||
|
**自己署名証明書だけでなく、期限切れやホスト名不一致も許容します。通信は暗号化されますが、相手の真正性を確認できず、中間者攻撃でパスワード・Bearer・文書等を盗み見られる危険があります。** 信頼できる検証環境でのみ明示指定し、常用する環境では信頼するCAをOSへ登録して通常の検証を使ってください。遠隔HTTP、リダイレクト追従、TLS失敗時の自動再送は引き続き許可しません。
|
||||||
|
|
||||||
|
OIDCでは `pages -k login --oidc --no-browser` のように指定できます。ただし、スキップするのはCLIのHTTPS要求のみです。開いたブラウザやOIDCプロバイダーの証明書検証は変更しません。
|
||||||
|
|
||||||
|
### 信頼できる端末でログインを維持する
|
||||||
|
|
||||||
|
開発版(未リリース)では、対応サーバーと組み合わせて最長30日のログインを選択できます。
|
||||||
|
|
||||||
|
```sh
|
||||||
|
pages login --remember
|
||||||
|
pages login --oidc --no-browser --remember
|
||||||
|
```
|
||||||
|
|
||||||
|
実際の期限はサーバー管理者の設定に従います。旧サーバーでは通常の期限になる場合があります。
|
||||||
|
パスワード認証のTOTP、ログアウト、管理者による失効、アカウント停止は従来どおり有効です。
|
||||||
|
共有端末では使用しないでください。アクセスによる期限の自動延長は行いません。
|
||||||
|
期限切れ後はlogoutなしで再ログインでき、同じアカウントの作業パスと未送信タスク下書きを保持します。
|
||||||
|
|
||||||
|
### OIDC認証の手順
|
||||||
|
|
||||||
OIDC連携を有効にしたDomainで利用します。サーバーは **v0.3.0以降** が必要です。独立版CLI v0.1.0は対応済みです(分離前のCLIではサーバー同梱版v0.3.0以降)。
|
OIDC連携を有効にしたDomainで利用します。サーバーは **v0.3.0以降** が必要です。独立版CLI v0.1.0は対応済みです(分離前のCLIではサーバー同梱版v0.3.0以降)。
|
||||||
CLIのファイルだけを更新しても、v0.2.xのサーバーでは利用できません。
|
CLIのファイルだけを更新しても、v0.2.xのサーバーでは利用できません。
|
||||||
@@ -150,12 +183,16 @@ pages edit /guide --lang en # 英語版。未作成なら既存内容から
|
|||||||
## テスト
|
## テスト
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
python3 -m unittest test_pages test_productivity test_distribution
|
python3 -m unittest test_pages test_productivity test_distribution test_tls
|
||||||
```
|
```
|
||||||
|
|
||||||
合成サーバーと一時ディレクトリのみを使用します。本番資格情報や外部カレンダーは不要です。Goサーバーとの結合テストはサーバーリポジトリ側で実行します。
|
合成サーバーと一時ディレクトリのみを使用します。TLS試験には一時証明書を生成するOpenSSLコマンドが必要です。本番資格情報や外部カレンダーは不要です。Goサーバーとの結合テストはサーバーリポジトリ側で実行します。
|
||||||
## タスクと連絡先
|
## タスクと連絡先
|
||||||
|
|
||||||
|
v0.4.0のメール保存先はML連番があれば `親Path/リスト名/連番`、なければ `親Path/YYYY/MM/識別子` です。この方式にはサーバーv0.9.0以降が必要です。年月・衝突・旧版からの再送の規則は下記NeoMuttガイドを参照してください。
|
||||||
|
|
||||||
|
v0.3.0の `pages task from-mail` は本文を関連Wikiへ保存します(サーバーv0.8.0以降)。先に `pages task preferences --wiki-prefix /YOUR/MAIL/PATH` で閲覧制限済みの親Pathを指定してください。タスクの公開範囲とは独立して、本文はWikiの権限に従います。本文を送信しない場合は `--metadata-only` を指定します。
|
||||||
|
|
||||||
`pages task --help` で作成・計画・開始/終了・レポートを操作できる。
|
`pages task --help` で作成・計画・開始/終了・レポートを操作できる。
|
||||||
`pages contacts --help` で個人アドレス帳の検索・vCard入出力を行える。
|
`pages contacts --help` で個人アドレス帳の検索・vCard入出力を行える。
|
||||||
[NeoMutt設定とタスク・連絡先の操作例](docs/neomutt.md)、[そのまま調整して使える設定例](examples/neomuttrc)を参照。これらは配布アーカイブにも同梱します。
|
[NeoMutt設定とタスク・連絡先の操作例](docs/neomutt.md)、[そのまま調整して使える設定例](examples/neomuttrc)を参照。これらは配布アーカイブにも同梱します。
|
||||||
@@ -4,7 +4,9 @@ pages-cliはPagesWikiのHTTPクライアントであり、DBやDocument Storeを
|
|||||||
|
|
||||||
## 接続と認証
|
## 接続と認証
|
||||||
|
|
||||||
接続先のoriginでDomainを決め、サーバーの既存認証・権限評価を使う。遠隔接続はHTTPS必須。証明書検証を無効にするオプションはない。HTTPはloopbackでの開発専用。originにuserinfo、Path、query、fragmentを含めず、リダイレクトには追従しない。ログイン画面のHTMLや302/303をAPIの成功として扱わない。
|
接続先のoriginでDomainを決め、サーバーの既存認証・権限評価を使う。遠隔接続はHTTPS必須で、既定では証明書とホスト名を検証する。v0.2.0以降の `--insecure` / `-k` はその呼出しだけ検証をスキップし、設定やセッションへ保存しない。期限切れ・ホスト名不一致も許容するため、信頼できる検証環境でのみ使用する。CLIのSSLContextだけを変更し、プロセス全体のTLS既定値やOIDCブラウザの検証は変更しない。警告は標準エラーへ出力する。詳細は[利用手順とリスク](../README.md#自己署名証明書の環境に接続する)を参照。
|
||||||
|
|
||||||
|
`-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 [--no-browser]` ではブラウザのOIDCログイン後に、ターミナルの確認コードを入力して承認する。S256でCLIのverifierに束縛し、短期リクエストを一度だけBearerセッションへ交換する。SSH先から開始し、別端末で承認できる。ブラウザCookie、外部OIDC token、Campus用PSKをCLIのBearerとして流用しない。
|
||||||
|
|
||||||
|
|||||||
+60
-5
@@ -5,6 +5,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 --no-browser
|
||||||
|
pages task preferences --wiki-prefix /private/mail
|
||||||
pages task --help
|
pages task --help
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -15,13 +16,35 @@ pages task --help
|
|||||||
```sh
|
```sh
|
||||||
pages task from-mail < message.eml
|
pages task from-mail < message.eml
|
||||||
pages task from-mail --project '開発 計画' --due 2026-11-03 < message.eml
|
pages task from-mail --project '開発 計画' --due 2026-11-03 < message.eml
|
||||||
# 本文を保存してよいメールに限り明示する
|
# このメールだけ保存先の親Pathを変更
|
||||||
pages task from-mail --include-body < message.eml
|
pages task from-mail --wiki-prefix /private/work-mail < message.eml
|
||||||
|
# 本文を送らず、件名とメタデータだけタスクにする
|
||||||
|
pages task from-mail --metadata-only < message.eml
|
||||||
```
|
```
|
||||||
|
|
||||||
既定では件名をタスク名、From・Date・Message-IDをメモにする。本文と添付はアップロードしない。include-bodyはplain text本文だけを追加し、HTML画像・添付・外部URLは取得しない。1通2 MiB、メモ16 KiBが上限。件名が300 UTF-8 bytesを超える場合は `--title '短い件名'` で指定する。
|
v0.3.0からは件名をタスク名、From・Date・Message-IDをメモにし、**本文を関連Wikiページに保存する**。PagesWiki v0.8.0以降が必要。保存先は `--wiki-prefix`、個人設定の既定Wiki親Path、選択プロジェクトのWiki配下(メモの階層)の順に決まる。どれも未設定なら保存を中止し、下書きを保持する。Webでは `/-/sys/config?panel=organizer` の「メール本文の既定Wiki親Path」で確認・変更できる。CLIで空文字を設定すると個人の既定Pathを解除できる。
|
||||||
|
|
||||||
同じ接続・本人・Message-IDから同じrequest_idを作るため、同じメールの再取り込みで重複しない。Message-IDなしはメール全体のSHA-256を使う。同じメールを別の独立タスクにもしたい場合は `task add` を使う。
|
本文の公開範囲は保存先Wikiの権限に従う。タスクが個人用でも、公開Pathに保存した本文は公開され得るため、メール用には閲覧者を制限したPathを指定する。設定例の `/private/mail` という名前自体が非公開を保証するものではない。
|
||||||
|
|
||||||
|
CLI v0.4.0のメール取り込みにはPagesWiki v0.9.0以降が必要。保存先は次の優先順で決める。
|
||||||
|
|
||||||
|
| メール | 保存先 |
|
||||||
|
| --- | --- |
|
||||||
|
| 先頭にML連番がある | `親Path/リスト名/連番`(例:`/mail/hogehoge/123`) |
|
||||||
|
| ML連番なし、Message-IDあり | `親Path/YYYY/MM/UUID` |
|
||||||
|
| 両方なし | `親Path/YYYY/MM/原文SHA-256` |
|
||||||
|
|
||||||
|
リスト名はASCII英数字で始まり、英数字・ピリオド・ハイフン・アンダースコアの100文字以内。連番は最大20桁で、先頭ゼロを除去する。Re:/Fw:/Fwd:の直後も認識し、先頭のML表記を使う。安全なリスト名・連番として解釈できない場合は年月方式へフォールバックする。表示件名の `--title` は保存先の判定を変えない。
|
||||||
|
|
||||||
|
年月はDateヘッダに記載されたタイムゾーンの年月。Dateが欠落・不正なら最初の取り込み時点のUTC年月を使い、未送信outboxに確定値を保持する。UUIDは接続先・本人・Message-IDから生成し、Message-ID自体をURLへ露出しない。同じML名・連番に異なるメールが来た場合は409で停止し、既存本文を上書きしない。
|
||||||
|
|
||||||
|
既存ページは移動・上書きせず、従来形式で保存済みの要求をretryしても元のページを返す。タスクのメモ閲覧・編集ボタンから本文ページを開ける。タスク・Wiki・再送receiptは同一トランザクションで保存し、途中失敗で片方だけを残さない。UUIDで紐づくので、その後Wikiを移動しても追従する。
|
||||||
|
|
||||||
|
CLI v0.3.1ではMIMEヘッダを復号した件名の先頭から `[list 123]`・`[list:123]`・`[list#123]` のような連番を除去する。Re:/Fwd:は維持し、その後の連番も除去する。`[重要]`、件名の途中の括弧、`--title` で明示した件名は変更しない。自動件名が300 UTF-8 bytesを超える場合は文字境界で省略して末尾に「…」を付ける。除去・省略・手動指定で変わった元のSubjectはWiki本文に残す。手動件名の上限超過は拒否する。
|
||||||
|
|
||||||
|
plain textを優先し、HTMLしかない場合はテキストを抽出する。添付・外部画像・CSS・JS・外部URLは取得せず、本文中のHTMLやWikiマクロも実行しない。原文EMLやHTMLレイアウトの保存機能ではない。入力1通2 MiB、Wiki本文(メタデータ込み)256 KiB、タスクメモ16 KiBまで。本文・メモの上限超過は切り捨てず拒否する。旧 `--include-body` は既定動作の別名として残す。以前の本文非送信動作には `--metadata-only` を使う。
|
||||||
|
|
||||||
|
同じ接続・本人・Message-IDから同じrequest_idを作るため、同じメールの再取り込みで重複しない。Message-IDなしはメール全体のSHA-256を使う。同じIDで本文・指定Path・オプションを変えると412となり、以前のページを上書きしない。旧版でメタデータのみ取り込み済みのメールに本文を追加する場合は、既存の関連Wikiを編集する。同じメールを別の独立タスクにもしたい場合は `task add` を使う。
|
||||||
|
|
||||||
`~/.config/neomutt/neomuttrc` の例。NeoMuttから実行するPATHに `pages` を含めるか、コマンドをインストール先の絶対パスに置き換える。件名等をシェルコマンド文字列に展開せず、メールを標準入力で渡す。[設定ファイル例](../examples/neomuttrc)も配布アーカイブに同梱する。
|
`~/.config/neomutt/neomuttrc` の例。NeoMuttから実行するPATHに `pages` を含めるか、コマンドをインストール先の絶対パスに置き換える。件名等をシェルコマンド文字列に展開せず、メールを標準入力で渡す。[設定ファイル例](../examples/neomuttrc)も配布アーカイブに同梱する。
|
||||||
|
|
||||||
@@ -43,7 +66,35 @@ pages task retry REQUEST_UUID
|
|||||||
|
|
||||||
最大20件を保留でき、成功した要求はローカルから削除する。同じ本人への再ログインで保留分を維持する。別アカウントへ切り替える場合は別プロファイルを使う。認証済みセッションがない状態からの完全オフライン入力受付ではない。
|
最大20件を保留でき、成功した要求はローカルから削除する。同じ本人への再ログインで保留分を維持する。別アカウントへ切り替える場合は別プロファイルを使う。認証済みセッションがない状態からの完全オフライン入力受付ではない。
|
||||||
|
|
||||||
サーバーで保存された直後に応答が失われても、同じrequest_idで再送すれば既存タスクが返る。保留要求を書き換えて再送すると412になる。セッションファイルにはトークンもあるため、デバッグ目的で内容を貼り付けない。
|
CLI v0.4.1以降では、同一内容の保留メールを再入力した場合は、確定済みの保存先を維持する。同じrequest_idで本文・件名・オプションを変更して再入力した場合は、ローカルの保留下書きを新しい内容で上書きしてから1回送信する。送信失敗時も新しい内容を保持する。`task add --request-id` も同じ動作。新しいrequest_idを発行して重複タスクを作る処理ではない。
|
||||||
|
|
||||||
|
`task retry` は、その時点で保持されている下書きを変更せずに送信する。下書きを上書きするには、NeoMuttから同じメールを改めて取り込むか、同じrequest_idを指定した `task add` を実行する。旧版で保留していた下書きも対象となる。
|
||||||
|
|
||||||
|
サーバーにすでに保存済みの同じ要求に対して本文・保存先・オプションが異なる場合は、従来どおり412で停止する。ローカル下書きの上書きは、保存済みタスクやWikiの強制上書きではない。保存済みの内容を変更する場合は通常のタスク/Wiki編集を使う。
|
||||||
|
|
||||||
|
サーバーで保存された直後に応答が失われても、同じrequest_id・同じ内容で再送すれば既存タスクが返る。サーバー保存済みの要求と異なる内容で再送すると412になる。セッションファイルにはトークンと保留中のメール本文があるため、デバッグ目的で内容を貼り付けない。保存先未設定で失敗した場合は `pages task preferences --wiki-prefix /YOUR/MAIL/PATH` で設定してからretryする。
|
||||||
|
|
||||||
|
### 削除済みタスクを再取り込みする
|
||||||
|
|
||||||
|
CLI v0.4.2/PagesWiki v0.14.1以降の機能です。サーバーとCLIの両方の更新が必要で、CLI v0.4.1/PagesWiki v0.14.0では利用できません。
|
||||||
|
|
||||||
|
削除後も重複防止の受付記録は残ります。対応サーバーでは、内容の違いにかかわらず削除済み要求を410 `deleted` で拒否します。通常のretryで復活させず、保留下書きを使った再取り込みは次のように明示します。
|
||||||
|
|
||||||
|
```sh
|
||||||
|
pages task retry REQUEST_UUID --recreate-deleted
|
||||||
|
```
|
||||||
|
|
||||||
|
新しいUUIDのタスクを作成し、旧UUIDの削除記録とCalDAVの識別子予約は残します。同じ操作から生成されるUUIDは一定なので、応答が失われても重複作成しません。旧タスクの完了状態・作業記録・サブタスクを復元する操作ではありません。存続中のタスクをこのオプションで上書きすることもできません。
|
||||||
|
|
||||||
|
Wiki保存先にページが残っている場合は、本文・リビジョンを上書きせず新しいタスクに再リンクします。ページがなければ保留本文から作ります。本文の変更は通常のWiki編集で行ってください。保存先の現在権限が必要です。保存先は保持したsuffix/指定prefixと現在の既定値で決まり、移動された元ページを自動追跡する機能ではありません。
|
||||||
|
|
||||||
|
CLIは送信前に保留下書きを新IDへ移して保存し、`Retry ID:` に新IDを表示します。通信失敗後は新IDを使い、`--recreate-deleted` を付けずに再送します。
|
||||||
|
|
||||||
|
```sh
|
||||||
|
pages task retry NEW_REQUEST_UUID
|
||||||
|
```
|
||||||
|
|
||||||
|
元のメールを再入力するだけでは削除済みの状態を解除しません。受付記録はあるのにタスクと削除記録が両方ない場合は409 `capture_missing` となり、サーバー側の整合性調査が必要です。受付記録・削除記録を手動削除して回避しないでください。
|
||||||
|
|
||||||
## 計画と実績
|
## 計画と実績
|
||||||
|
|
||||||
@@ -100,6 +151,8 @@ Content-Typeはapplication/json、AuthorizationはBearerセッション。例示
|
|||||||
"request_id": "884587b2-6ae5-4aef-86d0-fd21dac39d1c",
|
"request_id": "884587b2-6ae5-4aef-86d0-fd21dac39d1c",
|
||||||
"title": "メールで依頼された内容を確認",
|
"title": "メールで依頼された内容を確認",
|
||||||
"notes": "Message-ID: <example@example.invalid>",
|
"notes": "Message-ID: <example@example.invalid>",
|
||||||
|
"wiki_body": "メール本文をテキストとして保存",
|
||||||
|
"wiki_prefix": "/private/mail",
|
||||||
"estimate_minutes": 30,
|
"estimate_minutes": 30,
|
||||||
"complexity": 2,
|
"complexity": 2,
|
||||||
"due_on": "2026-11-03"
|
"due_on": "2026-11-03"
|
||||||
@@ -112,4 +165,6 @@ Content-Typeはapplication/json、AuthorizationはBearerセッション。例示
|
|||||||
|
|
||||||
NeoMuttでは対話ログインを起動せず、端末で先に `pages login` を完了させる。複数接続を使う場合は、メール取り込み・宛先検索の両方を `pages --profile work ...` に揃える。NeoMutt起動環境のHOME・XDG_CONFIG_HOMEが通常の端末と異なると、別の設定やセッションを参照するので確認する。
|
NeoMuttでは対話ログインを起動せず、端末で先に `pages login` を完了させる。複数接続を使う場合は、メール取り込み・宛先検索の両方を `pages --profile work ...` に揃える。NeoMutt起動環境のHOME・XDG_CONFIG_HOMEが通常の端末と異なると、別の設定やセッションを参照するので確認する。
|
||||||
|
|
||||||
|
自己署名証明書の検証環境ではv0.2.0以降の `pages -k login`、`pages -k task from-mail`、`pages -k contacts query --neomutt -- %s` が使える。`-k` は保存されないため、ログインとNeoMutt設定内の各コマンドに明示する必要がある。警告は標準エラーへ出力し、宛先候補の標準出力には混ぜない。配布設定例は検証有効のままとする。相手の真正性が保証されなくなるリスクと適用範囲は[README](../README.md#自己署名証明書の環境に接続する)を確認する。
|
||||||
|
|
||||||
`pages: not found` の場合は `command -v pages` でインストール先を確認し、設定内のコマンドをその絶対パスに置き換える。`contacts query` の候補がない場合は、まず端末から `pages contacts list --query 検索語` を実行する。認証切れは端末で再ログインしてから再試行する。公開CLIリポジトリへメール原文・連絡先・セッションJSONを添付しない。
|
`pages: not found` の場合は `command -v pages` でインストール先を確認し、設定内のコマンドをその絶対パスに置き換える。`contacts query` の候補がない場合は、まず端末から `pages contacts list --query 検索語` を実行する。認証切れは端末で再ログインしてから再試行する。公開CLIリポジトリへメール原文・連絡先・セッションJSONを添付しない。
|
||||||
@@ -1,5 +1,8 @@
|
|||||||
# Merge into your own NeoMutt configuration; do not replace unrelated settings.
|
# Merge into your own NeoMutt configuration; do not replace unrelated settings.
|
||||||
# Run `pages configure` and `pages login` in a terminal first.
|
# Run `pages configure` and `pages login` in a terminal first.
|
||||||
|
# Configure `pages task preferences --wiki-prefix /YOUR/MAIL/PATH` first.
|
||||||
|
# v0.3.0 uploads the body to Wiki with the destination's visibility/ACL.
|
||||||
|
# Use `from-mail --metadata-only` if the body must not be uploaded.
|
||||||
# `pages` must be on NeoMutt's PATH; otherwise use its absolute install path.
|
# `pages` must be on NeoMutt's PATH; otherwise use its absolute install path.
|
||||||
# For a named connection, use `pages --profile work ...` in BOTH commands.
|
# For a named connection, use `pages --profile work ...` in BOTH commands.
|
||||||
# These pipe settings also affect other pipe-message commands.
|
# These pipe settings also affect other pipe-message commands.
|
||||||
|
|||||||
@@ -3,6 +3,8 @@
|
|||||||
import argparse
|
import argparse
|
||||||
import email.policy
|
import email.policy
|
||||||
import email.parser
|
import email.parser
|
||||||
|
import email.utils
|
||||||
|
import datetime
|
||||||
import uuid
|
import uuid
|
||||||
import base64
|
import base64
|
||||||
import contextlib
|
import contextlib
|
||||||
@@ -10,6 +12,7 @@ import difflib
|
|||||||
import fcntl
|
import fcntl
|
||||||
import getpass
|
import getpass
|
||||||
import hashlib
|
import hashlib
|
||||||
|
from html.parser import HTMLParser
|
||||||
import json
|
import json
|
||||||
import os
|
import os
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
@@ -17,6 +20,7 @@ import posixpath
|
|||||||
import re
|
import re
|
||||||
import secrets
|
import secrets
|
||||||
import shlex
|
import shlex
|
||||||
|
import ssl
|
||||||
import stat
|
import stat
|
||||||
import subprocess
|
import subprocess
|
||||||
import sys
|
import sys
|
||||||
@@ -28,7 +32,7 @@ import urllib.parse as url
|
|||||||
import urllib.request as http
|
import urllib.request as http
|
||||||
import webbrowser
|
import webbrowser
|
||||||
|
|
||||||
VERSION = '0.1.0'
|
VERSION = '0.5.0'
|
||||||
|
|
||||||
class Failure(Exception):
|
class Failure(Exception):
|
||||||
def __init__(self, message, status=0, payload=None):
|
def __init__(self, message, status=0, payload=None):
|
||||||
@@ -75,9 +79,18 @@ class NoRedirect(http.HTTPRedirectHandler):
|
|||||||
|
|
||||||
|
|
||||||
class Client:
|
class Client:
|
||||||
def __init__(self, base, token='', lang='auto'):
|
def __init__(self, base, token='', lang='auto', *, insecure=False):
|
||||||
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.insecure = insecure
|
||||||
|
handlers = [NoRedirect()]
|
||||||
|
if insecure:
|
||||||
|
# This client's TLS policy only; never change Python's global defaults.
|
||||||
|
context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
|
||||||
|
context.check_hostname = False
|
||||||
|
context.verify_mode = ssl.CERT_NONE
|
||||||
|
context.set_alpn_protocols(['http/1.1'])
|
||||||
|
handlers.append(http.HTTPSHandler(context=context))
|
||||||
|
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):
|
||||||
if not route.startswith('/') or route.startswith('//'):
|
if not route.startswith('/') or route.startswith('//'):
|
||||||
@@ -131,9 +144,11 @@ class Client:
|
|||||||
except (ValueError, UnicodeError):
|
except (ValueError, UnicodeError):
|
||||||
raise Failure('Invalid JSON response.') from None
|
raise Failure('Invalid JSON response.') from None
|
||||||
|
|
||||||
def login(self, username, password, otp=getpass.getpass):
|
def login(self, username, password, otp=getpass.getpass, *, remember=False):
|
||||||
|
form={'username':username,'password':password}
|
||||||
|
if remember:form['remember']='1'
|
||||||
try:
|
try:
|
||||||
result = self.json('/_/auth/login', method='POST', form={'username': username, 'password': password})
|
result = self.json('/_/auth/login', method='POST', form=form)
|
||||||
except Failure as e:
|
except Failure as e:
|
||||||
if e.status != 401 or not e.payload.get('mfa_required') or not e.payload.get('challenge_token'):
|
if e.status != 401 or not e.payload.get('mfa_required') or not e.payload.get('challenge_token'):
|
||||||
raise
|
raise
|
||||||
@@ -151,12 +166,13 @@ 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='', *, sleep=time.sleep, clock=time.monotonic):
|
def login_oidc(self, no_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:
|
||||||
started = self.json('/_/auth/cli/start', method='POST', form={
|
form={'code_challenge':challenge,'code_challenge_method':'S256'}
|
||||||
'code_challenge': challenge, 'code_challenge_method': 'S256'})
|
if remember:form['remember']='1'
|
||||||
|
started = self.json('/_/auth/cli/start', method='POST', form=form)
|
||||||
except Failure as e:
|
except Failure as e:
|
||||||
if e.status in (404, 405, 501):
|
if e.status in (404, 405, 501):
|
||||||
raise Failure('CLI OIDC login is unavailable on this server. Check the configured server URL and deploy a server version supporting /_/auth/cli/start.', e.status) from None
|
raise Failure('CLI OIDC login is unavailable on this server. Check the configured server URL and deploy a server version supporting /_/auth/cli/start.', e.status) from None
|
||||||
@@ -470,21 +486,69 @@ def task_project(client, value):
|
|||||||
return matches[0]
|
return matches[0]
|
||||||
|
|
||||||
|
|
||||||
def task_mail(raw, include_body=False, override_title=None):
|
class MailText(HTMLParser):
|
||||||
|
"""Extract inert text; never load links, images, styles or attachments."""
|
||||||
|
def __init__(self):
|
||||||
|
super().__init__(convert_charrefs=True)
|
||||||
|
self.parts, self.hidden = [], []
|
||||||
|
def handle_starttag(self, tag, attrs):
|
||||||
|
if tag in ('script','style','head'): self.hidden.append(tag)
|
||||||
|
if not self.hidden and tag in ('br','p','div','li','tr','h1','h2','h3','pre'): self.parts.append('\n')
|
||||||
|
def handle_endtag(self, tag):
|
||||||
|
if self.hidden and tag == self.hidden[-1]: self.hidden.pop()
|
||||||
|
if not self.hidden and tag in ('p','div','li','tr','h1','h2','h3','pre'): self.parts.append('\n')
|
||||||
|
def handle_data(self, data):
|
||||||
|
if not self.hidden: self.parts.append(data)
|
||||||
|
|
||||||
|
|
||||||
|
def mail_subject(value):
|
||||||
|
# Remove only leading mailing-list sequence markers, preserving meaningful
|
||||||
|
# tags such as [Important], and any Re:/Fwd: prefix before the marker.
|
||||||
|
marker = re.compile(r'^(?P<reply>(?:(?:re|fw|fwd)\s*:\s*)*)\[[^\[\]\r\n]+[\s:#]\s*[0-9]+\]\s*', re.IGNORECASE)
|
||||||
|
while True:
|
||||||
|
match = marker.match(value)
|
||||||
|
if not match: return value.strip()
|
||||||
|
value = match.group('reply') + value[match.end():]
|
||||||
|
|
||||||
|
|
||||||
|
def task_mail_suffix(raw, request_id, now=None):
|
||||||
|
message = email.parser.BytesParser(policy=email.policy.default).parsebytes(raw)
|
||||||
|
subject = ' '.join(safe_text(str(message.get('Subject') or '')).split())
|
||||||
|
marker = re.match(r'^(?:(?:re|fw|fwd)\s*:\s*)*\[([A-Za-z0-9][A-Za-z0-9._-]{0,99})[\s:#]+([0-9]{1,20})\]',subject,re.IGNORECASE)
|
||||||
|
if marker:
|
||||||
|
return marker[1]+'/'+str(int(marker[2]))
|
||||||
|
try: date = email.utils.parsedate_to_datetime(str(message.get('Date') or ''))
|
||||||
|
except (ValueError, TypeError, OverflowError): date = now or datetime.datetime.now(datetime.timezone.utc)
|
||||||
|
# Preserve the month in the sender's Date timezone, not the receiving host's.
|
||||||
|
ident = request_id if ' '.join(safe_text(str(message.get('Message-ID') or '')).split()) else hashlib.sha256(raw).hexdigest()
|
||||||
|
return f'{date.year:04d}/{date.month:02d}/{ident}'
|
||||||
|
|
||||||
|
|
||||||
|
def task_mail(raw, include_body=True, override_title=None):
|
||||||
if len(raw) > 2 << 20: raise Failure('Mail input exceeds 2 MiB; pipe one message at a time.')
|
if len(raw) > 2 << 20: raise Failure('Mail input exceeds 2 MiB; pipe one message at a time.')
|
||||||
message = email.parser.BytesParser(policy=email.policy.default).parsebytes(raw)
|
message = email.parser.BytesParser(policy=email.policy.default).parsebytes(raw)
|
||||||
clean = lambda value: ' '.join(safe_text(str(value or '')).split())
|
clean = lambda value: ' '.join(safe_text(str(value or '')).split())
|
||||||
title = override_title or clean(message.get('Subject')) or '(No subject)'
|
subject = clean(message.get('Subject'))
|
||||||
|
title = override_title or mail_subject(subject) or '(No subject)'
|
||||||
|
if not override_title and len(title.encode()) > 300:
|
||||||
|
title = title.encode()[:297].decode('utf-8',errors='ignore').rstrip() + '…'
|
||||||
if len(title.encode()) > 300: raise Failure('Mail subject exceeds 300 UTF-8 bytes; use --title.')
|
if len(title.encode()) > 300: raise Failure('Mail subject exceeds 300 UTF-8 bytes; use --title.')
|
||||||
notes = '\n'.join(key+': '+clean(message.get(key)) for key in ('From','Date','Message-ID') if message.get(key))
|
notes = '\n'.join(key+': '+clean(message.get(key)) for key in ('From','Date','Message-ID') if message.get(key))
|
||||||
|
wiki_body = None
|
||||||
if include_body:
|
if include_body:
|
||||||
part = message.get_body(preferencelist=('plain',))
|
content = ''
|
||||||
|
part = message.get_body(preferencelist=('plain','html'))
|
||||||
if part:
|
if part:
|
||||||
content = part.get_content()
|
try: content = part.get_content()
|
||||||
|
except (LookupError, UnicodeError, ValueError) as e: raise Failure('Mail body encoding is not supported; convert to UTF-8 first.') from e
|
||||||
if not isinstance(content,str): raise Failure('Mail body is not readable text.')
|
if not isinstance(content,str): raise Failure('Mail body is not readable text.')
|
||||||
notes += '\n\n' + content
|
if part.get_content_type() == 'text/html':
|
||||||
if len(notes.encode()) > 16384: raise Failure('Mail notes exceed 16 KiB; omit --include-body.')
|
parser = MailText();parser.feed(content);parser.close();content = ''.join(parser.parts).strip()
|
||||||
return title, notes, clean(message.get('Message-ID')) or hashlib.sha256(raw).hexdigest()
|
# Retain the original subject when its mailing-list marker was removed.
|
||||||
|
wiki_body = (('Subject: '+subject+'\n') if title != subject else '') + notes + '\n\n' + content
|
||||||
|
if '\0' in wiki_body or len(wiki_body.encode()) > 256 << 10: raise Failure('Mail Wiki body must be valid text of at most 256 KiB; nothing was uploaded.')
|
||||||
|
if len(notes.encode()) > 16384: raise Failure('Mail metadata exceeds 16 KiB.')
|
||||||
|
return title, notes, clean(message.get('Message-ID')) or hashlib.sha256(raw).hexdigest(), wiki_body
|
||||||
|
|
||||||
|
|
||||||
def tasks(client, profile, words):
|
def tasks(client, profile, words):
|
||||||
@@ -498,7 +562,9 @@ def tasks(client, profile, words):
|
|||||||
p=sub.add_parser(name)
|
p=sub.add_parser(name)
|
||||||
if name=='add':p.add_argument('title')
|
if name=='add':p.add_argument('title')
|
||||||
elif name=='update':p.add_argument('uuid',type=task_uuid);p.add_argument('--title')
|
elif name=='update':p.add_argument('uuid',type=task_uuid);p.add_argument('--title')
|
||||||
else:p.add_argument('--title');p.add_argument('--include-body',action='store_true')
|
else:
|
||||||
|
p.add_argument('--title');p.add_argument('--wiki-prefix',help='Wiki parent Path (otherwise use personal default or project Wiki subtree)')
|
||||||
|
body=p.add_mutually_exclusive_group();body.add_argument('--include-body',action='store_true',help='Save body to Wiki (default; retained for compatibility)');body.add_argument('--metadata-only',action='store_true',help='Do not upload body or create a Wiki document')
|
||||||
p.add_argument('--notes');p.add_argument('--project');p.add_argument('--assignee')
|
p.add_argument('--notes');p.add_argument('--project');p.add_argument('--assignee')
|
||||||
p.add_argument('--due');p.add_argument('--start-on');p.add_argument('--planned');p.add_argument('--review')
|
p.add_argument('--due');p.add_argument('--start-on');p.add_argument('--planned');p.add_argument('--review')
|
||||||
p.add_argument('--estimate',type=int);p.add_argument('--complexity',type=int,choices=range(1,6))
|
p.add_argument('--estimate',type=int);p.add_argument('--complexity',type=int,choices=range(1,6))
|
||||||
@@ -506,19 +572,31 @@ def tasks(client, profile, words):
|
|||||||
for name in ('done','reopen','archive','start'):
|
for name in ('done','reopen','archive','start'):
|
||||||
p=sub.add_parser(name);p.add_argument('uuid',type=task_uuid)
|
p=sub.add_parser(name);p.add_argument('uuid',type=task_uuid)
|
||||||
sub.add_parser('stop');sub.add_parser('status')
|
sub.add_parser('stop');sub.add_parser('status')
|
||||||
p=sub.add_parser('retry');p.add_argument('request_id',type=task_uuid)
|
p=sub.add_parser('retry');p.add_argument('request_id',type=task_uuid);p.add_argument('--recreate-deleted',action='store_true',help='Explicitly recreate a deleted capture with a new UUID; preserve and relink any existing Wiki page')
|
||||||
p=sub.add_parser('report');p.add_argument('--from',dest='start');p.add_argument('--to',dest='end')
|
p=sub.add_parser('report');p.add_argument('--from',dest='start');p.add_argument('--to',dest='end')
|
||||||
p=sub.add_parser('preferences');p.add_argument('--project');p.add_argument('--assignee');p.add_argument('--due-days',type=int);p.add_argument('--start-days',type=int);p.add_argument('--planned-days',type=int);p.add_argument('--review-days',type=int);p.add_argument('--estimate',type=int);p.add_argument('--complexity',type=int);p.add_argument('--digest',choices=['on','off']);p.add_argument('--at');p.add_argument('--timezone')
|
p=sub.add_parser('preferences');p.add_argument('--wiki-prefix');p.add_argument('--project');p.add_argument('--assignee');p.add_argument('--due-days',type=int);p.add_argument('--start-days',type=int);p.add_argument('--planned-days',type=int);p.add_argument('--review-days',type=int);p.add_argument('--estimate',type=int);p.add_argument('--complexity',type=int);p.add_argument('--digest',choices=['on','off']);p.add_argument('--at');p.add_argument('--timezone')
|
||||||
for child in sub.choices.values():child.add_argument('--json',action='store_true')
|
for child in sub.choices.values():child.add_argument('--json',action='store_true')
|
||||||
a=parser.parse_args(words);action=a.action
|
a=parser.parse_args(words);action=a.action
|
||||||
def emit(data): print(json.dumps(data,ensure_ascii=False,indent=2))
|
def emit(data): print(json.dumps(data,ensure_ascii=False,indent=2))
|
||||||
def capture(payload):
|
def capture(payload):
|
||||||
pending=profile.data.setdefault('task_outbox',{})
|
pending=profile.data.setdefault('task_outbox',{})
|
||||||
if len(pending)>=20 and payload['request_id'] not in pending:raise Failure('20 pending captures retained. Retry them before adding more.')
|
if len(pending)>=20 and payload['request_id'] not in pending:raise Failure('20 pending captures retained. Retry them before adding more.')
|
||||||
|
replaced=payload['request_id'] in pending and pending[payload['request_id']] != payload
|
||||||
pending[payload['request_id']]=payload;profile.save()
|
pending[payload['request_id']]=payload;profile.save()
|
||||||
|
if replaced:print('Replaced the retained draft with the current input.',file=sys.stderr)
|
||||||
try: result=client.json(TASK_API+'capture',method='POST',data=payload)
|
try: result=client.json(TASK_API+'capture',method='POST',data=payload)
|
||||||
except Failure:
|
except Failure as e:
|
||||||
print('Draft retained; retry with: pages task retry '+payload['request_id'],file=sys.stderr);raise
|
if e.status==410 and e.payload.get('error')=='deleted':
|
||||||
|
raise Failure('Draft retained. This task was deleted; normal retry will not restore it. To explicitly create a new task (preserving any existing Wiki body), use: pages task retry '+payload['request_id']+' --recreate-deleted',e.status,e.payload) from e
|
||||||
|
if e.status==409 and e.payload.get('error')=='capture_missing':
|
||||||
|
raise Failure('Draft retained. The server has a capture receipt but no task or deletion record. Server-side consistency repair is required; retry will not fix it.',e.status,e.payload) from e
|
||||||
|
if e.status==412:
|
||||||
|
raise Failure('Draft retained. This request ID conflicts with a server capture or task. An unchanged retry will not resolve it; inspect with: pages task show '+payload['request_id'],e.status,e.payload) from e
|
||||||
|
if e.status==409 and e.payload.get('error')=='note_exists':
|
||||||
|
raise Failure('Draft retained. A Wiki page already occupies the destination; it was not overwritten.',e.status,e.payload) from e
|
||||||
|
print('Draft retained; retry with: pages task retry '+payload['request_id'],file=sys.stderr)
|
||||||
|
if e.payload.get('error') == 'wiki_prefix_required': raise Failure('Set a private Wiki destination first: pages task preferences --wiki-prefix /YOUR/MAIL/PATH',e.status) from e
|
||||||
|
raise
|
||||||
del pending[payload['request_id']];profile.save();return result
|
del pending[payload['request_id']];profile.save();return result
|
||||||
if action in ('list','projects'):
|
if action in ('list','projects'):
|
||||||
query={'kind':'project' if action=='projects' else 'task','view':getattr(a,'view','all'),'limit':100,'q':getattr(a,'q',''),'before':getattr(a,'before','')}
|
query={'kind':'project' if action=='projects' else 'task','view':getattr(a,'view','all'),'limit':100,'q':getattr(a,'q',''),'before':getattr(a,'before','')}
|
||||||
@@ -532,7 +610,7 @@ def tasks(client, profile, words):
|
|||||||
if action=='show':emit(client.json(TASK_API+'items/'+a.uuid));return
|
if action=='show':emit(client.json(TASK_API+'items/'+a.uuid));return
|
||||||
if action=='preferences':
|
if action=='preferences':
|
||||||
data=client.json(TASK_API+'preferences');p=data['preferences'];changed=False
|
data=client.json(TASK_API+'preferences');p=data['preferences'];changed=False
|
||||||
for attr,key in [('project','project_uuid'),('assignee','assignee_uuid'),('due_days','due_days'),('start_days','start_days'),('planned_days','planned_days'),('review_days','review_days'),('estimate','estimate_minutes'),('complexity','complexity'),('at','digest_time'),('timezone','timezone')]:
|
for attr,key in [('wiki_prefix','wiki_prefix'),('project','project_uuid'),('assignee','assignee_uuid'),('due_days','due_days'),('start_days','start_days'),('planned_days','planned_days'),('review_days','review_days'),('estimate','estimate_minutes'),('complexity','complexity'),('at','digest_time'),('timezone','timezone')]:
|
||||||
value=getattr(a,attr)
|
value=getattr(a,attr)
|
||||||
if value is not None:p[key]=task_project(client,value) if attr=='project' else value;changed=True
|
if value is not None:p[key]=task_project(client,value) if attr=='project' else value;changed=True
|
||||||
if a.digest:p['digest_enabled']=a.digest=='on';changed=True
|
if a.digest:p['digest_enabled']=a.digest=='on';changed=True
|
||||||
@@ -540,15 +618,39 @@ def tasks(client, profile, words):
|
|||||||
if action=='retry':
|
if action=='retry':
|
||||||
payload=profile.data.get('task_outbox',{}).get(a.request_id)
|
payload=profile.data.get('task_outbox',{}).get(a.request_id)
|
||||||
if not payload:raise Failure('No retained task capture with this request ID.')
|
if not payload:raise Failure('No retained task capture with this request ID.')
|
||||||
|
if a.recreate_deleted:
|
||||||
|
pending=profile.data['task_outbox']
|
||||||
|
replacement=str(uuid.uuid5(uuid.NAMESPACE_URL,'pages:task-recreate:'+a.request_id))
|
||||||
|
payload=dict(payload,request_id=replacement,replaces_deleted=a.request_id)
|
||||||
|
if replacement in pending and pending[replacement]!=payload:
|
||||||
|
raise Failure('A different recreation draft already exists; inspect or retry it first: '+replacement)
|
||||||
|
previous=pending.copy()
|
||||||
|
pending[replacement]=payload;del pending[a.request_id]
|
||||||
|
try:profile.save()
|
||||||
|
except Exception:
|
||||||
|
profile.data['task_outbox']=previous
|
||||||
|
raise
|
||||||
|
print('Recreation draft saved. Existing Wiki content will be preserved. Retry ID: '+replacement,file=sys.stderr)
|
||||||
emit(capture(payload));return
|
emit(capture(payload));return
|
||||||
if action in ('add','from-mail'):
|
if action in ('add','from-mail'):
|
||||||
payload={'request_id':getattr(a,'request_id',None) or str(uuid.uuid4()),'title':a.title,'notes':a.notes or ''}
|
payload={'request_id':getattr(a,'request_id',None) or str(uuid.uuid4()),'title':a.title,'notes':a.notes or ''}
|
||||||
if action=='from-mail':
|
if action=='from-mail':
|
||||||
title,notes,message_id=task_mail(sys.stdin.buffer.read((2<<20)+1),a.include_body,a.title)
|
if a.metadata_only and a.wiki_prefix is not None: raise Failure('--wiki-prefix cannot be combined with --metadata-only.')
|
||||||
|
raw=sys.stdin.buffer.read((2<<20)+1)
|
||||||
|
title,notes,message_id,wiki_body=task_mail(raw,not a.metadata_only,a.title)
|
||||||
payload.update(title=a.title or title,notes=a.notes if a.notes is not None else notes,request_id=str(uuid.uuid5(uuid.NAMESPACE_URL,client.base+'\n'+profile.data.get('username','')+'\n'+message_id)))
|
payload.update(title=a.title or title,notes=a.notes if a.notes is not None else notes,request_id=str(uuid.uuid5(uuid.NAMESPACE_URL,client.base+'\n'+profile.data.get('username','')+'\n'+message_id)))
|
||||||
|
if wiki_body is not None:
|
||||||
|
payload['wiki_body']=wiki_body
|
||||||
|
payload['wiki_suffix']=task_mail_suffix(raw,payload['request_id'])
|
||||||
|
if a.wiki_prefix is not None: payload['wiki_prefix']=a.wiki_prefix
|
||||||
for attr,key in [('project','project_uuid'),('assignee','assignee_uuid'),('due','due_on'),('start_on','start_on'),('planned','planned_on'),('review','review_on'),('estimate','estimate_minutes'),('complexity','complexity')]:
|
for attr,key in [('project','project_uuid'),('assignee','assignee_uuid'),('due','due_on'),('start_on','start_on'),('planned','planned_on'),('review','review_on'),('estimate','estimate_minutes'),('complexity','complexity')]:
|
||||||
value=getattr(a,attr)
|
value=getattr(a,attr)
|
||||||
if value is not None:payload[key]=task_project(client,value) if attr=='project' else value
|
if value is not None:payload[key]=task_project(client,value) if attr=='project' else value
|
||||||
|
# A retry of the same pending mail must not drift across a month boundary
|
||||||
|
# when Date was missing. Changed input replaces the pending draft below.
|
||||||
|
old=profile.data.get('task_outbox',{}).get(payload['request_id'])
|
||||||
|
if action=='from-mail' and old and {k:v for k,v in old.items() if k!='wiki_suffix'}=={k:v for k,v in payload.items() if k!='wiki_suffix'}:
|
||||||
|
payload=old.copy()
|
||||||
emit(capture(payload));return
|
emit(capture(payload));return
|
||||||
if action=='project-add':
|
if action=='project-add':
|
||||||
emit(client.json(TASK_API+'items',method='POST',data={'uuid':str(uuid.uuid4()),'kind':'project','title':a.title,'notes':a.notes,'status':'todo','bucket':'inbox','priority':1}));return
|
emit(client.json(TASK_API+'items',method='POST',data={'uuid':str(uuid.uuid4()),'kind':'project','title':a.title,'notes':a.notes,'status':'todo','bucket':'inbox','priority':1}));return
|
||||||
@@ -671,7 +773,7 @@ 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':
|
||||||
editing = Client(client.base, client.token, language(args.lang)) if args.lang else client
|
editing = Client(client.base, client.token, language(args.lang), insecure=client.insecure) if args.lang else client
|
||||||
editor(editing, addr, args.format)
|
editor(editing, addr, args.format)
|
||||||
elif cmd == 'put':
|
elif cmd == 'put':
|
||||||
state = client.snapshot(addr)
|
state = client.snapshot(addr)
|
||||||
@@ -743,11 +845,13 @@ def main(argv=None):
|
|||||||
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')
|
||||||
|
parser.add_argument('-k', '--insecure', action='store_true', help='Skip TLS certificate and hostname verification for this invocation only (unsafe; place before COMMAND)')
|
||||||
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)
|
||||||
if args.command == 'configure':
|
if args.command == 'configure':
|
||||||
if args.profile or args.lang: parser.error('Use pages configure set --profile NAME --lang TAG.')
|
if args.profile or args.lang: parser.error('Use pages configure set --profile NAME --lang TAG.')
|
||||||
|
if args.insecure: parser.error('--insecure is invocation-only; configure does not connect or save a TLS bypass.')
|
||||||
configure(args.args); return
|
configure(args.args); return
|
||||||
if args.command == 'help':
|
if args.command == 'help':
|
||||||
parser.print_help(); return
|
parser.print_help(); return
|
||||||
@@ -755,6 +859,7 @@ def main(argv=None):
|
|||||||
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('--no-browser', action='store_true', help='Print the browser login URL without opening it (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_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.no_browser and not login_args.oidc: login.error('--no-browser requires --oidc')
|
||||||
elif '--help' in args.args:
|
elif '--help' in args.args:
|
||||||
@@ -769,15 +874,17 @@ def main(argv=None):
|
|||||||
lang = language(args.lang or spec.get('lang', 'auto'))
|
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.insecure:
|
||||||
|
print('WARNING: --insecure disables TLS certificate and hostname verification for this invocation. Credentials and data can be intercepted; this option is not saved.', file=sys.stderr)
|
||||||
if args.command == 'login':
|
if args.command == 'login':
|
||||||
if not login_args.oidc and not spec.get('username'): raise Failure('Set your account with pages configure --username NAME, or use pages login --oidc.')
|
if not login_args.oidc and not spec.get('username'): raise Failure('Set your account with pages configure --username NAME, or use pages login --oidc.')
|
||||||
if profile.data.get('token'): raise Failure('Log out this profile before replacing its session.')
|
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)
|
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', ''))
|
expires, username = client.login_oidc(login_args.no_browser, spec.get('username', ''), remember=login_args.remember)
|
||||||
else:
|
else:
|
||||||
username = spec['username']
|
username = spec['username']
|
||||||
expires = client.login(username, getpass.getpass('Password: '))
|
expires = client.login(username, getpass.getpass('Password: '), remember=login_args.remember)
|
||||||
same_identity = profile.data.get('origin') == client.base and profile.data.get('username') == username
|
same_identity = profile.data.get('origin') == client.base and profile.data.get('username') == username
|
||||||
pending = profile.data.get('task_outbox', {})
|
pending = profile.data.get('task_outbox', {})
|
||||||
if pending and not same_identity:
|
if pending and not same_identity:
|
||||||
@@ -801,7 +908,7 @@ def main(argv=None):
|
|||||||
if args.command != 'logout' and (profile.data.get('origin') != spec['origin'] or profile.data.get('configured_username', profile.data.get('username')) != spec.get('username', '')):
|
if args.command != 'logout' and (profile.data.get('origin') != spec['origin'] or profile.data.get('configured_username', profile.data.get('username')) != spec.get('username', '')):
|
||||||
raise Failure('Session and configured identity differ. Log out before reconnecting.')
|
raise Failure('Session and configured identity differ. Log out before reconnecting.')
|
||||||
if args.command not in ('logout', 'status') and profile.data.get('expires', 0) <= time.time(): raise Failure('Session expired; log out and log in again.')
|
if args.command not in ('logout', 'status') and profile.data.get('expires', 0) <= time.time(): raise Failure('Session expired; log out and log in again.')
|
||||||
client = Client(profile.data['origin'], profile.data['token'], lang)
|
client = Client(profile.data['origin'], profile.data['token'], lang, insecure=args.insecure)
|
||||||
if args.command == 'shell': shell(client, profile)
|
if args.command == 'shell': shell(client, profile)
|
||||||
else: execute(client, profile, [args.command] + args.args)
|
else: execute(client, profile, [args.command] + args.args)
|
||||||
|
|
||||||
|
|||||||
+228
-3
@@ -9,15 +9,240 @@ import unittest
|
|||||||
m=runpy.run_path(str(Path(__file__).with_name('pages')))
|
m=runpy.run_path(str(Path(__file__).with_name('pages')))
|
||||||
|
|
||||||
class ProductivityTests(unittest.TestCase):
|
class ProductivityTests(unittest.TestCase):
|
||||||
|
def test_deleted_capture_message_retains_draft_without_retry_loop(self):
|
||||||
|
ident='b5550cab-22d4-54eb-b06d-3b432d3f5101'
|
||||||
|
original={'request_id':ident,'title':'Private title','notes':'Private notes'}
|
||||||
|
for status,code,message in [(410,'deleted','--recreate-deleted'),(409,'capture_missing','consistency repair'),(412,'conflict','unchanged retry'),(409,'note_exists','not overwritten')]:
|
||||||
|
profile=SimpleNamespace(data={'task_outbox':{ident:original.copy()}},save=lambda:None)
|
||||||
|
calls=[]
|
||||||
|
def send(*args,**kw):
|
||||||
|
calls.append(kw)
|
||||||
|
raise m['Failure']('old generic message',status,{'error':code})
|
||||||
|
output=io.StringIO()
|
||||||
|
with contextlib.redirect_stderr(output),self.assertRaises(m['Failure']) as error:
|
||||||
|
m['tasks'](SimpleNamespace(json=send),profile,['retry',ident])
|
||||||
|
self.assertIn(message,str(error.exception))
|
||||||
|
self.assertNotIn('Private',str(error.exception)+output.getvalue())
|
||||||
|
self.assertNotIn('retry with:',output.getvalue())
|
||||||
|
self.assertEqual(profile.data['task_outbox'][ident],original)
|
||||||
|
self.assertEqual(len(calls),1)
|
||||||
|
|
||||||
|
def test_recreate_deleted_persists_successor_and_retries_same_id(self):
|
||||||
|
import uuid
|
||||||
|
ident='b5550cab-22d4-54eb-b06d-3b432d3f5101'
|
||||||
|
replacement=str(uuid.uuid5(uuid.NAMESPACE_URL,'pages:task-recreate:'+ident))
|
||||||
|
payload={'request_id':ident,'title':'Private title','wiki_body':'Private body','wiki_suffix':'2030/01/'+ident}
|
||||||
|
saved,calls=[],[]
|
||||||
|
profile=SimpleNamespace(data={'task_outbox':{ident:payload.copy()}})
|
||||||
|
profile.save=lambda:saved.append(json.loads(json.dumps(profile.data)))
|
||||||
|
def send(route,**kw):
|
||||||
|
calls.append(kw['data'].copy())
|
||||||
|
self.assertEqual(saved[-1]['task_outbox'][replacement],kw['data'])
|
||||||
|
self.assertNotIn(ident,saved[-1]['task_outbox'])
|
||||||
|
if len(calls)==1:raise m['Failure']('Connection lost')
|
||||||
|
return {'item':{'uuid':replacement}}
|
||||||
|
output,error=io.StringIO(),io.StringIO()
|
||||||
|
with contextlib.redirect_stdout(output),contextlib.redirect_stderr(error):
|
||||||
|
with self.assertRaises(m['Failure']):m['tasks'](SimpleNamespace(json=send),profile,['retry',ident,'--recreate-deleted'])
|
||||||
|
self.assertEqual(len(profile.data['task_outbox']),1)
|
||||||
|
m['tasks'](SimpleNamespace(json=send),profile,['retry',replacement])
|
||||||
|
self.assertEqual(calls[0],calls[1])
|
||||||
|
self.assertEqual(calls[0]['request_id'],replacement)
|
||||||
|
self.assertEqual(calls[0]['replaces_deleted'],ident)
|
||||||
|
self.assertEqual(calls[0]['wiki_suffix'],payload['wiki_suffix'])
|
||||||
|
self.assertEqual(calls[0]['wiki_body'],payload['wiki_body'])
|
||||||
|
self.assertEqual(profile.data['task_outbox'],{})
|
||||||
|
self.assertIn(replacement,error.getvalue())
|
||||||
|
self.assertNotIn('Private',error.getvalue())
|
||||||
|
|
||||||
|
def test_recreate_deleted_save_failure_keeps_original_and_sends_nothing(self):
|
||||||
|
ident='b5550cab-22d4-54eb-b06d-3b432d3f5101'
|
||||||
|
payload={'request_id':ident,'title':'Draft'}
|
||||||
|
def fail():raise m['Failure']('disk full')
|
||||||
|
profile=SimpleNamespace(data={'task_outbox':{ident:payload.copy()}},save=fail)
|
||||||
|
calls=[]
|
||||||
|
with self.assertRaises(m['Failure']):m['tasks'](SimpleNamespace(json=lambda *a,**kw:calls.append(kw)),profile,['retry',ident,'--recreate-deleted'])
|
||||||
|
self.assertEqual(calls,[])
|
||||||
|
self.assertEqual(profile.data['task_outbox'],{ident:payload})
|
||||||
|
|
||||||
|
def test_recreate_deleted_never_clobbers_different_successor_draft(self):
|
||||||
|
import uuid
|
||||||
|
ident='b5550cab-22d4-54eb-b06d-3b432d3f5101'
|
||||||
|
replacement=str(uuid.uuid5(uuid.NAMESPACE_URL,'pages:task-recreate:'+ident))
|
||||||
|
pending={ident:{'request_id':ident,'title':'Original'},replacement:{'request_id':replacement,'title':'Different'}}
|
||||||
|
before=json.loads(json.dumps(pending))
|
||||||
|
calls=[]
|
||||||
|
profile=SimpleNamespace(data={'task_outbox':pending},save=lambda:calls.append('save'))
|
||||||
|
with self.assertRaises(m['Failure']):m['tasks'](SimpleNamespace(json=lambda *a,**kw:calls.append('send')),profile,['retry',ident,'--recreate-deleted'])
|
||||||
|
self.assertEqual(calls,[])
|
||||||
|
self.assertEqual(pending,before)
|
||||||
|
|
||||||
|
def test_mail_path_priority_and_dates(self):
|
||||||
|
import datetime,hashlib
|
||||||
|
ident='06cb3a24-61f8-4a9f-a0bf-89eea9632f25'
|
||||||
|
suffix=m['task_mail_suffix'];now=datetime.datetime(2030,2,1,tzinfo=datetime.timezone.utc)
|
||||||
|
for marker in ('[hogehoge 00123]','Re: [hogehoge:123]','Fwd: [hogehoge#123]'):
|
||||||
|
raw=('Subject: '+marker+' Title\r\n\r\nbody').encode()
|
||||||
|
self.assertEqual(suffix(raw,ident,now),'hogehoge/123')
|
||||||
|
raw=b'Subject: Plain\r\nDate: Sat, 31 Jan 2026 23:30:00 -0800\r\nMessage-ID: <id@example.invalid>\r\n\r\nbody'
|
||||||
|
self.assertEqual(suffix(raw,ident,now),'2026/01/'+ident)
|
||||||
|
noid=raw.replace(b'Message-ID: <id@example.invalid>\r\n',b'')
|
||||||
|
self.assertEqual(suffix(noid,ident,now),'2026/01/'+hashlib.sha256(noid).hexdigest())
|
||||||
|
for date in (b'',b'Date: broken\r\n'):
|
||||||
|
raw=b'Subject: [../unsafe 123] Title\r\n'+date+b'\r\nbody'
|
||||||
|
self.assertEqual(suffix(raw,ident,now),'2030/02/'+hashlib.sha256(raw).hexdigest())
|
||||||
|
|
||||||
|
def test_pending_mail_keeps_month_but_replaces_changed_options(self):
|
||||||
|
from unittest.mock import patch
|
||||||
|
raw=b'Subject: Test\r\nMessage-ID: <same@example.invalid>\r\n\r\nbody'
|
||||||
|
calls=[]
|
||||||
|
def send(route,**kw):
|
||||||
|
calls.append(kw['data'].copy())
|
||||||
|
raise m['Failure']('offline')
|
||||||
|
client=SimpleNamespace(base='https://example.invalid',json=send)
|
||||||
|
profile=SimpleNamespace(data={'username':'test'},save=lambda:None)
|
||||||
|
for month in ('2030/01','2030/02'):
|
||||||
|
with patch.dict(m['tasks'].__globals__,task_mail_suffix=lambda raw,ident:month+'/'+ident),patch('sys.stdin',SimpleNamespace(buffer=io.BytesIO(raw))),contextlib.redirect_stderr(io.StringIO()),self.assertRaises(m['Failure']):
|
||||||
|
m['tasks'](client,profile,['from-mail'])
|
||||||
|
self.assertEqual(calls[0],calls[1])
|
||||||
|
with patch('sys.stdin',SimpleNamespace(buffer=io.BytesIO(raw))),contextlib.redirect_stderr(io.StringIO()),self.assertRaises(m['Failure']):
|
||||||
|
m['tasks'](client,profile,['from-mail','--wiki-prefix','/changed'])
|
||||||
|
self.assertEqual(len(calls),3)
|
||||||
|
self.assertEqual(calls[2]['request_id'],calls[0]['request_id'])
|
||||||
|
self.assertEqual(calls[2]['wiki_prefix'],'/changed')
|
||||||
|
self.assertEqual(next(iter(profile.data['task_outbox'].values())),calls[2])
|
||||||
|
|
||||||
|
def test_changed_capture_is_saved_before_send_and_retained_on_conflict(self):
|
||||||
|
ident='b5550cab-22d4-54eb-b06d-3b432d3f5101'
|
||||||
|
saved,calls=[],[]
|
||||||
|
old={'request_id':ident,'title':'Old draft','notes':'Old private notes'}
|
||||||
|
profile=SimpleNamespace(data={'task_outbox':{ident:old}})
|
||||||
|
profile.save=lambda:saved.append(json.loads(json.dumps(profile.data)))
|
||||||
|
def send(route,**kw):
|
||||||
|
payload=kw['data'].copy();calls.append(payload)
|
||||||
|
self.assertEqual(saved[-1]['task_outbox'][ident],payload)
|
||||||
|
if len(calls)==1:raise m['Failure']('conflict',412,{'error':'conflict'})
|
||||||
|
return {'item':{'uuid':ident}}
|
||||||
|
client=SimpleNamespace(json=send)
|
||||||
|
out,err=io.StringIO(),io.StringIO()
|
||||||
|
with contextlib.redirect_stdout(out),contextlib.redirect_stderr(err):
|
||||||
|
with self.assertRaises(m['Failure']) as failure:
|
||||||
|
m['tasks'](client,profile,['add','New draft','--request-id',ident,'--notes','New private notes'])
|
||||||
|
self.assertEqual(failure.exception.status,412)
|
||||||
|
self.assertEqual(profile.data['task_outbox'][ident],calls[0])
|
||||||
|
self.assertEqual(len(calls),1) # No automatic server overwrite/retry.
|
||||||
|
m['tasks'](client,profile,['retry',ident])
|
||||||
|
self.assertEqual(calls[0],calls[1])
|
||||||
|
self.assertEqual(calls[0]['title'],'New draft')
|
||||||
|
self.assertEqual(profile.data['task_outbox'],{})
|
||||||
|
self.assertIn('Replaced the retained draft',err.getvalue())
|
||||||
|
self.assertNotIn('private notes',err.getvalue())
|
||||||
|
self.assertEqual(json.loads(out.getvalue())['item']['uuid'],ident)
|
||||||
|
|
||||||
|
def test_replacing_draft_does_not_send_when_local_save_fails(self):
|
||||||
|
ident='b5550cab-22d4-54eb-b06d-3b432d3f5101'
|
||||||
|
def fail_save():raise m['Failure']('local write failed')
|
||||||
|
profile=SimpleNamespace(data={'task_outbox':{ident:{'request_id':ident,'title':'Old','notes':''}}},save=fail_save)
|
||||||
|
calls=[]
|
||||||
|
client=SimpleNamespace(json=lambda *a,**kw:calls.append(kw))
|
||||||
|
with self.assertRaises(m['Failure']):m['tasks'](client,profile,['add','New','--request-id',ident])
|
||||||
|
self.assertEqual(calls,[])
|
||||||
|
|
||||||
|
def test_full_outbox_allows_replacement_but_not_new_id(self):
|
||||||
|
import uuid
|
||||||
|
pending={str(uuid.uuid4()):{'title':'Old'} for _ in range(20)}
|
||||||
|
ident=next(iter(pending))
|
||||||
|
profile=SimpleNamespace(data={'task_outbox':pending},save=lambda:None)
|
||||||
|
calls=[]
|
||||||
|
def send(route,**kw):
|
||||||
|
calls.append(kw['data'].copy())
|
||||||
|
raise m['Failure']('offline')
|
||||||
|
client=SimpleNamespace(json=send)
|
||||||
|
with contextlib.redirect_stderr(io.StringIO()),self.assertRaises(m['Failure']):
|
||||||
|
m['tasks'](client,profile,['add','Replacement','--request-id',ident])
|
||||||
|
self.assertEqual(len(calls),1)
|
||||||
|
self.assertEqual(pending[ident]['title'],'Replacement')
|
||||||
|
with self.assertRaises(m['Failure']):m['tasks'](client,profile,['add','Another'])
|
||||||
|
self.assertEqual(len(calls),1)
|
||||||
|
self.assertEqual(len(pending),20)
|
||||||
|
|
||||||
|
def test_reimported_mail_replaces_body_and_removes_obsolete_options(self):
|
||||||
|
from unittest.mock import patch
|
||||||
|
raw=b'Subject: Old\r\nMessage-ID: <same@example.invalid>\r\n\r\nOLD BODY'
|
||||||
|
calls=[]
|
||||||
|
def send(route,**kw):
|
||||||
|
calls.append(kw['data'].copy())
|
||||||
|
raise m['Failure']('offline')
|
||||||
|
client=SimpleNamespace(base='https://example.invalid',json=send)
|
||||||
|
profile=SimpleNamespace(data={'username':'test'},save=lambda:None)
|
||||||
|
changed=raw.replace(b'Subject: Old',b'Subject: New').replace(b'OLD BODY',b'NEW BODY')
|
||||||
|
for mail,args in [(raw,['--wiki-prefix','/old']),(changed,['--wiki-prefix','/new']),(changed,['--metadata-only'])]:
|
||||||
|
with patch('sys.stdin',SimpleNamespace(buffer=io.BytesIO(mail))),contextlib.redirect_stderr(io.StringIO()),self.assertRaises(m['Failure']):
|
||||||
|
m['tasks'](client,profile,['from-mail',*args])
|
||||||
|
self.assertEqual(len({c['request_id'] for c in calls}),1)
|
||||||
|
self.assertEqual(calls[1]['title'],'New')
|
||||||
|
self.assertIn('NEW BODY',calls[1]['wiki_body'])
|
||||||
|
self.assertNotIn('OLD BODY',calls[1]['wiki_body'])
|
||||||
|
for key in ('wiki_body','wiki_prefix','wiki_suffix'):self.assertNotIn(key,calls[2])
|
||||||
|
self.assertEqual(next(iter(profile.data['task_outbox'].values())),calls[2])
|
||||||
|
|
||||||
def test_mail_privacy_and_long_subject_override(self):
|
def test_mail_privacy_and_long_subject_override(self):
|
||||||
raw=b'Subject: Test\r\nFrom: Person <person@example.invalid>\r\nMessage-ID: <id@example.invalid>\r\nContent-Type: text/plain; charset=utf-8\r\n\r\nPRIVATE BODY'
|
raw=b'Subject: Test\r\nFrom: Person <person@example.invalid>\r\nMessage-ID: <id@example.invalid>\r\nContent-Type: text/plain; charset=utf-8\r\n\r\nPRIVATE BODY'
|
||||||
title,notes,ident=m['task_mail'](raw)
|
title,notes,ident,body=m['task_mail'](raw)
|
||||||
self.assertEqual(title,'Test');self.assertNotIn('PRIVATE BODY',notes);self.assertIn('Message-ID:',notes)
|
self.assertEqual(title,'Test');self.assertNotIn('PRIVATE BODY',notes);self.assertIn('Message-ID:',notes)
|
||||||
self.assertIn('PRIVATE BODY',m['task_mail'](raw,True)[1])
|
self.assertIn('PRIVATE BODY',body)
|
||||||
|
self.assertIsNone(m['task_mail'](raw,False)[3])
|
||||||
raw=raw.replace(b'Subject: Test',b'Subject: '+b'a'*301)
|
raw=raw.replace(b'Subject: Test',b'Subject: '+b'a'*301)
|
||||||
with self.assertRaises(m['Failure']):m['task_mail'](raw)
|
self.assertLessEqual(len(m['task_mail'](raw)[0].encode()),300)
|
||||||
|
with self.assertRaises(m['Failure']):m['task_mail'](raw,True,'x'*301)
|
||||||
self.assertEqual(m['task_mail'](raw,False,'Override')[0],'Override')
|
self.assertEqual(m['task_mail'](raw,False,'Override')[0],'Override')
|
||||||
|
|
||||||
|
def test_japanese_subject_and_mailing_list_markers(self):
|
||||||
|
from email.message import EmailMessage
|
||||||
|
from email.header import Header
|
||||||
|
for encoding in ('utf-8','iso-2022-jp'):
|
||||||
|
subject='Re: [hogehoge 00123] [team:456] 日本語の依頼 [重要]'
|
||||||
|
raw=('Subject: '+Header(subject,encoding).encode()+'\r\nMessage-ID: <same@example.invalid>\r\n\r\nbody').encode('ascii')
|
||||||
|
title,notes,ident,body=m['task_mail'](raw)
|
||||||
|
self.assertEqual(title,'Re: 日本語の依頼 [重要]')
|
||||||
|
self.assertEqual(ident,'<same@example.invalid>');self.assertIn('Subject: '+subject,body)
|
||||||
|
for subject in ('[重要] 日本語','報告 [list 123]','[release 1.2] 更新'):
|
||||||
|
self.assertEqual(m['mail_subject'](subject),subject)
|
||||||
|
msg=EmailMessage();msg['Subject']='[list 123] '+('日本語'*100);msg.set_content('Body')
|
||||||
|
title,_,_,body=m['task_mail'](msg.as_bytes())
|
||||||
|
self.assertLessEqual(len(title.encode()),300);self.assertTrue(title.endswith('…'))
|
||||||
|
self.assertIn('日本語'*100,body)
|
||||||
|
self.assertEqual(m['task_mail'](msg.as_bytes(),True,'[list 123] 手動指定')[0],'[list 123] 手動指定')
|
||||||
|
|
||||||
|
def test_html_mail_and_limits(self):
|
||||||
|
raw=b'Subject: HTML\r\nContent-Type: text/html; charset=utf-8\r\n\r\n<head><style>secret</style></head><p>Hello</p><script>evil()</script><img src="https://example.invalid/image"><p>World & friends</p>'
|
||||||
|
body=m['task_mail'](raw)[3]
|
||||||
|
self.assertIn('Hello\n',body);self.assertIn('World & friends',body)
|
||||||
|
for value in ('secret','evil','https://'):self.assertNotIn(value,body)
|
||||||
|
for body in (b'a'*(256<<10),b'bad\0text'):
|
||||||
|
with self.assertRaises(m['Failure']):m['task_mail'](b'Subject: Test\r\n\r\n'+body)
|
||||||
|
|
||||||
|
def test_mail_payload_wiki_and_metadata_only(self):
|
||||||
|
from unittest.mock import patch
|
||||||
|
raw=b'Subject: Test\r\nMessage-ID: <same@example.invalid>\r\n\r\nPRIVATE BODY'
|
||||||
|
calls=[]
|
||||||
|
client=SimpleNamespace(base='https://example.invalid',json=lambda route,**kw:calls.append(kw['data'].copy()) or {'item':{'uuid':kw['data']['request_id']}})
|
||||||
|
profile=SimpleNamespace(data={'username':'test'},save=lambda:None)
|
||||||
|
for args in (['--wiki-prefix','/private/mail'],['--metadata-only']):
|
||||||
|
with patch('sys.stdin',SimpleNamespace(buffer=io.BytesIO(raw))),contextlib.redirect_stdout(io.StringIO()):
|
||||||
|
m['tasks'](client,profile,['from-mail',*args])
|
||||||
|
self.assertIn('PRIVATE BODY',calls[0]['wiki_body']);self.assertNotIn('PRIVATE BODY',calls[0]['notes'])
|
||||||
|
self.assertEqual(calls[0]['wiki_prefix'],'/private/mail')
|
||||||
|
self.assertNotIn('wiki_body',calls[1]);self.assertEqual(calls[0]['request_id'],calls[1]['request_id'])
|
||||||
|
|
||||||
|
def test_multipart_prefers_plain_and_skips_attachment(self):
|
||||||
|
from email.message import EmailMessage
|
||||||
|
msg=EmailMessage();msg['Subject']='Mixed';msg.set_content('Plain body')
|
||||||
|
msg.add_alternative('<p>HTML alternate</p>',subtype='html')
|
||||||
|
msg.add_attachment(b'ATTACHMENT',maintype='application',subtype='octet-stream',filename='secret.bin')
|
||||||
|
body=m['task_mail'](msg.as_bytes())[3]
|
||||||
|
self.assertIn('Plain body',body);self.assertNotIn('alternate',body);self.assertNotIn('ATTACHMENT',body)
|
||||||
|
|
||||||
def test_capture_retains_request_until_explicit_retry(self):
|
def test_capture_retains_request_until_explicit_retry(self):
|
||||||
calls=[]
|
calls=[]
|
||||||
def send(route,**kwargs):
|
def send(route,**kwargs):
|
||||||
|
|||||||
@@ -0,0 +1,55 @@
|
|||||||
|
import contextlib
|
||||||
|
import io
|
||||||
|
import os
|
||||||
|
from pathlib import Path
|
||||||
|
import runpy
|
||||||
|
import time
|
||||||
|
import tempfile
|
||||||
|
import unittest
|
||||||
|
from unittest.mock import patch
|
||||||
|
|
||||||
|
m = runpy.run_path(str(Path(__file__).with_name('pages')))
|
||||||
|
|
||||||
|
|
||||||
|
class RememberTests(unittest.TestCase):
|
||||||
|
def test_expired_login_retains_same_account_drafts_and_path(self):
|
||||||
|
with tempfile.TemporaryDirectory() as root, patch.dict(os.environ, {'XDG_CONFIG_HOME': root}), contextlib.redirect_stdout(io.StringIO()):
|
||||||
|
with m['Configuration']().locked() as config:
|
||||||
|
config.data = {'version': 1, 'default_profile': 'default', 'profiles': {'default': {'origin': 'https://wiki.example', 'username': 'anya', 'lang': 'auto'}}}
|
||||||
|
config.save()
|
||||||
|
with m['Profile']('default').locked() as profile:
|
||||||
|
profile.data = {'origin': 'https://wiki.example', 'username': 'anya', 'token': 'expired', 'expires': 1,
|
||||||
|
'cwd': '/projects/demo', 'task_outbox': {'request': {'title': 'synthetic draft'}}}
|
||||||
|
profile.save()
|
||||||
|
def login(client, username, password, *, remember=False):
|
||||||
|
self.assertTrue(remember)
|
||||||
|
client.token = 'pw_api_'+'x'*43
|
||||||
|
return time.time()+2592000
|
||||||
|
with patch.object(m['Client'], 'login', login), patch.object(m['getpass'], 'getpass', return_value='synthetic'):
|
||||||
|
m['main'](['login', '--remember'])
|
||||||
|
with m['Profile']('default').locked() as profile:
|
||||||
|
self.assertEqual(profile.data['cwd'], '/projects/demo')
|
||||||
|
self.assertEqual(profile.data['task_outbox']['request']['title'], 'synthetic draft')
|
||||||
|
self.assertTrue(profile.data['token'].startswith('pw_api_'))
|
||||||
|
|
||||||
|
def test_password_choice_is_explicit_and_bound_before_totp(self):
|
||||||
|
for remember in (False, True):
|
||||||
|
client = m['Client']('https://wiki.example')
|
||||||
|
challenge = m['Failure']('MFA', 401, {'mfa_required': True, 'challenge_token': 'challenge'})
|
||||||
|
result = {'access_token': 'pw_api_' + 'x'*43, 'token_type': 'Bearer', 'expires_in': 2592000}
|
||||||
|
with patch.object(client, 'json', side_effect=[challenge, result]) as api:
|
||||||
|
expiry = client.login('anya', 'synthetic-password', lambda _: '123456', remember=remember)
|
||||||
|
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.assertAlmostEqual(expiry - time.time(), 2592000, delta=2)
|
||||||
|
|
||||||
|
def test_oidc_choice_is_bound_at_start(self):
|
||||||
|
for remember in (False, True):
|
||||||
|
client = m['Client']('https://wiki.example')
|
||||||
|
start = {'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_'+'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()):
|
||||||
|
client.login_oidc(True, 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.assertNotIn('remember', api.call_args_list[1].kwargs['form'])
|
||||||
@@ -5,6 +5,7 @@ import json
|
|||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
import runpy
|
import runpy
|
||||||
import sys
|
import sys
|
||||||
|
import uuid
|
||||||
|
|
||||||
def run():
|
def run():
|
||||||
m=runpy.run_path(str(Path(__file__).with_name('pages')))
|
m=runpy.run_path(str(Path(__file__).with_name('pages')))
|
||||||
@@ -36,5 +37,36 @@ def run():
|
|||||||
output=io.StringIO()
|
output=io.StringIO()
|
||||||
with contextlib.redirect_stdout(output):m['contacts'](client,['export',contact['uuid']])
|
with contextlib.redirect_stdout(output):m['contacts'](client,['export',contact['uuid']])
|
||||||
assert 'UID:urn:test:cli' in output.getvalue()
|
assert 'UID:urn:test:cli' in output.getvalue()
|
||||||
|
# A rejected capture can be corrected under the same request ID.
|
||||||
|
# A committed capture is still protected by the server receipt.
|
||||||
|
request_id=str(uuid.uuid4())
|
||||||
|
with contextlib.redirect_stderr(io.StringIO()):
|
||||||
|
try:task('add','Rejected draft','--request-id',request_id,'--estimate','-1')
|
||||||
|
except m['Failure'] as error:assert error.status==422
|
||||||
|
else:raise AssertionError('Invalid estimate accepted')
|
||||||
|
assert profile.data['task_outbox'][request_id]['estimate_minutes']==-1
|
||||||
|
corrected=task('add','Corrected draft','--request-id',request_id,'--estimate','15')['item']
|
||||||
|
assert corrected['uuid']==request_id and corrected['title']=='Corrected draft'
|
||||||
|
assert request_id not in profile.data['task_outbox']
|
||||||
|
try:task('add','Changed after commit','--request-id',request_id,'--estimate','30')
|
||||||
|
except m['Failure'] as error:assert error.status==412
|
||||||
|
else:raise AssertionError('Committed capture silently overwritten')
|
||||||
|
assert profile.data['task_outbox'][request_id]['title']=='Changed after commit'
|
||||||
|
stored=task('show',request_id)['item']
|
||||||
|
assert stored['title']=='Corrected draft' and stored['estimate_minutes']==15
|
||||||
|
# Recreate explicitly after deletion; never revive the old DAV identity.
|
||||||
|
client.request(m['TASK_API']+'items/'+request_id,method='DELETE',etag='"'+str(stored['version'])+'"')
|
||||||
|
with contextlib.redirect_stderr(io.StringIO()):
|
||||||
|
try:task('retry',request_id)
|
||||||
|
except m['Failure'] as error:
|
||||||
|
assert error.status==410 and '--recreate-deleted' in str(error)
|
||||||
|
else:raise AssertionError('Deleted task implicitly recreated')
|
||||||
|
recreated=task('retry',request_id,'--recreate-deleted')['item']
|
||||||
|
replacement=str(uuid.uuid5(uuid.NAMESPACE_URL,'pages:task-recreate:'+request_id))
|
||||||
|
assert recreated['uuid']==replacement and recreated['title']=='Changed after commit'
|
||||||
|
assert recreated['estimate_minutes']==30 and not profile.data.get('task_outbox')
|
||||||
|
try:task('show',request_id)
|
||||||
|
except m['Failure'] as error:assert error.status==404
|
||||||
|
else:raise AssertionError('Deleted UUID resurrected')
|
||||||
|
|
||||||
if __name__=='__main__':run()
|
if __name__=='__main__':run()
|
||||||
+153
@@ -0,0 +1,153 @@
|
|||||||
|
"""Synthetic self-signed HTTPS tests; never disable verification for real services.
|
||||||
|
|
||||||
|
Set PAGES_CLI_TEST_BINARY to run subprocess tests against the packaged executable.
|
||||||
|
"""
|
||||||
|
import contextlib
|
||||||
|
import io
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
from pathlib import Path
|
||||||
|
import runpy
|
||||||
|
import ssl
|
||||||
|
import subprocess
|
||||||
|
import sys
|
||||||
|
import tempfile
|
||||||
|
import threading
|
||||||
|
import unittest
|
||||||
|
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||||
|
from unittest.mock import patch
|
||||||
|
|
||||||
|
m=runpy.run_path(str(Path(__file__).with_name('pages')))
|
||||||
|
Client,Failure=m['Client'],m['Failure']
|
||||||
|
|
||||||
|
|
||||||
|
class TLSTests(unittest.TestCase):
|
||||||
|
@classmethod
|
||||||
|
def setUpClass(cls):
|
||||||
|
cls.temp=tempfile.TemporaryDirectory()
|
||||||
|
cls.addClassCleanup(cls.temp.cleanup)
|
||||||
|
cls.cert=Path(cls.temp.name)/'cert.pem'
|
||||||
|
cls.key=Path(cls.temp.name)/'key.pem'
|
||||||
|
subprocess.run(['openssl','req','-x509','-newkey','rsa:2048','-nodes',
|
||||||
|
'-keyout',str(cls.key),'-out',str(cls.cert),'-days','1',
|
||||||
|
'-subj','/CN=localhost','-addext','subjectAltName=DNS:localhost'],
|
||||||
|
check=True,stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL,timeout=30)
|
||||||
|
|
||||||
|
def setUp(self):
|
||||||
|
self.calls=[]
|
||||||
|
calls=self.calls
|
||||||
|
self.token='synthetic_tls_session_'+'x'*40
|
||||||
|
token=self.token
|
||||||
|
class Handler(BaseHTTPRequestHandler):
|
||||||
|
def log_message(self,*args):pass
|
||||||
|
def reply(self,data):
|
||||||
|
self.send_response(200);self.send_header('Content-Type','application/json');self.end_headers()
|
||||||
|
self.wfile.write(json.dumps(data).encode())
|
||||||
|
def do_GET(self):
|
||||||
|
calls.append((self.path,self.headers.get('Authorization')))
|
||||||
|
if self.path.startswith('/redirect'):
|
||||||
|
self.send_response(302);self.send_header('Location','/destination');self.end_headers();return
|
||||||
|
self.reply({'items':[{'uuid':'synthetic-task','title':'TLS task','status':'todo'}]})
|
||||||
|
def do_POST(self):
|
||||||
|
self.rfile.read(int(self.headers.get('Content-Length',0)))
|
||||||
|
calls.append((self.path,self.headers.get('Authorization')))
|
||||||
|
if self.path=='/_/auth/login':
|
||||||
|
self.reply({'access_token':token,'token_type':'Bearer','expires_in':3600})
|
||||||
|
elif self.path=='/_/auth/cli/start':
|
||||||
|
self.reply({'device_code':'D'*43,'verification_uri':'/_/auth/cli/verify?request='+'R'*43,'user_code':'ABCD-1234','expires_in':300,'interval':5})
|
||||||
|
elif self.path=='/_/auth/cli/token':
|
||||||
|
self.reply({'access_token':token,'token_type':'Bearer','expires_in':3600,'username':'synthetic'})
|
||||||
|
elif self.path=='/_/auth/logout':self.reply({})
|
||||||
|
else:self.send_error(404)
|
||||||
|
self.server=ThreadingHTTPServer(('127.0.0.1',0),Handler)
|
||||||
|
context=ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
|
||||||
|
context.load_cert_chain(self.cert,self.key)
|
||||||
|
self.server.socket=context.wrap_socket(self.server.socket,server_side=True)
|
||||||
|
self.thread=threading.Thread(target=self.server.serve_forever,daemon=True);self.thread.start()
|
||||||
|
self.base=f'https://localhost:{self.server.server_port}'
|
||||||
|
self.environment=patch.dict(os.environ,{'NO_PROXY':'localhost,127.0.0.1','no_proxy':'localhost,127.0.0.1'})
|
||||||
|
self.environment.start()
|
||||||
|
|
||||||
|
def tearDown(self):
|
||||||
|
self.environment.stop()
|
||||||
|
self.server.shutdown();self.server.server_close();self.thread.join()
|
||||||
|
|
||||||
|
def test_default_rejects_and_bypass_does_not_change_global_policy(self):
|
||||||
|
default_context=ssl._create_default_https_context
|
||||||
|
with self.assertRaises(Failure):Client(self.base,self.token).json('/first')
|
||||||
|
self.assertEqual(self.calls,[])
|
||||||
|
self.assertIn('items',Client(self.base,self.token,insecure=True).json('/explicit'))
|
||||||
|
self.assertEqual(self.calls,[('/explicit','Bearer '+self.token)])
|
||||||
|
with self.assertRaises(Failure):Client(self.base,self.token).json('/default-again')
|
||||||
|
self.assertEqual(len(self.calls),1)
|
||||||
|
self.assertIs(ssl._create_default_https_context,default_context)
|
||||||
|
|
||||||
|
def test_hostname_verification_and_secure_trusted_certificate(self):
|
||||||
|
# Trust our synthetic CA, but its certificate covers localhost, not 127.0.0.1.
|
||||||
|
with patch.dict(os.environ,{'SSL_CERT_FILE':str(self.cert)}):
|
||||||
|
self.assertIn('items',Client(self.base).json('/trusted'))
|
||||||
|
wrong_host=self.base.replace('localhost','127.0.0.1')
|
||||||
|
with self.assertRaises(Failure):Client(wrong_host).json('/wrong-host')
|
||||||
|
self.assertIn('items',Client(wrong_host,insecure=True).json('/explicit-wrong-host'))
|
||||||
|
self.assertEqual([p for p,_ in self.calls],['/trusted','/explicit-wrong-host'])
|
||||||
|
|
||||||
|
def test_bypass_does_not_allow_redirects_or_remote_http(self):
|
||||||
|
with self.assertRaises(Failure) as caught:Client(self.base,self.token,insecure=True).json('/redirect')
|
||||||
|
self.assertEqual(caught.exception.status,302)
|
||||||
|
self.assertEqual(self.calls,[('/redirect','Bearer '+self.token)])
|
||||||
|
with self.assertRaises(Failure):Client('http://example.invalid',insecure=True)
|
||||||
|
|
||||||
|
def test_edit_language_override_preserves_tls_policy(self):
|
||||||
|
for insecure in (False,True):
|
||||||
|
client=Client(self.base,self.token,insecure=insecure)
|
||||||
|
received=[]
|
||||||
|
def editor(editing,*args):received.append(editing)
|
||||||
|
with patch.dict(m['execute'].__globals__,{'editor':editor}):
|
||||||
|
m['execute'](client,type('Profile',(),{'data':{}})(),['edit','/test','--lang','ja'])
|
||||||
|
self.assertEqual(received[0].insecure,insecure)
|
||||||
|
self.assertEqual(received[0].lang,'ja')
|
||||||
|
|
||||||
|
def test_login_commands_shell_logout_and_non_persistence(self):
|
||||||
|
binary=os.environ.get('PAGES_CLI_TEST_BINARY')
|
||||||
|
command=[str(Path(binary).resolve())] if binary else [sys.executable,str(Path(__file__).with_name('pages'))]
|
||||||
|
with tempfile.TemporaryDirectory() as config:
|
||||||
|
env={**os.environ,'XDG_CONFIG_HOME':config}
|
||||||
|
def run(*args,stdin='',ok=True):
|
||||||
|
r=subprocess.run(command+list(args),input=stdin,text=True,capture_output=True,env=env,timeout=20)
|
||||||
|
self.assertEqual(r.returncode==0,ok,(args,r.stderr))
|
||||||
|
self.assertNotIn(self.token,r.stdout+r.stderr)
|
||||||
|
return r
|
||||||
|
run('configure','--origin',self.base,'--username','synthetic')
|
||||||
|
run('login',stdin='test-password\n',ok=False)
|
||||||
|
self.assertEqual(self.calls,[])
|
||||||
|
r=run('--insecure','login',stdin='test-password\n')
|
||||||
|
self.assertIn('WARNING: --insecure',r.stderr)
|
||||||
|
self.assertEqual(r.stderr.count('WARNING:'),1)
|
||||||
|
self.assertNotIn('WARNING:',r.stdout)
|
||||||
|
run('task','list',ok=False)
|
||||||
|
r=run('-k','task','list')
|
||||||
|
self.assertIn('TLS task',r.stdout)
|
||||||
|
r=run('-k','shell',stdin='task list\nexit\n')
|
||||||
|
self.assertIn('TLS task',r.stdout)
|
||||||
|
self.assertEqual(r.stderr.count('WARNING:'),1)
|
||||||
|
for path in Path(config).rglob('*.json'):
|
||||||
|
self.assertNotIn('insecure',path.read_text())
|
||||||
|
self.assertNotIn('verify_tls',path.read_text())
|
||||||
|
run('logout',ok=False)
|
||||||
|
self.assertIn('token',json.loads((Path(config)/'pages-cli/sessions/default.json').read_text()))
|
||||||
|
run('-k','logout')
|
||||||
|
self.assertNotIn('token',json.loads((Path(config)/'pages-cli/sessions/default.json').read_text()))
|
||||||
|
run('-k','configure',ok=False)
|
||||||
|
|
||||||
|
def test_oidc_client_uses_explicit_tls_context(self):
|
||||||
|
client=Client(self.base,insecure=True)
|
||||||
|
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)
|
||||||
|
browser.assert_not_called()
|
||||||
|
self.assertEqual(username,'synthetic')
|
||||||
|
self.assertEqual(client.token,self.token)
|
||||||
|
self.assertNotIn(self.token,out.getvalue())
|
||||||
|
self.assertEqual([p for p,_ in self.calls],['/_/auth/cli/start','/_/auth/cli/token'])
|
||||||
|
|
||||||
|
|
||||||
|
if __name__=='__main__':unittest.main()
|
||||||
+20
-5
@@ -6,11 +6,13 @@ import subprocess
|
|||||||
import sys
|
import sys
|
||||||
import tempfile
|
import tempfile
|
||||||
import threading
|
import threading
|
||||||
|
import uuid
|
||||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||||
|
|
||||||
binary=str(Path(sys.argv[1]).resolve())
|
binary=str(Path(sys.argv[1]).resolve())
|
||||||
token='synthetic_session_'+('x'*40)
|
token='synthetic_session_'+('x'*40)
|
||||||
seen=[]
|
seen=[]
|
||||||
|
captures=[]
|
||||||
class Handler(BaseHTTPRequestHandler):
|
class Handler(BaseHTTPRequestHandler):
|
||||||
def log_message(self,*args):pass
|
def log_message(self,*args):pass
|
||||||
def do_POST(self):
|
def do_POST(self):
|
||||||
@@ -19,7 +21,13 @@ class Handler(BaseHTTPRequestHandler):
|
|||||||
elif self.path=='/_/auth/logout':self.reply({})
|
elif self.path=='/_/auth/logout':self.reply({})
|
||||||
elif self.path=='/_/api/v1/extension/organizer.tasks/capture':
|
elif self.path=='/_/api/v1/extension/organizer.tasks/capture':
|
||||||
if self.headers.get('Authorization')!='Bearer '+token:self.send_error(401);return
|
if self.headers.get('Authorization')!='Bearer '+token:self.send_error(401);return
|
||||||
self.reply({'item':json.loads(body)})
|
item=json.loads(body)
|
||||||
|
captures.append(item.copy())
|
||||||
|
if item.get('wiki_prefix')=='/rejected':self.reply({'error':'invalid'},422);return
|
||||||
|
if item.get('wiki_prefix')=='/deleted' and not item.get('replaces_deleted'):self.reply({'error':'deleted'},410);return
|
||||||
|
if item.get('replaces_deleted') and item['request_id']!=str(uuid.uuid5(uuid.NAMESPACE_URL,'pages:task-recreate:'+item['replaces_deleted'])):self.send_error(422);return
|
||||||
|
if item.get('wiki_body') != 'Message-ID: <smoke@example.invalid>\n\nPRIVATE BODY':self.send_error(422);return
|
||||||
|
item.pop('wiki_body');self.reply({'item':item,'page_path':'/private/mail/synthetic'})
|
||||||
else:self.send_error(404)
|
else:self.send_error(404)
|
||||||
def do_GET(self):
|
def do_GET(self):
|
||||||
if self.headers.get('Authorization')!='Bearer '+token:self.send_error(401);return
|
if self.headers.get('Authorization')!='Bearer '+token:self.send_error(401);return
|
||||||
@@ -27,8 +35,8 @@ class Handler(BaseHTTPRequestHandler):
|
|||||||
if self.path.startswith('/_/api/v1/extension/organizer.contacts/items?'):
|
if self.path.startswith('/_/api/v1/extension/organizer.contacts/items?'):
|
||||||
self.reply({'items':[{'name':'Synthetic Person','emails':['person@example.invalid'],'organization':'Test'}]})
|
self.reply({'items':[{'name':'Synthetic Person','emails':['person@example.invalid'],'organization':'Test'}]})
|
||||||
else:self.reply({'items':[{'uuid':'synthetic-task','title':'Packaged CLI task','status':'todo'}]})
|
else:self.reply({'items':[{'uuid':'synthetic-task','title':'Packaged CLI task','status':'todo'}]})
|
||||||
def reply(self,value):
|
def reply(self,value,status=200):
|
||||||
self.send_response(200);self.send_header('Content-Type','application/json');self.end_headers();self.wfile.write(json.dumps(value).encode())
|
self.send_response(status);self.send_header('Content-Type','application/json');self.end_headers();self.wfile.write(json.dumps(value).encode())
|
||||||
|
|
||||||
server=ThreadingHTTPServer(('127.0.0.1',0),Handler)
|
server=ThreadingHTTPServer(('127.0.0.1',0),Handler)
|
||||||
thread=threading.Thread(target=server.serve_forever,daemon=True);thread.start()
|
thread=threading.Thread(target=server.serve_forever,daemon=True);thread.start()
|
||||||
@@ -44,15 +52,22 @@ try:
|
|||||||
run('login',stdin='synthetic-password\n')
|
run('login',stdin='synthetic-password\n')
|
||||||
if 'Packaged CLI task' not in run('task','list'):raise AssertionError('Task missing')
|
if 'Packaged CLI task' not in run('task','list'):raise AssertionError('Task missing')
|
||||||
mail='Subject: Mail task\r\nMessage-ID: <smoke@example.invalid>\r\nContent-Type: text/plain\r\n\r\nPRIVATE BODY'
|
mail='Subject: Mail task\r\nMessage-ID: <smoke@example.invalid>\r\nContent-Type: text/plain\r\n\r\nPRIVATE BODY'
|
||||||
captured=run('task','from-mail',stdin=mail)
|
run('task','from-mail','--wiki-prefix','/rejected',stdin=mail,success=False)
|
||||||
|
captured=run('task','from-mail','--wiki-prefix','/private/mail',stdin=mail)
|
||||||
|
if len(captures)!=2 or captures[0]['request_id']!=captures[1]['request_id'] or captures[1]['wiki_prefix']!='/private/mail':raise AssertionError('Retained draft was not overwritten under the same request ID')
|
||||||
if 'Mail task' not in captured or 'PRIVATE BODY' in captured:raise AssertionError('Mail privacy')
|
if 'Mail task' not in captured or 'PRIVATE BODY' in captured:raise AssertionError('Mail privacy')
|
||||||
|
run('task','from-mail','--wiki-prefix','/deleted',stdin=mail,success=False)
|
||||||
|
deleted_id=captures[-1]['request_id']
|
||||||
|
restored=json.loads(run('task','retry',deleted_id,'--recreate-deleted'))['item']
|
||||||
|
if restored['request_id']!=str(uuid.uuid5(uuid.NAMESPACE_URL,'pages:task-recreate:'+deleted_id)) or restored['replaces_deleted']!=deleted_id:raise AssertionError('Recreation identity')
|
||||||
contact=run('contacts','query','--neomutt','--','--name')
|
contact=run('contacts','query','--neomutt','--','--name')
|
||||||
if 'person@example.invalid\tSynthetic Person\tTest' not in contact:raise AssertionError('NeoMutt query')
|
if 'person@example.invalid\tSynthetic Person\tTest' not in contact:raise AssertionError('NeoMutt query')
|
||||||
run('shell',stdin='pwd\nexit\n')
|
run('shell',stdin='pwd\nexit\n')
|
||||||
profile=Path(root)/'pages-cli/sessions/default.json'
|
profile=Path(root)/'pages-cli/sessions/default.json'
|
||||||
|
if json.loads(profile.read_text()).get('task_outbox'):raise AssertionError('Successful replacement remains pending')
|
||||||
if profile.stat().st_mode&0o077:raise AssertionError('Credential permissions')
|
if profile.stat().st_mode&0o077:raise AssertionError('Credential permissions')
|
||||||
profile.chmod(0o644);run('task','list',success=False);profile.chmod(0o600)
|
profile.chmod(0o644);run('task','list',success=False);profile.chmod(0o600)
|
||||||
run('logout')
|
run('logout')
|
||||||
if not seen:raise AssertionError('No HTTP request')
|
if not seen:raise AssertionError('No HTTP request')
|
||||||
print('Packaged CLI: configure/login/task-list/mail-capture/neomutt-query/shell/permissions/logout passed')
|
print('Packaged CLI: configure/login/task-list/mail-capture/draft-overwrite/deleted-recreation/neomutt-query/shell/permissions/logout passed')
|
||||||
finally:server.shutdown();server.server_close();thread.join()
|
finally:server.shutdown();server.server_close();thread.join()
|
||||||
Reference in new issue
Block a user