mirror of
https://github.com/floci-io/floci.git
synced 2026-11-27 07:39:24 -05:00
feat(lambdaweb): enforce IamAuth on Web Function endpoints (#5855)
* fix(lambdaweb): accept role and user ARNs as resource policy principals AWS checks an ARN principal against a pattern that allows a slash, so a role or user ARN passes. Any other AWS principal value is still checked against the pattern without a slash. * feat(lambdaweb): verify SigV4 and InvokeWebFunctionEndpoint on IamAuth endpoints An IamAuth endpoint takes a request signed for the service lambda in the endpoint's region, in the Authorization header or a presigned query. The X-Amz-Content-SHA256 header is required and is the payload hash, as on AWS. A refused request gets the AWS 403 page with no error type. The check runs after the rateLimit 0 page and before the rate limit. Under IAM enforcement the signer also needs lambda:InvokeWebFunctionEndpoint on the endpoint ARN from its identity policy or the function's resource policy, with the auth type and the function tags as condition keys. An Authorization that is an AWS signature is dropped before the app on every endpoint, together with X-Amz-Security-Token. * fix(lambdaweb): give the app the path without dot segments and sign only the normalized path Lambda removes dot segments before the app sees the path, on every endpoint, and keeps repeated slashes and encoded dots. An IamAuth signature counts only over the path as signers normalize it. A signature over the path as sent is refused when the two differ. Floci forwarded the path as sent and took a signature over either form, so a request signed for /a/c could reach the app as /a/./b/../c. * fix(lambdaweb): answer 502 when the caller check fails inside Floci A malformed date or query is still a refused signature. Any other failure, such as in IAM storage, no longer looks like a 403. The endpoint answers it with 502 and no error type, as AWS answers its own failures. * fix(lambdaweb): check a principal against the ARN pattern only under AWS Lambda allows a path only in an ARN under the AWS key. A CanonicalUser or Federated value never matches that pattern. * docs(lambdaweb): MultiRegion SigV4, presigned queries and dot segments on the way to the app * chore(auth): share SigV4 signature parsing and age limits with API Gateway The API Gateway authorizer and Lambda Web IamAuth read a SigV4 signature from the Authorization header or a presigned query, and check its age, in the same way. Both now use one record in core.common.auth. Each still decides which placement wins and where it reads the session token, so neither behaves differently.
This commit is contained in:
1 parent
1d5940944e
commit
5eb4eecf99
16 files changed
+1243
-92
No files matched your search
@@ -0,0 +1,111 @@
|
||||
package io.github.hectorvent.floci.core.common.auth;
|
||||
|
||||
import java.time.DateTimeException;
|
||||
import java.time.Instant;
|
||||
import java.time.ZoneOffset;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.Locale;
|
||||
import java.util.function.UnaryOperator;
|
||||
|
||||
/**
|
||||
* A SigV4 signature as a request carries it, in the {@code Authorization} header or in a presigned
|
||||
* query, and the limits AWS puts on its age. Shared by {@code ExecuteApiSigV4Authorizer} (API Gateway)
|
||||
* and {@code LambdaWebIamAuth} (Lambda Web Functions). Each caller decides which placement wins when a
|
||||
* request carries both, and where it reads the session token.
|
||||
*/
|
||||
public record SigV4SignedRequest(String credential, String signedHeaders, String signature, String amzDate,
|
||||
Long expiresSeconds, boolean presigned) {
|
||||
|
||||
public static final String ALGORITHM = "AWS4-HMAC-SHA256";
|
||||
/** AWS refuses a signing time more than five minutes from its own clock. */
|
||||
public static final long MAX_CLOCK_SKEW_SECONDS = 300;
|
||||
/** The longest {@code X-Amz-Expires} AWS accepts, seven days. */
|
||||
public static final long MAX_PRESIGNED_EXPIRY_SECONDS = 604800;
|
||||
private static final DateTimeFormatter AMZ_DATE =
|
||||
DateTimeFormatter.ofPattern("yyyyMMdd'T'HHmmss'Z'").withZone(ZoneOffset.UTC);
|
||||
|
||||
/** How the signing time compares with the limits. */
|
||||
public enum Freshness {
|
||||
FRESH,
|
||||
/** A presigned {@code X-Amz-Expires} that is missing, not a number, or out of range. */
|
||||
BAD_EXPIRES,
|
||||
EXPIRED,
|
||||
/** Signed more than five minutes ahead of the clock. */
|
||||
NOT_YET_VALID,
|
||||
MALFORMED_DATE
|
||||
}
|
||||
|
||||
/** The signature in an {@code Authorization} header, or null when it is not a complete SigV4 one. */
|
||||
public static SigV4SignedRequest fromHeader(String authorization, String amzDate) {
|
||||
SigV4AuthorizationHeader parsed = SigV4AuthorizationHeader.parse(authorization);
|
||||
if (parsed == null || isBlank(parsed.credential()) || isBlank(parsed.signedHeaders())
|
||||
|| isBlank(parsed.signature()) || isBlank(amzDate)) {
|
||||
return null;
|
||||
}
|
||||
return new SigV4SignedRequest(parsed.credential(), parsed.signedHeaders().toLowerCase(Locale.ROOT),
|
||||
parsed.signature(), amzDate, null, false);
|
||||
}
|
||||
|
||||
/**
|
||||
* The presigned signature in a query, read through {@code parameter} as decoded values, or null
|
||||
* when it is not complete. It does not check {@code X-Amz-Algorithm}.
|
||||
*/
|
||||
public static SigV4SignedRequest fromQuery(UnaryOperator<String> parameter) {
|
||||
String credential = parameter.apply("X-Amz-Credential");
|
||||
String signedHeaders = parameter.apply("X-Amz-SignedHeaders");
|
||||
String signature = parameter.apply("X-Amz-Signature");
|
||||
String amzDate = parameter.apply("X-Amz-Date");
|
||||
if (isBlank(credential) || isBlank(signedHeaders) || isBlank(signature) || isBlank(amzDate)) {
|
||||
return null;
|
||||
}
|
||||
return new SigV4SignedRequest(credential, signedHeaders.toLowerCase(Locale.ROOT), signature, amzDate,
|
||||
expiresSeconds(parameter.apply("X-Amz-Expires")), true);
|
||||
}
|
||||
|
||||
private static Long expiresSeconds(String expires) {
|
||||
if (expires == null) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
return Long.valueOf(expires.trim());
|
||||
} catch (NumberFormatException expected) {
|
||||
// A value that is not a number is reported as BAD_EXPIRES.
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** The signing time, or null when {@code amzDate} is not in the SigV4 form. */
|
||||
public Instant signedAt() {
|
||||
try {
|
||||
return Instant.from(AMZ_DATE.parse(amzDate));
|
||||
} catch (DateTimeException expected) {
|
||||
// Reported as MALFORMED_DATE.
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** Whether the signature is within the time AWS allows at {@code now}. */
|
||||
public Freshness freshness(Instant now) {
|
||||
Instant signedAt = signedAt();
|
||||
if (signedAt == null) {
|
||||
return Freshness.MALFORMED_DATE;
|
||||
}
|
||||
if (presigned) {
|
||||
if (expiresSeconds == null || expiresSeconds < 1 || MAX_PRESIGNED_EXPIRY_SECONDS < expiresSeconds) {
|
||||
return Freshness.BAD_EXPIRES;
|
||||
}
|
||||
if (now.isAfter(signedAt.plusSeconds(expiresSeconds))) {
|
||||
return Freshness.EXPIRED;
|
||||
}
|
||||
return signedAt.isAfter(now.plusSeconds(MAX_CLOCK_SKEW_SECONDS)) ? Freshness.NOT_YET_VALID : Freshness.FRESH;
|
||||
}
|
||||
if (Math.abs(now.getEpochSecond() - signedAt.getEpochSecond()) > MAX_CLOCK_SKEW_SECONDS) {
|
||||
return signedAt.isAfter(now) ? Freshness.NOT_YET_VALID : Freshness.EXPIRED;
|
||||
}
|
||||
return Freshness.FRESH;
|
||||
}
|
||||
|
||||
private static boolean isBlank(String value) {
|
||||
return value == null || value.isBlank();
|
||||
}
|
||||
}
|
||||
+25
-82
@@ -2,9 +2,9 @@ package io.github.hectorvent.floci.services.apigateway;
|
||||
|
||||
import io.github.hectorvent.floci.core.common.RegionResolver;
|
||||
import io.github.hectorvent.floci.core.common.auth.CredentialScope;
|
||||
import io.github.hectorvent.floci.core.common.auth.SigV4AuthorizationHeader;
|
||||
import io.github.hectorvent.floci.core.common.auth.SigV4Canonicalization;
|
||||
import io.github.hectorvent.floci.core.common.auth.SigV4RequestValidator;
|
||||
import io.github.hectorvent.floci.core.common.auth.SigV4SignedRequest;
|
||||
import io.github.hectorvent.floci.services.iam.IamService;
|
||||
import io.github.hectorvent.floci.services.iam.model.AccessKey;
|
||||
import io.github.hectorvent.floci.services.iam.model.IamUser;
|
||||
@@ -19,9 +19,6 @@ import java.net.URI;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.MessageDigest;
|
||||
import java.time.Instant;
|
||||
import java.time.ZoneOffset;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.Locale;
|
||||
|
||||
/**
|
||||
* Verifies the SigV4 signature on an execute-api data-plane request, so a route or method whose
|
||||
@@ -55,20 +52,7 @@ public class ExecuteApiSigV4Authorizer {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(ExecuteApiSigV4Authorizer.class);
|
||||
|
||||
private static final String ALGORITHM = "AWS4-HMAC-SHA256";
|
||||
private static final String SIGNING_SERVICE = "execute-api";
|
||||
private static final DateTimeFormatter AMZ_DATE =
|
||||
DateTimeFormatter.ofPattern("yyyyMMdd'T'HHmmss'Z'").withZone(ZoneOffset.UTC);
|
||||
|
||||
/**
|
||||
* Real API Gateway rejects a header-signed request whose {@code X-Amz-Date} is more than five
|
||||
* minutes from the service's clock. Emulating it keeps a captured request from being replayed
|
||||
* indefinitely against a route the caller is testing authorization on.
|
||||
*/
|
||||
private static final long MAX_CLOCK_SKEW_SECONDS = 300;
|
||||
|
||||
/** Longest {@code X-Amz-Expires} AWS accepts on a presigned request (7 days). */
|
||||
private static final long MAX_PRESIGNED_EXPIRY_SECONDS = 604800;
|
||||
|
||||
/** Where a temporary credential's session token rides: a header, or a presigned query parameter. */
|
||||
private static final String SECURITY_TOKEN = "X-Amz-Security-Token";
|
||||
@@ -134,15 +118,15 @@ public class ExecuteApiSigV4Authorizer {
|
||||
String signedRequestPath) throws Exception {
|
||||
MultivaluedMap<String, String> queryParameters = uriInfo.getQueryParameters();
|
||||
String authorization = headers == null ? null : headers.getHeaderString(HttpHeaders.AUTHORIZATION);
|
||||
boolean presigned = ALGORITHM.equals(queryParameters.getFirst("X-Amz-Algorithm"));
|
||||
boolean presigned = SigV4SignedRequest.ALGORITHM.equals(queryParameters.getFirst("X-Amz-Algorithm"));
|
||||
|
||||
if (!presigned && (authorization == null || authorization.isBlank())) {
|
||||
return Result.rejected(Failure.MISSING, "request is not SigV4-signed");
|
||||
}
|
||||
|
||||
SignedRequest signed = presigned
|
||||
? presignedRequest(queryParameters)
|
||||
: headerSignedRequest(authorization, headers);
|
||||
SigV4SignedRequest signed = presigned
|
||||
? SigV4SignedRequest.fromQuery(queryParameters::getFirst)
|
||||
: SigV4SignedRequest.fromHeader(authorization, amzDate(headers));
|
||||
if (signed == null) {
|
||||
return Result.rejected(Failure.MALFORMED, "SigV4 credentials are incomplete");
|
||||
}
|
||||
@@ -168,8 +152,7 @@ public class ExecuteApiSigV4Authorizer {
|
||||
return Result.rejected(Failure.MALFORMED, "SignedHeaders does not cover host");
|
||||
}
|
||||
|
||||
Instant signedAt = Instant.from(AMZ_DATE.parse(signed.amzDate()));
|
||||
Result expiry = checkExpiry(signedAt, signed.expiresSeconds(), presigned);
|
||||
Result expiry = checkExpiry(signed);
|
||||
if (expiry != null) {
|
||||
return expiry;
|
||||
}
|
||||
@@ -207,26 +190,23 @@ public class ExecuteApiSigV4Authorizer {
|
||||
return Result.rejected(Failure.MISMATCH, "signature does not match");
|
||||
}
|
||||
|
||||
private Result checkExpiry(Instant signedAt, Long expiresSeconds, boolean presigned) {
|
||||
Instant now = Instant.now();
|
||||
if (presigned) {
|
||||
if (expiresSeconds == null || expiresSeconds < 1 || expiresSeconds > MAX_PRESIGNED_EXPIRY_SECONDS) {
|
||||
return Result.rejected(Failure.MALFORMED, "X-Amz-Expires is missing or out of range");
|
||||
}
|
||||
if (now.isAfter(signedAt.plusSeconds(expiresSeconds))) {
|
||||
return Result.rejected(Failure.EXPIRED, "presigned request expired");
|
||||
}
|
||||
/**
|
||||
* Real API Gateway rejects a header-signed request whose {@code X-Amz-Date} is more than five
|
||||
* minutes from the service's clock. Emulating it keeps a captured request from being replayed
|
||||
* indefinitely against a route the caller is testing authorization on.
|
||||
*/
|
||||
private static Result checkExpiry(SigV4SignedRequest signed) {
|
||||
return switch (signed.freshness(Instant.now())) {
|
||||
case FRESH -> null;
|
||||
case MALFORMED_DATE -> Result.rejected(Failure.MALFORMED, "signature could not be verified");
|
||||
case BAD_EXPIRES -> Result.rejected(Failure.MALFORMED, "X-Amz-Expires is missing or out of range");
|
||||
case EXPIRED -> Result.rejected(Failure.EXPIRED, signed.presigned() ? "presigned request expired"
|
||||
: "signature date " + signed.amzDate() + " is outside the accepted window");
|
||||
// A presigned URL signed in the future is still a forgery attempt, not a slow clock.
|
||||
if (signedAt.isAfter(now.plusSeconds(MAX_CLOCK_SKEW_SECONDS))) {
|
||||
return Result.rejected(Failure.EXPIRED, "presigned request is not yet valid");
|
||||
}
|
||||
return null;
|
||||
}
|
||||
if (Math.abs(now.getEpochSecond() - signedAt.getEpochSecond()) > MAX_CLOCK_SKEW_SECONDS) {
|
||||
return Result.rejected(Failure.EXPIRED,
|
||||
"signature date " + AMZ_DATE.format(signedAt) + " is outside the accepted window");
|
||||
}
|
||||
return null;
|
||||
case NOT_YET_VALID -> Result.rejected(Failure.EXPIRED, signed.presigned()
|
||||
? "presigned request is not yet valid"
|
||||
: "signature date " + signed.amzDate() + " is outside the accepted window");
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -326,47 +306,10 @@ public class ExecuteApiSigV4Authorizer {
|
||||
return new CallerIdentity(accessKeyId, accountId, userArn, userId);
|
||||
}
|
||||
|
||||
// ──────────────────────────── Signed-request parsing ────────────────────────────
|
||||
|
||||
private record SignedRequest(String credential, String signedHeaders, String signature,
|
||||
String amzDate, Long expiresSeconds) {}
|
||||
|
||||
private static SignedRequest headerSignedRequest(String authorization, HttpHeaders headers) {
|
||||
SigV4AuthorizationHeader parsed = SigV4AuthorizationHeader.parse(authorization);
|
||||
if (parsed == null) {
|
||||
return null;
|
||||
}
|
||||
/** The signing time of a header signature: {@code X-Amz-Date}, or {@code Date} when it is absent. */
|
||||
private static String amzDate(HttpHeaders headers) {
|
||||
String amzDate = headers.getHeaderString("X-Amz-Date");
|
||||
if (amzDate == null || amzDate.isBlank()) {
|
||||
amzDate = headers.getHeaderString("Date");
|
||||
}
|
||||
if (isBlank(parsed.credential()) || isBlank(parsed.signedHeaders())
|
||||
|| isBlank(parsed.signature()) || isBlank(amzDate)) {
|
||||
return null;
|
||||
}
|
||||
return new SignedRequest(parsed.credential(), parsed.signedHeaders().toLowerCase(Locale.ROOT),
|
||||
parsed.signature(), amzDate, null);
|
||||
}
|
||||
|
||||
private static SignedRequest presignedRequest(MultivaluedMap<String, String> queryParameters) {
|
||||
String credential = queryParameters.getFirst("X-Amz-Credential");
|
||||
String signedHeaders = queryParameters.getFirst("X-Amz-SignedHeaders");
|
||||
String signature = queryParameters.getFirst("X-Amz-Signature");
|
||||
String amzDate = queryParameters.getFirst("X-Amz-Date");
|
||||
String expires = queryParameters.getFirst("X-Amz-Expires");
|
||||
if (isBlank(credential) || isBlank(signedHeaders) || isBlank(signature) || isBlank(amzDate)) {
|
||||
return null;
|
||||
}
|
||||
Long expiresSeconds;
|
||||
try {
|
||||
expiresSeconds = expires == null ? null : Long.valueOf(expires.trim());
|
||||
} catch (NumberFormatException e) {
|
||||
LOG.debugv("execute-api presigned request carries a non-numeric X-Amz-Expires: {0}",
|
||||
SigV4RequestValidator.sanitizeForLog(expires));
|
||||
expiresSeconds = null;
|
||||
}
|
||||
return new SignedRequest(credential, signedHeaders.toLowerCase(Locale.ROOT), signature,
|
||||
amzDate, expiresSeconds);
|
||||
return isBlank(amzDate) ? headers.getHeaderString("Date") : amzDate;
|
||||
}
|
||||
|
||||
// ──────────────────────────── Canonical request ────────────────────────────
|
||||
|
||||
+88
-4
@@ -29,6 +29,7 @@ import jakarta.enterprise.event.Observes;
|
||||
import jakarta.inject.Inject;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.time.ZoneOffset;
|
||||
@@ -59,6 +60,7 @@ public class LambdaWebDataPlane {
|
||||
static final Set<String> DROPPED_RESPONSE_HEADERS = Set.of("connection", "keep-alive", "transfer-encoding",
|
||||
"upgrade", "te", "trailer", "trailers", "proxy-authenticate", "proxy-authorization");
|
||||
static final String REQUEST_ID_HEADER = "lambda-web-request-id";
|
||||
private static final String IAM_AUTH = "IamAuth";
|
||||
private static final Pattern ENDPOINT_DOMAIN = Pattern.compile(
|
||||
"[a-z0-9]{16}\\.(?:[0-9]{3}\\.lambda-web\\.[a-z0-9-]+|lambda-web\\.global)\\..+", Pattern.CASE_INSENSITIVE);
|
||||
private static final Logger LOG = Logger.getLogger(LambdaWebDataPlane.class);
|
||||
@@ -70,6 +72,7 @@ public class LambdaWebDataPlane {
|
||||
|
||||
private final LambdaWebService service;
|
||||
private final LambdaWebEnvironmentManager environments;
|
||||
private final LambdaWebIamAuth iamAuth;
|
||||
private final ServiceConfigAccess serviceConfigAccess;
|
||||
private final Vertx vertx;
|
||||
private final HttpClient client;
|
||||
@@ -77,9 +80,10 @@ public class LambdaWebDataPlane {
|
||||
|
||||
@Inject
|
||||
public LambdaWebDataPlane(LambdaWebService service, LambdaWebEnvironmentManager environments,
|
||||
ServiceConfigAccess serviceConfigAccess, Vertx vertx) {
|
||||
LambdaWebIamAuth iamAuth, ServiceConfigAccess serviceConfigAccess, Vertx vertx) {
|
||||
this.service = service;
|
||||
this.environments = environments;
|
||||
this.iamAuth = iamAuth;
|
||||
this.serviceConfigAccess = serviceConfigAccess;
|
||||
this.vertx = vertx;
|
||||
this.client = vertx.createHttpClient(new HttpClientOptions()
|
||||
@@ -119,12 +123,38 @@ public class LambdaWebDataPlane {
|
||||
page(request, LambdaWebErrorPages.ENDPOINT_DISABLED, requestId, false);
|
||||
return;
|
||||
}
|
||||
if (!IAM_AUTH.equals(target.endpoint().authType)) {
|
||||
admit(request, host, target, requestId);
|
||||
return;
|
||||
}
|
||||
// The signature is checked before the rate limit, so refused requests take no tokens.
|
||||
request.pause();
|
||||
LambdaWebIamAuth.Inbound signed = LambdaWebIamAuth.Inbound.of(request);
|
||||
vertx.<Boolean>executeBlocking(() -> iamAuth.allows(signed, target), false).onComplete(allowed -> {
|
||||
if (allowed.succeeded() && allowed.result()) {
|
||||
admit(request, host, target, requestId);
|
||||
return;
|
||||
}
|
||||
request.resume();
|
||||
if (allowed.failed()) {
|
||||
LOG.errorv(allowed.cause(), "Could not check the caller of {0}", host);
|
||||
internalError(request, requestId);
|
||||
return;
|
||||
}
|
||||
page(request, LambdaWebErrorPages.FORBIDDEN, requestId, false);
|
||||
});
|
||||
}
|
||||
|
||||
private void admit(HttpServerRequest request, String host, WebFunctionTarget target, String requestId) {
|
||||
Integer rateLimit = target.endpoint().throttleConfig == null ? null : target.endpoint().throttleConfig.rateLimit;
|
||||
if (rateLimit != null && !rateLimiter.tryAcquire(endpointKey(target), rateLimit)) {
|
||||
request.resume();
|
||||
page(request, LambdaWebErrorPages.ENDPOINT_REQUEST_THROTTLE, requestId, false);
|
||||
return;
|
||||
}
|
||||
WebFunctionRevision revision = LambdaWebService.pickRevision(target);
|
||||
if (revision == null) {
|
||||
request.resume();
|
||||
page(request, LambdaWebErrorPages.ORIGIN_REQUEST_ERROR, requestId, false);
|
||||
return;
|
||||
}
|
||||
@@ -183,7 +213,7 @@ public class LambdaWebDataPlane {
|
||||
RequestOptions options = new RequestOptions()
|
||||
.setHost(environment.host())
|
||||
.setPort(environment.port())
|
||||
.setURI(request.uri())
|
||||
.setURI(upstreamUri(request))
|
||||
.setMethod(request.method());
|
||||
client.request(options).onSuccess(upstream -> {
|
||||
copyRequestHeaders(request, upstream, host, target.endpoint().endpointName, requestId);
|
||||
@@ -376,6 +406,49 @@ public class LambdaWebDataPlane {
|
||||
return ENDPOINT_DOMAIN.matcher(host).matches();
|
||||
}
|
||||
|
||||
/** The app gets the path without dot segments, as on AWS. Repeated slashes and the query stay as sent. */
|
||||
static String upstreamUri(HttpServerRequest request) {
|
||||
String path = request.path();
|
||||
if (path == null) {
|
||||
return request.uri();
|
||||
}
|
||||
String query = request.query();
|
||||
return withoutDotSegments(path) + (query == null ? "" : "?" + query);
|
||||
}
|
||||
|
||||
/** RFC 3986 section 5.2.4. */
|
||||
static String withoutDotSegments(String path) {
|
||||
String in = path;
|
||||
StringBuilder out = new StringBuilder();
|
||||
while (!in.isEmpty()) {
|
||||
if (in.startsWith("../")) {
|
||||
in = in.substring(3);
|
||||
} else if (in.startsWith("./") || in.startsWith("/./")) {
|
||||
in = in.substring(2);
|
||||
} else if (in.equals("/.")) {
|
||||
in = "/";
|
||||
} else if (in.startsWith("/../")) {
|
||||
in = in.substring(3);
|
||||
removeLastSegment(out);
|
||||
} else if (in.equals("/..")) {
|
||||
in = "/";
|
||||
removeLastSegment(out);
|
||||
} else if (in.equals(".") || in.equals("..")) {
|
||||
in = "";
|
||||
} else {
|
||||
int next = in.indexOf('/', in.startsWith("/") ? 1 : 0);
|
||||
int end = next < 0 ? in.length() : next;
|
||||
out.append(in, 0, end);
|
||||
in = in.substring(end);
|
||||
}
|
||||
}
|
||||
return out.toString();
|
||||
}
|
||||
|
||||
private static void removeLastSegment(StringBuilder out) {
|
||||
out.setLength(Math.max(out.lastIndexOf("/"), 0));
|
||||
}
|
||||
|
||||
static boolean hasBody(HttpMethod method, int status) {
|
||||
return method != HttpMethod.HEAD && status >= 200 && status != 204 && status != 304;
|
||||
}
|
||||
@@ -388,6 +461,12 @@ public class LambdaWebDataPlane {
|
||||
dropped.add(token.trim().toLowerCase(Locale.ROOT));
|
||||
}
|
||||
}
|
||||
// An AWS signature and its session token never reach the app, whatever the auth type.
|
||||
String authorization = request.getHeader("Authorization");
|
||||
if (authorization != null && authorization.startsWith("AWS4-")) {
|
||||
dropped.add("authorization");
|
||||
dropped.add("x-amz-security-token");
|
||||
}
|
||||
MultiMap headers = upstream.headers();
|
||||
for (Map.Entry<String, String> header : request.headers()) {
|
||||
String name = header.getKey().toLowerCase(Locale.ROOT);
|
||||
@@ -445,9 +524,14 @@ public class LambdaWebDataPlane {
|
||||
response.headers().set("content-type", "text/html");
|
||||
response.headers().set("connection", close ? "close" : "keep-alive");
|
||||
response.headers().set(REQUEST_ID_HEADER, requestId);
|
||||
response.headers().set("lambda-web-error-type", page.errorType());
|
||||
if (page.errorType() != null) {
|
||||
response.headers().set("lambda-web-error-type", page.errorType());
|
||||
}
|
||||
response.headers().set("date", HTTP_DATE.format(Instant.now()));
|
||||
response.end(LambdaWebErrorPages.html(page, requestId)).onComplete(ignored -> {
|
||||
String html = LambdaWebErrorPages.html(page, requestId);
|
||||
// A HEAD request gets the length of the page it does not get, as on AWS.
|
||||
response.headers().set("content-length", String.valueOf(html.getBytes(StandardCharsets.UTF_8).length));
|
||||
response.end(html).onComplete(ignored -> {
|
||||
if (close) {
|
||||
response.close();
|
||||
}
|
||||
|
||||
@@ -15,6 +15,8 @@ final class LambdaWebErrorPages {
|
||||
|
||||
static final Page UNSUPPORTED_HTTP_VERSION = new Page(505, "HTTP Version Not Supported",
|
||||
"Platform.UnsupportedHttpVersion", "The provided HTTP version is not supported. Please use HTTP/1.1.");
|
||||
/** An IamAuth refusal names no error type. */
|
||||
static final Page FORBIDDEN = new Page(403, "Forbidden", null, "You are not authorized to access this endpoint.");
|
||||
static final Page INVALID_ENDPOINT = new Page(404, "Not Found", "Platform.InvalidEndpoint",
|
||||
"The requested endpoint could not be found.");
|
||||
static final Page ENDPOINT_DISABLED = new Page(503, "Service Unavailable", "Platform.EndpointDisabled",
|
||||
|
||||
@@ -0,0 +1,247 @@
|
||||
package io.github.hectorvent.floci.services.lambdaweb;
|
||||
|
||||
import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import io.github.hectorvent.floci.core.common.IamConditionContextResolver;
|
||||
import io.github.hectorvent.floci.core.common.RequestScopes;
|
||||
import io.github.hectorvent.floci.core.common.auth.CredentialScope;
|
||||
import io.github.hectorvent.floci.core.common.auth.SigV4Canonicalization;
|
||||
import io.github.hectorvent.floci.core.common.auth.SigV4RequestValidator;
|
||||
import io.github.hectorvent.floci.core.common.auth.SigV4SignedRequest;
|
||||
import io.github.hectorvent.floci.core.common.auth.SigV4SignedRequest.Freshness;
|
||||
import io.github.hectorvent.floci.services.iam.IamPolicyEvaluator;
|
||||
import io.github.hectorvent.floci.services.iam.IamPolicyEvaluator.Decision;
|
||||
import io.github.hectorvent.floci.services.iam.IamPolicyEvaluator.ResourceAccountRelationship;
|
||||
import io.github.hectorvent.floci.services.iam.IamPolicyEvaluator.ResourcePolicyDecision;
|
||||
import io.github.hectorvent.floci.services.iam.IamService;
|
||||
import io.github.hectorvent.floci.services.iam.IamService.CallerArns;
|
||||
import io.github.hectorvent.floci.services.iam.IamService.OwnedSecretKey;
|
||||
import io.github.hectorvent.floci.services.iam.RequestPrincipal;
|
||||
import io.github.hectorvent.floci.services.iam.ScpProvider;
|
||||
import io.github.hectorvent.floci.services.iam.model.CallerContext;
|
||||
import io.github.hectorvent.floci.services.lambdaweb.LambdaWebService.WebFunctionTarget;
|
||||
import io.vertx.core.MultiMap;
|
||||
import io.vertx.core.http.HttpServerRequest;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.enterprise.inject.Instance;
|
||||
import jakarta.inject.Inject;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
|
||||
/**
|
||||
* The checks an {@code IamAuth} endpoint makes before a request reaches the function: a SigV4
|
||||
* signature for the service {@code lambda} in the endpoint's region, then
|
||||
* {@code lambda:InvokeWebFunctionEndpoint} on the endpoint ARN. The signature is always checked.
|
||||
* The policies are evaluated when IAM enforcement is on, as everywhere else in Floci.
|
||||
*/
|
||||
@ApplicationScoped
|
||||
public class LambdaWebIamAuth {
|
||||
|
||||
private static final String ACTION = "lambda:InvokeWebFunctionEndpoint";
|
||||
private static final Logger LOG = Logger.getLogger(LambdaWebIamAuth.class);
|
||||
private static final String SERVICE = "lambda";
|
||||
private static final String SECURITY_TOKEN = "X-Amz-Security-Token";
|
||||
private static final String TEST_ACCESS_KEY = "test";
|
||||
|
||||
private final EmulatorConfig config;
|
||||
private final IamService iamService;
|
||||
private final IamPolicyEvaluator evaluator;
|
||||
private final Instance<ScpProvider> scpProvider;
|
||||
|
||||
@Inject
|
||||
public LambdaWebIamAuth(EmulatorConfig config, IamService iamService, IamPolicyEvaluator evaluator,
|
||||
Instance<ScpProvider> scpProvider) {
|
||||
this.config = config;
|
||||
this.iamService = iamService;
|
||||
this.evaluator = evaluator;
|
||||
this.scpProvider = scpProvider;
|
||||
}
|
||||
|
||||
/** What the checks read from a request, copied on the event loop so a worker can check it. */
|
||||
public record Inbound(String method, String path, String query, MultiMap headers, MultiMap params) {
|
||||
|
||||
static Inbound of(HttpServerRequest request) {
|
||||
MultiMap params = MultiMap.caseInsensitiveMultiMap();
|
||||
try {
|
||||
params.addAll(request.params());
|
||||
} catch (IllegalArgumentException e) {
|
||||
LOG.debugv("A request to a Lambda Web endpoint has a query that does not decode: {0}", e.getMessage());
|
||||
}
|
||||
return new Inbound(request.method().name(), request.path(), request.query(),
|
||||
MultiMap.caseInsensitiveMultiMap().addAll(request.headers()), params);
|
||||
}
|
||||
}
|
||||
|
||||
/** A signature and the session token that came with it. */
|
||||
private record Signed(SigV4SignedRequest request, String sessionToken) {
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether the request may invoke the target endpoint. A failure inside Floci, such as in IAM
|
||||
* storage, is thrown rather than taken for a refusal. Blocks on IAM storage.
|
||||
*/
|
||||
public boolean allows(Inbound request, WebFunctionTarget target) {
|
||||
String accessKeyId = authenticate(request, target.region());
|
||||
return accessKeyId != null && authorize(accessKeyId, target);
|
||||
}
|
||||
|
||||
/** The access key that signed the request, or null when the signature does not hold. */
|
||||
private String authenticate(Inbound request, String region) {
|
||||
Signed found = signed(request);
|
||||
// Lambda takes this header as the payload hash and never reads the body.
|
||||
String payloadHash = request.headers().get("X-Amz-Content-SHA256");
|
||||
if (found == null || isBlank(payloadHash)) {
|
||||
return null;
|
||||
}
|
||||
SigV4SignedRequest signed = found.request();
|
||||
CredentialScope scope = CredentialScope.parse(signed.credential());
|
||||
if (scope == null || !SERVICE.equals(scope.service()) || !region.equals(scope.region())
|
||||
|| !signed.amzDate().startsWith(scope.date())
|
||||
|| !SigV4RequestValidator.containsHeader(signed.signedHeaders(), "host")
|
||||
|| signed.freshness(Instant.now()) != Freshness.FRESH) {
|
||||
return null;
|
||||
}
|
||||
String secretKey = secretKey(scope.accessKeyId(), found.sessionToken());
|
||||
if (secretKey == null) {
|
||||
LOG.debugv("A request to a Lambda Web endpoint names an unknown access key {0}",
|
||||
SigV4RequestValidator.sanitizeForLog(scope.accessKeyId()));
|
||||
return null;
|
||||
}
|
||||
String canonicalHeaders = SigV4Canonicalization.canonicalHeaders(signed.signedHeaders(),
|
||||
name -> String.join(",", request.headers().getAll(name)));
|
||||
String canonicalQuery;
|
||||
try {
|
||||
canonicalQuery = SigV4Canonicalization.canonicalQueryString(request.query(), signed.presigned());
|
||||
} catch (IllegalArgumentException e) {
|
||||
LOG.debugv("A request to a Lambda Web endpoint has a query that does not decode: {0}", e.getMessage());
|
||||
return null;
|
||||
}
|
||||
boolean matches;
|
||||
try {
|
||||
matches = SigV4Canonicalization.signatureMatches(request.method(), signedPath(request.path()),
|
||||
canonicalQuery, canonicalHeaders, signed.signedHeaders(), payloadHash, signed.amzDate(), scope,
|
||||
secretKey, signed.signature());
|
||||
} catch (Exception e) {
|
||||
throw new IllegalStateException("Could not compute a SigV4 signature", e);
|
||||
}
|
||||
return matches ? scope.accessKeyId() : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* The path as signers sign it, with dot segments resolved and empty segments dropped. Lambda
|
||||
* refuses a signature over the path as sent when the two differ.
|
||||
*/
|
||||
static String signedPath(String path) {
|
||||
List<String> segments = new ArrayList<>();
|
||||
for (String segment : path.split("/")) {
|
||||
if (segment.equals("..")) {
|
||||
if (!segments.isEmpty()) {
|
||||
segments.removeLast();
|
||||
}
|
||||
} else if (!segment.isEmpty() && !segment.equals(".")) {
|
||||
segments.add(segment);
|
||||
}
|
||||
}
|
||||
String first = path.startsWith("/") ? "/" : "";
|
||||
String last = path.endsWith("/") && !segments.isEmpty() ? "/" : "";
|
||||
return first + String.join("/", segments) + last;
|
||||
}
|
||||
|
||||
/**
|
||||
* The header signature, or the presigned query when there is no {@code Authorization} header.
|
||||
* The header wins over the query, as on AWS.
|
||||
*/
|
||||
private static Signed signed(Inbound request) {
|
||||
String authorization = request.headers().get("Authorization");
|
||||
if (isBlank(authorization)) {
|
||||
MultiMap params = request.params();
|
||||
if (!SigV4SignedRequest.ALGORITHM.equals(params.get("X-Amz-Algorithm"))) {
|
||||
return null;
|
||||
}
|
||||
SigV4SignedRequest presigned = SigV4SignedRequest.fromQuery(params::get);
|
||||
return presigned == null ? null : new Signed(presigned, params.get(SECURITY_TOKEN));
|
||||
}
|
||||
SigV4SignedRequest header = SigV4SignedRequest.fromHeader(authorization, request.headers().get("X-Amz-Date"));
|
||||
return header == null ? null : new Signed(header, request.headers().get(SECURITY_TOKEN));
|
||||
}
|
||||
|
||||
/**
|
||||
* The secret of a key Floci issued. A temporary key needs its session token, and a long-term
|
||||
* key with a session token is refused, as on AWS. The local {@code test} key signs with
|
||||
* {@code test}.
|
||||
*/
|
||||
private String secretKey(String accessKeyId, String sessionToken) {
|
||||
if (TEST_ACCESS_KEY.equals(accessKeyId)) {
|
||||
return TEST_ACCESS_KEY;
|
||||
}
|
||||
boolean temporary = IamService.isTemporaryAccessKey(accessKeyId);
|
||||
if (temporary && isBlank(sessionToken) || !temporary && !isBlank(sessionToken)) {
|
||||
return null;
|
||||
}
|
||||
return iamService.findSecretKeyInAnyAccount(accessKeyId, sessionToken)
|
||||
.map(OwnedSecretKey::secretAccessKey)
|
||||
.orElse(null);
|
||||
}
|
||||
|
||||
private boolean authorize(String accessKeyId, WebFunctionTarget target) {
|
||||
if (!config.services().iam().enforcementEnabled() || TEST_ACCESS_KEY.equals(accessKeyId)) {
|
||||
return true;
|
||||
}
|
||||
Optional<String> callerAccount = iamService.resolveAccountId(accessKeyId);
|
||||
if (callerAccount.isEmpty()) {
|
||||
return false;
|
||||
}
|
||||
boolean allowed = RequestScopes.callAs(callerAccount.get(), target.region(),
|
||||
() -> evaluate(accessKeyId, callerAccount.get(), target));
|
||||
if (!allowed) {
|
||||
LOG.infov("IAM enforcement DENY: akid={0} action={1} resource={2}",
|
||||
SigV4RequestValidator.sanitizeForLog(accessKeyId), ACTION, target.endpoint().endpointArn);
|
||||
}
|
||||
return allowed;
|
||||
}
|
||||
|
||||
/**
|
||||
* Within one account the caller's policies or the function's resource policy can allow the
|
||||
* call, across accounts both have to, and an explicit deny in either refuses it.
|
||||
*/
|
||||
private boolean evaluate(String accessKeyId, String callerAccount, WebFunctionTarget target) {
|
||||
CallerContext caller = iamService.resolveCallerContext(accessKeyId, Instant.now());
|
||||
if (caller == null) {
|
||||
// A known credential with no policies to evaluate, as the enforcement filter treats it.
|
||||
return true;
|
||||
}
|
||||
List<List<String>> scpLevels = scpProvider.isResolvable()
|
||||
? scpProvider.get().effectiveScpLevels(callerAccount) : null;
|
||||
if (scpLevels != null) {
|
||||
caller = caller.withScpLevels(scpLevels);
|
||||
}
|
||||
Map<String, List<String>> context = new HashMap<>();
|
||||
context.put("lambda:Resource/WebFunctionAuthType", List.of(target.endpoint().authType));
|
||||
target.function().tags.forEach((key, value) -> context.put("aws:ResourceTag/" + key, List.of(value)));
|
||||
Optional<CallerArns> callerArns = iamService.resolveCallerArns(accessKeyId);
|
||||
if (callerArns.isPresent()) {
|
||||
caller = caller.withPrincipalArn(callerArns.get().callerArn());
|
||||
callerArns.get().putPrincipalKeys(context);
|
||||
}
|
||||
String endpointArn = target.endpoint().endpointArn;
|
||||
Map<String, List<String>> effective = IamConditionContextResolver.withGlobalContext(
|
||||
context, endpointArn, target.region(), callerAccount, target.accountId());
|
||||
String policy = target.function().policy;
|
||||
ResourcePolicyDecision grant = evaluator.evaluateResourcePolicyFor(
|
||||
isBlank(policy) ? null : List.of(policy), RequestPrincipal.caller(callerArns.orElse(null)),
|
||||
ACTION, endpointArn, effective);
|
||||
ResourceAccountRelationship relationship = callerAccount.equals(target.accountId())
|
||||
? ResourceAccountRelationship.SAME_ACCOUNT : ResourceAccountRelationship.CROSS_ACCOUNT;
|
||||
return evaluator.evaluateResolvedResourcePolicy(caller, grant, relationship, ACTION, endpointArn, effective)
|
||||
!= Decision.DENY;
|
||||
}
|
||||
|
||||
private static boolean isBlank(String value) {
|
||||
return value == null || value.isBlank();
|
||||
}
|
||||
}
|
||||
@@ -122,6 +122,7 @@ public class LambdaWebService implements Resettable {
|
||||
private static final Pattern FILTER_NAME = Pattern.compile("[a-zA-Z0-9]+");
|
||||
private static final Pattern FILTER_VALUE = Pattern.compile("[a-zA-Z0-9_-]+");
|
||||
private static final Pattern PRINCIPAL_AWS = Pattern.compile("[\\w+=,.@\\:-]*");
|
||||
private static final Pattern PRINCIPAL_AWS_ARN = Pattern.compile("[\\w+=/:,.@-]*");
|
||||
private static final Pattern PRINCIPAL_SERVICE = Pattern.compile("[\\w+=,.@-]*");
|
||||
|
||||
/** AWS assigns one shard label per cell. */
|
||||
@@ -1198,11 +1199,12 @@ public class LambdaWebService implements Resettable {
|
||||
if (!PRINCIPAL_KEYS.contains(field.getKey())) {
|
||||
throw policySyntax();
|
||||
}
|
||||
Pattern allowed = "Service".equals(field.getKey()) ? PRINCIPAL_SERVICE : PRINCIPAL_AWS;
|
||||
if (field.getValue().isArray() && field.getValue().isEmpty()) {
|
||||
throw new AwsException("ValidationException", INVALID_PRINCIPAL, 400);
|
||||
}
|
||||
for (String value : policyValues(field.getValue())) {
|
||||
Pattern allowed = "Service".equals(field.getKey()) ? PRINCIPAL_SERVICE
|
||||
: "AWS".equals(field.getKey()) && AwsArnUtils.isArn(value) ? PRINCIPAL_AWS_ARN : PRINCIPAL_AWS;
|
||||
if (!"*".equals(value) && !allowed.matcher(value).matches()) {
|
||||
throw new AwsException("ValidationException", "The provided input'" + value
|
||||
+ "'was invalid. Member must satisfy expression: " + allowed.pattern()
|
||||
|
||||
Reference in new issue
Block a user