Skip to content

feat: Cloud storage improvements - #4766

Closed
nielsenko wants to merge 34 commits into
mainfrom
feat-cloud-storage-revamp
Closed

nielsenko wants to merge 34 commits into
mainfrom
feat-cloud-storage-revamp

Conversation

@nielsenko

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

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.

Add new serverpod_cloud_storage_s3_compat package with endpoint
configuration abstractions for S3-compatible storage providers.

This introduces:
- S3EndpointConfig abstract interface for URL building
- AwsEndpointConfig for AWS S3 (virtual-hosted style)
- GcpEndpointConfig for GCP S3-compatible API (path-style)
- CustomEndpointConfig for MinIO and other providers

Part of #4623
Add upload strategy pattern to support different upload mechanisms:
- S3UploadStrategy abstract interface
- MultipartPostUploadStrategy for POST with presigned policy
- Policy class for generating presigned POST policies

This enables supporting providers with different upload methods
(POST vs PUT) through the same CloudStorage interface.

Part of #4623
Add parameterized S3 client that uses endpoint configuration:
- S3Client for GET, HEAD, DELETE operations with SigV4 signing
- S3Exception and NoPermissionsException for error handling
- Support for non-standard ports (MinIO, LocalStack)

Part of #4623
Add base CloudStorage implementation that uses the S3 abstractions:
- S3CompatCloudStorage implements all CloudStorage methods
- Uses S3EndpointConfig for URL building
- Uses S3UploadStrategy for file uploads
- Uses S3Client for API requests

This enables building provider-specific implementations as thin
configuration wrappers around the base class.

Part of #4623
…ackage

S3CloudStorage now extends S3CompatCloudStorage from the new
serverpod_cloud_storage_s3_compat package. This eliminates the
duplicated AWS S3 client and upload code.

- Remove aws_s3_client directory (moved to s3_compat)
- Remove aws_s3_upload directory (moved to s3_compat)
- S3CloudStorage is now a thin wrapper that configures credentials
  and endpoints for AWS S3
- Maintains backwards compatibility with existing API
…package

GoogleCloudStorage now extends S3CompatCloudStorage from the new
serverpod_cloud_storage_s3_compat package. This eliminates the
duplicated S3-compatible client and upload code.

- Remove aws_s3_client directory (moved to s3_compat)
- Remove aws_s3_upload directory (moved to s3_compat)
- GoogleCloudStorage is now a thin wrapper that configures
  HMAC credentials and GCP endpoints
- Maintains backwards compatibility with existing API
Adds a new cloud storage implementation that uses Google Cloud's native
JSON API instead of the S3-compatible layer. This provides:

- Native GCP authentication using service account credentials
- Full access to GCP-specific features via googleapis package
- Service account JSON loaded from Serverpod's password system

The package now exports both implementations:
- GoogleCloudStorage: S3-compatible API with HMAC credentials (existing)
- NativeGoogleCloudStorage: Native GCP API with service account (new)

Note: Direct upload (createDirectFileUploadDescription) is not yet
implemented for the native implementation. Users who need direct upload
should continue using GoogleCloudStorage.
Replace setUpAll with setUp to follow the project's testing conventions.
Add comprehensive unit tests for the native GCP cloud storage
implementation using mocktail to mock the StorageApi.

Tests cover:
- File existence checking (exists, not found, error handling)
- File storage (public and private ACLs)
- File retrieval (success and not found)
- Public URL generation (default and custom hosts)
- File deletion (success, already deleted, error handling)
- Direct upload (returns null - not yet implemented)
- Upload verification

Also adds withStorageApi constructor for testing purposes.
Add the new serverpod_cloud_storage_s3_compat package as a dependency
override in test server pubspecs to resolve package resolution errors.

Updated:
- tests/serverpod_test_server/pubspec.yaml
- tests/serverpod_test_nonvector/serverpod_test_nonvector_server/pubspec.yaml
- tests/serverpod_auth_test/serverpod_auth_test_server/pubspec.yaml
- Corresponding template files
The URL returned by uploadData was never used by callers. Removing
it avoids returning potentially incorrect URLs for path-style endpoints.
- Move setup code from group level into setUp() callbacks
- Use groups with setUp() when tests share common setup
- Use standalone multiline tests when no shared setup needed
- Fix When-Then ordering (was Then-When in some places)
- Remove redundant 'for X tests' from group descriptions
…criptions

The createDirectFileUploadDescription method was ignoring the public
configuration flag, causing all direct uploads to use the default ACL.

This fix:
- Sets x-goog-acl header based on public setting (public-read or private)
- Includes content-type and x-goog-acl in the signed URL headers
- Returns the ACL header in the upload description for clients to send
Add real integration tests for AWS S3, Cloudflare R2, and GCP cloud storage
that run against actual cloud services with credentials from environment
variables or GitHub secrets.

- Add shared test helper in s3_compat package for all S3-compatible providers
- Add integration tests for AWS S3, Cloudflare R2, and GCP (HMAC)
- Add GitHub Actions workflow with matrix for all providers
- Add local test runner script (util/run_tests_integration_cloud)
- Add INTEGRATION_TESTING.md with setup instructions

Tests automatically skip when credentials are not configured.
…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
Replace googleapis_auth 2.1.0 built-in signing with:
- pointycastle RSA-SHA256 for service account credentials (local signing)
- IAM signBlob API for Application Default Credentials (remote signing)
- GCE metadata server for service account email discovery

This avoids the googleapis_auth ^2.1.0 -> google_cloud ^0.3.0 -> meta ^1.18.1
transitive dependency chain that forces Flutter 3.38.1+.
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)
Constructors that perform async initialization (service account JSON,
ADC) are now static async factory methods that return a fully-initialized
instance. This eliminates the race between isCompleted checks and
async init, and removes the ambiguity between "not configured" and
"still initializing".

- create(): loads credentials from Serverpod password system
- fromServiceAccountJson(): authenticates with explicit JSON
- fromApplicationDefaultCredentials(): uses ADC
- withStorageApi / withSigningCredentials: remain sync (test-only)
- withAuthClient: new test constructor for ADC signing path

Also add unit tests for the IAM signBlob signing path via
the withAuthClient constructor and a MockAuthClient.
Replace _detectMimeType in both NativeGoogleCloudStorage and
PresignedPutUploadStrategy with lookupMimeType from the mime package.
The mime package was already a transitive dependency and provides a
more comprehensive and maintained MIME type database.

Also 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 instead of ByteData.view(bytes.buffer)
- 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

Copy link
Copy Markdown
Collaborator Author

Supersedes #4675

@nielsenko

Copy link
Copy Markdown
Collaborator Author

Rewrote history for easier review.

@nielsenko nielsenko mentioned this pull request Feb 24, 2026
8 tasks done
@nielsenko nielsenko self-assigned this Feb 25, 2026
@nielsenko

Copy link
Copy Markdown
Collaborator Author

Closing as github broke when rebasing 🙄 - this is getting old fast. Will open a new identical one shortly.

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

Labels

None yet

Projects

None yet

1 participant