From e05c541105198e5d528d7b7a9adf4a2982a468cd Mon Sep 17 00:00:00 2001 From: jackwjensen <48677596+jackwjensen@users.noreply.github.com> Date: Thu, 22 Oct 2026 21:27:56 +0200 Subject: [PATCH] Re-sync the pack at 2026.10.14-3 so CI's scanner tests run again The Lint job has failed on master since 2026-10-08, at "Scanner tests": test_standards_gitattributes.py read templates/.gitattributes from the repo root at import time -- a path only the pack itself has -- so pytest stopped at collection and the Verify step never ran. Both open Dependabot PRs fail on the same step; neither bump causes it. The pack fixed this on 2026-10-11 (f97558c) by shipping the template as engineering_standards/templates/.gitattributes. This re-runs the pack's installer (sync_pack.py --apply) rather than copying those files alone: the package is all-or-nothing, and a partial copy is an ImportError at commit. With the tests running, Verify reported one finding the pack has required since 2026-10-10: .gitignore ignored only `.env`. It now ignores `.env*` and re-admits `.env.example`. Verified: `pytest engineering_standards/` (1,308 passed) and `verify.py --strict`, both as CI runs them. Co-Authored-By: Claude Opus 5.5 --- .claude/rules/infrastructure.md | 37 ++- .claude/rules/secrets.md | 40 +-- .claude/rules/self-contained-repo.md | 2 +- .gitignore | 3 +- CHANGELOG.md | 5 + engineering_standards/check-source-limits.py | 62 +++- engineering_standards/standards_config.py | 3 +- .../standards_config_defaults.py | 117 +++++++ engineering_standards/standards_constants.py | 97 +----- engineering_standards/standards_deploy.py | 2 +- .../standards_deps_declared.py | 56 +++- .../standards_deps_lifecycle.py | 6 +- .../standards_deps_registry.py | 19 +- engineering_standards/standards_disclosure.py | 3 +- engineering_standards/standards_dispatch.py | 24 +- .../standards_exemption_report.py | 5 +- .../standards_exemption_scope.py | 2 + .../standards_gitattributes.py | 13 +- engineering_standards/standards_gitignore.py | 34 +- engineering_standards/standards_markdown.py | 4 +- engineering_standards/standards_scope.py | 80 +++-- engineering_standards/standards_secrets.py | 8 +- .../standards_seed_credentials.py | 208 ++++++++++++ engineering_standards/standards_versions.py | 2 +- .../templates/.gitattributes | 23 ++ engineering_standards/test_hook_blocks.py | 8 +- .../test_standards_baseline.py | 4 +- .../test_standards_config_defaults.py | 88 +++++ .../test_standards_constants.py | 61 +--- .../test_standards_deps_declared.py | 59 +++- .../test_standards_deps_pinning.py | 7 + .../test_standards_deps_registry.py | 15 + .../test_standards_deps_verdict.py | 16 + engineering_standards/test_standards_docs.py | 8 + .../test_standards_exemption_report.py | 8 + .../test_standards_gitattributes.py | 17 +- .../test_standards_layout.py | 37 ++- .../test_standards_readonly.py | 6 +- .../test_standards_secrets.py | 12 + .../test_standards_seed_credentials.py | 307 ++++++++++++++++++ engineering_standards/test_standards_tls.py | 2 +- engineering_standards/test_verify_cli.py | 4 +- 42 files changed, 1247 insertions(+), 267 deletions(-) create mode 100644 engineering_standards/standards_config_defaults.py create mode 100644 engineering_standards/standards_seed_credentials.py create mode 100644 engineering_standards/templates/.gitattributes create mode 100644 engineering_standards/test_standards_config_defaults.py create mode 100644 engineering_standards/test_standards_seed_credentials.py diff --git a/.claude/rules/infrastructure.md b/.claude/rules/infrastructure.md index c928652..79072ef 100644 --- a/.claude/rules/infrastructure.md +++ b/.claude/rules/infrastructure.md @@ -38,8 +38,8 @@ outside the compose file — remap freely to hit the assigned host number. |---|---|---| | **Frontend / the app's main entry point** | `8080` | all interfaces | | **Backend / admin / API / a second web surface** | `8081` | all interfaces | -| **Mail catcher — browsable inbox** | `1080` | all interfaces | -| **Mail catcher — SMTP the app delivers to** | `1025` | all interfaces | +| **Mail catcher — browsable inbox** | `1080` | **`127.0.0.1` only** | +| **Mail catcher — SMTP the app delivers to** | `1025` | **`127.0.0.1` only** | | **The app's database**, whatever the engine | `3307` | **`127.0.0.1` only** | | Cache / broker (Redis), *only if the host needs it* | `6380` | **`127.0.0.1` only** | | Everything else | **not published** | — | @@ -57,9 +57,15 @@ every webhook test. **The mail catcher is `1080`, and this reverses an earlier decision.** The convention was briefly MailHog's own default of `8025`, chosen so a stack adding MailHog out of the box would need no remapping. That optimised for the wrong thing: it made the port depend on *which tool* -caught the mail, when the whole registry is meant to depend on *what the port is for*. MailHog -therefore publishes `"1080:8025"`. The SMTP side needs no thought — MailHog and MailCatcher -both listen on `1025`. +caught the mail, when the whole registry is meant to depend on *what the port is for*. + +**The mail catcher's tool is fixed too: Mailpit** (`axllent/mailpit` at an exact tag, never +`:latest`), published as `"127.0.0.1:1080:8025"` and `"127.0.0.1:1025:1025"`. Fixing only the +ports let each repo take whatever was current — MailCatcher, MailHog, Mailpit all ran at once. +MailHog has had no release since 2020; Mailpit is maintained and moves through the dependency +gate like any image. One tool also means one API for headless mail tests: Mailpit's +`/api/v1/messages`. Migrating off MailHog moves its `/api/v2/messages` readers too — the JSON +shape differs. **The database is `3307` whatever the engine** — MySQL, PostgreSQL, anything. Same principle: one saved connection in a DB client serves every project, and "3307" means "the app I am @@ -115,6 +121,25 @@ fails on the laptop, and a runbook cannot name a container that only exists in o default in the compose file** — `${COMPOSE_PROJECT_NAME:-invotrack}-web` — because a repo with no `.env` in development expands the bare form to nothing and names the container `-web`. +### The project name gets the same fallback, as `name:` at the top of the base file + +```yaml +name: ${COMPOSE_PROJECT_NAME:-allegroit-dk} +``` + +**Every `docker-compose.yml` opens with this, with the site's identity as the default.** The +container-name default above is not enough on its own: without a `.env`, Compose takes the +*folder* name as the project. A git worktree never has a `.env`, since it is gitignored, so it +became its own project (measured on allegroit-dk, 2026-10-22: project, image and network all +named `php-8-5-12-0f94b3` after the worktree folder). Its literal `container_name`s stayed the +same as the main checkout's. Compose then saw two different projects fighting over one container +name: `up` in one fails with `Conflict. The container name ... is already in use`, and `down` in +one does not see the other's containers. + +The variable still wins wherever it is set, so the server's `.env` and a multi-instance repo +like WAPPIT (`wappit-api-staging`) behave exactly as before. The fallback covers only the +checkout that has no `.env`, and gives it the site's name instead of the folder's. + ### The service name is on the shared proxy network too A stack that joins `nginx-proxy-network` registers **both** its `container_name` and its *service @@ -139,7 +164,7 @@ the service key. **Only proxy-facing services need the unified name.** The collision this fixes is on `nginx-proxy-network`, so it applies to the service that joins it — the web one. A `mysql`, -`redis` or `mailhog` service lives on the project's own `default` network, which is per-project +`redis` or `mailpit` service lives on the project's own `default` network, which is per-project and cannot collide, so it keeps its short generic key and only needs a distinct `container_name` for `docker ps` to be readable. **Do not rename an internal service for tidiness**: the service key *is* the DNS name its siblings connect to, so renaming `mysql` to diff --git a/.claude/rules/secrets.md b/.claude/rules/secrets.md index 9239ea5..5e43275 100644 --- a/.claude/rules/secrets.md +++ b/.claude/rules/secrets.md @@ -33,7 +33,10 @@ In rough order of preference. Pick the first that fits the stack. 2. **A gitignored `.env`.** Fine, and the estate already relies on it — but only the repo's own `.gitignore` counts; a global ignore is a backstop that does not travel with the clone (`self-contained-repo.md`). Check with it off: `git -c core.excludesFile= check-ignore -v .env`. - `.env.example` is committed and carries the **key names with empty values**. + **Ignore every copy: `.env*`** (`gitignore-build-output` enforces it) — a copy is the same + credential; on 2026-10-10 a `.env.bak-staging` sat unignored in a production checkout, one + `git add -A` from a push. Admit the example on purpose with `!.env.example`. Never back up a + `.env`: a fresh `.env.example` plus the secret store restores everything in it. 3. **Generated at first run and printed once.** The strongest option where it fits: nothing to leak because nothing was written down. Good for a first-admin bootstrap, awkward for a demo cast that documentation names. @@ -47,28 +50,26 @@ In rough order of preference. Pick the first that fits the stack. example, and its lesson applies here: make it *obviously* fake, because a realistic-looking one invites somebody to "fix" it into a real credential. -## Seeders read credentials; they never contain them +## Seed test systems through an explicit local step — never through configuration -A seeder needs a password to hash, so it takes one — from configuration, never a literal — and -it **refuses rather than defaulting**: a fallback to a built-in value is the committed value -that then gets used wherever nobody set the variable. Throw and name the missing key -(`configuration["Demo:Password"] ?? throw ...`). Two more: **hash it, never store it**, even for -demo data; and **gate it on the environment**, with the guard in the seeder rather than the -caller's good intentions. +Test systems are seeded; the **mechanism** is the rule. A seeder, restore or app that reads an +account password from `.env`, a compose variable or an app setting is a standing "set a +password, get an admin" path on every machine that runs it — whoever can set that value gets +in (`seeded-credential-config` flags the key). Instead (snippets: `templates/seed-users/`): -**And it validates what it was given.** Writing a hash directly skips the framework's password -validators, so a placeholder value yields an account holding a password the application would -refuse — measured: a demo admin whose password was its own e-mail address, three database wipes -before anyone found out. Check configured credentials against the *real* validators at startup; -refuse to start otherwise, naming the failing rule and never the value. +- **A seed command with no values**: reads the accounts as JSON on **stdin**, **refuses unless + the system is local** (guard in the command, not the caller), validates each password against + the *real* validators (a direct hash skips them — a demo admin once held its own e-mail + address as password), **hashes, never stores**, prints only names. +- **A PC-side wrapper** pipes the values file into it; on a server there is nothing to pipe. +- **Logins without the password**: a local-only, single-use, short-lived link — never typed into + a browser through a tool call. **A live guard** fails if the test accounts exist in production. ## The estate's standard local accounts -`localadmin@allegroit.dk` and `localuser@allegroit.dk` are seeded in every repo that needs a -local superadmin or a plain test user, so that one set of credentials works everywhere. **The -addresses may be committed; the passwords may not.** Their values live in the identity notes -under `~/.claude/memory/` — which is exactly the split this file describes, and the reason the -values are in memory rather than in any repo. +`localadmin@allegroit.dk` and `localuser@allegroit.dk` are seeded that way wherever a repo needs +a local login. **The addresses may be committed; the passwords may not**, not even as an empty +key: they are in `~/.claude/shared/dev-seed-users.secret.json`, piped unread, never read by Claude. ## A secret must never reach the client, git or no git @@ -90,7 +91,6 @@ git diff --cached | grep -iE 'password|secret|api[_-]?key|token' ``` A hit is not automatically wrong — a key *name* is fine — but every hit deserves the question. -And when a credential has already been committed, rotating it is part of the fix, not an -optional follow-up: history keeps the old one whatever the working tree says. +A committed credential is rotated as part of the fix: history keeps it whatever the tree says. Source of truth: engineering-standards/claude/rules/secrets.md diff --git a/.claude/rules/self-contained-repo.md b/.claude/rules/self-contained-repo.md index b91b092..a361509 100644 --- a/.claude/rules/self-contained-repo.md +++ b/.claude/rules/self-contained-repo.md @@ -23,7 +23,7 @@ the next — usually without saying why, because the failure is in what is *abse | Toolchain version | `global.json`, `.python-version`, `.nvmrc`, `packageManager`, `require.php` | | Repo-local tools and dev dependencies | `.config/dotnet-tools.json`, `requirements*.txt` or a `pyproject.toml` dev group, `devDependencies`, `require-dev` | | The pack's own prerequisites | `engineering_standards/requirements.txt`, shipped with the pack | -| Ignore rules | the repo's own `.gitignore`, `.env` included (`gitignore-missing` reads only that file) | +| Ignore rules | the repo's own `.gitignore`, every `.env*` copy included and `!.env.example` re-admitted on purpose (`gitignore-missing` reads only that file) | | Commit gate | `engineering_standards/hooks/` plus the bootstrap that points git at them | | Configuration keys | `.env.example`: every key, empty values | | The one documented step | the README: clone → `.env` → build → test → run, every command spelled out | diff --git a/.gitignore b/.gitignore index 3f07623..2e23394 100644 --- a/.gitignore +++ b/.gitignore @@ -7,7 +7,8 @@ !.claude/rules/ # Environment -.env +.env* +!.env.example # WordPress uploads (synced separately, not in git) wp-content/uploads/* diff --git a/CHANGELOG.md b/CHANGELOG.md index 00486c7..fa0107a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -131,6 +131,11 @@ database). - `dev.bat cli` passed the word `cli` on to WP-CLI. - Line endings are pinned in `.gitattributes`: a clone without `core.autocrlf=true` checked the batch files out LF-only, where cmd can miss their labels. +- CI's scanner tests are green again: the pack copy (2026.10.08-2) read its + `.gitattributes` template from a path only the pack itself has. Re-synced to pack + 2026.10.14-3, which ships the template in `engineering_standards/templates/`. +- `.gitignore` ignores every `.env*` file, not only `.env` (`.env.example` stays + tracked) — a `.env.local` or `.env.bak` holds the same credentials. ## [1.0.0] - 2026-06-22 diff --git a/engineering_standards/check-source-limits.py b/engineering_standards/check-source-limits.py index f6ea0d3..720a0c7 100644 --- a/engineering_standards/check-source-limits.py +++ b/engineering_standards/check-source-limits.py @@ -18,7 +18,8 @@ (an exception's own text or a bare status code reaching the user -- see standards_user_errors.py), the constants family (config-default-in-code, const-environment-literal, plus const-duplicated-literal on -whole-tree scans -- see standards_constants.py), the deployment-contract family (compose-port, +whole-tree scans -- see standards_config_defaults.py and standards_constants.py), the +deployment-contract family (compose-port, compose-container-name, compose-overlay-name, deploy-gate, env-example-compose), plus the documentation family on whole-tree scans (docs-missing, docs-frontmatter, docs-broken-link, docs-orphan-page, docs-stale-symbol, claude-md-length -- see @@ -58,6 +59,7 @@ import argparse import sys from pathlib import Path +from typing import NamedTuple # Import the sibling module by path rather than relying on the caller's cwd: the commit # hook and the CI job both invoke this script from the repo root, not from engineering_standards/. @@ -82,7 +84,7 @@ Violation, ) from standards_coverage import check_coverage # noqa: E402 (same reason) -from standards_dispatch import check_source_file # noqa: E402 (same reason) +from standards_dispatch import check_migration_file, check_source_file # noqa: E402 (same reason) from standards_docs import check_documentation # noqa: E402 (same reason) from standards_exemption_report import ( # noqa: E402 (same reason) collect_exemptions, @@ -102,13 +104,24 @@ from standards_registry import NEVER_BASELINED, TOOLCHAINS # noqa: E402,F401 (same reason) from standards_repository import repository_violations # noqa: E402 (same reason) from standards_rules import check_rules # noqa: E402 (same reason) -from standards_scope import should_check # noqa: E402 (same reason) +from standards_scope import should_check, should_check_migration # noqa: E402 (same reason) from standards_tests import check_tests_cover_modules # noqa: E402 (same reason) from standards_userdocs import check_userdocs, unsynced_change_notes # noqa: E402 (same reason) -def candidate_files(root: Path, config: CheckConfig, only: list[Path] | None = None) -> list[Path]: - """Every in-scope file, or the in-scope subset of `only`. +class ScanScope(NamedTuple): + """What one run reads: the in-scope files, and the migrations only a few rules may see.""" + + paths: list[Path] + migrations: list[Path] + + +def candidate_files(root: Path, config: CheckConfig, only: list[Path] | None = None) -> ScanScope: + """Every in-scope file, or the in-scope subset of `only` -- plus the migrations among them. + + The migrations come out of the SAME walk rather than a second one: in a consumer with a + `node_modules/` the walk is the expensive half of a scan, and two resolvers would also be + two answers to "what was examined". `should_check_migration` explains why they exist. One resolver for all three collectors, so a scoped run cannot accidentally walk the tree for exemptions while checking a subset for violations -- the two would then @@ -117,8 +130,8 @@ def candidate_files(root: Path, config: CheckConfig, only: list[Path] | None = N `only` is filtered through the same `should_check` predicate rather than trusted: a staged path may be a deleted file, a submodule, or something the scanner is not - supposed to read (a migration, vendored code), and naming it explicitly does not make - it in scope. + supposed to read (vendored code), and naming it explicitly does not make it in scope. A + staged migration is filtered the same way, into the migration route and nothing more. FILES GIT IGNORES ARE NOT SCANNED. The walk reads the filesystem, but every rule here is about what a repository CONTAINS -- so a path git is told to ignore, and does not @@ -140,8 +153,12 @@ def candidate_files(root: Path, config: CheckConfig, only: list[Path] | None = N paths = [path for path in paths if path.is_relative_to(root)] ignored = ignored_files(root) + files = [path for path in paths if path.is_file() and path not in ignored] - return [path for path in paths if path.is_file() and path not in ignored and should_check(path, root, config)] + return ScanScope( + [path for path in files if should_check(path, root, config)], + [path for path in files if should_check_migration(path, root, config)], + ) def collect_oversized_files(root: Path, config: CheckConfig, paths: list[Path]) -> dict[str, int]: @@ -173,12 +190,13 @@ def write_baseline( that gates a write are standards_baseline.py's. Scope narrowing is ignored on purpose -- see write_baseline_file for what a partial baseline silently destroys. """ - paths = candidate_files(root, config) + scope = candidate_files(root, config) + paths = scope.paths oversized = collect_oversized_files(root, config, paths) member_violations = sorted( violation_key(violation, root) for violation in ( - *collect_violations(root, config, oversized, paths), + *collect_violations(root, config, oversized, scope), *check_documentation(root, config), *check_coverage(root, config), *check_userdocs(root, config), @@ -195,16 +213,21 @@ def write_baseline( return write_baseline_file(baseline_path, config, oversized, member_violations, consent_flag) -def collect_violations(root: Path, config: CheckConfig, baseline: dict[str, int], paths: list[Path]) -> list[Violation]: +def collect_violations(root: Path, config: CheckConfig, baseline: dict[str, int], scope: ScanScope) -> list[Violation]: violations: list[Violation] = [] - for path in paths: + for path in scope.paths: lines = read_source_lines(path) if lines is None: continue violations.extend(check_source_file(path, lines, config, baseline, root)) + for path in scope.migrations: + lines = read_source_lines(path) + if lines is not None: + violations.extend(check_migration_file(path, lines)) + return violations @@ -330,7 +353,7 @@ def baseline_argument_error(arguments: argparse.Namespace) -> int | None: def print_summary( root: Path, config: CheckConfig, - paths: list[Path], + scope: ScanScope, only: list[Path] | None, remaining: list[Violation], grandfathered: list[Violation], @@ -345,7 +368,9 @@ def print_summary( for setting, value, reason in config.tuning: print(f"tuned: {setting} = {value} -- {reason}") - exemptions = collect_exemptions(root, config, paths) + # File-scoped markers only, and no rule on the migration route reads one -- so a marker in + # a migration would be printed here as honoured while nothing honours it. + exemptions = collect_exemptions(root, config, scope.paths) for relative, rule, reason in exemptions: print(f"exempt: {relative} [{rule}] -- {reason}") @@ -355,7 +380,7 @@ def print_summary( print(f"\ncheck-source-limits: {len(remaining)} violation(s)", file=sys.stderr) return 1 - notes = [f"{len(paths)} file(s)" if only is not None else "whole tree"] + notes = [f"{len(scope.paths) + len(scope.migrations)} file(s)" if only is not None else "whole tree"] if grandfathered: notes.append(f"{len(grandfathered)} grandfathered") if exemptions: @@ -400,7 +425,8 @@ def main(argv: list[str]) -> int: if scope_error: return scope_error - paths = candidate_files(root, config, only) + scope = candidate_files(root, config, only) + paths = scope.paths # Named rather than silently tolerated: these are the only files where reading the # working tree can disagree with what is actually being committed. @@ -414,7 +440,7 @@ def main(argv: list[str]) -> int: oversized_baseline, known_violations = {}, set() else: oversized_baseline, known_violations = load_baseline(baseline_path) - violations = collect_violations(root, config, oversized_baseline, paths) + violations = collect_violations(root, config, oversized_baseline, scope) # The one check about the REPOSITORY rather than about a file, so it runs only on a # whole-tree scan. Running it at commit would block every commit in a repo whose @@ -445,7 +471,7 @@ def main(argv: list[str]) -> int: return print_summary( root, config, - paths, + scope, only, remaining, grandfathered, diff --git a/engineering_standards/standards_config.py b/engineering_standards/standards_config.py index 8652c57..f22571b 100644 --- a/engineering_standards/standards_config.py +++ b/engineering_standards/standards_config.py @@ -356,7 +356,8 @@ class CheckConfig: # The judgment layer judged as a budget -- see standards_rules.py. On by default in every # repo, because the cost it measures is paid in every repo that received the rules. check_rules: bool = True - # Where a value that may change is allowed to live -- see standards_constants.py. One flag + # Where a value that may change is allowed to live -- see standards_config_defaults.py and + # standards_constants.py. One flag # for all three shapes, because a repo that genuinely disagrees disagrees with the premise # rather than with one detector. Off is a real answer for a repo with no deployment of its # own -- a library, a shared schema package -- where "read it from the environment" names diff --git a/engineering_standards/standards_config_defaults.py b/engineering_standards/standards_config_defaults.py new file mode 100644 index 0000000..2fecf64 --- /dev/null +++ b/engineering_standards/standards_config_defaults.py @@ -0,0 +1,117 @@ +#!/usr/bin/env python3 +"""`config-default-in-code`: a configuration read whose fallback is a literal. + +The value already IS configuration, so a literal fallback is a second copy of it in the source +-- the committed-credential shape from `secrets.md` generalised past credentials. One of the +three "values that change" rules; the other two judge constant DECLARATIONS and live in +`standards_constants.py`, while this one judges configuration READS. Split out 2026-10-22, when +that module reached its 500-line limit with this rule's first real change; the reasoning shared +by all three is `docs/values-that-change.md`, and none of it is restated here. + +KNOWN BLIND SPOT. The rule reads one line at a time, so a fallback reached through a HELPER is +invisible to it -- neither line of `Stated(app.Configuration, KEY) ?? (isDev ? Fallback : null)` +carries both an accessor and a literal. `const-environment-literal` catches that case from the +declaration side instead; where the value's shape gives nothing away it is judgment. + +Source of truth: engineering-standards/engineering_standards/standards_config_defaults.py +""" + +from __future__ import annotations + +import re +from pathlib import Path +from typing import Iterable + +from standards_constants import CONSTANT_SUFFIXES, _clip, _is_test_path +from standards_core import Violation, iter_code_lines + +CONFIG_DEFAULT_RULE = "config-default-in-code" + +# PHP's $_SERVER holds two things in one array. Under php-fpm it carries the process +# environment -- configuration, which this rule is about. It ALSO carries the request: the CGI +# meta-variables (RFC 3875 section 4.1), every header as HTTP_*, and PHP's own script +# bookkeeping. Those are data the client or the server just sent, so `$_SERVER['REQUEST_URI'] +# ?? '/'` guards a missing request field rather than copying a setting. Reading them as +# configuration fired four times on jacks_corner's front controller (2026-10-22), none of them +# configuration, with no line exemption to clear them. +# +# Prefixes end in `_` and whole names must be followed by the closing quote, so an environment +# variable that merely starts like one (`HTTPS_PROXY`) is still configuration. A dynamic key, +# `$_SERVER[$name]`, stays in scope: nothing here can say which half of the array it reads. +SERVER_REQUEST_PREFIXES = ("HTTP_", "REQUEST_", "REMOTE_", "SERVER_", "SCRIPT_", "PHP_") +SERVER_REQUEST_NAMES = ( + "QUERY_STRING", "DOCUMENT_ROOT", "DOCUMENT_URI", "CONTENT_TYPE", "CONTENT_LENGTH", + "PATH_INFO", "PATH_TRANSLATED", "GATEWAY_INTERFACE", "AUTH_TYPE", "HTTPS", "argv", "argc", +) # fmt: skip +SERVER_REQUEST_KEY = "(?:" + "|".join(SERVER_REQUEST_PREFIXES) + "|(?:" + "|".join(SERVER_REQUEST_NAMES) + ")[\"'])" + +# The accessors that mean "this value is configuration". Matched anywhere on the line, then +# the fallback is looked for separately -- two conditions rather than one long pattern, so a +# new accessor spelling is one entry rather than a rewrite. +CONFIG_ACCESSORS = re.compile( + r"""(?x) + \bConfiguration\s*\[ # C#: Configuration["Key"], builder.Configuration[...] + | \bconfiguration\s*\[ + | \.GetConnectionString\s*\( + | \.GetValue\s*< # C#: GetValue("Key", "default") + | \bos\.environ\b | \benviron\.get\s*\( # Python + | \bos\.getenv\s*\( | \bgetenv\s*\( # Python / PHP + | \$_ENV\s*\[ # PHP + | \$_SERVER\s*\[(?!\s*["']REQUEST_KEY) # PHP: the environment half only, see above + | \bprocess\.env\b # JS / TS + """.replace("REQUEST_KEY", SERVER_REQUEST_KEY) +) + +# A fallback to a LITERAL. `?? "x"`, `or "x"`, `?: 'x'`, `|| "x"`, and the positional default +# of a getter call (`getenv("KEY", "default")`). +LITERAL_FALLBACK = re.compile( + r"""(?x) + (?:\?\?|\?:|\|\||\bor\b)\s*(?P["'])(?P(?:(?!\1).)*)(?P=quote) + | ,\s*(?P["'])(?P(?:(?!\3).)*)(?P=q2)\s*\) + """ +) + +# `?? throw ...` is the shape `secrets.md` MANDATES for a seeder, and `?? null` is not a +# default at all. Neither may ever be reported, or the rule would fire on the correct answer. +CORRECT_FALLBACKS = re.compile(r"(?:\?\?|\?:|\|\|)\s*(?:throw\b|null\b|None\b|undefined\b)") + + +def check_config_default(path: Path, lines: list[str]) -> Iterable[Violation]: + """A configuration read whose fallback is a literal written into the source. + + Test files are out of scope -- see `_is_test_path` for why the whole family skips them. + Here the reason is sharper than elsewhere: a scanner's OWN test files contain fixture + source as string literals, so this rule reads its own examples back as findings. Measured + on this pack, where `test_standards_debugflag.py`'s fixture `os.environ.get('DEBUG')` was + reported as a configuration default. + """ + if path.suffix not in CONSTANT_SUFFIXES or _is_test_path(path): + return + + for line_number, line in iter_code_lines(lines, path.suffix): + if not CONFIG_ACCESSORS.search(line): + continue + if CORRECT_FALLBACKS.search(line): + continue + + match = LITERAL_FALLBACK.search(line) + if match is None: + continue + + value = match.group("value") or match.group("v2") or "" + # An empty-string default is "absent", not an invented value, and is how a great deal + # of correct code spells "no override". Reporting it would train people to ignore this. + if value.strip() == "": + continue + + yield Violation( + path=path, + line=line_number, + rule=CONFIG_DEFAULT_RULE, + message=( + f"A configuration read falls back to the literal '{_clip(value)}'. The value " + f"already IS configuration, so this is a second copy of it that changes only " + f"when somebody deploys. State it in the environment file instead, or throw " + f"and name the missing key." + ), + ) diff --git a/engineering_standards/standards_constants.py b/engineering_standards/standards_constants.py index 5b01906..57ba972 100644 --- a/engineering_standards/standards_constants.py +++ b/engineering_standards/standards_constants.py @@ -14,23 +14,21 @@ classes these detectors had to lose, and what was deliberately NOT implemented are in `docs/values-that-change.md`. None of that is restated here -- a rule in two layers drifts. -Three shapes. The first two are per-file; the third is repo-level and runs from -`standards_repository.py`, because no per-file rule can see the other file: +Three shapes. The first, which judges configuration READS rather than declarations, lives in +`standards_config_defaults.py` (split out 2026-10-22). The other two are here: the first is +per-file, the second repo-level, running from `standards_repository.py` because no per-file +rule can see the other file: - * `config-default-in-code` -- a configuration read whose fallback is a literal. The value - already IS configuration and there is a second copy of it in the source, which is the - committed-credential shape from `secrets.md` generalised past credentials. + * `config-default-in-code` -- a configuration read whose fallback is a literal; see + `standards_config_defaults.py`. * `const-environment-literal` -- a constant whose VALUE is environment-specific by its own shape: an e-mail address, an absolute filesystem path, a URL or a host:port. * `const-duplicated-literal` -- one value with two homes, or a constant written raw in another file. It reads the tree twice, and it honours its own line exemptions rather than relying on the driver's filter, which only ever sees the per-file walk's findings. -KNOWN BLIND SPOT, stated here because it is load-bearing for the first rule. -`config-default-in-code` reads one line at a time, so a fallback reached through a HELPER is -invisible to it -- neither line of `Stated(app.Configuration, KEY) ?? (isDev ? Fallback : null)` -carries both an accessor and a literal. `const-environment-literal` catches that case from the -declaration side instead; where the value's shape gives nothing away it is judgment. +`const-environment-literal` is also what catches a configuration fallback reached through a +helper, which `config-default-in-code` cannot see -- the blind spot is stated in that module. Source of truth: engineering-standards/engineering_standards/standards_constants.py """ @@ -45,7 +43,6 @@ from standards_exemptions import line_exemption_reason from standards_scope import SCRIPT_SUFFIXES -CONFIG_DEFAULT_RULE = "config-default-in-code" ENVIRONMENT_LITERAL_RULE = "const-environment-literal" DUPLICATED_LITERAL_RULE = "const-duplicated-literal" @@ -53,79 +50,6 @@ # language here; only the syntax differs. CONSTANT_SUFFIXES = (".cs", ".razor", ".py", ".php", *SCRIPT_SUFFIXES) -# ---- config-default-in-code ------------------------------------------------------------- - -# The accessors that mean "this value is configuration". Matched anywhere on the line, then -# the fallback is looked for separately -- two conditions rather than one long pattern, so a -# new accessor spelling is one entry rather than a rewrite. -CONFIG_ACCESSORS = re.compile( - r"""(?x) - \bConfiguration\s*\[ # C#: Configuration["Key"], builder.Configuration[...] - | \bconfiguration\s*\[ - | \.GetConnectionString\s*\( - | \.GetValue\s*< # C#: GetValue("Key", "default") - | \bos\.environ\b | \benviron\.get\s*\( # Python - | \bos\.getenv\s*\( | \bgetenv\s*\( # Python / PHP - | \$_ENV\s*\[ | \$_SERVER\s*\[ # PHP - | \bprocess\.env\b # JS / TS - """ -) - -# A fallback to a LITERAL. `?? "x"`, `or "x"`, `?: 'x'`, `|| "x"`, and the positional default -# of a getter call (`getenv("KEY", "default")`). -LITERAL_FALLBACK = re.compile( - r"""(?x) - (?:\?\?|\?:|\|\||\bor\b)\s*(?P["'])(?P(?:(?!\1).)*)(?P=quote) - | ,\s*(?P["'])(?P(?:(?!\3).)*)(?P=q2)\s*\) - """ -) - -# `?? throw ...` is the shape `secrets.md` MANDATES for a seeder, and `?? null` is not a -# default at all. Neither may ever be reported, or the rule would fire on the correct answer. -CORRECT_FALLBACKS = re.compile(r"(?:\?\?|\?:|\|\|)\s*(?:throw\b|null\b|None\b|undefined\b)") - - -def check_config_default(path: Path, lines: list[str]) -> Iterable[Violation]: - """A configuration read whose fallback is a literal written into the source. - - Test files are out of scope -- see `_is_test_path` for why the whole family skips them. - Here the reason is sharper than elsewhere: a scanner's OWN test files contain fixture - source as string literals, so this rule reads its own examples back as findings. Measured - on this pack, where `test_standards_debugflag.py`'s fixture `os.environ.get('DEBUG')` was - reported as a configuration default. - """ - if path.suffix not in CONSTANT_SUFFIXES or _is_test_path(path): - return - - for line_number, line in iter_code_lines(lines, path.suffix): - if not CONFIG_ACCESSORS.search(line): - continue - if CORRECT_FALLBACKS.search(line): - continue - - match = LITERAL_FALLBACK.search(line) - if match is None: - continue - - value = match.group("value") or match.group("v2") or "" - # An empty-string default is "absent", not an invented value, and is how a great deal - # of correct code spells "no override". Reporting it would train people to ignore this. - if value.strip() == "": - continue - - yield Violation( - path=path, - line=line_number, - rule=CONFIG_DEFAULT_RULE, - message=( - f"A configuration read falls back to the literal '{_clip(value)}'. The value " - f"already IS configuration, so this is a second copy of it that changes only " - f"when somebody deploys. State it in the environment file instead, or throw " - f"and name the missing key." - ), - ) - - # ---- const-environment-literal ----------------------------------------------------------- # A constant declaration, per language, capturing the name and the quoted value. Deliberately @@ -472,10 +396,11 @@ def _read(path: Path) -> list[str] | None: A file that fails to open here contributes no declarations and no duplications, which is indistinguishable from a file that legitimately holds neither -- so the rule would report the repo clean about a file it never saw. That is the failure the whole pack is built - against, arriving through the error path. + against, arriving through the error path. `utf-8-sig` drops the BOM Visual Studio writes + into .razor files, which would otherwise hide a line-1 `@page` from FRAMEWORK_LITERAL_LINE. """ try: - return path.read_text(encoding="utf-8", errors="replace").splitlines() + return path.read_text(encoding="utf-8-sig", errors="replace").splitlines() except OSError as error: warn_unreadable( path, diff --git a/engineering_standards/standards_deploy.py b/engineering_standards/standards_deploy.py index 703d3a1..5bc87be 100644 --- a/engineering_standards/standards_deploy.py +++ b/engineering_standards/standards_deploy.py @@ -306,7 +306,7 @@ def check_compose_read_only(path: Path, lines: list[str]) -> Iterable[Violation] THE TRIGGER IS `build:`, not the service name or the proxy network, and that is what makes the rule quiet enough to keep. A service with `build:` has its Dockerfile here: we control what it writes and can give any new path a volume. A service running a third-party image - (mysql, redis, mailhog) is one whose write behaviour we do not control, and where + (mysql, redis, mailpit) is one whose write behaviour we do not control, and where read-only routinely stops the container starting at all -- the official MySQL entrypoint writes to its datadir, /var/run and /tmp before it will serve. Flagging those would produce findings whose only correct resolution is an exemption, and a rule whose findings are all diff --git a/engineering_standards/standards_deps_declared.py b/engineering_standards/standards_deps_declared.py index dc53488..874474c 100644 --- a/engineering_standards/standards_deps_declared.py +++ b/engineering_standards/standards_deps_declared.py @@ -10,6 +10,26 @@ lockless manifests, Dockerfiles, compose files, workflows, `global.json`. Lockfiles are NOT read: they record what was resolved, and the decision this gate polices is the one a person wrote. +HOW MANY NUMBERS NAME ONE RELEASE is a fact about the vendor, not about the tag. Most number a +release with three parts, so `redis:7.2-alpine` and `node:24` are LINES -- tags that move onto +every patch -- and stay unpinned. PostgreSQL has numbered releases MAJOR.MINOR since 10 +(`16.1`, `17.6`: the major is the line, the minor is the patch), so `postgres:16.1-alpine` is one +release and no three-part postgres tag exists to pin instead. `TWO_PART_RELEASES` names those +vendors' official images, and `release_parts` is the one answer both `is_exact` and the registry +lookup's tag shape read (found 2026-10-14, when allegro-it-services could only pin postgres by +digest). It is a pack-held list rather than either alternative, deliberately: + +* not REGISTRY EVIDENCE ("no `16.1.N` tag is published, so `16.1` is a release"): pinning is + decided offline, at commit, by `dependency-unpinned` from this same `is_exact` -- a network + answer would make the commit rule and the push gate disagree -- and Docker Hub's tag list is + paged, so an absent deeper tag is not proof; that failure would pass a floating tag. +* not a `.standards.json` DECLARATION: the numbering is the same in every repository, so a + per-repo key is a copy waiting to drift, and one repo declaring `redis` two-part would reopen + exactly the floating tag this rule refuses, with no reason attached. + +An image missing from the list fails closed -- its two-part pin reads as unpinned -- and the fix +is one line here, never a looser pattern. Until then a digest pin is still a pin. + PACK-OWNED FILES ARE SKIPPED IN A CONSUMER. `engineering_standards/requirements.txt` and the analyzer list in `Directory.Build.props` belong to the pack: a consumer cannot change them (the next sync overwrites the edit), so judging them there would block a push on a decision the @@ -60,9 +80,16 @@ SHA = re.compile(r"^[0-9a-f]{40}$") ACTION_TAG_COMMENT = re.compile(r"\s*(v?\d+(?:\.\d+)*)\b") +RELEASE_PARTS = 3 +# Official images whose vendor numbers a release with two parts (see the module docstring). +TWO_PART_RELEASES = frozenset({"postgres"}) + # A full release number, then any variant suffixes: `24.1.0-alpine`, `7.1.3-php8.5-fpm`. The -# number decides exactness; a suffix only picks a flavour of that one release. -EXACT_NUMERIC = re.compile(r"^v?\d+(?:\.\d+){2,3}(?:[-+][\w.]+)*$") +# number decides exactness; a suffix only picks a flavour of that one release. Keyed by how many +# parts make a full release number; a fourth is a build number (NuGet's `10.33.0.1635`). +EXACT_NUMERIC = { + parts: re.compile(rf"^v?\d+(?:\.\d+){{{parts - 1},3}}(?:[-+][\w.]+)*$") for parts in (2, RELEASE_PARTS) +} @dataclass(frozen=True) @@ -85,7 +112,7 @@ def key(self) -> str: @property def is_pinned(self) -> bool: """Whether the version names exactly one release (decision 1 of the 2026-10-02 plan).""" - return is_exact(self.ecosystem, self.version) + return is_exact(self.ecosystem, self.name, self.version) @property def release(self) -> str: @@ -96,17 +123,32 @@ def release(self) -> str: return version -def is_exact(ecosystem: str, version: str) -> bool: - """Whether a version as WRITTEN names exactly one release in its ecosystem.""" +def official_image(name: str) -> str | None: + """A Docker Hub official image's bare name (`docker.io/library/postgres` -> `postgres`), or + None for a vendor's own `org/name` or another registry's image -- which is not that product.""" + image = name.lower().removeprefix("docker.io/").removeprefix("library/") + return image if "/" not in image else None + + +def release_parts(ecosystem: str, name: str) -> int: + """How many numeric parts name exactly one release of this dependency (module docstring).""" + if ecosystem == DOCKER and official_image(name) in TWO_PART_RELEASES: + return 2 + return RELEASE_PARTS + + +def is_exact(ecosystem: str, name: str, version: str) -> bool: + """Whether a version as WRITTEN names exactly one release of this dependency.""" if ecosystem == PYPI: return version.startswith("==") and "*" not in version if ecosystem == ACTION: return bool(SHA.match(version)) + exact = EXACT_NUMERIC[release_parts(ecosystem, name)] if ecosystem == DOCKER: - return version.startswith("sha256:") or bool(EXACT_NUMERIC.match(version)) + return version.startswith("sha256:") or bool(exact.match(version)) # NuGet: a plain `Version="x"` resolves to exactly x for a direct reference (it is the # LOWEST version satisfying the floor), so a literal three-or-four part version is a pin. - return bool(EXACT_NUMERIC.match(version)) + return bool(exact.match(version)) def _line_number(text: str, offset: int) -> int: diff --git a/engineering_standards/standards_deps_lifecycle.py b/engineering_standards/standards_deps_lifecycle.py index 5b8a48a..2b287a6 100644 --- a/engineering_standards/standards_deps_lifecycle.py +++ b/engineering_standards/standards_deps_lifecycle.py @@ -25,7 +25,7 @@ from datetime import date from standards_deps_cache import cached_lookup, store_lookup -from standards_deps_declared import DOCKER, DOTNET_SDK, NUGET, Dependency +from standards_deps_declared import DOCKER, DOTNET_SDK, NUGET, Dependency, official_image # standards: const-environment-literal exempt -- endoflife.date's published API, identical in every environment; the source Jack chose for support dates (2026-10-02) LIFECYCLE_API = "https://endoflife.date/api/v1/products/" @@ -69,8 +69,8 @@ def product_for(dependency: Dependency) -> str | None: return "dotnet" if name.startswith("mcr.microsoft.com/mssql/"): return "mssqlserver" - image = name.removeprefix("docker.io/").removeprefix("library/") - if "/" not in image: # an official image; a vendor's own `org/name` is not the product + image = official_image(name) + if image is not None: # a vendor's own `org/name` is not the product return DOCKER_PRODUCTS.get(image) return None diff --git a/engineering_standards/standards_deps_registry.py b/engineering_standards/standards_deps_registry.py index 93690a3..c3e9e34 100644 --- a/engineering_standards/standards_deps_registry.py +++ b/engineering_standards/standards_deps_registry.py @@ -19,7 +19,8 @@ "STABLE" MEANS NO PRERELEASE: a preview SDK, an `-rc` package or an `11.0.0-preview.1` tag is never proposed. Docker tags are compared only within the pin's own SHAPE -- the same number of -numeric parts and the same suffix -- and an image's `lts` tag, where it publishes one, names the +numeric parts (at least the vendor's full release number, `release_parts`) and the same +suffix -- and an image's `lts` tag, where it publishes one, names the preferred release (MySQL's `innovation` 26.7.0 is not 8.4's successor; `lts` 9.7.2 is). A GitHub token is used when the environment provides one (`GITHUB_TOKEN`, as Actions sets it, @@ -44,7 +45,17 @@ from typing import Callable from standards_deps_cache import cached_lookup, store_lookup -from standards_deps_declared import ACTION, COMPOSER, DOCKER, DOTNET_SDK, NPM, NUGET, PYPI, Dependency +from standards_deps_declared import ( + ACTION, + COMPOSER, + DOCKER, + DOTNET_SDK, + NPM, + NUGET, + PYPI, + Dependency, + release_parts, +) Fetch = Callable[[str, dict[str, str]], bytes] Release = tuple[str, str | None, str | None] # version, ISO publish date, commit SHA (Actions only) @@ -244,7 +255,9 @@ def _docker(dependency: Dependency, fetch: Fetch) -> Answer: declared = _shape(dependency.version) if declared is None: return Answer(error=f"tag `{dependency.version}` is not a version number") - count, suffix = max(declared[0], 3), declared[1] + # A floating pin is compared with full release numbers -- three parts, or two for a vendor + # that numbers its releases that way (`postgres:16-alpine` -> `16.10-alpine`). + count, suffix = max(declared[0], release_parts(DOCKER, dependency.name)), declared[1] tags = _docker_tags(dependency.name, fetch) candidates = [tag for tag in tags if _shape(tag) == (count, suffix)] if not candidates: diff --git a/engineering_standards/standards_disclosure.py b/engineering_standards/standards_disclosure.py index 0f52dbd..ac42a47 100644 --- a/engineering_standards/standards_disclosure.py +++ b/engineering_standards/standards_disclosure.py @@ -79,6 +79,7 @@ from standards_core import CheckConfig, Violation, iter_code_lines, warn_unreadable from standards_exemptions import HEADER_SCAN_LINES, exemption_reason, line_exemption_reason from standards_git import ignored_files +from standards_scope import MIGRATION_FRAGMENT # ---- disclosure-file --------------------------------------------------------------------- @@ -279,7 +280,7 @@ def check_sensitive_files(repo_root: Path, config: CheckConfig) -> Iterable[Viol # it is the per-location opt-out for a dump that is deliberate. (A dump that carries # personal data still does not belong there -- the message says so.) SQL_EXEMPT_DIR_FRAGMENTS = ( - "/migrations/", + MIGRATION_FRAGMENT, "/migration/", "/db/migrate/", "/fixtures/", diff --git a/engineering_standards/standards_dispatch.py b/engineering_standards/standards_dispatch.py index 3c9eed2..baafeed 100644 --- a/engineering_standards/standards_dispatch.py +++ b/engineering_standards/standards_dispatch.py @@ -50,7 +50,8 @@ ) from standards_client_address import check_client_address from standards_concurrency import check_concurrency -from standards_constants import check_config_default, check_environment_literal +from standards_config_defaults import check_config_default +from standards_constants import check_environment_literal from standards_cors import check_cors_wildcard from standards_debugflag import check_debug_flag from standards_disclosure import check_disclosure_file @@ -62,6 +63,7 @@ SCRIPT_SUFFIXES, ) from standards_secrets import check_committed_credentials +from standards_seed_credentials import check_seeded_credentials from standards_sqlinjection import check_sql_injection from standards_tests import check_test_quality from standards_tls import check_tls_verification @@ -69,6 +71,20 @@ from standards_write_results import check_write_results +def check_migration_file(path: Path, lines: list[str]) -> Iterable[Violation]: + """The rules that reach INTO a migrations directory, and only those. + + Everything else stays out, deliberately: a framework writes most of a migration, so the + length, naming and structure rules would be judging generated code nobody chose. What + belongs here is a rule whose subject is MORE dangerous inside a migration than outside + one -- a migration runs on every environment the schema reaches, production included. + seeded-credential-config is that: a data migration creating an administrator from an + environment variable is the "set a password, get an admin" path on every server. Which + files arrive here is standards_scope.should_check_migration's decision. + """ + yield from check_seeded_credentials(path, lines) + + def check_source_file( path: Path, lines: list[str], @@ -103,6 +119,9 @@ def check_source_file( # file type this rule would otherwise be blind to, which is exactly how the mojibake rule # shipped broken once already. yield from check_committed_credentials(path, lines) + # Its sibling, for the same reason: the seeded-password MECHANISM lives in `.env.example`, + # compose files and appsettings -- all past the early returns below -- as much as in source. + yield from check_seeded_credentials(path, lines) # DEBUG FLAG RUNS BESIDE THE TWO ABOVE, ABOVE EVERY EARLY RETURN, AND FOR THE SAME REASON. # A verbose-error / debug flag turned on in production is an information-disclosure defect @@ -221,7 +240,8 @@ def check_source_file( # See standards_user_errors.py. yield from check_technical_error_shown(path, lines, config.user_facing_exceptions) - # Where a value that may change is allowed to live -- see standards_constants.py. Config- + # Where a value that may change is allowed to live -- see standards_config_defaults.py + # and standards_constants.py. Config- # gated rather than unconditional, unlike the four security rules above: a value in the # wrong place costs a deploy, not a breach, so a repo is allowed to disagree in writing. # The third rule of this family, const-duplicated-literal, is repo-level and runs in diff --git a/engineering_standards/standards_exemption_report.py b/engineering_standards/standards_exemption_report.py index 5e33902..e472a57 100644 --- a/engineering_standards/standards_exemption_report.py +++ b/engineering_standards/standards_exemption_report.py @@ -42,12 +42,15 @@ def read_source_lines(path: Path) -> list[str] | None: is the honest input: every content rule then finds nothing, which is correct, and the credential rule reports the file from its name alone, which is all it ever needed. A `.env` declares no exemptions either, which is the correct answer as well as the safe one. + + `utf-8-sig` drops a leading byte-order mark; left in, it hides whatever line 1 holds -- + a header exemption marker, a directive -- from every rule anchored at the line start. """ if is_never_read(path): return [] try: - return path.read_text(encoding="utf-8", errors="replace").splitlines() + return path.read_text(encoding="utf-8-sig", errors="replace").splitlines() except OSError as read_error: print(f"warning: could not read {path}: {read_error}", file=sys.stderr) return None diff --git a/engineering_standards/standards_exemption_scope.py b/engineering_standards/standards_exemption_scope.py index eb26f09..f3766f2 100644 --- a/engineering_standards/standards_exemption_scope.py +++ b/engineering_standards/standards_exemption_scope.py @@ -79,6 +79,7 @@ from standards_python_support import PYTHON_RULE from standards_rules import LENGTH_RULE as RULES_FILE_LENGTH_RULE from standards_secrets import SECRET_RULE +from standards_seed_credentials import SEEDED_RULE from standards_sqlinjection import RULE as SQL_INTERPOLATION_RULE from standards_tests import ( TEST_ALWAYS_PASSES_RULE, @@ -174,6 +175,7 @@ RETRY_RULE, RUNTIME_RULE, SECRET_RULE, + SEEDED_RULE, SQL_INTERPOLATION_RULE, SWALLOWS_RULE, TECHNICAL_ERROR_RULE, diff --git a/engineering_standards/standards_gitattributes.py b/engineering_standards/standards_gitattributes.py index d07f872..136000a 100644 --- a/engineering_standards/standards_gitattributes.py +++ b/engineering_standards/standards_gitattributes.py @@ -16,7 +16,7 @@ WHAT IS CHECKED: every versioned `*.sh`, every file under the pack's `hooks/` directory (git hooks have no extension for `*.sh` to catch), and every `Dockerfile`, `Dockerfile.*` and `*.Dockerfile` -- a `RUN` continuation ending in `\\` then CR breaks the same way. Each -must resolve `eol=lf`. `/apply-standards` seeds `templates/.gitattributes` into a repo that +must resolve `eol=lf`. `/apply-standards` seeds `BASELINE` into a repo that has none; a repo that already had one keeps it, and this rule is what says which lines it still needs -- the seed alone would be a one-off copy nothing re-checks. @@ -48,6 +48,15 @@ HOOKS_PREFIX = f"{PACK_DIRECTORY}/hooks/" +# The pack's current LF baseline, at the same repo-relative path in the pack and in every repo +# that adopts it (pack_manifest ships it there on each sync). A finding names it, so it has to +# be a path the reader's own checkout holds -- the pack root's old `templates/` never shipped. +BASELINE = f"{PACK_DIRECTORY}/templates/.gitattributes" + +# The same file, resolved from this module's own location rather than a repo root, so tests +# read it wherever the package sits. +BASELINE_FILE = Path(__file__).resolve().parent / "templates" / ".gitattributes" + def suggested_line(relative: str) -> str | None: """The `.gitattributes` line that covers this path, or None if it is not a shell file. @@ -117,6 +126,6 @@ def check_gitattributes(repo_root: Path) -> Iterable[Violation]: f"'{relative}' is read by a Unix shell but resolves eol={eol}, so a checkout " f"can hold CRLF (core.autocrlf=true does it) and the shell fails on the CR. Add " f"'{suggested_line(relative)}' to .gitattributes (the pack's baseline is " - f"templates/.gitattributes)." + f"{BASELINE})." ), ) diff --git a/engineering_standards/standards_gitignore.py b/engineering_standards/standards_gitignore.py index 593ece0..337c458 100644 --- a/engineering_standards/standards_gitignore.py +++ b/engineering_standards/standards_gitignore.py @@ -57,24 +57,46 @@ def normalised_ignore_patterns(lines: list[str]) -> set[str]: class Requirement: - """One thing a repo must ignore, and every spelling that satisfies it.""" + """One thing a repo must ignore, and every spelling that satisfies it. - def __init__(self, label: str, accepted: Iterable[str], why: str) -> None: + `accepted` holds single patterns, any one of which is enough; `together` holds sets of + patterns that only count when ALL of them are present (`.env` + `.env.*`). + """ + + def __init__( + self, + label: str, + accepted: Iterable[str], + why: str, + together: Iterable[Iterable[str]] = (), + ) -> None: self.label = label self.accepted = frozenset(form.casefold() for form in accepted) + self.together = tuple(frozenset(form.casefold() for form in group) for group in together) self.why = why def is_satisfied_by(self, patterns: set[str]) -> bool: - return bool(self.accepted & patterns) + return bool(self.accepted & patterns) or any(group <= patterns for group in self.together) # Applies to every repo, whatever it is written in. `.env` is first because it is the only # entry here whose absence is a security defect rather than a hygiene one. +# +# EVERY COPY, NOT JUST `.env` (Jack, 2026-10-10). A bare `.env` line used to pass, and a +# `.env.bak-staging` -- a copy made on a server before an edit, holding the same passwords -- +# then sat untracked but NOT ignored in a production checkout, one `git add -A` from being +# pushed. A copy of the file is the same credential. So the requirement is `.env*` (or +# `.env` + `.env.*`), and an example file is admitted ON PURPOSE with its own negation, +# `!.env.example`: a negation is never counted as coverage (normalised_ignore_patterns), so +# re-admitting the example cannot weaken the rule, and nothing else gets in by accident. UNIVERSAL_REQUIREMENTS = ( Requirement( - ".env", - (".env", ".env*", "*.env", ".env.local"), - "an unignored .env is a live credential the moment the repo is pushed", + ".env*", + (".env*",), + "every copy of .env (.env.local, .env.bak, .env.staging) is as live a credential as " + ".env itself; ignore '.env*' and re-admit an example file on purpose with " + "'!.env.example'", + together=((".env", ".env.*"),), ), ) diff --git a/engineering_standards/standards_markdown.py b/engineering_standards/standards_markdown.py index 4b7809f..371cbb2 100644 --- a/engineering_standards/standards_markdown.py +++ b/engineering_standards/standards_markdown.py @@ -76,8 +76,10 @@ def frontmatter_block(lines: list[str]) -> list[str] | None: def read_lines(path: Path) -> list[str]: + # `utf-8-sig` drops a leading byte-order mark, which would otherwise make line 1 read + # "---" and hide the page's whole frontmatter block. try: - return path.read_text(encoding="utf-8", errors="replace").splitlines() + return path.read_text(encoding="utf-8-sig", errors="replace").splitlines() except OSError as error: # The empty list is what makes this dangerous: an unreadable page becomes an EMPTY # page, and an empty page passes the frontmatter, broken-link and stale-symbol rules diff --git a/engineering_standards/standards_scope.py b/engineering_standards/standards_scope.py index 33469c2..e76e5d2 100644 --- a/engineering_standards/standards_scope.py +++ b/engineering_standards/standards_scope.py @@ -175,13 +175,25 @@ def looks_like_workflow(path: Path) -> bool: # here too: the sentinel traps are runtime behaviour, identical with or without types. SCRIPT_SUFFIXES = (".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs") +# THE ONE EXCLUSION A RULE MAY REACH THROUGH. A migrations directory is excluded because a +# framework writes most of what is in it, and length, naming and structure rules have no +# business judging generated code. But not everything in there is generated: a hand-written +# data migration that creates an administrator from an environment variable is the +# seeded-credential-config shape in its worst home -- it runs on EVERY environment the schema +# is applied to, production included. So a migration is skipped by `should_check` and offered +# instead to `should_check_migration`, whose files the driver hands to `check_migration_file` +# in standards_dispatch -- which runs only the rules that must see one. Found 2026-10-14: the +# whole-tree scan called allegro-it-services clean while the rule's own self-test, walking +# that tree without this exclusion, found a migration seeding a superuser from configuration. +MIGRATION_FRAGMENT = "/migrations/" + # Paths never checked: machine-generated, vendored, or build output. EXCLUDED_PATH_FRAGMENTS = ( "/obj/", "/bin/", "/node_modules/", "/vendor/", - "/migrations/", + MIGRATION_FRAGMENT, "/.git/", "/dist/", "/build/", @@ -196,20 +208,9 @@ def looks_like_workflow(path: Path) -> bool: EXCLUDED_NAME_FRAGMENTS = (".min.", ".g.", ".designer.", ".generated.") -def should_check(path: Path, repo_root: Path, config: CheckConfig) -> bool: - """Decide whether a file is in scope. - - Exclusions are matched against the REPO-RELATIVE path, never the absolute one: a repo - that happens to live under a directory called "build" or "dist" would otherwise have - every one of its files silently skipped. - - THE PACK'S OWN FILES ARE NOT THE CONSUMING REPO'S SOURCE. A repo that adopted the pack - holds ~100 files it did not write and must not edit, so measuring them here reported - findings and exemption markers nobody in that repo could act on -- see - standards_pack_identity. In the PACK's own repository they are the source, and are - checked exactly as before. - """ - in_scope = ( +def _in_scope_by_kind(path: Path, repo_root: Path) -> bool: + """Whether the file is a kind any rule reads at all -- by suffix, filename or location.""" + return bool( path.suffix in SOURCE_SUFFIXES or COMPOSE_FILENAME.match(path.name) or ENV_EXAMPLE_FILENAME.match(path.name) @@ -227,17 +228,52 @@ def should_check(path: Path, repo_root: Path, config: CheckConfig) -> bool: or DEPENDENCY_MANIFEST_FILENAME.match(path.name) or is_workflow(path, repo_root) ) - if not in_scope: - return False + +def _excluding_fragments(path: Path, repo_root: Path, config: CheckConfig) -> set[str] | None: + """The path exclusions this file falls under, or None when it is never read at all. + + None covers the two refusals no rule may reach through: the pack's own file inside a + consumer, and a generated NAME (`.Designer.cs`, `.min.js`) -- the latter is exactly what + EF writes beside every migration, and it stays skipped by the migration route too. + """ relative = path.relative_to(repo_root) if is_foreign_pack_file(relative, repo_root): - return False - + return None + if any(fragment in path.name.casefold() for fragment in EXCLUDED_NAME_FRAGMENTS): + return None lowered = "/" + relative.as_posix().casefold() + "/" - excluded = EXCLUDED_PATH_FRAGMENTS + config.extra_excluded_fragments - if any(fragment.casefold() in lowered for fragment in excluded): + return {fragment.casefold() for fragment in excluded if fragment.casefold() in lowered} + + +def should_check_migration(path: Path, repo_root: Path, config: CheckConfig) -> bool: + """A source file that `should_check` skips ONLY because it sits in a migrations directory. + + Source suffixes only: a migration is code, and nothing else in that directory carries + the shapes the migration route looks for. Any OTHER exclusion still wins -- a migration + under `node_modules/` or `vendor/` is somebody else's code, and a repo's own + `extra_excluded_fragments` are its stated decision. + """ + if path.suffix not in SOURCE_SUFFIXES: return False + fragments = _excluding_fragments(path, repo_root, config) + return fragments == {MIGRATION_FRAGMENT} + + +def should_check(path: Path, repo_root: Path, config: CheckConfig) -> bool: + """Decide whether a file is in scope. + + Exclusions are matched against the REPO-RELATIVE path, never the absolute one: a repo + that happens to live under a directory called "build" or "dist" would otherwise have + every one of its files silently skipped. - return not any(fragment in path.name.casefold() for fragment in EXCLUDED_NAME_FRAGMENTS) + THE PACK'S OWN FILES ARE NOT THE CONSUMING REPO'S SOURCE. A repo that adopted the pack + holds ~100 files it did not write and must not edit, so measuring them here reported + findings and exemption markers nobody in that repo could act on -- see + standards_pack_identity. In the PACK's own repository they are the source, and are + checked exactly as before. + """ + if not _in_scope_by_kind(path, repo_root): + return False + return _excluding_fragments(path, repo_root, config) == set() diff --git a/engineering_standards/standards_secrets.py b/engineering_standards/standards_secrets.py index d876bab..3410416 100644 --- a/engineering_standards/standards_secrets.py +++ b/engineering_standards/standards_secrets.py @@ -60,7 +60,13 @@ ("a Stripe webhook signing secret", re.compile(r"\bwhsec_[A-Za-z0-9]{16,}")), ("a Brevo API key", re.compile(r"\bxkeysib-[A-Za-z0-9]{16,}")), ("an AWS access key id", re.compile(r"\b(?:AKIA|ASIA)[0-9A-Z]{16}\b")), - ("a GitHub token", re.compile(r"\b(?:ghp|gho|ghs|ghu)_[A-Za-z0-9]{30,}|\bgithub_pat_[A-Za-z0-9_]{30,}")), + # `ghs_` is a GitHub App installation token, and since 2026 it can be a stateless JWT: ~520 + # characters, two dots, base64url's `-` and `_`. Letters-and-digits-only stopped at the first + # of those and passed the token. The charset is GitHub's own published validation pattern. + ( + "a GitHub token", + re.compile(r"\b(?:ghp|gho|ghu|ghr)_[A-Za-z0-9]{30,}|\bghs_[A-Za-z0-9._-]{36,}|\bgithub_pat_[A-Za-z0-9_]{30,}"), + ), ("a Slack token", re.compile(r"\bxox[baprs]-[A-Za-z0-9-]{10,}")), ("a Google API key", re.compile(r"\bAIza[0-9A-Za-z_\-]{35}\b")), ("a SendGrid API key", re.compile(r"\bSG\.[A-Za-z0-9_\-]{16,}\.[A-Za-z0-9_\-]{16,}")), diff --git a/engineering_standards/standards_seed_credentials.py b/engineering_standards/standards_seed_credentials.py new file mode 100644 index 0000000..7666cc6 --- /dev/null +++ b/engineering_standards/standards_seed_credentials.py @@ -0,0 +1,208 @@ +#!/usr/bin/env python3 +"""A seeded account's password, wired in through configuration. The enforceable half of the +"Seed test systems" section in claude/rules/secrets.md. + +Rules here: seeded-credential-config. + +THE SHAPE. A seeder, restore script or app that reads an admin / demo / seed account's password +from configuration -- a key in `.env.example`, a compose variable, an `appsettings` entry, an +environment read in code -- and creates or resets the account with it. The value itself never +reaches git, so `committed-credential` passes it, correctly. What it misses is the MECHANISM: +a standing "set a password, get an admin" path on every machine that runs the code. Whoever can +set that variable -- a wrong `.env`, a value set on a server by mistake -- gets into the system, +and because the estate uses one test password everywhere, the same value opens every project. + +WHY IT EARNS A RULE (2026-10-12). ellengaard-dk's restore created `localadmin` from +`LOCAL_ADMIN_PASSWORD` in `.env`, documented in `.env.example` -- the shape secrets.md itself +recommended at the time ("a seeder takes the password from configuration, never a literal"). +InvoTrack seeds its admin from a configuration key the same way. Jack: test systems should be +seeded, "but not through a feature where you can set a password and then gain access". The +right shape is an explicit, local-only seed step that takes the values on STDIN from the PC's +values file; snippets in templates/seed-users/. + +WHAT IT LOOKS AT. Two halves, because the pattern needs both and either alone is the defect: + DECLARATION the key, in a file that configures the code: `.env.example` (and other `.env.*` + examples -- never `.env` itself, which is never opened), compose files, + `appsettings*.json` / `settings*.json` (nested paths joined, so + `{"Demo": {"Password": ...}}` is `Demo:Password`). + READ the key, read from the environment or configuration in source: PHP `getenv` / + `$_ENV`, Python `os.environ` / `os.getenv`, C# `GetEnvironmentVariable` / + `configuration["..."]` / `GetValue("...")`, JS/TS `process.env`, shell `$VAR`, + PowerShell `$env:VAR`. + +MIGRATIONS INCLUDED -- THE ONE RULE THAT READS THEM (2026-10-14). The scanner skips every +migrations directory, because a framework writes most of what is in one. That skip made this +rule blind in its worst home: a hand-written data migration creating a superuser from an +environment variable runs on EVERY environment the schema reaches, production included, so +the "set a password, get an admin" path ships to every server rather than sitting in a +local-only script. allegro-it-services had exactly that, and the whole-tree scan called it +clean while this rule's own self-test -- which walked the tree without the exclusion -- found +it. The two now agree in the direction of the rule: `standards_scope.should_check_migration` +admits a source file skipped ONLY for being under `migrations/`, and +`standards_dispatch.check_migration_file` runs this rule on it and nothing else. Generated +migrations stay quiet without help: a framework never writes an environment read of a +seeded key. Pinned in test_standards_seed_credentials.py. + +WHAT COUNTS AS A SEEDED ACCOUNT'S PASSWORD. Decided on the key's NAME, normalised (case and +separators dropped): it ends in a password word and, before that, names an account a seeder +would create -- admin, superuser, seed, demo, a local/test/default/initial/bootstrap user. +`MYSQL_ROOT_PASSWORD` or `SMTP_PASSWORD` name no such account and stay quiet: a database or +mail credential is `committed-credential`'s subject, not this rule's. + +WHY IT IS LINE-EXEMPTABLE. A third-party tool configured by its own documented variable -- +pgAdmin's `PGADMIN_DEFAULT_PASSWORD`, Grafana's admin password in a local-only compose service -- +has the name and is not an estate seeder. That is a human's call, made on the line with a +reason; the rule's job is to make sure the question is asked. + +Source of truth: engineering-standards/engineering_standards/standards_seed_credentials.py +""" + +from __future__ import annotations + +import json +import re +from pathlib import Path +from typing import Iterable, Iterator, NamedTuple + +from standards_core import Violation +from standards_exemptions import line_exemption_reason +from standards_secrets import is_never_read + +SEEDED_RULE = "seeded-credential-config" + +# The NAME test, run on a normalised key (lower case, `_ - . :` removed). The account words are +# the ones a seeder creates; the password words end the key, which is how these are always named +# (`ADMIN_PASSWORD`, `Demo:AdminPassword`, `SeedUserPwd`). +_ACCOUNT = r"(?:admin|superuser|seed|demo|(?:local|test|default|initial|bootstrap|dev)user)" +SEEDED_KEY = re.compile(rf"{_ACCOUNT}\w*?(?:password|passwd|pwd|pass)$") +_SEPARATORS = re.compile(r"[_\-.:\s]") + +# ---- declarations ---------------------------------------------------------------------------- +ENV_EXAMPLE = re.compile(r"^\.env\.[\w.-]+$", re.IGNORECASE) +COMPOSE = re.compile(r"^(?:docker-)?compose(?:[\w.-]*)?\.ya?ml$", re.IGNORECASE) +JSON_SETTINGS = re.compile(r"^(?:appsettings[\w.-]*|settings[\w.-]*)\.json$", re.IGNORECASE) + +ENV_LINE_KEY = re.compile(r"^\s*#?\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=") +YAML_LINE_KEY = re.compile(r"^\s*-?\s*([A-Za-z_][\w.]*)\s*[:=]") +INTERPOLATION = re.compile(r"\$\{([A-Za-z_]\w*)") +JSON_LINE_KEY = re.compile(r'"([\w.:\-]+)"\s*:') + +# ---- reads in source, per language ----------------------------------------------------------- +_Q = r"""["']""" +SOURCE_READS: dict[str, tuple[re.Pattern[str], ...]] = { + ".php": ( + re.compile(rf"getenv\(\s*{_Q}([\w.:\-]+){_Q}"), + re.compile(rf"\$_(?:ENV|SERVER)\[\s*{_Q}([\w.:\-]+){_Q}"), + re.compile(rf"\benv\(\s*{_Q}([\w.:\-]+){_Q}"), + ), + ".py": ( + re.compile(rf"os\.(?:getenv|environ\.get)\(\s*{_Q}([\w.:\-]+){_Q}"), + re.compile(rf"os\.environ\[\s*{_Q}([\w.:\-]+){_Q}"), + ), + ".cs": ( + re.compile(r'GetEnvironmentVariable\(\s*"([\w.:\-]+)"'), + re.compile(r'\[\s*"([\w.:\-]+)"\s*\]'), + re.compile(r'GetValue<[^>]+>\(\s*"([\w.:\-]+)"'), + ), + ".js": ( + re.compile(r"process\.env\.([A-Za-z_]\w*)"), + re.compile(rf"process\.env\[\s*{_Q}([\w.:\-]+){_Q}"), + ), + ".sh": (re.compile(r"\$\{?([A-Za-z_]\w*)"),), + ".ps1": (re.compile(r"\$env:([A-Za-z_]\w*)", re.IGNORECASE),), +} +_ALIASES = {".ts": ".js", ".tsx": ".js", ".mjs": ".js", ".cjs": ".js", ".jsx": ".js", ".bash": ".sh"} + + +class Finding(NamedTuple): + """One seeded-password key on one line, and whether it was declared or read.""" + + index: int + key: str + how: str + + +def is_seeded_key(key: str) -> bool: + """Whether a configuration key names a seeded account's password.""" + return bool(SEEDED_KEY.search(_SEPARATORS.sub("", key).casefold())) + + +def _line_keys(lines: list[str], patterns: Iterable[re.Pattern[str]], how: str) -> Iterator[Finding]: + """One finding per line whose matched key names a seeded password.""" + compiled = tuple(patterns) + for index, line in enumerate(lines): + for pattern in compiled: + hit = next((m.group(1) for m in pattern.finditer(line) if is_seeded_key(m.group(1))), None) + if hit is not None: + yield Finding(index, hit, how) + break + + +def _json_paths(node: object, prefix: str = "") -> Iterator[str]: + """Every key path in parsed JSON, `Parent:Child` style (the .NET configuration form).""" + if isinstance(node, dict): + for key, value in node.items(): + path = f"{prefix}:{key}" if prefix else str(key) + yield path + yield from _json_paths(value, path) + elif isinstance(node, list): + for item in node: + yield from _json_paths(item, prefix) + + +def _json_findings(lines: list[str]) -> Iterator[Finding]: + """Nested paths when the file parses (appsettings may carry comments; then line keys).""" + try: + parsed = json.loads("\n".join(lines)) + except ValueError: + yield from _line_keys(lines, (JSON_LINE_KEY,), "declared") + return + reported: set[int] = set() + for path in _json_paths(parsed): + if not is_seeded_key(path): + continue + leaf = path.rsplit(":", 1)[-1] + index = next((i for i, line in enumerate(lines) if f'"{leaf}"' in line and i not in reported), 0) + reported.add(index) + yield Finding(index, path, "declared") + + +def findings_in(path: Path, lines: list[str]) -> Iterator[Finding]: + """Every seeded-password key this file declares or reads.""" + name = path.name + if is_never_read(path): + return + if ENV_EXAMPLE.match(name): + yield from _line_keys(lines, (ENV_LINE_KEY,), "declared") + elif COMPOSE.match(name): + yield from _line_keys(lines, (YAML_LINE_KEY, INTERPOLATION), "declared") + elif JSON_SETTINGS.match(name): + yield from _json_findings(lines) + else: + suffix = path.suffix.casefold() + patterns = SOURCE_READS.get(_ALIASES.get(suffix, suffix)) + if patterns: + yield from _line_keys(lines, patterns, "read from configuration") + + +def check_seeded_credentials(path: Path, lines: list[str]) -> Iterable[Violation]: + """Flag a seeded account's password wired in through configuration.""" + for finding in findings_in(path, lines): + if line_exemption_reason(lines, finding.index, SEEDED_RULE): + continue + yield Violation( + path=path, + line=finding.index + 1, + rule=SEEDED_RULE, + message=( + f"`{finding.key}` is {finding.how} as a seeded account's password. That makes " + f"a standing 'set a password, get an admin' path on every machine that runs " + f"this code -- whoever can set the value gets in, and the estate's test " + f"password is the same everywhere. Seed test accounts through an explicit, " + f"local-only step that refuses outside development and takes the values on " + f"stdin from the PC's values file (templates/seed-users/ in the pack). If this " + f"is a third-party tool's own documented setting rather than an estate seeder, " + f"say so on the line: `standards: {SEEDED_RULE} exempt -- `. See " + f".claude/rules/secrets.md." + ), + ) diff --git a/engineering_standards/standards_versions.py b/engineering_standards/standards_versions.py index 7ae561e..aae2d8d 100644 --- a/engineering_standards/standards_versions.py +++ b/engineering_standards/standards_versions.py @@ -72,7 +72,7 @@ # version that wrote it (`packVersion` in .standards-baseline.json). PROVENANCE, not # authority: sync_pack.py still decides drift by comparing file contents, so a forgotten # bump can never hide a stale file -- it only blurs the label on the report. -PACK_VERSION = "2026.10.08-2" +PACK_VERSION = "2026.10.14-3" # Minimum MAJOR version per action. Majors only: a patch pin is a security practice some repos # use deliberately (wordpress-docker-template pins @v7.0.0) and demanding an exact string would diff --git a/engineering_standards/templates/.gitattributes b/engineering_standards/templates/.gitattributes new file mode 100644 index 0000000..2fb1352 --- /dev/null +++ b/engineering_standards/templates/.gitattributes @@ -0,0 +1,23 @@ +# Line endings for files that run under a Unix shell. A CR is a syntax error to sh and bash +# -- in a container, in CI, in a git hook -- not a cosmetic difference. Whether a checkout +# gets CRLF is otherwise decided by core.autocrlf, which differs per PC and travels with no +# clone; this file travels with the repository and outranks it. +# +# Seeded once by /apply-standards (engineering_standards/templates/.gitattributes); this +# repository owns it from then on. The `gitattributes-eol` scanner rule checks that the LF +# lines below keep resolving, so edit freely around them. +# +# Deliberately no `* text=auto`: on adoption it would renormalise the whole index in one +# commit. Whether to take that is this repository's own decision. + +*.sh text eol=lf +Dockerfile text eol=lf +Dockerfile.* text eol=lf +*.Dockerfile text eol=lf + +# Git hooks are shell scripts without an extension -- same hazard, no *.sh to catch them. +engineering_standards/hooks/* text eol=lf + +# cmd.exe finds `goto` / `call :label` targets reliably only in CRLF files. +*.bat text eol=crlf +*.cmd text eol=crlf diff --git a/engineering_standards/test_hook_blocks.py b/engineering_standards/test_hook_blocks.py index baa5d1e..6eef84f 100644 --- a/engineering_standards/test_hook_blocks.py +++ b/engineering_standards/test_hook_blocks.py @@ -45,7 +45,13 @@ def make_wired_repo(tmp: Path) -> Path: for source in HOOKS_DIRECTORY.iterdir(): if source.is_file(): shutil.copy2(source, repo / "engineering_standards/hooks" / source.name) - (repo / ".gitignore").write_text(".env\n", encoding="utf-8") + (repo / ".gitignore").write_text(".env*\n", encoding="utf-8") + # Every adopting repo is seeded with the pack's .gitattributes, and `gitattributes-eol` + # (a repo-level rule the push stage runs) refuses hooks that do not resolve eol=lf. + # Without it this sandbox failed the push probe on that rule, not on the one under test. + # Read beside the package, which ships to every repo: the pack root's `templates/` does + # not, so reading it there broke this test in every consumer (2026.10.11-3). + shutil.copy2(PACK_DIRECTORY / "templates" / ".gitattributes", repo / ".gitattributes") git(repo, "init", "-q") git(repo, "config", "user.name", "probe") diff --git a/engineering_standards/test_standards_baseline.py b/engineering_standards/test_standards_baseline.py index 55736b5..2179590 100644 --- a/engineering_standards/test_standards_baseline.py +++ b/engineering_standards/test_standards_baseline.py @@ -42,7 +42,7 @@ def make_repo(root: Path) -> None: (root / ".standards.json").write_text(json.dumps({"maxFileLines": 10}), encoding="utf-8") # The plain check run also enforces the gitignore rule; satisfy it so these tests # exercise only the baseline writer. - (root / ".gitignore").write_text(".env\n", encoding="utf-8") + (root / ".gitignore").write_text(".env*\n", encoding="utf-8") filler = [f"int x{i};" for i in range(14)] (root / "alpha.cs").write_text("\n".join(["// plain"] + filler), encoding="utf-8") (root / "bravo.cs").write_text( @@ -132,7 +132,7 @@ def add_project(root: Path, *lines: str) -> None: a reason that has nothing to do with what they are testing. Caught by the exemption test below on its first run. """ - (root / ".gitignore").write_text(".env\nbin/\nobj/\n", encoding="utf-8") + (root / ".gitignore").write_text(".env*\nbin/\nobj/\n", encoding="utf-8") (root / "App.csproj").write_text( "\n".join(["", " ", *lines, " ", ""]), encoding="utf-8", diff --git a/engineering_standards/test_standards_config_defaults.py b/engineering_standards/test_standards_config_defaults.py new file mode 100644 index 0000000..b2f6861 --- /dev/null +++ b/engineering_standards/test_standards_config_defaults.py @@ -0,0 +1,88 @@ +#!/usr/bin/env python3 +"""Cases for `config-default-in-code`: a configuration read whose fallback is a literal. + +Plain asserts, no pytest, so it runs anywhere Python does: + + python engineering_standards/test_standards_config_defaults.py + +Split out of test_standards_constants.py with the rule itself (2026-10-22). As there, the +quiet cases matter most: a `??` is everywhere in correct code, so every negative case below is +a real false positive kept so it cannot come back -- this pack's own fixtures read as +configuration, and PHP's request fields in `$_SERVER` read as settings. +""" + +from __future__ import annotations + +import sys +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parent)) + +from standards_config_defaults import check_config_default # noqa: E402 + + +def defaults(source: str, name: str = "Startup.cs") -> list[str]: + return [v.rule for v in check_config_default(Path(name), source.splitlines())] + + +def test_a_csharp_configuration_read_with_a_literal_fallback_fires(): + assert defaults('var host = Configuration["Mail:Host"] ?? "localhost";') == ["config-default-in-code"] + + +def test_the_python_php_and_javascript_spellings_fire_too(): + """One rule, four languages -- the shape is the same and only the syntax differs.""" + assert defaults('host = os.getenv("MAIL_HOST", "localhost")', "settings.py") + assert defaults("$host = getenv('MAIL_HOST') ?: 'localhost';", "config.php") + assert defaults('const host = process.env.MAIL_HOST ?? "localhost";', "env.ts") + + +def test_throwing_instead_of_defaulting_is_the_correct_answer_and_stays_quiet(): + """`secrets.md` MANDATES this shape for a seeder. Firing on it would be firing on the fix.""" + assert defaults('var key = Configuration["Api:Key"] ?? throw new InvalidOperationException();') == [] + + +def test_falling_back_to_null_is_not_a_default(): + assert defaults('var host = Configuration["Mail:Host"] ?? null;') == [] + + +def test_an_empty_default_is_absence_not_an_invented_value(): + assert defaults('host = os.getenv("MAIL_HOST", "")', "settings.py") == [] + + +def test_falling_back_to_another_configured_value_is_quiet(): + assert defaults('var x = Configuration["A"] ?? Configuration["B"];') == [] + + +def test_a_literal_fallback_with_no_configuration_read_is_not_this_rule(): + assert defaults('var name = candidate ?? "unknown";') == [] + + +def test_php_request_fields_in_server_are_not_configuration(): + """$_SERVER also carries the request. A guard on a missing request field is not a setting + -- measured on jacks_corner's front controller, which this rule flagged four times.""" + assert defaults("$uri = parse_url($_SERVER['REQUEST_URI'] ?? '/', PHP_URL_PATH);", "index.php") == [] + assert defaults("$host = $_SERVER['HTTP_HOST'] ?? 'example.dk';", "seo.php") == [] + assert defaults('$proto = $_SERVER["HTTP_X_FORWARDED_PROTO"] ?? "http";', "seo.php") == [] + assert defaults("$on = $_SERVER['HTTPS'] ?? 'off';", "seo.php") == [] + assert defaults("$method = $_SERVER['REQUEST_METHOD'] ?? 'GET';", "index.php") == [] + assert defaults("$query = $_SERVER['QUERY_STRING'] ?? 'a=1';", "index.php") == [] + + +def test_php_environment_values_in_server_still_fire(): + """The other half of the array is the process environment, which IS configuration.""" + assert defaults("$host = $_SERVER['MAIL_HOST'] ?? 'localhost';", "config.php") + # A name that only STARTS like a request field is still an environment variable. + assert defaults("$proxy = $_SERVER['HTTPS_PROXY'] ?? 'http://proxy:3128';", "config.php") + # A dynamic key could be either half; nothing here can tell which. + assert defaults("$value = $_SERVER[$name] ?? 'fallback';", "config.php") + + +def test_a_test_files_fixture_source_is_not_a_configuration_default(): + """This pack's own tests carry example source as literals; the rule read them back.""" + assert defaults("source = \"DEBUG = os.environ.get('DEBUG') == '1'\"", "test_settings.py") == [] + + +if __name__ == "__main__": + from standards_selftest import run_module_tests + + sys.exit(run_module_tests(globals(), "config-default-in-code cases")) diff --git a/engineering_standards/test_standards_constants.py b/engineering_standards/test_standards_constants.py index d62f8ec..6e3c847 100644 --- a/engineering_standards/test_standards_constants.py +++ b/engineering_standards/test_standards_constants.py @@ -5,6 +5,9 @@ python engineering_standards/test_standards_constants.py +`config-default-in-code`'s cases moved to test_standards_config_defaults.py with the rule +(2026-10-22); the list below keeps its history. + THE CASES THAT MATTER MOST ARE THE QUIET ONES. All three rules fire on shapes that are extremely common in correct code -- a `??`, an absolute-looking string, a repeated word -- so the risk here is not a missed finding but a noisy rule, which gets baselined wholesale and @@ -29,16 +32,11 @@ from standards_config import CheckConfig # noqa: E402 from standards_constants import ( # noqa: E402 - check_config_default, check_duplicated_constants, check_environment_literal, ) -def defaults(source: str, name: str = "Startup.cs") -> list[str]: - return [v.rule for v in check_config_default(Path(name), source.splitlines())] - - def environment(source: str, name: str = "Startup.cs") -> list[str]: return [v.rule for v in check_environment_literal(Path(name), source.splitlines())] @@ -68,46 +66,6 @@ def messages(files: dict[str, str]) -> list[str]: return [v.message for v in check_duplicated_constants(root, paths, CheckConfig())] -# ---- config-default-in-code ------------------------------------------------------------- - - -def test_a_csharp_configuration_read_with_a_literal_fallback_fires(): - assert defaults('var host = Configuration["Mail:Host"] ?? "localhost";') == ["config-default-in-code"] - - -def test_the_python_php_and_javascript_spellings_fire_too(): - """One rule, four languages -- the shape is the same and only the syntax differs.""" - assert defaults('host = os.getenv("MAIL_HOST", "localhost")', "settings.py") - assert defaults("$host = getenv('MAIL_HOST') ?: 'localhost';", "config.php") - assert defaults('const host = process.env.MAIL_HOST ?? "localhost";', "env.ts") - - -def test_throwing_instead_of_defaulting_is_the_correct_answer_and_stays_quiet(): - """`secrets.md` MANDATES this shape for a seeder. Firing on it would be firing on the fix.""" - assert defaults('var key = Configuration["Api:Key"] ?? throw new InvalidOperationException();') == [] - - -def test_falling_back_to_null_is_not_a_default(): - assert defaults('var host = Configuration["Mail:Host"] ?? null;') == [] - - -def test_an_empty_default_is_absence_not_an_invented_value(): - assert defaults('host = os.getenv("MAIL_HOST", "")', "settings.py") == [] - - -def test_falling_back_to_another_configured_value_is_quiet(): - assert defaults('var x = Configuration["A"] ?? Configuration["B"];') == [] - - -def test_a_literal_fallback_with_no_configuration_read_is_not_this_rule(): - assert defaults('var name = candidate ?? "unknown";') == [] - - -def test_a_test_files_fixture_source_is_not_a_configuration_default(): - """This pack's own tests carry example source as literals; the rule read them back.""" - assert defaults("source = \"DEBUG = os.environ.get('DEBUG') == '1'\"", "test_settings.py") == [] - - # ---- const-environment-literal ----------------------------------------------------------- @@ -259,6 +217,19 @@ def test_a_blazor_page_directive_cannot_reference_a_constant_so_it_is_not_report assert findings == [] +def test_a_page_directive_after_a_byte_order_mark_is_still_a_page_directive(): + """Visual Studio saves .razor files with a UTF-8 BOM, and `\\s` does not match U+FEFF, so a + BOM left in line 1 hid the `@page` from the exemption. Measured on payvisia's + Dashboard.razor and Kriterier.razor, 2026-10-11.""" + findings = duplicated( + { + "Endpoints.cs": ' internal const string LoginPath = "/log-ind";\n', + "LogInd.razor": '@page "/log-ind"\n', + } + ) + assert findings == [] + + def test_a_test_file_may_pin_the_value_it_is_testing(): findings = duplicated( { diff --git a/engineering_standards/test_standards_deps_declared.py b/engineering_standards/test_standards_deps_declared.py index 3d0dd74..3f8258c 100644 --- a/engineering_standards/test_standards_deps_declared.py +++ b/engineering_standards/test_standards_deps_declared.py @@ -136,25 +136,50 @@ def test_a_malformed_manifest_is_named_not_skipped_quietly() -> None: def test_what_counts_as_a_pin() -> None: - assert is_exact(PYPI, "==9.1.1") - assert not is_exact(PYPI, ">=9.1") - assert is_exact(NUGET, "10.33.0.1635") - assert not is_exact(NUGET, "10.*") - assert is_exact(NPM, "19.1.0") - assert not is_exact(NPM, "^19.1.0") - assert is_exact(DOCKER, "8.4.11") - assert is_exact(DOCKER, "24.1.0-alpine") + assert is_exact(PYPI, "pytest", "==9.1.1") + assert not is_exact(PYPI, "pytest", ">=9.1") + assert is_exact(NUGET, "SonarAnalyzer.CSharp", "10.33.0.1635") + assert not is_exact(NUGET, "SonarAnalyzer.CSharp", "10.*") + assert is_exact(NPM, "react", "19.1.0") + assert not is_exact(NPM, "react", "^19.1.0") + assert is_exact(DOCKER, "mysql", "8.4.11") + assert is_exact(DOCKER, "node", "24.1.0-alpine") # Variant tags carry several suffix segments, and each still names one release -- the # gate itself proposes them as "newest pin in its line" (wordpress-docker-template, 2026-10-08). - assert is_exact(DOCKER, "7.1.3-php8.5-fpm") - assert is_exact(DOCKER, "8.3.12-fpm-alpine") - assert is_exact(DOCKER, "1.9.2-lsphp85") - assert not is_exact(DOCKER, "8.3-fpm-alpine") - assert not is_exact(DOCKER, "7.1-php8.5-fpm") - assert not is_exact(DOCKER, "8.4") - assert not is_exact(DOCKER, "latest") - assert is_exact(ACTION, SHA) - assert not is_exact(ACTION, "v7") + assert is_exact(DOCKER, "wordpress", "7.1.3-php8.5-fpm") + assert is_exact(DOCKER, "php", "8.3.12-fpm-alpine") + assert is_exact(DOCKER, "litespeedtech/openlitespeed", "1.9.2-lsphp85") + assert not is_exact(DOCKER, "php", "8.3-fpm-alpine") + assert not is_exact(DOCKER, "wordpress", "7.1-php8.5-fpm") + assert not is_exact(DOCKER, "mysql", "8.4") + assert not is_exact(DOCKER, "mysql", "latest") + assert is_exact(ACTION, "actions/checkout", SHA) + assert not is_exact(ACTION, "actions/checkout", "v7") + + +def test_two_parts_pin_only_a_vendor_that_numbers_releases_with_two() -> None: + """allegro-it-services, 2026-10-14: PostgreSQL numbers a release MAJOR.MINOR, so no postgres + tag could pass and the pin had to be a digest. Two parts are a release only for such a + vendor -- for everyone else they are a line that moves onto every patch.""" + for name in ("postgres", "library/postgres", "docker.io/library/postgres"): + assert is_exact(DOCKER, name, "16.1-alpine"), name + assert is_exact(DOCKER, "postgres", "17.6-bookworm") + assert is_exact(DOCKER, "postgres", "16.1") + assert not is_exact(DOCKER, "postgres", "16-alpine"), "a postgres major is a line" + assert not is_exact(DOCKER, "postgres", "16") + assert not is_exact(DOCKER, "postgres", "latest") + assert not is_exact(DOCKER, "redis", "7.2-alpine"), "redis numbers releases 7.2.N" + assert not is_exact(DOCKER, "node", "24") + assert not is_exact(DOCKER, "someone/postgres", "16.1"), "only the official image is that vendor" + assert not is_exact(NUGET, "postgres", "16.1"), "the list is Docker images, nothing else" + + +def test_a_dependency_s_pin_is_judged_by_its_own_vendor() -> None: + def pinned(name: str, version: str) -> bool: + return Dependency(DOCKER, name, version, Path("docker-compose.yml"), 1).is_pinned + + assert pinned("postgres", "16.1-alpine") + assert not pinned("redis", "7.2-alpine") def test_the_release_is_spelled_as_its_registry_spells_it() -> None: diff --git a/engineering_standards/test_standards_deps_pinning.py b/engineering_standards/test_standards_deps_pinning.py index 3ee4591..ac67d65 100644 --- a/engineering_standards/test_standards_deps_pinning.py +++ b/engineering_standards/test_standards_deps_pinning.py @@ -71,6 +71,13 @@ def test_exact_pins_are_quiet() -> None: assert unpinned_lines(relative, body) == [], f"{relative}: an exact pin was reported" +def test_a_two_part_vendor_s_release_is_a_pin_at_commit_too() -> None: + """The commit rule and the push gate share `is_exact`, so `postgres:16.1-alpine` passes both + -- and a two-part redis line still fails here, offline, before any registry is asked.""" + body = "services:\n db:\n image: postgres:16.1-alpine\n cache:\n image: redis:7.2-alpine\n" + assert unpinned_lines("docker-compose.yml", body) == [5] + + def test_the_finding_is_on_the_declaring_line() -> None: body = "services:\n app:\n build: .\n db:\n image: mysql:8.4\n" assert unpinned_lines("docker-compose.yml", body) == [5] diff --git a/engineering_standards/test_standards_deps_registry.py b/engineering_standards/test_standards_deps_registry.py index 449fcbb..1ae2265 100644 --- a/engineering_standards/test_standards_deps_registry.py +++ b/engineering_standards/test_standards_deps_registry.py @@ -160,6 +160,21 @@ def test_a_docker_tag_is_compared_only_with_tags_of_its_shape() -> None: assert versions(answer) == {"9.1.0", "8.4.11", "8.4.10"} +def test_a_two_part_vendor_is_compared_with_its_own_two_part_releases() -> None: + """PostgreSQL numbers releases MAJOR.MINOR: `16.1-alpine` is compared with the other + `N.N-alpine` releases, and a floating `16-alpine` is offered them too -- never three-part + tags, which postgres does not publish.""" + url = "https://hub.docker.com/v2/namespaces/library/repositories/postgres/tags?page_size=100&ordering=last_updated" + tags = ["16.1-alpine", "16.10-alpine", "17.6-alpine", "16-alpine", "16.10", "alpine", "latest"] + registry = Registry({url: {"results": [{"name": tag} for tag in tags], "next": None}}) + with isolated_cache(): + pinned = lookup(dependency(DOCKER, "postgres", "16.1-alpine"), registry) + floating = lookup(dependency(DOCKER, "postgres", "16-alpine"), registry) + assert versions(pinned) == {"16.1-alpine", "16.10-alpine", "17.6-alpine"} + assert pinned.newest[0] == "17.6-alpine", "16.10 is above 16.9, numerically" + assert versions(floating) == versions(pinned) + + def test_an_lts_tag_outranks_a_higher_innovation_number() -> None: """Measured 2026-10-02: MySQL's `lts` pointed at 9.7.2 while `innovation` pointed at 26.7.0. The highest number would move a production database from 8.4 LTS onto an innovation build.""" diff --git a/engineering_standards/test_standards_deps_verdict.py b/engineering_standards/test_standards_deps_verdict.py index 18259fd..52a5eb8 100644 --- a/engineering_standards/test_standards_deps_verdict.py +++ b/engineering_standards/test_standards_deps_verdict.py @@ -153,6 +153,22 @@ def test_a_floating_version_blocks_and_names_the_pin_to_use() -> None: assert "8.4.11" in verdict.message +def test_a_two_part_release_gets_its_patch_and_major_judged_like_any_other() -> None: + """PostgreSQL: the major is the line, the minor is the patch. `16.1` behind `16.10` blocks; + `17.6` existing while 16 has years of support left is news.""" + releases = Answer(releases=(("16.1-alpine", None, None), ("16.10-alpine", None, None), ("17.6-alpine", None, None))) + cycles = [Cycle("17", False, date(2029, 11, 8)), Cycle("16", False, date(2028, 11, 9))] + + def postgres(version: str) -> Dependency: + return Dependency(DOCKER, "postgres", version, Path("docker-compose.yml"), 4) + + behind = judge(postgres("16.1-alpine"), releases, cycles, {}, TODAY) + assert (behind.state, behind.target) == (NEWER, "16.10-alpine") + assert judge(postgres("16.10-alpine"), releases, cycles, {}, TODAY).state == MAJOR_AVAILABLE + floating = judge(postgres("16-alpine"), releases, cycles, {}, TODAY) + assert floating.state == UNPINNED and "16.10-alpine" in floating.message + + def test_an_unreachable_registry_does_not_block_by_itself() -> None: """Whether it fails is the caller's call: warned on a laptop, failed in CI.""" verdict = judge(RUFF, Answer(error="connection refused"), None, {}, TODAY) diff --git a/engineering_standards/test_standards_docs.py b/engineering_standards/test_standards_docs.py index 63dafda..31a264f 100644 --- a/engineering_standards/test_standards_docs.py +++ b/engineering_standards/test_standards_docs.py @@ -120,6 +120,14 @@ def test_frontmatter_value_comment_is_ignored() -> None: assert "docs-frontmatter" not in rules_fired(root) +def test_frontmatter_after_a_byte_order_mark_is_still_frontmatter() -> None: + """A BOM left in line 1 reads `\\ufeff---`, which is not a fence, so the whole block + vanished and both required keys were reported missing from a page that has them.""" + with repo() as root: + write(root, "docs/index.md", "---\naudience: dev\ntype: reference\n---\n") + assert "docs-frontmatter" not in rules_fired(root) + + # ---- docs-broken-link ---------------------------------------------------------------------- diff --git a/engineering_standards/test_standards_exemption_report.py b/engineering_standards/test_standards_exemption_report.py index 0b97c14..1c4508f 100644 --- a/engineering_standards/test_standards_exemption_report.py +++ b/engineering_standards/test_standards_exemption_report.py @@ -75,6 +75,14 @@ def test_undecodable_bytes_do_not_raise(): assert lines is not None and len(lines) == 2 +def test_a_byte_order_mark_is_not_part_of_line_one(): + """Left in, U+FEFF sits before whatever line 1 holds and hides it from every rule + anchored at the line start -- a Blazor `@page`, a header exemption marker.""" + with repo() as root: + path = write(root, "LogInd.razor", '@page "/log-ind"\n') + assert read_source_lines(path) == ['@page "/log-ind"'] + + # ---- what the report names -------------------------------------------------------------- diff --git a/engineering_standards/test_standards_gitattributes.py b/engineering_standards/test_standards_gitattributes.py index 0a42929..5c28e86 100644 --- a/engineering_standards/test_standards_gitattributes.py +++ b/engineering_standards/test_standards_gitattributes.py @@ -27,14 +27,20 @@ sys.path.insert(0, str(Path(__file__).resolve().parent)) from standards_gitattributes import ( # noqa: E402 + BASELINE, + BASELINE_FILE, GITATTRIBUTES_RULE, check_gitattributes, suggested_line, ) from standards_selftest import run_module_tests # noqa: E402 +# The repository the package sits in -- the pack itself, or a repo that adopted it. PACK_ROOT = Path(__file__).resolve().parent.parent -SEED = (PACK_ROOT / "templates" / ".gitattributes").read_text(encoding="utf-8") + +# Read beside the package, never from the pack root: the root's `templates/` does not ship, +# so this line once failed collection in every consuming repo (2026.10.11-3). +SEED = BASELINE_FILE.read_text(encoding="utf-8") SCRIPT = "#!/bin/sh\nset -eu\n" @@ -68,7 +74,14 @@ def test_a_shell_script_with_no_gitattributes_fires() -> None: found = flagged(root) assert list(found) == ["scripts/deploy.sh"] assert "*.sh text eol=lf" in found["scripts/deploy.sh"], "the finding names the line to add" - assert "templates/.gitattributes" in found["scripts/deploy.sh"], "and where the baseline is" + assert BASELINE in found["scripts/deploy.sh"], "and where the baseline is" + + +def test_the_baseline_a_finding_names_is_the_file_beside_the_package() -> None: + """The message points the reader at BASELINE; it must be the file the tests read, and both + must exist wherever the package runs -- in the pack and in every repo it is synced into.""" + assert BASELINE_FILE.is_file() + assert BASELINE_FILE.as_posix().endswith(BASELINE) def test_hooks_without_the_hooks_line_fire_even_when_sh_is_covered() -> None: diff --git a/engineering_standards/test_standards_layout.py b/engineering_standards/test_standards_layout.py index bc8d201..6826af4 100644 --- a/engineering_standards/test_standards_layout.py +++ b/engineering_standards/test_standards_layout.py @@ -264,12 +264,29 @@ def test_missing_env_is_reported() -> None: def test_a_complete_gitignore_is_clean() -> None: - assert gitignore_findings(".env\n") == [] + assert gitignore_findings(".env*\n") == [] + + +def test_a_bare_env_line_is_not_enough() -> None: + """A copy of .env is the same credential. `.env` alone left `.env.bak-staging` untracked + but not ignored in a production checkout (2026-10-10).""" + for spelling in (".env\n", ".env.local\n", "*.env\n", ".env\n.env.local\n"): + assert any(f.startswith("gitignore-build-output:'.env*'") for f in gitignore_findings(spelling)), spelling + + +def test_env_plus_its_copies_is_enough() -> None: + assert gitignore_findings(".env\n.env.*\n") == [] + + +def test_an_example_file_is_re_admitted_on_purpose() -> None: + """The negation that lets `.env.example` be committed must not count against coverage.""" + assert gitignore_findings(".env*\n!.env.example\n") == [] + assert any(".env*" in f for f in gitignore_findings(".env\n!.env.example\n")) def test_dotnet_requirements_apply_only_to_a_dotnet_repo() -> None: - clean = gitignore_findings(".env\n") - dotnet = gitignore_findings(".env\n", {"src/App.csproj": ""}) + clean = gitignore_findings(".env*\n") + dotnet = gitignore_findings(".env*\n", {"src/App.csproj": ""}) assert clean == [] assert any("bin/" in f for f in dotnet) assert any("obj/" in f for f in dotnet) @@ -278,18 +295,18 @@ def test_dotnet_requirements_apply_only_to_a_dotnet_repo() -> None: def test_the_visual_studio_template_spelling_satisfies_dotnet() -> None: """The most standard .NET .gitignore there is. A literal comparison reports it as missing both entries.""" - findings = gitignore_findings(".env\n[Bb]in/\n[Oo]bj/\n", {"src/App.csproj": ""}) + findings = gitignore_findings(".env*\n[Bb]in/\n[Oo]bj/\n", {"src/App.csproj": ""}) assert findings == [] def test_python_bytecode_accepts_either_spelling() -> None: project = {"pyproject.toml": "[project]\nname='x'\n"} - assert not any("__pycache__" in f for f in gitignore_findings(".env\n*.py[cod]\n.venv/\n", project)) - assert not any("__pycache__" in f for f in gitignore_findings(".env\n__pycache__/\n.venv/\n", project)) + assert not any("__pycache__" in f for f in gitignore_findings(".env*\n*.py[cod]\n.venv/\n", project)) + assert not any("__pycache__" in f for f in gitignore_findings(".env*\n__pycache__/\n.venv/\n", project)) def test_node_requirement_follows_package_json() -> None: - findings = gitignore_findings(".env\n", {"package.json": "{}"}) + findings = gitignore_findings(".env*\n", {"package.json": "{}"}) assert any("node_modules/" in f for f in findings) @@ -316,18 +333,18 @@ def test_a_present_dist_directory_must_be_ignored() -> None: """An external audit found a 33 MB `dist/` committed, churning a diff on every build. The requirement is CONDITIONAL on a dist/ existing, so a library that never builds one is not told to ignore it.""" - findings = gitignore_findings(".env\n", {"dist/main-ABC.js": "// bundle"}) + findings = gitignore_findings(".env*\n", {"dist/main-ABC.js": "// bundle"}) assert any("dist/" in finding for finding in findings) def test_an_ignored_dist_directory_is_clean() -> None: - findings = gitignore_findings(".env\ndist/\n", {"dist/main-ABC.js": "// bundle"}) + findings = gitignore_findings(".env*\ndist/\n", {"dist/main-ABC.js": "// bundle"}) assert not any("dist/" in finding for finding in findings) def test_no_dist_directory_means_no_dist_requirement() -> None: """The conditional half: absent a dist/, the rule asks for nothing.""" - findings = gitignore_findings(".env\n", {}) + findings = gitignore_findings(".env*\n", {}) assert not any("dist/" in finding for finding in findings) diff --git a/engineering_standards/test_standards_readonly.py b/engineering_standards/test_standards_readonly.py index 3e41046..0f52e5f 100644 --- a/engineering_standards/test_standards_readonly.py +++ b/engineering_standards/test_standards_readonly.py @@ -1,7 +1,7 @@ """Cases for the compose-read-only rule. The negatives decide whether this rule is keepable. It reads every compose file in the -estate, and the services it must stay silent on -- mysql, redis, mailhog -- are exactly the +estate, and the services it must stay silent on -- mysql, redis, mailpit -- are exactly the ones where read_only commonly prevents the container starting at all. If it fired on those, every finding's only correct resolution would be an exemption, and a rule whose findings are all exemptions is noise that gets switched off. @@ -82,8 +82,8 @@ def test_quiet_on_a_third_party_image() -> None: assert not findings(BASE, *service("mysql", "image: mysql:8.4", "restart: unless-stopped")) -def test_quiet_on_redis_and_mailhog() -> None: - for name, image in (("redis", "redis:7-alpine"), ("mailhog", "mailhog/mailhog")): +def test_quiet_on_redis_and_mailpit() -> None: + for name, image in (("redis", "redis:7-alpine"), ("mailpit", "axllent/mailpit:v1.31.4")): assert not findings(BASE, *service(name, f"image: {image}")), name diff --git a/engineering_standards/test_standards_secrets.py b/engineering_standards/test_standards_secrets.py index 031e60a..0f70359 100644 --- a/engineering_standards/test_standards_secrets.py +++ b/engineering_standards/test_standards_secrets.py @@ -44,6 +44,13 @@ BREVO = "xkeysib" + "-" + PAYLOAD AWS = "AKIA" + "J" * 16 GITHUB = "ghp_" + "b" * 36 +GITHUB_APP_CLASSIC = "ghs_" + "c" * 36 +GITHUB_REFRESH = "ghr_" + "r" * 76 +# The stateless installation-token format GitHub began rolling out in 2026: a ~520-character JWT +# behind the same `ghs_` prefix, so dots and base64url's `-` and `_` sit inside the payload. The +# `-` and `_` are placed early on purpose -- the old letters-and-digits-only pattern stopped at +# the first of them and let this token through. +GITHUB_APP_STATELESS = "ghs_" + "eyJ-hb_Gc" + "i" * 60 + "." + "d" * 380 + "." + "s" * 66 SLACK = "xoxb" + "-" + "1234567890" + "-" + PAYLOAD GOOGLE = "AIza" + "C" * 35 PEM = "-----BEGIN RSA " + "PRIVATE KEY" + "-----" @@ -66,6 +73,9 @@ def test_every_known_format_is_caught() -> None: ("brevo", BREVO), ("aws", AWS), ("github", GITHUB), + ("github app classic", GITHUB_APP_CLASSIC), + ("github app stateless", GITHUB_APP_STATELESS), + ("github refresh", GITHUB_REFRESH), ("slack", SLACK), ("google", GOOGLE), ("pem", PEM), @@ -89,6 +99,7 @@ def test_the_documented_prefix_alone_is_not_a_finding() -> None: detector itself clean -- a rule that fires on its own documentation gets exempted on sight.""" assert known_format("use sk_live_ keys in production") is None assert known_format("the AKIA prefix identifies an AWS key") is None + assert known_format("installation tokens start with ghs_ and may contain dots") is None # ---- tier 2: shape --------------------------------------------------------------------------- @@ -218,6 +229,7 @@ def test_the_finding_never_quotes_the_credential() -> None: the match relocates the leak into the terminal and the CI log rather than closing it.""" for line, secret in ( (f' "Stripe:SecretKey": "{STRIPE}"', STRIPE), + (f' "GitHub:Token": "{GITHUB_APP_STATELESS}"', GITHUB_APP_STATELESS), (' "Password": "Sommer2026!"', "Sommer2026!"), ): message = found("appsettings.json", line)[0] diff --git a/engineering_standards/test_standards_seed_credentials.py b/engineering_standards/test_standards_seed_credentials.py new file mode 100644 index 0000000..5ba5f0b --- /dev/null +++ b/engineering_standards/test_standards_seed_credentials.py @@ -0,0 +1,307 @@ +"""Cases for the seeded-credential-config rule. + +THE CASE THAT MOTIVATED IT is ellengaard-dk's restore (2026-10-12): `.env.example` documented a +local admin password key, compose passed it into the container, and the restore script created +an administrator from it -- the very shape secrets.md recommended until that day. Each of its +three appearances is pinned below, and the rule must reach all three through the real +dispatcher, because two of them live in files the dispatcher returns early for. + +The negatives matter as much: a database root password, an SMTP password, an admin e-mail +address and a markdown page that NAMES the forbidden key must all stay quiet -- a rule that +fired on those would be firing on the right answers and the documentation of the wrong one. + +THE KEYS ARE ASSEMBLED AT RUNTIME, so this file cannot match its own detector when the pack +lints itself: a literal environment read of a seeded key, written out here, would be a finding +in the pack's own gate. + +Run: python test_standards_seed_credentials.py (or pytest) +""" + +from __future__ import annotations + +import contextlib +import importlib.util +import io +import sys +import tempfile +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parent)) + +from standards_config import CheckConfig # noqa: E402 +from standards_dispatch import check_migration_file, check_source_file # noqa: E402 +from standards_exemptions import MIN_EXEMPTION_REASON_LENGTH # noqa: E402 +from standards_pack_identity import PACK_DIRECTORY # noqa: E402 +from standards_scope import should_check, should_check_migration # noqa: E402 +from standards_seed_credentials import SEEDED_RULE, check_seeded_credentials, is_seeded_key # noqa: E402 +from standards_selftest import run_module_tests # noqa: E402 + +PW = "PASS" + "WORD" +ADMIN = "LOCAL_ADMIN_" + PW +INVOTRACK = "INVOTRACK_DEV_ADMIN_" + PW +EXEMPT = "pgAdmin's own documented login for a local-only container, not an estate seeder" +assert len(EXEMPT) >= MIN_EXEMPTION_REASON_LENGTH, "fixture must clear the reason floor" + + +def found(name: str, *lines: str) -> list[int]: + """1-based line numbers the rule reports for this file.""" + return [v.line for v in check_seeded_credentials(Path(name), list(lines))] + + +def dispatched(name: str, *lines: str) -> list[str]: + """Rule ids the REAL entry point yields -- the half that proves the rule is reachable.""" + return [v.rule for v in check_source_file(Path(name), list(lines), CheckConfig(), {}, Path("."))] + + +# ---- the name test --------------------------------------------------------------------------- + + +def test_seeded_account_password_names_match() -> None: + for key in ( + ADMIN, + INVOTRACK, + "Demo:Admin" + "Password", + "SeedUser" + "Pwd", + "SUPERUSER_" + "PASS", + "DEFAULT_USER_" + PW, + "Seed:" + "Password", + "demo_" + PW.lower(), + ): + assert is_seeded_key(key), key + + +def test_other_passwords_and_admin_settings_do_not_match() -> None: + for key in ( + "MYSQL_ROOT_" + PW, + "WORDPRESS_DB_" + PW, + "SMTP_" + PW, + "ADMIN_EMAIL", + "TURNSTILE_SECRET", + PW + "_MIN_LENGTH", + "Admin" + "PasswordPolicy", + "RABBITMQ_DEFAULT_PASS" + "PHRASE_FILE", + ): + assert not is_seeded_key(key), key + + +# ---- declarations ---------------------------------------------------------------------------- + + +def test_env_example_key_is_flagged_set_or_commented() -> None: + assert found(".env.example", "COMPOSE_FILE=docker-compose.yml", f"{ADMIN}=") == [2] + assert found(".env.example", f"# {ADMIN}=") == [1] + + +def test_env_example_database_password_is_clean() -> None: + assert not found(".env.example", f"MYSQL_ROOT_{PW}=", f"WORDPRESS_DB_{PW}=") + + +def test_dotenv_itself_is_never_opened() -> None: + """`.env` is decided by name elsewhere and never read -- not even by this rule.""" + assert not found(".env", f"{ADMIN}=anything") + + +def test_compose_declaration_and_interpolation_are_flagged_once_per_line() -> None: + assert found("docker-compose.yml", " environment:", f" {ADMIN}: ${{{ADMIN}:-}}") == [2] + assert found("docker-compose.yml", f" - {INVOTRACK}=${{SEED:?x}}") == [1] + + +def test_compose_database_root_password_is_clean() -> None: + assert not found("docker-compose.yml", f" MYSQL_ROOT_{PW}: ${{MYSQL_ROOT_{PW}:?set it}}") + + +def test_appsettings_nested_path_is_flagged_on_its_line() -> None: + lines = ["{", ' "Demo": {', ' "Email": "localadmin@allegroit.dk",', f' "Admin{PW.title()}": ""', " }", "}"] + assert found("appsettings.Development.json", *lines) == [4] + + +def test_appsettings_section_named_seed_is_flagged() -> None: + lines = ["{", ' "Seed": {', f' "{PW.title()}": ""', " }", "}"] + assert found("appsettings.json", *lines) == [3] + + +def test_appsettings_with_comments_falls_back_to_line_keys() -> None: + lines = ["{", " // dev only", f' "Admin{PW.title()}": ""', "}"] + assert found("appsettings.Development.json", *lines) == [3] + + +def test_appsettings_connection_string_is_clean() -> None: + assert not found("appsettings.json", "{", ' "ConnectionStrings": { "Default": "Server=db" }', "}") + + +# ---- reads in source ------------------------------------------------------------------------- + + +def test_reads_are_flagged_in_every_language() -> None: + reads = { + "seed.php": "$pw = getenv('" + ADMIN + "');", + "seed2.php": "$pw = $_ENV['" + ADMIN + "'];", + "seed.py": "pw = os.environ['" + ADMIN + "']", + "seed2.py": "pw = os.getenv('" + ADMIN + "', '')", + "Seeder.cs": 'var pw = configuration["Demo:Admin' + PW.title() + '"];', + "Seeder2.cs": 'var pw = Environment.GetEnvironmentVariable("' + INVOTRACK + '");', + "seed.ts": "const pw = process.env." + ADMIN + ";", + "restore.sh": 'wp user update localadmin --user_pass="${' + ADMIN + ':-}"', + "seed.ps1": "$pw = $env:" + ADMIN, + } + for name, line in reads.items(): + assert found(name, line) == [1], name + + +def test_reads_of_other_passwords_are_clean() -> None: + assert not found("restore.sh", 'export MYSQL_PWD="$WORDPRESS_DB_' + PW + '"') + assert not found("seed.py", "pw = os.environ['SMTP_" + PW + "']") + + +def test_markdown_naming_the_key_is_clean() -> None: + """Documentation of the forbidden shape is not the shape.""" + assert not found("README.md", f"Never add `{ADMIN}` to .env.example.") + + +# ---- exemption ------------------------------------------------------------------------------- + + +def test_a_line_exemption_silences_it() -> None: + assert not found( + "docker-compose.yml", + f" # standards: {SEEDED_RULE} exempt -- {EXEMPT}", + " PGADMIN_DEFAULT_" + PW + ": ${PGADMIN_DEFAULT_" + PW + ":-}", + ) + + +# ---- the dispatcher: the rule must survive every early return -------------------------------- + + +def test_dispatcher_reaches_env_example_compose_and_appsettings() -> None: + assert SEEDED_RULE in dispatched(".env.example", f"{ADMIN}=") + assert SEEDED_RULE in dispatched("docker-compose.yml", f" {ADMIN}: ${{{ADMIN}:-}}") + assert SEEDED_RULE in dispatched("appsettings.json", "{", f' "Admin{PW.title()}": ""', "}") + assert SEEDED_RULE in dispatched("restore.sh", 'echo "${' + ADMIN + '}"') + + +# ---- migrations: the one excluded directory this rule reads ---------------------------------- + + +DJANGO_SEED = ( + "def create_admin(apps, schema_editor):", + " User = apps.get_model('users', 'User')", + " User.objects.create_superuser('admin', password=os.environ['DJANGO_SUPER" + "USER_" + PW + "'])", +) + + +def test_a_migration_reaches_the_migration_route_and_nothing_else_does() -> None: + root, config = Path("/repo"), CheckConfig() + for relative in ("app/users/migrations/0001_initial.py", "src/Data/Migrations/20260101_Init.cs"): + assert should_check_migration(root / relative, root, config), relative + assert not should_check(root / relative, root, config), f"{relative} must stay out of every other rule" + for relative in ( + "app/users/models.py", # not a migration: the ordinary route has it + "src/Data/Migrations/20260101_Init.Designer.cs", # a generated name stays skipped + "node_modules/pkg/migrations/0001.js", # somebody else's migration + "app/users/migrations/README.md", # not source + ): + assert not should_check_migration(root / relative, root, config), relative + + +def test_a_repo_exclusion_still_wins_over_the_migration_route() -> None: + root = Path("/repo") + config = CheckConfig(extra_excluded_fragments=("/legacy/",)) + assert not should_check_migration(root / "legacy/app/migrations/0001_initial.py", root, config) + + +def test_the_migration_route_runs_this_rule_and_only_this_rule() -> None: + """A 900-line generated migration would fail file-length on the ordinary route.""" + lines = [*DJANGO_SEED, *([" pass"] * 900)] + rules = {v.rule for v in check_migration_file(Path("app/users/migrations/0001_initial.py"), lines)} + assert rules == {SEEDED_RULE}, rules + + +def test_a_generated_migration_is_quiet() -> None: + lines = ["class Migration(migrations.Migration):", " dependencies = [('users', '0001_initial')]"] + assert not list(check_migration_file(Path("app/users/migrations/0002_auto.py"), lines)) + + +def test_the_whole_tree_scan_and_the_rule_agree_on_a_migration() -> None: + """THE INCONSISTENCY THIS PINS (2026-10-14): `check-source-limits.py --root .` called + allegro-it-services clean while the rule, walking the same tree, found this exact shape.""" + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + migration = root / "app" / "users" / "migrations" / "0001_initial.py" + migration.parent.mkdir(parents=True) + migration.write_text("\n".join(DJANGO_SEED) + "\n", encoding="utf-8") + output = io.StringIO() + with contextlib.redirect_stdout(output), contextlib.redirect_stderr(io.StringIO()): + code = _driver().main(["--root", str(root), "--no-baseline"]) + assert code == 1, output.getvalue() + assert f"app/users/migrations/0001_initial.py:3: [{SEEDED_RULE}]" in output.getvalue() + + +def _driver(): + spec = importlib.util.spec_from_file_location("driver", PACKAGE_DIRECTORY / "check-source-limits.py") + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +# ---- quiet on real source -------------------------------------------------------------------- +# +# THE PACKAGE DIRECTORY, NEVER `parents[1]`. This file ships to every consumer and runs there +# under `pytest engineering_standards/`. `parents[1]` is the pack's root here and the CONSUMER's +# root there: on 2026-10-14 this case walked allegro-it-services for 35 s, node_modules +# included, and failed its deploy on a migration of that repo's own -- a real finding, reported +# from the wrong place, in a repo whose own scan had not been asked. The directory beside this +# file holds the same files in every repo it lands in, so "the pack is clean" means one thing +# everywhere. The rest of the pack's tree is read by dev/test_pack_self.py, which never ships. + + +def scan_root_for(test_file: Path) -> Path: + """What the self-test reads, given where this test file sits.""" + return test_file.resolve().parent + + +PACKAGE_DIRECTORY = scan_root_for(Path(__file__)) + + +def findings_under(directory: Path) -> list[str]: + """`path:line` for every finding the rule makes under `directory`.""" + noisy = [] + for path in sorted(directory.rglob("*")): + if not path.is_file() or "__pycache__" in path.parts: + continue + try: + lines = path.read_text(encoding="utf-8").splitlines() + except UnicodeDecodeError, OSError: + continue + noisy += [f"{path.relative_to(directory).as_posix()}:{v.line}" for v in check_seeded_credentials(path, lines)] + return noisy + + +def test_the_self_test_reads_the_package_directory() -> None: + assert PACKAGE_DIRECTORY.name == PACK_DIRECTORY, PACKAGE_DIRECTORY + + +def test_a_consumer_tree_does_not_leak_into_the_self_test() -> None: + """The allegro-it-services shape: the pack beside a repo whose own migration seeds an admin.""" + with tempfile.TemporaryDirectory() as directory: + consumer = Path(directory) + package = consumer / PACK_DIRECTORY + package.mkdir() + shipped_test = package / Path(__file__).name + shipped_test.write_text("x = 1\n", encoding="utf-8") + migration = consumer / "packages" / "backend" / "apps" / "users" / "migrations" / "0001_initial.py" + migration.parent.mkdir(parents=True) + migration.write_text("\n".join(DJANGO_SEED) + "\n", encoding="utf-8") + + assert findings_under(consumer), "fixture has no teeth: the consumer's migration must be a finding" + assert scan_root_for(shipped_test) == package.resolve() + assert findings_under(scan_root_for(shipped_test)) == [] + + +def test_the_shipped_package_is_clean() -> None: + """Every file the pack ships into `engineering_standards/`, read by the rule: zero findings.""" + noisy = findings_under(PACKAGE_DIRECTORY) + assert not noisy, noisy + + +if __name__ == "__main__": + sys.exit(run_module_tests(globals(), "seeded-credential-config cases")) diff --git a/engineering_standards/test_standards_tls.py b/engineering_standards/test_standards_tls.py index d28ca99..585a7a0 100644 --- a/engineering_standards/test_standards_tls.py +++ b/engineering_standards/test_standards_tls.py @@ -30,7 +30,7 @@ from standards_selftest import run_module_tests # noqa: E402 from standards_tls import TLS_RULE, check_tls_verification # noqa: E402 -EXEMPT = "local mailhog endpoint with a self-signed certificate; never reached in production" +EXEMPT = "local mailpit endpoint with a self-signed certificate; never reached in production" assert len(EXEMPT) >= MIN_EXEMPTION_REASON_LENGTH, "fixture must clear the reason floor" diff --git a/engineering_standards/test_verify_cli.py b/engineering_standards/test_verify_cli.py index 1688e2d..4da6b95 100644 --- a/engineering_standards/test_verify_cli.py +++ b/engineering_standards/test_verify_cli.py @@ -30,7 +30,7 @@ def make_repo(root: Path) -> Path: (root / "engineering_standards").mkdir(parents=True) for source in PACK_DIRECTORY.glob("*.py"): shutil.copy2(source, root / "engineering_standards" / source.name) - (root / ".gitignore").write_text(".env\n", encoding="utf-8") + (root / ".gitignore").write_text(".env*\n", encoding="utf-8") # A clean fixture must satisfy every repo-level rule, so these tests exercise only the # CLI: gitignore above, and the documentation dimension's index here. (root / "docs").mkdir() @@ -80,7 +80,7 @@ def _adopted_repo_with_a_newer_ruff(root: Path, decisions: list[dict]) -> dict[s so the real `deps.py check` runs end to end through verify without touching the network.""" make_repo(root) (root / ".gitignore").write_text( - ".env\n__pycache__/\n.venv/\n", encoding="utf-8" + ".env*\n__pycache__/\n.venv/\n", encoding="utf-8" ) # a requirements file makes it Python (root / "requirements.txt").write_text("ruff==0.16.5\n", encoding="utf-8") record = {"format": 1, "dependencies": {"pypi:ruff": decisions}}