isis-report-lib — Architecture, Engineering, Security & Design Standards¶
Binding standards for contributors (human or agent). AGENTS.md covers the
daily workflow; this document covers why the code looks the way it does and
what must not be violated. Rules are written as MUST (CI or review blocks),
SHOULD (justify deviations in the PR), and GUIDELINE (preferred style).
The project's maxim: faithful presentation of data beats rigid layout. Every rule below serves it — the layout adapts to the data, missing data is explicit, and provenance is preserved. Nothing here may silently drop, invent, or misrepresent data.
Planned work lives in ROADMAP.md — consult it before starting
a feature so effort goes to the prioritized items first.
1. Architecture¶
1.1 The pipeline¶
payload (dict | ReportPayload | .toon)
→ Fetch → Process → HTML → PDF (service.TabularReportService.execute)
→ XLSX / CSV (export, no browser)
- MUST: all outputs share
service.prepare_report(payload), which returns exactly(dataset, layout, meta). No output path may build its own variant of the dataset — divergence between PDF and XLSX is a correctness bug. - MUST:
executekeeps the step order Fetch → Process → HTML → PDF. New stages (e.g. validation) slot into this order, never around it.
1.2 Module map and dependency direction¶
| Module | Owns | Must NOT import |
|---|---|---|
api.py |
public sync/async surface; _normalize_payload, _run |
anything except service/export/inputs/models/toon |
service.py |
orchestration, prepare_report, sections assembly |
pdf internals beyond get_pdf_from_html/close_owned_browser |
layout.py |
pure data shaping (build_report, aggregates, footnotes, color domains) |
rendering, pdf, export |
formatting.py |
pure value functions (masks, rules, scales, footnotes) | anything except babel, stdlib (lazy charts for sparkline SVG) |
rendering.py |
Jinja env, CSS vars/inlining | pdf, export |
pdf.py |
browser pool singleton (loop-bound) + egress route guard | rendering, export |
export.py |
collect_tables + XLSX/CSV builders |
rendering, pdf |
inputs.py |
adapters in (dataframe/csv/json) | output logic |
signing.py |
seal (bytes in/out); verify_* never raise |
network, filesystem |
charts.py, crosstab.py |
pure SVG strings / pure pivot math | I/O, network |
cli.py |
thin argv → API mapping; exit codes 0/1/2 |
business logic |
templates/ |
presentation only | Python |
- MUST: lower layers never import upper layers.
layout,formatting,charts,crosstabare pure: no I/O, no network, no global state (exceptfunctools.lru_cacheon side-effect-free functions). - GUIDELINE: lazy imports for optional extras (
openpyxl,pandas,css_inline,cryptography) with an install-hintImportError.
1.3 Shared state rules¶
- The Playwright pool (
pdf.py) is a singleton bound to one event loop. Foreign/closed-loop state is abandoned, never awaited (cross-loopawaithangs on Linux). The sync API shuts down only its own browser (close_owned_browser, current loop only). - Jinja environments are cached keyed by
template_dir. The browser context renders with JavaScript disabled — reports are static documents. - Mark assignment, numbering and totals are computed once in
prepare_reportwith shared traversal state, so HTML, XLSX and CSV always agree.
1.4 Data shapes¶
- Normalized layout fragments:
header/details/groups/footerfield-dict lists plus top-levelsummary. Field dicts carryname/label/format_mask/alignmentand optionalcell_rules,missing_text,substitutions,footnote(+_mark),color_scale(+_domain),data_bar,spark_*,aggregate,running_balance,visible*. export.Table/Columnmirror the layout so exports stay faithful without re-deriving anything.
2. Engineering¶
2.1 Dual API¶
- MUST: every new public feature ships as
async def a...plus a sync wrapper through_run(which handles an already-running loop). Pure helpers are exported in__init__.pyand added to__all__. - MUST: new public parameters are keyword-friendly. Never add a
positional parameter after a
functools.partial-bound function (context:formatter_forbindslocale/currencyby keyword, so templates and CSV code passfield=by keyword).
2.2 Types and validation¶
- MUST:
mypy srcis clean. Payloads aredict[str, Any]; validate at system boundaries (prepare_reportenforces theReportPayloadenvelope fail-closed, pluswith_meta_defaults/field normalizers), not in hot per-cell loops. - MUST: fail closed with
ValueErrornaming the offending value and the expected set (f"...: {x!r} (expected ...)"). Verdict-style APIs (verify_pdf) return result objects and never raise on input. - Recursion is bounded: parsers and builders convert
RecursionErrorintoValueError(seetoon,inputs.from_json,prepare_report).
2.3 Data integrity rules¶
- MUST NOT mutate caller-owned structures. Copy rows before enriching
(
_apply_running_balancepattern); normalize into fresh field dicts. - MUST be deterministic: sorted JSON keys, stable traversal order, shared numbering state. The same payload always yields the same bytes.
- MUST NOT silently drop data: empty tables render
empty_text(or a header plus export note);Nonerendersmissing_text(default blank, but explicit); unknown masks stringify; unobserved crosstab cells are0forcount/sumand blank otherwise — each documented.
2.4 Tests and gates¶
- Unit tests use mocks and never touch the network/browser; browser tests are
marked
browserand skip without Chromium. Match test file to source file. - Coverage gate is 85% (CI enforces; keep the suite near 100%).
bench/bench.py --checkis the perf gate: smoke-level budgets with headroom for shared runners, enforced in thee2ejob.- New behavior ships with tests; bugfixes ship with regression tests.
2.5 Docs and releases¶
- User-facing knobs (
README.mdparameters table) andCHANGELOG.md(Unreleased→ versioned sections on release) update in the same PR. docs/publishes as a Zensical site (docs.ymlbuild on PRs, deploy on push tomain); nav updates ship with the feature they document.- Conventional Commits;
mainvia squash-merge after thegatecheck. - Release: tag
vX.Y.Z+ GitHub Release → PyPI/TestPyPI via Trusted Publishing. Never publish from a laptop.
3. Security¶
The binding control mapping lives in ASVS.md
(OWASP ASVS 4.0.3, L1 target with L2/L3 where met); vulnerability reports
follow SECURITY.md. This section states the rules.
3.1 Trust boundaries¶
| Zone | Examples | Rule |
|---|---|---|
| Code (operator-trusted) | bundled/custom templates, CLI flags, keys | may execute; load templates only from trusted dirs |
| Schema (validated) | layout defs, meta, cell_rules, colors |
validate shape on ingest; escape on render |
| Data (untrusted) | records, CSV/JSON/dataframe cells, .toon values |
escaped, never executed; no network fetch triggered by it |
| Output (untrusted context) | HTML viewed in browsers/mail clients | must be safe to open: escaped, no scripts, no remote refs |
Report layout from untrusted authors is treated as schema: validated
strictly, escaped on output. Only template_dir is code. Network egress
policy (allowed_hosts) is operator configuration like template_dir and
keys: accepted from API/CLI arguments only, never from the payload.
3.2 Rendering rules (MUST)¶
- Jinja
autoescapestays ON. Only pre-built SVG (charts.*, returned asMarkup) is exempt — never mark caller-controlled strings. - No JavaScript in the PDF browser context (
java_script_enabled=False). - No remote resources at render time:
_inline_cssstrips<link>stylesheets instead of fetching them (email clients ignore them anyway). - Outbound http(s) from Chromium is denied by default via a per-page route
guard;
allowed_hosts(bare hostnames, API/CLI only) opts specific hosts back in. Data URIs and other non-network schemes always pass. - Spreadsheet safety: text cells starting with
= + - @(or tab/CR) are'-prefixed in CSV/XLSX; numeric values are never prefixed. verify_pdfis total: malformed blocks/keys/algorithms yieldinvalidverdicts, never exceptions.
3.3 Cryptography and secrets (MUST)¶
- HMAC-SHA256 via
hmac.compare_digeston a canonical JSON body that includeskey_id; Ed25519 keys are type-checked after PEM load; algorithms are allow-listed on both sign and verify paths. - Keys arrive as bytes (files); never log, print, or embed them in outputs.
Key files should be
0600(the CLI warns otherwise on POSIX). - Logs are single-line: caller-controlled fields go through
logging_utils.log_value, and the package logger installsLogEncodingFilterso CR/LF, ANSI/control characters and Unicode line separators cannot forge log entries. Never log keys, payload bodies or secrets. - Rotation runbook (no flag days): sign new reports with the new key under a
new
key_id; configure verifiers with the keyring ({key_id: key}mapping or ordered key list — the envelopekey_idselects first, the rest are tried in order); retire the old key once its seals expire out of circulation. - This is a tamper-evident seal, not Adobe PAdES: no CAs, no timestamps
as trust anchors (
issued_atis informational).
3.4 Supply chain (MUST)¶
pip-auditgates every PR (e2e job), including the docs env in isolation (docs/requirements-docs.txtin a throwaway venv, so its pins never leak into the test env); Dependabot stays enabled with a 7-daycooldownon version updates (security updates are exempt).- Every CI toolchain installs from a hash-pinned lock
(
.github/requirements/requirements-*.txt,docs/requirements-docs.txt) viapip install --require-hashes; the project itself installs editable with--no-depson top. Bump tools in the matching.infile and runscripts/lock-requirements.sh(uv, universal, py3.11) — never edit a.txtby hand. - Semgrep SAST gates every PR (plus push and weekly full scans): registry
pack (
p/default) and custom rules in.semgrep/locking §3.2 (sandboxed autoescaped templates,Markup-only-SVG, JS-disabled contexts, no network at render time); findings fail the job (--error) and upload as SARIF to code scanning undersemgrep. The scan image (semgrep/semgrep) is version-pinned; rule changes ship with fixture updates (semgrep --test). - Gitleaks secret scanning gates every PR (plus push and weekly scans of the
working tree and history); findings fail the job and upload as SARIF under
gitleaks. The scan image (zricethezav/gitleaks) is digest-pinned; a.pre-commit-config.yamlhook offers the same scan as an optional local gate. - GitHub Actions are pinned by commit SHA (with
# tagcomments);GITHUB_TOKENpermissions are minimal; publishing uses OIDC. - OpenSSF Scorecard runs weekly + on push (SARIF to code scanning); Codecov reports coverage via OIDC (no stored token; the gate stays on pytest).
- GuardDog scans the project's dependency environment for malicious packages
(capability + threat correlation; only
threat-*results upload as SARIF underguarddog— bare capabilities stay in the full artifact because they are expected in legitimate packages; the job gates on scanner health); dependency-review blocks vulnerable or copyleft-licensed deps on PRs (GPL/AGPL denied, LGPL/MPL allowed); apip-licensesgate fails closed on GPL/AGPL/unknown licenses. Socket Security (GitHub App) runs as an advisory PR check; it is not a required check, so GuardDog remains the blocking gate. - CodeQL advanced setup (Python + GitHub Actions,
nonebuild mode, default query suite, weekly + per-PR) complements Semgrep's fast patterns with cross-file dataflow; SARIF under/language:*. - Atheris fuzz targets (
.github/workflows/fuzz.yml) time-box every PR and run deeper weekly, covering the untrusted-input parsers (.toon, JSON payload envelope, layout specs). Each target asserts the fail-closed contract: data out orValueError, never an internal exception; a crash fails the job and uploads the minimized reproducer as an artifact. - Every GitHub Release (stable + prerelease) carries a reproducible
CycloneDX 1.6
sbom.json, built in an isolated env from the release wheel, plus Sigstore attestations (SLSA provenance fordist/*and the SBOM file) verifiable withgh attestation verify. Note: the generator omitsmetadata.component, so the SBOM is attested as a subject file — not viasbom-pathmode, which requires that field. - No secrets in the repo (
.envis gitignored); release artifacts come only from CI (twine check+ trusted publishing).
3.5 Security review checklist (every PR touching I/O, templates, export)¶
- Does any new output interpolate untrusted data without escaping?
- Does any new code fetch the network at render/generate time?
- Does any new browser capability get enabled (JS, plugins, downloads)?
- Does any new export path write attacker-controlled strings unevaluated?
- Does any new
verify_*/parser raise where callers expect a verdict/ValueError? - Does any new dependency widen the install or need a system package?
- Does any new log line include caller data without
log_value?
4. Design (data-first report design)¶
4.1 Principles¶
- Layout follows data. Buckets, columns and groups derive from observed values (crosstab, inferred layouts); the author declares mappings, never pixel positions.
- Absence is explicit.
missing_text,substitutions,empty_text, NaN→Nonenormalization — a blank cell must mean "no data", never "lost data". - Provenance travels with numbers. Footnotes and
source_note/sourcerender in every output (HTML list, XLSXNotessheet, CSV# [..]lines). - Totals agree everywhere. One aggregate implementation (
layout), reused by templates, crosstab and export — includingmedian/distinct. - Conditional presentation, unconditional data.
cell_rules,color_scale,data_bar, sparklines and visibility never remove values;$print_when/$order_byare the only row operators, and both are declarative in the payload.
4.2 Template conventions¶
- Templates render; they don't compute. Formatting goes through
fmt(value, mask, field=...), conditional style throughcellstyle(value, field). - New macro parameters default (
mark="",empty_text="") so custom templates overriding bundled macros keep working. - Header labels carry footnote
<sup>marks; notes lists close each report/section;sourcelines sit under their section. - Print CSS keeps groups together (
break-after/inside: avoidon headers, rows, summaries) and repeatsthead; the page footer carries timestamp, pagination and brand.
4.3 Email-safe output (inline_css=True)¶
- Stylesheets are inlined and CSS variables resolved to literals (Outlook
ignores
var());<html lang>followsmeta.locale;color-scheme: lightis declared. - No external resources, no scripts, no flex-dependent critical layout — degradation is graceful and content-complete.
4.4 XLSX/CSV fidelity contract¶
- Same labels, numbers, totals and notes as the HTML report.
- Native Excel types with number formats;
data_baruses native conditional formatting; empty tables keep headers plus their note. - Formula guard is disclosed (leading
');Notessheets never shift data rows (appended last).
5. Changing these standards¶
Amendments ship as PRs against this file with rationale and, when they alter guarantees (escaping, exports, verification), regression tests. The maxim outranks every rule: on conflict, prefer the option that keeps displayed data faithful.
References (normative for §3)¶
- OWASP Application Security Verification Standard 4.0.3 —
docs/ASVS.mdmaps each applicable requirement to evidence. - OWASP Cheat Sheets: Cross Site Scripting Prevention, Injection Prevention in Python, Deserialization, Key Management, Logging.
- CWE: CWE-79 (XSS), CWE-918 (SSRF), CWE-502 (deserialization), CWE-327/798/320 (crypto/keys), CWE-400 (DoS), CWE-22/73/78/98 (path/file injection), CWE-116/176 (encoding), CWE-829 (untrusted includes).
- SLSA / Sigstore provenance model: releases ship via OIDC trusted publishing; Actions are SHA-pinned.
- Keep a Changelog + Conventional Commits (process standards).