Search in sources :

Example 1 with HttpService

use of com.linecorp.armeria.server.HttpService in project curiostack by curioswitch.

the class ServerModule method decorateService.

private static HttpService decorateService(HttpService service, Tracing tracing, Lazy<FirebaseAuthorizer> firebaseAuthorizer, Lazy<JwtAuthorizer.Factory> jwtAuthorizer, Optional<SslCommonNamesProvider> sslCommonNamesProvider, ServerConfig serverConfig, FirebaseAuthConfig authConfig) {
    if (sslCommonNamesProvider.isPresent() && !serverConfig.isDisableSslAuthorization()) {
        AuthServiceBuilder authServiceBuilder = AuthService.builder();
        authServiceBuilder.add(new SslAuthorizer(sslCommonNamesProvider.get()));
        service = service.decorate(authServiceBuilder.newDecorator());
    }
    if (serverConfig.isEnableIapAuthorization()) {
        service = service.decorate((delegate, ctx, req) -> {
            DecodedJWT jwt = ctx.attr(JwtAuthorizer.DECODED_JWT);
            String loggedInUserEmail = jwt != null ? jwt.getClaim("email").asString() : "unknown";
            RequestLoggingContext.put(ctx, "logged_in_user", loggedInUserEmail);
            return delegate.serve(ctx, req);
        }).decorate(AuthService.builder().addTokenAuthorizer(headers -> OAuth2Token.of(headers.get(HttpHeaderNames.of("x-goog-iap-jwt-assertion"))), jwtAuthorizer.get().create(Algorithm.ES256, "https://www.gstatic.com/iap/verify/public_key")).newDecorator());
    }
    if (!authConfig.getServiceAccountBase64().isEmpty()) {
        FirebaseAuthorizer authorizer = firebaseAuthorizer.get();
        service = service.decorate(AuthService.builder().addOAuth2(authorizer).onFailure(authorizer).newDecorator());
    }
    service = service.decorate(MetricCollectingService.newDecorator(RpcMetricLabels.grpcRequestLabeler("grpc_services"))).decorate(BraveService.newDecorator(tracing)).decorate((delegate, ctx, req) -> {
        TraceContext traceCtx = tracing.currentTraceContext().get();
        if (traceCtx != null) {
            RequestLoggingContext.put(ctx, "traceId", traceCtx.traceIdString());
            RequestLoggingContext.put(ctx, "spanId", traceCtx.spanIdString());
        }
        return delegate.serve(ctx, req);
    });
    return service;
}
Also used : ResourceUtil(org.curioswitch.common.server.framework.util.ResourceUtil) StaticSiteService(org.curioswitch.common.server.framework.staticsite.StaticSiteService) SslCommonNamesProvider(org.curioswitch.common.server.framework.auth.ssl.SslCommonNamesProvider) KeyStoreException(java.security.KeyStoreException) GrpcService(com.linecorp.armeria.server.grpc.GrpcService) ClientAuth(io.netty.handler.ssl.ClientAuth) Module(dagger.Module) OAuth2Token(com.linecorp.armeria.common.auth.OAuth2Token) Multibinds(dagger.multibindings.Multibinds) Duration(java.time.Duration) RpcAclsCommonNamesProvider(org.curioswitch.common.server.framework.auth.ssl.RpcAclsCommonNamesProvider) Path(java.nio.file.Path) ApplicationProtocolConfig(io.netty.handler.ssl.ApplicationProtocolConfig) LoggingService(com.linecorp.armeria.server.logging.LoggingService) Production(dagger.producers.Production) SelectedListenerFailureBehavior(io.netty.handler.ssl.ApplicationProtocolConfig.SelectedListenerFailureBehavior) CollectorRegistry(io.prometheus.client.CollectorRegistry) ServiceRequestContext(com.linecorp.armeria.server.ServiceRequestContext) ImmutableList.toImmutableList(com.google.common.collect.ImmutableList.toImmutableList) Set(java.util.Set) JavascriptStaticService(org.curioswitch.common.server.framework.staticsite.JavascriptStaticService) StaticSiteServiceDefinition(org.curioswitch.common.server.framework.staticsite.StaticSiteServiceDefinition) TraceContext(brave.propagation.TraceContext) Lazy(dagger.Lazy) UncheckedIOException(java.io.UncheckedIOException) SecurityModule(org.curioswitch.common.server.framework.security.SecurityModule) Logger(org.apache.logging.log4j.Logger) FirebaseAuthorizer(org.curioswitch.common.server.framework.auth.firebase.FirebaseAuthorizer) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) StackdriverReporter(org.curioswitch.common.server.framework.monitoring.StackdriverReporter) ModifiableServerConfig(org.curioswitch.common.server.framework.config.ModifiableServerConfig) ConfigBeanFactory(com.typesafe.config.ConfigBeanFactory) DecodedJWT(com.auth0.jwt.interfaces.DecodedJWT) ModifiableJavascriptStaticConfig(org.curioswitch.common.server.framework.config.ModifiableJavascriptStaticConfig) ProtoReflectionService(io.grpc.protobuf.services.ProtoReflectionService) GrpcSerializationFormats(com.linecorp.armeria.common.grpc.GrpcSerializationFormats) InsecureTrustManagerFactory(io.netty.handler.ssl.util.InsecureTrustManagerFactory) SslContextKeyConverter(org.curioswitch.common.server.framework.armeria.SslContextKeyConverter) HttpService(com.linecorp.armeria.server.HttpService) SettableHealthChecker(com.linecorp.armeria.server.healthcheck.SettableHealthChecker) Config(com.typesafe.config.Config) Executor(java.util.concurrent.Executor) IOException(java.io.IOException) Futures(com.google.common.util.concurrent.Futures) HttpsOnlyService(org.curioswitch.common.server.framework.security.HttpsOnlyService) Paths(java.nio.file.Paths) JavascriptStaticConfig(org.curioswitch.common.server.framework.config.JavascriptStaticConfig) X509Certificate(java.security.cert.X509Certificate) CertificateFactory(java.security.cert.CertificateFactory) Algorithm(org.curioswitch.common.server.framework.auth.jwt.JwtVerifier.Algorithm) IpFilteringService(org.curioswitch.common.server.framework.filter.IpFilteringService) FileWatcher(org.curioswitch.common.server.framework.files.FileWatcher) HttpHeaderNames(com.linecorp.armeria.common.HttpHeaderNames) FirebaseAuthModule(org.curioswitch.common.server.framework.auth.firebase.FirebaseAuthModule) SecurityConfig(org.curioswitch.common.server.framework.config.SecurityConfig) BraveService(com.linecorp.armeria.server.brave.BraveService) Server(com.linecorp.armeria.server.Server) DSLContext(org.jooq.DSLContext) DocService(com.linecorp.armeria.server.docs.DocService) FirebaseAuthConfig(org.curioswitch.common.server.framework.auth.firebase.FirebaseAuthConfig) HttpServiceWithRoutes(com.linecorp.armeria.server.HttpServiceWithRoutes) HttpResponse(com.linecorp.armeria.common.HttpResponse) ImmutableSet(com.google.common.collect.ImmutableSet) TrustManagerFactory(javax.net.ssl.TrustManagerFactory) GcloudAuthModule(org.curioswitch.curiostack.gcloud.core.auth.GcloudAuthModule) AuthServiceBuilder(com.linecorp.armeria.server.auth.AuthServiceBuilder) GrpcServiceDefinition(org.curioswitch.common.server.framework.grpc.GrpcServiceDefinition) KeyStore(java.security.KeyStore) RequestContext(com.linecorp.armeria.common.RequestContext) List(java.util.List) WatchedPath(org.curioswitch.common.server.framework.files.WatchedPath) HealthCheckService(com.linecorp.armeria.server.healthcheck.HealthCheckService) PostServerCustomizer(org.curioswitch.common.server.framework.server.PostServerCustomizer) Optional(java.util.Optional) BindsOptionalOf(dagger.BindsOptionalOf) ServerBuilder(com.linecorp.armeria.server.ServerBuilder) BindableService(io.grpc.BindableService) MetricsHttpService(org.curioswitch.common.server.framework.monitoring.MetricsHttpService) MonitoringModule(org.curioswitch.common.server.framework.monitoring.MonitoringModule) Singleton(javax.inject.Singleton) PrometheusExpositionService(com.linecorp.armeria.server.metric.PrometheusExpositionService) Function(java.util.function.Function) MediaType(com.linecorp.armeria.common.MediaType) ServerListener(com.linecorp.armeria.server.ServerListener) RequestLoggingContext(org.curioswitch.common.server.framework.logging.RequestLoggingContext) ImmutableList(com.google.common.collect.ImmutableList) RpcMetricLabels(org.curioswitch.common.server.framework.monitoring.RpcMetricLabels) HttpStatus(com.linecorp.armeria.common.HttpStatus) HttpServiceDefinition(org.curioswitch.common.server.framework.server.HttpServiceDefinition) JwtModule(org.curioswitch.common.server.framework.auth.jwt.JwtModule) Protocol(io.netty.handler.ssl.ApplicationProtocolConfig.Protocol) JwtAuthorizer(org.curioswitch.common.server.framework.auth.jwt.JwtAuthorizer) MetricCollectingService(com.linecorp.armeria.server.metric.MetricCollectingService) Provides(dagger.Provides) Tracing(brave.Tracing) EagerInit(org.curioswitch.common.server.framework.inject.EagerInit) SelfSignedCertificate(io.netty.handler.ssl.util.SelfSignedCertificate) ApplicationProtocolNames(io.netty.handler.ssl.ApplicationProtocolNames) SslAuthorizer(org.curioswitch.common.server.framework.auth.ssl.SslAuthorizer) DocServiceBuilder(com.linecorp.armeria.server.docs.DocServiceBuilder) CertificateException(java.security.cert.CertificateException) HealthChecker(com.linecorp.armeria.server.healthcheck.HealthChecker) TimeUnit(java.util.concurrent.TimeUnit) Consumer(java.util.function.Consumer) AuthService(com.linecorp.armeria.server.auth.AuthService) SelectorFailureBehavior(io.netty.handler.ssl.ApplicationProtocolConfig.SelectorFailureBehavior) ServerConfig(org.curioswitch.common.server.framework.config.ServerConfig) ServerShutDownDelayer(org.curioswitch.common.server.framework.server.ServerShutDownDelayer) MeterRegistry(io.micrometer.core.instrument.MeterRegistry) LoggingModule(org.curioswitch.common.server.framework.logging.LoggingModule) Closeable(java.io.Closeable) GcloudIamModule(org.curioswitch.curiostack.gcloud.iam.GcloudIamModule) MonitoringConfig(org.curioswitch.common.server.framework.config.MonitoringConfig) CloseOnStop(org.curioswitch.common.server.framework.inject.CloseOnStop) GrpcServiceBuilder(com.linecorp.armeria.server.grpc.GrpcServiceBuilder) LogManager(org.apache.logging.log4j.LogManager) InputStream(java.io.InputStream) SslAuthorizer(org.curioswitch.common.server.framework.auth.ssl.SslAuthorizer) FirebaseAuthorizer(org.curioswitch.common.server.framework.auth.firebase.FirebaseAuthorizer) TraceContext(brave.propagation.TraceContext) AuthServiceBuilder(com.linecorp.armeria.server.auth.AuthServiceBuilder) DecodedJWT(com.auth0.jwt.interfaces.DecodedJWT)

Example 2 with HttpService

use of com.linecorp.armeria.server.HttpService in project curiostack by curioswitch.

the class StaticSiteService method addToServer.

/**
 * Creates a new {@link StaticSiteService}.
 *
 * @param staticPath the URL path from which static resources will be served, e.g., "/static".
 * @param classpathRoot the root directory in the classpath to serve resources from.
 */
public static void addToServer(String urlRoot, String staticPath, String classpathRoot, ServerBuilder sb) {
    FileService staticFileService = FileService.builder(StaticSiteService.class.getClassLoader(), classpathRoot).serveCompressedFiles(true).cacheControl(ServerCacheControl.IMMUTABLE).addHeader(HttpHeaderNames.VARY, "Accept-Encoding").build();
    HttpService indexHtmlService = HttpFile.builder(StaticSiteService.class.getClassLoader(), classpathRoot + "/index.html").cacheControl(ServerCacheControl.DISABLED).build().asService();
    TrailingSlashAddingService indexService = FileService.builder(StaticSiteService.class.getClassLoader(), classpathRoot).serveCompressedFiles(true).cacheControl(ServerCacheControl.DISABLED).build().orElse(indexHtmlService).decorate(TrailingSlashAddingService::new);
    String urlRootWithTrailingSlash = urlRoot.endsWith("/") ? urlRoot : urlRoot + "/";
    String staticPathWithoutLeadingSlash = staticPath.startsWith("/") ? staticPath.substring(1) : staticPath;
    sb.serviceUnder(urlRootWithTrailingSlash + staticPathWithoutLeadingSlash, staticFileService).serviceUnder(urlRootWithTrailingSlash, indexService);
}
Also used : FileService(com.linecorp.armeria.server.file.FileService) SimpleDecoratingHttpService(com.linecorp.armeria.server.SimpleDecoratingHttpService) HttpService(com.linecorp.armeria.server.HttpService)

Example 3 with HttpService

use of com.linecorp.armeria.server.HttpService in project zipkin by openzipkin.

the class ZipkinUiConfiguration method uiServerConfigurator.

@Bean
ArmeriaServerConfigurator uiServerConfigurator(HttpService indexService, Optional<MeterRegistry> meterRegistry) throws IOException {
    ServerCacheControl maxAgeYear = ServerCacheControl.builder().maxAgeSeconds(TimeUnit.DAYS.toSeconds(365)).build();
    HttpService uiFileService = FileService.builder(getClass().getClassLoader(), "zipkin-lens").cacheControl(maxAgeYear).build();
    String config = writeConfig(ui);
    return sb -> {
        sb.service("/zipkin/config.json", HttpFile.builder(HttpData.ofUtf8(config)).cacheControl(ServerCacheControl.builder().maxAgeSeconds(600).build()).contentType(MediaType.JSON_UTF_8).build().asService());
        sb.serviceUnder("/zipkin/", uiFileService);
        // TODO This approach requires maintenance when new UI routes are added. Change to the following:
        // If the path is a a file w/an extension, treat normally.
        // Otherwise instead of returning 404, forward to the index.
        // See https://github.com/twitter/finatra/blob/458c6b639c3afb4e29873d123125eeeb2b02e2cd/http/src/main/scala/com/twitter/finatra/http/response/ResponseBuilder.scala#L321
        sb.service("/zipkin/", indexService).service("/zipkin/index.html", indexService).service("/zipkin/traces/{id}", indexService).service("/zipkin/dependency", indexService).service("/zipkin/traceViewer", indexService);
        sb.service("/favicon.ico", new RedirectService(HttpStatus.FOUND, "/zipkin/favicon.ico")).service("/", new RedirectService(HttpStatus.FOUND, "/zipkin/")).service("/zipkin", new RedirectService(HttpStatus.FOUND, "/zipkin/"));
        // don't add metrics for favicon
        meterRegistry.ifPresent(m -> m.config().meterFilter(MeterFilter.deny(id -> {
            String uri = id.getTag("uri");
            return uri != null && uri.startsWith("/favicon.ico");
        })));
    };
}
Also used : MeterFilter(io.micrometer.core.instrument.config.MeterFilter) ArmeriaServerConfigurator(com.linecorp.armeria.spring.ArmeriaServerConfigurator) JsonGenerator(com.fasterxml.jackson.core.JsonGenerator) FileService(com.linecorp.armeria.server.file.FileService) Autowired(org.springframework.beans.factory.annotation.Autowired) DEFAULT_BASEPATH(zipkin2.server.internal.ui.ZipkinUiProperties.DEFAULT_BASEPATH) MediaType(com.linecorp.armeria.common.MediaType) HttpFile(com.linecorp.armeria.server.file.HttpFile) Value(org.springframework.beans.factory.annotation.Value) HttpStatus(com.linecorp.armeria.common.HttpStatus) BeanCreationException(org.springframework.beans.factory.BeanCreationException) EnableConfigurationProperties(org.springframework.boot.context.properties.EnableConfigurationProperties) HttpService(com.linecorp.armeria.server.HttpService) ConditionalOnProperty(org.springframework.boot.autoconfigure.condition.ConditionalOnProperty) Resource(org.springframework.core.io.Resource) HttpData(com.linecorp.armeria.common.HttpData) StreamUtils(org.springframework.util.StreamUtils) ServerCacheControl(com.linecorp.armeria.common.ServerCacheControl) UTF_8(java.nio.charset.StandardCharsets.UTF_8) RedirectService(com.linecorp.armeria.server.RedirectService) StringWriter(java.io.StringWriter) IOException(java.io.IOException) TimeUnit(java.util.concurrent.TimeUnit) MeterRegistry(io.micrometer.core.instrument.MeterRegistry) JsonUtil(zipkin2.server.internal.JsonUtil) Optional(java.util.Optional) Bean(org.springframework.context.annotation.Bean) InputStream(java.io.InputStream) HttpService(com.linecorp.armeria.server.HttpService) RedirectService(com.linecorp.armeria.server.RedirectService) ServerCacheControl(com.linecorp.armeria.common.ServerCacheControl) Bean(org.springframework.context.annotation.Bean)

Aggregations

HttpService (com.linecorp.armeria.server.HttpService)3 HttpStatus (com.linecorp.armeria.common.HttpStatus)2 MediaType (com.linecorp.armeria.common.MediaType)2 FileService (com.linecorp.armeria.server.file.FileService)2 Tracing (brave.Tracing)1 TraceContext (brave.propagation.TraceContext)1 DecodedJWT (com.auth0.jwt.interfaces.DecodedJWT)1 JsonGenerator (com.fasterxml.jackson.core.JsonGenerator)1 ImmutableList (com.google.common.collect.ImmutableList)1 ImmutableList.toImmutableList (com.google.common.collect.ImmutableList.toImmutableList)1 ImmutableSet (com.google.common.collect.ImmutableSet)1 Futures (com.google.common.util.concurrent.Futures)1 HttpData (com.linecorp.armeria.common.HttpData)1 HttpHeaderNames (com.linecorp.armeria.common.HttpHeaderNames)1 HttpResponse (com.linecorp.armeria.common.HttpResponse)1 RequestContext (com.linecorp.armeria.common.RequestContext)1 ServerCacheControl (com.linecorp.armeria.common.ServerCacheControl)1 OAuth2Token (com.linecorp.armeria.common.auth.OAuth2Token)1 GrpcSerializationFormats (com.linecorp.armeria.common.grpc.GrpcSerializationFormats)1 HttpServiceWithRoutes (com.linecorp.armeria.server.HttpServiceWithRoutes)1