/*
 * Copyright 2004-present the original author or authors.
 *
 * Licensed 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
 *
 *      https://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.
 */

package org.springframework.security.oauth2.client.registration;

import java.net.URI;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Supplier;

import com.nimbusds.oauth2.sdk.ParseException;
import com.nimbusds.oauth2.sdk.as.AuthorizationServerMetadata;
import com.nimbusds.openid.connect.sdk.op.OIDCProviderMetadata;
import net.minidev.json.JSONObject;
import org.jspecify.annotations.Nullable;

import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.RequestEntity;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.security.oauth2.core.AuthorizationGrantType;
import org.springframework.security.oauth2.core.ClientAuthenticationMethod;
import org.springframework.security.oauth2.core.oidc.IdTokenClaimNames;
import org.springframework.util.Assert;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponents;
import org.springframework.web.util.UriComponentsBuilder;

/**
 * Allows creating a {@link ClientRegistration.Builder} from an <a href=
 * "https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderConfig">OpenID
 * Provider Configuration</a> or
 * <a href="https://tools.ietf.org/html/rfc8414#section-3">Authorization Server
 * Metadata</a> based on provided issuer.
 *
 * @author Rob Winch
 * @author Josh Cummings
 * @author Rafiullah Hamedy
 * @author Evgeniy Cheban
 * @since 5.1
 */
public final class ClientRegistrations {

	private static final String OIDC_METADATA_PATH = "/.well-known/openid-configuration";

	private static final String OAUTH_METADATA_PATH = "/.well-known/oauth-authorization-server";

	private static final RestTemplate rest = new RestTemplate();

	static {
		SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
		requestFactory.setConnectTimeout(30_000);
		requestFactory.setReadTimeout(30_000);
		rest.setRequestFactory(requestFactory);
	}

	private static final ParameterizedTypeReference<Map<String, Object>> typeReference = new ParameterizedTypeReference<>() {
	};

	private ClientRegistrations() {
	}

	/**
	 * Creates a {@link ClientRegistration.Builder} using the provided map representation
	 * of an <a href=
	 * "https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderConfigurationResponse">OpenID
	 * Provider Configuration Response</a> to initialize the
	 * {@link ClientRegistration.Builder}.
	 *
	 * <p>
	 * This is useful when the OpenID Provider Configuration is not available at a
	 * well-known location, or if custom validation is needed for the issuer location
	 * (e.g. if the issuer is only accessible from a back-channel URI that is different
	 * from the issuer value in the configuration).
	 * </p>
	 *
	 * <p>
	 * Example usage:
	 * </p>
	 * <pre>
	 * RequestEntity&lt;Void&gt; request = RequestEntity.get(metadataEndpoint).build();
	 * ParameterizedTypeReference&lt;Map&lt;String, Object&gt;&gt; typeReference = new ParameterizedTypeReference&lt;&gt;() {};
	 * Map&lt;String, Object&gt; configuration = rest.exchange(request, typeReference).getBody();
	 * // Validate configuration.get("issuer") as per in the OIDC specification
	 * ClientRegistration registration = ClientRegistrations.fromOidcConfiguration(configuration)
	 *     .clientId("client-id")
	 *     .clientSecret("client-secret")
	 *     .build();
	 * </pre>
	 * @param configuration the OpenID Provider configuration map
	 * @return the {@link ClientRegistration} built from the configuration
	 */
	public static ClientRegistration.Builder fromOidcConfiguration(Map<String, Object> configuration) {
		OIDCProviderMetadata metadata = parseInput(configuration, OIDCProviderMetadata::parse);
		ClientRegistration.Builder builder = withProviderConfiguration(metadata, metadata.getIssuer().getValue());
		builder.jwkSetUri(metadata.getJWKSetURI().toASCIIString());
		if (metadata.getUserInfoEndpointURI() != null) {
			builder.userInfoUri(metadata.getUserInfoEndpointURI().toASCIIString());
		}
		return builder;
	}

	/**
	 * Creates a {@link ClientRegistration.Builder} using the provided <a href=
	 * "https://openid.net/specs/openid-connect-core-1_0.html#IssuerIdentifier">Issuer</a>
	 * by making an <a href=
	 * "https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderConfigurationRequest">OpenID
	 * Provider Configuration Request</a> and using the values in the <a href=
	 * "https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderConfigurationResponse">OpenID
	 * Provider Configuration Response</a> to initialize the
	 * {@link ClientRegistration.Builder}.
	 *
	 * <p>
	 * For example, if the issuer provided is "https://example.com", then an "OpenID
	 * Provider Configuration Request" will be made to
	 * "https://example.com/.well-known/openid-configuration". The result is expected to
	 * be an "OpenID Provider Configuration Response".
	 * </p>
	 *
	 * <p>
	 * Example usage:
	 * </p>
	 * <pre>
	 * ClientRegistration registration = ClientRegistrations.fromOidcIssuerLocation("https://example.com")
	 *     .clientId("client-id")
	 *     .clientSecret("client-secret")
	 *     .build();
	 * </pre>
	 * @param issuer the <a href=
	 * "https://openid.net/specs/openid-connect-core-1_0.html#IssuerIdentifier">Issuer</a>
	 * @return a {@link ClientRegistration.Builder} that was initialized by the OpenID
	 * Provider Configuration.
	 */
	public static ClientRegistration.Builder fromOidcIssuerLocation(String issuer) {
		Assert.hasText(issuer, "issuer cannot be empty");
		return getBuilder(issuer, oidc(issuer));
	}

	/**
	 * Creates a {@link ClientRegistration.Builder} using the provided <a href=
	 * "https://openid.net/specs/openid-connect-core-1_0.html#IssuerIdentifier">Issuer</a>
	 * by querying three different discovery endpoints serially, using the values in the
	 * first successful response to initialize. If an endpoint returns anything other than
	 * a 200 or a 4xx, the method will exit without attempting subsequent endpoints.
	 *
	 * The three endpoints are computed as follows, given that the {@code issuer} is
	 * composed of a {@code host} and a {@code path}:
	 *
	 * <ol>
	 * <li>{@code host/.well-known/openid-configuration/path}, as defined in
	 * <a href="https://tools.ietf.org/html/rfc8414#section-5">RFC 8414's Compatibility
	 * Notes</a>.</li>
	 * <li>{@code issuer/.well-known/openid-configuration}, as defined in <a href=
	 * "https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderConfigurationRequest">
	 * OpenID Provider Configuration</a>.</li>
	 * <li>{@code host/.well-known/oauth-authorization-server/path}, as defined in
	 * <a href="https://tools.ietf.org/html/rfc8414#section-3.1">Authorization Server
	 * Metadata Request</a>.</li>
	 * </ol>
	 *
	 * Note that the second endpoint is the equivalent of calling
	 * {@link ClientRegistrations#fromOidcIssuerLocation(String)}.
	 *
	 * <p>
	 * Example usage:
	 * </p>
	 * <pre>
	 * ClientRegistration registration = ClientRegistrations.fromIssuerLocation("https://example.com")
	 *     .clientId("client-id")
	 *     .clientSecret("client-secret")
	 *     .build();
	 * </pre>
	 * @param issuer
	 * @return a {@link ClientRegistration.Builder} that was initialized by one of the
	 * described endpoints
	 */
	public static ClientRegistration.Builder fromIssuerLocation(String issuer) {
		Assert.hasText(issuer, "issuer cannot be empty");
		return getBuilder(issuer, oidc(issuer), oidcRfc8414(issuer), oauth(issuer));
	}

	static Supplier<ClientRegistration.Builder> oidc(String issuer) {
		UriComponents uri = oidcUri(issuer);
		// @formatter:on
		return () -> {
			RequestEntity<Void> request = RequestEntity.get(uri.toUriString()).build();
			Map<String, Object> configuration = rest.exchange(request, typeReference).getBody();
			Assert.notNull(configuration, "OIDC provider configuration cannot be null");
			OIDCProviderMetadata metadata = parse(configuration, OIDCProviderMetadata::parse);
			ClientRegistration.Builder builder = withProviderConfiguration(metadata, issuer)
				.jwkSetUri(metadata.getJWKSetURI().toASCIIString());
			if (metadata.getUserInfoEndpointURI() != null) {
				builder.userInfoUri(metadata.getUserInfoEndpointURI().toASCIIString());
			}
			return builder;
		};
	}

	static UriComponents oidcUri(String issuer) {
		UriComponents uri = UriComponentsBuilder.fromUriString(issuer).build();
		// @formatter:off
		return UriComponentsBuilder.newInstance().uriComponents(uri)
				.replacePath(uri.getPath() + OIDC_METADATA_PATH)
				.build();
	}

	static Supplier<ClientRegistration.Builder> oidcRfc8414(String issuer) {
		UriComponents uri = oidcRfc8414Uri(issuer);
		// @formatter:on
		return getRfc8414Builder(issuer, uri);
	}

	static UriComponents oidcRfc8414Uri(String issuer) {
		UriComponents uri = UriComponentsBuilder.fromUriString(issuer).build();
		// @formatter:off
		return UriComponentsBuilder.newInstance().uriComponents(uri)
				.replacePath(OIDC_METADATA_PATH + uri.getPath())
				.build();
	}

	static Supplier<ClientRegistration.Builder> oauth(String issuer) {
		UriComponents uri = oauthUri(issuer);
		return getRfc8414Builder(issuer, uri);
	}

	static UriComponents oauthUri(String issuer) {
		UriComponents uri = UriComponentsBuilder.fromUriString(issuer).build();
		// @formatter:off
		return UriComponentsBuilder.newInstance().uriComponents(uri)
				.replacePath(OAUTH_METADATA_PATH + uri.getPath())
				.build();
		// @formatter:on
	}

	private static Supplier<ClientRegistration.Builder> getRfc8414Builder(String issuer, UriComponents uri) {
		return () -> {
			RequestEntity<Void> request = RequestEntity.get(uri.toUriString()).build();
			Map<String, Object> configuration = rest.exchange(request, typeReference).getBody();
			Assert.notNull(configuration, "Authorization server configuration cannot be null");
			AuthorizationServerMetadata metadata = parse(configuration, AuthorizationServerMetadata::parse);
			ClientRegistration.Builder builder = withProviderConfiguration(metadata, issuer);
			URI jwkSetUri = metadata.getJWKSetURI();
			if (jwkSetUri != null) {
				builder.jwkSetUri(jwkSetUri.toASCIIString());
			}
			String userinfoEndpoint = (String) configuration.get("userinfo_endpoint");
			if (userinfoEndpoint != null) {
				builder.userInfoUri(userinfoEndpoint);
			}
			return builder;
		};
	}

	@SafeVarargs
	private static ClientRegistration.Builder getBuilder(String issuer,
			Supplier<ClientRegistration.Builder>... suppliers) {
		String errorMessage = "Unable to resolve Configuration with the provided Issuer of \"" + issuer + "\"";
		List<String> errors = new ArrayList<>();
		for (Supplier<ClientRegistration.Builder> supplier : suppliers) {
			try {
				return supplier.get();
			}
			catch (HttpClientErrorException ex) {
				if (!ex.getStatusCode().is4xxClientError()) {
					throw ex;
				}
				errors.add(ex.getMessage());
				// else try another endpoint
			}
			catch (IllegalArgumentException | IllegalStateException ex) {
				throw ex;
			}
			catch (RuntimeException ex) {
				throw new IllegalArgumentException(errorMessage, ex);
			}
		}
		if (!errors.isEmpty()) {
			throw new IllegalArgumentException(errorMessage + ", errors: " + errors);
		}
		throw new IllegalArgumentException(errorMessage);
	}

	private static <T> T parseInput(Map<String, Object> body, ThrowingFunction<JSONObject, T, ParseException> parser) {
		try {
			return parse(body, parser);
		}
		catch (RuntimeException ex) {
			throw new IllegalArgumentException(ex);
		}
	}

	private static <T> T parse(Map<String, Object> body, ThrowingFunction<JSONObject, T, ParseException> parser) {
		try {
			return parser.apply(new JSONObject(body));
		}
		catch (ParseException ex) {
			throw new RuntimeException(ex);
		}
	}

	private static ClientRegistration.Builder withProviderConfiguration(AuthorizationServerMetadata metadata,
			String issuer) {
		String metadataIssuer = metadata.getIssuer().getValue();
		Assert.state(issuer.equals(metadataIssuer),
				() -> "The Issuer \"" + metadataIssuer + "\" provided in the configuration metadata did "
						+ "not match the requested issuer \"" + issuer + "\"");
		String name = URI.create(issuer).getHost();
		ClientAuthenticationMethod method = getClientAuthenticationMethod(metadata.getTokenEndpointAuthMethods());
		URI authorizationEndpointURI = metadata.getAuthorizationEndpointURI();
		URI tokenEndpointURI = metadata.getTokenEndpointURI();
		ClientAuthenticationMethod authMethod = (method != null) ? method
				: ClientAuthenticationMethod.CLIENT_SECRET_BASIC;
		Map<String, Object> configurationMetadata = new LinkedHashMap<>(metadata.toJSONObject());
		// @formatter:off
		ClientRegistration.Builder builder = ClientRegistration.withRegistrationId(name)
				.userNameAttributeName(IdTokenClaimNames.SUB)
				.authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE)
				.clientAuthenticationMethod(authMethod)
				.redirectUri("{baseUrl}/{action}/oauth2/code/{registrationId}")
				.authorizationUri((authorizationEndpointURI != null) ? authorizationEndpointURI.toASCIIString() : null)
				.providerConfigurationMetadata(configurationMetadata)
				.issuerUri(issuer)
				.clientName(issuer);
		if (tokenEndpointURI != null) {
			builder.tokenUri(tokenEndpointURI.toASCIIString());
		}
		return builder;
		// @formatter:on
	}

	private static @Nullable ClientAuthenticationMethod getClientAuthenticationMethod(
			List<com.nimbusds.oauth2.sdk.auth.ClientAuthenticationMethod> metadataAuthMethods) {
		if (metadataAuthMethods == null || metadataAuthMethods
			.contains(com.nimbusds.oauth2.sdk.auth.ClientAuthenticationMethod.CLIENT_SECRET_BASIC)) {
			// If null, the default includes client_secret_basic
			return ClientAuthenticationMethod.CLIENT_SECRET_BASIC;
		}
		if (metadataAuthMethods.contains(com.nimbusds.oauth2.sdk.auth.ClientAuthenticationMethod.CLIENT_SECRET_POST)) {
			return ClientAuthenticationMethod.CLIENT_SECRET_POST;
		}
		if (metadataAuthMethods.contains(com.nimbusds.oauth2.sdk.auth.ClientAuthenticationMethod.NONE)) {
			return ClientAuthenticationMethod.NONE;
		}
		return null;
	}

	private interface ThrowingFunction<S, T, E extends Throwable> {

		T apply(S src) throws E;

	}

}
