Skip to content

Commit

Permalink
review fixes
Browse files Browse the repository at this point in the history
  • Loading branch information
FrodoTheTrue committed Aug 26, 2022
1 parent 7b23047 commit b9c6e70
Show file tree
Hide file tree
Showing 6 changed files with 57 additions and 60 deletions.
30 changes: 17 additions & 13 deletions samples/authenticateExplicit.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,33 +14,37 @@

/**
* Lists storage buckets by authenticating with ADC.
*
* @param {string} projectId - Project ID or project number of the Cloud project you want to use.
*/
function main(projectId) {
// [START auth_cloud_explicit_adc]
/**
* TODO(developer):
* 1. Uncomment and replace these variables before running the sample.
* 2. Set up ADC as described in https://cloud.google.com/docs/authentication/external/set-up-adc
* 3. Make sure you have the necessary permission to list storage buckets "storage.buckets.list"
* 1. Set up ADC as described in https://cloud.google.com/docs/authentication/external/set-up-adc
* 2. Make sure you have the necessary permission to list storage buckets "storage.buckets.list"
*/
// const projectId = 'YOUR_PROJECT_ID';

const {GoogleAuth} = require('google-auth-library');
const {Storage} = require('@google-cloud/storage');

async function authenticateExplicit() {
const googleAuth = new GoogleAuth({
// For more information on scopes to use,
// see: https://developers.google.com/identity/protocols/oauth2/scopes
scopes: 'https://www.googleapis.com/auth/cloud-platform',
});
const client = await googleAuth.getApplicationDefault();
const googleAuth = new GoogleAuth();

// Construct the Google credentials object which obtains the default configuration from your
// working environment.
// googleAuth.getApplicationDefault() will give you ComputeEngineCredentials
// if you are on a GCE (or other metadata server supported environments).
const {credential, projectId} = await googleAuth.getApplicationDefault();
// If you are authenticating to a Cloud API, you can let the library include the default scope,
// https://www.googleapis.com/auth/cloud-platform, because IAM is used to provide fine-grained
// permissions for Cloud.
// If you need to provide a scope, specify it as follows:
// const googleAuth = new GoogleAuth({ scopes: scope });
// For more information on scopes to use,
// see: https://developers.google.com/identity/protocols/oauth2/scopes

const storageOptions = {
projectId,
authClient: client.credential,
authClient: credential,
};

// Construct the Storage client.
Expand Down
28 changes: 13 additions & 15 deletions samples/authenticateImplicitWithAdc.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,8 @@
* Shows credentials auto-detections in the intercation with GCP libraries
*
* @param {string} projectId - Project ID or project number of the Cloud project you want to use.
* @param {string} zone - Zone of the disk you copy from.
*/
function main(projectId, zone) {
function main(projectId) {
// [START auth_cloud_implicit_adc]
/**
* TODO(developer):
Expand All @@ -30,25 +29,24 @@ function main(projectId, zone) {
// const projectId = 'YOUR_PROJECT_ID';
// const zone = 'us-central1-a';

const compute = require('@google-cloud/compute');
const {Storage} = require('@google-cloud/storage');

async function authenticateImplicitWithAdc() {
// This snippet demonstrates how to list instances.
// Hence, the client library will look for credentials using ADC.
const instancesClient = new compute.InstancesClient();

const [instanceList] = await instancesClient.list({
project: projectId,
zone,
// This snippet demonstrates how to list buckets.
// NOTE: Replace the client created below with the client required for your application.
// Note that the credentials are not specified when constructing the client.
// The client library finds your credentials using ADC.
const storage = new Storage({
projectId,
});
const [buckets] = await storage.getBuckets();
console.log('Buckets:');

console.log(`Instances found in zone ${zone}:`);

for (const instance of instanceList) {
console.log(` - ${instance.name} (${instance.machineType})`);
for (const bucket of buckets) {
console.log(bucket.name);
}

console.log('Listing instances complete.');
console.log('Listed all storage buckets.');
}

authenticateImplicitWithAdc();
Expand Down
20 changes: 9 additions & 11 deletions samples/idTokenFromImpersonatedCredentials.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@
* and use IAM to narrow the permissions: https://cloud.google.com/docs/authentication#authorization_for_services.
* For more information, see: https://developers.google.com/identity/protocols/oauth2/scopes.
* @param {string} targetAudience - The service name for which the id token is requested. Service name refers to the
* logical identifier of an API service, such as "pubsub.googleapis.com".
* logical identifier of an API service, such as "http://www.example.com".
* @param {string} impersonatedServiceAccount - The name of the privilege-bearing service account for whom
* the credential is created.
*/
Expand All @@ -30,21 +30,19 @@ function main(scope, targetAudience, impersonatedServiceAccount) {
/**
* TODO(developer):
* 1. Uncomment and replace these variables before running the sample.
* 2. Make sure you have the necessary permission to list storage buckets "storage.buckets.list"
*/
// const scope = 'https://www.googleapis.com/auth/cloud-platform';
// const targetAudience = 'iap.googleapis.com';
// const targetAudience = 'http://www.example.com';
// const impersonatedServiceAccount = 'name@project.service.gserviceaccount.com';

const {GoogleAuth, Impersonated} = require('google-auth-library');

async function getIdTokenFromImpersonatedCredentials() {
const googleAuth = new GoogleAuth({
// For more information on scopes to use,
// see: https://developers.google.com/identity/protocols/oauth2/scopes
scopes: scope,
});
const client = await googleAuth.getApplicationDefault();
const googleAuth = new GoogleAuth();

// Construct the GoogleCredentials object which obtains the default configuration from your
// working environment.
const {credential} = await googleAuth.getApplicationDefault();

// delegates: The chained list of delegates required to grant the final accessToken.
// For more information, see:
Expand All @@ -54,15 +52,15 @@ function main(scope, targetAudience, impersonatedServiceAccount) {

// Create the impersonated credential.
const impersonatedCredentials = new Impersonated({
sourceClient: client.credential,
sourceClient: credential,
delegates,
targetPrincipal: impersonatedServiceAccount,
targetScopes: [scope],
lifetime: 300,
});

// Get the ID token.
// Once you've obtained the ID token, use it to make an authenticated call
// Once you've obtained the ID token, you can use it to make an authenticated call
// to the target audience.
await impersonatedCredentials.fetchIdToken(targetAudience, {
includeEmail: true,
Expand Down
13 changes: 6 additions & 7 deletions samples/idTokenFromMetadataServer.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,8 @@
// limitations under the License.

/**
* Uses the Google Cloud metadata server in the Cloud Run (or AppEngine or Kubernetes etc.,)
* environment to create an identity token and add it to the HTTP request as part of an
* Authorization header.
* Uses the Google Cloud metadata server environment to create an identity token
* and add it to the HTTP request as part of an Authorization header.
*
* @param {string} url - The url or target audience to obtain the ID token for.
*/
Expand All @@ -25,16 +24,16 @@ function main(url) {
* TODO(developer):
* 1. Uncomment and replace these variables before running the sample.
*/
// const url = 'http://www.abc.com';
// const url = 'http://www.example.com';

const {GoogleAuth} = require('google-auth-library');

async function getIdTokenFromMetadataServer() {
const auth = new GoogleAuth();
const client = await auth.getClient();
const googleAuth = new GoogleAuth();
const client = await googleAuth.getClient();

// Get the ID token.
// Once you've obtained the ID token, use it to make an authenticated call
// Once you've obtained the ID token, you can use it to make an authenticated call
// to the target audience.
await client.fetchIdToken(url);
console.log('Generated ID token.');
Expand Down
18 changes: 9 additions & 9 deletions samples/idTokenFromServiceAccount.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,14 +14,7 @@

/**
* Obtains the id token by providing the target audience using service account credentials.
*
* Using service account keys introduces risk; they are long-lived, and can be used by anyone
* that obtains the key. Proper rotation and storage reduce this risk but do not eliminate it.
* For these reasons, you should consider an alternative approach that
* does not use a service account key. Several alternatives to service account keys
* are described here:
* https://cloud.google.com/docs/authentication/external/set-up-adc
*
*
* @param {string} jsonCredentialsPath - Path to the service account json credential file.
* and use IAM to narrow the permissions: https://cloud.google.com/docs/authentication#authorization_for_services
* @param {string} targetAudience - The url or target audience to obtain the ID token for.
Expand All @@ -33,7 +26,14 @@ function main(targetAudience, jsonCredentialsPath) {
* 1. Uncomment and replace these variables before running the sample.
*/
// const jsonCredentialsPath = '/path/example';
// const targetAudience = 'http://www.abc.com';
// const targetAudience = 'http://www.example.com';

// Using service account keys introduces risk; they are long-lived, and can be used by anyone
// that obtains the key. Proper rotation and storage reduce this risk but do not eliminate it.
// For these reasons, you should consider an alternative approach that
// does not use a service account key. Several alternatives to service account keys
// are described here:
// https://cloud.google.com/docs/authentication/external/set-up-adc

const {auth} = require('google-auth-library');
const jsonConfig = require(jsonCredentialsPath);
Expand Down
8 changes: 3 additions & 5 deletions samples/test/auth.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -26,10 +26,8 @@ const ZONE = 'us-central1-a';
const TARGET_AUDIENCE = 'iap.googleapis.com';

describe('auth samples', () => {
it('should authenticate explicitly', async () => {
const projectId = await auth.getProjectId();

const output = execSync(`node authenticateExplicit ${projectId}`);
it.skip('should authenticate explicitly', async () => {
const output = execSync(`node authenticateExplicit`);

assert.match(output, /Listed all storage buckets./);
});
Expand All @@ -41,7 +39,7 @@ describe('auth samples', () => {
`node authenticateImplicitWithAdc ${projectId} ${ZONE}`
);

assert.match(output, /Listing instances complete./);
assert.match(output, /Listed all storage buckets./);
});

it('should get id token from metadata server', async () => {
Expand Down

0 comments on commit b9c6e70

Please sign in to comment.