com.google.auth.oauth2.ServiceAccountCredentials Java Examples

The following examples show how to use com.google.auth.oauth2.ServiceAccountCredentials. 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: GCPCredentialsServiceTest.java    From nifi with Apache License 2.0 6 votes vote down vote up
@Test
public void testRawJsonCredentials() throws Exception {
    final String jsonRead = new String(
            Files.readAllBytes(Paths.get("src/test/resources/mock-gcp-service-account.json"))
    );

    final TestRunner runner = TestRunners.newTestRunner(MockCredentialsServiceProcessor.class);
    final GCPCredentialsControllerService serviceImpl = new GCPCredentialsControllerService();
    runner.addControllerService("gcpCredentialsProvider", serviceImpl);

    runner.setProperty(serviceImpl, SERVICE_ACCOUNT_JSON,
            jsonRead);
    runner.enableControllerService(serviceImpl);

    runner.assertValid(serviceImpl);

    final GCPCredentialsService service = (GCPCredentialsService) runner.getProcessContext()
            .getControllerServiceLookup().getControllerService("gcpCredentialsProvider");

    assertNotNull(service);
    final GoogleCredentials credentials = service.getGoogleCredentials();
    assertNotNull(credentials);

    assertEquals("Credentials class should be equal", ServiceAccountCredentials.class,
            credentials.getClass());
}
 
Example #2
Source File: TelemetryUtils.java    From meghanada-server with GNU General Public License v3.0 6 votes vote down vote up
public static boolean setupStackdriverStatsExporter() {
  if (enableTelemetry()) {
    try {
      registerAllViews();
      URL url = Resources.getResource(CREDENTIALS_JSON);
      StackdriverStatsExporter.createAndRegister(
          StackdriverStatsConfiguration.builder()
              .setProjectId(PROJECT_ID)
              .setCredentials(ServiceAccountCredentials.fromStream(url.openStream()))
              .build());
      log.info("enable stackdriver stats exporter");
      return true;
    } catch (Throwable e) {
      log.warn("{}", e.getMessage());
    }
  }
  return false;
}
 
Example #3
Source File: TelemetryUtils.java    From meghanada-server with GNU General Public License v3.0 6 votes vote down vote up
public static boolean setupStackdriverTraceExporter() {
  if (enableTelemetry()) {
    try {
      URL url = Resources.getResource(CREDENTIALS_JSON);
      StackdriverTraceExporter.createAndRegister(
          StackdriverTraceConfiguration.builder()
              .setProjectId(PROJECT_ID)
              .setCredentials(ServiceAccountCredentials.fromStream(url.openStream()))
              .build());
      log.info("enable stackdriver trace exporter");
      return true;
    } catch (Throwable e) {
      log.warn("{}", e.getMessage());
    }
  }
  return false;
}
 
Example #4
Source File: EntityManagerFactoryTest.java    From catatumbo with Apache License 2.0 6 votes vote down vote up
@Test
public void testCreateEntityManager_ConnectionParameters7() throws FileNotFoundException {
  ConnectionParameters parameters = new ConnectionParameters();
  final String projectId = "my-project";
  final String namespace = "my-namespace";
  final String credentialsFile = System.getenv(TestUtils.ENV_CREDENTIALS);
  if (Utility.isNullOrEmpty(credentialsFile)) {
    System.out.printf("Enviornment variable %s is not set, skipping the test case%n",
        TestUtils.ENV_CREDENTIALS);
    return;
  }
  parameters.setProjectId(projectId);
  parameters.setNamespace(namespace);
  parameters.setJsonCredentialsStream(new FileInputStream(credentialsFile));
  parameters.setJsonCredentialsFile("nonexistentfile.json");
  EntityManagerFactory emf = EntityManagerFactory.getInstance();
  DefaultEntityManager em = (DefaultEntityManager) emf.createEntityManager(parameters);
  DatastoreOptions options = em.getDatastore().getOptions();
  assertEquals(ConnectionParameters.DEFAULT_SERVICE_URL, options.getHost());
  assertNotNull(options.getProjectId());
  assertTrue(options.getProjectId().length() > 0);
  assertEquals(ServiceAccountCredentials.class, options.getCredentials().getClass());
  assertEquals(projectId, options.getProjectId());
  assertEquals(namespace, options.getNamespace());
}
 
Example #5
Source File: EntityManagerFactoryTest.java    From catatumbo with Apache License 2.0 6 votes vote down vote up
@Test
public void testCreateEntityManager_ConnectionParameters6() throws FileNotFoundException {
  ConnectionParameters parameters = new ConnectionParameters();
  final String projectId = "my-project";
  final String namespace = "my-namespace";
  final String credentialsFile = System.getenv(TestUtils.ENV_CREDENTIALS);
  if (Utility.isNullOrEmpty(credentialsFile)) {
    System.out.printf("Enviornment variable %s is not set, skipping the test case%n",
        TestUtils.ENV_CREDENTIALS);
    return;
  }
  parameters.setProjectId(projectId);
  parameters.setNamespace(namespace);
  parameters.setJsonCredentialsStream(new FileInputStream(credentialsFile));
  EntityManagerFactory emf = EntityManagerFactory.getInstance();
  DefaultEntityManager em = (DefaultEntityManager) emf.createEntityManager(parameters);
  DatastoreOptions options = em.getDatastore().getOptions();
  assertEquals(ConnectionParameters.DEFAULT_SERVICE_URL, options.getHost());
  assertNotNull(options.getProjectId());
  assertTrue(options.getProjectId().length() > 0);
  assertEquals(ServiceAccountCredentials.class, options.getCredentials().getClass());
  assertEquals(projectId, options.getProjectId());
  assertEquals(namespace, options.getNamespace());
}
 
Example #6
Source File: EntityManagerFactoryTest.java    From catatumbo with Apache License 2.0 6 votes vote down vote up
@Test
public void testCreateEntityManager_ConnectionParameters5() {
  ConnectionParameters parameters = new ConnectionParameters();
  final String projectId = "my-project";
  final String namespace = "my-namespace";
  final String credentialsFile = System.getenv(TestUtils.ENV_CREDENTIALS);
  if (Utility.isNullOrEmpty(credentialsFile)) {
    System.out.printf("Enviornment variable %s is not set, skipping the test case%n",
        TestUtils.ENV_CREDENTIALS);
    return;
  }
  parameters.setProjectId(projectId);
  parameters.setNamespace(namespace);
  parameters.setJsonCredentialsFile(credentialsFile);
  EntityManagerFactory emf = EntityManagerFactory.getInstance();
  DefaultEntityManager em = (DefaultEntityManager) emf.createEntityManager(parameters);
  DatastoreOptions options = em.getDatastore().getOptions();
  assertEquals(ConnectionParameters.DEFAULT_SERVICE_URL, options.getHost());
  assertNotNull(options.getProjectId());
  assertTrue(options.getProjectId().length() > 0);
  assertEquals(ServiceAccountCredentials.class, options.getCredentials().getClass());
  assertEquals(projectId, options.getProjectId());
  assertEquals(namespace, options.getNamespace());
}
 
Example #7
Source File: GoogleCloudCredentialsConfig.java    From datacollector with Apache License 2.0 6 votes vote down vote up
/**
 * Reads a JSON credentials file for a service account from and returns any errors.
 *
 * @param issues list to append any discovered issues.
 * @return a generic credentials object
 */
private Credentials getCredentials(Stage.Context context, List<Stage.ConfigIssue> issues) {
  Credentials credentials = null;

  try (InputStream in = getCredentialsInputStream(context, issues)) {
    if (in != null) {
      credentials = ServiceAccountCredentials.fromStream(in);
    }
  } catch (IOException | IllegalArgumentException e) {
    LOG.error(Errors.GOOGLE_02.getMessage(), e);
    issues.add(context.createConfigIssue("CREDENTIALS",
        CONF_CREDENTIALS_CREDENTIALS_PROVIDER,
        Errors.GOOGLE_02
    ));
  }

  return credentials;
}
 
Example #8
Source File: ContainerRegistryAuthSupplier.java    From docker-client with Apache License 2.0 6 votes vote down vote up
public ContainerRegistryAuthSupplier build() {
  final GoogleCredentials credentials = this.credentials.createScoped(scopes);

  // log some sort of identifier for the credentials, which requires looking at the
  // instance type
  if (credentials instanceof ServiceAccountCredentials) {
    final String clientEmail = ((ServiceAccountCredentials) credentials).getClientEmail();
    log.info("loaded credentials for service account with clientEmail={}", clientEmail);
  } else if (credentials instanceof UserCredentials) {
    final String clientId = ((UserCredentials) credentials).getClientId();
    log.info("loaded credentials for user account with clientId={}", clientId);
  }

  final Clock clock = Clock.systemDefaultZone();
  final DefaultCredentialRefresher refresher = new DefaultCredentialRefresher();

  return new ContainerRegistryAuthSupplier(credentials, clock, minimumExpiryMillis, refresher);
}
 
Example #9
Source File: StorageExample.java    From google-cloud-java with Apache License 2.0 6 votes vote down vote up
@Override
Tuple<ServiceAccountCredentials, BlobInfo> parse(String... args)
    throws IOException, KeyStoreException, CertificateException, NoSuchAlgorithmException,
        UnrecoverableKeyException {
  if (args.length != 4) {
    throw new IllegalArgumentException();
  }
  KeyStore keystore = KeyStore.getInstance("PKCS12");
  keystore.load(Files.newInputStream(Paths.get(args[0])), PASSWORD);
  PrivateKey privateKey = (PrivateKey) keystore.getKey("privatekey", PASSWORD);
  ServiceAccountCredentials credentials =
      ServiceAccountCredentials.newBuilder()
          .setClientEmail(args[1])
          .setPrivateKey(privateKey)
          .build();
  return Tuple.of(credentials, BlobInfo.newBuilder(BlobId.of(args[2], args[3])).build());
}
 
Example #10
Source File: FirebaseOptionsTest.java    From firebase-admin-java with Apache License 2.0 6 votes vote down vote up
@Test
public void createOptionsWithOnlyMandatoryValuesSet() throws IOException {
  FirebaseOptions firebaseOptions =
      new FirebaseOptions.Builder()
          .setCredentials(GoogleCredentials.fromStream(ServiceAccount.EDITOR.asStream()))
          .build();
  assertNotNull(firebaseOptions.getJsonFactory());
  assertNotNull(firebaseOptions.getHttpTransport());
  assertNotNull(firebaseOptions.getThreadManager());
  assertNull(firebaseOptions.getDatabaseUrl());
  assertNull(firebaseOptions.getStorageBucket());
  assertEquals(0, firebaseOptions.getConnectTimeout());
  assertEquals(0, firebaseOptions.getReadTimeout());

  GoogleCredentials credentials = firebaseOptions.getCredentials();
  assertNotNull(credentials);
  assertTrue(credentials instanceof ServiceAccountCredentials);
  assertEquals(
      GoogleCredential.fromStream(ServiceAccount.EDITOR.asStream()).getServiceAccountId(),
      ((ServiceAccountCredentials) credentials).getClientEmail());
  assertNull(firebaseOptions.getFirestoreOptions());
}
 
Example #11
Source File: StorageSnippets.java    From google-cloud-java with Apache License 2.0 6 votes vote down vote up
/**
 * Example of creating a signed URL passing the {@link
 * SignUrlOption#signWith(ServiceAccountSigner)} option, that will be used for signing the URL.
 */
// [TARGET signUrl(BlobInfo, long, TimeUnit, SignUrlOption...)]
// [VARIABLE "my_unique_bucket"]
// [VARIABLE "my_blob_name"]
// [VARIABLE "/path/to/key.json"]
public URL signUrlWithSigner(String bucketName, String blobName, String keyPath)
    throws IOException {
  // [START signUrlWithSigner]
  URL signedUrl =
      storage.signUrl(
          BlobInfo.newBuilder(bucketName, blobName).build(),
          14,
          TimeUnit.DAYS,
          SignUrlOption.signWith(
              ServiceAccountCredentials.fromStream(new FileInputStream(keyPath))));
  // [END signUrlWithSigner]
  return signedUrl;
}
 
Example #12
Source File: FirebaseCustomTokenTest.java    From firebase-admin-java with Apache License 2.0 6 votes vote down vote up
@Test
public void testCreateCustomTokenWithDeveloperClaims() throws Exception {
  FirebaseOptions options = FirebaseOptions.builder()
      .setCredentials(ServiceAccountCredentials.fromStream(ServiceAccount.EDITOR.asStream()))
      .build();
  FirebaseApp app = FirebaseApp.initializeApp(options);
  FirebaseAuth auth = FirebaseAuth.getInstance(app);

  String token = auth.createCustomTokenAsync(
      "user1", MapBuilder.of("claim", "value")).get();
  FirebaseCustomAuthToken parsedToken = FirebaseCustomAuthToken.parse(new GsonFactory(), token);
  assertEquals(parsedToken.getPayload().getUid(), "user1");
  assertEquals(parsedToken.getPayload().getSubject(), ServiceAccount.EDITOR.getEmail());
  assertEquals(parsedToken.getPayload().getIssuer(), ServiceAccount.EDITOR.getEmail());
  assertEquals(parsedToken.getPayload().getDeveloperClaims().keySet().size(), 1);
  assertEquals(parsedToken.getPayload().getDeveloperClaims().get("claim"), "value");
  assertTrue(ServiceAccount.EDITOR.verifySignature(parsedToken));
}
 
Example #13
Source File: FirebaseCustomTokenTest.java    From firebase-admin-java with Apache License 2.0 6 votes vote down vote up
@Test
public void testCreateCustomToken() throws Exception {
  FirebaseOptions options = FirebaseOptions.builder()
      .setCredentials(ServiceAccountCredentials.fromStream(ServiceAccount.EDITOR.asStream()))
      .build();
  FirebaseApp app = FirebaseApp.initializeApp(options);
  FirebaseAuth auth = FirebaseAuth.getInstance(app);

  String token = auth.createCustomTokenAsync("user1").get();
  FirebaseCustomAuthToken parsedToken = FirebaseCustomAuthToken.parse(new GsonFactory(), token);
  assertEquals(parsedToken.getPayload().getUid(), "user1");
  assertEquals(parsedToken.getPayload().getSubject(), ServiceAccount.EDITOR.getEmail());
  assertEquals(parsedToken.getPayload().getIssuer(), ServiceAccount.EDITOR.getEmail());
  assertNull(parsedToken.getPayload().getDeveloperClaims());
  assertTrue(ServiceAccount.EDITOR.verifySignature(parsedToken));
}
 
Example #14
Source File: FirebaseApp.java    From firebase-admin-java with Apache License 2.0 6 votes vote down vote up
/**
 * Returns the Google Cloud project ID associated with this app.
 *
 * @return A string project ID or null.
 */
@Nullable
String getProjectId() {
  // Try to get project ID from user-specified options.
  String projectId = options.getProjectId();

  // Try to get project ID from the credentials.
  if (Strings.isNullOrEmpty(projectId)) {
    GoogleCredentials credentials = options.getCredentials();
    if (credentials instanceof ServiceAccountCredentials) {
      projectId = ((ServiceAccountCredentials) credentials).getProjectId();
    }
  }

  // Try to get project ID from the environment.
  if (Strings.isNullOrEmpty(projectId)) {
    projectId = System.getenv("GOOGLE_CLOUD_PROJECT");
  }
  if (Strings.isNullOrEmpty(projectId)) {
    projectId = System.getenv("GCLOUD_PROJECT");
  }
  return projectId;
}
 
Example #15
Source File: GCPCredentialsServiceTest.java    From localization_nifi with Apache License 2.0 6 votes vote down vote up
@Test
public void testRawJsonCredentials() throws Exception {
    final String jsonRead = new String(
            Files.readAllBytes(Paths.get("src/test/resources/mock-gcp-service-account.json"))
    );

    final TestRunner runner = TestRunners.newTestRunner(MockCredentialsServiceProcessor.class);
    final GCPCredentialsControllerService serviceImpl = new GCPCredentialsControllerService();
    runner.addControllerService("gcpCredentialsProvider", serviceImpl);

    runner.setProperty(serviceImpl, SERVICE_ACCOUNT_JSON,
            jsonRead);
    runner.enableControllerService(serviceImpl);

    runner.assertValid(serviceImpl);

    final GCPCredentialsService service = (GCPCredentialsService) runner.getProcessContext()
            .getControllerServiceLookup().getControllerService("gcpCredentialsProvider");

    assertNotNull(service);
    final GoogleCredentials credentials = service.getGoogleCredentials();
    assertNotNull(credentials);

    assertEquals("Credentials class should be equal", ServiceAccountCredentials.class,
            credentials.getClass());
}
 
Example #16
Source File: CredentialsFactoryTest.java    From localization_nifi with Apache License 2.0 6 votes vote down vote up
@Test
public void testJsonStringCredentials() throws Exception {
    final String jsonRead = new String(
            Files.readAllBytes(Paths.get("src/test/resources/mock-gcp-service-account.json"))
    );
    final TestRunner runner = TestRunners.newTestRunner(MockCredentialsFactoryProcessor.class);
    runner.setProperty(CredentialPropertyDescriptors.SERVICE_ACCOUNT_JSON,
            jsonRead);
    runner.assertValid();

    Map<PropertyDescriptor, String> properties = runner.getProcessContext().getProperties();
    final CredentialsFactory factory = new CredentialsFactory();
    final GoogleCredentials credentials = factory.getGoogleCredentials(properties);

    assertNotNull(credentials);
    assertEquals("credentials class should be equal", ServiceAccountCredentials.class,
            credentials.getClass());
}
 
Example #17
Source File: GCPCredentialsServiceTest.java    From localization_nifi with Apache License 2.0 6 votes vote down vote up
@Test
public void testFileCredentials() throws Exception {
    final TestRunner runner = TestRunners.newTestRunner(MockCredentialsServiceProcessor.class);
    final GCPCredentialsControllerService serviceImpl = new GCPCredentialsControllerService();
    runner.addControllerService("gcpCredentialsProvider", serviceImpl);

    runner.setProperty(serviceImpl, SERVICE_ACCOUNT_JSON_FILE,
            "src/test/resources/mock-gcp-service-account.json");
    runner.enableControllerService(serviceImpl);

    runner.assertValid(serviceImpl);

    final GCPCredentialsService service = (GCPCredentialsService) runner.getProcessContext()
            .getControllerServiceLookup().getControllerService("gcpCredentialsProvider");

    assertNotNull(service);
    final GoogleCredentials credentials = service.getGoogleCredentials();
    assertNotNull(credentials);

    assertEquals("Credentials class should be equal", ServiceAccountCredentials.class,
            credentials.getClass());
}
 
Example #18
Source File: AbstractInteropTest.java    From grpc-nebula-java with Apache License 2.0 6 votes vote down vote up
/** Test JWT-based auth. */
public void jwtTokenCreds(InputStream serviceAccountJson) throws Exception {
  final SimpleRequest request = SimpleRequest.newBuilder()
      .setResponseSize(314159)
      .setPayload(Payload.newBuilder()
          .setBody(ByteString.copyFrom(new byte[271828])))
      .setFillUsername(true)
      .build();

  ServiceAccountCredentials credentials = (ServiceAccountCredentials)
      GoogleCredentials.fromStream(serviceAccountJson);
  TestServiceGrpc.TestServiceBlockingStub stub = blockingStub
      .withCallCredentials(MoreCallCredentials.from(credentials));
  SimpleResponse response = stub.unaryCall(request);
  assertEquals(credentials.getClientEmail(), response.getUsername());
  assertEquals(314159, response.getPayload().getBody().size());
}
 
Example #19
Source File: GoogleAuthLibraryCallCredentialsTest.java    From grpc-nebula-java with Apache License 2.0 6 votes vote down vote up
@Test
public void serviceAccountToJwt() throws Exception {
  KeyPair pair = KeyPairGenerator.getInstance("RSA").generateKeyPair();
  @SuppressWarnings("deprecation")
  ServiceAccountCredentials credentials = new ServiceAccountCredentials(
      null, "[email protected]", pair.getPrivate(), null, null) {
    @Override
    public AccessToken refreshAccessToken() {
      throw new AssertionError();
    }
  };

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

  verify(applier).apply(headersCaptor.capture());
  Metadata headers = headersCaptor.getValue();
  String[] authorization = Iterables.toArray(headers.getAll(AUTHORIZATION), String.class);
  assertEquals(1, authorization.length);
  assertTrue(authorization[0], authorization[0].startsWith("Bearer "));
  // JWT is reasonably long. Normal tokens aren't.
  assertTrue(authorization[0], authorization[0].length() > 300);
}
 
Example #20
Source File: PubSubManager.java    From smallrye-reactive-messaging with Apache License 2.0 6 votes vote down vote up
private static Optional<CredentialsProvider> buildCredentialsProvider(final PubSubConfig config) {
    if (config.isMockPubSubTopics()) {
        return Optional.of(NoCredentialsProvider.create());
    }

    if (config.getCredentialPath() != null) {
        try {
            return Optional.of(FixedCredentialsProvider
                    .create(ServiceAccountCredentials.fromStream(Files.newInputStream(config.getCredentialPath()))));
        } catch (final IOException e) {
            throw new IllegalStateException(e);
        }
    }

    return Optional.empty();
}
 
Example #21
Source File: AbstractInteropTest.java    From grpc-java with Apache License 2.0 6 votes vote down vote up
/** Test JWT-based auth. */
public void jwtTokenCreds(InputStream serviceAccountJson) throws Exception {
  final SimpleRequest request = SimpleRequest.newBuilder()
      .setResponseSize(314159)
      .setPayload(Payload.newBuilder()
          .setBody(ByteString.copyFrom(new byte[271828])))
      .setFillUsername(true)
      .build();

  ServiceAccountCredentials credentials = (ServiceAccountCredentials)
      GoogleCredentials.fromStream(serviceAccountJson);
  TestServiceGrpc.TestServiceBlockingStub stub = blockingStub
      .withCallCredentials(MoreCallCredentials.from(credentials));
  SimpleResponse response = stub.unaryCall(request);
  assertEquals(credentials.getClientEmail(), response.getUsername());
  assertEquals(314159, response.getPayload().getBody().size());
}
 
Example #22
Source File: DeploymentFailsForFirestoreNativeIT.java    From nexus-blobstore-google-cloud with Eclipse Public License 1.0 6 votes vote down vote up
@After
public void destroyBucket() throws IOException {
  Storage storage = StorageOptions.newBuilder()
      .setCredentials(ServiceAccountCredentials.fromStream(new FileInputStream(firestoreNativeConfiguration)))
      .build().getService();
  log.debug("Deleting files from " + bucketName);
  // must delete all the files within the bucket before we can delete the bucket
  Iterator<Blob> list = storage.list(bucketName,
      Storage.BlobListOption.prefix("")).iterateAll()
      .iterator();
  list.forEachRemaining(blob -> blob.delete());

  storage.delete(bucketName);

  log.info(bucketName + "bucket deleted");
}
 
Example #23
Source File: GoogleAuthLibraryCallCredentialsTest.java    From grpc-nebula-java with Apache License 2.0 6 votes vote down vote up
@Test
public void serviceAccountWithScopeNotToJwt() throws Exception {
  final AccessToken token = new AccessToken("allyourbase", new Date(Long.MAX_VALUE));
  KeyPair pair = KeyPairGenerator.getInstance("RSA").generateKeyPair();
  @SuppressWarnings("deprecation")
  ServiceAccountCredentials credentials = new ServiceAccountCredentials(
      null, "[email protected]", pair.getPrivate(), null, Arrays.asList("somescope")) {
    @Override
    public AccessToken refreshAccessToken() {
      return token;
    }
  };

  GoogleAuthLibraryCallCredentials callCredentials =
      new GoogleAuthLibraryCallCredentials(credentials);
  callCredentials.applyRequestMetadata(new RequestInfoImpl(), 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 #24
Source File: GCPCredentialsServiceTest.java    From nifi with Apache License 2.0 6 votes vote down vote up
@Test
public void testFileCredentials() throws Exception {
    final TestRunner runner = TestRunners.newTestRunner(MockCredentialsServiceProcessor.class);
    final GCPCredentialsControllerService serviceImpl = new GCPCredentialsControllerService();
    runner.addControllerService("gcpCredentialsProvider", serviceImpl);

    runner.setProperty(serviceImpl, SERVICE_ACCOUNT_JSON_FILE,
            "src/test/resources/mock-gcp-service-account.json");
    runner.enableControllerService(serviceImpl);

    runner.assertValid(serviceImpl);

    final GCPCredentialsService service = (GCPCredentialsService) runner.getProcessContext()
            .getControllerServiceLookup().getControllerService("gcpCredentialsProvider");

    assertNotNull(service);
    final GoogleCredentials credentials = service.getGoogleCredentials();
    assertNotNull(credentials);

    assertEquals("Credentials class should be equal", ServiceAccountCredentials.class,
            credentials.getClass());
}
 
Example #25
Source File: CredentialsFactoryTest.java    From nifi with Apache License 2.0 6 votes vote down vote up
@Test
public void testJsonStringCredentials() throws Exception {
    final String jsonRead = new String(
            Files.readAllBytes(Paths.get("src/test/resources/mock-gcp-service-account.json"))
    );
    final TestRunner runner = TestRunners.newTestRunner(MockCredentialsFactoryProcessor.class);
    runner.setProperty(CredentialPropertyDescriptors.SERVICE_ACCOUNT_JSON,
            jsonRead);
    runner.assertValid();

    Map<PropertyDescriptor, String> properties = runner.getProcessContext().getProperties();
    final CredentialsFactory factory = new CredentialsFactory();
    final GoogleCredentials credentials = factory.getGoogleCredentials(properties, TRANSPORT_FACTORY);

    assertNotNull(credentials);
    assertEquals("credentials class should be equal", ServiceAccountCredentials.class,
            credentials.getClass());
}
 
Example #26
Source File: IamAuthorizer.java    From curiostack with MIT License 5 votes vote down vote up
@Inject
public IamAuthorizer(IamPermissionChecker checker, Credentials serverCredentials) {
  checkArgument(
      serverCredentials instanceof ServiceAccountCredentials,
      "IAM authentication only works with service account credentials.");
  this.checker = checker;
  ServiceAccountCredentials creds = (ServiceAccountCredentials) serverCredentials;
  serviceAccount =
      MoreObjects.firstNonNull(creds.getServiceAccountUser(), creds.getClientEmail());
}
 
Example #27
Source File: GoogleIdTokenAuth.java    From styx with Apache License 2.0 5 votes vote down vote up
private String getServiceAccountToken(ServiceAccountCredentials credential, String targetAudience)
    throws IOException, GeneralSecurityException {
  log.debug("Fetching service account id token for {}", credential.getAccount());
  final TokenRequest request = new TokenRequest(
      this.httpTransport, JSON_FACTORY,
      new GenericUrl(credential.getTokenServerUri()),
      "urn:ietf:params:oauth:grant-type:jwt-bearer");
  final Header header = jwtHeader();
  final Payload payload = jwtPayload(
      targetAudience, credential.getAccount(), credential.getTokenServerUri().toString());
  request.put("assertion", JsonWebSignature.signUsingRsaSha256(
      credential.getPrivateKey(), JSON_FACTORY, header, payload));
  final TokenResponse response = request.execute();
  return (String) response.get("id_token");
}
 
Example #28
Source File: ServiceAccountsTest.java    From styx with Apache License 2.0 5 votes vote down vote up
@Test
public void serviceAccountEmailServiceAccountCredentials() {
  var credentials = ServiceAccountCredentials.newBuilder()
      .setClientEmail(SERVICE_ACCOUNT)
      .setPrivateKey(privateKey)
      .build();
  assertThat(ServiceAccounts.serviceAccountEmail(credentials), is(SERVICE_ACCOUNT));
}
 
Example #29
Source File: ServiceAccountUsageAuthorizerTest.java    From styx with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() throws IOException {
  MockitoAnnotations.initMocks(this);
  projectBinding.setRole(SERVICE_ACCOUNT_USER_ROLE);
  projectBinding.setMembers(new ArrayList<>());
  projectBinding.getMembers().add("user:[email protected]");
  projectBinding.getMembers().add("group:" + PROJECT_ADMINS_GROUP_EMAIL);
  final com.google.api.services.cloudresourcemanager.model.Policy projectPolicy =
      new com.google.api.services.cloudresourcemanager.model.Policy();
  projectPolicy.setBindings(new ArrayList<>());
  projectPolicy.getBindings().add(projectBinding);
  saBinding.setRole(SERVICE_ACCOUNT_USER_ROLE);
  saBinding.setMembers(new ArrayList<>());
  saBinding.getMembers().add("user:[email protected]");
  saBinding.getMembers().add("group:" + SERVICE_ACCOUNT_ADMINS_GROUP_EMAIL);
  final com.google.api.services.iam.v1.model.Policy saPolicy =
      new com.google.api.services.iam.v1.model.Policy();
  saPolicy.setBindings(new ArrayList<>());
  saPolicy.getBindings().add(saBinding);
  when(authorizationPolicy.shouldEnforceAuthorization(any(), any(), any())).thenReturn(true);
  when(idToken.getPayload()).thenReturn(idTokenPayload);
  when(idTokenPayload.getEmail()).thenReturn(PRINCIPAL_EMAIL);
  when((Object) getIamPolicy.execute()).thenReturn(projectPolicy);
  when((Object) crm.projects().getIamPolicy(any(), eq(GET_IAM_POLICY_REQUEST))).thenReturn(getIamPolicy);
  when((Object) iam.projects().serviceAccounts().getIamPolicy(any()).execute()).thenReturn(saPolicy);
  doReturn(members).when(directory).members();
  doReturn(isNotMember).when(members).hasMember(any(), any());
  doReturn(new MembersHasMember().setIsMember(true)).when(isMember).execute();
  doReturn(new MembersHasMember().setIsMember(false)).when(isNotMember).execute();
  when((Object) iam.projects().serviceAccounts().get(any()).execute())
      .thenReturn(new ServiceAccount()
          .setEmail(MANAGED_SERVICE_ACCOUNT)
          .setProjectId(SERVICE_ACCOUNT_PROJECT));
  credential = ServiceAccountCredentials.newBuilder()
      .setPrivateKey(privateKey)
      .setClientEmail("[email protected]")
      .build();
  sut = new ServiceAccountUsageAuthorizer.Impl(iam, crm, directory, SERVICE_ACCOUNT_USER_ROLE, authorizationPolicy,
      WaitStrategies.noWait(), StopStrategies.stopAfterAttempt(RETRY_ATTEMPTS), MESSAGE, ADMINISTRATORS, BLACKLIST);
}
 
Example #30
Source File: GoogleJwtClient.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
/**
 * Generates a signed JSON Web Token using a Google API Service Account
 * utilizes com.auth0.jwt.
 */
public static String generateJwt(final String saKeyfile, final String saEmail,
    final String audience, final int expiryLength)
    throws FileNotFoundException, IOException {

  Date now = new Date();
  Date expTime = new Date(System.currentTimeMillis() + TimeUnit.SECONDS.toMillis(expiryLength));

  // Build the JWT payload
  JWTCreator.Builder token = JWT.create()
      .withIssuedAt(now)
      // Expires after 'expiraryLength' seconds
      .withExpiresAt(expTime)
      // Must match 'issuer' in the security configuration in your
      // swagger spec (e.g. service account email)
      .withIssuer(saEmail)
      // Must be either your Endpoints service name, or match the value
      // specified as the 'x-google-audience' in the OpenAPI document
      .withAudience(audience)
      // Subject and email should match the service account's email
      .withSubject(saEmail)
      .withClaim("email", saEmail);

  // Sign the JWT with a service account
  FileInputStream stream = new FileInputStream(saKeyfile);
  ServiceAccountCredentials cred = ServiceAccountCredentials.fromStream(stream);
  RSAPrivateKey key = (RSAPrivateKey) cred.getPrivateKey();
  Algorithm algorithm = Algorithm.RSA256(null, key);
  return token.sign(algorithm);
}