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.
This commit is contained in:
Priamo Germosen authored and GitHub committed 2026-10-16 17:25:46 -05:00
1 parent 49a3ff9a10
commit caa606ba7d
3 files changed
+59 -69

No files matched your search

+1 -1
View File
@@ -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.
@@ -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);
@@ -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);