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

The solution described in "google.auth.getClient options for domain wide delegation #610" doesn't work in Firebase

Open MGCataldo opened this issue 6 years ago • 8 comments

...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(){
        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 17:05 MGCataldo

the link below is to further detail the issue

The author (Ferris Argyle) shows how to realize exactly what I need, stating with the following question:

But what if you want to do the inverse, ie. impersonate a user with a service account? This is a common use case in a service-based architecture: services will perform actions (eg. store a record, retrieve a blob) on behalf of users.

He uses python libs versions of googleapis instead of node.js library as below:

from googleapiclient import discovery
from google.oauth2 import service_account
.... some code
scope = ("https://www.googleapis.com/auth/devstorage.read_write",)
subject = ''.join([user,'@',domain]);
delegated_credentials = service_account.Credentials.from_service_account_file(key_file, scopes=scope, subject=subject)

so it seems to be exactly the same situation as google.auth.getClient options for domain wide delegation #610

MGCataldo avatar May 05 '20 05:05 MGCataldo

@MGCataldo thanks for the bug report 👍 (@schmidt-sebastian any thoughts on who I might bother with this issue).

bcoe avatar May 06 '20 22:05 bcoe

@bcoe I'm deeply exploring the issue and I've add some other infos in the closed thread #610 (maybe should not be closed). Take a look, maybe something could suggest you a different exploration direction.

MGCataldo avatar May 07 '20 06:05 MGCataldo

I am a little lost for what is going on here. What might be happening here is that the Default Application Credentials of the Firebase project are used to talk to Google Drive. If this is running in Google Cloud Functions under a Firebase project, this will be the service account that is associated with that project. This might not work if these service accounts are not shared.

I am, however, guessing that a different credentials object can be used here:

  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});

I would think that we need to provide GoogleAuth with the explicit credentials that should be used for Google Drive on top of providing the subject.

Disclaimer: I have never used these libraries.

schmidt-sebastian avatar May 07 '20 17:05 schmidt-sebastian

@schmidt-sebastian

I would think that we need to provide GoogleAuth with the explicit credentials that should be used for Google Drive on top of providing the subject.

In other words, regarding the "explicit credential " you mention and referring the python code I posted, I would reformulate the issue: why using googleapis I cannot use a specific G-Suite user to acts as service account in firebase cloud functions?

MGCataldo avatar May 07 '20 21:05 MGCataldo

I don't know with certainty, but I would suspect that you have to add your service account manually to your function and not rely on Application Default Credentials. You should be able to pass them to any Google Cloud SDK as follows:

const credentialsJson  = {} // The Service Account
const service = new AmazingGoogleService({ credentials: credentialsJson, projectId: 'my-test-project' });

schmidt-sebastian avatar May 07 '20 21:05 schmidt-sebastian

@schmidt-sebastian IT WORKS, thank you! Only one thing, the property for the project id isn't project_id, it's projectId.

I explored this way without success, take a look to my post at google.auth.getClient options for domain wide delegation #610. Furthermore, I tried without success to give the Service Account auth json object to the GoogleAuth constructor as follows:

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

Now the following code works:

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 auth = new google.auth.GoogleAuth({
        credentials: myJson,
        projectId: 'YOUR_PROJECT_ID',
        scopes: [
            "https://www.googleapis.com/auth/drive"
        ],
        clientOptions: { subject: '[email protected]' }
    });
    const client = await auth.getClient();
    
    const drive = google.drive({version: 'v3',auth});

    let myFile;
    var fileMetadata = {
        'name': 'JustCreatedFolderTest',
        'mimeType': 'application/vnd.google-apps.folder'
        };
    
    try {
        let file = await drive.files.create({
                resource: fileMetadata,
                fields: 'id',
                parents:['1fvBxKSQaeGXejdJHfhoUbPrOJO7w2nOU']})
        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 06:05 MGCataldo

Updated my sample to use projectId. Glad it worked out!

schmidt-sebastian avatar May 08 '20 16:05 schmidt-sebastian