The OSINT investigator's workbench. One case, one folder, every tool. Local-first: your media and your investigations never leave your machine.
JavaScript
Report an issue from About, and carry presets in a backup (#40)
OsintMeThatafe2d5f1919f
diff --git a/docs/SPEC.md b/docs/SPEC.mdindex d6bfbe7..2dc4810 100644--- a/docs/SPEC.md+++ b/docs/SPEC.md@@ -113,6 +113,7 @@ proof for publication.| ✅ **Gated downloads** | Fetches login-walled media by borrowing a browser session or cookies.txt, cookie-less by default and prompted only on a wall. || ✅ **Find at scale** | Bounded, paged loading with a shared search box and sort across the Media Library and Files, plus case-name search in the switcher. || ✅ **Searchable pickers** | Pickers in Inspect, Reverse Search, Geo Proof and the Notebook notes menu search past six entries and browse case folders behind the "…". |+| ✅ **Report an issue** | About writes a bug or a request into a pre-filled GitHub issue, with version, OS and the run's last warnings, home path and account name scrubbed. || ✅ **Proofs on the map** | A fourth position of the Saved switch places each proof by its own coordinates, then by the captures it composes; `All` marks a worked capture with a dot rather than doubling it. || ✅ **Import enrichment** | Reads image EXIF/dHash and video container/stream metadata locally in the background; parsed GPS produces linked Suggestions and all fields appear in Details. || ✅ **GPS in Media** | A GPS filter and a per-row pin in the Media list send a stated position to the map, images and videos alike. |@@ -139,7 +140,6 @@ Each version delivers one complete daily workflow. Firm ideas move here from| **Command palette** | Ctrl+K reaches a tool, a case or an artifact. || **Sun, moon and local time** | Sunrise/sunset, solar and lunar azimuth, moon phase and bright-limb angle for a point and date, in Coordinates, each time in civil local time and UTC. Polar day/night and days with no moonrise are states, not errors; the moon needs topocentric parallax and sampled rise/set, and civil time adds `timezonefinder` + `tzdata` to bundle. || **Capture scale and north** | Preference-controlled scale bar, north arrow and graticule on app and extension captures. |-| **Report an issue** | Opens a pre-filled GitHub issue with version, OS and recent log lines. |### v3: GEOINT expansiondiff --git a/frontend/src/tools/Settings.svelte b/frontend/src/tools/Settings.svelteindex 8f563e4..f96a534 100644--- a/frontend/src/tools/Settings.svelte+++ b/frontend/src/tools/Settings.svelte@@ -209,8 +209,10 @@let sigBust = $state(0);let sigInput = $state(null);- // Move settings between machines: export writes settings.json to disk,- // import merges a previously exported file back (config keys only).+ // Move the app's own state between machines: the export writes one JSON file+ // holding settings, templates and the signature logo; the import merges it+ // back. A file written before those sections existed is a bare settings blob,+ // so it gets wrapped into the current shape.let settingsFile = $state(null);async function importSettings(event) {@@ -218,11 +220,19 @@if (!file) return;try {const parsed = JSON.parse(await file.text());- await api.post('/api/settings/import', { settings: parsed });- toast('Settings imported', 'ok');+ const bundle = parsed.settings ? parsed : { settings: parsed };+ const r = await api.post('/api/settings/import', bundle);+ const restored = [+ `${r.imported.length} setting${r.imported.length === 1 ? '' : 's'}`,+ r.templates ? `${r.templates} template${r.templates === 1 ? '' : 's'}` : null,+ r.signature ? 'signature' : null,+ ].filter(Boolean);+ toast(`Backup restored: ${restored.join(', ')}`, 'ok');await load();+ await loadTemplates();+ sigBust += 1; // the logo changed on disk; re-fetch it past the cache} catch (e) {- toast(`Could not import settings: ${e.message}`, 'danger');+ toast(`Could not import the backup: ${e.message}`, 'danger');} finally {event.currentTarget.value = '';}@@ -274,6 +284,38 @@}}+ // Report an issue. The server builds the body and the pre-filled link; this+ // only keeps them fresh as the user types, so the link is a real anchor and no+ // popup blocker sees a window.open after an await.+ let reportKind = $state('bug');+ let reportSummary = $state('');+ let report = $state(null); // { kind, title, report, url }+ let reportTimer = null;++ async function loadReport() {+ const params = new URLSearchParams({ kind: reportKind, summary: reportSummary });+ try {+ report = await api.get(`/api/settings/diagnostics?${params}`);+ } catch {+ report = null; // the About tab falls back to a plain link to the tracker+ }+ }++ // Debounced: typing a paragraph shouldn't rebuild the report on every key.+ function refreshReport() {+ clearTimeout(reportTimer);+ reportTimer = setTimeout(loadReport, 400);+ }++ async function copyReport() {+ try {+ await navigator.clipboard.writeText(report.report);+ toast('Report copied', 'ok');+ } catch {+ toast('Could not copy. Select the report text instead', 'warn');+ }+ }+async function updateScraper(dist) {if (updating[dist]) return;updating[dist] = true;@@ -458,6 +500,12 @@loadTemplates();});+ // Build the report the first time About is opened: it reads the log buffer and+ // shells nothing out, but there's no reason to do it for the other tabs.+ $effect(() => {+ if (tab === 'about' && !report) loadReport();+ });+$effect(() => {if (uiState.tool !== 'settings') return;const target = uiState.settingsTab;@@ -1150,17 +1198,77 @@</p></section>+ <section class="group">+ <h3>Report an issue</h3>+ <p class="note">+ Opens a new issue on the public GitHub tracker; anyone can read it.+ </p>+ <div class="report-kind">+ <label>+ <input+ type="radio"+ value="bug"+ bind:group={reportKind}+ onchange={loadReport}+ /> Something is broken+ </label>+ <label>+ <input+ type="radio"+ value="idea"+ bind:group={reportKind}+ onchange={loadReport}+ /> Something is missing+ </label>+ </div>+ <textarea+ class="report-summary"+ rows="3"+ maxlength="2000"+ placeholder={reportKind === 'bug'+ ? 'What you did, what you expected, what you got'+ : 'What you would like Azimut to do'}+ bind:value={reportSummary}+ oninput={refreshReport}+ ></textarea>+ {#if report}+ <details class="report-preview">+ <summary>What gets sent</summary>+ <pre class="mono">{report.report}</pre>+ </details>+ {/if}+ <div class="links">+ <a+ class="btn btn-sm btn-primary"+ href={report?.url || `${REPO_URL}/issues/new`}+ target="_blank"+ rel="noreferrer"+ >+ <Icon name="link" size={13} /> Open a GitHub issue <Icon name="external" size={11} />+ </a>+ <button class="btn btn-sm" onclick={copyReport} disabled={!report}>+ <Icon name="copy" size={13} /> Copy report+ </button>+ </div>+ <p class="note">+ Your text, the version, the OS and the last warnings of this run, with your+ paths, account name, case names and any keys removed. Nothing leaves the app+ until you open the issue.+ </p>+ </section>+<section class="group"><h3>Backup</h3><p class="note">- Export settings and keys for another machine; keep the file private.+ One file with your settings, keys, templates and signature, for another+ machine; keep it private. Your download login session stays on this machine.</p><div class="links"><a class="btn btn-sm" href="/api/settings/export" download>- <Icon name="save" size={13} /> Export settings+ <Icon name="save" size={13} /> Export backup</a><button class="btn btn-sm" onclick={() => settingsFile?.click()}>- <Icon name="file" size={13} /> Import settings+ <Icon name="file" size={13} /> Import backup</button><inputtype="file"@@ -1588,6 +1696,46 @@margin-top: 14px;flex-wrap: wrap;}++ /* Report an issue: kind, the user's words, then the report itself folded away. */+ .report-kind {+ display: flex;+ gap: 16px;+ margin: 10px 0 8px;+ font-size: var(--fs-xs);+ color: var(--text-2);+ }+ .report-kind label {+ display: flex;+ align-items: center;+ gap: 6px;+ }+ .report-summary {+ width: 100%;+ resize: vertical;+ font: inherit;+ font-size: var(--fs-sm);+ }+ .report-preview {+ margin-top: 10px;+ font-size: var(--fs-xs);+ }+ .report-preview summary {+ color: var(--text-3);+ cursor: pointer;+ }+ .report-preview pre {+ margin: 8px 0 0;+ padding: 8px 10px;+ max-height: 240px;+ overflow: auto;+ white-space: pre-wrap;+ overflow-wrap: anywhere;+ background: var(--bg-2);+ border: 1px solid var(--border);+ border-radius: var(--r-sm);+ color: var(--text-2);+ }.links .btn {gap: 6px;text-decoration: none;diff --git a/frontend/src/tools/Settings.test.js b/frontend/src/tools/Settings.test.jsnew file mode 100644index 0000000..882914c--- /dev/null+++ b/frontend/src/tools/Settings.test.js@@ -0,0 +1,55 @@+import { describe, expect, it } from 'vitest';+import { readFileSync } from 'node:fs';++const source = readFileSync(new URL('./Settings.svelte', import.meta.url), 'utf8');++describe('Report an issue', () => {+ it('lets the user say what happened, bug or request', () => {+ expect(source).toContain("let reportKind = $state('bug')");+ expect(source).toContain('bind:value={reportSummary}');+ expect(source).toContain('maxlength="2000"');+ expect(source).toContain('Something is broken');+ expect(source).toContain('Something is missing');+ });++ it('asks the server for the report and debounces typing', () => {+ expect(source).toContain("api.get(`/api/settings/diagnostics?${params}`)");+ expect(source).toContain('clearTimeout(reportTimer)');+ expect(source).toContain('setTimeout(loadReport, 400)');+ expect(source).toContain("if (tab === 'about' && !report) loadReport()");+ });++ it('files through a real anchor, so no popup blocker sees a deferred open', () => {+ expect(source).toContain('href={report?.url || `${REPO_URL}/issues/new`}');+ expect(source).not.toContain('window.open(report');+ });++ it('shows the exact report before it is filed, and can copy it whole', () => {+ expect(source).toContain('<summary>What gets sent</summary>');+ expect(source).toContain('<pre class="mono">{report.report}</pre>');+ expect(source).toContain('navigator.clipboard.writeText(report.report)');+ });++ it('warns that the tracker is public', () => {+ expect(source).toContain('public GitHub tracker; anyone can read it');+ });+});++describe('Backup', () => {+ it('posts the bundle as-is, and wraps a pre-bundle settings file', () => {+ expect(source).toContain('const bundle = parsed.settings ? parsed : { settings: parsed }');+ expect(source).toContain("api.post('/api/settings/import', bundle)");+ });++ it('reloads what a restore can change, logo included', () => {+ expect(source).toContain('await loadTemplates()');+ expect(source).toContain('sigBust += 1');+ });++ it('says what the file holds, and what it leaves behind', () => {+ expect(source).toContain('settings, keys, templates and signature');+ expect(source).toContain('login session stays on this machine');+ expect(source).toContain('Export backup');+ expect(source).toContain('Import backup');+ });+});diff --git a/src/azimut/api/settings.py b/src/azimut/api/settings.pyindex e0ab5a6..d66b372 100644--- a/src/azimut/api/settings.py+++ b/src/azimut/api/settings.py@@ -5,6 +5,8 @@ Keys and branding stay beside settings.json, outside cases and exports.from __future__ import annotations+import base64+import binasciiimport jsonimport refrom typing import Annotated, Any, Literal@@ -12,11 +14,16 @@ from typing import Annotated, Any, Literalimport httpxfrom fastapi import APIRouter, HTTPException, Response, UploadFilefrom fastapi.responses import FileResponse-from pydantic import BaseModel, ConfigDict, Field, field_validator+from pydantic import BaseModel, ConfigDict, Field, field_validator, model_validatorfrom .. import __version__, config-from ..engine import ffmpeg, google_tiles, scrapers, sentinel, tiles, updates+from ..engine import diagnostics, ffmpeg, google_tiles, scrapers, sentinel, tiles, updatesfrom .ingest import bundled_extension_version+from .templates import MAX_PER_KIND as MAX_TEMPLATES_PER_KIND++# A backup carries the signature logo as base64: 4 characters per 3 bytes, plus+# slack for padding and any line breaks a hand-edited file picked up.+SIGNATURE_B64_MAX_CHARS = 4 * (config.SIGNATURE_MAX_BYTES // 3 + 1) + 1024router = APIRouter(prefix="/api", tags=["settings"])@@ -285,17 +292,50 @@ def mint_ingest_token() -> dict[str, Any]:return {"ingest_token": config.ingest_token()}+def _signature_b64() -> str:+ """The signature logo as base64, or ``""`` when there is no usable one.++ Size is read from the directory entry before the bytes are: the upload route+ bounds what Settings accepts, but a file dropped into the workspace by hand+ has been through no gate at all, and a backup is not the place to discover it.+ The same ``valid_signature`` check the upload and the restore apply decides+ whether it travels.+ """+ path = config.signature_path()+ try:+ if not path.is_file() or path.stat().st_size > config.SIGNATURE_MAX_BYTES:+ return ""+ data = path.read_bytes()+ except OSError:+ return ""+ return base64.b64encode(data).decode("ascii") if config.valid_signature(data) else ""++@router.get("/settings/export")def export_settings() -> Response:- """Download the whole settings.json (keys, providers, preferences) so it can- be restored on another machine (POST /settings/import). It carries the- user's own keys by design — it's a local download to their own disk, the- same secrets that already live in the workspace."""- payload = json.dumps(config.load_settings(), indent=2, ensure_ascii=False)+ """Download everything app-wide that isn't a case, so another machine can be+ set up identically (POST /settings/import).++ Three files in one: settings.json verbatim (so a key added to+ ``DEFAULT_SETTINGS`` travels without anyone remembering to list it here),+ templates.json, and the signature logo base64-encoded. It carries the user's+ own API keys by design — it's a local download of secrets that already live+ in their workspace.++ Deliberately absent: ``cookies.txt`` (a live login session, tied to one+ machine's browser), the cases themselves (portable folders already), and a+ signature that isn't a valid PNG within the size gate.+ """+ bundle = {+ "settings": config.load_settings(),+ "templates": config.load_templates(),+ "signature_png": _signature_b64(),+ }+ payload = json.dumps(bundle, indent=2, ensure_ascii=False)return Response(content=payload,media_type="application/json",- headers={"Content-Disposition": 'attachment; filename="azimut-settings.json"'},+ headers={"Content-Disposition": 'attachment; filename="azimut-backup.json"'},)@@ -337,6 +377,35 @@ class ImportedHomeView(BaseModel):zoom: int = Field(ge=1, le=21)+class ImportedDownloadCookies(BaseModel):+ """The gated-download login source, as a backup can legitimately carry it.++ ``browser`` travels — the analyst's choice of browser is a preference, and+ the second machine reads that browser's own live cookies. ``file`` does not:+ the backup deliberately leaves ``cookies.txt`` behind (a live session), so a+ restore that pointed at it would select a file that isn't there. It lands on+ ``none`` instead, which is the state the app is built to work in.+ """++ model_config = ConfigDict(extra="ignore", strict=True)++ source: Literal["none", "browser", "file"] = "none"+ browser: str | None = Field(default=None, max_length=32)++ @field_validator("browser")+ @classmethod+ def known_browser(cls, value: str | None) -> str | None:+ return value if value in config.COOKIE_BROWSERS else None++ @model_validator(mode="after")+ def resolvable_source(self) -> ImportedDownloadCookies:+ if self.source == "browser" and self.browser is None:+ return ImportedDownloadCookies(source="none")+ if self.source == "file":+ return ImportedDownloadCookies(source="none")+ return self++class ImportedSettings(BaseModel):"""Validated, canonical subset of a settings backup.@@ -378,6 +447,7 @@ class ImportedSettings(BaseModel):ingest_token: str = Field(default="", max_length=128, pattern=r"^[A-Za-z0-9_-]*$")update_check_on_start: bool = Trueupdate_dismissed_version: str = Field(default="", max_length=64)+ download_cookies: ImportedDownloadCookies = Field(default_factory=ImportedDownloadCookies)@field_validator("api_keys")@classmethod@@ -406,11 +476,20 @@ class ImportedSettings(BaseModel):class ImportIn(BaseModel):- """A previously exported settings blob. Only keys Azimut recognises are- applied — anything else in the file is ignored, so a hand-edited or foreign- JSON can't inject arbitrary state."""+ """A previously exported backup. Only keys Azimut recognises are applied —+ anything else in the file is ignored, so a hand-edited or foreign JSON can't+ inject arbitrary state.++ Every part is optional: a backup written before that part existed restores+ the parts it does have.+ """- settings: ImportedSettings+ settings: ImportedSettings = Field(default_factory=ImportedSettings)+ templates: dict[str, Any] = Field(default_factory=dict)+ # Base64 of the signature PNG. Bounded as a string first — decoding a+ # megabytes-long field only to reject it is work an untrusted body shouldn't+ # get. The decoded bytes then face config.valid_signature().+ signature_png: str = Field(default="", max_length=SIGNATURE_B64_MAX_CHARS)@router.post("/settings/import")@@ -423,7 +502,30 @@ def import_settings(body: ImportIn) -> dict[str, Any]:settings[key] = canonical[key]config.update_settings(apply)- return {"imported": applied}++ # Templates pass the same validation as a templates.json read off disk, so a+ # restored preset can't be shaped differently from a saved one.+ templates = 0+ if body.templates:+ restored = config.canonical_templates(body.templates, max_per_kind=MAX_TEMPLATES_PER_KIND)+ templates = sum(len(restored[kind]) for kind in config.TEMPLATE_KINDS)+ if templates:+ config.save_templates(restored)++ # A malformed logo is dropped rather than failing the whole restore: the keys+ # and presets are the valuable part, and the user can re-upload a PNG.+ signature = False+ if body.signature_png:+ try:+ data = base64.b64decode(body.signature_png, validate=True)+ except (ValueError, binascii.Error):+ data = b""+ if config.valid_signature(data):+ path = config.signature_path()+ path.parent.mkdir(parents=True, exist_ok=True)+ path.write_bytes(data)+ signature = True+ return {"imported": applied, "templates": templates, "signature": signature}@router.post("/settings/keys/{provider}/status")@@ -524,7 +626,7 @@ async def put_signature(file: UploadFile) -> dict[str, Any]:detail=f"signature must be under {config.SIGNATURE_MAX_BYTES // 1024 // 1024} MB",)# sniff the bytes rather than trust the filename or the browser's content-type- if not data.startswith(config.PNG_MAGIC):+ if not config.valid_signature(data):raise HTTPException(status_code=422, detail="signature must be a PNG image")path = config.signature_path()path.parent.mkdir(parents=True, exist_ok=True)@@ -603,6 +705,22 @@ def check_app_update(check: bool = False) -> dict[str, Any]:return updates.check(__version__)[email protected]("/settings/diagnostics")+def get_diagnostics(summary: str = "", kind: str = diagnostics.DEFAULT_KIND) -> dict[str, str]:+ """The bug-report body and a pre-filled GitHub issue link for it.++ Pure local text: version, OS and the in-memory warning tail, with paths, the+ account name, case names and credentials scrubbed (engine/diagnostics.py, which+ owns the list and why each entry is on it). Touches no network —+ the user's browser opens the returned link on a click, so About can show the+ exact report first. ``summary`` is what the user typed; the engine caps it+ (``MAX_SUMMARY_CHARS``) rather than refusing it — losing a typed paragraph to+ a 422 is worse than shortening it, and the HTTP layer bounds the request line+ long before a summary could grow into a payload.+ """+ return diagnostics.payload(summary, kind=kind)++@router.post("/settings/scrapers/{dist}/update")def update_scraper(dist: str) -> dict[str, Any]:"""Fetch the latest wheel for one scraper into the workspace.diff --git a/src/azimut/config.py b/src/azimut/config.pyindex 3bde9ff..1d03499 100644--- a/src/azimut/config.py+++ b/src/azimut/config.py@@ -182,8 +182,10 @@ def signature_path() -> Path:"""The analyst's optional logo, stamped onto proofs they choose to sign.App-wide like the API keys, and under the same rule: it lives beside- settings.json and is never copied into a case folder or an export bundle.- Only the rendered proof PNG ever carries it.+ settings.json and is never copied into a case folder — only the rendered+ proof PNG ever carries it out of here. A settings backup does carry it,+ because that file goes to the user's own second machine, not to a third+ party (api/settings.py export/import)."""return workspace_root() / "signature.png"@@ -192,8 +194,9 @@ def templates_path() -> Path:"""Reusable proof-style and post-thread presets, app-wide.A "house style" spans every case, so it lives beside settings.json rather- than inside a case — same rule as the signature. Kept out of settings.json- itself so the secrets file stays small and single-purpose.+ than inside a case — same rule as the signature, and it travels in a settings+ backup for the same reason. Kept out of settings.json itself so the secrets+ file stays small and single-purpose."""return workspace_root() / "templates.json"@@ -219,6 +222,15 @@ SIGNATURE_MAX_BYTES = 2 * 1024 * 1024PNG_MAGIC = b"\x89PNG\r\n\x1a\n"+def valid_signature(data: bytes) -> bool:+ """Small enough, and actually a PNG — sniffed from the bytes, never a name.++ One gate for both ways a logo arrives: the Settings upload and a restored+ settings backup.+ """+ return 0 < len(data) <= SIGNATURE_MAX_BYTES and data.startswith(PNG_MAGIC)++def ensure_workspace() -> None:"""Create the workspace skeleton if missing (idempotent)."""cases_dir().mkdir(parents=True, exist_ok=True)@@ -351,6 +363,16 @@ def load_templates() -> dict[str, Any]:except (OSError, json.JSONDecodeError, ValueError) as exc:logger.warning("Ignoring unreadable templates.json: %s", exc)return copy.deepcopy(DEFAULT_TEMPLATES)+ return canonical_templates(data)+++def canonical_templates(data: Any, *, max_per_kind: int | None = None) -> dict[str, Any]:+ """Every well-formed template record in *data*, and nothing else.++ Shared by the file reader above and by a settings-backup import, so a preset+ restored from another machine passes exactly the checks a preset read off+ disk does — one gate, not two that can drift apart.+ """if not isinstance(data, dict) or data.get("schema", 1) != 1:logger.warning("Ignoring templates.json with an unsupported root or schema")return copy.deepcopy(DEFAULT_TEMPLATES)@@ -360,6 +382,8 @@ def load_templates() -> dict[str, Any]:if not isinstance(value, list):continueseen: set[str] = set()+ if max_per_kind is not None:+ value = value[:max_per_kind]for item in value:if not isinstance(item, dict):continuediff --git a/src/azimut/engine/diagnostics.py b/src/azimut/engine/diagnostics.pynew file mode 100644index 0000000..ab4b51b--- /dev/null+++ b/src/azimut/engine/diagnostics.py@@ -0,0 +1,383 @@+"""What to tell a bug report — build number, machine, and the last warnings.++A local app has no crash reporter behind it, so the useful facts about a broken+run only exist on the user's own machine. This module collects them into one+short Markdown block and turns it into a pre-filled GitHub issue URL, which the+About tab shows in full before the user decides to open it. Nothing is sent from+here: the report is text and a link, and the browser does the sending on a+click.++Three rules shape what goes in.++**The user's own words first.** A report is often a request, or a bug that logged+nothing at all, so the summary the analyst types is the body's first section and+the issue title. The environment and the log tail follow it as context; neither+is the point.++**Warnings only, only the last few, and never on disk.** A ring buffer keeps the+tail of the ``WARNING``-and-above log in memory (:class:`RingHandler`, installed+at server start) — bounded lines, each capped in length, so a long-running app+holds a few kilobytes and no log file ever grows in the workspace.++**Nothing personal.** A log line or a path can hold the account name, a case name+or a provider key, and an issue is public, so every string goes through+:func:`scrub`: the home directory and the workspace root collapse to placeholders,+and so do the account name, the case folder and any credential-shaped query+parameter. A case folder is a slug of the name the analyst typed, which in this+tool is routinely a subject's — that one is not a nicety. The workspace path is+also absent from the report outright: About shows it locally, a report does not+need it.+"""++from __future__ import annotations++import getpass+import logging+import os+import platform+import re+import sys+from collections import deque+from pathlib import Path+from urllib.parse import quote++from .. import __version__, config+from . import ffmpeg++#: Where a report lands. The repo's issue form, filled through query parameters.+ISSUE_NEW_URL = "https://github.com/OsintMeThat/azimut/issues/new"++#: How much log tail the report carries, and from which level up. The buffer is+#: the app's only log store — nothing is written to disk — so these two bounds+#: plus MAX_LINE_CHARS are the whole memory cost: ~12 kB at worst, for the life+#: of the process.+LOG_LINES = 30+LOG_LEVEL = logging.WARNING+#: One line's ceiling. A traceback or an embedded payload would otherwise make a+#: single record dwarf the other twenty-nine.+MAX_LINE_CHARS = 400+LOG_FORMAT = "%(asctime)s %(levelname)s %(name)s: %(message)s"+LOG_DATEFMT = "%Y-%m-%d %H:%M:%S"++#: Long URLs are silently dropped or truncated by servers and browsers well+#: before any hard limit, so the link stays under a conservative ceiling and+#: sheds context to fit. The Copy button always carries the whole report.+URL_LIMIT = 6000+TRIM_MARKER = "_(log trimmed to fit the link; use Copy for the full report)_"+#: Said when the summary itself is what overflowed. Distinct from the marker+#: above because it must not blame the log for a paragraph the user can see was+#: cut — a report that quietly drops what someone typed is worse than a long link.+SUMMARY_TRIM_MARKER = "_(summary trimmed to fit the link; use Copy for the full report)_"++#: What a report is: something broke, or something is missing. The kind picks the+#: title prefix, the heading the summary sits under, and the tracker label.+#: Both labels are GitHub's own defaults, so they exist on the repo — a label the+#: repo doesn't have would make GitHub refuse the whole pre-filled form.+KINDS = {+ "bug": ("Bug", "What happened", "bug"),+ "idea": ("Idea", "What you'd like", "enhancement"),+}+DEFAULT_KIND = "bug"+#: A summary is a few sentences; past that it's a paste, and the link stops fitting.+MAX_SUMMARY_CHARS = 2000++_PLACEHOLDER = "<user>"+_CASE_PLACEHOLDER = "<case>"+_WORKSPACE_PLACEHOLDER = "<workspace>"+_REDACTED = "<redacted>"++#: Query parameters whose value is a credential. A keyed imagery or geocoding+#: provider is reached over HTTP, so a warning about one carries the key in the+#: URL it names — and this text is on its way to a public tracker.+_CREDENTIAL_PARAM = re.compile(+ r"(?i)\b(api[_-]?key|access[_-]?token|auth[_-]?token|token|key|secret|password|passwd)"+ r"=[^&\s\"'<>]+"+)+++# ---- the log tail -------------------------------------------------------------+++def _cap(line: str) -> str:+ """One log line, shortened to :data:`MAX_LINE_CHARS` and kept single-line."""+ flat = line.replace("\n", " ⏎ ")+ return flat if len(flat) <= MAX_LINE_CHARS else flat[: MAX_LINE_CHARS - 1] + "…"+++class RingHandler(logging.Handler):+ """Keep the last *capacity* formatted records at ``WARNING`` and above."""++ def __init__(self, capacity: int = LOG_LINES) -> None:+ super().__init__(level=LOG_LEVEL)+ self.setFormatter(logging.Formatter(LOG_FORMAT, datefmt=LOG_DATEFMT))+ self._records: deque[str] = deque(maxlen=capacity)++ def emit(self, record: logging.LogRecord) -> None:+ try:+ self._records.append(_cap(self.format(record)))+ except Exception: # a handler that raises would break the logging call+ pass++ def lines(self) -> list[str]:+ return list(self._records)++ def clear(self) -> None:+ self._records.clear()+++_handler: RingHandler | None = None+++def install() -> RingHandler:+ """Start capturing warnings on the root logger. Safe to call twice.++ On the root logger rather than ``azimut``'s own so uvicorn's errors are+ captured too — those are often the whole story when a request fails.+ """+ global _handler+ if _handler is None:+ _handler = RingHandler()+ logging.getLogger().addHandler(_handler)+ return _handler+++def log_lines() -> list[str]:+ """The captured tail, scrubbed. Empty when nothing has warned yet."""+ if _handler is None:+ return []+ return [scrub(line) for line in _handler.lines()]+++# ---- scrubbing ----------------------------------------------------------------+++def _account_name() -> str:+ """The OS account name, or ``""`` when the environment doesn't say.++ ``getpass.getuser()`` raises rather than returning a default when no+ ``USER``/``LOGNAME`` is set and the uid has no passwd entry — a container,+ typically.+ """+ try:+ return getpass.getuser()+ except Exception:+ return ""+++def _path_pattern(path: str) -> re.Pattern[str]:+ """*path* as a pattern matching it however a log line happened to spell it.++ Either separator at every boundary, because one line legitimately carries+ both: this app names a file by a relative path that always uses ``/``+ (``media/photo.jpg``) and joins it to a workspace root that on Windows uses+ ``\\``. Case-insensitive on Windows for the same reason — that filesystem is,+ so two spellings name one directory and matching only one of them is a+ coin toss.++ Not cosmetic. The home prefix is what carries the account name, so a spelling+ this misses is a real name on its way to a public tracker.+ """+ parts = [re.escape(part) for part in re.split(r"[/\\]+", path)]+ flags = re.IGNORECASE if os.name == "nt" else 0+ return re.compile(r"[/\\]+".join(parts), flags)+++def scrub(text: str) -> str:+ """Take this machine and this investigation out of a string bound for a public+ issue.++ Each pass exists because the report is published:++ - the home directory collapses to ``~``+ - the workspace root collapses to ``<workspace>``, which catches a portable+ install living outside the home directory entirely+ - the account name becomes ``<user>``+ - a case folder becomes ``<case>``. A case directory is a slug of the name the+ analyst gave it (``workspace._slugify``), and in this tool that name is+ routinely a subject's — so the segment goes even though the path around it+ is useful.+ - a credential-shaped query parameter becomes ``<redacted>``++ None of this makes an arbitrary string safe to publish; it removes what this+ app's own log lines are known to carry.+ """+ try:+ home = str(Path.home())+ except Exception: # no home to hide+ home = ""+ if home:+ text = _path_pattern(home).sub("~", text)+ try:+ root = str(config.workspace_root())+ except Exception:+ root = ""+ if root and root not in ("~", "/"):+ text = _path_pattern(root).sub(_WORKSPACE_PLACEHOLDER, text)+ name = _account_name()+ # Two characters or fewer would match far too much ordinary prose.+ if len(name) > 2:+ text = text.replace(name, _PLACEHOLDER)+ for directory in _case_parents():+ segment = re.escape(directory.name)+ text = re.sub(+ rf"(?<![\w-])({segment})([/\\])[^/\\\s\"'<>]+",+ rf"\1\2{_CASE_PLACEHOLDER}",+ text,+ )+ return _CREDENTIAL_PARAM.sub(rf"\1={_REDACTED}", text)+++def _case_parents() -> tuple[Path, ...]:+ """The workspace directories a case folder sits in. Read from config rather+ than spelled out, so moving either one keeps the scrub honest."""+ try:+ return (config.cases_dir(), config.scratch_dir())+ except Exception:+ return ()+++# ---- the report ---------------------------------------------------------------+++def install_kind() -> str:+ """How this copy was installed, as far as it can tell about itself."""+ return "standalone binary" if getattr(sys, "frozen", False) else "Python package"+++_environment: dict[str, str] | None = None+++def environment() -> dict[str, str]:+ """The build and machine facts a maintainer needs to reproduce a bug.++ Built once per process. Not an optimisation for its own sake: reading the+ ffmpeg line runs ``ffmpeg -version``, and ``ffmpeg.info`` says in as many words+ that its caller is a dedicated endpoint rather than a hot poll. This one is+ hot — About rebuilds the report as the user types — and on Windows a+ subprocess per keystroke burst flashes a console window at someone in the+ middle of writing a bug report. None of these facts change within a run.+ """+ global _environment+ if _environment is not None:+ return dict(_environment)+ info = ffmpeg.info()+ if info.get("available"):+ version = str(info.get("version") or "installed")+ source = "bundled" if info.get("source") == "bundled" else "system PATH"+ ffmpeg_line = f"{version} ({source})"+ else:+ ffmpeg_line = "not found"+ _environment = {+ "Azimut": f"{__version__} ({install_kind()})",+ "OS": f"{platform.system()} {platform.release()} ({platform.machine()})",+ "Python": platform.python_version(),+ "ffmpeg": ffmpeg_line,+ }+ return dict(_environment)+++def _clean_summary(summary: str) -> str:+ """The typed summary, bounded and scrubbed. May be empty."""+ return scrub(summary.strip()[:MAX_SUMMARY_CHARS]).strip()+++def title(summary: str = "", *, kind: str = DEFAULT_KIND) -> str:+ """The issue title: the kind, then the summary's first line as the subject."""+ prefix = KINDS.get(kind, KINDS[DEFAULT_KIND])[0]+ first = _clean_summary(summary).split("\n", 1)[0][:120].rstrip(" .")+ return f"{prefix}: {first}" if first else f"{prefix}: "+++def report(summary: str = "", *, kind: str = DEFAULT_KIND) -> str:+ """The issue body: what the user wrote, then the environment and log tail."""+ heading = KINDS.get(kind, KINDS[DEFAULT_KIND])[1]+ written = _clean_summary(summary)+ lines = [f"### {heading}", ""]+ lines.append(written if written else "<!-- Describe it here. -->")+ lines += ["", "### Environment", ""]+ lines += [f"- **{key}**: {value}" for key, value in environment().items()]+ captured = log_lines()+ lines += ["", "### Recent warnings", ""]+ if captured:+ lines += ["```", *captured, "```"]+ else:+ lines.append("_None recorded this run._")+ return "\n".join(lines) + "\n"+++def _own_section(lines: list[str]) -> int:+ """How many leading lines are the user's own section: everything before the+ next heading. The floor the link may not shed past."""+ for index, line in enumerate(lines[1:], start=1):+ if line.startswith("### "):+ return index+ return len(lines)+++def _fit(text: str, budget: int) -> str:+ """*text*, shortened until its percent-encoded form fits *budget* characters.++ Counted encoded, not in characters, because that is the only measure the link+ cares about: one letter costs one character in ASCII, six in accented Latin and+ nine in an emoji, so a cap in letters says nothing about whether the URL fits.+ """+ if len(quote(text)) <= budget:+ return text+ low, high = 0, len(text)+ while low < high: # longest prefix whose encoding fits+ middle = (low + high + 1) // 2+ if len(quote(text[:middle])) <= budget:+ low = middle+ else:+ high = middle - 1+ return text[:low].rstrip()+++def issue_url(body: str, *, subject: str = "", label: str = "") -> str:+ """A pre-filled issue link that fits, shedding context before content.++ Two things can overflow. The log tail is the usual one, and it sits last in the+ body precisely so this reaches it first. The other is the summary itself: it is+ capped at ``MAX_SUMMARY_CHARS`` *characters*, and a paragraph in Cyrillic or+ Japanese costs nine characters a letter once percent-encoded, so a summary well+ inside the cap can be several times the whole link's budget. Shedding blindly+ from the end would then eat the report and leave a marker blaming the log — the+ user clicks through and finds their own words gone. So the user's section is a+ floor: everything after it goes first, and only if that is still too long is the+ summary itself shortened, with a marker that says which one was cut.+ """+ tag = f"&labels={quote(label)}" if label else ""++ def link(text: str) -> str:+ return f"{ISSUE_NEW_URL}?title={quote(subject)}{tag}&body={quote(text)}"++ lines = body.rstrip("\n").split("\n")+ floor = _own_section(lines)+ trimmed = False+ while True:+ url = link("\n".join([*lines, TRIM_MARKER] if trimmed else lines))+ if len(url) <= URL_LIMIT:+ return url+ if len(lines) <= floor:+ break+ lines.pop()+ trimmed = True++ marker = f"\n\n{SUMMARY_TRIM_MARKER}"+ budget = URL_LIMIT - len(link(marker))+ return link(_fit("\n".join(lines), max(budget, 0)) + marker)+++def payload(summary: str = "", *, kind: str = DEFAULT_KIND) -> dict[str, str]:+ """What the About tab renders: the full report, and the link to file it."""+ if kind not in KINDS:+ kind = DEFAULT_KIND+ body = report(summary, kind=kind)+ subject = title(summary, kind=kind)+ label = KINDS[kind][2]+ return {+ "kind": kind,+ "title": subject,+ "report": body,+ "url": issue_url(body, subject=subject, label=label),+ }diff --git a/src/azimut/server.py b/src/azimut/server.pyindex 2dc0db4..b67f70e 100644--- a/src/azimut/server.py+++ b/src/azimut/server.py@@ -80,6 +80,11 @@ def _recover_jobs() -> None:def create_app() -> FastAPI:config.ensure_workspace()+ # Start keeping the tail of the warning log, so "Report an issue" has+ # something to say about a run that already went wrong (engine/diagnostics).+ from .engine import diagnostics++ diagnostics.install()# Before any router can import a scraper: point yt-dlp/gallery-dl at the# newer copies in the workspace, if the user has fetched any. No network.from .engine import scrapersdiff --git a/tests/test_diagnostics.py b/tests/test_diagnostics.pynew file mode 100644index 0000000..f47fff9--- /dev/null+++ b/tests/test_diagnostics.py@@ -0,0 +1,442 @@+"""Report an issue (engine/diagnostics.py, api/settings.py).++Three things are load-bearing and asserted here: the log buffer stays bounded so+a long session can't grow it, the report never carries the home path or the+account name into a public tracker, and building the report touches no network —+the fake ``httpx.get`` explodes if anything reaches for it.+"""++from __future__ import annotations++import logging+from urllib.parse import parse_qs, urlparse++import httpx+import pytest++from azimut import __version__+from azimut.engine import diagnostics++[email protected](autouse=True)+def fresh_environment(monkeypatch):+ """The environment block is built once per process. Tests that change what the+ machine reports need that cache cleared, the same way `ring` gives each test a+ fresh log buffer."""+ monkeypatch.setattr(diagnostics, "_environment", None)+++def ring(monkeypatch):+ """A fresh capture buffer, wired the way the server wires it."""+ handler = diagnostics.RingHandler()+ monkeypatch.setattr(diagnostics, "_handler", handler)+ root = logging.getLogger()+ root.addHandler(handler)+ yield handler+ root.removeHandler(handler)+++def body_of(url: str) -> str:+ return parse_qs(urlparse(url).query)["body"][0]+++# -- the log buffer stays small -------------------------------------------+++def test_buffer_keeps_only_the_last_lines(ring):+ log = logging.getLogger("azimut.test")+ for i in range(diagnostics.LOG_LINES + 25):+ log.warning("warning %d", i)++ lines = ring.lines()+ assert len(lines) == diagnostics.LOG_LINES+ assert "warning 54" in lines[-1]+ assert "warning 0" not in "\n".join(lines)+++def test_buffer_caps_one_huge_line(ring):+ logging.getLogger("azimut.test").warning("x" * 10_000)++ (line,) = ring.lines()+ assert len(line) <= diagnostics.MAX_LINE_CHARS+ assert line.endswith("…")+++def test_buffer_flattens_multiline_records(ring):+ logging.getLogger("azimut.test").warning("first\nsecond")++ (line,) = ring.lines()+ assert "\n" not in line+ assert "first ⏎ second" in line+++def test_buffer_ignores_info_and_below(ring):+ log = logging.getLogger("azimut.test")+ log.info("routine")+ log.debug("noise")+ log.error("broken")++ assert [line.split(" ", 3)[-1] for line in ring.lines()] == ["azimut.test: broken"]+++def test_install_is_idempotent(monkeypatch):+ monkeypatch.setattr(diagnostics, "_handler", None)+ root = logging.getLogger()+ before = len(root.handlers)+ try:+ first = diagnostics.install()+ assert diagnostics.install() is first+ assert len(root.handlers) == before + 1+ finally:+ root.removeHandler(diagnostics._handler)+++# -- nothing personal reaches a public tracker ----------------------------+++def test_scrub_replaces_home_and_account_name(monkeypatch, tmp_path):+ monkeypatch.setattr(diagnostics.Path, "home", staticmethod(lambda: tmp_path / "gwen"))+ monkeypatch.setattr(diagnostics, "_account_name", lambda: "gwen")++ scrubbed = diagnostics.scrub(f"failed to open {tmp_path}/gwen/Azimut/cases/kyiv — gwen")+ assert "gwen" not in scrubbed+ # the path stays useful, but the case segment is a name the analyst chose and+ # this text is on its way to a public tracker+ assert "~/Azimut/cases/<case>" in scrubbed+ assert "kyiv" not in scrubbed+ assert "<user>" in scrubbed+++def test_scrub_collapses_a_home_path_spelled_with_either_separator(monkeypatch, tmp_path):+ """A Windows log line carries both separators at once, and the home prefix is+ what holds the account name.++ The app names a file by a relative path that always uses `/`+ (`media/photo.jpg`) and joins it to a root that on Windows uses `\\`, so the+ boundary between them flips. Matching only the native spelling let the real+ account name through into a public issue.+ """+ monkeypatch.setattr(diagnostics.Path, "home", staticmethod(lambda: tmp_path / "gwen"))+ monkeypatch.setattr(diagnostics, "_account_name", lambda: "gwen")+ native = str(tmp_path / "gwen")++ for spelling in (native, native.replace("\\", "/"), native.replace("/", "\\")):+ scrubbed = diagnostics.scrub(f"failed to open {spelling}/media/photo.jpg")+ assert "gwen" not in scrubbed+ assert scrubbed.endswith("photo.jpg")+++def test_scrub_keeps_a_very_short_account_name(monkeypatch):+ """A one- or two-letter name would match ordinary words all over the report."""+ monkeypatch.setattr(diagnostics, "_account_name", lambda: "an")++ assert diagnostics.scrub("an unexpected answer") == "an unexpected answer"+++def test_scrub_survives_a_homeless_environment(monkeypatch):+ monkeypatch.setattr(+ diagnostics.Path, "home", staticmethod(lambda: (_ for _ in ()).throw(RuntimeError))+ )+ monkeypatch.setattr(diagnostics.getpass, "getuser", lambda: (_ for _ in ()).throw(KeyError))++ assert diagnostics.scrub("plain text") == "plain text"+++def test_report_scrubs_the_captured_log(ring, monkeypatch, tmp_path):+ monkeypatch.setattr(diagnostics.Path, "home", staticmethod(lambda: tmp_path / "gwen"))+ monkeypatch.setattr(diagnostics, "_account_name", lambda: "gwen")+ logging.getLogger("azimut.test").warning("cannot read %s/gwen/Azimut/settings.json", tmp_path)++ text = diagnostics.report()+ assert "gwen" not in text+ assert "~/Azimut/settings.json" in text+++def test_report_scrubs_what_the_user_typed(monkeypatch, tmp_path):+ monkeypatch.setattr(diagnostics.Path, "home", staticmethod(lambda: tmp_path / "gwen"))+ monkeypatch.setattr(diagnostics, "_account_name", lambda: "gwen")++ text = diagnostics.report(f"crashed on {tmp_path}/gwen/photo.jpg")+ assert "gwen" not in text+ assert "~/photo.jpg" in text+++def test_report_never_carries_the_workspace_path(client):+ """About shows the workspace locally; a public issue has no use for it."""+ from azimut import config++ body = client.get("/api/settings/diagnostics").json()+ assert str(config.workspace_root()) not in body["report"]+++# -- the report reads as a report -----------------------------------------+++def test_report_leads_with_what_the_user_wrote():+ text = diagnostics.report("the map goes blank at zoom 19")+ assert text.index("the map goes blank at zoom 19") < text.index("### Environment")+ assert "### What happened" in text+ assert __version__ in text+++def test_report_prompts_when_nothing_was_typed():+ assert "<!-- Describe it here. -->" in diagnostics.report("")+++def test_report_says_so_when_no_warning_was_recorded(monkeypatch):+ monkeypatch.setattr(diagnostics, "_handler", None)+ assert "_None recorded this run._" in diagnostics.report()+++def test_an_idea_is_not_a_bug():+ text = diagnostics.report("a KML export", kind="idea")+ assert "### What you'd like" in text+ assert diagnostics.title("a KML export", kind="idea") == "Idea: a KML export"+++def test_each_kind_carries_a_label_the_repo_actually_has():+ """GitHub refuses the whole pre-filled form when a label doesn't exist, so+ these two stay GitHub's own defaults (`bug`, `enhancement`)."""+ assert {kind[2] for kind in diagnostics.KINDS.values()} == {"bug", "enhancement"}+ assert parse_qs(urlparse(diagnostics.payload("x")["url"]).query)["labels"] == ["bug"]+ assert parse_qs(urlparse(diagnostics.payload("x", kind="idea")["url"]).query)["labels"] == [+ "enhancement"+ ]+++def test_issue_url_omits_the_label_when_there_is_none():+ assert "labels=" not in diagnostics.issue_url("body", subject="Bug: x")+++def test_title_is_the_first_line_of_the_summary():+ assert diagnostics.title("blank map\nat zoom 19 only") == "Bug: blank map"+ assert diagnostics.title("") == "Bug: "+++def test_summary_is_bounded():+ text = diagnostics.report("z" * 5000)+ assert "z" * diagnostics.MAX_SUMMARY_CHARS in text+ assert "z" * (diagnostics.MAX_SUMMARY_CHARS + 1) not in text+++def test_install_kind_names_the_frozen_build(monkeypatch):+ monkeypatch.setattr(diagnostics.sys, "frozen", True, raising=False)+ assert diagnostics.install_kind() == "standalone binary"+++def test_environment_reports_a_missing_ffmpeg(monkeypatch):+ monkeypatch.setattr(diagnostics.ffmpeg, "ffmpeg_path", lambda: None)+ assert diagnostics.environment()["ffmpeg"] == "not found"+++# -- the link ---------------------------------------------------------------+++def test_issue_url_carries_the_title_and_body():+ url = diagnostics.issue_url("### What happened\n\nblank map\n", subject="Bug: blank map")+ assert url.startswith(diagnostics.ISSUE_NEW_URL + "?")+ query = parse_qs(urlparse(url).query)+ assert query["title"] == ["Bug: blank map"]+ assert "blank map" in query["body"][0]+++def test_issue_url_sheds_log_lines_to_fit_and_keeps_the_summary(ring):+ log = logging.getLogger("azimut.test")+ for i in range(diagnostics.LOG_LINES):+ log.warning("a tile request failed for a long-winded reason %d %s", i, "y" * 300)++ payload = diagnostics.payload("the map goes blank at zoom 19")+ assert len(payload["url"]) <= diagnostics.URL_LIMIT+ assert "the map goes blank at zoom 19" in body_of(payload["url"])+ assert diagnostics.TRIM_MARKER in body_of(payload["url"])+ # Copy still hands over everything the link had to drop.+ assert len(payload["report"]) > len(body_of(payload["url"]))+++def test_issue_url_fits_even_an_oversized_summary_alone():+ url = diagnostics.issue_url("q" * 20_000, subject="Bug: x")+ assert len(url) > 0 # terminates rather than looping on an unshrinkable body+++# -- the route --------------------------------------------------------------+++def test_diagnostics_route_returns_report_and_link(client):+ body = client.get("/api/settings/diagnostics?summary=blank+map&kind=bug").json()+ assert body["kind"] == "bug"+ assert body["title"] == "Bug: blank map"+ assert "blank map" in body["report"]+ assert body["url"].startswith(diagnostics.ISSUE_NEW_URL)+++def test_diagnostics_route_touches_no_network(client, monkeypatch):+ def explode(*args, **kwargs):+ raise AssertionError("a report must be built from local facts only")++ monkeypatch.setattr(httpx, "get", explode)+ monkeypatch.setattr(httpx, "post", explode)++ assert client.get("/api/settings/diagnostics").status_code == 200+++def test_diagnostics_route_falls_back_on_an_unknown_kind(client):+ body = client.get("/api/settings/diagnostics?kind=rant").json()+ assert body["kind"] == diagnostics.DEFAULT_KIND+++def test_diagnostics_route_shortens_rather_than_refusing_a_long_summary(client):+ body = client.get("/api/settings/diagnostics", params={"summary": "w" * 9000}).json()+ assert body["kind"] == diagnostics.DEFAULT_KIND+ assert "w" * diagnostics.MAX_SUMMARY_CHARS in body["report"]+++# -- the link fits without eating the report ------------------------------+++ "label, summary",+ [+ ("latin", "a" * diagnostics.MAX_SUMMARY_CHARS),+ ("accented latin", "é" * diagnostics.MAX_SUMMARY_CHARS),+ ("cyrillic", "ж" * 600),+ ("japanese", "事" * 400),+ ("emoji", "🛰" * 200),+ ],+)+def test_the_link_keeps_what_the_user_wrote(ring, label, summary, tmp_workspace):+ """The summary is capped in characters, but the link is measured in encoded+ characters — nine of them per letter in some scripts. A summary well inside the+ cap can therefore be several times the link's whole budget, and shedding+ blindly from the end would deliver a heading, a marker blaming the log, and+ none of the report."""+ built = diagnostics.payload(summary)+ body = body_of(built["url"])++ assert len(built["url"]) <= diagnostics.URL_LIMIT+ assert summary[0] in body, f"{label}: the user's own words were dropped"+ # and Copy always carries the whole thing, whatever the link had to drop+ assert summary in built["report"]+++def test_context_is_shed_before_content(ring, tmp_workspace):+ """A summary that fits leaves room for some context; one that does not takes+ the whole budget. Either way the order is the same: log first, environment+ next, the user's words last and only if nothing else is left."""+ log = logging.getLogger("azimut.test")+ for n in range(diagnostics.LOG_LINES):+ log.warning("a warning long enough to matter, number %s, %s", n, "x" * 300)++ modest = body_of(diagnostics.payload("It crashed on export.")["url"])+ assert "It crashed on export." in modest+ assert "### Environment" in modest+ assert diagnostics.TRIM_MARKER in modest # the log tail is what went++ huge = body_of(diagnostics.payload("é" * diagnostics.MAX_SUMMARY_CHARS)["url"])+ assert "### Recent warnings" not in huge+ assert "### Environment" not in huge+ # the marker names the right casualty rather than blaming the log+ assert diagnostics.SUMMARY_TRIM_MARKER in huge+ assert diagnostics.TRIM_MARKER not in huge+++def test_a_report_that_fits_is_left_whole(ring, tmp_workspace):+ body = body_of(diagnostics.payload("Short and to the point.")["url"])++ assert diagnostics.TRIM_MARKER not in body+ assert diagnostics.SUMMARY_TRIM_MARKER not in body+ assert "### Recent warnings" in body+++# -- the scrub covers what this app's logs actually carry ------------------+++def test_a_case_name_never_reaches_the_tracker(ring, tmp_workspace):+ """A case directory is a slug of the name the analyst typed, and in this tool+ that name is routinely a subject's. The path around it is useful; the segment+ is not ours to publish."""+ from azimut import config++ log = logging.getLogger("azimut.test")+ log.warning("could not open %s", config.cases_dir() / "operation-blue-heron" / "case.db")+ log.warning("scratch vanished: %s", config.scratch_dir() / "scratch_9f2c" / "media" / "a.jpg")++ captured = "\n".join(diagnostics.log_lines())++ assert "operation-blue-heron" not in captured+ assert "scratch_9f2c" not in captured+ assert "cases/<case>/case.db" in captured.replace("\\", "/")+ assert "scratch/<case>/media/a.jpg" in captured.replace("\\", "/")+++def test_a_credential_in_a_logged_url_is_redacted(ring, tmp_workspace):+ """A keyed imagery or geocoding provider is reached over HTTP, so a warning+ about one names the URL — key included."""+ log = logging.getLogger("azimut.test")+ log.warning("provider refused: https://api.example.com/v1?key=SECRET-ABC123&z=4")+ log.warning("upload rejected: token=eyJhbGciOiJIUzI1NiJ9.payload.sig")++ captured = "\n".join(diagnostics.log_lines())++ assert "SECRET-ABC123" not in captured+ assert "eyJhbGciOiJIUzI1NiJ9" not in captured+ assert "key=<redacted>&z=4" in captured+ assert "token=<redacted>" in captured+++def test_the_scrub_leaves_ordinary_prose_alone(tmp_workspace):+ """A blunt scrub that ate the word "cases" or every "key" would make the log+ tail useless, which is the one thing the report is for."""+ prose = "Two of the open cases and both API keys behave the same way"++ assert diagnostics.scrub(prose) == prose+++def test_a_workspace_outside_the_home_directory_is_still_hidden(monkeypatch, tmp_path):+ """A portable install can live anywhere — on a second disk, on a stick — and+ then no amount of home-collapsing hides where it is."""+ from azimut import config++ elsewhere = tmp_path / "volume" / "azimut-portable"+ monkeypatch.setattr(config, "workspace_root", lambda: elsewhere)+ # Home has to be pinned somewhere that is not an ancestor of the stick, or the+ # premise is gone: on Windows the temp directory lives *inside* the user+ # profile, so the real home would collapse the prefix first and there would be+ # nothing left for <workspace> to match.+ monkeypatch.setattr(diagnostics.Path, "home", staticmethod(lambda: tmp_path / "home"))++ scrubbed = diagnostics.scrub(f"failed to read {elsewhere / 'settings.json'}")++ assert str(elsewhere) not in scrubbed+ assert "<workspace>" in scrubbed+++# -- the environment block is read once -----------------------------------+++def test_the_environment_is_built_once_per_process(monkeypatch, tmp_workspace):+ """Reading the ffmpeg line runs `ffmpeg -version`, and About rebuilds the+ report as the user types. A subprocess per keystroke burst flashes a console+ window on Windows at someone in the middle of writing a bug report."""+ monkeypatch.setattr(diagnostics, "_environment", None)+ calls = []++ def counted() -> dict[str, object]:+ calls.append(1)+ return {"available": True, "path": "/x/ffmpeg", "source": "path", "version": "7.1"}++ monkeypatch.setattr(diagnostics.ffmpeg, "info", counted)++ for _ in range(5):+ diagnostics.payload("still typing…")++ assert len(calls) == 1+ assert diagnostics.environment()["ffmpeg"] == "7.1 (system PATH)"+++def test_the_cached_environment_cannot_be_mutated_by_a_caller(monkeypatch, tmp_workspace):+ monkeypatch.setattr(diagnostics, "_environment", None)+ first = diagnostics.environment()+ first["OS"] = "tampered"++ assert diagnostics.environment()["OS"] != "tampered"diff --git a/tests/test_settings_backup.py b/tests/test_settings_backup.pyindex ec25353..b953ccc 100644--- a/tests/test_settings_backup.py+++ b/tests/test_settings_backup.py@@ -1,8 +1,53 @@-"""Settings backup (export/import) and the lazy pairing-token mint."""+"""Settings backup (export/import) and the lazy pairing-token mint.++The backup is one JSON file carrying everything app-wide that isn't a case:+settings.json, templates.json and the signature logo. Two invariants are worth+more than the individual cases below — every setting that can be exported can be+imported back (the drift gate), and ``cookies.txt`` never travels.+"""++import base64import pytestfrom azimut import config+from azimut.api.settings import ImportedSettings++PNG = config.PNG_MAGIC + b"a tiny fake logo"+++def bundle_of(client) -> dict:+ return client.get("/api/settings/export").json()+++# -- the drift gate ---------------------------------------------------------++# Keys that settings.json holds but a backup deliberately does not restore.+# Empty on purpose: an entry here is a decision, and it needs a reason next to+# it. Anything else showing up in the gate below is an oversight, not a policy.+NOT_RESTORED: dict[str, str] = {}+++def test_every_exported_setting_can_be_imported_back():+ """The export dumps settings.json verbatim, so it can never fall behind; the+ import is an allowlist, so it can. This is the gate that says when it did.++ A new key in DEFAULT_SETTINGS fails here until it is either typed into+ ImportedSettings or listed in NOT_RESTORED with a reason. Without it, a+ forgotten key is exported and then silently dropped on the way back — which+ is exactly how `download_cookies` went missing.+ """+ exported = set(config.DEFAULT_SETTINGS)+ importable = {+ field.alias or name for name, field in ImportedSettings.model_fields.items()+ }+ unhandled = exported - importable - set(NOT_RESTORED)+ assert not unhandled, (+ f"settings key(s) {sorted(unhandled)} are exported but not importable: type them "+ "in ImportedSettings, or list them in NOT_RESTORED with the reason"+ )+ # And nothing claims to import a setting the app doesn't have.+ assert not importable - exporteddef test_opening_settings_does_not_mint_the_pairing_token(client):@@ -22,13 +67,13 @@ def test_export_then_import_restores_keys_and_prefs(client):exported = client.get("/api/settings/export")assert exported.headers["content-disposition"].startswith("attachment")blob = exported.json()- assert blob["api_keys"]["mapbox"] == "pk.exported"- assert blob["units"] == "imperial"+ assert blob["settings"]["api_keys"]["mapbox"] == "pk.exported"+ assert blob["settings"]["units"] == "imperial"- # wipe both, then restore from the exported blob+ # wipe both, then restore from the exported bundleclient.put("/api/settings/keys", json={"mapbox": ""})client.put("/api/settings/prefs", json={"units": "metric"})- res = client.post("/api/settings/import", json={"settings": blob}).json()+ res = client.post("/api/settings/import", json=blob).json()assert "api_keys" in res["imported"]restored = client.get("/api/settings").json()@@ -36,6 +81,152 @@ def test_export_then_import_restores_keys_and_prefs(client):assert restored["units"] == "imperial"+# -- what the bundle carries ------------------------------------------------+++def test_export_carries_templates_and_the_signature(client):+ client.post(+ "/api/templates/proof",+ json={"name": "House style", "data": {"frameColor": "#ff0000"}},+ )+ client.post("/api/settings/signature", files={"file": ("logo.png", PNG, "image/png")})++ blob = bundle_of(client)+ assert [t["name"] for t in blob["templates"]["proof"]] == ["House style"]+ assert base64.b64decode(blob["signature_png"]) == PNG+++def test_import_restores_templates_and_the_signature(client):+ client.post("/api/templates/post", json={"name": "Thread", "data": {"body": "hello"}})+ client.post("/api/settings/signature", files={"file": ("logo.png", PNG, "image/png")})+ blob = bundle_of(client)++ # a fresh machine: no presets, no logo+ template_id = client.get("/api/templates").json()["post"][0]["id"]+ client.delete(f"/api/templates/post/{template_id}")+ client.delete("/api/settings/signature")+ assert client.get("/api/settings").json()["signature"] is False++ res = client.post("/api/settings/import", json=blob).json()+ assert res["templates"] == 1+ assert res["signature"] is True+ assert [t["name"] for t in client.get("/api/templates").json()["post"]] == ["Thread"]+ assert config.signature_path().read_bytes() == PNG+++def test_export_leaves_the_login_session_behind(client):+ """cookies.txt is a live session: it stays on the machine that made it.++ Only the *choice* of login source travels (the test below); the session+ itself would expire in transit, trip the site's device checks, and multiply+ where a credential lives.+ """+ session = b"# Netscape HTTP Cookie File\n.x.com\tTRUE\t/\tTRUE\t0\tauth_token\tsecret\n"+ client.post(+ "/api/settings/cookies-file",+ files={"file": ("cookies.txt", session, "text/plain")},+ )+ assert config.cookies_file_path().is_file()++ raw = client.get("/api/settings/export").text+ assert "auth_token" not in raw+ assert "Netscape" not in raw+++def test_the_browser_login_choice_travels_but_a_missing_file_does_not(client):+ client.put(+ "/api/settings/prefs",+ json={"download_cookies": {"source": "browser", "browser": "firefox"}},+ )+ blob = bundle_of(client)+ assert blob["settings"]["download_cookies"] == {"source": "browser", "browser": "firefox"}++ client.put("/api/settings/prefs", json={"download_cookies": {"source": "none"}})+ client.post("/api/settings/import", json=blob)+ assert client.get("/api/settings").json()["download_cookies"] == {+ "source": "browser",+ "browser": "firefox",+ }+++def test_a_file_login_source_lands_on_none_because_the_file_never_travels(client):+ client.post("/api/settings/import", json={"settings": {"download_cookies": {"source": "file"}}})+ assert client.get("/api/settings").json()["download_cookies"] == {"source": "none"}+++def test_an_unknown_browser_lands_on_none(client):+ client.post(+ "/api/settings/import",+ json={"settings": {"download_cookies": {"source": "browser", "browser": "netscape"}}},+ )+ assert client.get("/api/settings").json()["download_cookies"]["source"] == "none"+++# -- restoring is forgiving where it can be, strict where it must be --------+++def test_an_older_backup_without_the_new_sections_still_imports(client):+ """A file written before templates and the logo travelled: settings only."""+ res = client.post("/api/settings/import", json={"settings": {"units": "imperial"}}).json()+ assert res == {"imported": ["units"], "templates": 0, "signature": False}+ assert client.get("/api/settings").json()["units"] == "imperial"+++def test_a_bundle_with_only_templates_imports(client):+ res = client.post(+ "/api/settings/import",+ json={"templates": {"schema": 1, "proof": [{"id": "a1", "name": "Style", "data": {}}]}},+ ).json()+ assert res["imported"] == []+ assert res["templates"] == 1+ assert [t["name"] for t in client.get("/api/templates").json()["proof"]] == ["Style"]+++def test_malformed_templates_are_dropped_not_saved(client):+ res = client.post(+ "/api/settings/import",+ json={"templates": {"schema": 1, "proof": [{"id": "bad id", "name": "", "data": "x"}]}},+ ).json()+ assert res["templates"] == 0+ assert client.get("/api/templates").json()["proof"] == []+++ "encoded",+ [+ "not base64 at all",+ base64.b64encode(b"GIF89a not a png").decode(),+ base64.b64encode(b"").decode(),+ ],+)+def test_a_bad_signature_is_dropped_without_failing_the_restore(client, encoded):+ res = client.post(+ "/api/settings/import",+ json={"settings": {"units": "imperial"}, "signature_png": encoded},+ )+ assert res.status_code == 200+ assert res.json()["signature"] is False+ # the valuable part still landed+ assert client.get("/api/settings").json()["units"] == "imperial"+ assert config.signature_path().is_file() is False+++def test_a_signature_over_the_size_cap_is_dropped_like_a_malformed_one(client):+ oversized = base64.b64encode(PNG + b"\0" * config.SIGNATURE_MAX_BYTES).decode()+ res = client.post("/api/settings/import", json={"signature_png": oversized})+ assert res.status_code == 200+ assert res.json()["signature"] is False+ assert config.signature_path().is_file() is False+++def test_a_grotesque_signature_field_is_refused_before_it_is_decoded(client):+ """The string bound comes first: a field far past any real logo is rejected+ without spending memory to base64-decode it."""+ res = client.post("/api/settings/import", json={"signature_png": "A" * 10_000_000})+ assert res.status_code == 422+ assert config.signature_path().is_file() is False++def test_import_ignores_unknown_keys(client):res = client.post("/api/settings/import", json={"settings": {"evil": "boom", "units": "imperial"}}@@ -91,3 +282,26 @@ def test_import_rejects_malformed_known_fields_without_partial_write(client, fieassert response.status_code == 422assert config.settings_path().read_bytes() == beforeassert config.load_settings()["units"] == "metric"+++def test_a_signature_no_gate_ever_saw_is_left_out_of_the_backup(client):+ """The upload route bounds what Settings accepts, but a file dropped into the+ workspace by hand has been through nothing. A backup is not the place to+ discover it: reading it whole to encode it is the work the gate exists to+ refuse."""+ from azimut import config++ path = config.signature_path()+ path.parent.mkdir(parents=True, exist_ok=True)++ # too big, even though it really is a PNG+ path.write_bytes(PNG + b"\x00" * (config.SIGNATURE_MAX_BYTES + 1))+ assert client.get("/api/settings/export").json()["signature_png"] == ""++ # small enough, but not a PNG at all+ path.write_bytes(b"GIF89a not really an image")+ assert client.get("/api/settings/export").json()["signature_png"] == ""++ # the real thing still travels+ path.write_bytes(PNG)+ assert base64.b64decode(client.get("/api/settings/export").json()["signature_png"]) == PNG