Files
CASAN/packages/casan-harness/scripts/bash/approval-verify.sh
T
thanhnvandClaude Opus 4.8 36a4812ef3 refactor(structure): promote app to repo root + remove redundant workspace cruft
Standard production layout: the OKR app (was nested under AINative_OKR_CASAN5/) is now
the repository root. No more wrapper directory.

- Promote AINative_OKR_CASAN5/* -> repo root (backend/ frontend/ packages/ apps/
  .specify/ docs/ infra/ nginx/ scripts/ + configs). Merge tool dirs: .gitea (kept the
  active deploy ci.yml, added harness-ci.yml + runbooks), .claude (agents/commands +
  launch.json), .github moved up.
- Remove redundant: 00_SUBMISSION_PACKAGE, scattered root notes (FPT_CASAN_Full.md,
  tu-tuong-casan.md, casan-tu-sinh..., casan_harness_assessment.md, source-review...,
  README_CASAN5_REFINED.md), casan-next-plans/ and optimize-docs/ (competition/planning
  artifacts — roadmap + design history preserved in git log / commit messages).
- Update all references to the old layout:
  - .gitea/workflows/{ci,harness-ci}.yml, .github/workflows/{ci,deploy}.yml:
    working-directory .; drop AINative_OKR_CASAN5/ prefix; .specify/{tests,scripts}
    -> packages/casan-harness/... (.specify/logs state kept)
  - .claude/launch.json, .gitea/*-runbook.md: path prefixes
  - CLAUDE.md, README.md: docs/input -> apps/okr/domain/input
  - policy-bundle.yaml: 8 policy paths -> packages/casan-harness/...; manifest re-signed
- secrets-scan.sh: fixture excludes -> new package/domain paths.

Full gate from the new root: PASS=64 FAIL=0 SKIP=3.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-08 13:26:36 +09:00

242 lines
9.3 KiB
Bash
Executable File

#!/usr/bin/env bash
set -uo pipefail
# CASAN H5 — Signed/JWT approval verifier (Approval-identity MVP · C4 / V20).
#
# Problem: high-risk approval used to trust a plain env var (CASAN_APPROVER=bob) —
# anyone who can set the env can "approve". This binds an approval to a REGISTERED
# reviewer's cryptographic identity: the reviewer must SIGN this exact request with
# their private key, AND their role must be authorized for the action class.
#
# The signed assertion is: casan-approval|v1|<action>|<actor>|<input_sha256>|<approver_id>
# — so a signature for one request/reviewer cannot be replayed for another.
#
# Usage:
# approval-verify.sh <action> <actor> <input-file> <approver-id> <sig-file>
# CASAN_APPROVAL_JWT=<rs256-jwt> approval-verify.sh <action> <actor> <input-file> <approver-id> -
# Registry (line format, no yaml dep):
# reviewer <id> <role> <pubkey-file>
# action <action-name|default> <comma,roles>
# Env: CASAN_REVIEWERS_FILE (default governance/reviewers.registry)
# CASAN_REVIEWERS_DIR (default governance/reviewers) — base dir for pubkey-file
# CASAN_APPROVAL_JWT (optional RS256 IdP token)
# CASAN_IDP_PUBLIC_KEY (default central-governance/idp-public.pem)
# CASAN_IDP_JWKS_URL (optional OIDC JWKS endpoint; overrides public key)
# CASAN_TRUSTED_TIME / CASAN_TRUSTED_TIME_FILE (SEC-22/ARCH-06: trusted time
# source for JWT `exp` instead of the manipulable local clock; file
# unreadable = fail-closed)
# Exit: 0 ok (prints "APPROVAL_OK role=<role>"), 3 deny (reason on stderr), 64 usage.
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
source "$SCRIPT_DIR/casan-paths.sh"
PROJECT_ROOT="$CASAN_APP_ROOT"
GOV_DIR="$CASAN_GOVERNANCE_ROOT"
REVIEWERS_FILE="${CASAN_REVIEWERS_FILE:-$GOV_DIR/reviewers.registry}"
REVIEWERS_DIR="${CASAN_REVIEWERS_DIR:-$GOV_DIR/reviewers}"
ACTION="${1:-}"; ACTOR="${2:-}"; INPUT_FILE="${3:-}"; APPROVER="${4:-}"; SIG_FILE="${5:-}"
if [[ -z "$ACTION" || -z "$ACTOR" || -z "$INPUT_FILE" || -z "$APPROVER" ]]; then
echo "Usage: approval-verify.sh <action> <actor> <input-file> <approver-id> <sig-file>" >&2
exit 64
fi
deny() { echo "APPROVAL_DENIED reason=$1 approver=$APPROVER action=$ACTION" >&2; exit 3; }
# SEC-30 (X-06): one-time-use. A verified approval token (JWT or offline signature)
# is valid for its whole exp window, so it could be REPLAYED. Record a per-token
# nonce (sha256 of the token/signature) and reject any repeat. Active in enforced
# mode or when an explicit nonce ledger is configured (dev default: off).
sha_stdin() {
if command -v sha256sum >/dev/null 2>&1; then sha256sum | awk '{print $1}'
else shasum -a 256 | awk '{print $1}'; fi
}
record_nonce_or_deny() {
local nonce="$1"
[[ "${CASAN_PROFILE:-}" == "prod" || -n "${CASAN_APPROVAL_NONCE_FILE:-}" ]] || return 0
local ledger="${CASAN_APPROVAL_NONCE_FILE:-$CASAN_STATE_ROOT/logs/level5/approval-nonces.txt}"
mkdir -p "$(dirname "$ledger")" 2>/dev/null || true
if [[ -f "$ledger" ]] && grep -qxF "$nonce" "$ledger" 2>/dev/null; then
deny "approval_replayed(nonce=${nonce:0:12}…)"
fi
printf '%s\n' "$nonce" >> "$ledger" || deny "nonce_ledger_unwritable"
}
[[ -f "$INPUT_FILE" ]] || deny "input_file_missing"
[[ -f "$REVIEWERS_FILE" ]] || deny "reviewer_registry_missing"
command -v openssl >/dev/null 2>&1 || deny "openssl_unavailable"
hash_file() {
if command -v sha256sum >/dev/null 2>&1; then sha256sum "$1" | awk '{print $1}'
else shasum -a 256 "$1" | awk '{print $1}'; fi
}
INPUT_SHA="$(hash_file "$INPUT_FILE")"
# Role authorization for this action (fallback to the "default" action policy).
ROLES="$(awk -v a="$ACTION" '$1=="action" && $2==a {print $3; exit}' "$REVIEWERS_FILE")"
[[ -n "$ROLES" ]] || ROLES="$(awk '$1=="action" && $2=="default" {print $3; exit}' "$REVIEWERS_FILE")"
if [[ -n "${CASAN_APPROVAL_JWT:-}" ]]; then
IDP_PUB="${CASAN_IDP_PUBLIC_KEY:-$GOV_DIR/idp-public.pem}"
if [[ -n "${CASAN_IDP_JWKS_URL:-}" ]]; then
IDP_PUB="jwks:${CASAN_IDP_JWKS_URL}"
else
[[ -f "$IDP_PUB" ]] || deny "idp_pubkey_missing($IDP_PUB)"
fi
JWT_OUT="$(
python3 - "$CASAN_APPROVAL_JWT" "$IDP_PUB" "$APPROVER" "$ROLES" "$ACTION" "$ACTOR" "$INPUT_SHA" <<'PY'
import base64
import json
import os
import subprocess
import sys
import tempfile
import time
import urllib.request
jwt, pub, approver, roles_csv, action, actor, input_sha = sys.argv[1:8]
def die(reason):
print(reason, file=sys.stderr)
sys.exit(3)
def b64u_decode(part):
try:
return base64.urlsafe_b64decode(part + "=" * (-len(part) % 4))
except Exception:
die("jwt_base64_invalid")
parts = jwt.split(".")
if len(parts) != 3:
die("jwt_shape_invalid")
header = json.loads(b64u_decode(parts[0]))
claims = json.loads(b64u_decode(parts[1]))
if header.get("alg") != "RS256":
die("jwt_alg_not_allowed")
# SEC-22 (ARCH-06): do NOT trust the local system clock alone for expiry. When a
# trusted time source is provided (CASAN_TRUSTED_TIME seconds, or
# CASAN_TRUSTED_TIME_FILE containing seconds from a trusted timestamp authority),
# use it; an unreadable/invalid source is fail-closed (deny).
def _trusted_now():
v = os.environ.get("CASAN_TRUSTED_TIME")
if v:
try:
return int(v)
except Exception:
die("trusted_time_invalid")
f = os.environ.get("CASAN_TRUSTED_TIME_FILE")
if f:
try:
return int(open(f).read().strip())
except Exception:
die("trusted_time_file_unreadable")
return int(time.time())
if int(claims.get("exp", 0)) <= _trusted_now():
die("jwt_expired")
if claims.get("sub") != approver:
die("jwt_sub_mismatch")
role = claims.get("role", "")
roles = [r for r in roles_csv.split(",") if r]
if role not in roles:
die(f"jwt_role_not_authorized(role={role} allowed={roles_csv})")
if claims.get("action") != action:
die("jwt_action_mismatch")
if claims.get("actor") != actor:
die("jwt_actor_mismatch")
if claims.get("input_sha256") != input_sha:
die("jwt_input_hash_mismatch")
sig = b64u_decode(parts[2])
signing_input = ".".join(parts[:2]).encode()
def der_len(n):
if n < 128:
return bytes([n])
raw = n.to_bytes((n.bit_length() + 7) // 8, "big")
return bytes([0x80 | len(raw)]) + raw
def der_tlv(tag, body):
return bytes([tag]) + der_len(len(body)) + body
def der_int(n):
raw = n.to_bytes((n.bit_length() + 7) // 8, "big") or b"\x00"
if raw[0] & 0x80:
raw = b"\x00" + raw
return der_tlv(0x02, raw)
def jwk_to_pem(jwk):
n = int.from_bytes(b64u_decode(jwk["n"]), "big")
e = int.from_bytes(b64u_decode(jwk["e"]), "big")
rsa_pub = der_tlv(0x30, der_int(n) + der_int(e))
alg_id = der_tlv(
0x30,
der_tlv(0x06, b"\x2a\x86\x48\x86\xf7\x0d\x01\x01\x01") + der_tlv(0x05, b""),
)
spki = der_tlv(0x30, alg_id + der_tlv(0x03, b"\x00" + rsa_pub))
b64 = base64.encodebytes(spki).decode().replace("\n", "")
lines = [b64[i:i+64] for i in range(0, len(b64), 64)]
return "-----BEGIN PUBLIC KEY-----\n" + "\n".join(lines) + "\n-----END PUBLIC KEY-----\n"
pub_file = pub
with tempfile.TemporaryDirectory() as td:
sig_path = os.path.join(td, "sig.bin")
msg_path = os.path.join(td, "msg.txt")
open(sig_path, "wb").write(sig)
open(msg_path, "wb").write(signing_input)
if pub.startswith("jwks:"):
try:
jwks = json.loads(urllib.request.urlopen(pub[len("jwks:"):], timeout=5).read().decode())
except Exception:
die("jwks_fetch_failed")
kid = header.get("kid")
keys = [k for k in jwks.get("keys", []) if k.get("kty") == "RSA" and (not kid or k.get("kid") == kid)]
if not keys:
die("jwks_key_not_found")
pub_file = os.path.join(td, "idp-public.pem")
open(pub_file, "w", encoding="utf-8").write(jwk_to_pem(keys[0]))
rc = subprocess.run(
["openssl", "dgst", "-sha256", "-verify", pub_file, "-signature", sig_path, msg_path],
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
).returncode
if rc != 0:
die("jwt_signature_invalid")
print(f"OK role={role}")
PY
)" || deny "oidc_jwt_invalid(${JWT_OUT:-see_stderr})"
ROLE="${JWT_OUT#OK role=}"
record_nonce_or_deny "$(printf '%s' "$CASAN_APPROVAL_JWT" | sha_stdin)"
echo "APPROVAL_OK mechanism=oidc role=$ROLE approver=$APPROVER action=$ACTION"
exit 0
fi
[[ -n "$SIG_FILE" && -f "$SIG_FILE" ]] || deny "signature_missing"
# Reviewer lookup (first matching registered reviewer).
REV_LINE="$(awk -v id="$APPROVER" '$1=="reviewer" && $2==id {print $3" "$4; exit}' "$REVIEWERS_FILE")"
[[ -n "$REV_LINE" ]] || deny "approver_not_registered"
ROLE="${REV_LINE%% *}"
PUB_REL="${REV_LINE##* }"
case ",$ROLES," in
*",$ROLE,"*) : ;;
*) deny "approver_role_not_authorized(role=$ROLE action=$ACTION allowed=$ROLES)" ;;
esac
# Resolve pubkey path (absolute or relative to reviewers dir).
PUB="$PUB_REL"; [[ "$PUB" = /* ]] || PUB="$REVIEWERS_DIR/$PUB_REL"
[[ -f "$PUB" ]] || deny "approver_pubkey_missing($PUB)"
# Rebuild the exact signed assertion and verify.
MSG="casan-approval|v1|$ACTION|$ACTOR|$INPUT_SHA|$APPROVER"
TMP="$(mktemp)"; trap 'rm -f "$TMP"' EXIT
printf '%s' "$MSG" > "$TMP"
openssl dgst -sha256 -verify "$PUB" -signature "$SIG_FILE" "$TMP" >/dev/null 2>&1 \
|| deny "approval_signature_invalid"
record_nonce_or_deny "$(sha_stdin < "$SIG_FILE")"
echo "APPROVAL_OK role=$ROLE approver=$APPROVER action=$ACTION"
exit 0