io.vertx.junit5.Timeout Java Examples

The following examples show how to use io.vertx.junit5.Timeout. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: DeviceRegistrationApiTests.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Verifies that the registry fails a non-existing gateway's request to assert a
 * device's registration status with a 403 error code.
 *
 * @param ctx The vert.x test context.
 */
@Timeout(value = 5, timeUnit = TimeUnit.SECONDS)
@Test
public void testAssertRegistrationFailsForNonExistingGateway(final VertxTestContext ctx) {

    final String deviceId = getHelper().getRandomDeviceId(Constants.DEFAULT_TENANT);

    getHelper().registry
    .registerDevice(Constants.DEFAULT_TENANT, deviceId)
    .compose(r -> getClient(Constants.DEFAULT_TENANT))
    .compose(client -> client.assertRegistration(deviceId, NON_EXISTING_GATEWAY_ID))
    .onComplete(ctx.failing(t -> {
        ctx.verify(() -> assertErrorCode(t, HttpURLConnection.HTTP_FORBIDDEN));
        ctx.completeNow();
    }));
}
 
Example #2
Source File: DeviceConnectionApiTests.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Verifies that a request to set the last known gateway for a device succeeds.
 *
 * @param ctx The vert.x test context.
 */
@Timeout(value = 5, timeUnit = TimeUnit.SECONDS)
@Test
public void testSetLastKnownGatewaySucceeds(final VertxTestContext ctx) {

    final String deviceId = randomId();
    final String gwId = randomId();

    getClient(Constants.DEFAULT_TENANT)
        .compose(client -> client.setLastKnownGatewayForDevice(deviceId, gwId, null).map(client))
        .compose(client -> client.getLastKnownGatewayForDevice(deviceId, null))
        .onComplete(ctx.succeeding(r -> {
            ctx.verify(() -> {
                assertThat(r.getString(DeviceConnectionConstants.FIELD_GATEWAY_ID)).isEqualTo(gwId);
            });
            ctx.completeNow();
        }));
}
 
Example #3
Source File: CoapTestBase.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Verifies that the CoAP adapter rejects messages from a disabled gateway
 * for an enabled device with a 403.
 *
 * @param ctx The test context
 */
@Test
@Timeout(value = 10, timeUnit = TimeUnit.SECONDS)
public void testUploadMessageFailsForDisabledGateway(final VertxTestContext ctx) {

    // GIVEN a device that is connected via a disabled gateway
    final Tenant tenant = new Tenant();
    final String gatewayId = helper.getRandomDeviceId(tenantId);
    final Device gatewayData = new Device();
    gatewayData.setEnabled(false);
    final Device deviceData = new Device();
    deviceData.setVia(Collections.singletonList(gatewayId));

    helper.registry.addPskDeviceForTenant(tenantId, tenant, gatewayId, gatewayData, SECRET)
    .compose(ok -> helper.registry.registerDevice(tenantId, deviceId, deviceData))
    .compose(ok -> {

        // WHEN the gateway tries to upload a message for the device
        final Promise<OptionSet> result = Promise.promise();
        final CoapClient client = getCoapsClient(gatewayId, tenantId, SECRET);
        client.advanced(getHandler(result, ResponseCode.FORBIDDEN), createCoapsRequest(Code.PUT, getPutResource(tenantId, deviceId), 0));
        return result.future();
    })
    .onComplete(ctx.completing());
}
 
Example #4
Source File: CoapTestBase.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Verifies that the CoAP adapter rejects messages from a device that belongs to a tenant for which the CoAP adapter
 * has been disabled.
 *
 * @param ctx The test context
 */
@Test
@Timeout(value = 10, timeUnit = TimeUnit.SECONDS)
public void testUploadMessageFailsForDisabledTenant(final VertxTestContext ctx) {

    // GIVEN a tenant for which the CoAP adapter is disabled
    final Tenant tenant = new Tenant();
    tenant.addAdapterConfig(new Adapter(Constants.PROTOCOL_ADAPTER_TYPE_COAP).setEnabled(false));

    helper.registry.addPskDeviceForTenant(tenantId, tenant, deviceId, SECRET)
    .compose(ok -> {

        // WHEN a device that belongs to the tenant uploads a message
        final CoapClient client = getCoapsClient(deviceId, tenantId, SECRET);
        final Promise<OptionSet> result = Promise.promise();
        client.advanced(getHandler(result, ResponseCode.FORBIDDEN), createCoapsRequest(Code.POST, getPostResource(), 0));
        return result.future();
    })
    .onComplete(ctx.completing());
}
 
Example #5
Source File: TelemetryCoapIT.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Verifies that the upload of a telemetry message containing a payload that
 * exceeds the CoAP adapter's configured max payload size fails with a 4.13
 * response code.
 *
 * @param ctx The test context.
 * @throws IOException if the CoAP request cannot be sent to the adapter.
 * @throws ConnectorException  if the CoAP request cannot be sent to the adapter.
 */
@Test
@Timeout(value = 10, timeUnit = TimeUnit.SECONDS)
public void testUploadFailsForLargePayload(final VertxTestContext ctx) throws ConnectorException, IOException {

    final Tenant tenant = new Tenant();

    helper.registry.addPskDeviceForTenant(tenantId, tenant, deviceId, SECRET)
    .compose(ok -> {
        final CoapClient client = getCoapsClient(deviceId, tenantId, SECRET);
        final Request request = createCoapsRequest(Code.POST, Type.CON, getPostResource(), IntegrationTestSupport.getPayload(4096));
        final Promise<OptionSet> result = Promise.promise();
        client.advanced(getHandler(result, ResponseCode.REQUEST_ENTITY_TOO_LARGE), request);
        return result.future();
    })
    .onComplete(ctx.completing());
}
 
Example #6
Source File: AmqpUploadTestBase.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Verifies that the AMQP Adapter rejects (closes) AMQP links that contain a target address.
 *
 * @param context The Vert.x test context.
 */
@Test
@Timeout(timeUnit = TimeUnit.SECONDS, value = 10)
public void testAnonymousRelayRequired(final VertxTestContext context) {

    final String tenantId = helper.getRandomTenantId();
    final String deviceId = helper.getRandomDeviceId(tenantId);
    final String username = IntegrationTestSupport.getUsername(deviceId, tenantId);
    final String targetAddress = String.format("%s/%s/%s", getEndpointName(), tenantId, deviceId);

    final Tenant tenant = new Tenant();
    helper.registry
    .addDeviceForTenant(tenantId, tenant, deviceId, DEVICE_PASSWORD)
    // connect and create sender (with a valid target address)
    .compose(ok -> connectToAdapter(username, DEVICE_PASSWORD))
    .compose(con -> {
        this.connection = con;
        return createProducer(targetAddress);
    })
    .onComplete(context.failing(t -> {
        log.info("failed to open sender", t);
        context.completeNow();
    }));
}
 
Example #7
Source File: ConnectionFactoryImplTest.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Verifies that the given result handler is invoked if a connection attempt times out.
 *
 * @param ctx The vert.x test context.
 */
@Test
@Timeout(value = 5, timeUnit = TimeUnit.SECONDS)
public void testConnectInvokesHandlerOnConnectTimeout(final VertxTestContext ctx) {

    // GIVEN a factory configured to connect to a server with a mocked ProtonClient that won't actually try to connect
    props.setConnectTimeout(10);
    final ConnectionFactoryImpl factory = new ConnectionFactoryImpl(vertx, props);
    final ProtonClient protonClientMock = mock(ProtonClient.class);
    factory.setProtonClient(protonClientMock);

    // WHEN trying to connect to the server
    factory.connect(null, null, null, ctx.failing(t -> {
        // THEN the connection attempt fails with a TimeoutException and the given handler is invoked
        ctx.verify(() -> assertTrue(t instanceof ConnectTimeoutException));
        ctx.completeNow();
    }));
}
 
Example #8
Source File: HonoClientImplIT.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Verifies that a connection attempt where the TLS handshake cannot be finished successfully fails after two
 * retries with a ClientErrorException with status code 400.
 *
 * @param ctx The vert.x test context.
 */
@Test
@Timeout(value = 10, timeUnit = TimeUnit.SECONDS)
public void testConnectFailsWithClientErrorIfTlsHandshakeFails(final VertxTestContext ctx) {

    // GIVEN a client that is configured to try to connect using TLS to a port that does not support TLS
    final ClientConfigProperties downstreamProps = new ClientConfigProperties();
    downstreamProps.setHost(IntegrationTestSupport.DOWNSTREAM_HOST);
    downstreamProps.setPort(IntegrationTestSupport.DOWNSTREAM_PORT);
    downstreamProps.setTlsEnabled(true);
    downstreamProps.setReconnectAttempts(2);

    clientFactory = IntegrationTestApplicationClientFactory.create(HonoConnection.newConnection(vertx, downstreamProps));
    // WHEN the client tries to connect
    clientFactory.connect().onComplete(ctx.failing(t -> {
        // THEN the connection attempt fails due to lack of authorization
        ctx.verify(() -> {
            assertThat(ServiceInvocationException.extractStatusCode(t)).isEqualTo(HttpURLConnection.HTTP_BAD_REQUEST);
        });
        ctx.completeNow();
    }));
}
 
Example #9
Source File: HonoProtonHelperTest.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Verifies that code is scheduled to be executed on a given Context
 * other than the current Context.
 *
 * @param ctx The vert.x test context.
 */
@SuppressWarnings("unchecked")
@Test
@Timeout(value = 5, timeUnit = TimeUnit.SECONDS)
public void testExecuteOnContextRunsOnGivenContext(final VertxTestContext ctx) {

    final Context mockContext = mock(Context.class);
    doAnswer(invocation -> {
        final Handler<Void> codeToRun = invocation.getArgument(0);
        codeToRun.handle(null);
        return null;
    }).when(mockContext).runOnContext(any(Handler.class));

    HonoProtonHelper.executeOnContext(mockContext, result -> result.complete("done"))
    .onComplete(ctx.succeeding(s -> {
        ctx.verify(() -> {
            verify(mockContext).runOnContext(any(Handler.class));
            assertThat(s).isEqualTo("done");
        });
        ctx.completeNow();
    }));
}
 
Example #10
Source File: FuturesTest.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Verifies that the Future returned by the <em>create</em> method
 * will be completed on the vert.x context it was invoked on.
 *
 * @param ctx The vert.x test context.
 * @param vertx The vert.x instance.
 */
@Test
@Timeout(value = 5, timeUnit = TimeUnit.SECONDS)
public void testCreateGetsCompletedOnOriginalContext(final VertxTestContext ctx, final Vertx vertx) {

    final Context context = vertx.getOrCreateContext();
    context.runOnContext(v -> {
        LOG.trace("run on context");
        Futures.create(() -> CompletableFuture.runAsync(() -> {
            LOG.trace("run async");
        })).onComplete(r -> {
            LOG.trace("after run async");
            ctx.verify(() -> {
                assertTrue(r.succeeded());
                assertEquals(context, vertx.getOrCreateContext());
            });
            ctx.completeNow();
        });
    });
}
 
Example #11
Source File: FuturesTest.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Verifies that the Future returned by the <em>create</em> method
 * won't be completed on a vert.x context if it wasn't started on one.
 *
 * @param ctx The vert.x test context.
 */
@Test
@Timeout(value = 5, timeUnit = TimeUnit.SECONDS)
public void testCreateWithNoVertxContext(final VertxTestContext ctx) {

    Futures.create(() -> CompletableFuture.runAsync(() -> {
        LOG.trace("run async");
    })).onComplete(r -> {
        LOG.trace("after run async");
        ctx.verify(() -> {
            assertTrue(r.succeeded());
            assertNull(Vertx.currentContext());
        });
        ctx.completeNow();
    });
}
 
Example #12
Source File: CoapTestBase.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Verifies that the CoAP adapter rejects messages from a disabled device.
 *
 * @param ctx The test context
 */
@Test
@Timeout(value = 10, timeUnit = TimeUnit.SECONDS)
public void testUploadMessageFailsForDisabledDevice(final VertxTestContext ctx) {

    // GIVEN a disabled device
    final Tenant tenant = new Tenant();
    final Device deviceData = new Device();
    deviceData.setEnabled(false);

    helper.registry.addPskDeviceForTenant(tenantId, tenant, deviceId, deviceData, SECRET)
    .compose(ok -> {

        // WHEN the device tries to upload a message
        final CoapClient client = getCoapsClient(deviceId, tenantId, SECRET);
        final Promise<OptionSet> result = Promise.promise();
        client.advanced(getHandler(result, ResponseCode.NOT_FOUND), createCoapsRequest(Code.POST, getPostResource(), 0));
        return result.future();
    })
    .onComplete(ctx.completing());
}
 
Example #13
Source File: DeviceConnectionApiTests.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Verifies that a request to remove the command-handling adapter instance for a device succeeds with
 * a <em>true</em> value if there was a matching adapter instance entry.
 *
 * @param ctx The vert.x test context.
 */
@Timeout(value = 5, timeUnit = TimeUnit.SECONDS)
@Test
public void testRemoveCommandHandlingAdapterInstanceSucceeds(final VertxTestContext ctx) {

    final String deviceId = randomId();
    final String adapterInstance = randomId();

    getClient(Constants.DEFAULT_TENANT)
            // add the entry
            .compose(client -> client
                    .setCommandHandlingAdapterInstance(deviceId, adapterInstance, null, null)
                    .map(client))
            // then remove it
            .compose(client -> client.removeCommandHandlingAdapterInstance(deviceId, adapterInstance, null))
            .onComplete(ctx.succeeding(result -> {
                ctx.verify(() -> assertThat(result).isTrue());
                ctx.completeNow();
            }));
}
 
Example #14
Source File: CoapTestBase.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Verifies that the adapter fails to authenticate a device if the shared key registered
 * for the device does not match the key used by the device in the DTLS handshake.
 *
 * @param ctx The vert.x test context.
 */
@Test
@Timeout(value = 10, timeUnit = TimeUnit.SECONDS)
public void testUploadFailsForNonMatchingSharedKey(final VertxTestContext ctx) {

    final Tenant tenant = new Tenant();

    // GIVEN a device for which PSK credentials have been registered
    helper.registry.addPskDeviceForTenant(tenantId, tenant, deviceId, "NOT" + SECRET)
    .compose(ok -> {
        // WHEN a device tries to upload data and authenticate using the PSK
        // identity for which the server has a different shared secret on record
        final CoapClient client = getCoapsClient(deviceId, tenantId, SECRET);
        final Promise<OptionSet> result = Promise.promise();
        client.advanced(getHandler(result), createCoapsRequest(Code.POST, getPostResource(), 0));
        return result.future();
    })
    .onComplete(ctx.failing(t -> {
        // THEN the request fails because the DTLS handshake cannot be completed
        assertStatus(ctx, HttpURLConnection.HTTP_UNAVAILABLE, t);
        ctx.completeNow();
    }));
}
 
Example #15
Source File: DeviceRegistrationApiTests.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Verifies that the registry succeeds a request to assert a device's registration status.
 *
 * @param ctx The vert.x test context.
 */
@Timeout(value = 5, timeUnit = TimeUnit.SECONDS)
@Test
public void testAssertRegistrationSucceedsForDevice(final VertxTestContext ctx) {

    final JsonObject defaults = new JsonObject()
            .put(MessageHelper.SYS_PROPERTY_CONTENT_TYPE, "application/vnd.acme+json");
    final Device device = new Device();
    device.setDefaults(defaults.getMap());
    final String deviceId = getHelper().getRandomDeviceId(Constants.DEFAULT_TENANT);

    getHelper().registry
            .registerDevice(Constants.DEFAULT_TENANT, deviceId, device)
            .compose(r -> getClient(Constants.DEFAULT_TENANT))
            .compose(client -> client.assertRegistration(deviceId))
            .onComplete(ctx.succeeding(resp -> {
                ctx.verify(() -> {
                    assertThat(resp.getString(RegistrationConstants.FIELD_PAYLOAD_DEVICE_ID)).isEqualTo(deviceId);
                    assertThat(resp.getJsonObject(RegistrationConstants.FIELD_PAYLOAD_DEFAULTS))
                            .isEqualTo(defaults);
                });
                ctx.completeNow();
            }));
}
 
Example #16
Source File: TestClose.java    From vertx-sse with Apache License 2.0 6 votes vote down vote up
@Test
@Timeout(value = 5, timeUnit = TimeUnit.SECONDS)
void closeHandlerOnServer(VertxTestContext context) {
	final EventSource eventSource = eventSource();
	eventSource.connect("/sse?token=" + TOKEN, handler -> {
		context.verify(() -> {
			assertTrue(handler.succeeded());
			assertNotNull(connection);
               sseHandler.closeHandler(sse -> {
                   context.completeNow();
               });
               waitSafely();
			eventSource.close(); /* closed by client */
		});
	});
}
 
Example #17
Source File: DeviceRegistrationApiTests.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Verifies that the registry fails a disabled gateway's request to assert a device's registration status with a 403
 * error code.
 *
 * @param ctx The vert.x test context.
 */
@Timeout(value = 5, timeUnit = TimeUnit.SECONDS)
@Test
public void testAssertRegistrationFailsForDisabledGateway(final VertxTestContext ctx) {

    assumeTrue(isGatewayModeSupported());

    final String deviceId = getHelper().getRandomDeviceId(Constants.DEFAULT_TENANT);
    final String gatewayId = getHelper().getRandomDeviceId(Constants.DEFAULT_TENANT);

    final Device gateway = new Device();
    gateway.setEnabled(false);
    final Device device = new Device();
    device.setVia(Collections.singletonList(gatewayId));

    getHelper().registry
            .registerDevice(Constants.DEFAULT_TENANT, gatewayId, gateway)
            .compose(ok -> getHelper().registry.registerDevice(
                    Constants.DEFAULT_TENANT, deviceId, device))
            .compose(r -> getClient(Constants.DEFAULT_TENANT))
            .compose(client -> client.assertRegistration(deviceId, gatewayId))
            .onComplete(ctx.failing(t -> {
                assertErrorCode(t, HttpURLConnection.HTTP_FORBIDDEN);
                ctx.completeNow();
            }));
}
 
Example #18
Source File: DeviceRegistrationApiTests.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Verifies that the registry fails a gateway's request to assert a device's registration status for which it is not
 * authorized with a 403 error code.
 *
 * @param ctx The vert.x test context.
 */
@Timeout(value = 5, timeUnit = TimeUnit.SECONDS)
@Test
public void testAssertRegistrationFailsForUnauthorizedGateway(final VertxTestContext ctx) {

    assumeTrue(isGatewayModeSupported());

    // Prepare the identities to insert
    final String deviceId = getHelper().getRandomDeviceId(Constants.DEFAULT_TENANT);
    final String authorizedGateway = getHelper().getRandomDeviceId(Constants.DEFAULT_TENANT);
    final String unauthorizedGateway = getHelper().getRandomDeviceId(Constants.DEFAULT_TENANT);

    final Device device = new Device();
    device.setVia(Collections.singletonList(authorizedGateway));

    getHelper().registry
            .registerDevice(Constants.DEFAULT_TENANT, authorizedGateway)
            .compose(ok -> getHelper().registry.registerDevice(Constants.DEFAULT_TENANT, unauthorizedGateway))
            .compose(ok -> getHelper().registry.registerDevice(Constants.DEFAULT_TENANT, deviceId, device))
            .compose(ok -> getClient(Constants.DEFAULT_TENANT))
            .compose(client -> client.assertRegistration(deviceId, unauthorizedGateway))
            .onComplete(ctx.failing(t -> {
                assertErrorCode(t, HttpURLConnection.HTTP_FORBIDDEN);
                ctx.completeNow();
            }));
}
 
Example #19
Source File: DeviceRegistrationApiTests.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Verifies that the registry fails to assert a disabled device's registration status with a 404 error code.
 *
 * @param ctx The vert.x test context.
 */
@Timeout(value = 5, timeUnit = TimeUnit.SECONDS)
@Test
public void testAssertRegistrationFailsForDisabledDevice(final VertxTestContext ctx) {

    final String deviceId = getHelper().getRandomDeviceId(Constants.DEFAULT_TENANT);

    final Device device = new Device();
    device.setEnabled(false);

    getHelper().registry
            .registerDevice(Constants.DEFAULT_TENANT, deviceId, device)
            .compose(ok -> getClient(Constants.DEFAULT_TENANT))
            .compose(client -> client.assertRegistration(deviceId))
            .onComplete(ctx.failing(t -> {
                ctx.verify(() -> assertErrorCode(t, HttpURLConnection.HTTP_NOT_FOUND));
                ctx.completeNow();
            }));
}
 
Example #20
Source File: TenantApiTests.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Verifies that a request to retrieve information for a tenant by the
 * subject DN of the trusted certificate authority fails with a
 * <em>403 Forbidden</em> status if the client is not authorized to retrieve
 * information for the tenant.
 *
 * @param ctx The vert.x test context.
 */
@Timeout(value = 5, timeUnit = TimeUnit.SECONDS)
@Test
public void testGetTenantByCaFailsIfNotAuthorized(final VertxTestContext ctx) {

    final String tenantId = getHelper().getRandomTenantId();
    final X500Principal subjectDn = new X500Principal("CN=ca-http,OU=Hono,O=Eclipse");
    final PublicKey publicKey = getRandomPublicKey();

    final Tenant tenant = Tenants.createTenantForTrustAnchor(subjectDn, publicKey);

    getHelper().registry
    .addTenant(tenantId, tenant)
    .compose(r -> getRestrictedClient().get(subjectDn))
    .onComplete(ctx.failing(t -> {
        assertErrorCode(t, HttpURLConnection.HTTP_FORBIDDEN);
        ctx.completeNow();
    }));
}
 
Example #21
Source File: CredentialsJmsIT.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Verifies that the service responds with a 400 status to a request that
 * has no subject.
 *
 * @param ctx The vert.x test context.
 */
@Timeout(value = 5, timeUnit = TimeUnit.SECONDS)
@Test
public void testRequestFailsForMissingSubject(final VertxTestContext ctx) {

    final JsonObject searchCriteria = CredentialsConstants.getSearchCriteria(
            CredentialsConstants.SECRETS_TYPE_PRESHARED_KEY, "device");

    getJmsBasedClient(Constants.DEFAULT_TENANT)
    .compose(client -> client.sendRequest(
            null,
            null,
            searchCriteria.toBuffer()))
    .onComplete(ctx.failing(t -> {
        assertErrorCode(t, HttpURLConnection.HTTP_BAD_REQUEST);
        ctx.completeNow();
    }));
}
 
Example #22
Source File: CredentialsJmsIT.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Verifies that the service responds with a 400 status to a request that
 * indicates an unsupported operation in its subject.
 *
 * @param ctx The vert.x test context.
 */
@Timeout(value = 5, timeUnit = TimeUnit.SECONDS)
@Test
public void testRequestFailsForUnsupportedOperation(final VertxTestContext ctx) {

    final JsonObject searchCriteria = CredentialsConstants.getSearchCriteria(
            CredentialsConstants.SECRETS_TYPE_PRESHARED_KEY, "device");

    getJmsBasedClient(Constants.DEFAULT_TENANT)
    .compose(client -> client.sendRequest(
            "unsupported-operation",
            null,
            searchCriteria.toBuffer()))
    .onComplete(ctx.failing(t -> {
        assertErrorCode(t, HttpURLConnection.HTTP_BAD_REQUEST);
        ctx.completeNow();
    }));
}
 
Example #23
Source File: TenantApiTests.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Verifies that an existing tenant can be retrieved by a trusted CA's subject DN.
 *
 * @param ctx The vert.x test context.
 */
@Timeout(value = 5, timeUnit = TimeUnit.SECONDS)
@Test
public void testGetTenantByCa(final VertxTestContext ctx) {

    final String tenantId = getHelper().getRandomTenantId();
    final X500Principal subjectDn = new X500Principal("CN=ca, OU=Hono, O=Eclipse");
    final PublicKey publicKey = getRandomPublicKey();

    final Tenant tenant = Tenants.createTenantForTrustAnchor(subjectDn, publicKey);

    getHelper().registry
    .addTenant(tenantId, tenant)
    .compose(r -> getAdminClient().get(subjectDn))
    .onComplete(ctx.succeeding(tenantObject -> {
        ctx.verify(() -> {
            assertThat(tenantObject.getTenantId()).isEqualTo(tenantId);
            assertThat(tenantObject.getTrustAnchors()).size().isEqualTo(1);
            final TrustAnchor trustAnchor = tenantObject.getTrustAnchors().iterator().next();
            assertThat(trustAnchor.getCA()).isEqualTo(subjectDn);
            assertThat(trustAnchor.getCAPublicKey()).isEqualTo(publicKey);
        });
        ctx.completeNow();
    }));
}
 
Example #24
Source File: DeviceRegistrationJmsIT.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Verifies that a request message which lacks a subject fails with a 400 status.
 *
 * @param ctx The vert.x test context.
 */
@Timeout(value = 5, timeUnit = TimeUnit.SECONDS)
@Test
public void testRequestFailsForMissingSubject(final VertxTestContext ctx) {

    final String deviceId = helper.getRandomDeviceId(Constants.DEFAULT_TENANT);

    helper.registry.registerDevice(Constants.DEFAULT_TENANT, deviceId)
    .compose(ok -> getJmsBasedClient(Constants.DEFAULT_TENANT))
    .compose(client -> client.sendRequest(
            null,
            Collections.singletonMap(MessageHelper.APP_PROPERTY_DEVICE_ID, deviceId),
            null))
    .onComplete(ctx.failing(t -> {
        DeviceRegistrationApiTests.assertErrorCode(t, HttpURLConnection.HTTP_BAD_REQUEST);
        ctx.completeNow();
    }));
}
 
Example #25
Source File: DeviceRegistrationJmsIT.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Verifies that a request message which lacks a subject fails with a 400 status.
 *
 * @param ctx The vert.x test context.
 */
@Timeout(value = 5, timeUnit = TimeUnit.SECONDS)
@Test
public void testRequestFailsForUnsupportedOperation(final VertxTestContext ctx) {

    final String deviceId = helper.getRandomDeviceId(Constants.DEFAULT_TENANT);

    helper.registry.registerDevice(Constants.DEFAULT_TENANT, deviceId)
    .compose(ok -> getJmsBasedClient(Constants.DEFAULT_TENANT))
    .compose(client -> client.sendRequest(
            "unsupported-operation",
            Collections.singletonMap(MessageHelper.APP_PROPERTY_DEVICE_ID, deviceId),
            null))
    .onComplete(ctx.failing(t -> {
        DeviceRegistrationApiTests.assertErrorCode(t, HttpURLConnection.HTTP_BAD_REQUEST);
        ctx.completeNow();
    }));
}
 
Example #26
Source File: TenantApiTests.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Verifies that a request to retrieve information for a tenant that the client
 * is not authorized for fails with a 403 status.
 *
 * @param ctx The vert.x test context.
 */
@Timeout(value = 5, timeUnit = TimeUnit.SECONDS)
@Test
public void testGetTenantFailsIfNotAuthorized(final VertxTestContext ctx) {

    final String tenantId = getHelper().getRandomTenantId();
    final var tenant = new Tenant();
    tenant.setEnabled(true);

    getHelper().registry
    .addTenant(tenantId, tenant)
    .compose(r -> getRestrictedClient().get(tenantId))
    .onComplete(ctx.failing(t -> {
        assertErrorCode(t, HttpURLConnection.HTTP_FORBIDDEN);
        ctx.completeNow();
    }));
}
 
Example #27
Source File: TenantJmsIT.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Verifies that the service responds with a 400 status to a request that
 * indicates an unsupported operation in its subject.
 *
 * @param ctx The vert.x test context.
 */
@Timeout(value = 5, timeUnit = TimeUnit.SECONDS)
@Test
public void testGetTenantFailsForUnknownOperation(final VertxTestContext ctx) {

    allTenantClient
    .sendRequest(
            "unsupported-operation",
            new JsonObject().put(TenantConstants.FIELD_PAYLOAD_TENANT_ID, "tenant").toBuffer())
    .onComplete(ctx.failing(t -> {
        ctx.verify(() -> {
            assertThat(((ServiceInvocationException) t).getErrorCode()).isEqualTo(HttpURLConnection.HTTP_BAD_REQUEST);
        });
        ctx.completeNow();
    }));
}
 
Example #28
Source File: CredentialsApiTests.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Verifies that the service fails when the credentials set is disabled.
 *
 * @param ctx The vert.x test context.
 */
@Timeout(value = 5, timeUnit = TimeUnit.SECONDS)
@Test
public void testGetCredentialsFailsForDisabledCredentials(final VertxTestContext ctx) {

    final String deviceId = getHelper().getRandomDeviceId(Constants.DEFAULT_TENANT);
    final String authId = UUID.randomUUID().toString();

    final CommonCredential credential = getRandomHashedPasswordCredential(authId);
    credential.setEnabled(false);

    getHelper().registry
            .registerDevice(Constants.DEFAULT_TENANT, deviceId)
            .compose(ok -> {
                return getHelper().registry
                        .addCredentials(Constants.DEFAULT_TENANT, deviceId, Collections.singleton(credential))
                        .compose(ok2 -> getClient(Constants.DEFAULT_TENANT))
                        .compose(client -> client.get(CredentialsConstants.SECRETS_TYPE_HASHED_PASSWORD, authId));
            })
            .onComplete(ctx.failing(t -> {
                ctx.verify(() -> assertErrorCode(t, HttpURLConnection.HTTP_NOT_FOUND));
                ctx.completeNow();
            }));
}
 
Example #29
Source File: CredentialsApiTests.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Verifies that a request for credentials using a non-matching client context
 * fails with a 404.
 *
 * @param ctx The vert.x test context.
 */
@Timeout(value = 5, timeUnit = TimeUnit.SECONDS)
@Test
@Disabled("credentials ext concept")
public void testGetCredentialsFailsForNonMatchingClientContext(final VertxTestContext ctx) {

    final String deviceId = getHelper().getRandomDeviceId(Constants.DEFAULT_TENANT);
    final String authId = UUID.randomUUID().toString();
    final Collection<CommonCredential> credentials = getRandomHashedPasswordCredentials(authId);
    // FIXME: credentials.setProperty("client-id", "gateway-one");

    final JsonObject clientContext = new JsonObject()
            .put("client-id", "non-matching");

    getHelper().registry
            .addCredentials(Constants.DEFAULT_TENANT, deviceId, credentials)
            .compose(ok -> getClient(Constants.DEFAULT_TENANT))
            .compose(client -> client.get(CredentialsConstants.SECRETS_TYPE_HASHED_PASSWORD, authId, clientContext))
            .onComplete(ctx.failing(t -> {
                ctx.verify(() -> assertErrorCode(t, HttpURLConnection.HTTP_NOT_FOUND));
                ctx.completeNow();
    }));
}
 
Example #30
Source File: CredentialsApiTests.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Verifies that a request for credentials using a non-existing client context
 * fails with a 404.
 *
 * @param ctx The vert.x test context.
 */
@Timeout(value = 5, timeUnit = TimeUnit.SECONDS)
@Test
public void testGetCredentialsFailsForNonExistingClientContext(final VertxTestContext ctx) {

    final String deviceId = getHelper().getRandomDeviceId(Constants.DEFAULT_TENANT);
    final String authId = UUID.randomUUID().toString();
    final Collection<CommonCredential> credentials = getRandomHashedPasswordCredentials(authId);

    final JsonObject clientContext = new JsonObject()
            .put("client-id", "gateway-one");

    getHelper().registry
            .addCredentials(Constants.DEFAULT_TENANT, deviceId, credentials)
            .compose(ok -> getClient(Constants.DEFAULT_TENANT))
            .compose(client -> client.get(CredentialsConstants.SECRETS_TYPE_HASHED_PASSWORD, authId, clientContext))
            .onComplete(ctx.failing(t -> {
                ctx.verify(() -> assertErrorCode(t, HttpURLConnection.HTTP_NOT_FOUND));
                ctx.completeNow();
    }));
}