Google Cloud Storage Signed URLs In Apps Script
Easy, secure icons
Two of the key challenges with Apps Script are storing non G Suite data, and extending Apps Script to take advantage of the broader Google ecosystem; advanced Google Services help address the latter challenge.
One of the places this comes to a head is in displaying images in your HTMLService UI: once you get beyond simple UI, you’ll want to provide your users with graphical hints in the form of icons.
Google Cloud Storage (GCS) is a natural place to store these, and you can simply refer to the object’s URL from your HTMLService… as long as the object is public. However, making libraries of icons which you’ve purchased from an icon vendor (or developed yourself) freely available may be more of a public service than you’d like to offer, to say nothing of potential licensing concerns.
You could make the GCS objects private, and only grant access to users on your domain…as long as you’re not providing a publicly available G Suite add-on, in which case you don’t know who your users are. Which is where GCS Signed URLs come in.
GCS Signed URLs give the user read, write, or delete access to that resource for a limited time. However, there isn’t an Apps Script advanced service for GCS; the GCS documentation provides a detailed recipe for rolling your own signed URLs, but like all things coding, there are many opportunities to go astray. Which is where the following function comes in.
Mint a service account credential in your add-on project’s GCloud console and download it.
- You didn’t store the credential in the add-on code did you? Pro-tip: write a script properties set wrapper function in the add-on and call this as a library method from an external harness to store the credential…this allows you to nuke the external harness and not worry about the credential being persisted in your add-on code as it goes through all its versions.
Delete the downloaded credential from your computer in a secure way, eg.
$ shred -u ~/Downloads/<KEY_FILE>
Grant reader permission on your objects or bucket to the service account.
In your HTMLService template, replace the hard-coded image reference with a scriptlet, eg.
<img src='<?= GCSImg ?>' alt="Signed URL Image"/>
In the function that creates your HTMLService
- Get the credential from the add-on’s script properties, convert it back to a JSON object
- Call the getSignedURL_ function with the appropriate parameters and set a template variable to the signed URL, eg.
template.GCSImg = getSignedURL_(GCSSignedURLCredential, GCSObjectURL,...);
Read the following to learn more about the solution components described in this article:
- Apps Script advanced Google Services.
- Apps Script HTMLService UI.
- Google Cloud Storage (GCS) Signed URLs.
Read the following guides to learn about Google Cloud Platform’s capabilities in the following area.