Search in sources :

Example 1 with BlockingHandlerDecorator

use of io.vertx.ext.web.impl.BlockingHandlerDecorator in project web3signer by ConsenSys.

the class Eth1Runner method populateRouter.

@Override
protected Router populateRouter(final Context context) {
    final RouterBuilder routerBuilder = context.getRouterBuilder();
    final LogErrorHandler errorHandler = context.getErrorHandler();
    final ArtifactSignerProvider signerProvider = context.getArtifactSignerProvider();
    addPublicKeysListHandler(routerBuilder, signerProvider, ETH1_LIST.name(), context.getErrorHandler());
    final SignerForIdentifier<SecpArtifactSignature> secpSigner = new SignerForIdentifier<>(signerProvider, this::formatSecpSignature, SECP256K1);
    routerBuilder.operation(ETH1_SIGN.name()).handler(new BlockingHandlerDecorator(new Eth1SignForIdentifierHandler(secpSigner, new HttpApiMetrics(context.getMetricsSystem(), SECP256K1)), false)).failureHandler(errorHandler);
    addReloadHandler(routerBuilder, signerProvider, RELOAD.name(), context.getErrorHandler());
    return context.getRouterBuilder().createRouter();
}
Also used : SignerForIdentifier(tech.pegasys.web3signer.core.service.http.handlers.signing.SignerForIdentifier) BlockingHandlerDecorator(io.vertx.ext.web.impl.BlockingHandlerDecorator) SecpArtifactSignature(tech.pegasys.web3signer.signing.SecpArtifactSignature) RouterBuilder(io.vertx.ext.web.openapi.RouterBuilder) ArtifactSignerProvider(tech.pegasys.web3signer.signing.ArtifactSignerProvider) DefaultArtifactSignerProvider(tech.pegasys.web3signer.signing.config.DefaultArtifactSignerProvider) Eth1SignForIdentifierHandler(tech.pegasys.web3signer.core.service.http.handlers.signing.Eth1SignForIdentifierHandler) HttpApiMetrics(tech.pegasys.web3signer.core.service.http.metrics.HttpApiMetrics) LogErrorHandler(tech.pegasys.web3signer.core.service.http.handlers.LogErrorHandler)

Example 2 with BlockingHandlerDecorator

use of io.vertx.ext.web.impl.BlockingHandlerDecorator in project web3signer by ConsenSys.

the class Eth2Runner method registerEth2Routes.

private void registerEth2Routes(final RouterBuilder routerBuilder, final ArtifactSignerProvider blsSignerProvider, final LogErrorHandler errorHandler, final MetricsSystem metricsSystem, final Optional<SlashingProtectionContext> slashingProtectionContext) {
    final ObjectMapper objectMapper = SigningObjectMapperFactory.createObjectMapper();
    // security handler for keymanager endpoints
    routerBuilder.securityHandler("bearerAuth", context -> {
        // TODO Auth token security logic
        final boolean authorized = true;
        if (authorized) {
            context.next();
        } else {
            context.response().setStatusCode(401).end("{ message: \"permission denied\" }");
        }
    });
    addPublicKeysListHandler(routerBuilder, blsSignerProvider, ETH2_LIST.name(), errorHandler);
    final SignerForIdentifier<BlsArtifactSignature> blsSigner = new SignerForIdentifier<>(blsSignerProvider, this::formatBlsSignature, BLS);
    routerBuilder.operation(ETH2_SIGN.name()).handler(new BlockingHandlerDecorator(new Eth2SignForIdentifierHandler(blsSigner, new HttpApiMetrics(metricsSystem, BLS), new SlashingProtectionMetrics(metricsSystem), slashingProtectionContext.map(SlashingProtectionContext::getSlashingProtection), objectMapper, eth2Spec), false)).failureHandler(errorHandler);
    addReloadHandler(routerBuilder, blsSignerProvider, RELOAD.name(), errorHandler);
    if (isKeyManagerApiEnabled) {
        routerBuilder.operation(KEYMANAGER_LIST.name()).handler(new BlockingHandlerDecorator(new ListKeystoresHandler(blsSignerProvider, objectMapper), false)).failureHandler(errorHandler);
        final ValidatorManager validatorManager = createValidatorManager(blsSignerProvider, objectMapper);
        routerBuilder.operation(KEYMANAGER_IMPORT.name()).handler(new BlockingHandlerDecorator(new ImportKeystoresHandler(objectMapper, config.getKeyConfigPath(), slashingProtectionContext.map(SlashingProtectionContext::getSlashingProtection), blsSignerProvider, validatorManager), false)).failureHandler(errorHandler);
        routerBuilder.operation(KEYMANAGER_DELETE.name()).handler(new BlockingHandlerDecorator(new DeleteKeystoresHandler(objectMapper, slashingProtectionContext.map(SlashingProtectionContext::getSlashingProtection), blsSignerProvider, validatorManager), false)).failureHandler(errorHandler);
    }
}
Also used : FileValidatorManager(tech.pegasys.web3signer.signing.FileValidatorManager) DbValidatorManager(tech.pegasys.web3signer.slashingprotection.DbValidatorManager) ValidatorManager(tech.pegasys.web3signer.signing.ValidatorManager) ListKeystoresHandler(tech.pegasys.web3signer.core.service.http.handlers.keymanager.list.ListKeystoresHandler) DeleteKeystoresHandler(tech.pegasys.web3signer.core.service.http.handlers.keymanager.delete.DeleteKeystoresHandler) SlashingProtectionMetrics(tech.pegasys.web3signer.core.metrics.SlashingProtectionMetrics) SignerForIdentifier(tech.pegasys.web3signer.core.service.http.handlers.signing.SignerForIdentifier) BlockingHandlerDecorator(io.vertx.ext.web.impl.BlockingHandlerDecorator) BlsArtifactSignature(tech.pegasys.web3signer.signing.BlsArtifactSignature) SlashingProtectionContext(tech.pegasys.web3signer.slashingprotection.SlashingProtectionContext) ImportKeystoresHandler(tech.pegasys.web3signer.core.service.http.handlers.keymanager.imports.ImportKeystoresHandler) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) Eth2SignForIdentifierHandler(tech.pegasys.web3signer.core.service.http.handlers.signing.eth2.Eth2SignForIdentifierHandler) HttpApiMetrics(tech.pegasys.web3signer.core.service.http.metrics.HttpApiMetrics)

Example 3 with BlockingHandlerDecorator

use of io.vertx.ext.web.impl.BlockingHandlerDecorator in project cryostat by cryostatio.

the class WebServer method start.

@Override
public void start() throws FlightRecorderException, SocketException, UnknownHostException {
    Router router = // a vertx is only available after server started
    Router.router(server.getVertx());
    // error page handler
    Handler<RoutingContext> failureHandler = ctx -> {
        HttpException exception;
        if (ctx.failure() instanceof HttpException) {
            exception = (HttpException) ctx.failure();
        } else if (ctx.failure() instanceof ApiException) {
            ApiException ex = (ApiException) ctx.failure();
            exception = new HttpException(ex.getStatusCode(), ex.getFailureReason(), ex);
        } else {
            exception = new HttpException(500, ctx.failure());
        }
        String payload = exception.getPayload() != null ? exception.getPayload() : exception.getMessage();
        if (!HttpStatusCodeIdentifier.isServerErrorCode(exception.getStatusCode())) {
            logger.warn("HTTP {}: {}\n{}", exception.getStatusCode(), payload, ExceptionUtils.getStackTrace(exception).trim());
        } else {
            logger.error("HTTP {}: {}\n{}", exception.getStatusCode(), payload, ExceptionUtils.getStackTrace(exception).trim());
        }
        if (exception.getStatusCode() == 401) {
            ctx.response().putHeader(AUTH_SCHEME_HEADER, auth.getScheme().toString());
        }
        ctx.response().setStatusCode(exception.getStatusCode());
        if (exception.getCause() instanceof ApiException) {
            ApiException ex = (ApiException) exception.getCause();
            String apiStatus = ex.getApiStatus() != null ? ex.getApiStatus() : EnglishReasonPhraseCatalog.INSTANCE.getReason(ex.getStatusCode(), null);
            ApiErrorResponse resp = new ApiErrorResponse(new ApiMeta(HttpMimeType.PLAINTEXT, apiStatus), new ApiErrorData(ex.getFailureReason()));
            ctx.response().putHeader(HttpHeaders.CONTENT_TYPE, HttpMimeType.JSON.mime()).end(gson.toJson(resp));
        } else {
            // kept for V1 API handler compatibility
            if (ExceptionUtils.hasCause(exception, HttpException.class)) {
                payload += " caused by " + ExceptionUtils.getRootCauseMessage(exception);
            }
            String accept = ctx.request().getHeader(HttpHeaders.ACCEPT);
            if (accept != null && accept.contains(HttpMimeType.JSON.mime()) && accept.indexOf(HttpMimeType.JSON.mime()) < accept.indexOf(HttpMimeType.PLAINTEXT.mime())) {
                ctx.response().putHeader(HttpHeaders.CONTENT_TYPE, HttpMimeType.JSON.mime()).end(gson.toJson(Map.of("message", payload)));
                return;
            }
            ctx.response().putHeader(HttpHeaders.CONTENT_TYPE, HttpMimeType.PLAINTEXT.mime()).end(payload);
        }
    };
    requestHandlers.forEach(handler -> {
        logger.trace("Registering request handler (priority {}) for [{}]\t{}", handler.getPriority(), handler.httpMethod(), handler.path());
        Route route;
        if (RequestHandler.ALL_PATHS.equals(handler.path())) {
            route = router.route();
        } else {
            route = router.route(handler.httpMethod(), handler.path());
        }
        route = route.order(handler.getPriority());
        if (handler.isAsync()) {
            route = route.handler(handler);
        } else {
            BlockingHandlerDecorator async = new BlockingHandlerDecorator(handler, handler.isOrdered());
            route = route.handler(async);
        }
        route = route.failureHandler(failureHandler);
        if (!handler.isAvailable()) {
            logger.trace("{} handler disabled", handler.getClass().getSimpleName());
            route = route.disable();
        }
    });
    this.server.requestHandler(req -> {
        Instant start = Instant.now();
        WebServerRequest evt = new WebServerRequest(req.remoteAddress().host(), req.remoteAddress().port(), req.method().toString(), req.path());
        evt.begin();
        req.response().endHandler((res) -> {
            logger.info("({}): {} {} {} {}ms", req.remoteAddress().toString(), req.method().toString(), req.path(), req.response().getStatusCode(), Duration.between(start, Instant.now()).toMillis());
            evt.setStatusCode(req.response().getStatusCode());
            evt.end();
            if (evt.shouldCommit()) {
                evt.commit();
            }
        });
        router.handle(req);
    });
}
Also used : ApiData(io.cryostat.net.web.http.api.ApiData) Event(jdk.jfr.Event) Label(jdk.jfr.Label) Arrays(java.util.Arrays) URL(java.net.URL) URISyntaxException(java.net.URISyntaxException) ApiResponse(io.cryostat.net.web.http.api.ApiResponse) Router(io.vertx.ext.web.Router) RoutingContext(io.vertx.ext.web.RoutingContext) ArrayList(java.util.ArrayList) Name(jdk.jfr.Name) SocketException(java.net.SocketException) HttpMimeType(io.cryostat.net.web.http.HttpMimeType) HttpServer(io.cryostat.net.HttpServer) Gson(com.google.gson.Gson) BlockingHandlerDecorator(io.vertx.ext.web.impl.BlockingHandlerDecorator) Duration(java.time.Duration) Map(java.util.Map) AuthManager(io.cryostat.net.AuthManager) Category(jdk.jfr.Category) Logger(io.cryostat.core.log.Logger) HttpStatusCodeIdentifier(io.cryostat.util.HttpStatusCodeIdentifier) ApiMeta(io.cryostat.net.web.http.api.ApiMeta) URI(java.net.URI) HttpException(io.vertx.ext.web.handler.HttpException) JFRConnection(io.cryostat.core.net.JFRConnection) Route(io.vertx.ext.web.Route) FlightRecorderException(org.openjdk.jmc.rjmx.services.jfr.FlightRecorderException) MalformedURLException(java.net.MalformedURLException) URIBuilder(org.apache.http.client.utils.URIBuilder) ApiVersion(io.cryostat.net.web.http.api.ApiVersion) Set(java.util.Set) HttpHeaders(io.vertx.core.http.HttpHeaders) IOException(java.io.IOException) NetworkConfiguration(io.cryostat.net.NetworkConfiguration) Instant(java.time.Instant) UnknownHostException(java.net.UnknownHostException) RequestHandler(io.cryostat.net.web.http.RequestHandler) List(java.util.List) EnglishReasonPhraseCatalog(org.apache.http.impl.EnglishReasonPhraseCatalog) AbstractVerticle(io.vertx.core.AbstractVerticle) Handler(io.vertx.core.Handler) Collections(java.util.Collections) ApiException(io.cryostat.net.web.http.api.v2.ApiException) SuppressFBWarnings(edu.umd.cs.findbugs.annotations.SuppressFBWarnings) ExceptionUtils(org.apache.commons.lang3.exception.ExceptionUtils) ApiMeta(io.cryostat.net.web.http.api.ApiMeta) Instant(java.time.Instant) Router(io.vertx.ext.web.Router) RoutingContext(io.vertx.ext.web.RoutingContext) BlockingHandlerDecorator(io.vertx.ext.web.impl.BlockingHandlerDecorator) HttpException(io.vertx.ext.web.handler.HttpException) Route(io.vertx.ext.web.Route) ApiException(io.cryostat.net.web.http.api.v2.ApiException)

Example 4 with BlockingHandlerDecorator

use of io.vertx.ext.web.impl.BlockingHandlerDecorator in project web3signer by ConsenSys.

the class Eth2Runner method registerEth2Routes.

private void registerEth2Routes(final RouterBuilder routerBuilder, final ArtifactSignerProvider blsSignerProvider, final LogErrorHandler errorHandler, final MetricsSystem metricsSystem, final Optional<SlashingProtection> slashingProtection) {
    final ObjectMapper objectMapper = SigningObjectMapperFactory.createObjectMapper();
    // security handler for keymanager endpoints
    routerBuilder.securityHandler("bearerAuth", context -> {
        // TODO Auth token security logic
        final boolean authorized = true;
        if (authorized) {
            context.next();
        } else {
            context.response().setStatusCode(401).end("{ message: \"permission denied\" }");
        }
    });
    addPublicKeysListHandler(routerBuilder, blsSignerProvider, ETH2_LIST.name(), errorHandler);
    final SignerForIdentifier<BlsArtifactSignature> blsSigner = new SignerForIdentifier<>(blsSignerProvider, this::formatBlsSignature, BLS);
    routerBuilder.operation(ETH2_SIGN.name()).handler(new BlockingHandlerDecorator(new Eth2SignForIdentifierHandler(blsSigner, new HttpApiMetrics(metricsSystem, BLS), new SlashingProtectionMetrics(metricsSystem), slashingProtection, objectMapper, eth2Spec), false)).failureHandler(errorHandler);
    addReloadHandler(routerBuilder, blsSignerProvider, RELOAD.name(), errorHandler);
    if (isKeyManagerApiEnabled) {
        routerBuilder.operation(KEYMANAGER_LIST.name()).handler(new BlockingHandlerDecorator(new ListKeystoresHandler(blsSignerProvider, objectMapper), false)).failureHandler(errorHandler);
        routerBuilder.operation(KEYMANAGER_IMPORT.name()).handler(new BlockingHandlerDecorator(new ImportKeystoresHandler(objectMapper, config.getKeyConfigPath(), slashingProtection, blsSignerProvider), false)).failureHandler(errorHandler);
        routerBuilder.operation(KEYMANAGER_DELETE.name()).handler(new BlockingHandlerDecorator(new DeleteKeystoresHandler(objectMapper, new KeystoreFileManager(config.getKeyConfigPath()), slashingProtection, blsSignerProvider), false)).failureHandler(errorHandler);
    }
}
Also used : KeystoreFileManager(tech.pegasys.web3signer.core.service.http.handlers.keymanager.delete.KeystoreFileManager) ListKeystoresHandler(tech.pegasys.web3signer.core.service.http.handlers.keymanager.list.ListKeystoresHandler) DeleteKeystoresHandler(tech.pegasys.web3signer.core.service.http.handlers.keymanager.delete.DeleteKeystoresHandler) SlashingProtectionMetrics(tech.pegasys.web3signer.core.metrics.SlashingProtectionMetrics) SignerForIdentifier(tech.pegasys.web3signer.core.service.http.handlers.signing.SignerForIdentifier) BlockingHandlerDecorator(io.vertx.ext.web.impl.BlockingHandlerDecorator) BlsArtifactSignature(tech.pegasys.web3signer.core.signing.BlsArtifactSignature) ImportKeystoresHandler(tech.pegasys.web3signer.core.service.http.handlers.keymanager.imports.ImportKeystoresHandler) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) Eth2SignForIdentifierHandler(tech.pegasys.web3signer.core.service.http.handlers.signing.eth2.Eth2SignForIdentifierHandler) HttpApiMetrics(tech.pegasys.web3signer.core.service.http.metrics.HttpApiMetrics)

Aggregations

BlockingHandlerDecorator (io.vertx.ext.web.impl.BlockingHandlerDecorator)4 SignerForIdentifier (tech.pegasys.web3signer.core.service.http.handlers.signing.SignerForIdentifier)3 HttpApiMetrics (tech.pegasys.web3signer.core.service.http.metrics.HttpApiMetrics)3 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)2 SlashingProtectionMetrics (tech.pegasys.web3signer.core.metrics.SlashingProtectionMetrics)2 DeleteKeystoresHandler (tech.pegasys.web3signer.core.service.http.handlers.keymanager.delete.DeleteKeystoresHandler)2 ImportKeystoresHandler (tech.pegasys.web3signer.core.service.http.handlers.keymanager.imports.ImportKeystoresHandler)2 ListKeystoresHandler (tech.pegasys.web3signer.core.service.http.handlers.keymanager.list.ListKeystoresHandler)2 Eth2SignForIdentifierHandler (tech.pegasys.web3signer.core.service.http.handlers.signing.eth2.Eth2SignForIdentifierHandler)2 Gson (com.google.gson.Gson)1 SuppressFBWarnings (edu.umd.cs.findbugs.annotations.SuppressFBWarnings)1 Logger (io.cryostat.core.log.Logger)1 JFRConnection (io.cryostat.core.net.JFRConnection)1 AuthManager (io.cryostat.net.AuthManager)1 HttpServer (io.cryostat.net.HttpServer)1 NetworkConfiguration (io.cryostat.net.NetworkConfiguration)1 HttpMimeType (io.cryostat.net.web.http.HttpMimeType)1 RequestHandler (io.cryostat.net.web.http.RequestHandler)1 ApiData (io.cryostat.net.web.http.api.ApiData)1 ApiMeta (io.cryostat.net.web.http.api.ApiMeta)1