From 02edb51b8a5023c28b981a0c816145128f3b2f5c Mon Sep 17 00:00:00 2001 From: Anya Tokugawa Date: Tue, 10 Nov 2026 07:12:10 +0900 Subject: [PATCH] test(tasks): preserve mail Wiki path diagnostics and regression coverage --- .gitignore | 1 + docs/operations/mail-wiki-path-diagnostics.md | 45 +++++++ internal/server/task_neomutt_test.go | 102 +++++++++++++++ internal/server/task_wiki_routing_test.go | 122 ++++++++++++++++++ pages-cli/test_neomutt_viewer.py | 109 ++++++++++++++++ 5 files changed, 379 insertions(+) create mode 100644 docs/operations/mail-wiki-path-diagnostics.md create mode 100644 internal/server/task_neomutt_test.go create mode 100644 internal/server/task_wiki_routing_test.go create mode 100644 pages-cli/test_neomutt_viewer.py diff --git a/.gitignore b/.gitignore index d51957b..3e3cca9 100644 --- a/.gitignore +++ b/.gitignore @@ -5,6 +5,7 @@ data/* !data/test_cli_dr.py !data/pageswiki-remote /data2/ +/docs/local/ /.codex/ /.agents/ /.env diff --git a/docs/operations/mail-wiki-path-diagnostics.md b/docs/operations/mail-wiki-path-diagnostics.md new file mode 100644 index 0000000..ff958d1 --- /dev/null +++ b/docs/operations/mail-wiki-path-diagnostics.md @@ -0,0 +1,45 @@ +# メールWikiのPath依存404の調査 + +## 状態と回避策 + +2026年11月6日、別インスタンスでNeoMuttから作成したWikiが一覧には見える一方、`/tasks` とその配下への直接アクセスで `{"detail":"Not Found"}` になる報告があった。同じオブジェクトに `/prj/awesome` 側のリンクを追加すると表示できた。原因は未確定で、修正済みとは扱わない。 + +回避策は表示できるWiki親prefixを既定値にし、既存オブジェクトには別Pathのリンクを使うこと。メールの再取り込み、オブジェクトの削除、既存Pathの一括移動は不要。Pathごとに権限が異なりうるため、新しいリンク先の公開範囲も確認する。 + +## アプリ内で確認した境界 + +タスク画面は `/v/plan/tasks`、APIは `/_/api/v1/extension/organizer.tasks/`。`/tasks` は予約ルートではなく、通常のWiki Pathとして解決する。末尾スラッシュは301で取り除く。 + +NeoMuttの `pipe_decode=no`・`pipe_split=yes` 相当の標準入力を使い、CLIプロセスから一時DBのフルHTTPハンドラへ取り込む試験を追加した。42パターンは、親prefix7種類、UTF-8/ISO-2022-JPの件名、ML連番/Message-ID/原文hashの組合せ。公開CLI v0.4.0でも一覧のdata-path、直接表示、末尾スラッシュ、言語指定を確認し、代表3パターンをChromiumで表示した。実メール・実アカウント設定は使用しない。 + +Python・Chromiumに依存しないGoテストでは、実際のAPIへ既定prefix `/tasks` を設定して取り込み、同一オブジェクトの `/tasks/...` と `/prj/awesome` の両方がHTMLの200を返すことを検証する。未認証閲覧のログイン誘導、一覧表示、旧CLI形式も対象。CIでPythonがない場合もこのテストは実行される。 + +親に文書がない場合は、仮想フォルダページ無効ならHTMLの404、有効ならchildren一覧の200となる。これは作成済み子ページまでJSONの404になる報告とは区別する。設定箇所は `/-/sys/config?panel=home` の「仮想フォルダページ」。設定は対象ドメイン単位で、調査のために自動変更しない。 + +## 機密情報を共有しない切り分け + +以下は問題のインスタンス内で行う。実URL・メール本文・Cookie・Bearer token・ログ全文を外部へ共有しない。 + +1. 問題のPathへのGET時刻を控え、PagesWikiプロセスのアクセスログに同じ要求が到達するか確認する。到達しない場合はプロキシ、ブラウザ、キャッシュなどアプリより手前を調べる。ログ出力先の取り違えにも注意する。 +2. 公開HTTPSとPagesWikiの直接待受で応答を比較する。Domainの振り分けが変わらないよう、同じHostとPathを使う。まず資格情報なし・リダイレクトを追わないGETのstatusとContent-Typeを比較すれば、メール本文を取得せずに判断できる。認証後の比較が必要ならローカル環境内の安全な手順を使い、コマンド履歴に資格情報を残さない。 +3. 直接待受は正常でプロキシ経由だけ失敗する場合、`/tasks` に一致するlocation、正規表現location、rewrite、別upstream、Custom Locationsを確認する。実際の設定で確認できるまではプロキシが原因と断定しない。 +4. PagesWikiへの直接要求も失敗する場合は、稼働イメージrevision、HostによるDomain選択、Path別ACL、既存リンクの対象UUIDをローカルで確認する。同一オブジェクトの別名が読めても、元Pathの権限が同じとは限らない。 + +X-Request-IDやServerヘッダーだけで応答元を断定しない。プロキシによる付加・上書きがありうる。原因が判明するまで、推測による `/tasks` 専用ルート追加や権限の緩和はしない。 + +## 回帰テストと残件 + +```sh +go test ./internal/server -run 'TestTaskWikiPrefixRouting|TestNeoMuttMailViewerFlow' -count=1 +# Chromiumがある開発環境のみ +PAGESWIKI_BROWSER_TEST=1 go test ./internal/server -run '^TestNeoMuttMailViewerFlow$' -count=1 +# 配布ELFでも同じ一時プロファイルを用いて確認する場合 +PAGES_CLI_TEST_BINARY=/absolute/path/to/pages PAGESWIKI_BROWSER_TEST=1 go test ./internal/server -run '^TestNeoMuttMailViewerFlow$' -count=1 +``` + +- [x] `/tasks` 配下のメール作成から通常ビューアまでの合成HTTP試験。 +- [x] 同一オブジェクトの別名、親の仮想フォルダ設定、認証境界のGo回帰テスト。 +- [ ] 問題インスタンスで、直接待受とプロキシ経由の差分を確定する。 +- [ ] 特定された原因に修正を適用し、元の `/tasks` でも表示できることを確認する。 + +テストと調査記録の追加は障害修正リリースではない。既存の回避策とデータを維持する。 diff --git a/internal/server/task_neomutt_test.go b/internal/server/task_neomutt_test.go new file mode 100644 index 0000000..7cdebbd --- /dev/null +++ b/internal/server/task_neomutt_test.go @@ -0,0 +1,102 @@ +package server + +import ( + "bytes" + "context" + "encoding/json" + "net/http" + "net/http/httptest" + "os" + "os/exec" + "strings" + "testing" + "time" +) + +// Exercise the actual CLI executable boundary, full production router and +// browser-session authentication. All mail, credentials and storage are synthetic. +func TestNeoMuttMailViewerFlow(t *testing.T) { + if _, err := exec.LookPath("python3"); err != nil { + t.Skip("python3 not installed") + } + fixture, token, domain := configFixture(t) + fixture.store.BackgroundJobsDisabled = true + s := New(fixture.store) + p, err := s.store.PrincipalForSession(domain, token) + if err != nil { + t.Fatal(err) + } + browser, err := s.store.CreateBrowserAuthSession(domain, p.UUID, 0) + if err != nil { + t.Fatal(err) + } + handler := s.handler() + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + r.Host = "localhost" + if r.URL.Path == "/fixture-browser-login" { + s.setAuthCookie(w, r, browser) + http.Redirect(w, r, r.URL.Query().Get("return"), http.StatusSeeOther) + return + } + handler.ServeHTTP(w, r) + })) + defer server.Close() + ctx, cancel := context.WithTimeout(context.Background(), 90*time.Second) + defer cancel() + input, _ := json.Marshal(map[string]any{"origin": server.URL, "browser": browser, "root": t.TempDir(), "chromium": os.Getenv("PAGESWIKI_BROWSER_TEST") == "1"}) + cmd := exec.CommandContext(ctx, "python3", "pages-cli/test_neomutt_viewer.py") + cmd.Stdin = bytes.NewReader(input) + out, err := cmd.CombinedOutput() + if err != nil { + t.Fatalf("NeoMutt flow: %v\n%s", err, out) + } + if !strings.Contains(string(out), "MAIL_VIEWER_OK") { + t.Fatalf("missing verification: %s", out) + } + t.Log(string(out)) + // Capture creates only the leaf document: prefix and date/list directories + // remain virtual. Exercise the parent URLs under both documented settings. + request := func(path string) *httptest.ResponseRecorder { + r := httptest.NewRequest(http.MethodGet, "http://localhost"+strings.ReplaceAll(path, " ", "%20"), nil) + r.AddCookie(&http.Cookie{Name: authCookieName, Value: browser}) + w := httptest.NewRecorder() + handler.ServeHTTP(w, r) + return w + } + for _, enabled := range []bool{false, true} { + value, expected := "false", http.StatusNotFound + if enabled { + value, expected = "true", http.StatusOK + } + if err := s.store.SetConfigInDomain(domain, "virtual_folder_pages", value); err != nil { + t.Fatal(err) + } + if w := request("/tasks/"); w.Code != http.StatusMovedPermanently || w.Header().Get("Location") != "/tasks" { + t.Fatalf("tasks trailing slash: %d %s", w.Code, w.Header().Get("Location")) + } + for _, path := range []string{"/tasks", "/tasks/example.list", "/tasks/2026/01", "/mail", "/mail/example.list", "/private/mail", "/private/mail/2026", "/private/mail/2026/01", "/受信 メール", "/docs/mail", "/api/mail"} { + w := request(path) + if w.Code != expected || !strings.Contains(strings.ToLower(w.Body.String()), "") { + t.Fatalf("parent %s virtual=%t: %d %s", path, enabled, w.Code, w.Body.String()) + } + if strings.Contains(w.Body.String(), `{"detail":"Not Found"}`) { + t.Fatal("unexpected JSON error") + } + } + t.Logf("parent prefix/list/year/month: virtual_folder_pages=%t status=%d HTML", enabled, expected) + } + if err := s.store.SetConfigInDomain(domain, "virtual_folder_pages", "false"); err != nil { + t.Fatal(err) + } + id, err := s.store.CreatePageAtPathInDomain(domain, "/private/mail") + if err != nil { + t.Fatal(err) + } + if _, err = s.store.SaveRevisionContent(id, []byte("

Synthetic mail portal

{{children}}"), "", "und", "text/html", ""); err != nil { + t.Fatal(err) + } + if w := request("/private/mail"); w.Code != 200 || !strings.Contains(w.Body.String(), "Synthetic mail portal") { + t.Fatalf("explicit parent document: %d", w.Code) + } + t.Log("explicit parent document: status=200 HTML with virtual folders disabled") +} diff --git a/internal/server/task_wiki_routing_test.go b/internal/server/task_wiki_routing_test.go new file mode 100644 index 0000000..9d75425 --- /dev/null +++ b/internal/server/task_wiki_routing_test.go @@ -0,0 +1,122 @@ +package server + +import ( + "bytes" + "encoding/json" + "net/http" + "net/http/httptest" + "strconv" + "strings" + "testing" + + "github.com/google/uuid" + "pageswiki/internal/store" +) + +// No Python/Chromium dependency: the production route and authorization stack +// must continue to serve /tasks as Wiki space, not the organizer task UI/API. +func TestTaskWikiPrefixRouting(t *testing.T) { + fixture, token, domain := configFixture(t) + fixture.store.BackgroundJobsDisabled = true + s := New(fixture.store) + p, err := s.store.PrincipalForSession(domain, token) + if err != nil { + t.Fatal(err) + } + cookie, err := s.store.CreateBrowserAuthSession(domain, p.UUID, 0) + if err != nil { + t.Fatal(err) + } + handler := s.handler() + request := func(method, target string, payload any, authenticated bool) *httptest.ResponseRecorder { + body, err := json.Marshal(payload) + if err != nil { + t.Fatal(err) + } + r := httptest.NewRequest(method, "http://localhost"+target, bytes.NewReader(body)) + if authenticated { + if method == http.MethodGet { + r.AddCookie(&http.Cookie{Name: authCookieName, Value: cookie}) + } else { + r.Header.Set("Authorization", "Bearer "+token) + } + } + r.Header.Set("Content-Type", "application/json") + w := httptest.NewRecorder() + handler.ServeHTTP(w, r) + return w + } + prefs, err := s.store.TaskPreferences(t.Context(), domain, p.UUID) + if err != nil { + t.Fatal(err) + } + prefs.WikiPrefix = "/tasks" + if w := request("PUT", tasksAPI+"preferences", prefs, true); w.Code != 200 { + t.Fatalf("preferences: %d %s", w.Code, w.Body) + } + for i, suffix := range []string{"example/123", "2026/11/" + uuid.NewString(), "2026/11/" + strings.Repeat("a", 64), ""} { + input := map[string]any{"request_id": uuid.NewString(), "title": "合成メール", "wiki_body": "Synthetic routing test body"} + if suffix != "" { + input["wiki_suffix"] = suffix + } + w := request("POST", tasksAPI+"capture", input, true) + if w.Code != 201 { + t.Fatalf("capture: %d %s", w.Code, w.Body) + } + var result struct { + Item store.TaskRecord `json:"item"` + Path string `json:"page_path"` + } + if err := json.Unmarshal(w.Body.Bytes(), &result); err != nil { + t.Fatal(err) + } + if !strings.HasPrefix(result.Path, "/tasks/") { + t.Fatal(result.Path) + } + alias := "/prj/awesome" + if i != 0 { + alias += "/" + strconv.Itoa(i) + } + if err := s.store.AddPathLinkInDomain(domain, result.Item.PageUUID, alias); err != nil { + t.Fatal(err) + } + for _, target := range []string{result.Path, alias} { + if taskRoute(target) { + t.Fatalf("Wiki path captured by organizer routing: %s", target) + } + id, err := s.store.ResolvePathInDomain(domain, target) + if err != nil || id != result.Item.PageUUID { + t.Fatalf("alias identity: %s %v", id, err) + } + w := request("GET", target, nil, true) + if w.Code != 200 || !strings.Contains(w.Body.String(), "Synthetic routing test body") || !strings.Contains(strings.ToLower(w.Body.String()), "") { + t.Fatalf("viewer %s: %d %s", target, w.Code, w.Body) + } + if w := request("GET", target+"/", nil, true); w.Code != 301 || w.Header().Get("Location") != target { + t.Fatalf("trailing slash %s: %d", target, w.Code) + } + if w := request("GET", target, nil, false); w.Code != 303 || strings.Contains(w.Body.String(), "Synthetic routing test body") { + t.Fatalf("anonymous isolation %s: %d", target, w.Code) + } + } + parent := result.Path[:strings.LastIndex(result.Path, "/")] + if w := request("GET", "/v/browser"+parent, nil, true); w.Code != 200 || !strings.Contains(w.Body.String(), `data-path="`+result.Path+`"`) { + t.Fatalf("listing: %d", w.Code) + } + } + for _, enabled := range []string{"false", "true"} { + if err := s.store.SetConfigInDomain(domain, "virtual_folder_pages", enabled); err != nil { + t.Fatal(err) + } + expected := http.StatusNotFound + if enabled == "true" { + expected = http.StatusOK + } + for _, target := range []string{"/tasks", "/tasks/example", "/tasks/2026", "/tasks/2026/11"} { + w := request("GET", target, nil, true) + if w.Code != expected || !strings.Contains(strings.ToLower(w.Body.String()), "") { + t.Fatalf("virtual parent %s enabled=%s: %d", target, enabled, w.Code) + } + } + } +} diff --git a/pages-cli/test_neomutt_viewer.py b/pages-cli/test_neomutt_viewer.py new file mode 100644 index 0000000..364044c --- /dev/null +++ b/pages-cli/test_neomutt_viewer.py @@ -0,0 +1,109 @@ +"""Synthetic NeoMutt pipe -> real CLI -> full HTTP router -> browser viewer. + +Run by TestNeoMuttMailViewerFlow; never reads a real mail or CLI profile. +""" +import hashlib +import json +import os +from pathlib import Path +import subprocess +import sys +from email.header import Header +from html.parser import HTMLParser +from urllib.parse import quote, unquote, urlencode, urlsplit +from urllib.request import Request, urlopen + + +class Links(HTMLParser): + def __init__(self): + super().__init__() + self.links = [] + + def handle_starttag(self, tag, attrs): + attrs = dict(attrs) + if 'browser-row' in attrs.get('class', '').split(): + self.links.append(attrs.get('data-path', '')) + if tag == 'a': + self.links.append(attrs.get('href', '')) + + +def main(): + fixture = json.load(sys.stdin) + root = Path(fixture['root']) + env = {**os.environ, 'HOME': str(root), 'XDG_CONFIG_HOME': str(root / 'config')} + executable = str(Path(__file__).with_name('pages').resolve()) + binary = os.environ.get('PAGES_CLI_TEST_BINARY') + command = [str(Path(binary).resolve())] if binary else [sys.executable, executable] + + def cli(*args, data=b''): + run = subprocess.run([*command, *args], input=data, + capture_output=True, env=env, timeout=15) + assert run.returncode == 0, (args, run.stderr.decode()) + return run.stdout + + def get(path): + request = Request(fixture['origin'] + quote(path, safe='/:?=&%'), + headers={'Cookie': 'pageswiki_session=' + fixture['browser'], + 'Accept-Language': 'ja,en;q=0.8'}) + with urlopen(request, timeout=10) as response: + body = response.read().decode() + assert response.status == 200, (path, response.status) + assert response.headers.get_content_type() == 'text/html', (path, body[:100]) + assert unquote(urlsplit(response.url).path) == unquote(urlsplit(path).path).rstrip('/'), response.url + return body + + cli('configure', '--origin', fixture['origin'], '--username', 'admin') + cli('login', data=b'a long test password\n') + paths = [] + for parent in ['/tasks', '/mail', '/private/mail', '/受信 メール', '/u/admin/mail', '/docs/mail', '/api/mail']: + cli('task', 'preferences', '--wiki-prefix', parent) + for charset in ['utf-8', 'iso-2022-jp']: + for kind in ['ml', 'message-id', 'hash']: + number = len(paths) + 1 + title = '日本語の依頼' + subject = (f'[example.list {number:05d}] ' if kind == 'ml' else '') + title + # pipe_decode=no / pipe_split=yes: exactly one un-decoded RFC mail + # is delivered to the CLI's stdin, as in the published NeoMutt macro. + raw = ('From: Test \r\n' + 'Date: Sat, 31 Jan 2026 23:30:00 -0800\r\n' + 'Subject: ' + Header(subject, charset).encode() + '\r\n' + + (f'Message-ID: \r\n' if kind != 'hash' else '') + + 'MIME-Version: 1.0\r\nContent-Type: text/plain; charset=utf-8\r\n' + 'Content-Transfer-Encoding: 8bit\r\n\r\n' + f'Synthetic mail body {number}. {{' + '{children}}\r\n').encode() + result = json.loads(cli('task', 'from-mail', data=raw)) + path = result['page_path'] + suffix = ('example.list/' + str(number) if kind == 'ml' else '2026/01/' + + (result['item']['uuid'] if kind == 'message-id' else hashlib.sha256(raw).hexdigest())) + assert path == parent + '/' + suffix, path + assert result['item']['title'] == title + # Confirm browser listing actually links to the same semantic URL. + listing = get('/v/browser' + path.rsplit('/', 1)[0]) + links = Links(); links.feed(listing) + linked = next((href for href in links.links if unquote(urlsplit(href).path) == path), None) + assert linked is not None, ('missing listing link', path, links.links, listing[:600]) + page = get(path) + assert f'Synthetic mail body {number}.' in page, path + assert title in page, path + assert '{"detail":"Not Found"}' not in page + assert f'Synthetic mail body {number}.' in get(linked) + assert f'Synthetic mail body {number}.' in get(path + '/') + assert f'Synthetic mail body {number}.' in get(path + '?lang=ja') + paths.append(path) + if fixture['chromium']: + # Real browser session, normal navigation and scripts, without injecting + # page HTML or bypassing the production handler. + for i, path in enumerate([paths[0], paths[14], paths[-1]]): + target = fixture['origin'] + '/fixture-browser-login?' + urlencode({'return': path}) + run = subprocess.run(['chromium', '--headless', '--no-sandbox', '--disable-gpu', + '--disable-background-networking', '--no-proxy-server', + '--user-data-dir=' + str(root / ('chromium-' + str(i))), + '--dump-dom', '--virtual-time-budget=2000', target], + capture_output=True, timeout=20) + assert run.returncode == 0, run.stderr.decode()[-1000:] + assert 'Synthetic mail body' in run.stdout.decode(), (path, run.stdout.decode()[:500]) + print('MAIL_VIEWER_OK cases=' + str(len(paths)) + ' chromium=' + str(fixture['chromium'])) + + +if __name__ == '__main__': + main()