Skip to content

feat: Cloud storage improvements - #4675

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

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

Conversation

@nielsenko

@nielsenko nielsenko commented Feb 2, 2026 •

Copy link
Copy Markdown
Collaborator

Refactor cloud storage with shared S3-compatible base package

Introduces a layered architecture for cloud storage integrations, eliminating ~98% 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. NativeGoogleCloudStorage constructors changed from sync+Completer to async factories, but this is a new class with no existing users.

@nielsenko nielsenko self-assigned this Feb 2, 2026
@nielsenko
nielsenko force-pushed the feat-cloud-storage-revamp branch from e1c5f01 to 3644828 Compare February 2, 2026 11:30
@nielsenko

Copy link
Copy Markdown
Collaborator Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Feb 2, 2026

Copy link
Copy Markdown
Contributor
✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@coderabbitai

coderabbitai Bot commented Feb 2, 2026 •

Copy link
Copy Markdown
Contributor
📝 Walkthrough

Walkthrough

This PR implements cloud storage architectural improvements and a new health check system. It introduces a layered S3-compatible storage architecture with shared base abstractions, provider-specific implementations for AWS, GCP, and R2, and a native Google Cloud Storage integration. Additionally, it establishes a modular, orchestrator-friendly health check framework with caching, per-indicator timeouts, and Kubernetes-style endpoints.

Changes

Cohort / File(s) Summary
Design Documents
docs/design/cloud_storage.md, docs/design/health_check.md
Architectural design documents for layered S3-compatible cloud storage and modular health check systems with extensibility, caching, and orchestrator integration.
S3-Compat Base Package
integrations/serverpod_cloud_storage_s3_compat/lib/src/*, integrations/serverpod_cloud_storage_s3_compat/pubspec.yaml
New shared S3-compatible storage package containing core abstractions (S3Client, S3EndpointConfig, S3UploadStrategy), endpoint configurations (AWS, GCP, R2, custom), upload strategies (multipart POST, presigned PUT), and comprehensive test coverage.
S3-Compat Tests
integrations/serverpod_cloud_storage_s3_compat/test/*
Test suites for S3-compat exceptions, client signing, endpoint configs, and upload strategies across multiple provider scenarios.
GCP Cloud Storage
integrations/serverpod_cloud_storage_gcp/lib/serverpod_cloud_storage_gcp.dart, integrations/serverpod_cloud_storage_gcp/lib/src/cloud_storage/google_cloud_storage.dart, integrations/serverpod_cloud_storage_gcp/lib/src/native/native_google_cloud_storage.dart, integrations/serverpod_cloud_storage_gcp/pubspec.yaml
Refactored GCP integration extending S3CompatCloudStorage for backward compatibility plus new NativeGoogleCloudStorage using Google Cloud JSON API with V4 signed URLs and service account credentials.
GCP Native Implementation Tests
integrations/serverpod_cloud_storage_gcp/test/native/native_google_cloud_storage_test.dart
Test coverage for native GCP implementation including file operations, signing credentials, and MIME type detection.
GCP S3-Compat Cleanup
integrations/serverpod_cloud_storage_gcp/lib/src/aws_s3_client/*, integrations/serverpod_cloud_storage_gcp/lib/src/aws_s3_upload/*
Removed legacy AWS S3 client code (219 lines), exceptions, XML parsing models, and presigned POST upload logic, replaced by S3-compat base package.
S3 Cloud Storage
integrations/serverpod_cloud_storage_s3/lib/src/cloud_storage.dart/s3_cloud_storage.dart, integrations/serverpod_cloud_storage_s3/pubspec.yaml
Refactored S3 integration from CloudStorage to extend S3CompatCloudStorage with credential loading from environment/passwords.
S3 S3-Compat Cleanup
integrations/serverpod_cloud_storage_s3/lib/src/aws_s3_client/*, integrations/serverpod_cloud_storage_s3/lib/src/aws_s3_upload/*
Removed legacy AWS S3 client (219 lines), exceptions, XML models, and presigned POST logic, replaced by S3-compat base package.
R2 Cloud Storage
integrations/serverpod_cloud_storage_r2/lib/serverpod_cloud_storage_r2.dart, integrations/serverpod_cloud_storage_r2/lib/src/r2_cloud_storage.dart, integrations/serverpod_cloud_storage_r2/pubspec.yaml
New Cloudflare R2 integration extending S3CompatCloudStorage with presigned PUT upload strategy and R2-specific endpoint configuration.
Health Check Framework
packages/serverpod/lib/src/server/health/health_indicator.dart, packages/serverpod/lib/src/server/health/health_response.dart, packages/serverpod/lib/src/server/health/health_config.dart, packages/serverpod/lib/src/server/health/health_check_service.dart
Core health check abstractions including HealthIndicator interface, status/result types, configuration, and orchestration service with caching and timeout handling.
Built-in Health Indicators
packages/serverpod/lib/src/server/health/database_health_indicator.dart, packages/serverpod/lib/src/server/health/redis_health_indicator.dart, packages/serverpod/lib/src/server/health/serverpod_startup_indicator.dart
Standard health indicators for database connectivity (2s timeout), Redis PING checks (2s timeout), and Serverpod startup status.
Health Library Export
packages/serverpod/lib/src/server/health/health.dart, packages/serverpod/lib/server.dart
Health module aggregation and top-level export from server.dart.
Server Health Endpoints
packages/serverpod/lib/src/server/server.dart, packages/serverpod/lib/src/server/serverpod.dart
Added /livez, /readyz, /startupz endpoints with auth-gated detailed responses; integrated HealthCheckService initialization and configuration into Serverpod class.
Health Check Tests
packages/serverpod/test/server/health/*, tests/serverpod_test_server/test/health_endpoints_test.dart
Unit and integration tests for health indicators, configurations, responses, and endpoint behavior including caching, timeouts, and authentication scenarios.
Health Test Utilities
tests/serverpod_test_server/lib/test_util/fake_health_indicator.dart
Configurable test helper for simulating health indicator behavior with delays and failure modes.
Client File Upload
packages/serverpod_client/lib/src/file_uploader.dart, packages/serverpod_client/lib/src/serverpod_client_browser.dart
Extended binary upload to support configurable HTTP methods, custom headers, and 204 success status; added file uploader tests.
WebSocket Messages
packages/serverpod_serialization/lib/src/websocket_messages.dart
Changed conditional map entry inclusion to unconditional keys with nullable values in WebSocket message serialization.
CLI Platform Scripts
tools/serverpod_cli/lib/src/scripts/script.dart
Changed platform-specific script constructor to always include both Windows and Posix keys with nullable values.
Pubspec Updates
integrations/serverpod_cloud_storage_gcp/pubspec.yaml, integrations/serverpod_cloud_storage_s3/pubspec.yaml, templates/pubspecs/integrations/*, templates/pubspecs/tests/*/pubspec.yaml, tests/*/pubspec.yaml
Updated dependencies: removed built_value/built_collection, added pointycastle/crypto/googleapis; added serverpod_cloud_storage_s3_compat to overrides across all test and integration configurations.

Sequence Diagrams

sequenceDiagram
    participant Client as Client Application
    participant Upload as Upload Strategy
    participant Endpoint as Endpoint Config
    participant S3 as S3Client
    participant Provider as Cloud Provider

    Client->>Upload: uploadData(credentials, bucket, region, path, data)
    activate Upload
    
    Upload->>Endpoint: buildBucketUri(bucket, region)
    Endpoint-->>Upload: bucket endpoint URI
    
    alt Multipart Strategy
        Upload->>Upload: Build presigned policy (SigV4)
        Upload->>S3: Sign policy
    else Presigned PUT Strategy
        Upload->>S3: buildSignedParams(key, method=PUT)
        S3-->>Upload: SignedRequestParams
    end
    
    Upload->>Provider: HTTP POST/PUT (with signature)
    Provider-->>Upload: 200/204 Success
    Upload-->>Client: Public file URL
    deactivate Upload
Loading
sequenceDiagram
    participant HTTP as HTTP Request
    participant Server as Serverpod Server
    participant Service as HealthCheckService
    participant Indicators as Health Indicators
    participant Cache as Result Cache

    HTTP->>Server: GET /readyz
    activate Server
    
    Server->>Service: checkReadiness()
    activate Service
    
    Service->>Cache: Check cached results (TTL)
    alt Cache Hit
        Cache-->>Service: Cached results
    else Cache Miss
        Service->>Indicators: Execute all indicators in parallel
        activate Indicators
        loop Per Indicator
            Indicators->>Indicators: runWithTimeout(5s default)
            Indicators-->>Service: HealthCheckResult (pass/fail)
        end
        deactivate Indicators
        Service->>Cache: Store results with TTL
    end
    
    Service->>Service: Aggregate results by name
    Service-->>Server: HealthResponse (status, checks, notes)
    deactivate Service
    
    alt Authenticated
        Server-->>HTTP: 200/503 + JSON body
    else Unauthenticated
        Server-->>HTTP: 200/503 (empty body)
    end
    deactivate Server
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

The changes span multiple subsystems (cloud storage refactoring with 4 provider integrations, new health check framework, client updates) with heterogeneous patterns including design docs, new abstractions, legacy cleanup, configuration changes, and extensive test coverage. While individual files follow consistent patterns, the scope requires understanding interactions between storage strategies/endpoints, health indicator lifecycle management, and server integration points.

Possibly related PRs

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Out of Scope Changes check ⚠️ Warning The PR includes changes beyond cloud storage refactoring: new health check endpoints (/livez, /readyz, /startupz), health indicators, and related infrastructure. These changes appear disconnected from the core cloud storage improvement objective outlined in issue #4623. Review health check implementation and either justify its inclusion as a prerequisite for cloud storage or split into a separate PR to maintain focused scope.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The PR title 'feat: Cloud storage improvements' is clear and concise, accurately reflecting the main change of refactoring cloud storage with a shared S3-compatible base package and adding new provider support.
Linked Issues check ✅ Passed The PR successfully addresses all requirements from issue #4623: introduces a native GCP integration using Google Cloud's JSON API and service accounts, creates a shared S3-compatible base package eliminating duplication, and maintains backward compatibility while adding support for new providers like R2.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Description check ✅ Passed The pull request description is comprehensive and detailed, covering the refactor objectives, new features, hardening improvements, and breaking changes (none).

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
  • 📝 Generate docstrings (stacked PR)
  • 📝 Generate docstrings (commit on current branch)
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 19

🤖 Fix all issues with AI agents
In `@docs/design/cloud_storage.md`:
- Around line 38-76: Update the markdown to satisfy markdownlint by labeling the
leading code fence with a language (e.g., replace the unlabeled ``` with ```text
for the integrations tree) and normalize the table separator row in the
S3UploadStrategy table to include spaces around pipes (e.g., change
"|----------|--------------|----------------|" to "| -------- | ------------- |
-------------- |") so the fenced block and the table separators conform to lint
rules; apply these edits where S3EndpointConfig and S3UploadStrategy are defined
in the document.

In `@docs/design/health_check.md`:
- Line 182: Replace the bare URL in the sentence "Health endpoints should return
JSON following the draft RFC: _Health Check Response Format for HTTP APIs_
(https://datatracker.ietf.org/doc/html/draft-inadarei-api-health-check-06)" with
a markdown link; change the parenthetical URL to a markdown link like [_Health
Check Response Format for HTTP
APIs_](https://datatracker.ietf.org/doc/html/draft-inadarei-api-health-check-06)
so the reference satisfies the linter and preserves the existing text and
emphasis.

In
`@integrations/serverpod_cloud_storage_gcp/lib/src/native/native_google_cloud_storage.dart`:
- Around line 337-338: The canonicalUri is built using raw path which breaks for
spaces/Unicode; update the construction in native_google_cloud_storage.dart to
URL-encode path segments before joining them into the canonicalUri (e.g. split
path on '/', encode each segment with Uri.encodeComponent and rejoin with '/');
also encode the bucket name similarly (use Uri.encodeComponent(bucket)) so
canonicalUri becomes '/{encodedBucket}/{encodedPathSegments}'. This ensures
special characters are correctly percent-encoded while preserving segment
separators.
- Around line 289-299: The TOCTOU occurs in createDirectFileUploadDescription
where it checks _signingCredentialsCompleter.isCompleted; instead await the
completer instead of short-circuiting: await _signingCredentialsCompleter.future
(or await with a short timeout) to obtain credentials set up by
_initializeAsync, and wrap that await in try/catch to return null only on
timeout or initialization errors rather than whenever isCompleted was false at
call time; update references to _signingCredentialsCompleter and any code that
reads the credentials in createDirectFileUploadDescription to use the awaited
result.

In
`@integrations/serverpod_cloud_storage_gcp/test/native/native_google_cloud_storage_test.dart`:
- Around line 275-284: The test title is misleading:
createDirectFileUploadDescription on storage (constructed via withStorageApi)
returns null because withStorageApi does not supply signing credentials, not
because the feature is unimplemented; update the test to reflect that (e.g.,
"returns null when signing credentials are not provided") or change the setup to
provide signing credentials so the call to
createDirectFileUploadDescription(session: mockSession, path: 'upload.txt')
returns a real description; adjust the test name and/or setup accordingly and
keep references to createDirectFileUploadDescription, withStorageApi,
mockSession, and storage to locate the code.

In
`@integrations/serverpod_cloud_storage_s3_compat/lib/src/client/s3_client.dart`:
- Around line 70-98: The canonical path used for SigV4 signing is built as
encodedPath from unencodedPath but currently prepends an extra '/' causing a
double-leading-slash and invalid signatures; update the construction of
encodedPath in s3_client.dart (the variable encodedPath that feeds SigV4
canonical request creation) to avoid adding an extra leading '/' — instead
URL-encode each segment of unencodedPath and join them with '/', preserving a
single leading slash (i.e., use the segments of unencodedPath and only add a
leading slash if unencodedPath does not already start with one) so the canonical
request used by SigV4.hashCanonicalRequest('') and
SigV4.buildCanonicalQueryString(...) is correct.

In
`@integrations/serverpod_cloud_storage_s3_compat/lib/src/endpoints/aws_endpoint_config.dart`:
- Around line 18-48: The _joinPaths used by buildPublicUri can produce double
slashes when callers pass a path that starts with '/', so update _joinPaths
(and/or call-site in buildPublicUri) to normalize the incoming path by removing
any leading '/' (and treating empty or '/' as empty) before concatenation;
specifically, in _joinPaths ensure you trim a single leading slash from the
parameter `path` and then join with the normalized basePath so the returned path
never contains '//' while still preserving a single leading '/' for the final
URI.

In
`@integrations/serverpod_cloud_storage_s3_compat/lib/src/s3_compat_cloud_storage.dart`:
- Around line 108-145: The code currently treats any non-200 response as
"missing" — update retrieveFile, getPublicUrl (which calls fileExists),
fileExists, and deleteFile to distinguish 404/not-found from other errors: call
_client.getObject/_client.headObject/_client.deleteObject and if statusCode ==
200 (or success for delete) proceed as now; if statusCode == 404 return null
(for retrieveFile/getPublicUrl) or false (for fileExists); for any other
statusCode throw a descriptive exception that includes response.statusCode and
response body (or message) so permission/config/server errors surface; ensure
deleteFile similarly throws on non-404 non-success responses instead of silently
ignoring failures.

In
`@integrations/serverpod_cloud_storage_s3_compat/lib/src/upload/multipart_post_strategy.dart`:
- Around line 74-76: The returned object URL construction drops the bucket path
for path-style endpoints; in the response handling where you check
response.statusCode == 204, instead of uploadUri.replace(path:
'/${policy.key}'), build the new path by preserving uploadUri.path and appending
policy.key (handling slashes to avoid duplicates) and call
uploadUri.replace(path: newPath). Update the code around the response.statusCode
== 204 branch that uses uploadUri and policy.key so path-style endpoints keep
the original path segment(s) and only append the object key.

In `@integrations/serverpod_cloud_storage_s3_compat/lib/src/upload/policy.dart`:
- Around line 92-106: The toString override builds the policy JSON via manual
string interpolation which can break with quotes/control chars; instead
construct a Dart Map representing the policy using the same keys (expiration,
conditions) and the field names used in this class (expiration, bucket, key,
public, maxFileSize, credential, datetime) and return jsonEncode(map) so all
values are safely escaped; update the toString method to build that Map
(including the ["starts-with", "$key" ...] and content-length-range entries and
the acl computed from public) and call jsonEncode to produce the final string.

In
`@integrations/serverpod_cloud_storage_s3_compat/lib/src/upload/presigned_put_strategy.dart`:
- Around line 41-43: The code uses data.buffer.asUint8List() which exposes the
entire underlying buffer; instead slice the buffer to the ByteData view bounds
to avoid including unrelated bytes — replace the payloadBytes assignment to use
data.buffer.asUint8List(data.offsetInBytes, data.lengthInBytes) (keep the
payloadHash computation unchanged) so the SHA256 is computed only over the
ByteData view referenced by data.
- Around line 46-55: The canonical request currently injects objectPath raw into
the string (symbol: canonicalRequest in presigned_put_strategy.dart), which
breaks SigV4 signing for paths with spaces or reserved/UTF-8 chars; change to
percent-encode each path segment before building the canonical request (split
objectPath on '/', encode each segment with Uri.encodeComponent(), then rejoin
with '/' to preserve delimiters), and replace raw objectPath usage in both
places where canonicalRequest is constructed (the PUT canonicalRequest and the
second occurrence around the later string build) so the signed string matches S3
SigV4 expectations (use the same encoding approach as s3_client.dart).

In
`@integrations/serverpod_cloud_storage_s3_compat/test/upload/multipart_post_strategy_test.dart`:
- Around line 6-12: The test description misses the "when" clause; update the
test case for MultipartPostUploadStrategy (the test with the expect on
strategy.uploadType) to follow "Given ... when ... then ..." — for example
change the test name to include a when clause like "when constructed" or "when
created" so it reads: Given a MultipartPostUploadStrategy when constructed then
uploadType is multipart; keep the assert on strategy.uploadType unchanged.

In
`@integrations/serverpod_cloud_storage_s3_compat/test/upload/presigned_put_strategy_test.dart`:
- Around line 6-12: The test description omits the "when" clause in the
Given/When/Then chain; update the test title inside the test(...) that asserts
strategy.uploadType to include a "when" action (e.g., "when accessing
uploadType") so the full phrase reads "Given a PresignedPutUploadStrategy when
accessing uploadType then uploadType is binary"; locate the test in
main/group('Given a PresignedPutUploadStrategy', ...) that creates final
strategy = PresignedPutUploadStrategy() and change the test name accordingly to
follow the Given/When/Then pattern.

In `@packages/serverpod_client/lib/src/file_uploader.dart`:
- Around line 46-65: The code must explicitly reject presigned PUT uploads
without a known content length instead of implicitly buffering; before creating
or sending the http.StreamedRequest (i.e., before using
_uploadDescription.method, request, stream.pipe or request.send), check if
_uploadDescription.method (case-insensitive) is 'PUT' and length is null and
throw an ArgumentError with a clear message like "PUT uploads require a known
content length" so the library avoids buffering and fails fast for S3/GCS/R2
presigned PUTs.

In `@packages/serverpod_client/test/file_uploader_test.dart`:
- Around line 7-81: Update the test descriptions to follow "Given, When, Then"
by adding an explicit "when" clause to each test name while keeping each phrase
only once; e.g. change the test strings inside the groups like "then
FileUploader parses it without error" to "when parsing the description then
FileUploader parses it without error" (apply similarly for the binary POST/PUT
and invalid-description tests), ensuring you edit the test() description
arguments in the file_uploader_test.dart tests that reference the FileUploader
parsing scenarios.

In `@packages/serverpod/lib/src/redis/controller.dart`:
- Around line 315-330: The ping() method currently returns false for non-PONG
results but leaves the cached _command intact; change ping() so that after
awaiting _command?.send_object(['PING']) you check the result and if it is not
exactly 'PONG' call _invalidateCommand() before returning false, ensuring that
subsequent calls to _connect() will re-establish a fresh connection; keep the
existing try/catch behavior (also call _invalidateCommand() in the catch block
as it already does).

In `@packages/serverpod/lib/src/server/health/health_indicator.dart`:
- Around line 27-35: The example implementation of HealthIndicator<double>
returns an enum value for the componentType getter which is declared to return
String; update the componentType getter in the example (in the
HealthIndicator<double> snippet) to return HealthComponentType.component.name
(use the enum's .name) so the getter returns a String and avoids copy‑paste
compile errors.

In `@packages/serverpod/test/server/health/health_response_test.dart`:
- Around line 31-236: Reorder the test groups that call
HealthResponse.fromResults so success cases appear before failure cases: move
the groups titled "Given empty results when HealthResponse.fromResults is
called" and "Given multiple results with same name when
HealthResponse.fromResults is called" (and the "Given all passing results when
HealthResponse.fromResults is called" group if not already before failures) to
precede the groups "Given one failing result when HealthResponse.fromResults is
called", "Given multiple failing results when HealthResponse.fromResults is
called", and "Given failing result without output when
HealthResponse.fromResults is called"; keep the HealthResponse.alive() group
as-is. Ensure grouping and usage of HealthResponse.fromResults, and the helper
functions (_pass, _fail) remain unchanged.
🧹 Nitpick comments (6)
integrations/serverpod_cloud_storage_s3_compat/lib/src/endpoints/r2_endpoint_config.dart (1)

52-60: Consider centralizing _joinPaths to avoid drift across endpoint configs.

The helper is duplicated in other endpoint configs; a shared utility keeps path normalization consistent.

packages/serverpod/lib/src/server/health/health_check_service.dart (1)

134-134: Remove unnecessary unawaited wrapper.

Map.remove() returns the removed value synchronously, not a Future. The unawaited() function is intended for Future objects to suppress the unawaited_futures lint. Here it serves no purpose.

♻️ Proposed fix
     } finally {
-      unawaited(_pendingChecks.remove(indicator.name));
+      _pendingChecks.remove(indicator.name);
     }
integrations/serverpod_cloud_storage_gcp/lib/src/native/native_google_cloud_storage.dart (4)

87-96: Consider documenting test-mode limitation in a more prominent way.

The withStorageApi constructor silently disables direct uploads. Users might be surprised when createDirectFileUploadDescription returns null.

📝 Proposed documentation improvement
   /// Creates a [NativeGoogleCloudStorage] with an already-initialized
   /// [StorageApi].
   ///
   /// This constructor is primarily intended for testing purposes.
   ///
   /// Note: Direct upload via signed URLs is not available when using this
   /// constructor, as signing credentials are not provided.
+  /// [createDirectFileUploadDescription] will return `null`.
   NativeGoogleCloudStorage.withStorageApi({

158-187: Consider adding validation for unexpected ASN.1 structures.

The parser assumes specific element counts and types. Malformed PEM could cause index-out-of-bounds or cast errors with unclear messages.

🛡️ Proposed defensive validation
   RSAPrivateKey _parsePrivateKeyFromPem(String pem) {
     final lines = pem
         .split('\n')
         .where((line) => !line.startsWith('-----'))
         .join();
     final bytes = base64.decode(lines);
     final asn1Parser = ASN1Parser(Uint8List.fromList(bytes));
     final topLevelSeq = asn1Parser.nextObject() as ASN1Sequence;

+    if (topLevelSeq.elements == null || topLevelSeq.elements!.isEmpty) {
+      throw FormatException('Invalid private key PEM: empty ASN.1 sequence');
+    }
+
     // PKCS#8 format: PrivateKeyInfo ::= SEQUENCE { version, algorithm, privateKey }
     // The privateKey is an OCTET STRING containing the RSA private key
     ASN1Sequence rsaSeq;
     if (topLevelSeq.elements!.length == 3) {
       // PKCS#8 format
       final privateKeyOctet = topLevelSeq.elements![2] as ASN1OctetString;
       final pkParser = ASN1Parser(privateKeyOctet.valueBytes);
       rsaSeq = pkParser.nextObject() as ASN1Sequence;
     } else {
       // PKCS#1 format (raw RSA key)
       rsaSeq = topLevelSeq;
     }

+    if (rsaSeq.elements == null || rsaSeq.elements!.length < 6) {
+      throw FormatException(
+        'Invalid RSA private key: expected at least 6 elements, '
+        'got ${rsaSeq.elements?.length ?? 0}',
+      );
+    }
+
     final modulus = (rsaSeq.elements![1] as ASN1Integer).integer!;

244-256: Potential performance concern: fileExists call for public URL generation.

getPublicUrl makes a network call to check file existence. If callers already know the file exists, this is an unnecessary round-trip. Consider documenting this behavior or providing an unchecked variant.


410-413: _uriEncode replaces + unnecessarily.

Uri.encodeComponent does not produce + for spaces (it uses %20). The replaceAll('+', '%2B') is a no-op and suggests a misunderstanding of the encoding behavior.

📝 Simplify or clarify the encoding
   /// URI-encodes a string according to RFC 3986.
   String _uriEncode(String input) {
-    return Uri.encodeComponent(input).replaceAll('+', '%2B');
+    // Uri.encodeComponent is RFC 3986 compliant; '+' is already encoded as %2B
+    return Uri.encodeComponent(input);
   }

Comment thread docs/design/cloud_storage.md Resolved
Comment thread docs/design/health_check.md Resolved
@nielsenko
nielsenko force-pushed the feat-cloud-storage-revamp branch 10 times, most recently from 6e99c99 to d137cf1 Compare February 3, 2026 17:55
@nielsenko
nielsenko requested a review from a team February 3, 2026 18:13
@nielsenko
nielsenko marked this pull request as ready for review February 3, 2026 18:37
@nielsenko
nielsenko marked this pull request as draft February 4, 2026 12:19
@nielsenko
nielsenko force-pushed the feat-cloud-storage-revamp branch 3 times, most recently from a9bebe3 to 512c3af Compare February 4, 2026 18:35
@nielsenko
nielsenko force-pushed the feat-cloud-storage-revamp branch from 512c3af to 2a7646b Compare February 4, 2026 19:17
@nielsenko
nielsenko force-pushed the feat-cloud-storage-revamp branch 4 times, most recently from 0e60c21 to 35e50ea Compare February 18, 2026 11:55
Comment on lines +139 to +142
final authClient = await clientViaServiceAccount(
credentials,
[gcs.StorageApi.devstorageFullControlScope],
);

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.

Hey, just saw the draft and wanted to give my 2 cents here.

I would suggest changing this to use clientViaApplicationDefaultCredentials instead, e.g. something like:

final client = auth.clientViaApplicationDefaultCredentials(
  scopes: ['https://www.googleapis.com/auth/cloud-platform'],
);

The reason is that clientViaApplicationDefaultCredentials has an internal logical order for checking credentials and will call the meta server in a kubernetes cluster for access, meaning you can do a keyless setup. But it will also work nicely if you have local credentials from your gcloud cli, meaning by using clientViaApplicationDefaultCredentials you can both have a very clean production setup and a simple dev setup. There are also environment variables this method is looking for for service accounts.

Additionally, I would argue for allowing to pass in an HttpClient into the constructor to override the default one, this is a convenient way to configure the bucket integration to talk with a mock server such as https://github.com/fsouza/fake-gcs-server or just use a mock http client.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

@Isakdl What about signing? Application Default Credentials don't allow for that, do they?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

I guess we could look into the IAM signBlob API 🤔

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.

Yeah precisely, I pinged you on slack already, but to keep the history

This type of call can be used to sign the payload:

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

There is one drawback with this approach, in that the user must provide the service account email. In the JSON credential blob this is usually included, but when using the applicationDefault, you cannot get the service account email, at least not in all the auth paths.

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: serverpod#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
nielsenko force-pushed the feat-cloud-storage-revamp branch from bafa42e to bb9d73c Compare February 24, 2026 20:25
@nielsenko

Copy link
Copy Markdown
Collaborator Author

Closing this to open again in serverpod (this will (/should) allow cloud storage integration tests to run.

@nielsenko nielsenko closed this Feb 24, 2026
@github-actions github-actions Bot locked and limited conversation to collaborators Feb 24, 2026
@nielsenko

Copy link
Copy Markdown
Collaborator Author

Superseded by #4766

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

None yet

Projects

None yet

2 participants