类io.grpc.SecurityLevel源码实例Demo

下面列出了怎么用io.grpc.SecurityLevel的API类实例代码及写法,或者点击链接到github查看源代码。

源代码1 项目: grpc-nebula-java   文件: CronetClientTransport.java
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();
}
 
源代码2 项目: grpc-nebula-java   文件: ProtocolNegotiators.java
@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);
}
 
@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));
}
 
@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));
}
 
@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());
}
 
@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));
}
 
@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));
}
 
@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());
}
 
@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());
}
 
@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());
}
 
@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));
}
 
@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));
}
 
@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());
}
 
源代码14 项目: grpc-java   文件: AltsProtocolNegotiator.java
@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))));
}
 
源代码15 项目: grpc-java   文件: InProcessTransport.java
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;
}
 
源代码16 项目: grpc-java   文件: CallCredentialsApplyingTest.java
@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());
}
 
源代码17 项目: grpc-java   文件: CallCredentialsApplyingTest.java
@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());
}
 
源代码18 项目: grpc-java   文件: CallCredentials2ApplyingTest.java
@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());
}
 
源代码19 项目: grpc-java   文件: CallCredentials2ApplyingTest.java
@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());
}
 
源代码20 项目: grpc-java   文件: CallCredentials2ApplyingTest.java
@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());
}
 
源代码21 项目: grpc-nebula-java   文件: ProtocolNegotiators.java
@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);
}
 
源代码22 项目: grpc-nebula-java   文件: ProtocolNegotiators.java
@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);
}
 
@Test
public void peerPropagated() throws Exception {
  doHandshake();

  assertThat(grpcHandler.attrs.get(AltsProtocolNegotiator.TSI_PEER_KEY))
      .isEqualTo(mockedTsiPeer);
  assertThat(grpcHandler.attrs.get(AltsProtocolNegotiator.ALTS_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(CallCredentials.ATTR_SECURITY_LEVEL))
      .isEqualTo(SecurityLevel.PRIVACY_AND_INTEGRITY);
}
 
@Override
@SuppressWarnings("deprecation")
public ClientStream newStream(
    MethodDescriptor<?, ?> method, Metadata headers, CallOptions callOptions) {
  CallCredentials creds = callOptions.getCredentials();
  if (creds != null) {
    MetadataApplierImpl applier = new MetadataApplierImpl(
        delegate, method, headers, callOptions);
    Attributes.Builder effectiveAttrsBuilder = Attributes.newBuilder()
        .set(CallCredentials.ATTR_AUTHORITY, authority)
        .set(CallCredentials.ATTR_SECURITY_LEVEL, SecurityLevel.NONE)
        .setAll(delegate.getAttributes());
    if (callOptions.getAuthority() != null) {
      effectiveAttrsBuilder.set(CallCredentials.ATTR_AUTHORITY, callOptions.getAuthority());
    }
    try {
      creds.applyRequestMetadata(method, effectiveAttrsBuilder.build(),
          firstNonNull(callOptions.getExecutor(), appExecutor), applier);
    } catch (Throwable t) {
      applier.fail(Status.UNAUTHENTICATED
          .withDescription("Credentials should use fail() instead of throwing exceptions")
          .withCause(t));
    }
    return applier.returnStream();
  } else {
    return delegate.newStream(method, headers, callOptions);
  }
}
 
@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<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));
  assertSame(AUTHORITY, attrs.get(CallCredentials.ATTR_AUTHORITY));
  assertSame(SecurityLevel.NONE, attrs.get(CallCredentials.ATTR_SECURITY_LEVEL));
}
 
源代码26 项目: armeria   文件: GrpcClientTest.java
@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");
}
 
源代码27 项目: armeria   文件: GrpcClientTest.java
@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();
}
 
源代码28 项目: grpc-java   文件: CronetClientTransport.java
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;
}
 
源代码29 项目: grpc-java   文件: CronetClientTransportTest.java
@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));
}
 
源代码30 项目: grpc-java   文件: ProtocolNegotiators.java
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));
}
 
 类所在包
 类方法
 同包方法