litmus-cli 0.3.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.
- litmus/__init__.py +27 -0
- litmus/artifact.py +179 -0
- litmus/cli.py +342 -0
- litmus/detectors/__init__.py +3 -0
- litmus/detectors/base.py +56 -0
- litmus/exif.py +158 -0
- litmus/inspectors/__init__.py +32 -0
- litmus/inspectors/base.py +36 -0
- litmus/inspectors/c2pa.py +159 -0
- litmus/inspectors/file_metadata.py +210 -0
- litmus/inspectors/office_metadata.py +54 -0
- litmus/inspectors/text_markers.py +75 -0
- litmus/inspectors/unicode_scan.py +308 -0
- litmus/io.py +54 -0
- litmus/model.py +173 -0
- litmus/office.py +198 -0
- litmus/pipeline.py +464 -0
- litmus/providers/__init__.py +17 -0
- litmus/providers/registry.py +239 -0
- litmus/reporting.py +150 -0
- litmus/server.py +176 -0
- litmus/transform/__init__.py +12 -0
- litmus/transform/base.py +30 -0
- litmus/transform/code_structural.py +119 -0
- litmus/transform/file_strip.py +148 -0
- litmus/transform/text_normalize.py +257 -0
- litmus/validate/__init__.py +3 -0
- litmus/validate/binary.py +75 -0
- litmus/validate/code.py +165 -0
- litmus/validate/office.py +73 -0
- litmus/validate/structural.py +136 -0
- litmus/validate/text.py +158 -0
- litmus/validate/treesitter_code.py +129 -0
- litmus/web_ui.py +728 -0
- litmus_cli-0.3.0.dist-info/METADATA +108 -0
- litmus_cli-0.3.0.dist-info/RECORD +39 -0
- litmus_cli-0.3.0.dist-info/WHEEL +4 -0
- litmus_cli-0.3.0.dist-info/entry_points.txt +2 -0
- litmus_cli-0.3.0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
"""Markers embedded in the visible byte stream but not in the rendered output.
|
|
2
|
+
|
|
3
|
+
Only structurally unambiguous markers are reported. This inspector deliberately
|
|
4
|
+
does **not** do stylometry or "does this read like an LLM" scoring: that is
|
|
5
|
+
``HEURISTIC_STYLE`` evidence, it is unreliable per document, and emitting it
|
|
6
|
+
would invite exactly the authorship conclusions the brief forbids.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import re
|
|
12
|
+
|
|
13
|
+
from ..artifact import Artifact
|
|
14
|
+
from ..model import ArtifactKind, EvidenceClass, Finding, Location, Severity
|
|
15
|
+
from .base import InspectorOutcome, line_col
|
|
16
|
+
|
|
17
|
+
MAX_LOCATIONS = 25
|
|
18
|
+
MAX_EXCERPT = 160
|
|
19
|
+
|
|
20
|
+
_HTML_COMMENT = re.compile(r"<!--(.*?)-->", re.DOTALL)
|
|
21
|
+
_MARKUP_KINDS = {".md", ".html", ".htm", ".xml", ".svg", ".markdown", ".txt"}
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class TextMarkerInspector:
|
|
25
|
+
name = "text_markers"
|
|
26
|
+
|
|
27
|
+
def applies_to(self, artifact: Artifact) -> bool:
|
|
28
|
+
if not artifact.is_textual:
|
|
29
|
+
return False
|
|
30
|
+
# HTML comments in .ts/.js/.py are not markup comments; skip source
|
|
31
|
+
# code to avoid reporting ordinary code as an embedded marker.
|
|
32
|
+
return artifact.ref.kind is not ArtifactKind.SOURCE_CODE
|
|
33
|
+
|
|
34
|
+
def inspect(self, artifact: Artifact) -> InspectorOutcome:
|
|
35
|
+
text = artifact.text
|
|
36
|
+
if text is None:
|
|
37
|
+
return InspectorOutcome.skipped("artifact is not decodable text")
|
|
38
|
+
|
|
39
|
+
matches = list(_HTML_COMMENT.finditer(text))
|
|
40
|
+
if not matches:
|
|
41
|
+
return InspectorOutcome(findings=[])
|
|
42
|
+
|
|
43
|
+
locations = []
|
|
44
|
+
for match in matches[:MAX_LOCATIONS]:
|
|
45
|
+
line, col = line_col(text, match.start())
|
|
46
|
+
body = " ".join(match.group(1).split())
|
|
47
|
+
locations.append(
|
|
48
|
+
Location(
|
|
49
|
+
offset=match.start(),
|
|
50
|
+
line=line,
|
|
51
|
+
column=col,
|
|
52
|
+
length=match.end() - match.start(),
|
|
53
|
+
excerpt=body[:MAX_EXCERPT],
|
|
54
|
+
)
|
|
55
|
+
)
|
|
56
|
+
|
|
57
|
+
return InspectorOutcome(
|
|
58
|
+
findings=[
|
|
59
|
+
Finding(
|
|
60
|
+
detector=self.name,
|
|
61
|
+
category="markup_comment",
|
|
62
|
+
evidence_class=EvidenceClass.EMBEDDED_METADATA,
|
|
63
|
+
severity=Severity.INFO,
|
|
64
|
+
summary=(
|
|
65
|
+
f"{len(matches)} HTML/XML comment(s) present "
|
|
66
|
+
"(not rendered, but present in the source)"
|
|
67
|
+
),
|
|
68
|
+
count=len(matches),
|
|
69
|
+
locations=locations,
|
|
70
|
+
# Comments can be load-bearing (licences, directives, build
|
|
71
|
+
# pragmas). Removing them is not automatically safe.
|
|
72
|
+
removable_by=[],
|
|
73
|
+
)
|
|
74
|
+
]
|
|
75
|
+
)
|
|
@@ -0,0 +1,308 @@
|
|
|
1
|
+
"""Unicode and invisible-character inspection.
|
|
2
|
+
|
|
3
|
+
Scope note (brief §5, and FINDINGS.md §3): invisible characters are *not* a
|
|
4
|
+
provider watermark. They are reported as invisible-character anomalies with
|
|
5
|
+
evidence class ``EMBEDDED_METADATA``, because that is the strongest honest
|
|
6
|
+
claim: someone or something put codepoints in the file that carry no visible
|
|
7
|
+
content. They are frequently mundane (word processors, PDF copy/paste, web
|
|
8
|
+
editors, CJK typography, RTL text).
|
|
9
|
+
|
|
10
|
+
All special codepoints below are written as escapes on purpose, so that this
|
|
11
|
+
source file itself contains no invisible characters.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
import re
|
|
17
|
+
import unicodedata
|
|
18
|
+
|
|
19
|
+
from ..artifact import Artifact
|
|
20
|
+
from ..model import ArtifactKind, EvidenceClass, EvidenceLabel, Finding, Location, Severity
|
|
21
|
+
from .base import InspectorOutcome, line_col
|
|
22
|
+
|
|
23
|
+
MAX_LOCATIONS = 50
|
|
24
|
+
|
|
25
|
+
BOM = "\ufeff"
|
|
26
|
+
|
|
27
|
+
# Codepoints with no visible rendering that can carry an out-of-band payload.
|
|
28
|
+
ZERO_WIDTH: dict[str, str] = {
|
|
29
|
+
"\u200b": "ZERO WIDTH SPACE",
|
|
30
|
+
"\u200c": "ZERO WIDTH NON-JOINER",
|
|
31
|
+
"\u200d": "ZERO WIDTH JOINER",
|
|
32
|
+
"\u2060": "WORD JOINER",
|
|
33
|
+
"\u180e": "MONGOLIAN VOWEL SEPARATOR",
|
|
34
|
+
"\ufeff": "ZERO WIDTH NO-BREAK SPACE (BOM)",
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
# Bidirectional formatting controls. Legitimate in RTL text; also the basis of
|
|
38
|
+
# the "Trojan Source" source-code attack, so they are a warning in code.
|
|
39
|
+
BIDI_CONTROLS: dict[str, str] = {
|
|
40
|
+
"\u202a": "LEFT-TO-RIGHT EMBEDDING",
|
|
41
|
+
"\u202b": "RIGHT-TO-LEFT EMBEDDING",
|
|
42
|
+
"\u202c": "POP DIRECTIONAL FORMATTING",
|
|
43
|
+
"\u202d": "LEFT-TO-RIGHT OVERRIDE",
|
|
44
|
+
"\u202e": "RIGHT-TO-LEFT OVERRIDE",
|
|
45
|
+
"\u2066": "LEFT-TO-RIGHT ISOLATE",
|
|
46
|
+
"\u2067": "RIGHT-TO-LEFT ISOLATE",
|
|
47
|
+
"\u2068": "FIRST STRONG ISOLATE",
|
|
48
|
+
"\u2069": "POP DIRECTIONAL ISOLATE",
|
|
49
|
+
"\u061c": "ARABIC LETTER MARK",
|
|
50
|
+
"\u200e": "LEFT-TO-RIGHT MARK",
|
|
51
|
+
"\u200f": "RIGHT-TO-LEFT MARK",
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
# Space characters that are neither U+0020 nor a tab.
|
|
55
|
+
EXOTIC_SPACES: dict[str, str] = {
|
|
56
|
+
"\u00a0": "NO-BREAK SPACE",
|
|
57
|
+
"\u1680": "OGHAM SPACE MARK",
|
|
58
|
+
"\u2000": "EN QUAD",
|
|
59
|
+
"\u2001": "EM QUAD",
|
|
60
|
+
"\u2002": "EN SPACE",
|
|
61
|
+
"\u2003": "EM SPACE",
|
|
62
|
+
"\u2004": "THREE-PER-EM SPACE",
|
|
63
|
+
"\u2005": "FOUR-PER-EM SPACE",
|
|
64
|
+
"\u2006": "SIX-PER-EM SPACE",
|
|
65
|
+
"\u2007": "FIGURE SPACE",
|
|
66
|
+
"\u2008": "PUNCTUATION SPACE",
|
|
67
|
+
"\u2009": "THIN SPACE",
|
|
68
|
+
"\u200a": "HAIR SPACE",
|
|
69
|
+
"\u202f": "NARROW NO-BREAK SPACE",
|
|
70
|
+
"\u205f": "MEDIUM MATHEMATICAL SPACE",
|
|
71
|
+
"\u3000": "IDEOGRAPHIC SPACE",
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
OTHER_INVISIBLE: dict[str, str] = {
|
|
75
|
+
"\u00ad": "SOFT HYPHEN",
|
|
76
|
+
"\u034f": "COMBINING GRAPHEME JOINER",
|
|
77
|
+
"\u2800": "BRAILLE PATTERN BLANK",
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
# Scripts that legitimately interleave inside a single whitespace-delimited run
|
|
81
|
+
# of Japanese or Chinese text; collapsing them avoids a flood of false hits.
|
|
82
|
+
_CJK_SCRIPTS = frozenset({"HIRAGANA", "KATAKANA", "CJK", "KANGXI", "IDEOGRAPHIC"})
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def is_variation_selector(ch: str) -> bool:
|
|
86
|
+
cp = ord(ch)
|
|
87
|
+
return 0xFE00 <= cp <= 0xFE0F or 0xE0100 <= cp <= 0xE01EF
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def is_tag_char(ch: str) -> bool:
|
|
91
|
+
# U+E0000..U+E007F: deprecated, invisible, and the most common vehicle for
|
|
92
|
+
# hiding an arbitrary ASCII payload inside otherwise-clean text.
|
|
93
|
+
return 0xE0000 <= ord(ch) <= 0xE007F
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def decode_tag_payload(chars: list[str]) -> str:
|
|
97
|
+
"""Tag characters mirror ASCII at an offset of U+E0000."""
|
|
98
|
+
return "".join(chr(ord(c) - 0xE0000) for c in chars if 0xE0020 <= ord(c) <= 0xE007E)
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def _script_of(ch: str) -> str | None:
|
|
102
|
+
"""Coarse script bucket, sufficient for homoglyph detection."""
|
|
103
|
+
if not ch.isalpha():
|
|
104
|
+
return None
|
|
105
|
+
try:
|
|
106
|
+
name = unicodedata.name(ch)
|
|
107
|
+
except ValueError:
|
|
108
|
+
return None
|
|
109
|
+
script = name.split(" ")[0]
|
|
110
|
+
return "CJK" if script in _CJK_SCRIPTS else script
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
class UnicodeInspector:
|
|
114
|
+
name = "unicode"
|
|
115
|
+
|
|
116
|
+
def applies_to(self, artifact: Artifact) -> bool:
|
|
117
|
+
return artifact.is_textual
|
|
118
|
+
|
|
119
|
+
def inspect(self, artifact: Artifact) -> InspectorOutcome:
|
|
120
|
+
text = artifact.text
|
|
121
|
+
if text is None:
|
|
122
|
+
return InspectorOutcome.skipped("artifact is not decodable text")
|
|
123
|
+
|
|
124
|
+
buckets: dict[str, list[tuple[int, str, str]]] = {
|
|
125
|
+
"zero_width": [],
|
|
126
|
+
"bidi_control": [],
|
|
127
|
+
"exotic_space": [],
|
|
128
|
+
"variation_selector": [],
|
|
129
|
+
"unicode_tag_char": [],
|
|
130
|
+
"other_invisible": [],
|
|
131
|
+
"control_char": [],
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
for offset, ch in enumerate(text):
|
|
135
|
+
if ch in ZERO_WIDTH:
|
|
136
|
+
# A leading BOM is reported by _structural_findings instead.
|
|
137
|
+
if not (offset == 0 and ch == BOM):
|
|
138
|
+
buckets["zero_width"].append((offset, ch, ZERO_WIDTH[ch]))
|
|
139
|
+
elif ch in BIDI_CONTROLS:
|
|
140
|
+
buckets["bidi_control"].append((offset, ch, BIDI_CONTROLS[ch]))
|
|
141
|
+
elif ch in EXOTIC_SPACES:
|
|
142
|
+
buckets["exotic_space"].append((offset, ch, EXOTIC_SPACES[ch]))
|
|
143
|
+
elif ch in OTHER_INVISIBLE:
|
|
144
|
+
buckets["other_invisible"].append((offset, ch, OTHER_INVISIBLE[ch]))
|
|
145
|
+
elif is_variation_selector(ch):
|
|
146
|
+
buckets["variation_selector"].append((offset, ch, "VARIATION SELECTOR"))
|
|
147
|
+
elif is_tag_char(ch):
|
|
148
|
+
buckets["unicode_tag_char"].append((offset, ch, "UNICODE TAG CHARACTER"))
|
|
149
|
+
elif unicodedata.category(ch) == "Cc" and ch not in "\n\r\t":
|
|
150
|
+
buckets["control_char"].append((offset, ch, "CONTROL CHARACTER"))
|
|
151
|
+
|
|
152
|
+
is_code = artifact.ref.kind is ArtifactKind.SOURCE_CODE
|
|
153
|
+
severity_by_bucket = {
|
|
154
|
+
"zero_width": Severity.WARNING,
|
|
155
|
+
"unicode_tag_char": Severity.WARNING,
|
|
156
|
+
"bidi_control": Severity.WARNING if is_code else Severity.NOTICE,
|
|
157
|
+
"variation_selector": Severity.NOTICE,
|
|
158
|
+
"control_char": Severity.WARNING,
|
|
159
|
+
"exotic_space": Severity.NOTICE,
|
|
160
|
+
"other_invisible": Severity.NOTICE,
|
|
161
|
+
}
|
|
162
|
+
removable_by = {
|
|
163
|
+
"zero_width": ["strip_zero_width"],
|
|
164
|
+
"unicode_tag_char": ["strip_tag_characters"],
|
|
165
|
+
"bidi_control": ["strip_bidi_controls"],
|
|
166
|
+
"variation_selector": ["strip_variation_selectors"],
|
|
167
|
+
"control_char": ["strip_control_characters"],
|
|
168
|
+
"exotic_space": ["normalize_spaces"],
|
|
169
|
+
"other_invisible": ["strip_other_invisible"],
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
findings: list[Finding] = []
|
|
173
|
+
for bucket, hits in buckets.items():
|
|
174
|
+
if not hits:
|
|
175
|
+
continue
|
|
176
|
+
details: dict[str, object] = {
|
|
177
|
+
"codepoints": sorted({f"U+{ord(c):04X}" for _, c, _ in hits}),
|
|
178
|
+
"names": sorted({name for _, _, name in hits}),
|
|
179
|
+
}
|
|
180
|
+
if bucket == "unicode_tag_char":
|
|
181
|
+
payload = decode_tag_payload([c for _, c, _ in hits])
|
|
182
|
+
if payload:
|
|
183
|
+
details["decoded_ascii_payload"] = payload
|
|
184
|
+
findings.append(
|
|
185
|
+
Finding(
|
|
186
|
+
detector=self.name,
|
|
187
|
+
category=bucket,
|
|
188
|
+
evidence_class=EvidenceClass.EMBEDDED_METADATA,
|
|
189
|
+
severity=severity_by_bucket[bucket],
|
|
190
|
+
summary=f"{len(hits)} {bucket.replace('_', ' ')} character(s) present",
|
|
191
|
+
label=EvidenceLabel.CONFIRMED,
|
|
192
|
+
count=len(hits),
|
|
193
|
+
locations=self._locations(text, hits),
|
|
194
|
+
details=details,
|
|
195
|
+
removable_by=removable_by[bucket],
|
|
196
|
+
)
|
|
197
|
+
)
|
|
198
|
+
|
|
199
|
+
findings.extend(self._structural_findings(artifact, text))
|
|
200
|
+
return InspectorOutcome(findings=findings)
|
|
201
|
+
|
|
202
|
+
def _locations(self, text: str, hits: list[tuple[int, str, str]]) -> list[Location]:
|
|
203
|
+
locations = []
|
|
204
|
+
for offset, ch, name in hits[:MAX_LOCATIONS]:
|
|
205
|
+
line, col = line_col(text, offset)
|
|
206
|
+
locations.append(
|
|
207
|
+
Location(
|
|
208
|
+
offset=offset,
|
|
209
|
+
line=line,
|
|
210
|
+
column=col,
|
|
211
|
+
length=1,
|
|
212
|
+
excerpt=f"U+{ord(ch):04X} {name}",
|
|
213
|
+
)
|
|
214
|
+
)
|
|
215
|
+
return locations
|
|
216
|
+
|
|
217
|
+
def _structural_findings(self, artifact: Artifact, text: str) -> list[Finding]:
|
|
218
|
+
findings: list[Finding] = []
|
|
219
|
+
|
|
220
|
+
if artifact.ref.encoding == "utf-8-sig" or text.startswith(BOM):
|
|
221
|
+
findings.append(
|
|
222
|
+
Finding(
|
|
223
|
+
detector=self.name,
|
|
224
|
+
category="byte_order_mark",
|
|
225
|
+
evidence_class=EvidenceClass.EMBEDDED_METADATA,
|
|
226
|
+
severity=Severity.NOTICE,
|
|
227
|
+
summary="File begins with a UTF-8 byte order mark",
|
|
228
|
+
locations=[Location(offset=0, line=1, column=1, length=1)],
|
|
229
|
+
removable_by=["strip_bom"],
|
|
230
|
+
)
|
|
231
|
+
)
|
|
232
|
+
|
|
233
|
+
if not unicodedata.is_normalized("NFC", text):
|
|
234
|
+
form = next(
|
|
235
|
+
(f for f in ("NFD", "NFKC", "NFKD") if unicodedata.is_normalized(f, text)),
|
|
236
|
+
"none",
|
|
237
|
+
)
|
|
238
|
+
findings.append(
|
|
239
|
+
Finding(
|
|
240
|
+
detector=self.name,
|
|
241
|
+
category="unicode_normalization",
|
|
242
|
+
evidence_class=EvidenceClass.EMBEDDED_METADATA,
|
|
243
|
+
severity=Severity.INFO,
|
|
244
|
+
summary="Text is not in Unicode NFC normalization form",
|
|
245
|
+
details={"current_form": form},
|
|
246
|
+
removable_by=["normalize_nfc"],
|
|
247
|
+
)
|
|
248
|
+
)
|
|
249
|
+
|
|
250
|
+
crlf = text.count("\r\n")
|
|
251
|
+
lf = text.count("\n") - crlf
|
|
252
|
+
cr = text.count("\r") - crlf
|
|
253
|
+
if sum(1 for n in (crlf, lf, cr) if n) > 1:
|
|
254
|
+
findings.append(
|
|
255
|
+
Finding(
|
|
256
|
+
detector=self.name,
|
|
257
|
+
category="mixed_line_endings",
|
|
258
|
+
evidence_class=EvidenceClass.EMBEDDED_METADATA,
|
|
259
|
+
severity=Severity.NOTICE,
|
|
260
|
+
summary="File mixes line ending styles",
|
|
261
|
+
details={"crlf": crlf, "lf": lf, "cr": cr},
|
|
262
|
+
removable_by=["normalize_line_endings"],
|
|
263
|
+
)
|
|
264
|
+
)
|
|
265
|
+
|
|
266
|
+
mixed = _mixed_script_words(text)
|
|
267
|
+
if mixed:
|
|
268
|
+
findings.append(
|
|
269
|
+
Finding(
|
|
270
|
+
detector=self.name,
|
|
271
|
+
category="mixed_script_word",
|
|
272
|
+
evidence_class=EvidenceClass.EMBEDDED_METADATA,
|
|
273
|
+
severity=Severity.WARNING,
|
|
274
|
+
summary=(
|
|
275
|
+
f"{len(mixed)} word(s) mix Latin with another script (possible homoglyphs)"
|
|
276
|
+
),
|
|
277
|
+
count=len(mixed),
|
|
278
|
+
details={"examples": mixed[:10]},
|
|
279
|
+
# Homoglyph substitution is not safely auto-reversible: the
|
|
280
|
+
# intended target character is genuinely ambiguous.
|
|
281
|
+
removable_by=[],
|
|
282
|
+
)
|
|
283
|
+
)
|
|
284
|
+
return findings
|
|
285
|
+
|
|
286
|
+
|
|
287
|
+
_ALPHA_RUN = re.compile(r"[^\W\d_]{2,}", re.UNICODE)
|
|
288
|
+
|
|
289
|
+
|
|
290
|
+
def _mixed_script_words(text: str) -> list[str]:
|
|
291
|
+
"""Maximal runs of letters that mix Latin with another script.
|
|
292
|
+
|
|
293
|
+
Two deliberate restrictions keep the false-positive rate usable:
|
|
294
|
+
|
|
295
|
+
* Only *letter runs* are examined, not whitespace-delimited words. In source
|
|
296
|
+
code a single "word" routinely spans an identifier and a string literal
|
|
297
|
+
(``_categories("...")``), which is not a homoglyph.
|
|
298
|
+
* Only Latin-plus-other counts. That is the homoglyph-attack shape; a run
|
|
299
|
+
mixing two non-Latin scripts is far more likely to be ordinary
|
|
300
|
+
multilingual text.
|
|
301
|
+
"""
|
|
302
|
+
mixed: list[str] = []
|
|
303
|
+
for match in _ALPHA_RUN.finditer(text):
|
|
304
|
+
run = match.group()
|
|
305
|
+
scripts = {s for s in (_script_of(ch) for ch in run) if s}
|
|
306
|
+
if len(scripts) > 1 and "LATIN" in scripts:
|
|
307
|
+
mixed.append(run)
|
|
308
|
+
return mixed
|
litmus/io.py
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
"""Safe, atomic output writing.
|
|
2
|
+
|
|
3
|
+
A transformation tool rewrites files the user cares about, so the write path
|
|
4
|
+
is a security boundary, not a convenience. Three rules:
|
|
5
|
+
|
|
6
|
+
* **Refuse symlinks.** Following a symlink lets a crafted tree redirect a write
|
|
7
|
+
outside its intended target. We refuse rather than resolve.
|
|
8
|
+
* **Write atomically.** A temp file in the same directory, then ``os.replace``.
|
|
9
|
+
A crash mid-write leaves the original intact rather than a truncated file.
|
|
10
|
+
* **Back up on request.** ``--backup`` copies the original to ``<name>.bak``
|
|
11
|
+
before replacing it.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
import os
|
|
17
|
+
import shutil
|
|
18
|
+
import tempfile
|
|
19
|
+
from pathlib import Path
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class SafeWriteError(Exception):
|
|
23
|
+
"""Raised when a write is refused for a safety reason."""
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def safe_write(path: Path, data: bytes, *, backup: bool = False) -> None:
|
|
27
|
+
"""Atomically write ``data`` to ``path``, refusing to follow a symlink.
|
|
28
|
+
|
|
29
|
+
``os.path.islink`` is checked (not ``Path.is_symlink`` after resolution) so
|
|
30
|
+
that a symlink at the destination is detected before anything is written.
|
|
31
|
+
"""
|
|
32
|
+
if os.path.islink(path):
|
|
33
|
+
raise SafeWriteError(f"refusing to write through a symlink: {path}")
|
|
34
|
+
|
|
35
|
+
parent = path.parent
|
|
36
|
+
if not parent.exists():
|
|
37
|
+
raise SafeWriteError(f"parent directory does not exist: {parent}")
|
|
38
|
+
|
|
39
|
+
if backup and path.exists():
|
|
40
|
+
shutil.copy2(path, path.with_name(path.name + ".bak"))
|
|
41
|
+
|
|
42
|
+
# Temp file in the same directory guarantees os.replace is a rename, not a
|
|
43
|
+
# cross-filesystem copy (which would not be atomic).
|
|
44
|
+
fd, tmp_name = tempfile.mkstemp(prefix=f".{path.name}.", suffix=".tmp", dir=parent)
|
|
45
|
+
tmp = Path(tmp_name)
|
|
46
|
+
try:
|
|
47
|
+
with os.fdopen(fd, "wb") as handle:
|
|
48
|
+
handle.write(data)
|
|
49
|
+
handle.flush()
|
|
50
|
+
os.fsync(handle.fileno())
|
|
51
|
+
os.replace(tmp, path)
|
|
52
|
+
except BaseException:
|
|
53
|
+
tmp.unlink(missing_ok=True)
|
|
54
|
+
raise
|
litmus/model.py
ADDED
|
@@ -0,0 +1,173 @@
|
|
|
1
|
+
"""Typed core models.
|
|
2
|
+
|
|
3
|
+
The enums here encode the rules from the project brief that must never be
|
|
4
|
+
violated by any subsystem:
|
|
5
|
+
|
|
6
|
+
* ``EvidenceClass`` keeps embedded metadata, signed provenance, statistical
|
|
7
|
+
watermarking and style heuristics permanently distinct (brief §5).
|
|
8
|
+
* ``EvidenceLabel`` forces every provider-specific claim to carry its epistemic
|
|
9
|
+
status (brief §20).
|
|
10
|
+
* ``Confidence`` has no numeric field, so a confidence value cannot be
|
|
11
|
+
fabricated (brief §16).
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
from enum import StrEnum
|
|
17
|
+
|
|
18
|
+
from pydantic import BaseModel, Field
|
|
19
|
+
|
|
20
|
+
REPORT_SCHEMA_VERSION = "1.0"
|
|
21
|
+
TOOL_VERSION = "0.3.0"
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class ArtifactKind(StrEnum):
|
|
25
|
+
TEXT = "text"
|
|
26
|
+
SOURCE_CODE = "source_code"
|
|
27
|
+
BINARY = "binary"
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
class EvidenceClass(StrEnum):
|
|
31
|
+
"""What kind of signal a finding is. These are never interchangeable."""
|
|
32
|
+
|
|
33
|
+
SIGNED_PROVENANCE = "signed_provenance"
|
|
34
|
+
EMBEDDED_METADATA = "embedded_metadata"
|
|
35
|
+
STATISTICAL_WATERMARK = "statistical_watermark"
|
|
36
|
+
HEURISTIC_STYLE = "heuristic_style"
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
class EvidenceLabel(StrEnum):
|
|
40
|
+
CONFIRMED = "confirmed"
|
|
41
|
+
INFERRED = "inferred"
|
|
42
|
+
UNVERIFIED = "unverified"
|
|
43
|
+
UNKNOWN = "unknown"
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
class Confidence(StrEnum):
|
|
47
|
+
"""Deliberately non-numeric."""
|
|
48
|
+
|
|
49
|
+
INSUFFICIENT_EVIDENCE = "insufficient_evidence"
|
|
50
|
+
SIGNAL_PRESENT = "signal_present"
|
|
51
|
+
SIGNAL_ABSENT_IN_SCOPE = "signal_absent_in_scope"
|
|
52
|
+
NOT_DETERMINABLE = "not_determinable"
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
class Severity(StrEnum):
|
|
56
|
+
INFO = "info"
|
|
57
|
+
NOTICE = "notice"
|
|
58
|
+
WARNING = "warning"
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
class Location(BaseModel):
|
|
62
|
+
"""Where in the artifact a finding sits. Offsets are 0-based, lines 1-based."""
|
|
63
|
+
|
|
64
|
+
offset: int
|
|
65
|
+
line: int | None = None
|
|
66
|
+
column: int | None = None
|
|
67
|
+
length: int = 1
|
|
68
|
+
excerpt: str | None = None
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
class Finding(BaseModel):
|
|
72
|
+
detector: str
|
|
73
|
+
category: str
|
|
74
|
+
evidence_class: EvidenceClass
|
|
75
|
+
severity: Severity = Severity.INFO
|
|
76
|
+
summary: str
|
|
77
|
+
label: EvidenceLabel = EvidenceLabel.CONFIRMED
|
|
78
|
+
count: int = 1
|
|
79
|
+
locations: list[Location] = Field(default_factory=list)
|
|
80
|
+
details: dict[str, object] = Field(default_factory=dict)
|
|
81
|
+
removable_by: list[str] = Field(
|
|
82
|
+
default_factory=list,
|
|
83
|
+
description="Transform operation ids that would remove this finding, if any.",
|
|
84
|
+
)
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
class ArtifactRef(BaseModel):
|
|
88
|
+
path: str | None = None
|
|
89
|
+
kind: ArtifactKind
|
|
90
|
+
language: str | None = None
|
|
91
|
+
media_type: str | None = None
|
|
92
|
+
sha256: str
|
|
93
|
+
size_bytes: int
|
|
94
|
+
encoding: str | None = None
|
|
95
|
+
decoded: bool = True
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
class InspectorStatus(BaseModel):
|
|
99
|
+
"""Per-inspector outcome, so a skipped inspector is never a silent gap."""
|
|
100
|
+
|
|
101
|
+
name: str
|
|
102
|
+
ran: bool
|
|
103
|
+
reason: str | None = None
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
class ProvenanceSummary(BaseModel):
|
|
107
|
+
known_signals_detected: list[str] = Field(default_factory=list)
|
|
108
|
+
unknown_signals: list[str] = Field(default_factory=list)
|
|
109
|
+
confidence: Confidence = Confidence.INSUFFICIENT_EVIDENCE
|
|
110
|
+
notes: list[str] = Field(default_factory=list)
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
class InspectionReport(BaseModel):
|
|
114
|
+
findings: list[Finding] = Field(default_factory=list)
|
|
115
|
+
inspectors: list[InspectorStatus] = Field(default_factory=list)
|
|
116
|
+
provenance: ProvenanceSummary = Field(default_factory=ProvenanceSummary)
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
class OperationResult(BaseModel):
|
|
120
|
+
operation: str
|
|
121
|
+
description: str
|
|
122
|
+
semantics_preserving: bool
|
|
123
|
+
applied: bool
|
|
124
|
+
changes: int = 0
|
|
125
|
+
details: dict[str, object] = Field(default_factory=dict)
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
class TransformationReport(BaseModel):
|
|
129
|
+
performed: bool = False
|
|
130
|
+
accepted: bool = False
|
|
131
|
+
rejected_reason: str | None = None
|
|
132
|
+
operations: list[OperationResult] = Field(default_factory=list)
|
|
133
|
+
output_sha256: str | None = None
|
|
134
|
+
output_size_bytes: int | None = None
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
class Check(BaseModel):
|
|
138
|
+
"""A single validation check.
|
|
139
|
+
|
|
140
|
+
``passed is None`` means the check could not be run; it is reported, never
|
|
141
|
+
silently dropped.
|
|
142
|
+
"""
|
|
143
|
+
|
|
144
|
+
name: str
|
|
145
|
+
passed: bool | None
|
|
146
|
+
detail: str
|
|
147
|
+
measurements: dict[str, object] = Field(default_factory=dict)
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
class ValidationReport(BaseModel):
|
|
151
|
+
performed: bool = False
|
|
152
|
+
all_passed: bool | None = None
|
|
153
|
+
checks: list[Check] = Field(default_factory=list)
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
class Report(BaseModel):
|
|
157
|
+
schema_version: str = REPORT_SCHEMA_VERSION
|
|
158
|
+
tool_version: str = TOOL_VERSION
|
|
159
|
+
artifact: ArtifactRef
|
|
160
|
+
inspection: InspectionReport = Field(default_factory=InspectionReport)
|
|
161
|
+
transformation: TransformationReport = Field(default_factory=TransformationReport)
|
|
162
|
+
validation: ValidationReport = Field(default_factory=ValidationReport)
|
|
163
|
+
|
|
164
|
+
@property
|
|
165
|
+
def has_findings(self) -> bool:
|
|
166
|
+
return bool(self.inspection.findings)
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
class BatchReport(BaseModel):
|
|
170
|
+
schema_version: str = REPORT_SCHEMA_VERSION
|
|
171
|
+
tool_version: str = TOOL_VERSION
|
|
172
|
+
reports: list[Report] = Field(default_factory=list)
|
|
173
|
+
errors: list[dict[str, str]] = Field(default_factory=list)
|