fix(signin): complete aws login --remote against an endpoint override (#5552)

The AWS CLI builds the cross-device redirect from the Sign-In endpoint
it resolved, so with --endpoint-url it sends Floci's own address plus
/v1/sessions/confirmation. Floci accepted only an https AWS sign-in host
there and served no confirmation page, so the authorize request was
refused and the remote login could not finish.

A cross-device redirect is now also accepted on the scheme, host and
port the authorize request arrived on, and GET /v1/sessions/confirmation
shows the verification code in the form the CLI decodes. Any other
origin is still refused.

Signed-off-by: Hector Ventura <hectorvent@gmail.com>
This commit is contained in:
Hector Ventura authored and GitHub committed 2026-10-12 23:09:28 -04:00
1 parent b4758b0018
commit bcda5958e0
6 files changed
+256 -6

No files matched your search

+11
View File
@@ -20,6 +20,17 @@ follows the AWS Sign-In `AuthorizeOAuth2Access` and `CreateOAuth2Token` wire sha
one-time codes, PKCE verification, refresh-token expiry, and the `aws_sigv4` temporary credential
type.
The cross-device flow works too, for a CLI that cannot open a browser on the same machine:
```bash
aws login --remote --endpoint-url http://localhost:4566 --region us-east-1
```
The CLI prints the authorize URL and waits for a code. After the consent page, Floci lands on
`/v1/sessions/confirmation` on the same endpoint, the path AWS Sign-In uses, and shows the
verification code to paste back. The redirect must point at the endpoint the request arrived on
or at an AWS Sign-In host; any other origin is refused.
## Supported Actions
### Users
@@ -20,6 +20,7 @@ import jakarta.ws.rs.core.HttpHeaders;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
import jakarta.ws.rs.core.UriBuilder;
import jakarta.ws.rs.core.UriInfo;
import java.io.IOException;
import java.net.URLDecoder;
@@ -51,9 +52,10 @@ public class SigninController {
@QueryParam("response_type") String responseType,
@QueryParam("scope") String scope,
@QueryParam("state") String state,
@QueryParam("resource") String resource) {
@QueryParam("resource") String resource,
@Context UriInfo uriInfo) {
String requestId = signinService.beginAuthorization(clientId, codeChallenge, codeChallengeMethod,
redirectUri, responseType, scope, state, resource);
redirectUri, responseType, scope, state, resource, uriInfo.getBaseUri());
String location = UriBuilder.fromPath("/_floci/signin/consent")
.queryParam("request_id", requestId)
.build()
@@ -131,6 +133,54 @@ public class SigninController {
}
}
/**
* The page AWS Sign-In lands on at the end of a cross-device login. It shows the verification
* code the user pastes back into {@code aws login --remote}.
*/
@GET
@Path(SigninService.CONFIRMATION_PATH)
@Produces(MediaType.TEXT_HTML)
public Response confirmationPage(@QueryParam("code") String code,
@QueryParam("state") String state,
@QueryParam("error") String error) {
try {
if (error != null) {
throw new SigninException(error, "The sign-in request was cancelled. Run aws login again to retry.");
}
String verificationCode = escape(signinService.verificationCode(code, state));
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>Verification code</h1>
<p>Copy this code and paste it into the AWS CLI to finish signing in.</p>
<p class="verification-code">%s</p>
</section>
</main>
</body>
</html>
""".formatted(verificationCode);
return secureHtml(Response.ok(page)).build();
} catch (SigninException e) {
return htmlError(e);
}
}
@POST
@Path("/v1/token")
@Consumes({MediaType.APPLICATION_JSON, MediaType.APPLICATION_FORM_URLENCODED})
@@ -13,12 +13,14 @@ import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import java.net.URI;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.SecureRandom;
import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
import java.util.Base64;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.regex.Pattern;
@@ -39,6 +41,7 @@ public class SigninService {
// how the China or GovCloud consoles spell theirs, so they stay literal (see docs/configuration/partitions.md).
static final String SAME_DEVICE_CLIENT = "arn:aws:signin:::devtools/same-device"; // partition-literal: console client id, non-commercial spelling unknown
static final String CROSS_DEVICE_CLIENT = "arn:aws:signin:::devtools/cross-device"; // partition-literal: console client id, non-commercial spelling unknown
static final String CONFIRMATION_PATH = "/v1/sessions/confirmation";
static final int ACCESS_TOKEN_TTL_SECONDS = 900;
private static final long AUTHORIZATION_CODE_TTL_SECONDS = 300;
private static final long REFRESH_TOKEN_TTL_SECONDS = 12 * 60 * 60;
@@ -74,6 +77,18 @@ public class SigninService {
public String beginAuthorization(String clientId, String codeChallenge, String codeChallengeMethod,
String redirectUri, String responseType, String scope, String state,
String resource) {
return beginAuthorization(clientId, codeChallenge, codeChallengeMethod, redirectUri, responseType,
scope, state, resource, null);
}
/**
* @param requestOrigin the base URI the authorize request arrived on, or null when unknown. The
* AWS CLI builds the cross-device redirect from the Sign-In endpoint it resolved, so
* with an endpoint override that redirect is this emulator's own confirmation page.
*/
public String beginAuthorization(String clientId, String codeChallenge, String codeChallengeMethod,
String redirectUri, String responseType, String scope, String state,
String resource, URI requestOrigin) {
validateClient(clientId);
if (!"SHA-256".equals(codeChallengeMethod)) {
throw new SigninException("invalid_request", "code_challenge_method must be SHA-256");
@@ -85,7 +100,7 @@ public class SigninService {
if (!"code".equals(responseType) || !"openid".equals(scope)) {
throw new SigninException("invalid_request", "response_type=code and scope=openid are required");
}
validateRedirectUri(clientId, redirectUri);
validateRedirectUri(clientId, redirectUri, requestOrigin);
if (state == null || state.isEmpty() || state.length() > MAX_STATE_LENGTH) {
throw new SigninException("invalid_request", "state must be 1-128 characters");
}
@@ -310,7 +325,7 @@ public class SigninService {
return value != null && PKCE_VALUE_PATTERN.matcher(value).matches();
}
private static void validateRedirectUri(String clientId, String redirectUri) {
private static void validateRedirectUri(String clientId, String redirectUri, URI requestOrigin) {
if (redirectUri == null || redirectUri.isEmpty() || redirectUri.length() > MAX_REDIRECT_URI_LENGTH) {
throw new SigninException("invalid_request", "redirect_uri must be 1-2048 characters");
}
@@ -324,7 +339,7 @@ public class SigninService {
boolean valid = SAME_DEVICE_CLIENT.equals(clientId)
? isSameDeviceRedirect(uri)
: isCrossDeviceRedirect(uri);
: isCrossDeviceRedirect(uri) || isOwnConfirmationRedirect(uri, requestOrigin);
if (!valid) {
throw new SigninException("invalid_request", "redirect_uri is invalid for the AWS Sign-In client");
}
@@ -445,12 +460,46 @@ public class SigninService {
&& uri.getHost() != null
&& AWS_SIGNIN_HOST_PATTERN.matcher(uri.getHost()).matches()
&& uri.getPort() == -1
&& "/v1/sessions/confirmation".equals(uri.getRawPath())
&& CONFIRMATION_PATH.equals(uri.getRawPath())
&& uri.getRawQuery() == null
&& uri.getRawFragment() == null
&& uri.getUserInfo() == null;
}
private static boolean isOwnConfirmationRedirect(URI uri, URI requestOrigin) {
return requestOrigin != null
&& uri.getScheme() != null
&& uri.getScheme().equalsIgnoreCase(requestOrigin.getScheme())
&& uri.getHost() != null
&& uri.getHost().equalsIgnoreCase(requestOrigin.getHost())
&& effectivePort(uri) == effectivePort(requestOrigin)
&& CONFIRMATION_PATH.equals(uri.getRawPath())
&& uri.getRawQuery() == null
&& uri.getRawFragment() == null
&& uri.getUserInfo() == null;
}
private static int effectivePort(URI uri) {
if (uri.getPort() != -1) {
return uri.getPort();
}
return "https".equalsIgnoreCase(uri.getScheme()) ? 443 : 80;
}
/**
* The code the cross-device confirmation page shows, in the form the AWS CLI decodes: base64
* of {@code state=<state>&code=<code>}.
*/
public String verificationCode(String code, String state) {
if (code == null || code.isEmpty() || code.length() > MAX_AUTHORIZATION_CODE_LENGTH
|| state == null || state.isEmpty() || state.length() > MAX_STATE_LENGTH) {
throw new SigninException("invalid_request", "The confirmation request is invalid");
}
String query = "state=" + URLEncoder.encode(state, StandardCharsets.UTF_8)
+ "&code=" + URLEncoder.encode(code, StandardCharsets.UTF_8);
return Base64.getEncoder().encodeToString(query.getBytes(StandardCharsets.UTF_8));
}
private static int remainingSeconds(Instant now, Instant expiresAt) {
Duration remaining = Duration.between(now, expiresAt);
long seconds = remaining.getSeconds() + (remaining.getNano() == 0 ? 0 : 1);
@@ -125,6 +125,18 @@ p + p {
font-weight: 700;
}
.verification-code {
padding: 12px;
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;
overflow-wrap: anywhere;
user-select: all;
}
.notice {
display: flex;
gap: 12px;
@@ -3,6 +3,7 @@ package io.github.hectorvent.floci.services.signin;
import io.github.hectorvent.floci.core.common.Base64Url;
import io.github.hectorvent.floci.core.common.Digests;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.RestAssured;
import io.restassured.response.Response;
import io.restassured.specification.RequestSpecification;
import org.junit.jupiter.api.Test;
@@ -10,10 +11,14 @@ import org.junit.jupiter.api.Test;
import java.net.URI;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.Map;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasKey;
import static org.hamcrest.Matchers.not;
@@ -27,6 +32,7 @@ import static org.junit.jupiter.api.Assertions.assertTrue;
class SigninIntegrationTest {
private static final String CLIENT_ID = "arn:aws:signin:::devtools/same-device";
private static final String CROSS_DEVICE_CLIENT_ID = "arn:aws:signin:::devtools/cross-device";
private static final String REDIRECT_URI = "http://127.0.0.1:4567/oauth/callback";
@Test
@@ -108,6 +114,89 @@ class SigninIntegrationTest {
assertEquals(state, params.get("state"));
}
@Test
void crossDeviceLoginShowsAVerificationCodeTheCliCanExchange() throws Exception {
String verifier = verifier();
String state = UUID.randomUUID().toString();
// What `aws login --remote --endpoint-url <floci>` sends: the endpoint it was given.
String redirectUri = "http://localhost:" + RestAssured.port + "/v1/sessions/confirmation";
String consentLocation = request()
.redirects().follow(false)
.queryParam("client_id", CROSS_DEVICE_CLIENT_ID)
.queryParam("code_challenge", challenge(verifier))
.queryParam("code_challenge_method", "SHA-256")
.queryParam("redirect_uri", redirectUri)
.queryParam("response_type", "code")
.queryParam("scope", "openid")
.queryParam("state", state)
.when()
.get("/v1/authorize")
.then()
.statusCode(302)
.extract()
.header("Location");
String confirmationLocation = approve(consentLocation);
assertTrue(confirmationLocation.startsWith(redirectUri + "?"), confirmationLocation);
String page = request()
.when()
.get(confirmationLocation)
.then()
.statusCode(200)
.header("Cache-Control", equalTo("no-store"))
.contentType(containsString("text/html"))
.extract()
.asString();
Matcher shown = Pattern.compile("<p class=\"verification-code\">([^<]+)</p>").matcher(page);
assertTrue(shown.find(), page);
Map<String, String> pasted = queryParams(
new String(Base64.getDecoder().decode(shown.group(1)), StandardCharsets.UTF_8));
assertEquals(state, pasted.get("state"));
request()
.contentType("application/json")
.body(Map.of(
"clientId", CROSS_DEVICE_CLIENT_ID,
"grantType", "authorization_code",
"code", pasted.get("code"),
"redirectUri", redirectUri,
"codeVerifier", verifier))
.when()
.post("/v1/token")
.then()
.statusCode(200)
.body("tokenType", equalTo("aws_sigv4"))
.body("accessToken.accessKeyId", notNullValue());
}
@Test
void crossDeviceLoginRefusesARedirectToAnotherOrigin() throws Exception {
request()
.redirects().follow(false)
.queryParam("client_id", CROSS_DEVICE_CLIENT_ID)
.queryParam("code_challenge", challenge(verifier()))
.queryParam("code_challenge_method", "SHA-256")
.queryParam("redirect_uri", "http://example.com:" + RestAssured.port + "/v1/sessions/confirmation")
.queryParam("response_type", "code")
.queryParam("scope", "openid")
.queryParam("state", "state")
.when()
.get("/v1/authorize")
.then()
.statusCode(400);
}
@Test
void confirmationPageWithoutACodeIsARequestError() {
request()
.when()
.get("/v1/sessions/confirmation")
.then()
.statusCode(400)
.contentType(containsString("text/html"));
}
@Test
void authorizeRejectsOauthS256Alias() throws Exception {
request()
@@ -10,10 +10,12 @@ 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.time.Duration;
import java.time.Instant;
import java.util.Base64;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
@@ -114,6 +116,38 @@ class SigninServiceTest {
assertInvalidAuthorization(challenge(VERIFIER), CLIENT_ID, "x".repeat(2049), "state");
}
@Test
void crossDeviceRedirectIsAcceptedOnTheOriginTheRequestArrivedOn() throws Exception {
URI origin = URI.create("http://localhost:4566/");
crossDeviceAuthorize("http://localhost:4566/v1/sessions/confirmation", origin);
crossDeviceAuthorize("http://LOCALHOST:4566/v1/sessions/confirmation", origin);
crossDeviceAuthorize("https://floci.example/v1/sessions/confirmation", URI.create("https://floci.example:443/"));
crossDeviceAuthorize("https://us-east-1.signin.aws.amazon.com/v1/sessions/confirmation", origin);
assertInvalidRequest(() -> crossDeviceAuthorize("http://localhost:4567/v1/sessions/confirmation", origin));
assertInvalidRequest(() -> crossDeviceAuthorize("https://localhost:4566/v1/sessions/confirmation", origin));
assertInvalidRequest(() -> crossDeviceAuthorize("http://example.com:4566/v1/sessions/confirmation", origin));
assertInvalidRequest(() -> crossDeviceAuthorize("http://localhost:4566/v1/sessions/other", origin));
assertInvalidRequest(() -> crossDeviceAuthorize("http://localhost:4566/v1/sessions/confirmation?x=1", origin));
assertInvalidRequest(() -> crossDeviceAuthorize("http://user@localhost:4566/v1/sessions/confirmation", origin));
assertInvalidRequest(() -> crossDeviceAuthorize("http://localhost:4566/v1/sessions/confirmation", null));
assertInvalidRequest(() -> service.beginAuthorization(CLIENT_ID, challengeUnchecked(VERIFIER), "SHA-256",
"http://localhost:4566/v1/sessions/confirmation", "code", "openid", "state", null, origin));
}
@Test
void verificationCodeIsTheBase64QueryTheCliDecodes() {
String verificationCode = service.verificationCode("the code/+", "state-1");
String decoded = new String(Base64.getDecoder().decode(verificationCode), StandardCharsets.UTF_8);
assertEquals(Map.of("state", "state-1", "code", "the code/+"), query("https://x/?" + decoded));
assertInvalidRequest(() -> service.verificationCode(null, "state"));
assertInvalidRequest(() -> service.verificationCode("code", ""));
assertInvalidRequest(() -> service.verificationCode("c".repeat(513), "state"));
assertInvalidRequest(() -> service.verificationCode("code", "s".repeat(129)));
}
@Test
void validatesPkceVerifierBoundaries() throws Exception {
String minimumVerifier = "A".repeat(43);
@@ -402,6 +436,11 @@ class SigninServiceTest {
"code", "openid", state, null);
}
private String crossDeviceAuthorize(String redirectUri, URI requestOrigin) {
return service.beginAuthorization(SigninService.CROSS_DEVICE_CLIENT, challengeUnchecked(VERIFIER),
"SHA-256", redirectUri, "code", "openid", "state", null, requestOrigin);
}
private TokenResult exchangeCode(String code, String verifier) {
return service.exchange(CLIENT_ID, "authorization_code", code,
REDIRECT_URI, verifier, null, null);