de-censor 0.7.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,191 @@
1
+ """Secrets belong in environment variables (`*_env`, `${VAR}`), never in spec text."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+ from collections.abc import Iterator
7
+ from typing import Final, cast
8
+
9
+ import yaml
10
+
11
+ from censor.context import ProjectContext, SpecFile
12
+ from censor.model import CheckResult, Dimension, Status
13
+
14
+ _ENV_REF: Final = "${"
15
+ _TOKEN_PATTERNS: Final[tuple[tuple[str, re.Pattern[str]], ...]] = (
16
+ ("AWS access key", re.compile(r"\bAKIA[0-9A-Z]{16}\b")),
17
+ ("GitHub token", re.compile(r"\b(?:ghp_[A-Za-z0-9]{36}|github_pat_[A-Za-z0-9_]{20,})\b")),
18
+ ("Slack token", re.compile(r"\bxox[baprs]-[A-Za-z0-9-]{10,}\b")),
19
+ ("API secret key", re.compile(r"(?<![\w/.-])sk-[A-Za-z0-9_-]{20,}\b")),
20
+ )
21
+ _URL_CREDENTIALS: Final = re.compile(
22
+ r"[a-z][a-z0-9+.-]*://[^\s/:@]*:(?P<password>[^\s/@]+)@", re.IGNORECASE
23
+ )
24
+ _PRIVATE_KEY: Final = re.compile(r"-----BEGIN (?:[A-Z0-9]+ )*PRIVATE KEY-----")
25
+ _QUERY_SECRET: Final = re.compile(
26
+ r"[?&](?:api_key|apikey|access_token|token|key)=(?P<value>[^&\s#]+)", re.IGNORECASE
27
+ )
28
+ _DSN_PASSWORD: Final = re.compile(r"(?:^|\s)password=(?P<value>'[^']*'|[^\s'\"]+)", re.IGNORECASE)
29
+ # Matches the whole key: `client_secret`, `x-api-key`; never `token_env` or `token_url`.
30
+ _SECRET_KEY_NAME: Final = re.compile(
31
+ r"(?:^|[_-])(?:authorization|api[_-]?key|token|access[_-]?token|password|passwd|pwd"
32
+ r"|secret|client[_-]?secret|private[_-]?key)$",
33
+ re.IGNORECASE,
34
+ )
35
+ # Line-scan fallback for text that is not YAML.
36
+ _SECRET_KEY_LINE: Final = re.compile(
37
+ r"^\s*[\"']?(authorization|x-api-key|api[_-]?key|token|password|secret)[\"']?\s*:\s*(.*)$",
38
+ re.IGNORECASE,
39
+ )
40
+ _NON_SECRET_SCALARS: Final = frozenset(
41
+ {"null", "~", "true", "false", "yes", "no", "on", "off", "|", ">", "|-", ">-", "|+", ">+"}
42
+ )
43
+ _FIX: Final = (
44
+ "move the value to an environment variable (`dsn_env`, `token_env`, `${VAR}`) and rotate it"
45
+ )
46
+
47
+
48
+ def _literal_scalar(value: str) -> bool:
49
+ value = value.strip().strip("\"'").strip()
50
+ return bool(value) and _ENV_REF not in value and value.lower() not in _NON_SECRET_SCALARS
51
+
52
+
53
+ def _literal_value(value: str) -> bool:
54
+ return _literal_scalar(value.split(" #", 1)[0])
55
+
56
+
57
+ def _pattern_secret(text: str) -> str | None:
58
+ """Kinds that are recognisable anywhere: in a value, a comment or a non-YAML line."""
59
+ for kind, pattern in _TOKEN_PATTERNS:
60
+ if pattern.search(text):
61
+ return kind
62
+ url = _URL_CREDENTIALS.search(text)
63
+ if url and _ENV_REF not in url.group("password"):
64
+ return "credentials in URL"
65
+ if _PRIVATE_KEY.search(text):
66
+ return "private key"
67
+ return None
68
+
69
+
70
+ def _value_secret(value: str) -> str | None:
71
+ kind = _pattern_secret(value)
72
+ if kind:
73
+ return kind
74
+ query = _QUERY_SECRET.search(value)
75
+ if query and _literal_scalar(query.group("value")):
76
+ return "secret in query string"
77
+ dsn = _DSN_PASSWORD.search(value)
78
+ if dsn and _literal_scalar(dsn.group("value")):
79
+ return "password in DSN"
80
+ return None
81
+
82
+
83
+ def _line_secret(line: str) -> str | None:
84
+ kind = _pattern_secret(line)
85
+ if kind or line.lstrip().startswith("#"):
86
+ return kind # only the key-name heuristic skips comments: `# password: x` is prose
87
+ key = _SECRET_KEY_LINE.match(line)
88
+ if key and _literal_value(key.group(2)):
89
+ return f"literal {key.group(1).lower()}"
90
+ return None
91
+
92
+
93
+ def _scan_lines(text: str) -> list[tuple[int, str]]:
94
+ found: list[tuple[int, str]] = []
95
+ for number, line in enumerate(text.splitlines(), start=1):
96
+ kind = _line_secret(line)
97
+ if kind:
98
+ found.append((number, kind))
99
+ return found
100
+
101
+
102
+ def _scalar_line(node: yaml.ScalarNode, kind: str) -> int:
103
+ line = node.start_mark.line + 1
104
+ if node.style != "|":
105
+ return line
106
+ for offset, text in enumerate(node.value.splitlines(), start=1):
107
+ if _value_secret(text) == kind:
108
+ return line + offset # a literal block keeps its lines: report the one that leaked
109
+ return line
110
+
111
+
112
+ class _Walker:
113
+ def __init__(self) -> None:
114
+ self.found: set[tuple[int, str]] = set()
115
+ self._seen: set[int] = set()
116
+
117
+ def walk(self, node: yaml.Node) -> None:
118
+ if id(node) in self._seen: # aliases can make the graph cyclic
119
+ return
120
+ self._seen.add(id(node))
121
+ if isinstance(node, yaml.ScalarNode):
122
+ kind = _value_secret(node.value)
123
+ if kind:
124
+ self.found.add((_scalar_line(node, kind), kind))
125
+ elif isinstance(node, yaml.SequenceNode):
126
+ for child in cast(list[yaml.Node], node.value):
127
+ self.walk(child)
128
+ elif isinstance(node, yaml.MappingNode):
129
+ for key, value in cast(list[tuple[yaml.Node, yaml.Node]], node.value):
130
+ self._pair(key, value)
131
+
132
+ def _pair(self, key: yaml.Node, value: yaml.Node) -> None:
133
+ self.walk(key)
134
+ self.walk(value)
135
+ if not (isinstance(key, yaml.ScalarNode) and isinstance(value, yaml.ScalarNode)):
136
+ return
137
+ if not _SECRET_KEY_NAME.search(key.value) or _value_secret(value.value):
138
+ return # a recognised value pattern already reported this pair
139
+ if _literal_scalar(value.value):
140
+ self.found.add((key.start_mark.line + 1, f"literal {key.value.lower()}"))
141
+
142
+
143
+ def find_secrets(text: str) -> list[tuple[int, str]]:
144
+ """Return (1-based line, kind) for each literal secret. Never returns the value."""
145
+ try:
146
+ composed = cast(
147
+ Iterator[yaml.Node | None],
148
+ yaml.compose_all(text, Loader=yaml.SafeLoader), # pyright: ignore[reportUnknownMemberType]
149
+ )
150
+ documents = list(composed)
151
+ except yaml.YAMLError:
152
+ return _scan_lines(text)
153
+ walker = _Walker()
154
+ for document in documents:
155
+ if document is not None:
156
+ walker.walk(document)
157
+ for number, line in enumerate(text.splitlines(), start=1):
158
+ kind = _pattern_secret(line)
159
+ if kind:
160
+ walker.found.add((number, kind))
161
+ return sorted(walker.found)
162
+
163
+
164
+ def _check_file(spec: SpecFile) -> CheckResult:
165
+ if spec.read_error is not None:
166
+ return CheckResult(
167
+ id=f"security.secrets:{spec.name}",
168
+ dimension=Dimension.SECURITY,
169
+ weight=5,
170
+ status=Status.NA,
171
+ subject=spec.name,
172
+ evidence=f"could not read: {spec.read_error}",
173
+ )
174
+ found = find_secrets(spec.text)
175
+ evidence = (
176
+ "; ".join(f"line {n}: {kind}" for n, kind in found) if found else "no literal secrets"
177
+ )
178
+ return CheckResult(
179
+ id=f"security.secrets:{spec.name}",
180
+ dimension=Dimension.SECURITY,
181
+ weight=5,
182
+ status=Status.FAIL if found else Status.PASS,
183
+ blocker=bool(found),
184
+ subject=spec.name,
185
+ evidence=evidence,
186
+ fix=_FIX if found else "",
187
+ )
188
+
189
+
190
+ def check_security(ctx: ProjectContext) -> list[CheckResult]:
191
+ return [_check_file(s) for s in (*ctx.pipelines, *ctx.transform_files)]
censor/cli.py ADDED
@@ -0,0 +1,109 @@
1
+ """censor CLI. JSON on stdout, people on stderr. Exit 0 clean, 1 failures, 2 tool error."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Sequence
6
+ from enum import StrEnum
7
+ from pathlib import Path
8
+ from typing import Annotated
9
+
10
+ import typer
11
+
12
+ from arsenal_core.errors import ArsenalError
13
+ from censor.audit import audit_project
14
+ from censor.history import diff_reports, list_reports, load_report, save_report, unique_run_id
15
+ from censor.report import Lang, render_markdown
16
+
17
+ app = typer.Typer(help="Censor — audit a DE Arsenal project and grade it.", no_args_is_help=True)
18
+
19
+ EXIT_FAILURES = 1
20
+ EXIT_TOOL_ERROR = 2
21
+
22
+
23
+ class Tier(StrEnum):
24
+ QUICK = "quick"
25
+ STANDARD = "standard"
26
+
27
+
28
+ def _err(message: str) -> None:
29
+ typer.echo(message, err=True)
30
+
31
+
32
+ @app.command()
33
+ def audit(
34
+ project: Annotated[Path, typer.Argument(help="Project directory")] = Path("."),
35
+ lang: Annotated[str, typer.Option("--lang", help="Report language: en or ko")] = "en",
36
+ json_only: Annotated[bool, typer.Option("--json-only", help="No summary on stderr")] = False,
37
+ tier: Annotated[
38
+ Tier, typer.Option("--tier", help="quick reads files only; standard is not available yet")
39
+ ] = Tier.QUICK,
40
+ ) -> None:
41
+ """Grade a project (quick tier: reads files only, runs nothing)."""
42
+ if lang not in ("en", "ko"):
43
+ raise typer.BadParameter("use en or ko", param_hint="--lang")
44
+ if tier is not Tier.QUICK:
45
+ _err(f"censor: tier {tier.value} is not available in this version")
46
+ raise typer.Exit(EXIT_TOOL_ERROR)
47
+ report_lang: Lang = "ko" if lang == "ko" else "en"
48
+ try:
49
+ audited = audit_project(project)
50
+ except ArsenalError as e:
51
+ _err(f"censor: {e}")
52
+ raise typer.Exit(EXIT_TOOL_ERROR) from e
53
+ run_id = unique_run_id(project.absolute(), audited.run_id)
54
+ result = audited.model_copy(update={"run_id": run_id})
55
+ typer.echo(result.model_dump_json(indent=2))
56
+ if not json_only:
57
+ score = "-" if result.score is None else f"{result.score:.1f}"
58
+ _err(f"grade {result.grade or '-'} · score {score} · run {result.run_id}")
59
+ try:
60
+ save_report(result, project.absolute(), markdown=render_markdown(result, report_lang))
61
+ except OSError as e:
62
+ _err(f"censor: could not save the run under {project}/.arsenal/censor: {e}")
63
+ raise typer.Exit(EXIT_TOOL_ERROR) from e
64
+ if result.has_failures:
65
+ raise typer.Exit(EXIT_FAILURES)
66
+
67
+
68
+ @app.command()
69
+ def report(project: Annotated[Path, typer.Argument()] = Path(".")) -> None:
70
+ """List saved runs: run id, grade, score."""
71
+ listing = list_reports(project.absolute())
72
+ for path in listing.skipped:
73
+ _err(f"censor: skipped unreadable saved run {path}")
74
+ for saved in listing.reports:
75
+ score = "-" if saved.score is None else f"{saved.score:.1f}"
76
+ typer.echo(f"{saved.run_id}\t{saved.grade or '-'}\t{score}")
77
+
78
+
79
+ @app.command()
80
+ def compare(
81
+ run_a: str,
82
+ run_b: str,
83
+ project: Annotated[Path, typer.Option("--project")] = Path("."),
84
+ ) -> None:
85
+ """Show the checks whose status changed between two saved runs."""
86
+ try:
87
+ before = load_report(project.absolute(), run_a)
88
+ after = load_report(project.absolute(), run_b)
89
+ except ArsenalError as e:
90
+ _err(f"censor: {e}")
91
+ raise typer.Exit(EXIT_TOOL_ERROR) from e
92
+ for change in diff_reports(before, after):
93
+ old = change.before.value if change.before else "absent"
94
+ new = change.after.value if change.after else "absent"
95
+ typer.echo(f"{change.id}: {old} -> {new}")
96
+
97
+
98
+ def run_cli(argv: Sequence[str]) -> int:
99
+ """Run the CLI in-process and return its exit code (used by `arsenal eval`)."""
100
+ command = typer.main.get_command(app)
101
+ # Standalone mode prints usage errors and always ends in SystemExit. Catching that avoids
102
+ # Typer's vendored Click exception classes, which are not public API (typer 0.26).
103
+ try:
104
+ command.main(args=list(argv), prog_name="censor", standalone_mode=True)
105
+ except SystemExit as e:
106
+ if e.code is None:
107
+ return 0
108
+ return e.code if isinstance(e.code, int) else EXIT_TOOL_ERROR
109
+ return 0
censor/context.py ADDED
@@ -0,0 +1,74 @@
1
+ """Load a DE Arsenal project for auditing without running or changing anything."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass
6
+ from pathlib import Path
7
+ from typing import Any, cast
8
+
9
+ import yaml
10
+ from arsenal.project import ArsenalProject, DbtProjectRef, load_project
11
+
12
+ from arsenal_core.errors import ArsenalError, FatalError
13
+
14
+ MANIFEST_NAME = "arsenal.yaml"
15
+
16
+
17
+ @dataclass(frozen=True)
18
+ class SpecFile:
19
+ path: Path
20
+ root: Path
21
+ text: str
22
+ raw: dict[str, Any] | None
23
+ read_error: str | None = None
24
+
25
+ @property
26
+ def name(self) -> str:
27
+ try:
28
+ return str(self.path.relative_to(self.root))
29
+ except ValueError:
30
+ return str(self.path)
31
+
32
+
33
+ @dataclass(frozen=True)
34
+ class ProjectContext:
35
+ root: Path
36
+ manifest: ArsenalProject | None
37
+ manifest_error: str | None
38
+ pipelines: tuple[SpecFile, ...]
39
+ transforms: tuple[Path | DbtProjectRef, ...]
40
+ transform_files: tuple[SpecFile, ...]
41
+
42
+
43
+ def _reason(error: Exception) -> str:
44
+ if isinstance(error, OSError) and error.strerror:
45
+ return error.strerror
46
+ return str(error) or type(error).__name__
47
+
48
+
49
+ def _read_spec(path: Path, root: Path) -> SpecFile:
50
+ try:
51
+ text = path.read_text(encoding="utf-8")
52
+ except (OSError, UnicodeDecodeError) as e:
53
+ return SpecFile(path, root, "", None, read_error=_reason(e))
54
+ try:
55
+ loaded: object = yaml.safe_load(text)
56
+ except yaml.YAMLError:
57
+ return SpecFile(path, root, text, None)
58
+ raw = cast(dict[str, Any], loaded) if isinstance(loaded, dict) else None
59
+ return SpecFile(path, root, text, raw)
60
+
61
+
62
+ def load_context(root: Path) -> ProjectContext:
63
+ root = root.absolute()
64
+ manifest_path = root / MANIFEST_NAME
65
+ if not manifest_path.is_file():
66
+ raise FatalError(f"no {MANIFEST_NAME} in {root}; pass a DE Arsenal project directory")
67
+ try:
68
+ manifest = load_project(manifest_path)
69
+ except ArsenalError as e:
70
+ return ProjectContext(root, None, str(e), (), (), ())
71
+ pipelines = tuple(_read_spec(p, root) for p in manifest.pipelines)
72
+ transforms = tuple(manifest.transforms)
73
+ transform_files = tuple(_read_spec(t, root) for t in transforms if isinstance(t, Path))
74
+ return ProjectContext(root, manifest, None, pipelines, transforms, transform_files)
censor/grade.py ADDED
@@ -0,0 +1,28 @@
1
+ """The only definition of grade thresholds. Change them here and nowhere else."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Final
6
+
7
+ GRADE_THRESHOLDS: Final[tuple[tuple[str, float], ...]] = (
8
+ ("A+", 95.0),
9
+ ("A", 90.0),
10
+ ("B", 80.0),
11
+ ("C", 70.0),
12
+ ("D", 60.0),
13
+ )
14
+ LOWEST_GRADE: Final = "F"
15
+ BLOCKER_CAP: Final = "C"
16
+ _ORDER: Final = tuple(grade for grade, _ in GRADE_THRESHOLDS) + (LOWEST_GRADE,)
17
+
18
+
19
+ def score_to_grade(score: float) -> str:
20
+ for grade, floor in GRADE_THRESHOLDS:
21
+ if score >= floor:
22
+ return grade
23
+ return LOWEST_GRADE
24
+
25
+
26
+ def cap_grade(grade: str, cap: str) -> str:
27
+ """Return the worse of `grade` and `cap`."""
28
+ return grade if _ORDER.index(grade) >= _ORDER.index(cap) else cap
censor/history.py ADDED
@@ -0,0 +1,143 @@
1
+ """Run history under <base>/.arsenal/censor/. Parquet so `gladius query` can aggregate it."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ from collections.abc import Callable
7
+ from dataclasses import dataclass
8
+ from pathlib import Path
9
+ from typing import Final
10
+
11
+ import pyarrow as pa
12
+ import pyarrow.parquet as pq
13
+ from pydantic import ValidationError
14
+
15
+ from arsenal_core.errors import FatalError
16
+ from censor.model import AuditReport, Status
17
+
18
+ CENSOR_SUBDIR: Final = Path(".arsenal") / "censor"
19
+
20
+
21
+ @dataclass(frozen=True)
22
+ class CheckChange:
23
+ id: str
24
+ before: Status | None
25
+ after: Status | None
26
+
27
+
28
+ def censor_dir(base: Path) -> Path:
29
+ return base / CENSOR_SUBDIR
30
+
31
+
32
+ def _atomic_write(path: Path, write: Callable[[Path], object]) -> None:
33
+ """Write via a temp file in the same directory, then replace; clean up on failure."""
34
+ tmp = path.with_name(f".{path.name}.tmp")
35
+ tmp.unlink(missing_ok=True) # never write through a planted temp symlink
36
+ try:
37
+ write(tmp)
38
+ os.replace(tmp, path)
39
+ except BaseException:
40
+ tmp.unlink(missing_ok=True)
41
+ raise
42
+
43
+
44
+ def _write_parquet(report: AuditReport, tmp: Path) -> None:
45
+ run = {
46
+ "run_id": report.run_id,
47
+ "tier": report.tier,
48
+ "target": report.target,
49
+ "target_kind": report.target_kind,
50
+ "censor_version": report.censor_version,
51
+ }
52
+ rows = [{**run, **c.model_dump(mode="json")} for c in report.checks]
53
+ try:
54
+ pq.write_table( # pyright: ignore[reportUnknownMemberType]
55
+ pa.Table.from_pylist(rows), tmp, compression="zstd"
56
+ )
57
+ except pa.ArrowException as e:
58
+ raise OSError(f"could not write parquet: {e}") from e
59
+
60
+
61
+ def _ensure_inside(base: Path, root: Path, dirs: tuple[Path, ...]) -> None:
62
+ """Refuse to write history anywhere but under `base`: no symlinked dirs, no escape."""
63
+ for path in (base / ".arsenal", root, *dirs):
64
+ if path.is_symlink():
65
+ raise OSError(f"{path} is a symlink; refusing to write run history through it")
66
+ if not root.resolve().is_relative_to(base.resolve()):
67
+ raise OSError(f"{root} resolves outside {base}; refusing to write run history there")
68
+
69
+
70
+ def unique_run_id(base: Path, run_id: str) -> str:
71
+ """`run_id`, or `run_id-2`, `-3`, ... when a saved run already has that id."""
72
+ runs = censor_dir(base) / "runs"
73
+ candidate, n = run_id, 1
74
+ while (runs / f"{candidate}.json").exists():
75
+ n += 1
76
+ candidate = f"{run_id}-{n}"
77
+ return candidate
78
+
79
+
80
+ def save_report(report: AuditReport, base: Path, *, markdown: str) -> Path:
81
+ """Write parquet and markdown first and the JSON last: the JSON is what marks a run."""
82
+ root = censor_dir(base)
83
+ runs = root / "runs"
84
+ reports = root / "reports"
85
+ _ensure_inside(base, root, (runs, reports))
86
+ runs.mkdir(parents=True, exist_ok=True)
87
+ reports.mkdir(parents=True, exist_ok=True)
88
+ gitignore = root / ".gitignore"
89
+ if not gitignore.exists() and not gitignore.is_symlink():
90
+ gitignore.write_text("*\n", encoding="utf-8")
91
+ json_path = runs / f"{report.run_id}.json"
92
+ _atomic_write(runs / f"{report.run_id}.parquet", lambda t: _write_parquet(report, t))
93
+ _atomic_write(
94
+ reports / f"{report.run_id}.md", lambda t: t.write_text(markdown, encoding="utf-8")
95
+ )
96
+ body = report.model_dump_json(indent=2) + "\n"
97
+ _atomic_write(json_path, lambda t: t.write_text(body, encoding="utf-8"))
98
+ return json_path
99
+
100
+
101
+ def _read_report(path: Path) -> AuditReport:
102
+ try:
103
+ return AuditReport.model_validate_json(path.read_text(encoding="utf-8"))
104
+ except (OSError, UnicodeDecodeError, ValidationError) as e:
105
+ reason = str(e).splitlines()[0] if str(e) else type(e).__name__
106
+ raise FatalError(f"saved run {path.stem} is unreadable ({path}): {reason}") from e
107
+
108
+
109
+ def load_report(base: Path, run_id: str) -> AuditReport:
110
+ if not run_id or run_id.startswith(".") or "/" in run_id or "\\" in run_id:
111
+ raise FatalError(f"invalid run id: {run_id!r}")
112
+ path = censor_dir(base) / "runs" / f"{run_id}.json"
113
+ if not path.is_file():
114
+ raise FatalError(f"no saved run {run_id} in {censor_dir(base)}")
115
+ return _read_report(path)
116
+
117
+
118
+ @dataclass(frozen=True)
119
+ class HistoryListing:
120
+ reports: list[AuditReport]
121
+ skipped: list[Path]
122
+
123
+
124
+ def list_reports(base: Path) -> HistoryListing:
125
+ runs = censor_dir(base) / "runs"
126
+ reports: list[AuditReport] = []
127
+ skipped: list[Path] = []
128
+ for path in sorted(runs.glob("*.json")) if runs.is_dir() else []:
129
+ try:
130
+ reports.append(_read_report(path))
131
+ except FatalError:
132
+ skipped.append(path)
133
+ return HistoryListing(reports, skipped)
134
+
135
+
136
+ def diff_reports(before: AuditReport, after: AuditReport) -> list[CheckChange]:
137
+ a = {c.id: c.status for c in before.checks}
138
+ b = {c.id: c.status for c in after.checks}
139
+ return [
140
+ CheckChange(check_id, a.get(check_id), b.get(check_id))
141
+ for check_id in sorted(a.keys() | b.keys())
142
+ if a.get(check_id) != b.get(check_id)
143
+ ]
censor/model.py ADDED
@@ -0,0 +1,82 @@
1
+ """Frozen result models. `AuditReport` is the stdout JSON contract (schemas/censor-report.json)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from enum import StrEnum
6
+ from typing import Literal
7
+
8
+ from pydantic import BaseModel, ConfigDict, Field
9
+
10
+
11
+ class Status(StrEnum):
12
+ PASS = "pass"
13
+ WARN = "warn"
14
+ FAIL = "fail"
15
+ NA = "na"
16
+ ERROR = "error"
17
+
18
+
19
+ class Dimension(StrEnum):
20
+ CORRECTNESS = "correctness"
21
+ GUARDS = "guards"
22
+ SECURITY = "security"
23
+ OPERABILITY = "operability"
24
+ AGENT_READINESS = "agent_readiness"
25
+ RELIABILITY = "reliability"
26
+ FRESHNESS = "freshness"
27
+ DATA_HEALTH = "data_health"
28
+
29
+
30
+ DIMENSION_WEIGHTS: dict[Dimension, int] = {
31
+ Dimension.CORRECTNESS: 20,
32
+ Dimension.GUARDS: 15,
33
+ Dimension.SECURITY: 15,
34
+ Dimension.OPERABILITY: 5,
35
+ Dimension.AGENT_READINESS: 5,
36
+ Dimension.RELIABILITY: 15,
37
+ Dimension.FRESHNESS: 10,
38
+ Dimension.DATA_HEALTH: 15,
39
+ }
40
+
41
+
42
+ class _Frozen(BaseModel):
43
+ model_config = ConfigDict(frozen=True, extra="forbid")
44
+
45
+
46
+ class CheckResult(_Frozen):
47
+ id: str = Field(description="Stable check id, e.g. `guards.validate:collect.yaml`")
48
+ dimension: Dimension
49
+ weight: int = Field(ge=1)
50
+ status: Status
51
+ blocker: bool = Field(default=False, description="A failed blocker caps the grade at C")
52
+ subject: str = Field(description="File, table or directory the check looked at")
53
+ evidence: str = Field(description="What was found; never contains a secret value")
54
+ fix: str = Field(default="", description="One line on how to fix it")
55
+
56
+
57
+ class DimensionScore(_Frozen):
58
+ dimension: Dimension
59
+ weight: int
60
+ score: float | None = Field(description="0-10, or null when no check applied")
61
+
62
+
63
+ class AuditReport(_Frozen):
64
+ schema_version: Literal[1] = 1
65
+ run_id: str
66
+ tier: Literal["quick", "standard"] = Field(
67
+ description="quick reads files only; standard (not available yet) also reads state and data"
68
+ )
69
+ target: str
70
+ target_kind: Literal["project", "files", "duckdb", "postgres"] = Field(
71
+ description="What `target` names; Plan 1 audits a DE Arsenal `project` only"
72
+ )
73
+ censor_version: str
74
+ score: float | None = Field(description="0-100, or null when nothing applied")
75
+ grade: str | None
76
+ capped_by_blocker: bool
77
+ dimensions: list[DimensionScore]
78
+ checks: list[CheckResult]
79
+
80
+ @property
81
+ def has_failures(self) -> bool:
82
+ return any(c.status in (Status.FAIL, Status.ERROR) for c in self.checks)
censor/py.typed ADDED
File without changes
censor/report.py ADDED
@@ -0,0 +1,63 @@
1
+ """Markdown report: grade -> dimensions -> what to fix."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Final, Literal
6
+
7
+ from censor.model import AuditReport, Status
8
+
9
+ Lang = Literal["en", "ko"]
10
+ _LABELS: Final[dict[Lang, dict[str, str]]] = {
11
+ "en": {
12
+ "grade": "Grade",
13
+ "score": "score",
14
+ "capped": "capped at C by a failed blocker",
15
+ "dimension": "Dimension",
16
+ "dim_score": "Score (0-10)",
17
+ "fix_heading": "To fix",
18
+ "nothing": "Nothing to fix.",
19
+ "none": "no grade: no check applied",
20
+ },
21
+ "ko": {
22
+ "grade": "등급",
23
+ "score": "점수",
24
+ "capped": "차단 체크 실패로 C 상한 적용",
25
+ "dimension": "차원",
26
+ "dim_score": "점수 (0-10)",
27
+ "fix_heading": "고칠 항목",
28
+ "nothing": "고칠 항목이 없습니다.",
29
+ "none": "등급 없음: 적용된 체크가 없음",
30
+ },
31
+ }
32
+ _ORDER: Final = {Status.FAIL: 0, Status.ERROR: 1, Status.WARN: 2}
33
+
34
+
35
+ def render_markdown(report: AuditReport, lang: Lang = "en") -> str:
36
+ t = _LABELS[lang]
37
+ lines = [
38
+ f"# Censor report — {report.run_id}",
39
+ "",
40
+ f"`{report.target}` · tier {report.tier}",
41
+ "",
42
+ ]
43
+ if report.grade is None or report.score is None:
44
+ lines.append(t["none"])
45
+ else:
46
+ capped = f" ({t['capped']})" if report.capped_by_blocker else ""
47
+ lines.append(f"**{t['grade']} {report.grade}** · {t['score']} {report.score:.1f}{capped}")
48
+ lines += ["", f"| {t['dimension']} | {t['dim_score']} |", "|---|---|"]
49
+ for d in report.dimensions:
50
+ lines.append(f"| {d.dimension.value} | {'n/a' if d.score is None else f'{d.score:.1f}'} |")
51
+ todo = sorted(
52
+ (c for c in report.checks if c.status in _ORDER),
53
+ key=lambda c: (_ORDER[c.status], -c.weight, c.id),
54
+ )
55
+ lines += ["", f"## {t['fix_heading']}", ""]
56
+ if not todo:
57
+ lines.append(t["nothing"])
58
+ for c in todo:
59
+ blocker = " · blocker" if c.blocker else ""
60
+ lines.append(f"- **{c.status.value}**{blocker} `{c.id}` — {c.evidence}")
61
+ if c.fix:
62
+ lines.append(f" - {c.fix}")
63
+ return "\n".join(lines) + "\n"