feat(signer): serve the Signer control plane for profiles, permissions and job records (#7680)

Signer was the last control plane Floci's CloudFormation provisioner stubbed:
SignerCfnProvisioner recorded only the identifiers a template handed it, with
a comment saying Floci has no Signer API. This serves the API, so an SDK, the
CLI or a stack sees the profile it actually created.

Cancellation keeps the profile, as AWS does: it stays readable through
GetSigningProfile with the same ARN and version and the status Canceled, it
stops accepting jobs, and ListSigningProfiles hides it unless includeCanceled
is set or statuses names Canceled. A PutSigningProfile on the same name brings
it back as a new active version.

A signing job fails by default, and says why. Nothing on this machine signs the
artifact, so a succeeded job would advertise a signedObject key that does not
exist and every download of it would fail; the job instead completes as Failed
with a statusReason naming the object that was not written, and RevokeSignature
refuses it because there is no signature to revoke. Metadata-only callers can
set floci.services.signer.mock-signing-jobs=true, which records jobs as
succeeded and is documented as a mock rather than as AWS behaviour.

Signer routes collide with S3's path-style ones, so a request signed for the
signer scope is rewritten onto an internal prefix before matching. That rewrite
used to happen before IAM resolved the action from the path, which left every
Signer call unchecked; IamActionRegistry now strips the internal prefix the
signing service owns, and SignerIamEnforcementIntegrationTest proves a key with
no policy is refused while one with signer:* is allowed.

Co-authored-by: David Guardiola <davidguardiola@gmail.com>
This commit is contained in:
dgl-aiandDavid Guardiola authored and GitHub committed 2026-11-09 09:08:00 -04:00
1 parent a65def00a4
commit 13640785a9
34 files changed
+3804 -38

No files matched your search

@@ -52,7 +52,7 @@ class PartitionCrossServiceSmokeIntegrationTest {
"lambdamicrovms", "lambdaweb", "memorydb", "msk", "mwaa", "networkfirewall", "oam", "opensearch", "organizations",
"paymentcryptography", "pipes", "quicksight", "ram", "rds", "redshift", "redshiftserverless",
"resourceexplorer2", "resourcegroups", "route53resolver",
"s3tables", "s3vectors", "sagemaker", "scheduler", "secretsmanager", "servicequotas", "ses", "sns", "sqs",
"s3tables", "s3vectors", "sagemaker", "scheduler", "secretsmanager", "servicequotas", "ses", "signer", "sns", "sqs",
"stepfunctions", "timestreaminfluxdb", "transfer", "verifiedpermissions", "wafv2");
private static final String JSON_1_0 = "application/x-amz-json-1.0";
@@ -1075,6 +1075,23 @@ class PartitionCrossServiceSmokeIntegrationTest {
PartitionMatrix.assertArnIn(partitionCase, arn);
}
@ParameterizedTest
@MethodSource(PartitionMatrix.NON_COMMERCIAL_CASES)
void signerProfileArn(PartitionCase partitionCase) {
String region = offered(partitionCase, "signer");
String profileName = "Smoke" + Long.toString(System.nanoTime(), 36);
signed(region, "signer")
.contentType(JSON)
.body("{\"platformId\":\"AWSLambda-SHA384-ECDSA\"}")
.when().put("/signing-profiles/" + profileName).then().statusCode(200);
cleanup.register(() -> signed(region, "signer").when()
.delete("/signing-profiles/" + profileName));
String arn = signed(region, "signer").when()
.get("/signing-profiles/" + profileName)
.then().statusCode(200).extract().jsonPath().getString("arn");
PartitionMatrix.assertArnIn(partitionCase, arn);
}
@ParameterizedTest
@MethodSource(PartitionMatrix.NON_COMMERCIAL_CASES)
void networkFirewallRuleGroupArn(PartitionCase partitionCase) {
@@ -172,6 +172,7 @@ import io.floci.aws.services.secretsmanager.SecretsManagerService;
import io.floci.aws.services.ses.SesIdentityService;
import io.floci.aws.services.ses.SesReceiptRuleService;
import io.floci.aws.services.ses.SesService;
import io.floci.aws.services.signer.SignerService;
import io.floci.aws.services.sns.SnsService;
import io.floci.aws.services.sqs.SqsService;
import io.floci.aws.services.ssm.SsmService;
@@ -208,6 +209,7 @@ final class CfnProvisionerFixture {
static final class Builder {
private SignerService signerService;
private S3Service s3Service;
private S3VectorsService s3VectorsService;
private SnsService snsService;
@@ -319,7 +321,9 @@ final class CfnProvisionerFixture {
ensureDynamicReferences();
List<CfnResourceProvisioner> discovered = new ArrayList<>();
discovered.add(new CdkMetadataCfnProvisioner());
discovered.add(new SignerCfnProvisioner());
if (signerService != null) {
discovered.add(new SignerCfnProvisioner(signerService));
}
if (stepFunctionsService != null) {
discovered.add(new StepFunctionsCfnProvisioner(stepFunctionsService, s3Service, objectMapper));
}
@@ -562,6 +566,11 @@ final class CfnProvisionerFixture {
return this;
}
public Builder signer(SignerService v) {
this.signerService = v;
return this;
}
public Builder s3(S3Service v) {
this.s3Service = v;
return this;
@@ -5,6 +5,8 @@ import io.floci.aws.services.lambda.LambdaService;
import io.floci.aws.testing.CfnStackWaits;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.path.xml.XmlPath;
import io.restassured.response.Response;
import io.restassured.specification.RequestSpecification;
import jakarta.inject.Inject;
import org.junit.jupiter.api.Test;
@@ -44,12 +46,22 @@ class CloudFormationLambdaCodeSigningIntegrationTest {
String version = output(stack, "ProfileVersion");
String cscArn = output(stack, "CscArn");
String function = output(stack, "Name");
String profileName = output(stack, "ProfileName");
assertEquals(profileArn, output(stack, "ProfileRef"));
assertThat(output(stack, "ProfileName"), matchesPattern("Profile_[A-Za-z0-9]{12}"));
assertEquals("arn:aws:signer:us-east-1:000000000000:/signing-profiles/" + output(stack, "ProfileName"),
profileArn);
assertThat(version, matchesPattern("[A-Za-z0-9]{10}"));
Response profileFromApi = signerApi()
.when()
.get("/signing-profiles/" + output(stack, "ProfileName"))
.then()
.statusCode(200)
.extract().response();
assertEquals(profileArn, profileFromApi.path("arn"));
assertEquals(version, profileFromApi.path("profileVersion"));
assertEquals("AWSLambda-SHA384-ECDSA", profileFromApi.path("platformId"));
assertEquals(profileArn + "/" + version, output(stack, "ProfileVersionArn"));
assertEquals(cscArn, output(stack, "CscRef"));
assertEquals(cscArn, "arn:aws:lambda:us-east-1:000000000000:code-signing-config:" + output(stack, "CscId"));
@@ -89,6 +101,19 @@ class CloudFormationLambdaCodeSigningIntegrationTest {
.get("/2020-04-22/code-signing-configs/" + cscArn)
.then()
.statusCode(404);
// A stack delete cancels the profile, which AWS keeps visible with the same ARN.
signerApi()
.when()
.get("/signing-profiles/" + profileName)
.then()
.statusCode(200)
.body("status", equalTo("Canceled"));
}
private static RequestSpecification signerApi() {
return given().header("Authorization",
"AWS4-HMAC-SHA256 Credential=000000000000/20260101/us-east-1/signer/aws4_request");
}
private static String template(String functionProperty) {
@@ -9,11 +9,16 @@ import com.fasterxml.jackson.databind.node.ObjectNode;
import io.floci.aws.core.common.AwsException;
import io.floci.aws.services.cloudformation.CloudFormationTemplateEngine;
import io.floci.aws.services.cloudformation.model.StackResource;
import io.floci.aws.services.signer.SignerService;
import io.floci.aws.services.signer.model.SigningProfile;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
@@ -21,16 +26,49 @@ 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.anyMap;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.ArgumentMatchers.nullable;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
class SignerCfnProvisionerTest {
private static final String PROFILE_ARN_PREFIX = "arn:aws:signer:eu-west-1:000000000000:/signing-profiles/";
private static final String STUB_VERSION = "AbCdEfGhIj";
private final SignerCfnProvisioner provisioner = new SignerCfnProvisioner();
private final SignerService signerService = mock(SignerService.class);
private final SignerCfnProvisioner provisioner = new SignerCfnProvisioner(signerService);
private final ObjectMapper mapper = new ObjectMapper();
/**
* A stand-in for the service's own upsert: it answers the identifiers the Signer API would, so the
* assertions here stay about what the provisioner puts on the resource. That a stack-created
* profile is readable through the API is asserted by
* {@code CloudFormationLambdaCodeSigningIntegrationTest}.
*/
@BeforeEach
void stubService() {
when(signerService.putSigningProfile(anyString(), anyString(), nullable(String.class),
nullable(Integer.class), anyMap(), anyString()))
.thenAnswer(inv -> {
String name = inv.getArgument(0);
String platformId = inv.getArgument(1);
String arn = PROFILE_ARN_PREFIX + name;
SigningProfile profile = new SigningProfile();
profile.setProfileName(name);
profile.setPlatformId(platformId);
profile.setProfileVersion(STUB_VERSION);
profile.setArn(arn);
profile.setProfileVersionArn(arn + "/" + STUB_VERSION);
return profile;
});
}
private ProvisionContext ctx(String priorPhysicalId) {
CloudFormationTemplateEngine engine = mock(CloudFormationTemplateEngine.class);
when(engine.resolve(any())).thenAnswer(inv -> {
@@ -287,4 +325,153 @@ class SignerCfnProvisionerTest {
assertEquals("ValidationError", e.getErrorCode(), "'" + name + "'");
}
}
@Test
void provisionCreatesTheProfileThroughTheSignerService() {
ObjectNode props = props("my_profile");
props.putObject("SignatureValidityPeriod").put("Type", "DAYS").put("Value", 30);
props.putArray("Tags").addObject().put("Key", "team").put("Value", "a");
provisioner.provision(profile(), props, ctx(null));
verify(signerService).putSigningProfile("my_profile", "AWSLambda-SHA384-ECDSA",
"DAYS", Integer.valueOf(30), Map.of("team", "a"), "eu-west-1");
}
@Test
void tagsOnlyUpdateReplacesTheTagsInsteadOfMintingAVersion() {
StackResource r = profile();
provisioner.provision(r, props("my_profile"), ctx(null));
ObjectNode tagged = props("my_profile");
tagged.putArray("Tags").addObject().put("Key", "team").put("Value", "a");
provisioner.provision(r, tagged, ctx(r.getPhysicalId()));
verify(signerService).replaceTags("my_profile", Map.of("team", "a"), "eu-west-1");
verify(signerService, times(1)).putSigningProfile(anyString(), anyString(),
any(), any(), anyMap(), anyString());
}
@Test
void deleteCancelsTheProfileThePhysicalIdNames() {
String arn = PROFILE_ARN_PREFIX + "my_profile";
provisioner.delete("AWS::Signer::SigningProfile", arn, "eu-west-1");
verify(signerService).cancelSigningProfile("my_profile", "eu-west-1");
}
@Test
void aStringValidityPeriodReachesTheServiceAsANumber() {
ObjectNode props = props("my_profile");
props.putObject("SignatureValidityPeriod").put("Type", "DAYS").put("Value", "135");
provisioner.provision(profile(), props, ctx(null));
verify(signerService).putSigningProfile(eq("my_profile"), eq("AWSLambda-SHA384-ECDSA"),
eq("DAYS"), eq(Integer.valueOf(135)), anyMap(), eq("eu-west-1"));
}
@Test
void aStackCannotTakeOverASigningProfileItDidNotCreate() {
when(signerService.findSigningProfile("my_profile", "eu-west-1"))
.thenReturn(Optional.of(new SigningProfile()));
AwsException e = assertThrows(AwsException.class,
() -> provisioner.provision(profile(), props("my_profile"), ctx(null)));
assertEquals("ValidationError", e.getErrorCode());
verify(signerService, never()).putSigningProfile(anyString(), anyString(),
any(), any(), anyMap(), anyString());
}
@Test
void aTagsOnlyUpdateAdoptsAProfileThatPredatesTheService() throws Exception {
StackResource r = profile();
r.setPhysicalId(PROFILE_ARN_PREFIX + "legacy");
r.getAttributes().put("Arn", PROFILE_ARN_PREFIX + "legacy");
r.getAttributes().put("ProfileName", "legacy");
r.getAttributes().put("ProfileVersion", "abcdefghij");
r.getAttributes().put("FlociSigningProfileCreateOnly",
"AWSLambda-SHA384-ECDSA|legacy|DAYS|30");
when(signerService.findSigningProfile("legacy", "eu-west-1")).thenReturn(Optional.empty());
ObjectNode props = props("legacy");
props.putObject("SignatureValidityPeriod").put("Type", "DAYS").put("Value", 30);
props.putArray("Tags").addObject().put("Key", "team").put("Value", "a");
provisioner.provision(r, props, ctx(r.getPhysicalId()));
verify(signerService).adoptSigningProfile("legacy", "AWSLambda-SHA384-ECDSA", "abcdefghij",
"DAYS", Integer.valueOf(30), "eu-west-1");
verify(signerService).replaceTags(eq("legacy"), eq(Map.of("team", "a")), eq("eu-west-1"));
}
@Test
void rollbackOfATagsOnlyUpdateRestoresThePreviousTags() {
StackResource r = profile();
provisioner.provision(r, props("my_profile"), ctx(null));
when(signerService.findSigningProfile("my_profile", "eu-west-1"))
.thenReturn(Optional.of(profileWithTags(Map.of("env", "old"))));
ObjectNode tagged = props("my_profile");
tagged.putArray("Tags").addObject().put("Key", "team").put("Value", "a");
provisioner.provision(r, tagged, ctx(r.getPhysicalId()));
assertTrue(provisioner.rollbackUpdate(r));
verify(signerService).replaceTags("my_profile", Map.of("env", "old"), "eu-west-1");
assertFalse(r.getAttributes().containsKey("FlociSigningProfilePriorTags"));
}
@Test
void aTagsUpdateThatChangesNothingLeavesNoSnapshot() {
StackResource r = profile();
provisioner.provision(r, props("my_profile"), ctx(null));
when(signerService.findSigningProfile("my_profile", "eu-west-1"))
.thenReturn(Optional.of(profileWithTags(Map.of("env", "same"))));
ObjectNode tagged = props("my_profile");
tagged.putArray("Tags").addObject().put("Key", "env").put("Value", "same");
provisioner.provision(r, tagged, ctx(r.getPhysicalId()));
assertFalse(r.getAttributes().containsKey("FlociSigningProfilePriorTags"));
verify(signerService, never())
.replaceTags(anyString(), anyMap(), anyString());
}
@Test
void intrinsicTagValuesAreResolvedBeforeTheyReachTheService() throws Exception {
CloudFormationTemplateEngine engine = mock(CloudFormationTemplateEngine.class);
when(engine.resolve(any())).thenAnswer(inv -> {
JsonNode node = inv.getArgument(0);
return node == null || node.isMissingNode() ? null : node.asText();
});
when(engine.resolveNodeOmittingNoValue(any())).thenAnswer(inv -> {
JsonNode node = inv.getArgument(0);
if (node != null && node.isObject() && node.has("Fn::Sub")) {
return mapper.getNodeFactory().textNode("resolved-" + node.path("Fn::Sub").asText());
}
return node;
});
ProvisionContext context =
new ProvisionContext(engine, "eu-west-1", "000000000000", "my-stack", null);
ObjectNode props = props("my_profile");
props.putArray("Tags").addObject()
.put("Key", "team")
.set("Value", mapper.readTree("{\"Fn::Sub\":\"platform\"}"));
provisioner.provision(profile(), props, context);
verify(signerService).putSigningProfile(eq("my_profile"), eq("AWSLambda-SHA384-ECDSA"),
any(), any(), eq(Map.of("team", "resolved-platform")), eq("eu-west-1"));
}
private static SigningProfile profileWithTags(Map<String, String> tags) {
SigningProfile profile = new SigningProfile();
profile.setProfileName("my_profile");
profile.setPlatformId("AWSLambda-SHA384-ECDSA");
profile.setProfileVersion("AbCdEfGhIj");
profile.setTags(new LinkedHashMap<>(tags));
return profile;
}
}
@@ -0,0 +1,144 @@
package io.floci.aws.services.signer;
import io.floci.aws.testing.EnforcementFixtures;
import io.floci.aws.testing.IamEnforcementProfile;
import io.floci.aws.testing.PartitionCleanup;
import io.quarkus.test.common.http.TestHTTPResource;
import io.quarkus.test.junit.QuarkusTest;
import io.quarkus.test.junit.TestProfile;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestInstance;
import org.junit.jupiter.api.extension.AfterAllCallback;
import org.junit.jupiter.api.extension.RegisterExtension;
import java.net.URI;
import java.util.UUID;
import static io.floci.aws.testing.EnforcementFixtures.auth;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;
/**
* Signer routes are rewritten onto an internal prefix before the IAM filter runs, so this proves
* the rewrite does not take a request out of IAM's reach: a key with no policy is refused on the
* same paths a key with {@code signer:*} is allowed through.
*/
@QuarkusTest
@TestProfile(IamEnforcementProfile.class)
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
class SignerIamEnforcementIntegrationTest {
private static final String ACCOUNT = "741686000030";
/** Signer profile names are [0-9a-zA-Z_] only, so no hyphen here. */
private static final String PROFILE = "IamProbe";
/** Names are [0-9a-zA-Z_], so a run-unique suffix drops the hyphens a UUID carries. */
private static final String SUFFIX = UUID.randomUUID().toString().replace("-", "");
private static final String SCOPED_PROFILE = "Scoped" + SUFFIX;
private static final String OTHER_PROFILE = "Other" + SUFFIX;
@TestHTTPResource("/")
URI baseUri;
private final PartitionCleanup cleanup = new PartitionCleanup();
@RegisterExtension
final AfterAllCallback classCleanup = cleanup::afterEach;
private String deniedKey;
private String allowedKey;
@BeforeAll
void createKeys() {
// Both profiles belong to the fixture account, so the scoped policy below can be written
// against a profile ARN that exists before the check runs.
for (String name : new String[] {SCOPED_PROFILE, OTHER_PROFILE}) {
given().port(baseUri.getPort()).header("Authorization", auth(ACCOUNT, "signer"))
.contentType("application/json")
.body("{\"platformId\":\"AWSLambda-SHA384-ECDSA\"}")
.when().put("/signing-profiles/" + name)
.then().statusCode(200);
}
deniedKey = userWithPolicy(null);
allowedKey = userWithPolicy("""
{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":"signer:*","Resource":"*"}]}
""");
}
@Test
void aKeyWithoutAPolicyCannotCreateOrReadAProfile() {
given().header("Authorization", auth(deniedKey, "signer"))
.contentType("application/json")
.body("{\"platformId\":\"AWSLambda-SHA384-ECDSA\"}")
.when().put("/signing-profiles/IamDenied")
.then().statusCode(403);
given().header("Authorization", auth(deniedKey, "signer"))
.when().get("/signing-profiles/" + PROFILE)
.then().statusCode(403);
}
@Test
void aKeyWithSignerAllowCreatesAndReadsAProfile() {
given().header("Authorization", auth(allowedKey, "signer"))
.contentType("application/json")
.body("{\"platformId\":\"AWSLambda-SHA384-ECDSA\"}")
.when().put("/signing-profiles/" + PROFILE)
.then().statusCode(200);
given().header("Authorization", auth(allowedKey, "signer"))
.when().get("/signing-profiles/" + PROFILE)
.then().statusCode(200)
.body("profileName", equalTo(PROFILE))
.body("status", equalTo("Active"));
}
@Test
void aPolicyScopedToOneProfileReadsThatProfileAndNotAnother() {
String scoped = userWithPolicy("""
{"Version":"2012-10-17","Statement":[{"Effect":"Allow",
"Action":"signer:GetSigningProfile",
"Resource":"arn:aws:signer:us-east-1:ACCOUNT:/signing-profiles/SCOPED"}]}
""".replace("ACCOUNT", ACCOUNT).replace("SCOPED", SCOPED_PROFILE));
given().header("Authorization", auth(scoped, "signer"))
.when().get("/signing-profiles/" + SCOPED_PROFILE)
.then().statusCode(200).body("profileName", equalTo(SCOPED_PROFILE));
given().header("Authorization", auth(scoped, "signer"))
.when().get("/signing-profiles/" + OTHER_PROFILE)
.then().statusCode(403);
}
@Test
void aKeyWithoutATaggingPolicyCannotTagAProfileThroughTheSharedTagsRoute() {
// /tags/{resourceArn} is served by the shared tags controller, not by Signer's prefix, so
// this is the route the generated table has to keep unprefixed for the check to see it.
String key = userWithPolicy("""
{"Version":"2012-10-17","Statement":[{"Effect":"Allow",
"Action":"signer:GetSigningProfile","Resource":"*"}]}
""");
String profileArn = "arn:aws:signer:us-east-1:" + ACCOUNT + ":/signing-profiles/" + SCOPED_PROFILE;
given().port(baseUri.getPort()).header("Authorization", auth(key, "signer"))
.contentType("application/json")
.body("{\"tags\":{\"team\":\"payments\"}}")
.when().post("/tags/" + profileArn)
.then().statusCode(403);
given().port(baseUri.getPort()).header("Authorization", auth(key, "signer"))
.when().get("/tags/" + profileArn)
.then().statusCode(403);
}
private String userWithPolicy(String policy) {
String user = "signer-iam-" + UUID.randomUUID();
String key = EnforcementFixtures.createUser(cleanup, baseUri.getPort(), auth(ACCOUNT, "iam"), user)
.accessKeyId();
if (policy != null) {
EnforcementFixtures.putUserPolicy(baseUri.getPort(), auth(ACCOUNT, "iam"), user, "signer", policy);
}
return key;
}
}
@@ -0,0 +1,325 @@
package io.floci.aws.services.signer;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.response.Response;
import io.restassured.specification.RequestSpecification;
import org.junit.jupiter.api.Test;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasItem;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.matchesPattern;
import static org.hamcrest.Matchers.not;
import static org.hamcrest.Matchers.notNullValue;
import static org.hamcrest.Matchers.nullValue;
@QuarkusTest
class SignerIntegrationTest {
private static final String ACCOUNT_ID = "723679240095";
private static final String PROFILE_ARN =
"arn:aws:signer:us-east-1:" + ACCOUNT_ID + ":/signing-profiles/ItProfile";
@Test
void profileRoundTripsThroughRestJsonIncludingTagsAndPermissions() {
signer(ACCOUNT_ID, "us-east-1")
.body("""
{"platformId":"AWSLambda-SHA384-ECDSA",
"signatureValidityPeriod":{"type":"DAYS","value":135},
"overrides":{"signingConfiguration":{"hashAlgorithm":"SHA-384"}},
"tags":{"env":"it"}}
""")
.when()
.put("/signing-profiles/ItProfile")
.then()
.statusCode(200)
.body("arn", equalTo(PROFILE_ARN))
.body("profileVersion", matchesPattern("[0-9a-zA-Z]{10}"))
.body("profileVersionArn", matchesPattern(
"arn:aws:signer:us-east-1:" + ACCOUNT_ID
+ ":/signing-profiles/ItProfile/[0-9a-zA-Z]{10}"));
try {
Response profile = signer(ACCOUNT_ID, "us-east-1")
.when()
.get("/signing-profiles/ItProfile")
.then()
.statusCode(200)
.body("profileName", equalTo("ItProfile"))
.body("platformId", equalTo("AWSLambda-SHA384-ECDSA"))
.body("platformDisplayName", equalTo("AWS Lambda"))
.body("status", equalTo("Active"))
.body("signatureValidityPeriod.type", equalTo("DAYS"))
.body("signatureValidityPeriod.value", equalTo(135))
.body("overrides.signingConfiguration.hashAlgorithm", equalTo("SHA-384"))
.body("tags.env", equalTo("it"))
.extract().response();
String profileVersion = profile.path("profileVersion");
signer(ACCOUNT_ID, "us-east-1")
.when()
.get("/signing-profiles")
.then()
.statusCode(200)
.body("profiles.profileName", hasItem("ItProfile"));
signer(ACCOUNT_ID, "us-east-1")
.body("{\"action\":\"signer:StartSigningJob\","
+ "\"principal\":\"123456789012\",\"statementId\":\"cross-account\"}")
.when()
.post("/signing-profiles/ItProfile/permissions")
.then()
.statusCode(200)
.body("revisionId", not(equalTo("")));
signer(ACCOUNT_ID, "us-east-1")
.when()
.get("/signing-profiles/ItProfile/permissions")
.then()
.statusCode(200)
.body("permissions[0].action", equalTo("signer:StartSigningJob"))
.body("permissions[0].statementId", equalTo("cross-account"))
.body("permissions[0].profileVersion", equalTo(profileVersion));
signer(ACCOUNT_ID, "us-east-1")
.body("{\"tags\":{\"team\":\"platform\"}}")
.when()
.post("/tags/" + PROFILE_ARN)
.then()
.statusCode(204);
signer(ACCOUNT_ID, "us-east-1")
.when()
.get("/tags/" + PROFILE_ARN)
.then()
.statusCode(200)
.body("tags.team", equalTo("platform"))
.body("tags.env", equalTo("it"));
signer(ACCOUNT_ID, "us-east-1")
.when()
.delete("/tags/" + PROFILE_ARN + "?tagKeys=team")
.then()
.statusCode(204);
signer(ACCOUNT_ID, "us-east-1")
.when()
.get("/tags/" + PROFILE_ARN)
.then()
.statusCode(200)
.body("tags.team", nullValue())
.body("tags.env", equalTo("it"));
} finally {
signer(ACCOUNT_ID, "us-east-1")
.when()
.delete("/signing-profiles/ItProfile")
.then()
.statusCode(200);
}
}
@Test
void aSigningJobFailsBecauseNoArtifactIsWritten() {
signer(ACCOUNT_ID, "us-east-1")
.body("{\"platformId\":\"AWSLambda-SHA384-ECDSA\"}")
.when()
.put("/signing-profiles/ItProfile")
.then()
.statusCode(200);
try {
Response started = signer(ACCOUNT_ID, "us-east-1")
.body("""
{"profileName":"ItProfile",
"source":{"s3":{"bucketName":"artifacts","key":"app.zip","version":"1"}},
"destination":{"s3":{"bucketName":"signed","prefix":"out/"}},
"clientRequestToken":"it-token"}
""")
.when()
.post("/signing-jobs")
.then()
.statusCode(200)
.body("jobId", matchesPattern(
"[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}"))
.body("jobOwner", equalTo(ACCOUNT_ID))
.extract().response();
String jobId = started.path("jobId");
signer(ACCOUNT_ID, "us-east-1")
.when()
.get("/signing-jobs/" + jobId)
.then()
.statusCode(200)
.body("status", equalTo("Failed"))
.body("profileName", equalTo("ItProfile"))
.body("source.s3.bucketName", equalTo("artifacts"))
.body("source.s3.key", equalTo("app.zip"))
.body("signedObject", nullValue())
.body("isRevoked", equalTo(false))
.body("statusReason", containsString("does not sign artifacts"))
.body("createdAt", notNullValue());
// No signature exists, so there is nothing to revoke.
signer(ACCOUNT_ID, "us-east-1")
.body("{\"reason\":\"artifact withdrawn\"}")
.when()
.put("/signing-jobs/" + jobId + "/revoke")
.then()
.statusCode(400)
.body("__type", equalTo("ValidationException"));
} finally {
signer(ACCOUNT_ID, "us-east-1")
.when()
.delete("/signing-profiles/ItProfile")
.then()
.statusCode(200);
}
}
@Test
void aPermissionToSignAPayloadIsAcceptedThroughTheWire() {
signer(ACCOUNT_ID, "us-east-1")
.body("{\"platformId\":\"AWSLambda-SHA384-ECDSA\"}")
.when()
.put("/signing-profiles/PermProfile")
.then()
.statusCode(200);
signer(ACCOUNT_ID, "us-east-1")
.body("{\"action\":\"signer:SignPayload\",\"principal\":\"123456789012\","
+ "\"statementId\":\"sign-payload\"}")
.when()
.post("/signing-profiles/PermProfile/permissions")
.then()
.statusCode(200)
.body("revisionId", notNullValue());
signer(ACCOUNT_ID, "us-east-1")
.when()
.get("/signing-profiles/PermProfile/permissions")
.then()
.statusCode(200)
.body("permissions", hasSize(1))
.body("permissions[0].action", equalTo("signer:SignPayload"))
.body("permissions[0].statementId", equalTo("sign-payload"));
}
@Test
void aCanceledProfileStaysReadableAndIsHiddenUnlessAskedFor() {
signer(ACCOUNT_ID, "us-east-1")
.body("{\"platformId\":\"AWSLambda-SHA384-ECDSA\"}")
.when()
.put("/signing-profiles/CancelProfile")
.then()
.statusCode(200);
signer(ACCOUNT_ID, "us-east-1")
.when()
.delete("/signing-profiles/CancelProfile")
.then()
.statusCode(200);
signer(ACCOUNT_ID, "us-east-1")
.when()
.get("/signing-profiles/CancelProfile")
.then()
.statusCode(200)
.body("status", equalTo("Canceled"))
.body("arn", equalTo("arn:aws:signer:us-east-1:" + ACCOUNT_ID
+ ":/signing-profiles/CancelProfile"));
signer(ACCOUNT_ID, "us-east-1")
.when()
.get("/signing-profiles")
.then()
.statusCode(200)
.body("profiles.profileName", not(hasItem("CancelProfile")));
signer(ACCOUNT_ID, "us-east-1")
.queryParam("includeCanceled", "true")
.when()
.get("/signing-profiles")
.then()
.statusCode(200)
.body("profiles.profileName", hasItem("CancelProfile"));
signer(ACCOUNT_ID, "us-east-1")
.body("{\"profileName\":\"CancelProfile\","
+ "\"source\":{\"s3\":{\"bucketName\":\"a\",\"key\":\"k\",\"version\":\"1\"}},"
+ "\"destination\":{\"s3\":{\"bucketName\":\"b\"}},"
+ "\"clientRequestToken\":\"after-cancel\"}")
.when()
.post("/signing-jobs")
.then()
.statusCode(400)
.body("__type", equalTo("ValidationException"));
}
@Test
void platformsAreServedAndAnUnknownOneIsNotFound() {
signer(ACCOUNT_ID, "us-east-1")
.when()
.get("/signing-platforms")
.then()
.statusCode(200)
.body("platforms.platformId",
hasItem("AWSLambda-SHA384-ECDSA"))
.body("platforms[0].signingConfiguration.hashAlgorithmOptions.allowedValues",
hasItem("SHA-384"));
signer(ACCOUNT_ID, "us-east-1")
.when()
.get("/signing-platforms/AWSLambda-SHA384-ECDSA")
.then()
.statusCode(200)
.body("category", equalTo("AWSLambda"))
.body("signingImageFormat.defaultFormat", equalTo("JSON"));
signer(ACCOUNT_ID, "us-east-1")
.when()
.get("/signing-platforms/Not-A-Platform")
.then()
.statusCode(404)
.body("__type", equalTo("ResourceNotFoundException"));
}
@Test
void aRequestSignedForAnotherServiceKeepsItsPathAndDoesNotReachSigner() {
given()
.contentType("application/json")
.header("Authorization", "AWS4-HMAC-SHA256 Credential=" + ACCOUNT_ID
+ "/20260101/us-east-1/s3/aws4_request")
.when()
.get("/signing-profiles")
.then()
.statusCode(404);
}
@Test
void validationErrorsUseTheSignerErrorShape() {
signer(ACCOUNT_ID, "us-east-1")
.body("{\"platformId\":\"Not-A-Platform\"}")
.when()
.put("/signing-profiles/ItProfile")
.then()
.statusCode(400)
.body("__type", equalTo("ValidationException"));
signer(ACCOUNT_ID, "us-east-1")
.when()
.get("/signing-profiles/Missing")
.then()
.statusCode(404)
.body("__type", equalTo("ResourceNotFoundException"));
}
private static RequestSpecification signer(String accountId, String region) {
String authorization = "AWS4-HMAC-SHA256 Credential=" + accountId
+ "/20260101/" + region + "/signer/aws4_request";
return given()
.contentType("application/json")
.header("Authorization", authorization);
}
}
@@ -0,0 +1,421 @@
package io.floci.aws.services.signer;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.floci.aws.core.common.AwsException;
import io.floci.aws.core.storage.AccountAwareStorageBackend;
import io.floci.aws.services.signer.model.SigningJob;
import io.floci.aws.services.signer.model.SigningProfile;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.util.List;
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.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
class SignerServiceTest {
private static final String REGION = "us-east-1";
private static final String CERT_ARN = "arn:aws:acm:us-east-1:000000000000:certificate/abc";
private static final Integer MAX_PAGE = Integer.valueOf(25);
private static final String ACCOUNT = "000000000000";
private static final String PROFILE_ARN =
"arn:aws:signer:us-east-1:" + ACCOUNT + ":/signing-profiles/MyProfile";
private final ObjectMapper objectMapper = new ObjectMapper();
private AccountAwareStorageBackend<SigningProfile> profiles;
private AccountAwareStorageBackend<SigningJob> jobs;
private SignerService service;
private SignerService mockSigning;
@BeforeEach
void setUp() {
profiles = AccountAwareStorageBackend.inMemory(ACCOUNT);
jobs = AccountAwareStorageBackend.inMemory(ACCOUNT);
service = new SignerService(profiles, jobs);
mockSigning = new SignerService(profiles, jobs, true);
}
@Test
void putSigningProfileKeepsPlatformOverridesAndTags() throws Exception {
SigningProfile created = service.putSigningProfile("MyProfile", profileRequest(), REGION);
assertEquals(PROFILE_ARN, created.getArn());
assertTrue(created.getProfileVersion().matches("[0-9a-zA-Z]{10}"));
assertEquals(PROFILE_ARN + "/" + created.getProfileVersion(), created.getProfileVersionArn());
assertEquals("AWSLambda-SHA384-ECDSA", created.getPlatformId());
assertEquals("AWS Lambda", created.getPlatformDisplayName());
assertEquals("Active", created.getStatus());
assertEquals("DAYS", created.getSignatureValidityPeriodType());
assertEquals(135, created.getSignatureValidityPeriodValue().intValue());
assertEquals("SHA-384", created.getOverrides().path("signingConfiguration")
.path("hashAlgorithm").asText());
assertEquals("env", created.getTags().keySet().iterator().next());
}
@Test
void putSigningProfileOnAnExistingNameMintsAVersionAndKeepsTagsItWasNotGiven() throws Exception {
String firstVersion = service.putSigningProfile("MyProfile", profileRequest(), REGION)
.getProfileVersion();
SigningProfile second = service.putSigningProfile("MyProfile",
objectMapper.readTree("{\"platformId\":\"AWSLambda-SHA384-ECDSA\"}"), REGION);
assertFalse(firstVersion.equals(second.getProfileVersion()));
assertEquals(1, second.getTags().size());
assertEquals("test", second.getTags().get("env"));
assertEquals("DAYS", second.getSignatureValidityPeriodType());
assertEquals(135, second.getSignatureValidityPeriodValue().intValue());
}
@Test
void putSigningProfileRejectsAnUnknownPlatformAndAnOutOfRangeValidity() throws Exception {
AwsException platform = assertThrows(AwsException.class, () -> service.putSigningProfile(
"MyProfile", objectMapper.readTree("{\"platformId\":\"Not-A-Platform\"}"), REGION));
assertEquals("ValidationException", platform.getErrorCode());
JsonNode tooLong = objectMapper.readTree("""
{"platformId":"AWSLambda-SHA384-ECDSA",
"signatureValidityPeriod":{"type":"DAYS","value":9999}}
""");
AwsException validity = assertThrows(AwsException.class,
() -> service.putSigningProfile("MyProfile", tooLong, REGION));
assertEquals("ValidationException", validity.getErrorCode());
AwsException name = assertThrows(AwsException.class,
() -> service.putSigningProfile("bad name?", profileRequest(), REGION));
assertEquals("ValidationException", name.getErrorCode());
}
@Test
void revokeSigningProfileRecordsTheReasonAndRefusesAStaleVersion() throws Exception {
SigningProfile profile = service.putSigningProfile("MyProfile", profileRequest(), REGION);
String revoke = "{\"profileVersion\":\"" + profile.getProfileVersion()
+ "\",\"reason\":\"key compromise\",\"effectiveTime\":\"2026-01-01T00:00:00Z\"}";
SigningProfile revoked = service.revokeSigningProfile("MyProfile",
objectMapper.readTree(revoke), REGION);
assertEquals("Revoked", revoked.getStatus());
assertEquals("key compromise", revoked.getStatusReason());
assertEquals(1767225600L, revoked.getRevocationEffectiveFrom().longValue());
assertNotNull(revoked.getRevokedAt());
JsonNode stale = objectMapper.readTree(
"{\"profileVersion\":\"aaaaaaaaaa\",\"reason\":\"x\",\"effectiveTime\":\"2026-01-01T00:00:00Z\"}");
AwsException refused = assertThrows(AwsException.class,
() -> service.revokeSigningProfile("MyProfile", stale, REGION));
assertEquals("ValidationException", refused.getErrorCode());
}
@Test
void profilePermissionsMoveTheRevisionAndRequireTheCurrentOneToRemove() throws Exception {
service.putSigningProfile("MyProfile", profileRequest(), REGION);
String revisionId = service.addProfilePermission("MyProfile",
objectMapper.readTree("{\"action\":\"signer:StartSigningJob\","
+ "\"principal\":\"123456789012\",\"statementId\":\"cross-account\"}"), REGION);
List<SigningProfile.ProfilePermission> permissions =
service.listProfilePermissions("MyProfile", REGION);
assertEquals(1, permissions.size());
assertEquals("signer:StartSigningJob", permissions.get(0).getAction());
assertNotNull(revisionId);
AwsException stale = assertThrows(AwsException.class,
() -> service.removeProfilePermission("MyProfile", "cross-account", "rev-1", REGION));
assertEquals("ConflictException", stale.getErrorCode());
String nextRevision = service.removeProfilePermission(
"MyProfile", "cross-account", revisionId, REGION);
assertFalse(revisionId.equals(nextRevision));
assertTrue(service.listProfilePermissions("MyProfile", REGION).isEmpty());
}
@Test
void aPermissionToSignAPayloadIsGrantedLikeTheOtherActions() throws Exception {
service.putSigningProfile("MyProfile", profileRequest(), REGION);
String revisionId = service.addProfilePermission("MyProfile", objectMapper.readTree(
"{\"action\":\"signer:SignPayload\",\"principal\":\"123456789012\","
+ "\"statementId\":\"sign-payload\"}"), REGION);
List<SigningProfile.ProfilePermission> permissions =
service.listProfilePermissions("MyProfile", REGION);
assertEquals(1, permissions.size());
assertEquals("signer:SignPayload", permissions.get(0).getAction());
assertNotNull(revisionId);
AwsException refused = assertThrows(AwsException.class,
() -> service.addProfilePermission("MyProfile", objectMapper.readTree(
"{\"action\":\"signer:DeleteSigningProfile\","
+ "\"principal\":\"123456789012\",\"statementId\":\"bogus\"}"),
REGION));
assertEquals("ValidationException", refused.getErrorCode());
}
@Test
void aJobFailsWhenNothingWritesTheSignedObject() throws Exception {
service.putSigningProfile("MyProfile", profileRequest(), REGION);
SigningJob job = service.startSigningJob(objectMapper.readTree(jobRequest("token-1")), REGION);
assertEquals("Failed", job.getStatus());
assertNull(job.getSignedObjectBucketName());
assertNull(job.getSignedObjectKey());
assertNull(job.getSignatureExpiresAt());
assertTrue(job.getStatusReason().contains("does not sign artifacts"));
assertEquals(job.getJobId(),
service.describeSigningJob(job.getJobId(), REGION).getJobId());
AwsException refused = assertThrows(AwsException.class, () -> service.revokeSignature(
job.getJobId(), objectMapper.readTree("{\"reason\":\"x\"}"), REGION));
assertEquals("ValidationException", refused.getErrorCode());
}
@Test
void aConfiguredMockJobSucceedsAndCanBeRevoked() throws Exception {
SigningProfile profile = mockSigning.putSigningProfile("MyProfile", profileRequest(), REGION);
SigningJob job = mockSigning.startSigningJob(
objectMapper.readTree(jobRequest("token-mock")), REGION);
assertEquals("Succeeded", job.getStatus());
assertEquals(profile.getProfileVersion(), job.getProfileVersion());
assertEquals("artifacts", job.getSourceBucketName());
assertEquals("out/app.zip", job.getSignedObjectKey());
assertEquals("signed", job.getSignedObjectBucketName());
assertNotNull(job.getSignatureExpiresAt());
SigningJob revoked = mockSigning.revokeSignature(job.getJobId(),
objectMapper.readTree("{\"reason\":\"artifact withdrawn\"}"), REGION);
assertTrue(revoked.isRevoked());
assertEquals("artifact withdrawn", revoked.getRevocationReason());
}
@Test
void startSigningJobRefusesARevokedProfileAndAMissingSource() throws Exception {
SigningProfile profile = service.putSigningProfile("MyProfile", profileRequest(), REGION);
service.revokeSigningProfile("MyProfile", objectMapper.readTree(
"{\"profileVersion\":\"" + profile.getProfileVersion()
+ "\",\"reason\":\"retired\",\"effectiveTime\":\"2026-01-01T00:00:00Z\"}"),
REGION);
AwsException revoked = assertThrows(AwsException.class, () -> service.startSigningJob(
objectMapper.readTree("{\"profileName\":\"MyProfile\",\"source\":{\"s3\":"
+ "{\"bucketName\":\"a\",\"key\":\"k\",\"version\":\"1\"}},"
+ "\"destination\":{\"s3\":{\"bucketName\":\"b\"}},"
+ "\"clientRequestToken\":\"token-revoked\"}"), REGION));
assertEquals("ValidationException", revoked.getErrorCode());
service.putSigningProfile("Other", profileRequest(), REGION);
AwsException noVersion = assertThrows(AwsException.class, () -> service.startSigningJob(
objectMapper.readTree("{\"profileName\":\"Other\",\"source\":{\"s3\":"
+ "{\"bucketName\":\"a\",\"key\":\"k\"}},"
+ "\"destination\":{\"s3\":{\"bucketName\":\"b\"}},"
+ "\"clientRequestToken\":\"token-no-version\"}"), REGION));
assertEquals("ValidationException", noVersion.getErrorCode());
}
@Test
void listsPageAndFilterByPlatformAndRegion() throws Exception {
service.putSigningProfile("Alpha", profileRequest(), REGION);
service.putSigningProfile("Beta", profileRequest(), REGION);
service.putSigningProfile("Gamma", objectMapper.readTree(
"{\"platformId\":\"Notation-OCI-SHA384-ECDSA\"}"), REGION);
SignerService.Page<SigningProfile> firstPage =
service.listSigningProfiles(REGION, null, null, false, 2, null);
assertEquals(2, firstPage.items().size());
assertEquals("Alpha", firstPage.items().get(0).getProfileName());
assertNotNull(firstPage.nextToken());
SignerService.Page<SigningProfile> secondPage =
service.listSigningProfiles(REGION, null, null, false, 2, firstPage.nextToken());
assertEquals(1, secondPage.items().size());
assertEquals("Gamma", secondPage.items().get(0).getProfileName());
assertNull(secondPage.nextToken());
SignerService.Page<SigningProfile> byPlatform = service.listSigningProfiles(
REGION, "Notation-OCI-SHA384-ECDSA", null, false, MAX_PAGE, null);
assertEquals(1, byPlatform.items().size());
assertTrue(service.listSigningProfiles("eu-west-1", null, null, false, MAX_PAGE, null)
.items().isEmpty());
}
@Test
void tagsAreManagedThroughTheSharedTagHandler() throws Exception {
service.putSigningProfile("MyProfile", profileRequest(), REGION);
service.tagResource(REGION, PROFILE_ARN, Map.of("team", "platform"));
Map<String, String> tags = service.listTags(REGION, PROFILE_ARN);
assertEquals("platform", tags.get("team"));
assertEquals("test", tags.get("env"));
service.untagResource(REGION, PROFILE_ARN, List.of("env"));
assertEquals(Map.of("team", "platform"), service.listTags(REGION, PROFILE_ARN));
assertEquals("signer", service.serviceKey());
}
@Test
void cancelKeepsTheProfileAsCanceledAndStopsNewJobs() throws Exception {
SigningProfile active = service.putSigningProfile("MyProfile", profileRequest(), REGION);
service.cancelSigningProfile("MyProfile", REGION);
SigningProfile canceled = service.getSigningProfile("MyProfile", REGION);
assertEquals("Canceled", canceled.getStatus());
assertEquals(active.getArn(), canceled.getArn());
assertEquals(active.getProfileVersion(), canceled.getProfileVersion());
assertTrue(service.listSigningProfiles(REGION, null, null, null, MAX_PAGE, null).items().isEmpty());
assertEquals(1, service.listSigningProfiles(REGION, null, null, true, MAX_PAGE, null)
.items().size());
assertEquals(1, service.listSigningProfiles(REGION, null, List.of("Canceled"), null,
MAX_PAGE, null).items().size());
AwsException noJob = assertThrows(AwsException.class,
() -> service.startSigningJob(objectMapper.readTree(jobRequest("token-canceled")), REGION));
assertEquals("ValidationException", noJob.getErrorCode());
// Cancelling again is a no-op, and a put brings the name back as a new active version.
service.cancelSigningProfile("MyProfile", REGION);
assertEquals("Canceled", service.getSigningProfile("MyProfile", REGION).getStatus());
assertEquals("Active", service.putSigningProfile("MyProfile", profileRequest(), REGION)
.getStatus());
}
@Test
void aRevokedProfileCannotBeCanceledAndForeignArnsAreRefused() throws Exception {
SigningProfile profile = service.putSigningProfile("MyProfile", profileRequest(), REGION);
service.revokeSigningProfile("MyProfile", objectMapper.readTree(
"{\"profileVersion\":\"" + profile.getProfileVersion()
+ "\",\"reason\":\"retired\",\"effectiveTime\":\"2026-01-01T00:00:00Z\"}"),
REGION);
AwsException revoked = assertThrows(AwsException.class,
() -> service.cancelSigningProfile("MyProfile", REGION));
assertEquals("ConflictException", revoked.getErrorCode());
AwsException foreign = assertThrows(AwsException.class, () -> service.listTags(REGION,
"arn:aws:signer:us-east-1:" + ACCOUNT + ":/signing-jobs/not-a-profile"));
assertEquals("ValidationException", foreign.getErrorCode());
}
private JsonNode profileRequest() throws Exception {
return objectMapper.readTree("""
{"platformId":"AWSLambda-SHA384-ECDSA",
"signingMaterial":{"certificateArn":"arn:aws:acm:us-east-1:000000000000:certificate/abc"},
"signatureValidityPeriod":{"type":"DAYS","value":135},
"overrides":{"signingConfiguration":{"hashAlgorithm":"SHA-384"},
"signingImageFormat":"JSON"},
"signingParameters":{"SignatureFormat":"SHA-384"},
"tags":{"env":"test"}}
""");
}
@Test
void rePuttingAProfileKeepsTheMembersTheRequestOmits() throws Exception {
service.putSigningProfile("MyProfile", profileRequest(), REGION);
service.putSigningProfile("MyProfile", objectMapper.readTree(
"{\"platformId\":\"AWSLambda-SHA384-ECDSA\"}"), REGION);
SigningProfile reread = service.getSigningProfile("MyProfile", REGION);
assertEquals(CERT_ARN, reread.getSigningMaterialCertificateArn());
assertEquals("SHA-384", reread.getOverrides().path("signingConfiguration")
.path("hashAlgorithm").asText());
assertEquals("SHA-384", reread.getSigningParameters().get("SignatureFormat"));
}
@Test
void tagKeysFollowTheAwsPattern() throws Exception {
SigningProfile profile = service.putSigningProfile("MyProfile", objectMapper.readTree("""
{"platformId":"AWSLambda-SHA384-ECDSA",
"tags":{"Env1":"a","k8s-app":"b","owner/team:x":"c"}}
"""), REGION);
assertEquals("a", profile.getTags().get("Env1"));
assertEquals("b", profile.getTags().get("k8s-app"));
for (String rejected : new String[] {"Cost Center", "owner@team"}) {
AwsException e = assertThrows(AwsException.class, () -> service.putSigningProfile(
"MyProfile", objectMapper.readTree("{\"platformId\":\"AWSLambda-SHA384-ECDSA\","
+ "\"tags\":{\"" + rejected + "\":\"x\"}}"), REGION));
assertEquals("ValidationException", e.getErrorCode(), rejected);
}
}
@Test
void theClientRequestTokenMakesStartSigningJobIdempotent() throws Exception {
service.putSigningProfile("MyProfile", profileRequest(), REGION);
JsonNode request = objectMapper.readTree(jobRequest("token-same"));
SigningJob first = service.startSigningJob(request, REGION);
SigningJob retried = service.startSigningJob(request, REGION);
assertEquals(first.getJobId(), retried.getJobId());
assertEquals(1, service.listSigningJobs(REGION, null, null, null, MAX_PAGE, null).items().size());
AwsException missingToken = assertThrows(AwsException.class,
() -> service.startSigningJob(objectMapper.readTree("""
{"profileName":"MyProfile",
"source":{"s3":{"bucketName":"artifacts","key":"app.zip","version":"1"}},
"destination":{"s3":{"bucketName":"signed"}}}
"""), REGION));
assertEquals("ValidationException", missingToken.getErrorCode());
}
@Test
void anArnFromAnotherAccountIsRefused() throws Exception {
service.putSigningProfile("MyProfile", profileRequest(), REGION);
AwsException foreign = assertThrows(AwsException.class, () -> service.listTags(REGION,
"arn:aws:signer:us-east-1:999999999999:/signing-profiles/MyProfile"));
assertEquals("ResourceNotFoundException", foreign.getErrorCode());
assertEquals("test", service.listTags(REGION, PROFILE_ARN).get("env"));
}
@Test
void aJobWithoutAValidityPeriodUsesTheDefaultSignerApplies() throws Exception {
service.putSigningProfile("MyProfile", objectMapper.readTree(
"{\"platformId\":\"AWSLambda-SHA384-ECDSA\"}"), REGION);
SigningJob job = mockSigning.startSigningJob(
objectMapper.readTree(jobRequest("token-default")), REGION);
assertNotNull(job.getSignatureExpiresAt());
long days = (job.getSignatureExpiresAt().longValue() - job.getCreatedAt().longValue()) / 86_400L;
assertTrue(days > 3_000L, "expected the 135 month default, got " + days + " days");
}
@Test
void aJobOnAPlatformWithoutRevocationCannotBeRevoked() throws Exception {
mockSigning.putSigningProfile("IotProfile", objectMapper.readTree(
"{\"platformId\":\"AWSIoTDeviceManagement-SHA256-ECDSA\"}"), REGION);
SigningJob job = mockSigning.startSigningJob(
objectMapper.readTree(jobRequest("token-iot", "IotProfile")), REGION);
assertNull(job.getSignatureExpiresAt());
AwsException refused = assertThrows(AwsException.class, () -> mockSigning.revokeSignature(
job.getJobId(), objectMapper.readTree("{\"reason\":\"x\"}"), REGION));
assertEquals("ValidationException", refused.getErrorCode());
}
private static String jobRequest(String token) {
return jobRequest(token, "MyProfile");
}
private static String jobRequest(String token, String profileName) {
return "{\"profileName\":\"" + profileName + "\","
+ "\"source\":{\"s3\":{\"bucketName\":\"artifacts\",\"key\":\"app.zip\",\"version\":\"1\"}},"
+ "\"destination\":{\"s3\":{\"bucketName\":\"signed\",\"prefix\":\"out/\"}},"
+ "\"clientRequestToken\":\"" + token + "\"}";
}
}