Verification code
+Copy this code and paste it into the AWS CLI to finish signing in.
+%s
+diff --git a/docs/services/iam.md b/docs/services/iam.md index 9e48dd0476..5f38141553 100644 --- a/docs/services/iam.md +++ b/docs/services/iam.md @@ -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 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 b488cc2edf..c67f29638c 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 @@ -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 = """ + + +
+ + + + + +Copy this code and paste it into the AWS CLI to finish signing in.
+%s
+}.
+ */
+ 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);
diff --git a/src/main/resources/META-INF/resources/_floci/signin/signin.css b/src/main/resources/META-INF/resources/_floci/signin/signin.css
index 9ced682d90..235b8b01fb 100644
--- a/src/main/resources/META-INF/resources/_floci/signin/signin.css
+++ b/src/main/resources/META-INF/resources/_floci/signin/signin.css
@@ -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;
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 6d782aea8e..a1d1aa7c41 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
@@ -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 ` 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("([^<]+)
").matcher(page);
+ assertTrue(shown.find(), page);
+ Map 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()
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 e5325506a6..1c94f01cb5 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
@@ -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);