#!/usr/bin/env bash
set -euo pipefail

fail() { echo "serviceification OCI verification: $*" >&2; exit 1; }
publisher_root="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/.." && pwd)"
usage() {
  echo "usage: $0 --owner-root DIR --source-repository OWNER/REPO [--source-commit SHA | --release-version VERSION] --oci-repository REPO --role ROLE --output FILE --evidence-output FILE [--digest SHA256 --binding SHA256]" >&2
}

owner_root= source_repository= source_commit= oci_repository= output= evidence_output=
exact_digest= role= binding= release_version=
while [[ $# -gt 0 ]]; do
  case "$1" in
    --owner-root) owner_root="${2:-}"; shift 2 ;;
    --source-repository) source_repository="${2:-}"; shift 2 ;;
    --source-commit) source_commit="${2:-}"; shift 2 ;;
    --release-version) release_version="${2:-}"; shift 2 ;;
    --oci-repository) oci_repository="${2:-}"; shift 2 ;;
    --output) output="${2:-}"; shift 2 ;;
    --evidence-output) evidence_output="${2:-}"; shift 2 ;;
    --digest) exact_digest="${2:-}"; shift 2 ;;
    --role) role="${2:-}"; shift 2 ;;
    --binding) binding="${2:-}"; shift 2 ;;
    *) usage; fail "unknown argument $1" ;;
  esac
done

[[ -n "$owner_root" && -n "$source_repository" && -n "$oci_repository" && -n "$output" && -n "$evidence_output" && -n "$role" ]] || { usage; exit 2; }
[[ "$source_repository" =~ ^[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+$ ]] || fail "invalid source repository"
[[ "$oci_repository" =~ ^ghcr\.io/[a-z0-9._-]+/[a-z0-9._/-]+$ ]] || fail "invalid OCI repository"
[[ "$(git -C "$owner_root" rev-parse --is-inside-work-tree 2>/dev/null)" == true ]] \
  || fail "owner source is not a git checkout"
if [[ "$role" == l0_engine ]]; then
  [[ -z "$source_commit" ]] || fail "L0 Engine selection must not supply a source commit"
  [[ "$release_version" =~ ^dev-[0-9]{8}-[0-9]+\.[0-9]+\.[0-9]+-[0-9a-f]{8}$ ]] \
    || fail "L0 Engine release version is not canonical"
  [[ "$source_repository" == pingcap-inc/NexusCRM ]] \
    || fail "L0 Engine release has the wrong source owner"
  [[ "$oci_repository" == ghcr.io/pingcap-inc/nexuscrm-l0-engine-release ]] \
    || fail "L0 Engine release has the wrong OCI repository"
  [[ "$exact_digest" =~ ^sha256:[0-9a-f]{64}$ ]] \
    || fail "L0 Engine release verification requires an exact digest"

  # The release artifact owns source provenance. Treat the requested version
  # and digest as selection data, derive the source commit from the embedded
  # descriptor, and only then use the owner checkout to verify policy material.
  release_probe="$(mktemp)"
  release_probe_container=
  cleanup_release_probe() {
    if [[ -n "$release_probe_container" ]]; then
      docker rm -f "$release_probe_container" >/dev/null 2>&1 || true
    fi
    rm -f "$release_probe"
  }
  trap cleanup_release_probe EXIT
  docker pull --quiet --platform linux/amd64 "$oci_repository@$exact_digest" >/dev/null
  release_probe_container="$(docker create --platform linux/amd64 \
    "$oci_repository@$exact_digest" /__nexuscrm_release_probe__)"
  docker cp "$release_probe_container:/release.json" "$release_probe"
  docker rm "$release_probe_container" >/dev/null
  release_probe_container=
  source_commit="$(jq -er --arg version "$release_version" '
    select(.schema_version == "nexuscrm.l0-engine-release/v1" and
           .version == $version and .source.repository == "pingcap-inc/NexusCRM") |
    .source.commit | select(test("^[0-9a-f]{40}$"))
  ' "$release_probe")" || fail "L0 Engine release descriptor is inconsistent"
  cleanup_release_probe
  trap - EXIT
else
  [[ -z "$release_version" ]] || fail "release version is only supported for L0 Engine"
  [[ "$source_commit" =~ ^[0-9a-f]{40}$ ]] || fail "source commit must be exact"
fi
if [[ "$role" == mcp_worker ]]; then
  [[ "$exact_digest" =~ ^sha256:[0-9a-f]{64}$ ]] || fail "MCP selection requires an immutable image digest"
fi
[[ "$(git -C "$owner_root" rev-parse HEAD)" == "$source_commit" ]] || fail "owner checkout disagrees with source commit"

## A source repository can publish more than one independently signed role.  The
## role, rather than the repository alone, selects the source-owned policy; the
## policy then supplies the only accepted OCI repository.  This is deliberately
## closed: a desired BOM cannot turn an owner checkout into a verifier for an
## arbitrary image.
case "$source_repository:$role" in
  pingcap-inc/NexusCRM:l0_engine)
    policy_relative=release/l0-engine-image-signing-policy.json
    policy_subject=engine-release
    ;;
  pingcap-inc/NexusCRM:runtime_api)
    policy_relative=release/runtime-api-image-signing-policy.json
    ;;
  pingcap-inc/NexusCRM:runtime_worker)
    policy_relative=release/runtime-worker-image-signing-policy.json
    ;;
  pingcap-inc/NexusCRM:integration_service)
    policy_relative=release/integration-service-image-signing-policy.json
    ;;
  pingcap-inc/nexuscrm-api-host:gateway)
    policy_relative=release/gateway-image-signing-policy.json
    ;;
  pingcap-inc/nexuscrm-app-packs:mcp_worker)
    policy_relative=release/mcp-worker-image-signing-policy.json
    ;;
  pingcap-inc/nexuscrm-app-packs:sfcrm_app_service)
    policy_relative=release/sfcrm-appservice-image-signing-policy.json
    ;;
  pingcap-inc/nexuscrm-controlplane:catalog_reconcile)
    policy_relative=release/catalog-reconcile-image-signing-policy.json
    ;;
  pingcap-inc/nexuscrm-pingcap-pack:frontend|pingcap-inc/nexuscrm-pingcap-pack:resolved_bom)
    policy_relative=release/serviceification-image-signing-policy.json
    [[ "$binding" =~ ^sha256:[0-9a-f]{64}$ ]] || fail "L2 verification requires an exact binding"
    ;;
  pingcap-inc/NexusCRM:*) fail "NexusCRM publication role is unsupported" ;;
  pingcap-inc/nexuscrm-api-host:*) fail "Gateway publication role is unsupported" ;;
  pingcap-inc/nexuscrm-app-packs:*) fail "AppService publication role is unsupported" ;;
  pingcap-inc/nexuscrm-controlplane:*) fail "Catalog publication role is unsupported" ;;
  pingcap-inc/nexuscrm-pingcap-pack:*) fail "L2 verification requires frontend or resolved_bom role" ;;
  *) fail "$source_repository has no D1 owner policy" ;;
esac

policy="$owner_root/$policy_relative"
[[ -f "$policy" ]] || fail "owner policy is missing"
selected_policy_subject="${policy_subject:-$role}"
expected_image="$(jq -er --arg role "$selected_policy_subject" '
  if (.image_repository? | type) == "string" then .image_repository
  elif (.subjects?[$role] | type) == "string" then .subjects[$role]
  elif (.subjects?[$role].image_repository | type) == "string" then .subjects[$role].image_repository
  else empty end
' "$policy")" || fail "owner policy has no image for the selected role"
[[ "$oci_repository" == "$expected_image" ]] || fail "OCI repository disagrees with owner role"
schema="$(jq -er '.schema_version' "$policy")"
keyless=false
if [[ "$schema" == nexuscrm.mcp-worker-keyless-signing-policy/v1 ]]; then
  [[ "$source_repository:$role" == pingcap-inc/nexuscrm-app-packs:mcp_worker ]] || fail "keyless policy is scoped to MCP Worker"
  jq -e '.publisher_state == "active" and .owner_repository == "pingcap-inc/nexuscrm-app-packs" and
    .repository_id == "1236725461" and .image_repository == "ghcr.io/pingcap-inc/nexuscrm-mcp-worker" and
    .source_ref == "refs/heads/main" and
    .workflow_ref == "pingcap-inc/nexuscrm-app-packs/.github/workflows/mcp-worker.yml@refs/heads/main" and
    .oidc_issuer == "https://token.actions.githubusercontent.com"' "$policy" >/dev/null || fail "MCP signer policy disagrees with the closed trust boundary"
  keyless=true
  public_key= public_key_sha256=
  policy_sha256="sha256:$(sha256sum "$policy" | awk '{print $1}')"
else
public_key_relative="$(jq -er '.public_key_path' "$policy")"
[[ "$public_key_relative" != /* && "$public_key_relative" != *..* ]] || fail "invalid public-key path"
public_key="$owner_root/$public_key_relative"
[[ -f "$public_key" ]] || fail "owner public key is missing"
openssl pkey -pubin -in "$public_key" -noout >/dev/null || fail "owner public key is invalid"
policy_sha256="sha256:$(sha256sum "$policy" | awk '{print $1}')"
public_key_sha256="sha256:$(sha256sum "$public_key" | awk '{print $1}')"
if [[ "$source_repository" == pingcap-inc/nexuscrm-pingcap-pack ]]; then
  [[ "$public_key_sha256" == sha256:348ad9206d3cc94e68dbd5bbfb422f5e57f75a90c550ffd7d7c4684942fbd8bf ]] \
    || fail "L2 owner public key is not the reviewed signing key"
fi
fi
schema="$(jq -er '.schema_version' "$policy")"
source_ref="$(jq -r '.source_ref // empty' "$policy")"
if [[ "$keyless" == true ]]; then
  workflow_ref="$(jq -er '.workflow_ref' "$policy")"
  signer_workflow_ref="$workflow_ref"
  provenance_workflow_ref="$workflow_ref"
elif [[ "$schema" == nexuscrm.l0-engine-image-signing-policy/v1 ]]; then
  [[ "$source_repository:$role" == pingcap-inc/NexusCRM:l0_engine ]] \
    || fail "L0 Engine policy is only supported for the unified Engine release"
  signer_workflow_ref="$(jq -er '.trusted_workflow_ref' "$policy")"
  provenance_workflow_ref="$(jq -er '.caller_workflow_ref' "$policy")"
  jq -e --arg owner "$source_repository" --arg image "$oci_repository" \
    --arg subject "$policy_subject" --arg public_key_path "$public_key_relative" \
    --arg public_key_sha256 "$public_key_sha256" \
    '.publisher_state == "active" and .owner_repository == $owner and
     .subjects[$subject].image_repository == $image and
     .source_ref == "refs/heads/main" and .public_key_path == $public_key_path and
     .public_key_sha256 == $public_key_sha256 and .key_spec == "ECC_NIST_P256" and
     .key_usage == "SIGN_VERIFY" and .signing_algorithm == "ECDSA_SHA_256" and
     (.caller_workflow_ref | type == "string" and endswith("@refs/heads/main")) and
     (.trusted_workflow_ref | test("^[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+/\\.github/workflows/[A-Za-z0-9._-]+@[0-9a-f]{40}$"))' \
    "$policy" >/dev/null || fail "L0 Engine owner policy facts are inconsistent"
elif [[ "$schema" == nexuscrm.l0-engine-image-signing-policy/v2 ]]; then
  [[ "$source_repository:$role" == pingcap-inc/NexusCRM:l0_engine ]] \
    || fail "L0 Engine policy is only supported for the unified Engine release"
  signer_workflow_ref="$(jq -er '.trusted_workflow_ref' "$policy")"
  provenance_workflow_ref=
  jq -e --arg owner "$source_repository" --arg image "$oci_repository" \
    --arg subject "$policy_subject" --arg public_key_path "$public_key_relative" \
    --arg public_key_sha256 "$public_key_sha256" \
    '.publisher_state == "active" and .owner_repository == $owner and
     .subjects[$subject].image_repository == $image and
     .caller_workflow_paths == [
       "pingcap-inc/NexusCRM/.github/workflows/go-ci.yml",
       "pingcap-inc/NexusCRM/.github/workflows/publish-l0-engine-dev-release.yml"
     ] and (.source_ref? == null) and (.caller_workflow_ref? == null) and
     .public_key_path == $public_key_path and
     .public_key_sha256 == $public_key_sha256 and .key_spec == "ECC_NIST_P256" and
     .key_usage == "SIGN_VERIFY" and .signing_algorithm == "ECDSA_SHA_256" and
     (.trusted_workflow_ref | test("^[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+/\\.github/workflows/[A-Za-z0-9._-]+@[0-9a-f]{40}$"))' \
    "$policy" >/dev/null || fail "L0 Engine owner policy facts are inconsistent"
elif [[ "$schema" == nexuscrm.l2-oci-owner-signing-policy/v2 || "$schema" == nexuscrm.l2-oci-owner-signing-policy/v3 ]]; then
  workflow_path="$(jq -er '.workflow_path' "$policy")"
  signer_workflow_ref="$(jq -er '.trusted_workflow_ref' "$policy")"
  provenance_workflow_ref=
  jq -e --arg owner "$source_repository" --arg image "$oci_repository" --arg role "$role" \
    --arg public_key_path "$public_key_relative" --arg public_key_sha256 "$public_key_sha256" \
    '.publisher_state == "active" and .owner_repository == $owner and
     .repository_id == "1227819622" and
     ((.image_repository? == $image) or (.subjects?[$role] == $image)) and
     .workflow_path == "pingcap-inc/nexuscrm-pingcap-pack/.github/workflows/publish-serviceification-test-stack.yml" and
     .public_key_path == $public_key_path and .public_key_sha256 == $public_key_sha256 and
     .key_spec == "ECC_NIST_P256" and .key_usage == "SIGN_VERIFY" and
     .signing_algorithm == "ECDSA_SHA_256" and
     (.trusted_workflow_ref | test("^pingcap-inc/nexuscrm-pingcap-pack/\\.github/workflows/trusted-publish-serviceification-test-stack\\.yml@([0-9a-f]{40}|refs/heads/main)$"))' \
    "$policy" >/dev/null || fail "L2 owner policy facts are inconsistent"
else
  workflow_ref="$(jq -er '.workflow_ref' "$policy")"
  signer_workflow_ref="$workflow_ref"
  provenance_workflow_ref="$workflow_ref"
  jq -e --arg owner "$source_repository" --arg image "$oci_repository" --arg role "$role" \
    --arg public_key_path "$public_key_relative" --arg public_key_sha256 "$public_key_sha256" \
    '.publisher_state == "active" and .owner_repository == $owner and
     ((.image_repository? == $image) or (.subjects?[$role] == $image)) and
     .source_ref == "refs/heads/main" and .public_key_path == $public_key_path and
     .public_key_sha256 == $public_key_sha256 and .key_spec == "ECC_NIST_P256" and
     .key_usage == "SIGN_VERIFY" and .signing_algorithm == "ECDSA_SHA_256" and
     (.workflow_ref | type == "string" and endswith("@refs/heads/main"))' "$policy" >/dev/null \
    || fail "owner policy facts are inconsistent"
fi

if [[ -n "$exact_digest" ]]; then
  [[ "$source_repository" == pingcap-inc/nexuscrm-pingcap-pack || "$role" == l0_engine || "$role" == mcp_worker ]] \
    || fail "only L0 Engine, MCP and L2 subjects use an explicit digest"
  digest="$exact_digest"
else
  selected_tag="$source_commit"
  if [[ "$role" == l0_engine ]]; then
    selected_tag="$release_version"
  fi
  manifest="$(docker buildx imagetools inspect "$oci_repository:$selected_tag" --format '{{json .Manifest}}')"
  digest="$(jq -er '.digest' <<<"$manifest")"
fi
[[ "$digest" =~ ^sha256:[0-9a-f]{64}$ ]] || fail "subject digest is not canonical"

docker pull --quiet "$oci_repository@$digest" >/dev/null
revision="$(docker image inspect --format '{{ index .Config.Labels "org.opencontainers.image.revision" }}' "$oci_repository@$digest")"
[[ "$revision" == "$source_commit" ]] || fail "OCI revision disagrees with source commit"

signing_policy_evidence="$(mktemp)"
signing_context="$(mktemp)"
signing_authority_commit=
signature_evidence="$(mktemp)"
raw_signature_evidence="$(mktemp)"
provenance_evidence="$(mktemp)"
normalized_evidence="$(mktemp)"
normalized_signature="$(mktemp)"
normalized_provenance="$(mktemp)"
index_json="$(mktemp)"
attestation_json="$(mktemp)"
sbom_blob="$(mktemp)"
sbom_verification="$(mktemp)"
registry_basic_header="$(mktemp)"
registry_token_response="$(mktemp)"
registry_curl_config="$(mktemp)"
embedded_artifact="$(mktemp)"
artifact_binding_evidence="$(mktemp)"
artifact_container=
cleanup() {
  if [[ -n "$artifact_container" ]]; then
    docker rm -f "$artifact_container" >/dev/null 2>&1 || true
  fi
  rm -f "$signing_policy_evidence" "$signing_context" "$signature_evidence" "$raw_signature_evidence" "$provenance_evidence" "$normalized_evidence" \
    "$normalized_signature" "$normalized_provenance" "$index_json" \
    "$attestation_json" "$sbom_blob" "$sbom_verification" "$registry_basic_header" \
    "$registry_token_response" "$registry_curl_config" "$embedded_artifact" \
    "$artifact_binding_evidence"
}
trap cleanup EXIT
chmod 600 "$registry_basic_header" "$registry_token_response" "$registry_curl_config"

case "$schema" in
  nexuscrm.mcp-worker-keyless-signing-policy/v1)
    trusted_workflow_ref="$workflow_ref"
    cosign verify --new-bundle-format=false \
      --certificate-identity "https://github.com/$workflow_ref" \
      --certificate-oidc-issuer https://token.actions.githubusercontent.com \
      --certificate-github-workflow-sha "$source_commit" \
      -a "io.nexuscrm.source.repository=$source_repository" \
      -a "io.nexuscrm.source.commit=$source_commit" \
      -a 'io.nexuscrm.source.ref=refs/heads/main' \
      -a "io.nexuscrm.signer.policy-sha256=$policy_sha256" \
      "$oci_repository@$digest" > "$signature_evidence"
    ;;
  nexuscrm.l0-engine-image-signing-policy/v1)
    trusted_workflow_ref="$signer_workflow_ref"
    cosign verify --key "$public_key" --new-bundle-format=false --insecure-ignore-tlog \
      -a "io.nexuscrm.release.version=$release_version" \
      -a "io.nexuscrm.source.repository=$source_repository" \
      -a "io.nexuscrm.source.commit=$source_commit" \
      -a 'io.nexuscrm.source.ref=refs/heads/main' \
      -a "io.nexuscrm.signer.workflow=$signer_workflow_ref" \
      -a "io.nexuscrm.signer.policy-sha256=$policy_sha256" \
      "$oci_repository@$digest" > "$signature_evidence"
    ;;
  nexuscrm.l0-engine-image-signing-policy/v2)
    trusted_workflow_ref="$signer_workflow_ref"
    cosign verify --key "$public_key" --new-bundle-format=false --insecure-ignore-tlog \
      -a "io.nexuscrm.release.version=$release_version" \
      -a "io.nexuscrm.source.repository=$source_repository" \
      -a "io.nexuscrm.source.commit=$source_commit" \
      -a "io.nexuscrm.signer.workflow=$signer_workflow_ref" \
      -a "io.nexuscrm.signer.policy-sha256=$policy_sha256" \
      "$oci_repository@$digest" > "$signature_evidence"
    source_ref="$(jq -er \
      '[.[].optional["io.nexuscrm.source.ref"]] | unique | select(length == 1) | .[0] |
       select(test("^refs/heads/[^[:space:]]+$"))' "$signature_evidence")" \
      || fail "L0 Engine signature does not bind exactly one branch ref"
    git check-ref-format "$source_ref" \
      || fail "L0 Engine signature contains an invalid branch ref"
    if [[ "$source_ref" == refs/heads/main ]]; then
      provenance_workflow_ref=pingcap-inc/NexusCRM/.github/workflows/go-ci.yml@refs/heads/main
    else
      provenance_workflow_ref=pingcap-inc/NexusCRM/.github/workflows/publish-l0-engine-dev-release.yml@refs/heads/main
    fi
    ;;
  nexuscrm.oci-owner-signing-policy/v1)
    trusted_workflow_ref="$(jq -er '.trusted_workflow_ref' "$policy")"
    [[ "$trusted_workflow_ref" =~ ^[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+/\.github/workflows/[A-Za-z0-9._-]+@[0-9a-f]{40}$ ]] \
      || fail "owner builder is not immutable"
    cosign verify --key "$public_key" --new-bundle-format=false --insecure-ignore-tlog \
      -a "io.nexuscrm.source.repository=$source_repository" \
      -a "io.nexuscrm.source.commit=$source_commit" \
      -a 'io.nexuscrm.source.ref=refs/heads/main' \
      -a "io.nexuscrm.signer.workflow=$workflow_ref" \
      -a "io.nexuscrm.signer.policy-sha256=$policy_sha256" \
      "$oci_repository@$digest" > "$signature_evidence"
    ;;
  nexuscrm.oci-owner-signing-policy/v4)
    [[ "$source_repository" == pingcap-inc/nexuscrm-api-host ]] || fail "v4 policy is only supported for Gateway"
    : "${GATEWAY_RELEASE_VERIFIER:?Gateway offline verifier is required}"
    [[ -x "$GATEWAY_RELEASE_VERIFIER" ]] || fail "Gateway offline verifier is not executable"
    kms_key_arn="$(jq -er '.kms_key_arn' "$policy")"
    cosign verify --key "$public_key" --new-bundle-format=false --insecure-ignore-tlog \
      -a "io.nexuscrm.source.repository=$source_repository" \
      -a "io.nexuscrm.source.commit=$source_commit" \
      -a 'io.nexuscrm.source.ref=refs/heads/main' \
      -a "io.nexuscrm.signer.workflow=$workflow_ref" \
      -a "io.nexuscrm.signer.key-arn=$kms_key_arn" \
      -a "io.nexuscrm.signer.policy-sha256=$policy_sha256" \
      "$oci_repository@$digest" > "$raw_signature_evidence"
    trusted_workflow_ref="$(jq -er '.provenance_builder_id | sub("^https://github.com/"; "")' "$policy")"
    ;;
  nexuscrm.l2-oci-owner-signing-policy/v1)
    [[ "$source_repository" == pingcap-inc/nexuscrm-pingcap-pack ]] || fail "L2 policy has the wrong owner"
    trusted_workflow_ref="$(jq -er '.trusted_workflow_ref' "$policy")"
    [[ "$trusted_workflow_ref" =~ ^pingcap-inc/nexuscrm-pingcap-pack/\.github/workflows/[A-Za-z0-9._-]+@[0-9a-f]{40}$ ]] \
      || fail "L2 builder is not immutable"
    cosign verify --key "$public_key" --new-bundle-format=false --insecure-ignore-tlog \
      -a "io.nexuscrm.source.repository=$source_repository" \
      -a "io.nexuscrm.source.commit=$source_commit" \
      -a 'io.nexuscrm.source.ref=refs/heads/main' \
      -a "io.nexuscrm.signer.workflow=$workflow_ref" \
      -a "io.nexuscrm.signer.policy-sha256=$policy_sha256" \
      -a "io.nexuscrm.subject.role=$role" \
      -a "io.nexuscrm.subject.binding-sha256=$binding" \
      "$oci_repository@$digest" > "$signature_evidence"
    ;;
  nexuscrm.l2-oci-owner-signing-policy/v2|nexuscrm.l2-oci-owner-signing-policy/v3)
    [[ "$source_repository" == pingcap-inc/nexuscrm-pingcap-pack ]] || fail "L2 policy has the wrong owner"
    # Authenticate the subject first. Its signature owns the signing policy;
    # the producer checkout owns only the artifact source and legacy evidence.
    cosign verify --key "$public_key" --new-bundle-format=false --insecure-ignore-tlog \
      -a "io.nexuscrm.source.repository=$source_repository" \
      -a "io.nexuscrm.source.commit=$source_commit" \
      -a "io.nexuscrm.subject.role=$role" \
      -a "io.nexuscrm.subject.binding-sha256=$binding" \
      "$oci_repository@$digest" > "$raw_signature_evidence"
    python3 "$publisher_root/scripts/verified_l2_signing_policy.py" \
      --signatures "$raw_signature_evidence" --legacy-policy "$policy" \
      --policy-output "$signing_policy_evidence" --signature-output "$signature_evidence" \
      --context-output "$signing_context"
    policy_sha256="$(jq -er .policy_sha256 "$signing_context")"
    source_ref="$(jq -er .source_ref "$signing_context")"
    git check-ref-format "$source_ref" || fail "L2 signature contains an invalid branch ref"
    provenance_workflow_ref="$(jq -er .workflow_ref "$signing_context")"
    trusted_workflow_ref="$(jq -er .builder_ref "$signing_context")"
    signing_authority_commit="$(jq -r .authority_commit "$signing_context")"
    ;;
  *) fail "unsupported owner signing policy schema $schema" ;;
esac

if [[ "$keyless" == true ]]; then
  cosign verify-attestation --new-bundle-format=false \
    --certificate-identity "https://github.com/$workflow_ref" \
    --certificate-oidc-issuer https://token.actions.githubusercontent.com \
    --certificate-github-workflow-sha "$source_commit" \
    --type slsaprovenance1 "$oci_repository@$digest" > "$provenance_evidence"
else
  cosign verify-attestation --key "$public_key" --new-bundle-format=false --insecure-ignore-tlog \
    --type slsaprovenance1 "$oci_repository@$digest" > "$provenance_evidence"
fi
builder="https://github.com/$trusted_workflow_ref"
digest_hex="${digest#sha256:}"
matching_payload="$({
  jq -r '.payload' "$provenance_evidence" | while IFS= read -r payload; do
    decoded="$(printf '%s' "$payload" | base64 --decode)"
    if jq -e --arg image "$oci_repository" --arg digest "$digest_hex" \
      --arg repository "$source_repository" --arg ref "$source_ref" --arg commit "$source_commit" \
      --arg workflow "$provenance_workflow_ref" --arg builder "$builder" \
      --arg authority "$signing_authority_commit" --arg policy "$policy_sha256" \
      '.predicateType == "https://slsa.dev/provenance/v1" and
       (.subject | length) == 1 and .subject[0].name == $image and .subject[0].digest.sha256 == $digest and
       .predicate.buildDefinition.externalParameters.source == {repository:$repository,ref:$ref,commit:$commit} and
       .predicate.buildDefinition.externalParameters.workflow == $workflow and
       .predicate.runDetails.builder.id == $builder and
       ($authority == "" or .predicate.buildDefinition.internalParameters.signingAuthority ==
         {commit:$authority,policySha256:$policy})' <<<"$decoded" >/dev/null; then
      printf '%s\n' "$payload"
    fi
  done
} | sort -u)"
[[ -n "$matching_payload" && "$matching_payload" != *$'\n'* ]] || fail "exactly one canonical provenance statement is required"
provenance_digest="sha256:$(printf '%s' "$matching_payload" | base64 --decode | sha256sum | awk '{print $1}')"

docker buildx imagetools inspect "$oci_repository@$digest" --raw > "$index_json"
platform_digest="$(jq -er '
  [.manifests[] | select(
    .mediaType == "application/vnd.oci.image.manifest.v1+json" and
    .platform.os == "linux" and .platform.architecture == "amd64" and
    .annotations["vnd.docker.reference.type"] != "attestation-manifest"
  )] | if length == 1 then .[0].digest else error("expected exactly one linux/amd64 manifest") end
' "$index_json")"
attestation_digest="$(jq -er --arg platform "$platform_digest" '
  [.manifests[] | select(
    .mediaType == "application/vnd.oci.image.manifest.v1+json" and
    .platform.os == "unknown" and .platform.architecture == "unknown" and
    .annotations["vnd.docker.reference.type"] == "attestation-manifest" and
    .annotations["vnd.docker.reference.digest"] == $platform
  )] | if length == 1 then .[0].digest else error("expected exactly one linked attestation manifest") end
' "$index_json")"
[[ "$attestation_digest" =~ ^sha256:[0-9a-f]{64}$ ]] || fail "attestation digest is not canonical"
docker buildx imagetools inspect "$oci_repository@$attestation_digest" --raw > "$attestation_json"
read -r sbom_digest sbom_size < <(jq -er '
  [.layers[] | select(
    .mediaType == "application/vnd.in-toto+json" and
    .annotations["in-toto.io/predicate-type"] == "https://spdx.dev/Document"
  )] | if length == 1 then [.[0].digest, (.[0].size | tostring)] | @tsv
      else error("expected exactly one SPDX in-toto layer") end
' "$attestation_json")
[[ "$sbom_digest" =~ ^sha256:[0-9a-f]{64}$ ]] || fail "SBOM digest is not canonical"
[[ "$sbom_size" =~ ^[1-9][0-9]*$ ]] || fail "SBOM size is not positive"
# This is a verifier resource-safety bound, not a Runtime or product limit.
(( sbom_size <= 134217728 )) || fail "SBOM exceeds the 128 MiB verifier safety bound"

docker_auth="$(jq -er '.auths["ghcr.io"].auth' "${DOCKER_CONFIG:-$HOME/.docker}/config.json")"
[[ "$docker_auth" =~ ^[A-Za-z0-9+/]+={0,2}$ ]] || fail "GHCR Docker credentials are malformed"
printf 'Authorization: Basic %s\n' "$docker_auth" > "$registry_basic_header"
unset docker_auth
registry_path="${oci_repository#ghcr.io/}"
curl --fail --silent --show-error --header @"$registry_basic_header" --get \
  --data-urlencode "scope=repository:$registry_path:pull" \
  --data-urlencode 'service=ghcr.io' \
  'https://ghcr.io/token' > "$registry_token_response"
registry_token="$(jq -er '.token' "$registry_token_response")"
[[ "$registry_token" =~ ^[A-Za-z0-9._~-]+={0,2}$ ]] || fail "GHCR returned an unsafe bearer token"
printf 'oauth2-bearer = "%s"\n' "$registry_token" > "$registry_curl_config"
unset registry_token
curl --fail --silent --show-error --location --max-filesize 134217728 \
  --proto '=https' --proto-redir '=https' --max-redirs 3 \
  --config "$registry_curl_config" \
  "https://ghcr.io/v2/$registry_path/blobs/$sbom_digest" --output "$sbom_blob"

python3 "$publisher_root/scripts/verify_buildkit_sbom.py" \
  --index "$index_json" --subject-digest "$digest" \
  --attestation-manifest "$attestation_json" --sbom "$sbom_blob" \
  --output "$sbom_verification"
[[ "$(jq -er '.platform_manifest_digest' "$sbom_verification")" == "$platform_digest" ]] \
  || fail "SBOM verifier disagrees with the platform manifest"
[[ "$(jq -er '.attestation_manifest_digest' "$sbom_verification")" == "$attestation_digest" ]] \
  || fail "SBOM verifier disagrees with the attestation manifest"
[[ "$(jq -er '.sbom_blob_digest' "$sbom_verification")" == "$sbom_digest" ]] \
  || fail "SBOM verifier disagrees with the SBOM blob"
sbom_verification_sha256="sha256:$(sha256sum "$sbom_verification" | awk '{print $1}')"

artifact_binding_evidence_sha256=
engine_release_sha256=
if [[ "$source_repository:$role" == pingcap-inc/NexusCRM:l0_engine ]]; then
  artifact_container="$(docker create "$oci_repository@$digest" /__nexuscrm_artifact_inspection__)"
  docker cp "$artifact_container:/release.json" "$embedded_artifact"
  docker rm "$artifact_container" >/dev/null
  artifact_container=
  PYTHONPATH="$publisher_root/scripts" python3 - "$embedded_artifact" "$source_commit" "$release_version" <<'PY'
import json
import sys
from pathlib import Path

from validate_serviceification_bom import validate_l0_engine_release

path = Path(sys.argv[1])
release = json.loads(path.read_text())
errors = validate_l0_engine_release(release, "release")
if release.get("source", {}).get("commit") != sys.argv[2]:
    errors.append("release.source.commit disagrees with selected Engine source commit")
if release.get("version") != sys.argv[3]:
    errors.append("release.version disagrees with selected Engine release version")
if errors:
    raise SystemExit("; ".join(errors))
path.write_text(json.dumps(release, sort_keys=True, separators=(",", ":")) + "\n")
PY
  engine_release_sha256="sha256:$(sha256sum "$embedded_artifact" | awk '{print $1}')"
fi
if [[ "$source_repository" == pingcap-inc/nexuscrm-pingcap-pack ]]; then
  case "$role" in
    frontend)
      binding_label=io.nexuscrm.frontend.source-tuple-sha256
      embedded_path=/usr/share/nexuscrm/release/source-tuple.json
      ;;
    resolved_bom)
      binding_label=io.nexuscrm.serviceification.desired-bom-sha256
      embedded_path=/nexuscrm/release/resolved-bom.json
      ;;
    *) fail "L2 artifact verification requires a known role" ;;
  esac
  embedded_label="$(docker image inspect --format "{{ index .Config.Labels \"$binding_label\" }}" "$oci_repository@$digest")"
  artifact_container="$(docker create "$oci_repository@$digest" /__nexuscrm_artifact_inspection__)"
  docker cp "$artifact_container:$embedded_path" "$embedded_artifact"
  docker rm "$artifact_container" >/dev/null
  artifact_container=
  python3 "$publisher_root/scripts/verify_serviceification_l2_artifact.py" \
    --role "$role" --binding "$binding" --label "$embedded_label" \
    --artifact "$embedded_artifact" --output "$artifact_binding_evidence"
  artifact_binding_evidence_sha256="sha256:$(sha256sum "$artifact_binding_evidence" | awk '{print $1}')"
fi

if [[ "$schema" == nexuscrm.oci-owner-signing-policy/v4 ]]; then
  # Registry access belongs to the reviewed L2 fetcher. Revoke it before any
  # owner-controlled executable receives the already-fetched evidence.
  docker logout ghcr.io >/dev/null
  docker_config_path="${DOCKER_CONFIG:?DOCKER_CONFIG must isolate registry credentials}/config.json"
  if [[ -f "$docker_config_path" ]]; then
    jq -e '(.auths["ghcr.io"] // null) == null' "$docker_config_path" >/dev/null \
      || fail "GHCR credential survived logout"
  fi
  rm -f "$registry_basic_header" "$registry_token_response" "$registry_curl_config"
  "$GATEWAY_RELEASE_VERIFIER" \
    --policy "$policy" --source-commit "$source_commit" --image-digest "$digest" \
    --cosign-evidence "$raw_signature_evidence" --provenance-evidence "$provenance_evidence" \
    > "$signature_evidence"
fi

jq -cS . "$signature_evidence" > "$normalized_signature"
jq -s -cS 'sort_by(.payload)' "$provenance_evidence" > "$normalized_provenance"
signature_evidence_sha256="sha256:$(sha256sum "$normalized_signature" | awk '{print $1}')"
provenance_evidence_sha256="sha256:$(sha256sum "$normalized_provenance" | awk '{print $1}')"

jq -cnS --arg repository "$source_repository" --arg commit "$source_commit" \
  --arg image "$oci_repository" --arg digest "$digest" --arg policy "$policy_sha256" \
  --arg key "$public_key_sha256" --arg provenance "$provenance_digest" --arg sbom "$sbom_digest" \
  --argjson keyless "$keyless" --arg signer "$signer_workflow_ref" \
  --arg sbom_verification "$sbom_verification_sha256" \
  --arg signature_evidence "$signature_evidence_sha256" --arg provenance_evidence "$provenance_evidence_sha256" \
  --arg role "$role" --arg binding "$binding" --arg artifact_binding "$artifact_binding_evidence_sha256" \
  --arg engine_release "$engine_release_sha256" \
  --argjson l2_subject "$( [[ "$source_repository" == pingcap-inc/nexuscrm-pingcap-pack ]] && printf true || printf false )" \
  --argjson engine_subject "$( [[ "$source_repository:$role" == pingcap-inc/NexusCRM:l0_engine ]] && printf true || printf false )" \
  '{schema_version:"nexuscrm.oci-verification-evidence/v1",source_repository:$repository,
    source_commit:$commit,oci_repository:$image,digest:$digest,policy_sha256:$policy,
    public_key_sha256:$key,provenance_digest:$provenance,sbom_digest:$sbom,
    buildkit_sbom_verification_sha256:$sbom_verification,
    signature_evidence_sha256:$signature_evidence,provenance_evidence_sha256:$provenance_evidence,
    subject_role:$role,subject_binding_sha256:$binding}
   | (if $keyless then del(.public_key_sha256) + {certificate_identity:("https://github.com/"+$signer),oidc_issuer:"https://token.actions.githubusercontent.com"} else . end)
   + (if $l2_subject then {artifact_binding_evidence_sha256:$artifact_binding} else {} end)
   + (if $engine_subject then {engine_release_sha256:$engine_release} else {} end)' > "$normalized_evidence"
verification_receipt_digest="sha256:$(sha256sum "$normalized_evidence" | awk '{print $1}')"

mkdir -p "$(dirname "$output")"
mkdir -p "$(dirname "$evidence_output")"
cp "$normalized_evidence" "$evidence_output"
jq -cnS --slurpfile release "$embedded_artifact" \
  --arg image "$oci_repository" --arg digest "$digest" \
  --arg repository "$source_repository" --arg commit "$source_commit" \
  --arg verification "$verification_receipt_digest" --arg provenance "$provenance_digest" \
  --arg sbom "$sbom_digest" --arg role "$role" --arg binding "$binding" \
  '{oci_repository:$image,digest:$digest,source_repository:$repository,source_commit:$commit,
    verification_receipt_digest:$verification,provenance_digest:$provenance,sbom_digest:$sbom}
   + (if $role == "frontend" then {source_tuple_sha256:$binding} else {} end)
   + (if $role == "l0_engine" then {release:$release[0]} else {} end)' > "$output"
