#!/usr/bin/env bash
# RiskRift scan for CI/CD: starts a scan, waits, saves the reports and fails the
# job at the severity you choose. Needs bash, curl and jq.
# Guide: https://riskrift.com/docs#ci
set -euo pipefail

API="${RISKRIFT_API_URL:-https://riskrift.com/api/v1}"
TARGET="" FAIL_ON="high" LIMIT="" FORMATS="json,sarif,pdf" OUTPUT="riskrift-report" TIMEOUT=300 ON_TIMEOUT="detach" WAIT=1 SCAN_ID="" AUTHORIZED=""

usage() {
  cat <<'USAGE'
Usage: riskrift-scan.sh --target URL --i-am-authorized [options]
       riskrift-scan.sh --scan ID [options]

  --target URL          Public URL to scan. Its hostname must be verified in RiskRift.
  --i-am-authorized     You confirm that you may test this application.
  --scan ID             Follow an existing scan instead of starting one.
  --limit DOLLARS       Most the scan may cost, 5 to 500 (needed once your free scan is used).
  --fail-on SEVERITY    critical, high (default), medium, low, informational or none.
  --formats LIST        Reports to save: json,sarif,pdf (default: all three).
  --output DIR          Where to save them (default: riskrift-report).
  --timeout MINUTES     How long to wait (default: 300).
  --on-timeout ACTION   detach (default: leave it running, exit 4) or finish (stop it and take the report).
  --no-wait             Start the scan and exit.

Set RISKRIFT_API_KEY in your CI secrets. Login for an authenticated scan:
RISKRIFT_LOGIN_USERNAME, RISKRIFT_LOGIN_PASSWORD and optionally RISKRIFT_LOGIN_URL.

Exit codes: 0 passed, 1 findings at or above --fail-on, 2 usage or request error,
3 scan failed or cancelled, 4 still running after --timeout, 5 waiting for you in the workspace.
USAGE
}
fail() { echo "riskrift: $2" >&2; exit "$1"; }

while [ $# -gt 0 ]; do
  case "$1" in
    --target|--scan|--limit|--fail-on|--formats|--output|--timeout|--on-timeout)
      [ $# -ge 2 ] || fail 2 "$1 needs a value."
      case "$1" in
        --target) TARGET="$2";; --scan) SCAN_ID="$2";; --limit) LIMIT="$2";; --fail-on) FAIL_ON="$2";;
        --formats) FORMATS="$2";; --output) OUTPUT="$2";; --timeout) TIMEOUT="$2";; --on-timeout) ON_TIMEOUT="$2";;
      esac
      shift 2;;
    --i-am-authorized) AUTHORIZED=1; shift;;
    --no-wait) WAIT=0; shift;;
    -h|--help) usage; exit 0;;
    *) usage >&2; fail 2 "unknown option: $1";;
  esac
done

command -v curl >/dev/null || fail 2 "curl is required."
command -v jq >/dev/null || fail 2 "jq is required."
[ -n "${RISKRIFT_API_KEY:-}" ] || fail 2 "set RISKRIFT_API_KEY."
case "$FAIL_ON" in critical|high|medium|low|informational|none) ;; *) fail 2 "--fail-on: unknown severity.";; esac
case "$ON_TIMEOUT" in detach|finish) ;; *) fail 2 "--on-timeout: use detach or finish.";; esac
[[ "$TIMEOUT" =~ ^[0-9]{1,5}$ ]] || fail 2 "--timeout: use whole minutes."
[ -z "$LIMIT" ] || [[ "$LIMIT" =~ ^[0-9]{1,3}$ ]] || fail 2 "--limit: use whole dollars, such as 10."
for format in ${FORMATS//,/ }; do case "$format" in json|sarif|pdf) ;; *) fail 2 "--formats: unknown format $format.";; esac; done

umask 077
WORK="$(mktemp -d)"; BODY="$WORK/answer"; trap 'rm -rf "$WORK"' EXIT

# The key goes through curl's standard input: never in the process list or the log.
request() { # method path [curl arguments]; prints the HTTP status, writes the answer to $BODY
  local method="$1" path="$2"; shift 2
  printf 'header = "Authorization: Bearer %s"\n' "$RISKRIFT_API_KEY" |
    curl --config - --silent --show-error --connect-timeout 15 --max-time 120 --retry 4 --retry-all-errors --retry-delay 5 --retry-max-time 90 \
      --request "$method" --write-out '%{http_code}' --output "$BODY" "$@" "$API$path" || fail 2 "RiskRift could not be reached."
}
refused() { fail 2 "$(jq -r '"\(.title): \(.detail) [\(.code), \(.request_id)]"' "$BODY" 2>/dev/null || echo "unexpected answer (HTTP $1)")"; }
field() { jq -r "$1" "$BODY"; }

if [ -z "$SCAN_ID" ]; then
  [ -n "$TARGET" ] || { usage >&2; fail 2 "--target is required."; }
  [ -n "$AUTHORIZED" ] || fail 2 "confirm that you may test this application with --i-am-authorized."
  # The test account is read from the environment by jq: never in the process list.
  jq -n --arg target "$TARGET" --arg limit "$LIMIT" '
    {target: $target, authorized: true,
     metadata: ({commit: (env.GITHUB_SHA // env.CI_COMMIT_SHA), branch: (env.GITHUB_REF_NAME // env.CI_COMMIT_REF_NAME),
                 run: (env.GITHUB_RUN_ID // env.CI_PIPELINE_ID // env.BUILD_NUMBER)} | with_entries(select(.value != null and .value != "")))}
    + (if $limit != "" then {spend_limit_cents: (($limit | tonumber) * 100)} else {} end)
    + (if (env.RISKRIFT_LOGIN_USERNAME // "") != "" then
        {login: ({username: env.RISKRIFT_LOGIN_USERNAME, password: (env.RISKRIFT_LOGIN_PASSWORD // "")}
          + (if (env.RISKRIFT_LOGIN_URL // "") != "" then {url: env.RISKRIFT_LOGIN_URL} else {} end))} else {} end)' > "$WORK/request"
  # One key per run: if the answer is lost, the retry returns the same scan instead of starting a second one.
  IDEMPOTENCY="ci-$(od -An -N16 -tx1 /dev/urandom | tr -d ' \n')"
  CODE="$(request POST /scans --header 'Content-Type: application/json' --header "Idempotency-Key: $IDEMPOTENCY" --data-binary "@$WORK/request")"
  if [ "$CODE" = 201 ]; then
    SCAN_ID="$(field .id)"; echo "riskrift: scan $SCAN_ID created for $(field .target)"
  elif [ "$CODE" = 409 ] && [ "$(field '.code // ""')" = scan_in_progress ]; then
    SCAN_ID="$(field .scan_id)"; echo "riskrift: a scan of this target is already in progress, following $SCAN_ID"
  else
    refused "$CODE"
  fi
fi
[[ "$SCAN_ID" =~ ^[0-9a-f-]{36}$ ]] || fail 2 "unexpected scan id."
if [ -n "${GITHUB_OUTPUT:-}" ]; then echo "scan-id=$SCAN_ID" >> "$GITHUB_OUTPUT"; fi
[ "$WAIT" = 1 ] || exit 0

DEADLINE=$(( $(date +%s) + TIMEOUT * 60 )); STATUS="" LAST="" FINISHED=""
while :; do
  CODE="$(request GET "/scans/$SCAN_ID")"
  [ "$CODE" = 200 ] || refused "$CODE"
  STATUS="$(field .status)"
  if [ "$STATUS" != "$LAST" ]; then echo "riskrift: $(date -u +%H:%M:%SZ) $STATUS ($(field .findings.total) findings so far)"; LAST="$STATUS"; fi
  case "$STATUS" in
    completed) break;;
    failed|cancelled) fail 3 "the scan is $STATUS. $(field '.error.message // ""')";;
    action_required) fail 5 "$(field .action_required.message) $(field '.dashboard_url // ""')";;
  esac
  if [ "$(date +%s)" -ge "$DEADLINE" ]; then
    if [ "$ON_TIMEOUT" = finish ] && [ -z "$FINISHED" ]; then
      CODE="$(request POST "/scans/$SCAN_ID/finish")"
      [ "$CODE" = 200 ] || refused "$CODE"
      echo "riskrift: time is up, finishing the scan to get its report"
      FINISHED=1; DEADLINE=$(( $(date +%s) + 3600 ))
    else
      fail 4 "still $STATUS. Collect it later with: riskrift-scan.sh --scan $SCAN_ID"
    fi
  fi
  sleep "${RISKRIFT_POLL_SECONDS:-30}"
done

cp "$BODY" "$WORK/scan"
mkdir -p "$OUTPUT"
for format in ${FORMATS//,/ }; do
  CODE="$(request GET "/scans/$SCAN_ID/report.$format")"
  [ "$CODE" = 200 ] || refused "$CODE"
  cp "$BODY" "$OUTPUT/riskrift.$format"
  echo "riskrift: saved $OUTPUT/riskrift.$format"
done

jq -r '"riskrift: \(.findings.total) findings: \(.findings.critical) critical, \(.findings.high) high, \(.findings.medium) medium, \(.findings.low) low, \(.findings.informational) informational",
  (if .coverage == "partial" then "riskrift: testing stopped before the end, so coverage is partial" else empty end),
  (if .billing.mode == "paid" then "riskrift: charged $\((.billing.charged_cents // .billing.spent_cents) / 100)" else empty end)' "$WORK/scan"
[ "$FAIL_ON" != none ] || exit 0
BLOCKING="$(jq --arg level "$FAIL_ON" '["critical","high","medium","low","informational"] as $order | .findings as $f | [$order[: ($order | index($level)) + 1][] | $f[.]] | add' "$WORK/scan")"
if [ "$BLOCKING" -gt 0 ]; then fail 1 "findings at or above $FAIL_ON: $BLOCKING. They were recorded automatically: review them in the report."; fi
echo "riskrift: no finding at or above $FAIL_ON. This does not prove that the site is secure."
