/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

/***************************************************************************
 * Copyright (C) 2017-2026 ZmartZone Holding BV
 * All rights reserved.
 *
 * DISCLAIMER OF WARRANTIES:
 *
 * THE SOFTWARE PROVIDED HEREUNDER IS PROVIDED ON AN "AS IS" BASIS, WITHOUT
 * ANY WARRANTIES OR REPRESENTATIONS EXPRESS, IMPLIED OR STATUTORY; INCLUDING,
 * WITHOUT LIMITATION, WARRANTIES OF QUALITY, PERFORMANCE, NONINFRINGEMENT,
 * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.  NOR ARE THERE ANY
 * WARRANTIES CREATED BY A COURSE OR DEALING, COURSE OF PERFORMANCE OR TRADE
 * USAGE.  FURTHERMORE, THERE ARE NO WARRANTIES THAT THE SOFTWARE WILL MEET
 * YOUR NEEDS OR BE FREE FROM ERRORS, OR THAT THE OPERATION OF THE SOFTWARE
 * WILL BE UNINTERRUPTED.  IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * @Author: Hans Zandbelt - hans.zandbelt@openidc.com
 */

#include "cfg/dir.h"
#include "handle/handle.h"
#include "metrics.h"
#include "mod_auth_openidc.h"
#include "proto/proto.h"
#include "state.h"
#include "util/util.h"
#include "util/util_cfg.h"

/*
 * redirect the browser to the session logout endpoint
 */
static int oidc_response_redirect_parent_window_to_logout(request_rec *r, const oidc_cfg_t *c) {

	oidc_debug(r, "enter");

	const char *java_script =
	    apr_psprintf(r->pool,
			 "    <script type=\"text/javascript\">\n"
			 "      window.top.location.href = '%s?session=logout';\n"
			 "    </script>\n",
			 oidc_util_html_javascript_escape(r->pool, oidc_util_url_redirect_uri(r, c)));

	return oidc_util_html_content_prep(r, OIDC_REQUEST_STATE_KEY_HTML, "Redirecting...", java_script, NULL, NULL);
}

/*
 * handle an error returned by the OP
 */
static int oidc_response_authorization_error(request_rec *r, const oidc_cfg_t *c, const oidc_proto_state_t *proto_state,
					     const char *error, const char *error_description) {
	const char *prompt = oidc_proto_state_get_prompt(proto_state);
	if (prompt != NULL)
		prompt = apr_pstrdup(r->pool, prompt);
	if ((prompt != NULL) && (_oidc_strcmp(prompt, OIDC_PROTO_PROMPT_NONE) == 0)) {
		return oidc_response_redirect_parent_window_to_logout(r, c);
	}
	return oidc_util_html_send_error(r, apr_psprintf(r->pool, "OpenID Connect Provider error: %s", error),
					 error_description, HTTP_BAD_REQUEST);
}

/* handle the browser back on an authorization response */
static apr_byte_t oidc_response_browser_back(request_rec *r, const char *r_state, const oidc_session_t *session) {
	const char *s_state = NULL;
	const char *o_url = NULL;

	/*  see if we have an existing session and browser-back was used */
	if (session->remote_user == NULL)
		/* no session was established yet */
		return FALSE;

	s_state = oidc_session_get_request_state(r, session);
	if ((r_state == NULL) || (s_state == NULL) || (_oidc_strcmp(r_state, s_state) != 0))
		/*  state does not match with the state that was used to create  the session earlier, no replay is going
		 * on here */
		return FALSE;

	/* get the URL that was originally accessed by the user */
	o_url = oidc_session_get_original_url(r, session);
	/* log the browser back event detection */
	oidc_warn(r, "browser back detected, redirecting to original URL: %s", o_url);
	/* go back to the URL that he originally tried to access */
	oidc_http_hdr_out_location_set(r, o_url);

	/* signal that a browser back event was detected indeed and we handled this here */
	return TRUE;
}

static char *_oidc_response_post_preserve_template_contents = NULL;

/*
 * send an OpenID Connect authorization request to the specified provider preserving POST parameters using HTML5 storage
 */
apr_byte_t oidc_response_post_preserve_javascript(request_rec *r, const char *location, char **javascript,
						  char **javascript_method) {

	if (oidc_cfg_dir_preserve_post_get(r) == 0)
		return FALSE;

	oidc_debug(r, "enter");

	oidc_cfg_t *cfg = ap_get_module_config(r->server->module_config, &auth_openidc_module);

	const char *method = oidc_original_request_method(r, cfg, FALSE);

	if (_oidc_strcmp(method, OIDC_METHOD_FORM_POST) != 0)
		return FALSE;

	/* read the parameters that are POST-ed to us */
	apr_table_t *params = apr_table_make(r->pool, 8);
	if (oidc_util_read_post_params(r, params, FALSE, NULL) == FALSE) {
		oidc_error(r, "something went wrong when reading the POST parameters");
		return FALSE;
	}

	/* collect the pairs and join them once: appending to the accumulated string per parameter would make
	 * the pool memory used here quadratic in the number of (client-supplied) POST parameters */
	const apr_array_header_t *arr = apr_table_elts(params);
	const apr_table_entry_t *elts = (const apr_table_entry_t *)arr->elts;
	apr_array_header_t *pairs = apr_array_make(r->pool, arr->nelts, sizeof(const char *));
	for (int i = 0; i < arr->nelts; i++) {
		APR_ARRAY_PUSH(pairs, const char *) = apr_psprintf(
		    r->pool, "'%s': '%s'", oidc_http_url_encode(r, elts[i].key), oidc_http_url_encode(r, elts[i].val));
	}
	char *json = apr_psprintf(r->pool, "{ %s }", apr_array_pstrcat(r->pool, pairs, OIDC_CHAR_COMMA));

	if ((oidc_cfg_post_preserve_template_get(cfg) != NULL) &&
	    (oidc_util_html_send_in_template(
		 r, oidc_cfg_post_preserve_template_get(cfg), &_oidc_response_post_preserve_template_contents, json,
		 OIDC_POST_PRESERVE_ESCAPE_NONE, location, OIDC_POST_PRESERVE_ESCAPE_JAVASCRIPT) == OK))
		return TRUE;

	const char *jmethod = "preserveOnLoad()";
	const char *jscript = apr_psprintf(
	    r->pool,
	    "    <script type=\"text/javascript\">\n"
	    "      function %s {\n"
	    "        sessionStorage.setItem('mod_auth_openidc_preserve_post_params', JSON.stringify(%s));\n"
	    "        %s"
	    "      }\n"
	    "    </script>\n",
	    jmethod, json,
	    location
		? apr_psprintf(r->pool, "window.location='%s';\n", oidc_util_html_javascript_escape(r->pool, location))
		: "");

	if (javascript_method)
		*javascript_method = apr_pstrdup(r->pool, jmethod);
	if (javascript)
		*javascript = apr_pstrdup(r->pool, jscript);

	return TRUE;
}

/*
 * restore POST parameters on original_url from HTML5 session storage
 */
static int oidc_response_post_preserved_restore(request_rec *r, const char *original_url) {

	oidc_debug(r, "enter: original_url=%s", original_url);

	const char *method = "postOnLoad()";
	const char *script =
	    apr_psprintf(r->pool,
			 "    <script type=\"text/javascript\">\n"
			 "      function str_decode(string) {\n"
			 "        try {\n"
			 "          result = decodeURIComponent(string);\n"
			 "        } catch (e) {\n"
			 "          result =  unescape(string);\n"
			 "        }\n"
			 "        return result;\n"
			 "      }\n"
			 "      function %s {\n"
			 "        var mod_auth_openidc_preserve_post_params = "
			 "JSON.parse(sessionStorage.getItem('mod_auth_openidc_preserve_post_params'));\n"
			 "\t\t sessionStorage.removeItem('mod_auth_openidc_preserve_post_params');\n"
			 "        for (var key in mod_auth_openidc_preserve_post_params) {\n"
			 "          var input = document.createElement(\"input\");\n"
			 "          input.type = \"hidden\";\n"
			 "          input.name = str_decode(key);\n"
			 "          input.value = str_decode(mod_auth_openidc_preserve_post_params[key]);\n"
			 "          document.forms[0].appendChild(input);\n"
			 "        }\n"
			 "        document.forms[0].action = \"%s\";\n"
			 "        HTMLFormElement.prototype.submit.call(document.forms[0]);\n"
			 "      }\n"
			 "    </script>\n",
			 method, oidc_util_html_javascript_escape(r->pool, original_url));

	const char *body = "    <p>Restoring...</p>\n"
			   "    <form method=\"post\"></form>\n";

	return oidc_util_html_content_prep(r, OIDC_REQUEST_STATE_KEY_HTML, "Restoring...", script, method, body);
}

char *oidc_response_make_sid_iss_unique(request_rec *r, const char *sid, const char *issuer) {
	return apr_psprintf(r->pool, "%s@%s", sid, issuer);
}

/*
 * store resolved information in the session
 */
apr_byte_t oidc_response_save_in_session(request_rec *r, const oidc_cfg_t *c, oidc_session_t *session,
					 const oidc_provider_t *provider, const char *remoteUser, const char *id_token,
					 oidc_jwt_t *id_token_jwt, const char *s_userinfo_claims,
					 oidc_json_t *userinfo_claims, const char *access_token,
					 const char *access_token_type, const int expires_in, const char *refresh_token,
					 const char *scope, const char *session_state, const char *state,
					 const char *original_url, const char *userinfo_jwt) {

	/* store the user in the session */
	session->remote_user = apr_pstrdup(r->pool, remoteUser);

	/* set the session expiry to the inactivity timeout */
	session->expiry = apr_time_now() + apr_time_from_sec(oidc_cfg_session_inactivity_timeout_get(c));

	/* store the claims payload in the id_token for later reference */
	oidc_session_set_idtoken_claims(r, session, id_token_jwt->payload.value.json);

	if (oidc_cfg_store_id_token_get(c)) {
		/* store the compact serialized representation of the id_token for later reference  */
		oidc_session_set_idtoken(r, session, id_token);
	}

	/* store the issuer in the session (at least needed for session mgmt and token refresh */
	oidc_session_set_issuer(r, session, oidc_cfg_provider_issuer_get(provider));

	/* store the state and original URL in the session for handling browser-back more elegantly */
	oidc_session_set_request_state(r, session, state);
	oidc_session_set_original_url(r, session, original_url);

	if ((session_state != NULL) && (oidc_cfg_provider_check_session_iframe_get(provider) != NULL)) {
		/* store the session state and required parameters session management  */
		oidc_session_set_session_state(r, session, session_state);
		oidc_debug(r,
			   "session management enabled: stored session_state (%s), check_session_iframe (%s) and "
			   "client_id (%s) in the session",
			   session_state, oidc_cfg_provider_check_session_iframe_get(provider),
			   oidc_cfg_provider_client_id_get(provider));
	} else if (oidc_cfg_provider_check_session_iframe_get(provider) == NULL) {
		oidc_debug(
		    r, "session management disabled: \"check_session_iframe\" is not set in provider configuration");
	} else {
		oidc_debug(r,
			   "session management disabled: no \"session_state\" value is provided in the authentication "
			   "response even though \"check_session_iframe\" (%s) is set in the provider configuration",
			   oidc_cfg_provider_check_session_iframe_get(provider));
	}

	/* store the, possibly, provider specific userinfo_refresh_interval for performance reasons */
	oidc_session_set_userinfo_refresh_interval(r, session,
						   oidc_cfg_provider_userinfo_refresh_interval_get(provider));

	/* store claims resolved from userinfo endpoint */
	oidc_userinfo_store_claims(r, c, session, provider, userinfo_claims, userinfo_jwt);

	/* see if we have an access_token */
	if (access_token != NULL) {
		/* store the access_token in the session context */
		oidc_session_set_access_token(r, session, access_token);
		/* store the access_token in the session context */
		oidc_session_set_access_token_type(r, session, access_token_type);
		/* store the associated expires_in value */
		oidc_session_set_access_token_expires(r, session, expires_in);
		/* reset the access token refresh timestamp */
		oidc_session_set_access_token_last_refresh(r, session, apr_time_now());
	}

	/* see if we have a refresh_token */
	if (refresh_token != NULL) {
		/* store the refresh_token in the session context */
		oidc_session_set_refresh_token(r, session, refresh_token);
	}

	/* see if a scope was returned from the token endpoint */
	if (scope != NULL) {
		/* store the scope in the session context */
		oidc_session_set_scope(r, session, scope);
	}

	/* store max session duration in the session as a hard cut-off expiry timestamp */
	apr_time_t session_expires =
	    (oidc_cfg_provider_session_max_duration_get(provider) == 0)
		? oidc_util_apr_time_from_sec(id_token_jwt->payload.exp)
		: (apr_time_now() + apr_time_from_sec(oidc_cfg_provider_session_max_duration_get(provider)));
	oidc_session_set_session_expires(r, session, session_expires);

	oidc_debug(r, "oidc_provider_session_max_duration_get(provider) = %d, session_expires=%" APR_TIME_T_FMT,
		   oidc_cfg_provider_session_max_duration_get(provider), session_expires);

	/* log message about max session duration */
	oidc_log_session_expires(r, "session max lifetime", session_expires);

	/* store the domain for which this session is valid */
	oidc_session_set_cookie_domain(r, session,
				       oidc_cfg_cookie_domain_get(c)
					   ? oidc_cfg_cookie_domain_get(c)
					   : oidc_util_url_cur_host(r, oidc_cfg_x_forwarded_headers_get(c)));

	char *sid = NULL;
	char *sub = id_token_jwt->payload.sub;
	oidc_debug(r, "provider->backchannel_logout_supported=%d",
		   oidc_cfg_provider_backchannel_logout_supported_get(provider));
	/* Store sid even without back-channel support because front-channel logout may supply it. */
	oidc_jose_get_string(r->pool, id_token_jwt->payload.value.json, OIDC_CLAIM_SID, FALSE, &sid, NULL);
	if (sid == NULL)
		sid = sub;
	session->sid = oidc_response_make_sid_iss_unique(r, sid, oidc_cfg_provider_issuer_get(provider));

	/* Index by sub when back-channel logout may identify the session without sid. */
	if ((oidc_cfg_provider_backchannel_logout_supported_get(provider)) && (sub != NULL) &&
	    (_oidc_strcmp(sid, sub) != 0))
		session->sub = oidc_response_make_sid_iss_unique(r, sub, oidc_cfg_provider_issuer_get(provider));

	/* indicate that this is a newly created session */
	oidc_session_set_session_new(r, session, 1);

	/* store the session */
	return oidc_session_save(r, session, OIDC_SESSION_SAVE_NEW);
}

/*
 * restore the state that was maintained between authorization request and response in an encrypted cookie
 */
static apr_byte_t oidc_response_proto_state_restore(request_rec *r, const oidc_cfg_t *c, const char *state,
						    oidc_proto_state_t **proto_state) {

	oidc_debug(r, "enter");

	const char *cookieName = oidc_state_cookie_name(r, state);

	/* clean expired state cookies to avoid pollution */
	oidc_state_cookies_clean_expired(r, c, cookieName, FALSE);

	/* get the state cookie value first */
	const char *cookieValue = oidc_http_get_cookie(r, cookieName);
	if (cookieValue == NULL) {
		oidc_error(r, "no \"%s\" state cookie found: check domain and samesite cookie settings", cookieName);
		return FALSE;
	}

	/* clear state cookie because we don't need it anymore */
	oidc_http_set_cookie(r, cookieName, "", 0, OIDC_HTTP_COOKIE_SAMESITE_NONE(c, r));

	*proto_state = oidc_proto_state_from_cookie(r, c, cookieValue);
	if (*proto_state == NULL)
		return FALSE;

	const char *nonce = oidc_proto_state_get_nonce(*proto_state);

	/* calculate the hash of the browser fingerprint concatenated with the nonce */
	char *calc = oidc_state_browser_fingerprint(r, c, nonce);
	/* compare the calculated hash with the value provided in the authorization response */
	if (oidc_util_strcmp_const_time(calc, state) == FALSE) {
		oidc_error(
		    r,
		    "calculated state from cookie does not match state parameter passed back in URL: \"%s\" != \"%s\"",
		    state, calc);
		return FALSE;
	}

	apr_time_t ts = oidc_proto_state_get_timestamp(*proto_state);

	/* check that the timestamp is not beyond the valid interval */
	if (apr_time_now() > ts + apr_time_from_sec(oidc_cfg_state_timeout_get(c))) {
		oidc_error(r, "state has expired");
		if ((oidc_cfg_default_sso_url_get(c) == NULL) ||
		    (apr_table_get(r->subprocess_env, "OIDC_NO_DEFAULT_URL_ON_STATE_TIMEOUT") != NULL)) {
			oidc_util_html_send_error(
			    r, "Invalid Authentication Response",
			    apr_psprintf(r->pool,
					 "This is due to a timeout; please restart your authentication session by "
					 "re-entering the URL/bookmark you originally wanted to access: %s",
					 oidc_proto_state_get_original_url(*proto_state)),
			    OK);
		}
		return FALSE;
	}

	/* add the state */
	oidc_proto_state_set_state(*proto_state, state);

	/* log the restored state object */
	oidc_debug(r, "restored state: %s", oidc_proto_state_to_string(r, *proto_state));

	/* we've made it */
	return TRUE;
}

/*
 * helper function for basic/implicit client flows upon receiving an authorization response:
 * check that it matches the state stored in the browser and return the variables associated
 * with the state, such as original_url and OP oidc_provider_t pointer.
 */
static apr_byte_t oidc_response_match_state(request_rec *r, oidc_cfg_t *c, const char *state,
					    struct oidc_provider_t **provider, oidc_proto_state_t **proto_state) {

	oidc_debug(r, "enter (state=%s)", state);

	if ((state == NULL) || (_oidc_strcmp(state, "") == 0)) {
		oidc_error(r, "state parameter is not set");
		return FALSE;
	}

	/* check the state parameter against what we stored in a cookie */
	if (oidc_response_proto_state_restore(r, c, state, proto_state) == FALSE) {
		oidc_error(r, "unable to restore state");
		return FALSE;
	}

	*provider = oidc_get_provider_for_issuer(r, c, oidc_proto_state_get_issuer(*proto_state), FALSE);

	return (*provider != NULL);
}

/*
 * handle the different flows (hybrid, implicit, Authorization Code)
 */
static apr_byte_t oidc_response_flows(request_rec *r, oidc_cfg_t *c, const oidc_proto_state_t *proto_state,
				      oidc_provider_t *provider, apr_table_t *params, const char *response_mode,
				      oidc_jwt_t **jwt) {

	apr_byte_t rc = FALSE;

	const char *requested_response_type = oidc_proto_state_get_response_type(proto_state);

	/* handle the requested response type/mode */
	if (oidc_util_spaced_string_equals(r->pool, requested_response_type,
					   OIDC_PROTO_RESPONSE_TYPE_CODE_IDTOKEN_TOKEN)) {
		rc = oidc_proto_response_code_idtoken_token(r, c, proto_state, provider, params, response_mode, jwt);
	} else if (oidc_util_spaced_string_equals(r->pool, requested_response_type,
						  OIDC_PROTO_RESPONSE_TYPE_CODE_IDTOKEN)) {
		rc = oidc_proto_response_code_idtoken(r, c, proto_state, provider, params, response_mode, jwt);
	} else if (oidc_util_spaced_string_equals(r->pool, requested_response_type,
						  OIDC_PROTO_RESPONSE_TYPE_CODE_TOKEN)) {
		rc = oidc_proto_response_code_token(r, c, proto_state, provider, params, response_mode, jwt);
	} else if (oidc_util_spaced_string_equals(r->pool, requested_response_type, OIDC_PROTO_RESPONSE_TYPE_CODE)) {
		rc = oidc_proto_response_code(r, c, proto_state, provider, params, response_mode, jwt);
	} else if (oidc_util_spaced_string_equals(r->pool, requested_response_type,
						  OIDC_PROTO_RESPONSE_TYPE_IDTOKEN_TOKEN)) {
		rc = oidc_proto_response_idtoken_token(r, c, proto_state, provider, params, response_mode, jwt);
	} else if (oidc_util_spaced_string_equals(r->pool, requested_response_type, OIDC_PROTO_RESPONSE_TYPE_IDTOKEN)) {
		rc = oidc_proto_response_idtoken(r, c, proto_state, provider, params, response_mode, jwt);
	} else {
		oidc_error(r, "unsupported response type: \"%s\"", requested_response_type);
	}

	if ((rc == FALSE) && (*jwt != NULL)) {
		oidc_jwt_destroy(*jwt);
		*jwt = NULL;
	}

	return rc;
}

/*
 * set the unique user identifier that will be propagated in the Apache r->user and REMOTE_USER variables
 */
static apr_byte_t oidc_response_set_request_user(request_rec *r, const oidc_cfg_t *c, const oidc_provider_t *provider,
						 oidc_jwt_t *jwt, const oidc_json_t *userinfo_claims) {

	const char *issuer = oidc_cfg_provider_issuer_get(provider);
	char *claim_name = apr_pstrdup(r->pool, oidc_cfg_remote_user_claim_name_get(c));
	int n = (int)_oidc_strlen(claim_name);
	apr_byte_t post_fix_with_issuer = (n > 0) && (claim_name[n - 1] == OIDC_CHAR_AT);
	if (post_fix_with_issuer == TRUE) {
		claim_name[n - 1] = '\0';
		issuer = (_oidc_strstr(issuer, "https://") == NULL)
			     ? apr_pstrdup(r->pool, issuer)
			     : apr_pstrdup(r->pool, issuer + _oidc_strlen("https://"));
	}

	/* extract the username claim (default: "sub") from the id_token payload or user claims */
	apr_byte_t rc = FALSE;
	char *remote_user = NULL;
	if (userinfo_claims == NULL) {
		rc = oidc_get_remote_user(r, claim_name, oidc_cfg_remote_user_claim_get(c)->reg_exp,
					  oidc_cfg_remote_user_claim_get(c)->replace, jwt->payload.value.json,
					  &remote_user);
	} else {
		oidc_json_t *claims = oidc_json_copy(userinfo_claims);
		oidc_json_merge(r, jwt->payload.value.json, claims);
		rc = oidc_get_remote_user(r, claim_name, oidc_cfg_remote_user_claim_get(c)->reg_exp,
					  oidc_cfg_remote_user_claim_get(c)->replace, claims, &remote_user);
		oidc_json_decref(claims);
	}

	if ((rc == FALSE) || (remote_user == NULL)) {
		oidc_error(r,
			   "" OIDCRemoteUserClaim " is set to \"%s\", but could not set the remote user based on the "
			   "requested claim \"%s\" and the available claims for the user",
			   oidc_cfg_remote_user_claim_name_get(c), claim_name);
		return FALSE;
	}

	if (post_fix_with_issuer == TRUE)
		remote_user = apr_psprintf(r->pool, "%s%s%s", remote_user, OIDC_STR_AT, issuer);

	r->user = apr_pstrdup(r->pool, remote_user);

	oidc_debug(
	    r, "set remote_user to \"%s\" based on claim: \"%s\"%s", r->user, oidc_cfg_remote_user_claim_name_get(c),
	    oidc_cfg_remote_user_claim_get(c)->reg_exp
		? apr_psprintf(r->pool, " and expression: \"%s\" and replace string: \"%s\"",
			       oidc_cfg_remote_user_claim_get(c)->reg_exp, oidc_cfg_remote_user_claim_get(c)->replace)
		: "");

	return TRUE;
}

static char *_oidc_response_post_restore_template_contents = NULL;

/*
 * handle the case where the state parameter from the authorization response could not be matched
 */
static int oidc_response_handle_state_mismatch(request_rec *r, const oidc_cfg_t *c) {
	if (oidc_cfg_default_sso_url_get(c) != NULL) {
		oidc_warn(r,
			  "invalid authorization response state; a default SSO URL is set, sending the user there: %s",
			  oidc_cfg_default_sso_url_get(c));
		oidc_http_hdr_out_location_set(r, oidc_util_url_abs(r, c, oidc_cfg_default_sso_url_get(c)));
		OIDC_METRICS_COUNTER_INC(r, c, OM_AUTHN_RESPONSE_ERROR_STATE_MISMATCH);
		return HTTP_MOVED_TEMPORARILY;
	}

	oidc_error(r, "invalid authorization response state and no default SSO URL is set, sending an error...");

	// if error text was already produced (e.g. state timeout) then just return with a 400
	if (apr_table_get(r->subprocess_env, OIDC_ERROR_ENVVAR) != NULL) {
		OIDC_METRICS_COUNTER_INC(r, c, OM_AUTHN_RESPONSE_ERROR_STATE_EXPIRED);
		return HTTP_BAD_REQUEST;
	}

	OIDC_METRICS_COUNTER_INC(r, c, OM_AUTHN_RESPONSE_ERROR_STATE_MISMATCH);

	return oidc_util_html_send_error(r, "Invalid Authorization Response",
					 "Could not match the authorization response to an earlier request via "
					 "the state parameter and corresponding state cookie",
					 HTTP_BAD_REQUEST);
}

/*
 * finalize a successful authorization response: restore preserved form-post data or redirect to the original URL
 */
static int oidc_response_finish_success(request_rec *r, const oidc_cfg_t *c, const char *original_url,
					const char *original_method) {
	/* log the successful response */
	oidc_debug(r, "session created and stored, returning to original URL: %s, original method: %s", original_url,
		   original_method);

	/* check whether form post data was preserved; if so restore it */
	if (_oidc_strcmp(original_method, OIDC_METHOD_FORM_POST) == 0) {
		if (oidc_cfg_post_restore_template_get(c) != NULL)
			return oidc_util_html_send_in_template(
			    r, oidc_cfg_post_restore_template_get(c), &_oidc_response_post_restore_template_contents,
			    original_url, OIDC_POST_PRESERVE_ESCAPE_JAVASCRIPT, NULL, OIDC_POST_PRESERVE_ESCAPE_NONE);
		return oidc_response_post_preserved_restore(r, original_url);
	}

	/* now we've authenticated the user so go back to the URL that he originally tried to access */
	oidc_http_hdr_out_location_set(r, original_url);

	/* do the actual redirect to the original URL */
	return HTTP_MOVED_TEMPORARILY;
}

/*
 * complete the handling of an authorization response by obtaining, parsing and verifying the
 * id_token and storing the authenticated user state in the session
 */
static int oidc_response_process(request_rec *r, oidc_cfg_t *c, oidc_session_t *session, apr_table_t *params,
				 const char *response_mode) {
	int rc = -1;
	oidc_provider_t *provider = NULL;
	oidc_proto_state_t *proto_state = NULL;
	oidc_jwt_t *id_token = NULL;
	oidc_json_t *userinfo_claims = NULL;
	int expires_in = 0;
	char *userinfo_jwt = NULL;
	const char *s_userinfo_claims = NULL;
	const char *original_url = NULL;
	const char *original_method = NULL;
	const char *prompt = NULL;

	oidc_debug(r, "enter, response_mode=%s", response_mode);

	/* see if this response came from a browser-back event */
	if (oidc_response_browser_back(r, apr_table_get(params, OIDC_PROTO_STATE), session) == TRUE) {
		rc = HTTP_MOVED_TEMPORARILY;
		goto end;
	}

	/* match the returned state parameter against the state stored in the browser */
	if (oidc_response_match_state(r, c, apr_table_get(params, OIDC_PROTO_STATE), &provider, &proto_state) ==
	    FALSE) {
		rc = oidc_response_handle_state_mismatch(r, c);
		goto end;
	}

	/* see if the response is an error response */
	if (apr_table_get(params, OIDC_PROTO_ERROR) != NULL) {
		OIDC_METRICS_COUNTER_INC(r, c, OM_AUTHN_RESPONSE_ERROR_PROVIDER);
		rc = oidc_response_authorization_error(r, c, proto_state, apr_table_get(params, OIDC_PROTO_ERROR),
						       apr_table_get(params, OIDC_PROTO_ERROR_DESCRIPTION));
		goto end;
	}

	/* handle the code, implicit or hybrid flow */
	if (oidc_response_flows(r, c, proto_state, provider, params, response_mode, &id_token) == FALSE) {
		OIDC_METRICS_COUNTER_INC(r, c, OM_AUTHN_RESPONSE_ERROR_PROTOCOL);
		rc = oidc_response_authorization_error(r, c, proto_state, "Error in handling response type.", NULL);
		goto end;
	}

	if (id_token == NULL) {
		oidc_error(r, "no id_token was provided");
		rc = oidc_response_authorization_error(r, c, proto_state, "No id_token was provided.", NULL);
		goto end;
	}

	expires_in = _oidc_str_to_int(apr_table_get(params, OIDC_PROTO_EXPIRES_IN), -1);

	/*
	 * optionally resolve additional claims against the userinfo endpoint
	 * parsed claims are not actually used here but need to be parsed anyway for error checking purposes
	 */
	s_userinfo_claims = oidc_userinfo_retrieve_claims(
	    r, c, provider, apr_table_get(params, OIDC_PROTO_ACCESS_TOKEN),
	    apr_table_get(params, OIDC_PROTO_TOKEN_TYPE), NULL, id_token->payload.sub, &userinfo_claims, &userinfo_jwt);

	/* restore the original protected URL that the user was trying to access */
	original_url = oidc_proto_state_get_original_url(proto_state);
	if (original_url != NULL)
		original_url = apr_pstrdup(r->pool, original_url);
	original_method = oidc_proto_state_get_original_method(proto_state);
	if (original_method != NULL)
		original_method = apr_pstrdup(r->pool, original_method);
	prompt = oidc_proto_state_get_prompt(proto_state);

	/* set the user */
	if (oidc_response_set_request_user(r, c, provider, id_token, userinfo_claims) == FALSE) {
		oidc_error(r, "remote user could not be set");
		OIDC_METRICS_COUNTER_INC(r, c, OM_AUTHN_RESPONSE_ERROR_REMOTE_USER);
		rc = oidc_response_authorization_error(
		    r, c, proto_state, "Remote user could not be set: contact the website administrator", NULL);
		goto end;
	}

	oidc_debug(r, "set remote_user to \"%s\" in new session \"%s\"", r->user, session->uuid);

	/* For prompt=none, reject a different existing remote user. With no prior user, establish a new session. */
	if ((prompt != NULL) && (_oidc_strcmp(prompt, OIDC_PROTO_PROMPT_NONE) == 0) && (session->remote_user != NULL) &&
	    (_oidc_strcmp(session->remote_user, r->user) != 0)) {
		oidc_warn(r, "user set from new id_token is different from current one");
		rc = oidc_response_authorization_error(r, c, proto_state, "User changed!", NULL);
		goto end;
	}

	/* Reset after checks that need the old session and before storing the new authentication. */
	oidc_session_reset(r, c, session);

	/* Persist per-path settings only when session management may reuse them for silent reauthentication. */
	if (oidc_cfg_provider_check_session_iframe_get(provider) != NULL) {
		oidc_session_set_path_auth_request_params(r, session,
							  oidc_proto_state_get_auth_request_params(proto_state));
		oidc_session_set_path_scope(r, session, oidc_proto_state_get_path_scope(proto_state));
	}

	/* store resolved information in the session */
	if (oidc_response_save_in_session(
		r, c, session, provider, r->user, apr_table_get(params, OIDC_PROTO_ID_TOKEN), id_token,
		s_userinfo_claims, userinfo_claims, apr_table_get(params, OIDC_PROTO_ACCESS_TOKEN),
		apr_table_get(params, OIDC_PROTO_TOKEN_TYPE), expires_in,
		apr_table_get(params, OIDC_PROTO_REFRESH_TOKEN), apr_table_get(params, OIDC_PROTO_SCOPE),
		apr_table_get(params, OIDC_PROTO_SESSION_STATE), apr_table_get(params, OIDC_PROTO_STATE), original_url,
		userinfo_jwt) == FALSE) {
		rc = HTTP_INTERNAL_SERVER_ERROR;
		goto end;
	}

	/* check that we've actually authenticated a user; functions as error handling for oidc_get_remote_user */
	if (r->user == NULL) {
		OIDC_METRICS_COUNTER_INC(r, c, OM_AUTHN_RESPONSE_ERROR_REMOTE_USER);
		rc = HTTP_UNAUTHORIZED;
		goto end;
	}

	rc = oidc_response_finish_success(r, c, original_url, original_method);

end:

	if (proto_state)
		oidc_proto_state_destroy(proto_state);
	if (id_token)
		oidc_jwt_destroy(id_token);
	if (userinfo_claims)
		oidc_json_decref(userinfo_claims);

	return rc;
}

/* specification-defined parameters that must not be repeated in an authorization response */
static const char *const OIDC_RESPONSE_NO_REPEAT[] = {OIDC_PROTO_STATE, OIDC_PROTO_CODE, OIDC_PROTO_ACCESS_TOKEN,
						      OIDC_PROTO_ID_TOKEN, NULL};

/*
 * handle an OpenID Connect Authorization Response using the POST (+fragment->POST) response_mode
 */
int oidc_response_authorization_post(request_rec *r, oidc_cfg_t *c, oidc_session_t *session) {

	oidc_debug(r, "enter");

	/* initialize local variables */
	const char *response_mode = NULL;

	/* read the parameters that are POST-ed to us */
	apr_table_t *params = apr_table_make(r->pool, 8);
	if (oidc_util_read_post_params_reject_dup(r, params, FALSE, NULL, OIDC_RESPONSE_NO_REPEAT) == FALSE) {
		oidc_error(r, "something went wrong when reading the POST parameters");
		return HTTP_BAD_REQUEST;
	}

	/* see if we've got any POST-ed data at all */
	if ((apr_table_elts(params)->nelts < 1) ||
	    ((apr_table_elts(params)->nelts == 1) && apr_table_get(params, OIDC_PROTO_RESPONSE_MODE) &&
	     (_oidc_strcmp(apr_table_get(params, OIDC_PROTO_RESPONSE_MODE), OIDC_PROTO_RESPONSE_MODE_FRAGMENT) == 0))) {
		return oidc_util_html_send_error(
		    r, "Invalid Request",
		    "You've hit an OpenID Connect Redirect URI with no parameters, this is an invalid request; you "
		    "should not open this URL in your browser directly, or have the server administrator use a "
		    "different " OIDCRedirectURI " setting.",
		    HTTP_INTERNAL_SERVER_ERROR);
	}

	/* get the parameters */
	response_mode = apr_table_get(params, OIDC_PROTO_RESPONSE_MODE);

	/* do the actual implicit work */
	return oidc_response_process(r, c, session, params,
				     response_mode ? response_mode : OIDC_PROTO_RESPONSE_MODE_FORM_POST);
}

/*
 * handle an OpenID Connect Authorization Response using the redirect response_mode
 */
int oidc_response_authorization_redirect(request_rec *r, oidc_cfg_t *c, oidc_session_t *session) {

	oidc_debug(r, "enter");

	/* read the parameters from the query string */
	apr_table_t *params = apr_table_make(r->pool, 8);
	if (oidc_util_read_form_encoded_params_reject_dup(r, params, r->args, OIDC_RESPONSE_NO_REPEAT) == FALSE)
		return HTTP_BAD_REQUEST;

	/* do the actual work */
	return oidc_response_process(r, c, session, params, OIDC_PROTO_RESPONSE_MODE_QUERY);
}
