Search in sources :

Example 16 with ServerInterceptor

use of io.grpc.ServerInterceptor in project grpc-java by grpc.

the class RbacFilter method generateAuthorizationInterceptor.

private ServerInterceptor generateAuthorizationInterceptor(AuthConfig config) {
    checkNotNull(config, "config");
    final GrpcAuthorizationEngine authEngine = new GrpcAuthorizationEngine(config);
    return new ServerInterceptor() {

        @Override
        public <ReqT, RespT> ServerCall.Listener<ReqT> interceptCall(final ServerCall<ReqT, RespT> call, final Metadata headers, ServerCallHandler<ReqT, RespT> next) {
            AuthDecision authResult = authEngine.evaluate(headers, call);
            if (logger.isLoggable(Level.FINE)) {
                logger.log(Level.FINE, "Authorization result for serverCall {0}: {1}, matching policy: {2}.", new Object[] { call, authResult.decision(), authResult.matchingPolicyName() });
            }
            if (GrpcAuthorizationEngine.Action.DENY.equals(authResult.decision())) {
                Status status = Status.PERMISSION_DENIED.withDescription("Access Denied");
                call.close(status, new Metadata());
                return new ServerCall.Listener<ReqT>() {
                };
            }
            return next.startCall(call, headers);
        }
    };
}
Also used : Status(io.grpc.Status) AuthDecision(io.grpc.xds.internal.rbac.engine.GrpcAuthorizationEngine.AuthDecision) ServerCallHandler(io.grpc.ServerCallHandler) ServerCall(io.grpc.ServerCall) ServerInterceptor(io.grpc.ServerInterceptor) Metadata(io.grpc.Metadata) GrpcAuthorizationEngine(io.grpc.xds.internal.rbac.engine.GrpcAuthorizationEngine)

Example 17 with ServerInterceptor

use of io.grpc.ServerInterceptor in project jetcd by coreos.

the class AuthUnitTest method testHeaders.

@Test
public void testHeaders() throws Exception {
    MutableHandlerRegistry serviceRegistry = new MutableHandlerRegistry();
    serviceRegistry.addService(new AuthGrpc.AuthImplBase() {

        @Override
        public void authenticate(io.etcd.jetcd.api.AuthenticateRequest request, io.grpc.stub.StreamObserver<io.etcd.jetcd.api.AuthenticateResponse> responseObserver) {
            responseObserver.onNext(AuthenticateResponse.newBuilder().setToken("token").build());
        }
    });
    serviceRegistry.addService(new KVGrpc.KVImplBase() {

        @Override
        public void put(io.etcd.jetcd.api.PutRequest request, io.grpc.stub.StreamObserver<io.etcd.jetcd.api.PutResponse> responseObserver) {
            responseObserver.onNext(PutResponse.newBuilder().build());
        }
    });
    Server server = null;
    Client client = null;
    try {
        Metadata intercepted = new Metadata();
        server = NettyServerBuilder.forPort(0).fallbackHandlerRegistry(serviceRegistry).intercept(new ServerInterceptor() {

            @Override
            public <ReqT, RespT> ServerCall.Listener<ReqT> interceptCall(ServerCall<ReqT, RespT> call, Metadata headers, ServerCallHandler<ReqT, RespT> next) {
                if (AUTHENTICATE_METHOD_NAME.equals(call.getMethodDescriptor().getFullMethodName())) {
                    intercepted.merge(headers);
                }
                return next.startCall(new ForwardingServerCall.SimpleForwardingServerCall<>(call) {
                }, headers);
            }
        }).directExecutor().build().start();
        client = Client.builder().endpoints(new URI("http://127.0.0.1:" + server.getPort())).user(user).password(userPass).authHeader("foo-a", "foo-auth").header("bar-h", "bar").build();
        client.getKVClient().put(key, value).get(30, TimeUnit.SECONDS);
        assertThat(intercepted.keys()).contains("foo-a");
    } finally {
        if (client != null) {
            client.close();
        }
        if (server != null) {
            server.shutdownNow();
        }
    }
}
Also used : AuthenticateResponse(io.etcd.jetcd.api.AuthenticateResponse) Server(io.grpc.Server) Metadata(io.grpc.Metadata) PutResponse(io.etcd.jetcd.api.PutResponse) URI(java.net.URI) Client(io.etcd.jetcd.Client) MutableHandlerRegistry(io.grpc.util.MutableHandlerRegistry) KVGrpc(io.etcd.jetcd.api.KVGrpc) AuthGrpc(io.etcd.jetcd.api.AuthGrpc) ServerInterceptor(io.grpc.ServerInterceptor) Test(org.junit.jupiter.api.Test)

Example 18 with ServerInterceptor

use of io.grpc.ServerInterceptor in project brave by openzipkin.

the class BaseITTracingServerInterceptor method userInterceptor_throwsOnSendMessage.

@Test
public void userInterceptor_throwsOnSendMessage() throws IOException {
    init(new ServerInterceptor() {

        @Override
        public <ReqT, RespT> ServerCall.Listener<ReqT> interceptCall(ServerCall<ReqT, RespT> call, Metadata metadata, ServerCallHandler<ReqT, RespT> next) {
            return next.startCall(new SimpleForwardingServerCall<ReqT, RespT>(call) {

                @Override
                public void sendMessage(RespT message) {
                    throw new IllegalStateException("I'm a bad interceptor.");
                }
            }, metadata);
        }
    });
    assertThatThrownBy(() -> GreeterGrpc.newBlockingStub(client).sayHello(HELLO_REQUEST)).isInstanceOf(StatusRuntimeException.class);
    testSpanHandler.takeRemoteSpanWithErrorMessage(Span.Kind.SERVER, "I'm a bad interceptor.");
}
Also used : SimpleForwardingServerCallListener(io.grpc.ForwardingServerCallListener.SimpleForwardingServerCallListener) ServerInterceptor(io.grpc.ServerInterceptor) Metadata(io.grpc.Metadata) SimpleForwardingServerCall(io.grpc.ForwardingServerCall.SimpleForwardingServerCall) Test(org.junit.Test)

Example 19 with ServerInterceptor

use of io.grpc.ServerInterceptor in project brave by openzipkin.

the class BaseITTracingServerInterceptor method bodyTaggingExample.

/**
 * This shows that a {@link ServerInterceptor} can see the server server span when processing the
 * request and response.
 */
@Test
public void bodyTaggingExample() throws IOException {
    SpanCustomizer customizer = CurrentSpanCustomizer.create(tracing);
    AtomicInteger sends = new AtomicInteger();
    AtomicInteger recvs = new AtomicInteger();
    init(new ServerInterceptor() {

        @Override
        public <ReqT, RespT> ServerCall.Listener<ReqT> interceptCall(ServerCall<ReqT, RespT> call, Metadata headers, ServerCallHandler<ReqT, RespT> next) {
            call = new SimpleForwardingServerCall<ReqT, RespT>(call) {

                @Override
                public void sendMessage(RespT message) {
                    delegate().sendMessage(message);
                    customizer.tag("grpc.message_send." + sends.getAndIncrement(), message.toString());
                }
            };
            return new SimpleForwardingServerCallListener<ReqT>(next.startCall(call, headers)) {

                @Override
                public void onMessage(ReqT message) {
                    customizer.tag("grpc.message_recv." + recvs.getAndIncrement(), message.toString());
                    delegate().onMessage(message);
                }
            };
        }
    });
    GreeterGrpc.newBlockingStub(client).sayHello(HELLO_REQUEST);
    assertThat(testSpanHandler.takeRemoteSpan(Span.Kind.SERVER).tags()).containsKeys("grpc.message_recv.0", "grpc.message_send.0");
    Iterator<HelloReply> replies = GreeterGrpc.newBlockingStub(client).sayHelloWithManyReplies(HELLO_REQUEST);
    assertThat(replies).toIterable().hasSize(10);
    // Intentionally verbose here to show that only one recv and 10 replies
    assertThat(testSpanHandler.takeRemoteSpan(Span.Kind.SERVER).tags()).containsKeys("grpc.message_recv.1", "grpc.message_send.1", "grpc.message_send.2", "grpc.message_send.3", "grpc.message_send.4", "grpc.message_send.5", "grpc.message_send.6", "grpc.message_send.7", "grpc.message_send.8", "grpc.message_send.9", "grpc.message_send.10");
}
Also used : SimpleForwardingServerCallListener(io.grpc.ForwardingServerCallListener.SimpleForwardingServerCallListener) Metadata(io.grpc.Metadata) SimpleForwardingServerCall(io.grpc.ForwardingServerCall.SimpleForwardingServerCall) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) ServerInterceptor(io.grpc.ServerInterceptor) HelloReply(io.grpc.examples.helloworld.HelloReply) CurrentSpanCustomizer(brave.CurrentSpanCustomizer) SpanCustomizer(brave.SpanCustomizer) Test(org.junit.Test)

Example 20 with ServerInterceptor

use of io.grpc.ServerInterceptor in project brave by openzipkin.

the class BaseITTracingServerInterceptor method currentSpanVisibleToUserInterceptors.

/**
 * NOTE: for this to work, the tracing interceptor must be last (so that it executes first)
 *
 * <p>Also notice that we are only making the current context available in the request side.
 */
@Test
public void currentSpanVisibleToUserInterceptors() throws IOException {
    AtomicReference<TraceContext> fromUserInterceptor = new AtomicReference<>();
    init(new ServerInterceptor() {

        @Override
        public <ReqT, RespT> ServerCall.Listener<ReqT> interceptCall(ServerCall<ReqT, RespT> call, Metadata headers, ServerCallHandler<ReqT, RespT> next) {
            fromUserInterceptor.set(tracing.currentTraceContext().get());
            return next.startCall(call, headers);
        }
    });
    GreeterGrpc.newBlockingStub(client).sayHello(HELLO_REQUEST);
    assertThat(fromUserInterceptor.get()).isNotNull();
    testSpanHandler.takeRemoteSpan(Span.Kind.SERVER);
}
Also used : SimpleForwardingServerCallListener(io.grpc.ForwardingServerCallListener.SimpleForwardingServerCallListener) ServerInterceptor(io.grpc.ServerInterceptor) Metadata(io.grpc.Metadata) TraceContext(brave.propagation.TraceContext) AtomicReference(java.util.concurrent.atomic.AtomicReference) Test(org.junit.Test)

Aggregations

ServerInterceptor (io.grpc.ServerInterceptor)37 Metadata (io.grpc.Metadata)23 Test (org.junit.Test)15 ServerCall (io.grpc.ServerCall)10 ServerCallHandler (io.grpc.ServerCallHandler)9 SimpleForwardingServerCallListener (io.grpc.ForwardingServerCallListener.SimpleForwardingServerCallListener)7 Server (io.grpc.Server)6 IOException (java.io.IOException)6 SimpleForwardingServerCall (io.grpc.ForwardingServerCall.SimpleForwardingServerCall)4 Status (io.grpc.Status)4 ManagedChannel (io.grpc.ManagedChannel)3 Listener (io.grpc.ServerCall.Listener)3 ServerTransportFilter (io.grpc.ServerTransportFilter)3 InetSocketAddress (java.net.InetSocketAddress)3 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)3 TraceContext (brave.propagation.TraceContext)2 GrpcStreamConfiguration (com.navercorp.pinpoint.collector.grpc.config.GrpcStreamConfiguration)2 DefaultServerRequestFactory (com.navercorp.pinpoint.collector.receiver.grpc.service.DefaultServerRequestFactory)2 StreamExecutorServerInterceptorFactory (com.navercorp.pinpoint.collector.receiver.grpc.service.StreamExecutorServerInterceptorFactory)2 MetadataServerTransportFilter (com.navercorp.pinpoint.grpc.server.MetadataServerTransportFilter)2