List of usage examples for io.vertx.core Future failedFuture
static <T> Future<T> failedFuture(String failureMessage)
From source file:org.eclipse.hono.service.auth.device.CredentialsApiAuthProvider.java
License:Open Source License
@Override public final void authenticate(final DeviceCredentials deviceCredentials, final Handler<AsyncResult<Device>> resultHandler) { Objects.requireNonNull(deviceCredentials); Objects.requireNonNull(resultHandler); final Future<Device> validationResult = Future.future(); validationResult.setHandler(resultHandler); getCredentialsForDevice(deviceCredentials).recover(t -> { final ServiceInvocationException e = (ServiceInvocationException) t; if (e.getErrorCode() == HttpURLConnection.HTTP_NOT_FOUND) { return Future.failedFuture( new ClientErrorException(HttpURLConnection.HTTP_UNAUTHORIZED, "bad credentials")); } else {//from ww w . java 2s.c o m return Future.failedFuture(t); } }).map(credentialsOnRecord -> { if (deviceCredentials.validate(credentialsOnRecord)) { return new Device(deviceCredentials.getTenantId(), credentialsOnRecord.getDeviceId()); } else { throw new ClientErrorException(HttpURLConnection.HTTP_UNAUTHORIZED, "invalid credentials"); } }).setHandler(resultHandler); }
From source file:org.eclipse.hono.service.auth.device.CredentialsApiAuthProvider.java
License:Open Source License
@Override public final void authenticate(final JsonObject authInfo, final Handler<AsyncResult<User>> resultHandler) { final DeviceCredentials credentials = getCredentials(Objects.requireNonNull(authInfo)); if (credentials == null) { resultHandler.handle(Future.failedFuture( new ClientErrorException(HttpURLConnection.HTTP_UNAUTHORIZED, "malformed credentials"))); } else {/* www .j a va 2 s .c om*/ authenticate(credentials, s -> { if (s.succeeded()) { resultHandler.handle(Future.succeededFuture(s.result())); } else { resultHandler.handle(Future.failedFuture(s.cause())); } }); } }
From source file:org.eclipse.hono.service.auth.device.HonoAuthHandler.java
License:Open Source License
@Override public void authorize(final User user, final Handler<AsyncResult<Void>> handler) { final int requiredcount = authorities.size(); if (requiredcount > 0) { if (user == null) { handler.handle(Future.failedFuture(FORBIDDEN)); return; }/*from ww w.j a va2s . c om*/ final AtomicInteger count = new AtomicInteger(); final AtomicBoolean sentFailure = new AtomicBoolean(); final Handler<AsyncResult<Boolean>> authHandler = res -> { if (res.succeeded()) { if (res.result()) { if (count.incrementAndGet() == requiredcount) { // Has all required authorities handler.handle(Future.succeededFuture()); } } else { if (sentFailure.compareAndSet(false, true)) { handler.handle(Future.failedFuture(FORBIDDEN)); } } } else { handler.handle(Future.failedFuture(res.cause())); } }; for (final String authority : authorities) { if (!sentFailure.get()) { user.isAuthorized(authority, authHandler); } } } else { // No auth required handler.handle(Future.succeededFuture()); } }
From source file:org.eclipse.hono.service.auth.device.HonoChainAuthHandler.java
License:Open Source License
private void iterate(final int idx, final RoutingContext ctx, final HttpStatusException lastException, final Handler<AsyncResult<JsonObject>> handler) { // stop condition if (idx >= handlers.size()) { // no more providers, means that we failed to find a provider capable of performing this operation handler.handle(Future.failedFuture(lastException)); return;/* w w w . j av a 2 s . c om*/ } // parse the request in order to extract the credentials object final AuthHandler authHandler = handlers.get(idx); authHandler.parseCredentials(ctx, res -> { if (res.failed()) { if (res.cause() instanceof HttpStatusException) { final HttpStatusException exception = (HttpStatusException) res.cause(); switch (exception.getStatusCode()) { case 302: case 400: case 401: case 403: // try again with next provider since we know what kind of error it is iterate(idx + 1, ctx, exception, handler); return; } } handler.handle(Future.failedFuture(res.cause())); return; } // setup the desired auth provider if we can if (authHandler instanceof HonoAuthHandler) { ctx.put(AUTH_PROVIDER_CONTEXT_KEY, ((HonoAuthHandler) authHandler).authProvider); } handler.handle(Future.succeededFuture(res.result())); }); }
From source file:org.eclipse.hono.service.auth.impl.FileBasedAuthenticationService.java
License:Open Source License
@Override public void verifyPlain(final String authzid, final String username, final String password, Handler<AsyncResult<HonoUser>> authenticationResultHandler) { if (username == null || username.isEmpty()) { authenticationResultHandler.handle(Future.failedFuture("missing username")); } else if (password == null || password.isEmpty()) { authenticationResultHandler.handle(Future.failedFuture("missing password")); } else {//from w w w. j av a 2 s. c om JsonObject user = getUser(username, AuthenticationConstants.MECHANISM_PLAIN); if (user == null) { log.debug("no such user [{}]", username); authenticationResultHandler.handle(Future.failedFuture("unauthorized")); } else if (password.equals(user.getString("password"))) { verify(username, user, authzid, authenticationResultHandler); } else { log.debug("password mismatch"); authenticationResultHandler.handle(Future.failedFuture("unauthorized")); } } }
From source file:org.eclipse.hono.service.auth.impl.FileBasedAuthenticationService.java
License:Open Source License
@Override public void verifyExternal(final String authzid, final String subjectDn, final Handler<AsyncResult<HonoUser>> authenticationResultHandler) { if (subjectDn == null || subjectDn.isEmpty()) { authenticationResultHandler.handle(Future.failedFuture("missing subject DN")); } else {// w w w. j a v a 2 s . c om String commonName = AuthenticationConstants.getCommonName(subjectDn); if (commonName == null) { authenticationResultHandler .handle(Future.failedFuture("could not determine authorization ID for subject DN")); } else { JsonObject user = getUser(commonName, AuthenticationConstants.MECHANISM_EXTERNAL); if (user == null) { authenticationResultHandler.handle(Future.failedFuture("unauthorized")); } else { verify(commonName, user, authzid, authenticationResultHandler); } } } }
From source file:org.eclipse.hono.service.auth.TenantApiBasedX509TrustManager.java
License:Open Source License
/** * Checks if the client certificate chain is trusted. * <p>//from w w w . j a va2 s.com * Retrieves tenant configuration data using the <em>issuer DN</em> from the client's certificate. * This method then tries to create a chain of trust using the client certificate and the * trusted CA certificate from the tenant configuration. * * @param chain The certificate chain provided by the client as part of the TLS handshake. * @param authType The cryptographic algorithm the certificate is based on, e.g. <em>RSA</em>. */ @Override public void checkClientTrusted(final X509Certificate[] chain, final String authType) throws CertificateException { Objects.requireNonNull(chain); final X509Certificate deviceCertificate = chain[0]; final CompletableFuture<Void> tenantRequest = new CompletableFuture<>(); LOG.debug("validating client certificate [issuer: {}]", deviceCertificate.getIssuerX500Principal().getName(X500Principal.RFC2253)); client.isConnected().compose(ok -> client.getOrCreateTenantClient()) .compose(tenantClient -> tenantClient.get(deviceCertificate.getIssuerX500Principal())) .compose(tenant -> { if (!tenant.isEnabled()) { // we let the protocol adapter reject the device // in order to provide a more consistent behavior // by returning an error (forbidden) at the application level LOG.debug("device belongs to disabled tenant"); } if (tenant.getTrustAnchor() == null) { return Future.failedFuture(new IllegalStateException( String.format("no trust anchor configured for tenant [%s]", tenant.getTenantId()))); } else { return checkCertPath(deviceCertificate, tenant.getTrustAnchor()); } }).setHandler(validation -> { if (validation.succeeded()) { tenantRequest.complete(null); } else { tenantRequest.completeExceptionally(validation.cause()); } }); try { tenantRequest.join(); } catch (CompletionException e) { LOG.debug("validation of device certificate failed: {}", e.getCause().getMessage()); throw new CertificateException("validation of device certificate failed", e.getCause()); } }
From source file:org.eclipse.hono.service.tenant.BaseTenantService.java
License:Open Source License
private Future<EventBusMessage> processGetRequest(final EventBusMessage request) { final String tenantId = request.getTenant(); final JsonObject payload = request.getJsonPayload(); if (tenantId == null && payload == null) { log.debug("request does not contain any query parameters"); return Future.failedFuture(new ClientErrorException(HttpURLConnection.HTTP_BAD_REQUEST)); } else if (tenantId != null) { // deprecated API log.debug("retrieving tenant [{}] using deprecated variant of get tenant request", tenantId); return processGetByIdRequest(request, tenantId); } else {//from www . j ava 2 s . c om final String tenantIdFromPayload = getTypesafeValueForField(payload, TenantConstants.FIELD_PAYLOAD_TENANT_ID); final String subjectDn = getTypesafeValueForField(payload, TenantConstants.FIELD_PAYLOAD_SUBJECT_DN); if (tenantIdFromPayload == null && subjectDn == null) { log.debug("payload does not contain any query parameters"); return Future.failedFuture(new ClientErrorException(HttpURLConnection.HTTP_BAD_REQUEST)); } else if (tenantIdFromPayload != null) { log.debug("retrieving tenant [id: {}]", tenantIdFromPayload); return processGetByIdRequest(request, tenantIdFromPayload); } else { return processGetByCaRequest(request, subjectDn); } } }
From source file:org.eclipse.hono.service.tenant.BaseTenantService.java
License:Open Source License
private Future<EventBusMessage> processGetByCaRequest(final EventBusMessage request, final String subjectDn) { try {/*from w w w .j a v a 2 s. c om*/ final X500Principal dn = new X500Principal(subjectDn); log.debug("retrieving tenant [subject DN: {}]", subjectDn); final Future<TenantResult<JsonObject>> getResult = Future.future(); get(dn, getResult.completer()); return getResult.map(tr -> { final EventBusMessage response = request.getResponse(tr.getStatus()).setJsonPayload(tr.getPayload()) .setCacheDirective(tr.getCacheDirective()); if (tr.isOk() && tr.getPayload() != null) { response.setTenant((String) getTypesafeValueForField(tr.getPayload(), TenantConstants.FIELD_PAYLOAD_TENANT_ID)); } return response; }); } catch (final IllegalArgumentException e) { // the given subject DN is invalid log.debug("cannot parse subject DN [{}] provided by client", subjectDn); return Future.failedFuture(new ClientErrorException(HttpURLConnection.HTTP_BAD_REQUEST)); } }
From source file:org.eclipse.hono.service.tenant.BaseTenantService.java
License:Open Source License
private Future<EventBusMessage> processAddRequest(final EventBusMessage request) { final String tenantId = request.getTenant(); final JsonObject payload = getRequestPayload(request.getJsonPayload()); if (tenantId == null) { log.debug("request does not contain mandatory property [{}]", MessageHelper.APP_PROPERTY_TENANT_ID); return Future.failedFuture(new ClientErrorException(HttpURLConnection.HTTP_BAD_REQUEST)); } else if (isValidRequestPayload(payload)) { log.debug("creating tenant [{}]", tenantId); final Future<TenantResult<JsonObject>> addResult = Future.future(); addNotPresentFieldsWithDefaultValuesForTenant(payload); add(tenantId, payload, addResult.completer()); return addResult.map(tr -> { return request.getResponse(tr.getStatus()).setJsonPayload(tr.getPayload()) .setCacheDirective(tr.getCacheDirective()); });//from ww w . java 2 s . c o m } else { log.debug("request contains malformed payload"); return Future.failedFuture(new ClientErrorException(HttpURLConnection.HTTP_BAD_REQUEST)); } }