From caa606ba7dc905c35c97c1c9d319196fe87fd606 Mon Sep 17 00:00:00 2001 From: Priamo Germosen <6233424+pgermosen@users.noreply.github.com> Date: Fri, 16 Oct 2026 18:25:46 -0400 Subject: [PATCH] fix(iot): resolve connect policy variables through the IAM resolver (#5827) IoT carried its own policy-variable pass. Before handing the attached documents to the evaluator, IotService walked each statement's parsed tree, replaced the connection's ${iot:...} values in every string it found, and dropped any statement that still held a ${...}. That was IoT's copy of the mechanism the evaluator gained for every other policy Floci reads, so the documents now go in as written and PolicyVariableResolver does the substituting, from the same condition context the connection already supplies. The developer guide gives IoT no policy language of its own to justify a second reader: AWS IoT Core policies "are JSON documents. They follow the same conventions as IAM policies", they "follow the same policy evaluation logic as IAM policies", and a policy variable is one "that can be used in AWS IoT Core policies in the Resource or Condition block". The predefined ${*}, ${?} and ${$} are documented by pointing at IAM's own variables page. Five corners move, each of them onto what those pages say: - A ${...} outside Resource and Condition is text. The text pass substituted into every string of the statement, Action and Sid included, where the guide gives a variable meaning in those two elements only. - ${*}, ${?} and ${$} resolve to the characters they stand for. Any statement holding one used to be dropped, the unresolved-variable scan being a plain \$\{[^}]*\} that matched them too. - A variable resolves whatever case its key is written in, the variables page being explicit that "Key names are case-insensitive. For example, aws:CurrentTime is equivalent to AWS:currenttime". A thing attribute spelled two ways in one registry now collides on that reading, which is the price of the IAM rule and not a surprise unique to IoT. - An unresolvable variable in a Condition value leaves the value null rather than taking the whole statement away, so a positive operator does not match and a negated one does. A Resource pattern holding one still matches no resource, which is what dropping the statement amounted to. - Variables need the version that introduced them. A document that does not declare "Version": "2012-10-17" keeps ${iot:ClientId} as literal text, the guide's answer being that "if you don't set the Version to 2012-10-17 or later, variables like ${aws:username} are treated as literal strings in the policy". Every policy example in the IoT guide declares it. A connection no longer rewrites the document it evaluates, which the evaluator's parse cache notices: it is keyed by document text, so it held one entry per client id where it now holds one per policy. Five tests in IotServiceDeviceAuthTest cover the five corners, and the unresolved-variable, JSON-syntax and thing-attribute tests already there cover what has to stay put. docs/services/iot.md says what resolves where. --- docs/services/iot.md | 2 +- .../floci/services/iot/IotService.java | 80 +++---------------- .../iot/IotServiceDeviceAuthTest.java | 46 +++++++++++ 3 files changed, 59 insertions(+), 69 deletions(-) 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:::client/`. 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 documents, Map variables, String region, String accountId, String clientId) { if (documents.isEmpty()) { return false; } - List resolved = documents.stream().map(document -> resolvePolicyVariables(document, variables)).toList(); Map> 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 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 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 variables) { - if (node.isTextual()) { - String text = node.asText(); - for (Map.Entry variable : variables.entrySet()) { - text = text.replace("${" + variable.getKey() + "}", variable.getValue()); - } - return TextNode.valueOf(text); - } - if (node instanceof ObjectNode object) { - for (Map.Entry 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> registeredCertificates(Predicate keyFilter) { if (certificateStore instanceof AccountAwareStorageBackend 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);