mirror of
https://github.com/floci-io/floci.git
synced 2026-11-23 22:11:36 -05:00
feat(cognito): implement federated sign-in (#3748)
* feat(cognito): add federation transaction stores * fix(cognito): atomically consume federation state * feat(cognito): support OIDC provider exchange * fix(cognito): validate OIDC federation providers * fix(cognito): validate OIDC endpoint schemes * feat(cognito): add federated oauth routes * fix(cognito): preserve oauth state and codes * feat(cognito): implement federated sign-in coverage * chore: remove internal task report * fix(cognito): use Cognito IdP callback for federation * fix(cognito): use provider callback for token exchange
This commit is contained in:
1 parent
d0d787d8a3
commit
f004aeaad5
17 files changed
+1952
-27
No files matched your search
+2
-1
@@ -16,7 +16,8 @@ import java.util.Optional;
|
||||
|
||||
/**
|
||||
* Routes Cognito custom-domain requests by Host. On AWS a custom domain serves
|
||||
* {@code https://<domain>/oauth2/token} and {@code /oauth2/userInfo}; Floci maps those onto
|
||||
* {@code https://<domain>/oauth2/token}, {@code /oauth2/userInfo}, {@code /oauth2/authorize}, and
|
||||
* {@code /oauth2/idpresponse}; Floci maps those onto
|
||||
* the {@code /cognito-idp/oauth2/...} handlers and pins the pool and the account that own the
|
||||
* domain, since the request itself carries no AWS credential.
|
||||
*/
|
||||
|
||||
+172
@@ -0,0 +1,172 @@
|
||||
package io.github.hectorvent.floci.services.cognito;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.services.cognito.model.CognitoAuthorizationCode;
|
||||
import io.github.hectorvent.floci.services.cognito.model.CognitoAuthorizationTransaction;
|
||||
import io.github.hectorvent.floci.services.cognito.model.CognitoUser;
|
||||
import io.github.hectorvent.floci.services.cognito.model.IdentityProvider;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
|
||||
import java.net.URI;
|
||||
import java.net.URLEncoder;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.Clock;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
@ApplicationScoped
|
||||
public class CognitoFederationService {
|
||||
|
||||
private static final Duration TRANSACTION_LIFETIME = Duration.ofMinutes(5);
|
||||
private static final Duration AUTHORIZATION_CODE_LIFETIME = Duration.ofMinutes(5);
|
||||
private static final String OIDC_PROVIDER_TYPE = "OIDC";
|
||||
|
||||
private final CognitoService cognitoService;
|
||||
private final CognitoFederationStateStore stateStore;
|
||||
private final CognitoOidcClient oidcClient;
|
||||
private final Clock clock;
|
||||
|
||||
@Inject
|
||||
public CognitoFederationService(CognitoService cognitoService, CognitoFederationStateStore stateStore,
|
||||
CognitoOidcClient oidcClient, Clock clock) {
|
||||
this.cognitoService = cognitoService;
|
||||
this.stateStore = stateStore;
|
||||
this.oidcClient = oidcClient;
|
||||
this.clock = clock;
|
||||
}
|
||||
|
||||
public String beginAuthorization(String userPoolId, String clientId, String redirectUri, List<String> scopes,
|
||||
String nonce, String providerName) {
|
||||
return beginAuthorization(userPoolId, clientId, redirectUri, scopes, nonce, providerName, null);
|
||||
}
|
||||
|
||||
public String beginAuthorization(String userPoolId, String clientId, String redirectUri, List<String> scopes,
|
||||
String nonce, String providerName, String relyingPartyState) {
|
||||
IdentityProvider provider = cognitoService.describeIdentityProvider(userPoolId, providerName);
|
||||
requireOidcProvider(provider);
|
||||
String authorizeEndpoint = requiredProviderDetail(provider, "authorize_url", "authorize endpoint");
|
||||
String providerClientId = requiredProviderDetail(provider, "client_id", "client_id");
|
||||
validateAuthorizeEndpoint(authorizeEndpoint, provider.getProviderName());
|
||||
Instant expiresAt = clock.instant().plus(TRANSACTION_LIFETIME);
|
||||
CognitoAuthorizationTransaction transaction = new CognitoAuthorizationTransaction(
|
||||
userPoolId, clientId, redirectUri, scopes, nonce, providerName, relyingPartyState, expiresAt);
|
||||
String state = stateStore.putTransaction(transaction);
|
||||
|
||||
Map<String, String> parameters = new LinkedHashMap<>();
|
||||
parameters.put("response_type", "code");
|
||||
parameters.put("client_id", providerClientId);
|
||||
parameters.put("redirect_uri", cognitoService.getIdentityProviderCallbackEndpoint(userPoolId));
|
||||
parameters.put("scope", providerScopes(provider, scopes));
|
||||
parameters.put("state", state);
|
||||
if (nonce != null && !nonce.isBlank()) {
|
||||
parameters.put("nonce", nonce);
|
||||
}
|
||||
return appendQuery(authorizeEndpoint, parameters);
|
||||
}
|
||||
|
||||
public String completeAuthorization(String state, String providerCode) {
|
||||
CognitoAuthorizationTransaction transaction = stateStore.consumeTransaction(state)
|
||||
.orElseThrow(() -> new AwsException("InvalidParameterException", "Invalid federation state", 400));
|
||||
return completeAuthorization(transaction, providerCode);
|
||||
}
|
||||
|
||||
String completeAuthorization(CognitoAuthorizationTransaction transaction, String providerCode) {
|
||||
IdentityProvider provider = cognitoService.describeIdentityProvider(
|
||||
transaction.userPoolId(), transaction.providerName());
|
||||
requireOidcProvider(provider);
|
||||
String providerCallback = cognitoService.getIdentityProviderCallbackEndpoint(transaction.userPoolId());
|
||||
JsonNode tokenResponse = oidcClient.exchangeCode(provider, providerCode, providerCallback);
|
||||
String accessToken = requiredText(tokenResponse, "access_token", "access token");
|
||||
JsonNode claims = oidcClient.fetchClaims(provider, accessToken);
|
||||
String subject = requiredText(claims, "sub", "subject");
|
||||
String issuer = optionalText(claims, "iss");
|
||||
CognitoUser user = cognitoService.provisionFederatedUser(transaction.userPoolId(), provider,
|
||||
subject, issuer, mapAttributes(provider, claims));
|
||||
CognitoAuthorizationCode authorizationCode = new CognitoAuthorizationCode(
|
||||
transaction.userPoolId(), transaction.clientId(), user.getUsername(), transaction.redirectUri(),
|
||||
transaction.scopes(), clock.instant().plus(AUTHORIZATION_CODE_LIFETIME));
|
||||
return stateStore.putAuthorizationCode(authorizationCode);
|
||||
}
|
||||
|
||||
private Map<String, String> mapAttributes(IdentityProvider provider, JsonNode claims) {
|
||||
Map<String, String> attributes = new LinkedHashMap<>();
|
||||
for (Map.Entry<String, String> mapping : provider.getAttributeMapping().entrySet()) {
|
||||
JsonNode claim = claims.get(mapping.getValue());
|
||||
if (claim != null && !claim.isNull() && claim.isValueNode()) {
|
||||
attributes.put(mapping.getKey(), claim.asText());
|
||||
}
|
||||
}
|
||||
return attributes;
|
||||
}
|
||||
|
||||
private String providerScopes(IdentityProvider provider, List<String> scopes) {
|
||||
String configuredScopes = provider.getProviderDetails().get("authorize_scopes");
|
||||
return configuredScopes != null && !configuredScopes.isBlank()
|
||||
? configuredScopes : String.join(" ", scopes);
|
||||
}
|
||||
|
||||
private String requiredText(JsonNode json, String fieldName, String description) {
|
||||
String value = optionalText(json, fieldName);
|
||||
if (value == null) {
|
||||
throw new AwsException("InvalidParameterException", "Identity provider response is missing " + description, 400);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
private String optionalText(JsonNode json, String fieldName) {
|
||||
JsonNode value = json.get(fieldName);
|
||||
if (value == null || value.isNull() || !value.isValueNode() || value.asText().isBlank()) {
|
||||
return null;
|
||||
}
|
||||
return value.asText();
|
||||
}
|
||||
|
||||
private String requiredProviderDetail(IdentityProvider provider, String detailName, String description) {
|
||||
String value = provider.getProviderDetails().get(detailName);
|
||||
if (value == null || value.isBlank()) {
|
||||
throw new AwsException("InvalidParameterException", "Identity provider " + provider.getProviderName()
|
||||
+ " does not have a " + description + " configured", 400);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
private void requireOidcProvider(IdentityProvider provider) {
|
||||
if (!OIDC_PROVIDER_TYPE.equals(provider.getProviderType())) {
|
||||
throw new AwsException("InvalidParameterException", "Identity provider " + provider.getProviderName()
|
||||
+ " must have ProviderType OIDC", 400);
|
||||
}
|
||||
}
|
||||
|
||||
private void validateAuthorizeEndpoint(String endpoint, String providerName) {
|
||||
try {
|
||||
URI uri = URI.create(endpoint);
|
||||
if (!uri.isAbsolute()) {
|
||||
throw new IllegalArgumentException("URI must be absolute");
|
||||
}
|
||||
} catch (IllegalArgumentException e) {
|
||||
throw new AwsException("InvalidParameterException", "Identity provider " + providerName
|
||||
+ " has an invalid authorize endpoint", 400);
|
||||
}
|
||||
}
|
||||
|
||||
private String appendQuery(String endpoint, Map<String, String> parameters) {
|
||||
StringBuilder result = new StringBuilder(endpoint);
|
||||
result.append(endpoint.contains("?") ? '&' : '?');
|
||||
boolean first = true;
|
||||
for (Map.Entry<String, String> parameter : parameters.entrySet()) {
|
||||
if (!first) {
|
||||
result.append('&');
|
||||
}
|
||||
result.append(URLEncoder.encode(parameter.getKey(), StandardCharsets.UTF_8));
|
||||
result.append('=');
|
||||
result.append(URLEncoder.encode(parameter.getValue(), StandardCharsets.UTF_8));
|
||||
first = false;
|
||||
}
|
||||
return result.toString();
|
||||
}
|
||||
}
|
||||
+87
@@ -0,0 +1,87 @@
|
||||
package io.github.hectorvent.floci.services.cognito;
|
||||
|
||||
import io.github.hectorvent.floci.services.cognito.model.CognitoAuthorizationCode;
|
||||
import io.github.hectorvent.floci.services.cognito.model.CognitoAuthorizationTransaction;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
|
||||
import java.security.SecureRandom;
|
||||
import java.time.Clock;
|
||||
import java.time.Instant;
|
||||
import java.util.Base64;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
import java.util.function.Function;
|
||||
|
||||
@ApplicationScoped
|
||||
public class CognitoFederationStateStore {
|
||||
|
||||
private static final int OPAQUE_KEY_BYTES = 32;
|
||||
|
||||
private final ConcurrentHashMap<String, CognitoAuthorizationTransaction> transactions = new ConcurrentHashMap<>();
|
||||
private final ConcurrentHashMap<String, CognitoAuthorizationCode> authorizationCodes = new ConcurrentHashMap<>();
|
||||
private final Clock clock;
|
||||
private final SecureRandom secureRandom = new SecureRandom();
|
||||
|
||||
public CognitoFederationStateStore(Clock clock) {
|
||||
this.clock = clock;
|
||||
}
|
||||
|
||||
public String putTransaction(CognitoAuthorizationTransaction transaction) {
|
||||
return put(transactions, transaction);
|
||||
}
|
||||
|
||||
public Optional<CognitoAuthorizationTransaction> consumeTransaction(String state) {
|
||||
return consume(transactions, state, CognitoAuthorizationTransaction::expiresAt);
|
||||
}
|
||||
|
||||
public String putAuthorizationCode(CognitoAuthorizationCode authorizationCode) {
|
||||
return put(authorizationCodes, authorizationCode);
|
||||
}
|
||||
|
||||
public Optional<CognitoAuthorizationCode> consumeAuthorizationCode(String code) {
|
||||
return consume(authorizationCodes, code, CognitoAuthorizationCode::expiresAt);
|
||||
}
|
||||
|
||||
public Optional<CognitoAuthorizationCode> findAuthorizationCode(String code) {
|
||||
CognitoAuthorizationCode authorizationCode = authorizationCodes.get(code);
|
||||
if (authorizationCode == null) {
|
||||
return Optional.empty();
|
||||
}
|
||||
if (isExpired(authorizationCode.expiresAt())) {
|
||||
authorizationCodes.remove(code, authorizationCode);
|
||||
return Optional.empty();
|
||||
}
|
||||
return Optional.of(authorizationCode);
|
||||
}
|
||||
|
||||
private <T> String put(ConcurrentHashMap<String, T> store, T value) {
|
||||
String key;
|
||||
do {
|
||||
key = generateOpaqueKey();
|
||||
} while (store.putIfAbsent(key, value) != null);
|
||||
return key;
|
||||
}
|
||||
|
||||
private <T> Optional<T> consume(ConcurrentHashMap<String, T> store, String key,
|
||||
Function<T, Instant> expiresAt) {
|
||||
AtomicReference<T> consumed = new AtomicReference<>();
|
||||
store.computeIfPresent(key, (ignored, value) -> {
|
||||
if (!isExpired(expiresAt.apply(value))) {
|
||||
consumed.set(value);
|
||||
}
|
||||
return null;
|
||||
});
|
||||
return Optional.ofNullable(consumed.get());
|
||||
}
|
||||
|
||||
private boolean isExpired(Instant expiresAt) {
|
||||
return !expiresAt.isAfter(clock.instant());
|
||||
}
|
||||
|
||||
private String generateOpaqueKey() {
|
||||
byte[] bytes = new byte[OPAQUE_KEY_BYTES];
|
||||
secureRandom.nextBytes(bytes);
|
||||
return Base64.getUrlEncoder().withoutPadding().encodeToString(bytes);
|
||||
}
|
||||
}
|
||||
+204
-6
@@ -3,12 +3,19 @@ package io.github.hectorvent.floci.services.cognito;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.services.cognito.model.CognitoAuthorizationCode;
|
||||
import io.github.hectorvent.floci.services.cognito.model.CognitoAuthorizationTransaction;
|
||||
import io.github.hectorvent.floci.services.cognito.model.CognitoUser;
|
||||
import io.github.hectorvent.floci.services.cognito.model.UserPool;
|
||||
import io.github.hectorvent.floci.services.cognito.model.UserPoolClient;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
import jakarta.ws.rs.Consumes;
|
||||
import jakarta.ws.rs.GET;
|
||||
import jakarta.ws.rs.HeaderParam;
|
||||
import jakarta.ws.rs.POST;
|
||||
import jakarta.ws.rs.Path;
|
||||
import jakarta.ws.rs.QueryParam;
|
||||
import jakarta.ws.rs.Produces;
|
||||
import jakarta.ws.rs.container.ContainerRequestContext;
|
||||
import jakarta.ws.rs.core.Context;
|
||||
@@ -17,9 +24,16 @@ import jakarta.ws.rs.core.MultivaluedMap;
|
||||
import jakarta.ws.rs.core.Response;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.net.URI;
|
||||
import java.net.URLEncoder;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.MessageDigest;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Base64;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
|
||||
@ApplicationScoped
|
||||
@Path("/")
|
||||
@@ -30,11 +44,100 @@ public class CognitoOAuthController {
|
||||
|
||||
private final CognitoService cognitoService;
|
||||
private final ObjectMapper objectMapper;
|
||||
private final CognitoFederationService federationService;
|
||||
private final CognitoFederationStateStore stateStore;
|
||||
|
||||
@Inject
|
||||
public CognitoOAuthController(CognitoService cognitoService, ObjectMapper objectMapper) {
|
||||
public CognitoOAuthController(CognitoService cognitoService, ObjectMapper objectMapper,
|
||||
CognitoFederationService federationService,
|
||||
CognitoFederationStateStore stateStore) {
|
||||
this.cognitoService = cognitoService;
|
||||
this.objectMapper = objectMapper;
|
||||
this.federationService = federationService;
|
||||
this.stateStore = stateStore;
|
||||
}
|
||||
|
||||
@GET
|
||||
@Path("/cognito-idp/oauth2/authorize")
|
||||
public Response authorize(@Context ContainerRequestContext requestContext,
|
||||
@QueryParam("client_id") String clientId,
|
||||
@QueryParam("redirect_uri") String redirectUri,
|
||||
@QueryParam("response_type") String responseType,
|
||||
@QueryParam("scope") String scope,
|
||||
@QueryParam("nonce") String nonce,
|
||||
@QueryParam("identity_provider") String providerName,
|
||||
@QueryParam("state") String relyingPartyState) {
|
||||
if (!"code".equals(trimToNull(responseType))) {
|
||||
return oauthError("unsupported_response_type", "Only response_type=code is supported");
|
||||
}
|
||||
if (trimToNull(clientId) == null || trimToNull(redirectUri) == null || trimToNull(providerName) == null) {
|
||||
return oauthError("invalid_request", "client_id, redirect_uri, and identity_provider are required");
|
||||
}
|
||||
|
||||
UserPoolClient client;
|
||||
try {
|
||||
client = cognitoService.findClientById(clientId);
|
||||
} catch (AwsException e) {
|
||||
return oauthError("invalid_client", "Client not found");
|
||||
}
|
||||
String domainPoolId = (String) requestContext.getProperty(CognitoCustomDomainFilter.POOL_PROPERTY);
|
||||
if (domainPoolId != null && !domainPoolId.equals(client.getUserPoolId())) {
|
||||
return oauthError("invalid_client", "Client not found");
|
||||
}
|
||||
if (!client.isAllowedOAuthFlowsUserPoolClient() || !client.getAllowedOAuthFlows().contains("code")) {
|
||||
return oauthError("unauthorized_client", "Client is not allowed to use the authorization code flow");
|
||||
}
|
||||
if (!client.getCallbackURLs().contains(redirectUri)) {
|
||||
return oauthError("invalid_request", "redirect_uri is not registered for this client");
|
||||
}
|
||||
|
||||
try {
|
||||
String location = federationService.beginAuthorization(client.getUserPoolId(), clientId, redirectUri,
|
||||
splitScopes(scope), trimToNull(nonce), providerName, relyingPartyState);
|
||||
return Response.status(Response.Status.FOUND).location(URI.create(location)).build();
|
||||
} catch (AwsException e) {
|
||||
return oauthError("invalid_request", e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
@GET
|
||||
@Path("/cognito-idp/oauth2/idpresponse")
|
||||
public Response idpResponse(@Context ContainerRequestContext requestContext,
|
||||
@QueryParam("state") String state,
|
||||
@QueryParam("code") String providerCode,
|
||||
@QueryParam("error") String error,
|
||||
@QueryParam("error_description") String errorDescription) {
|
||||
String normalizedState = trimToNull(state);
|
||||
if (normalizedState == null) {
|
||||
return oauthError("invalid_request", "state is required");
|
||||
}
|
||||
Optional<CognitoAuthorizationTransaction> transaction = stateStore.consumeTransaction(normalizedState);
|
||||
if (transaction.isEmpty()) {
|
||||
return oauthError("invalid_request", "Invalid federation state");
|
||||
}
|
||||
String domainPoolId = (String) requestContext.getProperty(CognitoCustomDomainFilter.POOL_PROPERTY);
|
||||
if (domainPoolId != null && !domainPoolId.equals(transaction.get().userPoolId())) {
|
||||
return oauthError("invalid_request", "Invalid federation state");
|
||||
}
|
||||
if (trimToNull(error) != null) {
|
||||
Map<String, String> errorParameters = new LinkedHashMap<>();
|
||||
errorParameters.put("error", error);
|
||||
errorParameters.put("error_description", errorDescription == null ? "" : errorDescription);
|
||||
putRelyingPartyState(errorParameters, transaction.get());
|
||||
return redirect(transaction.get().redirectUri(), errorParameters);
|
||||
}
|
||||
if (trimToNull(providerCode) == null) {
|
||||
return oauthError("invalid_request", "code is required");
|
||||
}
|
||||
try {
|
||||
String authorizationCode = federationService.completeAuthorization(transaction.get(), providerCode);
|
||||
Map<String, String> parameters = new LinkedHashMap<>();
|
||||
parameters.put("code", authorizationCode);
|
||||
putRelyingPartyState(parameters, transaction.get());
|
||||
return redirect(transaction.get().redirectUri(), parameters);
|
||||
} catch (AwsException e) {
|
||||
return oauthError("invalid_request", e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
@POST
|
||||
@@ -53,10 +156,6 @@ public class CognitoOAuthController {
|
||||
if (grantType == null) {
|
||||
return oauthError("invalid_request", "grant_type is required");
|
||||
}
|
||||
if (!"client_credentials".equals(grantType)) {
|
||||
return oauthError("unsupported_grant_type", "Only client_credentials is supported");
|
||||
}
|
||||
|
||||
BasicCredentials basicCredentials;
|
||||
try {
|
||||
basicCredentials = parseBasicCredentials(authorization);
|
||||
@@ -69,7 +168,7 @@ public class CognitoOAuthController {
|
||||
String basicClientId = basicCredentials != null ? basicCredentials.clientId() : null;
|
||||
String basicClientSecret = basicCredentials != null ? basicCredentials.clientSecret() : null;
|
||||
|
||||
if (bodyClientSecret != null && basicClientSecret != null && !bodyClientSecret.equals(basicClientSecret)) {
|
||||
if (bodyClientSecret != null && basicClientSecret != null && !secretsEqual(bodyClientSecret, basicClientSecret)) {
|
||||
return oauthError("invalid_request", "client_secret does not match Authorization header");
|
||||
}
|
||||
|
||||
@@ -83,6 +182,12 @@ public class CognitoOAuthController {
|
||||
}
|
||||
|
||||
String clientSecret = bodyClientSecret != null ? bodyClientSecret : basicClientSecret;
|
||||
if ("authorization_code".equals(grantType)) {
|
||||
return redeemAuthorizationCode(clientId, clientSecret, formParams, domainPoolId);
|
||||
}
|
||||
if (!"client_credentials".equals(grantType)) {
|
||||
return oauthError("unsupported_grant_type", "Only client_credentials and authorization_code are supported");
|
||||
}
|
||||
String scope = trimToNull(formParams.getFirst("scope"));
|
||||
|
||||
try {
|
||||
@@ -111,6 +216,99 @@ public class CognitoOAuthController {
|
||||
}
|
||||
}
|
||||
|
||||
private Response redeemAuthorizationCode(String clientId, String clientSecret,
|
||||
MultivaluedMap<String, String> formParams, String domainPoolId) {
|
||||
String code = trimToNull(formParams.getFirst("code"));
|
||||
String redirectUri = trimToNull(formParams.getFirst("redirect_uri"));
|
||||
if (code == null || redirectUri == null) {
|
||||
return oauthError("invalid_request", "code and redirect_uri are required");
|
||||
}
|
||||
UserPoolClient client;
|
||||
try {
|
||||
client = cognitoService.findClientById(clientId);
|
||||
} catch (AwsException e) {
|
||||
return oauthError("invalid_client", "Client not found");
|
||||
}
|
||||
if (client.getClientSecret() != null && !client.getClientSecret().isBlank()
|
||||
&& !secretsEqual(client.getClientSecret(), clientSecret)) {
|
||||
return oauthError("invalid_client", "Client secret is invalid");
|
||||
}
|
||||
|
||||
Optional<CognitoAuthorizationCode> authorizationCode = stateStore.findAuthorizationCode(code);
|
||||
if (authorizationCode.isEmpty()) {
|
||||
return oauthError("invalid_grant", "Authorization code is invalid or has expired");
|
||||
}
|
||||
CognitoAuthorizationCode storedCode = authorizationCode.get();
|
||||
if (!clientId.equals(storedCode.clientId()) || !redirectUri.equals(storedCode.redirectUri())
|
||||
|| (domainPoolId != null && !domainPoolId.equals(storedCode.userPoolId()))
|
||||
|| !storedCode.userPoolId().equals(client.getUserPoolId())) {
|
||||
return oauthError("invalid_grant", "Authorization code was not issued to this client");
|
||||
}
|
||||
Optional<CognitoAuthorizationCode> consumed = stateStore.consumeAuthorizationCode(code);
|
||||
if (consumed.isEmpty()) {
|
||||
return oauthError("invalid_grant", "Authorization code is invalid or has expired");
|
||||
}
|
||||
CognitoAuthorizationCode consumedCode = consumed.get();
|
||||
try {
|
||||
UserPool pool = cognitoService.describeUserPool(consumedCode.userPoolId());
|
||||
CognitoUser user = cognitoService.adminGetUser(consumedCode.userPoolId(), consumedCode.userId());
|
||||
Map<String, Object> authentication = cognitoService.generateAuthResult(user, pool, client, null);
|
||||
ObjectNode body = objectMapper.createObjectNode();
|
||||
body.put("access_token", (String) authentication.get("AccessToken"));
|
||||
body.put("id_token", (String) authentication.get("IdToken"));
|
||||
body.put("refresh_token", (String) authentication.get("RefreshToken"));
|
||||
body.put("expires_in", ((Number) authentication.get("ExpiresIn")).longValue());
|
||||
body.put("token_type", (String) authentication.get("TokenType"));
|
||||
return Response.ok(body).type(MediaType.APPLICATION_JSON)
|
||||
.header("Cache-Control", "no-store").header("Pragma", "no-cache").build();
|
||||
} catch (AwsException e) {
|
||||
LOG.error("Failed to redeem Cognito authorization code", e);
|
||||
return oauthError("invalid_grant", e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
private Response redirect(String redirectUri, Map<String, String> parameters) {
|
||||
StringBuilder location = new StringBuilder(redirectUri);
|
||||
location.append(redirectUri.contains("?") ? '&' : '?');
|
||||
boolean first = true;
|
||||
for (Map.Entry<String, String> parameter : parameters.entrySet()) {
|
||||
if (!first) {
|
||||
location.append('&');
|
||||
}
|
||||
location.append(URLEncoder.encode(parameter.getKey(), StandardCharsets.UTF_8));
|
||||
location.append('=').append(URLEncoder.encode(parameter.getValue(), StandardCharsets.UTF_8));
|
||||
first = false;
|
||||
}
|
||||
return Response.status(Response.Status.FOUND).location(URI.create(location.toString())).build();
|
||||
}
|
||||
|
||||
private boolean secretsEqual(String expected, String actual) {
|
||||
if (expected == null || actual == null) {
|
||||
return expected == actual;
|
||||
}
|
||||
return MessageDigest.isEqual(expected.getBytes(StandardCharsets.UTF_8), actual.getBytes(StandardCharsets.UTF_8));
|
||||
}
|
||||
|
||||
private void putRelyingPartyState(Map<String, String> parameters, CognitoAuthorizationTransaction transaction) {
|
||||
if (transaction.relyingPartyState() != null) {
|
||||
parameters.put("state", transaction.relyingPartyState());
|
||||
}
|
||||
}
|
||||
|
||||
private List<String> splitScopes(String scope) {
|
||||
String normalizedScope = trimToNull(scope);
|
||||
if (normalizedScope == null) {
|
||||
return List.of();
|
||||
}
|
||||
List<String> scopes = new ArrayList<>();
|
||||
for (String value : normalizedScope.split("\\s+")) {
|
||||
if (!value.isBlank()) {
|
||||
scopes.add(value);
|
||||
}
|
||||
}
|
||||
return scopes;
|
||||
}
|
||||
|
||||
private Response oauthError(String error, String description) {
|
||||
ObjectNode body = objectMapper.createObjectNode();
|
||||
body.put("error", error);
|
||||
|
||||
@@ -0,0 +1,140 @@
|
||||
package io.github.hectorvent.floci.services.cognito;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.services.cognito.model.IdentityProvider;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.URI;
|
||||
import java.net.URLEncoder;
|
||||
import java.net.http.HttpClient;
|
||||
import java.net.http.HttpRequest;
|
||||
import java.net.http.HttpResponse;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.Duration;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
import java.util.function.Function;
|
||||
|
||||
@ApplicationScoped
|
||||
public class CognitoOidcClient {
|
||||
|
||||
private static final Duration CONNECT_TIMEOUT = Duration.ofSeconds(10);
|
||||
private static final Duration REQUEST_TIMEOUT = Duration.ofSeconds(15);
|
||||
|
||||
private final HttpClient httpClient;
|
||||
private final ObjectMapper objectMapper;
|
||||
|
||||
@Inject
|
||||
public CognitoOidcClient(ObjectMapper objectMapper) {
|
||||
this(HttpClient.newBuilder().connectTimeout(CONNECT_TIMEOUT).build(), objectMapper);
|
||||
}
|
||||
|
||||
CognitoOidcClient(HttpClient httpClient, ObjectMapper objectMapper) {
|
||||
this.httpClient = httpClient;
|
||||
this.objectMapper = objectMapper;
|
||||
}
|
||||
|
||||
public JsonNode exchangeCode(IdentityProvider provider, String code, String redirectUri) {
|
||||
String tokenEndpoint = requiredEndpoint(provider, "token_url", "token");
|
||||
Map<String, String> form = new LinkedHashMap<>();
|
||||
form.put("grant_type", "authorization_code");
|
||||
form.put("client_id", requiredProviderDetail(provider, "client_id"));
|
||||
String clientSecret = provider.getProviderDetails().get("client_secret");
|
||||
if (clientSecret != null && !clientSecret.isBlank()) {
|
||||
form.put("client_secret", clientSecret);
|
||||
}
|
||||
form.put("code", code);
|
||||
form.put("redirect_uri", redirectUri);
|
||||
|
||||
HttpRequest request = buildRequest(tokenEndpoint, provider.getProviderName(), "token", builder -> builder
|
||||
.header("Accept", "application/json")
|
||||
.header("Content-Type", "application/x-www-form-urlencoded")
|
||||
.POST(HttpRequest.BodyPublishers.ofString(formEncode(form)))
|
||||
.build());
|
||||
return send(request, "token exchange");
|
||||
}
|
||||
|
||||
public JsonNode fetchClaims(IdentityProvider provider, String accessToken) {
|
||||
String claimsEndpoint = requiredEndpoint(provider, "attributes_url", "claims");
|
||||
if (accessToken == null || accessToken.isBlank()) {
|
||||
throw new AwsException("NotAuthorizedException", "Identity provider did not return an access token", 400);
|
||||
}
|
||||
|
||||
HttpRequest request = buildRequest(claimsEndpoint, provider.getProviderName(), "claims", builder -> builder
|
||||
.header("Accept", "application/json")
|
||||
.header("Authorization", "Bearer " + accessToken)
|
||||
.GET()
|
||||
.build());
|
||||
return send(request, "claims request");
|
||||
}
|
||||
|
||||
private JsonNode send(HttpRequest request, String operation) {
|
||||
try {
|
||||
HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
|
||||
if (response.statusCode() < 200 || response.statusCode() >= 300) {
|
||||
throw new AwsException("NotAuthorizedException", "Identity provider " + operation + " failed", 400);
|
||||
}
|
||||
JsonNode responseJson = objectMapper.readTree(response.body());
|
||||
if (responseJson == null || !responseJson.isObject()) {
|
||||
throw new AwsException("NotAuthorizedException", "Identity provider " + operation
|
||||
+ " returned an invalid response", 400);
|
||||
}
|
||||
return responseJson;
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
throw new AwsException("NotAuthorizedException", "Identity provider " + operation + " was interrupted", 400);
|
||||
} catch (IOException | IllegalArgumentException e) {
|
||||
throw new AwsException("NotAuthorizedException", "Identity provider " + operation + " failed", 400);
|
||||
}
|
||||
}
|
||||
|
||||
private String requiredEndpoint(IdentityProvider provider, String detailName, String endpointName) {
|
||||
String endpoint = provider.getProviderDetails().get(detailName);
|
||||
if (endpoint == null || endpoint.isBlank()) {
|
||||
throw new AwsException("InvalidParameterException", "Identity provider " + provider.getProviderName()
|
||||
+ " does not have a " + endpointName + " endpoint configured", 400);
|
||||
}
|
||||
return endpoint;
|
||||
}
|
||||
|
||||
private HttpRequest buildRequest(String endpoint, String providerName, String endpointName,
|
||||
Function<HttpRequest.Builder, HttpRequest> requestFactory) {
|
||||
try {
|
||||
URI uri = URI.create(endpoint);
|
||||
if (!"http".equalsIgnoreCase(uri.getScheme()) && !"https".equalsIgnoreCase(uri.getScheme())) {
|
||||
throw new IllegalArgumentException("Unsupported URI scheme");
|
||||
}
|
||||
HttpRequest.Builder builder = HttpRequest.newBuilder(uri).timeout(REQUEST_TIMEOUT);
|
||||
return requestFactory.apply(builder);
|
||||
} catch (IllegalArgumentException e) {
|
||||
throw new AwsException("InvalidParameterException", "Identity provider " + providerName
|
||||
+ " has an invalid " + endpointName + " endpoint", 400);
|
||||
}
|
||||
}
|
||||
|
||||
private String requiredProviderDetail(IdentityProvider provider, String detailName) {
|
||||
String value = provider.getProviderDetails().get(detailName);
|
||||
if (value == null || value.isBlank()) {
|
||||
throw new AwsException("InvalidParameterException", "Identity provider " + provider.getProviderName()
|
||||
+ " does not have " + detailName + " configured", 400);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
private String formEncode(Map<String, String> form) {
|
||||
StringBuilder encoded = new StringBuilder();
|
||||
for (Map.Entry<String, String> entry : form.entrySet()) {
|
||||
if (!encoded.isEmpty()) {
|
||||
encoded.append('&');
|
||||
}
|
||||
encoded.append(URLEncoder.encode(entry.getKey(), StandardCharsets.UTF_8));
|
||||
encoded.append('=');
|
||||
encoded.append(URLEncoder.encode(entry.getValue(), StandardCharsets.UTF_8));
|
||||
}
|
||||
return encoded.toString();
|
||||
}
|
||||
}
|
||||
@@ -2034,6 +2034,59 @@ public class CognitoService implements ResourceProvider {
|
||||
return MAPPER.createArrayNode();
|
||||
}
|
||||
|
||||
public Optional<CognitoUser> findFederatedUser(String userPoolId, String providerName, String subject) {
|
||||
describeUserPool(userPoolId);
|
||||
String prefix = userPoolId + "::";
|
||||
return userStore.scan(key -> key.startsWith(prefix)).stream()
|
||||
.filter(user -> providerName.equals(user.getFederatedProviderName())
|
||||
&& subject.equals(user.getFederatedSubject()))
|
||||
.findFirst();
|
||||
}
|
||||
|
||||
public CognitoUser provisionFederatedUser(String userPoolId, IdentityProvider provider, String subject,
|
||||
String issuer, Map<String, String> mappedAttributes) {
|
||||
describeUserPool(userPoolId);
|
||||
synchronized (identityLinkLock) {
|
||||
CognitoUser user = findFederatedUser(userPoolId, provider.getProviderName(), subject).orElse(null);
|
||||
if (user == null) {
|
||||
user = new CognitoUser();
|
||||
user.setUsername(provider.getProviderName() + "_" + UUID.randomUUID());
|
||||
user.setUserPoolId(userPoolId);
|
||||
user.getAttributes().put("sub", UUID.randomUUID().toString());
|
||||
}
|
||||
user.getAttributes().putAll(mappedAttributes);
|
||||
user.setFederatedProviderName(provider.getProviderName());
|
||||
user.setFederatedSubject(subject);
|
||||
updateFederatedIdentity(user, provider, subject, issuer);
|
||||
user.setEnabled(true);
|
||||
user.setUserStatus("CONFIRMED");
|
||||
user.setLastModifiedDate(System.currentTimeMillis() / 1000L);
|
||||
userStore.put(userKey(userPoolId, user.getUsername()), user);
|
||||
LOG.infov("Reconciled federated user {0} from provider {1} in pool {2}",
|
||||
user.getUsername(), provider.getProviderName(), userPoolId);
|
||||
return user;
|
||||
}
|
||||
}
|
||||
|
||||
private void updateFederatedIdentity(CognitoUser user, IdentityProvider provider, String subject, String issuer) {
|
||||
ArrayNode identities = readIdentities(user);
|
||||
ArrayNode reconciled = MAPPER.createArrayNode();
|
||||
for (JsonNode identity : identities) {
|
||||
if (!provider.getProviderName().equals(identity.path("providerName").asText())
|
||||
|| !subject.equals(identity.path("userId").asText())) {
|
||||
reconciled.add(identity);
|
||||
}
|
||||
}
|
||||
reconciled.addObject()
|
||||
.put("userId", subject)
|
||||
.put("providerName", provider.getProviderName())
|
||||
.put("providerType", provider.getProviderType())
|
||||
.put("issuer", issuer)
|
||||
.put("primary", false)
|
||||
.put("dateCreated", System.currentTimeMillis());
|
||||
user.getAttributes().put(IDENTITIES_ATTRIBUTE, reconciled.toString());
|
||||
}
|
||||
|
||||
public List<CognitoUser> listUsers(String userPoolId, String filter) {
|
||||
describeUserPool(userPoolId);
|
||||
String prefix = userPoolId + "::";
|
||||
@@ -2998,6 +3051,16 @@ public class CognitoService implements ResourceProvider {
|
||||
return oauthEndpoint(poolId, "userInfo");
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the callback endpoint that an external identity provider uses to return its
|
||||
* authorization response to Cognito.
|
||||
*/
|
||||
public String getIdentityProviderCallbackEndpoint(String poolId) {
|
||||
return findCustomDomainForPool(poolId)
|
||||
.map(d -> "https://" + d.getDomain() + "/oauth2/idpresponse")
|
||||
.orElse(baseUrl + "/cognito-idp/oauth2/idpresponse");
|
||||
}
|
||||
|
||||
private String oauthEndpoint(String poolId, String operation) {
|
||||
return findCustomDomainForPool(poolId)
|
||||
.map(d -> "https://" + d.getDomain() + "/oauth2/" + operation)
|
||||
|
||||
+7
-4
@@ -10,6 +10,8 @@ import jakarta.ws.rs.core.MediaType;
|
||||
import jakarta.ws.rs.core.Response;
|
||||
|
||||
import java.math.BigInteger;
|
||||
import java.security.interfaces.RSAPublicKey;
|
||||
import java.util.Arrays;
|
||||
import java.util.Base64;
|
||||
|
||||
/**
|
||||
@@ -43,7 +45,7 @@ public class CognitoWellKnownController {
|
||||
public Response getJwks(@PathParam("poolId") String poolId) {
|
||||
UserPool pool = cognitoService.describeUserPool(poolId);
|
||||
String kid = cognitoService.getSigningKeyId(pool);
|
||||
var publicKey = cognitoService.getSigningPublicKey(pool);
|
||||
RSAPublicKey publicKey = cognitoService.getSigningPublicKey(pool);
|
||||
String modulus = base64UrlEncodeUnsigned(publicKey.getModulus());
|
||||
String exponent = base64UrlEncodeUnsigned(publicKey.getPublicExponent());
|
||||
|
||||
@@ -61,17 +63,18 @@ public class CognitoWellKnownController {
|
||||
String jwksUri = cognitoService.getJwksUri(pool.getId());
|
||||
String tokenEndpoint = cognitoService.getTokenEndpoint(pool.getId());
|
||||
String userInfoEndpoint = cognitoService.getUserInfoEndpoint(pool.getId());
|
||||
String authorizationEndpoint = tokenEndpoint.replace("/token", "/authorize");
|
||||
|
||||
String body = """
|
||||
{"issuer":"%s","jwks_uri":"%s","token_endpoint":"%s","userinfo_endpoint":"%s","subject_types_supported":["public"],"response_types_supported":[],"grant_types_supported":["client_credentials"],"token_endpoint_auth_methods_supported":["client_secret_basic","client_secret_post"],"id_token_signing_alg_values_supported":["RS256"]}
|
||||
""".formatted(issuer, jwksUri, tokenEndpoint, userInfoEndpoint).strip();
|
||||
{"issuer":"%s","jwks_uri":"%s","authorization_endpoint":"%s","token_endpoint":"%s","userinfo_endpoint":"%s","subject_types_supported":["public"],"response_types_supported":["code"],"grant_types_supported":["client_credentials","authorization_code"],"token_endpoint_auth_methods_supported":["client_secret_basic","client_secret_post"],"id_token_signing_alg_values_supported":["RS256"]}
|
||||
""".formatted(issuer, jwksUri, authorizationEndpoint, tokenEndpoint, userInfoEndpoint).strip();
|
||||
return Response.ok(body).build();
|
||||
}
|
||||
|
||||
private String base64UrlEncodeUnsigned(BigInteger value) {
|
||||
byte[] bytes = value.toByteArray();
|
||||
if (bytes.length > 1 && bytes[0] == 0) {
|
||||
bytes = java.util.Arrays.copyOfRange(bytes, 1, bytes.length);
|
||||
bytes = Arrays.copyOfRange(bytes, 1, bytes.length);
|
||||
}
|
||||
return Base64.getUrlEncoder().withoutPadding().encodeToString(bytes);
|
||||
}
|
||||
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
package io.github.hectorvent.floci.services.cognito.model;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.List;
|
||||
|
||||
public record CognitoAuthorizationCode(
|
||||
String userPoolId,
|
||||
String clientId,
|
||||
String userId,
|
||||
String redirectUri,
|
||||
List<String> scopes,
|
||||
Instant expiresAt) {
|
||||
|
||||
public CognitoAuthorizationCode {
|
||||
scopes = List.copyOf(scopes);
|
||||
}
|
||||
}
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
package io.github.hectorvent.floci.services.cognito.model;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.List;
|
||||
|
||||
public record CognitoAuthorizationTransaction(
|
||||
String userPoolId,
|
||||
String clientId,
|
||||
String redirectUri,
|
||||
List<String> scopes,
|
||||
String nonce,
|
||||
String providerName,
|
||||
String relyingPartyState,
|
||||
Instant expiresAt) {
|
||||
|
||||
public CognitoAuthorizationTransaction {
|
||||
scopes = List.copyOf(scopes);
|
||||
}
|
||||
}
|
||||
@@ -26,6 +26,8 @@ public class CognitoUser {
|
||||
private String srpSalt;
|
||||
private String srpVerifier;
|
||||
private EmailMfaSettings emailMfaSettings;
|
||||
private String federatedProviderName;
|
||||
private String federatedSubject;
|
||||
|
||||
public CognitoUser() {
|
||||
long now = System.currentTimeMillis() / 1000L;
|
||||
@@ -89,4 +91,20 @@ public class CognitoUser {
|
||||
public void setEmailMfaSettings(EmailMfaSettings emailMfaSettings) {
|
||||
this.emailMfaSettings = emailMfaSettings;
|
||||
}
|
||||
|
||||
public String getFederatedProviderName() {
|
||||
return federatedProviderName;
|
||||
}
|
||||
|
||||
public void setFederatedProviderName(String federatedProviderName) {
|
||||
this.federatedProviderName = federatedProviderName;
|
||||
}
|
||||
|
||||
public String getFederatedSubject() {
|
||||
return federatedSubject;
|
||||
}
|
||||
|
||||
public void setFederatedSubject(String federatedSubject) {
|
||||
this.federatedSubject = federatedSubject;
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user