#!/usr/bin/env bash
#
# Scan a skill zip with AI Supply Chain Security.
#
# Looks the skill up by fingerprint first and returns the existing verdict on a hit;
# on a miss, uploads the zip, creates a scan and polls it until it finishes.
#
# Usage:
# scripts/scan-skill.sh <skill.zip> <scsg_uuid> [scan_name]
#
# Auth (one of):
# MODEL_SECURITY_ACCESS_TOKEN Bearer token to use as-is
# MODEL_SECURITY_CLIENT_ID Service account client ID (sa@<tsg_id>.iam.panserviceaccount.com)
# MODEL_SECURITY_CLIENT_SECRET Service account client secret
# MODEL_SECURITY_TSG_ID Optional; derived from the client ID when unset
#
# Optional:
# MODEL_SECURITY_API_ENDPOINT Data plane base URL (default: https://api.sase.paloaltonetworks.com/aims/data)
# MODEL_SECURITY_TOKEN_ENDPOINT OAuth token URL (default: https://auth.apps.paloaltonetworks.com/oauth2/access_token)
# MODEL_SECURITY_SCOPE_NAME Workspace (default: workspace_default)
# POLL_INTERVAL_SECONDS Seconds between polls (default: 5)
# POLL_TIMEOUT_SECONDS Give up polling after this long (default: 600)
#
# Requires: curl, jq, unzip, git, shasum, gcloud
#
# Output: the final scan JSON on stdout; progress on stderr.
# Exit codes: 0 ALLOWED, 2 BLOCKED, 1 error, failed scan or timeout.
set -euo pipefail
BASE_URL="${MODEL_SECURITY_API_ENDPOINT:-https://api.sase.paloaltonetworks.com/aims/data}"
BASE_URL="${BASE_URL%/}"
TOKEN_URL="${MODEL_SECURITY_TOKEN_ENDPOINT:-https://auth.apps.paloaltonetworks.com/oauth2/access_token}"
SCOPE_NAME="${MODEL_SECURITY_SCOPE_NAME:-workspace_default}"
POLL_INTERVAL_SECONDS="${POLL_INTERVAL_SECONDS:-5}"
POLL_TIMEOUT_SECONDS="${POLL_TIMEOUT_SECONDS:-600}"
log() { echo "[scan-skill] $*" >&2; }
die() { log "ERROR: $*"; exit 1; }
usage() {
sed -n '8,9p' "$0" >&2
exit 1
}
[[ $# -ge 2 && $# -le 3 ]] || usage
SKILL_ZIP="$1"
SCSG_UUID="$2"
[[ -f "$SKILL_ZIP" ]] || die "no such file: $SKILL_ZIP"
SCAN_NAME="${3:-$(basename "$SKILL_ZIP" .zip)}"
for cmd in curl jq unzip git shasum gcloud; do
command -v "$cmd" >/dev/null || die "missing required command: $cmd"
done
WORK_DIR="$(mktemp -d)"
trap 'rm -rf "$WORK_DIR"' EXIT
# Calls the API. Sets HTTP_STATUS and writes the body to $WORK_DIR/response.json.
api() {
local method="$1" path="$2" body="${3:-}"
local args=(
-sS -X "$method" "${BASE_URL}${path}"
-H "Authorization: Bearer ${ACCESS_TOKEN}"
-H "x-workspace-id: ${SCOPE_NAME}"
-o "$WORK_DIR/response.json"
-w '%{http_code}'
)
if [[ -n "$body" ]]; then
args+=(-H "Content-Type: application/json" --data "$body")
fi
HTTP_STATUS="$(curl "${args[@]}")" || die "$method $path: request failed"
}
response() { cat "$WORK_DIR/response.json"; }
# Prints the scan JSON and exits with a code for its verdict.
finish() {
local scan_json="$1"
echo "$scan_json" | jq .
local status outcome
status="$(echo "$scan_json" | jq -r '.status')"
outcome="$(echo "$scan_json" | jq -r '.eval_outcome // "none"')"
log "status=$status eval_outcome=$outcome"
case "$status:$outcome" in
COMPLETED:ALLOWED) exit 0 ;;
COMPLETED:BLOCKED) exit 2 ;;
*) exit 1 ;;
esac
}
# =============================================================================
# Auth: get a Bearer token
# =============================================================================
if [[ -n "${MODEL_SECURITY_ACCESS_TOKEN:-}" ]]; then
ACCESS_TOKEN="$MODEL_SECURITY_ACCESS_TOKEN"
else
: "${MODEL_SECURITY_CLIENT_ID:?set MODEL_SECURITY_ACCESS_TOKEN, or MODEL_SECURITY_CLIENT_ID and MODEL_SECURITY_CLIENT_SECRET}"
: "${MODEL_SECURITY_CLIENT_SECRET:?set MODEL_SECURITY_CLIENT_SECRET}"
TSG_ID="${MODEL_SECURITY_TSG_ID:-}"
if [[ -z "$TSG_ID" && "$MODEL_SECURITY_CLIENT_ID" =~ ^[^@]+@([^.]+)\.iam\.panserviceaccount\.com$ ]]; then
TSG_ID="${BASH_REMATCH[1]}"
fi
[[ -n "$TSG_ID" ]] || die "set MODEL_SECURITY_TSG_ID; it cannot be derived from the client ID"
log "Requesting access token for TSG $TSG_ID"
ACCESS_TOKEN="$(
curl -sS --fail-with-body -X POST "$TOKEN_URL" \
-u "${MODEL_SECURITY_CLIENT_ID}:${MODEL_SECURITY_CLIENT_SECRET}" \
-H "Content-Type: application/x-www-form-urlencoded" \
--data "grant_type=client_credentials&scope=tsg_id:${TSG_ID}" \
| jq -r '.access_token // empty'
)" || die "token request failed"
[[ -n "$ACCESS_TOKEN" ]] || die "token response had no access_token"
fi
# =============================================================================
# Step 1: Compute the skill's fingerprint
#
# Matches ModelSec's calc_aggregate_fingerprint():
# 1. Git-style SHA1 blob ID per file: SHA1("blob <len>\0<content>")
# 2. SHA-256 over "<rel_path>:<blob_id>\n" for every file, sorted by path
# Paths are relative to the skill root. A zip holding one top-level folder (as
# zipping a folder in Finder produces) is treated as that folder, and __MACOSX/
# metadata is ignored.
# =============================================================================
log "Step 1: Computing fingerprint of $SKILL_ZIP"
EXTRACT_DIR="$WORK_DIR/skill"
mkdir -p "$EXTRACT_DIR"
unzip -q "$SKILL_ZIP" -d "$EXTRACT_DIR"
rm -rf "$EXTRACT_DIR/__MACOSX"
SKILL_ROOT="$EXTRACT_DIR"
TOP_LEVEL=()
while IFS= read -r entry; do TOP_LEVEL+=("$entry"); done < <(ls -A "$EXTRACT_DIR")
if [[ ${#TOP_LEVEL[@]} -eq 1 && -d "$EXTRACT_DIR/${TOP_LEVEL[0]}" ]]; then
SKILL_ROOT="$EXTRACT_DIR/${TOP_LEVEL[0]}"
fi
# LC_ALL=C sorts by byte, which for UTF-8 is the same order as Python's str sort.
FINGERPRINT="$(
cd "$SKILL_ROOT"
find . -type f | sed 's|^\./||' | LC_ALL=C sort | while IFS= read -r rel_path; do
printf '%s:%s\n' "$rel_path" "$(git hash-object --no-filters -- "$rel_path")"
done | shasum -a 256 | cut -d' ' -f1
)"
[[ "$FINGERPRINT" =~ ^[a-f0-9]{64}$ ]] || die "could not compute fingerprint"
log "Fingerprint: $FINGERPRINT"
# =============================================================================
# Step 2: POST /v1/artifact-scans/lookup
#
# 201: the skill was already scanned; this records a new COMPLETED scan with its
# verdict under the SCSG's rules. Return it.
# 404 or 5xx: a miss (or lookup unavailable); fall through to upload.
# Anything else (e.g. 400 scsg_missing_security_group) would fail the upload too.
# =============================================================================
log "Step 2: Looking up fingerprint"
api POST /v1/artifact-scans/lookup "$(
jq -n --arg fp "$FINGERPRINT" --arg scsg "$SCSG_UUID" \
'{fingerprint: $fp, scsg_uuid: $scsg}'
)"
case "$HTTP_STATUS" in
201)
log "Lookup hit; returning the existing verdict"
finish "$(response)"
;;
404 | 5??)
log "Lookup miss (HTTP $HTTP_STATUS); uploading the skill"
;;
*)
die "lookup failed (HTTP $HTTP_STATUS): $(response)"
;;
esac
# =============================================================================
# Step 3: POST /v1/artifact-scans/upload-url
#
# Returns a scan_uuid and a signed URL that accepts one PUT of the zip, plus the
# headers that PUT must send exactly as given.
# =============================================================================
log "Step 3: Requesting upload URL"
api POST /v1/artifact-scans/upload-url
[[ "$HTTP_STATUS" == 200 ]] || die "upload-url failed (HTTP $HTTP_STATUS): $(response)"
SCAN_UUID="$(response | jq -r '.scan_uuid')"
UPLOAD_URL="$(response | jq -r '.upload_url')"
UPLOAD_HEADER_ARGS=()
while IFS= read -r header; do
UPLOAD_HEADER_ARGS+=(-H "$header")
done < <(response | jq -r '.upload_headers | to_entries[] | "\(.key): \(.value)"')
log "Scan UUID: $SCAN_UUID"
# =============================================================================
# Step 4: Upload the skill to the signed URL
#
# The URL carries its own auth, so no Bearer token. GCS rejects the PUT unless it
# sends upload_headers (Content-Type and the size limit signed into the URL).
# =============================================================================
log "Step 4: Uploading $SKILL_ZIP"
UPLOAD_STATUS="$(
curl -sS -X PUT "$UPLOAD_URL" \
"${UPLOAD_HEADER_ARGS[@]}" \
--data-binary "@$SKILL_ZIP" \
-o "$WORK_DIR/upload.txt" \
-w '%{http_code}'
)" || die "upload request failed"
[[ "$UPLOAD_STATUS" == 2?? ]] || die "upload failed (HTTP $UPLOAD_STATUS): $(cat "$WORK_DIR/upload.txt")"
# =============================================================================
# Step 5: POST /v1/artifact-scans to finalize the scan submission
#
# checksum_crc32c is the base64 CRC32C of the bytes just uploaded; the server
# compares it with what GCS stored and rejects a corrupt upload (409).
# 201 creates the scan; 200 means this scan_uuid was already submitted.
# =============================================================================
log "Step 5: Creating scan"
CHECKSUM_CRC32C="$(
gcloud storage hash "$SKILL_ZIP" --skip-md5 --format='value(crc32c_hash)'
)" || die "could not compute CRC32C"
api POST /v1/artifact-scans "$(
jq -n \
--arg scsg "$SCSG_UUID" \
--arg name "$SCAN_NAME" \
--arg scan_uuid "$SCAN_UUID" \
--arg crc "$CHECKSUM_CRC32C" \
'{
scsg_uuid: $scsg,
artifact_type: "SKILL",
name: $name,
upload: {scan_uuid: $scan_uuid, checksum_crc32c: $crc}
}'
)"
[[ "$HTTP_STATUS" == 201 || "$HTTP_STATUS" == 200 ]] \
|| die "create scan failed (HTTP $HTTP_STATUS): $(response)"
# =============================================================================
# Step 6: GET /v1/artifact-scans/{scan_uuid} until the scan finishes
#
# COMPLETED and FAILED are terminal; CLASSIFYING and ANALYZING are still running.
# =============================================================================
log "Step 6: Polling scan $SCAN_UUID"
DEADLINE=$(( $(date +%s) + POLL_TIMEOUT_SECONDS ))
while true; do
api GET "/v1/artifact-scans/${SCAN_UUID}"
[[ "$HTTP_STATUS" == 200 ]] || die "get scan failed (HTTP $HTTP_STATUS): $(response)"
STATUS="$(response | jq -r '.status')"
case "$STATUS" in
COMPLETED | FAILED) finish "$(response)" ;;
esac
if (( $(date +%s) >= DEADLINE )); then
response | jq .
die "timed out after ${POLL_TIMEOUT_SECONDS}s; scan is still $STATUS"
fi
log " status=$STATUS; checking again in ${POLL_INTERVAL_SECONDS}s"
sleep "$POLL_INTERVAL_SECONDS"
done