csync-local 0.1.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.
- csync_local-0.1.0.dist-info/METADATA +251 -0
- csync_local-0.1.0.dist-info/RECORD +98 -0
- csync_local-0.1.0.dist-info/WHEEL +5 -0
- csync_local-0.1.0.dist-info/entry_points.txt +2 -0
- csync_local-0.1.0.dist-info/licenses/LICENSE +21 -0
- csync_local-0.1.0.dist-info/top_level.txt +1 -0
- localcsync/__init__.py +3 -0
- localcsync/__main__.py +6 -0
- localcsync/_vendor/VENDORED_FROM +1 -0
- localcsync/_vendor/__init__.py +1 -0
- localcsync/_vendor/csync/backend/app/__init__.py +2 -0
- localcsync/_vendor/csync/backend/app/log_redaction.py +66 -0
- localcsync/_vendor/csync/backend/app/runtime_assets/__init__.py +1 -0
- localcsync/_vendor/csync/backend/app/runtime_assets/contract.py +168 -0
- localcsync/_vendor/csync/backend/app/sentry.py +415 -0
- localcsync/_vendor/csync/backend/app/validation/__init__.py +0 -0
- localcsync/_vendor/csync/backend/app/validation/codebuild_entry.py +96 -0
- localcsync/_vendor/csync/backend/app/validation/codebuild_run.py +291 -0
- localcsync/_vendor/csync/backend/app/validation/config_yaml_check/__init__.py +14 -0
- localcsync/_vendor/csync/backend/app/validation/config_yaml_check/checker.py +170 -0
- localcsync/_vendor/csync/backend/app/validation/config_yaml_check/gather.py +72 -0
- localcsync/_vendor/csync/backend/app/validation/config_yaml_check/prompt.py +121 -0
- localcsync/_vendor/csync/backend/app/validation/config_yaml_check/rules.py +823 -0
- localcsync/_vendor/csync/backend/app/validation/datetime_utc/__init__.py +0 -0
- localcsync/_vendor/csync/backend/app/validation/datetime_utc/checker.py +145 -0
- localcsync/_vendor/csync/backend/app/validation/datetime_utc/gather.py +541 -0
- localcsync/_vendor/csync/backend/app/validation/docker_manager.py +726 -0
- localcsync/_vendor/csync/backend/app/validation/engine.py +2787 -0
- localcsync/_vendor/csync/backend/app/validation/env_validator/__init__.py +0 -0
- localcsync/_vendor/csync/backend/app/validation/env_validator/batch_validators.py +238 -0
- localcsync/_vendor/csync/backend/app/validation/env_validator/models.py +64 -0
- localcsync/_vendor/csync/backend/app/validation/env_validator/utils/__init__.py +0 -0
- localcsync/_vendor/csync/backend/app/validation/env_validator/utils/async_http.py +233 -0
- localcsync/_vendor/csync/backend/app/validation/env_validator/utils/docker_utils.py +334 -0
- localcsync/_vendor/csync/backend/app/validation/env_validator/utils/http_utils.py +338 -0
- localcsync/_vendor/csync/backend/app/validation/env_validator/utils/port_utils.py +113 -0
- localcsync/_vendor/csync/backend/app/validation/env_validator/validators.py +661 -0
- localcsync/_vendor/csync/backend/app/validation/eval_awareness/__init__.py +0 -0
- localcsync/_vendor/csync/backend/app/validation/eval_awareness/checker.py +565 -0
- localcsync/_vendor/csync/backend/app/validation/external_network.py +1691 -0
- localcsync/_vendor/csync/backend/app/validation/feature_coverage/__init__.py +0 -0
- localcsync/_vendor/csync/backend/app/validation/feature_coverage/checker.py +97 -0
- localcsync/_vendor/csync/backend/app/validation/feature_coverage/gather.py +385 -0
- localcsync/_vendor/csync/backend/app/validation/file_scope.py +293 -0
- localcsync/_vendor/csync/backend/app/validation/fingerprint.py +265 -0
- localcsync/_vendor/csync/backend/app/validation/github_reporter.py +493 -0
- localcsync/_vendor/csync/backend/app/validation/keyboard_shortcuts/__init__.py +0 -0
- localcsync/_vendor/csync/backend/app/validation/keyboard_shortcuts/checker.py +275 -0
- localcsync/_vendor/csync/backend/app/validation/keyboard_shortcuts/fetch.py +491 -0
- localcsync/_vendor/csync/backend/app/validation/keyboard_shortcuts/keys.py +106 -0
- localcsync/_vendor/csync/backend/app/validation/keyboard_shortcuts/manifest.py +164 -0
- localcsync/_vendor/csync/backend/app/validation/keyboard_shortcuts/models.py +50 -0
- localcsync/_vendor/csync/backend/app/validation/keyboard_shortcuts/reference.py +115 -0
- localcsync/_vendor/csync/backend/app/validation/keyboard_shortcuts/scanner.py +169 -0
- localcsync/_vendor/csync/backend/app/validation/keyboard_shortcuts/search_provider.py +200 -0
- localcsync/_vendor/csync/backend/app/validation/live_log.py +135 -0
- localcsync/_vendor/csync/backend/app/validation/mcp_parity/__init__.py +9 -0
- localcsync/_vendor/csync/backend/app/validation/mcp_parity/detect.py +164 -0
- localcsync/_vendor/csync/backend/app/validation/mcp_parity/prompt.py +161 -0
- localcsync/_vendor/csync/backend/app/validation/mcp_parity/runner.py +115 -0
- localcsync/_vendor/csync/backend/app/validation/multi_rl/__init__.py +35 -0
- localcsync/_vendor/csync/backend/app/validation/multi_rl/app_contract.py +378 -0
- localcsync/_vendor/csync/backend/app/validation/multi_rl/ci_image.py +542 -0
- localcsync/_vendor/csync/backend/app/validation/multi_rl/em_dash.py +225 -0
- localcsync/_vendor/csync/backend/app/validation/multi_rl/findings.py +157 -0
- localcsync/_vendor/csync/backend/app/validation/multi_rl/image_checks.py +876 -0
- localcsync/_vendor/csync/backend/app/validation/multi_rl/pins.py +357 -0
- localcsync/_vendor/csync/backend/app/validation/multi_rl/profile_config.py +328 -0
- localcsync/_vendor/csync/backend/app/validation/multi_rl/runner.py +356 -0
- localcsync/_vendor/csync/backend/app/validation/multi_rl/secrets.py +241 -0
- localcsync/_vendor/csync/backend/app/validation/multi_rl/seed_cache.py +112 -0
- localcsync/_vendor/csync/backend/app/validation/multi_rl/suite_rules.py +424 -0
- localcsync/_vendor/csync/backend/app/validation/naming_audit/__init__.py +6 -0
- localcsync/_vendor/csync/backend/app/validation/naming_audit/candidates.py +159 -0
- localcsync/_vendor/csync/backend/app/validation/naming_audit/detectors.py +166 -0
- localcsync/_vendor/csync/backend/app/validation/naming_audit/prompt.py +181 -0
- localcsync/_vendor/csync/backend/app/validation/naming_audit/providers.py +137 -0
- localcsync/_vendor/csync/backend/app/validation/naming_audit/runner.py +206 -0
- localcsync/_vendor/csync/backend/app/validation/recovery.py +680 -0
- localcsync/_vendor/csync/backend/app/validation/registry.py +615 -0
- localcsync/_vendor/csync/backend/app/validation/restricted_terms/__init__.py +0 -0
- localcsync/_vendor/csync/backend/app/validation/restricted_terms/checker.py +321 -0
- localcsync/_vendor/csync/backend/app/validation/runtime_assets.py +121 -0
- localcsync/_vendor/csync/backend/app/validation/seed_paths.py +7 -0
- localcsync/_vendor/csync/backend/app/validation/single_rl_checks.py +326 -0
- localcsync/_vendor/csync/backend/app/validation/worker.py +210 -0
- localcsync/_vendor/csync/backend/tools/feature-mapping/action-facts.mjs +142 -0
- localcsync/_vendor/csync/backend/tools/feature-mapping/census.mjs +53 -0
- localcsync/_vendor/csync/backend/tools/feature-mapping/chain-facts.mjs +286 -0
- localcsync/_vendor/csync/backend/tools/feature-mapping/extract.mjs +806 -0
- localcsync/_vendor/csync/backend/tools/feature-mapping/keyboard-chords.mjs +211 -0
- localcsync/_vendor/csync/backend/tools/feature-mapping/package-lock.json +132 -0
- localcsync/_vendor/csync/backend/tools/feature-mapping/package.json +13 -0
- localcsync/cli.py +749 -0
- localcsync/docker_mode.py +351 -0
- localcsync/llm.py +138 -0
- localcsync/runtime.py +68 -0
- localcsync/verdicts.py +115 -0
|
@@ -0,0 +1,321 @@
|
|
|
1
|
+
"""restricted_terms: names that must not appear anywhere in an RL repository.
|
|
2
|
+
|
|
3
|
+
An RL environment ships to whoever runs it. A vendor or a client named in it -- in a
|
|
4
|
+
comment, a README, a seed row, a package name, a file name -- tells that reader who it was
|
|
5
|
+
built for or with. So every text file at the commit is read, every line that names one of
|
|
6
|
+
the terms is a finding, and any finding fails the run with its file and line.
|
|
7
|
+
|
|
8
|
+
The terms are the runtime setting ``validation.restricted_terms`` (Admin → Runtime
|
|
9
|
+
Settings), so a new client is added without a deploy.
|
|
10
|
+
|
|
11
|
+
How a term matches:
|
|
12
|
+
|
|
13
|
+
* as a word, not inside one: ``openai`` matches ``openai``, ``OPENAI_API_KEY``,
|
|
14
|
+
``openai:voyager`` and ``useOpenAI``, but ``xai`` does not match ``maxAI`` and
|
|
15
|
+
``meta`` does not match ``metadata``. A camelCase hump -- a lowercase letter, then a
|
|
16
|
+
capital -- counts as a word boundary, since that is how a name is spelled inside an
|
|
17
|
+
identifier; a digit then a capital does not, so the ASIN ``B001F71XAI`` is not xAI.
|
|
18
|
+
* without case by default. A term marked case-sensitive is a proper noun and matches
|
|
19
|
+
only as written and as a word of its own: the company ``Meta`` is a finding; the
|
|
20
|
+
``<meta>`` tag, a ``meta`` field and ``MetaData`` or ``PaginationMeta`` are not.
|
|
21
|
+
* not inside encoded data. A term inside a long run of base64 or hex (a token, a
|
|
22
|
+
signature, an image) is chance, not a name: ``…UnrxAItXaF…`` in a grader's changelog.
|
|
23
|
+
A long identifier or a path is not encoded data: ``MY_OPENAI_API_KEY_FOR_PRODUCTION``,
|
|
24
|
+
``useOpenAIClientForProductionEnvironment`` and ``src/components/v2/providers/openai``
|
|
25
|
+
are findings, however long.
|
|
26
|
+
* not where the code uses the vendor's library, which is real use, not naming it: an
|
|
27
|
+
import (``import openai``, ``from langchain_openai import ChatOpenAI``,
|
|
28
|
+
``import OpenAI from "openai"``, ``require("openai")``) and a dependency declared in a
|
|
29
|
+
manifest (``"openai": "^4.2"`` in package.json, ``langchain-openai>=0.2`` in
|
|
30
|
+
pyproject.toml or requirements.txt). The rest of that line, and the manifest's other
|
|
31
|
+
fields (its name, its description), are still read.
|
|
32
|
+
* not in an allowed identifier. The setting's ``allow`` names whole identifiers, matched
|
|
33
|
+
exactly, that are not findings: an SDK reads ``OPENAI_API_KEY`` under that name and no
|
|
34
|
+
other, and its classes are called ``ChatOpenAI`` and ``AsyncOpenAI``. ``OPENAI_ORG_ID``
|
|
35
|
+
beside them, or ``openai`` in a comment, still is.
|
|
36
|
+
|
|
37
|
+
Not read: what the runtime setting ``validation.ignore`` skips for this check
|
|
38
|
+
(app.validation.file_scope: dependency and build directories, lockfiles, vendored libraries,
|
|
39
|
+
minified bundles, by default), binary files, and text files over MAX_FILE_BYTES -- the last said, so a pass never claims more than
|
|
40
|
+
was read. A folder whose name is a term is one finding, not one per file inside it.
|
|
41
|
+
|
|
42
|
+
A finding shows the line around the match with credentials masked (app.sentry.redact): the
|
|
43
|
+
lines this check finds are exactly the ones likely to hold an OPENAI_API_KEY=sk-... value,
|
|
44
|
+
and the message is stored on the run, shown on the page and written to the worker log.
|
|
45
|
+
|
|
46
|
+
Until the setting's ``blocking`` is on, findings are a warning, not a failure: the list
|
|
47
|
+
shows what a rollout would fail before it fails anyone.
|
|
48
|
+
"""
|
|
49
|
+
from __future__ import annotations
|
|
50
|
+
|
|
51
|
+
import re
|
|
52
|
+
from dataclasses import dataclass, field
|
|
53
|
+
from pathlib import Path
|
|
54
|
+
from typing import AbstractSet, Iterable, List, Optional, Sequence, Set, Tuple
|
|
55
|
+
|
|
56
|
+
from ...sentry import redact
|
|
57
|
+
from ..file_scope import Scope, scope as file_scope
|
|
58
|
+
#: A run of base64 / hex / token characters this long may be encoded data... An = only
|
|
59
|
+
#: ends one (base64 padding), so NAME=value is two runs and a key cannot hide the name.
|
|
60
|
+
ENCODED_RUN = re.compile(r"[A-Za-z0-9+/_-]{40,}=*")
|
|
61
|
+
#: ...when one piece of it, between / _ or - separators, is this long and holds a digit.
|
|
62
|
+
#: An identifier's words and a path's folders are short (OPENAI, API, providers, v2) or
|
|
63
|
+
#: carry no digit (useOpenAIClientForProduction); random characters run long and nearly
|
|
64
|
+
#: always do, and a term elsewhere in such a run is chance too (…Lr0aZ/xai_Mq…).
|
|
65
|
+
ENCODED_PIECE = 20
|
|
66
|
+
ENCODED_SEPARATORS = re.compile(r"[/_-]")
|
|
67
|
+
#: Where the code uses a library, not names it: the statement, masked before matching.
|
|
68
|
+
#: Python: the import, up to a comment. JS/TS: the module of an import or a require.
|
|
69
|
+
IMPORT_SPANS = re.compile(
|
|
70
|
+
r"^\s*(?:from\s+[\w.]+\s+)?import\s+(?:(?!//)[^#\n])*"
|
|
71
|
+
r"|\bfrom\s*(['\"])[^'\"\s]+\1" # a module name has no spaces: not prose
|
|
72
|
+
r"|(?:^\s*(?:const|let|var)\s+[\w{}\s,:$]+=\s*(?:await\s+)?)?" # the binding it makes too
|
|
73
|
+
r"\b(?:require|import)\s*\(\s*(['\"])[^'\"\s]+\2\s*\)"
|
|
74
|
+
)
|
|
75
|
+
#: Files that declare dependencies, and the shapes of one dependency on a line of them;
|
|
76
|
+
#: only the package's name is masked, so ``"description": "Built on OpenAI"`` is still read.
|
|
77
|
+
MANIFEST_RE = re.compile(r"^(package\.json|pyproject\.toml|Pipfile|setup\.cfg|Cargo\.toml"
|
|
78
|
+
r"|(requirements|constraints)[\w.-]*\.txt)$")
|
|
79
|
+
DEPENDENCY_RES = (
|
|
80
|
+
re.compile(r'^\s*"(?P<name>@?[\w.-]+(?:/[\w.-]+)?)"\s*:\s*"[~^<>=*\d]'), # "openai": "^4.2"
|
|
81
|
+
re.compile(r"^\s*(?P<name>[\w.-]+)\s*=\s*(?:[\"'][~^<>=*\d]|\{)"), # openai = "^1.0"
|
|
82
|
+
re.compile(r"^\s*[\"']?(?P<name>[\w.-]+)(?:\[[\w,\s]*\])?\s*(?:[<>=!~]=?|;|[\"'],?\s*$|$)"), # PEP 508
|
|
83
|
+
)
|
|
84
|
+
#: Seed data and grader changelogs run to tens of MB and are exactly where a name hides.
|
|
85
|
+
MAX_FILE_BYTES = 100 * 1024 * 1024
|
|
86
|
+
#: Findings kept and written into the check's message; the headline counts all of them.
|
|
87
|
+
MAX_LISTED = 100
|
|
88
|
+
SNIPPET_CHARS = 160
|
|
89
|
+
#: How much of a file is held at once while looking for a term's letters.
|
|
90
|
+
CHUNK_BYTES = 1024 * 1024
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
@dataclass(frozen=True)
|
|
94
|
+
class Term:
|
|
95
|
+
text: str
|
|
96
|
+
case_sensitive: bool = False
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
@dataclass
|
|
100
|
+
class Finding:
|
|
101
|
+
file: str
|
|
102
|
+
line: int # 0: the file's own path names the term
|
|
103
|
+
term: str
|
|
104
|
+
text: str = ""
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
@dataclass
|
|
108
|
+
class Outcome:
|
|
109
|
+
findings: List[Finding] = field(default_factory=list) # the first MAX_LISTED
|
|
110
|
+
found: int = 0 # every finding
|
|
111
|
+
files_named: Set[str] = field(default_factory=set)
|
|
112
|
+
files_read: int = 0
|
|
113
|
+
skipped_large: List[str] = field(default_factory=list)
|
|
114
|
+
terms: Tuple[str, ...] = ()
|
|
115
|
+
error: Optional[str] = None
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def _pattern(term: Term) -> re.Pattern:
|
|
119
|
+
word = re.escape(term.text.strip())
|
|
120
|
+
if term.case_sensitive:
|
|
121
|
+
# A proper noun: a word of its own, so MetaData and PaginationMeta are not Meta.
|
|
122
|
+
return re.compile(rf"(?<![A-Za-z0-9]){word}(?![A-Za-z0-9])")
|
|
123
|
+
# Before: no letter or digit, or a camelCase hump into a capital (useOpenAI).
|
|
124
|
+
# After: no lowercase letter or digit, so OPENAI_KEY and openaiClient match but
|
|
125
|
+
# metadata does not. The boundaries themselves are always case-sensitive.
|
|
126
|
+
return re.compile(rf"(?:(?<![A-Za-z0-9])|(?<=[a-z])(?=[A-Z]))(?i:{word})(?![a-z0-9])")
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def compile_terms(terms: Iterable[Term]) -> List[Tuple[Term, re.Pattern]]:
|
|
130
|
+
return [(t, _pattern(t)) for t in terms if t.text.strip()]
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
def _encoded(text: str, start: int, end: int) -> bool:
|
|
134
|
+
for run in ENCODED_RUN.finditer(text):
|
|
135
|
+
if run.start() <= start and end <= run.end():
|
|
136
|
+
return any(len(piece) >= ENCODED_PIECE and any(ch.isdigit() for ch in piece)
|
|
137
|
+
for piece in ENCODED_SEPARATORS.split(run.group(0)))
|
|
138
|
+
return False
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
def _blank(line: str, start: int, end: int) -> str:
|
|
142
|
+
return line[:start] + " " * (end - start) + line[end:]
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
def _real_use_masked(line: str, manifest: bool) -> str:
|
|
146
|
+
"""The line with its library uses blanked out, positions kept: an import statement,
|
|
147
|
+
and in a manifest a dependency's name."""
|
|
148
|
+
for m in IMPORT_SPANS.finditer(line):
|
|
149
|
+
line = _blank(line, m.start(), m.end())
|
|
150
|
+
if manifest:
|
|
151
|
+
for dep in DEPENDENCY_RES:
|
|
152
|
+
m = dep.match(line)
|
|
153
|
+
if m:
|
|
154
|
+
line = _blank(line, m.start("name"), m.end("name"))
|
|
155
|
+
break
|
|
156
|
+
return line
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
#: The identifier a match sits in, for the allow list.
|
|
160
|
+
IDENTIFIER_CHAR = re.compile(r"[A-Za-z0-9_]")
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
def _identifier(text: str, start: int, end: int) -> str:
|
|
164
|
+
while start > 0 and IDENTIFIER_CHAR.match(text[start - 1]):
|
|
165
|
+
start -= 1
|
|
166
|
+
while end < len(text) and IDENTIFIER_CHAR.match(text[end]):
|
|
167
|
+
end += 1
|
|
168
|
+
return text[start:end]
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
def _first(compiled, text: str, allow: AbstractSet[str] = frozenset()) -> Tuple[Optional[Term], int]:
|
|
172
|
+
"""The first term the text names, and where."""
|
|
173
|
+
for term, pattern in compiled:
|
|
174
|
+
for m in pattern.finditer(text):
|
|
175
|
+
if _encoded(text, m.start(), m.end()):
|
|
176
|
+
continue
|
|
177
|
+
if allow and _identifier(text, m.start(), m.end()) in allow:
|
|
178
|
+
continue
|
|
179
|
+
return term, m.start()
|
|
180
|
+
return None, -1
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
def _mentions(text: str, needles) -> bool:
|
|
184
|
+
"""Cheaply, whether a term's letters appear at all -- in its case, when it has one."""
|
|
185
|
+
low = None
|
|
186
|
+
for needle, case_sensitive in needles:
|
|
187
|
+
if case_sensitive:
|
|
188
|
+
if needle in text:
|
|
189
|
+
return True
|
|
190
|
+
else:
|
|
191
|
+
low = text.lower() if low is None else low
|
|
192
|
+
if needle in low:
|
|
193
|
+
return True
|
|
194
|
+
return False
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
def _file_mentions(path: Path, needles) -> bool:
|
|
198
|
+
"""Whether the file holds a term's letters anywhere, CHUNK_BYTES at a time: a file near
|
|
199
|
+
MAX_FILE_BYTES is never held whole. Chunks overlap by the longest needle, so a term that
|
|
200
|
+
straddles two chunks is still seen."""
|
|
201
|
+
overlap = max(len(n.encode("utf-8")) for n, _ in needles)
|
|
202
|
+
tail = b""
|
|
203
|
+
with path.open("rb") as fh:
|
|
204
|
+
while True:
|
|
205
|
+
chunk = fh.read(CHUNK_BYTES)
|
|
206
|
+
if not chunk:
|
|
207
|
+
return False
|
|
208
|
+
if _mentions((tail + chunk).decode("utf-8", errors="replace"), needles):
|
|
209
|
+
return True
|
|
210
|
+
tail = chunk[-overlap:]
|
|
211
|
+
|
|
212
|
+
|
|
213
|
+
_BREAK = " \t\"',;"
|
|
214
|
+
|
|
215
|
+
|
|
216
|
+
def _snippet(line: str, at: int) -> str:
|
|
217
|
+
"""The line around the match, credentials masked: a seed file can be one line of
|
|
218
|
+
megabytes, and the line that names a vendor is often the one that holds its key. The
|
|
219
|
+
cut is widened to the nearest space or quote, so a key is never split where the
|
|
220
|
+
redaction could no longer recognise it."""
|
|
221
|
+
start = max(0, at - SNIPPET_CHARS // 3)
|
|
222
|
+
end = min(len(line), start + SNIPPET_CHARS)
|
|
223
|
+
while start > 0 and line[start - 1] not in _BREAK and at - start < SNIPPET_CHARS:
|
|
224
|
+
start -= 1
|
|
225
|
+
while end < len(line) and line[end] not in _BREAK and end - at < 2 * SNIPPET_CHARS:
|
|
226
|
+
end += 1
|
|
227
|
+
piece = redact(line[start:end]).strip()
|
|
228
|
+
return ("..." if start else "") + piece + ("..." if end < len(line) else "")
|
|
229
|
+
|
|
230
|
+
|
|
231
|
+
def scan(root: Path, terms: Sequence[Term], allow: Iterable[str] = (),
|
|
232
|
+
scope: Optional[Scope] = None) -> Outcome:
|
|
233
|
+
compiled = compile_terms(terms)
|
|
234
|
+
scope = scope or file_scope("restricted_terms")
|
|
235
|
+
allow = frozenset(a.strip() for a in allow if a.strip())
|
|
236
|
+
out = Outcome(terms=tuple(t.text for t, _ in compiled))
|
|
237
|
+
if not compiled:
|
|
238
|
+
return out
|
|
239
|
+
needles = {(t.text.strip() if t.case_sensitive else t.text.strip().lower(), t.case_sensitive)
|
|
240
|
+
for t, _ in compiled}
|
|
241
|
+
folders_named: Set[str] = set()
|
|
242
|
+
for path in scope.walk(root):
|
|
243
|
+
rel = path.relative_to(root).as_posix()
|
|
244
|
+
*folders, name = rel.split("/")
|
|
245
|
+
for depth in range(len(folders)):
|
|
246
|
+
folder = "/".join(folders[:depth + 1])
|
|
247
|
+
if folder in folders_named:
|
|
248
|
+
break # reported once, with all inside it
|
|
249
|
+
named, _ = _first(compiled, folders[depth], allow)
|
|
250
|
+
if named:
|
|
251
|
+
folders_named.add(folder)
|
|
252
|
+
_found(out, Finding(folder + "/", 0, named.text, "the folder's name"))
|
|
253
|
+
break
|
|
254
|
+
named, _ = _first(compiled, name, allow)
|
|
255
|
+
if named:
|
|
256
|
+
_found(out, Finding(rel, 0, named.text, "the file's name"))
|
|
257
|
+
with path.open("rb") as fh:
|
|
258
|
+
if b"\0" in fh.read(8192):
|
|
259
|
+
continue # binary: an image, a database
|
|
260
|
+
if path.stat().st_size > MAX_FILE_BYTES:
|
|
261
|
+
out.skipped_large.append(rel)
|
|
262
|
+
continue
|
|
263
|
+
out.files_read += 1
|
|
264
|
+
# The regexes only where a term's letters appear at all: a repository's grader
|
|
265
|
+
# changelogs alone can be a gigabyte, nearly all of it naming nothing.
|
|
266
|
+
if not _file_mentions(path, needles):
|
|
267
|
+
continue
|
|
268
|
+
manifest = bool(MANIFEST_RE.match(name))
|
|
269
|
+
with path.open(encoding="utf-8", errors="replace") as lines:
|
|
270
|
+
for number, line in enumerate(lines, 1):
|
|
271
|
+
if not _mentions(line, needles):
|
|
272
|
+
continue
|
|
273
|
+
term, at = _first(compiled, _real_use_masked(line, manifest), allow)
|
|
274
|
+
if term:
|
|
275
|
+
_found(out, Finding(rel, number, term.text, _snippet(line.rstrip("\n"), at)))
|
|
276
|
+
return out
|
|
277
|
+
|
|
278
|
+
|
|
279
|
+
def _found(out: Outcome, finding: Finding) -> None:
|
|
280
|
+
"""Count every finding; keep only the first MAX_LISTED, so a file of a million is not a million objects."""
|
|
281
|
+
out.found += 1
|
|
282
|
+
out.files_named.add(finding.file)
|
|
283
|
+
if len(out.findings) < MAX_LISTED:
|
|
284
|
+
out.findings.append(finding)
|
|
285
|
+
|
|
286
|
+
|
|
287
|
+
def run_restricted_terms(repo_path: Path, terms: Sequence[Term], allow: Iterable[str] = (),
|
|
288
|
+
scope: Optional[Scope] = None) -> Outcome:
|
|
289
|
+
try:
|
|
290
|
+
return scan(Path(repo_path), terms, allow, scope)
|
|
291
|
+
except Exception as exc: # noqa: BLE001 -- said as a warning, never a silent pass
|
|
292
|
+
return Outcome(error=f"{type(exc).__name__}: {str(exc)[:300]}")
|
|
293
|
+
|
|
294
|
+
|
|
295
|
+
def describe(f: Finding) -> str:
|
|
296
|
+
where = f.file if f.line == 0 else f"{f.file}:{f.line}"
|
|
297
|
+
return f"{where} names {f.term!r}: {f.text}"
|
|
298
|
+
|
|
299
|
+
|
|
300
|
+
def verdict(out: Outcome, blocking: bool = True) -> Tuple[str, str, List[str]]:
|
|
301
|
+
"""(status, headline, detail lines). Not ``blocking``: findings are a warning."""
|
|
302
|
+
if out.error:
|
|
303
|
+
return "warn", f"Not blocking. restricted_terms error: {out.error}", []
|
|
304
|
+
if not out.terms:
|
|
305
|
+
return "warn", "Not blocking. No restricted terms are set (validation.restricted_terms).", []
|
|
306
|
+
|
|
307
|
+
scanned = f"{out.files_read} file(s) read for {', '.join(out.terms)}"
|
|
308
|
+
notes = [f"WARNING: {rel} not read: over {MAX_FILE_BYTES // (1024 * 1024)} MB" for rel in out.skipped_large]
|
|
309
|
+
if not out.found:
|
|
310
|
+
return "pass", f"no restricted term anywhere in the repository. {scanned}", notes
|
|
311
|
+
|
|
312
|
+
n = out.found
|
|
313
|
+
lines = [f"FOUND: {describe(f)}" for f in out.findings]
|
|
314
|
+
if n > len(out.findings):
|
|
315
|
+
lines.append(f"... and {n - len(out.findings)} more")
|
|
316
|
+
files = len(out.files_named)
|
|
317
|
+
head = (f"{n} line{'s' if n != 1 else ''} in {files} file{'s' if files != 1 else ''} "
|
|
318
|
+
f"name{'s' if n == 1 else ''} a restricted term. {scanned}")
|
|
319
|
+
if not blocking:
|
|
320
|
+
return "warn", f"Not blocking yet (validation.restricted_terms: blocking is off). {head}", lines + notes
|
|
321
|
+
return "fail", head, lines + notes
|
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
"""Pin and stage validation inputs using the ECR runtime-asset contract.
|
|
2
|
+
|
|
3
|
+
Selection happens once after cloning the exact validation commit, before any
|
|
4
|
+
build. The existing job JSON stores the pin so retries don't follow a new latest.
|
|
5
|
+
"""
|
|
6
|
+
import json
|
|
7
|
+
import re
|
|
8
|
+
import subprocess
|
|
9
|
+
|
|
10
|
+
import boto3
|
|
11
|
+
|
|
12
|
+
from ..config import get_settings
|
|
13
|
+
from ..models import Repository
|
|
14
|
+
from ..runtime_assets.build import select_for_contract, stage_for_build
|
|
15
|
+
from ..runtime_assets.contract import AssetError, GammaLayout, asset_bucket, asset_contract, gamma_layout, is_gamma_bucket
|
|
16
|
+
from ..runtime_assets import gamma as gamma_module
|
|
17
|
+
from ..runtime_assets.models import AssetChannel
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def storage_client(settings):
|
|
21
|
+
key, secret, region, token = settings.artifacts_aws_creds
|
|
22
|
+
if not (key and secret):
|
|
23
|
+
key, secret, region, token = settings.ecr_push_aws_creds
|
|
24
|
+
return boto3.client(
|
|
25
|
+
's3', region_name=region or 'ap-south-1',
|
|
26
|
+
aws_access_key_id=key or None, aws_secret_access_key=secret or None,
|
|
27
|
+
aws_session_token=token or None,
|
|
28
|
+
)
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def _main_bucket(repo):
|
|
32
|
+
"""Main's own artifacts bucket, for a branch inheriting main's release.
|
|
33
|
+
|
|
34
|
+
Returned as a callable and called only on that path: a branch with a release of its
|
|
35
|
+
own never needs it. It is allowed to raise -- "main's app.config is unreadable" is a
|
|
36
|
+
far more useful failure than looking in this branch's bucket and reporting that main
|
|
37
|
+
has no release.
|
|
38
|
+
"""
|
|
39
|
+
from ..runtime_assets import buckets
|
|
40
|
+
|
|
41
|
+
def resolve():
|
|
42
|
+
return buckets.for_branch(repo, 'main')['bucket']
|
|
43
|
+
return resolve
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def stage_for_validation(db, job, root, log):
|
|
47
|
+
build_config = dict(job.build_config or {})
|
|
48
|
+
pin = build_config.get('runtime_asset_release')
|
|
49
|
+
requested = build_config.get('runtime_release_id')
|
|
50
|
+
path = root / 'app.config'
|
|
51
|
+
try:
|
|
52
|
+
config = json.loads(path.read_text()) if path.exists() else {}
|
|
53
|
+
except (ValueError, OSError):
|
|
54
|
+
if pin or requested:
|
|
55
|
+
raise AssetError('Pinned runtime app.config is missing or invalid')
|
|
56
|
+
return None # Preserve legacy handling of malformed configs.
|
|
57
|
+
assets = asset_contract(config)
|
|
58
|
+
if assets is None:
|
|
59
|
+
if pin or requested:
|
|
60
|
+
raise AssetError('Pinned code no longer declares runtime_assets')
|
|
61
|
+
return None
|
|
62
|
+
|
|
63
|
+
repo = db.get(Repository, job.repository_id) if job.repository_id else None
|
|
64
|
+
if repo is None or repo.is_deleted:
|
|
65
|
+
raise AssetError('Import this repository into Foundry before validating its runtime assets')
|
|
66
|
+
result = subprocess.run(['git', 'rev-parse', 'HEAD'], cwd=root,
|
|
67
|
+
capture_output=True, text=True, timeout=30, check=True)
|
|
68
|
+
commit = result.stdout.strip()
|
|
69
|
+
if not re.fullmatch(r'[0-9a-f]{40,64}', commit):
|
|
70
|
+
raise AssetError('Cannot identify the checked-out validation commit')
|
|
71
|
+
if job.commit_sha and not commit.startswith(job.commit_sha):
|
|
72
|
+
raise AssetError('Checked-out code does not match the validation commit')
|
|
73
|
+
settings = get_settings()
|
|
74
|
+
# The checked-out app.config decides, as it does for a push; the pin below then
|
|
75
|
+
# holds a retry to the same bucket whatever the branch says later.
|
|
76
|
+
bucket = asset_bucket(config) or settings.artifacts_s3_bucket
|
|
77
|
+
s3 = storage_client(settings)
|
|
78
|
+
|
|
79
|
+
if is_gamma_bucket(bucket):
|
|
80
|
+
lay = gamma_layout(config)
|
|
81
|
+
if lay is None:
|
|
82
|
+
raise AssetError('Gamma bucket requires rl_name and release_name in app.config')
|
|
83
|
+
lay = GammaLayout(*lay)
|
|
84
|
+
if pin:
|
|
85
|
+
if pin['commit'] != commit or pin['bucket'] != bucket or pin['build_branch'] != job.branch:
|
|
86
|
+
raise AssetError('Validation inputs changed; start a new validation instead of retrying this job')
|
|
87
|
+
else:
|
|
88
|
+
pin = {
|
|
89
|
+
'gamma': True, 'rl_name': lay.rl_name, 'release_name': lay.release_name,
|
|
90
|
+
'bucket': bucket, 'build_branch': job.branch, 'commit': commit,
|
|
91
|
+
}
|
|
92
|
+
job.commit_sha = commit
|
|
93
|
+
job.build_config = {**build_config, 'runtime_asset_release': pin}
|
|
94
|
+
db.commit()
|
|
95
|
+
log(f"Validation pinned to code {commit}; gamma {lay.rl_name}/{lay.release_name} from {bucket}")
|
|
96
|
+
gamma_module.stage_for_build(s3, bucket, lay, root, config, log)
|
|
97
|
+
return pin
|
|
98
|
+
|
|
99
|
+
# Where main's releases live, for a branch with none of its own: app.config names
|
|
100
|
+
# the bucket per branch, so inheriting main's assets means reading main's bucket.
|
|
101
|
+
main_bucket = _main_bucket(repo)
|
|
102
|
+
if pin:
|
|
103
|
+
if pin['commit'] != commit or pin['bucket'] != bucket or pin['build_branch'] != job.branch:
|
|
104
|
+
raise AssetError('Validation inputs changed; start a new validation instead of retrying this job')
|
|
105
|
+
else:
|
|
106
|
+
release = select_for_contract(db, repo, job.branch, assets, requested, s3=s3, bucket=bucket,
|
|
107
|
+
main_bucket=main_bucket)
|
|
108
|
+
channel = db.get(AssetChannel, release.channel_id)
|
|
109
|
+
pin = {
|
|
110
|
+
'release_id': str(release.id), 'branch': channel.branch,
|
|
111
|
+
'version': release.version, 'bucket': bucket,
|
|
112
|
+
'build_branch': job.branch, 'commit': commit,
|
|
113
|
+
}
|
|
114
|
+
job.commit_sha = commit
|
|
115
|
+
job.build_config = {**build_config, 'runtime_asset_release': pin}
|
|
116
|
+
db.commit() # Persist before I/O so a retry keeps exactly these inputs.
|
|
117
|
+
log(f"Validation pinned to code {commit}; assets {pin['branch']} / {pin['version']} "
|
|
118
|
+
f"({pin['release_id']}) from {pin['bucket']}")
|
|
119
|
+
stage_for_build(db, s3, bucket, repo, job.branch,
|
|
120
|
+
root, config, pin['release_id'], log, main_bucket=main_bucket)
|
|
121
|
+
return pin
|