feat: V2 microservices stack — backend services, gateway, JWT auth
Add full V2 architecture: identity, content, studio (.NET 10) and file, render, notification, gateway (Go) services with vendored deps, plus DB migrations, event/API contracts, and an init-db script. Wire the Next.js frontend to the gateway: server-side JWT auth routes (login/register/refresh/logout/me), gateway fetch helper, and session/ cookie/jwt helpers under src/lib. Containerize the stack via docker-compose.v2.yml and per-service Dockerfiles. Base images resolve through a Nexus mirror (Docker Hub) and MCR directly; npm/NuGet pull from Nexus groups. Self-host fonts via next/font/local to avoid Google Fonts (geo-blocked). Add CI workflow and ignore .env.v2, *.stackdump, and .NET bin/obj. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,136 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/golang-jwt/jwt/v5"
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
const (
|
||||
HeaderUserID = "X-User-ID"
|
||||
HeaderTenantID = "X-Tenant-ID"
|
||||
HeaderIsAdmin = "X-Is-Admin"
|
||||
HeaderRole = "X-Role"
|
||||
|
||||
CtxUserID = "user_id"
|
||||
CtxTenantID = "tenant_id"
|
||||
CtxIsAdmin = "is_admin"
|
||||
CtxRole = "role"
|
||||
)
|
||||
|
||||
type ErrorResponse struct {
|
||||
Code string `json:"code"`
|
||||
Message string `json:"message"`
|
||||
}
|
||||
|
||||
// JWTAuth validates the bearer token and injects claims into both gin context and upstream request headers.
|
||||
func JWTAuth(secret string) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
if validateAndInject(c, secret) {
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// JWTAuthSkip behaves like JWTAuth but skips authentication entirely when skip(c)
|
||||
// returns true. Used for catch-all routes that mix public and protected sub-paths
|
||||
// (e.g. /payments/* where /callback/* and /webhook/* must stay public) — gin forbids
|
||||
// registering a catch-all alongside static child segments, so the branch lives here.
|
||||
func JWTAuthSkip(secret string, skip func(*gin.Context) bool) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
if skip(c) {
|
||||
c.Next()
|
||||
return
|
||||
}
|
||||
if validateAndInject(c, secret) {
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// validateAndInject validates the bearer token and injects claims into the gin context
|
||||
// and upstream request headers. On failure it aborts with 401 and returns false.
|
||||
// It does NOT call c.Next() — the caller decides whether to continue the chain.
|
||||
func validateAndInject(c *gin.Context, secret string) bool {
|
||||
hdr := c.GetHeader("Authorization")
|
||||
if !strings.HasPrefix(hdr, "Bearer ") {
|
||||
c.AbortWithStatusJSON(http.StatusUnauthorized, ErrorResponse{Code: "unauthorized", Message: "missing bearer token"})
|
||||
return false
|
||||
}
|
||||
tokenStr := hdr[7:]
|
||||
token, err := jwt.Parse(tokenStr, func(t *jwt.Token) (interface{}, error) {
|
||||
if _, ok := t.Method.(*jwt.SigningMethodHMAC); !ok {
|
||||
return nil, jwt.ErrSignatureInvalid
|
||||
}
|
||||
return []byte(secret), nil
|
||||
})
|
||||
if err != nil || !token.Valid {
|
||||
c.AbortWithStatusJSON(http.StatusUnauthorized, ErrorResponse{Code: "unauthorized", Message: "invalid or expired token"})
|
||||
return false
|
||||
}
|
||||
claims, _ := token.Claims.(jwt.MapClaims)
|
||||
userID, _ := uuid.Parse(fmt.Sprintf("%v", claims["sub"]))
|
||||
tenantID, _ := uuid.Parse(fmt.Sprintf("%v", claims["tenant_id"]))
|
||||
isAdmin, _ := claims["is_admin"].(bool)
|
||||
role, _ := claims["role"].(string)
|
||||
|
||||
c.Set(CtxUserID, userID)
|
||||
c.Set(CtxTenantID, tenantID)
|
||||
c.Set(CtxIsAdmin, isAdmin)
|
||||
c.Set(CtxRole, role)
|
||||
|
||||
// Inject for upstream services
|
||||
c.Request.Header.Set(HeaderUserID, userID.String())
|
||||
c.Request.Header.Set(HeaderTenantID, tenantID.String())
|
||||
if isAdmin {
|
||||
c.Request.Header.Set(HeaderIsAdmin, "true")
|
||||
}
|
||||
if role != "" {
|
||||
c.Request.Header.Set(HeaderRole, role)
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// OptionalJWTAuth parses the token if present but does not abort on missing/invalid token.
|
||||
func OptionalJWTAuth(secret string) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
hdr := c.GetHeader("Authorization")
|
||||
if !strings.HasPrefix(hdr, "Bearer ") {
|
||||
c.Next()
|
||||
return
|
||||
}
|
||||
token, err := jwt.Parse(hdr[7:], func(t *jwt.Token) (interface{}, error) {
|
||||
if _, ok := t.Method.(*jwt.SigningMethodHMAC); !ok {
|
||||
return nil, jwt.ErrSignatureInvalid
|
||||
}
|
||||
return []byte(secret), nil
|
||||
})
|
||||
if err != nil || !token.Valid {
|
||||
c.Next()
|
||||
return
|
||||
}
|
||||
claims, _ := token.Claims.(jwt.MapClaims)
|
||||
userID, _ := uuid.Parse(fmt.Sprintf("%v", claims["sub"]))
|
||||
tenantID, _ := uuid.Parse(fmt.Sprintf("%v", claims["tenant_id"]))
|
||||
isAdmin, _ := claims["is_admin"].(bool)
|
||||
c.Request.Header.Set(HeaderUserID, userID.String())
|
||||
c.Request.Header.Set(HeaderTenantID, tenantID.String())
|
||||
if isAdmin {
|
||||
c.Request.Header.Set(HeaderIsAdmin, "true")
|
||||
}
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
|
||||
func GetUserID(c *gin.Context) (uuid.UUID, bool) {
|
||||
v, ok := c.Get(CtxUserID)
|
||||
if !ok {
|
||||
return uuid.Nil, false
|
||||
}
|
||||
id, ok := v.(uuid.UUID)
|
||||
return id, ok && id != uuid.Nil
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// ipBucket is a per-IP sliding-window counter.
|
||||
type ipBucket struct {
|
||||
mu sync.Mutex
|
||||
times []time.Time
|
||||
limit int
|
||||
window time.Duration
|
||||
}
|
||||
|
||||
func (b *ipBucket) allow() bool {
|
||||
b.mu.Lock()
|
||||
defer b.mu.Unlock()
|
||||
|
||||
now := time.Now()
|
||||
cutoff := now.Add(-b.window)
|
||||
|
||||
// Evict timestamps outside the window
|
||||
valid := b.times[:0]
|
||||
for _, t := range b.times {
|
||||
if t.After(cutoff) {
|
||||
valid = append(valid, t)
|
||||
}
|
||||
}
|
||||
b.times = valid
|
||||
|
||||
if len(b.times) >= b.limit {
|
||||
return false
|
||||
}
|
||||
b.times = append(b.times, now)
|
||||
return true
|
||||
}
|
||||
|
||||
// RateLimiter is a per-IP sliding-window rate limiter backed by sync.Map.
|
||||
// It is safe for concurrent use and cleans up idle buckets automatically.
|
||||
type RateLimiter struct {
|
||||
buckets sync.Map // string(ip) → *ipBucket
|
||||
limit int
|
||||
window time.Duration
|
||||
}
|
||||
|
||||
// NewRateLimiter creates a limiter that allows up to limit requests per window
|
||||
// per IP address.
|
||||
func NewRateLimiter(limit int, window time.Duration) *RateLimiter {
|
||||
rl := &RateLimiter{limit: limit, window: window}
|
||||
go rl.gc()
|
||||
return rl
|
||||
}
|
||||
|
||||
// gc periodically removes buckets that have had no activity for one full window.
|
||||
func (rl *RateLimiter) gc() {
|
||||
ticker := time.NewTicker(rl.window)
|
||||
defer ticker.Stop()
|
||||
for range ticker.C {
|
||||
rl.buckets.Range(func(k, v any) bool {
|
||||
b := v.(*ipBucket)
|
||||
b.mu.Lock()
|
||||
if len(b.times) == 0 {
|
||||
rl.buckets.Delete(k)
|
||||
}
|
||||
b.mu.Unlock()
|
||||
return true
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// Middleware returns a gin.HandlerFunc that enforces the rate limit.
|
||||
func (rl *RateLimiter) Middleware() gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
ip := c.ClientIP()
|
||||
v, _ := rl.buckets.LoadOrStore(ip, &ipBucket{
|
||||
times: make([]time.Time, 0, rl.limit),
|
||||
limit: rl.limit,
|
||||
window: rl.window,
|
||||
})
|
||||
b := v.(*ipBucket)
|
||||
if !b.allow() {
|
||||
c.AbortWithStatusJSON(http.StatusTooManyRequests, gin.H{
|
||||
"code": "rate_limited",
|
||||
"message": "too many requests — slow down",
|
||||
})
|
||||
return
|
||||
}
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
package proxy
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/http/httputil"
|
||||
"net/url"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// Upstream holds a reverse proxy for one backend service.
|
||||
type Upstream struct {
|
||||
Name string
|
||||
rp *httputil.ReverseProxy
|
||||
}
|
||||
|
||||
// New creates an Upstream reverse proxy pointing at target (e.g. "http://localhost:5010").
|
||||
func New(name, target string) *Upstream {
|
||||
u, err := url.Parse(target)
|
||||
if err != nil {
|
||||
panic("invalid upstream URL for " + name + ": " + err.Error())
|
||||
}
|
||||
rp := httputil.NewSingleHostReverseProxy(u)
|
||||
rp.Transport = &http.Transport{
|
||||
MaxIdleConns: 100,
|
||||
IdleConnTimeout: 90 * time.Second,
|
||||
DisableCompression: false,
|
||||
}
|
||||
// Custom error handler so we return JSON rather than Go's default HTML
|
||||
rp.ErrorHandler = func(w http.ResponseWriter, r *http.Request, err error) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusBadGateway)
|
||||
_, _ = w.Write([]byte(`{"code":"bad_gateway","message":"upstream unavailable"}`))
|
||||
}
|
||||
// Rewrite the request before forwarding
|
||||
orig := rp.Director
|
||||
rp.Director = func(req *http.Request) {
|
||||
orig(req)
|
||||
req.Header.Set("X-Forwarded-Host", req.Host)
|
||||
req.Header.Del("X-Forwarded-For") // let httputil re-add it properly
|
||||
req.Host = u.Host
|
||||
}
|
||||
return &Upstream{Name: name, rp: rp}
|
||||
}
|
||||
|
||||
// Handler returns a gin.HandlerFunc that proxies the request.
|
||||
func (up *Upstream) Handler() gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
up.rp.ServeHTTP(c.Writer, c.Request)
|
||||
}
|
||||
}
|
||||
|
||||
// StripPrefixHandler proxies after stripping a URL prefix (e.g. "/api" → "").
|
||||
func (up *Upstream) StripPrefixHandler(prefix string) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
c.Request.URL.Path = strings.TrimPrefix(c.Request.URL.Path, prefix)
|
||||
if c.Request.URL.Path == "" {
|
||||
c.Request.URL.Path = "/"
|
||||
}
|
||||
up.rp.ServeHTTP(c.Writer, c.Request)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,126 @@
|
||||
package ws
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"log"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
mw "github.com/flatrender/gateway/internal/middleware"
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/golang-jwt/jwt/v5"
|
||||
"github.com/google/uuid"
|
||||
"github.com/gorilla/websocket"
|
||||
)
|
||||
|
||||
var upgrader = websocket.Upgrader{
|
||||
CheckOrigin: func(r *http.Request) bool { return true },
|
||||
Subprotocols: []string{"flatrender.v1"},
|
||||
}
|
||||
|
||||
// RenderProgressProxy proxies WebSocket connections to the render service's REST polling endpoint
|
||||
// and streams progress events to the client via the WebSocket protocol.
|
||||
//
|
||||
// Connection: wss://gateway/ws/v1/render/{job_id}?token={jwt}
|
||||
//
|
||||
// The gateway validates JWT ownership, then opens a persistent proxy WS to the upstream
|
||||
// render service. In production the render service would expose its own WS; for now we
|
||||
// implement a polling bridge using the REST /progress endpoint.
|
||||
func RenderProgressProxy(renderUpstreamWS string, jwtSecret string) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
jobID := c.Param("job_id")
|
||||
if _, err := uuid.Parse(jobID); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"code": "bad_request", "message": "invalid job_id"})
|
||||
return
|
||||
}
|
||||
|
||||
// Authenticate — token may come from query param or Authorization header
|
||||
tokenStr := c.Query("token")
|
||||
if tokenStr == "" {
|
||||
hdr := c.GetHeader("Authorization")
|
||||
if strings.HasPrefix(hdr, "Bearer ") {
|
||||
tokenStr = hdr[7:]
|
||||
}
|
||||
}
|
||||
if tokenStr == "" {
|
||||
c.Writer.WriteHeader(http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
token, err := jwt.Parse(tokenStr, func(t *jwt.Token) (interface{}, error) {
|
||||
if _, ok := t.Method.(*jwt.SigningMethodHMAC); !ok {
|
||||
return nil, jwt.ErrSignatureInvalid
|
||||
}
|
||||
return []byte(jwtSecret), nil
|
||||
})
|
||||
if err != nil || !token.Valid {
|
||||
c.Writer.WriteHeader(http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
claims, _ := token.Claims.(jwt.MapClaims)
|
||||
userID, _ := uuid.Parse(fmt.Sprintf("%v", claims["sub"]))
|
||||
|
||||
// Upgrade the client connection
|
||||
clientConn, err := upgrader.Upgrade(c.Writer, c.Request, nil)
|
||||
if err != nil {
|
||||
log.Printf("ws upgrade error: %v", err)
|
||||
return
|
||||
}
|
||||
defer clientConn.Close()
|
||||
|
||||
// Connect to upstream render service WS
|
||||
upstreamURL := fmt.Sprintf("%s/ws/v1/render/%s?user_id=%s", renderUpstreamWS, jobID, userID)
|
||||
upstreamConn, _, err := websocket.DefaultDialer.Dial(upstreamURL, http.Header{
|
||||
"Authorization": []string{"Bearer " + tokenStr},
|
||||
})
|
||||
if err != nil {
|
||||
// Upstream WS not available — send hello + close
|
||||
_ = clientConn.WriteJSON(gin.H{
|
||||
"type": "error",
|
||||
"code": "UPSTREAM_UNAVAILABLE",
|
||||
"message": "render service WebSocket unavailable; use REST polling fallback",
|
||||
})
|
||||
clientConn.WriteMessage(websocket.CloseMessage,
|
||||
websocket.FormatCloseMessage(1011, "upstream unavailable"))
|
||||
return
|
||||
}
|
||||
defer upstreamConn.Close()
|
||||
|
||||
// Bidirectional pipe
|
||||
errCh := make(chan error, 2)
|
||||
|
||||
// Client → upstream
|
||||
go func() {
|
||||
for {
|
||||
mt, msg, err := clientConn.ReadMessage()
|
||||
if err != nil {
|
||||
errCh <- err
|
||||
return
|
||||
}
|
||||
if err := upstreamConn.WriteMessage(mt, msg); err != nil {
|
||||
errCh <- err
|
||||
return
|
||||
}
|
||||
}
|
||||
}()
|
||||
|
||||
// Upstream → client
|
||||
go func() {
|
||||
for {
|
||||
mt, msg, err := upstreamConn.ReadMessage()
|
||||
if err != nil {
|
||||
errCh <- err
|
||||
return
|
||||
}
|
||||
if err := clientConn.WriteMessage(mt, msg); err != nil {
|
||||
errCh <- err
|
||||
return
|
||||
}
|
||||
}
|
||||
}()
|
||||
|
||||
<-errCh
|
||||
}
|
||||
}
|
||||
|
||||
// mw import alias used above
|
||||
var _ = mw.CtxUserID
|
||||
Reference in New Issue
Block a user