diff --git a/docs/services/iam.md b/docs/services/iam.md index 8b280ee24b..210bf21fa5 100644 --- a/docs/services/iam.md +++ b/docs/services/iam.md @@ -14,10 +14,11 @@ aws login --endpoint-url http://localhost:4566 --region us-east-1 aws sts get-caller-identity --endpoint-url http://localhost:4566 ``` -The browser callback is still handled by the AWS CLI; Floci does not contact AWS or require a real -AWS account. This follows the AWS Sign-In `AuthorizeOAuth2Access` and `CreateOAuth2Token` wire -shapes, including one-time codes, PKCE verification, refresh-token expiry, and the `aws_sigv4` -temporary credential type. +The authorize endpoint first presents a local consent page, then redirects back to the callback +listener owned by the AWS CLI. Floci does not contact AWS or require a real AWS account. This +follows the AWS Sign-In `AuthorizeOAuth2Access` and `CreateOAuth2Token` wire shapes, including +one-time codes, PKCE verification, refresh-token expiry, and the `aws_sigv4` temporary credential +type. ## Supported Actions diff --git a/src/main/java/io/github/hectorvent/floci/services/signin/SigninController.java b/src/main/java/io/github/hectorvent/floci/services/signin/SigninController.java index 31042afc6a..b488cc2edf 100644 --- a/src/main/java/io/github/hectorvent/floci/services/signin/SigninController.java +++ b/src/main/java/io/github/hectorvent/floci/services/signin/SigninController.java @@ -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 = """ + + + + + + + + + Floci local sign-in + + +
+
+ Floci + Local only +
+
+ AWS CLI access +

Sign in to Floci

+

This local emulator is requesting temporary AWS credentials for account + . +

+
+ + No credentials leave this machine. Continuing creates a short-lived local session + for the AWS CLI. +
+
+ + + +
+
+
+ + + """.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 = """ + + + + + + + + + Floci sign-in request error + + +
+
+ Floci + Local only +
+
+ AWS CLI access +

Floci sign-in request error

+

%s

+ Return to Floci +
+
+ + + """.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("&", "&") + .replace("<", "<") + .replace(">", ">") + .replace("\"", """) + .replace("'", "'"); + } + } diff --git a/src/main/java/io/github/hectorvent/floci/services/signin/SigninService.java b/src/main/java/io/github/hectorvent/floci/services/signin/SigninService.java index 9678ae4faf..c0c7d98160 100644 --- a/src/main/java/io/github/hectorvent/floci/services/signin/SigninService.java +++ b/src/main/java/io/github/hectorvent/floci/services/signin/SigninService.java @@ -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}. * *

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 pendingAuthorizations = new ConcurrentHashMap<>(); private final ConcurrentHashMap authorizationCodes = new ConcurrentHashMap<>(); private final ConcurrentHashMap 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) { diff --git a/src/main/java/io/github/hectorvent/floci/services/signin/model/AuthorizationRequest.java b/src/main/java/io/github/hectorvent/floci/services/signin/model/AuthorizationRequest.java new file mode 100644 index 0000000000..7e8b054030 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/signin/model/AuthorizationRequest.java @@ -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) { +} diff --git a/src/main/resources/META-INF/resources/_floci/signin/floci-header.svg b/src/main/resources/META-INF/resources/_floci/signin/floci-header.svg new file mode 100644 index 0000000000..637a3797b3 --- /dev/null +++ b/src/main/resources/META-INF/resources/_floci/signin/floci-header.svg @@ -0,0 +1,41 @@ + + + + + + + + + + + + + + + + + + + + + diff --git a/src/main/resources/META-INF/resources/_floci/signin/floci.svg b/src/main/resources/META-INF/resources/_floci/signin/floci.svg new file mode 100644 index 0000000000..1b2e626d67 --- /dev/null +++ b/src/main/resources/META-INF/resources/_floci/signin/floci.svg @@ -0,0 +1,50 @@ + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/main/resources/META-INF/resources/_floci/signin/signin.css b/src/main/resources/META-INF/resources/_floci/signin/signin.css new file mode 100644 index 0000000000..9ced682d90 --- /dev/null +++ b/src/main/resources/META-INF/resources/_floci/signin/signin.css @@ -0,0 +1,247 @@ +:root { + color-scheme: light; + font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif; + --floci-ink: #262425; + --floci-brand: #5559a7; + --floci-orange: #ff9900; + --floci-orange-dark: #995c00; + --floci-surface: #ffffff; + --floci-muted: #5f6772; + --floci-border: #e4e7ec; +} + +* { + box-sizing: border-box; +} + +body { + margin: 0; + min-height: 100vh; + display: grid; + place-items: center; + padding: 32px 16px; + color: var(--floci-ink); + background: + radial-gradient(circle at 15% 10%, #ff99001f 0, transparent 34%), + radial-gradient(circle at 85% 90%, #5559a71f 0, transparent 34%), + #f5f6f8; +} + +.shell { + width: min(500px, 100%); + overflow: hidden; + border: 1px solid var(--floci-border); + border-radius: 22px; + background: var(--floci-surface); + box-shadow: 0 24px 64px #2624251f; +} + +.brand { + position: relative; + display: flex; + align-items: center; + justify-content: space-between; + gap: 24px; + min-height: 122px; + padding: 28px 36px; + overflow: hidden; + background: var(--floci-brand); +} + +.brand::after { + position: absolute; + right: -58px; + bottom: -78px; + width: 190px; + height: 190px; + border: 28px solid #ff990026; + border-radius: 50%; + content: ""; +} + +.brand img { + position: relative; + z-index: 1; + width: 190px; + max-width: 62%; + height: auto; +} + +.local-badge { + position: relative; + z-index: 1; + padding: 7px 10px; + border: 1px solid #ffffff38; + border-radius: 999px; + color: #ffffff; + font-size: 12px; + font-weight: 700; + letter-spacing: .08em; + text-transform: uppercase; + white-space: nowrap; +} + +.content { + padding: 36px; +} + +.eyebrow { + display: block; + margin-bottom: 8px; + color: var(--floci-orange-dark); + font-size: 12px; + font-weight: 800; + letter-spacing: .11em; + text-transform: uppercase; +} + +h1 { + margin: 0 0 14px; + font-size: clamp(28px, 7vw, 36px); + line-height: 1.12; + letter-spacing: -.025em; +} + +p { + margin: 0; + color: var(--floci-muted); + line-height: 1.65; +} + +p + p { + margin-top: 14px; +} + +.account { + display: inline-block; + margin-top: 6px; + padding: 4px 8px; + border: 1px solid #ff990052; + border-radius: 6px; + color: var(--floci-ink); + background: #fff7e8; + font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; + font-size: .9em; + font-weight: 700; +} + +.notice { + display: flex; + gap: 12px; + margin-top: 24px; + padding: 14px 16px; + border: 1px solid var(--floci-border); + border-radius: 12px; + background: #fafafa; + color: #464b53; + font-size: 14px; + line-height: 1.5; +} + +.notice-dot { + flex: 0 0 auto; + width: 10px; + height: 10px; + margin-top: 5px; + border-radius: 50%; + background: var(--floci-orange); + box-shadow: 0 0 0 4px #ff990024; +} + +form { + display: grid; + grid-template-columns: 1fr 1fr; + gap: 12px; + margin-top: 28px; +} + +button, +.home-link { + min-height: 46px; + padding: 11px 18px; + border: 1px solid transparent; + border-radius: 10px; + font: inherit; + font-weight: 750; +} + +button { + cursor: pointer; +} + +button:focus-visible, +.home-link:focus-visible { + outline: 3px solid #92400e; + outline-offset: 2px; +} + +.continue { + color: #1c1917; + background: var(--floci-orange); + box-shadow: 0 8px 18px #ff99002e; +} + +.continue:hover { + background: #ffad2f; +} + +.cancel { + border-color: #667085; + color: var(--floci-ink); + background: #f4f5f7; +} + +.cancel:hover { + background: #e9ebef; +} + +.home-link { + display: inline-flex; + align-items: center; + justify-content: center; + margin-top: 28px; + color: #1c1917; + background: var(--floci-orange); + text-decoration: none; +} + +@media (max-width: 480px) { + body { + align-items: start; + padding-top: 18px; + } + + .brand { + min-height: 104px; + padding: 24px; + } + + .brand::after { + right: -120px; + bottom: -105px; + } + + .brand img { + width: 166px; + } + + .local-badge { + display: none; + } + + .content { + padding: 28px 24px; + } + + form { + grid-template-columns: 1fr; + } +} + +@media (prefers-reduced-motion: reduce) { + *, + *::before, + *::after { + scroll-behavior: auto !important; + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/signin/SigninIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/signin/SigninIntegrationTest.java index f3f82c8925..0f6b9e5be3 100644 --- a/src/test/java/io/github/hectorvent/floci/services/signin/SigninIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/signin/SigninIntegrationTest.java @@ -19,6 +19,7 @@ import static org.hamcrest.Matchers.notNullValue; import static org.hamcrest.Matchers.not; import static org.hamcrest.Matchers.nullValue; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; @QuarkusTest @@ -28,7 +29,7 @@ class SigninIntegrationTest { private static final String REDIRECT_URI = "http://127.0.0.1:4567/oauth/callback"; @Test - void authorizeRedirectsWithStateAndPkceCode() throws Exception { + void authorizePresentsLocalConsentPageBeforeRedirectingWithCode() throws Exception { String verifier = verifier(); String state = UUID.randomUUID().toString(); @@ -45,10 +46,61 @@ class SigninIntegrationTest { .get("/v1/authorize") .then() .statusCode(302) + .header("Cache-Control", equalTo("no-store")) .extract() .header("Location"); - URI redirect = URI.create(location); + URI consent = URI.create(location); + assertFalse(consent.isAbsolute()); + assertEquals("/_floci/signin/consent", consent.getPath()); + String page = request() + .get(location) + .then() + .statusCode(200) + .header("Cache-Control", equalTo("no-store")) + .header("Referrer-Policy", equalTo("no-referrer")) + .header("X-Content-Type-Options", equalTo("nosniff")) + .header("Content-Security-Policy", equalTo("default-src 'none'; img-src 'self'; " + + "style-src 'self'; form-action 'self'; base-uri 'none'; frame-ancestors 'none'")) + .extract() + .asString(); + assertTrue(page.contains("Sign in to Floci")); + assertTrue(page.contains("src=\"/_floci/signin/floci-header.svg\"")); + assertTrue(page.contains("alt=\"Floci\"")); + assertTrue(page.contains("href=\"/_floci/signin/floci.svg\"")); + assertTrue(page.contains("href=\"/_floci/signin/signin.css\"")); + assertTrue(page.contains("

")); + String requestId = queryParams(consent.getRawQuery()).get("request_id"); + assertTrue(page.contains("name=\"request_id\" value=\"" + requestId + "\"")); + assertTrue(page.contains("name=\"action\" value=\"cancel\"")); + assertTrue(page.contains("name=\"action\" value=\"continue\"")); + assertTrue(page.contains("Continue")); + + request() + .get("/_floci/signin/floci-header.svg") + .then() + .statusCode(200) + .header("Content-Type", org.hamcrest.Matchers.startsWith("image/svg+xml")) + .body(org.hamcrest.Matchers.containsString("viewBox=\"0 0 531.25 156.71\"")) + .body(org.hamcrest.Matchers.containsString("#FF9900")); + + request() + .get("/_floci/signin/floci.svg") + .then() + .statusCode(200) + .header("Content-Type", org.hamcrest.Matchers.startsWith("image/svg+xml")); + + request() + .get("/_floci/signin/signin.css") + .then() + .statusCode(200) + .header("Content-Type", org.hamcrest.Matchers.startsWith("text/css")) + .body(org.hamcrest.Matchers.containsString("--floci-brand: #5559a7")) + .body(org.hamcrest.Matchers.containsString("--floci-orange: #ff9900")) + .body(org.hamcrest.Matchers.containsString("border-color: #667085")); + + String redirectLocation = approve(location); + URI redirect = URI.create(redirectLocation); assertEquals(REDIRECT_URI, redirect.getScheme() + "://" + redirect.getAuthority() + redirect.getPath()); Map params = queryParams(redirect.getRawQuery()); assertTrue(params.get("code").length() >= 1); @@ -74,6 +126,79 @@ class SigninIntegrationTest { .body("$", not(hasKey("__type"))); } + @Test + void denyingConsentRedirectsWithAccessDenied() throws Exception { + String state = UUID.randomUUID().toString(); + String consentLocation = request() + .redirects().follow(false) + .queryParam("client_id", CLIENT_ID) + .queryParam("code_challenge", challenge(verifier())) + .queryParam("code_challenge_method", "SHA-256") + .queryParam("redirect_uri", REDIRECT_URI) + .queryParam("response_type", "code") + .queryParam("scope", "openid") + .queryParam("state", state) + .when() + .get("/v1/authorize") + .then() + .statusCode(302) + .extract() + .header("Location"); + + URI consent = URI.create(consentLocation); + String requestId = queryParams(consent.getRawQuery()).get("request_id"); + String redirectLocation = request() + .redirects().follow(false) + .contentType("application/x-www-form-urlencoded") + .formParam("request_id", requestId) + .formParam("action", "cancel") + .when() + .post("/_floci/signin/consent") + .then() + .statusCode(302) + .header("Cache-Control", equalTo("no-store")) + .extract() + .header("Location"); + + Map params = queryParams(URI.create(redirectLocation).getRawQuery()); + assertEquals("access_denied", params.get("error")); + assertEquals(state, params.get("state")); + } + + @Test + void consentRejectsMissingRequestIdAndUnknownAction() throws Exception { + request() + .get("/_floci/signin/consent") + .then() + .statusCode(400) + .header("Cache-Control", equalTo("no-store")) + .header("Referrer-Policy", equalTo("no-referrer")) + .header("X-Content-Type-Options", equalTo("nosniff")) + .header("Content-Security-Policy", equalTo("default-src 'none'; img-src 'self'; " + + "style-src 'self'; form-action 'self'; base-uri 'none'; frame-ancestors 'none'")) + .body(org.hamcrest.Matchers.containsString("request_id is required")); + + String verifier = verifier(); + String state = UUID.randomUUID().toString(); + String consentLocation = beginAuthorization(verifier, state); + String requestId = queryParams(URI.create(consentLocation).getRawQuery()).get("request_id"); + + request() + .contentType("application/x-www-form-urlencoded") + .formParam("request_id", requestId) + .formParam("action", "approve") + .when() + .post("/_floci/signin/consent") + .then() + .statusCode(400) + .body(org.hamcrest.Matchers.containsString("action must be continue or cancel")); + + String redirectLocation = approve(consentLocation); + Map params = queryParams(URI.create(redirectLocation).getRawQuery()); + assertTrue(params.containsKey("code")); + assertEquals(state, params.get("state")); + } + @Test void malformedTokenJsonUsesOauthErrorEnvelope() { request() @@ -178,6 +303,53 @@ class SigninIntegrationTest { "The authorization grant type is not supported by the authorization server.")); } + @Test + void s3BucketNamedSigninDoesNotCollideWithConsentUi() { + String objectBody = "S3 object under the signin bucket"; + String formerAssetBody = "S3 object at the former static asset path"; + request() + .when() + .put("/signin") + .then() + .statusCode(200); + + try { + request() + .contentType("text/plain") + .body(objectBody) + .when() + .put("/signin/consent") + .then() + .statusCode(200); + + request() + .when() + .get("/signin/consent") + .then() + .statusCode(200) + .body(equalTo(objectBody)); + + request() + .contentType("text/plain") + .body(formerAssetBody) + .when() + .put("/signin/signin.css") + .then() + .statusCode(200); + + request() + .when() + .get("/signin/signin.css") + .then() + .statusCode(200) + .body(equalTo(formerAssetBody)); + } finally { + request().delete("/signin/signin.css").then().statusCode(204); + request().delete("/signin/consent").then().statusCode(204); + request().delete("/signin").then().statusCode(204); + } + } + @Test void authorizationCodeExchangeReturnsTemporaryAwsCredentials() throws Exception { String verifier = verifier(); @@ -308,6 +480,10 @@ class SigninIntegrationTest { } private String authorize(String verifier, String state) throws Exception { + return approve(beginAuthorization(verifier, state)); + } + + private String beginAuthorization(String verifier, String state) throws Exception { return request() .redirects().follow(false) .queryParam("client_id", CLIENT_ID) @@ -325,6 +501,23 @@ class SigninIntegrationTest { .header("Location"); } + private String approve(String consentLocation) { + URI consent = URI.create(consentLocation); + String requestId = queryParams(consent.getRawQuery()).get("request_id"); + return request() + .redirects().follow(false) + .contentType("application/x-www-form-urlencoded") + .formParam("request_id", requestId) + .formParam("action", "continue") + .when() + .post("/_floci/signin/consent") + .then() + .statusCode(302) + .header("Cache-Control", equalTo("no-store")) + .extract() + .header("Location"); + } + private RequestSpecification request() { return given(); } diff --git a/src/test/java/io/github/hectorvent/floci/services/signin/SigninServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/signin/SigninServiceTest.java index 83b5cea0f1..325585f244 100644 --- a/src/test/java/io/github/hectorvent/floci/services/signin/SigninServiceTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/signin/SigninServiceTest.java @@ -8,7 +8,6 @@ import io.github.hectorvent.floci.testing.MutableClock; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import java.net.URI; import java.net.URLDecoder; import java.nio.charset.StandardCharsets; import java.security.MessageDigest; @@ -79,11 +78,11 @@ class SigninServiceTest { @Test void requiresAwsSha256ChallengeMethod() throws Exception { SigninException error = assertThrows(SigninException.class, - () -> service.authorize(CLIENT_ID, challenge(VERIFIER), "S256", REDIRECT_URI, + () -> service.beginAuthorization(CLIENT_ID, challenge(VERIFIER), "S256", REDIRECT_URI, "code", "openid", "state", null)); assertEquals("invalid_request", error.error()); - service.authorize(CLIENT_ID, challenge(VERIFIER), "SHA-256", REDIRECT_URI, + service.beginAuthorization(CLIENT_ID, challenge(VERIFIER), "SHA-256", REDIRECT_URI, "code", "openid", "state", null); } @@ -137,9 +136,9 @@ class SigninServiceTest { REDIRECT_URI, VERIFIER, null, "r".repeat(2049))); assertTokenValidation(() -> service.exchange(CLIENT_ID, "refresh_token", null, null, null, "r".repeat(2049), null)); - assertInvalidRequest(() -> service.authorize(CLIENT_ID, challengeUnchecked(VERIFIER), "SHA-256", + assertInvalidRequest(() -> service.beginAuthorization(CLIENT_ID, challengeUnchecked(VERIFIER), "SHA-256", REDIRECT_URI, "code", "openid", "state", "")); - assertInvalidRequest(() -> service.authorize(CLIENT_ID, challengeUnchecked(VERIFIER), "SHA-256", + assertInvalidRequest(() -> service.beginAuthorization(CLIENT_ID, challengeUnchecked(VERIFIER), "SHA-256", REDIRECT_URI, "code", "openid", "state", "r".repeat(2049))); TokenResult result = service.exchange(CLIENT_ID, "authorization_code", code, @@ -183,6 +182,41 @@ class SigninServiceTest { assertTokenValidation(() -> exchangeCode(cleanedAfterCutoff, VERIFIER)); } + @Test + void authorizationCodeLifetimeStartsAtConsentCompletion() throws Exception { + String requestId = service.beginAuthorization(CLIENT_ID, challenge(VERIFIER), "SHA-256", REDIRECT_URI, + "code", "openid", "state", null); + clock.advance(Duration.ofMinutes(4)); + String code = query(service.completeAuthorization(requestId)).get("code"); + clock.advance(Duration.ofMinutes(4).plusSeconds(59)); + + TokenResult result = exchangeCode(code, VERIFIER); + + assertEquals(900, result.expiresIn()); + } + + @Test + void pendingAuthorizationRequestsAreSingleUse() throws Exception { + String approvedRequest = service.beginAuthorization(CLIENT_ID, challenge(VERIFIER), "SHA-256", REDIRECT_URI, + "code", "openid", "approved", null); + service.completeAuthorization(approvedRequest); + assertInvalidRequest(() -> service.completeAuthorization(approvedRequest)); + + String deniedRequest = service.beginAuthorization(CLIENT_ID, challenge(VERIFIER), "SHA-256", REDIRECT_URI, + "code", "openid", "denied", null); + service.denyAuthorization(deniedRequest); + assertInvalidRequest(() -> service.denyAuthorization(deniedRequest)); + } + + @Test + void pendingAuthorizationRequestsExpireAtFiveMinuteBoundary() throws Exception { + String requestId = service.beginAuthorization(CLIENT_ID, challenge(VERIFIER), "SHA-256", REDIRECT_URI, + "code", "openid", "state", null); + clock.advance(Duration.ofMinutes(5)); + + assertInvalidRequest(() -> service.completeAuthorization(requestId)); + } + @Test void rejectsPkceMismatchWithoutRegisteringCredentials() throws Exception { String code = authorizeCode(VERIFIER); @@ -241,13 +275,14 @@ class SigninServiceTest { } @Test - void rotatedRefreshTokenKeepsOriginalAbsoluteExpiry() throws Exception { + void rotatedRefreshTokenFamilyKeepsOriginalAbsoluteExpiry() throws Exception { TokenResult initial = issueInitialTokens(); clock.advance(Duration.ofHours(11).plusMinutes(59)); TokenResult rotated = refresh(initial.refreshToken()); clock.advance(Duration.ofMinutes(1)); + assertRefreshExpired(initial.refreshToken()); assertRefreshExpired(rotated.refreshToken()); } @@ -289,6 +324,18 @@ class SigninServiceTest { assertFalse(error.modeled()); } + @Test + void refreshGrantRetentionNeverOutlivesAbsoluteExpiry() { + var expiresAt = clock.instant().plus(Duration.ofHours(12)); + var earlierReplayExpiry = expiresAt.minus(Duration.ofMinutes(1)); + var replayExpiresAt = expiresAt.plus(Duration.ofMinutes(14)); + + assertEquals(expiresAt, SigninService.refreshGrantRetentionExpiry(expiresAt, null)); + assertEquals(earlierReplayExpiry, + SigninService.refreshGrantRetentionExpiry(expiresAt, earlierReplayExpiry)); + assertEquals(expiresAt, SigninService.refreshGrantRetentionExpiry(expiresAt, replayExpiresAt)); + } + @Test void expiryCleanupWaitsForInFlightRotation() throws Exception { TokenResult initial = issueInitialTokens(); @@ -341,13 +388,13 @@ class SigninServiceTest { } private String authorizeCode(String verifier) throws Exception { - String redirect = service.authorize(CLIENT_ID, challenge(verifier), "SHA-256", REDIRECT_URI, + String requestId = service.beginAuthorization(CLIENT_ID, challenge(verifier), "SHA-256", REDIRECT_URI, "code", "openid", "state", null); - return query(URI.create(redirect).getRawQuery()).get("code"); + return query(service.completeAuthorization(requestId)).get("code"); } private String authorize(String codeChallenge, String clientId, String redirectUri, String state) { - return service.authorize(clientId, codeChallenge, "SHA-256", redirectUri, + return service.beginAuthorization(clientId, codeChallenge, "SHA-256", redirectUri, "code", "openid", state, null); } @@ -418,7 +465,8 @@ class SigninServiceTest { return Base64.getUrlEncoder().withoutPadding().encodeToString(digest); } - private static Map query(String query) { + private static Map query(String redirect) { + String query = redirect.substring(redirect.indexOf('?') + 1); return java.util.Arrays.stream(query.split("&")) .map(pair -> pair.split("=", 2)) .collect(java.util.stream.Collectors.toMap(