mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
feat(eventbridgev2): rotate webhook credentials (#9443)
This commit is contained in:
1 parent
2dd81154f1
commit
aeb4593696
16 files changed
+1179
-40
No files matched your search
@@ -29,6 +29,7 @@ The AWS CLI calls it `aws eventsv2` and the SDKs `EventBridgeV2`.
|
||||
| `DescribeEventSource` | Return a webhook event source's configuration, URL, secret ARN, state and times |
|
||||
| `ListEventSources` | List the Region's event sources, or one event bus's, filtered by name prefix, a page at a time |
|
||||
| `UpdateEventSource` | Replace a webhook event source's configuration and description |
|
||||
| `RotateWebhookCredentials` | Replace the credential in a webhook event source's secret, with a given or a generated one |
|
||||
| `DeleteEventSource` | Delete a webhook event source and schedule its secret for deletion |
|
||||
| `PutEvents` | Publish events in the EventBridge envelope to an event bus |
|
||||
<!-- floci:actions:end -->
|
||||
@@ -114,6 +115,13 @@ Floci serves event sources of the `WebhookEventsConfiguration` kind. A request w
|
||||
- `DescribeEventSource` returns `Configuration` as given, without `SecretValue`, `Username` and `Password`.
|
||||
- `UpdateEventSource` replaces the whole webhook configuration and keeps the URL, the secret and the
|
||||
authentication type. It does not accept credentials.
|
||||
- `RotateWebhookCredentials` replaces the credential in the secret and keeps the URL, the secret ARN and
|
||||
`LastModifiedTime`. The new value becomes `AWSCURRENT` and the one it replaces `AWSPREVIOUS`. The webhook URL
|
||||
keeps accepting the credential the last rotation replaced for 15 minutes. An earlier one is refused at once.
|
||||
`Credential` must set the member of the source's authentication type, or be left out to generate a value.
|
||||
Basic keeps its username. A repeat of a `ClientToken` of the source with the same request changes nothing.
|
||||
Floci forgets a token 8 hours after its rotation. A rotation answers `InvalidStateException` (409) when the
|
||||
secret is scheduled for deletion or deleted.
|
||||
- `KmsKeyIdentifier` is stored and returned. It is not used for the secret.
|
||||
- `DeleteEventSource` schedules the secret for deletion at once.
|
||||
- `DescribeEventSource` and `ListEventSources` do not return `Revoked`.
|
||||
|
||||
@@ -57,7 +57,7 @@ Operation counts are exact. For dispatch-table services (Query and JSON 1.1) eac
|
||||
| [CloudFormation](cloudformation.md) | `POST /` with `Action=` param | Query | 36 |
|
||||
| [Cloud Control API](cloudcontrol.md) | `POST /` + `X-Amz-Target: CloudApiService.*` | JSON 1.1 | 5 |
|
||||
| [EventBridge](eventbridge.md) | `POST /` + `X-Amz-Target: AmazonEventBridge.*` | JSON 1.1 | 41 |
|
||||
| [EventBridge V2](eventbridgev2.md) | `POST /service/AWSEventsV2/operation/*` | Smithy RPC v2 CBOR | 15 |
|
||||
| [EventBridge V2](eventbridgev2.md) | `POST /service/AWSEventsV2/operation/*` | Smithy RPC v2 CBOR | 16 |
|
||||
| [EventBridge Scheduler](scheduler.md) | `/schedules/*`, `/schedule-groups/*`, `/tags/*` | REST JSON | 12 |
|
||||
| [EventBridge Pipes](pipes.md) | `/v1/pipes/*` | REST JSON | 10 |
|
||||
| [CloudWatch OAM](oam.md) | REST paths such as `POST /CreateSink` and `POST /CreateLink` | REST JSON | 15 |
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
package io.floci.aws.services.eventbridgev2;
|
||||
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.JsonNodeFactory;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import io.floci.aws.config.EmulatorConfig;
|
||||
@@ -16,6 +18,7 @@ import io.floci.aws.core.storage.AccountAwareStorageBackend;
|
||||
import io.floci.aws.core.storage.StorageFactory;
|
||||
import io.floci.aws.services.eventbridgev2.model.EventBusV2;
|
||||
import io.floci.aws.services.eventbridgev2.model.EventSourceV2;
|
||||
import io.floci.aws.services.eventbridgev2.model.RotationRequest;
|
||||
import io.floci.aws.services.secretsmanager.SecretsManagerService;
|
||||
import io.floci.aws.services.secretsmanager.model.Secret;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
@@ -25,6 +28,7 @@ import org.jboss.logging.Logger;
|
||||
import java.net.URI;
|
||||
import java.security.SecureRandom;
|
||||
import java.time.Clock;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.Base64;
|
||||
import java.util.LinkedHashMap;
|
||||
@@ -46,6 +50,12 @@ public class EventBridgeV2EventSources implements Resettable {
|
||||
private static final Logger LOG = Logger.getLogger(EventBridgeV2EventSources.class);
|
||||
private static final int GENERATED_SECRET_BYTES = 32;
|
||||
private static final String TOKEN_NAMESPACE = "event-sourcev2";
|
||||
private static final Duration ROTATION_TOKEN_MEMORY = Duration.ofHours(8);
|
||||
private static final ObjectMapper JSON = new ObjectMapper();
|
||||
private static final Map<String, String> ROTATION_MEMBERS = Map.of(
|
||||
WebhookEventsConfigurations.STATIC_TOKEN, "StaticTokenSecretValue",
|
||||
WebhookEventsConfigurations.BASIC, "BasicHttpPassword",
|
||||
WebhookEventsConfigurations.HMAC, "HmacSecretValue");
|
||||
|
||||
private final AccountAwareStorageBackend<EventSourceV2> sources;
|
||||
private final SecretsManagerService secrets;
|
||||
@@ -157,27 +167,138 @@ public class EventBridgeV2EventSources implements Resettable {
|
||||
configuration, WebhookEventsConfigurations.authType(
|
||||
source.getConfiguration().get(WebhookEventsConfigurations.WEBHOOK)));
|
||||
|
||||
EventSourceV2 changed = new EventSourceV2();
|
||||
changed.setName(source.getName());
|
||||
changed.setArn(source.getArn());
|
||||
changed.setEventBusArn(source.getEventBusArn());
|
||||
EventSourceV2 changed = copyOf(source);
|
||||
changed.setDescription(request.hasNonNull("Description") ? request.get("Description").textValue()
|
||||
: source.getDescription());
|
||||
changed.setConfiguration(webhook == null ? source.getConfiguration()
|
||||
: WebhookEventsConfigurations.echo(webhook));
|
||||
changed.setState(source.getState());
|
||||
changed.setCreationTime(source.getCreationTime());
|
||||
changed.setLastModifiedTime(clock.instant());
|
||||
changed.setTags(source.getTags());
|
||||
changed.setClientToken(source.getClientToken());
|
||||
changed.setCreateRequestHash(source.getCreateRequestHash());
|
||||
changed.setWebhookHostId(source.getWebhookHostId());
|
||||
changed.setWebhookToken(source.getWebhookToken());
|
||||
changed.setSecretArn(source.getSecretArn());
|
||||
sources.put(EventBridgeV2Service.storageKey(region, source.getName()), changed);
|
||||
return changed;
|
||||
}
|
||||
|
||||
/**
|
||||
* Replaces the credential in the source's secret, with the one the request gives or a generated one, and
|
||||
* returns the secret's ARN. The URL and the secret stay, and so does the time the source was modified. A
|
||||
* retry within 8 hours with a {@code ClientToken} of the source returns the ARN and changes nothing when it
|
||||
* repeats the request, and fails when it changes it.
|
||||
*/
|
||||
String rotateCredentials(JsonNode request, String region) {
|
||||
EventBridgeV2RequestShapes.check("RotateWebhookCredentials", request);
|
||||
String arn = request.get("EventSourceArn").textValue();
|
||||
checkArn(arn, region);
|
||||
String clientToken = request.path("ClientToken").textValue();
|
||||
if (clientToken == null) {
|
||||
throw EventBridgeV2Service.invalidInput("ClientToken is required");
|
||||
}
|
||||
JsonNode credential = request.hasNonNull("Credential") ? request.get("Credential") : null;
|
||||
String given = credential == null ? null : credentialMember(credential);
|
||||
EventSourceV2 source = require(arn, region);
|
||||
JsonNode webhook = source.getConfiguration().path(WebhookEventsConfigurations.WEBHOOK);
|
||||
String authType = WebhookEventsConfigurations.authType(webhook);
|
||||
String member = ROTATION_MEMBERS.get(authType);
|
||||
if (given != null && !given.equals(member)) {
|
||||
throw EventBridgeV2Service.invalidInput("Credential must set " + member
|
||||
+ ", because the authentication type of this EventSource is " + authType);
|
||||
}
|
||||
String value = given == null ? null : credential.get(given).textValue();
|
||||
if (WebhookEventsConfigurations.HMAC.equals(authType) && value != null) {
|
||||
value = WebhookEventsConfigurations.rotatedHmacSecret(value,
|
||||
webhook.path("AuthConfiguration").path(WebhookEventsConfigurations.HMAC));
|
||||
}
|
||||
|
||||
String requestHash = Digests.sha256Hex(EventBridgeV2Service.withoutClientToken(request));
|
||||
Instant now = clock.instant();
|
||||
RotationRequest seen = source.getRotationRequests().get(clientToken);
|
||||
if (seen != null && remembered(seen, now)) {
|
||||
if (!seen.requestHash().equals(requestHash)) {
|
||||
throw new AwsException("IdempotentParameterMismatchException",
|
||||
"ClientToken was used by a previous request with different parameters", 409);
|
||||
}
|
||||
return source.getSecretArn();
|
||||
}
|
||||
requireSecretUsable(source, region);
|
||||
|
||||
String current = secrets.getSecretValue(source.getSecretArn(), null, null, region).getSecretString();
|
||||
String replacement = WebhookEventsConfigurations.BASIC.equals(authType)
|
||||
? basicSecret(usernameOf(current), value != null ? value : generated())
|
||||
: value != null ? value : generated();
|
||||
if (!replacement.equals(current)) {
|
||||
secrets.rotateManagedSecretAfter(source.getSecretArn(), OWNING_SERVICE, region, () -> replacement,
|
||||
() -> { });
|
||||
}
|
||||
EventSourceV2 changed = copyOf(source);
|
||||
changed.getRotationRequests().values().removeIf(entry -> !remembered(entry, now));
|
||||
changed.getRotationRequests().put(clientToken, new RotationRequest(requestHash, now));
|
||||
sources.put(EventBridgeV2Service.storageKey(region, source.getName()), changed);
|
||||
return changed.getSecretArn();
|
||||
}
|
||||
|
||||
private static boolean remembered(RotationRequest request, Instant now) {
|
||||
return now.isBefore(request.rotatedAt().plus(ROTATION_TOKEN_MEMORY));
|
||||
}
|
||||
|
||||
private void requireSecretUsable(EventSourceV2 source, String region) {
|
||||
boolean unusable;
|
||||
try {
|
||||
unusable = secrets.describeSecret(source.getSecretArn(), region).getDeletedDate() != null;
|
||||
} catch (AwsException e) {
|
||||
if (!"ResourceNotFoundException".equals(e.getErrorCode())) {
|
||||
throw e;
|
||||
}
|
||||
unusable = true;
|
||||
}
|
||||
if (unusable) {
|
||||
throw new AwsException("InvalidStateException",
|
||||
"The secret of the EventSource is scheduled for deletion or has been deleted", 409);
|
||||
}
|
||||
}
|
||||
|
||||
/** The one member of {@code Credential} that is set, or an error when the request sets none or several. */
|
||||
private static String credentialMember(JsonNode credential) {
|
||||
List<String> set = ROTATION_MEMBERS.values().stream().filter(credential::hasNonNull).toList();
|
||||
if (set.size() != 1) {
|
||||
throw EventBridgeV2Service.invalidInput("Credential must set exactly one of StaticTokenSecretValue, "
|
||||
+ "BasicHttpPassword or HmacSecretValue");
|
||||
}
|
||||
return set.getFirst();
|
||||
}
|
||||
|
||||
private static String usernameOf(String basicSecret) {
|
||||
try {
|
||||
return JSON.readTree(basicSecret).path("username").textValue();
|
||||
} catch (JsonProcessingException e) {
|
||||
throw new IllegalStateException("The secret of a Basic webhook event source is not JSON", e);
|
||||
}
|
||||
}
|
||||
|
||||
private static EventSourceV2 copyOf(EventSourceV2 source) {
|
||||
EventSourceV2 copy = new EventSourceV2();
|
||||
copy.setName(source.getName());
|
||||
copy.setArn(source.getArn());
|
||||
copy.setEventBusArn(source.getEventBusArn());
|
||||
copy.setDescription(source.getDescription());
|
||||
copy.setConfiguration(source.getConfiguration());
|
||||
copy.setState(source.getState());
|
||||
copy.setCreationTime(source.getCreationTime());
|
||||
copy.setLastModifiedTime(source.getLastModifiedTime());
|
||||
copy.setTags(source.getTags());
|
||||
copy.setClientToken(source.getClientToken());
|
||||
copy.setCreateRequestHash(source.getCreateRequestHash());
|
||||
copy.setWebhookHostId(source.getWebhookHostId());
|
||||
copy.setWebhookToken(source.getWebhookToken());
|
||||
copy.setSecretArn(source.getSecretArn());
|
||||
copy.setRotationRequests(new LinkedHashMap<>(source.getRotationRequests()));
|
||||
return copy;
|
||||
}
|
||||
|
||||
private static String basicSecret(String username, String password) {
|
||||
ObjectNode credential = JsonNodeFactory.instance.objectNode();
|
||||
credential.put("username", username);
|
||||
credential.put("password", password);
|
||||
return credential.toString();
|
||||
}
|
||||
|
||||
EventSourceV2 describe(JsonNode request, String region) {
|
||||
return find("DescribeEventSource", request, region);
|
||||
}
|
||||
@@ -288,10 +409,8 @@ public class EventBridgeV2EventSources implements Resettable {
|
||||
String secretString;
|
||||
if (WebhookEventsConfigurations.BASIC.equals(authType)) {
|
||||
JsonNode basic = auth.get(WebhookEventsConfigurations.BASIC);
|
||||
ObjectNode credential = JsonNodeFactory.instance.objectNode();
|
||||
credential.put("username", basic.hasNonNull("Username") ? basic.get("Username").textValue() : generated());
|
||||
credential.put("password", basic.hasNonNull("Password") ? basic.get("Password").textValue() : generated());
|
||||
secretString = credential.toString();
|
||||
secretString = basicSecret(basic.hasNonNull("Username") ? basic.get("Username").textValue() : generated(),
|
||||
basic.hasNonNull("Password") ? basic.get("Password").textValue() : generated());
|
||||
} else if (WebhookEventsConfigurations.HMAC.equals(authType)) {
|
||||
String given = WebhookEventsConfigurations.hmacSecretValue(auth.get(WebhookEventsConfigurations.HMAC));
|
||||
secretString = given != null ? given : generated();
|
||||
|
||||
@@ -57,6 +57,7 @@ public class EventBridgeV2Handler {
|
||||
case "DescribeEventSource" -> handleDescribeEventSource(request, region);
|
||||
case "ListEventSources" -> handleListEventSources(request, region);
|
||||
case "UpdateEventSource" -> handleUpdateEventSource(request, region);
|
||||
case "RotateWebhookCredentials" -> handleRotateWebhookCredentials(request, region);
|
||||
case "DeleteEventSource" -> handleDeleteEventSource(request, region);
|
||||
case "PutEvents" -> handlePutEvents(request, region);
|
||||
default -> throw new AwsException("UnsupportedOperation",
|
||||
@@ -233,6 +234,12 @@ public class EventBridgeV2Handler {
|
||||
return Response.ok(response).build();
|
||||
}
|
||||
|
||||
private Response handleRotateWebhookCredentials(JsonNode request, String region) {
|
||||
ObjectNode response = objectMapper.createObjectNode();
|
||||
response.put("SecretArn", service.rotateWebhookCredentials(request, region));
|
||||
return Response.ok(response).build();
|
||||
}
|
||||
|
||||
private Response handleDeleteEventSource(JsonNode request, String region) {
|
||||
service.deleteEventSource(request, region);
|
||||
return Response.ok(objectMapper.createObjectNode()).build();
|
||||
|
||||
@@ -22,6 +22,11 @@ final class EventBridgeV2RequestShapes {
|
||||
"aws/eventbridgev2-request-shapes.json", "EventBridge V2 request shapes", new Messages(),
|
||||
new RequestConstraintCheck.ViolationOrder(true, true));
|
||||
|
||||
/** Every string member of RotateWebhookCredentials reports its length before its pattern. */
|
||||
private static final RequestConstraintCheck LENGTH_FIRST_CHECK = RequestConstraintCheck.load(
|
||||
"aws/eventbridgev2-request-shapes.json", "EventBridge V2 request shapes", new Messages(),
|
||||
new RequestConstraintCheck.ViolationOrder(false, true));
|
||||
|
||||
private EventBridgeV2RequestShapes() {
|
||||
}
|
||||
|
||||
@@ -31,7 +36,8 @@ final class EventBridgeV2RequestShapes {
|
||||
}
|
||||
|
||||
static void check(String operation, JsonNode request) {
|
||||
List<String> violations = CHECK.violations(operation, withoutWhsecPrefix(request));
|
||||
RequestConstraintCheck check = "RotateWebhookCredentials".equals(operation) ? LENGTH_FIRST_CHECK : CHECK;
|
||||
List<String> violations = check.violations(operation, withoutWhsecPrefix(request));
|
||||
if (!violations.isEmpty()) {
|
||||
throw SmithyValidationErrors.exception("InvalidInputException",
|
||||
violations.subList(0, Math.min(violations.size(), MAX_VIOLATIONS)));
|
||||
|
||||
@@ -426,6 +426,10 @@ public class EventBridgeV2Service implements Resettable {
|
||||
return eventSources.update(request, region);
|
||||
}
|
||||
|
||||
public synchronized String rotateWebhookCredentials(JsonNode request, String region) {
|
||||
return eventSources.rotateCredentials(request, region);
|
||||
}
|
||||
|
||||
public synchronized void deleteEventSource(JsonNode request, String region) {
|
||||
eventSources.delete(request, region);
|
||||
}
|
||||
|
||||
@@ -7,6 +7,7 @@ import io.floci.aws.core.common.RequestScopes;
|
||||
import io.floci.aws.services.eventbridgev2.EventBridgeV2EventSources.LocatedSource;
|
||||
import io.floci.aws.services.eventbridgev2.model.EventSourceV2;
|
||||
import io.floci.aws.services.secretsmanager.SecretsManagerService;
|
||||
import io.floci.aws.services.secretsmanager.model.SecretVersion;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
import org.jboss.logging.Logger;
|
||||
@@ -14,6 +15,8 @@ import org.jboss.logging.Logger;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.MessageDigest;
|
||||
import java.time.Clock;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
@@ -46,6 +49,7 @@ public class EventBridgeV2Webhooks {
|
||||
static final Answer NOT_FOUND = new Answer(404, "Not Found");
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(EventBridgeV2Webhooks.class);
|
||||
private static final Duration PREVIOUS_CREDENTIAL_GRACE = Duration.ofMinutes(15);
|
||||
private static final Pattern PATH = Pattern.compile("/(k1[A-Za-z0-9_-]{64})/");
|
||||
|
||||
private final EventBridgeV2Service service;
|
||||
@@ -90,10 +94,7 @@ public class EventBridgeV2Webhooks {
|
||||
String accountId = located.get().accountId();
|
||||
String region = AwsArnUtils.parse(source.getArn()).region();
|
||||
JsonNode webhook = source.getConfiguration().path(WebhookEventsConfigurations.WEBHOOK);
|
||||
Optional<String> secret = currentSecret(accountId, region, source);
|
||||
if (secret.isEmpty()
|
||||
|| !WebhookAuthenticator.allows(webhook, secret.get(), request.headers(), request.body(),
|
||||
clock.instant())) {
|
||||
if (!credentialAccepted(accountId, region, source, webhook, request)) {
|
||||
return FORBIDDEN;
|
||||
}
|
||||
Optional<JsonNode> data = WebhookEvents.parseBody(request.body());
|
||||
@@ -123,12 +124,39 @@ public class EventBridgeV2Webhooks {
|
||||
return OK;
|
||||
}
|
||||
|
||||
private Optional<String> currentSecret(String accountId, String region, EventSourceV2 source) {
|
||||
/** The current credential, and the one the last rotation replaced until that rotation is 15 minutes old. */
|
||||
private boolean credentialAccepted(String accountId, String region, EventSourceV2 source, JsonNode webhook,
|
||||
Request request) {
|
||||
Optional<SecretVersion> current = secretVersion(accountId, region, source, null);
|
||||
if (current.isEmpty()) {
|
||||
return false;
|
||||
}
|
||||
if (matches(webhook, current.get(), request)) {
|
||||
return true;
|
||||
}
|
||||
Instant rotated = current.get().getCreatedDate();
|
||||
if (rotated == null || !clock.instant().isBefore(rotated.plus(PREVIOUS_CREDENTIAL_GRACE))) {
|
||||
return false;
|
||||
}
|
||||
return secretVersion(accountId, region, source, "AWSPREVIOUS")
|
||||
.filter(previous -> matches(webhook, previous, request)).isPresent();
|
||||
}
|
||||
|
||||
private boolean matches(JsonNode webhook, SecretVersion version, Request request) {
|
||||
return version.getSecretString() != null
|
||||
&& WebhookAuthenticator.allows(webhook, version.getSecretString(), request.headers(), request.body(),
|
||||
clock.instant());
|
||||
}
|
||||
|
||||
private Optional<SecretVersion> secretVersion(String accountId, String region, EventSourceV2 source,
|
||||
String stage) {
|
||||
try {
|
||||
return Optional.ofNullable(RequestScopes.callAs(accountId, region,
|
||||
() -> secrets.getSecretValue(source.getSecretArn(), null, null, region).getSecretString()));
|
||||
() -> secrets.getSecretValue(source.getSecretArn(), null, stage, region)));
|
||||
} catch (AwsException e) {
|
||||
LOG.warnv("The secret of event source {0} could not be read: {1}", source.getArn(), e.getMessage());
|
||||
if (stage == null) {
|
||||
LOG.warnv("The secret of event source {0} could not be read: {1}", source.getArn(), e.getMessage());
|
||||
}
|
||||
return Optional.empty();
|
||||
}
|
||||
}
|
||||
|
||||
+42
-13
@@ -31,6 +31,7 @@ final class WebhookEventsConfigurations {
|
||||
private static final String HMAC_INVALID = AUTH + ".HmacAuthConfiguration is invalid: ";
|
||||
private static final String WHSEC = "whsec_";
|
||||
private static final int MIN_HMAC_SECRET_BYTES = 16;
|
||||
private static final int MAX_HMAC_SECRET_BYTES = 512;
|
||||
private static final String ONLY_WEBHOOK = "Only WebhookEventsConfiguration event sources are supported.";
|
||||
private static final List<String> SECRET_MEMBERS = List.of("SecretValue", "Username", "Password");
|
||||
private static final List<String> AUTH_MEMBERS = List.of(STATIC_TOKEN, BASIC, HMAC);
|
||||
@@ -154,18 +155,14 @@ final class WebhookEventsConfigurations {
|
||||
|
||||
private static void validateHmac(JsonNode hmac) {
|
||||
String secret = hmacSecretValue(hmac);
|
||||
boolean base64 = "BASE64".equals(hmac.path("SecretEncoding").asText(null));
|
||||
boolean base64 = isBase64(hmac);
|
||||
int secretBytes = 0;
|
||||
if (secret != null) {
|
||||
if (base64) {
|
||||
try {
|
||||
secretBytes = Base64.getDecoder().decode(secret).length;
|
||||
} catch (IllegalArgumentException e) {
|
||||
throw invalidInput(AUTH + ".HmacAuthConfiguration.SecretValue must be standard Base64 when "
|
||||
+ "SecretEncoding is BASE64");
|
||||
}
|
||||
} else {
|
||||
secretBytes = secret.getBytes(StandardCharsets.UTF_8).length;
|
||||
try {
|
||||
secretBytes = hmacSecretBytes(secret, base64);
|
||||
} catch (IllegalArgumentException e) {
|
||||
throw invalidInput(AUTH + ".HmacAuthConfiguration.SecretValue must be standard Base64 when "
|
||||
+ "SecretEncoding is BASE64");
|
||||
}
|
||||
}
|
||||
String signature = hmac.path("SignatureHttpHeader").asText(null);
|
||||
@@ -251,9 +248,41 @@ final class WebhookEventsConfigurations {
|
||||
if (node == null || !node.isTextual()) {
|
||||
return null;
|
||||
}
|
||||
String value = node.textValue();
|
||||
return "BASE64".equals(hmac.path("SecretEncoding").asText(null)) && value.startsWith(WHSEC)
|
||||
? value.substring(WHSEC.length()) : value;
|
||||
return storedHmacSecret(node.textValue(), isBase64(hmac));
|
||||
}
|
||||
|
||||
private static boolean isBase64(JsonNode hmac) {
|
||||
return "BASE64".equals(hmac.path("SecretEncoding").asText(null));
|
||||
}
|
||||
|
||||
private static String storedHmacSecret(String value, boolean base64) {
|
||||
return base64 && value.startsWith(WHSEC) ? value.substring(WHSEC.length()) : value;
|
||||
}
|
||||
|
||||
/** The bytes of the key a stored HMAC secret signs with. Throws when a BASE64 secret is not standard Base64. */
|
||||
private static int hmacSecretBytes(String stored, boolean base64) {
|
||||
return base64 ? Base64.getDecoder().decode(stored).length : stored.getBytes(StandardCharsets.UTF_8).length;
|
||||
}
|
||||
|
||||
/**
|
||||
* The HMAC secret a rotation stores for {@code value}, judged against the source's configuration. A rotation
|
||||
* has an upper bound that create does not.
|
||||
*/
|
||||
static String rotatedHmacSecret(String value, JsonNode hmac) {
|
||||
boolean base64 = isBase64(hmac);
|
||||
String stored = storedHmacSecret(value, base64);
|
||||
int bytes;
|
||||
try {
|
||||
bytes = hmacSecretBytes(stored, base64);
|
||||
} catch (IllegalArgumentException e) {
|
||||
throw invalidInput("Credential.HmacSecretValue must be standard Base64 when the SecretEncoding of the "
|
||||
+ "EventSource is BASE64");
|
||||
}
|
||||
if (bytes < MIN_HMAC_SECRET_BYTES || bytes > MAX_HMAC_SECRET_BYTES) {
|
||||
throw invalidInput("Credential.HmacSecretValue cannot be used with the authentication settings of "
|
||||
+ "this EventSource");
|
||||
}
|
||||
return stored;
|
||||
}
|
||||
|
||||
/** The authentication type of a webhook configuration, the name of its one authentication member. */
|
||||
|
||||
@@ -29,6 +29,7 @@ public class EventSourceV2 {
|
||||
private String webhookHost;
|
||||
private String webhookToken;
|
||||
private String secretArn;
|
||||
private Map<String, RotationRequest> rotationRequests = new LinkedHashMap<>();
|
||||
|
||||
public EventSourceV2() {
|
||||
}
|
||||
@@ -144,4 +145,13 @@ public class EventSourceV2 {
|
||||
public void setSecretArn(String secretArn) {
|
||||
this.secretArn = secretArn;
|
||||
}
|
||||
|
||||
/** The rotations of the last 8 hours, by ClientToken. */
|
||||
public Map<String, RotationRequest> getRotationRequests() {
|
||||
return rotationRequests;
|
||||
}
|
||||
|
||||
public void setRotationRequests(Map<String, RotationRequest> rotationRequests) {
|
||||
this.rotationRequests = rotationRequests == null ? new LinkedHashMap<>() : rotationRequests;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
package io.floci.aws.services.eventbridgev2.model;
|
||||
|
||||
import io.quarkus.runtime.annotations.RegisterForReflection;
|
||||
|
||||
import java.time.Instant;
|
||||
|
||||
/** A rotation a source remembers by its ClientToken: a hash of the request and the time it rotated. */
|
||||
@RegisterForReflection
|
||||
public record RotationRequest(String requestHash, Instant rotatedAt) {
|
||||
}
|
||||
@@ -8,6 +8,7 @@
|
||||
"DeleteEventSource": "DeleteEventSourceRequest",
|
||||
"DescribeEventSource": "DescribeEventSourceRequest",
|
||||
"ListEventSources": "ListEventSourcesRequest",
|
||||
"RotateWebhookCredentials": "RotateWebhookCredentialsRequest",
|
||||
"UpdateEventSource": "UpdateEventSourceRequest"
|
||||
},
|
||||
"shapes": {
|
||||
@@ -195,6 +196,17 @@
|
||||
"max": 1600,
|
||||
"pattern": "arn:aws(-[a-z0-9]+)*:iam::\\d{12}:role\\/[\\w+=,.@/-]+"
|
||||
},
|
||||
"RotateWebhookCredentialsRequest": {
|
||||
"type": "structure",
|
||||
"required": [
|
||||
"EventSourceArn"
|
||||
],
|
||||
"members": {
|
||||
"Credential": "WebhookCredential",
|
||||
"EventSourceArn": "WebhookEventSourceArn",
|
||||
"ClientToken": "ClientToken"
|
||||
}
|
||||
},
|
||||
"TagKey": {
|
||||
"type": "string",
|
||||
"min": 1,
|
||||
@@ -240,6 +252,14 @@
|
||||
"Username": "WebhookUsername"
|
||||
}
|
||||
},
|
||||
"WebhookCredential": {
|
||||
"type": "structure",
|
||||
"members": {
|
||||
"StaticTokenSecretValue": "WebhookSecretValue",
|
||||
"BasicHttpPassword": "WebhookSecretValue",
|
||||
"HmacSecretValue": "WebhookSecretValue"
|
||||
}
|
||||
},
|
||||
"WebhookDeduplicationConfiguration": {
|
||||
"type": "structure",
|
||||
"required": [
|
||||
@@ -261,6 +281,12 @@
|
||||
"max": 64,
|
||||
"pattern": "[\\u0020-\\u007E]+"
|
||||
},
|
||||
"WebhookEventSourceArn": {
|
||||
"type": "string",
|
||||
"min": 1,
|
||||
"max": 1011,
|
||||
"pattern": "arn:aws(-[a-z0-9]+)*:events:[a-z][a-z0-9]*(-[a-z0-9]+)*:([0-9]{12}):event-sourcev2\\/webhook\\/[A-Za-z0-9][\\.\\-_A-Za-z0-9]{0,255}\\/[a-z0-9]{25}"
|
||||
},
|
||||
"WebhookEventsSourceConfiguration": {
|
||||
"type": "structure",
|
||||
"required": [
|
||||
|
||||
@@ -559,6 +559,72 @@ class EventBridgeV2RequestShapesTest {
|
||||
assertTrue(found.get(2).endsWith("' at 'tags' failed to satisfy constraint: " + "Map value must satisfy constraint: [Member must have length less than or equal to 256, Member must have length greater than or equal to 0, Member must satisfy regular expression pattern: (\\S([\\s\\S]*\\S)?)?(?![\\s\\S]).*, Member must not be null]"), found.get(2));
|
||||
}
|
||||
|
||||
private static final String ROTATE_ARN_PATTERN = "arn:aws(-[a-z0-9]+)*:events:[a-z][a-z0-9]*(-[a-z0-9]+)*:"
|
||||
+ "([0-9]{12}):event-sourcev2\\/webhook\\/[A-Za-z0-9][\\.\\-_A-Za-z0-9]{0,255}\\/[a-z0-9]{25}";
|
||||
|
||||
@Test
|
||||
void rotateWebhookCredentialsWalksCredentialThenArnThenClientToken() {
|
||||
assertAnswers("RotateWebhookCredentials",
|
||||
"{\"EventSourceArn\":\"bad\",\"ClientToken\":\"a b\",\"Credential\":{\"StaticTokenSecretValue\":\"bad\"}}",
|
||||
"Value at 'credential.staticTokenSecretValue' failed to satisfy constraint: "
|
||||
+ "Member must have length greater than or equal to 6",
|
||||
"Value 'bad' at 'eventSourceArn' failed to satisfy constraint: "
|
||||
+ "Member must satisfy regular expression pattern: " + ROTATE_ARN_PATTERN,
|
||||
"Value 'a b' at 'clientToken' failed to satisfy constraint: "
|
||||
+ "Member must satisfy regular expression pattern: [\\u0021-\\u007E]+");
|
||||
}
|
||||
|
||||
@Test
|
||||
void rotateWebhookCredentialsPrintsLengthBeforePatternForAnEmptyClientToken() {
|
||||
assertAnswers("RotateWebhookCredentials",
|
||||
"{\"EventSourceArn\":\"bad\",\"ClientToken\":\"\",\"Credential\":{\"StaticTokenSecretValue\":\"bad\","
|
||||
+ "\"BasicHttpPassword\":\"bad\",\"HmacSecretValue\":\"bad\"}}",
|
||||
"Value at 'credential.staticTokenSecretValue' failed to satisfy constraint: "
|
||||
+ "Member must have length greater than or equal to 6",
|
||||
"Value at 'credential.basicHttpPassword' failed to satisfy constraint: "
|
||||
+ "Member must have length greater than or equal to 6",
|
||||
"Value at 'credential.hmacSecretValue' failed to satisfy constraint: "
|
||||
+ "Member must have length greater than or equal to 6",
|
||||
"Value 'bad' at 'eventSourceArn' failed to satisfy constraint: "
|
||||
+ "Member must satisfy regular expression pattern: " + ROTATE_ARN_PATTERN,
|
||||
"Value '' at 'clientToken' failed to satisfy constraint: Member must have length greater than or equal to 1",
|
||||
"Value '' at 'clientToken' failed to satisfy constraint: "
|
||||
+ "Member must satisfy regular expression pattern: [\\u0021-\\u007E]+");
|
||||
}
|
||||
|
||||
@Test
|
||||
void rotateWebhookCredentialsMissingArnAndOversizeMembers() {
|
||||
assertAnswers("RotateWebhookCredentials", "{}",
|
||||
"Value null at 'eventSourceArn' failed to satisfy constraint: Member must not be null");
|
||||
assertAnswers("RotateWebhookCredentials",
|
||||
"{\"EventSourceArn\":\"arn:aws:events:us-east-1:123456789012:event-sourcev2/webhook/x/abcdefghijklmnopqrstuvwxy\","
|
||||
+ "\"Credential\":{\"StaticTokenSecretValue\":\"" + "a".repeat(513) + "\"}}",
|
||||
"Value at 'credential.staticTokenSecretValue' failed to satisfy constraint: "
|
||||
+ "Member must have length less than or equal to 512");
|
||||
assertAnswers("RotateWebhookCredentials",
|
||||
"{\"EventSourceArn\":\"arn:aws:events:us-east-1:123456789012:event-sourcev2/webhook/x/abcdefghijklmnopqrstuvwxy\","
|
||||
+ "\"ClientToken\":\"" + "c".repeat(65) + "\"}",
|
||||
"Value '" + "c".repeat(65) + "' at 'clientToken' failed to satisfy constraint: "
|
||||
+ "Member must have length less than or equal to 64");
|
||||
}
|
||||
|
||||
@Test
|
||||
void rotateWebhookCredentialsAnswersSerializationExceptionForACredentialOfTheWrongType() {
|
||||
assertSerializationException("RotateWebhookCredentials",
|
||||
"{\"EventSourceArn\":\"arn:aws:events:us-east-1:123456789012:event-sourcev2/webhook/x/abcdefghijklmnopqrstuvwxy\","
|
||||
+ "\"Credential\":\"secret\"}");
|
||||
}
|
||||
|
||||
@Test
|
||||
void rotateWebhookCredentialsAcceptsANullCredentialAndANullMember() {
|
||||
assertDoesNotThrow(() -> EventBridgeV2RequestShapes.check("RotateWebhookCredentials", json(
|
||||
"{\"EventSourceArn\":\"arn:aws:events:us-east-1:123456789012:event-sourcev2/webhook/x/abcdefghijklmnopqrstuvwxy\","
|
||||
+ "\"Credential\":null}")));
|
||||
assertDoesNotThrow(() -> EventBridgeV2RequestShapes.check("RotateWebhookCredentials", json(
|
||||
"{\"EventSourceArn\":\"arn:aws:events:us-east-1:123456789012:event-sourcev2/webhook/x/abcdefghijklmnopqrstuvwxy\","
|
||||
+ "\"Credential\":{\"StaticTokenSecretValue\":\"abcdef\",\"HmacSecretValue\":null}}")));
|
||||
}
|
||||
|
||||
private static void assertAnswers(String operation, String request, String... violations) {
|
||||
assertAnswers(operation, json(request), violations);
|
||||
}
|
||||
|
||||
+762
@@ -0,0 +1,762 @@
|
||||
package io.floci.aws.services.eventbridgev2;
|
||||
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import io.floci.aws.config.EmulatorConfig;
|
||||
import io.floci.aws.core.common.AwsException;
|
||||
import io.floci.aws.core.common.RegionResolver;
|
||||
import io.floci.aws.core.storage.AccountAwareStorageBackend;
|
||||
import io.floci.aws.core.storage.StorageFactory;
|
||||
import io.floci.aws.services.eventbridgev2.EventBridgeV2Webhooks.Answer;
|
||||
import io.floci.aws.services.eventbridgev2.EventBridgeV2Webhooks.Request;
|
||||
import io.floci.aws.services.eventbridgev2.model.EventSourceV2;
|
||||
import io.floci.aws.services.eventbridgev2.model.RotationRequest;
|
||||
import io.floci.aws.services.secretsmanager.SecretsManagerService;
|
||||
import io.floci.aws.services.secretsmanager.model.Secret;
|
||||
import io.floci.aws.testing.ManualClock;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import javax.crypto.Mac;
|
||||
import javax.crypto.spec.SecretKeySpec;
|
||||
|
||||
import java.net.URI;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.Base64;
|
||||
import java.util.HexFormat;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.TreeMap;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotEquals;
|
||||
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;
|
||||
|
||||
/**
|
||||
* RotateWebhookCredentials against a real Secrets Manager service, with the messages, statuses and the order of
|
||||
* checks as measured on AWS.
|
||||
*/
|
||||
class EventBridgeV2RotateCredentialsTest {
|
||||
private static final String REGION = "us-east-1";
|
||||
private static final String ACCOUNT = "000000000000";
|
||||
private static final Instant NOW = Instant.parse("2026-11-25T06:00:00Z");
|
||||
private static final ObjectMapper MAPPER = new ObjectMapper();
|
||||
private static final String ROLE = "arn:aws:iam::000000000000:role/Hook";
|
||||
private static final String STATIC_AUTH = "{\"StaticTokenAuthConfiguration\":{\"TokenHttpHeader\":\"X-Tok\","
|
||||
+ "\"SecretValue\":\"original-token\"}}";
|
||||
private static final String BASIC_AUTH = "{\"BasicHttpAuthConfiguration\":{\"Username\":\"alice\","
|
||||
+ "\"Password\":\"original-pw\"}}";
|
||||
private static final String HMAC_AUTH = "{\"HmacAuthConfiguration\":{\"Algorithm\":\"SHA256\","
|
||||
+ "\"Encoding\":\"HEX\",\"SignatureHttpHeader\":\"X-Sig\",\"SignedMessageComposition\":\"BODY\","
|
||||
+ "\"SecretValue\":\"0123456789abcdef\"}}";
|
||||
private static final String HMAC_BASE64_AUTH = "{\"HmacAuthConfiguration\":{\"Algorithm\":\"SHA256\","
|
||||
+ "\"Encoding\":\"HEX\",\"SignatureHttpHeader\":\"X-Sig\",\"SignedMessageComposition\":\"BODY\","
|
||||
+ "\"SecretEncoding\":\"BASE64\",\"SecretValue\":\"MDEyMzQ1Njc4OWFiY2RlZg==\"}}";
|
||||
private static final String MISSING_SOURCE =
|
||||
"arn:aws:events:us-east-1:000000000000:event-sourcev2/webhook/nope/abcdefghijklmnopqrstuvwxy";
|
||||
private static final String UNION_MESSAGE =
|
||||
"Credential must set exactly one of StaticTokenSecretValue, BasicHttpPassword or HmacSecretValue";
|
||||
private static final String HMAC_RANGE_MESSAGE =
|
||||
"Credential.HmacSecretValue cannot be used with the authentication settings of this EventSource";
|
||||
private static final String HMAC_BASE64_MESSAGE = "Credential.HmacSecretValue must be standard Base64 when the "
|
||||
+ "SecretEncoding of the EventSource is BASE64";
|
||||
|
||||
private SecretsManagerService secrets;
|
||||
private EventBridgeV2Service service;
|
||||
private EventBridgeV2Webhooks webhooks;
|
||||
private ManualClock clock;
|
||||
private String bus;
|
||||
private int tokens;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
StorageFactory factory = mock(StorageFactory.class);
|
||||
when(factory.create(eq("secretsmanager"), any(), any(TypeReference.class)))
|
||||
.thenAnswer(call -> AccountAwareStorageBackend.<Secret>inMemory(ACCOUNT));
|
||||
EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
|
||||
when(config.services().secretsmanager().defaultRecoveryWindowDays()).thenReturn(30);
|
||||
RegionResolver regionResolver = new RegionResolver(REGION, ACCOUNT);
|
||||
secrets = new SecretsManagerService(factory, config, regionResolver, null, MAPPER, null);
|
||||
clock = new ManualClock(NOW);
|
||||
EventBridgeV2EventSources sources = new EventBridgeV2EventSources(
|
||||
AccountAwareStorageBackend.inMemory(ACCOUNT), secrets, regionResolver, clock, "http://floci.test:4566");
|
||||
service = new EventBridgeV2Service(AccountAwareStorageBackend.inMemory(ACCOUNT),
|
||||
AccountAwareStorageBackend.inMemory(ACCOUNT), regionResolver, mock(EventBridgeV2Delivery.class),
|
||||
sources, clock, true);
|
||||
webhooks = new EventBridgeV2Webhooks(service, sources, secrets, clock);
|
||||
bus = service.createEventBus(json("{\"Name\":\"orders\"}"), REGION).getArn();
|
||||
}
|
||||
|
||||
// ──────────────────────────── The secret ────────────────────────────
|
||||
|
||||
@Test
|
||||
void aSuppliedStaticTokenReplacesTheSecretAndKeepsTheOldOneAsPrevious() {
|
||||
EventSourceV2 source = source("hook", STATIC_AUTH);
|
||||
String first = versionOf(source, "AWSCURRENT");
|
||||
|
||||
String secretArn = rotate(source, "{\"StaticTokenSecretValue\":\"second-token\"}");
|
||||
|
||||
assertEquals(source.getSecretArn(), secretArn);
|
||||
assertEquals("second-token", valueOf(source, "AWSCURRENT"));
|
||||
assertEquals("original-token", valueOf(source, "AWSPREVIOUS"));
|
||||
assertEquals(first, versionOf(source, "AWSPREVIOUS"));
|
||||
assertEquals(Map.of("AWSCURRENT", versionOf(source, "AWSCURRENT"), "AWSPREVIOUS", first), stages(source));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aSecondRotationLeavesOnlyTheNewestTwoVersionsStaged() {
|
||||
EventSourceV2 source = source("hook", STATIC_AUTH);
|
||||
String first = versionOf(source, "AWSCURRENT");
|
||||
rotate(source, "{\"StaticTokenSecretValue\":\"second-token\"}");
|
||||
String second = versionOf(source, "AWSCURRENT");
|
||||
|
||||
rotate(source, "{\"StaticTokenSecretValue\":\"third-token\"}");
|
||||
|
||||
assertEquals("third-token", valueOf(source, "AWSCURRENT"));
|
||||
assertEquals("second-token", valueOf(source, "AWSPREVIOUS"));
|
||||
assertEquals(second, versionOf(source, "AWSPREVIOUS"));
|
||||
assertEquals(2, stages(source).size());
|
||||
assertEquals(List.of(), secrets.listSecretVersionIds(source.getSecretArn(), REGION).get(first));
|
||||
}
|
||||
|
||||
@Test
|
||||
void noCredentialGeneratesA44CharacterValue() {
|
||||
EventSourceV2 source = source("hook", STATIC_AUTH);
|
||||
|
||||
rotate(source, null);
|
||||
|
||||
String generated = valueOf(source, "AWSCURRENT");
|
||||
assertEquals(44, generated.length());
|
||||
assertEquals(32, Base64.getDecoder().decode(generated).length);
|
||||
assertEquals("original-token", valueOf(source, "AWSPREVIOUS"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aNullCredentialAndAKnownMemberWithANullOneAreAccepted() {
|
||||
EventSourceV2 source = source("hook", STATIC_AUTH);
|
||||
|
||||
service.rotateWebhookCredentials(json("{\"EventSourceArn\":\"" + source.getArn()
|
||||
+ "\",\"ClientToken\":\"t-null\",\"Credential\":null}"), REGION);
|
||||
assertEquals(44, valueOf(source, "AWSCURRENT").length());
|
||||
|
||||
rotate(source, "{\"StaticTokenSecretValue\":\"second-token\",\"HmacSecretValue\":null}");
|
||||
assertEquals("second-token", valueOf(source, "AWSCURRENT"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void basicKeepsItsUsernameWhetherThePasswordIsSuppliedOrGenerated() throws Exception {
|
||||
EventSourceV2 source = source("hook", BASIC_AUTH);
|
||||
|
||||
rotate(source, "{\"BasicHttpPassword\":\"pass:with:colon é\"}");
|
||||
JsonNode supplied = MAPPER.readTree(valueOf(source, "AWSCURRENT"));
|
||||
assertEquals("alice", supplied.get("username").textValue());
|
||||
assertEquals("pass:with:colon é", supplied.get("password").textValue());
|
||||
|
||||
rotate(source, null);
|
||||
JsonNode generated = MAPPER.readTree(valueOf(source, "AWSCURRENT"));
|
||||
assertEquals("alice", generated.get("username").textValue());
|
||||
assertEquals(44, generated.get("password").textValue().length());
|
||||
assertNotEquals("pass:with:colon é", generated.get("password").textValue());
|
||||
assertEquals("{\"username\":\"alice\",\"password\":\"pass:with:colon é\"}", valueOf(source, "AWSPREVIOUS"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void basicWithAGeneratedUsernameKeepsTheGeneratedOne() throws Exception {
|
||||
EventSourceV2 source = source("hook", "{\"BasicHttpAuthConfiguration\":{}}");
|
||||
String username = MAPPER.readTree(valueOf(source, "AWSCURRENT")).get("username").textValue();
|
||||
|
||||
rotate(source, "{\"BasicHttpPassword\":\"new-password\"}");
|
||||
|
||||
assertEquals(username, MAPPER.readTree(valueOf(source, "AWSCURRENT")).get("username").textValue());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aRawHmacSecretIsStoredAsGivenWithItsPrefix() {
|
||||
EventSourceV2 source = source("hook", HMAC_AUTH);
|
||||
|
||||
rotate(source, "{\"HmacSecretValue\":\"whsec_aaaaaaaaaa\"}");
|
||||
assertEquals("whsec_aaaaaaaaaa", valueOf(source, "AWSCURRENT"));
|
||||
|
||||
rotate(source, "{\"HmacSecretValue\":\"" + "é".repeat(8) + "\"}");
|
||||
assertEquals("é".repeat(8), valueOf(source, "AWSCURRENT"));
|
||||
|
||||
rotate(source, "{\"HmacSecretValue\":\"" + "é".repeat(256) + "\"}");
|
||||
assertEquals("é".repeat(256), valueOf(source, "AWSCURRENT"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aRawHmacSecretOutsideSixteenToFiveHundredTwelveBytesIsRefused() {
|
||||
EventSourceV2 source = source("hook", HMAC_AUTH);
|
||||
|
||||
assertRefused(source, "{\"HmacSecretValue\":\"aaaaaaaaaaaaaaa\"}", HMAC_RANGE_MESSAGE);
|
||||
assertRefused(source, "{\"HmacSecretValue\":\"" + "é".repeat(257) + "\"}", HMAC_RANGE_MESSAGE);
|
||||
rotate(source, "{\"HmacSecretValue\":\"aaaaaaaaaaaaaaaa\"}");
|
||||
assertEquals("aaaaaaaaaaaaaaaa", valueOf(source, "AWSCURRENT"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aBase64HmacSecretLosesItsPrefixAndKeepsItsPadding() {
|
||||
EventSourceV2 source = source("hook", HMAC_BASE64_AUTH);
|
||||
|
||||
rotate(source, "{\"HmacSecretValue\":\"whsec_a2tra2tra2tra2tra2traw==\"}");
|
||||
assertEquals("a2tra2tra2tra2tra2traw==", valueOf(source, "AWSCURRENT"));
|
||||
|
||||
rotate(source, "{\"HmacSecretValue\":\"a2tra2tra2tra2tra2traw\"}");
|
||||
assertEquals("a2tra2tra2tra2tra2traw", valueOf(source, "AWSCURRENT"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aBase64HmacSecretMustBeStandardBase64OfEnoughBytes() {
|
||||
EventSourceV2 source = source("hook", HMAC_BASE64_AUTH);
|
||||
|
||||
assertRefused(source, "{\"HmacSecretValue\":\"a2tra2tra2tra2tra2tr_w==\"}", HMAC_BASE64_MESSAGE);
|
||||
assertRefused(source, "{\"HmacSecretValue\":\"a2tra2tra2tra2tra2tr\\naw==\"}", HMAC_BASE64_MESSAGE);
|
||||
assertRefused(source, "{\"HmacSecretValue\":\"" + Base64.getEncoder().encodeToString(new byte[15]) + "\"}",
|
||||
HMAC_RANGE_MESSAGE);
|
||||
assertRefused(source, "{\"HmacSecretValue\":\"whsec_" + Base64.getEncoder().encodeToString(new byte[15])
|
||||
+ "\"}", HMAC_RANGE_MESSAGE);
|
||||
assertRefused(source, "{\"HmacSecretValue\":\"whsec_abcdef\"}", HMAC_RANGE_MESSAGE);
|
||||
}
|
||||
|
||||
@Test
|
||||
void aGeneratedHmacSecretIs44Characters() {
|
||||
EventSourceV2 source = source("hook", HMAC_BASE64_AUTH);
|
||||
|
||||
rotate(source, null);
|
||||
|
||||
assertEquals(44, valueOf(source, "AWSCURRENT").length());
|
||||
}
|
||||
|
||||
@Test
|
||||
void rotatingToTheValueThatIsAlreadyCurrentWritesNoVersion() {
|
||||
EventSourceV2 source = source("hook", STATIC_AUTH);
|
||||
Map<String, List<String>> before = secrets.listSecretVersionIds(source.getSecretArn(), REGION);
|
||||
|
||||
rotate(source, "{\"StaticTokenSecretValue\":\"original-token\"}");
|
||||
|
||||
assertEquals(before, secrets.listSecretVersionIds(source.getSecretArn(), REGION));
|
||||
}
|
||||
|
||||
@Test
|
||||
void rotatingBasicToTheCurrentPasswordWritesNoVersion() {
|
||||
EventSourceV2 source = source("hook", BASIC_AUTH);
|
||||
Map<String, List<String>> before = secrets.listSecretVersionIds(source.getSecretArn(), REGION);
|
||||
|
||||
rotate(source, "{\"BasicHttpPassword\":\"original-pw\"}");
|
||||
|
||||
assertEquals(before, secrets.listSecretVersionIds(source.getSecretArn(), REGION));
|
||||
}
|
||||
|
||||
@Test
|
||||
void rotatingHmacToTheCurrentValueWithItsPrefixWritesNoVersion() {
|
||||
EventSourceV2 source = source("hook", HMAC_BASE64_AUTH);
|
||||
Map<String, List<String>> before = secrets.listSecretVersionIds(source.getSecretArn(), REGION);
|
||||
|
||||
rotate(source, "{\"HmacSecretValue\":\"whsec_MDEyMzQ1Njc4OWFiY2RlZg==\"}");
|
||||
|
||||
assertEquals(before, secrets.listSecretVersionIds(source.getSecretArn(), REGION));
|
||||
}
|
||||
|
||||
@Test
|
||||
void theSourceKeepsItsModifiedTimeUrlAndSecret() {
|
||||
EventSourceV2 source = source("hook", STATIC_AUTH);
|
||||
String url = service.webhookUrl(source);
|
||||
clock.advance(Duration.ofMinutes(5));
|
||||
|
||||
rotate(source, "{\"StaticTokenSecretValue\":\"second-token\"}");
|
||||
|
||||
EventSourceV2 described = service.describeEventSource(json("{\"EventSourceArn\":\"" + source.getArn() + "\"}"),
|
||||
REGION);
|
||||
assertEquals(NOW, described.getLastModifiedTime());
|
||||
assertEquals(url, service.webhookUrl(described));
|
||||
assertEquals(source.getSecretArn(), described.getSecretArn());
|
||||
}
|
||||
|
||||
@Test
|
||||
void anUpdateKeepsTheRememberedTokens() {
|
||||
EventSourceV2 source = source("hook", STATIC_AUTH);
|
||||
rotate(source, "{\"StaticTokenSecretValue\":\"second-token\"}");
|
||||
|
||||
EventSourceV2 updated = service.updateEventSource(json("{\"EventSourceArn\":\"" + source.getArn()
|
||||
+ "\",\"Description\":\"d\"}"), REGION);
|
||||
|
||||
assertEquals(1, updated.getRotationRequests().size());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aSourceStoredWithoutTheTokenMapReadsAsEmpty() throws Exception {
|
||||
EventSourceV2 older = MAPPER.readValue("{\"name\":\"hook\",\"unknownMember\":1}", EventSourceV2.class);
|
||||
assertEquals(Map.of(), older.getRotationRequests());
|
||||
|
||||
older.setRotationRequests(null);
|
||||
assertEquals(Map.of(), older.getRotationRequests());
|
||||
}
|
||||
|
||||
// ──────────────────────────── Union and member rules ────────────────────────────
|
||||
|
||||
@Test
|
||||
void anyCountOfMembersButOneIsRefused() {
|
||||
EventSourceV2 source = source("hook", STATIC_AUTH);
|
||||
|
||||
assertRefused(source, "{}", UNION_MESSAGE);
|
||||
assertRefused(source, "{\"StaticTokenSecretValue\":null}", UNION_MESSAGE);
|
||||
assertRefused(source, "{\"Bogus\":\"secret-value\"}", UNION_MESSAGE);
|
||||
assertRefused(source, "{\"StaticTokenSecretValue\":\"second-token\",\"BasicHttpPassword\":\"second-pw\"}",
|
||||
UNION_MESSAGE);
|
||||
assertEquals("original-token", valueOf(source, "AWSCURRENT"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void theMemberMustBeTheOneOfTheAuthenticationType() {
|
||||
EventSourceV2 staticSource = source("tok", STATIC_AUTH);
|
||||
EventSourceV2 basicSource = source("bas", BASIC_AUTH);
|
||||
EventSourceV2 hmacSource = source("hmc", HMAC_AUTH);
|
||||
|
||||
assertRefused(staticSource, "{\"BasicHttpPassword\":\"second-pw\"}",
|
||||
"Credential must set StaticTokenSecretValue, because the authentication type of this EventSource is "
|
||||
+ "StaticTokenAuthConfiguration");
|
||||
assertRefused(basicSource, "{\"HmacSecretValue\":\"0123456789abcdef\"}",
|
||||
"Credential must set BasicHttpPassword, because the authentication type of this EventSource is "
|
||||
+ "BasicHttpAuthConfiguration");
|
||||
assertRefused(hmacSource, "{\"StaticTokenSecretValue\":\"second-token\"}",
|
||||
"Credential must set HmacSecretValue, because the authentication type of this EventSource is "
|
||||
+ "HmacAuthConfiguration");
|
||||
}
|
||||
|
||||
// ──────────────────────────── Order of checks ────────────────────────────
|
||||
|
||||
@Test
|
||||
void constraintsComeBeforeTheRegionCheck() {
|
||||
AwsException e = assertThrows(AwsException.class, () -> service.rotateWebhookCredentials(json(
|
||||
"{\"EventSourceArn\":\"arn:aws:events:eu-west-1:000000000000:event-sourcev2/webhook/x/"
|
||||
+ "abcdefghijklmnopqrstuvwxy\",\"ClientToken\":\"a b\"}"), REGION));
|
||||
assertEquals("InvalidInputException", e.getErrorCode());
|
||||
assertTrue(e.getMessage().startsWith("1 validation error detected: Value 'a b' at 'clientToken'"),
|
||||
e.getMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
void theRegionCheckComesBeforeTheAccountCheck() {
|
||||
assertAnswer(400, "InvalidInputException", "The region or partition in EventSourceArn does not match this "
|
||||
+ "endpoint", "{\"EventSourceArn\":\"arn:aws:events:eu-west-1:111111111111:event-sourcev2/webhook/x/"
|
||||
+ "abcdefghijklmnopqrstuvwxy\",\"ClientToken\":\"t\"}");
|
||||
}
|
||||
|
||||
@Test
|
||||
void theAccountCheckComesBeforeTheClientTokenCheck() {
|
||||
assertAnswer(403, "AccessDeniedException", "Access denied.",
|
||||
"{\"EventSourceArn\":\"arn:aws:events:us-east-1:111111111111:event-sourcev2/webhook/x/"
|
||||
+ "abcdefghijklmnopqrstuvwxy\",\"Credential\":{}}");
|
||||
}
|
||||
|
||||
@Test
|
||||
void theClientTokenCheckComesBeforeTheUnionCount() {
|
||||
assertAnswer(400, "InvalidInputException", "ClientToken is required",
|
||||
"{\"EventSourceArn\":\"" + MISSING_SOURCE + "\",\"Credential\":{}}");
|
||||
assertAnswer(400, "InvalidInputException", "ClientToken is required",
|
||||
"{\"EventSourceArn\":\"" + MISSING_SOURCE + "\",\"Credential\":{\"HmacSecretValue\":\"x12345\"}}");
|
||||
}
|
||||
|
||||
@Test
|
||||
void theUnionCountComesBeforeTheSourceLookup() {
|
||||
assertAnswer(400, "InvalidInputException", UNION_MESSAGE,
|
||||
"{\"EventSourceArn\":\"" + MISSING_SOURCE + "\",\"ClientToken\":\"t\",\"Credential\":{}}");
|
||||
}
|
||||
|
||||
@Test
|
||||
void theSourceLookupComesBeforeTheMemberCheck() {
|
||||
assertAnswer(404, "ResourceNotFoundException", "EventSource not found: " + MISSING_SOURCE,
|
||||
"{\"EventSourceArn\":\"" + MISSING_SOURCE + "\",\"ClientToken\":\"t\","
|
||||
+ "\"Credential\":{\"HmacSecretValue\":\"0123456789abcdef\"}}");
|
||||
}
|
||||
|
||||
@Test
|
||||
void theMemberCheckComesBeforeTheValueRules() {
|
||||
EventSourceV2 source = source("hook", HMAC_AUTH);
|
||||
|
||||
assertRefused(source, "{\"StaticTokenSecretValue\":\"short1\"}", "Credential must set HmacSecretValue, "
|
||||
+ "because the authentication type of this EventSource is HmacAuthConfiguration");
|
||||
}
|
||||
|
||||
@Test
|
||||
void theValueRulesComeBeforeTheClientTokenReplay() {
|
||||
EventSourceV2 source = source("hook", HMAC_AUTH);
|
||||
rotate(source, "t-replay", "{\"HmacSecretValue\":\"aaaaaaaaaaaaaaaa\"}");
|
||||
|
||||
AwsException e = assertThrows(AwsException.class,
|
||||
() -> rotate(source, "t-replay", "{\"HmacSecretValue\":\"aaaaaaa\"}"));
|
||||
|
||||
assertEquals("InvalidInputException", e.getErrorCode());
|
||||
assertEquals(HMAC_RANGE_MESSAGE, e.getMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aRefusedRotationChangesNothing() {
|
||||
EventSourceV2 source = source("hook", HMAC_AUTH);
|
||||
Map<String, List<String>> before = secrets.listSecretVersionIds(source.getSecretArn(), REGION);
|
||||
|
||||
assertRefused(source, "{\"HmacSecretValue\":\"short\"}", "1 validation error detected: Value at "
|
||||
+ "'credential.hmacSecretValue' failed to satisfy constraint: Member must have length greater than "
|
||||
+ "or equal to 6");
|
||||
assertRefused(source, "{\"HmacSecretValue\":\"aaaaaaa\"}", HMAC_RANGE_MESSAGE);
|
||||
|
||||
assertEquals(before, secrets.listSecretVersionIds(source.getSecretArn(), REGION));
|
||||
assertEquals(0, service.describeEventSource(json("{\"EventSourceArn\":\"" + source.getArn() + "\"}"), REGION)
|
||||
.getRotationRequests().size());
|
||||
}
|
||||
|
||||
// ──────────────────────────── ClientToken ────────────────────────────
|
||||
|
||||
@Test
|
||||
void aReplayWithTheSameRequestAnswersTheArnAndWritesNothing() {
|
||||
EventSourceV2 source = source("hook", STATIC_AUTH);
|
||||
rotate(source, "t-one", "{\"StaticTokenSecretValue\":\"second-token\"}");
|
||||
Map<String, List<String>> before = secrets.listSecretVersionIds(source.getSecretArn(), REGION);
|
||||
|
||||
String again = rotate(source, "t-one", "{\"StaticTokenSecretValue\":\"second-token\"}");
|
||||
|
||||
assertEquals(source.getSecretArn(), again);
|
||||
assertEquals(before, secrets.listSecretVersionIds(source.getSecretArn(), REGION));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aReplayStaysAReplayAfterLaterRotations() {
|
||||
EventSourceV2 source = source("hook", STATIC_AUTH);
|
||||
rotate(source, "t-one", "{\"StaticTokenSecretValue\":\"second-token\"}");
|
||||
rotate(source, "t-two", "{\"StaticTokenSecretValue\":\"third-token\"}");
|
||||
|
||||
rotate(source, "t-one", "{\"StaticTokenSecretValue\":\"second-token\"}");
|
||||
|
||||
assertEquals("third-token", valueOf(source, "AWSCURRENT"));
|
||||
assertEquals("second-token", valueOf(source, "AWSPREVIOUS"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aReplayOfAGeneratedRotationKeepsTheGeneratedValue() {
|
||||
EventSourceV2 source = source("hook", STATIC_AUTH);
|
||||
rotate(source, "t-gen", null);
|
||||
String generated = valueOf(source, "AWSCURRENT");
|
||||
Map<String, List<String>> before = secrets.listSecretVersionIds(source.getSecretArn(), REGION);
|
||||
|
||||
rotate(source, "t-gen", null);
|
||||
|
||||
assertEquals(generated, valueOf(source, "AWSCURRENT"));
|
||||
assertEquals(before, secrets.listSecretVersionIds(source.getSecretArn(), REGION));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aReplayWithAnotherRequestIsAConflict() {
|
||||
EventSourceV2 source = source("hook", STATIC_AUTH);
|
||||
rotate(source, "t-one", "{\"StaticTokenSecretValue\":\"second-token\"}");
|
||||
rotate(source, "t-gen", null);
|
||||
|
||||
for (String credential : new String[] {"{\"StaticTokenSecretValue\":\"other-token\"}", null}) {
|
||||
AwsException e = assertThrows(AwsException.class, () -> rotate(source, "t-one", credential));
|
||||
assertEquals("IdempotentParameterMismatchException", e.getErrorCode());
|
||||
assertEquals(409, e.getHttpStatus());
|
||||
assertEquals("ClientToken was used by a previous request with different parameters", e.getMessage());
|
||||
}
|
||||
AwsException e = assertThrows(AwsException.class,
|
||||
() -> rotate(source, "t-gen", "{\"StaticTokenSecretValue\":\"other-token\"}"));
|
||||
assertEquals("IdempotentParameterMismatchException", e.getErrorCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aTokenOfAnotherSourceRotatesThisOne() {
|
||||
EventSourceV2 one = source("one", STATIC_AUTH);
|
||||
EventSourceV2 two = source("two", STATIC_AUTH);
|
||||
rotate(one, "t-shared", "{\"StaticTokenSecretValue\":\"second-token\"}");
|
||||
|
||||
rotate(two, "t-shared", "{\"StaticTokenSecretValue\":\"second-token\"}");
|
||||
|
||||
assertEquals("second-token", valueOf(two, "AWSCURRENT"));
|
||||
assertEquals("original-token", valueOf(two, "AWSPREVIOUS"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aRotationToTheCurrentValueStillRemembersItsToken() {
|
||||
EventSourceV2 source = source("hook", STATIC_AUTH);
|
||||
rotate(source, "t-same", "{\"StaticTokenSecretValue\":\"original-token\"}");
|
||||
|
||||
AwsException e = assertThrows(AwsException.class,
|
||||
() -> rotate(source, "t-same", "{\"StaticTokenSecretValue\":\"other-token\"}"));
|
||||
|
||||
assertEquals("IdempotentParameterMismatchException", e.getErrorCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aTokenIsRememberedForJustUnderEightHours() {
|
||||
EventSourceV2 source = source("hook", STATIC_AUTH);
|
||||
rotate(source, "t-1", "{\"StaticTokenSecretValue\":\"second-token\"}");
|
||||
clock.advance(Duration.ofHours(8).minusSeconds(1));
|
||||
|
||||
assertEquals(source.getSecretArn(), rotate(source, "t-1", "{\"StaticTokenSecretValue\":\"second-token\"}"));
|
||||
AwsException e = assertThrows(AwsException.class,
|
||||
() -> rotate(source, "t-1", "{\"StaticTokenSecretValue\":\"other-token\"}"));
|
||||
|
||||
assertEquals("IdempotentParameterMismatchException", e.getErrorCode());
|
||||
assertEquals("second-token", valueOf(source, "AWSCURRENT"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aTokenIsForgottenAtExactlyEightHoursAndTheSameRequestRotatesAgain() {
|
||||
EventSourceV2 source = source("hook", STATIC_AUTH);
|
||||
rotate(source, "t-1", null);
|
||||
String first = versionOf(source, "AWSCURRENT");
|
||||
clock.advance(Duration.ofHours(8));
|
||||
|
||||
rotate(source, "t-1", null);
|
||||
|
||||
assertNotEquals(first, versionOf(source, "AWSCURRENT"));
|
||||
assertEquals(first, versionOf(source, "AWSPREVIOUS"));
|
||||
assertEquals(clock.instant(), storedRotations(source).get("t-1").rotatedAt());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aForgottenTokenRotatesAgainWithADifferentRequest() {
|
||||
EventSourceV2 source = source("hook", STATIC_AUTH);
|
||||
rotate(source, "t-1", "{\"StaticTokenSecretValue\":\"second-token\"}");
|
||||
clock.advance(Duration.ofHours(8));
|
||||
|
||||
rotate(source, "t-1", "{\"StaticTokenSecretValue\":\"other-token\"}");
|
||||
|
||||
assertEquals("other-token", valueOf(source, "AWSCURRENT"));
|
||||
assertEquals("second-token", valueOf(source, "AWSPREVIOUS"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aRotationDropsTheTokensItForgot() {
|
||||
EventSourceV2 source = source("hook", STATIC_AUTH);
|
||||
rotate(source, "t-old", "{\"StaticTokenSecretValue\":\"second-token\"}");
|
||||
clock.advance(Duration.ofHours(4));
|
||||
rotate(source, "t-mid", "{\"StaticTokenSecretValue\":\"third-token\"}");
|
||||
clock.advance(Duration.ofHours(4));
|
||||
|
||||
rotate(source, "t-new", "{\"StaticTokenSecretValue\":\"fourth-token\"}");
|
||||
|
||||
assertEquals(Set.of("t-mid", "t-new"), storedRotations(source).keySet());
|
||||
}
|
||||
|
||||
// ──────────────────────────── Secret state ────────────────────────────
|
||||
|
||||
private static final String SECRET_GONE_MESSAGE =
|
||||
"The secret of the EventSource is scheduled for deletion or has been deleted";
|
||||
|
||||
@Test
|
||||
void aSecretScheduledForDeletionAnswersInvalidState() {
|
||||
EventSourceV2 source = source("hook", STATIC_AUTH);
|
||||
secrets.deleteSecret(source.getSecretArn(), null, false, REGION);
|
||||
|
||||
AwsException e = assertThrows(AwsException.class,
|
||||
() -> rotate(source, "{\"StaticTokenSecretValue\":\"second-token\"}"));
|
||||
|
||||
assertEquals("InvalidStateException", e.getErrorCode());
|
||||
assertEquals(409, e.getHttpStatus());
|
||||
assertEquals(SECRET_GONE_MESSAGE, e.getMessage());
|
||||
assertEquals(0, storedRotations(source).size());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aDeletedSecretAnswersInvalidState() {
|
||||
EventSourceV2 source = source("hook", STATIC_AUTH);
|
||||
secrets.deleteSecret(source.getSecretArn(), null, true, REGION);
|
||||
|
||||
AwsException e = assertThrows(AwsException.class,
|
||||
() -> rotate(source, "{\"StaticTokenSecretValue\":\"second-token\"}"));
|
||||
|
||||
assertEquals("InvalidStateException", e.getErrorCode());
|
||||
assertEquals(409, e.getHttpStatus());
|
||||
assertEquals(SECRET_GONE_MESSAGE, e.getMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aRememberedTokenStillReplaysWhenTheSecretIsScheduledForDeletion() {
|
||||
EventSourceV2 source = source("hook", STATIC_AUTH);
|
||||
rotate(source, "t-1", "{\"StaticTokenSecretValue\":\"second-token\"}");
|
||||
secrets.deleteSecret(source.getSecretArn(), null, false, REGION);
|
||||
|
||||
assertEquals(source.getSecretArn(), rotate(source, "t-1", "{\"StaticTokenSecretValue\":\"second-token\"}"));
|
||||
}
|
||||
|
||||
// ──────────────────────────── Credentials the rotation replaced ────────────────────────────
|
||||
|
||||
@Test
|
||||
void aReplacedStaticTokenIsAcceptedUntilFifteenMinutesAfterTheRotation() {
|
||||
Target target = target(source("hook", STATIC_AUTH));
|
||||
assertEquals(EventBridgeV2Webhooks.OK, post(target, Map.of("x-tok", "original-token"), "{}"));
|
||||
|
||||
rotate(target.source(), "{\"StaticTokenSecretValue\":\"second-token\"}");
|
||||
stampCurrentVersion(target.source());
|
||||
|
||||
assertEquals(EventBridgeV2Webhooks.OK, post(target, Map.of("x-tok", "second-token"), "{}"));
|
||||
assertEquals(EventBridgeV2Webhooks.OK, post(target, Map.of("x-tok", "original-token"), "{}"));
|
||||
clock.advance(Duration.ofMinutes(15).minusSeconds(1));
|
||||
assertEquals(EventBridgeV2Webhooks.OK, post(target, Map.of("x-tok", "original-token"), "{}"));
|
||||
clock.advance(Duration.ofSeconds(1));
|
||||
assertEquals(EventBridgeV2Webhooks.FORBIDDEN, post(target, Map.of("x-tok", "original-token"), "{}"));
|
||||
assertEquals(EventBridgeV2Webhooks.OK, post(target, Map.of("x-tok", "second-token"), "{}"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aReplacedBasicCredentialIsAcceptedUntilFifteenMinutesAfterTheRotation() {
|
||||
Target target = target(source("hook", BASIC_AUTH));
|
||||
rotate(target.source(), "{\"BasicHttpPassword\":\"second-pw\"}");
|
||||
stampCurrentVersion(target.source());
|
||||
|
||||
assertEquals(EventBridgeV2Webhooks.OK, post(target, Map.of("authorization", basic("alice", "second-pw")), "{}"));
|
||||
assertEquals(EventBridgeV2Webhooks.OK,
|
||||
post(target, Map.of("authorization", basic("alice", "original-pw")), "{}"));
|
||||
clock.advance(Duration.ofMinutes(15).minusSeconds(1));
|
||||
assertEquals(EventBridgeV2Webhooks.OK,
|
||||
post(target, Map.of("authorization", basic("alice", "original-pw")), "{}"));
|
||||
clock.advance(Duration.ofSeconds(1));
|
||||
assertEquals(EventBridgeV2Webhooks.FORBIDDEN,
|
||||
post(target, Map.of("authorization", basic("alice", "original-pw")), "{}"));
|
||||
assertEquals(EventBridgeV2Webhooks.OK, post(target, Map.of("authorization", basic("alice", "second-pw")), "{}"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aReplacedHmacSecretIsAcceptedUntilFifteenMinutesAfterTheRotation() throws Exception {
|
||||
Target target = target(source("hook", HMAC_AUTH));
|
||||
rotate(target.source(), "{\"HmacSecretValue\":\"fedcba9876543210\"}");
|
||||
stampCurrentVersion(target.source());
|
||||
String body = "{\"a\":1}";
|
||||
Map<String, String> replaced = Map.of("x-sig", sign("0123456789abcdef", body));
|
||||
Map<String, String> current = Map.of("x-sig", sign("fedcba9876543210", body));
|
||||
|
||||
assertEquals(EventBridgeV2Webhooks.OK, post(target, current, body));
|
||||
assertEquals(EventBridgeV2Webhooks.OK, post(target, replaced, body));
|
||||
clock.advance(Duration.ofMinutes(15).minusSeconds(1));
|
||||
assertEquals(EventBridgeV2Webhooks.OK, post(target, replaced, body));
|
||||
clock.advance(Duration.ofSeconds(1));
|
||||
assertEquals(EventBridgeV2Webhooks.FORBIDDEN, post(target, replaced, body));
|
||||
assertEquals(EventBridgeV2Webhooks.OK, post(target, current, body));
|
||||
}
|
||||
|
||||
@Test
|
||||
void onlyTheCredentialTheLastRotationReplacedIsAccepted() {
|
||||
Target target = target(source("hook", STATIC_AUTH));
|
||||
rotate(target.source(), "{\"StaticTokenSecretValue\":\"second-token\"}");
|
||||
rotate(target.source(), "{\"StaticTokenSecretValue\":\"third-token\"}");
|
||||
stampCurrentVersion(target.source());
|
||||
|
||||
assertEquals(EventBridgeV2Webhooks.OK, post(target, Map.of("x-tok", "third-token"), "{}"));
|
||||
assertEquals(EventBridgeV2Webhooks.OK, post(target, Map.of("x-tok", "second-token"), "{}"));
|
||||
assertEquals(EventBridgeV2Webhooks.FORBIDDEN, post(target, Map.of("x-tok", "original-token"), "{}"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aSourceThatWasNeverRotatedAcceptsNothingButItsCurrentCredential() {
|
||||
Target target = target(source("hook", STATIC_AUTH));
|
||||
|
||||
assertEquals(EventBridgeV2Webhooks.OK, post(target, Map.of("x-tok", "original-token"), "{}"));
|
||||
assertEquals(EventBridgeV2Webhooks.FORBIDDEN, post(target, Map.of("x-tok", "other-token"), "{}"));
|
||||
assertEquals(EventBridgeV2Webhooks.FORBIDDEN, post(target, Map.of(), "{}"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aRotationToTheCurrentValueDoesNotStartAGracePeriodForAnythingElse() {
|
||||
Target target = target(source("hook", STATIC_AUTH));
|
||||
rotate(target.source(), "{\"StaticTokenSecretValue\":\"original-token\"}");
|
||||
|
||||
assertEquals(EventBridgeV2Webhooks.FORBIDDEN, post(target, Map.of("x-tok", "other-token"), "{}"));
|
||||
}
|
||||
|
||||
// ──────────────────────────── Helpers ────────────────────────────
|
||||
|
||||
private Map<String, RotationRequest> storedRotations(EventSourceV2 source) {
|
||||
return service.describeEventSource(json("{\"EventSourceArn\":\"" + source.getArn() + "\"}"), REGION)
|
||||
.getRotationRequests();
|
||||
}
|
||||
|
||||
private record Target(EventSourceV2 source, String hostId, String path) {
|
||||
}
|
||||
|
||||
private Target target(EventSourceV2 source) {
|
||||
return new Target(source, source.getWebhookHostId(), URI.create(service.webhookUrl(source)).getPath());
|
||||
}
|
||||
|
||||
private Answer post(Target target, Map<String, String> headers, String body) {
|
||||
return webhooks.receive(new Request("POST", target.hostId(), target.path(), headers,
|
||||
body.getBytes(StandardCharsets.UTF_8), false));
|
||||
}
|
||||
|
||||
/** The secret stamps a new version with the real time, so the test sets the rotation time on the test clock. */
|
||||
private void stampCurrentVersion(EventSourceV2 source) {
|
||||
secrets.getSecretValue(source.getSecretArn(), null, "AWSCURRENT", REGION).setCreatedDate(clock.instant());
|
||||
}
|
||||
|
||||
private static String basic(String username, String password) {
|
||||
return "Basic " + Base64.getEncoder().encodeToString((username + ":" + password).getBytes(StandardCharsets.UTF_8));
|
||||
}
|
||||
|
||||
private static String sign(String secret, String body) throws Exception {
|
||||
Mac mac = Mac.getInstance("HmacSHA256");
|
||||
mac.init(new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), "HmacSHA256"));
|
||||
return HexFormat.of().formatHex(mac.doFinal(body.getBytes(StandardCharsets.UTF_8)));
|
||||
}
|
||||
|
||||
private EventSourceV2 source(String name, String auth) {
|
||||
return service.createEventSource(json("{\"ClientToken\":\"" + name + "-token\",\"Name\":\"" + name
|
||||
+ "\",\"EventBusArn\":\"" + bus + "\",\"Configuration\":{\"WebhookEventsConfiguration\":"
|
||||
+ "{\"AuthConfiguration\":" + auth + ",\"RoleArn\":\"" + ROLE + "\"}}}"), REGION);
|
||||
}
|
||||
|
||||
private String rotate(EventSourceV2 source, String credential) {
|
||||
return rotate(source, "token-" + tokens++, credential);
|
||||
}
|
||||
|
||||
private String rotate(EventSourceV2 source, String clientToken, String credential) {
|
||||
return service.rotateWebhookCredentials(json("{\"EventSourceArn\":\"" + source.getArn()
|
||||
+ "\",\"ClientToken\":\"" + clientToken + "\""
|
||||
+ (credential == null ? "" : ",\"Credential\":" + credential) + "}"), REGION);
|
||||
}
|
||||
|
||||
private void assertRefused(EventSourceV2 source, String credential, String message) {
|
||||
AwsException e = assertThrows(AwsException.class, () -> rotate(source, credential));
|
||||
assertEquals("InvalidInputException", e.getErrorCode());
|
||||
assertEquals(400, e.getHttpStatus());
|
||||
assertEquals(message, e.getMessage());
|
||||
}
|
||||
|
||||
private void assertAnswer(int status, String code, String message, String request) {
|
||||
AwsException e = assertThrows(AwsException.class, () -> service.rotateWebhookCredentials(json(request), REGION));
|
||||
assertEquals(status, e.getHttpStatus());
|
||||
assertEquals(code, e.getErrorCode());
|
||||
assertEquals(message, e.getMessage());
|
||||
}
|
||||
|
||||
private String valueOf(EventSourceV2 source, String stage) {
|
||||
return secrets.getSecretValue(source.getSecretArn(), null, stage, REGION).getSecretString();
|
||||
}
|
||||
|
||||
private String versionOf(EventSourceV2 source, String stage) {
|
||||
return secrets.getSecretValue(source.getSecretArn(), null, stage, REGION).getVersionId();
|
||||
}
|
||||
|
||||
/** The version id of each stage, for the versions that have one. */
|
||||
private Map<String, String> stages(EventSourceV2 source) {
|
||||
Map<String, String> found = new TreeMap<>();
|
||||
secrets.listSecretVersionIds(source.getSecretArn(), REGION)
|
||||
.forEach((versionId, stages) -> stages.forEach(stage -> found.put(stage, versionId)));
|
||||
return found;
|
||||
}
|
||||
|
||||
private static JsonNode json(String json) {
|
||||
try {
|
||||
return MAPPER.readTree(json);
|
||||
} catch (Exception e) {
|
||||
throw new IllegalArgumentException(json, e);
|
||||
}
|
||||
}
|
||||
}
|
||||
+59
@@ -21,9 +21,12 @@ import software.amazon.awssdk.regions.Region;
|
||||
import software.amazon.awssdk.services.eventbridgev2.EventBridgeV2Client;
|
||||
import software.amazon.awssdk.services.eventbridgev2.model.CreateEventSourceResponse;
|
||||
import software.amazon.awssdk.services.eventbridgev2.model.EventSourceConfiguration;
|
||||
import software.amazon.awssdk.services.eventbridgev2.model.InvalidInputException;
|
||||
import software.amazon.awssdk.services.eventbridgev2.model.RotateWebhookCredentialsResponse;
|
||||
import software.amazon.awssdk.services.eventbridgev2.model.TransformerType;
|
||||
import software.amazon.awssdk.services.eventbridgev2.model.WebhookAuthConfiguration;
|
||||
import software.amazon.awssdk.services.eventbridgev2.model.WebhookEventsSourceConfiguration;
|
||||
import software.amazon.awssdk.services.secretsmanager.SecretsManagerClient;
|
||||
import software.amazon.awssdk.services.sqs.SqsClient;
|
||||
import software.amazon.awssdk.services.sqs.model.Message;
|
||||
import software.amazon.awssdk.services.sqs.model.QueueAttributeName;
|
||||
@@ -49,6 +52,7 @@ import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
import static org.hamcrest.Matchers.matchesPattern;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
/** A POST to the URL of a webhook event source becomes an event on its bus, read here from the queues of subscribers. */
|
||||
@@ -255,6 +259,53 @@ class EventBridgeV2WebhookIntegrationTest {
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void rotatedCredentialsReplaceTheSecretAndTheReplacedOnesStayValidOnlyForTheLastRotation() {
|
||||
String suffix = suffix();
|
||||
try (EventBridgeV2Client events = events(); SecretsManagerClient secrets = secrets()) {
|
||||
String bus = events.createEventBus(request -> request.name("v2-rot-" + suffix)).eventBusArn();
|
||||
CreateEventSourceResponse created = events.createEventSource(request -> request.name("rot-" + suffix)
|
||||
.eventBusArn(bus).configuration(EventSourceConfiguration.fromWebhookEventsConfiguration(
|
||||
configuration -> configuration.roleArn(ROLE)
|
||||
.authConfiguration(staticToken("X-Token", "original-token")))));
|
||||
URI url = URI.create(created.eventSourceDetails().webhookDetails().webhookUrl());
|
||||
Endpoint endpoint = new Endpoint(created.eventSourceArn(), url.getAuthority(), url.getPath());
|
||||
String secretArn = created.eventSourceDetails().webhookDetails().secretArn();
|
||||
|
||||
RotateWebhookCredentialsResponse supplied = events.rotateWebhookCredentials(request -> request
|
||||
.eventSourceArn(endpoint.arn()).clientToken("rotation-" + suffix)
|
||||
.credential(credential -> credential.staticTokenSecretValue("second-token")));
|
||||
|
||||
assertEquals(secretArn, supplied.secretArn());
|
||||
assertEquals("second-token", secretValue(secrets, secretArn, null));
|
||||
assertEquals("original-token", secretValue(secrets, secretArn, "AWSPREVIOUS"));
|
||||
expect(post(endpoint, "{}", "X-Token", "second-token"), 200, "OK");
|
||||
expect(post(endpoint, "{}", "X-Token", "original-token"), 200, "OK");
|
||||
|
||||
RotateWebhookCredentialsResponse replay = events.rotateWebhookCredentials(request -> request
|
||||
.eventSourceArn(endpoint.arn()).clientToken("rotation-" + suffix)
|
||||
.credential(credential -> credential.staticTokenSecretValue("second-token")));
|
||||
assertEquals(secretArn, replay.secretArn());
|
||||
assertEquals("original-token", secretValue(secrets, secretArn, "AWSPREVIOUS"));
|
||||
|
||||
events.rotateWebhookCredentials(request -> request.eventSourceArn(endpoint.arn()));
|
||||
String generated = secretValue(secrets, secretArn, null);
|
||||
assertEquals(44, generated.length());
|
||||
expect(post(endpoint, "{}", "X-Token", generated), 200, "OK");
|
||||
expect(post(endpoint, "{}", "X-Token", "second-token"), 200, "OK");
|
||||
expect(post(endpoint, "{}", "X-Token", "original-token"), 403, "Forbidden");
|
||||
|
||||
InvalidInputException refused = assertThrows(InvalidInputException.class,
|
||||
() -> events.rotateWebhookCredentials(request -> request.eventSourceArn(endpoint.arn())
|
||||
.credential(credential -> credential.basicHttpPassword("second-pw"))));
|
||||
assertEquals("Credential must set StaticTokenSecretValue, because the authentication type of this "
|
||||
+ "EventSource is StaticTokenAuthConfiguration", refused.awsErrorDetails().errorMessage());
|
||||
|
||||
events.deleteEventSource(request -> request.eventSourceArn(endpoint.arn()));
|
||||
events.deleteEventBus(request -> request.eventBusArn(bus));
|
||||
}
|
||||
}
|
||||
|
||||
// ──────────────────────────── Fixtures ────────────────────────────
|
||||
|
||||
private record Fixture(String bus, String metadataQueue, String rawQueue, String metadataSubscriber,
|
||||
@@ -416,6 +467,14 @@ class EventBridgeV2WebhookIntegrationTest {
|
||||
return AwsTestClients.create(EventBridgeV2Client.builder(), "000000000000", Region.US_EAST_1);
|
||||
}
|
||||
|
||||
private static SecretsManagerClient secrets() {
|
||||
return AwsTestClients.create(SecretsManagerClient.builder(), "000000000000", Region.US_EAST_1);
|
||||
}
|
||||
|
||||
private static String secretValue(SecretsManagerClient secrets, String secretArn, String stage) {
|
||||
return secrets.getSecretValue(request -> request.secretId(secretArn).versionStage(stage)).secretString();
|
||||
}
|
||||
|
||||
private static SqsClient sqs() {
|
||||
return AwsTestClients.create(SqsClient.builder(), "000000000000", Region.US_EAST_1);
|
||||
}
|
||||
|
||||
@@ -15,7 +15,7 @@ MODEL = Path("eventbridgev2/2025-05-15")
|
||||
OUTPUT = request_shapes.REPO_ROOT / "src/main/resources/aws/eventbridgev2-request-shapes.json"
|
||||
|
||||
OPERATIONS = ("CreateEventSource", "DeleteEventSource", "DescribeEventSource", "ListEventSources",
|
||||
"UpdateEventSource")
|
||||
"RotateWebhookCredentials", "UpdateEventSource")
|
||||
|
||||
# The order AWS lists the values of a violated enum in. It follows no rule, so each is measured.
|
||||
ENUM_ORDER = {
|
||||
|
||||
@@ -596,7 +596,8 @@ def test_eventbridgev2_shapes_keep_the_measured_orders_and_the_sensitive_mark():
|
||||
shapes = doc["shapes"]
|
||||
|
||||
assert sorted(doc["operations"]) == ["CreateEventSource", "DeleteEventSource", "DescribeEventSource",
|
||||
"ListEventSources", "UpdateEventSource"]
|
||||
"ListEventSources", "RotateWebhookCredentials",
|
||||
"UpdateEventSource"]
|
||||
assert shapes["WebhookSecretValue"] == {"type": "string", "min": 6, "max": 512, "sensitive": True}
|
||||
assert shapes["WebhookMetadataHttpHeaderList"]["max"] == 20
|
||||
assert shapes["TagMap"]["max"] == 200
|
||||
@@ -619,6 +620,10 @@ def test_eventbridgev2_shapes_list_members_in_the_order_aws_walks_them():
|
||||
assert list(shapes["UpdateEventSourceRequest"]["members"]) == ["Configuration", "EventSourceArn", "Description"]
|
||||
assert list(shapes["ListEventSourcesRequest"]["members"]) == [
|
||||
"MaxResults", "NextToken", "NamePrefix", "EventBusArn"]
|
||||
assert list(shapes["RotateWebhookCredentialsRequest"]["members"]) == [
|
||||
"Credential", "EventSourceArn", "ClientToken"]
|
||||
assert list(shapes["WebhookCredential"]["members"]) == [
|
||||
"StaticTokenSecretValue", "BasicHttpPassword", "HmacSecretValue"]
|
||||
assert list(shapes["WebhookEventsSourceConfiguration"]["members"]) == [
|
||||
"DeduplicationConfiguration", "KmsKeyIdentifier", "RoleArn", "LogConfiguration", "MetadataHttpHeaders",
|
||||
"AuthConfiguration"]
|
||||
|
||||
Reference in new issue
Block a user