io.grpc.SecurityLevel Java Examples

The following examples show how to use io.grpc.SecurityLevel. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: CallCredentials2ApplyingTest.java    From grpc-java with Apache License 2.0 6 votes vote down vote up
@Test
public void parameterPropagation_callOptionsSetAuthority() {
  Attributes transportAttrs = Attributes.newBuilder()
      .set(ATTR_KEY, ATTR_VALUE)
      .build();
  when(mockTransport.getAttributes()).thenReturn(transportAttrs);
  Executor anotherExecutor = mock(Executor.class);

  transport.newStream(method, origHeaders,
      callOptions.withAuthority("calloptions-authority").withExecutor(anotherExecutor));

  ArgumentCaptor<RequestInfo> infoCaptor = ArgumentCaptor.forClass(null);
  verify(mockCreds).applyRequestMetadata(
      infoCaptor.capture(), same(anotherExecutor),
      any(io.grpc.CallCredentials2.MetadataApplier.class));
  RequestInfo info = infoCaptor.getValue();
  assertSame(method, info.getMethodDescriptor());
  assertSame(ATTR_VALUE, info.getTransportAttrs().get(ATTR_KEY));
  assertEquals("calloptions-authority", info.getAuthority());
  assertSame(SecurityLevel.NONE, info.getSecurityLevel());
}
 
Example #2
Source File: CronetClientTransport.java    From grpc-nebula-java with Apache License 2.0 6 votes vote down vote up
CronetClientTransport(
    StreamBuilderFactory streamFactory,
    InetSocketAddress address,
    String authority,
    @Nullable String userAgent,
    Executor executor,
    int maxMessageSize,
    boolean alwaysUsePut,
    TransportTracer transportTracer) {
  this.address = Preconditions.checkNotNull(address, "address");
  this.authority = authority;
  this.userAgent = GrpcUtil.getGrpcUserAgent("cronet", userAgent);
  this.maxMessageSize = maxMessageSize;
  this.alwaysUsePut = alwaysUsePut;
  this.executor = Preconditions.checkNotNull(executor, "executor");
  this.streamFactory = Preconditions.checkNotNull(streamFactory, "streamFactory");
  this.transportTracer = Preconditions.checkNotNull(transportTracer, "transportTracer");
  this.attrs = Attributes.newBuilder()
      .set(GrpcAttributes.ATTR_SECURITY_LEVEL, SecurityLevel.PRIVACY_AND_INTEGRITY)
      .build();
}
 
Example #3
Source File: GoogleAuthLibraryCallCredentialsTest.java    From grpc-java with Apache License 2.0 6 votes vote down vote up
@Test
public void oauth2Credential() {
  final AccessToken token = new AccessToken("allyourbase", new Date(Long.MAX_VALUE));
  OAuth2Credentials credentials = new OAuth2Credentials() {
    @Override
    public AccessToken refreshAccessToken() throws IOException {
      return token;
    }
  };

  GoogleAuthLibraryCallCredentials callCredentials =
      new GoogleAuthLibraryCallCredentials(credentials);
  callCredentials.applyRequestMetadata(
      new RequestInfoImpl(SecurityLevel.NONE), executor, applier);
  assertEquals(1, runPendingRunnables());

  verify(applier).apply(headersCaptor.capture());
  Metadata headers = headersCaptor.getValue();
  Iterable<String> authorization = headers.getAll(AUTHORIZATION);
  assertArrayEquals(new String[]{"Bearer allyourbase"},
      Iterables.toArray(authorization, String.class));
}
 
Example #4
Source File: CallCredentials2ApplyingTest.java    From grpc-nebula-java with Apache License 2.0 6 votes vote down vote up
@Test
public void parameterPropagation_callOptionsSetAuthority() {
  Attributes transportAttrs = Attributes.newBuilder()
      .set(ATTR_KEY, ATTR_VALUE)
      .build();
  when(mockTransport.getAttributes()).thenReturn(transportAttrs);
  Executor anotherExecutor = mock(Executor.class);

  transport.newStream(method, origHeaders,
      callOptions.withAuthority("calloptions-authority").withExecutor(anotherExecutor));

  ArgumentCaptor<RequestInfo> infoCaptor = ArgumentCaptor.forClass(null);
  verify(mockCreds).applyRequestMetadata(
      infoCaptor.capture(), same(anotherExecutor), any(MetadataApplier.class));
  RequestInfo info = infoCaptor.getValue();
  assertSame(method, info.getMethodDescriptor());
  assertSame(ATTR_VALUE, info.getTransportAttrs().get(ATTR_KEY));
  assertEquals("calloptions-authority", info.getAuthority());
  assertSame(SecurityLevel.NONE, info.getSecurityLevel());
}
 
Example #5
Source File: CallCredentials2ApplyingTest.java    From grpc-nebula-java with Apache License 2.0 6 votes vote down vote up
@Test
public void parameterPropagation_transportSetSecurityLevel() {
  Attributes transportAttrs = Attributes.newBuilder()
      .set(ATTR_KEY, ATTR_VALUE)
      .set(GrpcAttributes.ATTR_SECURITY_LEVEL, SecurityLevel.INTEGRITY)
      .build();
  when(mockTransport.getAttributes()).thenReturn(transportAttrs);

  transport.newStream(method, origHeaders, callOptions);

  ArgumentCaptor<RequestInfo> infoCaptor = ArgumentCaptor.forClass(null);
  verify(mockCreds).applyRequestMetadata(
      infoCaptor.capture(), same(mockExecutor), any(MetadataApplier.class));
  RequestInfo info = infoCaptor.getValue();
  assertSame(method, info.getMethodDescriptor());
  assertSame(ATTR_VALUE, info.getTransportAttrs().get(ATTR_KEY));
  assertSame(AUTHORITY, info.getAuthority());
  assertSame(SecurityLevel.INTEGRITY, info.getSecurityLevel());
}
 
Example #6
Source File: CallCredentials2ApplyingTest.java    From grpc-nebula-java with Apache License 2.0 6 votes vote down vote up
@Test
public void parameterPropagation_base() {
  Attributes transportAttrs = Attributes.newBuilder().set(ATTR_KEY, ATTR_VALUE).build();
  when(mockTransport.getAttributes()).thenReturn(transportAttrs);

  transport.newStream(method, origHeaders, callOptions);

  ArgumentCaptor<RequestInfo> infoCaptor = ArgumentCaptor.forClass(null);
  verify(mockCreds).applyRequestMetadata(
      infoCaptor.capture(), same(mockExecutor), any(MetadataApplier.class));
  RequestInfo info = infoCaptor.getValue();
  assertSame(method, info.getMethodDescriptor());
  assertSame(ATTR_VALUE, info.getTransportAttrs().get(ATTR_KEY));
  assertSame(AUTHORITY, info.getAuthority());
  assertSame(SecurityLevel.NONE, info.getSecurityLevel());
}
 
Example #7
Source File: CallCredentialsApplyingTest.java    From grpc-nebula-java with Apache License 2.0 6 votes vote down vote up
@Test
public void parameterPropagation_overrideByCallOptions() {
  Attributes transportAttrs = Attributes.newBuilder()
      .set(ATTR_KEY, ATTR_VALUE)
      .set(CallCredentials.ATTR_AUTHORITY, "transport-override-authority")
      .set(CallCredentials.ATTR_SECURITY_LEVEL, SecurityLevel.INTEGRITY)
      .build();
  when(mockTransport.getAttributes()).thenReturn(transportAttrs);
  Executor anotherExecutor = mock(Executor.class);

  transport.newStream(method, origHeaders,
      callOptions.withAuthority("calloptions-authority").withExecutor(anotherExecutor));

  ArgumentCaptor<Attributes> attrsCaptor = ArgumentCaptor.forClass(null);
  verify(mockCreds).applyRequestMetadata(same(method), attrsCaptor.capture(),
      same(anotherExecutor), any(CallCredentials.MetadataApplier.class));
  Attributes attrs = attrsCaptor.getValue();
  assertSame(ATTR_VALUE, attrs.get(ATTR_KEY));
  assertEquals("calloptions-authority", attrs.get(CallCredentials.ATTR_AUTHORITY));
  assertSame(SecurityLevel.INTEGRITY, attrs.get(CallCredentials.ATTR_SECURITY_LEVEL));
}
 
Example #8
Source File: CallCredentialsApplyingTest.java    From grpc-nebula-java with Apache License 2.0 6 votes vote down vote up
@Test
public void parameterPropagation_overrideByTransport() {
  Attributes transportAttrs = Attributes.newBuilder()
      .set(ATTR_KEY, ATTR_VALUE)
      .set(CallCredentials.ATTR_AUTHORITY, "transport-override-authority")
      .set(CallCredentials.ATTR_SECURITY_LEVEL, SecurityLevel.INTEGRITY)
      .build();
  when(mockTransport.getAttributes()).thenReturn(transportAttrs);

  transport.newStream(method, origHeaders, callOptions);

  ArgumentCaptor<Attributes> attrsCaptor = ArgumentCaptor.forClass(null);
  verify(mockCreds).applyRequestMetadata(same(method), attrsCaptor.capture(), same(mockExecutor),
      any(CallCredentials.MetadataApplier.class));
  Attributes attrs = attrsCaptor.getValue();
  assertSame(ATTR_VALUE, attrs.get(ATTR_KEY));
  assertEquals("transport-override-authority", attrs.get(CallCredentials.ATTR_AUTHORITY));
  assertSame(SecurityLevel.INTEGRITY, attrs.get(CallCredentials.ATTR_SECURITY_LEVEL));
}
 
Example #9
Source File: GoogleAuthLibraryCallCredentialsTest.java    From grpc-java with Apache License 2.0 6 votes vote down vote up
@Test
public void googleCredential_privacyAndIntegrityAllowed() {
  final AccessToken token = new AccessToken("allyourbase", new Date(Long.MAX_VALUE));
  final Credentials credentials = GoogleCredentials.create(token);

  GoogleAuthLibraryCallCredentials callCredentials =
      new GoogleAuthLibraryCallCredentials(credentials);
  callCredentials.applyRequestMetadata(
      new RequestInfoImpl(SecurityLevel.PRIVACY_AND_INTEGRITY), executor, applier);
  runPendingRunnables();

  verify(applier).apply(headersCaptor.capture());
  Metadata headers = headersCaptor.getValue();
  Iterable<String> authorization = headers.getAll(AUTHORIZATION);
  assertArrayEquals(new String[]{"Bearer allyourbase"},
      Iterables.toArray(authorization, String.class));
}
 
Example #10
Source File: GoogleAuthLibraryCallCredentialsTest.java    From grpc-java with Apache License 2.0 6 votes vote down vote up
@Test
public void googleCredential_integrityDenied() {
  final AccessToken token = new AccessToken("allyourbase", new Date(Long.MAX_VALUE));
  final Credentials credentials = GoogleCredentials.create(token);
  // Anything less than PRIVACY_AND_INTEGRITY should fail

  GoogleAuthLibraryCallCredentials callCredentials =
      new GoogleAuthLibraryCallCredentials(credentials);
  callCredentials.applyRequestMetadata(
      new RequestInfoImpl(SecurityLevel.INTEGRITY), executor, applier);
  runPendingRunnables();

  verify(applier).fail(statusCaptor.capture());
  Status status = statusCaptor.getValue();
  assertEquals(Status.Code.UNAUTHENTICATED, status.getCode());
}
 
Example #11
Source File: AltsProtocolNegotiator.java    From grpc-java with Apache License 2.0 6 votes vote down vote up
@Override
public SecurityDetails validatePeerObject(Object peerObject) throws GeneralSecurityException {
  AltsAuthContext altsAuthContext = (AltsAuthContext) peerObject;
  // Checks peer Rpc Protocol Versions in the ALTS auth context. Fails the connection if
  // Rpc Protocol Versions mismatch.
  RpcVersionsCheckResult checkResult =
      RpcProtocolVersionsUtil.checkRpcProtocolVersions(
          RpcProtocolVersionsUtil.getRpcProtocolVersions(),
          altsAuthContext.getPeerRpcVersions());
  if (!checkResult.getResult()) {
    String errorMessage =
        "Local Rpc Protocol Versions "
            + RpcProtocolVersionsUtil.getRpcProtocolVersions()
            + " are not compatible with peer Rpc Protocol Versions "
            + altsAuthContext.getPeerRpcVersions();
    throw Status.UNAVAILABLE.withDescription(errorMessage).asRuntimeException();
  }
  return new SecurityDetails(
      SecurityLevel.PRIVACY_AND_INTEGRITY,
      new Security(new OtherSecurity("alts", Any.pack(altsAuthContext.context))));
}
 
Example #12
Source File: InProcessTransport.java    From grpc-java with Apache License 2.0 6 votes vote down vote up
private InProcessTransport(String name, int maxInboundMetadataSize, String authority,
    String userAgent, Attributes eagAttrs,
    Optional<ServerListener> optionalServerListener, boolean includeCauseWithStatus) {
  this.name = name;
  this.clientMaxInboundMetadataSize = maxInboundMetadataSize;
  this.authority = authority;
  this.userAgent = GrpcUtil.getGrpcUserAgent("inprocess", userAgent);
  checkNotNull(eagAttrs, "eagAttrs");
  this.attributes = Attributes.newBuilder()
      .set(GrpcAttributes.ATTR_SECURITY_LEVEL, SecurityLevel.PRIVACY_AND_INTEGRITY)
      .set(GrpcAttributes.ATTR_CLIENT_EAG_ATTRS, eagAttrs)
      .set(Grpc.TRANSPORT_ATTR_REMOTE_ADDR, new InProcessSocketAddress(name))
      .set(Grpc.TRANSPORT_ATTR_LOCAL_ADDR, new InProcessSocketAddress(name))
      .build();
  this.optionalServerListener = optionalServerListener;
  logId = InternalLogId.allocate(getClass(), name);
  this.includeCauseWithStatus = includeCauseWithStatus;
}
 
Example #13
Source File: CallCredentialsApplyingTest.java    From grpc-java with Apache License 2.0 6 votes vote down vote up
@Test
public void parameterPropagation_base() {
  Attributes transportAttrs = Attributes.newBuilder().set(ATTR_KEY, ATTR_VALUE).build();
  when(mockTransport.getAttributes()).thenReturn(transportAttrs);

  transport.newStream(method, origHeaders, callOptions);

  ArgumentCaptor<RequestInfo> infoCaptor = ArgumentCaptor.forClass(null);
  verify(mockCreds).applyRequestMetadata(infoCaptor.capture(), same(mockExecutor),
      any(CallCredentials.MetadataApplier.class));
  RequestInfo info = infoCaptor.getValue();
  assertSame(transportAttrs, info.getTransportAttrs());
  assertSame(method, info.getMethodDescriptor());
  assertSame(AUTHORITY, info.getAuthority());
  assertSame(SecurityLevel.NONE, info.getSecurityLevel());
}
 
Example #14
Source File: CallCredentialsApplyingTest.java    From grpc-java with Apache License 2.0 6 votes vote down vote up
@Test
public void parameterPropagation_overrideByCallOptions() {
  Attributes transportAttrs = Attributes.newBuilder()
      .set(ATTR_KEY, ATTR_VALUE)
      .set(GrpcAttributes.ATTR_SECURITY_LEVEL, SecurityLevel.INTEGRITY)
      .build();
  when(mockTransport.getAttributes()).thenReturn(transportAttrs);
  Executor anotherExecutor = mock(Executor.class);

  transport.newStream(method, origHeaders,
      callOptions.withAuthority("calloptions-authority").withExecutor(anotherExecutor));

  ArgumentCaptor<RequestInfo> infoCaptor = ArgumentCaptor.forClass(null);
  verify(mockCreds).applyRequestMetadata(infoCaptor.capture(),
      same(anotherExecutor), any(CallCredentials.MetadataApplier.class));
  RequestInfo info = infoCaptor.getValue();
  assertSame(transportAttrs, info.getTransportAttrs());
  assertSame(method, info.getMethodDescriptor());
  assertEquals("calloptions-authority", info.getAuthority());
  assertSame(SecurityLevel.INTEGRITY, info.getSecurityLevel());
}
 
Example #15
Source File: GoogleAuthLibraryCallCredentialsTest.java    From grpc-nebula-java with Apache License 2.0 6 votes vote down vote up
@Test
public void googleCredential_integrityDenied() {
  final AccessToken token = new AccessToken("allyourbase", new Date(Long.MAX_VALUE));
  final Credentials credentials = GoogleCredentials.create(token);
  // Anything less than PRIVACY_AND_INTEGRITY should fail

  GoogleAuthLibraryCallCredentials callCredentials =
      new GoogleAuthLibraryCallCredentials(credentials);
  callCredentials.applyRequestMetadata(
      new RequestInfoImpl(SecurityLevel.INTEGRITY), executor, applier);
  runPendingRunnables();

  verify(applier).fail(statusCaptor.capture());
  Status status = statusCaptor.getValue();
  assertEquals(Status.Code.UNAUTHENTICATED, status.getCode());
}
 
Example #16
Source File: GoogleAuthLibraryCallCredentialsTest.java    From grpc-nebula-java with Apache License 2.0 6 votes vote down vote up
@Test
public void googleCredential_privacyAndIntegrityAllowed() {
  final AccessToken token = new AccessToken("allyourbase", new Date(Long.MAX_VALUE));
  final Credentials credentials = GoogleCredentials.create(token);

  GoogleAuthLibraryCallCredentials callCredentials =
      new GoogleAuthLibraryCallCredentials(credentials);
  callCredentials.applyRequestMetadata(
      new RequestInfoImpl(SecurityLevel.PRIVACY_AND_INTEGRITY), executor, applier);
  runPendingRunnables();

  verify(applier).apply(headersCaptor.capture());
  Metadata headers = headersCaptor.getValue();
  Iterable<String> authorization = headers.getAll(AUTHORIZATION);
  assertArrayEquals(new String[]{"Bearer allyourbase"},
      Iterables.toArray(authorization, String.class));
}
 
Example #17
Source File: GoogleAuthLibraryCallCredentialsTest.java    From grpc-nebula-java with Apache License 2.0 6 votes vote down vote up
@Test
public void oauth2Credential() {
  final AccessToken token = new AccessToken("allyourbase", new Date(Long.MAX_VALUE));
  final OAuth2Credentials credentials = new OAuth2Credentials() {
    @Override
    public AccessToken refreshAccessToken() throws IOException {
      return token;
    }
  };

  GoogleAuthLibraryCallCredentials callCredentials =
      new GoogleAuthLibraryCallCredentials(credentials);
  callCredentials.applyRequestMetadata(
      new RequestInfoImpl(SecurityLevel.NONE), executor, applier);
  assertEquals(1, runPendingRunnables());

  verify(applier).apply(headersCaptor.capture());
  Metadata headers = headersCaptor.getValue();
  Iterable<String> authorization = headers.getAll(AUTHORIZATION);
  assertArrayEquals(new String[]{"Bearer allyourbase"},
      Iterables.toArray(authorization, String.class));
}
 
Example #18
Source File: ProtocolNegotiators.java    From grpc-nebula-java with Apache License 2.0 6 votes vote down vote up
@Override
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
  if (evt == HttpClientUpgradeHandler.UpgradeEvent.UPGRADE_SUCCESSFUL) {
    writeBufferedAndRemove(ctx);
    grpcHandler.handleProtocolNegotiationCompleted(
        Attributes
            .newBuilder()
            .set(Grpc.TRANSPORT_ATTR_REMOTE_ADDR, ctx.channel().remoteAddress())
            .set(Grpc.TRANSPORT_ATTR_LOCAL_ADDR, ctx.channel().localAddress())
            .set(GrpcAttributes.ATTR_SECURITY_LEVEL, SecurityLevel.NONE)
            .build(),
        /*securityInfo=*/ null);
  } else if (evt == HttpClientUpgradeHandler.UpgradeEvent.UPGRADE_REJECTED) {
    fail(ctx, unavailableException("HTTP/2 upgrade rejected"));
  }
  super.userEventTriggered(ctx, evt);
}
 
Example #19
Source File: CallCredentials2ApplyingTest.java    From grpc-java with Apache License 2.0 6 votes vote down vote up
@Test
public void parameterPropagation_base() {
  Attributes transportAttrs = Attributes.newBuilder().set(ATTR_KEY, ATTR_VALUE).build();
  when(mockTransport.getAttributes()).thenReturn(transportAttrs);

  transport.newStream(method, origHeaders, callOptions);

  ArgumentCaptor<RequestInfo> infoCaptor = ArgumentCaptor.forClass(null);
  verify(mockCreds).applyRequestMetadata(
      infoCaptor.capture(), same(mockExecutor),
      any(io.grpc.CallCredentials2.MetadataApplier.class));
  RequestInfo info = infoCaptor.getValue();
  assertSame(method, info.getMethodDescriptor());
  assertSame(ATTR_VALUE, info.getTransportAttrs().get(ATTR_KEY));
  assertSame(AUTHORITY, info.getAuthority());
  assertSame(SecurityLevel.NONE, info.getSecurityLevel());
}
 
Example #20
Source File: CallCredentials2ApplyingTest.java    From grpc-java with Apache License 2.0 6 votes vote down vote up
@Test
public void parameterPropagation_transportSetSecurityLevel() {
  Attributes transportAttrs = Attributes.newBuilder()
      .set(ATTR_KEY, ATTR_VALUE)
      .set(GrpcAttributes.ATTR_SECURITY_LEVEL, SecurityLevel.INTEGRITY)
      .build();
  when(mockTransport.getAttributes()).thenReturn(transportAttrs);

  transport.newStream(method, origHeaders, callOptions);

  ArgumentCaptor<RequestInfo> infoCaptor = ArgumentCaptor.forClass(null);
  verify(mockCreds).applyRequestMetadata(
      infoCaptor.capture(), same(mockExecutor),
      any(io.grpc.CallCredentials2.MetadataApplier.class));
  RequestInfo info = infoCaptor.getValue();
  assertSame(method, info.getMethodDescriptor());
  assertSame(ATTR_VALUE, info.getTransportAttrs().get(ATTR_KEY));
  assertSame(AUTHORITY, info.getAuthority());
  assertSame(SecurityLevel.INTEGRITY, info.getSecurityLevel());
}
 
Example #21
Source File: AltsProtocolNegotiatorTest.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
@Test
public void peerPropagated() throws Exception {
  doHandshake();

  assertThat(grpcHandler.attrs.get(AltsProtocolNegotiator.TSI_PEER_KEY)).isEqualTo(mockedTsiPeer);
  assertThat(grpcHandler.attrs.get(AltsProtocolNegotiator.AUTH_CONTEXT_KEY))
      .isEqualTo(mockedAltsContext);
  assertThat(grpcHandler.attrs.get(Grpc.TRANSPORT_ATTR_REMOTE_ADDR).toString())
      .isEqualTo("embedded");
  assertThat(grpcHandler.attrs.get(Grpc.TRANSPORT_ATTR_LOCAL_ADDR).toString())
      .isEqualTo("embedded");
  assertThat(grpcHandler.attrs.get(GrpcAttributes.ATTR_SECURITY_LEVEL))
      .isEqualTo(SecurityLevel.PRIVACY_AND_INTEGRITY);
}
 
Example #22
Source File: ProtocolNegotiators.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
private void replaceOnActive(ChannelHandlerContext ctx) {
  ProtocolNegotiationEvent existingPne = getProtocolNegotiationEvent();
  Attributes attrs = existingPne.getAttributes().toBuilder()
      .set(Grpc.TRANSPORT_ATTR_LOCAL_ADDR, ctx.channel().localAddress())
      .set(Grpc.TRANSPORT_ATTR_REMOTE_ADDR, ctx.channel().remoteAddress())
      // Later handlers are expected to overwrite this.
      .set(GrpcAttributes.ATTR_SECURITY_LEVEL, SecurityLevel.NONE)
      .build();
  replaceProtocolNegotiationEvent(existingPne.withAttributes(attrs));
}
 
Example #23
Source File: ProtocolNegotiators.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
private void propagateTlsComplete(ChannelHandlerContext ctx, SSLSession session) {
  Security security = new Security(new Tls(session));
  ProtocolNegotiationEvent existingPne = getProtocolNegotiationEvent();
  Attributes attrs = existingPne.getAttributes().toBuilder()
      .set(GrpcAttributes.ATTR_SECURITY_LEVEL, SecurityLevel.PRIVACY_AND_INTEGRITY)
      .set(Grpc.TRANSPORT_ATTR_SSL_SESSION, session)
      .build();
  replaceProtocolNegotiationEvent(existingPne.withAttributes(attrs).withSecurity(security));
  fireProtocolNegotiationEvent(ctx);
}
 
Example #24
Source File: ProtocolNegotiators.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
private void fireProtocolNegotiationEvent(ChannelHandlerContext ctx, SSLSession session) {
  Security security = new Security(new Tls(session));
  Attributes attrs = pne.getAttributes().toBuilder()
      .set(GrpcAttributes.ATTR_SECURITY_LEVEL, SecurityLevel.PRIVACY_AND_INTEGRITY)
      .set(Grpc.TRANSPORT_ATTR_SSL_SESSION, session)
      .build();
  ctx.fireUserEventTriggered(pne.withAttributes(attrs).withSecurity(security));
}
 
Example #25
Source File: GrpcClientTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Test
void credentialsUnaryCall_https() {
    final TestServiceBlockingStub stub =
            // Explicitly construct URL to better test authority.
            Clients.builder("gproto+https://127.0.0.1:" + server.httpsPort())
                   .decorator(LoggingClient.builder().newDecorator())
                   .factory(ClientFactory.insecure())
                   .build(TestServiceBlockingStub.class)
                   .withCallCredentials(
                           new CallCredentials() {
                               @Override
                               public void applyRequestMetadata(RequestInfo requestInfo,
                                                                Executor appExecutor,
                                                                MetadataApplier applier) {
                                   assertThat(requestInfo.getAuthority())
                                           .isEqualTo("127.0.0.1:" + server.httpsPort());
                                   assertThat(requestInfo.getSecurityLevel())
                                           .isEqualTo(SecurityLevel.PRIVACY_AND_INTEGRITY);
                                   applier.apply(new Metadata());
                               }

                               @Override
                               public void thisUsesUnstableApi() {
                               }
                           });

    assertThat(stub.emptyCall(EMPTY)).isNotNull();
}
 
Example #26
Source File: CronetClientTransportTest.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
@Test
public void transportAttributes() {
  Attributes attrs = transport.getAttributes();
  assertEquals(
      SecurityLevel.PRIVACY_AND_INTEGRITY, attrs.get(GrpcAttributes.ATTR_SECURITY_LEVEL));
  assertEquals(EAG_ATTRS, attrs.get(GrpcAttributes.ATTR_CLIENT_EAG_ATTRS));
}
 
Example #27
Source File: GrpcClientTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Test
void credentialsUnaryCall() {
    final TestServiceBlockingStub stub =
            // Explicitly construct URL to better test authority.
            Clients.builder("gproto+http://localhost:" + server.httpPort())
                   .decorator(LoggingClient.builder().newDecorator())
                   .build(TestServiceBlockingStub.class)
                   .withCallCredentials(
                           new CallCredentials() {
                               @Override
                               public void applyRequestMetadata(RequestInfo requestInfo,
                                                                Executor appExecutor,
                                                                MetadataApplier applier) {
                                   assertThat(requestInfo.getMethodDescriptor())
                                           .isEqualTo(TestServiceGrpc.getEmptyCallMethod());
                                   assertThat(requestInfo.getAuthority())
                                           .isEqualTo("localhost:" + server.httpPort());
                                   assertThat(requestInfo.getSecurityLevel())
                                           .isEqualTo(SecurityLevel.NONE);
                                   assertThat(appExecutor).isEqualTo(CommonPools.blockingTaskExecutor());

                                   CommonPools.blockingTaskExecutor().schedule(() -> {
                                       final Metadata metadata = new Metadata();
                                       metadata.put(TestServiceImpl.EXTRA_HEADER_KEY, "token");
                                       applier.apply(metadata);
                                   }, 100, TimeUnit.MILLISECONDS);
                               }

                               @Override
                               public void thisUsesUnstableApi() {
                               }
                           });

    assertThat(stub.emptyCall(EMPTY)).isNotNull();

    final HttpHeaders clientHeaders = CLIENT_HEADERS_CAPTURE.get();
    assertThat(clientHeaders.get(TestServiceImpl.EXTRA_HEADER_NAME)).isEqualTo("token");
}
 
Example #28
Source File: CronetClientTransport.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
CronetClientTransport(
    StreamBuilderFactory streamFactory,
    InetSocketAddress address,
    String authority,
    @Nullable String userAgent,
    Attributes eagAttrs,
    Executor executor,
    int maxMessageSize,
    boolean alwaysUsePut,
    TransportTracer transportTracer,
    boolean useGetForSafeMethods,
    boolean usePutForIdempotentMethods) {
  this.address = Preconditions.checkNotNull(address, "address");
  this.logId = InternalLogId.allocate(getClass(), address.toString());
  this.authority = authority;
  this.userAgent = GrpcUtil.getGrpcUserAgent("cronet", userAgent);
  this.maxMessageSize = maxMessageSize;
  this.alwaysUsePut = alwaysUsePut;
  this.executor = Preconditions.checkNotNull(executor, "executor");
  this.streamFactory = Preconditions.checkNotNull(streamFactory, "streamFactory");
  this.transportTracer = Preconditions.checkNotNull(transportTracer, "transportTracer");
  this.attrs = Attributes.newBuilder()
      .set(GrpcAttributes.ATTR_SECURITY_LEVEL, SecurityLevel.PRIVACY_AND_INTEGRITY)
      .set(GrpcAttributes.ATTR_CLIENT_EAG_ATTRS, eagAttrs)
      .build();
  this.useGetForSafeMethods = useGetForSafeMethods;
  this.usePutForIdempotentMethods = usePutForIdempotentMethods;
}
 
Example #29
Source File: ProtocolNegotiators.java    From grpc-nebula-java with Apache License 2.0 5 votes vote down vote up
@Override
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
  if (evt instanceof SslHandshakeCompletionEvent) {
    SslHandshakeCompletionEvent handshakeEvent = (SslHandshakeCompletionEvent) evt;
    if (handshakeEvent.isSuccess()) {
      SslHandler handler = ctx.pipeline().get(SslHandler.class);
      if (NEXT_PROTOCOL_VERSIONS.contains(handler.applicationProtocol())) {
        // Successfully negotiated the protocol.
        logSslEngineDetails(Level.FINER, ctx, "TLS negotiation succeeded.", null);

        // Wait until negotiation is complete to add gRPC.   If added too early, HTTP/2 writes
        // will fail before we see the userEvent, and the channel is closed down prematurely.
        ctx.pipeline().addBefore(ctx.name(), null, grpcHandler);

        SSLSession session = handler.engine().getSession();
        // Successfully negotiated the protocol.
        // Notify about completion and pass down SSLSession in attributes.
        grpcHandler.handleProtocolNegotiationCompleted(
            Attributes.newBuilder()
                .set(Grpc.TRANSPORT_ATTR_SSL_SESSION, session)
                .set(Grpc.TRANSPORT_ATTR_REMOTE_ADDR, ctx.channel().remoteAddress())
                .set(Grpc.TRANSPORT_ATTR_LOCAL_ADDR, ctx.channel().localAddress())
                .set(GrpcAttributes.ATTR_SECURITY_LEVEL, SecurityLevel.PRIVACY_AND_INTEGRITY)
                .build(),
            new InternalChannelz.Security(new InternalChannelz.Tls(session)));
        writeBufferedAndRemove(ctx);
      } else {
        Exception ex = new Exception(
            "Failed ALPN negotiation: Unable to find compatible protocol.");
        logSslEngineDetails(Level.FINE, ctx, "TLS negotiation failed.", ex);
        fail(ctx, ex);
      }
    } else {
      fail(ctx, handshakeEvent.cause());
    }
  }
  super.userEventTriggered(ctx, evt);
}
 
Example #30
Source File: ProtocolNegotiators.java    From grpc-nebula-java with Apache License 2.0 5 votes vote down vote up
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
  writeBufferedAndRemove(ctx);
  handler.handleProtocolNegotiationCompleted(
      Attributes
          .newBuilder()
          .set(Grpc.TRANSPORT_ATTR_REMOTE_ADDR, ctx.channel().remoteAddress())
          .set(Grpc.TRANSPORT_ATTR_LOCAL_ADDR, ctx.channel().localAddress())
          .set(GrpcAttributes.ATTR_SECURITY_LEVEL, SecurityLevel.NONE)
          .build(),
      /*securityInfo=*/ null);
  super.channelActive(ctx);
}