private static void prepareKmsKeys() throws IOException { String projectId = remoteStorageHelper.getOptions().getProjectId(); GoogleCredentials credentials = GoogleCredentials.getApplicationDefault(); ManagedChannel kmsChannel = ManagedChannelBuilder.forTarget("cloudkms.googleapis.com:443").build(); KeyManagementServiceBlockingStub kmsStub = KeyManagementServiceGrpc.newBlockingStub(kmsChannel) .withCallCredentials(MoreCallCredentials.from(credentials)); IAMPolicyGrpc.IAMPolicyBlockingStub iamStub = IAMPolicyGrpc.newBlockingStub(kmsChannel) .withCallCredentials(MoreCallCredentials.from(credentials)); ensureKmsKeyRingExistsForTests(kmsStub, projectId, KMS_KEY_RING_LOCATION, KMS_KEY_RING_NAME); ensureKmsKeyRingIamPermissionsForTests( iamStub, projectId, KMS_KEY_RING_LOCATION, KMS_KEY_RING_NAME); kmsKeyOneResourcePath = ensureKmsKeyExistsForTests( kmsStub, projectId, KMS_KEY_RING_LOCATION, KMS_KEY_RING_NAME, KMS_KEY_ONE_NAME); kmsKeyTwoResourcePath = ensureKmsKeyExistsForTests( kmsStub, projectId, KMS_KEY_RING_LOCATION, KMS_KEY_RING_NAME, KMS_KEY_TWO_NAME); }
/** * Converts a Google Auth Library {@link Credentials} to {@link CallCredentials}. * * <p>Although this is a stable API, note that the returned instance's API is not stable. You are * free to use the class name {@code CallCredentials} and pass the instance to other code, but the * instance can't be called directly from code expecting stable behavior. See {@link * CallCredentials}. */ public static CallCredentials from(Credentials creds) { return new GoogleAuthLibraryCallCredentials(creds); }
@VisibleForTesting GoogleAuthLibraryCallCredentials(Credentials creds, JwtHelper jwtHelper) { checkNotNull(creds, "creds"); boolean requirePrivacy = false; if (googleCredentialsClass != null) { // All GoogleCredentials instances are bearer tokens and should only be used on private // channels. This catches all return values from GoogleCredentials.getApplicationDefault(). // This should be checked before upgrading the Service Account to JWT, as JWT is also a bearer // token. requirePrivacy = googleCredentialsClass.isInstance(creds); } if (jwtHelper != null) { creds = jwtHelper.tryServiceAccountToJwt(creds); } this.requirePrivacy = requirePrivacy; this.creds = creds; }
/** Return channel with interceptor for returning credentials. */ private Channel newChannel() throws IOException { checkState(publisherChannel != null, "PubsubGrpcClient has been closed"); ClientAuthInterceptor interceptor = new ClientAuthInterceptor(credentials, Executors.newSingleThreadExecutor()); return ClientInterceptors.intercept(publisherChannel, interceptor); }
@VisibleForTesting @Nullable static JwtHelper createJwtHelperOrNull(ClassLoader loader) { Class<?> rawServiceAccountClass; try { // Specify loader so it can be overridden in tests rawServiceAccountClass = Class.forName("com.google.auth.oauth2.ServiceAccountCredentials", false, loader); } catch (ClassNotFoundException ex) { return null; } Exception caughtException; try { return new JwtHelper(rawServiceAccountClass, loader); } catch (ClassNotFoundException ex) { caughtException = ex; } catch (NoSuchMethodException ex) { caughtException = ex; } if (caughtException != null) { // Failure is a bug in this class, but we still choose to gracefully recover log.log(Level.WARNING, "Failed to create JWT helper. This is unexpected", caughtException); } return null; }
@Override protected void checkedStart(Listener<RespT> responseListener, Metadata headers) throws StatusException { Metadata cachedSaved; URI uri = serviceUri(next, method); synchronized (ClientAuthInterceptor.this) { // TODO(louiscryan): This is icky but the current auth library stores the same // metadata map until the next refresh cycle. This will be fixed once // https://github.com/google/google-auth-library-java/issues/3 // is resolved. // getRequestMetadata() may return a different map based on the provided URI, i.e., for // JWT. However, today it does not cache JWT and so we won't bother tring to cache its // return value based on the URI. Map<String, List<String>> latestMetadata = getRequestMetadata(uri); if (lastMetadata == null || lastMetadata != latestMetadata) { lastMetadata = latestMetadata; cached = toHeaders(lastMetadata); } cachedSaved = cached; } headers.merge(cachedSaved); delegate().start(responseListener, headers); } };
/** * Generate a JWT-specific service URI. The URI is simply an identifier with enough information * for a service to know that the JWT was intended for it. The URI will commonly be verified with * a simple string equality check. */ private static URI serviceUri(String authority, MethodDescriptor<?, ?> method) throws StatusException { // Always use HTTPS, by definition. final String scheme = "https"; final int defaultPort = 443; String path = "/" + MethodDescriptor.extractFullServiceName(method.getFullMethodName()); URI uri; try { uri = new URI(scheme, authority, path, null, null); } catch (URISyntaxException e) { throw Status.UNAUTHENTICATED.withDescription("Unable to construct service URI for auth") .withCause(e).asException(); } // The default port must not be present. Alternative ports should be present. if (uri.getPort() == defaultPort) { uri = removePort(uri); } return uri; }
/** * Generate a JWT-specific service URI. The URI is simply an identifier with enough information * for a service to know that the JWT was intended for it. The URI will commonly be verified with * a simple string equality check. */ private URI serviceUri(Channel channel, MethodDescriptor<?, ?> method) throws StatusException { String authority = channel.authority(); if (authority == null) { throw Status.UNAUTHENTICATED.withDescription("Channel has no authority").asException(); } // Always use HTTPS, by definition. final String scheme = "https"; final int defaultPort = 443; String path = "/" + MethodDescriptor.extractFullServiceName(method.getFullMethodName()); URI uri; try { uri = new URI(scheme, authority, path, null, null); } catch (URISyntaxException e) { throw Status.UNAUTHENTICATED.withDescription("Unable to construct service URI for auth") .withCause(e).asException(); } // The default port must not be present. Alternative ports should be present. if (uri.getPort() == defaultPort) { uri = removePort(uri); } return uri; }
final URI uri; try { uri = serviceUri(authority, info.getMethodDescriptor()); } catch (StatusException e) { applier.fail(e.getStatus());
@Override public GrpcCallContext withCredentials(Credentials newCredentials) { Preconditions.checkNotNull(newCredentials); CallCredentials callCredentials = MoreCallCredentials.from(newCredentials); return withCallOptions(callOptions.withCallCredentials(callCredentials)); }
/** Return {@link io.grpc.Channel} which is used by Cloud Pub/Sub gRPC API's. */ public static Channel getChannel(CredentialsProvider credentialsProvider) throws IOException { ManagedChannel channelImpl = NettyChannelBuilder.forAddress(ENDPOINT, 443) .negotiationType(NegotiationType.TLS) // Maximum Pub/Sub message size is 10MB. .maxInboundMessageSize(10 * 1024 * 1024) .build(); final ClientAuthInterceptor interceptor = new ClientAuthInterceptor( credentialsProvider.getCredentials(), Executors.newCachedThreadPool()); return ClientInterceptors.intercept(channelImpl, interceptor); }
@Override public GrpcCallContext withCredentials(Credentials newCredentials) { Preconditions.checkNotNull(newCredentials); CallCredentials callCredentials = MoreCallCredentials.from(newCredentials); return withCallOptions(callOptions.withCallCredentials(callCredentials)); }
/** * Create a new gRPC channel to the Google Genomics API, using the provided credentials for auth. * * @param creds The credential. * @param fields Which fields to return in the partial response, or null for none. * @return The ManagedChannel. * @throws SSLException */ public static ManagedChannel fromCreds(GoogleCredentials creds, String fields) throws SSLException { List<ClientInterceptor> interceptors = new ArrayList(); interceptors.add(new ClientAuthInterceptor(creds.createScoped(Arrays.asList(GENOMICS_SCOPE)), Executors.newSingleThreadExecutor())); if (!Strings.isNullOrEmpty(fields)) { Metadata headers = new Metadata(); Metadata.Key<String> partialResponseHeader = Metadata.Key.of(PARTIAL_RESPONSE_HEADER, Metadata.ASCII_STRING_MARSHALLER); headers.put(partialResponseHeader, fields); interceptors.add(MetadataUtils.newAttachHeadersInterceptor(headers)); } return getGenomicsManagedChannel(interceptors); }
/** * Get CallCredentials from OAuthCredentials * * @param oAuthCredentials the credentials from the AuthenticationHelper * @return the CallCredentials for the GRPC requests */ private CallCredentials getCallCredentials(OAuthCredentials oAuthCredentials) { AccessToken accessToken = new AccessToken( oAuthCredentials.getAccessToken(), new Date(oAuthCredentials.getExpirationTime()) ); OAuth2Credentials oAuth2Credentials = new OAuth2Credentials(accessToken); // Create an instance of {@link io.grpc.CallCredentials} return MoreCallCredentials.from(oAuth2Credentials); }
new ClientAuthInterceptor(credentials, MoreExecutors.directExecutor());
@Bean @ConditionalOnMissingBean StorageComponent storage( @Value("${zipkin.storage.strict-trace-id:true}") boolean strictTraceId, @Qualifier("projectId") String projectId, ManagedChannel managedChannel, Credentials credentials) { return StackdriverStorage.newBuilder(managedChannel) .projectId(projectId) .strictTraceId(strictTraceId) .callOptions(DEFAULT.withCallCredentials(MoreCallCredentials.from(credentials))) .build(); }
private GoogleDefaultChannelBuilder(String target) { delegate = NettyChannelBuilder.forTarget(target); InternalNettyChannelBuilder.setProtocolNegotiatorFactory( delegate(), new ProtocolNegotiatorFactory()); @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); } delegate().intercept(new GoogleDefaultInterceptor(credentials, status)); }
CallOptions callOptions = CallOptions.DEFAULT .withCallCredentials( MoreCallCredentials.from( this.finalCredentialsProvider.getCredentials())) .withExecutor(executorProvider.getExecutor());
if (credentials != null) { PravegaCredentialsWrapper wrapper = new PravegaCredentialsWrapper(credentials); client = client.withCallCredentials(MoreCallCredentials.from(wrapper));