Google Calendar API code not authenticating in Cloud Run - javascript

I've written a simple Calendar API call using the official NodeJS client: https://github.com/googleapis/google-api-nodejs-client#service-account-credentials
It works fine on my local machine, using a Service Account set up with Domain-Wide Delegation to create the event and invite a list of attendees on my behalf.
I set the credentials location using GOOGLE_APPLICATION_CREDENTIALS env var on my local machine, but do not set this on the Google Cloud Run service because it's supposedly automatic since I've associated the Service Account. This assumption seems true because I can call GoogleAuth functions and get back the expected service account name.
However, once I try to run it in Cloud Run, it throws the error:
Error: Service accounts cannot invite attendees without Domain-Wide Delegation of Authority.
At first I thought this was an issue with default credentials somehow loading the wrong service account.
I added logging directly before the event is called to see what account it is using:
const auth = new googleClient.auth.GoogleAuth({
clientOptions: {
subject: eventOwner
},
scopes: calendarScopes,
})
const serviceAcctName = (await auth.getCredentials())?.client_email
googleClient.options({
auth: auth
})
logger.info(`${serviceAcctName} acting as ${eventOwner}, using calendar ${calendarId}`)
const calendar = googleClient.calendar('v3')
const response = await calendar.events.insert(event)
The log output is exactly as expected, with the correct service account acting as the correct user on the correct calendar id.
I've double-checked that the account has domain-wide delegation of authority and the proper scopes, and it works fine on my local machine, so the only thing I can think of is something about the library's feature of grabbing default credentials in a Google environment is overwriting my googleClient.options() call. But I'm still confused because GoogleAuth functions still give the expected service account info when it grabs the 'default'.

Related

How to use trello webhook callbackURL pointing to localhost in php codeigniter?

I have created a web-based system in codeigniter and some trello integration using its API services. I wanted to achieve something like if there is a new card created in a particular board it will also send a notification in my system that a new card is created. I started reading some documentation in trello webhooks but I just can't figure it out. Am I heading in the right way? Would it be valid if I provide a callbackURL pointing in localhost callbackURL: "localhost/main_controller/trelloCallback" ? However the code below returns a 400 status. Please help me. Thank you.
Javascript
$.post("https://api.trello.com/1/tokens/5db4c9fbb5b2kaf8420771072b203616f3874fa92a4c57f0c796cf90819fa05c/webhooks?key=a2a93deccc7064dek5f4011c2e9810d6", {
description: "My first webhook",
callbackURL: "localhost/dti_infosys/main_controller/trelloCallback",
idModel: "5a73c33ad9a2dk1b473612eb",
});
main_controller/trelloCallback
function trelloCallback() {
$json = file_get_contents('php://input');
$action = json_decode($json,true);
var_dump($action);
}
I know it's an old question, but this use case of having an external tool access our localhost for development is quite common.
So for anyone (OP included) that would like a cloud based service to be able to call a local endpoint, you can use tools like ngrok.
Basically, it sets up a URL accessible via internet that forwards all calls to one of your local ports.
Let's say that your local webserver running your PHP listens on the port 8000 on your machine.
With ngrok installed, you could execute the following command:
$> ngrok http 8000
That would set up the forwarding session:
ngrok by #inconshreveable
Session Status online
Session Expires 6 hours, 21 minutes
Version 2.3.35
Region United States (us)
Web Interface http://127.0.0.1:4040
Forwarding http://b5d44737.ngrok.io -> http://localhost:8000
Forwarding https://b5d44737.ngrok.io -> http://localhost:8000
You can then use any of the Forwarding addresses pointing to ngrok.io to access your local webserver through internet, meaning that if you were to provide an URL using any of these addresses instead of localhost to an external tool, it would be able to indirectly call your local endpoint.
In your case, your javascript call to create a Trello webhook would be:
$.post("https://api.trello.com/1/tokens/<YOUR_ACCESS_TOKEN>/webhooks?key=<YOUR_API_KEY>", {
description: "My first webhook",
callbackURL: "https://b5d44737.ngrok.io/dti_infosys/main_controller/trelloCallback",
idModel: "<YOUR_MODEL_ID>",
});
A bit of warning though: In the case of ngrok, the Forwarding URLs are randomized at each session startup, meaning that the webhooks you created on one session would not work an another session because there callbacksUrl wouldn't be valid anymore.
Note that you can subscribe to a paid plan to "reserve" ngrok subdomains and have URL consistency between sessions. Or you could manually update your webhooks callbackUrls with the new forarding URLs.
Anyway, I hope this will help!
P.S.: When the forwarding session runs, you can access localhost:4040 to inspect calls made on the forwarding URLs and retry some of them.

Recommended way to get temporary AWS credentials? AWS.config or STS?

I'm using a third-party SDK that needs temporary AWS credentials to access AWS services. I'm using this SDK as part of an application that is running on EC2. All SDKs in my application need access to the same role, which is attached to my the EC2 instance. Below, I have listed two options I have found for getting temporary credentials. Which one of these options is the recommended way for getting temporary credentials for my third-party SDK?
AWS.config
var AWS = require("aws-sdk");
AWS.config.getCredentials();
var creds = AWS.config.credentials
Security Token Service (STS)
var sts = new AWS.STS();
var params = {
RoleArn: "arn:aws:iam::123456789012:role/demo",
RoleSessionName: "Bob",
};
sts.assumeRole(params, function(err, data) {
var creds = data.Credentials;
});
Should in this case is a bit fluid, but when you launch an EC2 instance and assign it an instance profile, (somewhat) temporary credentials are made available as instance metadata. You access instance metadata via a local HTTP server bound on 169.254.169.254
e.g.
curl http://169.254.169.254/latest/meta-data/ami-id
returns the AMI-ID of the running instance. AWS credentials associated with the instance profile assigned to the instance can be accessed in this manner.
Anything running on the instance can access this data, meaning that if you're trying to isolate the third-party SDK from your instance profile, you've already failed.
However, it doesn't sound like that's what you're trying to do. When you execute AWS.config.getCredentials();, it uses the instance metadata (among other things) to look up the credentials. This is advantageous because it allows you to supply the credentials in a variety of manners without changing the code that looks them up.
The STS use case, however, is if you want to temporarily change a given user to a particular role. The user you're requesting from must have the sts:AssumeRole permission and have the same permissions as the target role. This can be used for auditing purposes, etc.

Google Cloud Storage change notifications with Node.js

I have Firebase storage bucket and I would like to use Node.js Google-cloud notification API in order to listen to changes in the storage.
What I have so far:
const gcloud = require('google-cloud');
const storage = gcloud.storage({
projectId: 'projectId',
credentials: serviceAccount
});
const storageBucket = storage.bucket('bucketId');
Now from what I understand I have to create a channel in order to listen to storage changes.
So I have:
const storageBucketNotificationChannel = storage.channel('channelId', 'resourceId');
This is the threshold where the docs stop being clear, as I can't figure out what channelId a resourceId stand for.
Nor do I understand how to declare listening to channel changes itself. Are there any lifecycle-type methods to do so?
Can I do something like?
storageBucketNotificationChannel.onMessage(message => { ... })
Based on the existing documentation of the Google Cloud Node.js Client and the feedback from this Github issue, there is presently no way for the node client to create a channel or subscribe to object change notifications.
One of the reasons being that the machine using the client may not necessarily be the machine on which the application runs, and thus a security risk. One can still however, subscribe to object change notifications for a given bucket and have notifications received a Node.js GAE application.
Using Objects: watchAll JSON API
When using gsutil to subscribe, gsutil sends a POST request to https://www.googleapis.com/storage/v1/b/bucket/o/watch where bucket is the name of the bucket to be watched. This is essentially a wrapper around the JSON API Objects: watchAll. Once a desired application/endpoint has been authorized as described in Notification Authorization, one can send the appropriate POST request to said API and provide the desired endpoint URL in address. For instance, address could be https://my-node-app.example.com/change.
The Node/Express application service would then need to listen to POST requests to path /change for notifications resembling this. The application would then act upon that data accordingly. Note, the application should respond to the request as described in Reliable Delivery for Cloud Storage to retry if it failed or stop retrying if it succeeded.

Firebase Authentication data mismatch between web and jvm

I’m trying out the Authentication component in Firebase.
A) I have a situation where the web client javascript code firebase-app.js and firebase-auth.js 3.3.0...
firebase.auth().onAuthStateChanged and
firebase.auth().currentUser
... return different expected logged in user values, than the jvm
client [com.firebase/firebase-client-jvm "2.5.2"]. The JVM client
returns null user data.
My JVM client code is taken from Firebase’s QuickStart Guide. In
the JVM client, neither onAuthStateChanged handler is called, nor
does firebaseObj.getAuth() return any data.
I’m wondering where the discrepancy is. The web client was initialized
with “codepairio.firebaseapp.com”.
var config = { ... authDomain: “<my-firebase-app>.firebaseapp.com"
};
firebase.initializeApp(config);
B) The java client was initialized with “https://.firebaseio.com”. I’m using this URL as it’s specified in the guide and mentioned here. Also, if you try
to use “.firebaseapp.com”, you’ll get an error:
“IllegalStateException For a custom firebase host you must first set your authentication server before using authentication features!”.
So with that out of the way, we have...
new Firebase("https://<my-firebase-app>.firebaseio.com”);
Any ideas on how to get them to observe the same source of truth?
====> [EDIT]
Ok, I've gotten a bit further. It turns out that I was using an older firebase API (A) than the latest (B).
A) https://www.firebase.com/docs/android/guide/user-auth.html
B) https://firebase.google.com/docs/auth/server/
So if we look at Firebase's documentation for how to handle user's, we see this:
A Firebase User object represents the account of a user who has signed
up to an app in your Firebase project. Apps usually have many
registered users, and every app in a Firebase project shares a user
database.
A Firebase User instance is independent from a Firebase Auth instance. This means that you can have several references to different
users within the same context and still call any of their methods.
But i) the notion of FirebaseAuth.getInstance().getCurrentUser() doesn't make sense if our app is dealing with multiple users. And further, the FirebaseAuth.getInstance().getCurrentUser() method doesn't even exist. The FirebaseAuth class file (in com.firebase/firebase-client-jvm "2.5.2"), doesn't reflect the documentation.
$ javap -classpath ~/.m2/repository/com/google/firebase/firebase-server-sdk/3.0.1/firebase-server-sdk-3.0.1.jar com.google.firebase.auth.FirebaseAuth
Compiled from "FirebaseAuth.java"
public class com.google.firebase.auth.FirebaseAuth {
public static com.google.firebase.auth.FirebaseAuth getInstance();
public static synchronized com.google.firebase.auth.FirebaseAuth getInstance(com.google.firebase.FirebaseApp);
public java.lang.String createCustomToken(java.lang.String);
public java.lang.String createCustomToken(java.lang.String, java.util.Map<java.lang.String, java.lang.Object>);
public com.google.firebase.tasks.Task<com.google.firebase.auth.FirebaseToken> verifyIdToken(java.lang.String);
static com.google.api.client.json.JsonFactory access$000();
static com.google.firebase.auth.internal.FirebaseTokenVerifier access$100(com.google.firebase.auth.FirebaseAuth);
static {};
}
C) So far, using Firebase's Authentication service, on the server is very opaque to me at the moment. Can someone clarify the semantics of handling multiple users, getting lists of logged in users, verifying users with request tokens, etc. Where's the working API for all this?
I actually got an answer back, from Firebase Support, on this. Turns out that, based on the documentation, the capabilities available for the server side (nodejs and java) in terms of authentication are only i) creating custom tokens and ii) verifying ID tokens. As of now, handling users or getting the current user is not supported yet.
For the creation and verifying tokens in the server side, you can refer to this guide for more information. You can also check these posts for more information.
Firebase Java client with custom authentication
Is it still possible to do server side verification of tokens in Firebase 3?
https://firebase.googleblog.com/2013/03/where-does-firebase-fit-in-your-app.html
Hth

Google Analytics API access with a service account

Can I access Google Analytics data using a service account in a client-side application? If not, are there other ways of achieving the same outcome?
Must be entirely client-side, and must not require users to authenticate (hence the desire to use a service account).
Yes you can in https://code.google.com/apis/console make sure you say that its a Service account it will give you a key file to download. With that you dont need a user to click ok to give you access.
For a service acccount to work you need to have a key file. Anyone that has access to that key file will then be able to access your Analytics data. Javascript is client sided which means you will need to send the key file. See the Problem? You are handing everyone access to your account. Even if you could get a service account to work using javascript for security reasons its probably not a very good idea.
You can use the official (and alpha) Google API for Node.js to generate the token. It's helpful if you have a service account.
On the server:
npm install -S googleapis
ES6:
import google from 'googleapis'
import googleServiceAccountKey from '/path/to/private/google-service-account-private-key.json' // see docs on how to generate a service account
const googleJWTClient = new google.auth.JWT(
googleServiceAccountKey.client_email,
null,
googleServiceAccountKey.private_key,
['https://www.googleapis.com/auth/analytics.readonly'], // You may need to specify scopes other than analytics
null,
)
googleJWTClient.authorize((error, access_token) => {
if (error) {
return console.error("Couldn't get access token", e)
}
// ... access_token ready to use to fetch data and return to client
// even serve access_token back to client for use in `gapi.analytics.auth.authorize`
})
If you went the "pass the access_token back to client" route:
gapi.analytics.auth.authorize({
'serverAuth': {
access_token // received from server, through Ajax request
}
})

Categories