diff --git a/.devcontainer/devcontainer.json b/.devcontainer/devcontainer.json index 5268c1c..bba51df 100644 --- a/.devcontainer/devcontainer.json +++ b/.devcontainer/devcontainer.json @@ -1,9 +1,3 @@ -// SPDX-License-Identifier: MPL-2.0 -// Copyright (c) 2026 Jonathan D.A. Jewell (hyperpolymath) -// -// Dev Container configuration for systemet -// Works with: VS Code Dev Containers, GitHub Codespaces, Gitpod -// Container runtime: Podman (recommended) or any OCI-compliant runtime { "name": "systemet", diff --git a/.devcontainer/devcontainer.json.license b/.devcontainer/devcontainer.json.license new file mode 100644 index 0000000..296665a --- /dev/null +++ b/.devcontainer/devcontainer.json.license @@ -0,0 +1,2 @@ +SPDX-FileCopyrightText: 2026 Jonathan D.A. Jewell (hyperpolymath) +SPDX-License-Identifier: MPL-2.0 diff --git a/.editorconfig b/.editorconfig index a466807..ff8de6c 100644 --- a/.editorconfig +++ b/.editorconfig @@ -69,3 +69,25 @@ indent_size = 2 indent_style = space indent_size = 4 +# Prose, legal text and proofs use alignment within paragraphs and expressions. +[*.{md,adoc,agda,lean}] +indent_size = unset + +[LICENSES/CC-BY-SA-4.0.txt] +indent_size = unset + +[docs/legal/EXHIBIT-{A-ETHICAL-USE,B-QUANTUM-SAFE}.txt] +indent_size = unset + +# Embedded shell/JQ and aligned template data use a different indent width. +[{Justfile,.machine_readable/contractiles/Justfile,.github/scripts/classify-issue.jq}] +indent_size = unset + +[.github/workflows/{label-triage,labels,openssf-compliance,secret-scanner}.yml] +indent_size = unset + +[{scripts/scan-dangerous.sh,scripts/validate-template.sh,tests/e2e/template_instantiation_test.sh}] +indent_size = unset + +[{.machine_readable/contractiles/trust/Trustfile.a2ml,machine-readable-design/canonical-directory-structure/Trustfile.a2ml,.machine_readable/contractiles/intend/intend.k9.ncl,systemet_chora.deed,verification/proofs/lean4/lake-manifest.json}] +indent_size = unset diff --git a/.githooks/validate-a2ml.sh b/.githooks/validate-a2ml.sh index b053676..869fe86 100755 --- a/.githooks/validate-a2ml.sh +++ b/.githooks/validate-a2ml.sh @@ -62,9 +62,27 @@ WARNINGS=0 # --------------------------------------------------------------------------- # Usage: annotate # level: error | warning | notice +escape_data() { + local value="$1" + value="${value//'%'/'%25'}" + value="${value//$'\r'/'%0D'}" + value="${value//$'\n'/'%0A'}" + printf '%s' "$value" +} + +escape_property() { + local value + value="$(escape_data "$1")" + value="${value//':'/'%3A'}" + value="${value//','/'%2C'}" + printf '%s' "$value" +} + annotate() { local level="$1" file="$2" line="$3" message="$4" - echo "::${level} file=${file},line=${line}::${message}" + printf '::%s file=%s,line=%s::%s\n' \ + "$level" "$(escape_property "$file")" \ + "$(escape_property "$line")" "$(escape_data "$message")" } # --------------------------------------------------------------------------- @@ -267,6 +285,8 @@ validate_a2ml() { # --- Check 4: Section heading syntax --- # Validate that [section] headings are well-formed (no unclosed brackets) line_num=0 + # report_issue uses the file path as an annotation label; it writes to stdout. + # shellcheck disable=SC2094 while IFS= read -r line; do line_num=$((line_num + 1)) # Lines starting with [ should have a matching ] @@ -288,8 +308,11 @@ echo "::group::A2ML Manifest Validation" echo "Scanning ${SCAN_PATH} for .a2ml files..." echo "" -# Find all .a2ml files, excluding .git directory -mapfile -t a2ml_candidates < <(find "$SCAN_PATH" -name '*.a2ml' -not -path '*/.git/*' -type f | sort) +# Null-delimited discovery preserves unusual paths; a broken find/sort must fail. +discovery_tmp="$(mktemp)" +trap 'rm -f "$discovery_tmp"' EXIT +find "$SCAN_PATH" -name '*.a2ml' -not -path '*/.git/*' -type f -print0 | sort -z > "$discovery_tmp" +mapfile -d '' -t a2ml_candidates < "$discovery_tmp" # Apply paths-ignore filter a2ml_files=() @@ -319,7 +342,7 @@ echo "Found ${#a2ml_files[@]} .a2ml file(s)" echo "" for file in "${a2ml_files[@]}"; do - echo " Validating: ${file}" + printf ' Validating: %s\n' "$(escape_data "$file")" validate_a2ml "$file" done diff --git a/.githooks/validate-k9.sh b/.githooks/validate-k9.sh index c83e290..99a392b 100755 --- a/.githooks/validate-k9.sh +++ b/.githooks/validate-k9.sh @@ -64,9 +64,27 @@ VALID_LEVELS="kennel yard hunt" # --------------------------------------------------------------------------- # Helper: emit GitHub annotation # --------------------------------------------------------------------------- +escape_data() { + local value="$1" + value="${value//'%'/'%25'}" + value="${value//$'\r'/'%0D'}" + value="${value//$'\n'/'%0A'}" + printf '%s' "$value" +} + +escape_property() { + local value + value="$(escape_data "$1")" + value="${value//':'/'%3A'}" + value="${value//','/'%2C'}" + printf '%s' "$value" +} + annotate() { local level="$1" file="$2" line="$3" message="$4" - echo "::${level} file=${file},line=${line}::${message}" + printf '::%s file=%s,line=%s::%s\n' \ + "$level" "$(escape_property "$file")" \ + "$(escape_property "$line")" "$(escape_data "$message")" } # --------------------------------------------------------------------------- @@ -98,13 +116,9 @@ normalise_level() { raw="${raw#*=}" # Remove everything before = raw="${raw//\"/}" # Remove double quotes raw="${raw//\'/}" # Remove single quotes (Nickel tick) - raw="${raw//,/}" # Remove trailing commas - raw="${raw## }" # Trim leading space - raw="${raw%% }" # Trim trailing space - raw="${raw%%#*}" # Remove inline comments - raw="${raw## }" # Trim again - raw="${raw%% }" - echo "${raw,,}" # Lowercase + raw="${raw#"${raw%%[![:space:]]*}"}" # Trim leading whitespace + raw="${raw%"${raw##*[![:space:]]}"}" # Trim trailing whitespace + echo "${raw,,}" # Lowercase } # --------------------------------------------------------------------------- @@ -165,77 +179,54 @@ validate_k9() { local in_pedigree=false local pedigree_depth=0 + # Split each line at record delimiters outside quoted strings. A comment + # ends the line, so its contents cannot count as assignments or braces. + local segment_re='^(([^"#,{}]|"([^"\\]|\\.)*")*)([#{},]|$)' + local field_re='^[[:space:]]*(name|version|schema_version|leash|security_level|signature|signature_required)[[:space:]]*=(.*)$' + local remaining segment delimiter + line_num=0 - while IFS= read -r line; do + while IFS= read -r line || [[ -n "$line" ]]; do line_num=$((line_num + 1)) - # Detect pedigree block start. Note: do NOT `continue` here — the - # `pedigree = {` line itself contains the opening brace that - # establishes the block. Falling through to the brace counter - # below makes depth start at 1, so a subsequent `security = {…},` - # closing brace correctly takes depth to 1 (not 0), keeping us - # inside the pedigree block when later fields (name/version/leash) - # are checked. Previously the `continue` skipped this opening - # brace, depth started at 0, and the first nested block's close - # prematurely terminated the validator's view of the pedigree — - # making `pedigree.metadata.name` invisible. if [[ "$line" =~ ^[[:space:]]*pedigree[[:space:]]*= ]]; then has_pedigree=true in_pedigree=true pedigree_depth=0 - # fall through fi if [[ "$in_pedigree" == "true" ]]; then - # Track brace depth to know when pedigree block ends - local opens closes - opens="${line//[^\{]/}" - closes="${line//[^\}]/}" - pedigree_depth=$(( pedigree_depth + ${#opens} - ${#closes} )) - - if [[ $pedigree_depth -le 0 && "$has_pedigree" == "true" ]]; then - # Check this final line too before leaving - : - fi - - # Check for name field within pedigree.metadata or pedigree directly. - # Two patterns cover both multi-line and single-line pedigrees: - # 1. ^[[:space:]]+name[[:space:]]*= — the normal multi-line case where - # `name = "..."` appears on its own indented line. - # 2. [[:space:]]name[[:space:]]*= — inline within a single-line - # pedigree assignment such as: - # pedigree = component_pedigree & { name = "foo" } - # (root cause: developer-ecosystem@baab1534 — single-line form - # was missed entirely because the pedigree block opened and - # closed in one line, never reaching the ^[[:space:]]+ check on - # a subsequent iteration.) - if [[ "$line" =~ ^[[:space:]]+name[[:space:]]*= ]] || \ - [[ "$line" =~ [[:space:]]name[[:space:]]*= ]]; then - has_pedigree_name=true - fi - - # Check for version field - if [[ "$line" =~ ^[[:space:]]+(version|schema_version)[[:space:]]*= ]] || \ - [[ "$line" =~ [[:space:]](version|schema_version)[[:space:]]*= ]]; then - has_pedigree_version=true - fi - - # Check for security level (leash field) - if [[ "$line" =~ ^[[:space:]]+(leash|security_level)[[:space:]]*= ]]; then - has_security_level=true - security_level_value="$(normalise_level "$line")" - security_level_line=$line_num - fi - - # Check for signature fields - if [[ "$line" =~ ^[[:space:]]+(signature|signature_required)[[:space:]]*= ]]; then - has_signature_field=true - fi - - # End of pedigree block - if [[ $pedigree_depth -le 0 && "$has_pedigree" == "true" && "$line" == *"}"* ]]; then - in_pedigree=false - fi + remaining="$line" + while [[ -n "$remaining" && "$remaining" =~ $segment_re ]]; do + segment="${BASH_REMATCH[1]}" + delimiter="${BASH_REMATCH[4]}" + remaining="${remaining:"${#BASH_REMATCH[0]}"}" + + if [[ "$segment" =~ $field_re ]]; then + case "${BASH_REMATCH[1]}" in + name) has_pedigree_name=true ;; + version|schema_version) has_pedigree_version=true ;; + leash|security_level) + has_security_level=true + security_level_value="$(normalise_level "$segment")" + security_level_line=$line_num + ;; + signature|signature_required) has_signature_field=true ;; + esac + fi + + case "$delimiter" in + '{') pedigree_depth=$((pedigree_depth + 1)) ;; + '}') + pedigree_depth=$((pedigree_depth - 1)) + if [[ $pedigree_depth -le 0 ]]; then + in_pedigree=false + break + fi + ;; + '#'|'') break ;; + esac + done fi # Also check for signature fields outside pedigree (top-level) @@ -295,8 +286,11 @@ echo "::group::K9 Configuration Validation" echo "Scanning ${SCAN_PATH} for K9 files (.k9, .k9.ncl)..." echo "" -# Find all K9 files, excluding .git directory -mapfile -t k9_candidates < <(find "$SCAN_PATH" \( -name '*.k9' -o -name '*.k9.ncl' \) -not -path '*/.git/*' -type f | sort) +# Null-delimited discovery preserves unusual paths; a broken find/sort must fail. +discovery_tmp="$(mktemp)" +trap 'rm -f "$discovery_tmp"' EXIT +find "$SCAN_PATH" \( -name '*.k9' -o -name '*.k9.ncl' \) -not -path '*/.git/*' -type f -print0 | sort -z > "$discovery_tmp" +mapfile -d '' -t k9_candidates < "$discovery_tmp" # Apply paths-ignore filter k9_files=() @@ -326,7 +320,7 @@ echo "Found ${#k9_files[@]} K9 file(s)" echo "" for file in "${k9_files[@]}"; do - echo " Validating: ${file}" + printf ' Validating: %s\n' "$(escape_data "$file")" validate_k9 "$file" done diff --git a/.githooks/validate-stapeln-manifest.sh b/.githooks/validate-stapeln-manifest.sh new file mode 100755 index 0000000..99b5ff0 --- /dev/null +++ b/.githooks/validate-stapeln-manifest.sh @@ -0,0 +1,25 @@ +#!/usr/bin/env bash +# SPDX-License-Identifier: MPL-2.0 +# Validate the Cerro Torre manifest using a sample numeric template port. +# Usage: validate-stapeln-manifest.sh +set -euo pipefail + +path="${1:?usage: $0 }" +[ -r "$path" ] || { echo "$path: cannot read manifest" >&2; exit 1; } + +# Render the template placeholder with a sample port, then pull the +# listen_tcp key out of the [security.network] table. +line=$(sed 's/{{PORT}}/8080/g' "$path" | awk ' + /^[[:space:]]*\[/ { in_net = ($0 ~ /^[[:space:]]*\[security\.network\][[:space:]]*(#.*)?$/) ; next } + in_net && /^[[:space:]]*listen_tcp[[:space:]]*=/ { print; exit } +') + +if [ -z "$line" ]; then + echo "$path: security.network.listen_tcp is missing" >&2 + exit 1 +fi + +if ! printf '%s\n' "$line" | grep -Eq '^[[:space:]]*listen_tcp[[:space:]]*=[[:space:]]*\[[[:space:]]*([0-9]+([[:space:]]*,[[:space:]]*[0-9]+)*)?[[:space:]]*,?[[:space:]]*\][[:space:]]*(#.*)?$'; then + echo "$path: security.network.listen_tcp must be an array of integers" >&2 + exit 1 +fi diff --git a/.github/CODE_OF_CONDUCT.md b/.github/CODE_OF_CONDUCT.md index 83a1028..832dd2d 100644 --- a/.github/CODE_OF_CONDUCT.md +++ b/.github/CODE_OF_CONDUCT.md @@ -4,7 +4,7 @@ Copyright (c) Jonathan D.A. Jewell --> # Code of Conduct - - + # You are in the hyperpolymath estate — orient before acting @@ -67,4 +67,4 @@ Deny: **Nix, TypeScript, Python, Go, AGPL**. JS runtimes in preference order **B - **Golden path** (ANCHOR) — `just test && just quality` → Core tests pass; Quality gates pass; No unresolved critical security findings. - **State** — lifecycle active; maturity experimental. Phase, blockers and next action: `docs/status/JOURNAL.adoc`. - + diff --git a/LICENSE b/LICENSE index 14e2f77..a612ad9 100644 --- a/LICENSE +++ b/LICENSE @@ -35,7 +35,7 @@ Mozilla Public License Version 2.0 means any form of the work other than Source Code Form. 1.7. "Larger Work" - means a work that combines Covered Software with other material, in + means a work that combines Covered Software with other material, in a separate file or files, that is not Covered Software. 1.8. "License" diff --git a/LICENSES/CC-BY-SA-4.0.txt b/LICENSES/CC-BY-SA-4.0.txt index 2d58298..7d4f96c 100644 --- a/LICENSES/CC-BY-SA-4.0.txt +++ b/LICENSES/CC-BY-SA-4.0.txt @@ -425,4 +425,3 @@ the avoidance of doubt, this paragraph does not form part of the public licenses. Creative Commons may be contacted at creativecommons.org. - diff --git a/benches/template_bench.sh b/benches/template_bench.sh index 5fb58a8..35f5693 100755 --- a/benches/template_bench.sh +++ b/benches/template_bench.sh @@ -13,7 +13,6 @@ OUTPUT_FORMAT="${2:-human}" # human | json | csv # ANSI colors BLUE='\033[0;34m' GREEN='\033[0;32m' -YELLOW='\033[1;33m' NC='\033[0m' # No Color log_info() { @@ -24,14 +23,6 @@ log_pass() { echo -e "${GREEN}✓${NC} $*" } -# Ensure we have required commands -command -v /usr/bin/time >/dev/null 2>&1 || { - echo "Warning: /usr/bin/time not available, using built-in time" - TIME_CMD="time" -} - -TIME_CMD="/usr/bin/time -f %e" 2>/dev/null || TIME_CMD="time" - echo "" echo "═══════════════════════════════════════════════════════════════════════════════" echo "Template Benchmarks" diff --git a/container/stapeln/compose.example.toml b/container/stapeln/compose.example.toml index d8d717c..81ad7ea 100644 --- a/container/stapeln/compose.example.toml +++ b/container/stapeln/compose.example.toml @@ -28,13 +28,11 @@ ports = ["8080:8080"] # Environment variables passed into the container at startup. # These override defaults in the Containerfile ENV directives. -environment = { - RUST_LOG = "info", # Rust log level (trace, debug, info, warn, error) - APP_HOST = "[::]", # Listen on all interfaces (IPv4 + IPv6) - APP_PORT = "8080", # Internal container port - APP_LOG_FORMAT = "json", # Structured logging for selur/vordr - APP_DATA_DIR = "/data", # Persistent data directory (matches VOLUME) -} +environment.RUST_LOG = "info" # Rust log level (trace, debug, info, warn, error) +environment.APP_HOST = "[::]" # Listen on all interfaces (IPv4 + IPv6) +environment.APP_PORT = "8080" # Internal container port +environment.APP_LOG_FORMAT = "json" # Structured logging for selur/vordr +environment.APP_DATA_DIR = "/data" # Persistent data directory (matches VOLUME) # Bind-mount a named volume for persistent data. # Format: "volume-name:/container/path" @@ -60,12 +58,10 @@ ports = ["4000:4000"] # The worker connects to the Rust API over the internal selur network. # Service names resolve as hostnames within the compose network. -environment = { - API_URL = "http://rust-api:8080/api/v1", # Internal service discovery - MIX_ENV = "prod", # Elixir release mode - APP_LOG_FORMAT = "json", # Match structured logging format - POOL_SIZE = "10", # DB connection pool size -} +environment.API_URL = "http://rust-api:8080/api/v1" # Internal service discovery +environment.MIX_ENV = "prod" # Elixir release mode +environment.APP_LOG_FORMAT = "json" # Match structured logging format +environment.POOL_SIZE = "10" # DB connection pool size # depends_on ensures the Rust API starts before the worker. # Note: This only waits for the container to start, not for the health check. @@ -90,17 +86,15 @@ image = "ghcr.io/hyperpolymath/svalinn:latest.ctp" # External-facing ports: HTTPS (443) and HTTP->HTTPS redirect (80). ports = ["443:443", "80:80"] -environment = { - # Backend routing: svalinn proxies to internal services. - SVALINN_BACKEND = "http://rust-api:8080", - SVALINN_WORKER_BACKEND = "http://elixir-worker:4000", +# Backend routing: svalinn proxies to internal services. +environment.SVALINN_BACKEND = "http://rust-api:8080" +environment.SVALINN_WORKER_BACKEND = "http://elixir-worker:4000" - # Policy file: mounted from the svalinn-config volume. - SVALINN_POLICY_FILE = "/etc/svalinn/gatekeeper.yaml", +# Policy file: mounted from the svalinn-config volume. +environment.SVALINN_POLICY_FILE = "/etc/svalinn/gatekeeper.yaml" - # Auto-provision TLS certificates (Let's Encrypt). - SVALINN_TLS_AUTO = "true", -} +# Auto-provision TLS certificates (Let's Encrypt). +environment.SVALINN_TLS_AUTO = "true" # Mount .gatekeeper.yaml as read-only policy configuration. volumes = ["svalinn-config:/etc/svalinn:ro"] diff --git a/container/stapeln/compose.toml b/container/stapeln/compose.toml index 6c33ce4..bd5e97a 100644 --- a/container/stapeln/compose.toml +++ b/container/stapeln/compose.toml @@ -25,15 +25,13 @@ version = "1.0" # ============================================================================ # Primary application service -[services.{{SERVICE_NAME}}] +[services."{{SERVICE_NAME}}"] image = "{{REGISTRY}}/{{SERVICE_NAME}}:latest.ctp" ports = ["{{PORT}}:{{PORT}}"] -environment = { - APP_HOST = "[::]", - APP_PORT = "{{PORT}}", - APP_LOG_FORMAT = "json", - APP_DATA_DIR = "/data", -} +environment.APP_HOST = "[::]" +environment.APP_PORT = "{{PORT}}" +environment.APP_LOG_FORMAT = "json" +environment.APP_DATA_DIR = "/data" volumes = ["{{SERVICE_NAME}}-data:/data"] restart = "always" healthcheck = { test = "curl -sf http://localhost:{{PORT}}/health", interval = "30s", timeout = "5s", retries = 3 } @@ -44,13 +42,11 @@ healthcheck = { test = "curl -sf http://localhost:{{PORT}}/health", interval = " [services.rokur] image = "ghcr.io/hyperpolymath/rokur:latest.ctp" ports = ["8081:8081"] -environment = { - ROKUR_BACKEND = "http://{{SERVICE_NAME}}:{{PORT}}", - ROKUR_LISTEN = "[::]:8081", - ROKUR_REQUIRED_SECRETS = "", - ROKUR_AUDIT_LOG = "/var/log/rokur/audit.jsonl", - ROKUR_LOG_FORMAT = "json", -} +environment.ROKUR_BACKEND = "http://{{SERVICE_NAME}}:{{PORT}}" +environment.ROKUR_LISTEN = "[::]:8081" +environment.ROKUR_REQUIRED_SECRETS = "" +environment.ROKUR_AUDIT_LOG = "/var/log/rokur/audit.jsonl" +environment.ROKUR_LOG_FORMAT = "json" volumes = ["rokur-audit:/var/log/rokur"] depends_on = ["{{SERVICE_NAME}}"] restart = "always" @@ -61,11 +57,9 @@ healthcheck = { test = "curl -sf http://localhost:8081/health", interval = "30s" [services.svalinn] image = "ghcr.io/hyperpolymath/svalinn:latest.ctp" ports = ["443:443", "80:80"] -environment = { - SVALINN_BACKEND = "http://rokur:8081", - SVALINN_POLICY_FILE = "/etc/svalinn/gatekeeper.yaml", - SVALINN_TLS_AUTO = "true", -} +environment.SVALINN_BACKEND = "http://rokur:8081" +environment.SVALINN_POLICY_FILE = "/etc/svalinn/gatekeeper.yaml" +environment.SVALINN_TLS_AUTO = "true" volumes = ["svalinn-config:/etc/svalinn:ro"] depends_on = ["rokur"] restart = "always" @@ -75,7 +69,7 @@ healthcheck = { test = "curl -sf http://localhost:80/health", interval = "30s", # Volumes # ============================================================================ -[volumes.{{SERVICE_NAME}}-data] +[volumes."{{SERVICE_NAME}}-data"] driver = "local" [volumes.rokur-audit] diff --git a/docs/ci-gates/REGISTER.adoc b/docs/ci-gates/REGISTER.adoc new file mode 100644 index 0000000..96b59da --- /dev/null +++ b/docs/ci-gates/REGISTER.adoc @@ -0,0 +1,156 @@ +// SPDX-License-Identifier: CC-BY-SA-4.0 += CI Gate Safety Register +:revdate: 2026-11-22 + +This register records the CI controls reviewed for this change. *Safe* means the +check has a bounded, explicit subject; missing tools, invalid output and API or +scanner errors cannot turn into a pass; and a green result means the stated +check actually ran. An advisory or not-applicable result is not a pass for a +mandatory check. + +== Scope and GitHub visibility + +The repository has no open pull requests at the time of this review, so there +was no open PR checklist or check list to update. GitHub branch-protection API +access returned HTTP 403 (`Resource not accessible by integration`); required +contexts could not be read or changed. The latest historical `Static Analysis +Gate` and `Dogfood Gate` runs in the available run list were green, but that +alone did not establish that their tools had run or their output had been +validated. + +== Decisions + +== Trust boundary still open + +The changed jobs use the pull-request checkout. A pull request that can change a +workflow or one of its scripts can change the check implementation too; these +local changes improve honest-run correctness but do not make the check's own +source tamper-proof. The central suite's current tamper guard protects its +`ci-gate*` paths, not this repository's `static-analysis-gate.yml` or +`dogfood-gate.yml`. We could not inspect this repository's active ruleset or +required contexts (the branch-protection API returned 403), so no claim is made +that code-owner review or required checks close this trust boundary. The checks +below are therefore *implementation-hardened, not yet qualified as an +independent security boundary*. + + +[cols="2,2,1,4",options="header"] +|=== +|Workflow / control |Classification |State |Safety decision + +|`static-analysis-gate.yml` — panic-attack +|Blocking on critical; advisory annotations below threshold +|*Changed; live CI pending* +|Builds from a fixed full commit, checks out that exact commit, uses the pinned +Rust toolchain and lockfile, and runs the documented machine-readable command. +The previous latest-release URL could return no asset and silently skip. Missing +source/compiler, incomplete coverage, scanner failure, malformed or unknown +report schema now fails. The validator understands the pinned `AssailReport` +2.6 object (`weak_points`, PascalCase severities, complete coverage), rather +than treating it as a findings array. Suppressed entries remain in the saved +report but do not count toward blocking thresholds, as the scanner contract +specifies. + +|`static-analysis-gate.yml` — Hypatia +|Blocking on critical; advisory annotations below threshold +|*Changed; live CI pending* +|Builds at a fixed full commit with the committed dependency lock; clone, +build, or scan failures are fatal. A finding array must have recognized +severity, source file and description for every item. No empty-array fallback +or zero-count substitution remains. Untrusted annotation fields are escaped. + +|`static-analysis-gate.yml` — Patch Bridge +|Advisory and conditionally applicable +|*Changed; live CI pending* +|The scanner supports four named lockfile kinds; no supported tracked lockfile +now produces an explicit `not_applicable` receipt, not a fabricated clean +report. Applicable scans use the fixed panic-attack build, fail on command or +schema errors, and reject `offline-unavailable` output. Unmitigable CVEs are +still a human-review warning, not a blocking policy; the step is named +accordingly. + +|`static-analysis-gate.yml` — finding deposit +|Required evidence aggregation +|*Changed; live CI pending* +|The collector now checks out the validator and refuses missing or malformed +scanner artifacts instead of manufacturing `[]` or zero-count Bridge data. +The unified report consumes the actual AssailReport `weak_points` list. + +|`dogfood-gate.yml` — A2ML / K9 +|Required when applicable +|*Changed; local checks pass* +|A missing A2ML manifest fails for this repository. Config-bearing repositories +with no K9 contracts fail; absence of covered configuration is explicitly +not-applicable. Both existing validators pass locally (103 A2ML files, 17 K9 +files; A2ML reported six SPDX warnings). + +|`dogfood-gate.yml` — invisible-character scanner +|Blocking +|*Changed; local negative and positive controls pass* +|Moved the scan to a tested helper. A no-match exit from `grep` is handled as a +normal clean file, but grep/find errors fail; findings now fail the check. It +reports paths without emitting unescaped user-controlled workflow annotations. + +|`dogfood-gate.yml` — Groove manifest +|Conditional +|*Changed; live CI pending* +|A present manifest must be a JSON object with non-empty `service_id`; malformed +or structurally incomplete JSON fails instead of emitting an annotation and +continuing. No manifest is not applicable unless a service is detected; the +existing missing-endpoint recommendation remains advisory. + +|`dogfood-gate.yml` — energy manifest and scorecard +|Advisory / optional +|*Existing; not a required assurance claim* +|These signals remain informational. A missing optional energy manifest does +not certify energy compliance; the summary score is not a security or build +verdict. + +|`.githooks/validate-a2ml.sh`, `.githooks/validate-k9.sh` annotations +|Output safety +|*Changed; syntax and local validators pass* +|Null-delimited file discovery handles newlines; file names and messages are +escaped for GitHub workflow-command delimiters before annotation emission. + +|`quality.yml` — static report, invisible scan and annotation controls +|Regression controls +|*Added; local tests pass* +|Positive and negative JSON/report controls, invisible-character fixtures, and +newline-based workflow-command injection controls run in the quality job. The +separate EditorConfig action still has `continue-on-error: true`; it is advisory +and must not be counted as a required gate until that is removed and the action +is witnessed failing on bad input. + +|`proven-cicd-and-workflows` `CI/gate` reusable +|Not adopted +|*Not qualified for this consumer* +|The upstream suite's own README says its operational Idris2/GitHub adapter is +unpromoted after a duplicate-field false-pass was reproduced, and its required +profile for `hyperpolymath/system-et` is absent. Its documented +`Assurance.Verdict` kernel is a pure decision model; the unverified adapter, +observation admission and completeness are outside the proof. Calling that +workflow or copying its profile would not make this consumer safe. No new +Idris2 gate was invented here because there is no proven operational adapter +that can bind GitHub's real run evidence to the kernel without trusting the +same unverified boundary. +|=== + +== Verification performed locally + +* `bash tests/static-analysis-json.sh` — pass; positive cases and malformed, + missing, unknown-severity, incomplete-coverage, and offline cases. +* `bash tests/check-invisible-characters.sh` — pass; clean and NBSP fixtures, + plus missing-root failure. +* `bash tests/workflow-annotation-escaping.sh` — pass; crafted newline filenames + cannot inject GitHub workflow commands through A2ML/K9 annotations. +* `bash scripts/check-invisible-characters.sh .` — pass; repository clean. +* `bash .githooks/validate-a2ml.sh` — pass (six warnings; see above). +* `bash .githooks/validate-k9.sh` — pass (17 files, zero warnings). +* YAML parsing, Bash syntax and `git diff --check` — pass. + +The workspace has no `rustup`/`cargo` installation, so the two upstream scanner +builds and the end-to-end GitHub Actions run were not executed locally. The +changed gates remain *live-CI pending*, not certified safe, until their pinned +builds, real scan outputs, artifact round-trip and failure controls are +witnessed on the PR head. The Idris2 assurance kernel is intentionally not +represented as evidence for that unverified runtime boundary. diff --git a/scripts/check-invisible-characters.sh b/scripts/check-invisible-characters.sh new file mode 100644 index 0000000..48e042d --- /dev/null +++ b/scripts/check-invisible-characters.sh @@ -0,0 +1,64 @@ +#!/usr/bin/env bash +# SPDX-License-Identifier: MPL-2.0 +# Check tracked-source/document extensions for invisible control/format characters. +# Exit: 0 = scan completed and clean; 1 = findings or scanner/infrastructure error. +set -euo pipefail +root="${1:-.}" +[[ -d "$root" ]] || { echo "::error::invisible-character scan path is not a directory: $root"; exit 1; } + +patterns='(*UTF)[\x00-\x08\x0B\x0C\x0E-\x1F\x{a0}\x{ad}\x{200b}-\x{200f}\x{202a}-\x{202f}\x{2060}\x{2066}-\x{2069}\x{feff}]' +tmp="$(mktemp -d)" +trap 'rm -rf "$tmp"' EXIT + +# Capture discovery errors distinctly from grep's normal "no match" exit 1. +find "$root" \ + -not -path '*/.git/*' -not -path '*/node_modules/*' \ + -not -path '*/.deno/*' -not -path '*/target/*' \ + -not -path '*/_build/*' -not -path '*/deps/*' \ + -not -path '*/external_corpora/*' -not -path '*/.lake/*' \ + -type f \( -name '*.rs' -o -name '*.ex' -o -name '*.exs' -o -name '*.res' \ + -o -name '*.js' -o -name '*.ts' -o -name '*.json' -o -name '*.toml' \ + -o -name '*.yml' -o -name '*.yaml' -o -name '*.md' -o -name '*.adoc' \ + -o -name '*.idr' -o -name '*.zig' -o -name '*.v' -o -name '*.jl' \ + -o -name '*.gleam' -o -name '*.hs' -o -name '*.ml' -o -name '*.sh' \) \ + -print0 > "$tmp/candidates" + +: > "$tmp/findings" +while IFS= read -r -d '' file; do + if grep -aPl -- "$patterns" "$file" >/dev/null; then + printf '%s\0' "$file" >> "$tmp/findings" + else + status=$? + if [[ $status -ne 1 ]]; then + echo "::error::invisible-character scanner failed on a candidate file (grep exit $status)" + exit 1 + fi + fi +done < "$tmp/candidates" + +mapfile -d '' -t findings < "$tmp/findings" +if [[ ${#findings[@]} -gt 0 ]]; then + echo "::error::invisible-character scan found ${#findings[@]} file(s) with prohibited characters" + # The runner searches anywhere on the line for the legacy prefix. + # Encode it before using %q to keep control characters on one line. + rendered=() + for file in "${findings[@]}"; do + printf -v path '%q' "${file//"##["/"%23%23%5B"}" + rendered+=("$path") + done + printf ' file: %s\n' "${rendered[@]}" + if [[ -n "${GITHUB_STEP_SUMMARY:-}" ]]; then + { + echo '## Invisible-character scan — blocked' + echo + echo "Found **${#findings[@]}** affected file(s):" + printf -- "- \`%s\`\n" "${rendered[@]}" + } >> "$GITHUB_STEP_SUMMARY" + fi + exit 1 +fi + +echo 'invisible-character scan completed: no prohibited characters found' +if [[ -n "${GITHUB_STEP_SUMMARY:-}" ]]; then + printf '%s\n' '## Invisible-character scan' '' 'No prohibited characters found.' >> "$GITHUB_STEP_SUMMARY" +fi diff --git a/scripts/check-proofs.sh b/scripts/check-proofs.sh index 31a8539..a70b050 100755 --- a/scripts/check-proofs.sh +++ b/scripts/check-proofs.sh @@ -173,13 +173,13 @@ missing="$(comm -23 <(printf '%s\n' "$listed") <(printf '%s\n' "$found") || true if [ -n "${unlisted//[[:space:]]/}" ]; then echo "FAIL: .$EXT proofs on disk but absent from $MANIFEST_FILE:" - printf ' %s\n' $unlisted + printf ' %s\n' "${unlisted//$'\n'/$'\n '}" echo " List each as 'gated' or 'quarantine'; new proofs are gated by default." fails=$((fails + 1)) fi if [ -n "${missing//[[:space:]]/}" ]; then echo "FAIL: MANIFEST lists modules that do not exist (stale entries):" - printf ' %s\n' $missing + printf ' %s\n' "${missing//$'\n'/$'\n '}" fails=$((fails + 1)) fi [ -z "${unlisted//[[:space:]]/}${missing//[[:space:]]/}" ] && \ diff --git a/scripts/validate-static-analysis-json.sh b/scripts/validate-static-analysis-json.sh new file mode 100644 index 0000000..36fb141 --- /dev/null +++ b/scripts/validate-static-analysis-json.sh @@ -0,0 +1,110 @@ +#!/usr/bin/env bash +# SPDX-License-Identifier: MPL-2.0 +# Validate scanner output before any severity count can influence a gate. +# Usage: validate-static-analysis-json.sh hypatia|assail|bridge FILE [GITHUB_OUTPUT] +set -euo pipefail + +mode="${1:-}" +file="${2:-}" +output="${3:-${GITHUB_OUTPUT:-}}" + +fail() { + echo "::error::static-analysis output rejected: $*" >&2 + exit 1 +} + +case "$mode" in hypatia|assail|bridge) ;; *) fail "unknown report mode: $mode" ;; esac +[[ -n "$file" && -s "$file" ]] || fail "missing or empty report: ${file:-}" +command -v jq >/dev/null 2>&1 || fail "jq is required; no report was evaluated" +jq -es 'length == 1' "$file" >/dev/null 2>&1 || fail "invalid JSON in $file" +[[ -n "$output" ]] || fail "GITHUB_OUTPUT is not set" + +write_findings_counts() { + local total critical high medium low informational + total="$(jq 'length' "$file")" + critical="$(jq '[.[] | select(.severity == "critical" or .severity == "Critical") ] | length' "$file")" + high="$(jq '[.[] | select(.severity == "high" or .severity == "High") ] | length' "$file")" + medium="$(jq '[.[] | select(.severity == "medium" or .severity == "Medium") ] | length' "$file")" + low="$(jq '[.[] | select(.severity == "low" or .severity == "Low") ] | length' "$file")" + informational="$(jq '[.[] | select(.severity == "info" or .severity == "informational") ] | length' "$file")" + { + printf 'total=%s\n' "$total" + printf 'critical=%s\n' "$critical" + printf 'high=%s\n' "$high" + printf 'medium=%s\n' "$medium" + printf 'low=%s\n' "$low" + printf 'informational=%s\n' "$informational" + } >> "$output" +} + +case "$mode" in + hypatia) + # Hypatia's documented JSON contract is an array of findings. Unknown or + # absent severities are rejected instead of vanishing from a jq select(). + jq -e ' + type == "array" and + all(.[]; + type == "object" and + (.severity | type == "string" and + IN("critical", "high", "medium", "low", "info", "informational")) and + (.file | type == "string") and + ((.reason? // .message? // .type?) | type == "string" and length > 0) + ) + ' "$file" >/dev/null || fail "expected Hypatia array of findings with recognized severity, file, and description" + write_findings_counts + ;; + assail) + # The pinned panic-attack 2.6 report is an AssailReport object, not an array. + # Require the exact schema generation and complete coverage; otherwise a + # tool/schema upgrade or partial scan cannot be mistaken for zero findings. + jq -e ' + type == "object" and .schema_version == "2.6" and + (.coverage | type == "object" and .status == "complete" and + (.candidate_files | type == "number" and isfinite and . >= 0 and floor == .) and + (.analyzed_files | type == "number" and isfinite and . > 0 and floor == .)) and + (.weak_points | type == "array") and + all(.weak_points[]; + type == "object" and + (.severity | type == "string" and IN("Critical", "High", "Medium", "Low")) and + (.description | type == "string" and length > 0) and + ((.file? == null) or (.file | type == "string" and length > 0)) and + ((.location? == null) or (.location | type == "string" and length > 0)) and + ((.suppressed? == null) or (.suppressed | type == "boolean")) + ) + ' "$file" >/dev/null || fail "expected complete panic-attack AssailReport schema 2.6" + # Suppressed findings remain in the report for review but do not contribute + # to scanner blocking counts, per the pinned tool's documented contract. + jq '[.weak_points[] | select(.suppressed != true)]' "$file" > "${file}.active" + file="${file}.active" + write_findings_counts + rm -f "${file}" + ;; + bridge) + # The Patch Bridge contract distinguishes a real no-dependency scan from an + # offline/unknown result. The latter is never a clean report. + if jq -e 'type == "object" and .status == "not_applicable" and (.reason | type == "string" and length > 0)' "$file" >/dev/null; then + printf 'bridge_status=not_applicable\n' >> "$output" + else + jq -e ' + def classified($kind): [.cves[] | select(.classification == $kind)] | length; + type == "object" and .schema_version == "0.3.0" and + (.vulnerability_data | IN("queried", "no-dependencies")) and + (.cves | type == "array") and + ([.mitigated, .unmitigable, .concatenative, .informational] | + all(.[]; type == "number" and isfinite and . >= 0 and floor == .)) and + all(.cves[]; type == "object" and + (.classification | IN("mitigable", "unmitigable", "informational"))) and + .mitigated == classified("mitigable") and + .unmitigable == classified("unmitigable") and + .informational == classified("informational") + ' "$file" >/dev/null || fail "expected online or confirmed no-dependencies Patch Bridge report" + printf 'bridge_status=completed\n' >> "$output" + { + jq -r '"unmitigable=" + (.unmitigable|tostring)' "$file" + jq -r '"mitigated=" + (.mitigated|tostring)' "$file" + jq -r '"concatenative=" + (.concatenative|tostring)' "$file" + jq -r '"informational=" + (.informational|tostring)' "$file" + } >> "$output" + fi + ;; +esac diff --git a/tests/check-invisible-characters.sh b/tests/check-invisible-characters.sh new file mode 100644 index 0000000..1e1d3c7 --- /dev/null +++ b/tests/check-invisible-characters.sh @@ -0,0 +1,44 @@ +#!/usr/bin/env bash +# SPDX-License-Identifier: MPL-2.0 +set -euo pipefail +root="$(cd "$(dirname "$0")/.." && pwd)" +scanner="$root/scripts/check-invisible-characters.sh" +tmp="$(mktemp -d)" +trap 'rm -rf "$tmp"' EXIT +mkdir -p "$tmp/clean" "$tmp/dirty" "$tmp/forged" +printf 'ordinary text\n' > "$tmp/clean/ok.adoc" +printf 'ordinary source\n' > "$tmp/clean/ok.rs" +bash "$scanner" "$tmp/clean" > "$tmp/clean.log" +grep -Fq 'no prohibited characters' "$tmp/clean.log" + +# NBSP is intentionally a literal U+00A0 character in this fixture. +printf 'a\302\240b\n' > "$tmp/dirty/bad.rs" +if bash "$scanner" "$tmp/dirty" > "$tmp/dirty.log" 2>&1; then + echo 'FAIL: scanner accepted a source file containing NBSP' >&2 + exit 1 +fi +grep -Fq 'found 1 file(s)' "$tmp/dirty.log" +grep -Fq 'bad.rs' "$tmp/dirty.log" + +forged="$tmp/forged/ordinary"$'\n'"::warning::forged-command.rs"$'\n'"::stop-commands::forged"$'\n'"##[warning]legacy.rs" +printf 'a\302\240b\n' > "$forged" +if GITHUB_STEP_SUMMARY="$tmp/summary" bash "$scanner" "$tmp/forged" > "$tmp/forged.log" 2>&1; then + echo 'FAIL: scanner missed the finding in a file with a newline in its name' >&2 + exit 1 +fi +grep -Fq '::warning::forged-command.rs' "$tmp/forged.log" +grep -Eq '^ file: .*legacy\.rs' "$tmp/forged.log" +if [[ "$(wc -l < "$tmp/forged.log")" -ne 2 || + "$(grep -E '^[[:space:]]*::' "$tmp/forged.log")" != '::error::invisible-character scan found 1 file(s) with prohibited characters' ]] || + grep -Eq '^[[:space:]]*::' "$tmp/summary" || + grep -Fq '##[' "$tmp/forged.log" "$tmp/summary"; then + echo 'FAIL: file path injected a workflow command' >&2 + exit 1 +fi + +if bash "$scanner" "$tmp/missing" > "$tmp/missing.log" 2>&1; then + echo 'FAIL: scanner accepted a missing scan root' >&2 + exit 1 +fi +grep -Fq 'not a directory' "$tmp/missing.log" +echo 'invisible-character scanner tests passed' diff --git a/tests/e2e.sh b/tests/e2e.sh index 11143fc..08762bd 100755 --- a/tests/e2e.sh +++ b/tests/e2e.sh @@ -17,6 +17,7 @@ set -euo pipefail SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +# shellcheck disable=SC2034 # Used by the example preflight below. PROJECT_DIR="$(cd "$SCRIPT_DIR/.." && pwd)" PASS=0 @@ -32,6 +33,7 @@ bold() { printf '\033[1m%s\033[0m\n' "$*"; } # ─── Assertion helpers ─────────────────────────────────────────────── # check