Skip to content

armgit / floci

Public Imported from GitHub
0

Light, fluffy, and always free - The AWS Local Emulator alternative

fix(iot): resolve connect policy variables through the IAM resolver (#5827)

Priamo Germosencaa606ba7dc9
diff --git a/docs/services/iot.md b/docs/services/iot.md
index 4c2dd781e7..e622bcdd42 100644
--- a/docs/services/iot.md
+++ b/docs/services/iot.md
@@ -203,7 +203,7 @@ The connection is admitted when all of these hold, otherwise the broker answers
2. The certificate is `ACTIVE` and inside its validity dates.
3. The default versions of the policies attached to the certificate (`AttachPolicy` with the certificate ARN as target, in the certificate's own account and region) allow `iot:Connect` on `arn:aws:iot:<region>:<account>:client/<clientId>`. No attached policy means deny, and an explicit `Deny` wins.
-Policy variables are substituted and are also available as condition keys: `iot:ClientId`, `aws:SourceIp`, `iot:DomainName` (the server name the client sent in the TLS handshake, absent when it dialled an IP address), `iot:Connection.Thing.IsAttached` and, only when the client id names a thing attached to the certificate with `AttachThingPrincipal`, `iot:Connection.Thing.ThingName`, `iot:Connection.Thing.ThingTypeName` and `iot:Connection.Thing.Attributes[name]`. A statement that uses a variable Floci cannot resolve, such as the certificate variables `iot:Certificate.*`, matches nothing.
+The connection carries these condition keys: `iot:ClientId`, `aws:SourceIp`, `iot:DomainName` (the server name the client sent in the TLS handshake, absent when it dialled an IP address), `iot:Connection.Thing.IsAttached` and, only when the client id names a thing attached to the certificate with `AttachThingPrincipal`, `iot:Connection.Thing.ThingName`, `iot:Connection.Thing.ThingTypeName` and `iot:Connection.Thing.Attributes[name]`. They are also what the policy's own `${...}` resolves against, in the `Resource` and `Condition` elements and nowhere else, read by the same resolver as an IAM policy's variables: key names are case-insensitive, `${*}`, `${?}` and `${$}` stand for those three characters, and a variable with no value, the certificate variables `iot:Certificate.*` among them, leaves a `Resource` pattern matching no resource and a `Condition` value null. A document that does not declare `"Version": "2012-10-17"` has no variables at all, `${iot:ClientId}` there being the literal text it looks like.
Differences from AWS: AWS rejects an unregistered, inactive or expired certificate during the TLS handshake and closes an MQTT 3.1.1 connection it does not authorize without a `CONNACK`; Floci completes the handshake and always answers with the return code, so the reason is visible to the client. Deactivating the certificate or detaching the policy takes effect on the next connect; established sessions are not dropped. Policies attached to thing groups are not consulted, and exclusive thing attachment (`thingPrincipalType`) is not modelled: the thing is always the one named by the client id.
diff --git a/src/main/java/io/github/hectorvent/floci/services/iot/IotService.java b/src/main/java/io/github/hectorvent/floci/services/iot/IotService.java
index 06f99873f7..9feef1a229 100644
--- a/src/main/java/io/github/hectorvent/floci/services/iot/IotService.java
+++ b/src/main/java/io/github/hectorvent/floci/services/iot/IotService.java
@@ -6,7 +6,6 @@ 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 com.fasterxml.jackson.databind.node.TextNode;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.config.FlociCertificateAuthority;
import io.github.hectorvent.floci.core.common.AwsArnUtils;
@@ -86,8 +85,6 @@ public class IotService {
private static final Pattern THING_NAME_PATTERN = Pattern.compile("[a-zA-Z0-9:_-]{1,128}");
/** The {@code FirehoseSeparator} shape of the IoT API model. */
private static final Pattern FIREHOSE_SEPARATOR = Pattern.compile("([\\n\\t])|(\\r\\n)|(,)");
- /** An AWS policy variable such as {@code ${iot:ClientId}}. */
- private static final Pattern POLICY_VARIABLE = Pattern.compile("\\$\\{[^}]*\\}");
public static final int MAX_POLICY_VERSIONS = 5;
/** One lock for every policy version write and the policy delete, so a cap check, an append and a delete cannot interleave. */
@@ -484,8 +481,8 @@ public class IotService {
/**
* Decides {@code iot:Connect} for a client id the way AWS IoT does on a CONNECT: the certificate
* must be ACTIVE and within its validity dates, the policies are the default versions attached
- * to the certificate in its own account and region, and the connection's policy variables are
- * substituted and offered as condition keys. No policy means deny; an explicit deny wins.
+ * to the certificate in its own account and region, and the connection's policy variables go in
+ * as condition keys. No policy means deny; an explicit deny wins.
*/
public boolean isConnectAllowed(RegisteredDevice device, String clientId, String sourceIp, String domainName) {
IotCertificate certificate = device.certificate();
@@ -508,16 +505,24 @@ public class IotService {
regionResolver.getDefaultRegion(), regionResolver.getDefaultAccountId(), clientId);
}
+ /**
+ * Decides {@code iot:Connect} for the client ARN against the documents as they are written,
+ * with the connection's variables offered as condition keys. The {@code ${...}} placeholders
+ * are the evaluator's to resolve, from that same context, because the developer guide gives
+ * IoT no policy language of its own: its policies "follow the same conventions as IAM
+ * policies" and "the same policy evaluation logic", and a variable is one "that can be used
+ * in AWS IoT Core policies in the Resource or Condition block", which is where that resolver
+ * substitutes and the only place AWS says a variable has meaning.
+ */
private boolean isConnectAllowed(List<String> documents, Map<String, String> variables, String region, String accountId,
String clientId) {
if (documents.isEmpty()) {
return false;
}
- List<String> resolved = documents.stream().map(document -> resolvePolicyVariables(document, variables)).toList();
Map<String, List<String>> conditionContext = new LinkedHashMap<>();
variables.forEach((key, value) -> conditionContext.put(key, List.of(value)));
String clientArn = AwsArnUtils.Arn.of("iot", region, accountId, "client/" + clientId).toString();
- return policyEvaluator.evaluate(CallerContext.of(resolved), null, "iot:Connect", clientArn, conditionContext)
+ return policyEvaluator.evaluate(CallerContext.of(documents), null, "iot:Connect", clientArn, conditionContext)
== IamPolicyEvaluator.Decision.ALLOW;
}
@@ -575,67 +580,6 @@ public class IotService {
return variables;
}
- /**
- * Substitutes the connection's variables into every string of the document on the parsed tree,
- * so a client id is never read as JSON. A statement still holding a variable Floci cannot
- * resolve matches nothing, as an unresolvable variable does on AWS, and is dropped. A document
- * that does not parse is returned as is: the evaluator logs it and skips it.
- */
- private String resolvePolicyVariables(String document, Map<String, String> variables) {
- JsonNode root;
- try {
- root = objectMapper.readTree(document);
- } catch (JsonProcessingException e) {
- return document;
- }
- if (!(root instanceof ObjectNode policy)) {
- return document;
- }
- JsonNode statements = policy.get("Statement");
- Iterable<JsonNode> each = statements == null ? List.of() : statements.isArray() ? statements : List.of(statements);
- ArrayNode resolved = objectMapper.createArrayNode();
- for (JsonNode statement : each) {
- JsonNode substituted = substituteVariables(statement.deepCopy(), variables);
- if (!hasUnresolvedVariable(substituted)) {
- resolved.add(substituted);
- }
- }
- policy.set("Statement", resolved);
- return policy.toString();
- }
-
- private static JsonNode substituteVariables(JsonNode node, Map<String, String> variables) {
- if (node.isTextual()) {
- String text = node.asText();
- for (Map.Entry<String, String> variable : variables.entrySet()) {
- text = text.replace("${" + variable.getKey() + "}", variable.getValue());
- }
- return TextNode.valueOf(text);
- }
- if (node instanceof ObjectNode object) {
- for (Map.Entry<String, JsonNode> property : object.properties()) {
- property.setValue(substituteVariables(property.getValue(), variables));
- }
- } else if (node instanceof ArrayNode array) {
- for (int i = 0; i < array.size(); i++) {
- array.set(i, substituteVariables(array.get(i), variables));
- }
- }
- return node;
- }
-
- private static boolean hasUnresolvedVariable(JsonNode node) {
- if (node.isTextual()) {
- return POLICY_VARIABLE.matcher(node.asText()).find();
- }
- for (JsonNode child : node) {
- if (hasUnresolvedVariable(child)) {
- return true;
- }
- }
- return false;
- }
-
private List<AccountAwareStorageBackend.AccountEntry<IotCertificate>> registeredCertificates(Predicate<String> keyFilter) {
if (certificateStore instanceof AccountAwareStorageBackend<IotCertificate> aware) {
return aware.scanAllAccountEntries(keyFilter);
diff --git a/src/test/java/io/github/hectorvent/floci/services/iot/IotServiceDeviceAuthTest.java b/src/test/java/io/github/hectorvent/floci/services/iot/IotServiceDeviceAuthTest.java
index 3bc5c4967d..e8d27777fb 100644
--- a/src/test/java/io/github/hectorvent/floci/services/iot/IotServiceDeviceAuthTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/iot/IotServiceDeviceAuthTest.java
@@ -377,6 +377,52 @@ class IotServiceDeviceAuthTest {
assertFalse(connect(device, "${iot:Certificate.Subject.CommonName}"));
}
+ @Test
+ void aVariableOutsideResourceAndConditionIsNotAVariable() {
+ RegisteredDevice device = registeredDevice(true);
+ createAndAttach("p", "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Sid\":\"${iot:Certificate.Subject.CommonName}\","
+ + "\"Effect\":\"Allow\",\"Action\":\"iot:Connect\",\"Resource\":\"arn:aws:iot:*:*:client/*\"}]}", device);
+
+ assertTrue(connect(device, "sensor-1"),
+ "a variable has meaning in the Resource or Condition block, so a Sid is text like any other");
+ }
+
+ @Test
+ void theAsteriskVariableStandsForALiteralAsterisk() {
+ RegisteredDevice device = registeredDevice(true);
+ createAndAttach("p", statement("Allow", "arn:aws:iot:*:*:client/${*}", null), device);
+
+ assertTrue(connect(device, "*"), "the one client id the pattern names");
+ assertFalse(connect(device, "sensor-1"), "the predefined variable is the character, not a wildcard");
+ }
+
+ @Test
+ void aVariableResolvesWhateverCaseItsKeyIsWrittenIn() {
+ RegisteredDevice device = registeredDevice(true);
+ createAndAttach("p", statement("Allow", "arn:aws:iot:*:*:client/${IOT:clientid}", null), device);
+
+ assertTrue(connect(device, "sensor-1"), "key names are case-insensitive, aws:CurrentTime being AWS:currenttime");
+ }
+
+ @Test
+ void aDocumentWithoutTheVersionThatIntroducedVariablesReadsThemLiterally() {
+ RegisteredDevice device = registeredDevice(true);
+ createAndAttach("p", "{\"Statement\":[{\"Effect\":\"Allow\",\"Action\":\"iot:Connect\","
+ + "\"Resource\":\"arn:aws:iot:*:*:client/${iot:ClientId}\"}]}", device);
+
+ assertFalse(connect(device, "sensor-1"), "variables arrived with 2012-10-17 and are literal text without it");
+ assertTrue(connect(device, "${iot:ClientId}"), "which leaves the pattern naming that client id and no other");
+ }
+
+ @Test
+ void anUnresolvedConditionValueIsNullRatherThanAStatementThatVanishes() {
+ RegisteredDevice device = registeredDevice(true);
+ createAndAttach("p", statement("Allow", "arn:aws:iot:*:*:client/*",
+ "{\"StringNotEquals\":{\"iot:ClientId\":\"${iot:Connection.Thing.ThingName}\"}}"), device);
+
+ assertTrue(connect(device, "sensor-1"), "no thing is attached, so the client id is neither equal to nor like a null");
+ }
+
@Test
void aClientIdCarryingJsonSyntaxIsDataNotPolicy() {
RegisteredDevice device = registeredDevice(true);