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:
Anya Tokugawa committed 2026-11-30 23:14:24 +09:00
1 parent 1fd2de4c6b
commit 4a863fe63c
17 files changed
+2039

No files matched your search

+1
View File
@@ -0,0 +1 @@
__pycache__/
+97
View File
@@ -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)
}
}
+187
View File
@@ -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()
+323
View File
@@ -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()
+127
View File
@@ -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()
+32
View File
@@ -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()