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:
TATSUNO “Taz” Yasuhiro authored and GitHub committed 2026-10-17 08:12:48 -04:00
1 parent 1d5940944e
commit 5eb4eecf99
16 files changed
+1243 -92

No files matched your search

+6 -3
View File
@@ -37,11 +37,11 @@ The `Lambda Web` service model (apiVersion 2025-03-07, `aws lambda-web` in the A
- **Instant convergence:** a revision and an endpoint are stored `Active` and an endpoint update is stored `Successful`. The create and update responses still report the transitional state AWS reports (`Pending`, `updateStatus: InProgress`, and the per-region block as it was before the update), so a waiter sees one poll.
- **Code comes from S3 only.** The object named in `buildConfig.codeConfig.s3Object` must exist in Floci's S3, as on AWS. AWS also requires bucket versioning and a bucket policy for the Lambda service principal. Floci does not check them yet, and the revision does not pin a `versionId` the request did not give yet.
- **Execution role and network connector** ARNs are checked for shape only. The assume-role check AWS makes is not done yet.
- **Resource policies** are checked the way AWS checks them before storing: the document grammar, a `lambda:` action, a `Resource` that names the function, a valid principal, and no public `Allow`. A wildcard principal needs a positive condition (`StringEquals`, `StringLike`, `ArnLike`, `Bool`) on a trusted key such as `aws:PrincipalAccount` or `aws:PrincipalArn`, with no wildcard in the account it names. The policy is not evaluated on requests yet.
- **Resource policies** are checked the way AWS checks them before storing: the document grammar, a `lambda:` action, a `Resource` that names the function, a valid principal, and no public `Allow`. A wildcard principal needs a positive condition (`StringEquals`, `StringLike`, `ArnLike`, `Bool`) on a trusted key such as `aws:PrincipalAccount` or `aws:PrincipalArn`, with no wildcard in the account it names. An `IamAuth` endpoint evaluates it on requests, as below.
- **ARNs** given as identifiers must name the request's region and the caller's account, as on AWS. A revision or endpoint ARN resolves by its id or name only.
- **Page tokens** are base64 cursors that carry the request and the position of the page, not the UUIDs AWS issues. A token reused with other parameters gets the AWS "does not match the request" error, and any other token the "invalid or has expired" error.
- **Domain names** take the form `<id>.001.lambda-web.<region>.<floci host>` and `<id>.lambda-web.global.<floci host>`, with the host and port of `floci.base-url`. A `PerRegion` endpoint gets one domain per region in `regionalEndpoints`.
- **Not implemented yet:** `IamAuth` on requests, the automatic deletion of revisions past 50, the metadata API, the logs and metrics, and serving a `MultiRegion` or `PerRegion` endpoint in its other regions.
- **Not implemented yet:** SigV4a on `MultiRegion` endpoints, the check that a policy's principal exists, the automatic deletion of revisions past 50, the metadata API, the logs and metrics, and serving a `MultiRegion` or `PerRegion` endpoint in its other regions.
### `aws lambda-web deploy`
@@ -68,7 +68,9 @@ An execution environment is a `public.ecr.aws/lambda/nodejs:24` container that a
Each endpoint scales on its own, as on AWS. An environment takes up to the revision's `maxConcurrencyPerEnvironment` requests at once, the least busy one first, so requests rotate over the environments. A request that finds every environment full starts another one, or waits for one that is starting and has room. When the endpoint already runs `maxEnvironments`, an idle environment of another revision makes room, and without one the request is refused with `429` and `Platform.EndpointMaxEnvThrottle`. A `rateLimit` admits a burst of up to `rateLimit` requests that refills at `rateLimit` per second, and refuses the rest with `429` and `Platform.EndpointRequestThrottle`. AWS adjusts the concurrency of each environment under `maxConcurrencyPerEnvironment` from the measured load, so a burst there can spread over more environments than in Floci, and the account quotas are not applied.
Requests are forwarded over HTTP/1.1 with the headers AWS adds and drops: `lambda-web-request-id`, `lambda-web-endpoint-name`, `x-forwarded-proto`, `x-forwarded-port` and `Connection: close` are set, the client address is appended as an `X-Forwarded-For` line, and `Connection`, `Keep-Alive`, `Upgrade`, `Expect`, `Trailer`, the `Proxy-*` headers, `X-Real-IP`, the method override headers and any `lambda-web-*` header the client sent are dropped. A body without a `Content-Length` reaches the app chunked. Responses carry `lambda-web-request-id` and `lambda-web-logstream`, lose their connection headers and trailers, and stream as the app writes them. Requests with two revisions in `revisionWeights` are split by weight.
Requests are forwarded over HTTP/1.1 with the headers AWS adds and drops: `lambda-web-request-id`, `lambda-web-endpoint-name`, `x-forwarded-proto`, `x-forwarded-port` and `Connection: close` are set, the client address is appended as an `X-Forwarded-For` line, and `Connection`, `Keep-Alive`, `Upgrade`, `Expect`, `Trailer`, the `Proxy-*` headers, `X-Real-IP`, the method override headers and any `lambda-web-*` header the client sent are dropped. A body without a `Content-Length` reaches the app chunked. The path reaches the app without dot segments, as on AWS, and repeated slashes stay. Responses carry `lambda-web-request-id` and `lambda-web-logstream`, lose their connection headers and trailers, and stream as the app writes them. Requests with two revisions in `revisionWeights` are split by weight.
An `IamAuth` endpoint takes a request signed with SigV4 for the service `lambda` in the endpoint's region, in the `Authorization` header or in a presigned query. The request must carry `X-Amz-Content-SHA256`. Lambda takes its value as the payload hash and does not read the body, so `UNSIGNED-PAYLOAD` works. The signing time must be within five minutes. Floci verifies keys whose secret it holds: `test` with the secret `test`, IAM user keys and STS credentials with their session token. Any other key is refused. When `floci.services.iam.enforcement-enabled` is on, the signer also needs `lambda:InvokeWebFunctionEndpoint` on the endpoint ARN. Within one account the identity policy or the function's resource policy can allow it, and across accounts both must. `lambda:Resource/WebFunctionAuthType` and the function's tags as `aws:ResourceTag/<key>` are in the context. The `test` key is not evaluated, as elsewhere in Floci. A `MultiRegion` endpoint also takes SigV4 for the region that serves the request, which in Floci is always the home region. Its SigV4a requests are refused, because Floci does not verify SigV4a yet. On every endpoint, an `Authorization` that is an AWS signature is removed before the request reaches the app, together with the `X-Amz-Security-Token` header. Other `Authorization` values pass. A presigned query reaches the app unchanged, as on AWS.
The revision's `timeoutSeconds` bounds the whole exchange, as on AWS: a response that has not started by then is the 504 page, and one that is still streaming is cut. The request body is taken in full before the answer, so a slow upload gets its 504 once the body is in.
@@ -79,6 +81,7 @@ The platform answers these cases itself, with the AWS HTML pages and `lambda-web
| Status | Error type | When |
| --- | --- | --- |
| 400 | `Platform.MalformedRequest` | A method other than `GET`, `HEAD`, `POST`, `PUT`, `PATCH`, `OPTIONS`, `DELETE` |
| 403 | none | An `IamAuth` request with no valid signature or no permission. The endpoint's `rateLimit` 0 answers first, and a refused request takes no part of the `rateLimit` |
| 404 | `Platform.InvalidEndpoint` | The `Host` is a `lambda-web` domain Floci did not mint |
| 429 | `Platform.EndpointMaxEnvThrottle` | Every environment is full and the endpoint runs `maxEnvironments` |
| 429 | `Platform.EndpointRequestThrottle` | The requests exceed the endpoint's `rateLimit` |
@@ -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();
}
}
@@ -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 ────────────────────────────
@@ -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()
@@ -0,0 +1,94 @@
package io.github.hectorvent.floci.core.common.auth;
import io.github.hectorvent.floci.core.common.auth.SigV4SignedRequest.Freshness;
import org.junit.jupiter.api.Test;
import java.time.Duration;
import java.time.Instant;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
class SigV4SignedRequestTest {
private static final Instant NOW = Instant.parse("2026-10-17T12:00:00Z");
private static final DateTimeFormatter AMZ_DATE =
DateTimeFormatter.ofPattern("yyyyMMdd'T'HHmmss'Z'").withZone(ZoneOffset.UTC);
private static final String AUTHORIZATION = "AWS4-HMAC-SHA256 Credential=AKIDEXAMPLE/20261017/us-east-1/lambda/aws4_request,"
+ " SignedHeaders=Host;X-Amz-Date, Signature=abc123";
@Test
void theHeaderSignatureNeedsEveryPartAndADate() {
SigV4SignedRequest signed = SigV4SignedRequest.fromHeader(AUTHORIZATION, "20261017T120000Z");
assertEquals("AKIDEXAMPLE/20261017/us-east-1/lambda/aws4_request", signed.credential());
assertEquals("host;x-amz-date", signed.signedHeaders());
assertEquals("abc123", signed.signature());
assertFalse(signed.presigned());
assertNull(SigV4SignedRequest.fromHeader(AUTHORIZATION, null));
assertNull(SigV4SignedRequest.fromHeader("Bearer abc", "20261017T120000Z"));
assertNull(SigV4SignedRequest.fromHeader("AWS4-HMAC-SHA256 Credential=AKIDEXAMPLE/20261017/us-east-1/lambda/aws4_request,"
+ " SignedHeaders=host", "20261017T120000Z"));
}
@Test
void thePresignedSignatureNeedsEveryPartAndKeepsAnExpiryItCannotRead() {
Map<String, String> query = presigned(NOW, "300");
SigV4SignedRequest signed = SigV4SignedRequest.fromQuery(query::get);
assertTrue(signed.presigned());
assertEquals(300L, signed.expiresSeconds());
query.put("X-Amz-Expires", "soon");
assertNull(SigV4SignedRequest.fromQuery(query::get).expiresSeconds());
query.remove("X-Amz-Signature");
assertNull(SigV4SignedRequest.fromQuery(query::get));
}
@Test
void aHeaderSignatureIsFreshWithinFiveMinutesEitherWay() {
assertEquals(Freshness.FRESH, header(NOW.minus(Duration.ofMinutes(4))).freshness(NOW));
assertEquals(Freshness.FRESH, header(NOW.plus(Duration.ofMinutes(4))).freshness(NOW));
assertEquals(Freshness.EXPIRED, header(NOW.minus(Duration.ofMinutes(6))).freshness(NOW));
assertEquals(Freshness.NOT_YET_VALID, header(NOW.plus(Duration.ofMinutes(6))).freshness(NOW));
assertEquals(Freshness.MALFORMED_DATE,
SigV4SignedRequest.fromHeader(AUTHORIZATION, "20261017T99").freshness(NOW));
}
@Test
void aPresignedSignatureLastsItsExpiryOfUpToSevenDays() {
assertEquals(Freshness.FRESH, query(NOW.minus(Duration.ofMinutes(4)), "300").freshness(NOW));
assertEquals(Freshness.EXPIRED, query(NOW.minus(Duration.ofMinutes(6)), "300").freshness(NOW));
assertEquals(Freshness.NOT_YET_VALID, query(NOW.plus(Duration.ofMinutes(6)), "300").freshness(NOW));
assertEquals(Freshness.FRESH, query(NOW.minus(Duration.ofDays(6)), "604800").freshness(NOW));
assertEquals(Freshness.BAD_EXPIRES, query(NOW, "604801").freshness(NOW));
assertEquals(Freshness.BAD_EXPIRES, query(NOW, "0").freshness(NOW));
assertEquals(Freshness.BAD_EXPIRES, query(NOW, null).freshness(NOW));
}
private static SigV4SignedRequest header(Instant signedAt) {
return SigV4SignedRequest.fromHeader(AUTHORIZATION, AMZ_DATE.format(signedAt));
}
private static SigV4SignedRequest query(Instant signedAt, String expires) {
Map<String, String> query = presigned(signedAt, expires);
return SigV4SignedRequest.fromQuery(query::get);
}
private static Map<String, String> presigned(Instant signedAt, String expires) {
Map<String, String> query = new HashMap<>();
query.put("X-Amz-Credential", "AKIDEXAMPLE/20261017/us-east-1/lambda/aws4_request");
query.put("X-Amz-SignedHeaders", "host");
query.put("X-Amz-Signature", "abc123");
query.put("X-Amz-Date", AMZ_DATE.format(signedAt));
if (expires != null) {
query.put("X-Amz-Expires", expires);
}
return query;
}
}
@@ -161,6 +161,51 @@ class LambdaWebDataPlaneDockerIntegrationTest {
assertTrue(chunked.startsWith("HTTP/1.1 200 "), chunked);
assertTrue(chunked.contains("\"bodyLength\":17"), chunked);
assertTrue(chunked.contains("\"transfer-encoding\":\"chunked\""), chunked);
// The app gets the path without dot segments, as on AWS. Repeated slashes stay.
String dotted = raw("GET /a//b/./c/../d?x=1 HTTP/1.1\r\nHost: " + domain + "\r\nConnection: close\r\n\r\n");
assertTrue(dotted.contains("\"url\":\"/a//b/d?x=1\""), dotted);
// An AWS signature and its session token never reach the app. Other credentials do.
given().header("Host", domain).header("Authorization", "Bearer abc").header("X-Amz-Security-Token", "tok")
.when().get("/")
.then().statusCode(200)
.body("headers.authorization", equalTo("Bearer abc"))
.body("headers.x-amz-security-token", equalTo("tok"));
given().header("Host", domain).header("Authorization", "AWS4-HMAC-SHA256 Credential=x")
.header("X-Amz-Security-Token", "tok").header("X-Amz-Date", "20260101T000000Z")
.when().get("/")
.then().statusCode(200)
.body("headers.authorization", nullValue())
.body("headers.x-amz-security-token", nullValue())
.body("headers.x-amz-date", equalTo("20260101T000000Z"));
}
@Test
@Timeout(180)
void anIamAuthEndpointServesSignedRequestsWithoutTheirSignature() throws Exception {
String domain = createFunction(30);
given().contentType("application/json").body("{\"authType\": \"IamAuth\"}")
.when().patch(BASE + "/web-functions/" + functionName + "/endpoints/dev")
.then().statusCode(202);
given().header("Host", domain).when().get("/").then().statusCode(403);
LambdaWebRequestSigner.Signed signed = new LambdaWebRequestSigner().sign("POST", domain, "/items?b=2&a=1");
given().urlEncodingEnabled(false).header("Host", domain).headers(signed.headers()).body("hello body")
.when().post(signed.pathAndQuery())
.then().statusCode(200)
.body("url", equalTo(signed.pathAndQuery()))
.body("bodyLength", equalTo(10))
.body("headers.authorization", nullValue())
.body("headers.x-amz-content-sha256", equalTo("UNSIGNED-PAYLOAD"))
.body("headers.x-amz-date", equalTo(signed.headers().get("X-Amz-Date")));
// A presigned request reaches the app with its query as sent.
LambdaWebRequestSigner.Signed presigned = new LambdaWebRequestSigner().presigned().sign("GET", domain, "/q");
given().urlEncodingEnabled(false).header("Host", domain).headers(presigned.headers())
.when().get(presigned.pathAndQuery())
.then().statusCode(200)
.body("url", equalTo(presigned.pathAndQuery()));
}
@Test
@@ -17,6 +17,7 @@ import java.util.Map;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.matchesPattern;
import static org.hamcrest.Matchers.nullValue;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
@@ -99,6 +100,39 @@ class LambdaWebDataPlaneIntegrationTest {
return read.toString();
}
@Test
void anIamAuthEndpointRefusesARequestWithoutAValidSignature() {
String functionName = "dp-iam-" + Long.toString(System.nanoTime(), 36);
String domain = createFunction(functionName, "IamAuth");
Response unsigned = given().header("Host", domain).when().get("/");
unsigned.then().statusCode(403)
.header("content-type", "text/html")
.header("connection", "keep-alive")
.header("lambda-web-error-type", nullValue())
.header("lambda-web-request-id", matchesPattern(REQUEST_ID))
.header("content-length", "230")
.body(equalTo(LambdaWebErrorPages.html(LambdaWebErrorPages.FORBIDDEN,
unsigned.header("lambda-web-request-id"))));
given().header("Host", domain).when().head("/")
.then().statusCode(403).header("content-length", "230").body(equalTo(""));
given().header("Host", domain).header("Authorization", "Bearer abc").when().get("/")
.then().statusCode(403);
LambdaWebRequestSigner.Signed forged = new LambdaWebRequestSigner()
.credentials("test", "not-the-secret", null).sign("GET", domain, "/");
given().header("Host", domain).headers(forged.headers()).when().get("/")
.then().statusCode(403);
// A disabled endpoint answers before the signature is checked.
given().contentType("application/json").body("{\"throttleConfig\": {\"rateLimit\": 0}}")
.when().patch(BASE + "/web-functions/" + functionName + "/endpoints/dev")
.then().statusCode(202);
given().header("Host", domain).when().get("/")
.then().statusCode(503).header("lambda-web-error-type", "Platform.EndpointDisabled");
given().when().delete(BASE + "/web-functions/" + functionName).then().statusCode(204);
}
@Test
void httpOneDotZeroIsRefused() throws IOException {
String response = raw("GET / HTTP/1.0\r\nHost: " + UNKNOWN_HOST + "\r\n\r\n");
@@ -124,6 +158,10 @@ class LambdaWebDataPlaneIntegrationTest {
}
private String createFunction(String functionName) {
return createFunction(functionName, "ApplicationManaged");
}
private String createFunction(String functionName, String authType) {
s3Service.createBucket(BUCKET, "us-east-1");
s3Service.putObject(BUCKET, "app.zip", "zip".getBytes(StandardCharsets.UTF_8), "application/zip", Map.of());
return given().contentType("application/json")
@@ -134,8 +172,8 @@ class LambdaWebDataPlaneIntegrationTest {
"runtimeConfig": {"runtime": "nodejs24.x"}},
"serviceConfig": {"executionRoleArn": "%s"}},
"endpointConfig": {"endpointName": "dev", "endpointType": "HomeRegion",
"authType": "ApplicationManaged", "autoDeploymentMode": "LatestRevision"}}
""".formatted(functionName, BUCKET, ROLE))
"authType": "%s", "autoDeploymentMode": "LatestRevision"}}
""".formatted(functionName, BUCKET, ROLE, authType))
.when().put(BASE + "/web-functions")
.then().statusCode(202)
.extract().path("endpoint.domainName");
@@ -27,6 +27,20 @@ class LambdaWebDataPlaneTest {
assertTrue(id.matches("[A-Z2-7]{26}"), id);
}
@Test
void theAppGetsThePathWithoutDotSegmentsAndWithItsRepeatedSlashes() {
assertEquals("/a/c", LambdaWebDataPlane.withoutDotSegments("/a/./b/../c"));
assertEquals("/a/", LambdaWebDataPlane.withoutDotSegments("/a/b/.."));
assertEquals("/a/b/", LambdaWebDataPlane.withoutDotSegments("/a/b/."));
assertEquals("/a", LambdaWebDataPlane.withoutDotSegments("/./a"));
assertEquals("/a", LambdaWebDataPlane.withoutDotSegments("/../a"));
assertEquals("/a/b/", LambdaWebDataPlane.withoutDotSegments("/a/b/"));
assertEquals("/", LambdaWebDataPlane.withoutDotSegments("/"));
assertEquals("/a//b", LambdaWebDataPlane.withoutDotSegments("/a//b"));
assertEquals("//a", LambdaWebDataPlane.withoutDotSegments("//a"));
assertEquals("/a/%2e%2e/b", LambdaWebDataPlane.withoutDotSegments("/a/%2e%2e/b"));
}
@Test
void thePortComesFromTheHostOrTheScheme() {
assertEquals(4566, LambdaWebDataPlane.port("x.001.lambda-web.us-east-1.localhost:4566", "http"));
@@ -15,6 +15,7 @@ class LambdaWebErrorPagesTest {
@Test
void pagesHaveTheRecordedContentLengths() {
assertEquals(230, length(LambdaWebErrorPages.FORBIDDEN));
assertEquals(225, length(LambdaWebErrorPages.INVALID_ENDPOINT));
assertEquals(264, length(LambdaWebErrorPages.UNSUPPORTED_HTTP_VERSION));
assertEquals(274, length(LambdaWebErrorPages.ENDPOINT_DISABLED));
@@ -0,0 +1,162 @@
package io.github.hectorvent.floci.services.lambdaweb;
import com.github.dockerjava.api.DockerClient;
import io.github.hectorvent.floci.services.s3.S3Service;
import io.github.hectorvent.floci.testing.EnforcementFixtures;
import io.github.hectorvent.floci.testing.EnforcementFixtures.UserCredentials;
import io.github.hectorvent.floci.testing.IamEnforcementProfile;
import io.github.hectorvent.floci.testing.PartitionCleanup;
import io.quarkus.test.common.http.TestHTTPResource;
import io.quarkus.test.junit.QuarkusTest;
import io.quarkus.test.junit.TestProfile;
import io.restassured.response.ValidatableResponse;
import jakarta.inject.Inject;
import org.junit.jupiter.api.Assumptions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.Timeout;
import org.junit.jupiter.api.extension.RegisterExtension;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import static io.github.hectorvent.floci.testing.EnforcementFixtures.auth;
import static io.restassured.RestAssured.given;
/** Under IAM enforcement an IamAuth endpoint evaluates lambda:InvokeWebFunctionEndpoint for the signer. */
@QuarkusTest
@TestProfile(IamEnforcementProfile.class)
class LambdaWebIamAuthIntegrationTest {
private static final String BASE = "/2025-03-07";
private static final String BUCKET = "web-code-iam-auth";
private static final String ROOT = auth("000000000000", "lambda");
private static final String IAM_ROOT = auth("000000000000", "iam");
private static final String APP = """
const http = require('node:http');
const [host, port] = process.env.AWS_LAMBDA_HTTP_ENDPOINT.split(':');
http.createServer((req, res) => res.end('ok')).listen(Number(port), host);
""";
@TestHTTPResource("/")
static URI baseUri;
@RegisterExtension
final PartitionCleanup cleanup = new PartitionCleanup();
@Inject
S3Service s3Service;
@Inject
LambdaWebEnvironmentManager environments;
@Inject
DockerClient dockerClient;
private String functionName;
private String functionArn;
private String domain;
@BeforeEach
void createFunction() throws IOException {
functionName = "iam-auth-" + Long.toString(System.nanoTime(), 36);
s3Service.createBucket(BUCKET, "us-east-1");
s3Service.putObject(BUCKET, functionName + ".zip", zip(), "application/zip", Map.of());
int port = baseUri.getPort();
String name = functionName;
cleanup.register(() -> {
environments.stopManagedContainers();
given().port(port).header("Authorization", ROOT).delete(BASE + "/web-functions/" + name);
});
ValidatableResponse created = given().header("Authorization", ROOT).contentType("application/json")
.body("""
{"functionName": "%s",
"revisionConfig": {
"buildConfig": {"codeConfig": {"s3Object": {"bucket": "%s", "key": "%s.zip"}},
"runtimeConfig": {"runtime": "nodejs24.x"}},
"serviceConfig": {"executionRoleArn": "arn:aws:iam::000000000000:role/web"}},
"endpointConfig": {"endpointName": "prod", "endpointType": "HomeRegion",
"authType": "IamAuth", "autoDeploymentMode": "LatestRevision"}}
""".formatted(functionName, BUCKET, functionName))
.when().put(BASE + "/web-functions")
.then().statusCode(202);
functionArn = created.extract().path("functionArn");
domain = created.extract().path("endpoint.domainName");
}
@Test
void aSignerWithoutInvokeOnTheEndpointIsRefused() {
invoke(user(userName(), null)).statusCode(403);
invoke(user(userName(), functionArn)).statusCode(403);
}
@Test
@Timeout(180)
void anIdentityPolicyOrTheFunctionPolicyAllowsTheSigner() {
Assumptions.assumeTrue(isDockerAvailable(), "Docker must be available for the Lambda Web data plane");
invoke(user(userName(), functionArn + "/endpoint/prod")).statusCode(200);
String userName = userName();
UserCredentials granted = user(userName, null);
String policy = """
{"Version":"2012-10-17","Statement":[{"Effect":"Allow",
"Principal":{"AWS":"arn:aws:iam::000000000000:user/%s"},
"Action":"lambda:InvokeWebFunctionEndpoint","Resource":"%s/endpoint/prod"}]}"""
.formatted(userName, functionArn);
given().header("Authorization", ROOT).contentType("application/json").body(Map.of("Policy", policy))
.when().put(BASE + "/resource-policy/" + functionArn)
.then().statusCode(200);
invoke(granted).statusCode(200);
}
private static String userName() {
return "iam-auth-" + Long.toString(System.nanoTime(), 36);
}
private UserCredentials user(String userName, String invokeResource) {
UserCredentials credentials = EnforcementFixtures.createUser(cleanup, baseUri.getPort(), IAM_ROOT, userName);
if (invokeResource != null) {
given().header("Authorization", IAM_ROOT).contentType("application/x-www-form-urlencoded")
.formParam("Action", "PutUserPolicy").formParam("Version", "2010-05-08")
.formParam("UserName", userName).formParam("PolicyName", "invoke")
.formParam("PolicyDocument", """
{"Version":"2012-10-17","Statement":[{"Effect":"Allow",
"Action":"lambda:InvokeWebFunctionEndpoint","Resource":"%s"}]}"""
.formatted(invokeResource))
.when().post("/")
.then().statusCode(200);
}
return credentials;
}
private ValidatableResponse invoke(UserCredentials credentials) {
LambdaWebRequestSigner.Signed signed = new LambdaWebRequestSigner()
.credentials(credentials.accessKeyId(), credentials.secretAccessKey(), null)
.sign("GET", domain, "/");
return given().header("Host", domain).headers(signed.headers()).when().get("/").then();
}
private static byte[] zip() throws IOException {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
try (ZipOutputStream zip = new ZipOutputStream(bytes)) {
zip.putNextEntry(new ZipEntry("index.js"));
zip.write(APP.getBytes(StandardCharsets.UTF_8));
zip.closeEntry();
}
return bytes.toByteArray();
}
private boolean isDockerAvailable() {
try {
dockerClient.pingCmd().exec();
return true;
} catch (RuntimeException e) {
return false;
}
}
}
@@ -0,0 +1,266 @@
package io.github.hectorvent.floci.services.lambdaweb;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.services.iam.IamPolicyEvaluator;
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.ScpProvider;
import io.github.hectorvent.floci.services.iam.model.CallerContext;
import io.github.hectorvent.floci.services.lambdaweb.LambdaWebIamAuth.Inbound;
import io.github.hectorvent.floci.services.lambdaweb.LambdaWebService.WebFunctionTarget;
import io.github.hectorvent.floci.services.lambdaweb.model.WebFunction;
import io.github.hectorvent.floci.services.lambdaweb.model.WebFunctionEndpoint;
import io.netty.handler.codec.http.QueryStringDecoder;
import io.vertx.core.MultiMap;
import jakarta.enterprise.inject.Instance;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.time.Duration;
import java.time.Instant;
import java.util.List;
import java.util.Optional;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
class LambdaWebIamAuthTest {
private static final String ACCOUNT = "111111111111";
private static final String OTHER_ACCOUNT = "222222222222";
private static final String HOST = "abcdefghijklmnop.001.lambda-web.us-east-1.localhost:4566";
private static final String FUNCTION_ARN = "arn:aws:lambda:us-east-1:" + ACCOUNT + ":web-function/app";
private static final String ENDPOINT_ARN = FUNCTION_ARN + "/endpoint/prod";
private static final String USER_KEY = "AKIAUSERKEY000000001";
private static final String USER_SECRET = "user-secret";
private static final String SESSION_KEY = "ASIASESSIONKEY000001";
private final EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
private final IamService iamService = mock(IamService.class);
@SuppressWarnings("unchecked")
private final Instance<ScpProvider> scpProvider = mock(Instance.class);
private final LambdaWebIamAuth iamAuth = new LambdaWebIamAuth(config, iamService,
new IamPolicyEvaluator(new ObjectMapper()), scpProvider);
private final WebFunction function = new WebFunction();
private final WebFunctionEndpoint endpoint = new WebFunctionEndpoint();
@BeforeEach
void setUp() {
function.functionName = "app";
function.functionArn = FUNCTION_ARN;
endpoint.endpointName = "prod";
endpoint.endpointArn = ENDPOINT_ARN;
endpoint.authType = "IamAuth";
when(iamService.findSecretKeyInAnyAccount(USER_KEY, null))
.thenReturn(Optional.of(new OwnedSecretKey(USER_SECRET, ACCOUNT)));
when(iamService.findSecretKeyInAnyAccount(SESSION_KEY, "token"))
.thenReturn(Optional.of(new OwnedSecretKey("session-secret", null)));
}
@Test
void aRequestSignedForLambdaInTheEndpointRegionPasses() {
assertTrue(allows(signer().sign("GET", HOST, "/items?b=2&a=1")));
assertTrue(allows(signer().sign("POST", HOST, "/")));
assertTrue(allows(signer().presigned().sign("GET", HOST, "/q?x=1")));
}
@Test
void theSignatureCoversThePathAsSignersNormalizeIt() {
assertTrue(allows(signer().sign("GET", HOST, "/a/c").withPathAndQuery("/a/./b/../c")));
assertTrue(allows(signer().sign("GET", HOST, "/a/b").withPathAndQuery("/a//b")));
assertTrue(allows(signer().sign("GET", HOST, "/a").withPathAndQuery("/a/b/..")));
assertTrue(allows(signer().sign("GET", HOST, "/path%2Fenc/a%20b?c=x%2By")));
}
@Test
void aSignatureOverThePathAsSentIsRefusedWhenSignersWouldNormalizeIt() {
assertFalse(allows(signer().rawPath().sign("GET", HOST, "/a/./b/../c")));
assertFalse(allows(signer().rawPath().sign("GET", HOST, "/a//b")));
assertTrue(allows(signer().rawPath().sign("GET", HOST, "/a/b/")));
}
@Test
void signersResolveDotSegmentsAndDropEmptySegments() {
assertEquals("/a/c", LambdaWebIamAuth.signedPath("/a/./b/../c"));
assertEquals("/a/b", LambdaWebIamAuth.signedPath("/a//b"));
assertEquals("/a", LambdaWebIamAuth.signedPath("//a"));
assertEquals("/a", LambdaWebIamAuth.signedPath("/a/b/.."));
assertEquals("/a/b/", LambdaWebIamAuth.signedPath("/a/b/"));
assertEquals("/", LambdaWebIamAuth.signedPath("/a/.."));
assertEquals("/", LambdaWebIamAuth.signedPath("/"));
assertEquals("/a/%2e%2e/b", LambdaWebIamAuth.signedPath("/a/%2e%2e/b"));
}
@Test
void anUnsignedOrForeignAuthorizationIsRefused() {
LambdaWebRequestSigner.Signed signed = signer().sign("GET", HOST, "/");
assertFalse(allows(signed.withHeader("Authorization", null)));
assertFalse(allows(signed.withHeader("Authorization", "Bearer abc")));
assertFalse(allows(signer().presigned().sign("GET", HOST, "/").withHeader("Authorization", "Bearer abc")),
"the header wins over the query");
}
@Test
void theContentSha256HeaderIsRequired() {
assertFalse(allows(signer().sign("GET", HOST, "/").withHeader("X-Amz-Content-SHA256", null)));
assertFalse(allows(signer().contentSha256(null).presigned().sign("GET", HOST, "/")));
}
@Test
void theScopeMustNameLambdaAndTheEndpointRegion() {
assertFalse(allows(signer().region("us-west-2").sign("GET", HOST, "/")));
assertFalse(allows(signer().service("lambda-web").sign("GET", HOST, "/")));
assertFalse(allows(signer().service("execute-api").sign("GET", HOST, "/")));
}
@Test
void theSigningTimeMustBeWithinFiveMinutes() {
Instant now = Instant.now();
assertTrue(allows(signer().signedAt(now.minus(Duration.ofMinutes(4))).sign("GET", HOST, "/")));
assertFalse(allows(signer().signedAt(now.minus(Duration.ofMinutes(6))).sign("GET", HOST, "/")));
assertFalse(allows(signer().signedAt(now.plus(Duration.ofMinutes(6))).sign("GET", HOST, "/")));
assertFalse(allows(signer().presigned().signedAt(now.minus(Duration.ofMinutes(6))).sign("GET", HOST, "/")),
"a presigned request expires");
}
@Test
void anAlteredRequestIsRefused() {
LambdaWebRequestSigner.Signed signed = signer().sign("GET", HOST, "/x?b=1");
assertFalse(allows(signed.withPathAndQuery("/x?a=1")));
assertFalse(allows(signed.withPathAndQuery("/y?b=1")));
assertFalse(allows(signer().credentials("test", "other", null).sign("GET", HOST, "/")));
}
@Test
void theKeyMustBeKnownAndCarryItsSessionTokenOnlyWhenTemporary() {
assertTrue(allows(signer().credentials(USER_KEY, USER_SECRET, null).sign("GET", HOST, "/")));
assertFalse(allows(signer().credentials("AKIAUNKNOWN000000001", "x", null).sign("GET", HOST, "/")));
assertFalse(allows(signer().credentials(USER_KEY, USER_SECRET, "token").sign("GET", HOST, "/")),
"a long-term key with a session token");
assertTrue(allows(signer().credentials(SESSION_KEY, "session-secret", "token").sign("GET", HOST, "/")));
assertFalse(allows(signer().credentials(SESSION_KEY, "session-secret", "token").sign("GET", HOST, "/")
.withHeader("X-Amz-Security-Token", null)));
}
@Test
void aMalformedDateOrQueryIsRefused() {
assertFalse(allows(signer().sign("GET", HOST, "/").withHeader("X-Amz-Date", "20261017T99")));
assertFalse(allows(signer().sign("GET", HOST, "/q?x=1").withPathAndQuery("/q?x=%zz")));
}
@Test
void aFailureInsideFlociIsNotTakenForARefusal() {
when(iamService.findSecretKeyInAnyAccount(USER_KEY, null)).thenThrow(new IllegalStateException("storage"));
assertThrows(IllegalStateException.class,
() -> allows(signer().credentials(USER_KEY, USER_SECRET, null).sign("GET", HOST, "/")));
}
@Test
void underEnforcementTheCallerNeedsInvokeOnTheEndpoint() {
enforceFor(ACCOUNT);
assertTrue(allowsUserWith(allow(ENDPOINT_ARN, "")));
assertTrue(allowsUserWith(allow(FUNCTION_ARN + "/endpoint/*", "")));
assertFalse(allowsUserWith(allow(FUNCTION_ARN, "")));
assertFalse(allowsUserWith());
assertFalse(allowsUserWith(allow("*", ""), """
{"Version":"2012-10-17","Statement":[{"Effect":"Deny","Action":"lambda:InvokeWebFunctionEndpoint",
"Resource":"%s"}]}""".formatted(ENDPOINT_ARN)));
}
@Test
void underEnforcementTheAuthTypeAndTagConditionKeysAreSet() {
enforceFor(ACCOUNT);
function.tags.put("env", "probe");
assertTrue(allowsUserWith(allow(ENDPOINT_ARN,
",\"Condition\":{\"StringEquals\":{\"lambda:Resource/WebFunctionAuthType\":\"IamAuth\"}}")));
assertFalse(allowsUserWith(allow(ENDPOINT_ARN,
",\"Condition\":{\"StringEquals\":{\"lambda:Resource/WebFunctionAuthType\":\"ApplicationManaged\"}}")));
assertTrue(allowsUserWith(allow(ENDPOINT_ARN,
",\"Condition\":{\"StringEquals\":{\"aws:ResourceTag/env\":\"probe\"}}")));
assertFalse(allowsUserWith(allow(ENDPOINT_ARN,
",\"Condition\":{\"StringEquals\":{\"aws:ResourceTag/env\":\"prod\"}}")));
}
@Test
void underEnforcementTheResourcePolicyAllowsWithinTheAccountAndItsDenyWins() {
enforceFor(ACCOUNT);
function.policy = resourcePolicy("Allow", ACCOUNT);
assertTrue(allowsUserWith());
function.policy = resourcePolicy("Deny", ACCOUNT);
assertFalse(allowsUserWith(allow(ENDPOINT_ARN, "")));
}
@Test
void underEnforcementAnotherAccountNeedsBothPolicies() {
enforceFor(OTHER_ACCOUNT);
assertFalse(allowsUserWith(allow(ENDPOINT_ARN, "")));
function.policy = resourcePolicy("Allow", OTHER_ACCOUNT);
assertFalse(allowsUserWith());
assertTrue(allowsUserWith(allow(ENDPOINT_ARN, "")));
}
@Test
void theTestKeyIsNotEvaluated() {
enforceFor(ACCOUNT);
assertTrue(allows(signer().sign("GET", HOST, "/")));
}
private void enforceFor(String callerAccount) {
when(config.services().iam().enforcementEnabled()).thenReturn(true);
when(iamService.findSecretKeyInAnyAccount(USER_KEY, null))
.thenReturn(Optional.of(new OwnedSecretKey(USER_SECRET, callerAccount)));
when(iamService.resolveAccountId(USER_KEY)).thenReturn(Optional.of(callerAccount));
String userArn = "arn:aws:iam::" + callerAccount + ":user/caller";
when(iamService.resolveCallerArns(USER_KEY)).thenReturn(Optional.of(
new CallerArns(userArn, userArn, CallerArns.TYPE_USER, "AIDACALLER", "caller", false)));
}
private boolean allowsUserWith(String... identityPolicies) {
when(iamService.resolveCallerContext(eq(USER_KEY), any(Instant.class)))
.thenReturn(CallerContext.of(List.of(identityPolicies)));
return allows(signer().credentials(USER_KEY, USER_SECRET, null).sign("GET", HOST, "/"));
}
private static String resourcePolicy(String effect, String callerAccount) {
return """
{"Version":"2012-10-17","Statement":[{"Effect":"%s","Principal":{"AWS":"arn:aws:iam::%s:user/caller"},
"Action":"lambda:InvokeWebFunctionEndpoint","Resource":"%s"}]}"""
.formatted(effect, callerAccount, ENDPOINT_ARN);
}
private static String allow(String resource, String condition) {
return """
{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":"lambda:InvokeWebFunctionEndpoint",
"Resource":"%s"%s}]}""".formatted(resource, condition);
}
private static LambdaWebRequestSigner signer() {
return new LambdaWebRequestSigner();
}
private boolean allows(LambdaWebRequestSigner.Signed signed) {
String pathAndQuery = signed.pathAndQuery();
int question = pathAndQuery.indexOf('?');
String path = question < 0 ? pathAndQuery : pathAndQuery.substring(0, question);
String query = question < 0 ? null : pathAndQuery.substring(question + 1);
MultiMap headers = MultiMap.caseInsensitiveMultiMap().add("Host", HOST);
signed.headers().forEach(headers::add);
MultiMap params = MultiMap.caseInsensitiveMultiMap();
try {
new QueryStringDecoder(pathAndQuery).parameters().forEach(params::add);
} catch (IllegalArgumentException expected) {
// The data plane keeps going with no parameters when the query does not decode.
}
return iamAuth.allows(new Inbound(signed.method(), path, query, headers, params),
new WebFunctionTarget(ACCOUNT, "us-east-1", function, endpoint));
}
}
@@ -0,0 +1,124 @@
package io.github.hectorvent.floci.services.lambdaweb;
import software.amazon.awssdk.http.SdkHttpFullRequest;
import software.amazon.awssdk.http.SdkHttpMethod;
import software.amazon.awssdk.http.SdkHttpRequest;
import software.amazon.awssdk.http.auth.aws.signer.AwsV4FamilyHttpSigner.AuthLocation;
import software.amazon.awssdk.http.auth.aws.signer.AwsV4HttpSigner;
import software.amazon.awssdk.http.auth.spi.signer.HttpSigner;
import software.amazon.awssdk.identity.spi.AwsCredentialsIdentity;
import software.amazon.awssdk.identity.spi.AwsSessionCredentialsIdentity;
import java.net.URI;
import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
import java.time.ZoneOffset;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
/** Signs a request to a Lambda Web endpoint with the AWS SDK signer, as a client would. */
final class LambdaWebRequestSigner {
/** What goes on the wire: the method, the path with its query, and the headers to add. */
record Signed(String method, String pathAndQuery, Map<String, String> headers) {
Signed withPathAndQuery(String other) {
return new Signed(method, other, headers);
}
Signed withHeader(String name, String value) {
Map<String, String> copy = new LinkedHashMap<>(headers);
if (value == null) {
copy.remove(name);
} else {
copy.put(name, value);
}
return new Signed(method, pathAndQuery, copy);
}
}
private String accessKeyId = "test";
private String secretKey = "test";
private String sessionToken;
private String region = "us-east-1";
private String service = "lambda";
private Instant signedAt = Instant.now();
private boolean presigned;
private boolean normalizePath = true;
private String contentSha256 = "UNSIGNED-PAYLOAD";
LambdaWebRequestSigner credentials(String accessKeyId, String secretKey, String sessionToken) {
this.accessKeyId = accessKeyId;
this.secretKey = secretKey;
this.sessionToken = sessionToken;
return this;
}
LambdaWebRequestSigner region(String region) {
this.region = region;
return this;
}
LambdaWebRequestSigner service(String service) {
this.service = service;
return this;
}
LambdaWebRequestSigner signedAt(Instant signedAt) {
this.signedAt = signedAt;
return this;
}
LambdaWebRequestSigner presigned() {
this.presigned = true;
return this;
}
/** Signs the path as it is sent, without resolving its dot segments. */
LambdaWebRequestSigner rawPath() {
this.normalizePath = false;
return this;
}
/** The {@code X-Amz-Content-SHA256} value to send and sign, or null to send none. */
LambdaWebRequestSigner contentSha256(String contentSha256) {
this.contentSha256 = contentSha256;
return this;
}
Signed sign(String method, String host, String pathAndQuery) {
URI uri = URI.create("http://" + host + pathAndQuery);
SdkHttpFullRequest.Builder builder = SdkHttpFullRequest.builder()
.method(SdkHttpMethod.fromValue(method))
.uri(uri);
if (contentSha256 != null) {
builder.putHeader("X-Amz-Content-SHA256", contentSha256);
}
AwsCredentialsIdentity identity = sessionToken == null
? AwsCredentialsIdentity.create(accessKeyId, secretKey)
: AwsSessionCredentialsIdentity.create(accessKeyId, secretKey, sessionToken);
SdkHttpRequest signed = AwsV4HttpSigner.create().sign(request -> request
.identity(identity)
.request(builder.build())
.putProperty(AwsV4HttpSigner.SERVICE_SIGNING_NAME, service)
.putProperty(AwsV4HttpSigner.REGION_NAME, region)
.putProperty(AwsV4HttpSigner.PAYLOAD_SIGNING_ENABLED, false)
.putProperty(AwsV4HttpSigner.NORMALIZE_PATH, normalizePath)
.putProperty(AwsV4HttpSigner.AUTH_LOCATION, presigned ? AuthLocation.QUERY_STRING : AuthLocation.HEADER)
.putProperty(AwsV4HttpSigner.EXPIRATION_DURATION, presigned ? Duration.ofMinutes(5) : null)
.putProperty(HttpSigner.SIGNING_CLOCK, Clock.fixed(signedAt, ZoneOffset.UTC))).request();
Map<String, String> headers = new LinkedHashMap<>();
for (Map.Entry<String, List<String>> header : signed.headers().entrySet()) {
if (!"Host".equalsIgnoreCase(header.getKey())) {
headers.put(header.getKey(), String.join(",", header.getValue()));
}
}
if (contentSha256 != null) {
headers.put("X-Amz-Content-SHA256", contentSha256);
}
String query = signed.encodedQueryParameters().map(encoded -> "?" + encoded).orElse("");
return new Signed(method, signed.encodedPath() + query, headers);
}
}
@@ -475,6 +475,21 @@ class LambdaWebServiceTest {
+ " input and try again.", message(() -> service.putResourcePolicy(REGION, missing,
policy("{\"Statement\":[{\"Effect\":\"Allow\",\"Principal\":{\"Service\":\"*\"},"
+ "\"Action\":\"lambda:InvokeWebFunctionEndpoint\",\"Resource\":\"" + resource + "\"}]}"))));
// An ARN may carry a path, any other AWS principal may not.
assertEquals("The provided input'arn:aws:iam::000000000000:role/has space'was invalid. Member must satisfy"
+ " expression: [\\w+=/:,.@-]* Please check your input and try again.",
message(() -> service.putResourcePolicy(REGION, missing,
policy(members.formatted("{\"AWS\":\"arn:aws:iam::000000000000:role/has space\"}", invoke,
"\"" + resource + "\"")))));
assertEquals("The provided input'foo/bar'was invalid. Member must satisfy expression: [\\w+=,.@\\:-]*"
+ " Please check your input and try again.", message(() -> service.putResourcePolicy(REGION, missing,
policy(members.formatted("{\"AWS\":\"foo/bar\"}", invoke, "\"" + resource + "\"")))));
assertEquals("ResourceNotFoundException", error(() -> service.putResourcePolicy(REGION, missing,
policy(members.formatted("{\"AWS\":\"arn:aws:iam::000000000000:user/path/alice\"}", invoke,
"\"" + resource + "\"")))).getErrorCode());
assertEquals("ValidationException", error(() -> service.putResourcePolicy(REGION, missing,
policy(members.formatted("{\"CanonicalUser\":\"arn:aws:iam::000000000000:foo/bar\"}", invoke,
"\"" + resource + "\"")))).getErrorCode(), "only an AWS principal may carry a path");
assertEquals("Lambda blocked the creation of this policy because it would grant public access to your function.",
message(() -> service.putResourcePolicy(REGION, missing, policy("{\"Statement\":[{\"Effect\":\"Allow\","
+ "\"Principal\":{\"AWS\":[\"arn:aws:iam::000000000000:root\",\"*\"]},"