io.grpc.CallCredentials Java Examples

The following examples show how to use io.grpc.CallCredentials. 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: SdsClient.java    From grpc-java with Apache License 2.0 6 votes vote down vote up
private SdsClient(
    SdsSecretConfig sdsSecretConfig,
    Node node,
    Executor watcherExecutor,
    ManagedChannel channel,
    EventLoopGroup eventLoopGroup,
    CallCredentials callCredentials) {
  checkNotNull(sdsSecretConfig, "sdsSecretConfig");
  checkNotNull(node, "node");
  this.sdsSecretConfig = sdsSecretConfig;
  this.clientNode = node;
  this.watcherExecutor = watcherExecutor;
  this.eventLoopGroup = eventLoopGroup;
  checkNotNull(channel, "channel");
  this.channel = channel;
  this.callCredentials = callCredentials;
}
 
Example #2
Source File: CallCredentialsApplyingTest.java    From grpc-nebula-java with Apache License 2.0 6 votes vote down vote up
@Test
public void applyMetadata_inline() {
  when(mockTransport.getAttributes()).thenReturn(Attributes.EMPTY);
  doAnswer(new Answer<Void>() {
      @Override
      public Void answer(InvocationOnMock invocation) throws Throwable {
        CallCredentials.MetadataApplier applier =
            (CallCredentials.MetadataApplier) invocation.getArguments()[3];
        Metadata headers = new Metadata();
        headers.put(CREDS_KEY, CREDS_VALUE);
        applier.apply(headers);
        return null;
      }
    }).when(mockCreds).applyRequestMetadata(same(method), any(Attributes.class),
        same(mockExecutor), any(CallCredentials.MetadataApplier.class));

  ClientStream stream = transport.newStream(method, origHeaders, callOptions);

  verify(mockTransport).newStream(method, origHeaders, callOptions);
  assertSame(mockStream, stream);
  assertEquals(CREDS_VALUE, origHeaders.get(CREDS_KEY));
  assertEquals(ORIG_HEADER_VALUE, origHeaders.get(ORIG_HEADER_KEY));
}
 
Example #3
Source File: CallCredentialsApplyingTest.java    From grpc-java with Apache License 2.0 6 votes vote down vote up
@Test
public void applyMetadata_inline() {
  when(mockTransport.getAttributes()).thenReturn(Attributes.EMPTY);
  doAnswer(new Answer<Void>() {
      @Override
      public Void answer(InvocationOnMock invocation) throws Throwable {
        CallCredentials.MetadataApplier applier =
            (CallCredentials.MetadataApplier) invocation.getArguments()[2];
        Metadata headers = new Metadata();
        headers.put(CREDS_KEY, CREDS_VALUE);
        applier.apply(headers);
        return null;
      }
    }).when(mockCreds).applyRequestMetadata(any(RequestInfo.class),
        same(mockExecutor), any(CallCredentials.MetadataApplier.class));

  ClientStream stream = transport.newStream(method, origHeaders, callOptions);

  verify(mockTransport).newStream(method, origHeaders, callOptions);
  assertSame(mockStream, stream);
  assertEquals(CREDS_VALUE, origHeaders.get(CREDS_KEY));
  assertEquals(ORIG_HEADER_VALUE, origHeaders.get(ORIG_HEADER_KEY));
}
 
Example #4
Source File: ComputeEngineChannelBuilder.java    From grpc-java with Apache License 2.0 6 votes vote down vote up
private ComputeEngineChannelBuilder(String target) {
  delegate = NettyChannelBuilder.forTarget(target);
  SslContext sslContext;
  try {
    sslContext = GrpcSslContexts.forClient().build();
  } catch (SSLException e) {
    throw new RuntimeException(e);
  }
  InternalNettyChannelBuilder.setProtocolNegotiatorFactory(
      delegate(),
      new GoogleDefaultProtocolNegotiatorFactory(
          /* targetServiceAccounts= */ ImmutableList.<String>of(),
          SharedResourcePool.forResource(HandshakerServiceChannel.SHARED_HANDSHAKER_CHANNEL),
          sslContext));
  CallCredentials credentials = MoreCallCredentials.from(ComputeEngineCredentials.create());
  Status status = Status.OK;
  if (!CheckGcpEnvironment.isOnGcp()) {
    status =
        Status.INTERNAL.withDescription(
            "Compute Engine Credentials can only be used on Google Cloud Platform");
  }
  delegate().intercept(new CallCredentialsInterceptor(credentials, status));
}
 
Example #5
Source File: GrpcCacheClient.java    From bazel with Apache License 2.0 6 votes vote down vote up
@VisibleForTesting
public GrpcCacheClient(
    ReferenceCountedChannel channel,
    CallCredentials credentials,
    RemoteOptions options,
    RemoteRetrier retrier,
    DigestUtil digestUtil,
    ByteStreamUploader uploader) {
  this.credentials = credentials;
  this.channel = channel;
  this.options = options;
  this.digestUtil = digestUtil;
  this.retrier = retrier;
  this.uploader = uploader;
  maxMissingBlobsDigestsPerMessage = computeMaxMissingBlobsDigestsPerMessage();
  Preconditions.checkState(
      maxMissingBlobsDigestsPerMessage > 0, "Error: gRPC message size too small.");
}
 
Example #6
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 #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-java with Apache License 2.0 6 votes vote down vote up
@Test
public void fail_inline() {
  final Status error = Status.FAILED_PRECONDITION.withDescription("channel not secure for creds");
  when(mockTransport.getAttributes()).thenReturn(Attributes.EMPTY);
  doAnswer(new Answer<Void>() {
      @Override
      public Void answer(InvocationOnMock invocation) throws Throwable {
        CallCredentials.MetadataApplier applier =
            (CallCredentials.MetadataApplier) invocation.getArguments()[2];
        applier.fail(error);
        return null;
      }
    }).when(mockCreds).applyRequestMetadata(any(RequestInfo.class),
        same(mockExecutor), any(CallCredentials.MetadataApplier.class));

  FailingClientStream stream =
      (FailingClientStream) transport.newStream(method, origHeaders, callOptions);

  verify(mockTransport, never()).newStream(method, origHeaders, callOptions);
  assertSame(error, stream.getError());
}
 
Example #9
Source File: CallCredentialsApplyingTest.java    From grpc-nebula-java with Apache License 2.0 6 votes vote down vote up
@Test
public void fail_inline() {
  final Status error = Status.FAILED_PRECONDITION.withDescription("channel not secure for creds");
  when(mockTransport.getAttributes()).thenReturn(Attributes.EMPTY);
  doAnswer(new Answer<Void>() {
      @Override
      public Void answer(InvocationOnMock invocation) throws Throwable {
        CallCredentials.MetadataApplier applier =
            (CallCredentials.MetadataApplier) invocation.getArguments()[3];
        applier.fail(error);
        return null;
      }
    }).when(mockCreds).applyRequestMetadata(same(method), any(Attributes.class),
        same(mockExecutor), any(CallCredentials.MetadataApplier.class));

  FailingClientStream stream =
      (FailingClientStream) transport.newStream(method, origHeaders, callOptions);

  verify(mockTransport, never()).newStream(method, origHeaders, callOptions);
  assertSame(error, stream.getError());
}
 
Example #10
Source File: CallCredentialsApplyingTest.java    From grpc-nebula-java with Apache License 2.0 6 votes vote down vote up
@Test
public void fail_delayed() {
  when(mockTransport.getAttributes()).thenReturn(Attributes.EMPTY);

  // Will call applyRequestMetadata(), which is no-op.
  DelayedStream stream = (DelayedStream) transport.newStream(method, origHeaders, callOptions);

  ArgumentCaptor<CallCredentials.MetadataApplier> applierCaptor = ArgumentCaptor.forClass(null);
  verify(mockCreds).applyRequestMetadata(same(method), any(Attributes.class),
      same(mockExecutor), applierCaptor.capture());

  Status error = Status.FAILED_PRECONDITION.withDescription("channel not secure for creds");
  applierCaptor.getValue().fail(error);

  verify(mockTransport, never()).newStream(method, origHeaders, callOptions);
  FailingClientStream failingStream = (FailingClientStream) stream.getRealStream();
  assertSame(error, failingStream.getError());
}
 
Example #11
Source File: GrpcClient.java    From cloud-spanner-r2dbc with Apache License 2.0 6 votes vote down vote up
/**
 * Initializes the Cloud Spanner gRPC async stub.
 *
 * @param credentials the Google Cloud Platform credentials used to authenticate with Spanner.
 */
public GrpcClient(GoogleCredentials credentials) {
  // Create blocking and async stubs using the channel
  CallCredentials callCredentials = MoreCallCredentials.from(credentials);

  // Create a channel
  this.channel = ManagedChannelBuilder
      .forTarget(GRPC_TARGET)
      .userAgent(USER_AGENT_LIBRARY_NAME + "/" + PACKAGE_VERSION)
      .build();

  // Async stub for general Spanner SQL queries
  this.spanner = SpannerGrpc.newStub(this.channel)
      .withCallCredentials(callCredentials);

  // Async stub for DDL queries
  this.databaseAdmin = DatabaseAdminGrpc.newStub(this.channel)
      .withCallCredentials(callCredentials);

  this.operations = OperationsGrpc.newStub(this.channel).withCallCredentials(callCredentials);
}
 
Example #12
Source File: GrpcClient.java    From etcd-java with Apache License 2.0 6 votes vote down vote up
/**
 * @deprecated use other constructor
 */
@Deprecated
public GrpcClient(ManagedChannel channel,
        Predicate<Throwable> reauthRequired,
        Supplier<CallCredentials> credsSupplier,
        ScheduledExecutorService executor, Condition isEventThread, 
        Executor userExecutor, boolean sendViaEventLoop, long defaultTimeoutMs) {
    this(channel, reauthRequired == null ? null : new AuthProvider() {
        {
            Preconditions.checkArgument((reauthRequired == null) == (credsSupplier == null),
                    "must supply both or neither reauth and creds");
        }
        @Override
        public boolean requiresReauth(Throwable t) {
            return reauthRequired.apply(t);
        }
        @Override
        public CallCredentials refreshCredentials() {
            return credsSupplier.get();
        }
    }, executor, isEventThread, userExecutor, sendViaEventLoop, defaultTimeoutMs);
}
 
Example #13
Source File: GrpcRemoteDownloaderTest.java    From bazel with Apache License 2.0 6 votes vote down vote up
private GrpcRemoteDownloader newDownloader(RemoteCacheClient cacheClient) throws IOException {
  final RemoteOptions remoteOptions = Options.getDefaults(RemoteOptions.class);
  final RemoteRetrier retrier =
      TestUtils.newRemoteRetrier(
          () -> new ExponentialBackoff(remoteOptions),
          RemoteRetrier.RETRIABLE_GRPC_ERRORS,
          retryService);
  final ReferenceCountedChannel channel =
      new ReferenceCountedChannel(
          InProcessChannelBuilder.forName(fakeServerName).directExecutor().build());
  return new GrpcRemoteDownloader(
      channel.retain(),
      Optional.<CallCredentials>empty(),
      retrier,
      withEmptyMetadata,
      cacheClient,
      remoteOptions);
}
 
Example #14
Source File: CallCredentialsApplyingTest.java    From grpc-java with Apache License 2.0 6 votes vote down vote up
@Test
public void applyMetadata_delayed() {
  when(mockTransport.getAttributes()).thenReturn(Attributes.EMPTY);

  // Will call applyRequestMetadata(), which is no-op.
  DelayedStream stream = (DelayedStream) transport.newStream(method, origHeaders, callOptions);

  ArgumentCaptor<CallCredentials.MetadataApplier> applierCaptor = ArgumentCaptor.forClass(null);
  verify(mockCreds).applyRequestMetadata(any(RequestInfo.class),
      same(mockExecutor), applierCaptor.capture());
  verify(mockTransport, never()).newStream(method, origHeaders, callOptions);

  Metadata headers = new Metadata();
  headers.put(CREDS_KEY, CREDS_VALUE);
  applierCaptor.getValue().apply(headers);

  verify(mockTransport).newStream(method, origHeaders, callOptions);
  assertSame(mockStream, stream.getRealStream());
  assertEquals(CREDS_VALUE, origHeaders.get(CREDS_KEY));
  assertEquals(ORIG_HEADER_VALUE, origHeaders.get(ORIG_HEADER_KEY));
}
 
Example #15
Source File: CallCredentialsApplyingTest.java    From grpc-nebula-java with Apache License 2.0 6 votes vote down vote up
@Test
public void applyMetadata_delayed() {
  when(mockTransport.getAttributes()).thenReturn(Attributes.EMPTY);

  // Will call applyRequestMetadata(), which is no-op.
  DelayedStream stream = (DelayedStream) transport.newStream(method, origHeaders, callOptions);

  ArgumentCaptor<CallCredentials.MetadataApplier> applierCaptor = ArgumentCaptor.forClass(null);
  verify(mockCreds).applyRequestMetadata(same(method), any(Attributes.class),
      same(mockExecutor), applierCaptor.capture());
  verify(mockTransport, never()).newStream(method, origHeaders, callOptions);

  Metadata headers = new Metadata();
  headers.put(CREDS_KEY, CREDS_VALUE);
  applierCaptor.getValue().apply(headers);

  verify(mockTransport).newStream(method, origHeaders, callOptions);
  assertSame(mockStream, stream.getRealStream());
  assertEquals(CREDS_VALUE, origHeaders.get(CREDS_KEY));
  assertEquals(ORIG_HEADER_VALUE, origHeaders.get(ORIG_HEADER_KEY));
}
 
Example #16
Source File: CallCredentialsApplyingTest.java    From grpc-java with Apache License 2.0 6 votes vote down vote up
@Test
public void fail_delayed() {
  when(mockTransport.getAttributes()).thenReturn(Attributes.EMPTY);

  // Will call applyRequestMetadata(), which is no-op.
  DelayedStream stream = (DelayedStream) transport.newStream(method, origHeaders, callOptions);

  ArgumentCaptor<CallCredentials.MetadataApplier> applierCaptor = ArgumentCaptor.forClass(null);
  verify(mockCreds).applyRequestMetadata(any(RequestInfo.class),
      same(mockExecutor), applierCaptor.capture());

  Status error = Status.FAILED_PRECONDITION.withDescription("channel not secure for creds");
  applierCaptor.getValue().fail(error);

  verify(mockTransport, never()).newStream(method, origHeaders, callOptions);
  FailingClientStream failingStream = (FailingClientStream) stream.getRealStream();
  assertSame(error, failingStream.getError());
}
 
Example #17
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 #18
Source File: SdsClient.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
private static CallCredentials getVerifiedCredentials(GoogleGrpc googleGrpc) {
  final String credentialsFactoryName = googleGrpc.getCredentialsFactoryName();
  if (credentialsFactoryName.isEmpty()) {
    // without factory name, no creds expected
    checkArgument(
        !googleGrpc.hasChannelCredentials() && googleGrpc.getCallCredentialsCount() == 0,
        "No credentials supported in GoogleGrpc");
    logger.warning("No CallCredentials specified.");
    return null;
  }
  checkArgument(
      credentialsFactoryName.equals(FileBasedPluginCredential.PLUGIN_NAME),
      "factory name should be %s", FileBasedPluginCredential.PLUGIN_NAME);
  if (googleGrpc.hasChannelCredentials()) {
    checkArgument(
        googleGrpc.getChannelCredentials().hasLocalCredentials(),
        "only GoogleLocalCredentials supported");
  }
  if (googleGrpc.getCallCredentialsCount() > 0) {
    checkArgument(
        googleGrpc.getCallCredentialsCount() == 1,
        "Exactly one CallCredential expected in GoogleGrpc");
    GoogleGrpc.CallCredentials callCreds = googleGrpc.getCallCredentials(0);
    checkArgument(callCreds.hasFromPlugin(), "only plugin credential supported");
    return new FileBasedPluginCredential(callCreds.getFromPlugin());
  }
  logger.warning("No CallCredentials specified.");
  return null;
}
 
Example #19
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 #20
Source File: AuthClient.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
/**
 * Construct client for accessing GreeterGrpc server.
 */
AuthClient(CallCredentials callCredentials, String host, int port) {
  this(
      callCredentials,
      ManagedChannelBuilder
          .forAddress(host, port)
          // Channels are secure by default (via SSL/TLS). For this example we disable TLS
          // to avoid needing certificates, but it is recommended to use a secure channel
          // while passing credentials.
          .usePlaintext()
          .build());
}
 
Example #21
Source File: GoogleAuthUtils.java    From bazel with Apache License 2.0 5 votes vote down vote up
/**
 * Create a new {@link CallCredentials} object.
 *
 * @throws IOException in case the call credentials can't be constructed.
 */
public static CallCredentials newCallCredentials(AuthAndTLSOptions options) throws IOException {
  Credentials creds = newCredentials(options);
  if (creds != null) {
    return MoreCallCredentials.from(creds);
  }
  return null;
}
 
Example #22
Source File: GoogleAuthUtils.java    From bazel with Apache License 2.0 5 votes vote down vote up
@VisibleForTesting
public static CallCredentials newCallCredentials(
    @Nullable InputStream credentialsFile, List<String> authScope) throws IOException {
  Credentials creds = newCredentials(credentialsFile, authScope);
  if (creds != null) {
    return MoreCallCredentials.from(creds);
  }
  return null;
}
 
Example #23
Source File: GrpcRemoteExecutor.java    From bazel with Apache License 2.0 5 votes vote down vote up
public GrpcRemoteExecutor(
    ReferenceCountedChannel channel,
    @Nullable CallCredentials callCredentials,
    RemoteRetrier retrier,
    RemoteOptions options) {
  this.channel = channel;
  this.callCredentials = callCredentials;
  this.retrier = retrier;
  this.options = options;
}
 
Example #24
Source File: GrpcClientTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Test
void credentialsUnaryCall_fail() {
    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) {
                                   applier.fail(Status.FAILED_PRECONDITION);
                               }

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

    assertThatThrownBy(() -> stub.emptyCall(EMPTY))
            .isInstanceOfSatisfying(StatusRuntimeException.class,
                                    t -> assertThat(t.getStatus().getCode())
                                            .isEqualTo(Code.FAILED_PRECONDITION));
}
 
Example #25
Source File: CallCredentialsHelper.java    From grpc-spring-boot-starter with MIT License 5 votes vote down vote up
/**
 * Creates a new {@link StubTransformer} that will assign credentials to the given {@link AbstractStub} based on the
 * name. If the given map does not contain a value for the given name, then the optional fallback will be used
 * otherwise the call credentials will be omitted.
 *
 * @param credentialsByName The map that contains the call credentials.
 * @param fallback The optional fallback to use.
 * @return The transformed stub.
 * @see AbstractStub#withCallCredentials(CallCredentials)
 */
public static StubTransformer mappedCredentialsStubTransformer(
        final Map<String, CallCredentials> credentialsByName,
        @Nullable final CallCredentials fallback) {
    requireNonNull(credentialsByName, "credentials");
    return (name, stub) -> {
        final CallCredentials credentials = credentialsByName.getOrDefault(name, fallback);
        if (credentials == null) {
            return stub;
        } else {
            return stub.withCallCredentials(credentials);
        }
    };
}
 
Example #26
Source File: GoogleAuthUtils.java    From bazel-buildfarm with Apache License 2.0 5 votes vote down vote up
/**
 * Create a new {@link CallCredentials} object.
 *
 * @throws IOException in case the call credentials can't be constructed.
 */
public static CallCredentials newCallCredentials(AuthAndTLSOptions options) throws IOException {
  Credentials creds = newCredentials(options);
  if (creds != null) {
    return MoreCallCredentials.from(creds);
  }
  return null;
}
 
Example #27
Source File: FirestoreIntegrationTestsConfiguration.java    From spring-cloud-gcp with Apache License 2.0 5 votes vote down vote up
@Bean
FirestoreGrpc.FirestoreStub firestoreStub()  throws IOException {
	GoogleCredentials credentials = GoogleCredentials.getApplicationDefault();
	CallCredentials callCredentials = MoreCallCredentials.from(credentials);

	// Create a channel
	ManagedChannel channel = ManagedChannelBuilder
			.forTarget("dns:///firestore.googleapis.com:443")
			.build();
	return FirestoreGrpc.newStub(channel).withCallCredentials(callCredentials);
}
 
Example #28
Source File: WithBasicAuthSecurityConfiguration.java    From grpc-spring-boot-starter with MIT License 5 votes vote down vote up
@Bean
StubTransformer mappedCredentialsStubTransformer() {
    return CallCredentialsHelper.mappedCredentialsStubTransformer(ImmutableMap.<String, CallCredentials>builder()
            .put("test", testCallCredentials("client1"))
            .put("noPerm", testCallCredentials("client2"))
            .put("unknownUser", testCallCredentials("unknownUser"))
            // .put("noAuth", null)
            .build());
}
 
Example #29
Source File: CallCredentialsApplyingTest.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
@Test
public void credentialThrows() {
  final RuntimeException ex = new RuntimeException();
  when(mockTransport.getAttributes()).thenReturn(Attributes.EMPTY);
  doThrow(ex).when(mockCreds).applyRequestMetadata(
      any(RequestInfo.class), same(mockExecutor),
      any(CallCredentials.MetadataApplier.class));

  FailingClientStream stream =
      (FailingClientStream) transport.newStream(method, origHeaders, callOptions);

  verify(mockTransport, never()).newStream(method, origHeaders, callOptions);
  assertEquals(Status.Code.UNAUTHENTICATED, stream.getError().getCode());
  assertSame(ex, stream.getError().getCause());
}
 
Example #30
Source File: CallCredentialsDecoratingClient.java    From armeria with Apache License 2.0 5 votes vote down vote up
CallCredentialsDecoratingClient(PooledHttpClient delegate, CallCredentials credentials,
                                MethodDescriptor<?, ?> method, String authority) {
    super(delegate);
    this.credentials = credentials;
    this.method = method;
    this.authority = authority;
}