feat(signin): add secure branded consent flow (#2429)

This commit is contained in:
Alex Banna authored and GitHub committed 2026-08-26 11:02:05 -04:00
1 parent 1e443acd06
commit 09d7502b28
9 files changed
+804 -39

No files matched your search

@@ -5,18 +5,21 @@ import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectReader;
import io.github.hectorvent.floci.services.iam.model.SessionCreds;
import io.github.hectorvent.floci.services.signin.model.AuthorizationRequest;
import io.github.hectorvent.floci.services.signin.model.TokenResult;
import jakarta.inject.Inject;
import jakarta.ws.rs.Consumes;
import jakarta.ws.rs.FormParam;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.POST;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.QueryParam;
import jakarta.ws.rs.core.Context;
import jakarta.ws.rs.core.HttpHeaders;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
import jakarta.ws.rs.core.Context;
import jakarta.ws.rs.core.UriBuilder;
import java.io.IOException;
import java.net.URLDecoder;
@@ -49,11 +52,83 @@ public class SigninController {
@QueryParam("scope") String scope,
@QueryParam("state") String state,
@QueryParam("resource") String resource) {
String location = signinService.authorize(clientId, codeChallenge, codeChallengeMethod,
String requestId = signinService.beginAuthorization(clientId, codeChallenge, codeChallengeMethod,
redirectUri, responseType, scope, state, resource);
return Response.status(Response.Status.FOUND)
.header(HttpHeaders.LOCATION, location)
.build();
String location = UriBuilder.fromPath("/_floci/signin/consent")
.queryParam("request_id", requestId)
.build()
.toString();
return redirect(location);
}
@GET
@Path("/_floci/signin/consent")
@Produces(MediaType.TEXT_HTML)
public Response consentPage(@QueryParam("request_id") String requestId) {
try {
AuthorizationRequest request = signinService.pendingAuthorization(requestId);
String accountId = escape(request.accountId());
String escapedRequestId = escape(requestId);
String page = """
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="theme-color" content="#5559a7">
<link rel="icon" href="/_floci/signin/floci.svg" type="image/svg+xml">
<link rel="stylesheet" href="/_floci/signin/signin.css">
<title>Floci local sign-in</title>
</head>
<body>
<main class="shell">
<header class="brand">
<img src="/_floci/signin/floci-header.svg" alt="Floci" width="190" height="56">
<span class="local-badge">Local only</span>
</header>
<section class="content">
<span class="eyebrow">AWS CLI access</span>
<h1>Sign in to Floci</h1>
<p>This local emulator is requesting temporary AWS credentials for account
<span class="account">%s</span>.
</p>
<div class="notice">
<span class="notice-dot" aria-hidden="true"></span>
<span>No credentials leave this machine. Continuing creates a short-lived local session
for the AWS CLI.</span>
</div>
<form method="post" action="/_floci/signin/consent">
<input type="hidden" name="request_id" value="%s">
<button class="cancel" type="submit" name="action" value="cancel">Cancel</button>
<button class="continue" type="submit" name="action" value="continue">Continue</button>
</form>
</section>
</main>
</body>
</html>
""".formatted(accountId, escapedRequestId);
return secureHtml(Response.ok(page)).build();
} catch (SigninException e) {
return htmlError(e);
}
}
@POST
@Path("/_floci/signin/consent")
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public Response consent(@FormParam("request_id") String requestId,
@FormParam("action") String action) {
try {
if (!"continue".equals(action) && !"cancel".equals(action)) {
throw new SigninException("invalid_request", "action must be continue or cancel");
}
String location = "cancel".equals(action)
? signinService.denyAuthorization(requestId)
: signinService.completeAuthorization(requestId);
return redirect(location);
} catch (SigninException e) {
return htmlError(e);
}
}
@POST
@@ -127,4 +202,63 @@ public class SigninController {
return null;
}
private static Response htmlError(SigninException exception) {
String message = escape(exception.getMessage());
String page = """
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="theme-color" content="#5559a7">
<link rel="icon" href="/_floci/signin/floci.svg" type="image/svg+xml">
<link rel="stylesheet" href="/_floci/signin/signin.css">
<title>Floci sign-in request error</title>
</head>
<body>
<main class="shell">
<header class="brand">
<img src="/_floci/signin/floci-header.svg" alt="Floci" width="190" height="56">
<span class="local-badge">Local only</span>
</header>
<section class="content">
<span class="eyebrow">AWS CLI access</span>
<h1>Floci sign-in request error</h1>
<p>%s</p>
<a class="home-link" href="/">Return to Floci</a>
</section>
</main>
</body>
</html>
""".formatted(message);
return secureHtml(Response.status(Response.Status.BAD_REQUEST).entity(page)).build();
}
private static Response redirect(String location) {
return Response.status(Response.Status.FOUND)
.header(HttpHeaders.LOCATION, location)
.header(HttpHeaders.CACHE_CONTROL, "no-store")
.build();
}
private static Response.ResponseBuilder secureHtml(Response.ResponseBuilder response) {
return response.type(MediaType.TEXT_HTML)
.header(HttpHeaders.CACHE_CONTROL, "no-store")
.header("Referrer-Policy", "no-referrer")
.header("X-Content-Type-Options", "nosniff")
.header("Content-Security-Policy", "default-src 'none'; img-src 'self'; style-src 'self'; "
+ "form-action 'self'; base-uri 'none'; frame-ancestors 'none'");
}
private static String escape(String value) {
if (value == null) {
return "";
}
return value.replace("&", "&amp;")
.replace("<", "&lt;")
.replace(">", "&gt;")
.replace("\"", "&quot;")
.replace("'", "&#39;");
}
}
@@ -5,6 +5,7 @@ import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.services.iam.IamService;
import io.github.hectorvent.floci.services.iam.model.SessionCreds;
import io.github.hectorvent.floci.services.signin.model.AuthorizationRequest;
import io.github.hectorvent.floci.services.signin.model.TokenResult;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
@@ -26,8 +27,9 @@ import java.util.regex.Pattern;
* Local implementation of the AWS Sign-In OAuth flow used by {@code aws login}.
*
* <p>Floci has no external console to authenticate against, so the authorization endpoint
* represents the local emulator account and immediately issues a one-time PKCE authorization
* code. The token endpoint still follows the AWS flow: codes are single-use, PKCE is verified,
* presents a local consent page for the emulator account before issuing a one-time PKCE
* authorization code. The token endpoint still follows the AWS flow: codes are single-use,
* PKCE is verified,
* refresh tokens expire, and returned credentials are registered with IAM for request signing.
*/
@ApplicationScoped
@@ -53,6 +55,7 @@ public class SigninService {
private final ObjectMapper objectMapper;
private final Clock clock;
private final SecureRandom random;
private final ConcurrentHashMap<String, AuthorizationRequest> pendingAuthorizations = new ConcurrentHashMap<>();
private final ConcurrentHashMap<String, AuthorizationCode> authorizationCodes = new ConcurrentHashMap<>();
private final ConcurrentHashMap<String, RefreshGrant> refreshGrants = new ConcurrentHashMap<>();
@@ -66,9 +69,9 @@ public class SigninService {
this.random = new SecureRandom();
}
public String authorize(String clientId, String codeChallenge, String codeChallengeMethod,
String redirectUri, String responseType, String scope, String state,
String resource) {
public String beginAuthorization(String clientId, String codeChallenge, String codeChallengeMethod,
String redirectUri, String responseType, String scope, String state,
String resource) {
validateClient(clientId);
if (!"SHA-256".equals(codeChallengeMethod)) {
throw new SigninException("invalid_request", "code_challenge_method must be SHA-256");
@@ -87,12 +90,54 @@ public class SigninService {
validateOptionalResource(resource);
String accountId = regionResolver.getAccountId();
Instant now = clock.instant();
pendingAuthorizations.entrySet().removeIf(entry -> !entry.getValue().expiresAt().isAfter(now));
String requestId = randomToken(24);
pendingAuthorizations.put(requestId, new AuthorizationRequest(
clientId, codeChallenge, redirectUri, resource, state, accountId,
now.plusSeconds(AUTHORIZATION_CODE_TTL_SECONDS)));
return requestId;
}
public AuthorizationRequest pendingAuthorization(String requestId) {
validateRequestId(requestId);
AuthorizationRequest request = pendingAuthorizations.get(requestId);
if (request == null || !request.expiresAt().isAfter(clock.instant())) {
pendingAuthorizations.remove(requestId, request);
throw new SigninException("invalid_request", "The authorization request is invalid or expired");
}
return request;
}
public String completeAuthorization(String requestId) {
Instant now = clock.instant();
AuthorizationRequest request = consumeAuthorizationRequest(requestId, now);
cleanupExpiredAuthorizationCodes(now);
String code = randomToken(32);
authorizationCodes.put(code, AuthorizationCode.active(
clientId, codeChallenge, redirectUri, resource, accountId,
request.clientId(), request.codeChallenge(), request.redirectUri(), request.resource(),
request.accountId(),
now.plusSeconds(AUTHORIZATION_CODE_TTL_SECONDS)));
return appendQuery(redirectUri, "code", code, "state", state);
return appendQuery(request.redirectUri(), "code", code, "state", request.state());
}
public String denyAuthorization(String requestId) {
AuthorizationRequest request = consumeAuthorizationRequest(requestId, clock.instant());
return appendQuery(request.redirectUri(), "error", "access_denied", "state", request.state());
}
private AuthorizationRequest consumeAuthorizationRequest(String requestId, Instant now) {
validateRequestId(requestId);
AuthorizationRequest request = pendingAuthorizations.remove(requestId);
if (request == null || !request.expiresAt().isAfter(now)) {
throw new SigninException("invalid_request", "The authorization request is invalid or expired");
}
return request;
}
private static void validateRequestId(String requestId) {
if (requestId == null || requestId.isBlank()) {
throw new SigninException("invalid_request", "request_id is required");
}
}
public TokenResult exchange(String clientId, String grantType, String code, String redirectUri,
@@ -143,12 +188,13 @@ public class SigninService {
}
Instant now = clock.instant();
RefreshGrant grant = refreshGrants.get(refreshToken);
cleanupExpiredRefreshGrants(now, refreshToken);
boolean identityMatches = grant != null && clientId.equals(grant.clientId());
cleanupExpiredRefreshGrants(now, identityMatches ? refreshToken : null);
if (grant == null) {
throw new SigninException("invalid_grant", "The refresh token is invalid or expired");
}
rejectExpiredRefreshTombstone(refreshToken, grant, now);
if (!clientId.equals(grant.clientId())) {
if (!identityMatches) {
throw new SigninException("invalid_grant", "The refresh token is invalid or expired");
}
synchronized (grant) {
@@ -188,7 +234,7 @@ public class SigninService {
private TokenResult issueTokens(String clientId, String resource, String accountId, boolean includeIdToken,
Instant now) {
cleanupExpiredRefreshGrants(now);
cleanupExpiredRefreshGrants(now, null);
StoredRefreshGrant stored = storeRefreshGrant(
clientId, resource, accountId, now.plusSeconds(REFRESH_TOKEN_TTL_SECONDS));
try {
@@ -346,10 +392,6 @@ public class SigninService {
});
}
private void cleanupExpiredRefreshGrants(Instant now) {
cleanupExpiredRefreshGrants(now, null);
}
private void cleanupExpiredRefreshGrants(Instant now, String refreshTokenInUse) {
refreshGrants.forEach((token, grant) -> {
if (token.equals(refreshTokenInUse)) {
@@ -388,6 +430,11 @@ public class SigninService {
return false;
}
static Instant refreshGrantRetentionExpiry(Instant expiresAt, Instant replayExpiresAt) {
return replayExpiresAt == null || expiresAt.isBefore(replayExpiresAt)
? expiresAt : replayExpiresAt;
}
private static boolean isSameDeviceRedirect(URI uri) {
return "http".equalsIgnoreCase(uri.getScheme())
&& "127.0.0.1".equals(uri.getHost())
@@ -532,10 +579,7 @@ public class SigninService {
if (expiredTombstone()) {
return !expiredTombstoneUntil.isAfter(now);
}
Instant replayExpiry = replayExpiresAt;
Instant retentionExpiry = replayExpiry == null || expiresAt.isBefore(replayExpiry)
? expiresAt : replayExpiry;
return !retentionExpiry.isAfter(now);
return !refreshGrantRetentionExpiry(expiresAt, replayExpiresAt).isAfter(now);
}
private TokenResult replayResultWithRemainingLifetime(Instant now) {
@@ -0,0 +1,7 @@
package io.github.hectorvent.floci.services.signin.model;
import java.time.Instant;
public record AuthorizationRequest(String clientId, String codeChallenge, String redirectUri,
String resource, String state, String accountId, Instant expiresAt) {
}