#!/bin/sh
# git's credential helper in a Claude Managed Agents sandbox on AgentCore. git runs it as
# `git-credential-cma get` whenever it needs a password, and it answers with a short-lived token.
#
# It answers with the token it last fetched, which it keeps in ~/.cma-git-tokens/cache/<host> as
# the token lambda's answer, while that is more than five minutes from its expires_at. Otherwise
# it invokes the token lambda as the runtime's execution role. Nothing is fetched before git asks,
# because AgentCore restores every session from one snapshot of the started container. When the
# host refuses a token, git runs `git-credential-cma erase`, which drops the cached one.
#
# The base image has no AWS CLI and no jq, and the image's build runs nothing. So the Invoke
# call is signed with curl --aws-sigv4, and JSON fields are read with sed.
set -u

tokens=$HOME/.cma-git-tokens
fresh_for_s=300
metadata=${CMA_METADATA_URL:-http://169.254.169.254/latest}

main() {
    host=$(asked_host)
    case $host in
        '' | *[!A-Za-z0-9.:-]*) fail "git named no host this helper can use" ;;
    esac
    # git also runs a helper with `store`, which has nothing to do here.
    case ${1:-} in
        get) give_a_token "$host" ;;
        erase) rm -f "$tokens/cache/$host" ;;
    esac
}

give_a_token() {
    if fresh "$tokens/cache/$1"; then
        answer_git "$(cat "$tokens/cache/$1")"
        return
    fi
    answer=$(token_from_lambda "$1") || exit 1
    keep "$answer" "$tokens/cache/$1"
    answer_git "$answer"
}

asked_host() {
    while IFS='=' read -r key value; do
        [ "$key" = host ] && printf '%s' "$value"
    done
}

fresh() {
    [ -r "$1" ] || return 1
    expires_at=$(field expires_at "$(cat "$1")")
    [ -n "$expires_at" ] || return 1
    expires_s=$(date -u -d "$expires_at" +%s 2>/dev/null) || return 1
    [ "$expires_s" -gt $(($(date -u +%s) + fresh_for_s)) ]
}

answer_git() {
    printf 'username=%s\npassword=%s\n' "$(field username "$1")" "$(field password "$1")"
}

token_from_lambda() {
    arn=${CMA_TOKEN_LAMBDA_ARN:-}
    [ -n "$arn" ] || fail "CMA_TOKEN_LAMBDA_ARN is not set"
    region=$(printf '%s' "$arn" | cut -d: -f4)
    lambda=${CMA_LAMBDA_URL:-https://lambda.$region.amazonaws.com}

    session=$(curl -fsS -m 5 -X PUT -H "X-aws-ec2-metadata-token-ttl-seconds: 60" "$metadata/api/token") ||
        fail "the metadata service gave no token"
    role=$(curl -fsS -m 5 -H "X-aws-ec2-metadata-token: $session" "$metadata/meta-data/iam/security-credentials/") ||
        fail "the metadata service has no role"
    credentials=$(curl -fsS -m 5 -H "X-aws-ec2-metadata-token: $session" "$metadata/meta-data/iam/security-credentials/$role") ||
        fail "the metadata service gave no credentials for $role"
    key_id=$(field AccessKeyId "$credentials")
    secret_key=$(field SecretAccessKey "$credentials")
    session_token=$(field Token "$credentials")
    [ -n "$key_id" ] && [ -n "$secret_key" ] && [ -n "$session_token" ] ||
        fail "the metadata service's answer for $role is missing a key"

    # The keys go on curl's stdin, not its command line, where ps would show them.
    answer=$(
        printf 'user = "%s:%s"\nheader = "x-amz-security-token: %s"\n' "$key_id" "$secret_key" "$session_token" |
            curl -sS -m 20 -K - --aws-sigv4 "aws:amz:$region:lambda" \
                -H "Content-Type: application/json" \
                --data "{\"host\":\"$1\"}" \
                "$lambda/2015-03-31/functions/${arn##*:}/invocations"
    ) || fail "could not reach Lambda in $region"
    # Lambda reports its own refusal as Message, and an error the function threw as errorMessage.
    [ -n "$(field password "$answer")" ] ||
        fail "the token lambda gave no token: $(field Message "$answer")$(field errorMessage "$answer")"
    printf '%s' "$answer"
}

# A git command that runs beside this one reads either the old file or the new one, never half of one.
keep() {
    (
        umask 077
        mkdir -p "${2%/*}" && printf '%s' "$1" >"$2.$$" && mv "$2.$$" "$2"
    ) || echo "git-credential-cma: could not keep the token in $2" >&2
}

field() {
    printf '%s' "$2" | sed -n "s/.*\"$1\" *: *\"\([^\"]*\)\".*/\1/p"
}

# Nothing goes to standard output, so git reports an authentication failure the agent can relay.
fail() {
    echo "git-credential-cma: $1" >&2
    exit 1
}

main "$@"
