mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
feat(iot): enforce custom authorizer decisions on MQTT connections (#4835)
* test(iot): cover custom authorizer invocation and enforcement against AWS * feat(iot): enforce custom authorizer decisions on MQTT connections Serve TestInvokeAuthorizer and invoke an authorizer's function on an MQTT CONNECT that names it, on the plaintext listener and the /mqtt WebSocket bridge. The event, the request and answer checks, signed-token verification and the refusal per MQTT version follow what was measured against AWS IoT Core. The bridge hands the upgrade's headers, query and server name to the broker keyed by its connection's local address. Closes #4823 * fix(iot): evaluate WebSocket custom authorizer policies against the client's address * docs(iot): note that a non-UTF-8 MQTT password reaches the authorizer altered * test(iot): cover custom authorizer CONNECTs on the plain MQTT listener * fix(iot): refuse TestInvokeAuthorizer tokens and signatures outside their length bounds * fix(iot): refuse authorizer JSON with trailing content TestInvokeAuthorizer, CreateAuthorizer and UpdateAuthorizer bodies, a custom authorizer's answer and each policy document it returns are now read with FAIL_ON_TRAILING_TOKENS, as the shared JSON controllers do, so a valid prefix followed by junk is refused instead of half-read. * fix(iot): keep address literals out of the WebSocket server name Over WSS without SNI the bridge fell back to the Host header unfiltered, so a client dialing an IP got that IP as tls.serverName in the authorizer event and as iot:DomainName in policy evaluation. Apply the same address literal filter SNI already uses. Also name the context validation ceiling in TestInvokeAuthorizer's ponytail note.
This commit is contained in:
1 parent
e9f2463103
commit
a33eea05cd
17 files changed
+2862
-50
No files matched your search
+357
@@ -0,0 +1,357 @@
|
||||
package io.github.hectorvent.floci.services.iot;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import io.github.hectorvent.floci.services.lambda.LambdaService;
|
||||
import io.github.hectorvent.floci.services.lambda.model.InvocationType;
|
||||
import io.github.hectorvent.floci.services.lambda.model.InvokeResult;
|
||||
import io.quarkus.test.InjectMock;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.quarkus.test.junit.TestProfile;
|
||||
import org.eclipse.microprofile.config.inject.ConfigProperty;
|
||||
import org.eclipse.paho.client.mqttv3.MqttClient;
|
||||
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
|
||||
import org.eclipse.paho.client.mqttv3.MqttException;
|
||||
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
|
||||
import org.eclipse.paho.mqttv5.client.MqttAsyncClient;
|
||||
import org.eclipse.paho.mqttv5.client.MqttConnectionOptions;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Base64;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.Properties;
|
||||
import java.util.concurrent.BlockingQueue;
|
||||
import java.util.concurrent.LinkedBlockingQueue;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/**
|
||||
* Custom authorizers on the real routes and broker: {@code TestInvokeAuthorizer} on its REST-JSON
|
||||
* path, and an MQTT CONNECT on the TCP listener or over WebSocket admitted or refused by the
|
||||
* authorizer's answer the way AWS IoT does it (MQTT 3.1.1 closed without a CONNACK, MQTT 5
|
||||
* answered with reason 135). The function is mocked and decides by the MQTT password; what it
|
||||
* received is asserted as the event.
|
||||
*/
|
||||
@QuarkusTest
|
||||
@TestProfile(IotMqttWebSocketIntegrationTest.Profile.class)
|
||||
class IotCustomAuthorizerIntegrationTest {
|
||||
|
||||
private static final String FUNCTION_ARN = "arn:aws:lambda:us-east-1:000000000000:function:it-custom-auth";
|
||||
private static final String NAME_PARAM = "x-amz-customauthorizer-name=";
|
||||
private static final ObjectMapper MAPPER = new ObjectMapper();
|
||||
|
||||
@ConfigProperty(name = "quarkus.http.test-port", defaultValue = "0")
|
||||
int testHttpPort;
|
||||
|
||||
@ConfigProperty(name = "quarkus.http.test-ssl-port", defaultValue = "0")
|
||||
int testSslPort;
|
||||
|
||||
@InjectMock
|
||||
LambdaService lambdaService;
|
||||
|
||||
private final BlockingQueue<JsonNode> events = new LinkedBlockingQueue<>();
|
||||
private String authorizer;
|
||||
|
||||
@BeforeEach
|
||||
void functionDecidesByThePassword() {
|
||||
when(lambdaService.invokeArn(eq(FUNCTION_ARN), any(byte[].class), eq(InvocationType.RequestResponse)))
|
||||
.thenAnswer(invocation -> {
|
||||
JsonNode event = MAPPER.readTree((byte[]) invocation.getArgument(1));
|
||||
events.add(event);
|
||||
JsonNode mqtt = event.path("protocolData").path("mqtt");
|
||||
String secret = new String(Base64.getDecoder().decode(mqtt.path("password").asText("")),
|
||||
StandardCharsets.UTF_8);
|
||||
String answer = switch (secret) {
|
||||
case "allow" -> allow(mqtt.path("clientId").asText());
|
||||
case "garbage" -> "{\"foo\": 1}";
|
||||
default -> "{\"isAuthenticated\": false, \"principalId\": \"itprincipal\", \"policyDocuments\": []}";
|
||||
};
|
||||
return new InvokeResult(200, null, answer.getBytes(StandardCharsets.UTF_8), null, "request-id");
|
||||
});
|
||||
authorizer = "it-cauth-" + System.nanoTime();
|
||||
given().contentType("application/json")
|
||||
.body("{\"authorizerFunctionArn\": \"" + FUNCTION_ARN + "\", \"signingDisabled\": true, \"status\": \"ACTIVE\"}")
|
||||
.when().post("/authorizer/" + authorizer)
|
||||
.then().statusCode(200);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testInvokeAuthorizerAnswersWithTheVerdictPoliciesAndDefaultedTtls() {
|
||||
given().contentType("application/json")
|
||||
.body("{\"mqttContext\": {\"username\": \"c1?" + NAME_PARAM + authorizer + "\", \"password\": \""
|
||||
+ base64("allow") + "\", \"clientId\": \"c1\"}}")
|
||||
.when().post("/authorizer/" + authorizer + "/test")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body(equalTo("{\"disconnectAfterInSeconds\":86400,\"isAuthenticated\":true,\"policyDocuments\":["
|
||||
+ MAPPER.valueToTree(policy("c1")) + "],\"principalId\":\"itprincipal\",\"refreshAfterInSeconds\":300}"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testInvokeAuthorizerReportsAnInvalidAnswerAsInvalidResponseException() {
|
||||
given().contentType("application/json")
|
||||
.body("{\"mqttContext\": {\"clientId\": \"c1\", \"password\": \"" + base64("garbage") + "\"}}")
|
||||
.when().post("/authorizer/" + authorizer + "/test")
|
||||
.then()
|
||||
.statusCode(400)
|
||||
.header("X-Amzn-ErrorType", "InvalidResponseException")
|
||||
.body("message", equalTo("Lambda invocation result is in invalid format"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testInvokeAuthorizerOnAMissingAuthorizerIsNotFound() {
|
||||
given().contentType("application/json").body("{\"httpContext\": {}}")
|
||||
.when().post("/authorizer/it-cauth-missing/test")
|
||||
.then()
|
||||
.statusCode(404)
|
||||
.header("X-Amzn-ErrorType", "ResourceNotFoundException")
|
||||
.body("message", equalTo("Authorizer it-cauth-missing not found"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aTestInvokeBodyWithTrailingContentIsAnInvalidRequest() {
|
||||
given().contentType("application/json").body("{\"mqttContext\": {}} trailing")
|
||||
.when().post("/authorizer/" + authorizer + "/test")
|
||||
.then()
|
||||
.statusCode(400)
|
||||
.header("X-Amzn-ErrorType", "InvalidRequestException");
|
||||
}
|
||||
|
||||
@Test
|
||||
void mqtt3AllowedConnectSendsTheWebSocketEventWithTheUsernameVerbatim() throws Exception {
|
||||
String clientId = "cauth-v3-" + System.nanoTime();
|
||||
String username = clientId + "?" + NAME_PARAM + authorizer;
|
||||
|
||||
connectV3(ws(""), clientId, username, "allow", Map.of()).disconnect();
|
||||
|
||||
JsonNode event = takeEvent();
|
||||
assertEquals(List.of("http", "mqtt"), protocols(event));
|
||||
JsonNode headers = event.path("protocolData").path("http").path("headers");
|
||||
headers.fieldNames().forEachRemaining(name -> assertEquals(name.toLowerCase(Locale.ROOT), name, "header names are lower-cased"));
|
||||
assertTrue(headers.path("sec-websocket-protocol").asText().contains("mqtt"), headers.toString());
|
||||
assertEquals("", event.path("protocolData").path("http").path("queryString").asText(null));
|
||||
assertEquals(username, event.path("protocolData").path("mqtt").path("username").asText());
|
||||
assertEquals(base64("allow"), event.path("protocolData").path("mqtt").path("password").asText());
|
||||
assertEquals(clientId, event.path("protocolData").path("mqtt").path("clientId").asText());
|
||||
assertFalse(event.path("signatureVerified").asBoolean(true));
|
||||
}
|
||||
|
||||
@Test
|
||||
void mqtt3RefusedConnectIsClosedWithoutAConnack() {
|
||||
String clientId = "cauth-v3-deny-" + System.nanoTime();
|
||||
|
||||
MqttException refused = assertThrows(MqttException.class,
|
||||
() -> connectV3(ws(""), clientId, clientId + "?" + NAME_PARAM + authorizer, "deny", Map.of()));
|
||||
|
||||
assertEquals(MqttException.REASON_CODE_CONNECTION_LOST, refused.getReasonCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void mqtt3ConnectForAClientIdThePolicyDoesNotCoverIsRefused() {
|
||||
String clientId = "cauth-v3-other-" + System.nanoTime();
|
||||
when(lambdaService.invokeArn(eq(FUNCTION_ARN), any(byte[].class), eq(InvocationType.RequestResponse)))
|
||||
.thenReturn(new InvokeResult(200, null, allow("someone-else").getBytes(StandardCharsets.UTF_8), null, "id"));
|
||||
|
||||
MqttException refused = assertThrows(MqttException.class,
|
||||
() -> connectV3(ws(""), clientId, clientId + "?" + NAME_PARAM + authorizer, "allow", Map.of()));
|
||||
|
||||
assertEquals(MqttException.REASON_CODE_CONNECTION_LOST, refused.getReasonCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void mqtt3ConnectNamingAnUnknownAuthorizerIsRefusedWithoutInvokingAnyFunction() {
|
||||
String clientId = "cauth-v3-unknown-" + System.nanoTime();
|
||||
|
||||
MqttException refused = assertThrows(MqttException.class,
|
||||
() -> connectV3(ws(""), clientId, clientId + "?" + NAME_PARAM + "it-cauth-nope", "allow", Map.of()));
|
||||
|
||||
assertEquals(MqttException.REASON_CODE_CONNECTION_LOST, refused.getReasonCode());
|
||||
verify(lambdaService, never()).invokeArn(anyString(), any(byte[].class), any(InvocationType.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
void mqtt5AllowedConnectWithTheNameInTheUrlQueryConnects() throws Exception {
|
||||
String clientId = "cauth-v5-" + System.nanoTime();
|
||||
|
||||
MqttAsyncClient client = connectV5(ws("?" + NAME_PARAM + authorizer), clientId, clientId, "allow");
|
||||
client.disconnect().waitForCompletion(5000);
|
||||
client.close();
|
||||
|
||||
JsonNode event = takeEvent();
|
||||
assertEquals(NAME_PARAM + authorizer, event.path("protocolData").path("http").path("queryString").asText());
|
||||
assertEquals(clientId, event.path("protocolData").path("mqtt").path("username").asText());
|
||||
}
|
||||
|
||||
@Test
|
||||
void mqtt5RefusedConnectGetsReasonCode135() {
|
||||
String clientId = "cauth-v5-deny-" + System.nanoTime();
|
||||
|
||||
org.eclipse.paho.mqttv5.common.MqttException refused = assertThrows(org.eclipse.paho.mqttv5.common.MqttException.class,
|
||||
() -> connectV5(ws(""), clientId, clientId + "?" + NAME_PARAM + authorizer, "deny"));
|
||||
|
||||
assertEquals(135, refused.getReasonCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void theNameInTheUpgradeHeaderIsSentAmongTheLowerCasedHeaders() throws Exception {
|
||||
String clientId = "cauth-header-" + System.nanoTime();
|
||||
|
||||
connectV3(ws(""), clientId, clientId, "allow", Map.of("X-Amz-CustomAuthorizer-Name", authorizer)).disconnect();
|
||||
|
||||
assertEquals(authorizer, takeEvent().path("protocolData").path("http").path("headers")
|
||||
.path("x-amz-customauthorizer-name").asText());
|
||||
}
|
||||
|
||||
@Test
|
||||
void overWssTheEventCarriesTheServerName() throws Exception {
|
||||
String clientId = "cauth-wss-" + System.nanoTime();
|
||||
|
||||
connectV3("wss://localhost:" + testSslPort + "/mqtt", clientId, clientId + "?" + NAME_PARAM + authorizer, "allow",
|
||||
Map.of()).disconnect();
|
||||
|
||||
JsonNode event = takeEvent();
|
||||
assertEquals(List.of("tls", "http", "mqtt"), protocols(event));
|
||||
assertEquals("localhost", event.path("protocolData").path("tls").path("serverName").asText());
|
||||
List<String> keys = new ArrayList<>();
|
||||
event.path("protocolData").fieldNames().forEachRemaining(keys::add);
|
||||
assertEquals(List.of("tls", "mqtt", "http"), keys);
|
||||
}
|
||||
|
||||
@Test
|
||||
void overWssToAnAddressLiteralTheEventCarriesNoServerName() throws Exception {
|
||||
String clientId = "cauth-wss-ip-" + System.nanoTime();
|
||||
|
||||
connectV3("wss://127.0.0.1:" + testSslPort + "/mqtt", clientId, clientId + "?" + NAME_PARAM + authorizer, "allow",
|
||||
Map.of()).disconnect();
|
||||
|
||||
JsonNode event = takeEvent();
|
||||
assertEquals(List.of("http", "mqtt"), protocols(event));
|
||||
assertFalse(event.path("protocolData").has("tls"), event.path("protocolData").toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void mqtt3AllowedConnectOnTheTcpListenerSendsAnMqttOnlyEvent() throws Exception {
|
||||
String clientId = "cauth-tcp-v3-" + System.nanoTime();
|
||||
String username = clientId + "?" + NAME_PARAM + authorizer;
|
||||
|
||||
connectV3(tcp(), clientId, username, "allow", Map.of()).disconnect();
|
||||
|
||||
JsonNode event = takeEvent();
|
||||
assertEquals(List.of("mqtt"), protocols(event));
|
||||
JsonNode protocolData = event.path("protocolData");
|
||||
assertFalse(protocolData.has("http"), protocolData.toString());
|
||||
assertFalse(protocolData.has("tls"), protocolData.toString());
|
||||
assertEquals(username, protocolData.path("mqtt").path("username").asText());
|
||||
assertEquals(base64("allow"), protocolData.path("mqtt").path("password").asText());
|
||||
assertEquals(clientId, protocolData.path("mqtt").path("clientId").asText());
|
||||
}
|
||||
|
||||
@Test
|
||||
void mqtt5RefusedConnectOnTheTcpListenerGetsReasonCode135() throws Exception {
|
||||
String clientId = "cauth-tcp-v5-deny-" + System.nanoTime();
|
||||
|
||||
org.eclipse.paho.mqttv5.common.MqttException refused = assertThrows(org.eclipse.paho.mqttv5.common.MqttException.class,
|
||||
() -> connectV5(tcp(), clientId, clientId + "?" + NAME_PARAM + authorizer, "deny"));
|
||||
|
||||
assertEquals(135, refused.getReasonCode());
|
||||
assertEquals(base64("deny"), takeEvent().path("protocolData").path("mqtt").path("password").asText());
|
||||
}
|
||||
|
||||
// Helpers
|
||||
|
||||
private MqttClient connectV3(String url, String clientId, String username, String password, Map<String, String> headers)
|
||||
throws Exception {
|
||||
MqttClient client = new MqttClient(url, clientId, new MemoryPersistence());
|
||||
client.setTimeToWait(10_000);
|
||||
MqttConnectOptions options = new MqttConnectOptions();
|
||||
options.setMqttVersion(MqttConnectOptions.MQTT_VERSION_3_1_1);
|
||||
options.setCleanSession(true);
|
||||
options.setConnectionTimeout(10);
|
||||
options.setUserName(username);
|
||||
options.setPassword(password.toCharArray());
|
||||
if (!headers.isEmpty()) {
|
||||
Properties custom = new Properties();
|
||||
custom.putAll(headers);
|
||||
options.setCustomWebSocketHeaders(custom);
|
||||
}
|
||||
if (url.startsWith("wss://")) {
|
||||
options.setSocketFactory(IotMqttWebSocketIntegrationTest.trustOnlyFlociCa().getSocketFactory());
|
||||
}
|
||||
try {
|
||||
client.connect(options);
|
||||
} catch (MqttException e) {
|
||||
client.close();
|
||||
throw e;
|
||||
}
|
||||
return client;
|
||||
}
|
||||
|
||||
private MqttAsyncClient connectV5(String url, String clientId, String username, String password)
|
||||
throws org.eclipse.paho.mqttv5.common.MqttException {
|
||||
MqttAsyncClient client = new MqttAsyncClient(url, clientId, new org.eclipse.paho.mqttv5.client.persist.MemoryPersistence());
|
||||
MqttConnectionOptions options = new MqttConnectionOptions();
|
||||
options.setCleanStart(true);
|
||||
options.setConnectionTimeout(10);
|
||||
options.setUserName(username);
|
||||
options.setPassword(password.getBytes(StandardCharsets.UTF_8));
|
||||
try {
|
||||
client.connect(options).waitForCompletion(10_000);
|
||||
} catch (org.eclipse.paho.mqttv5.common.MqttException e) {
|
||||
client.close(true);
|
||||
throw e;
|
||||
}
|
||||
return client;
|
||||
}
|
||||
|
||||
private String ws(String query) {
|
||||
return "ws://127.0.0.1:" + testHttpPort + "/mqtt" + query;
|
||||
}
|
||||
|
||||
private static String tcp() {
|
||||
return "tcp://127.0.0.1:" + IotMqttWebSocketIntegrationTest.PLAIN_PORT;
|
||||
}
|
||||
|
||||
private JsonNode takeEvent() throws InterruptedException {
|
||||
JsonNode event = events.poll(10, TimeUnit.SECONDS);
|
||||
assertNotNull(event, "the authorizer function was not invoked");
|
||||
return event;
|
||||
}
|
||||
|
||||
private static List<String> protocols(JsonNode event) {
|
||||
List<String> protocols = new ArrayList<>();
|
||||
event.path("protocols").forEach(protocol -> protocols.add(protocol.asText()));
|
||||
return protocols;
|
||||
}
|
||||
|
||||
private static String allow(String clientId) {
|
||||
return "{\"isAuthenticated\": true, \"principalId\": \"itprincipal\", \"policyDocuments\": ["
|
||||
+ MAPPER.valueToTree(policy(clientId)) + "]}";
|
||||
}
|
||||
|
||||
private static String policy(String clientId) {
|
||||
return "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\",\"Action\":\"iot:Connect\","
|
||||
+ "\"Resource\":\"arn:aws:iot:us-east-1:000000000000:client/" + clientId + "\"}]}";
|
||||
}
|
||||
|
||||
private static String base64(String text) {
|
||||
return Base64.getEncoder().encodeToString(text.getBytes(StandardCharsets.UTF_8));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,594 @@
|
||||
package io.github.hectorvent.floci.services.iot;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.common.RegionResolver;
|
||||
import io.github.hectorvent.floci.core.storage.InMemoryStorage;
|
||||
import io.github.hectorvent.floci.services.iot.IotCustomAuthorizer.WebSocketUpgrade;
|
||||
import io.github.hectorvent.floci.services.lambda.LambdaService;
|
||||
import io.github.hectorvent.floci.services.lambda.model.InvocationType;
|
||||
import io.github.hectorvent.floci.services.lambda.model.InvokeResult;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.function.Executable;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.CsvSource;
|
||||
|
||||
import java.net.URLEncoder;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.GeneralSecurityException;
|
||||
import java.security.KeyPair;
|
||||
import java.security.KeyPairGenerator;
|
||||
import java.security.PrivateKey;
|
||||
import java.security.Signature;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Base64;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/**
|
||||
* The custom authorizer decision as AWS IoT makes it, with the function mocked: the event each
|
||||
* request or connection produces, the checks on the function's answer in AWS's order and wording,
|
||||
* and token signature verification.
|
||||
*/
|
||||
class IotCustomAuthorizerTest {
|
||||
|
||||
private static final String REGION = "us-east-1";
|
||||
private static final String FUNCTION_ARN = "arn:aws:lambda:us-east-1:000000000000:function:auth";
|
||||
private static final String POLICY = "{\"Version\": \"2012-10-17\", \"Statement\": [{\"Effect\": \"Allow\", "
|
||||
+ "\"Action\": \"iot:Connect\", \"Resource\": \"*\"}]}";
|
||||
private static final String NAME_PARAM = "x-amz-customauthorizer-name=";
|
||||
private static final String SIGNATURE_PARAM = "x-amz-customauthorizer-signature=";
|
||||
private static final String PRINCIPAL_CONSTRAINT =
|
||||
" at principalId failed to satisfy constraint: Member must satisfy ([a-zA-Z0-9]){1,128}";
|
||||
private static final String TTL_CONSTRAINT =
|
||||
" failed to satisfy constraint: Member must be greater than 5 minutes and less than 24 hours.";
|
||||
|
||||
private static KeyPair key1;
|
||||
private static KeyPair key2;
|
||||
private static KeyPair unregistered;
|
||||
|
||||
private final ObjectMapper mapper = new ObjectMapper();
|
||||
private final RegionResolver regionResolver = new RegionResolver(REGION, "000000000000");
|
||||
private final IotAuthorizerService authorizers = new IotAuthorizerService(new InMemoryStorage<>(), regionResolver);
|
||||
private final LambdaService lambda = mock(LambdaService.class);
|
||||
private final IotCustomAuthorizer customAuthorizer = new IotCustomAuthorizer(authorizers, lambda, mapper, regionResolver);
|
||||
private final List<JsonNode> events = new ArrayList<>();
|
||||
private String answer = response("[" + quoted(POLICY) + "]", "\"refreshAfterInSeconds\": 600, \"disconnectAfterInSeconds\": 3600");
|
||||
private String functionError;
|
||||
|
||||
@BeforeAll
|
||||
static void generateKeys() throws GeneralSecurityException {
|
||||
KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA");
|
||||
generator.initialize(2048);
|
||||
key1 = generator.generateKeyPair();
|
||||
key2 = generator.generateKeyPair();
|
||||
unregistered = generator.generateKeyPair();
|
||||
}
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
when(lambda.invokeArn(eq(FUNCTION_ARN), any(byte[].class), eq(InvocationType.RequestResponse)))
|
||||
.thenAnswer(invocation -> {
|
||||
events.add(mapper.readTree((byte[]) invocation.getArgument(1)));
|
||||
return new InvokeResult(200, functionError, answer.getBytes(StandardCharsets.UTF_8), null, "request-id");
|
||||
});
|
||||
create("a", "ACTIVE", false);
|
||||
create("s", "ACTIVE", true);
|
||||
create("off", "INACTIVE", false);
|
||||
}
|
||||
|
||||
// TestInvokeAuthorizer
|
||||
|
||||
@Test
|
||||
void testInvokeReturnsTheVerdictWithPoliciesVerbatimAndSendsTheMqttFieldsAsGiven() {
|
||||
ObjectNode response = customAuthorizer.testInvoke("a", request("""
|
||||
{"mqttContext": {"username": "c?x-amz-customauthorizer-name=a", "password": "c2VjcmV0", "clientId": "c"}}
|
||||
"""), REGION);
|
||||
|
||||
assertEquals("{\"disconnectAfterInSeconds\":3600,\"isAuthenticated\":true,\"policyDocuments\":["
|
||||
+ quoted(POLICY) + "],\"principalId\":\"p1\",\"refreshAfterInSeconds\":600}", response.toString());
|
||||
assertEquals("{\"protocolData\":{\"mqtt\":{\"username\":\"c?x-amz-customauthorizer-name=a\",\"password\":\"c2VjcmV0\","
|
||||
+ "\"clientId\":\"c\"}},\"protocols\":[\"mqtt\"],\"signatureVerified\":false,"
|
||||
+ "\"connectionMetadata\":{\"id\":\"ID\"}}", lastEvent());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testInvokeOrdersProtocolDataTlsMqttHttpAndProtocolsTlsHttpMqtt() {
|
||||
customAuthorizer.testInvoke("a", request("""
|
||||
{"httpContext": {"headers": {"X-Secret": "s", "X-Mixed-Case": "Value"}, "queryString": "?a=b&c=d"},
|
||||
"mqttContext": {"clientId": "c"}, "tlsContext": {"serverName": "iot.example.com"}}
|
||||
"""), REGION);
|
||||
|
||||
assertEquals("{\"protocolData\":{\"tls\":{\"serverName\":\"iot.example.com\"},\"mqtt\":{\"clientId\":\"c\"},"
|
||||
+ "\"http\":{\"headers\":{\"X-Secret\":\"s\",\"X-Mixed-Case\":\"Value\"},\"queryString\":\"?a=b&c=d\"}},"
|
||||
+ "\"protocols\":[\"tls\",\"http\",\"mqtt\"],\"signatureVerified\":false,"
|
||||
+ "\"connectionMetadata\":{\"id\":\"ID\"}}", lastEvent());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testInvokeWithAnEmptyHttpContextSendsAnEmptyHttpObject() {
|
||||
customAuthorizer.testInvoke("a", request("{\"httpContext\": {}}"), REGION);
|
||||
|
||||
assertEquals("{\"protocolData\":{\"http\":{}},\"protocols\":[\"http\"],\"signatureVerified\":false,"
|
||||
+ "\"connectionMetadata\":{\"id\":\"ID\"}}", lastEvent());
|
||||
}
|
||||
|
||||
@Test
|
||||
void connectionMetadataIdIsAFreshUuidForEveryInvocation() {
|
||||
customAuthorizer.testInvoke("a", request("{\"httpContext\": {}}"), REGION);
|
||||
customAuthorizer.testInvoke("a", request("{\"httpContext\": {}}"), REGION);
|
||||
|
||||
String first = events.get(0).path("connectionMetadata").path("id").asText();
|
||||
String second = events.get(1).path("connectionMetadata").path("id").asText();
|
||||
assertTrue(first.matches("[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[0-9a-f]{4}-[0-9a-f]{12}"), first);
|
||||
assertNotEquals(first, second);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testInvokeWorksOnAnInactiveAuthorizer() {
|
||||
assertTrue(customAuthorizer.testInvoke("off", request("{\"httpContext\": {}}"), REGION)
|
||||
.path("isAuthenticated").asBoolean());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testInvokeOnAMissingAuthorizerIsNotFound() {
|
||||
assertAwsError("ResourceNotFoundException", 404, "Authorizer nope not found",
|
||||
() -> customAuthorizer.testInvoke("nope", request("{\"httpContext\": {}}"), REGION));
|
||||
verifyNotInvoked();
|
||||
}
|
||||
|
||||
@Test
|
||||
void omittedTtlsAreDefaultedTo300And86400() {
|
||||
answer = response("[" + quoted(POLICY) + "]", null);
|
||||
|
||||
ObjectNode response = testInvoke();
|
||||
|
||||
assertEquals(300, response.path("refreshAfterInSeconds").asInt());
|
||||
assertEquals(86400, response.path("disconnectAfterInSeconds").asInt());
|
||||
}
|
||||
|
||||
@Test
|
||||
void ttlsAtTheInclusiveBoundsAreAccepted() {
|
||||
answer = response("[" + quoted(POLICY) + "]", "\"refreshAfterInSeconds\": 300, \"disconnectAfterInSeconds\": 86400");
|
||||
|
||||
ObjectNode response = testInvoke();
|
||||
|
||||
assertEquals(300, response.path("refreshAfterInSeconds").asInt());
|
||||
assertEquals(86400, response.path("disconnectAfterInSeconds").asInt());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aPolicyGivenAsAnObjectIsReturnedAsOneCompactString() throws Exception {
|
||||
answer = response("[" + POLICY + "]", null);
|
||||
|
||||
ObjectNode response = testInvoke();
|
||||
|
||||
assertEquals(mapper.writeValueAsString(mapper.readTree(POLICY)), response.path("policyDocuments").get(0).asText());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aDenyWithPrincipalAndPoliciesIsReturnedAsIs() {
|
||||
answer = "{\"isAuthenticated\": false, \"principalId\": \"p1\", \"policyDocuments\": [" + quoted(POLICY) + "]}";
|
||||
|
||||
ObjectNode response = testInvoke();
|
||||
|
||||
assertFalse(response.path("isAuthenticated").asBoolean());
|
||||
assertEquals(POLICY, response.path("policyDocuments").get(0).asText());
|
||||
}
|
||||
|
||||
@Test
|
||||
void anEmptyPolicyListIsReturnedAsIs() {
|
||||
answer = response("[]", null);
|
||||
|
||||
assertEquals(0, testInvoke().path("policyDocuments").size());
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@CsvSource(delimiter = '|', value = {
|
||||
"{\"foo\": 1}|Lambda invocation result is in invalid format",
|
||||
"{\"principalId\": \"p1\", \"policyDocuments\": []}|Lambda invocation result is in invalid format",
|
||||
"{\"isAuthenticated\": false}|null" + PRINCIPAL_CONSTRAINT,
|
||||
"{\"isAuthenticated\": true, \"policyDocuments\": []}|null" + PRINCIPAL_CONSTRAINT,
|
||||
"{\"isAuthenticated\": true, \"principalId\": \"bad-principal!\"}|bad-principal!" + PRINCIPAL_CONSTRAINT,
|
||||
"{\"isAuthenticated\": true, \"principalId\": \"p1\"}|policyDocuments failed to satisfy constraint: List of policies cannot be null.",
|
||||
"{\"isAuthenticated\": false, \"principalId\": \"p1\"}|policyDocuments failed to satisfy constraint: List of policies cannot be null.",
|
||||
"{\"isAuthenticated\": true, \"principalId\": \"p1\", \"policyDocuments\": [\"this is not json\"]}"
|
||||
+ "|policyDocuments failed to satisfy constraint: Policy document is Malformed: Invalid policy syntax.",
|
||||
"{\"isAuthenticated\": true, \"principalId\": \"p1\", \"policyDocuments\": [\"{} {}\"]}"
|
||||
+ "|policyDocuments failed to satisfy constraint: Policy document is Malformed: Invalid policy syntax.",
|
||||
"{\"isAuthenticated\": true, \"principalId\": \"p1\", \"policyDocuments\": [\"{}\",\"{}\",\"{}\",\"{}\",\"{}\",\"{}\",\"{}\",\"{}\",\"{}\",\"{}\",\"{}\"]}"
|
||||
+ "|policyDocuments failed to satisfy constraint: Number of policies allowed cannot exceed 10",
|
||||
"{\"isAuthenticated\": true, \"principalId\": \"p1\", \"policyDocuments\": [{}], \"refreshAfterInSeconds\": 299}"
|
||||
+ "|299 at refreshAfterInSeconds" + TTL_CONSTRAINT,
|
||||
"{\"isAuthenticated\": true, \"principalId\": \"p1\", \"policyDocuments\": [{}], \"refreshAfterInSeconds\": 86401}"
|
||||
+ "|86401 at refreshAfterInSeconds" + TTL_CONSTRAINT,
|
||||
"{\"isAuthenticated\": true, \"principalId\": \"p1\", \"policyDocuments\": [{}], \"disconnectAfterInSeconds\": 299}"
|
||||
+ "|299 at disconnectAfterInSeconds" + TTL_CONSTRAINT,
|
||||
"{\"isAuthenticated\": true, \"principalId\": \"p1\", \"policyDocuments\": [{}], \"disconnectAfterInSeconds\": 86401}"
|
||||
+ "|86401 at disconnectAfterInSeconds" + TTL_CONSTRAINT,
|
||||
"{\"isAuthenticated\": true, \"principalId\": \"p1\", \"policyDocuments\": [{}], \"refreshAfterInSeconds\": 10, \"disconnectAfterInSeconds\": 10}"
|
||||
+ "|10 at refreshAfterInSeconds" + TTL_CONSTRAINT,
|
||||
"not json|Lambda invocation result is in invalid format",
|
||||
"{\"isAuthenticated\": true, \"principalId\": \"p1\", \"policyDocuments\": []} junk|Lambda invocation result is in invalid format"
|
||||
})
|
||||
void anInvalidAnswerIsAnInvalidResponseInAwsOrderAndWording(String invalidAnswer, String message) {
|
||||
answer = invalidAnswer;
|
||||
|
||||
assertAwsError("InvalidResponseException", 400, message, this::testInvoke);
|
||||
}
|
||||
|
||||
@Test
|
||||
void aPolicyOverTheSizeLimitIsAnInvalidResponse() {
|
||||
answer = response("[" + quoted("{\"Version\": \"2012-10-17\", \"Statement\": [], \"Id\": \"" + "x".repeat(2048) + "\"}")
|
||||
+ "]", null);
|
||||
|
||||
assertAwsError("InvalidResponseException", 400,
|
||||
"policyDocuments failed to satisfy constraint: Size of a policy document cannot exceeds hard limit of 2048",
|
||||
this::testInvoke);
|
||||
}
|
||||
|
||||
@Test
|
||||
void aFunctionErrorReportsItsMessageAndType() {
|
||||
functionError = "Unhandled";
|
||||
answer = "{\"errorMessage\": \"compat-raise\", \"errorType\": \"Exception\", \"stackTrace\": []}";
|
||||
|
||||
assertAwsError("InvalidResponseException", 400,
|
||||
"Lambda function encountered error in execution: compat-raise: Exception", this::testInvoke);
|
||||
}
|
||||
|
||||
@Test
|
||||
void tokenWithoutSignatureIsRefused() {
|
||||
assertInvalidRequest("Request must provide both token and tokenSignature together.",
|
||||
() -> customAuthorizer.testInvoke("a", request("{\"token\": \"allow-me\"}"), REGION));
|
||||
}
|
||||
|
||||
@Test
|
||||
void tokenAndSignatureOnASigningDisabledAuthorizerAreRefused() throws GeneralSecurityException {
|
||||
assertInvalidRequest("Token and token signature provided but signing is disabled for the authorizer.",
|
||||
() -> customAuthorizer.testInvoke("a", tokenRequest("allow-me", sign(key1, "allow-me")), REGION));
|
||||
}
|
||||
|
||||
@Test
|
||||
void tokenWithAContextIsRefused() throws GeneralSecurityException {
|
||||
ObjectNode request = tokenRequest("allow-me", sign(key1, "allow-me"));
|
||||
request.putObject("mqttContext").put("clientId", "c");
|
||||
|
||||
assertInvalidRequest("Request cannot have token and Http/Mqtt/Tls context.",
|
||||
() -> customAuthorizer.testInvoke("s", request, REGION));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aRequestWithoutTokenOrContextIsRefused() {
|
||||
assertInvalidRequest("Request must have Http/Mqtt/Tls context.",
|
||||
() -> customAuthorizer.testInvoke("a", request("{}"), REGION));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aSignatureThatIsNotBase64IsAValidationError() {
|
||||
assertInvalidRequest("1 validation error detected: Value at 'tokenSignature' failed to satisfy constraint: "
|
||||
+ "Member must satisfy regular expression pattern: [A-Za-z0-9+/]+={0,2}",
|
||||
() -> customAuthorizer.testInvoke("s", tokenRequest("allow-me", "not base64!"), REGION));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aQueryStringWithoutTheQuestionMarkIsRefused() {
|
||||
assertInvalidRequest("Invalid arguments in the call", () -> customAuthorizer.testInvoke("a",
|
||||
request("{\"httpContext\": {\"headers\": {\"X-Secret\": \"s\"}, \"queryString\": \"a=b\"}}"), REGION));
|
||||
}
|
||||
|
||||
@Test
|
||||
void anEmptyQueryStringIsAValidationError() {
|
||||
assertInvalidRequest("1 validation error detected: Value at 'httpContext.queryString' failed to satisfy "
|
||||
+ "constraint: Member must have length greater than or equal to 1",
|
||||
() -> customAuthorizer.testInvoke("a", request("{\"httpContext\": {\"queryString\": \"\"}}"), REGION));
|
||||
}
|
||||
|
||||
@Test
|
||||
void anEmptyTokenIsAValidationError() throws GeneralSecurityException {
|
||||
assertInvalidRequest("1 validation error detected: Value at 'token' failed to satisfy constraint: "
|
||||
+ "Member must have length greater than or equal to 1",
|
||||
() -> customAuthorizer.testInvoke("s", tokenRequest("", sign(key1, "")), REGION));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aTokenOverItsMaximumLengthIsAValidationError() throws GeneralSecurityException {
|
||||
String token = "t".repeat(6145);
|
||||
|
||||
assertInvalidRequest("1 validation error detected: Value at 'token' failed to satisfy constraint: "
|
||||
+ "Member must have length less than or equal to 6144",
|
||||
() -> customAuthorizer.testInvoke("s", tokenRequest(token, sign(key1, token)), REGION));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aSignatureOverItsMaximumLengthIsAValidationError() {
|
||||
assertInvalidRequest("1 validation error detected: Value at 'tokenSignature' failed to satisfy constraint: "
|
||||
+ "Member must have length less than or equal to 2560",
|
||||
() -> customAuthorizer.testInvoke("s", tokenRequest("allow-me", "A".repeat(2561)), REGION));
|
||||
}
|
||||
|
||||
@Test
|
||||
void tokenModeVerifiesASignatureByEitherKeyAndSendsOnlyTheToken() throws GeneralSecurityException {
|
||||
for (KeyPair key : List.of(key1, key2)) {
|
||||
assertTrue(customAuthorizer.testInvoke("s", tokenRequest("allow-me", sign(key, "allow-me")), REGION)
|
||||
.path("isAuthenticated").asBoolean());
|
||||
assertEquals("{\"token\":\"allow-me\",\"signatureVerified\":true,\"connectionMetadata\":{\"id\":\"ID\"}}",
|
||||
lastEvent());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void aSignatureOverAnotherTokenOrByAnUnregisteredKeyIsAMismatch() throws GeneralSecurityException {
|
||||
assertInvalidRequest("Token signature mismatch for authorizer s",
|
||||
() -> customAuthorizer.testInvoke("s", tokenRequest("allow-me", sign(key1, "other-token")), REGION));
|
||||
assertInvalidRequest("Token signature mismatch for authorizer s",
|
||||
() -> customAuthorizer.testInvoke("s", tokenRequest("allow-me", sign(unregistered, "allow-me")), REGION));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aSignedMqttUsernameIsVerifiedAndItsTokenSent() throws GeneralSecurityException {
|
||||
String username = signedUsername(sign(key1, "allow-me"), "allow-me");
|
||||
ObjectNode request = mapper.createObjectNode();
|
||||
request.putObject("mqttContext").put("username", username).put("clientId", "c");
|
||||
|
||||
customAuthorizer.testInvoke("s", request, REGION);
|
||||
|
||||
assertEquals("{\"protocolData\":{\"mqtt\":{\"username\":" + quoted(username) + ",\"clientId\":\"c\"}},"
|
||||
+ "\"protocols\":[\"mqtt\"],\"token\":\"allow-me\",\"signatureVerified\":true,"
|
||||
+ "\"connectionMetadata\":{\"id\":\"ID\"}}", lastEvent());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aSignatureInHttpHeadersOrQueryStringIsVerified() throws GeneralSecurityException {
|
||||
String signature = sign(key2, "allow-me");
|
||||
ObjectNode headers = mapper.createObjectNode();
|
||||
headers.putObject("httpContext").putObject("headers").put("tok", "allow-me").put("x-amz-customauthorizer-signature", signature);
|
||||
ObjectNode query = mapper.createObjectNode();
|
||||
query.putObject("httpContext").put("queryString", "?tok=allow-me&" + SIGNATURE_PARAM + urlEncoded(signature));
|
||||
|
||||
customAuthorizer.testInvoke("s", headers, REGION);
|
||||
assertEquals("allow-me", events.getLast().path("token").asText());
|
||||
customAuthorizer.testInvoke("s", query, REGION);
|
||||
assertEquals("allow-me", events.getLast().path("token").asText());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aSignedAuthorizerWithoutATokenInTheContextIsRefusedWithoutAMessage() {
|
||||
AwsException failure = assertThrows(AwsException.class, () -> customAuthorizer.testInvoke("s",
|
||||
request("{\"mqttContext\": {\"clientId\": \"c\", \"password\": \"c2VjcmV0\"}}"), REGION));
|
||||
|
||||
assertEquals("InvalidRequestException", failure.getErrorCode());
|
||||
assertNull(failure.getMessage());
|
||||
verifyNotInvoked();
|
||||
}
|
||||
|
||||
// MQTT CONNECT
|
||||
|
||||
@Test
|
||||
void aWebSocketConnectSendsTlsMqttAndHttpWithTheUsernameVerbatim() {
|
||||
Map<String, String> headers = new LinkedHashMap<>();
|
||||
headers.put("host", "iot.example.com");
|
||||
headers.put("sec-websocket-protocol", "mqtt");
|
||||
|
||||
List<String> policies = customAuthorizer.connectPolicies("a", "c", "c?" + NAME_PARAM + "a", "secret",
|
||||
new WebSocketUpgrade(headers, "", "iot.example.com", null));
|
||||
|
||||
assertEquals(List.of(POLICY), policies);
|
||||
assertEquals("{\"protocolData\":{\"tls\":{\"serverName\":\"iot.example.com\"},\"mqtt\":{\"username\":"
|
||||
+ "\"c?x-amz-customauthorizer-name=a\",\"password\":\"c2VjcmV0\",\"clientId\":\"c\"},\"http\":{\"headers\":"
|
||||
+ "{\"host\":\"iot.example.com\",\"sec-websocket-protocol\":\"mqtt\"},\"queryString\":\"\"}},"
|
||||
+ "\"protocols\":[\"tls\",\"http\",\"mqtt\"],\"signatureVerified\":false,"
|
||||
+ "\"connectionMetadata\":{\"id\":\"ID\"}}", lastEvent());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aConnectWithoutUsernamePasswordOrTlsLeavesThemOut() {
|
||||
customAuthorizer.connectPolicies("a", "c", null, null, new WebSocketUpgrade(Map.of(), NAME_PARAM + "a", null, null));
|
||||
|
||||
assertEquals("{\"protocolData\":{\"mqtt\":{\"clientId\":\"c\"},\"http\":{\"headers\":{},"
|
||||
+ "\"queryString\":\"x-amz-customauthorizer-name=a\"}},\"protocols\":[\"http\",\"mqtt\"],"
|
||||
+ "\"signatureVerified\":false,\"connectionMetadata\":{\"id\":\"ID\"}}", lastEvent());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aPlainTcpConnectSendsOnlyMqtt() {
|
||||
customAuthorizer.connectPolicies("a", "c", "c?" + NAME_PARAM + "a", null, null);
|
||||
|
||||
assertEquals("{\"protocolData\":{\"mqtt\":{\"username\":\"c?x-amz-customauthorizer-name=a\",\"clientId\":\"c\"}},"
|
||||
+ "\"protocols\":[\"mqtt\"],\"signatureVerified\":false,\"connectionMetadata\":{\"id\":\"ID\"}}", lastEvent());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aDenyOrAnEmptyPolicyListAdmitsNoPolicies() {
|
||||
answer = "{\"isAuthenticated\": false, \"principalId\": \"p1\", \"policyDocuments\": [" + quoted(POLICY) + "]}";
|
||||
assertEquals(List.of(), connect("a"));
|
||||
|
||||
answer = response("[]", null);
|
||||
assertEquals(List.of(), connect("a"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void anObjectPolicyReachesTheConnectAsACompactString() throws Exception {
|
||||
answer = response("[" + POLICY + "]", null);
|
||||
|
||||
assertEquals(List.of(mapper.writeValueAsString(mapper.readTree(POLICY))), connect("a"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void anInvalidAnswerFailsTheConnect() {
|
||||
answer = "{\"isAuthenticated\": false}";
|
||||
|
||||
assertAwsError("InvalidResponseException", 400, "null" + PRINCIPAL_CONSTRAINT, () -> connect("a"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void anInactiveAuthorizerAdmitsNothingWithoutInvokingTheFunction() {
|
||||
assertEquals(List.of(), connect("off"));
|
||||
verifyNotInvoked();
|
||||
}
|
||||
|
||||
@Test
|
||||
void anUnknownAuthorizerFailsTheConnectWithoutInvokingTheFunction() {
|
||||
assertThrows(AwsException.class, () -> connect("nope"));
|
||||
verifyNotInvoked();
|
||||
}
|
||||
|
||||
@Test
|
||||
void aSignedConnectSendsTheTokenAfterTheProtocols() throws GeneralSecurityException {
|
||||
String username = signedUsername(sign(key2, "allow-me"), "allow-me");
|
||||
|
||||
customAuthorizer.connectPolicies("s", "c", username, null, null);
|
||||
|
||||
assertEquals("{\"protocolData\":{\"mqtt\":{\"username\":" + quoted(username) + ",\"clientId\":\"c\"}},"
|
||||
+ "\"protocols\":[\"mqtt\"],\"token\":\"allow-me\",\"signatureVerified\":true,"
|
||||
+ "\"connectionMetadata\":{\"id\":\"ID\"}}", lastEvent());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aSignedConnectReadsTokenAndSignatureFromTheWebSocketQueryOrHeaders() throws GeneralSecurityException {
|
||||
String signature = sign(key1, "allow-me");
|
||||
|
||||
customAuthorizer.connectPolicies("s", "c", "c", null, new WebSocketUpgrade(Map.of(),
|
||||
NAME_PARAM + "s&" + SIGNATURE_PARAM + urlEncoded(signature) + "&tok=allow-me", null, null));
|
||||
assertEquals("allow-me", events.getLast().path("token").asText());
|
||||
|
||||
customAuthorizer.connectPolicies("s", "c", "c", null, new WebSocketUpgrade(
|
||||
Map.of("x-amz-customauthorizer-signature", signature, "tok", "allow-me"), "", null, null));
|
||||
assertEquals("allow-me", events.getLast().path("token").asText());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aSignedConnectWithABadOrMissingSignatureNeverInvokesTheFunction() throws GeneralSecurityException {
|
||||
String overOtherToken = signedUsername(sign(key1, "other-token"), "allow-me");
|
||||
String withoutToken = "c?" + NAME_PARAM + "s&" + SIGNATURE_PARAM + urlEncoded(sign(key1, "allow-me"));
|
||||
|
||||
for (String username : List.of(overOtherToken, withoutToken, "c?" + NAME_PARAM + "s&tok=allow-me")) {
|
||||
assertThrows(AwsException.class, () -> customAuthorizer.connectPolicies("s", "c", username, null, null), username);
|
||||
}
|
||||
verifyNotInvoked();
|
||||
}
|
||||
|
||||
@Test
|
||||
void theAuthorizerNameComesFromTheUsernameTheWebSocketQueryOrTheUpgradeHeader() {
|
||||
assertEquals("u", IotCustomAuthorizer.authorizerName("c?" + NAME_PARAM + "u&tok=t", null));
|
||||
assertEquals("q", IotCustomAuthorizer.authorizerName("c", new WebSocketUpgrade(Map.of(), NAME_PARAM + "q", null, null)));
|
||||
assertEquals("h", IotCustomAuthorizer.authorizerName(null,
|
||||
new WebSocketUpgrade(Map.of("x-amz-customauthorizer-name", "h"), "", null, null)));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aConnectNamingNoAuthorizerHasNoName() {
|
||||
assertNull(IotCustomAuthorizer.authorizerName(null, null));
|
||||
assertNull(IotCustomAuthorizer.authorizerName("plain-user", null));
|
||||
assertNull(IotCustomAuthorizer.authorizerName("c?X-Amz-Algorithm=AWS4-HMAC-SHA256", new WebSocketUpgrade(
|
||||
Map.of("sec-websocket-protocol", "mqtt"), "X-Amz-Signature=00", null, null)));
|
||||
assertEquals("%zz", IotCustomAuthorizer.authorizerName("c?" + NAME_PARAM + "%zz", null),
|
||||
"a malformed escape is kept as sent instead of failing the CONNECT");
|
||||
}
|
||||
|
||||
// Helpers
|
||||
|
||||
private void create(String name, String status, boolean signed) {
|
||||
ObjectNode body = mapper.createObjectNode().put("authorizerFunctionArn", FUNCTION_ARN).put("status", status);
|
||||
if (signed) {
|
||||
body.put("tokenKeyName", "tok");
|
||||
body.putObject("tokenSigningPublicKeys").put("k1", pem(key1)).put("k2", pem(key2));
|
||||
} else {
|
||||
body.put("signingDisabled", true);
|
||||
}
|
||||
authorizers.createAuthorizer(name, body, REGION);
|
||||
}
|
||||
|
||||
private ObjectNode testInvoke() {
|
||||
return customAuthorizer.testInvoke("a", request("{\"mqttContext\": {\"clientId\": \"c\", \"password\": \"c2VjcmV0\"}}"),
|
||||
REGION);
|
||||
}
|
||||
|
||||
private List<String> connect(String name) {
|
||||
return customAuthorizer.connectPolicies(name, "c", "c?" + NAME_PARAM + name, "secret", null);
|
||||
}
|
||||
|
||||
private ObjectNode request(String json) {
|
||||
try {
|
||||
return (ObjectNode) mapper.readTree(json);
|
||||
} catch (Exception e) {
|
||||
throw new IllegalArgumentException(json, e);
|
||||
}
|
||||
}
|
||||
|
||||
private ObjectNode tokenRequest(String token, String signature) {
|
||||
return mapper.createObjectNode().put("token", token).put("tokenSignature", signature);
|
||||
}
|
||||
|
||||
/** The last event the function received, with its random connection id replaced by {@code ID}. */
|
||||
private String lastEvent() {
|
||||
ObjectNode event = (ObjectNode) events.getLast().deepCopy();
|
||||
((ObjectNode) event.get("connectionMetadata")).put("id", "ID");
|
||||
return event.toString();
|
||||
}
|
||||
|
||||
private void verifyNotInvoked() {
|
||||
verify(lambda, never()).invokeArn(anyString(), any(byte[].class), any(InvocationType.class));
|
||||
}
|
||||
|
||||
private static String response(String policies, String ttls) {
|
||||
return "{\"isAuthenticated\": true, \"principalId\": \"p1\", \"policyDocuments\": " + policies
|
||||
+ (ttls == null ? "" : ", " + ttls) + "}";
|
||||
}
|
||||
|
||||
private static String quoted(String text) {
|
||||
return "\"" + text.replace("\\", "\\\\").replace("\"", "\\\"") + "\"";
|
||||
}
|
||||
|
||||
private static String signedUsername(String signature, String token) {
|
||||
return "c?" + NAME_PARAM + "s&" + SIGNATURE_PARAM + urlEncoded(signature) + "&tok=" + token;
|
||||
}
|
||||
|
||||
private static String urlEncoded(String value) {
|
||||
return URLEncoder.encode(value, StandardCharsets.UTF_8);
|
||||
}
|
||||
|
||||
private static String sign(KeyPair key, String token) throws GeneralSecurityException {
|
||||
PrivateKey privateKey = key.getPrivate();
|
||||
Signature signature = Signature.getInstance("SHA256withRSA");
|
||||
signature.initSign(privateKey);
|
||||
signature.update(token.getBytes(StandardCharsets.UTF_8));
|
||||
return Base64.getEncoder().encodeToString(signature.sign());
|
||||
}
|
||||
|
||||
private static String pem(KeyPair key) {
|
||||
return "-----BEGIN PUBLIC KEY-----\n"
|
||||
+ Base64.getMimeEncoder(64, "\n".getBytes(StandardCharsets.US_ASCII)).encodeToString(key.getPublic().getEncoded())
|
||||
+ "\n-----END PUBLIC KEY-----";
|
||||
}
|
||||
|
||||
private void assertInvalidRequest(String message, Executable call) {
|
||||
assertAwsError("InvalidRequestException", 400, message, call);
|
||||
verifyNotInvoked();
|
||||
}
|
||||
|
||||
private static void assertAwsError(String code, int status, String message, Executable call) {
|
||||
AwsException failure = assertThrows(AwsException.class, call);
|
||||
assertEquals(code, failure.getErrorCode());
|
||||
assertEquals(status, failure.getHttpStatus());
|
||||
assertEquals(message, failure.getMessage());
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -108,7 +108,7 @@ class IotMqttBrokerDeviceVerificationTest {
|
||||
.addCertValue(Buffer.buffer(serverLeaf.certificatePem()))
|
||||
.addKeyValue(Buffer.buffer(serverLeaf.privateKeyPem())));
|
||||
when(iotService.get()).thenReturn(service);
|
||||
broker = new IotMqttBrokerService(config, vertx, iotService, registry);
|
||||
broker = new IotMqttBrokerService(config, vertx, iotService, mock(IotCustomAuthorizer.class), registry);
|
||||
broker.startIfEnabled();
|
||||
}
|
||||
|
||||
|
||||
+28
-1
@@ -32,6 +32,7 @@ import io.vertx.core.Vertx;
|
||||
import io.vertx.core.buffer.Buffer;
|
||||
import io.vertx.core.net.KeyCertOptions;
|
||||
import io.vertx.core.net.PemKeyCertOptions;
|
||||
import io.vertx.core.net.SocketAddress;
|
||||
import io.vertx.mqtt.MqttEndpoint;
|
||||
import io.vertx.mqtt.MqttTopicSubscription;
|
||||
import io.vertx.mqtt.messages.MqttSubscribeMessage;
|
||||
@@ -68,6 +69,7 @@ import java.security.cert.Certificate;
|
||||
import java.security.cert.X509Certificate;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.BlockingQueue;
|
||||
@@ -93,6 +95,7 @@ import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
|
||||
import static org.mockito.Mockito.doAnswer;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.timeout;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.verifyNoInteractions;
|
||||
import static org.mockito.Mockito.when;
|
||||
@@ -130,6 +133,7 @@ class IotMqttBrokerServiceTest {
|
||||
private final TlsConfiguration tls = mock(TlsConfiguration.class);
|
||||
@SuppressWarnings("unchecked")
|
||||
private final Instance<IotService> iotService = mock(Instance.class);
|
||||
private final IotCustomAuthorizer customAuthorizer = mock(IotCustomAuthorizer.class);
|
||||
private int plainPort;
|
||||
private int tlsPort;
|
||||
private IotMqttBrokerService broker;
|
||||
@@ -162,7 +166,7 @@ class IotMqttBrokerServiceTest {
|
||||
when(config.tls().enabled()).thenReturn(true);
|
||||
when(registry.getDefault()).thenReturn(Optional.of(tls));
|
||||
when(tls.getKeyStoreOptions()).thenReturn(pem(bootLeaf));
|
||||
broker = new IotMqttBrokerService(config, vertx, iotService, registry);
|
||||
broker = new IotMqttBrokerService(config, vertx, iotService, customAuthorizer, registry);
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
@@ -481,6 +485,29 @@ class IotMqttBrokerServiceTest {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A WebSocket client's CONNECT reaches the broker from the bridge's loopback socket, so the
|
||||
* policies its custom authorizer returns are evaluated against the address the bridge recorded
|
||||
* for the WebSocket client.
|
||||
*/
|
||||
@Test
|
||||
void aWebSocketConnectThroughACustomAuthorizerIsEvaluatedAgainstTheWebSocketClientsAddress() {
|
||||
IotService service = mock(IotService.class);
|
||||
when(iotService.get()).thenReturn(service);
|
||||
when(customAuthorizer.connectPolicies(eq("ws-auth"), eq("ws-client"), any(), any(), any()))
|
||||
.thenReturn(List.of("{}"));
|
||||
SocketAddress bridge = SocketAddress.inetSocketAddress(50123, "127.0.0.1");
|
||||
broker.webSocketUpgrades().put(bridge, new IotCustomAuthorizer.WebSocketUpgrade(
|
||||
Map.of(), IotCustomAuthorizer.NAME_PARAM + "=ws-auth", null, "203.0.113.7"));
|
||||
MqttEndpoint endpoint = mock(MqttEndpoint.class);
|
||||
when(endpoint.clientIdentifier()).thenReturn("ws-client");
|
||||
when(endpoint.remoteAddress()).thenReturn(bridge);
|
||||
|
||||
broker.handleEndpoint(endpoint, false);
|
||||
|
||||
verify(service, timeout(10_000)).isConnectAllowedBy(List.of("{}"), "ws-client", "203.0.113.7", null);
|
||||
}
|
||||
|
||||
/**
|
||||
* Two publishes from two connections, the first one's rule action held on a latch: the second
|
||||
* publish is fanned out, so its rules were handed over, yet they start only once the first
|
||||
|
||||
+52
-4
@@ -3,9 +3,17 @@ package io.github.hectorvent.floci.services.iot;
|
||||
import io.vertx.core.Handler;
|
||||
import io.vertx.core.http.ServerWebSocket;
|
||||
import io.vertx.core.net.NetSocket;
|
||||
import io.vertx.core.net.SocketAddress;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertSame;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.anyShort;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.Mockito.mock;
|
||||
@@ -22,7 +30,7 @@ class IotMqttWebSocketBridgeTest {
|
||||
when(webSocket.isClosed()).thenReturn(false);
|
||||
|
||||
IotMqttWebSocketBridge.BridgeSession session =
|
||||
new IotMqttWebSocketBridge.BridgeSession(webSocket, socket);
|
||||
new IotMqttWebSocketBridge.BridgeSession(webSocket, socket, () -> { });
|
||||
session.start();
|
||||
|
||||
ArgumentCaptor<Handler<Void>> closeCaptor = ArgumentCaptor.forClass(Handler.class);
|
||||
@@ -44,7 +52,7 @@ class IotMqttWebSocketBridgeTest {
|
||||
when(webSocket.isClosed()).thenReturn(false);
|
||||
|
||||
IotMqttWebSocketBridge.BridgeSession session =
|
||||
new IotMqttWebSocketBridge.BridgeSession(webSocket, socket);
|
||||
new IotMqttWebSocketBridge.BridgeSession(webSocket, socket, () -> { });
|
||||
session.start();
|
||||
|
||||
ArgumentCaptor<Handler<Void>> closeCaptor = ArgumentCaptor.forClass(Handler.class);
|
||||
@@ -66,7 +74,7 @@ class IotMqttWebSocketBridgeTest {
|
||||
when(webSocket.isClosed()).thenReturn(false);
|
||||
|
||||
IotMqttWebSocketBridge.BridgeSession session =
|
||||
new IotMqttWebSocketBridge.BridgeSession(webSocket, socket);
|
||||
new IotMqttWebSocketBridge.BridgeSession(webSocket, socket, () -> { });
|
||||
session.start();
|
||||
|
||||
ArgumentCaptor<Handler<Throwable>> exceptionCaptor = ArgumentCaptor.forClass(Handler.class);
|
||||
@@ -89,7 +97,7 @@ class IotMqttWebSocketBridgeTest {
|
||||
when(webSocket.isClosed()).thenReturn(false);
|
||||
|
||||
IotMqttWebSocketBridge.BridgeSession session =
|
||||
new IotMqttWebSocketBridge.BridgeSession(webSocket, socket);
|
||||
new IotMqttWebSocketBridge.BridgeSession(webSocket, socket, () -> { });
|
||||
session.start();
|
||||
|
||||
ArgumentCaptor<Handler<Void>> closeCaptor = ArgumentCaptor.forClass(Handler.class);
|
||||
@@ -104,4 +112,44 @@ class IotMqttWebSocketBridgeTest {
|
||||
verify(webSocket, never()).close();
|
||||
verify(webSocket, never()).close(anyShort(), anyString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void everyWayTheSessionEndsRunsTheCloseHookOnce() {
|
||||
for (int path = 0; path < 3; path++) {
|
||||
ServerWebSocket webSocket = mock(ServerWebSocket.class);
|
||||
NetSocket socket = mock(NetSocket.class);
|
||||
AtomicInteger hooks = new AtomicInteger();
|
||||
new IotMqttWebSocketBridge.BridgeSession(webSocket, socket, hooks::incrementAndGet).start();
|
||||
ArgumentCaptor<Handler<Void>> socketClose = ArgumentCaptor.forClass(Handler.class);
|
||||
verify(socket).closeHandler(socketClose.capture());
|
||||
ArgumentCaptor<Handler<Void>> webSocketClose = ArgumentCaptor.forClass(Handler.class);
|
||||
verify(webSocket).closeHandler(webSocketClose.capture());
|
||||
ArgumentCaptor<Handler<Throwable>> failure = ArgumentCaptor.forClass(Handler.class);
|
||||
verify(socket).exceptionHandler(failure.capture());
|
||||
|
||||
switch (path) {
|
||||
case 0 -> socketClose.getValue().handle(null);
|
||||
case 1 -> webSocketClose.getValue().handle(null);
|
||||
default -> failure.getValue().handle(new IllegalStateException("broker failed"));
|
||||
}
|
||||
socketClose.getValue().handle(null);
|
||||
webSocketClose.getValue().handle(null);
|
||||
|
||||
assertEquals(1, hooks.get(), "path " + path);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void closingAnOlderSessionKeepsANewerSessionsEqualUpgradeOnTheSameAddress() {
|
||||
SocketAddress address = SocketAddress.inetSocketAddress(50000, "127.0.0.1");
|
||||
IotCustomAuthorizer.WebSocketUpgrade older = new IotCustomAuthorizer.WebSocketUpgrade(Map.of("host", "h"), "", null, null);
|
||||
IotCustomAuthorizer.WebSocketUpgrade newer = new IotCustomAuthorizer.WebSocketUpgrade(Map.of("host", "h"), "", null, null);
|
||||
Map<SocketAddress, IotCustomAuthorizer.WebSocketUpgrade> upgrades = new ConcurrentHashMap<>(Map.of(address, newer));
|
||||
|
||||
IotMqttWebSocketBridge.forgetting(upgrades, address, older).run();
|
||||
assertSame(newer, upgrades.get(address));
|
||||
|
||||
IotMqttWebSocketBridge.forgetting(upgrades, address, newer).run();
|
||||
assertTrue(upgrades.isEmpty());
|
||||
}
|
||||
}
|
||||
+4
-4
@@ -128,12 +128,12 @@ public class IotMqttWebSocketIntegrationTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
void customAuthorizerStyleConnectIsAccepted() throws Exception {
|
||||
void connectNamingAnUnknownCustomAuthorizerIsRefused() {
|
||||
String clientId = "tunnel-" + System.nanoTime();
|
||||
String username = clientId + "?x-amz-customauthorizer-name=my-authorizer";
|
||||
try (WsClient client = WsClient.connect(wss("/mqtt"), clientId, username, "token-" + System.nanoTime())) {
|
||||
assertTrue(client.isConnected());
|
||||
}
|
||||
MqttException refused = assertThrows(MqttException.class,
|
||||
() -> WsClient.connect(wss("/mqtt"), clientId, username, "token-" + System.nanoTime()));
|
||||
assertEquals(MqttException.REASON_CODE_CONNECTION_LOST, refused.getReasonCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
@@ -396,6 +396,27 @@ class IotServiceDeviceAuthTest {
|
||||
assertFalse(connect(device, "sensor-1"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void customAuthorizerPoliciesAllowTheClientArnOfTheDefaultAccountAndRegion() {
|
||||
String onlySensor1 = statement("Allow", "arn:aws:iot:" + REGION + ":" + ACCOUNT + ":client/sensor-1", null);
|
||||
|
||||
assertTrue(service.isConnectAllowedBy(List.of(onlySensor1), "sensor-1", "127.0.0.1", null));
|
||||
assertFalse(service.isConnectAllowedBy(List.of(onlySensor1), "sensor-2", "127.0.0.1", null));
|
||||
assertFalse(service.isConnectAllowedBy(List.of(statement("Allow", "arn:aws:iot:eu-west-1:" + ACCOUNT + ":client/sensor-1",
|
||||
null)), "sensor-1", "127.0.0.1", null), "a client ARN in another region");
|
||||
assertFalse(service.isConnectAllowedBy(List.of(), "sensor-1", "127.0.0.1", null), "no policy means deny");
|
||||
}
|
||||
|
||||
@Test
|
||||
void customAuthorizerPoliciesResolveTheConnectionVariables() {
|
||||
String policy = statement("Allow", "arn:aws:iot:*:*:client/${iot:ClientId}",
|
||||
"{\"StringEquals\":{\"iot:DomainName\":\"iot.example.com\"},\"IpAddress\":{\"aws:SourceIp\":\"10.0.0.0/8\"}}");
|
||||
|
||||
assertTrue(service.isConnectAllowedBy(List.of(policy), "sensor-1", "10.1.2.3", "iot.example.com"));
|
||||
assertFalse(service.isConnectAllowedBy(List.of(policy), "sensor-1", "127.0.0.1", "iot.example.com"));
|
||||
assertFalse(service.isConnectAllowedBy(List.of(policy), "sensor-1", "10.1.2.3", null));
|
||||
}
|
||||
|
||||
private RegisteredDevice registeredDevice(boolean active) {
|
||||
IotCertificate created = service.createKeysAndCertificate(active, REGION);
|
||||
return service.findRegisteredCertificate(parse(created)).orElseThrow();
|
||||
|
||||
Reference in new issue
Block a user