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,823 @@
|
|
|
1
|
+
"""Deterministic runtime-config rules: the blocking half of config_yaml_check.
|
|
2
|
+
|
|
3
|
+
Each rule reads the cloned repo and returns findings with file:line evidence. The same
|
|
4
|
+
files always produce the same findings, so re-running a commit gets the same verdict.
|
|
5
|
+
|
|
6
|
+
A rule runs in one of two modes: "enforce" (a finding fails the check) or "warn" (a
|
|
7
|
+
finding is reported but never blocks). Rules in DEFAULT_ENFORCED block; the rest only
|
|
8
|
+
warn. Today that is legacy_app_config, which every RL repo's frontend date override
|
|
9
|
+
still trips.
|
|
10
|
+
|
|
11
|
+
env_config_parity blocks: config.yaml is the source of truth for serving the app,
|
|
12
|
+
so a setting it does not declare is configurable only from someone's shell, and a
|
|
13
|
+
key nothing reads configures nothing while reading like it does. Measured across
|
|
14
|
+
the fleet before enforcing -- nine repos declare about a hundred env aliases
|
|
15
|
+
between them and three findings come out, all the same real gap.
|
|
16
|
+
|
|
17
|
+
A rule that crashes is reported as a rule error (a warning), never as a pass, a skip or
|
|
18
|
+
a failure. The clone is untrusted, so a file is read only if it is a regular file inside
|
|
19
|
+
the checkout, and at most MAX_SCAN_BYTES of it.
|
|
20
|
+
"""
|
|
21
|
+
from __future__ import annotations
|
|
22
|
+
|
|
23
|
+
import ast
|
|
24
|
+
import json
|
|
25
|
+
import re
|
|
26
|
+
from dataclasses import dataclass, field
|
|
27
|
+
from pathlib import Path
|
|
28
|
+
from typing import Callable, Dict, Iterator, List, Optional, Set, Tuple
|
|
29
|
+
|
|
30
|
+
from ..file_scope import Scope, scope as file_scope
|
|
31
|
+
|
|
32
|
+
DEFAULT_ENFORCED = frozenset({
|
|
33
|
+
"presence", "schema", "mandatory_keys", "database_seed", "env_reads", "entrypoint_exports",
|
|
34
|
+
"env_config_parity",
|
|
35
|
+
})
|
|
36
|
+
|
|
37
|
+
# Env vars carrying config.yaml values; a repo's AliasChoices names are added on top.
|
|
38
|
+
GOVERNED_FLOOR = frozenset({
|
|
39
|
+
"PROJECT_NAME", "RL_ENV_PROJECT_NAME",
|
|
40
|
+
"CONTROL_HUB_URL", "RL_ENV_CONTROL_HUB_URL",
|
|
41
|
+
"BASIC_AUTH_ENABLED", "RL_ENV_BASIC_AUTH_ENABLED",
|
|
42
|
+
"AUTH_KEY", "RL_ENV_AUTH_KEY",
|
|
43
|
+
"CURRENT_USER_ID", "RL_ENV_CURRENT_USER_ID",
|
|
44
|
+
"APP_URL", "RL_ENV_APP_URL",
|
|
45
|
+
"CURRENT_DATE", "RL_ENV_CURRENT_DATE",
|
|
46
|
+
"RL_ENV_DATABASE_SEED",
|
|
47
|
+
})
|
|
48
|
+
|
|
49
|
+
# Which config.yaml key declares the value an env var overrides. "apps.*" means the
|
|
50
|
+
# key lives under every app. An env var absent from this table is matched by name:
|
|
51
|
+
# RL_ENV_FOO / FOO -> a "foo" key, top level or per app.
|
|
52
|
+
ENV_TO_CONFIG_KEY = {
|
|
53
|
+
"PROJECT_NAME": "project_name",
|
|
54
|
+
"CONTROL_HUB_URL": "control_hub_url",
|
|
55
|
+
"BASIC_AUTH_ENABLED": "basic_auth.enabled",
|
|
56
|
+
"AUTH_KEY": "basic_auth.keys",
|
|
57
|
+
"CURRENT_USER_ID": "apps.*.login.user_id",
|
|
58
|
+
"CURRENT_LOGIN_USER_ID": "apps.*.login.user_id",
|
|
59
|
+
"APP_URL": "apps.*.app_url",
|
|
60
|
+
"CURRENT_DATE": "apps.*.reference_current_timestamp",
|
|
61
|
+
"DATABASE_SEED": "apps.*.database_seed",
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
# The container runtime owns these; they are not the environment's config surface.
|
|
65
|
+
PLATFORM_VARS = frozenset({
|
|
66
|
+
"DATABASE_URL", "PORT", "HOST", "PATH", "HOME", "TZ", "LANG", "LC_ALL",
|
|
67
|
+
"PYTHONPATH", "PYTHONUNBUFFERED", "NODE_ENV", "HOSTNAME", "USER", "SHELL",
|
|
68
|
+
})
|
|
69
|
+
|
|
70
|
+
SETTINGS_LAYER = frozenset({"backend/app/config.py", "backend/app/runtime_config.py"})
|
|
71
|
+
ENTRYPOINT_CANDIDATES = [
|
|
72
|
+
"docker/start.sh", "start.sh", "backend/start.sh",
|
|
73
|
+
"scripts/start.sh", "docker/scripts/start.sh", "backend/docker/start.sh",
|
|
74
|
+
]
|
|
75
|
+
|
|
76
|
+
# What is skipped -- dependencies, tests, and what is not part of the running app
|
|
77
|
+
# (migrations, seeders, scripts, graders) -- is the runtime setting validation.ignore
|
|
78
|
+
# (app.validation.file_scope).
|
|
79
|
+
PY_EXT = frozenset({".py"})
|
|
80
|
+
JS_EXT = frozenset({".ts", ".tsx", ".js", ".jsx", ".mjs"})
|
|
81
|
+
MAX_SCAN_BYTES = 2_000_000
|
|
82
|
+
MAX_STATEMENT_LINES = 40
|
|
83
|
+
LEGACY_READ_SPAN = 6 # path, read, parse, field access
|
|
84
|
+
|
|
85
|
+
LEGACY_APP_CONFIG_RE = re.compile(r"""['"/]app\.config['"]""") # the file, not the module
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
@dataclass
|
|
89
|
+
class Finding:
|
|
90
|
+
rule: str
|
|
91
|
+
message: str
|
|
92
|
+
file: str = ""
|
|
93
|
+
line: int = 0
|
|
94
|
+
|
|
95
|
+
@property
|
|
96
|
+
def where(self) -> str:
|
|
97
|
+
if self.file and self.line:
|
|
98
|
+
return f"{self.file}:{self.line}"
|
|
99
|
+
return self.file
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
@dataclass
|
|
103
|
+
class RuleResult:
|
|
104
|
+
rule: str
|
|
105
|
+
mode: str = "warn" # set by run_rules: "enforce" | "warn"
|
|
106
|
+
findings: List[Finding] = field(default_factory=list)
|
|
107
|
+
error: Optional[str] = None
|
|
108
|
+
not_applicable: Optional[str] = None
|
|
109
|
+
|
|
110
|
+
@property
|
|
111
|
+
def status(self) -> str:
|
|
112
|
+
if self.error:
|
|
113
|
+
return "error"
|
|
114
|
+
if self.findings:
|
|
115
|
+
return "finding"
|
|
116
|
+
if self.not_applicable:
|
|
117
|
+
return "n/a"
|
|
118
|
+
return "pass"
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
@dataclass
|
|
122
|
+
class SettledLine:
|
|
123
|
+
file: str
|
|
124
|
+
line: int
|
|
125
|
+
end: int
|
|
126
|
+
what: str
|
|
127
|
+
decided: str
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
@dataclass
|
|
131
|
+
class RulesOutcome:
|
|
132
|
+
results: List[RuleResult] = field(default_factory=list)
|
|
133
|
+
settled: List[SettledLine] = field(default_factory=list)
|
|
134
|
+
config_present: bool = False
|
|
135
|
+
|
|
136
|
+
@property
|
|
137
|
+
def blocking(self) -> List[Finding]:
|
|
138
|
+
return [f for r in self.results if r.mode == "enforce" for f in r.findings]
|
|
139
|
+
|
|
140
|
+
@property
|
|
141
|
+
def warnings(self) -> List[Finding]:
|
|
142
|
+
return [f for r in self.results if r.mode == "warn" for f in r.findings]
|
|
143
|
+
|
|
144
|
+
@property
|
|
145
|
+
def errors(self) -> List[RuleResult]:
|
|
146
|
+
return [r for r in self.results if r.error]
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
@dataclass
|
|
150
|
+
class _Repo:
|
|
151
|
+
root: Path
|
|
152
|
+
scope: Scope = field(default_factory=lambda: file_scope("config_yaml_check"))
|
|
153
|
+
config: Optional[dict] = None
|
|
154
|
+
config_error: Optional[str] = None
|
|
155
|
+
entrypoint: Optional[Path] = None
|
|
156
|
+
governed: Set[str] = field(default_factory=set)
|
|
157
|
+
settled: List[SettledLine] = field(default_factory=list)
|
|
158
|
+
|
|
159
|
+
def rel(self, p: Path) -> str:
|
|
160
|
+
return str(p.relative_to(self.root))
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
def _app_files(root: Path, exts: frozenset, scope: Scope) -> Iterator[Path]:
|
|
164
|
+
for p in scope.walk(root):
|
|
165
|
+
if p.suffix in exts and repo_file(root, p):
|
|
166
|
+
yield p
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
# The clone is untrusted: never follow a link out of it or read a device.
|
|
170
|
+
def repo_file(root: Path, p: Path) -> bool:
|
|
171
|
+
try:
|
|
172
|
+
real = p.resolve()
|
|
173
|
+
return real.is_relative_to(root.resolve()) and real.is_file()
|
|
174
|
+
except (OSError, RuntimeError):
|
|
175
|
+
return False
|
|
176
|
+
|
|
177
|
+
|
|
178
|
+
def read_repo_file(root: Path, p: Path, limit: int = MAX_SCAN_BYTES) -> str:
|
|
179
|
+
if not repo_file(root, p):
|
|
180
|
+
return ""
|
|
181
|
+
try:
|
|
182
|
+
with p.resolve().open("rb") as fh:
|
|
183
|
+
return fh.read(limit).decode("utf-8", errors="ignore")
|
|
184
|
+
except OSError:
|
|
185
|
+
return ""
|
|
186
|
+
|
|
187
|
+
|
|
188
|
+
def find_entrypoint(root: Path, scope: Optional[Scope] = None) -> Optional[Path]:
|
|
189
|
+
for rel in ENTRYPOINT_CANDIDATES:
|
|
190
|
+
if repo_file(root, root / rel):
|
|
191
|
+
return root / rel
|
|
192
|
+
for p in (scope or file_scope("config_yaml_check")).walk(root):
|
|
193
|
+
if p.name == "start.sh" and repo_file(root, p):
|
|
194
|
+
return p
|
|
195
|
+
return None
|
|
196
|
+
|
|
197
|
+
|
|
198
|
+
def declared_env_aliases(root: Path) -> Set[str]:
|
|
199
|
+
"""Env var names THIS repo's settings layer accepts, from its own AliasChoices.
|
|
200
|
+
|
|
201
|
+
Not ``governed_vars() - GOVERNED_FLOOR``: that would also drop an alias a repo
|
|
202
|
+
genuinely declares which happens to be on the floor (RL_ENV_DATABASE_SEED, say),
|
|
203
|
+
and parity would stop asking about it. The floor is a reference list of names
|
|
204
|
+
that carry config values org-wide, not evidence any given app reads them, so it
|
|
205
|
+
is simply never added here.
|
|
206
|
+
"""
|
|
207
|
+
names: Set[str] = set()
|
|
208
|
+
cfg = root / "backend" / "app" / "config.py"
|
|
209
|
+
if not repo_file(root, cfg):
|
|
210
|
+
return names
|
|
211
|
+
try:
|
|
212
|
+
tree = ast.parse(read_repo_file(root, cfg))
|
|
213
|
+
except (SyntaxError, ValueError, RecursionError):
|
|
214
|
+
return names
|
|
215
|
+
for node in ast.walk(tree):
|
|
216
|
+
if isinstance(node, ast.Call):
|
|
217
|
+
fn = node.func
|
|
218
|
+
fname = fn.id if isinstance(fn, ast.Name) else fn.attr if isinstance(fn, ast.Attribute) else ""
|
|
219
|
+
if fname == "AliasChoices":
|
|
220
|
+
names.update(a.value for a in node.args
|
|
221
|
+
if isinstance(a, ast.Constant) and isinstance(a.value, str))
|
|
222
|
+
return names
|
|
223
|
+
|
|
224
|
+
|
|
225
|
+
def governed_vars(root: Path) -> Set[str]:
|
|
226
|
+
return set(GOVERNED_FLOOR) | declared_env_aliases(root)
|
|
227
|
+
|
|
228
|
+
|
|
229
|
+
def _env_aliases(tree: ast.AST) -> Tuple[Set[str], Set[str], Set[str]]:
|
|
230
|
+
os_names, environ_names, getenv_names = {"os"}, {"environ"}, {"getenv"}
|
|
231
|
+
for node in ast.walk(tree):
|
|
232
|
+
if isinstance(node, ast.Import):
|
|
233
|
+
for a in node.names:
|
|
234
|
+
if a.name == "os":
|
|
235
|
+
os_names.add(a.asname or "os")
|
|
236
|
+
elif isinstance(node, ast.ImportFrom) and node.module == "os":
|
|
237
|
+
for a in node.names:
|
|
238
|
+
if a.name == "environ":
|
|
239
|
+
environ_names.add(a.asname or "environ")
|
|
240
|
+
elif a.name == "getenv":
|
|
241
|
+
getenv_names.add(a.asname or "getenv")
|
|
242
|
+
return os_names, environ_names, getenv_names
|
|
243
|
+
|
|
244
|
+
|
|
245
|
+
def py_env_reads(source: str) -> Iterator[Tuple[int, Optional[str], str]]:
|
|
246
|
+
"""Yield (line, var name or None if dynamic, kind) per env access."""
|
|
247
|
+
try:
|
|
248
|
+
tree = ast.parse(source)
|
|
249
|
+
except (SyntaxError, ValueError, RecursionError): # unparsable files are skipped, not a rule error
|
|
250
|
+
return
|
|
251
|
+
os_names, environ_names, getenv_names = _env_aliases(tree)
|
|
252
|
+
|
|
253
|
+
def is_environ(n: ast.AST) -> bool:
|
|
254
|
+
return (isinstance(n, ast.Name) and n.id in environ_names) or (
|
|
255
|
+
isinstance(n, ast.Attribute) and n.attr == "environ"
|
|
256
|
+
and isinstance(n.value, ast.Name) and n.value.id in os_names)
|
|
257
|
+
|
|
258
|
+
def is_getenv(f: ast.AST) -> bool:
|
|
259
|
+
return (isinstance(f, ast.Name) and f.id in getenv_names) or (
|
|
260
|
+
isinstance(f, ast.Attribute) and f.attr == "getenv"
|
|
261
|
+
and isinstance(f.value, ast.Name) and f.value.id in os_names)
|
|
262
|
+
|
|
263
|
+
def literal(n: Optional[ast.AST]) -> Optional[str]:
|
|
264
|
+
if isinstance(n, ast.Constant) and isinstance(n.value, str):
|
|
265
|
+
return n.value
|
|
266
|
+
if isinstance(n, ast.BinOp) and isinstance(n.op, ast.Add): # "APP_" + "URL", iterative so long chains can't crash
|
|
267
|
+
parts: List[str] = []
|
|
268
|
+
pending: List[ast.AST] = [n]
|
|
269
|
+
while pending:
|
|
270
|
+
cur = pending.pop()
|
|
271
|
+
if isinstance(cur, ast.Constant) and isinstance(cur.value, str):
|
|
272
|
+
parts.append(cur.value)
|
|
273
|
+
elif isinstance(cur, ast.BinOp) and isinstance(cur.op, ast.Add):
|
|
274
|
+
pending += [cur.right, cur.left]
|
|
275
|
+
else:
|
|
276
|
+
return None
|
|
277
|
+
return "".join(parts)
|
|
278
|
+
return None
|
|
279
|
+
|
|
280
|
+
for node in ast.walk(tree):
|
|
281
|
+
if isinstance(node, ast.Call):
|
|
282
|
+
f = node.func
|
|
283
|
+
if isinstance(f, ast.Attribute) and f.attr in ("get", "pop", "setdefault") and is_environ(f.value):
|
|
284
|
+
yield node.lineno, literal(node.args[0] if node.args else None), f"environ.{f.attr}"
|
|
285
|
+
elif is_getenv(f):
|
|
286
|
+
yield node.lineno, literal(node.args[0] if node.args else None), "getenv"
|
|
287
|
+
elif isinstance(node, ast.Subscript) and is_environ(node.value):
|
|
288
|
+
kind = "environ[] write" if isinstance(node.ctx, ast.Store) else "environ[]"
|
|
289
|
+
yield node.lineno, literal(node.slice), kind
|
|
290
|
+
|
|
291
|
+
|
|
292
|
+
JS_ENV_RE = re.compile(r"process\.env\.([A-Za-z_][A-Za-z0-9_]*)|process\.env\[\s*['\"]([^'\"]+)['\"]\s*\]")
|
|
293
|
+
|
|
294
|
+
|
|
295
|
+
def js_env_reads(source: str) -> Iterator[Tuple[int, str]]:
|
|
296
|
+
for i, line in enumerate(source.splitlines(), 1):
|
|
297
|
+
if line.lstrip().startswith(("//", "*", "/*")):
|
|
298
|
+
continue
|
|
299
|
+
for m in JS_ENV_RE.finditer(line):
|
|
300
|
+
yield i, m.group(1) or m.group(2)
|
|
301
|
+
|
|
302
|
+
|
|
303
|
+
_ASSIGN_RE = re.compile(r"^\s*(?:export\s+|declare\s+-x\s+|local\s+)?([A-Za-z_][A-Za-z0-9_]*)=(.*)$", re.DOTALL)
|
|
304
|
+
_COLON_DEFAULT_RE = re.compile(r'^\s*:\s+"?\$\{([A-Za-z_][A-Za-z0-9_]*):?=(.*)\}"?\s*$')
|
|
305
|
+
_CONFIG_READ_RE = re.compile(r"cfg_\w+|runtime_config|load_config")
|
|
306
|
+
_VAR_REF_RE = re.compile(r"\$\{?([A-Za-z_][A-Za-z0-9_]*)")
|
|
307
|
+
|
|
308
|
+
|
|
309
|
+
def _shell_statements(text: str) -> Iterator[Tuple[int, str]]:
|
|
310
|
+
"""Yield (first line, statement) with continuations and multi-line $( ) joined."""
|
|
311
|
+
buf, start, depth = "", 0, 0
|
|
312
|
+
for i, raw in enumerate(text.splitlines(), 1):
|
|
313
|
+
if not buf:
|
|
314
|
+
start = i
|
|
315
|
+
buf += raw + "\n"
|
|
316
|
+
depth += raw.count("$(") - (raw.count(")") if (depth or "$(" in raw) else 0)
|
|
317
|
+
# an unbalanced "$(" must not swallow the rest of the file
|
|
318
|
+
if (raw.rstrip().endswith("\\") or depth > 0) and i - start < MAX_STATEMENT_LINES:
|
|
319
|
+
continue
|
|
320
|
+
yield start, buf.replace("\\\n", " ")
|
|
321
|
+
buf, depth = "", 0
|
|
322
|
+
if buf:
|
|
323
|
+
yield start, buf.replace("\\\n", " ")
|
|
324
|
+
|
|
325
|
+
|
|
326
|
+
def entrypoint_assignments(text: str, governed: Set[str]) -> Iterator[Tuple[int, str, bool, str]]:
|
|
327
|
+
"""Yield (line, var, ok, reason) per governed assignment; ok once the value reaches config."""
|
|
328
|
+
fed: Set[str] = set()
|
|
329
|
+
for line, stmt in _shell_statements(text):
|
|
330
|
+
first = stmt.splitlines()[0] if stmt.strip() else ""
|
|
331
|
+
if first.lstrip().startswith("#"):
|
|
332
|
+
continue
|
|
333
|
+
m = _ASSIGN_RE.match(stmt.rstrip("\n")) or _COLON_DEFAULT_RE.match(first)
|
|
334
|
+
if not m:
|
|
335
|
+
continue
|
|
336
|
+
name, rhs = m.group(1), m.group(2)
|
|
337
|
+
refs = set(_VAR_REF_RE.findall(rhs)) - {name}
|
|
338
|
+
from_config = bool(_CONFIG_READ_RE.search(rhs)) or bool(refs & fed)
|
|
339
|
+
was_fed = name in fed
|
|
340
|
+
if from_config:
|
|
341
|
+
fed.add(name)
|
|
342
|
+
if name not in governed:
|
|
343
|
+
continue
|
|
344
|
+
if from_config:
|
|
345
|
+
yield line, name, True, "falls back to config.yaml"
|
|
346
|
+
elif was_fed:
|
|
347
|
+
yield line, name, True, "last resort after a config-fed assignment"
|
|
348
|
+
else:
|
|
349
|
+
yield line, name, False, f"sets {name} from the environment or a literal without consulting config.yaml"
|
|
350
|
+
|
|
351
|
+
|
|
352
|
+
def _rule_presence(repo: _Repo) -> RuleResult:
|
|
353
|
+
r = RuleResult("presence")
|
|
354
|
+
for name in ("config.yaml", "config.schema.json"):
|
|
355
|
+
if not repo_file(repo.root, repo.root / name):
|
|
356
|
+
r.findings.append(Finding("presence", "is missing at the repo root", name))
|
|
357
|
+
return r
|
|
358
|
+
|
|
359
|
+
|
|
360
|
+
def _rule_schema(repo: _Repo) -> RuleResult:
|
|
361
|
+
r = RuleResult("schema")
|
|
362
|
+
cfg_p, schema_p = repo.root / "config.yaml", repo.root / "config.schema.json"
|
|
363
|
+
if not (repo_file(repo.root, cfg_p) and repo_file(repo.root, schema_p)):
|
|
364
|
+
r.not_applicable = "config.yaml or config.schema.json missing (see presence)"
|
|
365
|
+
return r
|
|
366
|
+
if repo.config_error:
|
|
367
|
+
r.findings.append(Finding("schema", f"config.yaml does not parse: {repo.config_error}", "config.yaml"))
|
|
368
|
+
return r
|
|
369
|
+
try:
|
|
370
|
+
schema = json.loads(read_repo_file(repo.root, schema_p))
|
|
371
|
+
except ValueError as exc:
|
|
372
|
+
r.findings.append(Finding("schema", f"config.schema.json does not parse: {exc}", "config.schema.json"))
|
|
373
|
+
return r
|
|
374
|
+
from jsonschema import Draft202012Validator, FormatChecker
|
|
375
|
+
from jsonschema.exceptions import SchemaError
|
|
376
|
+
from referencing.exceptions import Unresolvable
|
|
377
|
+
try:
|
|
378
|
+
Draft202012Validator.check_schema(schema)
|
|
379
|
+
validator = Draft202012Validator(schema, format_checker=FormatChecker())
|
|
380
|
+
errors = sorted(validator.iter_errors(repo.config), key=lambda e: [str(p) for p in e.path])
|
|
381
|
+
except (SchemaError, Unresolvable) as exc:
|
|
382
|
+
msg = exc.message if isinstance(exc, SchemaError) else str(exc)
|
|
383
|
+
r.findings.append(Finding("schema", f"is not a valid JSON Schema: {msg[:200]}", "config.schema.json"))
|
|
384
|
+
return r
|
|
385
|
+
for e in errors:
|
|
386
|
+
loc = "/".join(str(p) for p in e.path) or "<root>"
|
|
387
|
+
r.findings.append(Finding("schema", f"{loc}: {e.message}", "config.yaml"))
|
|
388
|
+
return r
|
|
389
|
+
|
|
390
|
+
|
|
391
|
+
def _is_blank(v) -> bool:
|
|
392
|
+
return v is None or (isinstance(v, str) and not v.strip())
|
|
393
|
+
|
|
394
|
+
|
|
395
|
+
def _rule_mandatory_keys(repo: _Repo) -> RuleResult:
|
|
396
|
+
r = RuleResult("mandatory_keys")
|
|
397
|
+
cfg = repo.config
|
|
398
|
+
if not isinstance(cfg, dict):
|
|
399
|
+
if repo_file(repo.root, repo.root / "config.yaml") and not repo.config_error:
|
|
400
|
+
kind = "empty" if cfg is None else f"a {type(cfg).__name__}"
|
|
401
|
+
r.findings.append(Finding("mandatory_keys", f"must be a mapping of keys, but is {kind}", "config.yaml"))
|
|
402
|
+
else:
|
|
403
|
+
r.not_applicable = "config.yaml missing or unparsable (see presence and schema)"
|
|
404
|
+
return r
|
|
405
|
+
|
|
406
|
+
def miss(msg: str) -> None:
|
|
407
|
+
r.findings.append(Finding("mandatory_keys", msg, "config.yaml"))
|
|
408
|
+
|
|
409
|
+
if _is_blank(cfg.get("project_name")):
|
|
410
|
+
miss("project_name is missing or empty")
|
|
411
|
+
if "control_hub_url" not in cfg: # "" is valid
|
|
412
|
+
miss("control_hub_url key is missing (an empty string is fine)")
|
|
413
|
+
ba = cfg.get("basic_auth")
|
|
414
|
+
if not isinstance(ba, dict):
|
|
415
|
+
miss("basic_auth is missing")
|
|
416
|
+
else:
|
|
417
|
+
if not isinstance(ba.get("enabled"), bool):
|
|
418
|
+
miss("basic_auth.enabled is missing or not a boolean")
|
|
419
|
+
if not (isinstance(ba.get("keys"), list) and ba["keys"]):
|
|
420
|
+
miss("basic_auth.keys is missing or empty")
|
|
421
|
+
apps = cfg.get("apps")
|
|
422
|
+
if not isinstance(apps, dict) or not apps:
|
|
423
|
+
miss("apps is missing or empty")
|
|
424
|
+
return r
|
|
425
|
+
for name, app in apps.items():
|
|
426
|
+
app = app if isinstance(app, dict) else {}
|
|
427
|
+
login = app.get("login")
|
|
428
|
+
if _is_blank(login.get("user_id") if isinstance(login, dict) else None): # 0 is a valid id
|
|
429
|
+
miss(f"apps.{name}.login.user_id is missing or empty")
|
|
430
|
+
if _is_blank(app.get("app_url")):
|
|
431
|
+
miss(f"apps.{name}.app_url is missing or empty")
|
|
432
|
+
return r
|
|
433
|
+
|
|
434
|
+
|
|
435
|
+
def _rule_database_seed(repo: _Repo) -> RuleResult:
|
|
436
|
+
r = RuleResult("database_seed")
|
|
437
|
+
cfg = repo.config
|
|
438
|
+
if not isinstance(cfg, dict):
|
|
439
|
+
r.not_applicable = "config.yaml missing or not a mapping"
|
|
440
|
+
return r
|
|
441
|
+
apps = cfg.get("apps") if isinstance(cfg.get("apps"), dict) else {}
|
|
442
|
+
for name, app in apps.items():
|
|
443
|
+
if not isinstance(app, dict) or "database_seed" not in app: # "" is valid
|
|
444
|
+
r.findings.append(Finding("database_seed", f"apps.{name}.database_seed key is missing "
|
|
445
|
+
"(an empty string is fine)", "config.yaml"))
|
|
446
|
+
if repo.entrypoint is None:
|
|
447
|
+
r.findings.append(Finding("database_seed", "no container entrypoint (start.sh) found to consume "
|
|
448
|
+
"database_seed"))
|
|
449
|
+
return r
|
|
450
|
+
text = read_repo_file(repo.root, repo.entrypoint)
|
|
451
|
+
code = [ln for ln in text.splitlines() if not ln.lstrip().startswith("#")]
|
|
452
|
+
consumes = any("cfg_database_seed" in ln or ("database_seed" in ln and "load_config" in ln) for ln in code)
|
|
453
|
+
if not consumes:
|
|
454
|
+
r.findings.append(Finding("database_seed", "the entrypoint never reads database_seed from config "
|
|
455
|
+
"(expected cfg_database_seed())", repo.rel(repo.entrypoint)))
|
|
456
|
+
return r
|
|
457
|
+
|
|
458
|
+
|
|
459
|
+
def _rule_env_reads(repo: _Repo) -> RuleResult:
|
|
460
|
+
r = RuleResult("env_reads")
|
|
461
|
+
for p in _app_files(repo.root, PY_EXT, repo.scope):
|
|
462
|
+
rel = repo.rel(p)
|
|
463
|
+
for line, name, kind in py_env_reads(read_repo_file(repo.root, p)):
|
|
464
|
+
if name is None:
|
|
465
|
+
continue # dynamic names are left to the advisory
|
|
466
|
+
verb = {"environ[] write": "sets", "environ.setdefault": "sets", "environ.pop": "removes"}.get(kind, "reads")
|
|
467
|
+
if rel in SETTINGS_LAYER:
|
|
468
|
+
decided = "the settings layer (sanctioned)"
|
|
469
|
+
elif name in repo.governed:
|
|
470
|
+
decided = "reported by the env_reads rule"
|
|
471
|
+
# writes count too: env outranks config.yaml
|
|
472
|
+
where = "in" if verb == "sets" else "from"
|
|
473
|
+
r.findings.append(Finding("env_reads", f"{verb} {name} directly {where} the environment outside "
|
|
474
|
+
"the settings layer; use settings.* instead", rel, line))
|
|
475
|
+
else:
|
|
476
|
+
decided = "not a config.yaml value (out of scope)"
|
|
477
|
+
repo.settled.append(SettledLine(rel, line, line, f"direct env access of {name}", decided))
|
|
478
|
+
for p in _app_files(repo.root, JS_EXT, repo.scope):
|
|
479
|
+
rel = repo.rel(p)
|
|
480
|
+
for line, name in js_env_reads(read_repo_file(repo.root, p)):
|
|
481
|
+
# Node can't call the Python reader; entrypoint_exports covers where the value came from.
|
|
482
|
+
decided = ("a frontend read of an entrypoint-exported value (allowed)" if name in repo.governed
|
|
483
|
+
else "not a config.yaml value (out of scope)")
|
|
484
|
+
repo.settled.append(SettledLine(rel, line, line, f"direct env read of {name}", decided))
|
|
485
|
+
return r
|
|
486
|
+
|
|
487
|
+
|
|
488
|
+
def _rule_entrypoint_exports(repo: _Repo) -> RuleResult:
|
|
489
|
+
r = RuleResult("entrypoint_exports")
|
|
490
|
+
if repo.entrypoint is None:
|
|
491
|
+
r.not_applicable = "no container entrypoint (start.sh) found"
|
|
492
|
+
return r
|
|
493
|
+
rel = repo.rel(repo.entrypoint)
|
|
494
|
+
for line, name, ok, reason in entrypoint_assignments(read_repo_file(repo.root, repo.entrypoint), repo.governed):
|
|
495
|
+
if not ok:
|
|
496
|
+
r.findings.append(Finding("entrypoint_exports", reason, rel, line))
|
|
497
|
+
repo.settled.append(SettledLine(rel, line, line, f"entrypoint assignment of {name}",
|
|
498
|
+
"allowed: " + reason if ok else "reported by the entrypoint_exports rule"))
|
|
499
|
+
return r
|
|
500
|
+
|
|
501
|
+
|
|
502
|
+
def _rule_legacy_app_config(repo: _Repo) -> RuleResult:
|
|
503
|
+
r = RuleResult("legacy_app_config")
|
|
504
|
+
for p in _app_files(repo.root, PY_EXT | JS_EXT, repo.scope):
|
|
505
|
+
rel = repo.rel(p)
|
|
506
|
+
source = read_repo_file(repo.root, p)
|
|
507
|
+
if "app.config" not in source:
|
|
508
|
+
continue
|
|
509
|
+
lines = source.splitlines()
|
|
510
|
+
if p.suffix == ".py":
|
|
511
|
+
try:
|
|
512
|
+
tree = ast.parse(source)
|
|
513
|
+
except SyntaxError:
|
|
514
|
+
tree = None # An unparseable file gets the conservative text scan.
|
|
515
|
+
if tree is not None:
|
|
516
|
+
import_functions = {
|
|
517
|
+
alias.asname or alias.name for node in ast.walk(tree)
|
|
518
|
+
if isinstance(node, ast.ImportFrom) and node.module == "importlib"
|
|
519
|
+
for alias in node.names if alias.name == "import_module"
|
|
520
|
+
}
|
|
521
|
+
import_modules = {
|
|
522
|
+
alias.asname or alias.name for node in ast.walk(tree)
|
|
523
|
+
if isinstance(node, ast.Import)
|
|
524
|
+
for alias in node.names if alias.name == "importlib"
|
|
525
|
+
}
|
|
526
|
+
|
|
527
|
+
def mask_module_name(arg: ast.AST) -> None:
|
|
528
|
+
if (isinstance(arg, ast.Constant) and arg.value == "app.config"
|
|
529
|
+
and arg.lineno == arg.end_lineno):
|
|
530
|
+
index = arg.lineno - 1
|
|
531
|
+
lines[index] = (lines[index][:arg.col_offset]
|
|
532
|
+
+ " " * (arg.end_col_offset - arg.col_offset)
|
|
533
|
+
+ lines[index][arg.end_col_offset:])
|
|
534
|
+
|
|
535
|
+
for node in ast.walk(tree):
|
|
536
|
+
if isinstance(node, ast.Call) and node.args:
|
|
537
|
+
func = node.func
|
|
538
|
+
importing = (isinstance(func, ast.Name)
|
|
539
|
+
and func.id in import_functions | {"__import__"}
|
|
540
|
+
or isinstance(func, ast.Attribute) and func.attr == "import_module"
|
|
541
|
+
and isinstance(func.value, ast.Name) and func.value.id in import_modules)
|
|
542
|
+
if importing:
|
|
543
|
+
mask_module_name(node.args[0])
|
|
544
|
+
elif isinstance(node, ast.ExceptHandler) and node.name and node.type:
|
|
545
|
+
types = node.type.elts if isinstance(node.type, ast.Tuple) else [node.type]
|
|
546
|
+
if not any(isinstance(part, ast.Name) and part.id == "ModuleNotFoundError"
|
|
547
|
+
for part in types):
|
|
548
|
+
continue
|
|
549
|
+
for statement in node.body:
|
|
550
|
+
for comparison in ast.walk(statement):
|
|
551
|
+
if not isinstance(comparison, ast.Compare):
|
|
552
|
+
continue
|
|
553
|
+
parts = [comparison.left, *comparison.comparators]
|
|
554
|
+
if any(isinstance(part, ast.Attribute) and part.attr == "name"
|
|
555
|
+
and isinstance(part.value, ast.Name) and part.value.id == node.name
|
|
556
|
+
for part in parts):
|
|
557
|
+
for part in parts:
|
|
558
|
+
mask_module_name(part)
|
|
559
|
+
for line, text in enumerate(lines, 1):
|
|
560
|
+
if LEGACY_APP_CONFIG_RE.search(text) and not text.lstrip().startswith(("#", "//", "*")):
|
|
561
|
+
r.findings.append(Finding("legacy_app_config", "reads the legacy app.config file; runtime values "
|
|
562
|
+
"should come from config.yaml", rel, line))
|
|
563
|
+
repo.settled.append(SettledLine(rel, line, line + LEGACY_READ_SPAN,
|
|
564
|
+
"legacy app.config read (and the value read from it)",
|
|
565
|
+
"reported by the legacy_app_config rule"))
|
|
566
|
+
return r
|
|
567
|
+
|
|
568
|
+
|
|
569
|
+
def _config_has_path(config, dotted: str) -> bool:
|
|
570
|
+
"""Is this dotted config.yaml path present? 'apps.*' means every app must have it."""
|
|
571
|
+
if not isinstance(config, dict):
|
|
572
|
+
return False
|
|
573
|
+
head, _, rest = dotted.partition(".")
|
|
574
|
+
if head == "apps":
|
|
575
|
+
apps = config.get("apps")
|
|
576
|
+
if not isinstance(apps, dict) or not apps:
|
|
577
|
+
return False
|
|
578
|
+
star, _, tail = rest.partition(".")
|
|
579
|
+
assert star == "*", dotted
|
|
580
|
+
return all(_config_has_path(a, tail) for a in apps.values() if isinstance(a, dict))
|
|
581
|
+
if head not in config:
|
|
582
|
+
return False
|
|
583
|
+
return _config_has_path(config[head], rest) if rest else True
|
|
584
|
+
|
|
585
|
+
|
|
586
|
+
def _declares_env_var(config, name: str) -> bool:
|
|
587
|
+
"""Does config.yaml declare the value this env var overrides?
|
|
588
|
+
|
|
589
|
+
Matched by meaning, not by string: an explicit mapping first, then the var's own
|
|
590
|
+
name with any RL_ENV_ prefix dropped, looked for top level and under every app.
|
|
591
|
+
A different name for the same value is parity, not a violation.
|
|
592
|
+
"""
|
|
593
|
+
bare = name[len("RL_ENV_"):] if name.startswith("RL_ENV_") else name
|
|
594
|
+
mapped = ENV_TO_CONFIG_KEY.get(bare) or ENV_TO_CONFIG_KEY.get(name)
|
|
595
|
+
if mapped:
|
|
596
|
+
return _config_has_path(config, mapped)
|
|
597
|
+
key = bare.lower()
|
|
598
|
+
return _config_has_path(config, key) or _config_has_path(config, f"apps.*.{key}")
|
|
599
|
+
|
|
600
|
+
|
|
601
|
+
# The keys csync requires of every config.yaml, which _rule_mandatory_keys
|
|
602
|
+
# enforces a few hundred lines below. They are the one case the settings layer
|
|
603
|
+
# cannot answer for: csync demands them whether or not this app reads them, so
|
|
604
|
+
# an app that ignores one has still not got a dead key.
|
|
605
|
+
#
|
|
606
|
+
# Kept honest by test_every_required_key_is_actually_required, which deletes
|
|
607
|
+
# each entry from a valid config and asserts mandatory_keys complains. An entry
|
|
608
|
+
# that stopped being required would fail that test rather than quietly start
|
|
609
|
+
# hiding orphans -- which is exactly how a hand-written "frontend" came to hide
|
|
610
|
+
# a dead key in two environments for two months.
|
|
611
|
+
REQUIRED_BY_CSYNC = frozenset({
|
|
612
|
+
"project_name", "control_hub_url",
|
|
613
|
+
"basic_auth", "basic_auth.enabled", "basic_auth.keys",
|
|
614
|
+
"apps", "apps.*", "apps.*.app_url", "apps.*.login", "apps.*.login.user_id",
|
|
615
|
+
})
|
|
616
|
+
|
|
617
|
+
|
|
618
|
+
def _config_leaf_paths(config, prefix: str = ""):
|
|
619
|
+
"""Every leaf path in config.yaml, with the app name folded to '*'."""
|
|
620
|
+
if isinstance(config, dict) and config:
|
|
621
|
+
for key, value in config.items():
|
|
622
|
+
head = "*" if prefix == "apps" else str(key)
|
|
623
|
+
yield from _config_leaf_paths(value, f"{prefix}.{head}" if prefix else head)
|
|
624
|
+
elif prefix:
|
|
625
|
+
yield prefix
|
|
626
|
+
|
|
627
|
+
|
|
628
|
+
def _is_platform_path(path: str) -> bool:
|
|
629
|
+
return path in REQUIRED_BY_CSYNC
|
|
630
|
+
|
|
631
|
+
|
|
632
|
+
def _config_path_is_read(root: Path, config, path: str) -> bool:
|
|
633
|
+
"""Does anything consume this config.yaml path?
|
|
634
|
+
|
|
635
|
+
Three consumers, and any one is enough:
|
|
636
|
+
|
|
637
|
+
csync requires it of every environment (REQUIRED_BY_CSYNC)
|
|
638
|
+
the app through its settings layer, where an env alias names the
|
|
639
|
+
value it overrides -- the forward direction's mapping,
|
|
640
|
+
backwards
|
|
641
|
+
the container docker/start.sh and friends read config.yaml too, which a
|
|
642
|
+
hardcoded list of names cannot keep up with: rl_monday's
|
|
643
|
+
`frontends` is read six times in start.sh and nowhere else,
|
|
644
|
+
and an allowlist missing it blocked the build
|
|
645
|
+
|
|
646
|
+
The last is why this asks the repo rather than a list. A key whose name
|
|
647
|
+
appears nowhere outside config.yaml is the only one reported, and the
|
|
648
|
+
evidence for that comes from the clone, not from a table someone has to
|
|
649
|
+
remember to update.
|
|
650
|
+
"""
|
|
651
|
+
if _is_platform_path(path):
|
|
652
|
+
return True
|
|
653
|
+
for name in declared_env_aliases(root):
|
|
654
|
+
bare = name[len("RL_ENV_"):] if name.startswith("RL_ENV_") else name
|
|
655
|
+
mapped = ENV_TO_CONFIG_KEY.get(bare) or ENV_TO_CONFIG_KEY.get(name)
|
|
656
|
+
if mapped == path or (not mapped and bare.lower() in (path, path.rsplit(".", 1)[-1])):
|
|
657
|
+
return True
|
|
658
|
+
return _named_in_settings_layer(root, path)
|
|
659
|
+
|
|
660
|
+
|
|
661
|
+
def _ancestor_blocks(path: str):
|
|
662
|
+
"""The blocks this key sits inside, innermost first.
|
|
663
|
+
|
|
664
|
+
"apps.*.mcp_servers.catalog.enabled" yields the catalog block and the
|
|
665
|
+
mcp_servers block. Not "apps" or "apps.*": every settings layer names
|
|
666
|
+
those -- it is how they reach the per-app block -- and treating them as
|
|
667
|
+
ancestors would excuse every per-app key ever written.
|
|
668
|
+
"""
|
|
669
|
+
parts = path.split(".")
|
|
670
|
+
for cut in range(len(parts) - 1, 0, -1):
|
|
671
|
+
block = ".".join(parts[:cut])
|
|
672
|
+
if block in ("apps", "apps.*"):
|
|
673
|
+
break
|
|
674
|
+
yield block
|
|
675
|
+
|
|
676
|
+
|
|
677
|
+
def _named_in_settings_layer(root: Path, path: str) -> bool:
|
|
678
|
+
"""Is this key, or a block containing it, used in the settings layer?
|
|
679
|
+
|
|
680
|
+
SETTINGS_LAYER is where config.yaml is read -- docker/start.sh shells out
|
|
681
|
+
to runtime_config rather than parsing YAML -- so a key nothing there names
|
|
682
|
+
is read by nothing in this repo.
|
|
683
|
+
|
|
684
|
+
Ancestors count, because an accessor usually takes a block whole:
|
|
685
|
+
cfg_mcp_servers() reads the mcp_servers map and never names the "port"
|
|
686
|
+
inside apps.app.mcp_servers.catalog. Checking leaves alone reported valid
|
|
687
|
+
platform config as unused.
|
|
688
|
+
|
|
689
|
+
Matched as a whole identifier, not a substring: "mode" is inside "model".
|
|
690
|
+
The root-key fallback covers a block read whole at the top level --
|
|
691
|
+
rl_monday reads frontends_registry() and never names "nextjs" -- and is
|
|
692
|
+
skipped for "apps" for the reason in _ancestor_blocks.
|
|
693
|
+
"""
|
|
694
|
+
leaf = path.rsplit(".", 1)[-1]
|
|
695
|
+
root_key = path.split(".", 1)[0]
|
|
696
|
+
if not leaf or leaf == "*":
|
|
697
|
+
return True
|
|
698
|
+
|
|
699
|
+
names = {leaf}
|
|
700
|
+
if root_key not in ("apps",):
|
|
701
|
+
names.add(root_key)
|
|
702
|
+
for block in _ancestor_blocks(path):
|
|
703
|
+
names.add(block.rsplit(".", 1)[-1])
|
|
704
|
+
names.discard("*")
|
|
705
|
+
if not names:
|
|
706
|
+
return True
|
|
707
|
+
|
|
708
|
+
pattern = re.compile(r"\b(" + "|".join(re.escape(n) for n in sorted(names)) + r")\b")
|
|
709
|
+
for rel in SETTINGS_LAYER:
|
|
710
|
+
f = root / rel
|
|
711
|
+
if not repo_file(root, f):
|
|
712
|
+
continue
|
|
713
|
+
try:
|
|
714
|
+
text = read_repo_file(root, f)
|
|
715
|
+
except Exception:
|
|
716
|
+
continue
|
|
717
|
+
if pattern.search(text):
|
|
718
|
+
return True
|
|
719
|
+
return False
|
|
720
|
+
|
|
721
|
+
|
|
722
|
+
def _rule_env_config_parity(repo: _Repo) -> RuleResult:
|
|
723
|
+
"""Every env var the settings layer accepts must be declared in config.yaml.
|
|
724
|
+
|
|
725
|
+
The mirror of env_reads. That rule asks whether code bypasses config; this asks
|
|
726
|
+
whether everything the app can be configured with is actually written down. An
|
|
727
|
+
AliasChoices name with no config key is a setting that exists only in someone's
|
|
728
|
+
shell -- undiscoverable from a fresh clone, invisible to anyone reading
|
|
729
|
+
config.yaml to learn what this environment takes.
|
|
730
|
+
"""
|
|
731
|
+
r = RuleResult("env_config_parity")
|
|
732
|
+
if repo.config is None:
|
|
733
|
+
r.not_applicable = "config.yaml missing or unparseable (the presence/schema rules own that)"
|
|
734
|
+
return r
|
|
735
|
+
cfg_rel = "backend/app/config.py"
|
|
736
|
+
_report_unread_config_keys(repo, r)
|
|
737
|
+
# FOO and RL_ENV_FOO are two spellings of one setting; report the setting once.
|
|
738
|
+
missing: Dict[str, List[str]] = {}
|
|
739
|
+
for name in sorted(declared_env_aliases(repo.root)):
|
|
740
|
+
bare = name[len("RL_ENV_"):] if name.startswith("RL_ENV_") else name
|
|
741
|
+
if bare in PLATFORM_VARS or _declares_env_var(repo.config, name):
|
|
742
|
+
continue
|
|
743
|
+
missing.setdefault(bare, []).append(name)
|
|
744
|
+
for bare, names in sorted(missing.items()):
|
|
745
|
+
expected = ENV_TO_CONFIG_KEY.get(bare, bare.lower())
|
|
746
|
+
r.findings.append(Finding(
|
|
747
|
+
"env_config_parity",
|
|
748
|
+
f"{' / '.join(names)} can configure this environment but config.yaml never "
|
|
749
|
+
f"declares it; expected a '{expected}' key. The value exists only where "
|
|
750
|
+
"someone exports it.",
|
|
751
|
+
cfg_rel, 0,
|
|
752
|
+
))
|
|
753
|
+
return r
|
|
754
|
+
|
|
755
|
+
|
|
756
|
+
|
|
757
|
+
def _report_unread_config_keys(repo: _Repo, r: RuleResult) -> None:
|
|
758
|
+
"""The other direction: a key config.yaml declares that nothing consumes.
|
|
759
|
+
|
|
760
|
+
The pair of this rule's first half. That half catches a setting the app
|
|
761
|
+
accepts but the file never mentions -- configurable only from someone's
|
|
762
|
+
shell. This half catches the reverse: a key sitting in the file that neither
|
|
763
|
+
the app nor csync ever reads, which is worse than useless, because the next
|
|
764
|
+
person to edit it will believe they changed something.
|
|
765
|
+
|
|
766
|
+
Deliberately narrow. Most of config.yaml is read by csync rather than by the
|
|
767
|
+
app, so "the settings layer does not load it" is not evidence of anything --
|
|
768
|
+
every key in the fleet's twelve config files is consumed by one side or the
|
|
769
|
+
other today, and this reports none of them. What it catches is a key outside
|
|
770
|
+
that vocabulary entirely: a leftover from a rename, or one copied from
|
|
771
|
+
another environment that this one never wired up.
|
|
772
|
+
"""
|
|
773
|
+
for path in sorted(set(_config_leaf_paths(repo.config))):
|
|
774
|
+
if _config_path_is_read(repo.root, repo.config, path):
|
|
775
|
+
continue
|
|
776
|
+
r.findings.append(Finding(
|
|
777
|
+
"env_config_parity",
|
|
778
|
+
f"config.yaml declares '{path}' but nothing reads it — neither this "
|
|
779
|
+
f"environment's settings layer nor csync itself. Wire it up, or remove "
|
|
780
|
+
f"it: a key that configures nothing still reads like it does.",
|
|
781
|
+
"config.yaml", 0,
|
|
782
|
+
))
|
|
783
|
+
|
|
784
|
+
RULES: Dict[str, Callable[[_Repo], RuleResult]] = {
|
|
785
|
+
"presence": _rule_presence,
|
|
786
|
+
"schema": _rule_schema,
|
|
787
|
+
"mandatory_keys": _rule_mandatory_keys,
|
|
788
|
+
"database_seed": _rule_database_seed,
|
|
789
|
+
"env_reads": _rule_env_reads,
|
|
790
|
+
"env_config_parity": _rule_env_config_parity,
|
|
791
|
+
"entrypoint_exports": _rule_entrypoint_exports,
|
|
792
|
+
"legacy_app_config": _rule_legacy_app_config,
|
|
793
|
+
}
|
|
794
|
+
|
|
795
|
+
|
|
796
|
+
def run_rules(repo_path: Path, enforce: Optional[Set[str]] = None,
|
|
797
|
+
scope: Optional[Scope] = None) -> RulesOutcome:
|
|
798
|
+
"""``enforce``: rule ids whose findings block; None means DEFAULT_ENFORCED."""
|
|
799
|
+
enforced = DEFAULT_ENFORCED if enforce is None else frozenset(enforce)
|
|
800
|
+
root = Path(repo_path)
|
|
801
|
+
repo = _Repo(root=root, scope=scope or file_scope("config_yaml_check"))
|
|
802
|
+
cfg_p = root / "config.yaml"
|
|
803
|
+
config_present = repo_file(root, cfg_p)
|
|
804
|
+
if config_present:
|
|
805
|
+
try:
|
|
806
|
+
import yaml
|
|
807
|
+
repo.config = yaml.safe_load(read_repo_file(root, cfg_p))
|
|
808
|
+
except Exception as exc: # a schema finding, not a crash
|
|
809
|
+
repo.config_error = f"{type(exc).__name__}: {str(exc)[:200]}"
|
|
810
|
+
repo.entrypoint = find_entrypoint(root, repo.scope)
|
|
811
|
+
repo.governed = governed_vars(root)
|
|
812
|
+
|
|
813
|
+
out = RulesOutcome(config_present=config_present)
|
|
814
|
+
for rule_id, rule in RULES.items():
|
|
815
|
+
mode = "enforce" if rule_id in enforced else "warn"
|
|
816
|
+
try:
|
|
817
|
+
result = rule(repo)
|
|
818
|
+
except Exception as exc:
|
|
819
|
+
result = RuleResult(rule_id, error=f"{type(exc).__name__}: {str(exc)[:200]}")
|
|
820
|
+
result.mode = mode
|
|
821
|
+
out.results.append(result)
|
|
822
|
+
out.settled = repo.settled
|
|
823
|
+
return out
|