mirror of
https://github.com/floci-io/floci.git
synced 2026-11-27 07:39:24 -05:00
refactor: read and check ARNs through AwsArnUtils in IAM, KMS, EC2, SSO and the core condition resolvers (#6969)
The arn-probe, arn-split and arn-concat sites in these files now go through looksLikeArn, isArn, parse, accountOrDefault and regionOrDefault instead of startsWith("arn:") and split(":"). A well-formed ARN reads the same as before. tools/partition/baseline.tsv drops from 24 to 0, the last baselined sites, and AGENTS.md no longer says the arn-* categories have any.
Signed-off-by: Hector Ventura <hectorvent@gmail.com>
This commit is contained in:
1 parent
0d02528d43
commit
4d3f3b664d
11 files changed
+44
-58
No files matched your search
+2
-10
@@ -271,7 +271,7 @@ public class IamConditionContextResolver {
|
||||
// the owner has to come from service state. When neither source knows it, the key is left
|
||||
// out rather than guessed: an absent key fails a Condition that tests it, whereas a wrong
|
||||
// one would silently authorize cross-account access the policy meant to refuse.
|
||||
String resourceAccount = accountFromArn(resourceArn);
|
||||
String resourceAccount = AwsArnUtils.accountOrDefault(resourceArn, null);
|
||||
if (resourceAccount == null || resourceAccount.isBlank()) {
|
||||
resourceAccount = resourceOwnerAccountId;
|
||||
}
|
||||
@@ -308,21 +308,13 @@ public class IamConditionContextResolver {
|
||||
&& AwsArnUtils.isArnFor(resourceArn, "sns")) {
|
||||
putIfPresent(conditions, "aws:SourceOwner", sourceAccount);
|
||||
}
|
||||
String resourceAccount = accountFromArn(resourceArn);
|
||||
String resourceAccount = AwsArnUtils.accountOrDefault(resourceArn, null);
|
||||
putIfPresent(conditions, "aws:ResourceAccount",
|
||||
resourceAccount == null || resourceAccount.isBlank() ? resourceOwnerAccountId : resourceAccount);
|
||||
putIfPresent(conditions, "aws:RequestedRegion", AwsArnUtils.regionOrDefault(resourceArn, null));
|
||||
return conditions;
|
||||
}
|
||||
|
||||
private static String accountFromArn(String arn) {
|
||||
if (arn == null || !arn.startsWith("arn:")) {
|
||||
return null;
|
||||
}
|
||||
String[] segments = arn.split(":", 6);
|
||||
return segments.length > 4 ? segments[4] : null;
|
||||
}
|
||||
|
||||
private static void putIfPresent(Map<String, List<String>> conditions, String key, String value) {
|
||||
if (value != null && !value.isBlank()) {
|
||||
conditions.put(key, List.of(value));
|
||||
|
||||
@@ -400,7 +400,7 @@ final class PassedRoles {
|
||||
List<String> arns = new ArrayList<>();
|
||||
for (String role : roles) {
|
||||
if (!role.isBlank()) {
|
||||
arns.add(role.startsWith("arn:") ? role
|
||||
arns.add(AwsArnUtils.looksLikeArn(role) ? role
|
||||
: lookups.heldRoleArn(role).orElseGet(() -> lookups.roleArn(role)));
|
||||
}
|
||||
}
|
||||
@@ -587,7 +587,7 @@ final class PassedRoles {
|
||||
List<String> arns = new ArrayList<>();
|
||||
for (String role : roles) {
|
||||
if (!role.isBlank()) {
|
||||
arns.add(role.startsWith("arn:") ? role : lookups.roleArn(role));
|
||||
arns.add(AwsArnUtils.looksLikeArn(role) ? role : lookups.roleArn(role));
|
||||
}
|
||||
}
|
||||
return passed(arns, service);
|
||||
|
||||
@@ -109,26 +109,35 @@ final class Ec2InstanceCredentials {
|
||||
return heldProfile(arn)
|
||||
.filter(profile -> profile.getRoleNames() != null && profile.getRoleNames().size() == 1)
|
||||
.flatMap(profile -> {
|
||||
String[] parts = arn.split(":", 6);
|
||||
return iam.findRole(parts[4], profile.getRoleNames().getFirst())
|
||||
.filter(role -> role.getArn() != null && role.getArn().startsWith(
|
||||
"arn:" + parts[1] + ":iam::" + parts[4] + ":role/"))
|
||||
AwsArnUtils.Arn profileArn = AwsArnUtils.parse(arn);
|
||||
return iam.findRole(profileArn.accountId(), profile.getRoleNames().getFirst())
|
||||
.filter(role -> isRoleOf(role.getArn(), profileArn))
|
||||
.map(role -> new AttachedProfile(profile, role));
|
||||
});
|
||||
}
|
||||
|
||||
/** A role ARN in the profile's own partition and account. */
|
||||
private static boolean isRoleOf(String roleArn, AwsArnUtils.Arn profileArn) {
|
||||
if (!AwsArnUtils.isArn(roleArn)) {
|
||||
return false;
|
||||
}
|
||||
AwsArnUtils.Arn role = AwsArnUtils.parse(roleArn);
|
||||
return role.partition().equals(profileArn.partition()) && "iam".equals(role.service())
|
||||
&& role.region().isEmpty() && role.accountId().equals(profileArn.accountId())
|
||||
&& role.resource().startsWith("role/");
|
||||
}
|
||||
|
||||
private Optional<InstanceProfile> heldProfile(String arn) {
|
||||
if (arn == null) {
|
||||
if (!AwsArnUtils.isArn(arn)) {
|
||||
return Optional.empty();
|
||||
}
|
||||
String[] parts = arn.split(":", 6);
|
||||
if (parts.length != 6 || !"arn".equals(parts[0]) || !"iam".equals(parts[2])
|
||||
|| !parts[3].isEmpty() || !parts[4].matches("[0-9]{12}")
|
||||
|| !parts[5].startsWith("instance-profile/")) {
|
||||
AwsArnUtils.Arn parsed = AwsArnUtils.parse(arn);
|
||||
if (!"iam".equals(parsed.service()) || !parsed.region().isEmpty()
|
||||
|| !parsed.accountId().matches("[0-9]{12}") || !parsed.resource().startsWith("instance-profile/")) {
|
||||
return Optional.empty();
|
||||
}
|
||||
String name = arn.substring(arn.lastIndexOf('/') + 1);
|
||||
return iam.findInstanceProfile(parts[4], name).filter(profile -> arn.equals(profile.getArn()));
|
||||
return iam.findInstanceProfile(parsed.accountId(), name).filter(profile -> arn.equals(profile.getArn()));
|
||||
}
|
||||
|
||||
synchronized Optional<SessionCredential> get(Instance instance, String roleName, Instant now) {
|
||||
@@ -157,7 +166,7 @@ final class Ec2InstanceCredentials {
|
||||
}
|
||||
}
|
||||
IamRole role = resolved.get();
|
||||
String account = role.getArn().split(":", 6)[4];
|
||||
String account = AwsArnUtils.parse(role.getArn()).accountId();
|
||||
SessionCredential session = new SessionCredential(newAccessKey(), randomString(30), randomString(48),
|
||||
role.getArn(), now.plusSeconds(3600), null, account);
|
||||
session.setEc2InstanceId(instance.getInstanceId());
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
package io.github.hectorvent.floci.services.iam;
|
||||
|
||||
import io.github.hectorvent.floci.core.common.AwsArnUtils;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.util.HashSet;
|
||||
@@ -52,8 +53,7 @@ public final class PublicAccessConditions {
|
||||
|
||||
/** An ARN of six fields whose account has no wildcard. */
|
||||
public static boolean pinsAccount(String arn) {
|
||||
String[] fields = arn.split(":", 6);
|
||||
return fields.length == 6 && !hasWildcard(fields[4]);
|
||||
return AwsArnUtils.isArn(arn) && !hasWildcard(AwsArnUtils.parse(arn).accountId());
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -241,7 +241,7 @@ public class ResourceArnBuilder {
|
||||
if (group.isEmpty()) {
|
||||
return "*";
|
||||
}
|
||||
return group.startsWith("arn:") ? group
|
||||
return AwsArnUtils.looksLikeArn(group) ? group
|
||||
: AwsArnUtils.Arn.of("resource-groups", region, accountId, "group/" + group).toString();
|
||||
}
|
||||
|
||||
@@ -1103,7 +1103,7 @@ public class ResourceArnBuilder {
|
||||
|
||||
/** An identifier's name: an ARN's part after its last {@code :}, as the MicroVM service unwraps it. */
|
||||
private static String trailingName(String identifier) {
|
||||
return identifier.startsWith("arn:") ? identifier.substring(identifier.lastIndexOf(':') + 1) : identifier;
|
||||
return AwsArnUtils.looksLikeArn(identifier) ? identifier.substring(identifier.lastIndexOf(':') + 1) : identifier;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -1128,7 +1128,7 @@ public class ResourceArnBuilder {
|
||||
type + tagged.substring(tagged.lastIndexOf(':') + 1)).toString();
|
||||
}
|
||||
}
|
||||
if (!tagged.startsWith("arn:")) {
|
||||
if (!AwsArnUtils.looksLikeArn(tagged)) {
|
||||
return "*";
|
||||
}
|
||||
try {
|
||||
@@ -1355,7 +1355,7 @@ public class ResourceArnBuilder {
|
||||
/** The ARN a shared tagging route names, or {@code *} for any other route. */
|
||||
private String taggedResource(ContainerRequestContext ctx) {
|
||||
String arn = taggedArn(ctx);
|
||||
return arn != null && arn.startsWith("arn:") ? arn : "*";
|
||||
return AwsArnUtils.looksLikeArn(arn) ? arn : "*";
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -1406,7 +1406,7 @@ public class ResourceArnBuilder {
|
||||
String rest = path.substring("/2025-03-07/".length());
|
||||
if (rest.startsWith("tags/") || rest.startsWith("resource-policy/")) {
|
||||
String arn = rest.substring(rest.indexOf('/') + 1);
|
||||
return arn.startsWith("arn:") ? arn : "*";
|
||||
return AwsArnUtils.looksLikeArn(arn) ? arn : "*";
|
||||
}
|
||||
if (!rest.startsWith("web-functions/")) {
|
||||
return "*";
|
||||
@@ -1416,7 +1416,7 @@ public class ResourceArnBuilder {
|
||||
return "*";
|
||||
}
|
||||
String functionArn;
|
||||
if (segments.getFirst().startsWith("arn:") && segments.size() > 1) {
|
||||
if (AwsArnUtils.looksLikeArn(segments.getFirst()) && segments.size() > 1) {
|
||||
// A function ARN carries one slash: arn:...:web-function/<name>.
|
||||
functionArn = segments.get(0) + "/" + segments.get(1);
|
||||
segments.subList(0, 2).clear();
|
||||
@@ -1428,7 +1428,7 @@ public class ResourceArnBuilder {
|
||||
if (segments.size() >= 2 && ("revisions".equals(segments.get(0)) || "endpoints".equals(segments.get(0)))) {
|
||||
String child = "revisions".equals(segments.get(0)) ? "revision" : "endpoint";
|
||||
String id = String.join("/", segments.subList(1, segments.size()));
|
||||
if (id.startsWith("arn:") && id.contains("/" + child + "/")) {
|
||||
if (AwsArnUtils.looksLikeArn(id) && id.contains("/" + child + "/")) {
|
||||
// A revision or endpoint ARN ends in its id: arn:...:web-function/<name>/revision/<id>.
|
||||
id = id.substring(id.lastIndexOf('/') + 1);
|
||||
}
|
||||
@@ -1446,7 +1446,7 @@ public class ResourceArnBuilder {
|
||||
private static boolean readsInTheAccountItNames(String path, String name,
|
||||
LambdaArnUtils.ResolvedFunctionRef ref,
|
||||
ContainerRequestContext ctx) {
|
||||
if (!"GET".equals(ctx.getMethod()) || !name.startsWith("arn:")) {
|
||||
if (!"GET".equals(ctx.getMethod()) || !AwsArnUtils.looksLikeArn(name)) {
|
||||
return false;
|
||||
}
|
||||
String route = path.substring(path.indexOf("/functions/" + name) + "/functions/".length() + name.length());
|
||||
|
||||
@@ -4,6 +4,7 @@ import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ArrayNode;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import io.github.hectorvent.floci.core.common.AwsArnUtils;
|
||||
import io.github.hectorvent.floci.core.common.AwsErrorResponse;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.common.RegionResolver;
|
||||
@@ -933,17 +934,12 @@ public class KmsJsonHandler {
|
||||
if (!"PRIMARY".equals(candidate.getMultiRegionKeyType())) {
|
||||
ObjectNode replica = replicas.addObject();
|
||||
replica.put("Arn", candidate.getArn());
|
||||
replica.put("Region", regionFromArn(candidate.getArn()));
|
||||
replica.put("Region", AwsArnUtils.regionOrDefault(candidate.getArn(), ""));
|
||||
}
|
||||
}
|
||||
return configuration;
|
||||
}
|
||||
|
||||
private static String regionFromArn(String arn) {
|
||||
String[] parts = arn.split(":", 6);
|
||||
return parts.length > 3 ? parts[3] : "";
|
||||
}
|
||||
|
||||
private static void addTags(ArrayNode array, KmsKey key) {
|
||||
key.getTags().forEach((keyName, value) -> {
|
||||
ObjectNode tag = array.addObject();
|
||||
|
||||
+3
-3
@@ -479,7 +479,7 @@ public class SecretsManagerService implements ResourceProvider {
|
||||
* included, however the request names the secret.
|
||||
*/
|
||||
public Optional<String> findArn(String accountId, String secretId, String region) {
|
||||
if (!secretId.startsWith("arn:")) {
|
||||
if (!AwsArnUtils.looksLikeArn(secretId)) {
|
||||
return findArnByName(accountId, secretId, region);
|
||||
}
|
||||
AwsArnUtils.Arn arn = parseOrNull(secretId);
|
||||
@@ -513,7 +513,7 @@ public class SecretsManagerService implements ResourceProvider {
|
||||
* addresses. Passing a name instead of an ARN would read the wrong account.
|
||||
*/
|
||||
public void markOwnedByService(String secretArn, String owningService) {
|
||||
if (secretArn == null || !secretArn.startsWith("arn:")) {
|
||||
if (!AwsArnUtils.looksLikeArn(secretArn)) {
|
||||
return;
|
||||
}
|
||||
AwsArnUtils.Arn arn;
|
||||
@@ -2021,7 +2021,7 @@ public class SecretsManagerService implements ResourceProvider {
|
||||
}
|
||||
|
||||
private Secret resolveSecret(String secretId, String region) {
|
||||
if (secretId.startsWith("arn:")) {
|
||||
if (AwsArnUtils.looksLikeArn(secretId)) {
|
||||
// 1. Exact full-ARN match
|
||||
List<Secret> found = store.scan(key -> {
|
||||
Secret s = store.get(key).orElse(null);
|
||||
|
||||
@@ -739,7 +739,7 @@ public class SsoAdminService implements Resettable {
|
||||
if (!kmsArnMatcher.matches() || !instance.primaryRegion().equals(kmsArnMatcher.group(1))) {
|
||||
throw validation("The customer managed KMS key must be in the IAM Identity Center primary Region.");
|
||||
}
|
||||
String kmsAccountId = kmsKeyArn.split(":", 6)[4];
|
||||
String kmsAccountId = AwsArnUtils.parse(kmsKeyArn).accountId();
|
||||
if (!instance.ownerAccountId().equals(kmsAccountId)) {
|
||||
throw validation("The customer managed KMS key must be owned by the IAM Identity Center instance account.");
|
||||
}
|
||||
|
||||
@@ -6,6 +6,7 @@ import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ArrayNode;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import io.github.hectorvent.floci.core.common.AwsArnUtils;
|
||||
import io.github.hectorvent.floci.core.common.Base64Url;
|
||||
import io.github.hectorvent.floci.core.common.RequestContext;
|
||||
import io.github.hectorvent.floci.services.ssoadmin.SsoAdminService;
|
||||
@@ -300,7 +301,7 @@ public class SsoOidcController {
|
||||
private void validateTokenExchangeTarget(JsonNode request, String targetApplicationArn) {
|
||||
String subjectToken = requiredText(request, "subjectToken");
|
||||
TokenSession subject = service.requireAccessToken(subjectToken);
|
||||
if (targetApplicationArn.equals(subject.clientId()) || !subject.clientId().startsWith("arn:")) {
|
||||
if (targetApplicationArn.equals(subject.clientId()) || !AwsArnUtils.looksLikeArn(subject.clientId())) {
|
||||
throw new SsoOidcException("invalid_grant", "Subject token must come from a different IAM application", 400);
|
||||
}
|
||||
boolean authorizedTarget = ssoAdminService.applicationAccessScopesForOidc(subject.clientId()).stream()
|
||||
@@ -370,7 +371,7 @@ public class SsoOidcController {
|
||||
throw new SsoOidcException("invalid_request", "code_challenge_method must be S256", 400);
|
||||
}
|
||||
AuthorizationCode authorization;
|
||||
if (clientId != null && clientId.startsWith("arn:")) {
|
||||
if (AwsArnUtils.looksLikeArn(clientId)) {
|
||||
ApplicationGrant grant = ssoAdminService.applicationGrantForOidc(clientId, "authorization_code");
|
||||
List<String> redirects = new ArrayList<>();
|
||||
grant.grant().path("AuthorizationCode").path("RedirectUris")
|
||||
|
||||
Reference in new issue
Block a user