#!/bin/sh
# This file is part of caucase
# Copyright (C) 2017-2020  Nexedi SA
#     Vincent Pelletier <vincent@nexedi.com>
#
# This program is free software: you can Use, Study, Modify and Redistribute
# it under the terms of the GNU General Public License version 3, or (at your
# option) any later version, as published by the Free Software Foundation.
#
# You can also Link and Combine this program with other software covered by
# the terms of any of the Free Software licenses or any of the Open Source
# Initiative approved licenses and Convey the resulting work. Corresponding
# source of such a combination shall include the source code for all other
# software used.
#
# This program is distributed WITHOUT ANY WARRANTY; without even the implied
# warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
#
# See COPYING file for full licensing terms.
# See https://www.nexedi.com/licensing for rationale and options.
set -u

str2json () {
  # Convert some text into a json string.
  # Usage: < str

  # Note: using $() to strip the trailing newline added by jq.
  printf '%s' "$(jq --raw-input --slurp .)"
}

pairs2obj () {
  # Convert pairs of arguments into keys & values of a json objet.
  # Usage: <key0> <value0> [...]
  # Outputs: {"key0":value0}
  # No sanity checks on keys nor values.
  # Keys are expected unquoted, as they must be strings anyway.
  # Values are expected in json.
  # If arg count is odd, last argument is ignored.
  # shellcheck disable=SC2039
  local first=1
  printf '{'
  while [ $# -ge 2 ]; do
    if [ $first -eq 1 ]; then
      first=0
    else
      printf ','
    fi
    printf '"%s":%s' "$1" "$2"
    shift 2
  done
  printf '}'
}

forEachJSONListItem () {
  # Usage: <command> [<arg> ...] < json
  # <command> is receives each item in json as input.
  # If <command> exit status is non-zero, enumeration stops.
  # shellcheck disable=SC2039
  local list index
  list="$(cat)"
  for index in $(seq 0 $(($(printf '%s\n' "$list" | jq length) - 1))); do
    printf '%s\n' "$list" | jq ".[$index]" | "$@" || return
  done
}

wrap () {
  # Wrap payload in a format suitable for caucase and sign it
  # Usage: <key file> <digest> < payload > wrapped
  # shellcheck disable=SC2039
  local digest="$2" payload
  payload="$(cat)"
  # Note: $() looses trailing newlines, so payload should not need to end with
  # any newline.
  pairs2obj \
    'digest' "$(printf '%s' "$digest" | str2json)" \
    'payload' "$(printf '%s' "$payload" | str2json)" \
    'signature' "$(
      printf '%s%s ' "$payload" "$digest" \
      | openssl dgst \
        -"$digest" \
        -binary \
        -sign "$1" \
        -sigopt rsa_padding_mode:pss \
        -sigopt rsa_pss_saltlen:-2 \
        -sigopt digest:"$digest" \
      | base64 -w 0 \
      | str2json
    )"
}

nullWrap () {
  # Wrap payload in a format suitable for caucase without signing it
  # Usage: < payload > wrapped
  pairs2obj digest null payload "$(str2json)"
}

unwrap () {
  # Usage: <command> [...] < wrapped > payload
  # <command> must output the x509 certificate to use to verify the signature.
  # It receives the payload being unwrapped.
  # shellcheck disable=SC2039
  local wrapped status json_digest digest signature_file payload pubkey_file
  wrapped="$(cat)"

  json_digest="$(printf '%s\n' "$wrapped" | jq .digest)"
  if [ "$json_digest" = 'null' ]; then
    return 1
  fi
  digest="$(
    printf '%s\n' "$json_digest" | jq --raw-output ascii_downcase
  )"
  case "$digest" in
    sha256|sha384|sha512)
    ;;
    *)
      # Note: printing json-encoded digest so it is safe to print
      # (especially, ESC is encoded as \u001b, avoiding shell escape code
      # injections).
      echo "Unhandled digest: $json_digest" >&2
      return 1
    ;;
  esac
  signature_file="$(mktemp --suffix=unwrap.sig)"
  printf '%s\n' "$wrapped" | jq --raw-output .signature | \
    base64 -d > "$signature_file"
  payload="$(printf '%s\n' "$wrapped" | jq --raw-output .payload)"
  pubkey_file="$(mktemp --suffix=unwrap.pub)"
  if printf '%s\n' "$payload" "$@" | openssl x509 -pubkey -noout > "$pubkey_file"; then
    printf '%s%s ' "$payload" "$digest" \
    | openssl dgst \
      -"$digest" \
      -verify "$pubkey_file" \
      -sigopt rsa_padding_mode:pss \
      -sigopt rsa_pss_saltlen:-2 \
      -sigopt digest:"$digest" \
      -signature "$signature_file" > /dev/null
    status=$?
  else
    status=2
  fi
  rm "$signature_file" "$pubkey_file"
  test $status -eq 0 && printf '%s' "$payload"
  return $status
}

nullUnwrap () {
  # Usage: < wrapped > payload
  # shellcheck disable=SC2039
  local wrapped
  wrapped="$(cat)"
  if [ "$(printf '%s\n' "$wrapped" | jq '.digest')" != 'null' ]; then
    return 1
  fi
  printf '%s\n' "$wrapped" | jq .payload
}

writeCertKey () {
  # Write given certificate and key to file(s).
  # Usage: <crt data> <crt path> <key data> <key path>
  # shellcheck disable=SC2039
  local crt_path="$1" crt_data="$2" key_path="$3" key_data="$4" need_chmod
  test ! -e "$key_path"
  need_chmod=$?
  # Empty both files first, as they may be the same.
  : > "$crt_path"
  : > "$key_path"
  test $need_chmod -eq 0 && chmod go= "$key_path"
  printf '%s\n' "$key_data" >> "$key_path"
  printf '%s\n' "$crt_data" >> "$crt_path"
}

_curlInsecure () {
  # Because caucased https certificate does not need to be trusted.
  # Usage: ...
  curl --silent --insecure "$@"
}

_putInsecure () {
  # To PUT stdin via https.
  # Usage: ... < input
  _curlInsecure --upload-file - "$@"
}

_putInsecureNoOut () {
  # For when _putInsecure does not provide a response body, so the only way to
  # check for issues is checking HTTP status.
  # Usage: ... < input
  # shellcheck disable=SC2039
  local result
  if result="$(
    _putInsecure \
      --write-out '\n%{http_code}\n' \
      "$@"
  )"; then
    :
  else
    return 3
  fi
  case "$(printf '%s\n' "$result" | tail -n 1)" in
    2?? )
      return 0
    ;;
    401 )
      printf 'Unauthorized\n' >&2
      return 2
    ;;
    409 )
      printf 'Found\n' >&2
      return 4
    ;;
    * )
      printf '%s\n' "$result" | head -n -1 >&2
      return 1
    ;;
  esac
}

_matchCertificateBoundary () {
  test "$1" = '-----END CERTIFICATE-----'
}

_matchPrivateKeyBoundary () {
  case "$1" in
    '-----END PRIVATE KEY-----' | '-----END RSA PRIVATE KEY-----')
      return 0
    ;;
  esac
  return 1
}

_forEachPEM () {
  # Iterate over components of a PEM file, piping each to <command>
  # Usage: <type tester> <command> [<arg> ...] < pem
  # <type tester> is called with the end boundary as argument
  # <command> receives each matching PEM element as input.
  # If <command> exit status is non-zero, enumeration stops.
  # shellcheck disable=SC2039
  local tester="$1" current=''
  shift
  while IFS= read -r line; do
    if [ -z "$current" ]; then
      current="$line"
    else
      current="$(printf '%s\n%s' "$current" "$line")"
    fi
    case "$line" in
      '-----END '*'-----')
        if "$tester" "$line"; then
          printf '%s\n' "$current" | "$@" || return
        fi
        current=''
        ;;
    esac
  done
}

alias forEachCertificate='_forEachPEM _matchCertificateBoundary'
# Iterate over certificate of a PEM file, piping each to <command>
# Usage: <command> [<arg> ...] < pem

alias forEachPrivateKey='_forEachPEM _matchPrivateKeyBoundary'
# Iterate over private key of a PEM file, piping each to <command>
# Usage: <command> [<arg> ...] < pem

alias pem2fingerprint='openssl x509 -fingerprint -noout'

pemFingerprintIs () {
  # Usage: <fingerprint> < certificate
  # Return 1 when certificate's fingerprint matches argument
  test "$1" = "$(pem2fingerprint)" && return 1
}

expiresBefore () {
  # Tests whether certificate is expired at given date
  # Usage: <date> < certificate > certificate
  # <date> must be a unix timestamp (date +%s)
  # shellcheck disable=SC2039
  local enddate
  enddate="$(openssl x509 -enddate -noout | sed 's/^[^=]*=//')"
  test $? -ne 0 && return 1
  test "$(date --date="$enddate" +%s)" -lt "$1"
}

printIfExpiresAfter () {
  # Print certificate if it expires after given date
  # Usage: <date> < certificate > certificate
  # <date> must be a unix timestamp (date +%s)
  # shellcheck disable=SC2039
  local crt
  crt="$(cat)"
  printf '%s\n' "$crt" | expiresBefore "$1" || printf '%s\n' "$crt"
}

storeCertBySerial () {
  # Store certificate in a file named after its serial, in given directory
  # and using given printf format string.
  # Usage: storeCertBySerial <dir> <patterm> < certificate
  # shellcheck disable=SC2039
  local crt
  crt="$(cat)"
  serial="$(printf "%s\n" "$crt" \
    | openssl x509 -serial -noout | sed 's/^[^=]*=\(.*\)/\L\1/')"
  test $? -ne 0 && return 1
  printf "%s\n" "$crt" > "$(printf "%s/$2" "$1" "$serial")"
}

appendValidCA () {
  # TODO: test
  # Append CA to given file if it is signed by a CA we know of already.
  # Usage: <ca path> < json
  # Appends valid certificates to the file at <ca path>
  # shellcheck disable=SC2039
  local ca="$1" payload cert
  if payload=$(unwrap jq --raw-output .old_pem); then
    :
  else
    printf 'Bad signature, something is very wrong' >&2
    return 1
  fi
  cert="$(printf '%s\n' "$payload" | jq --raw-output .old_pem)"
  forEachCertificate \
    pemFingerprintIs \
    "$(printf '%s\n' "$cert" | pem2fingerprint)" < "$ca"
  if [ $? -eq 1 ]; then
    printf '%s\n' "$cert" >> "$ca"
  fi
}

checkCertificateMatchesKey () {
  # Usage: <crt> <key>
  # Returns 0 if certificate's public key matches private key's public key,
  # 1 otherwise.
  test "$(
    printf '%s\n' "$1" | openssl x509 -modulus -noout | sed 's/^Modulus=//'
  )" = "$(
    echo "$2" | openssl rsa -modulus -noout | sed 's/^Modulus=//'
  )"
}

checkDeps () {
  # shellcheck disable=SC2039
  local missingdeps='' dep
  # Expected builtins & keywords:
  #   alias local if then else elif fi for in do done case esac return [ test
  #   shift set
  for dep in jq openssl printf echo curl sed base64 cat date mktemp; do
    command -v $dep > /dev/null || missingdeps="$missingdeps $dep"
  done
  if [ -n "$missingdeps" ]; then
    echo "Missing dependencies: $missingdeps" >&2
    return 1
  fi
  if [ ! -r /dev/null ] || [ ! -w /dev/null ]; then
    echo 'Cannot read from & write to /dev/null' >&2
    return 1
  fi
}

renewCertificate () {
  # Usage: <url> <old key> <new key len> <new crt> <new key> < old crt
  # <new key> and <new crt> are created.
  # Given paths may be identical in any combination.
  # If "new" path are the same as "old" paths, old content will be overwritten
  # on success.
  # If created, key file permissions will be set so group and other have no
  # access.
  # shellcheck disable=SC2039
  local url="$1" oldkey="$2" bits="$3" newcrt="$4" newkey="$5" emptyreqcnf
  # shellcheck disable=SC2039
  local newkeydata newcrtdata

  emptyreqcnf="$(mktemp --suffix=emptyreq.cnf)"
  cat > "$emptyreqcnf" << EOF
[ req ]
distinguished_name = req_distinguished_name
string_mask = utf8only
req_extensions = v3_req

[ req_distinguished_name ]
CN = Common Name

[ v3_req ]
basicConstraints = CA:FALSE
EOF
  newkeydata="$(
    openssl genpkey \
      -algorithm rsa \
      -pkeyopt "rsa_keygen_bits:$bits" \
      -outform PEM 2> /dev/null
  )"
  if newcrtdata="$(
    pairs2obj \
      'crt_pem' "$(str2json)" \
      'renew_csr_pem' "$(
        echo "$newkeydata" \
        | openssl req \
          -new \
          -key - \
          -subj '/CN=dummy' \
          -config "$emptyreqcnf" \
        | str2json
      )" \
    | wrap "$oldkey" 'sha256' \
    | _putInsecure \
      --header 'Content-Type: application/json' \
      "$url/crt/renew/"
  )"; then
    if [ \
      "x$(printf '%s\n' "$newcrtdata" | head -n 1)" \
      = \
      'x-----BEGIN CERTIFICATE-----' \
    ]; then
      if checkCertificateMatchesKey "$newcrtdata" "$newkeydata"; then
        writeCertKey "$newcrt" "$newcrtdata" "$newkey" "$newkeydata"
        rm "$emptyreqcnf"
        return 0
      fi
      printf 'Certificate does not match private key\n' >&2
    else
      printf '%s' "$newcrtdata" >&2
    fi
  fi
  rm "$emptyreqcnf"
  return 1
}

revokeCertificate () {
  # Usage: <url> <key_path> < crt
  pairs2obj 'revoke_crt_pem' "$(str2json)" \
  | wrap "$2" 'sha256' \
  | _putInsecureNoOut \
    --header 'Content-Type: application/json' \
    --insecure \
    "$1/crt/revoke/"
}

revokeCRTWithoutKey () {
  # Usage: <url> <user crt> < crt
  pairs2obj 'revoke_crt_pem' "$(str2json)" \
  | nullWrap \
  | _putInsecureNoOut \
    --cert "$2" \
    --header 'Content-Type: application/json' \
    "$1/crt/revoke/"
}

revokeSerial () {
  # Usage: <url> <user crt> <serial>
  pairs2obj 'revoke_serial' "$3" \
  | nullWrap \
  | _putInsecureNoOut \
    --cert "$2" \
    --header 'Content-Type: application/json' \
    "$1/crt/revoke/"
}

updateCACertificate () {
  # Usage: <url> <ca>
  # shellcheck disable=SC2039
  local url="$1" \
    ca="$2" \
    future_ca \
    status \
    orig_ca="" \
    ca_is_file \
    ca_file \
    valid_ca
  if [ -e "$ca" ]; then
    if [ -f "$ca" ]; then
      ca_is_file=1
      orig_ca="$(cat "$ca")"
    elif [ -d "$ca" ]; then
      ca_is_file=0
    else
      printf "%s exists and is neither a directory nor a file\n" "$ca"
      return 1
    fi
  else
    case "$ca" in
      *.*)
        ca_is_file=1
        ;;
      *)
        mkdir "$ca"
        ca_is_file=0
        ;;
    esac
  fi
  if [ $ca_is_file -eq 0 ]; then
    for ca_file in "$ca"/*; do
      # double use:
      # - skips non-files
      # - skips the one iteration when there is nothing in "$ca"/
      if [ -f "$ca_file" ] && [ ! -h "$ca_file" ]; then
        orig_ca="$( \
          printf "%s\n%s" "$orig_ca" "$(cat "$ca_file")" \
        )"
      fi
    done
  fi
  if [ -z "$orig_ca" ]; then
    orig_ca="$(_curlInsecure "$url/crt/ca.crt.pem")"
  fi
  status=$?
  test $status -ne 0 && return 1
  valid_ca="$(
    printf '%s\n' "$orig_ca" \
    | forEachCertificate printIfExpiresAfter "$(date +%s)"
  )"
  status=$?
  test $status -ne 0 && return 1
  if [ $ca_is_file -eq 1 ]; then
    printf '%s\n' "$valid_ca" > "$ca"
  else
    for ca_file in "$ca"/*; do
      test -f "$ca_file" && rm "$ca_file"
    done
    printf '%s\n' "$valid_ca" \
    | forEachCertificate storeCertBySerial "$ca" "%s.pem"
    # other commands (openssl crl, curl) may need openssl-style subject hash
    # symlinks, so create them.
    openssl rehash "$ca" > /dev/null
  fi
  if [ ! -r "$cas_ca" ]; then
    # Should never be reached, as this function should be run once with
    # cas_ca == ca (to update CAS' CA), in which case cas_ca exists by this
    # point. CAU's CA should only be updated after, and by that point CAS' CA
    # already exists.
    printf '%s does not exist\n' "$cas_ca"
    return 1
  fi
  future_ca="$(_curlInsecure "$url/crt/ca.crt.json")"
  status=$?
  test $status -ne 0 && return 1
  printf '%s\n' "$future_ca" | forEachJSONListItem appendValidCA "$ca"
}

getCertificateRevocationList () {
  # Usage: <url> <ca>
  _curlInsecure "$1/crl" | openssl crl "$(
    if [ -d "$2" ]; then
      printf -- '-CApath'
    else
      printf -- '-CAfile'
    fi
  )" "$2" 2> /dev/null
}

getCertificateSigningRequest () {
  # Usage: <url> <csr id>
  _curlInsecure "$1/csr/$2"
}

getPendingCertificateRequestList () {
  # Usage: <url> <user crt>
  _curlInsecure --cert "$2" "$1/csr"
}

createCertificateSigningRequest () {
  # Usage: <url> < csr > csr id
  _putInsecure --header 'Content-Type: application/pkcs10' "$1/csr" \
    --dump-header - | while IFS= read -r line; do
    # Note: $line contains trailing \r, which will not get stripped by $().
    # So strip it with sed instead.
    case "$line" in
      'Location: '*)
        printf '%s\n' "$line" | sed 's/^Location: \(\S*\).*/\1/'
      ;;
    esac
  done
}

deletePendingCertificateRequest () {
  # Usage: <url> <user crt> <csr id>
  _curlInsecure --request DELETE --cert "$2" "$1/csr/$3"
}

getCertificate () {
  # Usage: <url> <csr id>
  # shellcheck disable=SC2039
  local status
  _curlInsecure --fail "$1/crt/$2"
  status=$?
  if [ $status -ne 0 ]; then
    printf 'Certificate %s not found (not signed yet or rejected)\n' "$2" >&2
    return 1
  fi
}

createCertificate () {
  # Usage: <url> <user crt> <csr id>
  # shellcheck disable=SC2039
  local result
  _putInsecureNoOut --cert "$2" "$1/crt/$3" < /dev/null
  result=$?
  if [ $result -ne 0 ]; then
    printf '%s: No such pending signing request\n' "$3" >&2
  fi
  return $result
}

createCertificateWith () {
  # Usage: <url> <user crt> <csr id> < csr
  _putInsecureNoOut --cert "$2" \
    --header 'Content-Type: application/pkcs10' "$1/crt/$3"
}

if [ $# -ne 0 ]; then
  _usage () {
    cat << EOF
Usage: $0 <caucase url> [--ca-crt PATH] --ca-url URL [...]

caucase client
Certificate Authority for Users, Certificate Authority for SErvices

Arguments are taken into account in given order, options overriding any
previous occurrence and actions being executed in given order.

General options
--ca-url URL
  Required. Base URL of the caucase service to access.
  Ex: http://caucase.example.com:8000
--ca-crt PATH
  Default: cas.crt.pem
  Path of the service CA certificate file or directory. Updated on each run.
  If nothing with that name exists, a directory is created if given name does
  not contain a dot, and a file otherwise.
--user-ca-crt PATH
  Default: cau.crt.pem
  Path of the user CA certificate file or directory. See --update-user and
  --ca-crt.
--crl PATH
  Default: cas.crl.pem
  Path of the service revocation list. Updated on each run.
--user-crl PATH
  Default: cau.crl.pem
  Path of the service revocation list. See --update-user .
--threshold DAYS
  Default: 31
  Skip renewal when certificate is still valid for this many days.
  See --renew-crt .
--key-len BITS
  Default: 2048
  Size of the private key to generate. See --renew-crt .
--user-key PATH
  A file containing a private key and corresponding certificate, to
  authenticate as a caucase user.
--mode {service|user}
  Default: service
  Caucase personality to query.

Anonymous actions
--send-csr PATH
  Submit given certificate signing request, and print the identifier under which
  the server accepted it (see --get-crt and --get-csr).
--get-crt CSR_ID CRT_PATH
  Retrieve the certificate corresponding to the signing request with identifier
  CSR_ID, and store it in CRT_PATH.
  If CRT_PATH exists and contains a private key, verifies it matches received
  certificate, and exit before modifying the file if it does not match.
  See also --get-csr .
--revoke-crt CRT_PATH KEY_PATH
  Revoke the certificate at CRT_PATH. Revocation request must be signed with
  corresponding private key, read from KEY_PATH.
  Both paths may point at the same file.
--renew-crt CRT_PATH KEY_PATH
  Renew the certificate from CRT_PATH with a new private key. Upon success,
  write resulting certificate in CRT_PATH and key in KEY_PATH.
  Both paths may point at the same file.
--get-csr CSR_ID CSR_PATH
  Retrieve the signing request with identifier CSR_ID, and store it in CSR_PATH.
  Allows checking whether a signature request is still pending if --get-crt
  failed, or if it has been rejected.
--update-user
  In addition to updating CA certificate and revocation list for service more,
  also update the equivalents for user mode. You should not need this.

Authenticated actions
These options require --user-key .
--list-csr
  List pending certificate signing requests.
--sign-csr CSR_ID
  Sign the pending request with identifier CSR_ID.
--sign-csr-with CSR_ID CSR_PATH
  Sign the pending request with identifier CSR_ID, replacing its extensions with
  the ones from CSR_PATH.
--reject-csr
  Reject pending request with identifier CSR_ID.
--revoke-other-crt CRT_PATH
  Revoke certificate read from CRT_PATH, without requiring access to its private
  key.
--revoke-serial SERIAL
  Revoke certificate with given serial. When not even the original certificate
  is available for revocation.

Special actions
--help
  Display this help and exit.
--version
  Display command version and exit.
EOF
  }

  _argUsage () {
    printf '%s: %s\n' "$arg" "$1" >&2
    _usage >&2
  }

  _needArg () {
    if [ "$argc" -lt "$1" ]; then
      printf '%s\n' "$arg needs $1 arguments" >&2
      _usage >&2
      return 1
    fi
  }

  _needURLAndArg () {
    if [ -z "$ca_anon_url" ]; then
      printf '%s\n' "--ca-url must be provided before $arg" >&2
      return 1
    fi
    _needArg "$1" || return 1
  }

  _needAuthURLAndArg () {
    if [ -z "$user_key" ]; then
      printf '%s\n' "--user-key must be provided before $arg" >&2
      return 1
    fi
    _needURLAndArg "$1" || return 1
  }

  _checkCertficateMatchesOneKey () {
    # Called from _main, sets global "key_found".
    test "$key_found" -ne 0 && return 2
    key_found=1
    checkCertificateMatchesKey "$1" "$(cat)" || return 1
  }

  _printOneKey () {
    # Called from _main, sets global "key_found".
    if [ $key_found -ne 0 ]; then
      _argUsage 'Multiple private keys'
      return 1
    fi
    key_found=1
    cat
  }

  _printOneCert () {
    # Called indirectly from _main, sets global "crt_found".
    if [ "$crt_found" -ne 0 ]; then
      _argUsage 'Multiple certificates'
      return 1
    fi
    crt_found=1
    cat
  }

  _printOneMatchingCert () {
    # Called indirectly from _main, sets global "crt_found".
    # shellcheck disable=SC2039
    local crt
    crt="$(cat)"
    if [ $crt_found -ne 0 ]; then
      _argUsage 'Multiple certificates'
      return 1
    fi
    crt_found=1
    checkCertificateMatchesKey "$crt" "$1" && printf '%s\n' "$crt"
  }

  _matchOneKeyAndPrintOneMatchingCert () {
    # Usage: <crt path> <key path>
    # Sets globals "crt_found" and "key_found"
    # shellcheck disable=SC2039
    local crt
    key_found=0
    key="$(forEachPrivateKey _printOneKey < "$2")"
    status=$?
    test $status -ne 0 && return $status
    crt_found=0
    crt="$(forEachCertificate _printOneMatchingCert "$key" < "$1")"
    status=$?
    test $status -ne 0 && return $status
    if [ -z "$crt" ]; then
      _argUsage 'No certificate matches private key'
      return 1
    fi
    printf '%s\n' "$crt"
  }

  _printPendingCSR () {
    # shellcheck disable=SC2039
    local json
    json="$(cat)"
    printf '%20s | %s\n' \
      "$(printf '%s\n' "$json" | jq --raw-output .id)" \
      "$(printf '%s\n' "$json" | jq --raw-output .csr \
        | openssl req -subject -noout | sed 's/^subject=//')"
  }

  _main() {
    checkDeps || return 1

    # shellcheck disable=SC2039
    local ca_anon_url='' \
      ca_auth_url \
      mode='service' \
      mode_path='cas' \
      cas_ca='cas.crt.pem' \
      cau_ca='cau.crt.pem' \
      cas_crl='cas.crl.pem' \
      cau_crl='cau.crl.pem' \
      key_len=2048 \
      update_user=0 \
      user_key='' \
      threshold=31 \
      status arg argc \
      ca_netloc ca_address ca_port ca_path \
      csr_id csr csr_path crl crt crt_path crt_dir key_path key serial \
      csr_list_json version

    while test $# -gt 0; do
      arg="$1"
      shift
      argc=$#
      case "$arg" in
        --help)
          _usage
          return
        ;;
        --version)
          # shellcheck disable=SC2016
          version='$Format:%H$'
          if [ "x$(echo "$version" | base64)" = 'xJEZvcm1hdDolSCQK' ]; then
            if command -v git > /dev/null; then
              version="$(git describe --tags --dirty --always --long)"
            else
              version='unknown'
            fi
          fi
          printf '%s\n' "$version"
          return
        ;;
        --ca-url)
          _needArg 1 || return 1
          ca_anon_url="$1"
          shift
          case "$ca_anon_url" in
            https://*)
              ca_auth_url="$ca_anon_url"
            ;;
            http://*)
              ca_netloc="$(
                printf '%s\n' "$ca_anon_url" | sed 's!^http://\([^/?#]*\).*!\1!'
              )"
              ca_path="$(
                printf '%s\n' "$ca_anon_url" | sed 's!^http://[^/?#]*!!'
              )"
              ca_port=80
              # Note: too bad there is no portable case fall-through...
              case "$ca_netloc" in
                *\]:*)
                  # Bracket-enclosed address, which may contain colons
                  ca_address="$(
                    printf '%s\n' "$ca_netloc" | sed 's!^\(.*\]\).*!\1!'
                  )"
                  ca_port="$(
                    printf '%s\n' "$ca_netloc" | sed 's!.*\]:!!'
                  )"
                ;;
                *\]*)
                  # Bracket-enclosed address, which may contain colons
                  ca_address="$(
                    printf '%s\n' "$ca_netloc" | sed 's!^\(.*\]\).*!\1!'
                  )"
                ;;
                *:*)
                  # No bracket-enclosed address, rely on colon
                  ca_address="$(
                    printf '%s\n' "$ca_netloc" | sed 's!^\([^:]*\).*!\1!'
                  )"
                  ca_port="$(
                    printf '%s\n' "$ca_netloc" | sed 's!^[^:]*:!!'
                  )"
                ;;
                *)
                  # No bracket-encosed address, rely on colon
                  ca_address="$(
                    printf '%s\n' "$ca_netloc" | sed 's!^\([^:]*\).*!\1!'
                  )"
                ;;
              esac
              if [ "$ca_port" -eq 80 ]; then
                ca_port=''
              else
                ca_port=":$((ca_port + 1))"
              fi
              ca_auth_url="https://${ca_address}${ca_port}${ca_path}"
            ;;
            *)
              _argUsage 'Unrecognised URL scheme'
              return 1
            ;;
          esac
          updateCACertificate "${ca_anon_url}/cas" "$cas_ca"
          status=$?
          test $status -ne 0 && return $status
        ;;
        --ca-crt)
          _needArg 1 || return 1
          if [ -n "$ca_anon_url" ]; then
            _argUsage "$arg must be provided once, before --ca-url"
            return 1
          fi
          cas_ca="$1"
          shift
        ;;
        --user-ca-crt)
          _needArg 1 || return 1
          cau_ca="$1"
          shift
        ;;
        --crl)
          _needArg 1 || return 1
          cas_crl="$1"
          shift
        ;;
        --user-crl)
          _needArg 1 || return 1
          cau_crl="$1"
          shift
        ;;
        --threshold)
          _needArg 1 || return 1
          threshold="$1"
          shift
          if [ "$threshold" -eq "$threshold" ] 2> /dev/null ; then
            :
          else
            _argUsage 'Argument must be an integer'
            return 1
          fi
        ;;
        --key-len)
          _needArg 1 || return 1
          # XXX: check key length ?
          key_len="$1"
          shift
        ;;
        --user-key)
          _needArg 1 || return 1
          user_key="$1"
          shift
        ;;
        --mode)
          _needArg 1 || return 1
          mode="$1"
          shift
          case "$mode" in
            service)
              mode_path='cas'
            ;;
            user)
              mode_path='cau'
            ;;
            *)
              _argUsage 'Invalid mode'
              return 1
            ;;
          esac
        ;;
        # Anonymous actions
        --send-csr)
          _needURLAndArg 1 || return 1
          if [ ! -r "$1" ]; then
            _argUsage "$1 is not readable"
            return 1
          fi
          csr_id="$(
            createCertificateSigningRequest "${ca_anon_url}/${mode_path}" < "$1"
          )"
          status=$?
          test $status -ne 0 && return $status
          printf '%s %s\n' "$csr_id" "$1"
          shift
        ;;
        --get-crt)
          _needURLAndArg 2 || return 1
          csr_id="$1"
          crt_path="$2"
          shift 2
          crt_dir="$(dirname "$crt_path")"
          if [ "x$crt_path" = 'x-' ]; then # stdin & stdout
            :
          elif [ -w "$crt_path" ] && [ -r "$crt_path" ]; then # existing file
            :
          elif [ -w "$crt_dir" ] && [ -x "$crt_dir" ]; then # containing directory
            :
          else
            _argUsage \
              "$crt_path is not writeable (and/or not readable if exists)"
            return 1
          fi
          crt="$(getCertificate "${ca_anon_url}/${mode_path}" "$csr_id")"
          status=$?
          test $status -ne 0 && return $status
          if [ "x$crt_path" = 'x-' ]; then
            printf '%s\n' "$crt"
          else
            if [ -e "$crt_path" ]; then
              key_found=0
              forEachPrivateKey _checkCertficateMatchesOneKey "$crt" \
                < "$crt_path"
              status=$?
              if [ $status -eq 1 ]; then
                _argUsage 'Certificate does not match private key'
                return 1
              elif [ $status -eq 2 ]; then
                _argUsage 'Multiple private keys'
                return 1
              fi
            fi
            printf '%s\n' "$crt" >> "$crt_path"
          fi
        ;;
        --revoke-crt)
          _needURLAndArg 2 || return 1
          crt_path="$1"
          key_path="$2"
          shift 2
          crt="$(_matchOneKeyAndPrintOneMatchingCert "$crt_path" "$key_path")"
          status=$?
          test $status -ne 0 && return $status
          printf '%s\n' "$crt" \
          | revokeCertificate "${ca_anon_url}/${mode_path}" "$key_path"
          status=$?
          test $status -ne 0 && return $status
        ;;
        --renew-crt)
          _needURLAndArg 2 || return 1
          crt_path="$1"
          key_path="$2"
          shift 2
          crt="$(_matchOneKeyAndPrintOneMatchingCert "$crt_path" "$key_path")"
          status=$?
          test $status -ne 0 && return $status
          if printf '%s\n' "$crt" \
          | expiresBefore "$(date --date="$threshold days" +%s)"; then
            printf '%s\n' "$crt" \
            | renewCertificate "${ca_anon_url}/${mode_path}" \
              "$key_path" \
              "$key_len" \
              "$crt_path" "$key_path"
            status=$?
            test $status -ne 0 && return $status
          else
            printf '%s did not reach renew threshold, not renewing\n' \
              "$crt_path" >&2
          fi
        ;;
        --get-csr)
          _needURLAndArg 2 || return 1
          csr_id="$1"
          csr_path="$2"
          shift 2
          csr="$(
            getCertificateSigningRequest "${ca_anon_url}/${mode_path}" "$csr_id"
          )"
          status=$?
          test $status -ne 0 && return $status
          if [ "x$csr_path" = 'x-' ]; then
            printf '%s\n' "$csr"
          else
            printf '%s\n' "$csr" > "$csr_path"
          fi
        ;;
        --update-user)
          update_user=1
        ;;

        # Authenticated actions
        --list-csr)
          _needAuthURLAndArg 0 || return 1
          printf '%s\n' "-- pending $mode CSRs --"
          printf \
            '%20s | subject preview (fetch csr and check full content !)\n' \
            'csr_id'
          csr_list_json="$(
            getPendingCertificateRequestList "${ca_auth_url}/${mode_path}" \
              "$user_key"
          )"
          status=$?
          test $status -ne 0 && return $status
          printf '%s' "$csr_list_json" | forEachJSONListItem _printPendingCSR
          printf '%s\n' "-- end of pending $mode CSRs --"
        ;;
        --sign-csr)
          _needAuthURLAndArg 1 || return 1
          csr_id="$1"
          shift
          createCertificate "${ca_auth_url}/${mode_path}" \
            "$user_key" "$csr_id"
          status=$?
          test $status -ne 0 && return $status
        ;;
        --sign-csr-with)
          _needAuthURLAndArg 2 || return 1
          csr_id="$1"
          csr="$2"
          shift
          createCertificateWith "${ca_auth_url}/${mode_path}" \
            "$user_key" "$csr_id" < "$csr"
          status=$?
          test $status -ne 0 && return $status
        ;;
        --reject-csr)
          _needAuthURLAndArg 1 || return 1
          csr_id="$1"
          shift
          deletePendingCertificateRequest "${ca_auth_url}/${mode_path}" \
            "$user_key" "$csr_id"
          status=$?
          test $status -ne 0 && return $status
        ;;
        --revoke-other-crt)
          _needAuthURLAndArg 1 || return 1
          crt_path="$1"
          shift
          crt_found=0
          crt="$(forEachCertificate _printOneCert < "$crt_path")"
          status=$?
          test $status -ne 0 && return $status
          printf '%s\n' "$crt" | revokeCRTWithoutKey \
            "${ca_auth_url}/${mode_path}" "$user_key"
          status=$?
          test $status -ne 0 && return $status
        ;;
        --revoke-serial)
          _needAuthURLAndArg 1 || return 1
          serial="$1"
          shift
          revokeSerial "${ca_auth_url}/${mode_path}" \
            "$user_key" "$serial"
          status=$?
          test $status -ne 0 && return $status
        ;;

        *)
          _argUsage 'Unknown argument'
          return 1
        ;;
      esac
    done
    if [ -n "$ca_anon_url" ] && [ -r "$cas_ca" ]; then
      if crl="$(
        getCertificateRevocationList "${ca_anon_url}/cas" "$cas_ca"
      )"; then
        printf '%s\n' "$crl" > "$cas_crl"
      else
        printf \
          'Received CAS CRL was not signed by CAS CA certificate, skipping\n'
      fi
      if [ $update_user -eq 1 ]; then
        updateCACertificate "${ca_anon_url}/cau" "$cau_ca"
        status=$?
        test $status -ne 0 && return $status
        if crl="$(
          getCertificateRevocationList "${ca_anon_url}/cau" "$cau_ca"
        )"; then
          printf '%s\n' "$crl" > "$cau_crl"
        else
          printf \
            'Received CAU CRL was not signed by CAU CA certificate, skipping\n'
        fi
      fi
    fi
  }
  _test() {
    # shellcheck disable=SC2039
    local netloc="$1" \
      cas_file \
      cas_found=0 \
      csr_id \
      status \
      tmp_dir \
      caucased_dir \
      caucased_type \
      caucased_pid
    echo 'Automated testing...'
    if command -v caucased > /dev/null; then
      caucased_type="path"
    elif [ "x$CAUCASE_PYTHON" != "x" ] && [ -x "$CAUCASE_PYTHON" ]; then
      # Used when ran from python caucase.test
      caucased_type="environment"
    else
      echo 'caucased not found in PATH, cannot run tests' >&2
      return 1
    fi
    tmp_dir="$(mktemp -d --suffix=caucase_sh)"
    caucased_dir="$tmp_dir/caucased"
    mkdir "$caucased_dir"
    if cd "$caucased_dir"; then
      :
    else
      echo 'Could not setup caucased directory'
      return 1
    fi
    echo 'Starting caucased...'
    case "$caucased_type" in
      path)
        caucased --netloc "$netloc" > /dev/null &
        ;;
      environment)
        "$CAUCASE_PYTHON" \
          -c 'from caucase.http import main; main()' \
          --netloc "$netloc" > /dev/null &
        ;;
      *)
        echo "Unhandled caucased_type $caucased_type"
        return 1
        ;;
    esac
    caucased_pid="$!"
    # shellcheck disable=SC2064
    trap "kill \"$caucased_pid\"; wait; rm -rf \"$tmp_dir\"" EXIT
    # wait for up to about 60 seconds for caucased to start listening (initial
    # certificate generation.
    echo 'Waiting for caucased to be ready...'
    for _ in $(seq 600); do
      _curlInsecure "http://$netloc" > /dev/null
      status=$?
      test $status -eq 0 && break
      # is caucased still alive ?
      if kill -0 "$caucased_pid" 2> /dev/null; then
        :
      else
        echo "caucased exited"
        return 1
      fi
      # curl status 7 means "could not connect"
      if [ $status -ne 7 ]; then
        echo "curl failed while accessing test caucased with status $status"
        return 1
      fi
      sleep 0.1
    done
    if [ $status -ne 0 ]; then
      echo 'Timeout while waiting for caucased to start'
      return 1
    fi
    if cd "$tmp_dir"; then
      :
    else
      echo 'Could not enter test temporary directory'
      return 1
    fi
    cat > "openssl.cnf" << EOF
[ req ]
distinguished_name = req_distinguished_name
string_mask = utf8only
req_extensions = v3_req

[ req_distinguished_name ]
CN = Common Name

[ v3_req ]
basicConstraints = CA:FALSE
EOF
    echo 'Generating a key and csr...'
    openssl req \
      -new \
      -keyout user_crt.pem \
      -subj "/CN=testuser" \
      -config openssl.cnf \
      -nodes \
      -out user_csr.pem 2> /dev/null
    echo 'Bootstraping trust and submitting csr for a user certificate...'
    csr_id="$(_main \
      --ca-crt "cas_crt" \
      --ca-url "http://$netloc" \
      --update-user \
      --mode user \
      --send-csr user_csr.pem \
      | sed 's/\s.*//' \
    )"
    if [ ! -d cas_crt ]; then
      echo 'cas_crt not created'
      find . -ls
      return 1
    fi
    for cas_file in cas_crt/*; do
      if [ -r "$cas_file" ] && [ ! -h "$cas_file" ]; then
        if [ "$cas_found" -eq 1 ]; then
          echo 'Multiple CAS CA certificates found'
          find . -ls
          return 1
        fi
        cas_found=1
      fi
    done
    if [ "$cas_found" -eq 0 ]; then
      echo 'No CAS CA certificates found, but directory exists'
      find . -ls
      return 1
    fi
    if [ ! -f cau.crt.pem ]; then
      echo 'cau.crt.pem not created'
      find . -ls
      return 1
    fi
    echo 'Retrieving auto-issued user certificate...'
    if _main \
      --ca-crt "cas_crt" \
      --ca-url "http://$netloc" \
      --mode user \
      --get-crt "$csr_id" user_crt.pem
    then
      :
    else
      echo 'Failed to receive signed user certificate.'
      find . -ls
      return 1
    fi
    echo 'Using the user certificate...'
    if _main \
      --ca-crt "cas_crt" \
      --ca-url "http://$netloc" \
      --user-key user_crt.pem \
      --list-csr \
      > /dev/null; then
      :
    else
      echo 'Failed to list pending CSR, authentication failed ?'
      find . -ls
      return 1
    fi
    echo 'Success'
  }
  if [ "$#" -gt 0 ] && [ "x$1" = 'x--test' ]; then
    if [ "$#" -le 2 ]; then
      _test "${2:-localhost:8000}"
    else
      echo 'Usage: --test [<hostname/address>:<port>]'
      return 1
    fi
  else
    _main "$@"
  fi
fi