#!/bin/sh
# This file is part of caucase
# Copyright (C) 2017  Nexedi
#     Vincent Pelletier <vincent@nexedi.com>
#
# caucase is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# caucase is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with caucase.  If not, see <http://www.gnu.org/licenses/>.
set -u

str2json () {
  # Convert some text into a json string.
  # Usage: str2json < 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: pairs2obj <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.
  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.
  local list="$(cat)" index
  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: wrap <key file> <digest> < payload > wrapped
  local digest="$2" 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: nullWrap < payload > wrapped
  pairs2obj digest null payload "$(str2json)"
}

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

  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)"
  printf "%s\n" "$payload" "$@" | openssl x509 -pubkey -noout > "$pubkey_file"
  if [ $? -eq 0 ]; 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: nullUnwrap < wrapped > payload
  local 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: writeCertKey <crt data> <crt path> <key data> <key path>
  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"
}

alias CURL='curl --silent'
alias PUT='CURL --upload-file -'

PUTNoOut () {
  # For when PUT does not provide a response body, so the only way to check
  # for issues is checking HTTP status.
  local result
  result="$(
    PUT \
      --write-out "\n%{http_code}\n" \
      "$@"
  )"
  if [ $? -ne 0 ]; then
    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-----"
  return $?
}

_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: _forEachPEM <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.
  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: _forEachPEM <command> [<arg> ...] < pem

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

alias pem2fingerprint="openssl x509 -fingerprint -noout"

pemFingerprintIs () {
  # Usage: pemFingerprintIs <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: expiresBefore <date> < certificate > certificate
  # <date> must be a unix timestamp (date +%s)
  local enddate="$(openssl x509 -enddate -noout | sed "s/^[^=]*=//")"
  test $? -ne 0 && return 1
  test "$(date --date="$enddate" +%s)" -lt "$1"
  return $?
}

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

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

checkCertificateMatchesKey () {
  # Usage: checkCertificateMatchesKey <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=//"
  )"
  return $?
}

checkDeps () {
  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; 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 -o ! -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.
  local url="$1" oldkey="$2" bits="$3" newcrt="$4" newkey="$5"
  local newkeydata newcrtdata

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

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

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

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

updateCACertificate () {
  # Usage: <url> <cas_ca> <ca>
  local url="$1" cas_ca="$2" ca="$3" future_ca status orig_ca valid_ca
  orig_ca="$(
    if [ -e "$ca" ]; then
      cat "$ca"
    else
      CURL --insecure "$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
  printf "%s\n" "$valid_ca" > "$ca"
  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="$(CURL --cacert "$cas_ca" "$url/crt/ca.crt.json")"
  status=$?
  test $status -ne 0 && return 1
  printf "%s\n" "$future_ca" | forEachJSONListItem appendValidCA "$ca"
}

getCertificateRevocationList () {
  # Usage: <url> <ca>
  CURL --insecure "$1/crl" | openssl crl -CAfile "$2" 2> /dev/null
  return $?
}

getCertificateSigningRequest () {
  # Usage: <url> <csr id>
  CURL --insecure "$1/csr/$2"
  return $?
}

getPendingCertificateRequestList () {
  # Usage: <url> <ca> <user crt>
  CURL --cert "$3" --cacert "$2" "$1/csr"
  return $?
}

createCertificateSigningRequest () {
  # Usage: <url> < csr > csr id
  PUT --insecure --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
  return $?
}

deletePendingCertificateRequest () {
  # Usage: <url> <ca> <user crt> <csr id>
  CURL --request DELETE --cert "$3" --cacert "$2" "$1/csr/$4"
  return $?
}

getCertificate () {
  # Usage: <url> <csr id>
  local status
  CURL --fail --insecure "$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> <ca> <user crt> <csr id>
  local result
  PUTNoOut --cert "$3" --cacert "$2" "$1/crt/$4" < /dev/null
  result=$?
  if [ $result -ne 0 ]; then
    printf "%s: No such pending signing request\n" "$4" >&2
  fi
  return $result
}

createCertificateWith () {
  # Usage: <url> <ca> <user crt> <csr id> < csr
  PUTNoOut --cert "$3" --cacert "$2" \
    --header "Content-Type: application/pkcs10" "$1/crt/$4"
  return $?
}

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. Updated on each run.
--user-ca-crt PATH
  Default: cau.crt.pem
  Path of the user CA certificate file. See --update-user .
--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.
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".
    local 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: _matchOneKeyAndPrintOneMatchingCert <crt path> <key path>
    # Sets globals "crt_found" and "key_found"
    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 () {
    local 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

    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 key_path key serial \
      csr_list_json

    while test $# -gt 0; do
      arg="$1"
      shift
      argc=$#
      case "$arg" in
        --help)
          _usage
          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-encosed 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" "$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
          # Apparent no-op, but fails if "$threshoold" is not a number
          # Also, test outside of "if" statemnt so we do not have an
          # "if ... then : else ... fi".
          test "$threshold" -ge 0 -o "$threshold" -lt 0
          if [ $? -ne 0 ]; then
            _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
          if [ "$crt_path" != "-" -a ! -d "$(dirname "$crt_path")" -o "(" \
            -e "$crt_path" -a ! "(" -w "$crt_path" -a -r "$crt_path" ")" \
          ")" ]; then
            _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 [ "$crt_path" = "-" ]; 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 [ "$csr_path" = "-" ]; 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}" \
              "$cas_ca" "$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}" \
            "$cas_ca" "$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}" \
            "$cas_ca" "$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}" \
            "$cas_ca" "$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}" "$cas_ca" "$user_key"
          status=$?
          test $status -ne 0 && return $status
        ;;
        --revoke-serial)
          _needAuthURLAndArg 1 || return 1
          serial="$1"
          shift
          revokeSerial "${ca_auth_url}/${mode_path}" \
            "$cas_ca" "$user_key" "$serial"
          status=$?
          test $status -ne 0 && return $status
        ;;

        *)
          _argUsage "Unknown argument"
          return 1
        ;;
      esac
    done
    if [ -n "$ca_anon_url" -a -r "$cas_ca" ]; then
      crl="$(
        getCertificateRevocationList "${ca_anon_url}/cas" "$cas_ca"
      )"
      if [ $? -eq 0 ]; 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" "$cas_ca" "$cau_ca"
        status=$?
        test $status -ne 0 && return $status
        crl="$(
          getCertificateRevocationList "${ca_anon_url}/cau" "$cau_ca"
        )"
        if [ $? -eq 0 ]; then
          printf "%s\n" "$crl" > "$cau_crl"
        else
          printf \
            "Received CAU CRL was not signed by CAU CA certificate, skipping\n"
        fi
      fi
    fi
  }
  _main "$@"
fi