google-auth-library-nodejs icon indicating copy to clipboard operation
google-auth-library-nodejs copied to clipboard

google.auth.getClient options for domain wide delegation

Open D34THWINGS opened this issue 7 years ago • 17 comments

Hi,

When using the method google.auth.getClient method, there's no way of specifying a user to impersonate when using a service account. The only way to do it is to use the google.auth.JWT constructor and that bypasses the internal credentials caching which is sad. I would suggest to add an additional param in getClient options to pass to fromJSON second argument (in googleauth.js).

Thanks

D34THWINGS avatar Jan 30 '19 16:01 D34THWINGS

So - I think this should actually work :) You should be able to do something like this:

const client = await auth.getClient({
  credentials: {
    type?: string;
    client_email?: string;
    private_key?: string;
    private_key_id?: string;
    project_id?: string;
    client_id?: string;
    client_secret?: string;
    refresh_token?: string;
  }
);

Can you give that a try?

JustinBeckwith avatar Jan 30 '19 17:01 JustinBeckwith

Nope the thing that is missing is subject it is not assigned to JWT when calling JWT.fromJSON() (which is called internally by getClient)

D34THWINGS avatar Jan 30 '19 19:01 D34THWINGS

Rats. You think this will cover it? https://github.com/googleapis/google-auth-library-nodejs/pull/611

JustinBeckwith avatar Jan 31 '19 00:01 JustinBeckwith

Yeah definitely! Thanks for the quick reply!

D34THWINGS avatar Jan 31 '19 00:01 D34THWINGS

@JustinBeckwith

So - I think this should actually work :) You should be able to do something like this:

const client = await auth.getClient({
  credentials: {
    type?: string;
    client_email?: string;
    private_key?: string;
    private_key_id?: string;
    project_id?: string;
    client_id?: string;
    client_secret?: string;
    refresh_token?: string;
  }
);

Can you give that a try?

I'm not sure it's working in my end. Is this still the updated way to use this? I can't see it in the documentation.

I'm using a google cloud function to create calendar entries.

Here's how my implementation looks like:

const credentials = require('./service-credentials.json');
exports = module.exports = functions.firestore
  .document('reservations/{reservationId}')
  .onCreate(async (snapshot, context) => {
    const auth = await google.auth.getClient({
      credentials,
    });
    const event = await snapshot.data();

    return await addEvent(event, auth);
});

function addEvent(event, auth) {
return new Promise((resolve, reject) => {
    calendar.events.insert(
      {
        auth,
        calendarId: event.email,
        resource: event.resource,
      },
      (err, res) => {
        if (err) {
          console.info('Rejecting because of error', err);
          reject(err);
        } else {
          console.info('Request successful', res.data);
          resolve(res.data);
        }
      }
    );
  });
}

I'm getting below error:

Error adding event:  { Error: Invalid Credentials
    at Gaxios.request (/srv/node_modules/googleapis/node_modules/gaxios/build/src/gaxios.js:70:23)
    at <anonymous>
    at process._tickDomainCallback (internal/process/next_tick.js:229:7)
  response: 
   { config: 
      { url: 'https://www.googleapis.com/calendar/v3/calendars/jojo%40vananaz.com/events',
        method: 'POST',
        paramsSerializer: [Function],
        data: [Object],
        headers: [Object],
        params: {},
        validateStatus: [Function],
        retry: true,
        body: '{"summary":"Charging reservation ","description":"Reservation scheduled at [object Object] - [object Object] ","start":{"dateTime":"2019-07-24T22:00:00.000Z"},"end":{"dateTime":"2019-07-24T23:00:00.000Z"}}',
        responseType: 'json',
        retryConfig: [Object] },
     data: { error: [Object] },
     headers: 
      { 'alt-svc': 'quic=":443"; ma=2592000; v="46,43,39"',
        'cache-control': 'private, max-age=0',
        connection: 'close',
        'content-encoding': 'gzip',
        'content-type': 'application/json; charset=UTF-8',
        date: 'Fri, 19 Jul 2019 09:06:39 GMT',
        expires: 'Fri, 19 Jul 2019 09:06:39 GMT',
        server: 'GSE',
        'transfer-encoding': 'chunked',
        vary: 'Origin, X-Origin',
        'www-authenticate': 'Bearer realm="https://accounts.google.com/", error=invalid_token',
        'x-content-type-options': 'nosniff',
        'x-frame-options': 'SAMEORIGIN',
        'x-xss-protection': '1; mode=block' },
     status: 401,
     statusText: 'Unauthorized' },
  config: 
   { url: 'https://www.googleapis.com/calendar/v3/calendars/jojo%40vananaz.com/events',
     method: 'POST',
     paramsSerializer: [Function],
     data: 
      { summary: 'Charging reservation ',
        description: 'Reservation scheduled at [object Object] - [object Object] ',
        start: [Object],
        end: [Object] },
     headers: 
      { 'Accept-Encoding': 'gzip',
        'User-Agent': 'google-api-nodejs-client/2.0.4 (gzip)',
        Authorization: 'Bearer eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCIsImtpZCI6IjI2ODc2Mjc4OWIyNzYyMjU2OWU3OGYwMjlhZGNhNGQ4NDUxOWUzYTkifQ.eyJpc3MiOiJ5b3VyLXN0YW5kLWF1dGgtc2VydmljZUB5b3Vyc3RhbmQtYXBwcy5pYW0uZ3NlcnZpY2VhY2NvdW50LmNvbSIsInN1YiI6InlvdXItc3RhbmQtYXV0aC1zZXJ2aWNlQHlvdXJzdGFuZC1hcHBzLmlhbS5nc2VydmljZWFjY291bnQuY29tIiwiYXVkIjoiaHR0cHM6Ly93d3cuZ29vZ2xlYXBpcy5jb20vY2FsZW5kYXIvdjMvY2FsZW5kYXJzL2pvam8lNDB2YW5hbmF6LmNvbS9ldmVudHMiLCJleHAiOjE1NjM1MzA3OTgsImlhdCI6MTU2MzUyNzE5OH0.eVLyJtmA3J7cMeYpwUV5S0-T9n2Zqd8CgzQpeP5q-JLtk9uuCMIesLQFE-CGSPdqgialwFgkP3dGgL8ogwFewyVzOJlhbpcUQNIfhcJ8KTcugEJc1YcwhFa6KZ7c-CrKx6hq53lT024UlCI7h0BNWR9k8RzsMnkfqJSTFLrM68aqmORJgVRIfdOCQgQn0PqH0pum0jAIAhfidIARCLsxeSST1wn-vm8tSzEESv7cDSyhFw-gG7sA1uZOchKNnRiH8P-V4-V3XL7MuaPLhVtiNxS0l4REptvRxRufNQqwbJ03sfyJZTyM9ElCzSxvXCL9wD7NfnBCsRHnF_EdRaRbgw',
        'Content-Type': 'application/json',
        Accept: 'application/json' },
     params: {},
     validateStatus: [Function],
     retry: true,
     body: '{"summary":"Charging reservation ","description":"Reservation scheduled at [object Object] - [object Object] ","start":{"dateTime":"2019-07-24T22:00:00.000Z"},"end":{"dateTime":"2019-07-24T23:00:00.000Z"}}',
     responseType: 'json',
     retryConfig: 
      { currentRetryAttempt: 0,
        retry: 3,
        retryDelay: 100,
        httpMethodsToRetry: [Array],
        noResponseRetries: 2,
        statusCodesToRetry: [Array] } },
  code: 401,
  errors: 
   [ { domain: 'global',
       reason: 'authError',
       message: 'Invalid Credentials',
       locationType: 'header',

jojonarte avatar Jul 19 '19 09:07 jojonarte

Hello, this worked perfectly for me!!! Thank you, especially the tests in the PR were really useful for understanding the implementation.

const Auth = new google.auth.GoogleAuth({
	scopes: [
		'https://www.googleapis.com/auth/gmail.settings.basic',
		'https://www.googleapis.com/auth/gmail.settings.sharing',
		'https://www.googleapis.com/auth/admin.directory.user',
	],
	clientOptions: { subject: '[email protected]' },
});

const auth = await Auth.getClient();

auth.subject === '[email protected]' // true

And now my admin API requests work. Thank you!!!!!!!

p.s. wish this was documented better somewhere. This helped me impersonate an admin on my service account on Nodejs.

(that last bit was for Google searchers).

nabilfreeman avatar Sep 04 '19 20:09 nabilfreeman

It doesn't work for me and I cannot understand why. I'm trying to build a multiuser app that will use cloud functions to work with google drive, I need a single specific user, a kind of "administrator" as owner of the files and folder created. I'm testing the idea and running the cloud function hosted by Firebase, successfully deployed the following code

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

exports = module.exports = functions.https.onCall(async (data,context) =>{
                           
    const auth = new GoogleAuth({
        scopes: [
            "https://www.googleapis.com/auth/drive"
        ],
        clientOptions: { subject: '[email protected]' }
    });
    const client = await auth.getClient();
    const drive = google.drive({version: 'v3',client});
    let myFile;
    var fileMetadata = {
        'name': 'JustCreateFolderTest',
        'mimeType': 'application/vnd.google-apps.folder'
      };
    await drive.files.create({
        resource: fileMetadata,
        fields: 'id'
        })
        .then(file=> {
            console.log('Folder Id: ', file.id);
            myFile=file
        })
        .catch(err=>console.error(err));
    return 'Folder Id: ', myFile.id
});

run the function from inside a Vuejs app as follows

      impersonateSGT(){
        console.log('Chiamata a impersonateSGT')
        let driveCreateFolderAsSGT = firebase.functions().httpsCallable('driveCreateFolderAsSGT2')
        driveCreateFolderAsSGT()
          .then(result =>{
              console.log(result)
          })
          .catch( err => {
              console.log(err.message)
          })
      }, 

and the cloud function logs report the following error

{ Error: Login Required at Gaxios._request (/srv/node_modules/googleapis-common/node_modules/gaxios/build/src/gaxios.js:85:23) at at process._tickDomainCallback (internal/process/next_tick.js:229:7) response: { config: { client: [Object], url: 'https://www.googleapis.com/drive/v3/files?fields=id', method: 'POST', paramsSerializer: [Function], data: [Object], headers: [Object], params: [Object], validateStatus: [Function], retry: true, body: '{"name":"JustCreateFolderTest","mimeType":"application/vnd.google-apps.folder"}', responseType: 'json', retryConfig: [Object] }, data: { error: [Object] }, headers: { 'alt-svc': 'h3-Q050=":443"; ma=2592000,h3-Q049=":443"; ma=2592000,h3-Q048=":443"; ma=2592000,h3-Q046=":443"; ma=2592000,h3-Q043=":443"; ma=2592000,quic=":443"; ma=2592000; v="46,43"', 'cache-control': 'private, max-age=0', connection: 'close', 'content-encoding': 'gzip', 'content-security-policy': 'frame-ancestors 'self'', 'content-type': 'application/json; charset=UTF-8', date: 'Mon, 04 May 2020 16:41:54 GMT', expires: 'Mon, 04 May 2020 16:41:54 GMT', server: 'GSE', 'transfer-encoding': 'chunked', vary: 'Origin, X-Origin', 'www-authenticate': 'Bearer realm="https://accounts.google.com/"', 'x-content-type-options': 'nosniff', 'x-frame-options': 'SAMEORIGIN', 'x-xss-protection': '1; mode=block' }, status: 401, statusText: 'Unauthorized', request: { responseURL: 'https://www.googleapis.com/drive/v3/files?fields=id' } }, config: { client: Compute { domain: [Object], _events: {}, _eventsCount: 0, _maxListeners: undefined, transporter: DefaultTransporter {}, credentials: [Object], certificateCache: {}, certificateExpiry: null, certificateCacheFormat: 'PEM', refreshTokenPromises: Map {}, _clientId: undefined, _clientSecret: undefined, redirectUri: undefined, eagerRefreshThresholdMillis: 300000, forceRefreshOnFailure: false, serviceAccountEmail: 'default', scopes: [Array] }, url: 'https://www.googleapis.com/drive/v3/files?fields=id', method: 'POST', paramsSerializer: [Function], data: { name: 'JustCreateFolderTest', mimeType: 'application/vnd.google-apps.folder' }, headers: { 'x-goog-api-client': 'gdcl/4.1.0 gl-node/8.16.0 auth/6.0.0', 'Accept-Encoding': 'gzip', 'User-Agent': 'google-api-nodejs-client/4.1.0 (gzip)', 'Content-Type': 'application/json', Accept: 'application/json' }, params: { fields: 'id' }, validateStatus: [Function], retry: true, body: '{"name":"JustCreateFolderTest","mimeType":"application/vnd.google-apps.folder"}', responseType: 'json', retryConfig: { currentRetryAttempt: 0, retry: 3, httpMethodsToRetry: [Array], noResponseRetries: 2, statusCodesToRetry: [Array] } }, code: 401, errors: [ { domain: 'global', reason: 'required', message: 'Login Required', locationType: 'header', location: 'Authorization' } ] }

...any idea

MGCataldo avatar May 04 '20 16:05 MGCataldo

@MGCataldo could I trouble you to open a new issue? Thanks!

JustinBeckwith avatar May 04 '20 16:05 JustinBeckwith

@JustinBeckwith I'm shocked for the very very fast response, Thank you!!! I've open a new issue as requested.

Closed issue "google.auth.getClient options for domain wide delegation #610" doesn't work for me #955

I hope to clarify my mind there. Thank you once more!

MGCataldo avatar May 04 '20 17:05 MGCataldo

@nabilfreeman This is a closed issue but I'm going to ask some details to explore why the solution works for you and not for me. Please nabilfreeman, can you place here the libs you used and some details on the environment? Thank you!

MGCataldo avatar May 05 '20 12:05 MGCataldo

Hi @MGCataldo, it's been a while since we worked on this but I'll try and share what I remember...

That auth error you are getting suggests that Google is rejecting your request due to invalid credentials rather than not being able to find the user.

  • Make sure GOOGLE_APPLICATION_CREDENTIALS=./auth.json is set in environment and the json file contains your service account credentials (can't show mine here due to security)
  • In Google Cloud console under IAM make sure your service account has domain-wide delegation enabled Screenshot 2020-05-05 at 13 25 24

p.s. here I'm assuming you are authenticating via service account, using G Suite and the person you are trying to impersonate is a member of that G Suite organization.

If any of those are different I won't be able to help any more.

Good luck!

nabilfreeman avatar May 05 '20 12:05 nabilfreeman

@nabilfreeman thank you very much for the answer!

I can confirm your assumptions are valid. Unfortunately I'm still getting some errors even if I can confirm that:

domain-wide delegation is active image

The person I'm trying to impersonate is a G-suite member

From the G-Suite admin console I've enabled the delegation as explained here: Delegating domain-wide authority to the service account

I've download the Service account auth.json file from console.cloud.google.com -- Service account as follows image and I've put the file in my Vuejs project under the folder "functions"

I've created the environment variable GOOGLE_APPLICATION_CREDENTIALS and set it:

  • from my pc using powershell command $env:GOOGLE_APPLICATION_CREDENTIALS="./auth.json"
  • and also from the cloud functions editor image

the logs are image

I really cannot realize what is going wrong...

MGCataldo avatar May 05 '20 13:05 MGCataldo

@MGCataldo

Ok, that's a shame it's not working for you! I haven't used Google Cloud Functions but I'm hoping they are fairly similar to Lambda which is where we actually implemented this.

Try removing the quote marks from the value in the environment text field. I've run into this before, even though it's copy pasted from here: https://cloud.google.com/docs/authentication/getting-started#linux-or-macos

It can still be parsed incorrectly when loaded as an environment file. https://stackoverflow.com/a/48411223/1395078

Hopefully that's it.

p.s. What happens when you run on your PC? Does it work?

nabilfreeman avatar May 05 '20 21:05 nabilfreeman

Try removing the quote marks from the value in the environment text field.

Not working, it is like in firebase cloud function environment the library "google-auth-library" cannot find/use the environment variable GOOGLE_APPLICATION_CREDENTIALS

I've also tried to build the envirnoment variable in index.js as follows:

  • first I've created a variable for firebase cloud function: using firebase CLI:
    firebase functions:config:set auth.json_file_name="auth.json"
  • then in index.js I've built the GOOGLE_APPLICATION_CREDENTIALS environment variable like so: process.env.GOOGLE_APPLICATION_CREDENTIALS=process.cwd()+'/'+functions.config().auth.json_file_name;
  • proved in a different module that the needed variables are available: console.log( process.env.GOOGLE_APPLICATION_CREDENTIALS+ " "+ process.env.GCLOUD_PROJECT);
  • proved that json file containing credential can be read like so:
const myJson = require(process.cwd()+'/'+functions.config().auth.json_file_name); 
console.log(myJson) // ... shows the content!
  • tested the function: it didn't work

Error: Login Required at Gaxios._request (/srv/node_modules/googleapis-common/node_modules/gaxios/build/src/gaxios.js:85:23)

  • It didn't work also after that I've tried to directly read the auth.json file and push the object into getClient method like so:
...
const myJson = require(process.cwd()+'/'+functions.config().auth.json_file_name);
exports = module.exports = functions.https.onCall(async (data,context) =>{
    const auth = new GoogleAuth({
        scopes: [
            "https://www.googleapis.com/auth/drive"
        ],
        clientOptions: { subject: '[email protected]' }
    });
    const client = await auth.getClient({credentials:myJson});
...

no way, it's a nightmare... I've asked for support to firebase support team.

@nabilfreeman I thank you very much for having tried to help!

MGCataldo avatar May 06 '20 08:05 MGCataldo

I've taken a look to the source code of the "google-auth-library" and referring my previous post I've to add that I've also tried to pass credentials object directly to the GoogleAuth object creation, plus many other possible combination as possible work around... any of them worked.

The example I've build is for a folder creation on Google Drive, the folder must have a specific user as the folder owner, not the service account. For a further exploration and possible work around I slightly modified the script to let the service account create the folder and immediately after transfer the folder property to the target user as follows:

const {google} = require('googleapis');
const functions = require('firebase-functions');

exports = module.exports = functions.https.onCall(async (data,context) =>{
   
    const auth = await google.auth.getClient({
        scopes: [
         "https://www.googleapis.com/auth/drive",
        ]
     });
     
    const drive = google.drive({version: 'v3',auth});

    let myFile;
    var fileMetadata = {
        'name': 'JustCreatedFolderTest',
        'mimeType': 'application/vnd.google-apps.folder'
        };

    await drive.files.create({
        resource: fileMetadata,
        fields: 'id',
        parents:["1fvBxKSQaeGXejdJHfhoUbPrOJO7w2nOU"]
        })
        .then(file=> {
            let fileId = file.data.id
 
            return drive.permissions.create({
                "fileId": fileId,
                "transferOwnership": true,
                "resource": {
                  "role": "owner",
                  "type": "user",
                  "emailAddress": "[email protected]"
                }
            })    
        })
        .then(res=>{
            return "Cartella create, risposta: "+res;
        })
        .catch(err=>{console.error("errore nella creazione ",err);
            return 'Failed, error: '+err.message});
});

The folder has been correctly created but the problem here is that the Google policies disallow files/folder property transfer across different domains.

..rubrik created a simpler cube to solve... :)

MGCataldo avatar May 07 '20 06:05 MGCataldo

OK, now I'm sure the issue #610 is to be closed as resolved.

Below the working code for anyone who need to let a Service Account impersonate an arbitrary G-Suite user to accomplish whatever function on google cloud platform. The example is for a google drive folder creation, other goal can be achieved using the related scope (i.e. gmail, calendar, storage or whatever). The code runs on node >= 8 that is the presently supported LTS conf for Firebase Cloud Functions

const {google} = require('googleapis');
const functions = require('firebase-functions');
const myJson = require(process.cwd()+'/'+functions.config().auth.json_file_name);

exports = module.exports = functions.https.onCall(async (data,context) =>{
    
    const parentFolder = data.parentFolder;
    const folderName = data.folderName;
    const folderOwner =  data.folderOwner;

    const envParms = JSON.parse(process.env.FIREBASE_CONFIG);

    const auth = new google.auth.GoogleAuth({
        credentials: myJson,
        projectId: envParms.projectId,
        scopes: [
            "https://www.googleapis.com/auth/drive"
        ],
        clientOptions: { subject: folderOwner }
    });
    const client = await auth.getClient();
    
    const drive = google.drive({version: 'v3',auth});

    let myFile;
    var fileMetadata = {
        'name': folderName,
        'mimeType': 'application/vnd.google-apps.folder',
        'parents':[parentFolder]
        };
    
    try {
        let file = await drive.files.create({resource: fileMetadata,
                                             fields: 'id'})
        let fileId = file.data.id
        return 'Folder created, id: '+(fileId);
    }   
    catch(err){
        console.error("error during folder creation: ",err);
        return 'Failed, error: '+err.message};
});

MGCataldo avatar May 08 '20 12:05 MGCataldo

@MGCataldo thanks for that code sample, I think this is exactly what I need for a project I'm working on. Looking at the code though, you create a client constant which doesn't seem to be used anywhere in the sample. Can you explain what its purpose is?

Should the code be this: const drive = google.drive({version: 'v3', auth: client});?

PS: I tried the code yesterday with that change in there and it worked great for me. Thank you so much for providing it.

johnwargo avatar Mar 05 '21 12:03 johnwargo