From 4a863fe63cf0ad3a8a21b7096ed0557854e1ba92 Mon Sep 17 00:00:00 2001 From: Anya Tokugawa Date: Mon, 30 Nov 2026 23:14:24 +0900 Subject: [PATCH] chore(exhibition): preserve deployment and synthetic demo tooling Separate one-time bootstrap, historical deployment examples and local validation. Document final hostname and historical status; exclude credentials and runtime data. --- deploy/kubernetes/exhibition/README.md | 35 ++ deploy/kubernetes/exhibition/app.yaml | 68 +++ deploy/kubernetes/exhibition/bootstrap.yaml | 94 ++++ deploy/kubernetes/exhibition/demo/README.md | 94 ++++ .../kubernetes/exhibition/demo/catalog.json | 81 ++++ .../exhibition/pageswiki.yaml.example | 99 ++++ deploy/kubernetes/exhibition/postgres.yaml | 145 ++++++ .../root-storage-check.yaml.example | 103 +++++ .../exhibition/storage-check.yaml.example | 90 ++++ .../exhibition-kubernetes-dns-tls.md | 431 ++++++++++++++++++ docs/operations/exhibition-noc-reply-draft.md | 32 ++ tools/exhibition-demo/.gitignore | 1 + tools/exhibition-demo/fixtures_test.go | 97 ++++ tools/exhibition-demo/generate.py | 187 ++++++++ tools/exhibition-demo/seed.py | 323 +++++++++++++ tools/exhibition-demo/test_generate.py | 127 ++++++ tools/exhibition-demo/test_seed.py | 32 ++ 17 files changed, 2039 insertions(+) create mode 100644 deploy/kubernetes/exhibition/README.md create mode 100644 deploy/kubernetes/exhibition/app.yaml create mode 100644 deploy/kubernetes/exhibition/bootstrap.yaml create mode 100644 deploy/kubernetes/exhibition/demo/README.md create mode 100644 deploy/kubernetes/exhibition/demo/catalog.json create mode 100644 deploy/kubernetes/exhibition/pageswiki.yaml.example create mode 100644 deploy/kubernetes/exhibition/postgres.yaml create mode 100644 deploy/kubernetes/exhibition/root-storage-check.yaml.example create mode 100644 deploy/kubernetes/exhibition/storage-check.yaml.example create mode 100644 docs/operations/exhibition-kubernetes-dns-tls.md create mode 100644 docs/operations/exhibition-noc-reply-draft.md create mode 100644 tools/exhibition-demo/.gitignore create mode 100644 tools/exhibition-demo/fixtures_test.go create mode 100644 tools/exhibition-demo/generate.py create mode 100644 tools/exhibition-demo/seed.py create mode 100644 tools/exhibition-demo/test_generate.py create mode 100644 tools/exhibition-demo/test_seed.py diff --git a/deploy/kubernetes/exhibition/README.md b/deploy/kubernetes/exhibition/README.md new file mode 100644 index 0000000..3d1c667 --- /dev/null +++ b/deploy/kubernetes/exhibition/README.md @@ -0,0 +1,35 @@ +# 2026年11月・じさばかん展示環境 + +展示時の構成と合成データツールを保存する。汎用本番デプロイのテンプレートではない。 +利用者から展示成功の報告あり。2026-11-30の整理では実クラスタへ接続していない。 + +## ファイルの役割 + +| ファイル | 用途・注意 | +| --- | --- | +| `postgres.yaml` | PostgreSQL、専用ディレクトリ初期化、Service、NetworkPolicy。初期化だけroot、常駐は非root | +| `bootstrap.yaml` | **新規展示DB向け、一度限り**。emptyDirのSQLiteからPostgreSQLへ初期import。GitOpsの継続同期へ入れない | +| `app.yaml` | bootstrap成功後のPages本体とService。1 replica、Recreate、固定digest | +| `storage-check.yaml.example` | 非rootで専用一時ディレクトリを使う保存先の検査 | +| `root-storage-check.yaml.example` | rootで専用一時ディレクトリを準備し、非rootで検査する別案。運営の許可が必要 | +| `pageswiki.yaml.example` | 初期のSQLite向け一般ひな形。**展示NFSには適用しない** | +| `demo/` | 架空データのカタログ、生成・投入手順 | + +`kubectl apply -f deploy/kubernetes/exhibition/` のような一括適用は禁止。 +namespace、PVC、Secret、公開Gateway/TLSは、このディレクトリだけでは準備されない。 +Secretの値、秘密鍵、kubeconfig、投入済みDBはGitへ含めない。初期化Jobの削除・再実行を更新手段にしない。 + +最後に指定された公開名は `pages.anya.jisaba.sh`、Serviceは `pageswiki:80`。 +公開TLS終端はNOC側。古いFQDNとCloudflare案は +[当時の運用記録](../../../docs/operations/exhibition-kubernetes-dns-tls.md)に経緯として残す。 +固定digest・UID・PVC subPath・Secret名・証明書期限は展示当時の値であり、再利用時に照合が必要。 + +## ローカル検証 + +```sh +PYTHONDONTWRITEBYTECODE=1 python3 -m unittest discover -s tools/exhibition-demo -v +go test ./tools/exhibition-demo +``` + +合成データだけでZIP/Markdown/CSV/iCalendar/vCardを検証する。クラスタ、DB、外部カレンダーへ接続しない。 +YAMLの構文検査だけではRBAC、admission、NFS永続性、TLS、公開経路の成立は保証しない。 diff --git a/deploy/kubernetes/exhibition/app.yaml b/deploy/kubernetes/exhibition/app.yaml new file mode 100644 index 0000000..1c00e4e --- /dev/null +++ b/deploy/kubernetes/exhibition/app.yaml @@ -0,0 +1,68 @@ +# Apply only after the one-time bootstrap Job has completed successfully. +apiVersion: apps/v1 +kind: Deployment +metadata: {name: pageswiki} +spec: + replicas: 1 + strategy: {type: Recreate} + selector: + matchLabels: {app: pageswiki} + template: + metadata: + labels: {app: pageswiki, pageswiki-db-client: 'true'} + spec: + automountServiceAccountToken: false + terminationGracePeriodSeconds: 90 + securityContext: + runAsNonRoot: true + runAsUser: 10001 + runAsGroup: 10001 + seccompProfile: {type: RuntimeDefault} + affinity: + podAffinity: + requiredDuringSchedulingIgnoredDuringExecution: + - labelSelector: + matchLabels: {app: pageswiki-postgres} + topologyKey: kubernetes.io/hostname + containers: + - name: pageswiki + image: git.anya.jp/anya/pageswiki-app@sha256:a999fe16f11ef91dbdb9904c63bb43d9ec3caef93f77cc07b1fe4a80460f67f9 + env: + - {name: PAGESWIKI_DATA_DIR, value: /data} + - {name: PAGESWIKI_DB_BACKEND, value: postgresql} + - name: PAGESWIKI_AUTH_KEY + valueFrom: {secretKeyRef: {name: pageswiki-exhibition-app, key: auth-key}} + - name: PAGESWIKI_POSTGRES_DSN + valueFrom: {secretKeyRef: {name: pageswiki-exhibition-app, key: postgres-dsn}} + ports: [{name: http, containerPort: 3000}] + securityContext: + allowPrivilegeEscalation: false + capabilities: {drop: [ALL]} + resources: + requests: {cpu: 250m, memory: 512Mi} + limits: {cpu: '1', memory: 2Gi} + startupProbe: + httpGet: {path: /health, port: http} + periodSeconds: 5 + failureThreshold: 120 + readinessProbe: + httpGet: {path: /health, port: http} + periodSeconds: 5 + volumeMounts: + - {name: data, mountPath: /data, subPath: pageswiki-exhibit-v018/wiki} + - {name: ca, mountPath: /pg-ca, readOnly: true} + volumes: + - name: data + persistentVolumeClaim: {claimName: pageswiki-data} + - name: ca + secret: + secretName: pageswiki-exhibition-tls + items: [{key: ca.crt, path: ca.crt}] +--- +apiVersion: v1 +kind: Service +metadata: {name: pageswiki} +spec: + type: ClusterIP + selector: {app: pageswiki} + ports: [{name: http, port: 80, targetPort: http}] diff --git a/deploy/kubernetes/exhibition/bootstrap.yaml b/deploy/kubernetes/exhibition/bootstrap.yaml new file mode 100644 index 0000000..7dcef1f --- /dev/null +++ b/deploy/kubernetes/exhibition/bootstrap.yaml @@ -0,0 +1,94 @@ +# One-time, fresh exhibition only. SQLite lives on emptyDir, NEVER on NFS. +# Refuses any second import. Keep the completed Job until verification ends. +apiVersion: batch/v1 +kind: Job +metadata: {name: pageswiki-exhibition-bootstrap} +spec: + backoffLimit: 0 + activeDeadlineSeconds: 1800 + template: + metadata: + labels: {pageswiki-db-client: 'true'} + spec: + restartPolicy: Never + automountServiceAccountToken: false + securityContext: + runAsNonRoot: true + runAsUser: 10001 + runAsGroup: 10001 + seccompProfile: {type: RuntimeDefault} + affinity: + podAffinity: + requiredDuringSchedulingIgnoredDuringExecution: + - labelSelector: + matchLabels: {app: pageswiki-postgres} + topologyKey: kubernetes.io/hostname + initContainers: + - name: initialize-local-source + image: python@sha256:9ef1a599f863231c3d91e941389bfdc4a2d6070557243d54df1a4e57015b960e + command: [python3, -c, "import os; os.chown('/data', 10001, 10001)"] + securityContext: + runAsNonRoot: false + runAsUser: 0 + runAsGroup: 0 + allowPrivilegeEscalation: false + readOnlyRootFilesystem: true + capabilities: {drop: [ALL], add: [CHOWN]} + resources: + requests: {cpu: 50m, memory: 32Mi} + limits: {cpu: 100m, memory: 64Mi} + volumeMounts: + - {name: source, mountPath: /data} + containers: + - name: bootstrap + image: git.anya.jp/anya/pageswiki-app@sha256:a999fe16f11ef91dbdb9904c63bb43d9ec3caef93f77cc07b1fe4a80460f67f9 + command: [/bin/sh, -ec] + args: + - | + umask 077 + test ! -e /persistent/import-complete.json + PAGESWIKI_DB_BACKEND=sqlite /pageswiki >/tmp/bootstrap.log 2>&1 & + pid=$! + trap 'kill -TERM "$pid" 2>/dev/null || true' EXIT + healthy=false + for attempt in $(seq 1 120); do + if wget -q -O /dev/null http://127.0.0.1:3000/health; then healthy=true; break; fi + kill -0 "$pid" + sleep 1 + done + test "$healthy" = true + kill -TERM "$pid" + wait "$pid" + trap - EXIT + /pageswiki migrate-postgres --data-dir /data --apply --timeout 20m >/persistent/import-report.pending.json + mv /persistent/import-report.pending.json /persistent/import-complete.json + # Preserve the stopped synthetic source for audit, not runtime use. + mkdir /persistent/bootstrap-source + cp /data/pages.db /persistent/bootstrap-source/pages.db + echo 'Synthetic namespace initialized and verified PostgreSQL import committed.' + env: + - {name: PAGESWIKI_DATA_DIR, value: /data} + - name: PAGESWIKI_AUTH_KEY + valueFrom: {secretKeyRef: {name: pageswiki-exhibition-app, key: auth-key}} + - name: PAGESWIKI_POSTGRES_DSN + valueFrom: {secretKeyRef: {name: pageswiki-exhibition-app, key: postgres-dsn}} + securityContext: + allowPrivilegeEscalation: false + capabilities: {drop: [ALL]} + resources: + requests: {cpu: 250m, memory: 512Mi} + limits: {cpu: '1', memory: 2Gi} + volumeMounts: + - {name: source, mountPath: /data} + - {name: data, mountPath: /data/documents, subPath: pageswiki-exhibit-v018/wiki/documents} + - {name: data, mountPath: /persistent, subPath: pageswiki-exhibit-v018/wiki} + - {name: ca, mountPath: /pg-ca, readOnly: true} + volumes: + - name: source + emptyDir: {} + - name: data + persistentVolumeClaim: {claimName: pageswiki-data} + - name: ca + secret: + secretName: pageswiki-exhibition-tls + items: [{key: ca.crt, path: ca.crt}] diff --git a/deploy/kubernetes/exhibition/demo/README.md b/deploy/kubernetes/exhibition/demo/README.md new file mode 100644 index 0000000..cc871fa --- /dev/null +++ b/deploy/kubernetes/exhibition/demo/README.md @@ -0,0 +1,94 @@ +# 展示用合成データの準備と投入前確認 + +灯架図書館、雲庭研究街区、帆灯運用街区という架空の街を巡るデータセットです。日本語のWiki 26ページ、合成CSV 1件、タスク8件、予定6件、架空連絡先6件をローカル生成します。実在の人物や団体、実測値、本番データ、認証情報を含みません。連絡先はすべて `example.invalid` です。 + +生成ツール `generate.py` にはHTTPクライアント、DB接続、クラスタ操作、投入機能がありません。別の `seed.py` が、展示namespaceと固定releaseイメージを確認し、localhost限定port-forward越しに通常のimport/API/DAVで投入します。 + +2026年11月15日に展示環境へ全件投入済みです。PostgreSQLとPagesWikiのPod再作成後にも、ログイン、Wiki/CSV 27文書、予定6件・タスク8件・連絡先6件のUIDとETagを確認しました。再投入は既存DAV20件を上書きせずにスキップします。本番や外部カレンダーのデータは使いません。 + +## 配置済み展示環境の検証 + +保存済みの展示用kubeconfigを利用し、別の端末で次を起動します。 + +```sh +kubectl -n exhibit-anya port-forward --address 127.0.0.1 service/pageswiki 18381:80 +``` + +`seed.py` はこのリポジトリの保存済み展示用kubeconfigと、`pageswiki-exhibition-app` Secretの `owner-password` を利用します。接続先は `127.0.0.1:18381` 固定、既定Hostは `pages.anya.jisaba.sh`、管理者は `exhibition-admin` です。トークンやパスワードは表示しません。 + +この投入ツールは2026年11月の展示専用です。kubectlとkubeconfigの参照先は +Git管理外の `.deployment-backups/exhibition-session/` に固定されており、別環境向けの汎用CLIではありません。 +当時の資格情報は同梱しません。`verify` もログインを行うため、オフライン検証には下記の単体テストを使います。 + +```sh +python3 tools/exhibition-demo/seed.py verify +``` + +新規環境での投入順は `configure --host localhost`、`wiki`、`organizers`、`city-labels`、`verify` です。既存展示への通常確認には `verify` だけを使います。`organizers` の再実行は `If-None-Match: *` により既存項目をスキップし、更新しません。 + +Cityの内部名はASCII制約があるため、日本語を識別子として渡しません。現在の展示は `/exhibition-demo` を起点としたURL自動生成を維持し、`city-labels` で表示タイトルだけを日本語化しています。データセットの3領域はこの起点の下に表示され、3つのトップレベルQuartierへ手動分割する構成ではありません。 + +## ローカル生成 + +リポジトリのルートでPython 3.10以上を使用します。追加パッケージは不要です。`--base-date` は日本時間の展示開始日を明示指定してください。 + +```sh +python3 tools/exhibition-demo/generate.py \ + --base-date 2026-11-15 \ + --output /tmp/pageswiki-exhibition-demo + +python3 -m unittest discover -s tools/exhibition-demo -p 'test_*.py' -v + +go test ./tools/exhibition-demo +``` + +投入前には独立したPythonテスト(生成6件・投入補助3件)を必ず実行します。Goテストはアプリの既存パーサーとの追加確認です。Pythonを含まない既存CI環境ではGoの追加確認だけをskipし、CIイメージに新しい依存は要求しません。 + +予定は基準日の9時、11時、14時と、その翌日、3日後、6日後に配置します。タスクの期限は前日から6日後までに分散し、完了・進行中・未着手の状態を用意しています。JSONには日本時間のオフセットを残し、ICSの時刻はUTCで出力します。 + +同じ基準日とprefixからは同じ内容とZIPが生成されます。基準日を変えてもタスク、予定、連絡先のUIDは変わりません。再生成は既存の `manifest.json` と全ファイルのSHA-256を照合し、手編集したファイル、無関係なファイル、symlinkがある出力先を拒否します。生成物を手編集した場合は別の出力先を指定してください。中断で生成が不完全になった場合も、新しいディレクトリで再生成してください。 + +## 出力内容 + +| 出力 | 用途 | +| --- | --- | +| `wiki.zip` | 既存Archive Import向け。26個のMarkdownと1個のCSVのみを収録 | +| `wiki/` | ZIPと同一内容の閲覧用展開データ | +| `fixtures.json` | 日付を解決済みの合成データ。アプリの直接import形式ではない | +| `tasks/*.ics` | 1ファイルにつき1個のVTODO。タスクDAVの単一リソース形式を想定 | +| `events/*.ics` | 1ファイルにつき1個のVEVENT | +| `calendar.ics` | 6予定をまとめた閲覧・import用カレンダー | +| `contacts/*.vcf` | 1ファイルにつき1人のvCard 3.0 | +| `manifest.json` | 基準日、prefix、件数、生成物のSHA-256 | + +Wikiの階層は「街区 → 通り → 場所 → 個別資料」の最大4階層です。各ページには `children` マクロと内部リンクがあり、風見テラスには表とCSV、再現ノートには集計コードを用意しています。五分の案内コースは `帆灯運用街区/案内通り/案内台本` から始められます。 + +## 展示用Wikiへの投入手順 + +以下は、展示専用の新規データ領域、利用者、接続先が確定した後に運営者が行う手順です。本番や既存利用者の環境には投入しません。 + +1. 展示専用環境のバックアップ方針と権限を確認し、通常の `/v/import` 画面を開きます。 +2. `wiki.zip` を選び、投入先prefixを **`/exhibition-demo`** に指定します。変更する場合は、生成時にも同じ `--target-prefix` を指定します。内部リンクはこのprefixを含むため、ZIPだけ別prefixに投入しないでください。 +3. 解析結果の27項目を確認します。Markdownは拡張子が除去されたPathになり、CSVの拡張子は残ります。 +4. 現在の展示構成ではimportのQuartier、Street、Spotを空欄とし、保存後のURL自動生成に任せます。手動指定する場合はASCIIの内部名を使い、日本語は別途Cityの表示タイトルへ設定します。 +5. 競合は `skip` を選びます。既存import APIのcommitは `conflict=skip` が既定です。`rename` は複製を作るので再投入には使用しません。 +6. `/exhibition-demo/展示案内` を開き、children一覧、パンくず、内部リンク、コード、表、CSVを確認します。 + +同prefixでの `skip` は既存Pathを上書きしません。日付や内容を変更したZIPの再投入でも既存ページは更新されません。更新や削除が必要な場合は、展示専用データであることを確認して別途計画してください。ローカル再生成の安全性と、サーバ側での再投入の安全性は別の確認事項です。 + +## タスクと予定と連絡先の投入前確認 + +JSON fixtureはアプリのAPIペイロードを装っていません。通常のタスクDAV、カレンダー、CardDAVのディスカバリと権限確認を経て、展示専用コレクションへ投入する後続作業が必要です。認証設定や外部カレンダー購読はこの準備ツールでは作成しません。 + +- タスクDAVには `tasks/` の単一VTODOを使います。全タスクを1個のリソースに連結しないでください。 +- 予定は対応するimport経路で `calendar.ics` を使うか、通常のDAVリソース操作で `events/` を使います。両方を重複投入しません。 +- 連絡先は `contacts/` の単一vCardを使います。電話番号、実住所、実在ドメインは含みません。 +- DAVの新規作成は固定のリソース名・UIDを使い、`If-None-Match: *` で既存リソースの上書きを防ぎます。412応答は内容を確認し、無条件PUTで上書きしないでください。日付を更新する場合は既存ETagの確認と `If-Match` による更新を別途実装・検証します。 + +投入後は展示専用アカウントで当日・今週の予定、タスク状態、日本時間の表示を確認してください。実サーバでのimport、条件付き作成、UID/ETagと文書の読み戻しは `seed.py` で検証済みです。公開HTTPS経路を通したブラウザの描画・操作確認は残っています。 + +## 仕様の参照先 + +- [Archive Importの設計](../../../../docs/design/archive-import.md) +- [childrenマクロの設計](../../../../docs/design/projection-adapters.md#children-macro-views) +- ソース上の確認箇所は `internal/server/import_handler.go`、`internal/server/task_ical.go`、`internal/server/contact_dav.go` です。 diff --git a/deploy/kubernetes/exhibition/demo/catalog.json b/deploy/kubernetes/exhibition/demo/catalog.json new file mode 100644 index 0000000..95535ee --- /dev/null +++ b/deploy/kubernetes/exhibition/demo/catalog.json @@ -0,0 +1,81 @@ +{ + "schema_version": 1, + "dataset_id": "pageswiki-exhibition-fiction-v1", + "notice": "すべて架空の展示用データです。実在の人物、団体、設備、観測値とは関係ありません。", + "districts": [ + { + "name": "灯架図書館", + "intro": "空想の港町にある灯架図書館。物語と設計記録を同じ棚に並べ、読むことから小さな発見を始めます。", + "streets": [ + {"name": "閲覧通り", "intro": "初めての来館者が、書棚と読書の記録を巡る通りです。", "spots": [ + {"name": "星図の書棚", "intro": "架空の星座を描いた地図帳を集めました。星の位置ではなく、物語のつながりを調べる棚です。", "details": ["銀の帆座は航海日誌の章から探せます。", "青い栞は共同読書で選ばれた資料の目印です。"]}, + {"name": "読書ラウンジ", "intro": "短い感想を持ち寄る静かな場所。結論を急がず、気になった一文から話を始めます。", "details": ["一回の読書会は二十五分を想定しています。", "紹介カードには作品名と問いを一つ書きます。"]} + ]}, + {"name": "記録通り", "intro": "紙の資料を整理し、次の読者に伝えるための作業記録です。", "spots": [ + {"name": "修復工房", "intro": "破れた架空の航海日誌を題材に、修復前後の記録の残し方を学びます。", "details": ["修復前の状態と作業の判断を分けて記録します。", "展示の作業記録には実物の文化財情報を含めません。"]}, + {"name": "目録編集室", "intro": "題名、分類、紹介文を揃えて資料を見つけやすくします。", "details": ["分類は星図、航海、暮らしの三種類です。", "略称から正式な架空資料名へのリンクを残します。"]} + ]} + ] + }, + { + "name": "雲庭研究街区", + "intro": "雲庭研究街区は、合成データで観察と分析を練習する架空の研究拠点です。数値は測定結果ではありません。", + "streets": [ + {"name": "観測通り", "intro": "データの意味、単位、欠測を揃えてから図や表に進みます。", "spots": [ + {"name": "風見テラス", "intro": "紙で作った風車の回転数を想定した、完全合成の観測セットです。", "details": ["回転数は説明用の規則から生成します。", "気象予測や設備判断には利用できません。"]}, + {"name": "露の温室", "intro": "架空の苗床ごとの観察メモを並べ、記録の粒度を比較します。", "details": ["苗床名は琥珀、翡翠、真珠の三つです。", "成長の違いは物語上の設定で、栽培助言ではありません。"]} + ]}, + {"name": "解析通り", "intro": "小さな表から仮説と確認事項を分けて考える通りです。", "spots": [ + {"name": "比較実験室", "intro": "同じ条件のつもりでも何が異なるか、試行表から探します。", "details": ["条件名、入力、結果を一行にまとめます。", "一つの結果だけで原因を決めない練習に使います。"]}, + {"name": "再現ノート", "intro": "入力と手順を残し、別の人が同じ合成結果を得られるか確かめます。", "details": ["基準日を固定すると展示データを再現できます。", "実データや認証情報のコピーは使いません。"]} + ]} + ] + }, + { + "name": "帆灯運用街区", + "intro": "帆灯運用街区は、展示を案内する架空の運営チームです。受付、点検、振り返りを一つの流れで紹介します。", + "streets": [ + {"name": "案内通り", "intro": "初めての見学者にも、現在地と次の見どころを伝えます。", "spots": [ + {"name": "受付デスク", "intro": "三つの街区を巡る見学コースの起点です。参加者の実名や連絡先は収集しません。", "details": ["図書館、研究街区、運用街区の順に巡ります。", "質問は架空の案内係に向けたサンプルとして扱います。"]}, + {"name": "案内台本", "intro": "階層、内部リンク、タスクと予定の関係を短い説明でつなぎます。", "details": ["まず子ページ一覧から目的の場所へ移動します。", "最後に日付の変わる展示用予定を紹介します。"]} + ]}, + {"name": "整備通り", "intro": "点検結果と引き継ぎ事項を分けて記録する運用の練習場です。", "spots": [ + {"name": "点検室", "intro": "架空の案内灯と展示端末を題材に、確認項目を見える形にします。", "details": ["点検項目は表示、操作、案内文の三つです。", "このページの手順は実設備を操作しません。"]}, + {"name": "引継ぎ広場", "intro": "終わったこと、残ったこと、次に確かめることを短く残します。", "details": ["未完了の項目には確認する日を添えます。", "担当名は展示専用の架空役名を使います。"]} + ]} + ] + } + ], + "deep_pages": [ + {"parent": "灯架図書館/閲覧通り/星図の書棚", "name": "銀の帆座", "intro": "銀の帆座は、迷った船が灯りを持ち寄るという架空の物語です。", "details": ["分類は星図、資料番号は SYN-LIB-001 です。", "関連する読書会は合成カレンダーに収録しています。"]}, + {"parent": "灯架図書館/記録通り/修復工房", "name": "青い航海日誌", "intro": "青い航海日誌の綴じ直しを想定した、展示専用の修復記録です。", "details": ["作業前の課題は架空の綴じ糸のゆるみです。", "完了条件は記録表の項目が揃っていることです。"]}, + {"parent": "雲庭研究街区/解析通り/再現ノート", "name": "合成データの読み方", "intro": "CSVの各列が何を表すかを確認します。行の日付は展示の基準日から相対生成されます。", "details": ["sample_id は固定の標本識別子です。", "rotations は説明用の整数、synthetic は常に true です。"]}, + {"parent": "帆灯運用街区/整備通り/点検室", "name": "開場前チェック", "intro": "実環境を変更せず、展示画面の見どころを確認するチェックリストです。", "details": ["階層を移動して戻れることを確認します。", "図書館から研究街区へのリンクを確認します。"]} + ], + "tasks": [ + {"id": "task-01", "title": "星図の紹介カードを揃える", "due_offset": -1, "status": "COMPLETED", "page": "灯架図書館/閲覧通り/星図の書棚"}, + {"id": "task-02", "title": "読書会の問いを一つ選ぶ", "due_offset": 0, "status": "IN-PROCESS", "page": "灯架図書館/閲覧通り/読書ラウンジ"}, + {"id": "task-03", "title": "合成観測表の単位を確認する", "due_offset": 0, "status": "NEEDS-ACTION", "page": "雲庭研究街区/観測通り/風見テラス"}, + {"id": "task-04", "title": "再現ノートに基準日を記録する", "due_offset": 1, "status": "NEEDS-ACTION", "page": "雲庭研究街区/解析通り/再現ノート"}, + {"id": "task-05", "title": "開場前の表示を点検する", "due_offset": 0, "status": "NEEDS-ACTION", "page": "帆灯運用街区/整備通り/点検室"}, + {"id": "task-06", "title": "案内台本を読み合わせる", "due_offset": 2, "status": "NEEDS-ACTION", "page": "帆灯運用街区/案内通り/案内台本"}, + {"id": "task-07", "title": "修復記録の分類を揃える", "due_offset": 3, "status": "NEEDS-ACTION", "page": "灯架図書館/記録通り/修復工房"}, + {"id": "task-08", "title": "見学コースを振り返る", "due_offset": 6, "status": "NEEDS-ACTION", "page": "帆灯運用街区/整備通り/引継ぎ広場"} + ], + "events": [ + {"id": "event-01", "title": "開場前の読み合わせ", "offset": 0, "hour": 9, "duration_minutes": 30, "location": "帆灯運用街区 受付デスク"}, + {"id": "event-02", "title": "銀の帆座の読書会", "offset": 0, "hour": 11, "duration_minutes": 45, "location": "灯架図書館 読書ラウンジ"}, + {"id": "event-03", "title": "合成観測表の見学", "offset": 0, "hour": 14, "duration_minutes": 30, "location": "雲庭研究街区 風見テラス"}, + {"id": "event-04", "title": "再現ノートの交換会", "offset": 1, "hour": 13, "duration_minutes": 45, "location": "雲庭研究街区 比較実験室"}, + {"id": "event-05", "title": "青い航海日誌の紹介", "offset": 3, "hour": 10, "duration_minutes": 30, "location": "灯架図書館 修復工房"}, + {"id": "event-06", "title": "街区横断の振り返り", "offset": 6, "hour": 16, "duration_minutes": 30, "location": "帆灯運用街区 引継ぎ広場"} + ], + "contacts": [ + {"id": "contact-01", "name": "栞係 ルリ", "organization": "架空の灯架図書館", "email": "ruri@example.invalid"}, + {"id": "contact-02", "name": "修復係 コハク", "organization": "架空の灯架図書館", "email": "kohaku@example.invalid"}, + {"id": "contact-03", "name": "観測係 ソラ", "organization": "架空の雲庭研究街区", "email": "sora@example.invalid"}, + {"id": "contact-04", "name": "記録係 ナギ", "organization": "架空の雲庭研究街区", "email": "nagi@example.invalid"}, + {"id": "contact-05", "name": "案内係 トワ", "organization": "架空の帆灯運用街区", "email": "towa@example.invalid"}, + {"id": "contact-06", "name": "点検係 ハル", "organization": "架空の帆灯運用街区", "email": "haru@example.invalid"} + ] +} diff --git a/deploy/kubernetes/exhibition/pageswiki.yaml.example b/deploy/kubernetes/exhibition/pageswiki.yaml.example new file mode 100644 index 0000000..177960f --- /dev/null +++ b/deploy/kubernetes/exhibition/pageswiki.yaml.example @@ -0,0 +1,99 @@ +# 旧SQLite用の一般ひな形。現在の展示NFSへは適用しない。 +# 展示ではpostgres.yaml、初回のみbootstrap.yaml、app.yamlを使う。 +# 適用前に運営の方針と照合する。 +# kubectl -n "$NS" apply -f pageswiki.yaml +apiVersion: v1 +kind: PersistentVolumeClaim +metadata: + name: pageswiki-data +spec: + storageClassName: REPLACE_WITH_STORAGE_CLASS + accessModes: + - ReadWriteOnce + resources: + requests: + storage: 20Gi +--- +apiVersion: apps/v1 +kind: Deployment +metadata: + name: pageswiki +spec: + replicas: 1 + strategy: + type: Recreate + selector: + matchLabels: + app: pageswiki + template: + metadata: + labels: + app: pageswiki + spec: + automountServiceAccountToken: false + terminationGracePeriodSeconds: 60 + securityContext: + runAsNonRoot: true + runAsUser: 10001 + runAsGroup: 10001 + fsGroup: 10001 + seccompProfile: + type: RuntimeDefault + containers: + - name: pageswiki + # 本書の作成時点のrelease例。新しい展示機能を含める場合は別途releaseし検証する。 + image: git.anya.jp/anya/pageswiki-app:v0.17.3 + imagePullPolicy: IfNotPresent + ports: + - name: http + containerPort: 3000 + env: + - name: PAGESWIKI_DATA_DIR + value: /data + resources: + requests: + cpu: 250m + memory: 512Mi + limits: + cpu: "2" + memory: 2Gi + securityContext: + allowPrivilegeEscalation: false + capabilities: + drop: + - ALL + volumeMounts: + - name: data + mountPath: /data + - name: tmp + mountPath: /tmp + startupProbe: + httpGet: + path: /health + port: http + periodSeconds: 5 + failureThreshold: 120 + readinessProbe: + httpGet: + path: /health + port: http + periodSeconds: 5 + volumes: + - name: data + persistentVolumeClaim: + claimName: pageswiki-data + - name: tmp + emptyDir: {} +--- +apiVersion: v1 +kind: Service +metadata: + name: pageswiki +spec: + type: ClusterIP + selector: + app: pageswiki + ports: + - name: http + port: 80 + targetPort: http diff --git a/deploy/kubernetes/exhibition/postgres.yaml b/deploy/kubernetes/exhibition/postgres.yaml new file mode 100644 index 0000000..a0778a0 --- /dev/null +++ b/deploy/kubernetes/exhibition/postgres.yaml @@ -0,0 +1,145 @@ +apiVersion: v1 +kind: ConfigMap +metadata: + name: pageswiki-exhibition-init +data: + storage.py: | + import os, pathlib, shutil, stat + root = pathlib.Path('/volume/pageswiki-exhibit-v018') + def owned_directory(path, uid, gid, mode): + try: + path.mkdir(mode=mode) + except FileExistsError: + s = path.lstat() + if not stat.S_ISDIR(s.st_mode) or (s.st_uid, s.st_gid) != (uid, gid): + raise RuntimeError('unexpected existing directory ownership: ' + str(path)) + else: + os.chown(path, uid, gid) + owned_directory(root, 0, 0, 0o755) + owned_directory(root / 'wiki', 10001, 10001, 0o700) + owned_directory(root / 'wiki' / 'documents', 10001, 10001, 0o700) + owned_directory(root / 'postgres', 70, 70, 0o700) + os.chown('/pgsocket', 70, 70) + for name in ('server.crt', 'server.key'): + shutil.copyfile('/cert-source/' + name, '/tls/' + name) + os.chmod('/tls/' + name, 0o600) + os.chown('/tls/' + name, 70, 70) + print('Dedicated directories and PostgreSQL TLS files ready; existing ownership unchanged.') + 10-app.sh: | + set -eu + psql -v ON_ERROR_STOP=1 --username postgres --dbname postgres < 初期相談時の草案を保存したもの。実際の展示ではPostgreSQLとNOC管理の公開経路を利用し、 +> 最終指定URLは `https://pages.anya.jisaba.sh/` となった。以下を現在の依頼文として再送しない。 +> 配置の経緯は [展示運用記録](exhibition-kubernetes-dns-tls.md) を参照。 + +ぼいどさん + +ご連絡ありがとうございます。 +PagesWikiの展示について、Aの運営側で用意されているKubernetes Clusterを利用させていただければと思っています。 + +こちらでコンテナイメージとデプロイ用のマニフェストを用意し、割り当ていただいたNamespace内へ配置する想定です。クラスタ全体の管理権限や特権コンテナは必要としない構成で考えています。Kubernetesの利用経験がまだ少ないため、事前に動作確認できる期間をいただけると助かります。 + +アプリは現在SQLiteとファイル保存を使う単一writer構成のため、本体は1 replicaとし、永続ボリュームを利用したいです。リソースはひとまず合計CPU 2〜4 vCPU、メモリ4〜8 GiB、永続ストレージ20 GiB程度を目安に相談させてください。展示する機能を絞って検証し、必要量を調整する予定です。 + +アクセス先は、こちらで管理する `pages.jsb.anya.jp` を使用したいと考えています。グローバルDNSに、会場ネットワークから到達できるIngress等のローカルIPをAレコードとして登録する想定です。追加のドメイン展示用に `*.pages.jsb.anya.jp` も同じ入口へ向けられると助かります。DNSはCloudflareのDNS onlyとし、Cloudflare経由の通信中継は利用しません。 + +証明書はこちらでCloudflareのDNS-01認証を使い、`pages.jsb.anya.jp` と `*.pages.jsb.anya.jp` を含むものを取得する予定です。DNS操作用のAPI Tokenは共有クラスタへ置かず、証明書と秘密鍵だけをTLS Secretとして持ち込み、Ingress側でTLS終端する形を第一案としています。 + +以下について教えていただけますでしょうか。 + +- Namespaceの割り当てと接続方法、利用できるリソース・権限の範囲 +- linux/amd64のイメージが動くことと、外部レジストリ `git.anya.jp` からのpull可否 +- 利用可能なStorageClassと、そのストレージがSQLiteの保存先に適しているか +- Ingress等の利用方法と、DNSへ登録できるローカルIP、会場端末からの到達性 +- 持ち込み証明書によるTLS終端の可否と、Secretの投入・更新方法 +- 会場DNSで、公開DNSに登録したプライベートIPがリバインディング対策等で遮断されないか +- Podの実行権限・ネットワーク等の制約と、事前検証できる期間 + +もしストレージや公開経路などの制約でAが難しい場合は、BのVM提供も含めて相談させていただければと思います。 + +よろしくお願いいたします。 diff --git a/tools/exhibition-demo/.gitignore b/tools/exhibition-demo/.gitignore new file mode 100644 index 0000000..c18dd8d --- /dev/null +++ b/tools/exhibition-demo/.gitignore @@ -0,0 +1 @@ +__pycache__/ diff --git a/tools/exhibition-demo/fixtures_test.go b/tools/exhibition-demo/fixtures_test.go new file mode 100644 index 0000000..8f05efa --- /dev/null +++ b/tools/exhibition-demo/fixtures_test.go @@ -0,0 +1,97 @@ +package exhibitiondemo + +import ( + "archive/zip" + "io" + "os" + "os/exec" + "path/filepath" + "strings" + "testing" + + ical "github.com/emersion/go-ical" + "pageswiki/internal/calendar" + "pageswiki/internal/render" + "pageswiki/internal/store" +) + +// This test only generates local files and invokes parsers, never HTTP or a DB. +func TestGeneratedArtifactsWithApplicationParsers(t *testing.T) { + python, err := exec.LookPath("python3") + if err != nil { + t.Skip("optional application-parser integration requires python3; run the independent Python fixture tests before exhibition import") + } + out := filepath.Join(t.TempDir(), "demo") + command := exec.Command(python, "generate.py", "--base-date", "2026-11-15", "--output", out) + if result, err := command.CombinedOutput(); err != nil { + t.Fatalf("generate: %v\n%s", err, result) + } + read := func(name string) []byte { + t.Helper() + data, err := os.ReadFile(filepath.Join(out, name)) + if err != nil { + t.Fatal(err) + } + return data + } + events, err := calendar.ParseFeed(read("calendar.ics")) + if err != nil || len(events) != 6 { + t.Fatalf("calendar feed: count=%d error=%v", len(events), err) + } + for _, folder := range []string{"contacts", "events", "tasks"} { + entries, err := os.ReadDir(filepath.Join(out, folder)) + if err != nil { + t.Fatal(err) + } + for _, entry := range entries { + name := filepath.Join(folder, entry.Name()) + data := string(read(name)) + switch folder { + case "contacts": + if _, err := store.ParseContact(data); err != nil { + t.Errorf("%s: %v", name, err) + } + case "events": + if _, err := calendar.Parse(data); err != nil { + t.Errorf("%s: %v", name, err) + } + case "tasks": + value, err := ical.NewDecoder(strings.NewReader(data)).Decode() + if err != nil { + t.Fatalf("%s: %v", name, err) + } + if len(value.Children) != 1 || value.Children[0].Name != "VTODO" { + t.Errorf("%s: expected one VTODO", name) + } + } + } + } + archive, err := zip.OpenReader(filepath.Join(out, "wiki.zip")) + if err != nil { + t.Fatal(err) + } + defer archive.Close() + count := 0 + for _, file := range archive.File { + if !strings.HasSuffix(file.Name, ".md") { + continue + } + reader, err := file.Open() + if err != nil { + t.Fatal(err) + } + data, err := io.ReadAll(reader) + reader.Close() + if err != nil { + t.Fatal(err) + } + html := render.Markdown(string(data)) + if !strings.Contains(html, "

") || !strings.Contains(html, "{{children:/exhibition-demo") || !strings.Contains(html, "href=\"/exhibition-demo/") { + t.Errorf("%s: expected heading, preserved macro and internal link", file.Name) + } + count++ + } + if count != 26 { + t.Errorf("page count=%d", count) + } +} diff --git a/tools/exhibition-demo/generate.py b/tools/exhibition-demo/generate.py new file mode 100644 index 0000000..a8cd6e2 --- /dev/null +++ b/tools/exhibition-demo/generate.py @@ -0,0 +1,187 @@ +#!/usr/bin/env python3 +"""Build fictional exhibition artifacts locally. No network or database access.""" + +import argparse +import csv +from datetime import date, datetime, time, timedelta, timezone +import hashlib +import io +import json +from pathlib import Path +import re +import zipfile + +CATALOG = Path(__file__).resolve().parents[2] / "deploy/kubernetes/exhibition/demo/catalog.json" +MARKER = "manifest.json" +JST = timezone(timedelta(hours=9)) + + +def json_bytes(value): + return (json.dumps(value, ensure_ascii=False, indent=2, sort_keys=True) + "\n").encode() + + +def sha(data): + return hashlib.sha256(data).hexdigest() + + +def escaped(text): + return text.replace("\\", "\\\\").replace("\n", "\\n").replace(";", "\\;").replace(",", "\\,") + + +def folded(lines): + """RFC 5545/6350 content lines, at most 75 UTF-8 octets including continuation.""" + result = [] + for line in lines: + current = "" + for char in line: + if len((current + char).encode()) > 75: + result.append(current) + current = " " + current += char + result.append(current) + return ("\r\n".join(result) + "\r\n").encode() + + +def utc(value): + return value.astimezone(timezone.utc).strftime("%Y%m%dT%H%M%SZ") + + +def calendar(component, properties): + return folded(["BEGIN:VCALENDAR", "VERSION:2.0", "PRODID:-//PagesWiki//Synthetic Exhibition//JA", + "BEGIN:" + component, *properties, "END:" + component, "END:VCALENDAR"]) + + +def build(base_date, prefix="/exhibition-demo"): + if not re.fullmatch(r"/[a-zA-Z0-9_-]+(?:/[a-zA-Z0-9_-]+)*", prefix): + raise ValueError("target prefix must be a dedicated absolute ASCII path, not /") + source = json.loads(CATALOG.read_text()) + pages = {} + notice = source["notice"] + + def link(path, label=None): + return f"[{label or path.rsplit('/', 1)[-1]}]({prefix}/{path})" + + def page(path, intro, details=()): + parent = path.rsplit("/", 1)[0] if "/" in path else "展示案内" + text = f"# {path.rsplit('/', 1)[-1]}\n\n{intro}\n\n> {notice}\n\n" + if details: + text += "## 見どころ\n\n" + "\n".join("- " + item for item in details) + "\n\n" + text += f"## この場所のページ\n\n{{{{children:{prefix}/{path}}}}}\n\n" + if path != "展示案内": + text += f"## 街区を巡る\n\n{link(parent, 'ひとつ上の案内')} · {link('展示案内', '展示全体の案内')}\n" + pages[path + ".md"] = text + + page("展示案内", "灯架図書館、雲庭研究街区、帆灯運用街区を巡る展示です。階層の移動から、資料、タスク、予定のつながりを体験できます。") + pages["展示案内.md"] += "\n## 街区を巡る\n\n| 街区 | 体験 |\n| --- | --- |\n" + "".join( + f"| {link(d['name'])} | {label} |\n" for d, label in zip(source["districts"], ["資料を読む", "合成データを比べる", "準備と引き継ぎをつなぐ"])) + # The landing page lives beside the three district roots, not above them. + pages["展示案内.md"] = pages["展示案内.md"].replace(f"children:{prefix}/展示案内", f"children:{prefix}") + for district in source["districts"]: + page(district["name"], district["intro"]) + for street in district["streets"]: + street_path = district["name"] + "/" + street["name"] + page(street_path, street["intro"]) + for spot in street["spots"]: + page(street_path + "/" + spot["name"], spot["intro"], spot["details"]) + for entry in source["deep_pages"]: + page(entry["parent"] + "/" + entry["name"], entry["intro"], entry["details"]) + csv_path = "雲庭研究街区/観測通り/風見テラス/合成観測.csv" + pages["雲庭研究街区/観測通り/風見テラス.md"] += f"\n## 合成観測データ\n\n{link(csv_path, '合成観測CSVを開く')}\n\n| 標本 | 回転数 | 注記 |\n| --- | ---: | --- |\n| SYN-001 | 18 | 合成値 |\n| SYN-002 | 25 | 合成値 |\n| SYN-003 | 32 | 合成値 |\n" + pages["雲庭研究街区/解析通り/再現ノート.md"] += "\n## 集計のコード例\n\n次のコードはCSVを読むだけで、外部通信や書き込みを行いません。\n\n```python\nimport csv\n\nwith open(\"合成観測.csv\", encoding=\"utf-8\", newline=\"\") as source:\n rows = list(csv.DictReader(source))\nprint(sum(int(row[\"rotations\"]) for row in rows))\n```\n" + pages["帆灯運用街区/案内通り/案内台本.md"] += "\n## 五分の案内コース\n\n1. " + link("灯架図書館/閲覧通り/星図の書棚") + "で四階層目の資料を開きます。\n2. " + link("雲庭研究街区/観測通り/風見テラス") + "で表とCSVを見比べます。\n3. " + link("帆灯運用街区/整備通り/引継ぎ広場") + "からタスクと予定の紹介に進みます。\n" + stream = io.StringIO(newline="") + writer = csv.writer(stream, lineterminator="\n") + writer.writerow(["sample_id", "date", "station", "rotations", "synthetic"]) + for i in range(14): + writer.writerow([f"SYN-{i+1:03d}", (base_date + timedelta(days=i-6)).isoformat(), ["琥珀", "翡翠", "真珠"][i % 3], 18 + i * 7 % 31, "true"]) + wiki = {path: text.encode() for path, text in pages.items()} + wiki[csv_path] = stream.getvalue().encode() + files = {"wiki/" + path: data for path, data in wiki.items()} + buffer = io.BytesIO() + with zipfile.ZipFile(buffer, "w", compression=zipfile.ZIP_DEFLATED) as archive: + for path, data in sorted(wiki.items()): + info = zipfile.ZipInfo(path, date_time=(2020, 1, 1, 0, 0, 0)) + info.compress_type = zipfile.ZIP_DEFLATED + info.external_attr = 0o100644 << 16 + archive.writestr(info, data) + files["wiki.zip"] = buffer.getvalue() + stamp = utc(datetime.combine(base_date, time(), JST)) + fixture = {"schema_version": 1, "dataset_id": source["dataset_id"], "synthetic": True, + "base_date": base_date.isoformat(), "timezone": "Asia/Tokyo", "target_prefix": prefix, + "tasks": [], "events": [], "contacts": source["contacts"]} + for task in source["tasks"]: + due = base_date + timedelta(days=task["due_offset"]) + uid = task["id"] + "@example.invalid" + fixture["tasks"].append({**task, "uid": uid, "due_date": due.isoformat(), "page_path": prefix + "/" + task["page"]}) + properties = ["UID:" + uid, "DTSTAMP:" + stamp, "SUMMARY:" + escaped(task["title"]), + "DESCRIPTION:" + escaped(notice + "\n" + prefix + "/" + task["page"]), + "DUE;VALUE=DATE:" + due.strftime("%Y%m%d"), "STATUS:" + task["status"], + "PERCENT-COMPLETE:" + ("100" if task["status"] == "COMPLETED" else "50" if task["status"] == "IN-PROCESS" else "0")] + if task["status"] == "COMPLETED": + properties.append("COMPLETED:" + utc(datetime.combine(due, time(15), JST))) + files["tasks/" + task["id"] + ".ics"] = calendar("VTODO", properties) + event_components = [] + for event in source["events"]: + start = datetime.combine(base_date + timedelta(days=event["offset"]), time(event["hour"]), JST) + end = start + timedelta(minutes=event["duration_minutes"]) + uid = event["id"] + "@example.invalid" + fixture["events"].append({**event, "uid": uid, "start": start.isoformat(), "end": end.isoformat()}) + properties = ["UID:" + uid, "DTSTAMP:" + stamp, "DTSTART:" + utc(start), "DTEND:" + utc(end), + "SUMMARY:" + escaped(event["title"]), "DESCRIPTION:" + escaped(notice), "LOCATION:" + escaped(event["location"])] + files["events/" + event["id"] + ".ics"] = calendar("VEVENT", properties) + event_components += ["BEGIN:VEVENT", *properties, "END:VEVENT"] + files["calendar.ics"] = folded(["BEGIN:VCALENDAR", "VERSION:2.0", "PRODID:-//PagesWiki//Synthetic Exhibition//JA", *event_components, "END:VCALENDAR"]) + for contact in source["contacts"]: + if not re.fullmatch(r"[a-z0-9-]+@example\.invalid", contact["email"]): + raise ValueError("only example.invalid contact addresses are allowed") + files["contacts/" + contact["id"] + ".vcf"] = folded(["BEGIN:VCARD", "VERSION:3.0", "UID:" + contact["id"] + "@example.invalid", + "FN:" + escaped(contact["name"]), "N:;" + escaped(contact["name"]) + ";;;", "ORG:" + escaped(contact["organization"]), + "EMAIL:" + contact["email"], "NOTE:" + escaped(notice), "END:VCARD"]) + files["fixtures.json"] = json_bytes(fixture) + manifest = {"dataset_id": source["dataset_id"], "schema_version": 1, "synthetic": True, "base_date": base_date.isoformat(), + "target_prefix": prefix, "page_count": len(pages), "archive_entry_count": len(wiki), + "files": {name: sha(data) for name, data in sorted(files.items())}} + files[MARKER] = json_bytes(manifest) + return files + + +def write_output(output, files): + """Refuse unrelated/modified files and symlinks; reruns only replace owned artifacts.""" + output = Path(output).absolute() + if any(path.is_symlink() for path in [output, *output.parents]): + raise ValueError("output path must not contain symlinks") + existing = list(output.rglob("*")) if output.exists() else [] + if any(path.is_symlink() for path in existing): + raise ValueError("output contains a symlink") + names = {str(path.relative_to(output)) for path in existing if path.is_file()} + if existing: + if MARKER not in names: + raise ValueError("output is not an owned exhibition directory; choose a new directory") + previous = json.loads((output / MARKER).read_text()) + expected = set(previous.get("files", {})) | {MARKER} + if previous.get("dataset_id") != "pageswiki-exhibition-fiction-v1" or names != expected or names != set(files): + raise ValueError("output contains unrelated files or a different dataset layout") + if any(sha((output / name).read_bytes()) != digest for name, digest in previous["files"].items()): + raise ValueError("output contains modified artifacts; choose a new directory") + for name, data in files.items(): + path = output / name + path.parent.mkdir(parents=True, exist_ok=True) + path.write_bytes(data) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--base-date", required=True, type=date.fromisoformat, help="展示開始日 YYYY-MM-DD、日本時間") + parser.add_argument("--output", required=True, type=Path, help="新規またはこのツールが生成したディレクトリ") + parser.add_argument("--target-prefix", default="/exhibition-demo") + args = parser.parse_args() + try: + files = build(args.base_date, args.target_prefix) + write_output(args.output, files) + except (ValueError, OSError) as error: + parser.exit(2, f"生成を中止しました: {error}\n") + print(f"ローカル生成完了: {args.output} (Wiki 26ページ、CSV 1件、タスク 8件、予定 6件、連絡先 6件)。投入は未実施です。") + + +if __name__ == "__main__": + main() diff --git a/tools/exhibition-demo/seed.py b/tools/exhibition-demo/seed.py new file mode 100644 index 0000000..525b4d9 --- /dev/null +++ b/tools/exhibition-demo/seed.py @@ -0,0 +1,323 @@ +#!/usr/bin/env python3 +"""Seed ONLY the assigned exhibition via an existing loopback port-forward. + +Credentials come from the exhibition Secret, never from CLI arguments. This +tool does not connect to a database, a public URL, or an external calendar. +""" +import argparse +import base64 +from html.parser import HTMLParser +import json +import os +from pathlib import Path +import re +import subprocess +import time +import urllib.error +import urllib.parse +import urllib.request +import uuid + +ROOT = Path(__file__).resolve().parents[2] +NS = "exhibit-anya" +IMAGE = "git.anya.jp/anya/pageswiki-app@sha256:a999fe16f11ef91dbdb9904c63bb43d9ec3caef93f77cc07b1fe4a80460f67f9" +CAL = "/_/api/v1/extension/organizer.calendar/" +DAV = "/_/api/v1/caldav/" +EXHIBITION_HOST = "pages.anya.jisaba.sh" + + +def kubectl(*args): + env = dict(os.environ) + directory = ROOT / ".deployment-backups/exhibition-session" + env["PATH"] = str(directory / "tools") + os.pathsep + env.get("PATH", "") + env["KUBECONFIG"] = str(directory / "config/kubeconfig-keyboard") + return subprocess.check_output([str(directory / "tools/kubectl"), "--request-timeout=20s", "-n", NS, *args], env=env) + + +class NoRedirect(urllib.request.HTTPRedirectHandler): + def redirect_request(self, *args): + return None + + +class Forms(HTMLParser): + def __init__(self): + super().__init__() + self.forms, self.current, self.select = {}, None, None + + def handle_starttag(self, tag, attrs): + a = dict(attrs) + if tag == "form": + self.current = a.get("id") + form = a.get("form", self.current) + if tag in ("input", "select") and form and a.get("name") and "disabled" not in a: + fields = self.forms.setdefault(form, {}) + if tag == "select": + self.select = (form, a["name"]) + elif a.get("type") not in ("checkbox", "radio") or "checked" in a: + fields[a["name"]] = a.get("value", "") + if tag == "option" and self.select: + form, name = self.select + if "selected" in a or name not in self.forms[form]: + self.forms[form][name] = a.get("value", "") + + def handle_endtag(self, tag): + if tag == "form": + self.current = None + if tag == "select": + self.select = None + + +class Client: + def __init__(self, host): + deployment = json.loads(kubectl("get", "deployment", "pageswiki", "-o", "json")) + container = deployment["spec"]["template"]["spec"]["containers"][0] + if container["image"] != IMAGE: + raise RuntimeError("Unexpected exhibition deployment image") + secret = json.loads(kubectl("get", "secret", "pageswiki-exhibition-app", "-o", "json")) + self.password = base64.b64decode(secret["data"]["owner-password"]).decode() + self.host, self.token = host, None + self.opener = urllib.request.build_opener(urllib.request.ProxyHandler({}), NoRedirect()) + + def request(self, method, path, data=None, content_type=None, headers=None, expected=(200,)): + if not path.startswith("/") or path.startswith("//"): + raise ValueError("Only origin-relative paths allowed") + h = {"Host": self.host, "Origin": "http://" + self.host} + if self.token: + h["Authorization"] = "Bearer " + self.token + if content_type: + h["Content-Type"] = content_type + h.update(headers or {}) + req = urllib.request.Request("http://127.0.0.1:18381" + urllib.parse.quote(path, safe="/%?=&:"), data=data, headers=h, method=method) + try: + response = self.opener.open(req, timeout=45) + except urllib.error.HTTPError as error: + response = error + body = response.read() + if response.code not in expected: + # Never print credentials, login bodies, or full config documents. + detail = "" + if path.startswith("/_/api/v1/import/"): + try: + detail = ": " + str(json.loads(body).get("error", ""))[:300] + except (ValueError, AttributeError): + pass + raise RuntimeError(f"{method} {path}: HTTP {response.code}{detail}") + return response.code, response.headers, body + + def json(self, method, path, value=None, expected=(200,)): + body = None if value is None else json.dumps(value).encode() + _, _, result = self.request(method, path, body, "application/json", expected=expected) + return json.loads(result) + + def form(self, path, value, expected=(302, 303)): + response = self.request("POST", path, urllib.parse.urlencode(value).encode(), "application/x-www-form-urlencoded", expected=expected) + if not response[1].get("Location", "").startswith("/-/sys/config"): + raise RuntimeError("Unexpected configuration redirect") + return response + + def login(self): + _, _, page = self.request("GET", "/_/auth/login") + fields = {"username": "exhibition-admin", "password": self.password, "display_name": "展示管理者", "email": ""} + action = "login" + if b'name="bootstrap_token"' in page: + logs = kubectl("logs", "deployment/pageswiki", "-c", "pageswiki", "--tail=200").decode() + tokens = re.findall(r"AUTH BOOTSTRAP TOKEN domain=\S+ token=(\S+)", logs) + if len(tokens) != 1: + raise RuntimeError("Expected exactly one new exhibition bootstrap token") + fields["bootstrap_token"] = tokens[0] + action = "setup" + _, _, body = self.request("POST", "/_/auth/" + action, urllib.parse.urlencode(fields).encode(), "application/x-www-form-urlencoded", {"Accept": "application/json"}) + self.token = json.loads(body)["access_token"] + print("Exhibition owner authenticated; credentials not displayed.") + + def configure(self): + _, _, body = self.request("GET", "/-/sys/config?panel=campuses") + forms = Forms() + forms.feed(body.decode()) + campuses = [v for k, v in forms.forms.items() if k.startswith("campus-update-")] + domains = [v for k, v in forms.forms.items() if k.startswith("domain-update-")] + if len(campuses) != 1 or len(domains) != 1: + raise RuntimeError("Only a fresh single-campus single-domain exhibition is supported") + domain, campus = domains[0], campuses[0] + if campus["campus_fqdn"] not in ("localhost", "pages.jsb.anya.jp", "wiki.pages.jisaba.sh", EXHIBITION_HOST): + raise RuntimeError("Unexpected campus host") + domain.update(domain_title="PagesWiki 展示図書館", domain_enabled="1", domain_placement="local") + self.form("/-/sys/config", domain) + campus.update(campus_title="PagesWiki 展示キャンパス", campus_default_lang="ja", campus_fqdn=EXHIBITION_HOST, campus_enabled="1") + self.form("/-/sys/config", campus) + self.host = EXHIBITION_HOST + self.request("GET", "/-/sys/config") + print("Exhibition FQDN and Japanese titles configured.") + + def update_host(self): + """Change only the existing exhibition campus FQDN, preserving its data.""" + _, _, body = self.request("GET", "/-/sys/config?panel=campuses") + forms = Forms() + forms.feed(body.decode()) + campuses = [v for k, v in forms.forms.items() if k.startswith("campus-update-")] + domains = [v for k, v in forms.forms.items() if k.startswith("domain-update-")] + if len(campuses) != 1 or len(domains) != 1: + raise RuntimeError("Expected one existing exhibition campus and domain") + campus = campuses[0] + if campus.get("campus_fqdn") not in ("pages.jsb.anya.jp", "wiki.pages.jisaba.sh", EXHIBITION_HOST): + raise RuntimeError("Unexpected campus host; no change made") + if domains[0].get("domain_host", "").strip(): + raise RuntimeError("Expected default domain with empty hostname; no change made") + campus["campus_fqdn"] = EXHIBITION_HOST + self.form("/-/sys/config", campus) + self.host = EXHIBITION_HOST + self.request("GET", "/-/sys/config?panel=campuses") + print("Exhibition campus FQDN updated to " + EXHIBITION_HOST) + + def wiki(self, folder): + _, _, listing = self.request("GET", "/v/import") + sessions = re.findall(r'href="(/v/import/[a-f0-9-]+)"[^>]*>pageswiki-exhibition-demo.zip<', listing.decode()) + if len(sessions) > 1: + raise RuntimeError("Multiple exhibition import sessions; inspect before continuing") + if sessions: + location = sessions[0] + else: + boundary = "pageswiki-demo-" + uuid.uuid4().hex + data = (f"--{boundary}\r\nContent-Disposition: form-data; name=\"target_prefix\"\r\n\r\n/exhibition-demo\r\n" + f"--{boundary}\r\nContent-Disposition: form-data; name=\"archive\"; filename=\"pageswiki-exhibition-demo.zip\"\r\nContent-Type: application/zip\r\n\r\n").encode() + data += (folder / "wiki.zip").read_bytes() + f"\r\n--{boundary}--\r\n".encode() + _, headers, _ = self.request("POST", "/v/import", data, "multipart/form-data; boundary=" + boundary, expected=(303,)) + location = headers["Location"] + for _ in range(30): + _, _, body = self.request("GET", location) + html = body.decode() + status = re.search(r"
([^<]+)", html).group(1) + if status in ("ready", "completed", "failed"): + break + time.sleep(1) + if status == "completed": + print("Wiki import already completed.") + return + if status != "ready": + raise RuntimeError("Wiki import status: " + status) + rows = re.findall(r'(.*?)', html, re.S) + if len(rows) != 27: + raise RuntimeError("Expected exactly 27 archive entries") + items = [] + for sequence, row in rows: + from html import unescape + target = unescape(re.search(r'data-field="target_path" value="([^"]+)"', row).group(1)) + if not target.startswith("/exhibition-demo/"): + raise RuntimeError("Import target escaped exhibition prefix") + # City identifiers are ASCII; Japanese labels are titles. Create + # the exact directory boundaries separately via the City API. + items.append(dict(sequence=int(sequence), selected=True, target_path=target, quartier="", street="", spot="")) + api = "/_/api/v1/import/" + location.rsplit("/", 1)[1] + self.json("PATCH", api, {"items": items}) + self.json("POST", api, {"conflict": "skip"}, expected=(202,)) + print("Wiki import queued: 26 pages and one CSV; conflict=skip.") + + def organizers(self, folder): + calendars = self.json("GET", CAL + "calendars") + # Only this newly created exhibition account's synthetic collection. + found = [c for c in calendars["calendars"] if c["pretty_name"] == "exhibition-demo"] + if len(found) > 1: + raise RuntimeError("Duplicate exhibition calendars") + calendar = found[0] if found else self.json("POST", CAL + "calendars", {"name": "展示の予定", "pretty_name": "exhibition-demo"}, expected=(201,)) + if calendar.get("source"): + raise RuntimeError("External calendar is never used for exhibition seeding") + task_id = str(uuid.uuid5(uuid.NAMESPACE_URL, "https://example.invalid/pageswiki-exhibition/task-list")) + task_path = DAV + task_id + "/" + status, _, _ = self.request("PROPFIND", task_path, headers={"Depth": "0"}, expected=(207, 404)) + if status == 404: + xml = '展示の準備' + self.request("MKCALENDAR", task_path, xml.encode(), "application/xml", expected=(201,)) + card_path = "/_/api/v1/carddav/" + calendars["actor"] + "/contacts/" + for directory, prefix, media in (("events", DAV + calendar["id"] + "/", "text/calendar"), ("tasks", task_path, "text/calendar"), ("contacts", card_path, "text/vcard")): + created, skipped = 0, 0 + for file in sorted((folder / directory).iterdir()): + name = "exhibition-demo-" + file.name + status, _, _ = self.request("PUT", prefix + name, file.read_bytes(), media, {"If-None-Match": "*"}, expected=(201, 412)) + created += status == 201 + skipped += status == 412 + print(f"{directory}: created={created}, existing={skipped}; no overwrite.") + self.json("PUT", CAL + "preferences", {"calendars": [calendar["id"]]}) + + def city_labels(self): + # URL reconciliation keeps the dedicated prefix as the top district. + # Preserve that topology; change only labels within this dataset. + model = self.json("GET", "/_/api/v1/city/map") + desired = [] + for q in model.get("quartiers") or []: + if q["path_prefix"] != "/exhibition-demo": + continue + desired.append(("quartier", q, "展示図書館")) + for street in q.get("streets") or []: + desired.append(("street", street, street["path_prefix"].rsplit("/", 1)[-1])) + for spot in street.get("spots") or []: + label = spot["path_prefix"].rsplit("/", 1)[-1] + desired.append(("spot", spot, "案内ページ" if label == "_undefined" else label)) + for kind, node, title in desired: + if not node["path_prefix"].startswith("/exhibition-demo") or node["title"] == title: + continue + current = self.json("GET", "/_/api/v1/city/map") + endpoint = "spots" if kind == "spot" else "zones" + self.json("POST", f"/_/api/v1/city/{endpoint}/{node['uuid']}/title", {"kind": kind, "title": title, "base_version": current["version"]}) + print("Generated exhibition City topology retained; Japanese display labels applied.") + + def verify(self, folder): + for path in ("/health", "/v/browser", "/v/city", "/v/plan", "/v/plan/tasks", "/v/plan/contacts", "/v/plan/dashboard"): + status, _, _ = self.request("GET", path, expected=(200,)) + print(f"{path}: {status}") + manifest = json.loads((folder / "manifest.json").read_text()) + checked = 0 + for name in manifest["files"]: + if not name.startswith("wiki/"): + continue + path = name[5:] + if path.endswith(".md"): + path = path[:-3] + self.request("GET", "/exhibition-demo/" + path) + checked += 1 + print(f"Wiki documents readable after import: {checked}") + calendars = self.json("GET", CAL + "calendars") + calendar = next(c for c in calendars["calendars"] if c["pretty_name"] == "exhibition-demo" and not c.get("source")) + task_id = str(uuid.uuid5(uuid.NAMESPACE_URL, "https://example.invalid/pageswiki-exhibition/task-list")) + for directory, prefix in (("events", DAV + calendar["id"] + "/"), ("tasks", DAV + task_id + "/"), ("contacts", "/_/api/v1/carddav/" + calendars["actor"] + "/contacts/")): + count = 0 + for file in sorted((folder / directory).iterdir()): + _, headers, body = self.request("GET", prefix + "exhibition-demo-" + file.name) + expected_uid = file.stem + "@example.invalid" + if expected_uid.encode() not in body or not headers.get("ETag"): + raise RuntimeError("Synthetic DAV resource failed UID/ETag verification") + count += 1 + print(f"{directory}: {count} synthetic resources verified with ETags.") + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("step", choices=("configure", "set-host", "wiki", "organizers", "city-labels", "verify")) + parser.add_argument("--host", choices=("localhost", "pages.jsb.anya.jp", "wiki.pages.jisaba.sh", EXHIBITION_HOST), default=EXHIBITION_HOST) + parser.add_argument("--data", type=Path, default=Path("/tmp/pageswiki-exhibition-demo")) + args = parser.parse_args() + if args.step in ("wiki", "organizers"): + manifest = json.loads((args.data / "manifest.json").read_text()) + if manifest.get("dataset_id") != "pageswiki-exhibition-fiction-v1" or manifest.get("target_prefix") != "/exhibition-demo": + raise RuntimeError("Only generated exhibition fixtures are accepted") + import hashlib + for name, digest in manifest["files"].items(): + if Path(name).is_absolute() or ".." in Path(name).parts or hashlib.sha256((args.data / name).read_bytes()).hexdigest() != digest: + raise RuntimeError("Modified or unsafe fixture") + client = Client(args.host) + client.login() + if args.step == "configure": + client.configure() + elif args.step == "set-host": + client.update_host() + elif args.step == "wiki": + client.wiki(args.data) + elif args.step == "organizers": + client.organizers(args.data) + elif args.step == "city-labels": + client.city_labels() + else: + client.verify(args.data) + + +if __name__ == "__main__": + main() diff --git a/tools/exhibition-demo/test_generate.py b/tools/exhibition-demo/test_generate.py new file mode 100644 index 0000000..2ee6bc4 --- /dev/null +++ b/tools/exhibition-demo/test_generate.py @@ -0,0 +1,127 @@ +import importlib.util +from datetime import date, datetime, timedelta +import io +import json +from pathlib import Path +import re +import tempfile +import unittest +import zipfile + +spec = importlib.util.spec_from_file_location("exhibition_generate", Path(__file__).with_name("generate.py")) +demo = importlib.util.module_from_spec(spec) +spec.loader.exec_module(demo) + + +class DemoTests(unittest.TestCase): + def setUp(self): + self.base = date(2026, 11, 15) + self.files = demo.build(self.base) + + def test_reproducible_archive_and_hierarchy(self): + self.assertEqual(self.files, demo.build(self.base)) + with zipfile.ZipFile(io.BytesIO(self.files["wiki.zip"])) as archive: + pages = [name for name in archive.namelist() if name.endswith(".md")] + self.assertEqual(len(pages), 26) + self.assertEqual(len(archive.namelist()), 27) + self.assertEqual(max(len(Path(name).parts) for name in pages), 4) + self.assertEqual(archive.testzip(), None) + targets = {"/exhibition-demo/" + (name[:-3] if name.endswith(".md") else name) for name in archive.namelist()} + for name in archive.namelist(): + self.assertFalse(name.startswith("/")) + self.assertNotIn("..", Path(name).parts) + self.assertEqual(archive.read(name), self.files["wiki/" + name]) + for name in pages: + content = archive.read(name).decode() + self.assertIn("{{children:", content) + self.assertIn("すべて架空", content) + for target in re.findall(r"\]\(([^)]+)\)", content): + self.assertIn(target, targets) + + def test_dates_and_stable_identity(self): + before = json.loads(self.files["fixtures.json"]) + after = json.loads(demo.build(self.base + timedelta(days=20))["fixtures.json"]) + self.assertEqual(len(before["tasks"]), 8) + self.assertEqual(len(before["events"]), 6) + self.assertEqual(len(before["contacts"]), 6) + for first, second in zip(before["tasks"], after["tasks"]): + self.assertEqual(first["uid"], second["uid"]) + self.assertEqual(date.fromisoformat(second["due_date"]) - date.fromisoformat(first["due_date"]), timedelta(days=20)) + for first, second in zip(before["events"], after["events"]): + self.assertEqual(first["uid"], second["uid"]) + start, end = datetime.fromisoformat(first["start"]), datetime.fromisoformat(first["end"]) + self.assertEqual(start.utcoffset(), timedelta(hours=9)) + self.assertGreater(end, start) + self.assertEqual(datetime.fromisoformat(second["start"]) - start, timedelta(days=20)) + for contact in before["contacts"]: + self.assertTrue(contact["email"].endswith("@example.invalid")) + + def test_dav_resources_and_folding(self): + for name, data in self.files.items(): + if not name.endswith((".ics", ".vcf")): + continue + self.assertTrue(data.endswith(b"\r\n")) + for line in data.split(b"\r\n"): + self.assertLessEqual(len(line), 75) + line.decode("utf-8") + unfolded = data.decode().replace("\r\n ", "") + self.assertEqual(len(re.findall(r"^BEGIN:", unfolded, re.M)), len(re.findall(r"^END:", unfolded, re.M))) + if name.startswith("tasks/"): + self.assertEqual(unfolded.count("BEGIN:VTODO"), 1) + self.assertIn("DUE;VALUE=DATE:", unfolded) + if name.startswith("events/"): + self.assertEqual(unfolded.count("BEGIN:VEVENT"), 1) + self.assertRegex(unfolded, r"DTSTART:\d{8}T\d{6}Z") + if name.endswith(".vcf"): + self.assertIn("VERSION:3.0", unfolded) + self.assertIn("@example.invalid", unfolded) + + def test_owned_output_rebuild_and_tamper_refusal(self): + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) / "demo" + demo.write_output(root, self.files) + demo.write_output(root, self.files) + future = demo.build(self.base + timedelta(days=1)) + demo.write_output(root, future) + self.assertEqual((root / "wiki.zip").read_bytes(), future["wiki.zip"]) + (root / "fixtures.json").write_text("user change") + with self.assertRaisesRegex(ValueError, "modified"): + demo.write_output(root, self.files) + self.assertEqual((root / "fixtures.json").read_text(), "user change") + + def test_foreign_files_and_symlinks_refused(self): + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) / "demo" + root.mkdir() + (root / "keep.txt").write_text("keep") + with self.assertRaisesRegex(ValueError, "not an owned"): + demo.write_output(root, self.files) + self.assertEqual((root / "keep.txt").read_text(), "keep") + alias = Path(tmp) / "alias" + alias.symlink_to(root, target_is_directory=True) + with self.assertRaisesRegex(ValueError, "symlinks"): + demo.write_output(alias, self.files) + clean = Path(tmp) / "clean" + demo.write_output(clean, self.files) + (clean / "foreign.txt").write_text("keep") + with self.assertRaisesRegex(ValueError, "unrelated"): + demo.write_output(clean, self.files) + + def test_manifest_hashes_and_prefix(self): + manifest = json.loads(self.files[demo.MARKER]) + self.assertEqual(manifest["page_count"], 26) + for name, digest in manifest["files"].items(): + self.assertEqual(demo.sha(self.files[name]), digest) + with self.assertRaises(ValueError): + demo.build(self.base, "/") + with self.assertRaises(ValueError): + demo.build(self.base, "/../production") + with self.assertRaises(ValueError): + demo.build(self.base, "https://example.invalid") + alternate = demo.build(self.base, "/demo/autumn") + self.assertIn(b"/demo/autumn/", alternate["wiki/展示案内.md"]) + self.assertNotIn(b"/exhibition-demo/", alternate["wiki/展示案内.md"]) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/exhibition-demo/test_seed.py b/tools/exhibition-demo/test_seed.py new file mode 100644 index 0000000..a50d408 --- /dev/null +++ b/tools/exhibition-demo/test_seed.py @@ -0,0 +1,32 @@ +import importlib.util +from pathlib import Path +import unittest + +spec = importlib.util.spec_from_file_location("exhibition_seed", Path(__file__).with_name("seed.py")) +seed = importlib.util.module_from_spec(spec) +spec.loader.exec_module(seed) + + +class SeedSafetyTests(unittest.TestCase): + def test_origin_relative_only(self): + client = seed.Client.__new__(seed.Client) + for path in ("https://pages.anya.jp/", "//pages.anya.jp/", "relative"): + with self.assertRaises(ValueError): + client.request("GET", path) + + def test_redirects_not_followed(self): + self.assertIsNone(seed.NoRedirect().redirect_request(None, None, 302, "", {}, "https://example.invalid/")) + + def test_external_form_controls_and_disabled_fields(self): + forms = seed.Forms() + forms.feed('''
+ + + + + ''') + self.assertEqual(forms.forms, {"campus-update-1": {"campus_id": "1", "campus_enabled": "1", "mode": "standalone"}}) + + +if __name__ == "__main__": + unittest.main()