Skip to content

feat: Cloud storage improvements - #4771

Merged
nielsenko merged 23 commits into
mainfrom
feat-cloud-storage-revamp
Mar 3, 2026
Merged

nielsenko merged 23 commits into
mainfrom
feat-cloud-storage-revamp

Conversation

@nielsenko

@nielsenko nielsenko commented Feb 25, 2026 •

Copy link
Copy Markdown
Collaborator

Refactor cloud storage with shared S3-compatible base package

Introduces a layered architecture for cloud storage integrations, eliminating code duplication between S3 and GCP packages while adding support for new providers.

Shared base package (serverpod_cloud_storage_s3_compat)

  • S3CompatCloudStorage base implementation using configurable abstractions
  • S3EndpointConfig interface with implementations for AWS, GCP, R2, and custom endpoints
  • S3UploadStrategy interface with multipart POST (AWS/GCP/MinIO) and presigned PUT (R2) strategies
  • S3Client for signed S3 API requests with proper resource lifecycle (close())
  • Proper error handling: distinguishes 404 from server errors instead of silently swallowing failures

Native Google Cloud Storage (NativeGoogleCloudStorage)

  • Full GCS JSON API implementation with service account credentials
  • Application Default Credentials (ADC) support via IAM signBlob API and GCE metadata server
  • Local RSA-SHA256 signing via pointycastle (avoids googleapis_auth ^2.1.0 dependency chain that forces Flutter 3.38.1+)
  • Async factory constructors: create(), fromServiceAccountJson(), fromApplicationDefaultCredentials()

New features

  • preventOverwrite parameter on storeFile and createDirectFileUploadDescription — prevents uploading to an existing path (GCS native: ifGenerationMatch: '0'; S3 presigned PUT: If-None-Match: *; S3 multipart POST: not supported)
  • maxFileSize, expirationDuration, and contentLength exposed on StorageAccess.createDirectFileUploadDescription. When contentLength is provided it is validated against maxFileSize and signed into presigned PUT URLs, enabling server-side enforcement of exact file size
  • New serverpod_cloud_storage_r2 package for Cloudflare R2 support
  • FileUploader updated to support PUT method and custom headers for R2-style uploads

Hardening & cleanup

  • Fix silent error swallowing: retrieveFile, fileExists, and deleteFile now properly distinguish 404 from 5xx errors
  • Throw exceptions on upload failure instead of silent null return
  • Fix HTTP client leak in PresignedPutUploadStrategy.uploadData
  • Fix ByteData buffer aliasing in retrieveFile using ByteData.sublistView
  • Fix Policy expiration to use proper ISO 8601 formatting
  • Add close() to S3Client and S3CompatCloudStorage for resource cleanup
  • Replace hand-rolled MIME type lookup with mime package
  • Replace Completer pattern with async factory constructors (eliminates race between isCompleted checks and async init)
  • Improve GCP HMAC credential error messages

Fixes #4623
Fixes #4588
Fixes #4733
Fixes #1625
Closes: #3701

Related:

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

None. Refactored packages maintain full backwards compatibility with same constructor parameters and environment variable names.

@nielsenko nielsenko self-assigned this Feb 25, 2026
@nielsenko
nielsenko requested a review from a team February 25, 2026 10:17
@nielsenko
nielsenko marked this pull request as draft February 25, 2026 10:30
@nielsenko
nielsenko force-pushed the feat-cloud-storage-revamp branch 3 times, most recently from bcae0ed to d4d2830 Compare February 25, 2026 11:35
Introduce serverpod_cloud_storage_s3_compat with:
- S3EndpointConfig abstraction with AWS, GCP, and custom implementations
- S3UploadStrategy interface with multipart POST strategy
- S3Client for SigV4-signed API requests (GET, HEAD, DELETE)
- S3CompatCloudStorage base class wiring everything together

Upload strategies use Future<void> and throw typed exceptions
(S3Exception, NoPermissionsException) on failure.

Includes design documentation and comprehensive unit tests.
Refactor serverpod_cloud_storage_s3 and serverpod_cloud_storage_gcp
to thin wrappers around S3CompatCloudStorage, eliminating duplicated
S3 signing and upload logic.
Implements NativeGoogleCloudStorage that uses Google's native JSON API
with service account credentials for signing, rather than HMAC/S3-compat.

Includes unit tests for the native GCS implementation.
New serverpod_cloud_storage_r2 package using presigned PUT upload
strategy. Includes s3_compat dependency override for test servers.

Uses the mime package for content type detection in presigned PUT URLs.
Also adds R2 endpoint config and binary upload support to FileUploader.
Add createDirectFileUploadDescription to NativeGoogleCloudStorage using
signed URL v4 for direct browser-to-GCS uploads, with ACL header support.
- Add LICENSE, CHANGELOG, README to new packages.
- Add pubspec templates and update_pubspecs script.
- Add integration tests for S3-compat, native GCS, and R2 providers with shared test helper.
- Add CI workflow andrun_tests_integration_cloud script.
- Fix Given-When-Then test patterns.
…orageAccess

Add optional maxFileSize, expirationDuration, and contentLength parameters
to StorageAccess.createDirectFileUploadDescription, forwarding them to the
underlying CloudStorage implementations.

When contentLength is provided:
- Validated against maxFileSize (throws if exceeded)
- Signed into presigned PUT URLs for R2 and NativeGCS, enabling
  server-side enforcement of exact file size
- For S3/GCP HMAC (multipart POST), content-length-range policy
  already enforces maxFileSize

When contentLength is omitted, behavior is unchanged (backwards compatible).

Closes: #4733
Add Application Default Credentials (ADC) support via:
- IAM signBlob API for remote signing
- GCE metadata server for service account email discovery

Replace Completer-based initialization with async factory constructors:
- create(): loads credentials from Serverpod password system
- fromServiceAccountJson(): authenticates with explicit JSON
- fromApplicationDefaultCredentials(): uses ADC
- withStorageApi / withSigningCredentials / withAuthClient: sync (test-only)
Add optional named preventOverwrite parameter to both storeFile and
createDirectFileUploadDescription. If set to `true` it prevents uploading to a path where an
object already exists, if supported by the specific provider.

- GCS native: ifGenerationMatch: '0' (storeFile) / x-goog-if-generation-match: 0 (direct upload)
- S3 presigned PUT (AWS, R2): If-None-Match: * header
- S3 multipart POST: not supported (flag is accepted but ignored)
…ativeGoogleCloudStorage

- Replace _detectMimeType with lookupMimeType from the mime package.
- Add close() for HTTP client cleanup.
- Replace manual byte concatenation with BytesBuilder.
- Fix query parameter sorting in signed URL generation.
- Fix integration test to use async fromServiceAccountJson factory.
- Fix silent error swallowing: retrieveFile, fileExists, and deleteFile
  now properly distinguish 404 from server errors (5xx) instead of
  treating all non-200 responses as 'not found'

- Add public check to getPublicUrl to skip HEAD request for non-public
  storage (matching NativeGoogleCloudStorage behavior)

- Fix HTTP client leak in PresignedPutUploadStrategy.uploadData by
  properly creating and closing an http.Client instead of using the
  global http.put() function

- Add close() to S3Client and S3CompatCloudStorage for resource cleanup

- Fix ByteData buffer aliasing in retrieveFile by using ByteData.sublistView

- Fix Policy expiration to use proper ISO 8601 formatting instead of
  relying on DateTime.toString() which produces microsecond precision

- Rename misnamed cloud_storage.dart directory to cloud_storage in S3
  package and replace placeholder library docs

- Improve GCP HMAC credential error messages to include env var hints

- Document MultipartPostUploadStrategy preventOverwrite limitation
@nielsenko
nielsenko force-pushed the feat-cloud-storage-revamp branch from d4d2830 to 0ad3287 Compare February 25, 2026 11:44
@nielsenko

Copy link
Copy Markdown
Collaborator Author

Rebased on main

@nielsenko
nielsenko marked this pull request as ready for review February 25, 2026 12:09
@nielsenko
nielsenko force-pushed the feat-cloud-storage-revamp branch 10 times, most recently from 2550be1 to 05c9998 Compare February 26, 2026 10:11
@nielsenko
nielsenko force-pushed the feat-cloud-storage-revamp branch from 05c9998 to 1d438f5 Compare February 26, 2026 10:14
@nielsenko
nielsenko marked this pull request as draft February 26, 2026 10:15
…tegration_test_support package

The Dart package validator rejects importing `test` from `lib/` when
it is only a dev dependency, but promoting it to a regular dependency
would leak it to all consumers of `serverpod_cloud_storage_s3_compat`.

- Create a local-only (`publish_to: none`) package that owns the
  `test` dependency and hosts `runS3CompatIntegrationTests` and
  `S3CompatTestConfig`
- Move the shared test suite out of `serverpod_cloud_storage_s3_compat/lib/`
- Update consumer packages (S3, R2, GCP) to import from the new package
- Update INTEGRATION_TESTING.md to reflect the new structure
Replaces the single matrix job with four independent jobs (AWS S3,
Cloudflare R2, GCP, GCP Native), each with only the secrets it needs.
Skips at job level when credentials are missing. Switches from Flutter
to dart-lang/setup-dart and removes the multi-version matrix.
…oad strategies

Add supportsPreventOverwrite flag to skip preventOverwrite integration
tests when using MultipartPostUploadStrategy (which cannot support it).
Run the shared test suite twice for AWS S3 and GCP S3-compat: once with
MultipartPost and once with PresignedPut (which supports preventOverwrite).
Also fix secret names in CI workflow (remove incorrect SERVERPOD_ prefix).
@nielsenko
nielsenko force-pushed the feat-cloud-storage-revamp branch from 1d438f5 to bf9a949 Compare February 26, 2026 11:05
Add supportsObjectAcl capability to S3EndpointConfig (defaults true).
GCP and R2 override to false. MultipartPostUploadStrategy and Policy
conditionally omit ACL fields/conditions based on this flag.

Also switch endpoint configs from implements to extends, and disable
preventOverwrite tests for GCP S3-compat (no If-None-Match support).
@nielsenko
nielsenko force-pushed the feat-cloud-storage-revamp branch from 39c5417 to e7594b8 Compare February 26, 2026 12:45
…eAccess

StorageAccess.storeFile and createDirectFileUploadDescription now accept
contentLength and preventOverwrite as direct named parameters instead of
exposing the CloudStorageOptions type. The options object is built
internally before dispatching to the mixin.

@marcelomendoncasoares marcelomendoncasoares 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.

Great work with this big refactor! Only a few suggestions and questions on the comments.

Comment thread util/update_pubspecs Resolved
Move AwsEndpointConfig, GcpEndpointConfig, and R2EndpointConfig from
the base s3_compat package to their respective provider packages
(serverpod_cloud_storage_s3, _gcp, _r2). The base package retains only
the abstract S3EndpointConfig and the generic CustomEndpointConfig.

Update s3_compat tests to use CustomEndpointConfig as a generic fixture
instead of depending on provider-specific implementations.
@nielsenko
nielsenko force-pushed the feat-cloud-storage-revamp branch from 32cfe04 to 21e64b2 Compare February 27, 2026 10:04

@marcelomendoncasoares marcelomendoncasoares 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.

Just a few more comments on the tests and one point for discussion regarding the folder name for the endpoint config classes.

@nielsenko
nielsenko force-pushed the feat-cloud-storage-revamp branch from 3730daa to c432352 Compare February 27, 2026 16:33
Rename src/endpoints/ to src/config/ in all cloud storage packages to
avoid confusion with Serverpod Endpoint classes.

Also address remaining review comments:
- Break special-character path tests into separate Given scenarios
- Extract 1MB upload test into its own Given group
- Remove redundant inline comments in delete tests
- Remove inaccurate comment about throwing behavior
- Add unit tests for DatabaseCloudStorage preventOverwrite and
  contentLength validation

@marcelomendoncasoares marcelomendoncasoares 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.

Only one minor suggestion to replicate the changes done on the run_s3_compat_integration_tests.dart to the other similar storage tests (like the native_gcp_integration_test.dart). Apart from this, LGTM! 🚀

I'll leave it already approved, so feel free to merge directly after synchronizing the tests.

@nielsenko
nielsenko merged commit 317d0a8 into main Mar 3, 2026
148 of 152 checks passed
@github-actions github-actions Bot locked and limited conversation to collaborators Mar 3, 2026
@marcelomendoncasoares
marcelomendoncasoares deleted the feat-cloud-storage-revamp branch April 2, 2026 14:07
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.