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.
This commit is contained in:
1 parent
1fd2de4c6b
commit
4a863fe63c
17 files changed
+2039
No files matched your search
@@ -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、公開経路の成立は保証しない。
|
||||
@@ -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}]
|
||||
@@ -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}]
|
||||
@@ -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` です。
|
||||
@@ -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"}
|
||||
]
|
||||
}
|
||||
@@ -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
|
||||
@@ -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 <<SQL
|
||||
CREATE ROLE pageswiki LOGIN PASSWORD '${APP_DB_PASSWORD}' NOSUPERUSER NOCREATEDB NOCREATEROLE;
|
||||
CREATE DATABASE pageswiki OWNER pageswiki;
|
||||
SQL
|
||||
---
|
||||
apiVersion: apps/v1
|
||||
kind: Deployment
|
||||
metadata:
|
||||
name: pageswiki-postgres
|
||||
spec:
|
||||
replicas: 1
|
||||
strategy: {type: Recreate}
|
||||
selector:
|
||||
matchLabels: {app: pageswiki-postgres}
|
||||
template:
|
||||
metadata:
|
||||
labels: {app: pageswiki-postgres}
|
||||
spec:
|
||||
automountServiceAccountToken: false
|
||||
terminationGracePeriodSeconds: 90
|
||||
securityContext:
|
||||
seccompProfile: {type: RuntimeDefault}
|
||||
initContainers:
|
||||
- name: initialize-storage
|
||||
image: python@sha256:9ef1a599f863231c3d91e941389bfdc4a2d6070557243d54df1a4e57015b960e
|
||||
command: [python3, /scripts/storage.py]
|
||||
securityContext:
|
||||
runAsUser: 0
|
||||
runAsGroup: 0
|
||||
allowPrivilegeEscalation: false
|
||||
readOnlyRootFilesystem: true
|
||||
capabilities: {drop: [ALL], add: [CHOWN, DAC_OVERRIDE]}
|
||||
resources:
|
||||
requests: {cpu: 50m, memory: 32Mi}
|
||||
limits: {cpu: 250m, memory: 128Mi}
|
||||
volumeMounts:
|
||||
- {name: data, mountPath: /volume}
|
||||
- {name: scripts, mountPath: /scripts, readOnly: true}
|
||||
- {name: certificates, mountPath: /cert-source, readOnly: true}
|
||||
- {name: tls, mountPath: /tls}
|
||||
- {name: socket, mountPath: /pgsocket}
|
||||
containers:
|
||||
- name: postgres
|
||||
image: postgres@sha256:005c5c37db96c1e6652a79ea31f9886402fba81ac95dc2db897739121dd7f8f2
|
||||
args:
|
||||
- postgres
|
||||
- -c
|
||||
- ssl=on
|
||||
- -c
|
||||
- ssl_cert_file=/tls/server.crt
|
||||
- -c
|
||||
- ssl_key_file=/tls/server.key
|
||||
- -c
|
||||
- shared_buffers=128MB
|
||||
- -c
|
||||
- max_connections=40
|
||||
env:
|
||||
- {name: PGDATA, value: /var/lib/postgresql/data/pgdata}
|
||||
- name: POSTGRES_PASSWORD
|
||||
valueFrom: {secretKeyRef: {name: pageswiki-exhibition-db, key: admin-password}}
|
||||
- name: APP_DB_PASSWORD
|
||||
valueFrom: {secretKeyRef: {name: pageswiki-exhibition-db, key: app-password}}
|
||||
- {name: POSTGRES_INITDB_ARGS, value: '--auth-host=scram-sha-256'}
|
||||
ports: [{name: postgres, containerPort: 5432}]
|
||||
securityContext:
|
||||
runAsNonRoot: true
|
||||
runAsUser: 70
|
||||
runAsGroup: 70
|
||||
allowPrivilegeEscalation: false
|
||||
capabilities: {drop: [ALL]}
|
||||
resources:
|
||||
requests: {cpu: 250m, memory: 256Mi}
|
||||
limits: {cpu: '1', memory: 1Gi}
|
||||
startupProbe:
|
||||
exec: {command: [pg_isready, -U, postgres, -d, postgres]}
|
||||
periodSeconds: 5
|
||||
failureThreshold: 60
|
||||
readinessProbe:
|
||||
exec: {command: [pg_isready, -U, postgres, -d, postgres]}
|
||||
periodSeconds: 5
|
||||
volumeMounts:
|
||||
- {name: data, mountPath: /var/lib/postgresql/data, subPath: pageswiki-exhibit-v018/postgres}
|
||||
- {name: scripts, mountPath: /docker-entrypoint-initdb.d/10-app.sh, subPath: 10-app.sh, readOnly: true}
|
||||
- {name: tls, mountPath: /tls, readOnly: true}
|
||||
- {name: socket, mountPath: /var/run/postgresql}
|
||||
volumes:
|
||||
- name: data
|
||||
persistentVolumeClaim: {claimName: pageswiki-data}
|
||||
- name: scripts
|
||||
configMap: {name: pageswiki-exhibition-init}
|
||||
- name: certificates
|
||||
secret: {secretName: pageswiki-exhibition-tls, defaultMode: 0400}
|
||||
- name: tls
|
||||
emptyDir: {}
|
||||
- name: socket
|
||||
emptyDir: {}
|
||||
---
|
||||
apiVersion: v1
|
||||
kind: Service
|
||||
metadata: {name: pageswiki-postgres}
|
||||
spec:
|
||||
selector: {app: pageswiki-postgres}
|
||||
ports: [{name: postgres, port: 5432, targetPort: postgres}]
|
||||
---
|
||||
apiVersion: networking.k8s.io/v1
|
||||
kind: NetworkPolicy
|
||||
metadata: {name: pageswiki-postgres}
|
||||
spec:
|
||||
podSelector:
|
||||
matchLabels: {app: pageswiki-postgres}
|
||||
policyTypes: [Ingress]
|
||||
ingress:
|
||||
- from:
|
||||
- podSelector:
|
||||
matchLabels: {pageswiki-db-client: 'true'}
|
||||
ports: [{protocol: TCP, port: 5432}]
|
||||
@@ -0,0 +1,103 @@
|
||||
# Isolated root initialization followed by a non-root storage test.
|
||||
# Does not inspect or change existing data or the PVC root permissions.
|
||||
apiVersion: batch/v1
|
||||
kind: Job
|
||||
metadata:
|
||||
name: pageswiki-root-storage-check
|
||||
spec:
|
||||
backoffLimit: 0
|
||||
activeDeadlineSeconds: 120
|
||||
ttlSecondsAfterFinished: 3600
|
||||
template:
|
||||
spec:
|
||||
restartPolicy: Never
|
||||
automountServiceAccountToken: false
|
||||
securityContext:
|
||||
runAsUser: 0
|
||||
runAsGroup: 0
|
||||
seccompProfile:
|
||||
type: RuntimeDefault
|
||||
containers:
|
||||
- name: check
|
||||
image: python:3.13-alpine
|
||||
command: [python3, -u, -c]
|
||||
args:
|
||||
- |
|
||||
import hashlib, json, os, pathlib, tempfile
|
||||
mount = None
|
||||
for line in pathlib.Path('/proc/self/mountinfo').read_text().splitlines():
|
||||
before, after = line.split(' - ', 1)
|
||||
fields, detail = before.split(), after.split()
|
||||
if fields[4] == '/check':
|
||||
mount = (detail[0], set(fields[5].split(',')) | set(detail[2].split(',')))
|
||||
if mount is None:
|
||||
raise RuntimeError('PVC mount not found')
|
||||
fs, options = mount
|
||||
if fs in ('nfs', 'nfs4') and ('hard' not in options or options & {'soft', 'softerr', 'softreval'}):
|
||||
raise RuntimeError('NFS hard mount required')
|
||||
root = pathlib.Path(tempfile.mkdtemp(prefix='.pageswiki-root-check-', dir='/check'))
|
||||
print(json.dumps({'stage': 'created', 'directory': root.name, 'filesystem': fs, 'hard_mount': 'hard' in options}))
|
||||
try:
|
||||
os.chown(root, 10001, 10001)
|
||||
pid = os.fork()
|
||||
if pid == 0:
|
||||
try:
|
||||
os.setgroups([])
|
||||
os.setgid(10001)
|
||||
os.setuid(10001)
|
||||
directory = os.open(root, os.O_RDONLY | os.O_DIRECTORY)
|
||||
payload = b'PagesWiki isolated non-root storage verification\n'
|
||||
try:
|
||||
with (root / 'source').open('xb') as f:
|
||||
f.write(payload)
|
||||
f.flush()
|
||||
os.fsync(f.fileno())
|
||||
os.link(root / 'source', root / 'published')
|
||||
try:
|
||||
os.link(root / 'source', root / 'published')
|
||||
except FileExistsError:
|
||||
pass
|
||||
else:
|
||||
raise RuntimeError('no-replace publication failed')
|
||||
os.rename(root / 'source', root / 'renamed')
|
||||
os.fsync(directory)
|
||||
for name in ('published', 'renamed'):
|
||||
if hashlib.sha256((root / name).read_bytes()).digest() != hashlib.sha256(payload).digest():
|
||||
raise RuntimeError('readback mismatch')
|
||||
print(json.dumps({'result': 'passed', 'process_uid': os.getuid(), 'process_gid': os.getgid(), 'server_durability': 'not verified'}))
|
||||
finally:
|
||||
for name in ('source', 'published', 'renamed'):
|
||||
(root / name).unlink(missing_ok=True)
|
||||
os.fsync(directory)
|
||||
os.close(directory)
|
||||
except BaseException:
|
||||
import traceback
|
||||
traceback.print_exc()
|
||||
os._exit(1)
|
||||
os._exit(0)
|
||||
_, status = os.waitpid(pid, 0)
|
||||
if os.waitstatus_to_exitcode(status) != 0:
|
||||
raise RuntimeError('non-root storage verification failed')
|
||||
finally:
|
||||
# Only remove the empty directory created by this process.
|
||||
root.rmdir()
|
||||
securityContext:
|
||||
allowPrivilegeEscalation: false
|
||||
readOnlyRootFilesystem: true
|
||||
capabilities:
|
||||
drop: [ALL]
|
||||
add: [CHOWN, SETUID, SETGID]
|
||||
resources:
|
||||
requests:
|
||||
cpu: 100m
|
||||
memory: 64Mi
|
||||
limits:
|
||||
cpu: 250m
|
||||
memory: 128Mi
|
||||
volumeMounts:
|
||||
- name: data
|
||||
mountPath: /check
|
||||
volumes:
|
||||
- name: data
|
||||
persistentVolumeClaim:
|
||||
claimName: pageswiki-data
|
||||
@@ -0,0 +1,90 @@
|
||||
# Run only in the assigned exhibit-anya namespace after release verification.
|
||||
# kubectl -n exhibit-anya apply --dry-run=server -f storage-check.yaml.example
|
||||
# No database or existing application data is opened by this job.
|
||||
apiVersion: batch/v1
|
||||
kind: Job
|
||||
metadata:
|
||||
name: pageswiki-storage-check
|
||||
spec:
|
||||
backoffLimit: 0
|
||||
activeDeadlineSeconds: 120
|
||||
ttlSecondsAfterFinished: 3600
|
||||
template:
|
||||
spec:
|
||||
restartPolicy: Never
|
||||
automountServiceAccountToken: false
|
||||
securityContext:
|
||||
runAsNonRoot: true
|
||||
runAsUser: 10001
|
||||
runAsGroup: 10001
|
||||
seccompProfile:
|
||||
type: RuntimeDefault
|
||||
containers:
|
||||
- name: check
|
||||
image: python:3.13-alpine
|
||||
imagePullPolicy: IfNotPresent
|
||||
command: [python3, -c]
|
||||
args:
|
||||
- |
|
||||
import hashlib, json, os, pathlib, tempfile
|
||||
mount = None
|
||||
for line in pathlib.Path('/proc/self/mountinfo').read_text().splitlines():
|
||||
before, after = line.split(' - ', 1)
|
||||
fields, detail = before.split(), after.split()
|
||||
if fields[4] == '/check':
|
||||
mount = (detail[0], set(fields[5].split(',')) | set(detail[2].split(',')))
|
||||
if mount is None:
|
||||
raise RuntimeError('PVC mount was not found')
|
||||
fs, options = mount
|
||||
if fs in ('nfs', 'nfs4') and ('hard' not in options or options & {'soft', 'softerr', 'softreval'}):
|
||||
raise RuntimeError('NFS hard mount required; unsafe or unknown options')
|
||||
root = pathlib.Path(tempfile.mkdtemp(prefix='.pageswiki-storage-check-', dir='/check'))
|
||||
directory = os.open(root, os.O_RDONLY | os.O_DIRECTORY)
|
||||
payload = b'PagesWiki isolated storage verification\n'
|
||||
try:
|
||||
with (root / 'source').open('xb') as f:
|
||||
f.write(payload)
|
||||
f.flush()
|
||||
os.fsync(f.fileno())
|
||||
os.link(root / 'source', root / 'published')
|
||||
try:
|
||||
os.link(root / 'source', root / 'published')
|
||||
except FileExistsError:
|
||||
pass
|
||||
else:
|
||||
raise RuntimeError('link publication replaced an existing entry')
|
||||
os.fsync(directory)
|
||||
os.rename(root / 'source', root / 'renamed')
|
||||
os.fsync(directory)
|
||||
expected = hashlib.sha256(payload).digest()
|
||||
for name in ('published', 'renamed'):
|
||||
if hashlib.sha256((root / name).read_bytes()).digest() != expected:
|
||||
raise RuntimeError('content mismatch')
|
||||
print(json.dumps({'result': 'passed', 'filesystem': fs,
|
||||
'hard_mount': 'hard' in options,
|
||||
'server_durability': 'not verified by this client-side test'}))
|
||||
finally:
|
||||
for name in ('source', 'published', 'renamed'):
|
||||
(root / name).unlink(missing_ok=True)
|
||||
os.fsync(directory)
|
||||
os.close(directory)
|
||||
root.rmdir()
|
||||
resources:
|
||||
requests:
|
||||
cpu: 100m
|
||||
memory: 64Mi
|
||||
limits:
|
||||
cpu: 250m
|
||||
memory: 128Mi
|
||||
securityContext:
|
||||
allowPrivilegeEscalation: false
|
||||
readOnlyRootFilesystem: true
|
||||
capabilities:
|
||||
drop: [ALL]
|
||||
volumeMounts:
|
||||
- name: data
|
||||
mountPath: /check
|
||||
volumes:
|
||||
- name: data
|
||||
persistentVolumeClaim:
|
||||
claimName: pageswiki-data
|
||||
@@ -0,0 +1,431 @@
|
||||
# 展示用PagesWikiのKubernetes配置とDNS認証
|
||||
|
||||
## 記録の位置づけ(2026-11-30整理)
|
||||
|
||||
展示は完了し、利用者から成功の報告を受けている。以下は準備・配置時点の記録で、
|
||||
途中の疎通失敗や未確認項目も経緯として残す。現在の障害・稼働状態を示すものではない。
|
||||
今回の整理ではクラスタ・公開URLへ接続せず、再配置・データ投入・Secret操作も行っていない。
|
||||
|
||||
最後に指定された入口は `https://pages.anya.jisaba.sh/`。初期の
|
||||
`pages.jsb.anya.jp`/Cloudflare DNS-01案やHTTP公開案は採用済み設定ではない。
|
||||
[展示ファイル一覧](../../deploy/kubernetes/exhibition/README.md)から用途別に参照する。
|
||||
再利用時は当日の権限・保存先・証明書期限・イメージを確認し、ディレクトリ全体を一括applyしない。
|
||||
|
||||
## 最終指定の入口:HTTPS・pages.anya.jisaba.sh(当時の確認記録)
|
||||
|
||||
2026-11-15、利用者指定により入口を `https://pages.anya.jisaba.sh/` に再変更した。
|
||||
展示キャンパスのFQDNを通常の設定APIで変更し、既存のドメインUUID・空ホスト指定・データを維持。
|
||||
新しいHostでlocalhost限定port-forward越しのログイン、27文書、8タスク、6予定、6連絡先の
|
||||
UID/ETagを確認済み。Serviceは引き続きHTTP port 80、アプリは3000。公開TLS終端はNOC管理。
|
||||
|
||||
この端末からDNS A `202.226.7.202` とHTTP 301による同一ホストHTTPSへの転送を確認した。
|
||||
HTTPSは `/` と `/health` の両方で `Connection reset by peer`(curl exit 35)。
|
||||
証明書検証の成功・公開ログイン・ブラウザ描画は未確認で、公開接続へ資格情報は送っていない。
|
||||
TLS終端/経路/アクセス制御のどこが原因かは未確定。証明書検証を無効化して回避しない。
|
||||
以前の `*.pages.jisaba.sh` とは別のホスト階層なので、新FQDNのListener・Route・証明書が必要。
|
||||
PostgreSQL向けverified TLSは引き続き維持する。
|
||||
|
||||
## 旧公開案:HTTP・wiki.pages.jisaba.sh(上記で置換済み)
|
||||
|
||||
2026-11-15、利用者の確認により入口を `http://wiki.pages.jisaba.sh/` に変更した。
|
||||
NOCへ `*.pages.jisaba.sh` のHTTP・80番転送を依頼済み(利用者報告)。
|
||||
接続先は namespace `exhibit-anya`、Service `pageswiki`、port 80。
|
||||
ワイルドカードに含まれない `pages.jisaba.sh` 自体は入口に使わない。
|
||||
以下の `pages.jsb.anya.jp`・Cloudflare証明書の記述は旧案であり、現行の公開設定ではない。
|
||||
|
||||
既存キャンパスのFQDNだけを通常の設定APIで更新し、ドメインの空ホスト指定、UUID、
|
||||
文書・設定・ユーザーは保持した。localhost限定port-forward経由で新Host名によるログインと
|
||||
27文書、8タスク、6予定、6連絡先のUID/ETagを再確認した。外部カレンダーへはアクセスしていない。
|
||||
公開DNSと会場からのHTTP到達・ブラウザ描画は別の確認事項。
|
||||
HTTPRouteの参照権限はなく、NOC側の適用状況を直接確認できない。
|
||||
|
||||
公開HTTPではログイン資格情報・本文が暗号化されない。展示専用アカウント・合成データだけを使い、
|
||||
本番の認証・秘密情報は持ち込まない。Web Push等のsecure context必須機能は利用できない。
|
||||
これはブラウザ側の通信方針であり、アプリからPostgreSQLへのverified TLSは維持する。
|
||||
任意のサブドメインがPagesのサイトとして自動作成されるわけではない。追加する場合はDomainの登録が必要。
|
||||
|
||||
## 2026年11月15日の配置記録(FQDN変更前を含む)
|
||||
|
||||
以下の初期案よりも、[運営の最新公開手順](https://github.com/cniajp/jisabakan-exhibit/blob/main/docs/publishing.md)と
|
||||
[接続手順](https://github.com/cniajp/jisabakan-exhibit/blob/main/docs/omni-login.md)を優先する。
|
||||
今回の展示は `anya/` → `exhibit-anya` の GitOps 配置であり、Gateway・HTTPRoute・TLS は NOC 管理。
|
||||
この文書の Ingress・Certificate・公開用 LoadBalancer を参加者側で作る手順は適用しない。
|
||||
独自ドメイン `pages.jsb.anya.jp` と Cloudflare DNS-01 を希望する場合も、公開先・TLS の受渡しを NOC と調整する。
|
||||
|
||||
保存済みの別端末用 kubeconfig で読取り・Deployment 作成権限を確認した。
|
||||
`pageswiki-data` は `nfs-csi` の20Gi RWOで Bound、storage quotaの20Giを消費済み。
|
||||
PagesWikiとPostgreSQLをそれぞれ1 replicaで起動済み。requests上限はCPU 2、メモリ4Gi、limits.memoryは8Gi、PVC上限は5。
|
||||
SQLite WALをNFS上で動かさないため、PostgreSQL対応リリースを使って配置する。
|
||||
本番のデータ・鍵・外部カレンダーは展示へ持ち込まない。
|
||||
|
||||
v0.18.0 は通常テスト・PostgreSQL 17実DBテスト・4イメージの公開とrelease昇格が成功済み。
|
||||
アプリの固定イメージは `git.anya.jp/anya/pageswiki-app@sha256:a999fe16f11ef91dbdb9904c63bb43d9ec3caef93f77cc07b1fe4a80460f67f9`。
|
||||
展示用の26ページ・8タスク・6予定・6連絡先は[合成データ手順](../../deploy/kubernetes/exhibition/demo/README.md)で生成できる。
|
||||
通常のimport/API/DAV経路でWiki 26ページ、CSV 1件、タスク8件、予定6件、連絡先6件を投入済み。
|
||||
DBとアプリのPod再作成後も認証・27文書・20 DAVリソースのUID/ETagを確認した。
|
||||
公開FQDNのDNSは手元の名前解決では未登録。NOCのGateway/HTTPRoute/TLS設定と公開ブラウザ確認は残件。
|
||||
|
||||
PVC最上位はroot:root / 0755のまま保持し、承認されたroot初期化で新設した
|
||||
`pageswiki-exhibit-v018/wiki` を10001:10001、`postgres`を70:70として分離した。
|
||||
NFSv4のhard mount、非rootでのhard-link/no-replace・fsync・rename・読み戻しは隔離試験で成功。
|
||||
既存領域の再帰的なchownは行っていない。NFS server側の障害時永続性はこの試験では保証しない。
|
||||
root初期化にはPodSecurity restrictedの警告が出るが、現namespaceのadmissionは許可する。
|
||||
常駐プロセスは非root。クラスタのポリシー自体は変更していない。
|
||||
|
||||
配置済みのマニフェストは `deploy/kubernetes/exhibition/postgres.yaml` と `app.yaml`。
|
||||
今回はkubectlで直接適用しており、運営GitHubの `anya/` へのGitOps反映は未実施。
|
||||
`bootstrap.yaml` は一度限りの初期化用で、継続同期するディレクトリへ入れない。
|
||||
空のSQLiteはemptyDirで起動・停止し、verified TLSで全件importした。
|
||||
停止した合成SQLiteはアプリPVC内の `bootstrap-source/pages.db` に監査用として保存するが、通常起動では開かない。
|
||||
`import-complete.json` が完了記録。初期化Jobを削除・再作成して再移行しない。
|
||||
|
||||
Secretは `pageswiki-exhibition-app`、`pageswiki-exhibition-db`、`pageswiki-exhibition-tls`。
|
||||
新規生成した展示専用値のみを使い、public repositoryへは記録しない。
|
||||
PostgreSQLのサーバー証明書は90日、専用CAは180日で失効するため、長期展示では更新が必要。
|
||||
管理者名は `exhibition-admin`。パスワードはapp Secretの `owner-password` を管理端末で確認する。
|
||||
アプリのFQDN設定は `pages.jsb.anya.jp`。内部確認はlocalhost限定port-forwardとHostヘッダーで行う。
|
||||
|
||||
レジストリ `git.anya.jp` は当初IPv6のみでノードから到達できなかった。
|
||||
IPv4追加後にpullが成功し、release digestを固定して起動した。
|
||||
|
||||
公開までの残件:
|
||||
|
||||
- NOCに `exhibit-anya` のService `pageswiki`、HTTP port 80、全Path、希望ホスト `pages.jsb.anya.jp` を接続先として伝え、DNS・Gateway・TLSを調整する。管理画面はログイン必須であり、展示管理者パスワードを公開しない。
|
||||
- 公開HTTPSからのログイン・各ビューアの描画・操作をブラウザで確認する。現時点の確認はport-forward越しのHTTP/API検証。
|
||||
- 運営GitHubの `anya/` に通常運用のConfigMap・Deployment・Service・NetworkPolicyを移管する。Secretと一度限りのbootstrap Jobは含めず、既存PVCを削除する差分も作らない。GitHubのpush権限はOmni認証とは別に確認する。
|
||||
- NFS server側の永続化保証・保全方針はNOCと確認する。[PostgreSQLのNFS要件](https://www.postgresql.org/docs/17/creating-cluster.html#CREATING-CLUSTER-NFS)に従い、`fsync`は無効化しない。証明書の期限・更新と展示撤収時のSecret/PVCの扱いも決める。
|
||||
|
||||
以降は当初の一般手順として残す。保存と公開経路に関しては上記の実環境に合わせて読み替える。
|
||||
|
||||
運営のKubernetes Clusterを借りる方式Aを第一希望とし、展示用の独立したPagesWikiを1 replicaで配置する。公開名は `pages.jsb.anya.jp`。グローバルDNSに会場から到達できるローカルIPを登録し、Cloudflare DNS-01で取得した証明書をIngressへ設定する。
|
||||
|
||||
本書は実施手順であり、DNS登録・証明書発行・クラスタ操作はまだ実行していない。IP、Namespace、StorageClass、IngressClass、リソース上限は運営との相談後に確定する。本番データ・認証鍵・外部サービス資格情報は流用しない。
|
||||
|
||||
## 1 構成と役割
|
||||
|
||||
| 対象 | 方針 |
|
||||
| --- | --- |
|
||||
| 利用者の入口 | `https://pages.jsb.anya.jp/` |
|
||||
| 追加Domainの例 | `https://blog.pages.jsb.anya.jp/` |
|
||||
| 公開DNS | 入口のローカルIPv4をAへ登録。CloudflareはDNS only |
|
||||
| TLS証明書のSAN | `pages.jsb.anya.jp` と `*.pages.jsb.anya.jp` |
|
||||
| TLS終端 | 運営のIngress Controller等 |
|
||||
| PagesWiki本体 | 1 replica、HTTP 3000、`/data`をPVCへ保存 |
|
||||
| 初期の周辺機能 | code-server・Kroki・外部Campus等は追加せず、本体確認後に判断 |
|
||||
| 証明書の取得 | 自分の管理端末でCertbotとCloudflare pluginを使用 |
|
||||
| 更新 | 証明書更新とTLS Secret反映を一組で行う |
|
||||
|
||||
通信経路は、会場端末からIngressの443、Serviceの80、PagesWiki Podの3000、保存先PVCの順。DNSは入口の住所を知らせるだけで、ネットワーク到達性や経路を作らない。
|
||||
|
||||
DNS-01は公開DNSのTXTを検証するため、Webサーバーへのインターネットからの着信を必要とせず、ワイルドカードも取得できる。[Let's Encrypt DNS-01](https://letsencrypt.org/docs/challenge-types/#dns-01-challenge)
|
||||
|
||||
### ローカルIPを公開DNSへ入れる場合の注意
|
||||
|
||||
- Aへ入れるのは、来場者用ネットワークから到達できるIngressのVIP等。Pod IP、ClusterIP、`127.0.0.1`は使用しない。Node IPを使う場合も443の受け口を運営に確認する。
|
||||
- プライベートIPはインターネット全体から到達できない。会場LANやVPN等で経路がある利用者向けの公開となる。
|
||||
- 公開DNS上に名前とローカルIPが掲載される。公開CAの証明書に含めた名前もCTログの対象となる。[Let's Encrypt CT](https://letsencrypt.org/docs/ct-logs/)
|
||||
- DNSリバインディング対策で公開DNSからのプライベートIP応答を遮断する環境がある。会場の実利用DNSと端末で確認し、必要なら限定的な許可または運営管理のsplit DNSを相談する。防御機能全体を無効にしない。
|
||||
- Cloudflareの通常のオレンジ雲proxyは使わずDNS onlyとする。private originへの接続には別の構成が必要。[Cloudflare proxy status](https://developers.cloudflare.com/dns/proxy-status/)
|
||||
- 証明書の取得成功と、会場からのHTTPS到達成功は別々に検証する。
|
||||
|
||||
## 2 運営から受け取る情報
|
||||
|
||||
| 確認項目 | 必要な情報 |
|
||||
| --- | --- |
|
||||
| 接続 | kubeconfig、Namespace、接続可能な期間・ネットワーク |
|
||||
| 権限 | Deployment、Service、PVC、ConfigMap、Secret、Ingress等の操作、ログとport-forward |
|
||||
| ノード | `linux/amd64`対応。現在のリリースイメージの対象architecture |
|
||||
| リソース | CPU・メモリQuota、PVC容量、ephemeral storage制限 |
|
||||
| 保存 | StorageClass名、実体、SQLiteのlocking/fsyncに適するか、PVC保持・撤収時の扱い |
|
||||
| 公開 | IngressまたはGateway API、Class、入口のローカルIP、会場LANから443の到達性 |
|
||||
| TLS | 自分のNamespaceでTLS Secretを作れるか、終端の所有者、証明書更新の反映方法 |
|
||||
| 通信 | イメージレジストリへのpull、必要な外向き通信、会場DNSでの名前解決 |
|
||||
| セキュリティ | 非root UID、fsGroup、Pod Security、NetworkPolicy等の制約 |
|
||||
| 検証 | 展示前に同じ制約でデプロイ・再起動・HTTPS確認できる期間 |
|
||||
|
||||
最初の相談値は合計CPU 2〜4 vCPU、メモリ4〜8 GiB、PVC 20 GiB程度。計測済みの必要量ではなく、展示データと連携機能の選択後に調整する。NamespaceやIngress Controller、cert-managerを自分でクラスタ全体へ新設する前提にはしない。
|
||||
|
||||
## 3 手元の接続設定
|
||||
|
||||
対応バージョンのkubectlを手元へインストールする。受領したkubeconfigはGitへ入れず、信頼できる運営から受け取ったものだけを使用する。[kubeconfig](https://kubernetes.io/docs/tasks/access-application-cluster/configure-access-multiple-clusters/)
|
||||
|
||||
```bash
|
||||
chmod 600 "$HOME/.kube/jsb-exhibition.yaml"
|
||||
export KUBECONFIG="$HOME/.kube/jsb-exhibition.yaml"
|
||||
export NS='REPLACE_WITH_ASSIGNED_NAMESPACE'
|
||||
|
||||
kubectl config current-context
|
||||
kubectl -n "$NS" get pods
|
||||
kubectl -n "$NS" auth can-i create deployments.apps
|
||||
kubectl -n "$NS" auth can-i create persistentvolumeclaims
|
||||
kubectl -n "$NS" auth can-i create secrets
|
||||
kubectl -n "$NS" auth can-i create ingresses.networking.k8s.io
|
||||
```
|
||||
|
||||
Forbiddenが出たら運営へ相談する。別の管理者contextへ切り替えて回避しない。
|
||||
|
||||
## 4 CloudflareにDNSを登録する
|
||||
|
||||
前提として、対象の実際の権威DNS zoneを自分がCloudflareで管理できることを確認する。`jsb.anya.jp`が別のDNSへ委譲されている場合、親zoneの画面へレコードを追加しただけでは有効にならない。
|
||||
|
||||
```bash
|
||||
dig +short NS anya.jp
|
||||
dig +short SOA pages.jsb.anya.jp
|
||||
dig +trace pages.jsb.anya.jp A
|
||||
```
|
||||
|
||||
`anya.jp`がCloudflare上の対象zoneで、途中のNS委譲がない場合の入力例:
|
||||
|
||||
| 種別 | Name | Content | Proxy | TTL |
|
||||
| --- | --- | --- | --- | --- |
|
||||
| A | `pages.jsb` | 運営指定のIngress入口IPv4 | DNS only | 300秒を目安に選択 |
|
||||
| A | `*.pages.jsb` | 同じIngress入口IPv4 | DNS only | 同上 |
|
||||
|
||||
最初は本体のAだけでもよい。追加Domainを展示する場合にワイルドカードAを使う。不要なAAAAや旧A、競合するCNAMEがあれば影響を確認する。既存の別サービスのレコードを無断で消さない。
|
||||
|
||||
証明書のワイルドカードとDNSのワイルドカードは別設定。`*.pages.jsb.anya.jp`の証明書は `blog.pages.jsb.anya.jp`を含むが、`pages.jsb.anya.jp`自身や `a.b.pages.jsb.anya.jp`はカバーしない。
|
||||
|
||||
```bash
|
||||
# 公開DNSの応答を確認。これは会場の実利用DNSでの確認とは別。
|
||||
dig @1.1.1.1 pages.jsb.anya.jp A +short
|
||||
dig @1.1.1.1 blog.pages.jsb.anya.jp A +short
|
||||
dig @1.1.1.1 pages.jsb.anya.jp AAAA +short
|
||||
|
||||
# CA制限が設定されている場合は親からの継承も含めて確認する
|
||||
dig pages.jsb.anya.jp CAA
|
||||
dig jsb.anya.jp CAA
|
||||
dig anya.jp CAA
|
||||
```
|
||||
|
||||
## 5 自分の管理端末で証明書を取得する
|
||||
|
||||
共有クラスタへCloudflareのzone更新権限を置かないことを基本とする。運営へ渡すのは展示用の証明書・秘密鍵を格納したTLS Secretであり、Cloudflare API Tokenや本番サービスの秘密は渡さない。ただし運営のクラスタ管理者はTLS Secretへアクセス可能なため、鍵の管理責任は事前に合意する。
|
||||
|
||||
### 5.1 CertbotとCloudflare plugin
|
||||
|
||||
以下は自分が管理するUbuntu/Debianホストの例。運営のノードへSSHして実行しない。他のOSでは公式の導入手順を使い、Snap・pip・ディストリビューションpackageのpluginを混在させない。
|
||||
|
||||
```bash
|
||||
sudo apt-get update
|
||||
sudo apt-get install certbot python3-certbot-dns-cloudflare
|
||||
sudo certbot plugins
|
||||
```
|
||||
|
||||
`dns-cloudflare`が利用可能であることを確認する。[Certbot導入](https://eff-certbot.readthedocs.io/en/stable/install.html)、[Cloudflare plugin](https://certbot-dns-cloudflare.readthedocs.io/en/stable/)
|
||||
|
||||
### 5.2 専用API Token
|
||||
|
||||
CloudflareでDNS更新用のAPI Tokenを作る。Global API Keyは使わない。対象は実際に権威を持つ特定のzoneだけに限定し、全zoneを許可しない。DNS編集と、利用するclientがzone検出に必要とするzone読取を確認する。
|
||||
|
||||
Cloudflare Tokenの典型的な権限は `Zone / DNS / Edit` と `Zone / Zone / Read`。zoneを `anya.jp`へ限定しても、このTokenは `pages.jsb`のレコードだけに限定された権限とは限らない。より狭い委譲が必要なら認証専用zoneへの委譲を別途設計する。cert-managerの設定例をそのままCertbotへ流用しない。[Cloudflare認証設定](https://cert-manager.io/docs/configuration/acme/dns01/cloudflare/)
|
||||
|
||||
```bash
|
||||
install -d -m 700 "$HOME/.config/pageswiki-exhibition"
|
||||
```
|
||||
|
||||
エディタで `$HOME/.config/pageswiki-exhibition/cloudflare.ini` を作成する:
|
||||
|
||||
```ini
|
||||
dns_cloudflare_api_token = REPLACE_WITH_DEDICATED_TOKEN
|
||||
```
|
||||
|
||||
```bash
|
||||
chmod 600 "$HOME/.config/pageswiki-exhibition/cloudflare.ini"
|
||||
export ACME_EMAIL='REPLACE_WITH_YOUR_EMAIL'
|
||||
```
|
||||
|
||||
Tokenをコマンド引数、Git、チャット、一般ログへ書かない。作業端末からCloudflare API・ACMEへのHTTPSと、必要な公開DNS問い合わせが通ることを確認する。
|
||||
|
||||
### 5.3 stagingで確認する
|
||||
|
||||
```bash
|
||||
sudo certbot certonly \
|
||||
--test-cert \
|
||||
--non-interactive --agree-tos \
|
||||
--email "$ACME_EMAIL" \
|
||||
--cert-name pages-jsb-staging \
|
||||
--dns-cloudflare \
|
||||
--dns-cloudflare-credentials "$HOME/.config/pageswiki-exhibition/cloudflare.ini" \
|
||||
--dns-cloudflare-propagation-seconds 60 \
|
||||
-d 'pages.jsb.anya.jp' \
|
||||
-d '*.pages.jsb.anya.jp'
|
||||
```
|
||||
|
||||
DNS-01のTXT名は `_acme-challenge.pages.jsb.anya.jp`。親名とワイルドカードの認証で、同じ名前に複数TXT値を使う場合がある。clientが作った値を手で上書き・削除しない。propagation待ちは環境に応じて調整する。
|
||||
|
||||
staging証明書はブラウザに信頼されないため、本番用TLS Secretには使わない。
|
||||
|
||||
### 5.4 本番CAで発行する
|
||||
|
||||
```bash
|
||||
sudo certbot certonly \
|
||||
--non-interactive --agree-tos \
|
||||
--email "$ACME_EMAIL" \
|
||||
--cert-name pages-jsb \
|
||||
--dns-cloudflare \
|
||||
--dns-cloudflare-credentials "$HOME/.config/pageswiki-exhibition/cloudflare.ini" \
|
||||
--dns-cloudflare-propagation-seconds 60 \
|
||||
-d 'pages.jsb.anya.jp' \
|
||||
-d '*.pages.jsb.anya.jp'
|
||||
|
||||
sudo openssl x509 \
|
||||
-in /etc/letsencrypt/live/pages-jsb/fullchain.pem \
|
||||
-noout -subject -issuer -dates -ext subjectAltName
|
||||
```
|
||||
|
||||
CAが発行した実際の有効期限を確認する。固定の日数を前提に展示予定を組まない。失敗時にforce-renewalを連打せず、DNS・CAA・API権限・通信を確認する。
|
||||
|
||||
## 6 PagesWikiを先に内部確認する
|
||||
|
||||
Namespace内にPVC、1 replicaのDeployment、ClusterIP Serviceを配置する。[マニフェストひな形](../../deploy/kubernetes/exhibition/pageswiki.yaml.example)を作業領域の `pageswiki.yaml` にコピーし、`REPLACE_WITH_STORAGE_CLASS`、使用するreleaseタグ、運営指定のUID・Quota等を確認してから適用する。
|
||||
|
||||
| 設定 | 方針 |
|
||||
| --- | --- |
|
||||
| image | 検証済みのreleaseタグまたはdigestで固定。latestを使わない |
|
||||
| 本体 | `replicas: 1`、通常更新は `strategy.type: Recreate` |
|
||||
| port | `3000`。DockerfileのEXPOSEだけを待受の根拠にしない |
|
||||
| env | `PAGESWIKI_DATA_DIR=/data` |
|
||||
| 保存 | `/data`をPVC、必要な一時領域は別途確保 |
|
||||
| health | `/health`にstartup/readiness probe。起動処理中の再起動連発を避ける |
|
||||
| 権限 | 運営の非root・fsGroup等の方針で新規volumeの書き込みを検証する |
|
||||
|
||||
SQLite向け保存のlocking/fsyncを確認する。`ReadWriteOnce`自体は1 Podだけの排他保証ではない。対応CSIならReadWriteOncePodも相談し、いずれも手動の二重writerを作らない。[Volume access modes](https://kubernetes.io/docs/concepts/storage/persistent-volumes/)
|
||||
|
||||
```bash
|
||||
kubectl -n "$NS" apply --dry-run=server -f pageswiki.yaml
|
||||
kubectl -n "$NS" apply -f pageswiki.yaml
|
||||
kubectl -n "$NS" rollout status deployment/pageswiki --timeout=10m
|
||||
kubectl -n "$NS" get pods,pvc,svc
|
||||
kubectl -n "$NS" port-forward service/pageswiki 8080:80
|
||||
```
|
||||
|
||||
別ターミナルで `curl http://localhost:8080/health`。ブラウザで `http://localhost:8080/_/auth/login` を開き、初期管理者を作成する。初回画面要求時に生成されるbootstrap tokenは自分だけでログを確認し、貼り付け・共有しない。アカウント作成後はenforcing等の認可設定を確認し、外部公開前にログイン・匿名拒否を試す。
|
||||
|
||||
PagesWikiのCampus FQDNを `pages.jsb.anya.jp`、本体Domainのホスト名を空として、Campus FQDN自身を本体へ対応させる。既存の本番Campusへ参加させない。Wiki名等も展示用にする。FQDN変更後にlocalhostでDomainを解決できなくなる場合は、公開経路または適切なHostを用いて検証する。`PAGESWIKI_INSTANCE_FQDN`はCampus/Domain設定の代わりにはならない。
|
||||
|
||||
## 7 TLS Secretを作成する
|
||||
|
||||
証明書・秘密鍵を持つ管理端末にkubectlと運営用kubeconfigがある場合の例。証明書ファイルだけを保護した一時領域へコピーし、kubectl自体は通常の利用者として実行する。kubeconfigのcontext、Namespaceを必ず確認する。
|
||||
|
||||
```bash
|
||||
kubectl config current-context
|
||||
|
||||
# bashのサブシェル内で実行し、終了時に一時コピーを消す
|
||||
(
|
||||
set -euo pipefail
|
||||
TLS_TMP="$(mktemp -d)"
|
||||
chmod 700 "$TLS_TMP"
|
||||
trap 'rm -f "$TLS_TMP/tls.crt" "$TLS_TMP/tls.key"; rmdir "$TLS_TMP"' EXIT
|
||||
sudo install -m 600 -o "$(id -u)" -g "$(id -g)" \
|
||||
/etc/letsencrypt/live/pages-jsb/fullchain.pem "$TLS_TMP/tls.crt"
|
||||
sudo install -m 600 -o "$(id -u)" -g "$(id -g)" \
|
||||
/etc/letsencrypt/live/pages-jsb/privkey.pem "$TLS_TMP/tls.key"
|
||||
kubectl -n "$NS" create secret tls pages-jsb-tls \
|
||||
--cert="$TLS_TMP/tls.crt" --key="$TLS_TMP/tls.key" \
|
||||
--dry-run=client -o yaml | \
|
||||
kubectl -n "$NS" apply --server-side --field-manager=pageswiki-exhibition-tls -f -
|
||||
)
|
||||
|
||||
kubectl -n "$NS" describe secret pages-jsb-tls
|
||||
```
|
||||
|
||||
shellでpipelineを使う作業は `set -o pipefail` を有効にする。上記をログ収集用の `tee` へ流さない。server-side applyは秘密値をlast-applied annotationへ重複保存しないために使う。競合時は所有者を確認し、`--force-conflicts`で他の管理主体を奪わない。運営のRBAC・admissionでこの方法が許可されない場合は、運営指定の秘密投入手順へ切り替える。
|
||||
|
||||
SecretとIngressは同じNamespaceに置く。証明書の公開部分と秘密鍵は用途が異なり、TLS Secret全体のYAMLやbase64値を公開しない。[kubectl create secret tls](https://kubernetes.io/docs/reference/kubectl/generated/kubectl_create/kubectl_create_secret_tls/)
|
||||
|
||||
## 8 Ingressを作成する
|
||||
|
||||
以下を `pageswiki-ingress.yaml` として保存する。`REPLACE_WITH_INGRESS_CLASS`を実際の値へ変更する。運営がIngressを所有する場合、この設定内容を渡して運営に反映を依頼する。Gateway APIの場合は同等のHTTPRouteとTLS設定へ読み替える。
|
||||
|
||||
```yaml
|
||||
apiVersion: networking.k8s.io/v1
|
||||
kind: Ingress
|
||||
metadata:
|
||||
name: pageswiki
|
||||
spec:
|
||||
ingressClassName: REPLACE_WITH_INGRESS_CLASS
|
||||
tls:
|
||||
- hosts:
|
||||
- pages.jsb.anya.jp
|
||||
- "*.pages.jsb.anya.jp"
|
||||
secretName: pages-jsb-tls
|
||||
rules:
|
||||
- host: pages.jsb.anya.jp
|
||||
http:
|
||||
paths:
|
||||
- path: /
|
||||
pathType: Prefix
|
||||
backend:
|
||||
service:
|
||||
name: pageswiki
|
||||
port:
|
||||
number: 80
|
||||
- host: "*.pages.jsb.anya.jp"
|
||||
http:
|
||||
paths:
|
||||
- path: /
|
||||
pathType: Prefix
|
||||
backend:
|
||||
service:
|
||||
name: pageswiki
|
||||
port:
|
||||
number: 80
|
||||
```
|
||||
|
||||
```bash
|
||||
kubectl -n "$NS" apply --dry-run=server -f pageswiki-ingress.yaml
|
||||
kubectl -n "$NS" apply -f pageswiki-ingress.yaml
|
||||
kubectl -n "$NS" describe ingress pageswiki
|
||||
```
|
||||
|
||||
ワイルドカードIngressがあっても、未知HostをPagesWikiの本体Domainへフォールバックさせない。`blog`等を使う場合はPagesWiki側でもDomainを作成し、ホスト名を登録する。設定しない子Domainが404等になることは正常な拒否である。
|
||||
|
||||
Ingressでは元のHostを保ち、TLS終端後の `X-Forwarded-Proto: https` 等の扱いを確認する。転送ヘッダは信頼したIngressで上書きし、利用者からの偽装値をそのまま通さない。HTTPS redirect、アップロードサイズ、長い要求、将来のadapter接続はController固有の設定として相談する。
|
||||
|
||||
## 9 会場から検証する
|
||||
|
||||
```bash
|
||||
# 実際に利用者が使うDNSの答えと、経路を確認する
|
||||
dig pages.jsb.anya.jp A +short
|
||||
curl -I https://pages.jsb.anya.jp/
|
||||
|
||||
# DNS反映前でも、正しいSNIとHostを維持して入口だけ指定できる
|
||||
export INGRESS_IP='REPLACE_WITH_ASSIGNED_INGRESS_IP'
|
||||
curl --resolve "pages.jsb.anya.jp:443:$INGRESS_IP" \
|
||||
-I https://pages.jsb.anya.jp/
|
||||
|
||||
# 信頼チェーンとホスト名を検証する。検証失敗を-kで隠さない
|
||||
openssl s_client \
|
||||
-connect "$INGRESS_IP:443" \
|
||||
-servername pages.jsb.anya.jp \
|
||||
-verify_hostname pages.jsb.anya.jp \
|
||||
-verify_return_error </dev/null
|
||||
```
|
||||
|
||||
合格条件:展示LANの端末で名前解決とTCP443が通る、SAN・有効期限・信頼チェーンが正しい、ログインとログアウトが動く、非公開文書へ匿名アクセスできない、編集保存とPod再起動後の永続化が動く、必要な追加Domainだけが正しい。会場外から接続不可であることはプライベートIP構成では想定内。
|
||||
|
||||
## 10 更新と撤収
|
||||
|
||||
証明書更新後も、クラスタのTLS Secretは自動的には更新されない。まずstagingで試した後、必要な時期にCertbotの `renew --cert-name pages-jsb` を実施し、手順7で同じSecretへ反映する。Ingress ControllerがSecret更新を取り込んだことを実接続で確認する。自動更新するなら、更新とSecret反映の両方を自分の管理ホストで監視付きに運用する。
|
||||
|
||||
```bash
|
||||
sudo certbot renew --cert-name pages-jsb --dry-run
|
||||
sudo certbot renew --cert-name pages-jsb
|
||||
```
|
||||
|
||||
cert-managerを使う場合は代わりに運営の許可を得て既設controllerを利用する。Namespace内のIssuer、Cloudflare Token Secret、Certificateを同じNamespaceに置き、CertificateのdnsNamesを親名とワイルドカード、secretNameを `pages-jsb-tls` とする。Secretへ手動投入する方式とcert-managerに同じSecretを同時管理させない。ClusterIssuer作成権限やcert-manager新設を要求しない。[Issuerのscope](https://cert-manager.io/docs/concepts/issuer/)、[Certificate](https://cert-manager.io/docs/usage/certificate/)
|
||||
|
||||
ただしAPI Tokenを共有クラスタへ置く権限・影響、Cloudflare/ACMEへの外向き通信、DNS self-checkを事前確認する。外部で発行してTLSだけ持ち込む方式なら、これらをクラスタへ追加する必要はない。
|
||||
|
||||
撤収時は、展示データを整合した手段で保全し、公開経路停止、展示用のAレコード整理、TLS鍵・専用Token・kubeconfigの保持/失効、PVCの保持/削除を運営と合意する。NamespaceやPVCの削除を再起動の代わりに使わない。
|
||||
|
||||
## 参考資料
|
||||
|
||||
- [certbot-dns-cloudflare](https://certbot-dns-cloudflare.readthedocs.io/en/stable/)
|
||||
- [Let's Encryptの認証方式](https://letsencrypt.org/docs/challenge-types/)
|
||||
- [Cloudflare DNS onlyとproxy](https://developers.cloudflare.com/dns/proxy-status/)
|
||||
- [Kubernetes Ingress](https://kubernetes.io/docs/concepts/services-networking/ingress/)
|
||||
- [単一インスタンスの配置例](https://kubernetes.io/docs/tasks/run-application/run-single-instance-stateful-application/)
|
||||
- [PagesWikiの運用・保全設計](../design/ja/operations.md)
|
||||
|
||||
公式資料確認日:2026-11-12。記載例は実クラスタへ適用していない。運営指定のClass、証明書終端方式、UID、Quotaが確定してからマニフェストを検証する。
|
||||
@@ -0,0 +1,32 @@
|
||||
# 展示環境についてのNOCへの返信案
|
||||
|
||||
> 初期相談時の草案を保存したもの。実際の展示では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提供も含めて相談させていただければと思います。
|
||||
|
||||
よろしくお願いいたします。
|
||||
@@ -0,0 +1 @@
|
||||
__pycache__/
|
||||
@@ -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, "<h1>") || !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)
|
||||
}
|
||||
}
|
||||
@@ -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()
|
||||
@@ -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"<dd><strong>([^<]+)</strong>", 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'<tr data-import-item data-sequence="(\d+)">(.*?)</tr>', 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 = '<c:mkcalendar xmlns:c="urn:ietf:params:xml:ns:caldav" xmlns:d="DAV:"><d:set><d:prop><d:displayname>展示の準備</d:displayname><c:supported-calendar-component-set><c:comp name="VTODO"/></c:supported-calendar-component-set></d:prop></d:set></c:mkcalendar>'
|
||||
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()
|
||||
@@ -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()
|
||||
@@ -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('''<form id="campus-update-1"></form>
|
||||
<input form="campus-update-1" name="campus_id" value="1">
|
||||
<input form="campus-update-1" name="ignore" value="secret" disabled>
|
||||
<input form="campus-update-1" name="campus_enabled" type="checkbox" value="1" checked>
|
||||
<input form="campus-update-1" name="unchecked" type="checkbox" value="1">
|
||||
<select form="campus-update-1" name="mode"><option value="first"></option><option value="standalone" selected></option></select>''')
|
||||
self.assertEqual(forms.forms, {"campus-update-1": {"campus_id": "1", "campus_enabled": "1", "mode": "standalone"}})
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in new issue
Block a user