Skip to content

Commit ca3564f

Browse files
authored
Merge pull request #25 from GRACENOBLE/observability.sentry
feat(observability): add Sentry error tracking across backend, web, and mobile
2 parents 38eacd3 + 05dc1b8 commit ca3564f

33 files changed

Lines changed: 2012 additions & 113 deletions

‎backend/.env.example‎

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,5 +10,9 @@ BLUEPRINT_DB_SSLMODE=disable
1010
REDIS_URL=
1111
RATE_LIMIT_RPS=100 # requests/sec per IP (omit or 0 = disabled)
1212
RATE_LIMIT_BURST=500 # burst capacity (defaults to RPS×5)
13-
FIREBASE_PROJECT_ID=# Firebase project ID — e.g. my-app-12345 (omit to disable auth)
14-
FIREBASE_SERVICE_ACCOUNT_JSON=# Service account key as a single-line JSON string. Get from: Firebase Console → Project Settings → Service Accounts → Generate new private key
13+
# Firebase project ID — e.g. my-app-12345 (omit to disable auth)
14+
FIREBASE_PROJECT_ID=
15+
# Service account key as a single-line JSON string. Get from: Firebase Console → Project Settings → Service Accounts → Generate new private key
16+
FIREBASE_SERVICE_ACCOUNT_JSON=
17+
# Sentry error tracking DSN (optional; leave empty to disable)
18+
SENTRY_DSN=

‎backend/docs/_index.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,3 +13,5 @@ The `docs` agent reads this index first to locate the right file before diving i
1313
| Error handling conventions | [error-handling.md](error-handling.md) | `internal/infrastructure/database/postgres/health_repository.go`, `internal/transport/handlers/health_handler.go`, `cmd/api/main.go` |
1414
| Environment variables | [environment.md](environment.md) | `.env`, `internal/bootstrap/bootstrap.go`, `internal/infrastructure/database/postgres/db.go` |
1515
| Middleware (logger, rate limiter) | [middleware.md](middleware.md) | `internal/transport/middleware/logger.go`, `internal/transport/middleware/ratelimit.go`, `internal/transport/handlers/routes.go` |
16+
| Firebase Auth (token verification, middleware, MeHandler) | [auth.md](auth.md) | `internal/usecase/auth_usecase.go`, `internal/transport/middleware/auth.go`, `internal/transport/handlers/auth_handler.go`, `pkg/firebase/admin.go`, `internal/bootstrap/bootstrap.go` |
17+
| Observability (Sentry error tracking) | [observability.md](observability.md) | `internal/transport/middleware/sentry.go`, `internal/bootstrap/bootstrap.go`, `internal/transport/handlers/routes.go` |

‎backend/docs/auth.md‎

Lines changed: 110 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,110 @@
1+
---
2+
topic: auth
3+
last_verified: 2026-06-15
4+
sources:
5+
- internal/usecase/auth_usecase.go
6+
- internal/transport/middleware/auth.go
7+
- internal/transport/handlers/auth_handler.go
8+
- pkg/firebase/admin.go
9+
- internal/bootstrap/bootstrap.go
10+
---
11+
12+
# Firebase Auth
13+
14+
## Domain type
15+
16+
`FirebaseToken` is defined in `internal/usecase/auth_usecase.go` and holds the claims extracted from a verified Firebase ID token:
17+
18+
```go
19+
type FirebaseToken struct {
20+
UID string `json:"uid"`
21+
Email string `json:"email"`
22+
Name string `json:"name"`
23+
PhotoURL string `json:"photoUrl"`
24+
Claims map[string]any `json:"claims"`
25+
}
26+
```
27+
28+
`UID`, `Email`, `Name`, and `PhotoURL` are promoted from the raw Firebase JWT claims (`uid`, `email`, `name`, `picture`). `Claims` contains the full unmodified payload.
29+
30+
## Usecase interfaces
31+
32+
Both interfaces live in `internal/usecase/auth_usecase.go`.
33+
34+
```go
35+
// FirebaseTokenVerifier can verify a raw Firebase ID token string.
36+
type FirebaseTokenVerifier interface {
37+
VerifyIDToken(ctx context.Context, idToken string) (*FirebaseToken, error)
38+
}
39+
40+
// FirebaseAdminClient extends FirebaseTokenVerifier with user-management operations.
41+
type FirebaseAdminClient interface {
42+
FirebaseTokenVerifier
43+
GetUserByEmail(ctx context.Context, email string) (string, error)
44+
UpdateUserPassword(ctx context.Context, uid, newPassword string) error
45+
}
46+
```
47+
48+
`FirebaseTokenVerifier` is the narrow interface used by the `FirebaseAuth` middleware. `FirebaseAdminClient` is the broader interface stored on `bootstrap.App` and wired into the server.
49+
50+
## pkg/firebase/admin.go
51+
52+
`NewAuthClient` initialises the Firebase Admin SDK and returns a `usecase.FirebaseAdminClient`:
53+
54+
```go
55+
func NewAuthClient(ctx context.Context, projectID, credentialsJSON string) (usecase.FirebaseAdminClient, error)
56+
```
57+
58+
- When `credentialsJSON` is non-empty the SDK is initialised with `option.WithCredentialsJSON` (service account key).
59+
- When `credentialsJSON` is empty the SDK falls back to Application Default Credentials (ADC) — used on GCP.
60+
61+
The returned value is `*authClientAdapter`, a private type that wraps `*auth.Client` from the Firebase Admin SDK. This adapter satisfies both `FirebaseTokenVerifier` and `FirebaseAdminClient` without leaking the SDK type into the application layer.
62+
63+
## FirebaseAuth middleware
64+
65+
Defined in `internal/transport/middleware/auth.go`.
66+
67+
```go
68+
const FirebaseClaimsKey = "firebase_claims"
69+
70+
func FirebaseAuth(verifier usecase.FirebaseTokenVerifier) gin.HandlerFunc
71+
```
72+
73+
For every request the middleware:
74+
1. Reads the `Authorization` header; aborts with `401` if the header is missing or does not start with `Bearer `.
75+
2. Calls `verifier.VerifyIDToken(ctx, idToken)`.
76+
3. On success: stores `*usecase.FirebaseToken` in the Gin context under `FirebaseClaimsKey` and calls `c.Next()`.
77+
4. On error: aborts with `401` and `{"error": "invalid or expired token"}`.
78+
79+
Retrieve claims inside a handler:
80+
```go
81+
val, _ := c.Get(middleware.FirebaseClaimsKey)
82+
token, ok := val.(*usecase.FirebaseToken)
83+
```
84+
85+
## MeHandler (GET /api/v1/me)
86+
87+
Defined in `internal/transport/handlers/auth_handler.go`.
88+
89+
```go
90+
func (h *Handler) MeHandler(c *gin.Context)
91+
```
92+
93+
- Reads `*usecase.FirebaseToken` from the Gin context (`FirebaseClaimsKey`).
94+
- Returns `200 OK` with the token struct serialised as JSON.
95+
- Returns `401 Unauthorized` with `{"error": "unauthorized"}` if the context value is missing or of the wrong type (should not happen when `FirebaseAuth` is applied to the group).
96+
97+
The handler is registered on the `/api/v1` group in `RegisterRoutes`:
98+
```go
99+
api := r.Group("/api/v1")
100+
if verifier != nil {
101+
api.Use(middleware.FirebaseAuth(verifier))
102+
}
103+
api.GET("/me", h.MeHandler)
104+
```
105+
106+
## Disabling auth in development
107+
108+
When `FIREBASE_PROJECT_ID` is not set `bootstrap.Run` skips Firebase initialisation and `app.Firebase` is `nil`. `server.NewServer` passes `app.Firebase` directly to `RegisterRoutes` as the `verifier` argument. When `verifier` is `nil` the `if verifier != nil` guard in `RegisterRoutes` skips `api.Use(middleware.FirebaseAuth(...))`, so `/api/v1/me` is reachable without a token.
109+
110+
To enable auth locally set both `FIREBASE_PROJECT_ID` and `FIREBASE_SERVICE_ACCOUNT_JSON` in `backend/.env`.

‎backend/docs/bootstrap.md‎

Lines changed: 20 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
---
22
topic: bootstrap
3-
last_verified: 2026-06-14
3+
last_verified: 2026-06-15
44
sources:
55
- internal/bootstrap/bootstrap.go
66
- internal/server/server.go
@@ -15,22 +15,30 @@ sources:
1515
## App struct
1616
```go
1717
type App struct {
18-
DB *sql.DB
19-
Config Config
20-
Log *slog.Logger
18+
DB *sql.DB
19+
Cache usecase.CacheService // nil when REDIS_URL is not set
20+
Firebase usecase.FirebaseAdminClient // nil when FIREBASE_PROJECT_ID is not set
21+
Config Config
22+
Log *slog.Logger
2123
}
2224
```
23-
`App` is constructed once by `Run` and passed to `server.NewServer`. Nothing re-initialises dependencies after this point.
25+
`App` is constructed once by `Run` and passed to `server.NewServer`. Nothing re-initialises dependencies after this point. Optional fields (`Cache`, `Firebase`) are nil when their corresponding env vars are absent.
2426

2527
## Config struct
2628
```go
2729
type Config struct {
28-
Port int
29-
AppEnv string
30-
DB postgres.DBConfig
30+
Port int
31+
Env string
32+
DB postgres.DBConfig
33+
RedisURL string
34+
RateLimitRPS float64
35+
RateLimitBurst int
36+
FirebaseProjectID string
37+
FirebaseServiceAccountJSON string
38+
SentryDSN string
3139
}
3240
```
33-
`loadConfig()` reads all values from environment variables. `PORT` defaults to `8080`; `BLUEPRINT_DB_SCHEMA` defaults to `public`; `BLUEPRINT_DB_SSLMODE` defaults to `disable`.
41+
`loadConfig()` reads all values from environment variables. `PORT` defaults to `8080`; `BLUEPRINT_DB_SCHEMA` defaults to `public`; `BLUEPRINT_DB_SSLMODE` defaults to `disable`. `RateLimitBurst` is derived as `int(RPS)*5` when omitted and RPS is set. Optional fields (`RedisURL`, `FirebaseProjectID`, `FirebaseServiceAccountJSON`) default to empty string — their respective services are skipped when empty.
3442

3543
## Run sequence
3644
`bootstrap.Run(ctx)` executes these steps in order:
@@ -39,7 +47,9 @@ type Config struct {
3947
2. Validate required fields via `validateConfig()` — fast, no I/O
4048
3. Open `*sql.DB` via `postgres.NewPostgresDB(cfg.DB)`
4149
4. Probe Postgres with `probeWithRetry` under a 60-second total timeout
42-
5. Return `*App` on success; return a non-nil error on any failure
50+
5. Init Redis via `redis.New(cfg.RedisURL)` and probe it — skipped when `REDIS_URL` is empty
51+
6. Init Firebase Admin SDK via `firebase.NewAuthClient(ctx, projectID, credentialsJSON)` — skipped when `FIREBASE_PROJECT_ID` is empty
52+
7. Return `*App` on success; return a non-nil error on any failure
4353

4454
```go
4555
ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)

‎backend/docs/environment.md‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ sources:
55
- .env
66
- internal/bootstrap/bootstrap.go
77
- internal/infrastructure/database/postgres/db.go
8+
- pkg/firebase/admin.go
89
---
910

1011
# Environment Variables
@@ -31,6 +32,8 @@ This runs on package init before any env var is read — no explicit `godotenv.L
3132
| `BLUEPRINT_DB_SSLMODE` | `bootstrap.go` | `disable` | Postgres SSL mode (`disable`, `require`, `verify-full`) |
3233
| `RATE_LIMIT_RPS` | `bootstrap.go` | `0` (disabled) | Max requests per second per IP. Set to `0` or omit to disable rate limiting. |
3334
| `RATE_LIMIT_BURST` | `bootstrap.go` | `int(RPS) * 5`, min 1 | Token-bucket burst capacity. Derived as `int(RPS)*5` when omitted; clamped to 1 so fractional RPS values never block all traffic. |
35+
| `FIREBASE_PROJECT_ID` | `bootstrap.go`, `pkg/firebase/admin.go` | — | Firebase project ID. When omitted the Firebase Admin client is not initialised and `FirebaseAuth` middleware is skipped (auth disabled). |
36+
| `FIREBASE_SERVICE_ACCOUNT_JSON` | `bootstrap.go`, `pkg/firebase/admin.go` | — | Raw JSON content of a Firebase service account key file. When omitted the SDK falls back to Application Default Credentials (ADC) — appropriate for GCP-hosted deployments. Only relevant when `FIREBASE_PROJECT_ID` is set. |
3437

3538
Variables marked **required** are validated by `bootstrap.validateConfig` at startup — the process exits before attempting a DB connection if any are missing.
3639

‎backend/docs/middleware.md‎

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ last_verified: 2026-06-15
44
sources:
55
- internal/transport/middleware/logger.go
66
- internal/transport/middleware/ratelimit.go
7+
- internal/transport/middleware/auth.go
78
- internal/transport/handlers/routes.go
89
---
910

@@ -20,6 +21,18 @@ r.Use(gin.Recovery(), middleware.Logger())
2021
r.Use(middleware.RateLimit(rps, burst))
2122
// 3. CORS
2223
r.Use(cors.New(...))
24+
25+
// Global routes (no auth):
26+
r.GET("/", h.HelloWorldHandler)
27+
r.GET("/health", h.HealthHandler)
28+
r.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler))
29+
30+
// Protected group — FirebaseAuth applied when verifier != nil:
31+
api := r.Group("/api/v1")
32+
if verifier != nil {
33+
api.Use(middleware.FirebaseAuth(verifier))
34+
}
35+
api.GET("/me", h.MeHandler)
2336
```
2437

2538
## Logger
@@ -36,6 +49,30 @@ In debug mode (`ENV` not set to `staging`/`production`) Gin's built-in colorful
3649
- **429 Too Many Requests** returned when the bucket is empty; body: `{"error": "rate limit exceeded"}`.
3750
- Configured via env vars `RATE_LIMIT_RPS` and `RATE_LIMIT_BURST` (see [environment](environment.md)).
3851

52+
## FirebaseAuth
53+
54+
`FirebaseAuth(verifier usecase.FirebaseTokenVerifier) gin.HandlerFunc` validates a Firebase ID token on every request to the routes it guards.
55+
56+
```go
57+
const FirebaseClaimsKey = "firebase_claims"
58+
59+
func FirebaseAuth(verifier usecase.FirebaseTokenVerifier) gin.HandlerFunc
60+
```
61+
62+
Behaviour:
63+
- Expects `Authorization: Bearer <firebase-id-token>` header.
64+
- Calls `verifier.VerifyIDToken(ctx, idToken)` — the concrete implementation is `pkg/firebase.authClientAdapter`.
65+
- On success: stores `*usecase.FirebaseToken` in the Gin context under `FirebaseClaimsKey` and calls `c.Next()`.
66+
- On failure (missing header, malformed header, or token verification error): aborts with `401 Unauthorized` and a JSON body `{"error": "..."}`.
67+
68+
Retrieve verified claims inside a handler:
69+
```go
70+
val, _ := c.Get(middleware.FirebaseClaimsKey)
71+
token, ok := val.(*usecase.FirebaseToken)
72+
```
73+
74+
Pass `nil` as the `verifier` to `RegisterRoutes` to skip Firebase auth entirely (development without credentials).
75+
3976
## Adding new middleware
4077

4178
1. Create `internal/transport/middleware/<name>.go` with a function returning `gin.HandlerFunc`.

‎backend/docs/observability.md‎

Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
---
2+
topic: observability
3+
last_verified: 2026-06-15
4+
sources:
5+
- internal/transport/middleware/sentry.go
6+
- internal/bootstrap/bootstrap.go
7+
- internal/transport/handlers/routes.go
8+
---
9+
10+
# Observability
11+
12+
## Sentry SDK
13+
14+
| Package | Version |
15+
|---|---|
16+
| `github.com/getsentry/sentry-go` | v0.46.2 |
17+
| `github.com/getsentry/sentry-go/gin` | v0.46.2 |
18+
19+
## SentryMiddleware
20+
21+
`internal/transport/middleware/sentry.go` exports a single function:
22+
23+
```go
24+
func SentryMiddleware(dsn string) gin.HandlerFunc
25+
```
26+
27+
Behavior:
28+
- When `dsn` is empty, returns `func(c *gin.Context) { c.Next() }` — a no-op that adds no overhead.
29+
- When `dsn` is non-empty, calls `sentry.Init(sentry.ClientOptions{Dsn: dsn})` and returns `sentrygin.New(sentrygin.Options{Repanic: true})`.
30+
- `Repanic: true` means the middleware re-panics after capturing, allowing Gin's `Recovery()` to handle the panic response normally.
31+
32+
## Middleware registration order
33+
34+
`RegisterRoutes` in `internal/transport/handlers/routes.go` registers middleware in this order:
35+
36+
1. `SentryMiddleware(sentryDSN)` — first, so it wraps all subsequent handlers
37+
2. `gin.Recovery()` + `gin.Logger()` (debug) or `gin.Recovery()` + `middleware.Logger()` (non-debug)
38+
3. `middleware.RateLimit(rps, burst)`
39+
4. CORS
40+
41+
`RegisterRoutes` signature:
42+
43+
```go
44+
func (h *Handler) RegisterRoutes(rps float64, burst int, verifier usecase.FirebaseTokenVerifier, sentryDSN string) http.Handler
45+
```
46+
47+
The `sentryDSN` parameter is forwarded directly from `Config.SentryDSN`.
48+
49+
## Environment variable
50+
51+
| Variable | Required | Default |
52+
|---|---|---|
53+
| `SENTRY_DSN` | No | `""` (Sentry disabled) |
54+
55+
Loaded in `loadConfig()` in `internal/bootstrap/bootstrap.go`:
56+
57+
```go
58+
SentryDSN: os.Getenv("SENTRY_DSN"),
59+
```
60+
61+
Stored on `Config.SentryDSN`. Not validated — an empty value disables Sentry without error.
62+
63+
## Supplying the DSN
64+
65+
**Local development** — add to `backend/.env`:
66+
```dotenv
67+
SENTRY_DSN=https://<key>@o<org>.ingest.sentry.io/<project>
68+
```
69+
70+
**Production** — set `SENTRY_DSN` as an environment variable in your deployment platform. The app reads it at startup via `godotenv/autoload` (dev) or the process environment (production).
71+
72+
Leave `SENTRY_DSN` empty (or omit it) to run without Sentry. The app starts and serves normally in both cases.

0 commit comments

Comments
 (0)