mirror of
https://github.com/floci-io/floci.git
synced 2026-11-27 07:39:24 -05:00
feat(iam): model server certificates (#4975)
Replace the ListServerCertificates stub with the server-certificate lifecycle: UploadServerCertificate, GetServerCertificate, UpdateServerCertificate, DeleteServerCertificate, ListServerCertificates and the tag operations. The uploaded material is really parsed, because two of the upload's modeled errors cannot be answered otherwise. CertificateBody, and every certificate in CertificateChain rather than only its first block, must be readable PEM or the upload is MalformedCertificate; the private key must match the certificate's public key or it is KeyPairMismatch. The match is a sign-then-verify check, so it holds for RSA and EC alike. All of it goes through core.common.Pem rather than a second copy of the parsing. Expiration is read from the certificate's own notAfter rather than stored separately, so it cannot drift from what it describes. ServerCertificateId uses AWS's ASCA prefix. The private key is stored and never returned: AWS marks privateKeyType sensitive and models it only on the upload, so neither reader echoes it back, and ListServerCertificates returns metadata only as AWS documents. Request shapes are enforced from the wire model: the 16384-character caps on the body and key, the much larger 2097152 cap on the chain, and the per-account quota of 20 that the User Guide's table publishes, counted under the same lock as the write. A rename that only changes case is allowed, excluding the certificate from its own duplicate check by id the way updateUser does. GetAccountSummary's ServerCertificates count is now backed by the store instead of a hardcoded zero. ResourceArnBuilder gains an iam case naming the certificate an operation targets, so a policy statement scoped to one certificate constrains it under enforcement. Every other IAM action still resolves to *, which is long-standing behaviour rather than something this adds; documented in docs/services/iam.md and tracked in #4979. DeleteServerCertificate does not raise the in-use DeleteConflict AWS returns when a load balancer still references the certificate. Floci cannot determine that yet, because ELB Classic and CloudFront store certificate identifiers without resolving them against IAM. Documented, and tracked in #4875.
This commit is contained in:
1 parent
543f01618f
commit
d0c7c23f6b
16 files changed
+2090
-22
No files matched your search
@@ -112,7 +112,13 @@ public class AwsQueryController {
|
||||
"UpdateSAMLProvider", "DeleteSAMLProvider",
|
||||
"TagSAMLProvider", "UntagSAMLProvider", "ListSAMLProviderTags",
|
||||
"GenerateServiceLastAccessedDetails", "GetServiceLastAccessedDetails",
|
||||
"GetServiceLastAccessedDetailsWithEntities", "ListPoliciesGrantingServiceAccess"
|
||||
"GetServiceLastAccessedDetailsWithEntities", "ListPoliciesGrantingServiceAccess",
|
||||
"UploadServerCertificate", "GetServerCertificate", "UpdateServerCertificate",
|
||||
"DeleteServerCertificate", "ListServerCertificates",
|
||||
"TagServerCertificate", "UntagServerCertificate", "ListServerCertificateTags",
|
||||
"CreateVirtualMFADevice", "DeleteVirtualMFADevice", "ListVirtualMFADevices",
|
||||
"EnableMFADevice", "DeactivateMFADevice", "ResyncMFADevice", "ListMFADevices",
|
||||
"TagMFADevice", "UntagMFADevice", "ListMFADeviceTags"
|
||||
);
|
||||
|
||||
private static final Set<String> AUTOSCALING_ACTIONS = Set.of(
|
||||
|
||||
@@ -14,6 +14,7 @@ import io.github.hectorvent.floci.services.iam.model.LoginProfile;
|
||||
import io.github.hectorvent.floci.services.iam.model.OpenIDConnectProvider;
|
||||
import io.github.hectorvent.floci.services.iam.model.PolicyVersion;
|
||||
import io.github.hectorvent.floci.services.iam.model.SAMLProvider;
|
||||
import io.github.hectorvent.floci.services.iam.model.ServerCertificate;
|
||||
import io.github.hectorvent.floci.services.iam.model.ServiceLastAccessedEntity;
|
||||
import io.github.hectorvent.floci.services.iam.model.ServiceLastAccessedJob;
|
||||
import io.github.hectorvent.floci.services.iam.model.VirtualMfaDevice;
|
||||
@@ -130,7 +131,14 @@ public class IamQueryHandler {
|
||||
case "TagOpenIDConnectProvider" -> handleTagOpenIDConnectProvider(params);
|
||||
case "UntagOpenIDConnectProvider" -> handleUntagOpenIDConnectProvider(params);
|
||||
case "ListOpenIDConnectProviderTags" -> handleListOpenIDConnectProviderTags(params);
|
||||
case "UploadServerCertificate" -> handleUploadServerCertificate(params);
|
||||
case "GetServerCertificate" -> handleGetServerCertificate(params);
|
||||
case "UpdateServerCertificate" -> handleUpdateServerCertificate(params);
|
||||
case "DeleteServerCertificate" -> handleDeleteServerCertificate(params);
|
||||
case "ListServerCertificates" -> handleListServerCertificates(params);
|
||||
case "TagServerCertificate" -> handleTagServerCertificate(params);
|
||||
case "UntagServerCertificate" -> handleUntagServerCertificate(params);
|
||||
case "ListServerCertificateTags" -> handleListServerCertificateTags(params);
|
||||
|
||||
// Account Aliases
|
||||
case "ListAccountAliases" -> handleListAccountAliases(params);
|
||||
@@ -683,13 +691,100 @@ public class IamQueryHandler {
|
||||
return Response.ok(AwsQueryResponse.envelope("ListOpenIDConnectProviderTags", AwsNamespaces.IAM, result)).build();
|
||||
}
|
||||
|
||||
private Response handleListServerCertificates(MultivaluedMap<String, String> params) {
|
||||
// Server certificates are not modeled; return an empty paginated list.
|
||||
private Response handleUploadServerCertificate(MultivaluedMap<String, String> params) {
|
||||
ServerCertificate certificate = iamService.uploadServerCertificate(
|
||||
getParam(params, "ServerCertificateName"), getParam(params, "Path"),
|
||||
getParam(params, "CertificateBody"), getParam(params, "PrivateKey"),
|
||||
getParam(params, "CertificateChain"), extractTags(params, false));
|
||||
String result = new XmlBuilder()
|
||||
.start("ServerCertificateMetadataList").end("ServerCertificateMetadataList")
|
||||
.elem("IsTruncated", false)
|
||||
.start("ServerCertificateMetadata").raw(serverCertificateMetadataXml(certificate))
|
||||
.end("ServerCertificateMetadata")
|
||||
.raw(tagsElement(new TreeMap<>(certificate.getTags())))
|
||||
.build();
|
||||
return Response.ok(AwsQueryResponse.envelope("UploadServerCertificate", AwsNamespaces.IAM, result)).build();
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the stored certificate and its chain, but never the private key: AWS marks
|
||||
* {@code privateKeyType} sensitive and models it only on the upload, so no reader returns it.
|
||||
*/
|
||||
private Response handleGetServerCertificate(MultivaluedMap<String, String> params) {
|
||||
ServerCertificate certificate = iamService.getServerCertificate(
|
||||
getParam(params, "ServerCertificateName"));
|
||||
XmlBuilder xml = new XmlBuilder().start("ServerCertificate")
|
||||
.start("ServerCertificateMetadata").raw(serverCertificateMetadataXml(certificate))
|
||||
.end("ServerCertificateMetadata")
|
||||
.elem("CertificateBody", certificate.getCertificateBody());
|
||||
if (certificate.getCertificateChain() != null) {
|
||||
xml.elem("CertificateChain", certificate.getCertificateChain());
|
||||
}
|
||||
xml.raw(tagsElement(new TreeMap<>(certificate.getTags()))).end("ServerCertificate");
|
||||
return Response.ok(AwsQueryResponse.envelope("GetServerCertificate", AwsNamespaces.IAM, xml.build())).build();
|
||||
}
|
||||
|
||||
private Response handleUpdateServerCertificate(MultivaluedMap<String, String> params) {
|
||||
iamService.updateServerCertificate(getParam(params, "ServerCertificateName"),
|
||||
getParam(params, "NewServerCertificateName"), getParam(params, "NewPath"));
|
||||
return Response.ok(AwsQueryResponse.envelopeNoResult("UpdateServerCertificate", AwsNamespaces.IAM)).build();
|
||||
}
|
||||
|
||||
private Response handleDeleteServerCertificate(MultivaluedMap<String, String> params) {
|
||||
iamService.deleteServerCertificate(getParam(params, "ServerCertificateName"));
|
||||
return Response.ok(AwsQueryResponse.envelopeNoResult("DeleteServerCertificate", AwsNamespaces.IAM)).build();
|
||||
}
|
||||
|
||||
/**
|
||||
* The metadata list only, as AWS documents: "this operation does not return the certificate
|
||||
* body, certificate chain, or private key".
|
||||
*/
|
||||
private Response handleListServerCertificates(MultivaluedMap<String, String> params) {
|
||||
Page<ServerCertificate> page = paginate(
|
||||
iamService.listServerCertificates(getParam(params, "PathPrefix")), params);
|
||||
XmlBuilder xml = new XmlBuilder().start("ServerCertificateMetadataList");
|
||||
for (ServerCertificate certificate : page.items()) {
|
||||
xml.start("member").raw(serverCertificateMetadataXml(certificate)).end("member");
|
||||
}
|
||||
xml.end("ServerCertificateMetadataList").elem("IsTruncated", page.truncated());
|
||||
if (page.marker() != null) {
|
||||
xml.elem("Marker", page.marker());
|
||||
}
|
||||
return Response.ok(AwsQueryResponse.envelope("ListServerCertificates", AwsNamespaces.IAM, xml.build())).build();
|
||||
}
|
||||
|
||||
private Response handleTagServerCertificate(MultivaluedMap<String, String> params) {
|
||||
iamService.tagServerCertificate(getParam(params, "ServerCertificateName"), extractTags(params, false));
|
||||
return Response.ok(AwsQueryResponse.envelopeNoResult("TagServerCertificate", AwsNamespaces.IAM)).build();
|
||||
}
|
||||
|
||||
private Response handleUntagServerCertificate(MultivaluedMap<String, String> params) {
|
||||
iamService.untagServerCertificate(getParam(params, "ServerCertificateName"), extractTagKeys(params));
|
||||
return Response.ok(AwsQueryResponse.envelopeNoResult("UntagServerCertificate", AwsNamespaces.IAM)).build();
|
||||
}
|
||||
|
||||
private Response handleListServerCertificateTags(MultivaluedMap<String, String> params) {
|
||||
Map<String, String> tags = new TreeMap<>(iamService.listServerCertificateTags(
|
||||
getParam(params, "ServerCertificateName")));
|
||||
Page<Map.Entry<String, String>> page = paginate(List.copyOf(tags.entrySet()), params);
|
||||
XmlBuilder xml = new XmlBuilder().start("Tags");
|
||||
for (Map.Entry<String, String> tag : page.items()) {
|
||||
xml.start("member").elem("Key", tag.getKey()).elem("Value", tag.getValue()).end("member");
|
||||
}
|
||||
xml.end("Tags").elem("IsTruncated", page.truncated());
|
||||
if (page.marker() != null) {
|
||||
xml.elem("Marker", page.marker());
|
||||
}
|
||||
return Response.ok(AwsQueryResponse.envelope("ListServerCertificateTags", AwsNamespaces.IAM, xml.build())).build();
|
||||
}
|
||||
|
||||
private String serverCertificateMetadataXml(ServerCertificate certificate) {
|
||||
return new XmlBuilder()
|
||||
.elem("Path", certificate.getPath())
|
||||
.elem("ServerCertificateName", certificate.getServerCertificateName())
|
||||
.elem("ServerCertificateId", certificate.getServerCertificateId())
|
||||
.elem("Arn", certificate.getArn())
|
||||
.elem("UploadDate", isoDate(certificate.getUploadDate()))
|
||||
.elem("Expiration", isoDate(certificate.getExpiration()))
|
||||
.build();
|
||||
return Response.ok(AwsQueryResponse.envelope("ListServerCertificates", AwsNamespaces.IAM, result)).build();
|
||||
}
|
||||
|
||||
// =========================================================================
|
||||
|
||||
@@ -4,6 +4,8 @@ import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import io.github.hectorvent.floci.core.common.AwsArnUtils;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.common.AwsPartitions;
|
||||
import io.github.hectorvent.floci.core.common.CertificateMaterialException;
|
||||
import io.github.hectorvent.floci.core.common.Pem;
|
||||
import io.github.hectorvent.floci.core.common.RegionResolver;
|
||||
import io.github.hectorvent.floci.core.common.ServicePrincipals;
|
||||
import io.github.hectorvent.floci.core.common.SessionAccountLookup;
|
||||
@@ -28,6 +30,7 @@ import io.github.hectorvent.floci.services.iam.model.OpenIDConnectProvider;
|
||||
import io.github.hectorvent.floci.services.iam.model.OrganizationRootFeatures;
|
||||
import io.github.hectorvent.floci.services.iam.model.PolicyVersion;
|
||||
import io.github.hectorvent.floci.services.iam.model.CallerContext;
|
||||
import io.github.hectorvent.floci.services.iam.model.ServerCertificate;
|
||||
import io.github.hectorvent.floci.services.iam.model.SessionCredential;
|
||||
import io.github.hectorvent.floci.services.iam.model.VirtualMfaDevice;
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
@@ -39,7 +42,9 @@ import org.jboss.logging.Logger;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.PrivateKey;
|
||||
import java.security.SecureRandom;
|
||||
import java.security.cert.X509Certificate;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
@@ -133,6 +138,15 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
|
||||
private static final Pattern IAM_PATH_PATTERN = Pattern.compile("(/)|(/[\\x21-\\x7E]+/)");
|
||||
private static final int IAM_PATH_MAX_LENGTH = 512;
|
||||
private static final int MAX_TAGS_PER_RESOURCE = 50;
|
||||
/**
|
||||
* The IAM User Guide's quota table gives "Server certificates per account" as 20, with 20 as
|
||||
* the maximum it can be raised to, so this is a real ceiling rather than a default.
|
||||
*/
|
||||
private static final int MAX_SERVER_CERTIFICATES = 20;
|
||||
/** {@code certificateBodyType} and {@code privateKeyType} are both 1 to 16384 characters. */
|
||||
private static final int MAX_CERTIFICATE_BODY_LENGTH = 16384;
|
||||
/** {@code certificateChainType} is far larger, at 1 to 2097152. */
|
||||
private static final int MAX_CERTIFICATE_CHAIN_LENGTH = 2097152;
|
||||
/**
|
||||
* "You can register up to eight MFA devices of any combination of the currently supported MFA
|
||||
* types" (IAM User Guide). Floci models only virtual devices, so this bounds those alone.
|
||||
@@ -201,6 +215,14 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
|
||||
private final StorageBackend<String, CredentialReport> credentialReports;
|
||||
/** Virtual MFA devices, keyed by serial number, which for a virtual device is its own ARN. */
|
||||
private final StorageBackend<String, VirtualMfaDevice> virtualMfaDevices;
|
||||
/** Server certificates, keyed by name, which is unique within the account. */
|
||||
private final StorageBackend<String, ServerCertificate> serverCertificates;
|
||||
/**
|
||||
* Guards the check-then-write on a server certificate. Upload checks the name is free before
|
||||
* storing, and UpdateServerCertificate checks a new name is free before moving to it, so two
|
||||
* requests racing the same name would otherwise both pass the check.
|
||||
*/
|
||||
private final Object serverCertificateLock = new Object();
|
||||
/**
|
||||
* Guards every check-then-write on an MFA device. Assignment is the reason it has to exist:
|
||||
* EnableMFADevice reads the device to confirm it is unassigned and reads the user's device
|
||||
@@ -241,6 +263,7 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
|
||||
storageFactory.create("iam", "iam-org-root-features.json", new TypeReference<>() {}),
|
||||
storageFactory.create("iam", "iam-credential-reports.json", new TypeReference<>() {}),
|
||||
storageFactory.create("iam", "iam-virtual-mfa-devices.json", new TypeReference<>() {}),
|
||||
storageFactory.create("iam", "iam-server-certificates.json", new TypeReference<>() {}),
|
||||
regionResolver,
|
||||
config.services().iam().seedDeployerPrincipal(),
|
||||
config.services().iam().accountAlias().orElse(null)
|
||||
@@ -270,8 +293,8 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
|
||||
this(users, groups, roles, policies, accessKeys, instanceProfiles, sessions,
|
||||
new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(),
|
||||
new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(),
|
||||
new InMemoryStorage<>(), new InMemoryStorage<>(), regionResolver,
|
||||
seedDeployerPrincipal, null);
|
||||
new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(),
|
||||
regionResolver, seedDeployerPrincipal, null);
|
||||
}
|
||||
|
||||
// 8-backend constructor (no org-root-features): kept for existing callers/tests;
|
||||
@@ -293,7 +316,8 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
|
||||
this(users, groups, roles, policies, accessKeys, instanceProfiles, sessions,
|
||||
accountAliases, passwordPolicies, new InMemoryStorage<>(), oidcProviders,
|
||||
serviceLinkedRoleDeletions, new InMemoryStorage<>(), new InMemoryStorage<>(),
|
||||
new InMemoryStorage<>(), regionResolver, seedDeployerPrincipal, seededAccountAlias);
|
||||
new InMemoryStorage<>(), new InMemoryStorage<>(), regionResolver,
|
||||
seedDeployerPrincipal, seededAccountAlias);
|
||||
}
|
||||
|
||||
// 9-backend constructor (no alias/OIDC/SLR backends): kept for existing callers/tests;
|
||||
@@ -312,8 +336,8 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
|
||||
this(users, groups, roles, policies, accessKeys, instanceProfiles, sessions,
|
||||
new InMemoryStorage<>(), passwordPolicies, new InMemoryStorage<>(),
|
||||
new InMemoryStorage<>(), new InMemoryStorage<>(), orgRootFeatures,
|
||||
new InMemoryStorage<>(), new InMemoryStorage<>(), regionResolver,
|
||||
seedDeployerPrincipal, null);
|
||||
new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(),
|
||||
regionResolver, seedDeployerPrincipal, null);
|
||||
}
|
||||
|
||||
IamService(StorageBackend<String, IamUser> users,
|
||||
@@ -331,6 +355,7 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
|
||||
StorageBackend<String, OrganizationRootFeatures> orgRootFeatures,
|
||||
StorageBackend<String, CredentialReport> credentialReports,
|
||||
StorageBackend<String, VirtualMfaDevice> virtualMfaDevices,
|
||||
StorageBackend<String, ServerCertificate> serverCertificates,
|
||||
RegionResolver regionResolver,
|
||||
boolean seedDeployerPrincipal,
|
||||
String seededAccountAlias) {
|
||||
@@ -349,6 +374,7 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
|
||||
this.orgRootFeatures = orgRootFeatures;
|
||||
this.credentialReports = credentialReports;
|
||||
this.virtualMfaDevices = virtualMfaDevices;
|
||||
this.serverCertificates = serverCertificates;
|
||||
this.regionResolver = regionResolver;
|
||||
this.seedDeployerPrincipal = seedDeployerPrincipal;
|
||||
this.seededAccountAlias = seededAccountAlias;
|
||||
@@ -1213,9 +1239,8 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
|
||||
* keys; quota values are cross-checked against AWS's published IAM service quotas
|
||||
* (docs.aws.amazon.com/general/latest/gr/iam-service.html), though floci itself enforces
|
||||
* only the 5-versions-per-policy cap in {@link #createPolicyVersion}. Resources floci does
|
||||
* not track at all (server certificates, account password - stub-empty elsewhere in this
|
||||
* handler) are reported as zero rather than omitted, so callers indexing into the full AWS
|
||||
* field set don't hit a missing-key error.
|
||||
* not track at all (the account password) are reported as zero rather than omitted, so
|
||||
* callers indexing into the full AWS field set don't hit a missing-key error.
|
||||
*/
|
||||
public Map<String, Long> getAccountSummary() {
|
||||
long localPolicyCount = 0;
|
||||
@@ -1253,7 +1278,7 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
|
||||
summary.put("RolePolicySizeQuota", 10240L);
|
||||
summary.put("AccessKeysPerUserQuota", 2L);
|
||||
summary.put("SigningCertificatesPerUserQuota", 2L);
|
||||
summary.put("ServerCertificates", 0L);
|
||||
summary.put("ServerCertificates", (long) serverCertificates.scan(k -> true).size());
|
||||
summary.put("ServerCertificatesQuota", 20L);
|
||||
summary.put("Providers", (long) oidcProviders.scan(k -> true).size());
|
||||
List<VirtualMfaDevice> mfaDevices = virtualMfaDevices.scan(k -> true);
|
||||
@@ -2036,6 +2061,235 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
|
||||
}
|
||||
}
|
||||
|
||||
// Server certificates
|
||||
// =========================================================================
|
||||
|
||||
/**
|
||||
* Stores an uploaded server certificate. The PEM material is really parsed and the key really
|
||||
* checked against the certificate, so a caller cannot store something unusable: AWS models
|
||||
* MalformedCertificate and KeyPairMismatch on this operation, and neither can be answered
|
||||
* without reading the material. {@code Expiration} is read off the certificate rather than
|
||||
* stored separately, so it cannot drift from what it describes.
|
||||
*/
|
||||
public ServerCertificate uploadServerCertificate(String name, String path, String certificateBody,
|
||||
String privateKeyPem, String certificateChain,
|
||||
Map<String, String> tags) {
|
||||
validateIamResourceName(name, "ServerCertificateName");
|
||||
validateIamPath(path, "Path");
|
||||
if (certificateBody == null || certificateBody.isBlank()) {
|
||||
throw new AwsException("ValidationError",
|
||||
"The request must contain the parameter CertificateBody.", 400);
|
||||
}
|
||||
if (privateKeyPem == null || privateKeyPem.isBlank()) {
|
||||
throw new AwsException("ValidationError",
|
||||
"The request must contain the parameter PrivateKey.", 400);
|
||||
}
|
||||
// Length before parsing: an over-long body is a request-shape error, and rejecting it here
|
||||
// keeps a multi-megabyte string from reaching the PEM reader at all.
|
||||
checkMaterialLength(certificateBody, "CertificateBody", MAX_CERTIFICATE_BODY_LENGTH);
|
||||
checkMaterialLength(privateKeyPem, "PrivateKey", MAX_CERTIFICATE_BODY_LENGTH);
|
||||
checkMaterialLength(certificateChain, "CertificateChain", MAX_CERTIFICATE_CHAIN_LENGTH);
|
||||
if (tags != null && tags.size() > MAX_TAGS_PER_RESOURCE) {
|
||||
throw new AwsException("LimitExceeded",
|
||||
"Cannot exceed quota for TagsPerServerCertificate: " + MAX_TAGS_PER_RESOURCE, 409);
|
||||
}
|
||||
X509Certificate certificate = parseUploadedCertificate(certificateBody, "CertificateBody");
|
||||
if (certificateChain != null) {
|
||||
// An omitted chain is fine, an empty one is not: certificateChainType has a minimum
|
||||
// of 1, so a present-but-empty value breaks the request shape. Anything longer is
|
||||
// parsed, which is what makes a whitespace-only chain a malformed certificate rather
|
||||
// than silently storing no chain at all.
|
||||
if (certificateChain.isEmpty()) {
|
||||
throw new AwsException("ValidationError",
|
||||
"1 validation error detected: Value at 'CertificateChain' failed to satisfy "
|
||||
+ "constraint: Member must have length greater than or equal to 1", 400);
|
||||
}
|
||||
parseUploadedChain(certificateChain);
|
||||
}
|
||||
PrivateKey privateKey;
|
||||
try {
|
||||
privateKey = Pem.parsePrivateKey(privateKeyPem);
|
||||
} catch (CertificateMaterialException e) {
|
||||
// The key itself is unreadable, which AWS reports as a malformed certificate too:
|
||||
// MalformedCertificate covers the uploaded material, not only the certificate body.
|
||||
throw new AwsException("MalformedCertificate",
|
||||
"The private key is not a valid PEM private key.", 400);
|
||||
}
|
||||
boolean matches;
|
||||
try {
|
||||
matches = Pem.isPair(privateKey, certificate.getPublicKey());
|
||||
} catch (Exception e) {
|
||||
// A key and certificate of different algorithms cannot be compared by signing, which
|
||||
// is itself a mismatch rather than a server-side failure.
|
||||
LOG.debugv("Server certificate key pair could not be verified: {0}", e.getMessage());
|
||||
matches = false;
|
||||
}
|
||||
if (!matches) {
|
||||
throw new AwsException("KeyPairMismatch",
|
||||
"The public key certificate and the private key do not match.", 400);
|
||||
}
|
||||
|
||||
String normalizedPath = normalizePath(path);
|
||||
ServerCertificate stored = new ServerCertificate();
|
||||
stored.setServerCertificateName(name);
|
||||
stored.setServerCertificateId("ASCA" + randomId(16));
|
||||
stored.setPath(normalizedPath);
|
||||
stored.setArn(iamArn("server-certificate", normalizedPath, name));
|
||||
stored.setCertificateBody(certificateBody);
|
||||
stored.setPrivateKey(privateKeyPem);
|
||||
stored.setCertificateChain(certificateChain);
|
||||
stored.setExpiration(certificate.getNotAfter().toInstant());
|
||||
stored.setTags(tags);
|
||||
synchronized (serverCertificateLock) {
|
||||
if (containsNameIgnoreCase(serverCertificates, ServerCertificate::getServerCertificateName, name)) {
|
||||
throw new AwsException("EntityAlreadyExists",
|
||||
"The Server Certificate with name " + name + " already exists.", 409);
|
||||
}
|
||||
// Counted under the same lock as the write, so concurrent uploads cannot both see
|
||||
// room for one more and together exceed the quota.
|
||||
if (serverCertificates.scan(k -> true).size() >= MAX_SERVER_CERTIFICATES) {
|
||||
throw new AwsException("LimitExceeded",
|
||||
"Cannot exceed quota for ServerCertificatesPerAccount: "
|
||||
+ MAX_SERVER_CERTIFICATES, 409);
|
||||
}
|
||||
serverCertificates.put(name, stored);
|
||||
}
|
||||
LOG.infov("Uploaded IAM server certificate: {0}", name);
|
||||
return stored;
|
||||
}
|
||||
|
||||
private void checkMaterialLength(String value, String paramName, int limit) {
|
||||
if (value != null && value.length() > limit) {
|
||||
throw new AwsException("ValidationError",
|
||||
"1 validation error detected: Value at '" + paramName
|
||||
+ "' failed to satisfy constraint: Member must have length less than "
|
||||
+ "or equal to " + limit, 400);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Every certificate in an uploaded chain, not just the first. A PEM reader stops at the first
|
||||
* block, so checking the chain with one call would store a chain whose later certificates are
|
||||
* unreadable and only surface them when something tried to use it.
|
||||
*/
|
||||
private void parseUploadedChain(String chainPem) {
|
||||
int blocks = 0;
|
||||
for (String block : chainPem.split("(?<=-----END CERTIFICATE-----)")) {
|
||||
if (block.isBlank()) {
|
||||
continue;
|
||||
}
|
||||
parseUploadedCertificate(block, "CertificateChain");
|
||||
blocks++;
|
||||
}
|
||||
if (blocks == 0) {
|
||||
throw new AwsException("MalformedCertificate",
|
||||
"CertificateChain is not a valid PEM certificate.", 400);
|
||||
}
|
||||
}
|
||||
|
||||
/** Parses uploaded PEM, reporting AWS's MalformedCertificate rather than a parse exception. */
|
||||
private X509Certificate parseUploadedCertificate(String pem, String paramName) {
|
||||
try {
|
||||
return Pem.parseCertificate(pem);
|
||||
} catch (CertificateMaterialException e) {
|
||||
LOG.debugv("Rejected unparseable {0}: {1}", paramName, e.getMessage());
|
||||
throw new AwsException("MalformedCertificate",
|
||||
paramName + " is not a valid PEM certificate.", 400);
|
||||
}
|
||||
}
|
||||
|
||||
/** The certificate, when one is stored under that name, for callers that must not throw. */
|
||||
public Optional<ServerCertificate> findServerCertificate(String name) {
|
||||
return name == null ? Optional.empty() : serverCertificates.get(name);
|
||||
}
|
||||
|
||||
public ServerCertificate getServerCertificate(String name) {
|
||||
validateIamResourceName(name, "ServerCertificateName");
|
||||
return serverCertificates.get(name)
|
||||
.orElseThrow(() -> new AwsException("NoSuchEntity",
|
||||
"The Server Certificate with name " + name + " cannot be found.", 404));
|
||||
}
|
||||
|
||||
public List<ServerCertificate> listServerCertificates(String pathPrefix) {
|
||||
String prefix = pathPrefix != null && !pathPrefix.isEmpty() ? pathPrefix : "/";
|
||||
return serverCertificates.scan(k -> true).stream()
|
||||
.filter(c -> c.getPath().startsWith(prefix))
|
||||
.sorted(Comparator.comparing(ServerCertificate::getServerCertificateName))
|
||||
.toList();
|
||||
}
|
||||
|
||||
/**
|
||||
* Renames or moves a server certificate. The stored material is untouched, so the certificate
|
||||
* keeps its id and expiry; only the name, path and the ARN built from them change.
|
||||
*/
|
||||
public ServerCertificate updateServerCertificate(String name, String newName, String newPath) {
|
||||
validateIamResourceName(name, "ServerCertificateName");
|
||||
if (newName != null) {
|
||||
validateIamResourceName(newName, "NewServerCertificateName");
|
||||
}
|
||||
validateIamPath(newPath, "NewPath");
|
||||
synchronized (serverCertificateLock) {
|
||||
ServerCertificate existing = getServerCertificate(name);
|
||||
String targetName = newName != null ? newName : name;
|
||||
// Excluded by id, not by name: a rename that only changes case would otherwise match
|
||||
// the certificate against itself, the same reason updateUser compares user ids here.
|
||||
boolean taken = resourcesInCurrentAccount(serverCertificates)
|
||||
.filter(other -> !other.getServerCertificateId().equals(existing.getServerCertificateId()))
|
||||
.anyMatch(other -> other.getServerCertificateName().equalsIgnoreCase(targetName));
|
||||
if (taken) {
|
||||
throw new AwsException("EntityAlreadyExists",
|
||||
"The Server Certificate with name " + targetName + " already exists.", 409);
|
||||
}
|
||||
if (newPath != null) {
|
||||
existing.setPath(normalizePath(newPath));
|
||||
}
|
||||
existing.setServerCertificateName(targetName);
|
||||
existing.setArn(iamArnBeside(existing.getArn(), "server-certificate",
|
||||
existing.getPath(), targetName));
|
||||
if (!targetName.equals(name)) {
|
||||
serverCertificates.delete(name);
|
||||
}
|
||||
serverCertificates.put(targetName, existing);
|
||||
return existing;
|
||||
}
|
||||
}
|
||||
|
||||
public void deleteServerCertificate(String name) {
|
||||
validateIamResourceName(name, "ServerCertificateName");
|
||||
synchronized (serverCertificateLock) {
|
||||
getServerCertificate(name);
|
||||
serverCertificates.delete(name);
|
||||
}
|
||||
LOG.infov("Deleted IAM server certificate: {0}", name);
|
||||
}
|
||||
|
||||
public void tagServerCertificate(String name, Map<String, String> newTags) {
|
||||
validateIamResourceName(name, "ServerCertificateName");
|
||||
synchronized (serverCertificateLock) {
|
||||
ServerCertificate certificate = getServerCertificate(name);
|
||||
certificate.setTags(mergeTagsWithinQuota(certificate.getTags(), newTags,
|
||||
"TagsPerServerCertificate", false));
|
||||
serverCertificates.put(certificate.getServerCertificateName(), certificate);
|
||||
}
|
||||
}
|
||||
|
||||
public void untagServerCertificate(String name, List<String> tagKeys) {
|
||||
validateIamResourceName(name, "ServerCertificateName");
|
||||
synchronized (serverCertificateLock) {
|
||||
ServerCertificate certificate = getServerCertificate(name);
|
||||
Map<String, String> remaining = new LinkedHashMap<>(certificate.getTags());
|
||||
if (tagKeys != null) {
|
||||
tagKeys.forEach(remaining::remove);
|
||||
}
|
||||
certificate.setTags(remaining);
|
||||
serverCertificates.put(certificate.getServerCertificateName(), certificate);
|
||||
}
|
||||
}
|
||||
|
||||
public Map<String, String> listServerCertificateTags(String name) {
|
||||
return getServerCertificate(name).getTags();
|
||||
}
|
||||
|
||||
// Virtual MFA devices
|
||||
// =========================================================================
|
||||
|
||||
|
||||
@@ -3,8 +3,11 @@ package io.github.hectorvent.floci.services.iam;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import io.github.hectorvent.floci.core.common.AwsArnUtils;
|
||||
import io.github.hectorvent.floci.core.common.AwsQueryServiceResolver;
|
||||
import io.github.hectorvent.floci.core.common.AwsRegions;
|
||||
import io.github.hectorvent.floci.services.iam.model.ServerCertificate;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.enterprise.inject.Instance;
|
||||
import jakarta.inject.Inject;
|
||||
import jakarta.ws.rs.container.ContainerRequestContext;
|
||||
|
||||
@@ -27,15 +30,34 @@ import java.util.Set;
|
||||
@ApplicationScoped
|
||||
public class ResourceArnBuilder {
|
||||
|
||||
/**
|
||||
* The IAM actions whose resource this builder can name. Deliberately only the
|
||||
* server-certificate operations; see {@link #buildIamArn}.
|
||||
*/
|
||||
private static final Set<String> SERVER_CERTIFICATE_ACTIONS = Set.of(
|
||||
"UploadServerCertificate", "GetServerCertificate", "UpdateServerCertificate",
|
||||
"DeleteServerCertificate", "TagServerCertificate", "UntagServerCertificate",
|
||||
"ListServerCertificateTags");
|
||||
|
||||
private final ObjectMapper objectMapper;
|
||||
/**
|
||||
* Looked up lazily through a provider: this builder is constructed by the enforcement filter,
|
||||
* which IamService itself does not depend on, and a direct injection would close that loop.
|
||||
*/
|
||||
private final Instance<IamService> iamService;
|
||||
|
||||
@Inject
|
||||
public ResourceArnBuilder(ObjectMapper objectMapper) {
|
||||
public ResourceArnBuilder(ObjectMapper objectMapper, Instance<IamService> iamService) {
|
||||
this.objectMapper = objectMapper;
|
||||
this.iamService = iamService;
|
||||
}
|
||||
|
||||
public ResourceArnBuilder() {
|
||||
this(new ObjectMapper());
|
||||
this(new ObjectMapper(), null);
|
||||
}
|
||||
|
||||
public ResourceArnBuilder(ObjectMapper objectMapper) {
|
||||
this(objectMapper, null);
|
||||
}
|
||||
|
||||
public String build(String credentialScope, ContainerRequestContext ctx,
|
||||
@@ -60,10 +82,82 @@ public class ResourceArnBuilder {
|
||||
case "secretsmanager" -> List.of(buildSecretsManagerArn(ctx, region, accountId));
|
||||
case "ssm" -> List.of(buildSsmArn(ctx, region, accountId));
|
||||
case "kms" -> List.of(buildKmsArn(path, region, accountId));
|
||||
case "iam" -> List.of(buildIamArn(ctx, region, accountId));
|
||||
default -> List.of("*");
|
||||
};
|
||||
}
|
||||
|
||||
// ── IAM ─────────────────────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* IAM resource ARNs are only built for the server-certificate operations. Every other IAM
|
||||
* action still resolves to {@code *}, so a policy naming a specific user, role, policy or MFA
|
||||
* device does not constrain it. That is how IAM behaved before server certificates existed,
|
||||
* and closing it for the rest means mapping the resource of every dispatched IAM action, which
|
||||
* is its own change rather than a side effect of this one: tracked in issue 4979, and
|
||||
* described in docs/services/iam.md.
|
||||
*
|
||||
* <p>The operation is resolved through {@link AwsQueryServiceResolver#action(String, String)},
|
||||
* so the legacy {@code Operation} parameter names the resource exactly as {@code Action} does.
|
||||
* Reading {@code Action} alone would let a caller spell the operation the other way and have
|
||||
* the request evaluated against {@code *}, skipping a deny that names the certificate.
|
||||
*
|
||||
* <p>The path is taken from the stored certificate when one exists: a policy names the full
|
||||
* ARN, path included, and only the store knows the path.
|
||||
*/
|
||||
private String buildIamArn(ContainerRequestContext ctx, String region, String accountId) {
|
||||
String action = AwsQueryServiceResolver.action(
|
||||
RequestBodyReader.formField(ctx, "Action"),
|
||||
RequestBodyReader.formField(ctx, "Operation"));
|
||||
if (action == null || !SERVER_CERTIFICATE_ACTIONS.contains(action)) {
|
||||
return "*";
|
||||
}
|
||||
String name = RequestBodyReader.formField(ctx, "ServerCertificateName");
|
||||
if (name == null || name.isBlank()) {
|
||||
return "*";
|
||||
}
|
||||
// Every operation but the upload acts on a certificate that already exists, so the check
|
||||
// uses that certificate's own stored ARN instead of deriving one again. The stored ARN
|
||||
// carries the path and, more to the point, the partition the certificate was created in:
|
||||
// a resource stays in its partition, so re-minting from the caller's signing region would
|
||||
// name an ARN that no resource has and leave a deny on the real one unmatched.
|
||||
if (!"UploadServerCertificate".equals(action)) {
|
||||
return storedServerCertificateArn(name);
|
||||
}
|
||||
// An upload names a certificate that does not exist yet, so its ARN is minted from the
|
||||
// request: the path it asks for, in the partition it is being created in. Reading a stored
|
||||
// path here would authorize an upload to /team/ against the root path.
|
||||
String path = normalizeArnPath(RequestBodyReader.formField(ctx, "Path"));
|
||||
// IAM is global, so the ARN carries no region. Minted in the request's partition rather
|
||||
// than through a blank-region Arn.of, which would silently mean the commercial one.
|
||||
return AwsArnUtils.Arn.global(AwsRegions.partitionFor(region), "iam", accountId,
|
||||
"server-certificate" + path + name).toString();
|
||||
}
|
||||
|
||||
/** A request's Path as it appears in an ARN: slash-delimited, defaulting to a bare slash. */
|
||||
private static String normalizeArnPath(String path) {
|
||||
if (path == null || path.isBlank()) {
|
||||
return "/";
|
||||
}
|
||||
String normalized = path.startsWith("/") ? path : "/" + path;
|
||||
return normalized.endsWith("/") ? normalized : normalized + "/";
|
||||
}
|
||||
|
||||
/**
|
||||
* The certificate's own ARN as stored, or {@code *} when this account has no certificate of
|
||||
* that name: the operation fails as NoSuchEntity either way, and minting an ARN for a resource
|
||||
* that is not there would only offer a policy something to match.
|
||||
*/
|
||||
private String storedServerCertificateArn(String name) {
|
||||
if (iamService == null) {
|
||||
return "*";
|
||||
}
|
||||
return iamService.get().findServerCertificate(name)
|
||||
.map(ServerCertificate::getArn)
|
||||
.filter(arn -> !arn.isBlank())
|
||||
.orElse("*");
|
||||
}
|
||||
|
||||
// ── S3 ──────────────────────────────────────────────────────────────────────
|
||||
// Minted in the request's partition; IamEnforcementFilter re-mints an existing bucket's ARN
|
||||
// in the bucket's own partition through S3ResourcePolicyProvider before any policy sees it.
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
package io.github.hectorvent.floci.services.iam.model;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
|
||||
import io.quarkus.runtime.annotations.RegisterForReflection;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
/**
|
||||
* An IAM server certificate: a PEM certificate, its private key and an optional chain, stored under
|
||||
* a name unique within the account.
|
||||
*
|
||||
* <p>{@code expiration} is read off the certificate's {@code notAfter} at upload rather than stored
|
||||
* independently, so it cannot drift from the certificate it describes.
|
||||
*/
|
||||
@RegisterForReflection
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
public class ServerCertificate {
|
||||
private String serverCertificateName;
|
||||
private String serverCertificateId;
|
||||
private String path = "/";
|
||||
private String arn;
|
||||
private String certificateBody;
|
||||
/** PEM private key. Never echoed back: no AWS reader returns it once uploaded. */
|
||||
private String privateKey;
|
||||
/** Optional, and absent rather than empty when the upload omitted it. */
|
||||
private String certificateChain;
|
||||
private Instant uploadDate = Instant.now();
|
||||
/** The certificate's own {@code notAfter}. */
|
||||
private Instant expiration;
|
||||
private Map<String, String> tags = new ConcurrentHashMap<>();
|
||||
|
||||
public ServerCertificate() {}
|
||||
|
||||
public String getServerCertificateName() { return serverCertificateName; }
|
||||
public void setServerCertificateName(String serverCertificateName) {
|
||||
this.serverCertificateName = serverCertificateName;
|
||||
}
|
||||
public String getServerCertificateId() { return serverCertificateId; }
|
||||
public void setServerCertificateId(String serverCertificateId) {
|
||||
this.serverCertificateId = serverCertificateId;
|
||||
}
|
||||
public String getPath() { return path; }
|
||||
public void setPath(String path) { this.path = path; }
|
||||
public String getArn() { return arn; }
|
||||
public void setArn(String arn) { this.arn = arn; }
|
||||
public String getCertificateBody() { return certificateBody; }
|
||||
public void setCertificateBody(String certificateBody) { this.certificateBody = certificateBody; }
|
||||
public String getPrivateKey() { return privateKey; }
|
||||
public void setPrivateKey(String privateKey) { this.privateKey = privateKey; }
|
||||
public String getCertificateChain() { return certificateChain; }
|
||||
public void setCertificateChain(String certificateChain) { this.certificateChain = certificateChain; }
|
||||
public Instant getUploadDate() { return uploadDate; }
|
||||
public void setUploadDate(Instant uploadDate) { this.uploadDate = uploadDate; }
|
||||
public Instant getExpiration() { return expiration; }
|
||||
public void setExpiration(Instant expiration) { this.expiration = expiration; }
|
||||
public Map<String, String> getTags() { return tags; }
|
||||
public void setTags(Map<String, String> tags) {
|
||||
this.tags = tags == null ? new ConcurrentHashMap<>() : new ConcurrentHashMap<>(tags);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user