Access to controller (for connection metadata)
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?
I think the best way to provide this information is as header metadata. What would you do with this information? Some form of ACLing?
Yes, I was planning on using the client-cert for authentication.
Is there a way to get the header metadata inside the service method?
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.
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.
It should be easy enough to use ThreadLocal as the interceptor interfaces provide closure over calls into your service implementation via ServerCall.Listener#onPayload
OK. Is there a reason you don't pass a context object though? Would you accept a PR that added a context object?
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
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.
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?
Created a straw-man patch/PR. Comments welcome!
+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.
+1
With #1506, there is now an attributes() method on ServerCall. You can use the keys in #1564 to access the SslSession and IP address.
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 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 Thanks. Seems that I got it working. I am certainly not used to doing things this way.
@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 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.