diff --git a/.github/workflows/codeql-analysis-gate.yml b/.github/workflows/codeql-analysis-gate.yml new file mode 100644 index 0000000..bf15445 --- /dev/null +++ b/.github/workflows/codeql-analysis-gate.yml @@ -0,0 +1,501 @@ +name: CodeQL Analysis Gate + +# This workflow runs from the pull_request merge commit. It is a fail-closed +# analysis check, not an immutable workflow signature. Workflow changes remain +# subject to owner review and Luna's independent audit. + +on: + pull_request: + branches: + - main + types: + - opened + - synchronize + - reopened + - ready_for_review + +concurrency: + group: codeql-analysis-gate-${{ github.event.pull_request.number }} + cancel-in-progress: true + +permissions: + actions: read + contents: read + checks: read + pull-requests: read + security-events: read + +jobs: + codeql-analysis-gate: + name: CodeQL Analysis Gate + runs-on: ubuntu-latest + timeout-minutes: 20 + + steps: + - name: Verify CodeQL analysis provenance and aggregate result + env: + GH_TOKEN: ${{ github.token }} + GH_REPO: ${{ github.repository }} + PR_NUMBER: ${{ github.event.pull_request.number }} + HEAD_SHA: ${{ github.event.pull_request.head.sha }} + BASE_SHA: ${{ github.event.pull_request.base.sha }} + MERGE_SHA: ${{ github.sha }} + POLL_SECONDS: "20" + START_DEADLINE_SECONDS: "300" + COMPLETION_DEADLINE_SECONDS: "900" + COMPLETION_GRACE_SECONDS: "180" + shell: bash + run: | + set -euo pipefail + + fail() { + echo "::error title=CodeQL Analysis Gate::$*" + exit 1 + } + + [ -n "${PR_NUMBER:-}" ] || fail "Missing pull request number." + [ -n "${HEAD_SHA:-}" ] || fail "Missing pull request head SHA." + [ -n "${BASE_SHA:-}" ] || fail "Missing pull request base SHA." + [ -n "${MERGE_SHA:-}" ] && [ "$MERGE_SHA" != "null" ] \ + || fail "Execution SHA is missing; refusing to evaluate an unidentified candidate." + [ "$MERGE_SHA" != "$HEAD_SHA" ] \ + || fail "Execution SHA equals the PR head; refusing to substitute the head for the test merge." + + TMP_DIR="$(mktemp -d)" + trap 'rm -rf "$TMP_DIR"' EXIT + + PR_JSON="$TMP_DIR/pr.json" + MAIN_JSON="$TMP_DIR/main.json" + COMMIT_JSON="$TMP_DIR/merge.json" + RUNS_RAW="$TMP_DIR/runs.raw.json" + RUNS_JSON="$TMP_DIR/runs.json" + ASSOCIATED_RUNS_JSON="$TMP_DIR/associated-runs.json" + ATTEMPT_JSON="$TMP_DIR/attempt.json" + ANALYSES_RAW="$TMP_DIR/analyses.raw.json" + ANALYSES_JSON="$TMP_DIR/analyses.json" + CHECKS_RAW="$TMP_DIR/checks.raw.json" + CHECKS_JSON="$TMP_DIR/checks.json" + AGG_STATE="$TMP_DIR/aggregate-state.json" + ERR="$TMP_DIR/api.err" + + gh_retry() { + local label="$1" + shift + local out="$1" + shift + local err="$1" + shift + local attempt=1 + local max_attempts=4 + local message + + while :; do + if gh api "$@" >"$out" 2>"$err"; then + return 0 + fi + message="$(cat "$err")" + case "$message" in + *"HTTP 401"*|*"HTTP 403"*) + fail "GitHub API denied for $label: $message" + ;; + *"HTTP 404"*|*"HTTP 422"*) + fail "GitHub API rejected $label: $message" + ;; + esac + if [ "$attempt" -ge "$max_attempts" ]; then + fail "GitHub API unavailable for $label after $max_attempts attempts: $message" + fi + sleep $((attempt * 5)) + attempt=$((attempt + 1)) + done + } + + validate_identity() { + IDENTITY_PENDING="" + gh_retry "pull request identity" "$PR_JSON" "$ERR" \ + "repos/$GH_REPO/pulls/$PR_NUMBER" + gh_retry "main ref" "$MAIN_JSON" "$ERR" \ + "repos/$GH_REPO/git/ref/heads/main" + + jq -e \ + --arg repo "$GH_REPO" \ + --arg head "$HEAD_SHA" \ + --arg base "$BASE_SHA" \ + ' + .state == "open" + and .head.sha == $head + and .base.sha == $base + and .base.ref == "main" + and .base.repo.full_name == $repo + ' "$PR_JSON" >/dev/null \ + || fail "PR identity changed or no longer matches the event. A new push requires a new gate run." + + local main_sha + main_sha="$(jq -r '.object.sha' "$MAIN_JSON")" + [ "$main_sha" = "$BASE_SHA" ] \ + || fail "PR base $BASE_SHA is not current main $main_sha. Update the branch and rerun." + + gh_retry "test merge commit" "$COMMIT_JSON" "$ERR" \ + "repos/$GH_REPO/commits/$MERGE_SHA" + local parents expected + parents="$(jq -r '.parents[].sha' "$COMMIT_JSON" | sort)" + expected="$(printf '%s\n%s\n' "$BASE_SHA" "$HEAD_SHA" | sort)" + [ "$parents" = "$expected" ] \ + || fail "Execution SHA does not have the current base and PR head as parents." + + local live_merge + live_merge="$(jq -r '.merge_commit_sha // empty' "$PR_JSON")" + if [ -z "$live_merge" ] || [ "$live_merge" = "null" ]; then + if [ "$ELAPSED" -ge "$START_DEADLINE_SECONDS" ]; then + fail "Live PR test-merge SHA did not become available within ${START_DEADLINE_SECONDS}s." + fi + IDENTITY_PENDING="live PR test-merge SHA is not yet available" + return 0 + fi + [ "$live_merge" = "$MERGE_SHA" ] \ + || fail "Execution SHAs differ: workflow execution $MERGE_SHA vs live PR test merge $live_merge. A fresh reviewed head is required." + } + + get_runs() { + gh_retry "CodeQL workflow runs" "$RUNS_RAW" "$ERR" \ + --paginate --slurp \ + "repos/$GH_REPO/actions/runs?head_sha=$HEAD_SHA&per_page=100" + jq '{workflow_runs: [.[].workflow_runs[]]}' "$RUNS_RAW" > "$RUNS_JSON" + } + + get_associated_runs() { + get_runs + jq \ + --arg branch "refs/pull/$PR_NUMBER/head" \ + --arg sha "$HEAD_SHA" \ + --argjson pr "$PR_NUMBER" \ + ' + [ .workflow_runs[] + | select( + .head_sha == $sha + and .event == "dynamic" + and .path == "dynamic/github-code-scanning/codeql" + and ( + .head_branch == $branch + or ((.pull_requests // []) | any(.number == $pr)) + ) + ) + ] + ' "$RUNS_JSON" > "$ASSOCIATED_RUNS_JSON" + } + + select_first_attempt() { + SELECTED_RUN="" + SELECTED_ATTEMPT="" + SELECTED_RUN_ID="" + SELECTED_RUN_ATTEMPT="" + SELECTED_ATTEMPT_START="" + + local run_count + run_count="$(jq 'length' "$ASSOCIATED_RUNS_JSON")" + ASSOCIATED_RUN_COUNT="$run_count" + if [ "$run_count" -eq 0 ]; then + return + fi + if [ "$run_count" -gt 1 ]; then + fail "CodeQL analysis evidence cannot be attributed unambiguously across multiple runs or attempts on this PR head. Push a fresh reviewed commit and allow a new first-attempt CodeQL analysis." + fi + + SELECTED_RUN="$(jq -c '.[0]' "$ASSOCIATED_RUNS_JSON")" + local run_id run_attempt + run_id="$(jq -r '.id // empty' <<<"$SELECTED_RUN")" + run_attempt="$(jq -r '.run_attempt // empty' <<<"$SELECTED_RUN")" + [[ "$run_id" =~ ^[0-9]+$ ]] \ + || fail "CodeQL attempt metadata is missing or inconsistent. Push a fresh reviewed commit and allow a new first-attempt CodeQL analysis." + if [ -z "$OBSERVED_RUN_ID" ]; then + OBSERVED_RUN_ID="$run_id" + elif [ "$run_id" != "$OBSERVED_RUN_ID" ]; then + fail "CodeQL analysis evidence cannot be attributed unambiguously across multiple runs or attempts on this PR head. Push a fresh reviewed commit and allow a new first-attempt CodeQL analysis." + fi + [[ "$run_attempt" =~ ^[0-9]+$ ]] && [ "$run_attempt" -eq 1 ] \ + || fail "CodeQL analysis evidence cannot be attributed unambiguously across multiple runs or attempts on this PR head. Push a fresh reviewed commit and allow a new first-attempt CodeQL analysis." + + gh_retry "first workflow attempt $run_id/1" "$ATTEMPT_JSON" "$ERR" \ + "repos/$GH_REPO/actions/runs/$run_id/attempts/1" + + jq -e \ + --argjson id "$run_id" \ + --arg branch "refs/pull/$PR_NUMBER/head" \ + --arg sha "$HEAD_SHA" \ + --argjson pr "$PR_NUMBER" \ + ' + .id == $id + and .run_attempt == 1 + and .head_sha == $sha + and .event == "dynamic" + and .path == "dynamic/github-code-scanning/codeql" + and ( + .head_branch == $branch + or ((.pull_requests // []) | any(.number == $pr)) + ) + ' "$ATTEMPT_JSON" >/dev/null \ + || fail "CodeQL attempt metadata is missing or inconsistent. Push a fresh reviewed commit and allow a new first-attempt CodeQL analysis." + + if ! jq -e ' + (.run_started_at | type) == "string" + and (.run_started_at | length) > 0 + and (.updated_at | type) == "string" + and (.updated_at | length) > 0 + ' "$ATTEMPT_JSON" >/dev/null; then + fail "CodeQL attempt metadata is missing or inconsistent. Push a fresh reviewed commit and allow a new first-attempt CodeQL analysis." + fi + + SELECTED_ATTEMPT="$(cat "$ATTEMPT_JSON")" + SELECTED_RUN_ID="$run_id" + SELECTED_RUN_ATTEMPT="1" + SELECTED_ATTEMPT_START="$(jq -r '.run_started_at' "$ATTEMPT_JSON")" + } + + get_analyses() { + gh_retry "CodeQL analyses" "$ANALYSES_RAW" "$ERR" \ + --paginate --slurp \ + "repos/$GH_REPO/code-scanning/analyses?ref=refs/pull/$PR_NUMBER/head&sort=created&direction=desc&per_page=100" + jq 'add // []' "$ANALYSES_RAW" > "$ANALYSES_JSON" + } + + get_checks() { + gh_retry "head check runs" "$CHECKS_RAW" "$ERR" \ + --paginate --slurp \ + "repos/$GH_REPO/commits/$HEAD_SHA/check-runs?per_page=100" + jq '{check_runs: [.[].check_runs[]]}' "$CHECKS_RAW" > "$CHECKS_JSON" + } + + evaluate_once() { + IDENTITY_PENDING="" + validate_identity + if [ -n "$IDENTITY_PENDING" ]; then + RESULT="PENDING" + REASON="$IDENTITY_PENDING" + return + fi + get_associated_runs + SELECTED_RUN="" + SELECTED_ATTEMPT="" + SELECTED_RUN_ID="" + SELECTED_RUN_ATTEMPT="" + SELECTED_ATTEMPT_START="" + ASSOCIATED_RUN_COUNT=0 + select_first_attempt + + if [ -z "$SELECTED_ATTEMPT" ]; then + if [ "$ELAPSED" -ge "$START_DEADLINE_SECONDS" ]; then + fail "No CodeQL dynamic analysis run associated with PR #$PR_NUMBER started within ${START_DEADLINE_SECONDS}s. This is expected for Dependabot or fork heads under default setup. Use a maintainer-authored branch/update or an approved advanced-setup migration." + fi + RESULT="PENDING" + REASON="no CodeQL run associated with this PR has started" + return + fi + + local run_status run_conclusion run_updated_at run_updated_epoch run_age + run_status="$(jq -r '.status' <<<"$SELECTED_ATTEMPT")" + run_conclusion="$(jq -r '.conclusion // empty' <<<"$SELECTED_ATTEMPT")" + run_updated_at="$(jq -r '.updated_at' <<<"$SELECTED_ATTEMPT")" + run_updated_epoch="$(date -d "$run_updated_at" +%s)" + run_age=$((NOW - run_updated_epoch)) + [ "$run_age" -ge 0 ] || run_age=0 + + if [ "$run_status" != "completed" ]; then + RESULT="PENDING" + REASON="selected CodeQL attempt $SELECTED_RUN_ID/$SELECTED_RUN_ATTEMPT is $run_status" + return + fi + if [ "$run_conclusion" != "success" ]; then + fail "Selected CodeQL attempt $SELECTED_RUN_ID/$SELECTED_RUN_ATTEMPT concluded '$run_conclusion', not success." + fi + + local attempt_start_epoch + attempt_start_epoch="$(date -d "$SELECTED_ATTEMPT_START" +%s)" + + get_analyses + get_checks + + jq -c \ + --arg sha "$HEAD_SHA" \ + --argjson start "$attempt_start_epoch" \ + ' + [ .check_runs[] + | select( + .name == "CodeQL" + and .app.id == 57789 + and .head_sha == $sha + ) + ] + | { + candidates: [ + .[] + | select(.started_at != null and .started_at != "") + | . + { + start_epoch: ( + try (.started_at | fromdateiso8601) catch null + ) + } + | select(.start_epoch != null and .start_epoch >= $start) + ], + unresolved: [ + .[] + | select(.started_at == null or .started_at == "") + ] + } + ' "$CHECKS_JSON" > "$AGG_STATE" + + local unresolved_pending unresolved_completed + unresolved_pending="$(jq '[.unresolved[] | select(.status != "completed")] | length' "$AGG_STATE")" + unresolved_completed="$(jq '[.unresolved[] | select(.status == "completed")] | length' "$AGG_STATE")" + if [ "$unresolved_completed" -gt 0 ]; then + fail "Aggregate CodeQL check has no publication timestamp; fresh attempt association cannot be established." + fi + if [ "$unresolved_pending" -gt 0 ]; then + RESULT="PENDING" + REASON="aggregate CodeQL check is pending without a publication timestamp" + return + fi + + local candidate_count + candidate_count="$(jq '.candidates | length' "$AGG_STATE")" + if [ "$candidate_count" -eq 0 ]; then + if [ "$run_age" -ge "$COMPLETION_GRACE_SECONDS" ]; then + fail "The aggregate CodeQL check did not appear after the selected attempt start within ${COMPLETION_GRACE_SECONDS}s of attempt completion." + fi + RESULT="PENDING" + REASON="aggregate CodeQL check has not appeared for the selected attempt" + return + fi + + if jq -e 'any(.candidates[]; .status != "completed")' "$AGG_STATE" >/dev/null; then + RESULT="PENDING" + REASON="aggregate CodeQL check is pending for the selected attempt" + return + fi + + local latest_aggregate_start aggregate_candidates_at_start + latest_aggregate_start="$(jq -r \ + '.candidates | sort_by(.start_epoch, .id) | last | .start_epoch' \ + "$AGG_STATE")" + aggregate_candidates_at_start="$(jq -r --argjson start "$latest_aggregate_start" \ + '[.candidates[] | select(.start_epoch == $start)] | length' \ + "$AGG_STATE")" + if [ "$aggregate_candidates_at_start" -ne 1 ]; then + fail "Multiple aggregate CodeQL checks share the latest publication start; fresh attempt association is ambiguous." + fi + + AGGREGATE="$(jq -c \ + '.candidates | sort_by(.start_epoch, .id) | last' \ + "$AGG_STATE")" + local aggregate_conclusion + aggregate_conclusion="$(jq -r '.conclusion // empty' <<<"$AGGREGATE")" + if [ "$aggregate_conclusion" != "success" ]; then + fail "Aggregate CodeQL check concluded '$aggregate_conclusion', not success." + fi + + LATEST_ANALYSES="$TMP_DIR/latest-analyses.json" + jq \ + --arg ref "refs/pull/$PR_NUMBER/head" \ + --arg sha "$HEAD_SHA" \ + --argjson start "$attempt_start_epoch" \ + ' + [ .[] + | select( + .ref == $ref + and .commit_sha == $sha + and .tool.name == "CodeQL" + and .analysis_key == "dynamic/github-code-scanning/codeql:analyze" + and (.created_at | type) == "string" + and (.created_at | length) > 0 + and ( + (try (.created_at | fromdateiso8601) catch null) != null + ) + and ( + (try (.created_at | fromdateiso8601) catch null) >= $start + ) + ) + ] + | sort_by(.created_at, .id) + | group_by(.category) + | map(last) + ' "$ANALYSES_JSON" > "$LATEST_ANALYSES" + + for category in \ + "/language:actions" \ + "/language:c-cpp" \ + "/language:javascript-typescript" \ + "/language:python"; do + entry="$(jq -c --arg category "$category" \ + '[.[] | select(.category == $category)] | last // empty' \ + "$LATEST_ANALYSES")" + if [ -z "$entry" ]; then + if [ "$run_age" -ge "$COMPLETION_GRACE_SECONDS" ]; then + fail "CodeQL attempt $SELECTED_RUN_ID/$SELECTED_RUN_ATTEMPT completed but required analysis configuration $category has no fresh record after the attempt start." + fi + RESULT="PENDING" + REASON="missing fresh analysis configuration $category" + return + fi + + error="$(jq -r '.error // ""' <<<"$entry")" + [ -z "$error" ] \ + || fail "CodeQL analysis configuration $category reported an error: $error" + + language="$(jq -r '(.environment | fromjson? | .language) // empty' <<<"$entry")" + case "$category" in + "/language:actions") expected_language="actions" ;; + "/language:c-cpp") expected_language="c-cpp" ;; + "/language:javascript-typescript") expected_language="javascript-typescript" ;; + "/language:python") expected_language="python" ;; + *) fail "Unexpected required category: $category" ;; + esac + [ "$language" = "$expected_language" ] \ + || fail "Configuration $category has unexpected language identity: ${language:-missing}" + done + + RESULT="PASS" + REASON="fresh attempt $SELECTED_RUN_ID/$SELECTED_RUN_ATTEMPT has four analyses and aggregate success" + } + + START_EPOCH="$(date +%s)" + RESULT="" + REASON="" + OBSERVED_RUN_ID="" + + while :; do + NOW="$(date +%s)" + ELAPSED=$((NOW - START_EPOCH)) + if [ "$ELAPSED" -ge "$COMPLETION_DEADLINE_SECONDS" ]; then + fail "Timed out after ${COMPLETION_DEADLINE_SECONDS}s without complete fresh CodeQL attempt evidence. Last status: ${REASON:-unknown}." + fi + + evaluate_once + + if [ "$RESULT" = "PASS" ]; then + PASS_RUN_ID="$SELECTED_RUN_ID" + PASS_RUN_ATTEMPT="$SELECTED_RUN_ATTEMPT" + # Revalidate immediately before success so a newly started attempt, + # changed head/base, or newer aggregate failure cannot be ignored. + evaluate_once + if [ "$RESULT" = "PASS" ] \ + && [ "$SELECTED_RUN_ID" = "$PASS_RUN_ID" ] \ + && [ "$SELECTED_RUN_ATTEMPT" = "$PASS_RUN_ATTEMPT" ]; then + NOW="$(date +%s)" + ELAPSED=$((NOW - START_EPOCH)) + [ "$ELAPSED" -lt "$COMPLETION_DEADLINE_SECONDS" ] \ + || fail "Timed out before final success at ${ELAPSED}s." + echo "CodeQL Analysis Gate passed for $HEAD_SHA." + echo "$REASON" + exit 0 + fi + if [ "$RESULT" = "PASS" ]; then + fail "CodeQL analysis evidence cannot be attributed unambiguously across multiple runs or attempts on this PR head. Push a fresh reviewed commit and allow a new first-attempt CodeQL analysis." + fi + fi + + REMAINING=$((COMPLETION_DEADLINE_SECONDS - ELAPSED)) + SLEEP_SECONDS="$POLL_SECONDS" + if [ "$REMAINING" -lt "$SLEEP_SECONDS" ]; then + SLEEP_SECONDS="$REMAINING" + fi + [ "$SLEEP_SECONDS" -gt 0 ] && sleep "$SLEEP_SECONDS" + done