Skip to content

Latest commit

 

History

History
157 lines (122 loc) · 8.45 KB

common.md

File metadata and controls

157 lines (122 loc) · 8.45 KB

common.sh (scripts/forge/lib)

Revision: 1 Last modified: 2026-12-04T18:15:21Z

Overview

This is a library. It is sourced, never executed. It has no shebang and is not marked executable; the file mode is rw-rw-r--. Running it directly does nothing useful and is not a supported use.

scripts/forge/lib/common.sh is the shared layer of scripts/forge/forge.sh and is also sourced by scripts/forge/live_probe.sh for the output sanitiser. It owns four things:

  1. Environment hygiene — building the environment of every child process positively (allow-list) instead of stripping a denylist, by re-executing the caller once with an empty environment.
  2. The one output sanitiser — every line the tool prints passes through it, so no token value can reach a terminal or a log.
  3. Output and exit helpers — the RESULT: / REASON: protocol and the exit-code vocabulary.
  4. Validators for every string that can reach a URL path or the output.

Prerequisites

  • bash 4+ (compgen -e, arrays, ${var,,}).
  • Linux /proc for fg_env_clean (it verifies the re-executed state from /proc/$$/cmdline and /proc/$$/environ).
  • Callers must have set nothing in particular in advance, but fg_secret_hit and fg_scrub are only useful after fg_secrets_load (in lib/credentials.sh) has filled FG_SEC_VALS / FG_SEC_NAMES.

Usage examples

# how a caller loads it
. "$FG_DIR/lib/common.sh" || { printf 'RESULT: USAGE\n'; exit 2; }

# build the clean child environment (call FIRST, before any external command); re-executes once
fg_env_clean "$@"; rc=$?
case "$rc" in 0) ;; *) printf 'RESULT: GAP\n'; exit 3 ;; esac

# output
fg_line "PROVIDER: $FG_PROVIDER"        # stdout, scrubbed
fg_msg  "no answer"                     # stderr, prefixed "forge: ", scrubbed
fg_end  OK 0                            # prints "RESULT: OK" and exits 0
fg_end  FAIL 1 tag_sha_mismatch         # prints "REASON: ..." then "RESULT: FAIL", exits 1

# the typed error helpers (each ends the run)
fg_usage_err "a command is required"            # exit 2, RESULT: USAGE
fg_gap      credentials_absent:GH_TOKEN "..."   # exit 3, RESULT: GAP
fg_api_err  auth_failed "..."                   # exit 4, RESULT: API
fg_fail     present_mismatch "..."              # exit 1, RESULT: FAIL

# validators (return status, never exit)
fg_ok_segment "my-repo" && echo safe
fg_ok_tag     "v1.2.3"
fg_ok_sha     "0123456789abcdef0123456789abcdef01234567"
fg_ok_id      "12345"                # numeric ids and UUIDs; never "/" or "."
fg_ok_port    "8443"
fg_ok_varname "GITHUB_TOKEN"         # must match [A-Z][A-Z0-9_]*TOKEN

Exit codes

common.sh itself does not exit; it returns statuses, and the fg_* helpers it defines exit the process.

Helper Status / exit Meaning
fg_env_clean 0 environment is clean, values restored, ready to run
fg_env_clean 3 /proc/$$ unreadable — state cannot be checked, so the caller must refuse
fg_env_clean 4 the re-exec failed
fg_env_clean 5 the re-executed process still has a non-empty environment (refused; no loop)
fg_end WORD RC exits RC prints optional REASON:, then RESULT: WORD
fg_usage_err 2 RESULT: USAGE
fg_gap 3 RESULT: GAP (precondition / forge state)
fg_api_err 4 RESULT: API (network or unexpected HTTP)
fg_fail 1 RESULT: FAIL
fg_ok_* 0 / 1 valid / not valid
fg_secret_hit 0 / 1 the text contains a secret window / it does not
fg_bool prints true / false / unknown (never fails)

Contract — what a caller must set, what it may read

Must be available before the relevant calls:

  • FG_DIR — the scripts/forge directory, so lib/*.sh and providers/*.sh can be sourced off it.
  • _FG_* state set by fg_env_clean itself; do not pre-set them.

May read after the call:

  • _FG_STATE (clean | dirty | blind), _FG_A0.
  • FG_SEC_NAMES[] / FG_SEC_VALS[] — filled by fg_secrets_load (credentials.sh), consumed here.
  • FG_SECRET_NAME — set by fg_secret_hit to the name of the variable whose value was matched. Never the value.

Exported to children (the whole list, nothing else): PATH HOME USER LOGNAME LANG LANGUAGE TZ TMPDIR SSH_AUTH_SOCK XDG_RUNTIME_DIR; LC_ALL is then forced to C. Carried as unexported shell variables (no child sees them): every name matching [A-Z][A-Z0-9_]*TOKEN and every FORGE_* setting. Everything else is dropped — including SHELLOPTS/BASHOPTS (an inherited xtrace or allexport), BASH_ENV, exported functions, proxy variables, and any name that is not a shell identifier.

Function reference

Function Purpose
fg_env_clean "$@" Build the clean child environment; re-executes the script once with exec -c, argv[0] = forge-clean-env, values over fd 9 (a pipe written by builtins — never an argv, never a file).
fg_secret_hit TEXT Status 0 when TEXT holds a window of any known token value: the whole value when shorter than 12 characters, otherwise any 12-character piece of it. Sets FG_SECRET_NAME. Text longer than 4096 bytes is pre-filtered through one grep -qF and then confirmed by the exact loop — a grep that cannot run (status 2) falls through to the exact loop rather than being read as "no secret".
fg_scrub TEXT Returns TEXT with every space-separated word holding a secret window replaced by unsafe; key=value words keep a clean key (request_id=unsafe). Multi-line input is scrubbed line by line and every line is kept.
fg_msg / fg_line scrubbed write to stderr (forge: … prefix) / stdout
fg_end WORD RC [REASON] the only sanctioned way to end a run
fg_*_err / fg_gap / fg_fail typed endings, see the table above
fg_ok_segment ^[A-Za-z0-9][A-Za-z0-9._-]{0,99}$ and no ..
fg_ok_tag ^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$ and no ..
fg_ok_sha exactly 40 lower-case hex characters
fg_ok_id ^[A-Za-z0-9][A-Za-z0-9-]{0,63}$ — numeric ids and UUIDs; never /, never .
fg_ok_port decimal 1–65535
fg_ok_varname ^[A-Z][A-Z0-9_]{0,62}TOKEN$
fg_bool true/false passthrough, anything else unknown

Internal helpers (_fg_reserved, _fg_carry_shell, _fg_env_dump, _fg_env_restore, _fg_env_state, _fg_windows) are not part of the caller contract.

Edge cases

  • No /proc (non-Linux, hardened container): fg_env_clean returns 3 and the caller must refuse. It does not silently continue with an unverified environment.
  • A second re-exec attempt with the marker already set returns 5 instead of looping.
  • Empty FG_SEC_VALS makes fg_secret_hit return 1 immediately — no secret can be detected, so callers that need assurance must check that fg_secrets_load succeeded (see credentials.sh).
  • A multi-line message is scrubbed per line; lines are never dropped.
  • grep unavailable in the fast path is treated as "could not decide" and the exact loop still runs.

Internal behaviour

  1. _fg_env_state reads /proc/$$/cmdline for argv[0] and counts entries in /proc/$$/environ. clean requires argv[0] == forge-clean-env and zero environment entries.
  2. clean → _fg_env_restore reads the e|s NUL NAME NUL VALUE NUL records from fd 9, re-exports the allow-list, sets the rest as plain variables, forces LC_ALL=C.
  3. blind → return 3. Already marked but not clean → 5. Otherwise exec -c -a forge-clean-env "$BASH" "$0" "$@" 9< <(_fg_env_dump), where _fg_env_dump runs in a forked subshell using builtins only.
  4. fg_scrub first asks fg_secret_hit about the whole text; if there is no hit it returns the text unchanged. On a hit it splits into words, tests each, and rewrites only the offending ones.

Related scripts

  • scripts/forge/forge.sh — the main consumer.
  • scripts/forge/lib/credentials.sh — fills the secret set this file scrubs with.
  • scripts/forge/lib/http.sh — the HTTP client that relies on these traps and the temp dir.
  • scripts/forge/live_probe.sh — sources this file for fg_secret_hit in its leak check.

Last verified

2026-12-04 — bash -n scripts/forge/lib/common.sh → exit 0 (parses; it is a library so it is not executed). Sourcing check that a reader can repeat:

bash -c '. scripts/forge/lib/common.sh && fg_ok_sha 0123456789abcdef0123456789abcdef01234567 && echo validator-ok'

Expected: validator-ok.