下面列出了怎么用io.grpc.CallCredentials的API类实例代码及写法,或者点击链接到github查看源代码。
@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());
}
@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 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));
}
@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());
}
@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));
}
@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());
}
/**
* 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);
}
@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());
}
/**
* @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);
}
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;
}
@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());
}
@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));
}
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);
}
@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.");
}
@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));
}
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));
}
@Override
public ManagedChannel build() {
@Nullable CallCredentials credentials = null;
Status status = Status.OK;
try {
credentials = MoreCallCredentials.from(GoogleCredentials.getApplicationDefault());
} catch (IOException e) {
status =
Status.UNAUTHENTICATED
.withDescription("Failed to get Google default credentials")
.withCause(e);
}
return delegate().intercept(new GoogleDefaultInterceptor(credentials, status)).build();
}
@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));
}
@VisibleForTesting
static ChannelInfo extractChannelInfo(ConfigSource configSource) {
checkNotNull(configSource, "configSource");
checkArgument(
configSource.hasApiConfigSource(), "only configSource with ApiConfigSource supported");
ApiConfigSource apiConfigSource = configSource.getApiConfigSource();
checkArgument(
ApiType.GRPC.equals(apiConfigSource.getApiType()),
"only GRPC ApiConfigSource type supported");
checkArgument(
apiConfigSource.getGrpcServicesCount() == 1,
"expecting exactly 1 GrpcService in ApiConfigSource");
GrpcService grpcService = apiConfigSource.getGrpcServices(0);
checkArgument(
grpcService.hasGoogleGrpc() && !grpcService.hasEnvoyGrpc(),
"only GoogleGrpc expected in GrpcService");
GoogleGrpc googleGrpc = grpcService.getGoogleGrpc();
CallCredentials callCredentials = getVerifiedCredentials(googleGrpc);
String targetUri = googleGrpc.getTargetUri();
String channelType = null;
if (googleGrpc.hasConfig()) {
Struct struct = googleGrpc.getConfig();
Value value = struct.getFieldsMap().get("channelType");
channelType = value.getStringValue();
}
checkArgument(!Strings.isNullOrEmpty(targetUri), "targetUri in GoogleGrpc is empty!");
return new ChannelInfo(targetUri, channelType, callCredentials);
}
@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());
}
@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());
}
@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);
}
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;
}
/**
* 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;
}
/**
* 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);
}
};
}
@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());
}
CallCredentialsDecoratingClient(PooledHttpClient delegate, CallCredentials credentials,
MethodDescriptor<?, ?> method, String authority) {
super(delegate);
this.credentials = credentials;
this.method = method;
this.authority = authority;
}