#!/usr/bin/env bash
# Prints a client_assertion (JWT RS256) for OAuth2 private_key_jwt, using only openssl.
# The assertion is valid for 60 seconds and only once (unique jti).
#
#   ./generate-client-assertion.sh <client_id> <token_url> <private_key.pem>
#
# The client id and the token URL are the ones shown in the eFurnizori portal.
set -euo pipefail

if [ "$#" -ne 3 ]; then
  echo "Usage: $0 <client_id> <token_url> <private_key.pem>" >&2
  exit 2
fi

CLIENT_ID="$1"
TOKEN_URL="$2"
KEY="$3"

b64url() { openssl base64 -e -A | tr '+/' '-_' | tr -d '='; }
hex_b64url() { local hex="$1"; [ $(( ${#hex} % 2 )) -eq 1 ] && hex="0$hex"; printf '%s' "$hex" | xxd -r -p | b64url; }

# The kid is the RFC 7638 thumbprint of the public key, as shown in the eFurnizori portal.
MODULUS_HEX=$(openssl rsa -in "$KEY" -noout -modulus 2>/dev/null | cut -d= -f2)
EXPONENT_HEX=$(openssl rsa -in "$KEY" -noout -text 2>/dev/null | sed -n 's/^publicExponent: [0-9]* (0x\([0-9a-fA-F]*\))$/\1/p')
JWK=$(printf '{"e":"%s","kty":"RSA","n":"%s"}' "$(hex_b64url "$EXPONENT_HEX")" "$(hex_b64url "$MODULUS_HEX")")
KID=$(printf '%s' "$JWK" | openssl dgst -sha256 -binary | b64url)

NOW=$(date +%s)
JTI=$(openssl rand -hex 16)
HEADER=$(printf '{"alg":"RS256","typ":"JWT","kid":"%s"}' "$KID")
PAYLOAD=$(printf '{"iss":"%s","sub":"%s","aud":"%s","jti":"%s","iat":%d,"exp":%d}' \
  "$CLIENT_ID" "$CLIENT_ID" "$TOKEN_URL" "$JTI" "$NOW" "$((NOW + 60))")

SIGNING_INPUT="$(printf '%s' "$HEADER" | b64url).$(printf '%s' "$PAYLOAD" | b64url)"
SIGNATURE=$(printf '%s' "$SIGNING_INPUT" | openssl dgst -sha256 -sign "$KEY" -binary | b64url)

echo "${SIGNING_INPUT}.${SIGNATURE}"
