go-guess/backend/internal/web/middleware/TenantSchemaMiddleware.go

81 lines
2.4 KiB
Go
Raw Normal View History

2026-10-01 09:06:58 +02:00
package middleware
import (
"context"
"fmt"
"net/http"
"regexp"
"github.com/danyel/go-guess/backend/internal/golooseauth"
2026-10-02 21:44:26 +02:00
"github.com/danyel/go-loose/client"
2026-10-01 09:06:58 +02:00
"gorm.io/gorm"
)
type contextKey string
const TxKey contextKey = "tenant_db_tx"
// Alphanumeric or underscores only to prevent SQL Injection in schema names
var safeSchemaRegex = regexp.MustCompile(`^[a-zA-Z0-9_:-]+$`)
// TenantSchemaMiddleware isolates database connections per request using PostgreSQL schemas
func TenantSchemaMiddleware(db *gorm.DB, appDomain string) func(http.Handler) http.Handler {
2026-10-01 09:06:58 +02:00
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/api/health" || r.URL.Path == "/api/openapi.json" {
next.ServeHTTP(w, r)
return
}
2026-10-02 21:44:26 +02:00
tenantID := r.Header.Get(client.XTenantId)
2026-10-01 09:06:58 +02:00
if tenantID == "" {
feat: avatar, account menu, and single sign-on from Go Loose Signing in now starts at the sign-in screen and one button that hands the browser to Go Loose, which returns to the welcome page. Nothing redirects to the identity provider on its own any more: that fired on every anonymous visit and read as a redirect loop rather than as a choice to sign in. The password form remains only where the API reports that Go Loose login is not configured for the host, because otherwise the application is unreachable on a bare localhost. A person's picture is carried through from the Go Loose identity and rendered in the account menu and on the profile page, with their initials as the fallback. Two things make that fallback necessary rather than decorative: Go Loose retires a picture key when a picture is replaced, so a link cached in a browser can be dead, and most people have not uploaded one. The URL is deliberately not persisted locally, since a stored key would keep failing after the picture changed. The account menu is a disclosure rather than a hover menu: a real button with aria-expanded, Escape and outside clicks closing it, and focus returning to the trigger. It is not an ARIA menu, because its actions are a link and a button and menuitem roles would strip the link semantics from one of them for no gain. The account URL of the Go Loose identity is resolved on each sign-in and is read from the live identity provider every time, which is also what makes it correct after a picture change. Depends on the Go Loose revision that serves avatar_url through /connect/userinfo, so the picture URL reaches this application at all.
2026-10-05 21:50:06 +02:00
tenantID = golooseauth.TenantFromHost(golooseauth.Host(r), appDomain)
}
if tenantID == "" || db == nil {
next.ServeHTTP(w, r)
2026-10-01 09:06:58 +02:00
return
}
// Validate schema name to guarantee safety against SQL injection
if !safeSchemaRegex.MatchString(tenantID) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusBadRequest)
_, _ = w.Write([]byte(`{"error": "Invalid characters in tenant ID"}`))
return
}
// Start a fresh transaction scoped exclusively to this HTTP request
tx := db.Begin()
// Set the local search_path for the duration of this transaction block
if err := tx.Exec(fmt.Sprintf("SET LOCAL search_path TO %s", tenantID)).Error; err != nil {
tx.Rollback()
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusInternalServerError)
_, _ = w.Write([]byte(`{"error": "Failed to resolve tenant storage isolation"}`))
return
}
// Embed the transaction database instance into the request context
ctx := context.WithValue(r.Context(), TxKey, tx)
// Execute the subsequent request handlers
next.ServeHTTP(w, r.WithContext(ctx))
// Commit or Rollback based on the transaction error status
if tx.Error != nil {
tx.Rollback()
} else {
tx.Commit()
}
})
}
}
// GetDB retrieves the transaction-bound tenant GORM DB instance from context
func GetDB(ctx context.Context) *gorm.DB {
if tx, ok := ctx.Value(TxKey).(*gorm.DB); ok {
return tx.WithContext(ctx)
}
panic("GetDB was invoked outside of TenantSchemaMiddleware")
}