Skip to content

feat(backend): add Firebase Auth middleware and protected routes#24

Merged
GRACENOBLE merged 3 commits into
mainfrom
backend.firebase
Jun 15, 2026
Merged

feat(backend): add Firebase Auth middleware and protected routes#24
GRACENOBLE merged 3 commits into
mainfrom
backend.firebase

Conversation

@GRACENOBLE

@GRACENOBLE GRACENOBLE commented Jun 15, 2026

Copy link
Copy Markdown
Owner

Closes #15

Summary

  • Adds FirebaseAuth Gin middleware that validates Authorization: Bearer <token> headers using the Firebase Admin SDK; returns 401 on missing or invalid tokens
  • Initialises the Firebase client in bootstrap when FIREBASE_PROJECT_ID is set; middleware is skipped when nil (safe for local dev without Firebase configured)
  • Introduces GET /api/v1/me as the first protected route — returns the verified user's UID, email, name, and photo URL
  • Defines FirebaseToken, FirebaseTokenVerifier, and FirebaseAdminClient interfaces in usecase/ following the project's Clean Architecture dependency rule
  • pkg/firebase/admin.go wraps the Admin SDK and satisfies FirebaseAdminClient without leaking SDK types into the application layer
  • Swagger BearerAuth security definition added; FirebaseToken schema exposed via type alias in swagger_types.go
  • R2 storage adapter (ported from previous project) fixed — removed broken gigz/ import, StorageService interface now defined locally

Test plan

  • TestFirebaseAuth_MissingHeader → 401
  • TestFirebaseAuth_NonBearerHeader → 401
  • TestFirebaseAuth_InvalidToken → 401 (verifier returns error)
  • TestFirebaseAuth_ValidToken → 200, claims in context
  • TestMeHandler_WithClaims → 200, correct JSON body
  • TestMeHandler_WithoutClaims → 401
  • go vet ./... passes
  • make swagger regenerated without errors

New env vars (added to .env.example)

Var Required Notes
FIREBASE_PROJECT_ID No Omit to disable auth (local dev)
FIREBASE_SERVICE_ACCOUNT_JSON No Single-line JSON from Firebase Console → Service Accounts

Summary by CodeRabbit

  • New Features

    • Added Firebase authentication support with Bearer token verification
    • Added /api/v1/me endpoint to retrieve authenticated user information
    • Added Cloudflare R2 storage adapter for object management
  • Documentation

    • Updated API documentation with new authentication endpoints and security definitions
  • Chores

    • Updated Go toolchain and dependencies (Firebase, AWS SDK, OpenTelemetry, and others)
    • Added tests for authentication flows

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>
@coderabbitai

coderabbitai Bot commented Jun 15, 2026

Copy link
Copy Markdown

Review Change Stack

Warning

Review limit reached

@GRACENOBLE, we couldn't start this review because you've reached your PR review rate limit.

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 @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

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 configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 3cb3bb93-5463-4d4c-a85c-40c99096d890

📥 Commits

Reviewing files that changed from the base of the PR and between 8b7dc6b and 8a313b7.

📒 Files selected for processing (5)
  • backend/.env.example
  • backend/internal/infrastructure/ipgeo/ipapi_client.go
  • backend/internal/infrastructure/ipgeo/ipapi_client_test.go
  • backend/internal/infrastructure/storage/r2/storage.go
  • backend/internal/transport/middleware/auth.go
📝 Walkthrough

Walkthrough

Adds Firebase Authentication to the Go backend: defines FirebaseToken/FirebaseAdminClient domain contracts, implements an Admin SDK adapter, adds a Gin Bearer-token middleware, wires a protected GET /api/v1/me handler, extends bootstrap and env config, documents the endpoint in Swagger, and introduces a standalone Cloudflare R2 storage adapter.

Changes

Firebase Authentication Integration

Layer / File(s) Summary
Auth domain contracts
backend/internal/usecase/auth_usecase.go
Defines FirebaseToken struct and FirebaseTokenVerifier/FirebaseAdminClient interfaces used across all layers.
Firebase Admin SDK adapter
backend/pkg/firebase/admin.go
Implements NewAuthClient and authClientAdapter wrapping the Firebase Admin SDK to satisfy FirebaseAdminClient; supports both service account JSON and ADC initialization.
Firebase auth middleware, MeHandler, and route wiring
backend/internal/transport/middleware/auth.go, backend/internal/transport/middleware/auth_test.go, backend/internal/transport/handlers/auth_handler.go, backend/internal/transport/handlers/auth_handler_test.go, backend/internal/transport/handlers/routes.go, backend/internal/transport/handlers/swagger_types.go, backend/internal/server/server.go
Implements FirebaseAuth Gin middleware for Bearer token validation; adds MeHandler that reads claims from context; updates RegisterRoutes to accept a verifier and conditionally protect /api/v1; wires app.Firebase into server handler setup; adds FirebaseToken Swagger type alias; includes tests for both middleware and handler.
Bootstrap and environment config
backend/internal/bootstrap/bootstrap.go, backend/.env.example
Extends App and Config with Firebase fields, loads FIREBASE_PROJECT_ID and FIREBASE_SERVICE_ACCOUNT_JSON from env, conditionally initializes the Firebase auth client in Run, and documents the new env vars.
Swagger/OpenAPI documentation
backend/cmd/api/main.go, backend/docs/swagger/docs.go, backend/docs/swagger/swagger.json, backend/docs/swagger/swagger.yaml
Adds BearerAuth security definition and GET /api/v1/me path with handlers.FirebaseToken response schema across all Swagger artifacts.
Cloudflare R2 storage adapter
backend/internal/infrastructure/storage/r2/storage.go
Introduces a standalone StorageService interface and New constructor for Cloudflare R2 using AWS SDK v2, with PresignUpload, Delete, and PublicURL methods.
Go module updates
backend/go.mod
Bumps Go toolchain, updates firebase.google.com/go/v4 and AWS SDK v2 direct deps, and advances a large set of indirect dependencies (Google Cloud, OpenTelemetry 1.43.0, grpc, transport).

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
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related issues

  • #15 (feat: add Firebase Authentication across all app layers): This PR directly implements the backend scope of issue #15 — Firebase Admin SDK integration, Gin middleware for token verification, 401 on invalid tokens, decoded claims passed to handlers via context, wiring in server.go, Swagger docs updated, and new env vars added to .env.example.

Possibly related PRs

  • GRACENOBLE/fullstack-template#14: This PR extends RegisterRoutes (originally wired with rate-limit parameters in PR #14) to also accept a FirebaseTokenVerifier and conditionally protect the /api/v1 route group.

Suggested labels

area: backend

🐇 A rabbit hops through the auth gate,
Bearer tokens checked — no fake ID fate!
Firebase claims flow into the Gin,
/api/v1/me returns who you've been.
R2 storage waits for uploads to land,
🔥 Secured and stored — just as planned! 🗂️

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (1 warning, 1 inconclusive)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 46.15% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
Out of Scope Changes check ❓ Inconclusive An R2 storage adapter was added alongside Firebase auth changes; while unrelated to the stated Firebase authentication objectives, the PR objectives acknowledge this as an infrastructure fix ported from a previous project. Clarify whether the R2 storage adapter changes are necessary for this PR or should be split into a separate pull request to maintain focus.
✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately summarizes the main change: adding Firebase Auth middleware and protected routes for the backend.
Linked Issues check ✅ Passed The PR implements all backend objectives from issue #15: Firebase token verification middleware with 401 responses, decoded claims passed via context, Firebase Admin SDK integration, middleware wiring, and protected routes.

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

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch backend.firebase

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.

@github-actions github-actions Bot added area: backend Go REST API type: chore Cleanup or maintenance tasks labels Jun 15, 2026

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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 | 🔴 Critical

Update 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.0 has 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 vulnerable aws/protocol/eventstream sub-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

📥 Commits

Reviewing files that changed from the base of the PR and between 6fc9fc1 and 8b7dc6b.

⛔ Files ignored due to path filters (1)
  • backend/go.sum is excluded by !**/*.sum
📒 Files selected for processing (17)
  • backend/.env.example
  • backend/cmd/api/main.go
  • backend/docs/swagger/docs.go
  • backend/docs/swagger/swagger.json
  • backend/docs/swagger/swagger.yaml
  • backend/go.mod
  • backend/internal/bootstrap/bootstrap.go
  • backend/internal/infrastructure/storage/r2/storage.go
  • backend/internal/server/server.go
  • backend/internal/transport/handlers/auth_handler.go
  • backend/internal/transport/handlers/auth_handler_test.go
  • backend/internal/transport/handlers/routes.go
  • backend/internal/transport/handlers/swagger_types.go
  • backend/internal/transport/middleware/auth.go
  • backend/internal/transport/middleware/auth_test.go
  • backend/internal/usecase/auth_usecase.go
  • backend/pkg/firebase/admin.go

Comment thread backend/.env.example Outdated
Comment thread backend/internal/infrastructure/storage/r2/storage.go
Comment thread backend/internal/infrastructure/storage/r2/storage.go Outdated
Comment thread backend/internal/transport/middleware/auth.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
@GRACENOBLE GRACENOBLE merged commit 38eacd3 into main Jun 15, 2026
3 checks passed
@GRACENOBLE GRACENOBLE deleted the backend.firebase branch June 15, 2026 10:29
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area: backend Go REST API type: chore Cleanup or maintenance tasks

Projects

None yet

Development

Successfully merging this pull request may close these issues.

feat: add Firebase Authentication across all app layers

1 participant