#!/usr/bin/env bash
# This file is in the public domain.
#
# Tests that re-submitting to /challenge for an already-solved
# validation returns a redirect_url with both ``code`` and ``state``
# query parameters, so the user agent can still be sent back to the
# OAuth client with a usable authorization grant.
#
# Regression test: previously the "already solved" branch returned the
# bare client redirect URI without code/state.

set -eu

function exit_skip() {
    echo " SKIP: $1"
    exit 77
}

function exit_fail() {
    echo " FAIL: $@"
    exit 1
}

function cleanup()
{
    for n in $(jobs -p)
    do
        kill $n 2> /dev/null || true
    done
    rm -f "$LAST_RESPONSE" "$FILENAME"
    wait
}

LAST_RESPONSE=$(mktemp responseXXXXXX.log)
FILENAME="test-challenger-revisit.txt"

trap cleanup EXIT

export PATH="$PATH:."

echo -n "Testing for jq"
jq -h > /dev/null || exit_skip "jq required"
echo " FOUND"
echo -n "Testing for curl"
curl -h > /dev/null || exit_skip "curl required"
echo " FOUND"
echo -n "Testing for wget"
wget -h > /dev/null || exit_skip "wget required"
echo " FOUND"
echo -n "Testing for challenger-httpd ..."
challenger-httpd -h > /dev/null || exit_skip "challenger-httpd required"
echo " FOUND"

CONF="test-challenger.conf"
BURL="http://localhost:9967"
REDIRECT_URI="http://client.example.com/"

echo -n "Initialize challenger database ..."
challenger-dbinit -r -c "${CONF}" &> dbinit.log
echo " OK"

echo -n "Add challenger client ..."
CLIENT_SECRET="secret-token:secret"
challenger-admin -c "${CONF}" -a "${CLIENT_SECRET}" "${REDIRECT_URI}" &> admin.log
echo " OK"
CLIENT_ID=1

echo -n "Start challenger-httpd ..."
challenger-httpd -L INFO -c "${CONF}" &> httpd.log &

for n in $(seq 1 50)
do
    echo -n "."
    sleep 0.2
    OK=0
    wget --tries=1 --timeout=1 "${BURL}/config" -o /dev/null -O /dev/null >/dev/null || continue
    OK=1
    break
done
if [ 1 != $OK ]
then
    exit_skip "Failed to launch challenger service"
fi


echo -n "Setup new validation process..."
STATUS=$(curl "${BURL}/setup/${CLIENT_ID}" \
    -H "Authorization: Bearer ${CLIENT_SECRET}" \
    -d '' \
    -w "%{http_code}" -s -o $LAST_RESPONSE)

if [ "$STATUS" != "200" ]
then
    exit_fail "Expected 200 OK. Got: $STATUS" $(cat $LAST_RESPONSE)
fi
NONCE=$(jq -r .nonce < "$LAST_RESPONSE")
echo " OK"

CLIENT_STATE="the-client-state"
CLIENT_SCOPE="the-client-scope"

echo -n "Initiating user login..."
STATUS=$(curl "${BURL}/authorize/${NONCE}" \
    -G \
    -H "Accept: application/json" \
    --data-urlencode "response_type=code" \
    --data-urlencode "client_id=${CLIENT_ID}" \
    --data-urlencode "redirect_uri=${REDIRECT_URI}" \
    --data-urlencode "state=${CLIENT_STATE}" \
    --data-urlencode "scope=${CLIENT_SCOPE}" \
    -w "%{http_code}" -s -o $LAST_RESPONSE)

if [ "$STATUS" != "200" ]
then
    exit_fail "Expected 200 OK. Got: $STATUS" $(cat $LAST_RESPONSE)
fi
echo "OK"


echo -n "Initiating address submission..."
STATUS=$(curl "${BURL}/challenge/${NONCE}" \
    -X POST \
    -H "Accept: application/json" \
    --data-urlencode "filename=${FILENAME}" \
    -w "%{http_code}" -s -o $LAST_RESPONSE)

if [ "$STATUS" != "200" ]
then
    exit_fail "Expected 200 OK. Got: $STATUS" $(cat $LAST_RESPONSE)
fi
echo "OK"

PIN=$(cat ${FILENAME} | awk '{print $5}')

echo -n "Initiating PIN ${PIN} submission..."
RESULT=$(curl "${BURL}/solve/${NONCE}" \
    -X POST \
    -H "Accept: text/html" \
    --data-urlencode "pin=${PIN}" \
    -w "%{http_code} %{redirect_url}" -s -o $LAST_RESPONSE)
STATUS=$(echo "$RESULT" | awk '{print $1}')
TARGET=$(echo "$RESULT" | awk '{print $2}')

if [ "$STATUS" != "302" ]
then
    exit_fail "Expected 302. Got: $STATUS" $(cat $LAST_RESPONSE)
fi

# This is where we start to diverge from test-challenger.sh:
# We track the original (good) response and then check we get
# it again later.

ORIG_CODE=$(echo "$TARGET" | sed -e "s/.*?code=//g" -e "s/&.*//g")
ORIG_STATE=$(echo "$TARGET" | sed -e "s/.*&state=//g")

if [ -z "${ORIG_CODE}" ]
then
    exit_fail "No code returned from /solve"
fi
echo "OK"

# Now the actual regression test: re-submit the SAME address to
# /challenge.  Since the validation is already solved, the server
# should reply with a JSON ChallengeRedirect whose redirect_url
# carries an OAuth ``code`` (and the original ``state``) so the user
# agent can still be returned to the client with a valid grant.
echo -n "Re-submitting address after solve..."
STATUS=$(curl "${BURL}/challenge/${NONCE}" \
    -X POST \
    -H "Accept: application/json" \
    --data-urlencode "filename=${FILENAME}" \
    -w "%{http_code}" -s -o $LAST_RESPONSE)

if [ "$STATUS" != "200" ]
then
    exit_fail "Expected 200 OK on re-submit. Got: $STATUS" $(cat $LAST_RESPONSE)
fi

TYPE=$(jq -r .type < "$LAST_RESPONSE")
if [ "$TYPE" != "completed" ]
then
    exit_fail "Expected type=completed on re-submit. Got: $TYPE" $(cat $LAST_RESPONSE)
fi

REDIRECT_URL=$(jq -r .redirect_url < "$LAST_RESPONSE")
if [ -z "${REDIRECT_URL}" ] || [ "${REDIRECT_URL}" = "null" ]
then
    exit_fail "Missing redirect_url in re-submit response" $(cat $LAST_RESPONSE)
fi

# redirect_url must have a query string with code= and state=.
case "${REDIRECT_URL}" in
    *\?*code=*)
        # Good!
        ;;
    *)
        exit_fail "redirect_url has no 'code' parameter: ${REDIRECT_URL}"
        ;;
esac
case "${REDIRECT_URL}" in
    *state=*)
        # Good!
        ;;
    *)
        exit_fail "redirect_url has no 'state' parameter: ${REDIRECT_URL}"
        ;;
esac

REVISIT_URL=$(echo "${REDIRECT_URL}" | sed -e "s/?.*//g")
REVISIT_CODE=$(echo "${REDIRECT_URL}" | sed -e "s/.*?code=//g" -e "s/&.*//g")
REVISIT_STATE=$(echo "${REDIRECT_URL}" | sed -e "s/.*&state=//g")

if [ "${REVISIT_URL}" != "${REDIRECT_URI}" ]
then
    exit_fail "Re-submit redirect URL ${REVISIT_URL} differs from registered ${REDIRECT_URI}"
fi
if [ "${REVISIT_STATE}" != "${CLIENT_STATE}" ]
then
    exit_fail "Re-submit state ${REVISIT_STATE} differs from original ${CLIENT_STATE}"
fi
# The code is deterministic over (nonce, secret, scope, address,
# redirect_uri), so re-issuing must produce the same value as /solve did.
if [ "${REVISIT_CODE}" != "${ORIG_CODE}" ]
then
    exit_fail "Re-submit code ${REVISIT_CODE} differs from /solve code ${ORIG_CODE}"
fi
echo "OK"

exit 0
