feat(backend): add Firebase Auth middleware and protected routes#24
Conversation
Integrates Firebase Admin SDK to verify ID tokens on protected routes. Unauthenticated requests to /api/v1/* return 401; verified claims are passed downstream via Gin context. - FirebaseToken / FirebaseTokenVerifier / FirebaseAdminClient interfaces in usecase/ - FirebaseAuth Gin middleware (Bearer token extraction + verification) - GET /api/v1/me returns the authenticated user's decoded Firebase claims - Bootstrap initialises Firebase client when FIREBASE_PROJECT_ID is set; nil = auth disabled - Swagger BearerAuth security definition + FirebaseToken schema - FIREBASE_PROJECT_ID and FIREBASE_SERVICE_ACCOUNT_JSON added to .env.example - R2 storage adapter ported and fixed (StorageService interface defined locally) Closes #15 Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
|
Warning Review limit reached
More reviews will be available in 13 minutes and 37 seconds. Learn how PR review limits work. Your organization has run out of usage credits. Purchase more credits in the billing tab to continue. ⌛ How to resolve this issue?After more reviews become available, a review can be triggered using the We recommend that you space out your commits to avoid hitting the rate limit. 🚦 How do rate limits work?CodeRabbit enforces hourly rate limits for each developer per organization. Our paid plans include higher PR review limits than trial, open-source, and free plans. In all cases, reviews become available again over time. During sustained high-volume PR review activity, CodeRabbit may temporarily slow when the next review becomes available. Please see our Fair Usage Limits Policy for further information. ℹ️ Review info⚙️ Run configurationConfiguration used: defaults Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (5)
📝 WalkthroughWalkthroughAdds Firebase Authentication to the Go backend: defines ChangesFirebase Authentication Integration
Sequence Diagram(s)sequenceDiagram
participant Client
participant FirebaseAuth
participant authClientAdapter
participant MeHandler
rect rgba(255, 200, 100, 0.5)
note over Client,MeHandler: Protected /api/v1/me flow
end
Client->>FirebaseAuth: GET /api/v1/me<br/>Authorization: Bearer <token>
FirebaseAuth->>authClientAdapter: VerifyIDToken(ctx, token)
alt invalid or missing token
authClientAdapter-->>FirebaseAuth: error
FirebaseAuth-->>Client: 401 {"error":"unauthorized"}
else valid token
authClientAdapter-->>FirebaseAuth: *FirebaseToken{UID, Email, Name, ...}
FirebaseAuth->>MeHandler: c.Next() with FirebaseClaimsKey set
MeHandler-->>Client: 200 FirebaseToken JSON
end
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~25 minutes Possibly related issues
Possibly related PRs
Suggested labels
🚥 Pre-merge checks | ✅ 3 | ❌ 2❌ Failed checks (1 warning, 1 inconclusive)
✅ Passed checks (3 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches🧪 Generate unit tests (beta)
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. Comment |
There was a problem hiding this comment.
Actionable comments posted: 4
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
backend/go.mod (1)
1-173:⚠️ Potential issue | 🔴 CriticalUpdate aws-sdk-go-v2 to a newer version to address potential security vulnerability.
The Firebase Admin SDK (
firebase.google.com/go/v4 v4.20.0) is secure with no known advisories (released May 14, 2026). However,aws-sdk-go-v2 v1.42.0has a potential security exposure: a DoS vulnerability in the EventStream decoder (GHSA-xmrv-pmrh-hhx2) affects versions released before March 2026. Since v1.42.0 predates that cutoff and the codebase includes the vulnerableaws/protocol/eventstreamsub-package (visible in the indirect dependencies), upgrading to the latest stable version of aws-sdk-go-v2 is necessary to incorporate the security patch and defense-in-depth improvements.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@backend/go.mod` around lines 1 - 173, The aws-sdk-go-v2 module at version v1.42.0 contains a DoS vulnerability in the EventStream decoder that was patched in versions released after March 2026. Update github.com/aws/aws-sdk-go-v2 to a newer stable version (such as the latest available), and also update its related sub-packages github.com/aws/aws-sdk-go-v2/config, github.com/aws/aws-sdk-go-v2/credentials, and github.com/aws/aws-sdk-go-v2/service/s3 to compatible versions that correspond to the updated base module. After updating these direct dependencies, run go mod tidy to ensure all indirect aws-sdk-go-v2 sub-packages (including aws/protocol/eventstream) are also updated to patched versions.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@backend/.env.example`:
- Around line 13-14: Remove the extra spaces around the equals signs in the
FIREBASE_PROJECT_ID and FIREBASE_SERVICE_ACCOUNT_JSON variable assignments in
backend/.env.example. Normalize both lines by eliminating spaces after the
equals sign and before the comments to comply with dotenv standards and avoid
dotenv-linter warnings. Keep the comments intact but ensure the format is
VARIABLE_NAME=value # comment with no extra spacing.
In `@backend/internal/infrastructure/storage/r2/storage.go`:
- Around line 30-51: Add validation checks in the New function to ensure all
required configuration parameters are provided before using them. Specifically,
validate that accountID, accessKey, secretKey, bucket, and publicBaseURL are not
empty strings at the start of the function, before calling
config.LoadDefaultConfig or creating the S3 client. If any parameter is empty,
return an error with a clear message indicating which configuration value is
missing. This ensures misconfiguration is caught immediately rather than failing
at runtime during actual storage operations.
- Around line 77-78: The PublicURL method in the storageService struct is
concatenating the key parameter directly into the URL without escaping special
characters, which causes invalid URLs when the key contains spaces or reserved
characters. Modify the PublicURL method to URL-escape the key parameter using
url.PathEscape from Go's net/url package before composing and returning the
final URL string with fmt.Sprintf.
In `@backend/internal/transport/middleware/auth.go`:
- Around line 27-34: The middleware in the VerifyIDToken call block does not
validate that claims is non-nil before proceeding. If verifier.VerifyIDToken
returns (nil, nil), the code will treat it as authenticated and call c.Next()
with nil claims. Add a nil check after the err check: if claims is nil, abort
with http.StatusUnauthorized and an appropriate error message, similar to how
the error case is handled. This prevents setting nil claims in the context and
proceeding with an unauthenticated request.
---
Outside diff comments:
In `@backend/go.mod`:
- Around line 1-173: The aws-sdk-go-v2 module at version v1.42.0 contains a DoS
vulnerability in the EventStream decoder that was patched in versions released
after March 2026. Update github.com/aws/aws-sdk-go-v2 to a newer stable version
(such as the latest available), and also update its related sub-packages
github.com/aws/aws-sdk-go-v2/config, github.com/aws/aws-sdk-go-v2/credentials,
and github.com/aws/aws-sdk-go-v2/service/s3 to compatible versions that
correspond to the updated base module. After updating these direct dependencies,
run go mod tidy to ensure all indirect aws-sdk-go-v2 sub-packages (including
aws/protocol/eventstream) are also updated to patched versions.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro
Run ID: 4fc3c902-aa2f-4293-af17-438446ebf735
⛔ Files ignored due to path filters (1)
backend/go.sumis excluded by!**/*.sum
📒 Files selected for processing (17)
backend/.env.examplebackend/cmd/api/main.gobackend/docs/swagger/docs.gobackend/docs/swagger/swagger.jsonbackend/docs/swagger/swagger.yamlbackend/go.modbackend/internal/bootstrap/bootstrap.gobackend/internal/infrastructure/storage/r2/storage.gobackend/internal/server/server.gobackend/internal/transport/handlers/auth_handler.gobackend/internal/transport/handlers/auth_handler_test.gobackend/internal/transport/handlers/routes.gobackend/internal/transport/handlers/swagger_types.gobackend/internal/transport/middleware/auth.gobackend/internal/transport/middleware/auth_test.gobackend/internal/usecase/auth_usecase.gobackend/pkg/firebase/admin.go
- .env.example: remove spaces around = for dotenv-linter compatibility - FirebaseAuth middleware: reject nil claims from VerifyIDToken (nil, nil) - r2.New: validate all required args and return early on empty values - r2.PublicURL: url.PathEscape object key before composing URL
Closes #15
Summary
FirebaseAuthGin middleware that validatesAuthorization: Bearer <token>headers using the Firebase Admin SDK; returns 401 on missing or invalid tokensFIREBASE_PROJECT_IDis set; middleware is skipped when nil (safe for local dev without Firebase configured)GET /api/v1/meas the first protected route — returns the verified user's UID, email, name, and photo URLFirebaseToken,FirebaseTokenVerifier, andFirebaseAdminClientinterfaces inusecase/following the project's Clean Architecture dependency rulepkg/firebase/admin.gowraps the Admin SDK and satisfiesFirebaseAdminClientwithout leaking SDK types into the application layerBearerAuthsecurity definition added;FirebaseTokenschema exposed via type alias inswagger_types.gogigz/import,StorageServiceinterface now defined locallyTest plan
TestFirebaseAuth_MissingHeader→ 401TestFirebaseAuth_NonBearerHeader→ 401TestFirebaseAuth_InvalidToken→ 401 (verifier returns error)TestFirebaseAuth_ValidToken→ 200, claims in contextTestMeHandler_WithClaims→ 200, correct JSON bodyTestMeHandler_WithoutClaims→ 401go vet ./...passesmake swaggerregenerated without errorsNew env vars (added to
.env.example)FIREBASE_PROJECT_IDFIREBASE_SERVICE_ACCOUNT_JSONSummary by CodeRabbit
New Features
/api/v1/meendpoint to retrieve authenticated user informationDocumentation
Chores