Files
warmbly/internal/api/middleware/internal_auth.go
Matthew Meszaros 99226338c9 infra(encryptedkeys): pluggable DEK store with HTTP proxy for workers
New encryptedkeys.Store interface with three impls:

  postgres  - backend default, durable via PG
  dynamodb  - existing AWS path, also covers Scylla Alternator via
              AWS_ENDPOINT_URL_DYNAMODB
  http      - worker-side adapter that talks to the backend's new
              /api/v1/internal/dek/:userID endpoint, so workers never
              connect directly to Postgres

The HTTP endpoint sits behind a new InternalAuthMiddleware that does
constant-time bearer-token compare against INTERNAL_API_TOKEN. Fail-
closed if the env var is unset.

cipher.Service now takes an encryptedkeys.Store instead of a Dynamo
repository. The old internal/repository/dynamo_user_encrypted_keys.go
is deleted (the file also had a pre-existing copy-paste bug using
EmailMessageMapTable in Get/Del that's gone with it).

New migration 38 adds user_encrypted_keys (user_id PK, encrypted_data_key,
created_at, updated_at).

20 tests cover HTTP round-trip, conflict semantics, factory selection,
middleware auth (fail-closed / wrong-scheme / timing-safe / happy path),
and DEK handler responses through gin's test harness.
2026-05-27 14:42:11 +00:00

55 lines
1.5 KiB
Go

package middleware
import (
"crypto/subtle"
"net/http"
"os"
"strings"
"sync"
"github.com/gin-gonic/gin"
)
// InternalAuthMiddleware protects backend-to-backend endpoints (the worker DEK
// fetch is the first user) with a static bearer token sourced from the
// INTERNAL_API_TOKEN env var. Constant-time compare to defeat timing oracles.
//
// This is a deliberately simple primitive — workers and backend share one
// secret out-of-band (env var in both processes). Task #9 will replace this
// with per-worker JWTs minted at registration time.
//
// If INTERNAL_API_TOKEN is unset, every request is rejected — fail closed.
func (h *Handler) InternalAuthMiddleware() gin.HandlerFunc {
return internalAuth
}
var (
internalTokenOnce sync.Once
internalToken []byte
)
func loadInternalToken() {
if v := os.Getenv("INTERNAL_API_TOKEN"); v != "" {
internalToken = []byte(v)
}
}
func internalAuth(c *gin.Context) {
internalTokenOnce.Do(loadInternalToken)
if len(internalToken) == 0 {
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "internal auth not configured"})
return
}
header := c.GetHeader("Authorization")
if !strings.HasPrefix(header, "Bearer ") {
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "missing bearer token"})
return
}
provided := []byte(strings.TrimPrefix(header, "Bearer "))
if subtle.ConstantTimeCompare(provided, internalToken) != 1 {
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "invalid bearer token"})
return
}
c.Next()
}