@oira-oira/pi 0.0.0-stage → 0.13.0
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.
- package/README.md +30 -2
- package/mcp.json +8 -0
- package/package.json +17 -4
- package/skills/oira-work-reporting/SKILL.md +60 -0
- package/skills/oira-work-reporting/references/examples/correction.json +22 -0
- package/skills/oira-work-reporting/references/examples/declare-with-deferral.json +39 -0
- package/skills/oira-work-reporting/references/examples/defer-whole-task.json +19 -0
- package/skills/oira-work-reporting/references/examples/history-import.json +38 -0
- package/skills/oira-work-reporting/references/examples/milestone-handoff.json +24 -0
- package/skills/oira-work-reporting/references/examples/parent-with-seven-deferrals.json +212 -0
- package/skills/oira-work-reporting/references/examples/related-work.json +35 -0
- package/skills/oira-work-reporting/references/examples/technical-alignment.json +31 -0
- package/skills/oira-work-reporting/references/examples/update-progress.json +24 -0
- package/skills/oira-work-reporting/references/extraction-guide.md +216 -0
- package/skills/oira-work-reporting/references/oira_work_update.v2.schema.json +1100 -0
- package/skills/oira-work-reporting/scripts/prepare_work_update.py +1482 -0
|
@@ -0,0 +1,1482 @@
|
|
|
1
|
+
"""Local outbound preflight for Oira work updates (``oira_work_update.v2``).
|
|
2
|
+
|
|
3
|
+
Usage::
|
|
4
|
+
|
|
5
|
+
python3 prepare_work_update.py < candidate.json
|
|
6
|
+
python3 prepare_work_update.py --new-ref
|
|
7
|
+
python3 prepare_work_update.py --history-stream SESSION_ID
|
|
8
|
+
|
|
9
|
+
The first form reads one candidate update on standard input, applies the
|
|
10
|
+
closed contract's allowlist and limits and a recursive credential scan, and
|
|
11
|
+
prints only the accepted canonical JSON. On refusal it prints field paths and
|
|
12
|
+
reason codes, never the rejected values. The second prints a fresh random
|
|
13
|
+
reference for ``update_ref`` or ``stream_ref``. The third prints the
|
|
14
|
+
``stream_ref`` of one past session in a history import: derived one way from
|
|
15
|
+
the coding app's own session id, so the same session always gets the same
|
|
16
|
+
reference while the id itself never leaves this computer.
|
|
17
|
+
|
|
18
|
+
Invoke this module with Python, as shown above; it is not a shell command.
|
|
19
|
+
Its only update input is standard input. It never reads environment variables,
|
|
20
|
+
credential files or authentication tokens. Credential names and remote URL
|
|
21
|
+
patterns below are rejection rules for the candidate, not data sources or
|
|
22
|
+
network destinations. Authentication belongs to the host's Oira MCP OAuth
|
|
23
|
+
connection and is not handled by this module.
|
|
24
|
+
|
|
25
|
+
The script uses the Python standard library only. It opens no network
|
|
26
|
+
connection, writes no files, keeps no logs and sends no telemetry. Exit codes:
|
|
27
|
+
0 accepted, 2 refused (rewrite the named fields and run it again), 3 reporting
|
|
28
|
+
unavailable on this host (nothing may be sent).
|
|
29
|
+
|
|
30
|
+
Its checks find recognized credential patterns; they cannot prove that an
|
|
31
|
+
arbitrary sentence contains no secret. Oira runs the same checks again before
|
|
32
|
+
it stores anything.
|
|
33
|
+
|
|
34
|
+
Canonical source: ``server/brain/v4/external_connectors/agent_sessions/mcp/
|
|
35
|
+
work_update_preflight.py`` in the Oira repository. The plugin copies
|
|
36
|
+
(``skills/oira-work-reporting/scripts/prepare_work_update.py``) are generated
|
|
37
|
+
from it and must not be edited.
|
|
38
|
+
"""
|
|
39
|
+
|
|
40
|
+
from __future__ import annotations
|
|
41
|
+
|
|
42
|
+
import hashlib
|
|
43
|
+
import json
|
|
44
|
+
import math
|
|
45
|
+
import re
|
|
46
|
+
import sys
|
|
47
|
+
import unicodedata
|
|
48
|
+
import uuid
|
|
49
|
+
from urllib.parse import parse_qsl, urlsplit
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
SCHEMA = 'oira_work_update.v2'
|
|
53
|
+
# The outbound filter this file implements. A skill reports it as
|
|
54
|
+
# ``privacy_policy_version``; the value is an assertion, not proof of a scan.
|
|
55
|
+
FILTER_POLICY_VERSION = 'oira_outbound_filter.v1'
|
|
56
|
+
MINIMUM_PYTHON = (3, 11)
|
|
57
|
+
|
|
58
|
+
MAX_RAW_INPUT_BYTES = 131_072
|
|
59
|
+
MAX_UPDATE_BYTES = 32_768
|
|
60
|
+
MAX_FINDINGS = 40
|
|
61
|
+
|
|
62
|
+
MAX_WORKS = 8
|
|
63
|
+
MAX_FACTS = 16
|
|
64
|
+
MAX_DETAILS = 12
|
|
65
|
+
MAX_MENTIONS = 16
|
|
66
|
+
MAX_REFERENCES = 12
|
|
67
|
+
MAX_RELATION_HINTS = 12
|
|
68
|
+
MAX_REVISIONS = 8
|
|
69
|
+
MAX_BOUNDARIES = 6
|
|
70
|
+
MAX_SUPPORTING_FACTS = 8
|
|
71
|
+
MAX_COMMITS = 20
|
|
72
|
+
MAX_PULL_REQUESTS = 10
|
|
73
|
+
MAX_SUBJECT_LABELS = 6
|
|
74
|
+
MAX_FUNCTION_LABELS = 4
|
|
75
|
+
MAX_VERSION_REFS = 6
|
|
76
|
+
MAX_SEQUENCE = 1_000_000_000
|
|
77
|
+
|
|
78
|
+
PROJECT_LABEL_MAX_CHARS = 200
|
|
79
|
+
TITLE_MAX_CHARS = 160
|
|
80
|
+
OUTCOME_MAX_BYTES = 1_200
|
|
81
|
+
BOUNDARY_MAX_BYTES = 600
|
|
82
|
+
STATEMENT_MAX_BYTES = 1_200
|
|
83
|
+
UNCERTAINTY_MAX_BYTES = 600
|
|
84
|
+
DEFERRAL_TEXT_MAX_BYTES = 600
|
|
85
|
+
DETAIL_DESCRIPTION_MAX_BYTES = 600
|
|
86
|
+
SAFE_LABEL_MAX_BYTES = 160
|
|
87
|
+
SUBJECT_LABEL_MAX_CHARS = 160
|
|
88
|
+
FUNCTION_LABEL_MAX_CHARS = 120
|
|
89
|
+
ENVIRONMENT_MAX_CHARS = 120
|
|
90
|
+
VERSION_REF_MAX_CHARS = 255
|
|
91
|
+
SAFE_URL_MAX_BYTES = 255
|
|
92
|
+
REPOSITORY_URL_MAX_CHARS = 300
|
|
93
|
+
BRANCH_MAX_CHARS = 200
|
|
94
|
+
|
|
95
|
+
ACTIVITIES = ('planning', 'execution', 'validation', 'mixed')
|
|
96
|
+
OPERATIONS = ('declare', 'update')
|
|
97
|
+
FACT_KINDS = (
|
|
98
|
+
'decision', 'alternative', 'attempted_change', 'implemented_change',
|
|
99
|
+
'commitment', 'assignment', 'explicit_deferral', 'verification',
|
|
100
|
+
'blocker', 'question', 'next_step', 'limitation',
|
|
101
|
+
)
|
|
102
|
+
# The existing internal ClaimStatus vocabulary, unchanged.
|
|
103
|
+
CLAIM_STATUSES = (
|
|
104
|
+
'proposed', 'accepted', 'attempted', 'tested', 'committed', 'merged',
|
|
105
|
+
'released', 'unresolved', 'deferred', 'unknown',
|
|
106
|
+
)
|
|
107
|
+
STATUSES_BY_KIND = {
|
|
108
|
+
'decision': ('proposed', 'accepted'),
|
|
109
|
+
'alternative': ('proposed', 'unresolved'),
|
|
110
|
+
'attempted_change': ('attempted',),
|
|
111
|
+
'implemented_change': (
|
|
112
|
+
'accepted', 'tested', 'committed', 'merged', 'released',
|
|
113
|
+
),
|
|
114
|
+
'commitment': ('proposed', 'accepted'),
|
|
115
|
+
'assignment': ('proposed', 'accepted'),
|
|
116
|
+
'explicit_deferral': ('deferred',),
|
|
117
|
+
'verification': ('tested', 'unresolved', 'unknown'),
|
|
118
|
+
'blocker': ('unresolved',),
|
|
119
|
+
'question': ('unresolved',),
|
|
120
|
+
'next_step': ('proposed', 'accepted'),
|
|
121
|
+
'limitation': ('unknown',),
|
|
122
|
+
}
|
|
123
|
+
DELIVERY_STATUSES = ('tested', 'committed', 'merged', 'released')
|
|
124
|
+
BASES = (
|
|
125
|
+
'agent_report', 'user_statement_paraphrase', 'agent_inference',
|
|
126
|
+
'relayed_report',
|
|
127
|
+
)
|
|
128
|
+
# Absent: the user's current work. ``history_import``: work from a past
|
|
129
|
+
# session the member asked Oira to import; every fact then says when it
|
|
130
|
+
# happened, inside the window Oira gave.
|
|
131
|
+
ORIGINS = ('history_import',)
|
|
132
|
+
DETAIL_KINDS = (
|
|
133
|
+
'surface', 'input_output', 'assumption', 'behavior', 'transform',
|
|
134
|
+
'verification', 'decision', 'open_point', 'contribution',
|
|
135
|
+
)
|
|
136
|
+
TEMPORAL_STATUSES = ('proposed', 'current', 'superseded', 'unknown')
|
|
137
|
+
VERSION_REF_KINDS = (
|
|
138
|
+
'git_commit', 'pull_request', 'branch', 'model', 'prompt',
|
|
139
|
+
'retrieval_index', 'dataset', 'schema', 'mobile_build', 'api', 'sdk',
|
|
140
|
+
'mcp_server', 'artifact_version',
|
|
141
|
+
)
|
|
142
|
+
ENTITY_KINDS = (
|
|
143
|
+
'person', 'team_agent', 'function', 'project', 'repository', 'file',
|
|
144
|
+
'symbol', 'task', 'discussion', 'artifact',
|
|
145
|
+
)
|
|
146
|
+
REFERENCE_KINDS = (
|
|
147
|
+
'work_item', 'artifact', 'discussion', 'external_task', 'pull_request',
|
|
148
|
+
'issue', 'repository', 'source_object',
|
|
149
|
+
)
|
|
150
|
+
TARGET_KINDS = ('returned_handle', 'work_ref', 'safe_url')
|
|
151
|
+
TARGET_KINDS_BY_REFERENCE = {
|
|
152
|
+
'work_item': ('returned_handle', 'work_ref'),
|
|
153
|
+
'artifact': ('returned_handle',),
|
|
154
|
+
'discussion': ('returned_handle',),
|
|
155
|
+
'source_object': ('returned_handle',),
|
|
156
|
+
'external_task': ('safe_url',),
|
|
157
|
+
'pull_request': ('safe_url',),
|
|
158
|
+
'issue': ('safe_url',),
|
|
159
|
+
'repository': ('safe_url',),
|
|
160
|
+
}
|
|
161
|
+
RELATION_KINDS = (
|
|
162
|
+
'same_work', 'new_work', 'related', 'depends_on', 'blocks',
|
|
163
|
+
'conflicts_with', 'duplicate', 'possibly_same_as',
|
|
164
|
+
)
|
|
165
|
+
SYMMETRIC_RELATION_KINDS = (
|
|
166
|
+
'same_work', 'conflicts_with', 'duplicate', 'possibly_same_as',
|
|
167
|
+
)
|
|
168
|
+
RELATION_DIRECTIONS = (
|
|
169
|
+
'primary_to_target', 'target_to_primary', 'symmetric', 'not_applicable',
|
|
170
|
+
)
|
|
171
|
+
CONTINUITY_RELATIONSHIPS = (
|
|
172
|
+
'continues_prior', 'returns_to_prior', 'new_work', 'corrects_prior',
|
|
173
|
+
'reviews_completed', 'resumes_completed', 'follow_up',
|
|
174
|
+
)
|
|
175
|
+
CONTINUITY_TARGET_KINDS = ('returned_handle', 'work_ref')
|
|
176
|
+
# Relationships about one earlier piece of work. An update may name its own
|
|
177
|
+
# work with one of them (for example resuming its own completed work).
|
|
178
|
+
PRIOR_WORK_RELATIONSHIPS = (
|
|
179
|
+
'continues_prior', 'returns_to_prior', 'corrects_prior',
|
|
180
|
+
'reviews_completed', 'resumes_completed',
|
|
181
|
+
)
|
|
182
|
+
REVISION_KINDS = ('corrects', 'supersedes', 'reaffirms')
|
|
183
|
+
|
|
184
|
+
LOCAL_REF = re.compile(r'^[a-z][a-z0-9_-]{0,63}$')
|
|
185
|
+
RANDOM_REF = re.compile(
|
|
186
|
+
r'^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$'
|
|
187
|
+
)
|
|
188
|
+
VERSION_TEXT = re.compile(r'^[A-Za-z0-9][A-Za-z0-9._+-]{0,39}$')
|
|
189
|
+
CONFIDENCE = re.compile(r'^(?:0(?:\.[0-9]{1,4})?|1(?:\.0{1,4})?)$')
|
|
190
|
+
RFC3339 = re.compile(
|
|
191
|
+
r'^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}'
|
|
192
|
+
r'(?:\.[0-9]{1,6})?(?:Z|[+-][0-9]{2}:[0-9]{2})$'
|
|
193
|
+
)
|
|
194
|
+
# Server-issued opaque handles: a work handle, or a fact handle naming the
|
|
195
|
+
# update unit it was reported in and its own local fact label.
|
|
196
|
+
WORK_HANDLE = re.compile(r'^wh_[a-z2-7]{26}$')
|
|
197
|
+
FACT_HANDLE = re.compile(r'^uh_[a-z2-7]{26}\.[a-z][a-z0-9_-]{0,63}$')
|
|
198
|
+
RETURNED_HANDLE = WORK_HANDLE
|
|
199
|
+
GIT_SHA = re.compile(r'^[0-9a-f]{7,40}$')
|
|
200
|
+
GIT_BRANCH = re.compile(r'^(?!-)(?!.*\.\.)[^\x00-\x20\x7f~^:?*\[\\]{1,200}$')
|
|
201
|
+
SCP_REMOTE = re.compile(
|
|
202
|
+
r'^(?:[A-Za-z0-9._-]+@)?(?P<host>[A-Za-z0-9.-]+):(?P<path>[A-Za-z0-9._~/-]+)$'
|
|
203
|
+
)
|
|
204
|
+
|
|
205
|
+
ENVELOPE_FIELDS = {
|
|
206
|
+
'schema', 'project_label', 'update_ref', 'stream_ref', 'sequence',
|
|
207
|
+
'works', 'reporter_version', 'privacy_policy_version', 'origin',
|
|
208
|
+
'session_complete',
|
|
209
|
+
}
|
|
210
|
+
WORK_FIELDS = {
|
|
211
|
+
'work_ref', 'operation', 'title', 'intended_outcome', 'activity',
|
|
212
|
+
'boundaries', 'facts', 'details', 'mentions', 'references',
|
|
213
|
+
'relation_hints', 'code', 'continuity', 'deferral', 'revisions',
|
|
214
|
+
}
|
|
215
|
+
FACT_FIELDS = {
|
|
216
|
+
'fact_ref', 'kind', 'status', 'statement', 'basis', 'confidence',
|
|
217
|
+
'occurred_at', 'uncertainty', 'repeats',
|
|
218
|
+
}
|
|
219
|
+
DETAIL_FIELDS = {
|
|
220
|
+
'detail_ref', 'kind', 'description', 'subject_labels', 'function_labels',
|
|
221
|
+
'environment', 'version_refs', 'temporal_status', 'uncertainty',
|
|
222
|
+
'supporting_fact_refs',
|
|
223
|
+
}
|
|
224
|
+
VERSION_REF_FIELDS = {'ref_kind', 'ref'}
|
|
225
|
+
MENTION_FIELDS = {
|
|
226
|
+
'mention_ref', 'entity_kind', 'safe_label', 'supporting_fact_refs',
|
|
227
|
+
}
|
|
228
|
+
REFERENCE_FIELDS = {
|
|
229
|
+
'reference_ref', 'reference_kind', 'target', 'supporting_fact_refs',
|
|
230
|
+
}
|
|
231
|
+
TARGET_FIELDS = {'kind', 'value'}
|
|
232
|
+
RELATION_FIELDS = {
|
|
233
|
+
'relation_kind', 'target_reference_ref', 'direction',
|
|
234
|
+
'supporting_fact_refs',
|
|
235
|
+
}
|
|
236
|
+
CODE_FIELDS = {'repository_url', 'branch', 'commits', 'pull_requests'}
|
|
237
|
+
CONTINUITY_FIELDS = {'relationship', 'target', 'supporting_fact_refs'}
|
|
238
|
+
DEFERRAL_FIELDS = {
|
|
239
|
+
'reason', 'resume_condition', 'resume_after', 'origin_work_ref',
|
|
240
|
+
'supporting_fact_refs',
|
|
241
|
+
}
|
|
242
|
+
REVISION_FIELDS = {'fact_handle', 'revision_kind', 'supporting_fact_refs'}
|
|
243
|
+
# A finding's path is built from these names and list indices only. A key
|
|
244
|
+
# the candidate made up is never repeated (it could itself hold a secret):
|
|
245
|
+
# it is shown as ``*``.
|
|
246
|
+
PATH_NAMES = frozenset().union(
|
|
247
|
+
ENVELOPE_FIELDS, WORK_FIELDS, FACT_FIELDS, DETAIL_FIELDS,
|
|
248
|
+
VERSION_REF_FIELDS, MENTION_FIELDS, REFERENCE_FIELDS, TARGET_FIELDS,
|
|
249
|
+
RELATION_FIELDS, CODE_FIELDS, CONTINUITY_FIELDS, DEFERRAL_FIELDS,
|
|
250
|
+
REVISION_FIELDS,
|
|
251
|
+
)
|
|
252
|
+
UNKNOWN_KEY = '*'
|
|
253
|
+
MAX_PATH_CHARS = 160
|
|
254
|
+
|
|
255
|
+
# Reason codes. Structural codes name the rule a field broke; ``secret.*``
|
|
256
|
+
# and ``privacy.*`` codes name the kind of value found, never the value.
|
|
257
|
+
REASON_CODES = (
|
|
258
|
+
'input_too_large', 'input_not_utf8', 'input_not_json', 'duplicate_key',
|
|
259
|
+
'non_finite_number', 'invalid_unicode', 'update_too_large',
|
|
260
|
+
'required', 'unknown_field', 'wrong_type', 'not_allowed', 'too_long',
|
|
261
|
+
'too_short', 'too_many', 'too_few', 'invalid_format', 'not_trimmed',
|
|
262
|
+
'control_character', 'hidden_character', 'duplicate', 'not_canonical',
|
|
263
|
+
'out_of_range', 'unknown_fact_ref', 'unknown_reference_ref',
|
|
264
|
+
'self_reference', 'declare_requires_field',
|
|
265
|
+
'declare_requires_commitment_or_deferral',
|
|
266
|
+
'status_not_allowed_for_kind', 'inference_cannot_assert_delivery',
|
|
267
|
+
'deferral_required', 'deferral_requires_deferred_fact',
|
|
268
|
+
'relation_direction_invalid', 'relation_target_required',
|
|
269
|
+
'relation_target_forbidden', 'continuity_target_required',
|
|
270
|
+
'continuity_target_forbidden', 'reference_target_not_allowed',
|
|
271
|
+
'required_for_history_import', 'history_import_only',
|
|
272
|
+
'secret.private_key', 'secret.provider_key', 'secret.authorization',
|
|
273
|
+
'secret.sensitive_assignment', 'secret.jwt', 'secret.credential_url',
|
|
274
|
+
'secret.sensitive_url_parameter', 'secret.webhook_url',
|
|
275
|
+
'secret.opaque_blob', 'privacy.local_path',
|
|
276
|
+
'preflight_internal_error', 'python_version_unsupported',
|
|
277
|
+
)
|
|
278
|
+
|
|
279
|
+
|
|
280
|
+
class Finding(tuple):
|
|
281
|
+
"""One refusal: where (a JSON path) and why (a reason code)."""
|
|
282
|
+
|
|
283
|
+
__slots__ = ()
|
|
284
|
+
|
|
285
|
+
def __new__(cls, path: str, code: str):
|
|
286
|
+
return tuple.__new__(cls, (str(path)[:MAX_PATH_CHARS], code))
|
|
287
|
+
|
|
288
|
+
@property
|
|
289
|
+
def path(self) -> str:
|
|
290
|
+
return self[0]
|
|
291
|
+
|
|
292
|
+
@property
|
|
293
|
+
def code(self) -> str:
|
|
294
|
+
return self[1]
|
|
295
|
+
|
|
296
|
+
def wire(self) -> dict:
|
|
297
|
+
return {'path': self[0], 'code': self[1]}
|
|
298
|
+
|
|
299
|
+
|
|
300
|
+
class CandidateRefused(ValueError):
|
|
301
|
+
def __init__(self, findings):
|
|
302
|
+
super().__init__('candidate refused')
|
|
303
|
+
self.findings = list(findings)
|
|
304
|
+
|
|
305
|
+
|
|
306
|
+
# ── Strict JSON input ─────────────────────────────────────────────────────
|
|
307
|
+
|
|
308
|
+
|
|
309
|
+
def _reject_duplicates(pairs):
|
|
310
|
+
seen = {}
|
|
311
|
+
for key, value in pairs:
|
|
312
|
+
if key in seen:
|
|
313
|
+
raise CandidateRefused([Finding('$', 'duplicate_key')])
|
|
314
|
+
seen[key] = value
|
|
315
|
+
return seen
|
|
316
|
+
|
|
317
|
+
|
|
318
|
+
def _reject_constant(_name):
|
|
319
|
+
raise CandidateRefused([Finding('$', 'non_finite_number')])
|
|
320
|
+
|
|
321
|
+
|
|
322
|
+
def _parse_float(text):
|
|
323
|
+
value = float(text)
|
|
324
|
+
if not math.isfinite(value):
|
|
325
|
+
raise CandidateRefused([Finding('$', 'non_finite_number')])
|
|
326
|
+
return value
|
|
327
|
+
|
|
328
|
+
|
|
329
|
+
def load_candidate(raw) -> object:
|
|
330
|
+
"""Parse one candidate with a size cap, strict UTF-8 and unique keys."""
|
|
331
|
+
|
|
332
|
+
if isinstance(raw, str):
|
|
333
|
+
try:
|
|
334
|
+
raw = raw.encode('utf-8')
|
|
335
|
+
except UnicodeEncodeError:
|
|
336
|
+
raise CandidateRefused([Finding('$', 'invalid_unicode')])
|
|
337
|
+
if len(raw) > MAX_RAW_INPUT_BYTES:
|
|
338
|
+
raise CandidateRefused([Finding('$', 'input_too_large')])
|
|
339
|
+
try:
|
|
340
|
+
text = raw.decode('utf-8')
|
|
341
|
+
except UnicodeDecodeError:
|
|
342
|
+
raise CandidateRefused([Finding('$', 'input_not_utf8')])
|
|
343
|
+
try:
|
|
344
|
+
return json.loads(
|
|
345
|
+
text,
|
|
346
|
+
object_pairs_hook=_reject_duplicates,
|
|
347
|
+
parse_constant=_reject_constant,
|
|
348
|
+
parse_float=_parse_float,
|
|
349
|
+
)
|
|
350
|
+
except CandidateRefused:
|
|
351
|
+
raise
|
|
352
|
+
except (ValueError, RecursionError):
|
|
353
|
+
raise CandidateRefused([Finding('$', 'input_not_json')])
|
|
354
|
+
|
|
355
|
+
|
|
356
|
+
# ── Canonical form ────────────────────────────────────────────────────────
|
|
357
|
+
|
|
358
|
+
|
|
359
|
+
def _without_nulls(value):
|
|
360
|
+
if isinstance(value, dict):
|
|
361
|
+
return {
|
|
362
|
+
key: _without_nulls(item) for key, item in value.items()
|
|
363
|
+
if item is not None
|
|
364
|
+
}
|
|
365
|
+
if isinstance(value, list):
|
|
366
|
+
return [_without_nulls(item) for item in value]
|
|
367
|
+
return value
|
|
368
|
+
|
|
369
|
+
|
|
370
|
+
def canonical_json(value) -> str:
|
|
371
|
+
"""Sorted keys, no insignificant whitespace, no null members."""
|
|
372
|
+
|
|
373
|
+
return json.dumps(
|
|
374
|
+
_without_nulls(value), sort_keys=True, separators=(',', ':'),
|
|
375
|
+
ensure_ascii=False, allow_nan=False,
|
|
376
|
+
)
|
|
377
|
+
|
|
378
|
+
|
|
379
|
+
def canonical_bytes(value) -> bytes:
|
|
380
|
+
return canonical_json(value).encode('utf-8')
|
|
381
|
+
|
|
382
|
+
|
|
383
|
+
# ── Structural validation ─────────────────────────────────────────────────
|
|
384
|
+
|
|
385
|
+
|
|
386
|
+
def _hidden(char: str) -> bool:
|
|
387
|
+
return unicodedata.category(char) in ('Cf', 'Co')
|
|
388
|
+
|
|
389
|
+
|
|
390
|
+
def _text_findings(path, value, *, max_chars=None, max_bytes=None):
|
|
391
|
+
if not isinstance(value, str):
|
|
392
|
+
return [Finding(path, 'wrong_type')]
|
|
393
|
+
if any(unicodedata.category(char) == 'Cs' for char in value):
|
|
394
|
+
return [Finding(path, 'invalid_unicode')]
|
|
395
|
+
if not value.strip():
|
|
396
|
+
return [Finding(path, 'too_short')]
|
|
397
|
+
found = []
|
|
398
|
+
if value != value.strip():
|
|
399
|
+
found.append(Finding(path, 'not_trimmed'))
|
|
400
|
+
if any(unicodedata.category(char) == 'Cc' for char in value):
|
|
401
|
+
found.append(Finding(path, 'control_character'))
|
|
402
|
+
if any(_hidden(char) for char in value):
|
|
403
|
+
found.append(Finding(path, 'hidden_character'))
|
|
404
|
+
if max_chars is not None and len(value) > max_chars:
|
|
405
|
+
found.append(Finding(path, 'too_long'))
|
|
406
|
+
if max_bytes is not None and len(value.encode('utf-8')) > max_bytes:
|
|
407
|
+
found.append(Finding(path, 'too_long'))
|
|
408
|
+
return found
|
|
409
|
+
|
|
410
|
+
|
|
411
|
+
def _token_findings(path, value, pattern):
|
|
412
|
+
if not isinstance(value, str):
|
|
413
|
+
return [Finding(path, 'wrong_type')]
|
|
414
|
+
if pattern.fullmatch(value) is None:
|
|
415
|
+
return [Finding(path, 'invalid_format')]
|
|
416
|
+
return []
|
|
417
|
+
|
|
418
|
+
|
|
419
|
+
def _enum_findings(path, value, allowed):
|
|
420
|
+
if not isinstance(value, str):
|
|
421
|
+
return [Finding(path, 'wrong_type')]
|
|
422
|
+
if value not in allowed:
|
|
423
|
+
return [Finding(path, 'not_allowed')]
|
|
424
|
+
return []
|
|
425
|
+
|
|
426
|
+
|
|
427
|
+
def _timestamp_findings(path, value):
|
|
428
|
+
if not isinstance(value, str):
|
|
429
|
+
return [Finding(path, 'wrong_type')]
|
|
430
|
+
if RFC3339.fullmatch(value) is None:
|
|
431
|
+
return [Finding(path, 'invalid_format')]
|
|
432
|
+
from datetime import datetime
|
|
433
|
+
|
|
434
|
+
try:
|
|
435
|
+
parsed = datetime.fromisoformat(value.replace('Z', '+00:00'))
|
|
436
|
+
except ValueError:
|
|
437
|
+
return [Finding(path, 'invalid_format')]
|
|
438
|
+
if parsed.tzinfo is None:
|
|
439
|
+
return [Finding(path, 'invalid_format')]
|
|
440
|
+
return []
|
|
441
|
+
|
|
442
|
+
|
|
443
|
+
def _object(path, value, allowed, required=()):
|
|
444
|
+
"""(object or None, findings) for a closed object."""
|
|
445
|
+
|
|
446
|
+
if not isinstance(value, dict):
|
|
447
|
+
return None, [Finding(path, 'wrong_type')]
|
|
448
|
+
found = (
|
|
449
|
+
[Finding(_join(path, UNKNOWN_KEY), 'unknown_field')]
|
|
450
|
+
if set(value) - set(allowed) else []
|
|
451
|
+
)
|
|
452
|
+
for key in required:
|
|
453
|
+
if value.get(key) is None:
|
|
454
|
+
found.append(Finding(_join(path, key), 'required'))
|
|
455
|
+
return value, found
|
|
456
|
+
|
|
457
|
+
|
|
458
|
+
def _join(path, key):
|
|
459
|
+
return key if path == '$' else f'{path}.{key}'
|
|
460
|
+
|
|
461
|
+
|
|
462
|
+
def _list(path, value, *, maximum, minimum=0):
|
|
463
|
+
if not isinstance(value, list):
|
|
464
|
+
return None, [Finding(path, 'wrong_type')]
|
|
465
|
+
found = []
|
|
466
|
+
if len(value) > maximum:
|
|
467
|
+
found.append(Finding(path, 'too_many'))
|
|
468
|
+
if len(value) < minimum:
|
|
469
|
+
found.append(Finding(path, 'too_few'))
|
|
470
|
+
return value, found
|
|
471
|
+
|
|
472
|
+
|
|
473
|
+
def _present(value, key):
|
|
474
|
+
return isinstance(value, dict) and value.get(key) is not None
|
|
475
|
+
|
|
476
|
+
|
|
477
|
+
def _supporting_findings(path, value, fact_refs):
|
|
478
|
+
items, found = _list(path, value, maximum=MAX_SUPPORTING_FACTS, minimum=1)
|
|
479
|
+
if items is None:
|
|
480
|
+
return found
|
|
481
|
+
seen = set()
|
|
482
|
+
for index, item in enumerate(items):
|
|
483
|
+
item_path = f'{path}[{index}]'
|
|
484
|
+
problems = _token_findings(item_path, item, LOCAL_REF)
|
|
485
|
+
if problems:
|
|
486
|
+
found.extend(problems)
|
|
487
|
+
continue
|
|
488
|
+
if item in seen:
|
|
489
|
+
found.append(Finding(item_path, 'duplicate'))
|
|
490
|
+
seen.add(item)
|
|
491
|
+
if item not in fact_refs:
|
|
492
|
+
found.append(Finding(item_path, 'unknown_fact_ref'))
|
|
493
|
+
return found
|
|
494
|
+
|
|
495
|
+
|
|
496
|
+
def safe_repository_url(value) -> str | None:
|
|
497
|
+
"""A git remote with credentials, query and fragment removed.
|
|
498
|
+
|
|
499
|
+
Remotes can carry tokens (``https://user:token@host/...``); nothing but
|
|
500
|
+
the host and path is kept. Returns None for anything unusable. The same
|
|
501
|
+
sanitizer the v1 report contract uses; v2 requires the canonical result.
|
|
502
|
+
"""
|
|
503
|
+
|
|
504
|
+
text = str(value or '').strip()
|
|
505
|
+
if not text or any(char.isspace() for char in text):
|
|
506
|
+
return None
|
|
507
|
+
if '://' not in text:
|
|
508
|
+
match = SCP_REMOTE.fullmatch(text)
|
|
509
|
+
if match is None:
|
|
510
|
+
return None
|
|
511
|
+
return f'{match.group("host").lower()}:{match.group("path")}'
|
|
512
|
+
try:
|
|
513
|
+
parts = urlsplit(text)
|
|
514
|
+
port = parts.port
|
|
515
|
+
except ValueError:
|
|
516
|
+
return None
|
|
517
|
+
if parts.scheme not in ('https', 'http', 'ssh', 'git') or not parts.hostname:
|
|
518
|
+
return None
|
|
519
|
+
if not parts.path or parts.path == '/':
|
|
520
|
+
return None
|
|
521
|
+
host = parts.hostname.lower() + (f':{port}' if port else '')
|
|
522
|
+
return f'{parts.scheme}://{host}{parts.path}'
|
|
523
|
+
|
|
524
|
+
|
|
525
|
+
def _safe_url_findings(path, value):
|
|
526
|
+
found = _text_findings(path, value, max_bytes=SAFE_URL_MAX_BYTES)
|
|
527
|
+
if found:
|
|
528
|
+
return found
|
|
529
|
+
if any(char.isspace() for char in value):
|
|
530
|
+
return [Finding(path, 'invalid_format')]
|
|
531
|
+
try:
|
|
532
|
+
parts = urlsplit(value)
|
|
533
|
+
parts.port
|
|
534
|
+
except ValueError:
|
|
535
|
+
return [Finding(path, 'invalid_format')]
|
|
536
|
+
if parts.scheme != 'https' or not parts.hostname:
|
|
537
|
+
return [Finding(path, 'invalid_format')]
|
|
538
|
+
# Credentials in a URL are a secret finding, reported by the scan.
|
|
539
|
+
return []
|
|
540
|
+
|
|
541
|
+
|
|
542
|
+
def _code_findings(path, value):
|
|
543
|
+
code, found = _object(path, value, CODE_FIELDS)
|
|
544
|
+
if code is None:
|
|
545
|
+
return found
|
|
546
|
+
if not any(code.get(key) for key in CODE_FIELDS):
|
|
547
|
+
found.append(Finding(path, 'too_few'))
|
|
548
|
+
if code.get('repository_url') is not None:
|
|
549
|
+
item_path = _join(path, 'repository_url')
|
|
550
|
+
problems = _text_findings(
|
|
551
|
+
item_path, code['repository_url'],
|
|
552
|
+
max_chars=REPOSITORY_URL_MAX_CHARS,
|
|
553
|
+
)
|
|
554
|
+
if problems:
|
|
555
|
+
found.extend(problems)
|
|
556
|
+
elif safe_repository_url(code['repository_url']) is None:
|
|
557
|
+
found.append(Finding(item_path, 'invalid_format'))
|
|
558
|
+
elif safe_repository_url(code['repository_url']) != code['repository_url']:
|
|
559
|
+
found.append(Finding(item_path, 'not_canonical'))
|
|
560
|
+
if code.get('branch') is not None:
|
|
561
|
+
item_path = _join(path, 'branch')
|
|
562
|
+
problems = _text_findings(item_path, code['branch'], max_chars=BRANCH_MAX_CHARS)
|
|
563
|
+
if problems:
|
|
564
|
+
found.extend(problems)
|
|
565
|
+
elif GIT_BRANCH.fullmatch(code['branch']) is None:
|
|
566
|
+
found.append(Finding(item_path, 'invalid_format'))
|
|
567
|
+
if code.get('commits') is not None:
|
|
568
|
+
items, problems = _list(
|
|
569
|
+
_join(path, 'commits'), code['commits'], maximum=MAX_COMMITS,
|
|
570
|
+
)
|
|
571
|
+
found.extend(problems)
|
|
572
|
+
seen = set()
|
|
573
|
+
for index, item in enumerate(items or ()):
|
|
574
|
+
item_path = f'{_join(path, "commits")}[{index}]'
|
|
575
|
+
problems = _token_findings(item_path, item, GIT_SHA)
|
|
576
|
+
found.extend(problems)
|
|
577
|
+
if not problems:
|
|
578
|
+
if item in seen:
|
|
579
|
+
found.append(Finding(item_path, 'duplicate'))
|
|
580
|
+
seen.add(item)
|
|
581
|
+
if code.get('pull_requests') is not None:
|
|
582
|
+
items, problems = _list(
|
|
583
|
+
_join(path, 'pull_requests'), code['pull_requests'],
|
|
584
|
+
maximum=MAX_PULL_REQUESTS,
|
|
585
|
+
)
|
|
586
|
+
found.extend(problems)
|
|
587
|
+
seen = set()
|
|
588
|
+
for index, item in enumerate(items or ()):
|
|
589
|
+
item_path = f'{_join(path, "pull_requests")}[{index}]'
|
|
590
|
+
if isinstance(item, bool) or not isinstance(item, int):
|
|
591
|
+
found.append(Finding(item_path, 'wrong_type'))
|
|
592
|
+
continue
|
|
593
|
+
if not 0 < item < 100_000_000:
|
|
594
|
+
found.append(Finding(item_path, 'out_of_range'))
|
|
595
|
+
continue
|
|
596
|
+
if item in seen:
|
|
597
|
+
found.append(Finding(item_path, 'duplicate'))
|
|
598
|
+
seen.add(item)
|
|
599
|
+
return found
|
|
600
|
+
|
|
601
|
+
|
|
602
|
+
def _target_findings(path, value, allowed_kinds, *, own_work_ref, allow_self=False):
|
|
603
|
+
target, found = _object(path, value, TARGET_FIELDS, ('kind', 'value'))
|
|
604
|
+
if target is None or found:
|
|
605
|
+
return found
|
|
606
|
+
kind = target['kind']
|
|
607
|
+
found.extend(_enum_findings(_join(path, 'kind'), kind, TARGET_KINDS))
|
|
608
|
+
if found:
|
|
609
|
+
return found
|
|
610
|
+
if kind not in allowed_kinds:
|
|
611
|
+
return [Finding(_join(path, 'kind'), 'reference_target_not_allowed')]
|
|
612
|
+
value_path = _join(path, 'value')
|
|
613
|
+
if kind == 'returned_handle':
|
|
614
|
+
return _token_findings(value_path, target['value'], RETURNED_HANDLE)
|
|
615
|
+
if kind == 'work_ref':
|
|
616
|
+
problems = _token_findings(value_path, target['value'], LOCAL_REF)
|
|
617
|
+
if not problems and target['value'] == own_work_ref and not allow_self:
|
|
618
|
+
problems.append(Finding(value_path, 'self_reference'))
|
|
619
|
+
return problems
|
|
620
|
+
return _safe_url_findings(value_path, target['value'])
|
|
621
|
+
|
|
622
|
+
|
|
623
|
+
def _fact_findings(path, value):
|
|
624
|
+
fact, found = _object(
|
|
625
|
+
path, value, FACT_FIELDS,
|
|
626
|
+
('fact_ref', 'kind', 'status', 'statement', 'basis', 'confidence'),
|
|
627
|
+
)
|
|
628
|
+
if fact is None:
|
|
629
|
+
return found
|
|
630
|
+
if fact.get('fact_ref') is not None:
|
|
631
|
+
found.extend(_token_findings(_join(path, 'fact_ref'), fact['fact_ref'], LOCAL_REF))
|
|
632
|
+
kind_ok = status_ok = False
|
|
633
|
+
if fact.get('kind') is not None:
|
|
634
|
+
problems = _enum_findings(_join(path, 'kind'), fact['kind'], FACT_KINDS)
|
|
635
|
+
found.extend(problems)
|
|
636
|
+
kind_ok = not problems
|
|
637
|
+
if fact.get('status') is not None:
|
|
638
|
+
problems = _enum_findings(_join(path, 'status'), fact['status'], CLAIM_STATUSES)
|
|
639
|
+
found.extend(problems)
|
|
640
|
+
status_ok = not problems
|
|
641
|
+
if kind_ok and status_ok and fact['status'] not in STATUSES_BY_KIND[fact['kind']]:
|
|
642
|
+
found.append(Finding(_join(path, 'status'), 'status_not_allowed_for_kind'))
|
|
643
|
+
if fact.get('statement') is not None:
|
|
644
|
+
found.extend(_text_findings(
|
|
645
|
+
_join(path, 'statement'), fact['statement'],
|
|
646
|
+
max_bytes=STATEMENT_MAX_BYTES,
|
|
647
|
+
))
|
|
648
|
+
if fact.get('basis') is not None:
|
|
649
|
+
problems = _enum_findings(_join(path, 'basis'), fact['basis'], BASES)
|
|
650
|
+
found.extend(problems)
|
|
651
|
+
if (
|
|
652
|
+
not problems and status_ok and fact['basis'] == 'agent_inference'
|
|
653
|
+
and fact['status'] in DELIVERY_STATUSES
|
|
654
|
+
):
|
|
655
|
+
found.append(Finding(_join(path, 'status'), 'inference_cannot_assert_delivery'))
|
|
656
|
+
if fact.get('confidence') is not None:
|
|
657
|
+
found.extend(_token_findings(
|
|
658
|
+
_join(path, 'confidence'), fact['confidence'], CONFIDENCE,
|
|
659
|
+
))
|
|
660
|
+
if fact.get('occurred_at') is not None:
|
|
661
|
+
found.extend(_timestamp_findings(_join(path, 'occurred_at'), fact['occurred_at']))
|
|
662
|
+
if fact.get('uncertainty') is not None:
|
|
663
|
+
found.extend(_text_findings(
|
|
664
|
+
_join(path, 'uncertainty'), fact['uncertainty'],
|
|
665
|
+
max_bytes=UNCERTAINTY_MAX_BYTES,
|
|
666
|
+
))
|
|
667
|
+
if fact.get('repeats') is not None:
|
|
668
|
+
found.extend(_token_findings(
|
|
669
|
+
_join(path, 'repeats'), fact['repeats'], FACT_HANDLE,
|
|
670
|
+
))
|
|
671
|
+
return found
|
|
672
|
+
|
|
673
|
+
|
|
674
|
+
def _labels_findings(path, value, *, maximum, max_chars):
|
|
675
|
+
items, found = _list(path, value, maximum=maximum)
|
|
676
|
+
seen = set()
|
|
677
|
+
for index, item in enumerate(items or ()):
|
|
678
|
+
item_path = f'{path}[{index}]'
|
|
679
|
+
problems = _text_findings(item_path, item, max_chars=max_chars)
|
|
680
|
+
found.extend(problems)
|
|
681
|
+
if not problems:
|
|
682
|
+
if item in seen:
|
|
683
|
+
found.append(Finding(item_path, 'duplicate'))
|
|
684
|
+
seen.add(item)
|
|
685
|
+
return found
|
|
686
|
+
|
|
687
|
+
|
|
688
|
+
def _detail_findings(path, value, fact_refs):
|
|
689
|
+
detail, found = _object(
|
|
690
|
+
path, value, DETAIL_FIELDS,
|
|
691
|
+
('detail_ref', 'kind', 'description', 'temporal_status',
|
|
692
|
+
'supporting_fact_refs'),
|
|
693
|
+
)
|
|
694
|
+
if detail is None:
|
|
695
|
+
return found
|
|
696
|
+
if detail.get('detail_ref') is not None:
|
|
697
|
+
found.extend(_token_findings(_join(path, 'detail_ref'), detail['detail_ref'], LOCAL_REF))
|
|
698
|
+
if detail.get('kind') is not None:
|
|
699
|
+
found.extend(_enum_findings(_join(path, 'kind'), detail['kind'], DETAIL_KINDS))
|
|
700
|
+
if detail.get('description') is not None:
|
|
701
|
+
found.extend(_text_findings(
|
|
702
|
+
_join(path, 'description'), detail['description'],
|
|
703
|
+
max_bytes=DETAIL_DESCRIPTION_MAX_BYTES,
|
|
704
|
+
))
|
|
705
|
+
if detail.get('subject_labels') is not None:
|
|
706
|
+
found.extend(_labels_findings(
|
|
707
|
+
_join(path, 'subject_labels'), detail['subject_labels'],
|
|
708
|
+
maximum=MAX_SUBJECT_LABELS, max_chars=SUBJECT_LABEL_MAX_CHARS,
|
|
709
|
+
))
|
|
710
|
+
if detail.get('function_labels') is not None:
|
|
711
|
+
found.extend(_labels_findings(
|
|
712
|
+
_join(path, 'function_labels'), detail['function_labels'],
|
|
713
|
+
maximum=MAX_FUNCTION_LABELS, max_chars=FUNCTION_LABEL_MAX_CHARS,
|
|
714
|
+
))
|
|
715
|
+
if detail.get('environment') is not None:
|
|
716
|
+
found.extend(_text_findings(
|
|
717
|
+
_join(path, 'environment'), detail['environment'],
|
|
718
|
+
max_chars=ENVIRONMENT_MAX_CHARS,
|
|
719
|
+
))
|
|
720
|
+
if detail.get('version_refs') is not None:
|
|
721
|
+
refs_path = _join(path, 'version_refs')
|
|
722
|
+
items, problems = _list(refs_path, detail['version_refs'], maximum=MAX_VERSION_REFS)
|
|
723
|
+
found.extend(problems)
|
|
724
|
+
seen = set()
|
|
725
|
+
for index, item in enumerate(items or ()):
|
|
726
|
+
item_path = f'{refs_path}[{index}]'
|
|
727
|
+
ref, problems = _object(item_path, item, VERSION_REF_FIELDS, ('ref_kind', 'ref'))
|
|
728
|
+
found.extend(problems)
|
|
729
|
+
if ref is None or problems:
|
|
730
|
+
continue
|
|
731
|
+
problems = _enum_findings(_join(item_path, 'ref_kind'), ref['ref_kind'], VERSION_REF_KINDS)
|
|
732
|
+
problems += _text_findings(
|
|
733
|
+
_join(item_path, 'ref'), ref['ref'], max_chars=VERSION_REF_MAX_CHARS,
|
|
734
|
+
)
|
|
735
|
+
if not problems and any(char.isspace() for char in ref['ref']):
|
|
736
|
+
problems.append(Finding(_join(item_path, 'ref'), 'invalid_format'))
|
|
737
|
+
found.extend(problems)
|
|
738
|
+
if not problems:
|
|
739
|
+
key = (ref['ref_kind'], ref['ref'])
|
|
740
|
+
if key in seen:
|
|
741
|
+
found.append(Finding(item_path, 'duplicate'))
|
|
742
|
+
seen.add(key)
|
|
743
|
+
if detail.get('temporal_status') is not None:
|
|
744
|
+
found.extend(_enum_findings(
|
|
745
|
+
_join(path, 'temporal_status'), detail['temporal_status'],
|
|
746
|
+
TEMPORAL_STATUSES,
|
|
747
|
+
))
|
|
748
|
+
if detail.get('uncertainty') is not None:
|
|
749
|
+
found.extend(_text_findings(
|
|
750
|
+
_join(path, 'uncertainty'), detail['uncertainty'],
|
|
751
|
+
max_bytes=UNCERTAINTY_MAX_BYTES,
|
|
752
|
+
))
|
|
753
|
+
if detail.get('supporting_fact_refs') is not None:
|
|
754
|
+
found.extend(_supporting_findings(
|
|
755
|
+
_join(path, 'supporting_fact_refs'), detail['supporting_fact_refs'],
|
|
756
|
+
fact_refs,
|
|
757
|
+
))
|
|
758
|
+
return found
|
|
759
|
+
|
|
760
|
+
|
|
761
|
+
def _work_findings(path, value, fact_refs_by_work=None):
|
|
762
|
+
work, found = _object(
|
|
763
|
+
path, value, WORK_FIELDS, ('work_ref', 'operation', 'facts'),
|
|
764
|
+
)
|
|
765
|
+
if work is None:
|
|
766
|
+
return found
|
|
767
|
+
own = work.get('work_ref') if isinstance(work.get('work_ref'), str) else None
|
|
768
|
+
if work.get('work_ref') is not None:
|
|
769
|
+
found.extend(_token_findings(_join(path, 'work_ref'), work['work_ref'], LOCAL_REF))
|
|
770
|
+
operation = work.get('operation')
|
|
771
|
+
if operation is not None:
|
|
772
|
+
found.extend(_enum_findings(_join(path, 'operation'), operation, OPERATIONS))
|
|
773
|
+
if operation == 'declare':
|
|
774
|
+
for key in ('title', 'intended_outcome', 'activity'):
|
|
775
|
+
if work.get(key) is None:
|
|
776
|
+
found.append(Finding(_join(path, key), 'declare_requires_field'))
|
|
777
|
+
if work.get('title') is not None:
|
|
778
|
+
found.extend(_text_findings(_join(path, 'title'), work['title'], max_chars=TITLE_MAX_CHARS))
|
|
779
|
+
if work.get('intended_outcome') is not None:
|
|
780
|
+
found.extend(_text_findings(
|
|
781
|
+
_join(path, 'intended_outcome'), work['intended_outcome'],
|
|
782
|
+
max_bytes=OUTCOME_MAX_BYTES,
|
|
783
|
+
))
|
|
784
|
+
if work.get('activity') is not None:
|
|
785
|
+
found.extend(_enum_findings(_join(path, 'activity'), work['activity'], ACTIVITIES))
|
|
786
|
+
if work.get('boundaries') is not None:
|
|
787
|
+
boundaries_path = _join(path, 'boundaries')
|
|
788
|
+
items, problems = _list(boundaries_path, work['boundaries'], maximum=MAX_BOUNDARIES)
|
|
789
|
+
found.extend(problems)
|
|
790
|
+
seen = set()
|
|
791
|
+
for index, item in enumerate(items or ()):
|
|
792
|
+
item_path = f'{boundaries_path}[{index}]'
|
|
793
|
+
problems = _text_findings(item_path, item, max_bytes=BOUNDARY_MAX_BYTES)
|
|
794
|
+
found.extend(problems)
|
|
795
|
+
if not problems:
|
|
796
|
+
if item in seen:
|
|
797
|
+
found.append(Finding(item_path, 'duplicate'))
|
|
798
|
+
seen.add(item)
|
|
799
|
+
|
|
800
|
+
fact_refs = set()
|
|
801
|
+
fact_kinds = {}
|
|
802
|
+
if work.get('facts') is not None:
|
|
803
|
+
facts_path = _join(path, 'facts')
|
|
804
|
+
items, problems = _list(facts_path, work['facts'], maximum=MAX_FACTS, minimum=1)
|
|
805
|
+
found.extend(problems)
|
|
806
|
+
for index, item in enumerate(items or ()):
|
|
807
|
+
item_path = f'{facts_path}[{index}]'
|
|
808
|
+
found.extend(_fact_findings(item_path, item))
|
|
809
|
+
ref = item.get('fact_ref') if isinstance(item, dict) else None
|
|
810
|
+
if isinstance(ref, str) and LOCAL_REF.fullmatch(ref):
|
|
811
|
+
if ref in fact_refs:
|
|
812
|
+
found.append(Finding(_join(item_path, 'fact_ref'), 'duplicate'))
|
|
813
|
+
fact_refs.add(ref)
|
|
814
|
+
if isinstance(item.get('kind'), str):
|
|
815
|
+
fact_kinds[ref] = item['kind']
|
|
816
|
+
kinds = {
|
|
817
|
+
item['kind'] for item in (items or ())
|
|
818
|
+
if isinstance(item, dict) and isinstance(item.get('kind'), str)
|
|
819
|
+
}
|
|
820
|
+
if operation == 'declare' and items and not kinds & {
|
|
821
|
+
'commitment', 'explicit_deferral',
|
|
822
|
+
}:
|
|
823
|
+
found.append(Finding(facts_path, 'declare_requires_commitment_or_deferral'))
|
|
824
|
+
if 'explicit_deferral' in kinds and work.get('deferral') is None:
|
|
825
|
+
found.append(Finding(_join(path, 'deferral'), 'deferral_required'))
|
|
826
|
+
|
|
827
|
+
for key, fields, limit, ref_key in (
|
|
828
|
+
('details', DETAIL_FIELDS, MAX_DETAILS, 'detail_ref'),
|
|
829
|
+
('mentions', MENTION_FIELDS, MAX_MENTIONS, 'mention_ref'),
|
|
830
|
+
('references', REFERENCE_FIELDS, MAX_REFERENCES, 'reference_ref'),
|
|
831
|
+
):
|
|
832
|
+
if work.get(key) is None:
|
|
833
|
+
continue
|
|
834
|
+
list_path = _join(path, key)
|
|
835
|
+
items, problems = _list(list_path, work[key], maximum=limit)
|
|
836
|
+
found.extend(problems)
|
|
837
|
+
labels = set()
|
|
838
|
+
for index, item in enumerate(items or ()):
|
|
839
|
+
item_path = f'{list_path}[{index}]'
|
|
840
|
+
if key == 'details':
|
|
841
|
+
found.extend(_detail_findings(item_path, item, fact_refs))
|
|
842
|
+
elif key == 'mentions':
|
|
843
|
+
found.extend(_mention_findings(item_path, item, fact_refs))
|
|
844
|
+
else:
|
|
845
|
+
found.extend(_reference_findings(item_path, item, fact_refs, own))
|
|
846
|
+
label = item.get(ref_key) if isinstance(item, dict) else None
|
|
847
|
+
if isinstance(label, str) and LOCAL_REF.fullmatch(label):
|
|
848
|
+
if label in labels:
|
|
849
|
+
found.append(Finding(_join(item_path, ref_key), 'duplicate'))
|
|
850
|
+
labels.add(label)
|
|
851
|
+
|
|
852
|
+
reference_refs = {
|
|
853
|
+
item.get('reference_ref') for item in (work.get('references') or ())
|
|
854
|
+
if isinstance(item, dict) and isinstance(item.get('reference_ref'), str)
|
|
855
|
+
} if isinstance(work.get('references'), list) else set()
|
|
856
|
+
if work.get('relation_hints') is not None:
|
|
857
|
+
hints_path = _join(path, 'relation_hints')
|
|
858
|
+
items, problems = _list(hints_path, work['relation_hints'], maximum=MAX_RELATION_HINTS)
|
|
859
|
+
found.extend(problems)
|
|
860
|
+
for index, item in enumerate(items or ()):
|
|
861
|
+
found.extend(_relation_findings(
|
|
862
|
+
f'{hints_path}[{index}]', item, fact_refs, reference_refs,
|
|
863
|
+
))
|
|
864
|
+
if work.get('code') is not None:
|
|
865
|
+
found.extend(_code_findings(_join(path, 'code'), work['code']))
|
|
866
|
+
if work.get('continuity') is not None:
|
|
867
|
+
found.extend(_continuity_findings(
|
|
868
|
+
_join(path, 'continuity'), work['continuity'], fact_refs, own,
|
|
869
|
+
operation=operation,
|
|
870
|
+
))
|
|
871
|
+
if work.get('deferral') is not None:
|
|
872
|
+
found.extend(_deferral_findings(
|
|
873
|
+
_join(path, 'deferral'), work['deferral'], fact_refs, fact_kinds, own,
|
|
874
|
+
))
|
|
875
|
+
if work.get('revisions') is not None:
|
|
876
|
+
revisions_path = _join(path, 'revisions')
|
|
877
|
+
items, problems = _list(revisions_path, work['revisions'], maximum=MAX_REVISIONS)
|
|
878
|
+
found.extend(problems)
|
|
879
|
+
seen = set()
|
|
880
|
+
for index, item in enumerate(items or ()):
|
|
881
|
+
item_path = f'{revisions_path}[{index}]'
|
|
882
|
+
revision, problems = _object(
|
|
883
|
+
item_path, item, REVISION_FIELDS,
|
|
884
|
+
('fact_handle', 'revision_kind', 'supporting_fact_refs'),
|
|
885
|
+
)
|
|
886
|
+
found.extend(problems)
|
|
887
|
+
if revision is None:
|
|
888
|
+
continue
|
|
889
|
+
if revision.get('fact_handle') is not None:
|
|
890
|
+
problems = _token_findings(
|
|
891
|
+
_join(item_path, 'fact_handle'), revision['fact_handle'],
|
|
892
|
+
FACT_HANDLE,
|
|
893
|
+
)
|
|
894
|
+
found.extend(problems)
|
|
895
|
+
if not problems:
|
|
896
|
+
if revision['fact_handle'] in seen:
|
|
897
|
+
found.append(Finding(_join(item_path, 'fact_handle'), 'duplicate'))
|
|
898
|
+
seen.add(revision['fact_handle'])
|
|
899
|
+
if revision.get('revision_kind') is not None:
|
|
900
|
+
found.extend(_enum_findings(
|
|
901
|
+
_join(item_path, 'revision_kind'), revision['revision_kind'],
|
|
902
|
+
REVISION_KINDS,
|
|
903
|
+
))
|
|
904
|
+
if revision.get('supporting_fact_refs') is not None:
|
|
905
|
+
found.extend(_supporting_findings(
|
|
906
|
+
_join(item_path, 'supporting_fact_refs'),
|
|
907
|
+
revision['supporting_fact_refs'], fact_refs,
|
|
908
|
+
))
|
|
909
|
+
return found
|
|
910
|
+
|
|
911
|
+
|
|
912
|
+
def _mention_findings(path, value, fact_refs):
|
|
913
|
+
mention, found = _object(
|
|
914
|
+
path, value, MENTION_FIELDS,
|
|
915
|
+
('mention_ref', 'entity_kind', 'safe_label', 'supporting_fact_refs'),
|
|
916
|
+
)
|
|
917
|
+
if mention is None:
|
|
918
|
+
return found
|
|
919
|
+
if mention.get('mention_ref') is not None:
|
|
920
|
+
found.extend(_token_findings(_join(path, 'mention_ref'), mention['mention_ref'], LOCAL_REF))
|
|
921
|
+
if mention.get('entity_kind') is not None:
|
|
922
|
+
found.extend(_enum_findings(_join(path, 'entity_kind'), mention['entity_kind'], ENTITY_KINDS))
|
|
923
|
+
if mention.get('safe_label') is not None:
|
|
924
|
+
found.extend(_text_findings(
|
|
925
|
+
_join(path, 'safe_label'), mention['safe_label'],
|
|
926
|
+
max_bytes=SAFE_LABEL_MAX_BYTES,
|
|
927
|
+
))
|
|
928
|
+
if mention.get('supporting_fact_refs') is not None:
|
|
929
|
+
found.extend(_supporting_findings(
|
|
930
|
+
_join(path, 'supporting_fact_refs'), mention['supporting_fact_refs'],
|
|
931
|
+
fact_refs,
|
|
932
|
+
))
|
|
933
|
+
return found
|
|
934
|
+
|
|
935
|
+
|
|
936
|
+
def _reference_findings(path, value, fact_refs, own_work_ref):
|
|
937
|
+
reference, found = _object(
|
|
938
|
+
path, value, REFERENCE_FIELDS,
|
|
939
|
+
('reference_ref', 'reference_kind', 'target', 'supporting_fact_refs'),
|
|
940
|
+
)
|
|
941
|
+
if reference is None:
|
|
942
|
+
return found
|
|
943
|
+
if reference.get('reference_ref') is not None:
|
|
944
|
+
found.extend(_token_findings(
|
|
945
|
+
_join(path, 'reference_ref'), reference['reference_ref'], LOCAL_REF,
|
|
946
|
+
))
|
|
947
|
+
kind = reference.get('reference_kind')
|
|
948
|
+
kind_ok = False
|
|
949
|
+
if kind is not None:
|
|
950
|
+
problems = _enum_findings(_join(path, 'reference_kind'), kind, REFERENCE_KINDS)
|
|
951
|
+
found.extend(problems)
|
|
952
|
+
kind_ok = not problems
|
|
953
|
+
if reference.get('target') is not None:
|
|
954
|
+
found.extend(_target_findings(
|
|
955
|
+
_join(path, 'target'), reference['target'],
|
|
956
|
+
TARGET_KINDS_BY_REFERENCE[kind] if kind_ok else TARGET_KINDS,
|
|
957
|
+
own_work_ref=own_work_ref,
|
|
958
|
+
))
|
|
959
|
+
if reference.get('supporting_fact_refs') is not None:
|
|
960
|
+
found.extend(_supporting_findings(
|
|
961
|
+
_join(path, 'supporting_fact_refs'), reference['supporting_fact_refs'],
|
|
962
|
+
fact_refs,
|
|
963
|
+
))
|
|
964
|
+
return found
|
|
965
|
+
|
|
966
|
+
|
|
967
|
+
def _relation_findings(path, value, fact_refs, reference_refs):
|
|
968
|
+
relation, found = _object(
|
|
969
|
+
path, value, RELATION_FIELDS,
|
|
970
|
+
('relation_kind', 'direction', 'supporting_fact_refs'),
|
|
971
|
+
)
|
|
972
|
+
if relation is None:
|
|
973
|
+
return found
|
|
974
|
+
kind = relation.get('relation_kind')
|
|
975
|
+
direction = relation.get('direction')
|
|
976
|
+
kind_ok = direction_ok = False
|
|
977
|
+
if kind is not None:
|
|
978
|
+
problems = _enum_findings(_join(path, 'relation_kind'), kind, RELATION_KINDS)
|
|
979
|
+
found.extend(problems)
|
|
980
|
+
kind_ok = not problems
|
|
981
|
+
if direction is not None:
|
|
982
|
+
problems = _enum_findings(_join(path, 'direction'), direction, RELATION_DIRECTIONS)
|
|
983
|
+
found.extend(problems)
|
|
984
|
+
direction_ok = not problems
|
|
985
|
+
target = relation.get('target_reference_ref')
|
|
986
|
+
if target is not None:
|
|
987
|
+
problems = _token_findings(_join(path, 'target_reference_ref'), target, LOCAL_REF)
|
|
988
|
+
found.extend(problems)
|
|
989
|
+
if not problems and target not in reference_refs:
|
|
990
|
+
found.append(Finding(_join(path, 'target_reference_ref'), 'unknown_reference_ref'))
|
|
991
|
+
if kind_ok and direction_ok:
|
|
992
|
+
if kind in SYMMETRIC_RELATION_KINDS and direction != 'symmetric':
|
|
993
|
+
found.append(Finding(_join(path, 'direction'), 'relation_direction_invalid'))
|
|
994
|
+
if kind == 'new_work':
|
|
995
|
+
if target is not None:
|
|
996
|
+
found.append(Finding(_join(path, 'target_reference_ref'), 'relation_target_forbidden'))
|
|
997
|
+
if direction != 'not_applicable':
|
|
998
|
+
found.append(Finding(_join(path, 'direction'), 'relation_direction_invalid'))
|
|
999
|
+
elif target is None:
|
|
1000
|
+
found.append(Finding(_join(path, 'target_reference_ref'), 'relation_target_required'))
|
|
1001
|
+
if relation.get('supporting_fact_refs') is not None:
|
|
1002
|
+
found.extend(_supporting_findings(
|
|
1003
|
+
_join(path, 'supporting_fact_refs'), relation['supporting_fact_refs'],
|
|
1004
|
+
fact_refs,
|
|
1005
|
+
))
|
|
1006
|
+
return found
|
|
1007
|
+
|
|
1008
|
+
|
|
1009
|
+
def _continuity_findings(path, value, fact_refs, own_work_ref, *, operation=None):
|
|
1010
|
+
continuity, found = _object(
|
|
1011
|
+
path, value, CONTINUITY_FIELDS, ('relationship', 'supporting_fact_refs'),
|
|
1012
|
+
)
|
|
1013
|
+
if continuity is None:
|
|
1014
|
+
return found
|
|
1015
|
+
relationship = continuity.get('relationship')
|
|
1016
|
+
if relationship is not None:
|
|
1017
|
+
problems = _enum_findings(
|
|
1018
|
+
_join(path, 'relationship'), relationship, CONTINUITY_RELATIONSHIPS,
|
|
1019
|
+
)
|
|
1020
|
+
found.extend(problems)
|
|
1021
|
+
if not problems:
|
|
1022
|
+
if relationship == 'new_work' and continuity.get('target') is not None:
|
|
1023
|
+
found.append(Finding(_join(path, 'target'), 'continuity_target_forbidden'))
|
|
1024
|
+
if relationship != 'new_work' and continuity.get('target') is None:
|
|
1025
|
+
found.append(Finding(_join(path, 'target'), 'continuity_target_required'))
|
|
1026
|
+
if continuity.get('target') is not None:
|
|
1027
|
+
found.extend(_target_findings(
|
|
1028
|
+
_join(path, 'target'), continuity['target'], CONTINUITY_TARGET_KINDS,
|
|
1029
|
+
own_work_ref=own_work_ref,
|
|
1030
|
+
allow_self=(
|
|
1031
|
+
operation == 'update'
|
|
1032
|
+
and relationship in PRIOR_WORK_RELATIONSHIPS
|
|
1033
|
+
),
|
|
1034
|
+
))
|
|
1035
|
+
if continuity.get('supporting_fact_refs') is not None:
|
|
1036
|
+
found.extend(_supporting_findings(
|
|
1037
|
+
_join(path, 'supporting_fact_refs'), continuity['supporting_fact_refs'],
|
|
1038
|
+
fact_refs,
|
|
1039
|
+
))
|
|
1040
|
+
return found
|
|
1041
|
+
|
|
1042
|
+
|
|
1043
|
+
def _deferral_findings(path, value, fact_refs, fact_kinds, own_work_ref):
|
|
1044
|
+
deferral, found = _object(
|
|
1045
|
+
path, value, DEFERRAL_FIELDS, ('reason', 'supporting_fact_refs'),
|
|
1046
|
+
)
|
|
1047
|
+
if deferral is None:
|
|
1048
|
+
return found
|
|
1049
|
+
if deferral.get('reason') is not None:
|
|
1050
|
+
found.extend(_text_findings(
|
|
1051
|
+
_join(path, 'reason'), deferral['reason'],
|
|
1052
|
+
max_bytes=DEFERRAL_TEXT_MAX_BYTES,
|
|
1053
|
+
))
|
|
1054
|
+
if deferral.get('resume_condition') is not None:
|
|
1055
|
+
found.extend(_text_findings(
|
|
1056
|
+
_join(path, 'resume_condition'), deferral['resume_condition'],
|
|
1057
|
+
max_bytes=DEFERRAL_TEXT_MAX_BYTES,
|
|
1058
|
+
))
|
|
1059
|
+
if deferral.get('resume_after') is not None:
|
|
1060
|
+
found.extend(_timestamp_findings(_join(path, 'resume_after'), deferral['resume_after']))
|
|
1061
|
+
origin = deferral.get('origin_work_ref')
|
|
1062
|
+
if origin is not None:
|
|
1063
|
+
problems = _token_findings(_join(path, 'origin_work_ref'), origin, LOCAL_REF)
|
|
1064
|
+
if not problems and origin == own_work_ref:
|
|
1065
|
+
problems.append(Finding(_join(path, 'origin_work_ref'), 'self_reference'))
|
|
1066
|
+
found.extend(problems)
|
|
1067
|
+
supporting = deferral.get('supporting_fact_refs')
|
|
1068
|
+
if supporting is not None:
|
|
1069
|
+
problems = _supporting_findings(
|
|
1070
|
+
_join(path, 'supporting_fact_refs'), supporting, fact_refs,
|
|
1071
|
+
)
|
|
1072
|
+
found.extend(problems)
|
|
1073
|
+
if not problems and not any(
|
|
1074
|
+
fact_kinds.get(ref) == 'explicit_deferral' for ref in supporting
|
|
1075
|
+
):
|
|
1076
|
+
found.append(Finding(
|
|
1077
|
+
_join(path, 'supporting_fact_refs'),
|
|
1078
|
+
'deferral_requires_deferred_fact',
|
|
1079
|
+
))
|
|
1080
|
+
return found
|
|
1081
|
+
|
|
1082
|
+
|
|
1083
|
+
def validate_update(value) -> list:
|
|
1084
|
+
"""Every structural finding for one parsed candidate, bounded."""
|
|
1085
|
+
|
|
1086
|
+
envelope, found = _object(
|
|
1087
|
+
'$', value, ENVELOPE_FIELDS,
|
|
1088
|
+
('schema', 'project_label', 'update_ref', 'stream_ref', 'sequence',
|
|
1089
|
+
'works', 'reporter_version', 'privacy_policy_version'),
|
|
1090
|
+
)
|
|
1091
|
+
if envelope is None:
|
|
1092
|
+
return found
|
|
1093
|
+
if envelope.get('schema') is not None and envelope['schema'] != SCHEMA:
|
|
1094
|
+
found.append(Finding('schema', 'not_allowed'))
|
|
1095
|
+
if envelope.get('project_label') is not None:
|
|
1096
|
+
found.extend(_text_findings(
|
|
1097
|
+
'project_label', envelope['project_label'],
|
|
1098
|
+
max_chars=PROJECT_LABEL_MAX_CHARS,
|
|
1099
|
+
))
|
|
1100
|
+
for key in ('update_ref', 'stream_ref'):
|
|
1101
|
+
if envelope.get(key) is not None:
|
|
1102
|
+
found.extend(_token_findings(key, envelope[key], RANDOM_REF))
|
|
1103
|
+
sequence = envelope.get('sequence')
|
|
1104
|
+
if sequence is not None:
|
|
1105
|
+
if isinstance(sequence, bool) or not isinstance(sequence, int):
|
|
1106
|
+
found.append(Finding('sequence', 'wrong_type'))
|
|
1107
|
+
elif not 1 <= sequence <= MAX_SEQUENCE:
|
|
1108
|
+
found.append(Finding('sequence', 'out_of_range'))
|
|
1109
|
+
for key in ('reporter_version', 'privacy_policy_version'):
|
|
1110
|
+
if envelope.get(key) is not None:
|
|
1111
|
+
found.extend(_token_findings(key, envelope[key], VERSION_TEXT))
|
|
1112
|
+
history = False
|
|
1113
|
+
if envelope.get('origin') is not None:
|
|
1114
|
+
problems = _enum_findings('origin', envelope['origin'], ORIGINS)
|
|
1115
|
+
found.extend(problems)
|
|
1116
|
+
history = not problems and envelope['origin'] == 'history_import'
|
|
1117
|
+
if envelope.get('session_complete') is not None:
|
|
1118
|
+
if not isinstance(envelope['session_complete'], bool):
|
|
1119
|
+
found.append(Finding('session_complete', 'wrong_type'))
|
|
1120
|
+
elif not history:
|
|
1121
|
+
found.append(Finding('session_complete', 'history_import_only'))
|
|
1122
|
+
if envelope.get('works') is not None:
|
|
1123
|
+
items, problems = _list('works', envelope['works'], maximum=MAX_WORKS, minimum=1)
|
|
1124
|
+
found.extend(problems)
|
|
1125
|
+
refs = set()
|
|
1126
|
+
for index, item in enumerate(items or ()):
|
|
1127
|
+
item_path = f'works[{index}]'
|
|
1128
|
+
found.extend(_work_findings(item_path, item))
|
|
1129
|
+
ref = item.get('work_ref') if isinstance(item, dict) else None
|
|
1130
|
+
if isinstance(ref, str) and LOCAL_REF.fullmatch(ref):
|
|
1131
|
+
if ref in refs:
|
|
1132
|
+
found.append(Finding(_join(item_path, 'work_ref'), 'duplicate'))
|
|
1133
|
+
refs.add(ref)
|
|
1134
|
+
facts = item.get('facts') if isinstance(item, dict) else None
|
|
1135
|
+
if history and isinstance(facts, list):
|
|
1136
|
+
found.extend(
|
|
1137
|
+
Finding(f'{item_path}.facts[{position}].occurred_at',
|
|
1138
|
+
'required_for_history_import')
|
|
1139
|
+
for position, fact in enumerate(facts)
|
|
1140
|
+
if isinstance(fact, dict) and fact.get('occurred_at') is None
|
|
1141
|
+
)
|
|
1142
|
+
if not found:
|
|
1143
|
+
try:
|
|
1144
|
+
size = len(canonical_bytes(envelope))
|
|
1145
|
+
except (TypeError, ValueError):
|
|
1146
|
+
found.append(Finding('$', 'invalid_unicode'))
|
|
1147
|
+
else:
|
|
1148
|
+
if size > MAX_UPDATE_BYTES:
|
|
1149
|
+
found.append(Finding('$', 'update_too_large'))
|
|
1150
|
+
return _bounded(found)
|
|
1151
|
+
|
|
1152
|
+
|
|
1153
|
+
def _bounded(found) -> list:
|
|
1154
|
+
unique = []
|
|
1155
|
+
for item in found:
|
|
1156
|
+
if item not in unique:
|
|
1157
|
+
unique.append(item)
|
|
1158
|
+
return unique[:MAX_FINDINGS]
|
|
1159
|
+
|
|
1160
|
+
|
|
1161
|
+
# ── Credential and private-path scan ──────────────────────────────────────
|
|
1162
|
+
|
|
1163
|
+
_PROVIDER_KEYS = tuple(re.compile(pattern) for pattern in (
|
|
1164
|
+
r'\b(?:AKIA|ASIA|AGPA|AIDA|AROA|AIPA|ANPA|ANVA|APKA)[0-9A-Z]{16}\b',
|
|
1165
|
+
r'\bgh[pousr]_[A-Za-z0-9]{36,255}\b',
|
|
1166
|
+
r'\bgithub_pat_[A-Za-z0-9_]{22,255}\b',
|
|
1167
|
+
r'\bglpat-[A-Za-z0-9_-]{20,}',
|
|
1168
|
+
r'\bsk-(?:ant-|proj-|svcacct-|admin-)?[A-Za-z0-9_-]{20,}',
|
|
1169
|
+
r'\bxox[abposre]-[A-Za-z0-9-]{10,}',
|
|
1170
|
+
r'\b(?:sk|rk|pk|whsec)_(?:live|test)_[A-Za-z0-9]{16,}',
|
|
1171
|
+
r'\bwhsec_[A-Za-z0-9]{24,}',
|
|
1172
|
+
r'\bAIza[0-9A-Za-z_-]{35}',
|
|
1173
|
+
r'\bGOCSPX-[A-Za-z0-9_-]{20,}',
|
|
1174
|
+
r'\bya29\.[A-Za-z0-9_-]{20,}',
|
|
1175
|
+
r'\bnpm_[A-Za-z0-9]{36}\b',
|
|
1176
|
+
r'\bpypi-[A-Za-z0-9_-]{50,}',
|
|
1177
|
+
r'\bhf_[A-Za-z0-9]{30,}\b',
|
|
1178
|
+
r'\bSG\.[A-Za-z0-9_-]{16,}\.[A-Za-z0-9_-]{16,}',
|
|
1179
|
+
r'\bSK[0-9a-f]{32}\b',
|
|
1180
|
+
r'\bdo[opr]_v1_[a-f0-9]{64}\b',
|
|
1181
|
+
r'\bshp(?:at|ca|pa|ss)_[a-fA-F0-9]{32}\b',
|
|
1182
|
+
r'\bkey-[0-9a-f]{32}\b',
|
|
1183
|
+
r'\bAccountKey=[A-Za-z0-9+/=]{20,}',
|
|
1184
|
+
r'\b(?:SharedAccessSignature|SharedAccessKey)=[A-Za-z0-9+/=%]{20,}',
|
|
1185
|
+
r'\b(?:sq0atp|sq0csp|EAAA)[A-Za-z0-9_-]{20,}',
|
|
1186
|
+
r'\bdckr_pat_[A-Za-z0-9_-]{20,}',
|
|
1187
|
+
r'\b(?:lin|linear)_(?:api|oauth)_[A-Za-z0-9]{20,}',
|
|
1188
|
+
r'\bsecret_[A-Za-z0-9]{40,}',
|
|
1189
|
+
r'\bntn_[A-Za-z0-9]{40,}',
|
|
1190
|
+
r'\boira_k1\.[0-9a-f-]{36}\.[A-Za-z0-9_-]{43}(?![A-Za-z0-9_-])',
|
|
1191
|
+
))
|
|
1192
|
+
_PRIVATE_KEY = re.compile(
|
|
1193
|
+
r'-----BEGIN [A-Z0-9 ]*PRIVATE KEY(?: BLOCK)?-----|PuTTY-User-Key-File-'
|
|
1194
|
+
)
|
|
1195
|
+
_AUTHORIZATION = (
|
|
1196
|
+
re.compile(
|
|
1197
|
+
r'(?i)\bauthorization\s*[:=]\s*(?:bearer|basic|token|digest)?\s*'
|
|
1198
|
+
r'[A-Za-z0-9._~+/-]{8,}=*'
|
|
1199
|
+
),
|
|
1200
|
+
re.compile(r'(?i)\bbearer\s+[A-Za-z0-9._~+/-]{16,}=*'),
|
|
1201
|
+
)
|
|
1202
|
+
_BASIC = re.compile(r'(?i)\bbasic\s+([A-Za-z0-9+/]{12,}={0,2})(?![A-Za-z0-9+/=])')
|
|
1203
|
+
_JWT = re.compile(
|
|
1204
|
+
r'\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}'
|
|
1205
|
+
)
|
|
1206
|
+
_ASSIGNMENT = re.compile(
|
|
1207
|
+
r'(?i)(?<![a-z0-9])'
|
|
1208
|
+
r'(?:pass(?:word|wd|phrase)?|pwd|secret(?:[_-]?key)?|client[_-]?secret|'
|
|
1209
|
+
r'api[_-]?key|apikey|access[_-]?(?:key|token)|refresh[_-]?token|'
|
|
1210
|
+
r'auth[_-]?token|id[_-]?token|session[_-]?(?:key|token|secret)|'
|
|
1211
|
+
r'private[_-]?key|bearer[_-]?token|x-api-key|token|cookie|'
|
|
1212
|
+
r'credentials?)'
|
|
1213
|
+
r'["\']?\s*(?:=|:|=>|->)\s*(?P<quote>["\']?)'
|
|
1214
|
+
r'(?P<value>[^\s"\'`,;)\]}]{4,})'
|
|
1215
|
+
)
|
|
1216
|
+
_PLACEHOLDER = re.compile(
|
|
1217
|
+
r'(?i)^(?:<[^>]*>|\$\{?[a-z_][a-z0-9_]*\}?|\{\{.*\}\}|x{3,}|\*{3,}|'
|
|
1218
|
+
r'\.{3,}|redacted|\[redacted\]|none|null|nil|true|false|undefined|'
|
|
1219
|
+
r'required|optional|string|str|bytes|text|secret|password|token|'
|
|
1220
|
+
r'example|placeholder|changeme|your[_-].*|my[_-].*|'
|
|
1221
|
+
r'[a-z_][a-z0-9_.]*\(.*|(?:os|process|settings|config|env|self|'
|
|
1222
|
+
r'request|ctx)\..*)$'
|
|
1223
|
+
)
|
|
1224
|
+
_URL = re.compile(r'(?i)\b[a-z][a-z0-9+.-]{1,15}://[^\s<>"\'`]+')
|
|
1225
|
+
_BARE_CREDENTIALS = re.compile(
|
|
1226
|
+
r'(?<![\w/@.:-])[A-Za-z0-9._%+-]{1,64}:[^\s@/:]{6,}@'
|
|
1227
|
+
r'[A-Za-z0-9-]+(?:\.[A-Za-z0-9-]+)+'
|
|
1228
|
+
)
|
|
1229
|
+
_SENSITIVE_PARAMETER = re.compile(
|
|
1230
|
+
r'(?i)^(?:access_?token|id_?token|refresh_?token|token|auth_?token|'
|
|
1231
|
+
r'api_?key|apikey|key|secret|client_?secret|password|passwd|pwd|sig|'
|
|
1232
|
+
r'signature|x-amz-signature|x-amz-credential|x-amz-security-token|'
|
|
1233
|
+
r'x-goog-signature|x-goog-credential|auth|authorization|code|session|'
|
|
1234
|
+
r'session_?id|sessionid|sid|jwt|bearer|private_?token|ticket)$'
|
|
1235
|
+
)
|
|
1236
|
+
_WEBHOOK_HOSTS = (
|
|
1237
|
+
('hooks.slack.com', '/services/'),
|
|
1238
|
+
('discord.com', '/api/webhooks/'),
|
|
1239
|
+
('discordapp.com', '/api/webhooks/'),
|
|
1240
|
+
('outlook.office.com', '/webhook'),
|
|
1241
|
+
)
|
|
1242
|
+
_OPAQUE = re.compile(r'[A-Za-z0-9+/=_-]{32,}')
|
|
1243
|
+
# These specific link coordinates join several ordinary IDs with the same slash
|
|
1244
|
+
# characters used by base64. Scan their segments individually for opaque blobs.
|
|
1245
|
+
# Everything after the coordinate (including slugs and query values) stays intact.
|
|
1246
|
+
_WORK_LINK_COORDINATE = re.compile(
|
|
1247
|
+
r'\bhttps://(?:'
|
|
1248
|
+
r'(?:[a-z0-9-]+\.)+slack\.com/archives/[CDG][A-Z0-9]{1,32}/p[0-9]{16}'
|
|
1249
|
+
r'|app\.slack\.com/client/T[A-Z0-9]{1,32}/[CDG][A-Z0-9]{1,32}'
|
|
1250
|
+
r'(?:/(?:thread/[CDG][A-Z0-9]{1,32}-[0-9]{10}\.[0-9]{6}|p[0-9]{16}))?'
|
|
1251
|
+
r'|linear\.app/[a-zA-Z0-9_-]+/issue/[a-zA-Z][a-zA-Z0-9_]*-[0-9]+'
|
|
1252
|
+
r')(?=/|[?#.,;:)|>\]\s]|$)'
|
|
1253
|
+
)
|
|
1254
|
+
_LOCAL_PATH = (
|
|
1255
|
+
re.compile(
|
|
1256
|
+
r'(?<![A-Za-z0-9_.-])/(?:Users|home|root)/[^\s"\'`/]+'
|
|
1257
|
+
r'|(?<![A-Za-z0-9_.-])/(?:private/var|var/folders|private/tmp)/'
|
|
1258
|
+
# Windows homes mounted inside WSL.
|
|
1259
|
+
r'|(?<![A-Za-z0-9_.-])/mnt/[a-z]/(?:Users|home)/[^\s"\'`/]+'
|
|
1260
|
+
),
|
|
1261
|
+
re.compile(r'(?i)(?<![A-Za-z0-9])[a-z]:\\(?:users|documents and settings)\\'),
|
|
1262
|
+
# WSL distributions reached from Windows (\\wsl$\ and \\wsl.<host>\),
|
|
1263
|
+
# and other UNC shares that expose a user's home folders.
|
|
1264
|
+
re.compile(r'(?i)\\\\wsl(?:\$|\.[a-z]+)\\'),
|
|
1265
|
+
re.compile(r'(?i)\\\\[a-z0-9._-]+\\(?:users|home)\\'),
|
|
1266
|
+
# The coding apps' own home folders: Claude Code, Codex, Kiro, GitHub
|
|
1267
|
+
# Copilot and Cursor.
|
|
1268
|
+
re.compile(
|
|
1269
|
+
r'(?i)(?:~|%userprofile%|\$home|\$env:userprofile)'
|
|
1270
|
+
r'[/\\]\.(?:claude|codex|kiro|copilot|cursor)(?:[/\\]|\b)'
|
|
1271
|
+
),
|
|
1272
|
+
re.compile(r'(?i)(?:\$(?:env:)?copilot_home|%copilot_home%)[/\\]'),
|
|
1273
|
+
)
|
|
1274
|
+
|
|
1275
|
+
|
|
1276
|
+
def _assignment_is_secret(match) -> bool:
|
|
1277
|
+
value = match.group('value').rstrip('.')
|
|
1278
|
+
if _PLACEHOLDER.match(value):
|
|
1279
|
+
return False
|
|
1280
|
+
if match.group('quote'):
|
|
1281
|
+
return len(value) >= 6
|
|
1282
|
+
has_digit = any(char.isdigit() for char in value)
|
|
1283
|
+
mixed_case = (
|
|
1284
|
+
any(char.isupper() for char in value)
|
|
1285
|
+
and any(char.islower() for char in value)
|
|
1286
|
+
)
|
|
1287
|
+
symbol = any(char in '_-+/=.~!@#$%^&*' for char in value)
|
|
1288
|
+
return (len(value) >= 6 and has_digit) or (
|
|
1289
|
+
len(value) >= 8 and (mixed_case or symbol)
|
|
1290
|
+
)
|
|
1291
|
+
|
|
1292
|
+
|
|
1293
|
+
def _url_findings(url: str) -> set:
|
|
1294
|
+
codes = set()
|
|
1295
|
+
trimmed = url.rstrip('.,;:)]}')
|
|
1296
|
+
try:
|
|
1297
|
+
parts = urlsplit(trimmed)
|
|
1298
|
+
host = (parts.hostname or '').lower()
|
|
1299
|
+
except ValueError:
|
|
1300
|
+
return codes
|
|
1301
|
+
if '@' in parts.netloc:
|
|
1302
|
+
userinfo = parts.netloc.rsplit('@', 1)[0]
|
|
1303
|
+
user, _separator, password = userinfo.partition(':')
|
|
1304
|
+
if password or parts.scheme.lower() in ('http', 'https') or (
|
|
1305
|
+
user and user.lower() not in ('git', 'ssh', 'hg', 'svn')
|
|
1306
|
+
):
|
|
1307
|
+
codes.add('secret.credential_url')
|
|
1308
|
+
for part in (parts.query, parts.fragment):
|
|
1309
|
+
if '=' not in part:
|
|
1310
|
+
continue
|
|
1311
|
+
for key, item in parse_qsl(part, keep_blank_values=True):
|
|
1312
|
+
if item and _SENSITIVE_PARAMETER.match(key.strip()):
|
|
1313
|
+
codes.add('secret.sensitive_url_parameter')
|
|
1314
|
+
path = parts.path or ''
|
|
1315
|
+
for webhook_host, prefix in _WEBHOOK_HOSTS:
|
|
1316
|
+
if (host == webhook_host or host.endswith('.' + webhook_host)) and (
|
|
1317
|
+
path.startswith(prefix)
|
|
1318
|
+
):
|
|
1319
|
+
codes.add('secret.webhook_url')
|
|
1320
|
+
if host.endswith('.webhook.office.com'):
|
|
1321
|
+
codes.add('secret.webhook_url')
|
|
1322
|
+
return codes
|
|
1323
|
+
|
|
1324
|
+
|
|
1325
|
+
def _opaque(run: str) -> bool:
|
|
1326
|
+
if all(char in '0123456789abcdef' for char in run.lower()) and (
|
|
1327
|
+
run == run.lower() or run == run.upper()
|
|
1328
|
+
):
|
|
1329
|
+
return False
|
|
1330
|
+
upper = any(char.isupper() for char in run)
|
|
1331
|
+
lower = any(char.islower() for char in run)
|
|
1332
|
+
digit = any(char.isdigit() for char in run)
|
|
1333
|
+
return (upper and lower and digit) or len(run) >= 120
|
|
1334
|
+
|
|
1335
|
+
|
|
1336
|
+
def scan_text(value: str) -> set:
|
|
1337
|
+
"""Reason codes for one string; never the matched text."""
|
|
1338
|
+
|
|
1339
|
+
text = unicodedata.normalize('NFKC', value)
|
|
1340
|
+
codes = set()
|
|
1341
|
+
if _PRIVATE_KEY.search(text):
|
|
1342
|
+
codes.add('secret.private_key')
|
|
1343
|
+
if any(pattern.search(text) for pattern in _PROVIDER_KEYS):
|
|
1344
|
+
codes.add('secret.provider_key')
|
|
1345
|
+
if any(pattern.search(text) for pattern in _AUTHORIZATION):
|
|
1346
|
+
codes.add('secret.authorization')
|
|
1347
|
+
for match in _BASIC.finditer(text):
|
|
1348
|
+
token = match.group(1)
|
|
1349
|
+
if any(char.isdigit() for char in token) or token.endswith('=') or (
|
|
1350
|
+
'+' in token or '/' in token
|
|
1351
|
+
):
|
|
1352
|
+
codes.add('secret.authorization')
|
|
1353
|
+
if _JWT.search(text):
|
|
1354
|
+
codes.add('secret.jwt')
|
|
1355
|
+
if any(_assignment_is_secret(match) for match in _ASSIGNMENT.finditer(text)):
|
|
1356
|
+
codes.add('secret.sensitive_assignment')
|
|
1357
|
+
for match in _URL.finditer(text):
|
|
1358
|
+
codes |= _url_findings(match.group(0))
|
|
1359
|
+
if _BARE_CREDENTIALS.search(text):
|
|
1360
|
+
codes.add('secret.credential_url')
|
|
1361
|
+
opaque_text = _WORK_LINK_COORDINATE.sub(lambda m: m.group(0).replace('/', ' '), text)
|
|
1362
|
+
if any(_opaque(match.group(0)) for match in _OPAQUE.finditer(opaque_text)):
|
|
1363
|
+
codes.add('secret.opaque_blob')
|
|
1364
|
+
if any(pattern.search(text) for pattern in _LOCAL_PATH):
|
|
1365
|
+
codes.add('privacy.local_path')
|
|
1366
|
+
return codes
|
|
1367
|
+
|
|
1368
|
+
|
|
1369
|
+
def _walk_strings(value, path='$'):
|
|
1370
|
+
if isinstance(value, dict):
|
|
1371
|
+
for key in sorted(value, key=str):
|
|
1372
|
+
name = key if key in PATH_NAMES else UNKNOWN_KEY
|
|
1373
|
+
yield from _walk_strings(value[key], _join(path, name))
|
|
1374
|
+
elif isinstance(value, list):
|
|
1375
|
+
for index, item in enumerate(value):
|
|
1376
|
+
yield from _walk_strings(item, f'{path}[{index}]')
|
|
1377
|
+
elif isinstance(value, str):
|
|
1378
|
+
yield path, value
|
|
1379
|
+
|
|
1380
|
+
|
|
1381
|
+
def scan_update(value) -> list:
|
|
1382
|
+
"""Credential and private-path findings for every string field."""
|
|
1383
|
+
|
|
1384
|
+
found = []
|
|
1385
|
+
for path, text in _walk_strings(value):
|
|
1386
|
+
try:
|
|
1387
|
+
codes = scan_text(text)
|
|
1388
|
+
except (ValueError, TypeError):
|
|
1389
|
+
codes = {'invalid_unicode'}
|
|
1390
|
+
found.extend(Finding(path, code) for code in sorted(codes))
|
|
1391
|
+
return _bounded(found)
|
|
1392
|
+
|
|
1393
|
+
|
|
1394
|
+
# ── One entry point for the skill and for Oira ────────────────────────────
|
|
1395
|
+
|
|
1396
|
+
|
|
1397
|
+
def prepare(raw) -> dict:
|
|
1398
|
+
"""Return ``{'ok': True, 'canonical': ...}`` or bounded refusals."""
|
|
1399
|
+
|
|
1400
|
+
try:
|
|
1401
|
+
candidate = load_candidate(raw)
|
|
1402
|
+
except CandidateRefused as exc:
|
|
1403
|
+
return {'ok': False, 'errors': [item.wire() for item in exc.findings]}
|
|
1404
|
+
found = _bounded([*validate_update(candidate), *scan_update(candidate)])
|
|
1405
|
+
if found:
|
|
1406
|
+
return {'ok': False, 'errors': [item.wire() for item in found]}
|
|
1407
|
+
return {'ok': True, 'canonical': canonical_json(candidate)}
|
|
1408
|
+
|
|
1409
|
+
|
|
1410
|
+
def history_stream_ref(session_id: str) -> str:
|
|
1411
|
+
"""The stream reference of one past session (see the module docstring)."""
|
|
1412
|
+
|
|
1413
|
+
digest = hashlib.sha256(
|
|
1414
|
+
b'oira_history_stream.v1\x00' + session_id.encode('utf-8'),
|
|
1415
|
+
).digest()
|
|
1416
|
+
return str(uuid.UUID(bytes=digest[:16], version=4))
|
|
1417
|
+
|
|
1418
|
+
|
|
1419
|
+
def _session_id(value: str) -> bool:
|
|
1420
|
+
return 0 < len(value) <= 255 and value.isprintable() and value == value.strip()
|
|
1421
|
+
|
|
1422
|
+
|
|
1423
|
+
def _emit(text: str) -> None:
|
|
1424
|
+
"""Write one line of UTF-8 to standard output, whatever the console is.
|
|
1425
|
+
|
|
1426
|
+
The canonical update keeps non-ASCII text as it is. On Windows a
|
|
1427
|
+
redirected standard output uses the ANSI code page unless the caller
|
|
1428
|
+
set UTF-8 mode, which would re-encode accented text and fail on text
|
|
1429
|
+
the code page cannot represent; writing the bytes directly makes the
|
|
1430
|
+
output the same on every host and shell.
|
|
1431
|
+
"""
|
|
1432
|
+
|
|
1433
|
+
data = (text + '\n').encode('utf-8')
|
|
1434
|
+
stream = getattr(sys.stdout, 'buffer', None)
|
|
1435
|
+
if stream is None:
|
|
1436
|
+
sys.stdout.write(data.decode('utf-8'))
|
|
1437
|
+
sys.stdout.flush()
|
|
1438
|
+
return
|
|
1439
|
+
stream.write(data)
|
|
1440
|
+
stream.flush()
|
|
1441
|
+
|
|
1442
|
+
|
|
1443
|
+
def _write(payload: dict) -> None:
|
|
1444
|
+
_emit(json.dumps(payload, separators=(',', ':')))
|
|
1445
|
+
|
|
1446
|
+
|
|
1447
|
+
def main(argv=None) -> int:
|
|
1448
|
+
arguments = list(sys.argv[1:] if argv is None else argv)
|
|
1449
|
+
try:
|
|
1450
|
+
if sys.version_info < MINIMUM_PYTHON:
|
|
1451
|
+
_write({'ok': False, 'errors': [
|
|
1452
|
+
{'path': '$', 'code': 'python_version_unsupported'},
|
|
1453
|
+
]})
|
|
1454
|
+
return 3
|
|
1455
|
+
if arguments == ['--new-ref']:
|
|
1456
|
+
_emit(str(uuid.uuid4()))
|
|
1457
|
+
return 0
|
|
1458
|
+
if (
|
|
1459
|
+
len(arguments) == 2 and arguments[0] == '--history-stream'
|
|
1460
|
+
and _session_id(arguments[1])
|
|
1461
|
+
):
|
|
1462
|
+
_emit(history_stream_ref(arguments[1]))
|
|
1463
|
+
return 0
|
|
1464
|
+
if arguments:
|
|
1465
|
+
_write({'ok': False, 'errors': [{'path': '$', 'code': 'not_allowed'}]})
|
|
1466
|
+
return 2
|
|
1467
|
+
raw = sys.stdin.buffer.read(MAX_RAW_INPUT_BYTES + 1)
|
|
1468
|
+
result = prepare(raw)
|
|
1469
|
+
if result['ok']:
|
|
1470
|
+
_emit(result['canonical'])
|
|
1471
|
+
return 0
|
|
1472
|
+
_write(result)
|
|
1473
|
+
return 2
|
|
1474
|
+
except Exception: # noqa: BLE001 - fail closed without echoing input
|
|
1475
|
+
_write({'ok': False, 'errors': [
|
|
1476
|
+
{'path': '$', 'code': 'preflight_internal_error'},
|
|
1477
|
+
]})
|
|
1478
|
+
return 3
|
|
1479
|
+
|
|
1480
|
+
|
|
1481
|
+
if __name__ == '__main__':
|
|
1482
|
+
raise SystemExit(main())
|