Skip to content

Refactor GoogleCloudStorage to use gcloud - #2745

Closed
olivoil wants to merge 7 commits into
serverpod:mainfrom
olivoil:feature/gcp-native-storage
Closed

olivoil wants to merge 7 commits into
serverpod:mainfrom
olivoil:feature/gcp-native-storage

Conversation

@olivoil

@olivoil olivoil commented Sep 12, 2024 •

Copy link
Copy Markdown

This PR refactors the implementation of the GoogleCloudStorage integration to use gcloud.

Authentication to Cloud Storage switches was previously done using HMAC keys, this PR uses service account credentials. Users are expected to provide the path to the credentials file when creating a GoogleCloudStorage instance.

Fixes #2517.
Alternate solution to #2523 which could be closed in favor of this PR.

This implementation is based on a gist I shared in #2517 (comment), which I have been using on an app in development. It's been adapted to the current version of Serverpod.

All existing tests seem to pass, as it runs util/run_tests without error. However, I think the s3 and gcp storage integrations likely need more tests. I would have expected at least one fail since I introduced a breaking change to the GoogleCloudStorage constructor (documented below). It may be good to add tests to both storage integrations.

Pre-launch Checklist

  • I read the Contribute page and followed the process outlined there for submitting PRs.
  • This update contains only one single feature or bug fix and nothing else. (If you are submitting multiple fixes, please make multiple PRs.)
  • I read and followed the Dart Style Guide and formatted the code with dart format.
  • I listed at least one issue that this PR fixes in the description above.
  • I updated/added relevant documentation (doc comments with ///), and made sure that the documentation follows the same style as other Serverpod documentation. I checked spelling and grammar.
  • I added new tests to check the change I am making.
  • All existing and new tests are passing.
  • Any breaking changes are documented below.

If you need help, consider asking for advice on the discussion board.

Breaking changes

The way to instantiate a GoogleCloudStorage instance is slightly different, as we need to run an async function to read the service credentials file and setup authentication to gcloud.

An example of usage has been added to the GoogleCloudStorage class:

final publicStorage = await GoogleCloudStorage.init(
  serverpod: pod,
  storageId: 'public',
  public: true,
  bucket: myBucket,
  serviceAccountPath: '/config/google_account_credentials.json',
);

pod.addCloudStorage(publicStorage);

Additionally, users are now expected to provide service account credentials instead of using HMAC keys to authenticate with storage. The documentation on the website likely needs to be updated to reflect it. I am assuming the website documentation falls outside of this PR, but happy to contribute to it if needed.

@github-actions

github-actions Bot commented Sep 12, 2024 •

Copy link
Copy Markdown

CLA Assistant Lite bot All contributors have signed the CLA ✍️ ✅

@olivoil

olivoil commented Sep 12, 2024

Copy link
Copy Markdown
Author

I have read the CLA Document and I hereby sign the CLA

@Isakdl Isakdl left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thank you very much for the PR @olivoil very helpful and good work putting this together 😄!

I have taken a look at the code and made a few suggestions. On top of these comments I would like to put this code into a complete new package rather than overriding the old one as you point out this is a breaking change. But if we create an additional package it is not.

On the tests, yes unfortunately we have 0 tests on this code today. There are two different approaches to test this, either using a mock for the google services, such as this https://github.com/fsouza/fake-gcs-server, or implement a real e2e test against a real bucket.

It would be good to have coverage here, but I understand that this may be difficult to setup and I can help you with that if you like.

required Session session,
required String path,
String? subresource,
int expiration = 604800,

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: Make this magic number into a variable and declare it like 7 * 24 * 60 * 60 as it is much easier to digest the value this way.

Comment on lines +51 to +57
final instance = GoogleCloudStorage._(
serverpod: serverpod,
storageId: storageId,
public: public,
bucket: bucket,
serviceAccountPath: serviceAccountPath,
);

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggestion: the publicHost variable is not passed down here.

required this.serviceAccountPath,
String? publicHost,
}) : super(storageId) {
this.publicHost = publicHost ?? 'storage.googleapis.com/$bucket';

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggestion: Set the publicHost as the default in the constructor instead. It shouldn't contain the /$bucket part either, add that part where it is relevant.

required String storageId,
required bool public,
required String bucket,
required String serviceAccountPath,

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggestion:

This comment comes with a few implications. By passing in a path to the service account we are forcing people to use a service account stored on disc to authenticate with google. But there are otherways people may want to auth such as via the metaserver in a hosted environment. Google also has a method for default authentication, e.g. clientViaApplicationDefaultCredentials that will use an environment variable with the path to the service account, or the metaserver if running in cloud engine.

So it would be nice to use this method instead of passing in the path to the service account.

On top of this, it would be great to take an optional http client. If set it would override the call to clientViaApplicationDefaultCredentials. Then the user can use any available Google auth client or even a mock client for testing.

There is one implication of this though, and that is that we are currently signing the URL in process because we have direct access to the private key. This is not possible if we have authed via the meta server.

Luckily Google has an API to sign the URL though, but it requires the service account email. We could in other words take the service account email as input instead of the service account path and call this endpoint.

Like so:

var _iamCredentials = IAMCredentialsApi(authedClient);

final response = await _iamCredentials.projects.serviceAccounts.signBlob(
  SignBlobRequest(payload: base64.encode(stringToSignList)),
  'projects/-/serviceAccounts/$_serviceAccountEmail',
);

Where the the class IamCredentials comes from import 'package:googleapis/iamcredentials/v1.dart';

With the above change we can remove all service account management inside the code.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think using the API to get a signature makes sense, and removes the burden of maintaining the signature logic. I'll update it


import 'package:crypto/crypto.dart';
import 'package:hex/hex.dart';
import 'package:gcloud/storage.dart';

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggestion: Reading up on this dependency, it is tagged as experimental by Google. I'm a little reluctant to add it because of that. It is also possible to implement this same functionality with googleapis/storage, it is a bigger deviation from the current solution, but I believe it would be more resilient.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It does have a status of experimental, and I don't know what their timeline to GA is, or if it will make it to GA... Will look into googleapis/storage to see how it works

@alexdess

Copy link
Copy Markdown

Hello,
I just tested your PR, it works well, thank you.

For the web integration, it’s necessary to configure CORS as follows:

[
  {
    "origin": ["http://localhost:49423", [TO_BE_COMPLETED]],
    "method": ["DELETE", "GET", "HEAD", "POST","PUT"],
    "responseHeader": ["Content-Type", "x-goog-content-length-range"],
    "maxAgeSeconds": 3600
  }
]

I created a file named gcloud_cors.json containing this configuration and applied it using the following command:

gcloud storage buckets update gs://[YOUR_BUCKET_NAME] --cors-file=gcloud_cors.json

Google doc for CORS infos

I believe it could be beneficial to include this information in the project's documentation once the PR is merged. I'd be happy to contribute and help with that if needed.

@olivoil

olivoil commented Sep 20, 2024 •

Copy link
Copy Markdown
Author

Thank you very much for the PR @olivoil very helpful and good work putting this together 😄!

I have taken a look at the code and made a few suggestions. On top of these comments I would like to put this code into a complete new package rather than overriding the old one as you point out this is a breaking change. But if we create an additional package it is not.

On the tests, yes unfortunately we have 0 tests on this code today. There are two different approaches to test this, either using a mock for the google services, such as this https://github.com/fsouza/fake-gcs-server, or implement a real e2e test against a real bucket.

It would be good to have coverage here, but I understand that this may be difficult to setup and I can help you with that if you like.

Thank you for the review! I'll post an update addressing the feedback, then we can look at how to test it

@Isakdl any preference on what to name the package? Since serverpod_cloud_storage_gcp will be taken, maybe something to indicate it's a variant of it, e.g. serverpod_cloud_storage_gcp_iam ?

@Isakdl

Isakdl commented Sep 20, 2024

Copy link
Copy Markdown
Collaborator

@olivoil good question, but some variant sounds nice. Not 100% sure on the naming but ideally it should look nice and be kind of obvious that this is the one you should use. Some ideas: _native _bucket _iam, but we don't have to set it in stone yet.

@iampopal

Copy link
Copy Markdown

In which version of serverpod this will release because we really need to check is file uploaded or not and better control the security of files so each user only see files that belongs to them.

@marcelomendoncasoares

Copy link
Copy Markdown
Collaborator

Closing now that the issue is solved with the refactor of the storage packages.

@github-actions github-actions Bot locked and limited conversation to collaborators Apr 9, 2026
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

verifyDirectFileUpload always returns false even when upload succeeds

5 participants