feat: integrate tenant SSO and remote toggle

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
This commit is contained in:
Daniel Noulet 2026-10-03 00:14:23 +02:00
parent 660d5291ec
commit ca5765b988
27 changed files with 529 additions and 159 deletions

View file

@ -6,6 +6,7 @@ import (
"net/http"
"regexp"
"github.com/danyel/go-guess/backend/internal/golooseauth"
"github.com/danyel/go-loose/client"
"gorm.io/gorm"
)
@ -18,7 +19,7 @@ const TxKey contextKey = "tenant_db_tx"
var safeSchemaRegex = regexp.MustCompile(`^[a-zA-Z0-9_:-]+$`)
// TenantSchemaMiddleware isolates database connections per request using PostgreSQL schemas
func TenantSchemaMiddleware(db *gorm.DB) func(http.Handler) http.Handler {
func TenantSchemaMiddleware(db *gorm.DB, appDomain string) func(http.Handler) http.Handler {
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" {
@ -27,9 +28,10 @@ func TenantSchemaMiddleware(db *gorm.DB) func(http.Handler) http.Handler {
}
tenantID := r.Header.Get(client.XTenantId)
if tenantID == "" {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusBadRequest)
_, _ = w.Write([]byte(`{"error": "Missing X-Tenant-Id header"}`))
tenantID = golooseauth.TenantFromHost(r.Host, appDomain)
}
if tenantID == "" || db == nil {
next.ServeHTTP(w, r)
return
}

View file

@ -10,7 +10,7 @@ func TestTenantMiddlewareAllowsSystemEndpointsWithoutTenant(t *testing.T) {
next := http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(http.StatusOK)
})
handler := TenantSchemaMiddleware(nil)(next)
handler := TenantSchemaMiddleware(nil, "guess.dev")(next)
for _, path := range []string{"/api/health", "/api/openapi.json"} {
response := httptest.NewRecorder()
@ -21,15 +21,15 @@ func TestTenantMiddlewareAllowsSystemEndpointsWithoutTenant(t *testing.T) {
}
}
func TestTenantMiddlewareStillRequiresTenantForDataEndpoints(t *testing.T) {
handler := TenantSchemaMiddleware(nil)(http.HandlerFunc(func(http.ResponseWriter, *http.Request) {
t.Fatal("data endpoint reached without a tenant")
func TestTenantMiddlewareUsesPublicSchemaWithoutTenant(t *testing.T) {
handler := TenantSchemaMiddleware(nil, "guess.dev")(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(http.StatusOK)
}))
response := httptest.NewRecorder()
handler.ServeHTTP(response, httptest.NewRequest(http.MethodGet, "/api/jobs", nil))
if response.Code != http.StatusBadRequest {
t.Fatalf("expected 400, got %d", response.Code)
if response.Code != http.StatusOK {
t.Fatalf("expected 200, got %d", response.Code)
}
}