vctlzac
vctlzac

Reputation: 847

Call cloud function through another in the same project without allUsers permission

I have 2 functions in the same google cloud functions project (myfunction1 and myfunction2.

exports.myfunction1 = async (req, res) => {

 await axios({
                    method: 'post',
                        url: 'https://SERVER-PROJECT-ID.cloudfunctions.net/myfunction2',
                        timeout: 15000,
                        headers: {
                                    'Content-Type': 'application/json',
                                },
                                data: myjson
                        }).then(response => {
                           console.log(JSON.stringify(response.data));
                        }).catch(err => {
                            console.error("catch error");
                            console.error(err);
                     })
            }

It is works fine, but only if I configure invokers permission for allUsers. If I remove this permission, e receive 403 code error. Not sounds good keep this permisson activate, because the function is exposed. I tried solve with this link and this link, but, no sucess.

Edit1:

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

const targetAudience = 'https://SERVER-PROJECT-ID.cloudfunctions.net/myfunction2'

const url = '??????????';

async function request() {
  console.info('request ${url} with target audience ${targetAudience}');
  const client = await auth.getIdTokenClient(targetAudience);
  const res = await client.request({url});
  console.info(res.data);
}

I'm trying using this code, but, who is const url?

Upvotes: 1

Views: 2038

Answers (2)

vctlzac
vctlzac

Reputation: 847

let audience = 'https://SERVER-PROJECT-ID.cloudfunctions.net/myfunction2';
let token_request_url = 'http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/default/identity?audience=' + audience;

var token_response = await axios.get(token_request_url, { headers: {'Metadata-Flavor': 'Google'} });

let token_auth = token_response.data;

axios({
      method: 'post',
      url: audience,
        timeout: 15000,
          headers: {
                'Authorization': "Bearer " + token_auth
              },
                data: myJSON
    }).catch(err => {
        console.error(err);
});

Upvotes: 0

guillaume blaquiere
guillaume blaquiere

Reputation: 75940

You must perform service to service authentication. You can find a great tutorial in the Cloud Run page (ok you use Cloud Functions but the underlying infrastructure is the same and the doc is better).

You also have to be aware about the Functions identity and how to change them (or to grant the current service account the correct permission)

Upvotes: 1

Related Questions