grpc-java icon indicating copy to clipboard operation
grpc-java copied to clipboard

Access to controller (for connection metadata)

Open justinsb opened this issue 11 years ago • 18 comments

I would like to get the remote client's IP and TLS client-certificate from within a GRPC service. And I guess cancellation information as well.

Protobuf services had the controller argument. Is there an equivalent in GRPC?

justinsb avatar Mar 07 '15 18:03 justinsb

I think the best way to provide this information is as header metadata. What would you do with this information? Some form of ACLing?

louiscryan avatar Mar 09 '15 17:03 louiscryan

Yes, I was planning on using the client-cert for authentication.

Is there a way to get the header metadata inside the service method?

justinsb avatar Mar 09 '15 18:03 justinsb

I would suggest you use a ServerInterceptor to implement this logic in a cross-cutting fashion rather than trying to code it into your service methods. Our interfaces are designed to encourage layering in common cross-cutting behaviors like auth/acl/log/monitor/... in a service-interface agnostic way.

louiscryan avatar Mar 09 '15 18:03 louiscryan

I agree that auth belongs in a cross-cutting layer. But I'll still need the "current user id" in the service method. So how can I communicate from the ServerInterceptor to the service method? I just don't see any means by which I can do this: StreamObserver is pretty sparse and I don't think I could get something useful even with a lot of type-casts. I don't think I can use ThreadLocals because of Netty's threading model.

I was expecting to see a Context object, just like we get in C++: https://github.com/grpc/grpc-common/blob/master/cpp/helloworld/greeter_server.cc#L54-L55

Really appreciate your help on this, by the way. I'm excited to use GRPC, having implemented protobuf-service-transports poorly myself more times than I care to admit.

justinsb avatar Mar 09 '15 19:03 justinsb

It should be easy enough to use ThreadLocal as the interceptor interfaces provide closure over calls into your service implementation via ServerCall.Listener#onPayload

louiscryan avatar Mar 09 '15 20:03 louiscryan

OK. Is there a reason you don't pass a context object though? Would you accept a PR that added a context object?

justinsb avatar Mar 09 '15 20:03 justinsb

There are a few reasons why we did this:

We looked at all the internal code using context-objects and found < 1% of per-service code doing anything meaningful with it and that largely reduced to varying timeouts. Anything more interesting was being done with interceptors as a cross-cut

We're strong believers in IoC containers and they provide nice facilities for binding request scoped values which are easily populated by the interceptor pattern. This makes your code easier to test as your test can fake/mock production of the value more easily. This can be done without something like Guice/Spring using ThreadLocal. I'd love to see a contribution for that. E.g.

class YourServiceImpl implements YourServiceInterface {
   public YourServiceImpl(Provider<CertDetails> certDetails) {
      this.certDetails = certDetails;
   }

   public Response someOperation(Request req) {
     certDetails.get() // Returns request scoped value
   }

CertDetailsInterceptor x = new CertDetailsInterceptor();
YourServiceImpl serviceImpl = new YourServiceImpl(x.provider());

This pattern can be generalized easily enough to handle any type bound to Metadata

louiscryan avatar Mar 09 '15 23:03 louiscryan

Ah! I am also a big fan of Guice, and I think injection could be a great approach here. Thanks for the hints - I'll give it a go.

justinsb avatar Mar 10 '15 00:03 justinsb

So it looks like I'd have also to change the Netty code to get to the client certificate. (right?)

I was thinking that this is similar to header information, and that it therefore should be stored into Metadata.Headers (special-cased like path & authority).

Then I'd still have to implement the interceptor - I was thinking of building a GrpcContext object to which would be a thread-local, which would allow access to the headers, along with some notion of the session (as defined by the current collection).

At this point, I feel like I'm really changing huge chunks of GRPC, and I'm sure I'd be doing it in the way you would like. Do you have any plans to implement this functionality?

justinsb avatar Mar 14 '15 13:03 justinsb

Created a straw-man patch/PR. Comments welcome!

justinsb avatar Mar 15 '15 22:03 justinsb

+1 to providing access to the client's certificate. Supporting TLS client auth is great, but of very limited value if the server cannot determine the client's identity.

matthild avatar Jul 05 '15 15:07 matthild

+1

hughneale avatar Feb 25 '16 09:02 hughneale

With #1506, there is now an attributes() method on ServerCall. You can use the keys in #1564 to access the SslSession and IP address.

ejona86 avatar Mar 22 '16 16:03 ejona86

So, to recap. How do you get the "current user id" in service method?

I have a bidirectional stream and need to know which client I am talking to.

public StreamObserver<GameAction> connectToGame(final StreamObserver<GameState> responseObserver) {
    return new StreamObserver<GameAction>() {
        public void onNext(GameAction value) {}
        public void onError(Throwable t) {}
        public void onCompleted() {}
    };
}

I could implement custom handshake logic if I were to send the client id with every message, something like this

public void onNext(GameAction action) {
    int playerId = action.getId();
    if (action.getActionCase() == HELLO) {
        // initialize
    } else {
        // handle actual messages
    }
}

But the id cannot be trusted, I need more secure way to identify the client and in case of an error, how would I know which client got the error?

public void onError(Throwable t) { 
    // which client? 
}

Also, I do have a working HeaderServerInterceptor implementation and can print out "current user id" from the headers, which the client put there, but how do I communicate it to service method?

lploom avatar Sep 16 '16 19:09 lploom

@lploom you should try using Context:

// create user id context key
static Context.Key<Long> USER_ID_CTX_KEY = Context.key("user-id");
// create context, assign value to key
Context ctx = Context.current().withValue(USER_ID_CTX_KEY, 123);
// wrap the call that you're returning from interceptor and pass down context
return Contexts.interceptCall(ctx, call, headers, next);
// then in the action access it
USER_ID_CTX_KEY.get();

lukaszx0 avatar Sep 16 '16 19:09 lukaszx0

@lukaszx0 Thanks. Seems that I got it working. I am certainly not used to doing things this way.

lploom avatar Sep 17 '16 11:09 lploom

@lukaszx0 I have implemented exactly that but USER_ID_CTX_KEY.get() is always returning null! Could you please tell me what's wrong with the code?

The server interceptor:

public class HeaderServerInterceptor implements ServerInterceptor {
  private static Context.Key<Long> USER_ID_CTX_KEY = Context.key("user-id");

  public <ReqT, RespT> ServerCall.Listener<ReqT> interceptCall(ServerCall<ReqT, RespT> call, final, Metadata requestHeaders, ServerCallHandler<ReqT, RespT> next) {

    Metadata.Key<String> authorization = Metadata.Key.of("authorization", Metadata.ASCII_STRING_MARSHALLER);
    System.out.println("header received from client:" + requestHeaders.get(authorization));


    Context ctx = Context.current().withValue(USER_ID_CTX_KEY, 123L);
    return Contexts.interceptCall(ctx, call, requestHeaders, next);
  }
}

Accessing it in the service's RPC is always returning null:

public void getData(UserRequest request, StreamObserver<UserResponse> responseObserver) {

    Context.Key<Long> USER_ID_CTX_KEY = Context.key("user-id");
    System.out.printlin("----------------> user id is " + USER_ID_CTX_KEY.get());
    // build the response 
    responseObserver.onNext(response);
    responseObserver.onCompleted();
}

What's missing in the code? Thanks.

haggag avatar Mar 13 '17 06:03 haggag

@haggag you're creating two different key objects (USER_ID_CTX_KEY) so in getData you're doing lookup for a different key object. Try making USER_ID_CTX_KEY public in HeaderServerInterceptor and re-use it in getData or extract it to separate class, eg. RpcUtils.USER_ID_CTX_KEY.

lukaszx0 avatar Mar 13 '17 17:03 lukaszx0