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

@ -19,6 +19,7 @@ import (
"github.com/danyel/go-guess/backend/internal/database/repository"
"github.com/danyel/go-guess/backend/internal/eventbus"
"github.com/danyel/go-guess/backend/internal/golooseauth"
"github.com/danyel/go-guess/backend/internal/security"
"github.com/danyel/go-guess/backend/internal/service"
servicemodel "github.com/danyel/go-guess/backend/internal/service/model"
@ -37,6 +38,7 @@ type Handler struct {
interviews service.IScheduledInterviewService
maxUpload int64
frontendURL string
browser *golooseauth.Registry
}
func New(
@ -651,7 +653,8 @@ func (h *Handler) frontendURLForRequest(r *http.Request) string {
if err != nil || (parsed.Scheme != "http" && parsed.Scheme != "https") {
return h.frontendURL
}
if strings.EqualFold(parsed.Hostname(), tenant+".guess.local") {
if strings.EqualFold(parsed.Hostname(), tenant+".guess.local") ||
strings.EqualFold(parsed.Hostname(), tenant+".guess.dev") {
return origin
}
return h.frontendURL

View file

@ -28,3 +28,14 @@ func TestFrontendURLRejectsDifferentTenantOrigin(t *testing.T) {
t.Fatalf("expected configured frontend URL, got %q", value)
}
}
func TestFrontendURLAcceptsDevTenantOrigin(t *testing.T) {
handler := &Handler{frontendURL: "http://localhost:5173"}
request := httptest.NewRequest("GET", "/api/jobs/2/invitations", nil)
request.Header.Set("Origin", "https://ypto.guess.dev")
request.Header.Set(client.XTenantId, "ypto")
if value := handler.frontendURLForRequest(request); value != "https://ypto.guess.dev" {
t.Fatalf("expected tenant dev origin, got %q", value)
}
}

View file

@ -0,0 +1,92 @@
package handler
import (
"errors"
"net/http"
goloose "github.com/danyel/go-loose/client"
"github.com/danyel/go-guess/backend/internal/golooseauth"
webmapper "github.com/danyel/go-guess/backend/internal/web/mapper"
webmodel "github.com/danyel/go-guess/backend/internal/web/model"
)
var (
errMissingSession = errors.New("missing Go Loose session")
errTenantMismatch = errors.New("Go Loose session does not match this tenant")
)
func (h *Handler) SetBrowserAuth(auth *golooseauth.Registry) {
h.browser = auth
}
func (h *Handler) AppDomain() string {
if h.browser == nil {
return "guess.dev"
}
return h.browser.AppDomain()
}
func (h *Handler) BeginExternalLogin(w http.ResponseWriter, r *http.Request) {
auth, ok := h.externalAuth(r)
if !ok {
http.NotFound(w, r)
return
}
auth.LoginHandler(w, r)
}
func (h *Handler) CompleteExternalLogin(w http.ResponseWriter, r *http.Request) {
auth, ok := h.externalAuth(r)
if !ok {
http.NotFound(w, r)
return
}
auth.CallbackHandler(w, r)
}
func (h *Handler) ExternalLogout(w http.ResponseWriter, r *http.Request) {
auth, ok := h.externalAuth(r)
if !ok {
http.NotFound(w, r)
return
}
auth.LogoutHandler(w, r)
}
func (h *Handler) ExternalSession(w http.ResponseWriter, r *http.Request) {
auth, slug, ok := h.externalAuthWithSlug(r)
if !ok {
http.NotFound(w, r)
return
}
if _, err := r.Cookie(golooseauth.SessionCookie); err != nil {
writeError(w, http.StatusUnauthorized, errMissingSession)
return
}
auth.Middleware(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
user, ok := goloose.UserFromContext(r.Context())
if !ok || user.TenantSlug != slug {
writeError(w, http.StatusForbidden, errTenantMismatch)
return
}
token, local, err := h.auth.EstablishExternalSession(r.Context(), user.Email, user.DisplayName)
if err != nil {
internalError(w, r, err)
return
}
writeJSON(w, http.StatusOK, webmodel.LoginResponse{Token: token, User: webmapper.UserToWeb(local)})
})).ServeHTTP(w, r)
}
func (h *Handler) externalAuth(r *http.Request) (*goloose.BrowserAuth, bool) {
auth, _, ok := h.externalAuthWithSlug(r)
return auth, ok
}
func (h *Handler) externalAuthWithSlug(r *http.Request) (*goloose.BrowserAuth, string, bool) {
if h.browser == nil {
return nil, "", false
}
return h.browser.ForHost(r.Host)
}

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)
}
}

View file

@ -89,7 +89,6 @@ func (b *Builder) Add(method, path string, operation Operation) {
}
if operation.Protected {
value["security"] = []map[string][]string{{
"apiKeyAuth": {},
"bearerAuth": {},
}}
}
@ -131,7 +130,6 @@ func (b *Builder) Document() map[string]any {
"paths": b.paths,
"components": map[string]any{
"securitySchemes": map[string]any{
"apiKeyAuth": map[string]any{"type": "apiKey", "in": "header", "name": client.DefaultHeader},
"bearerAuth": map[string]any{"type": "http", "scheme": "bearer", "bearerFormat": "JWT"},
},
"schemas": b.schemas,

View file

@ -22,12 +22,22 @@ func New(h *handler.Handler, tokens security.ITokenManager, frontendURL string)
spec := openapi.New()
router.Use(middleware.RequestID, middleware.RealIP, middleware.Recoverer, middleware.Compress(5))
router.Use(cors(frontendURL))
router.Use(mw.TenantSchemaMiddleware(h.Db()))
router.Use(mw.TenantSchemaMiddleware(h.Db(), h.AppDomain()))
router.Use(middleware.Timeout(2 * time.Minute))
register(router, spec, false, http.MethodGet, "/api/openapi.json", spec.ServeHTTP,
openapi.Operation{Summary: "Get the current OpenAPI contract", Response: map[string]any{}, NoTenant: true})
register(router, spec, false, http.MethodGet, "/api/health", h.Health,
openapi.Operation{Summary: "Check API health", Response: map[string]string{}, NoTenant: true})
register(router, spec, false, http.MethodGet, "/api/auth/login", h.BeginExternalLogin,
openapi.Operation{Summary: "Start Go Loose browser authentication", NoTenant: true})
register(router, spec, false, http.MethodGet, "/api/auth/callback", h.CompleteExternalLogin,
openapi.Operation{Summary: "Complete Go Loose browser authentication", NoTenant: true})
register(router, spec, false, http.MethodGet, "/api/auth/logout", h.ExternalLogout,
openapi.Operation{Summary: "End the Go Loose browser session", NoTenant: true})
register(router, spec, false, http.MethodPost, "/api/auth/logout", h.ExternalLogout,
openapi.Operation{Summary: "End the Go Loose browser session", NoTenant: true})
register(router, spec, false, http.MethodGet, "/api/auth/session", h.ExternalSession,
openapi.Operation{Summary: "Exchange a Go Loose browser session for an API token", Response: webmodel.LoginResponse{}, NoTenant: true})
register(router, spec, false, http.MethodPost, "/api/auth/login", h.Login,
openapi.Operation{Summary: "Authenticate an interviewer", Request: webmodel.LoginRequest{}, Response: webmodel.LoginResponse{}})
register(router, spec, false, http.MethodGet, "/api/interviews/{token}", h.GetInterview,
@ -43,7 +53,6 @@ func New(h *handler.Handler, tokens security.ITokenManager, frontendURL string)
register(router, spec, false, http.MethodGet, "/api/participant-meetings/{token}/events", h.ParticipantMeetingEvents,
openapi.Operation{Summary: "Stream participant meeting events", Response: eventbus.InterviewEvent{}, ResponseContentType: "text/event-stream"})
router.Group(func(protected chi.Router) {
protected.Use(mw.GoLooseMiddleware())
protected.Use(authenticate(tokens))
register(protected, spec, true, http.MethodGet, "/api/jobs", h.ListJobs,
openapi.Operation{Summary: "List job postings", Response: []webmodel.JobResponse{}})

View file

@ -9,10 +9,13 @@ import (
"io"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
"github.com/danyel/go-guess/backend/internal/config"
"github.com/danyel/go-guess/backend/internal/eventbus"
"github.com/danyel/go-guess/backend/internal/golooseauth"
"github.com/danyel/go-guess/backend/internal/security"
"github.com/danyel/go-guess/backend/internal/service"
"github.com/danyel/go-guess/backend/internal/service/model"
@ -24,7 +27,6 @@ import (
const (
testTenant = "ypto"
testAPIKey = "gl_test_key_that_is_long_enough_for_client"
)
func init() {
@ -45,16 +47,6 @@ func openStubDB(t *testing.T) *gorm.DB {
return db
}
func allowGoLoose(t *testing.T) {
t.Helper()
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(`{"allowed":true,"tenant_slug":"ypto","application_slug":"guess","api_key_name":"guess"}`))
}))
t.Cleanup(server.Close)
t.Setenv("GO_LOOSE_BASE_URL", server.URL)
}
func newTestHandler(t *testing.T, interviews service.IScheduledInterviewService) *handler.Handler {
t.Helper()
if interviews == nil {
@ -71,16 +63,16 @@ func withTenant(request *http.Request) {
request.Header.Set(client.XTenantId, testTenant)
}
func withAPIKey(request *http.Request) {
request.Header.Set(client.DefaultHeader, testAPIKey)
}
type authStub struct{}
func (authStub) Login(context.Context, string, string) (string, model.User, error) {
return "", model.User{}, service.ErrInvalidCredentials
}
func (authStub) EstablishExternalSession(context.Context, string, string) (string, model.User, error) {
return "", model.User{}, service.ErrInvalidCredentials
}
type jobStub struct{}
func (jobStub) List(context.Context) ([]model.JobPosting, error) { return []model.JobPosting{}, nil }
@ -237,13 +229,11 @@ func TestHealthDoesNotRequireAuthentication(t *testing.T) {
}
func TestProtectedRouteRequiresValidToken(t *testing.T) {
allowGoLoose(t)
tokens := security.NewTokenManager("01234567890123456789012345678901", time.Hour)
router := New(newTestHandler(t, nil), tokens, "http://localhost:5173")
unauthorizedRequest := httptest.NewRequest(http.MethodGet, "/api/jobs", nil)
withTenant(unauthorizedRequest)
withAPIKey(unauthorizedRequest)
unauthorized := httptest.NewRecorder()
router.ServeHTTP(unauthorized, unauthorizedRequest)
if unauthorized.Code != http.StatusUnauthorized || unauthorized.Header().Get("Content-Type") != "application/json" {
@ -255,7 +245,6 @@ func TestProtectedRouteRequiresValidToken(t *testing.T) {
}
request := httptest.NewRequest(http.MethodGet, "/api/jobs", nil)
withTenant(request)
withAPIKey(request)
request.Header.Set("Authorization", "Bearer "+token)
authorized := httptest.NewRecorder()
router.ServeHTTP(authorized, request)
@ -265,7 +254,6 @@ func TestProtectedRouteRequiresValidToken(t *testing.T) {
}
func TestProtectedInterviewUsesAuthenticatedUserID(t *testing.T) {
allowGoLoose(t)
interviews := &interviewCapture{}
tokens := security.NewTokenManager("01234567890123456789012345678901", time.Hour)
api := New(newTestHandler(t, interviews), tokens, "http://localhost:5173")
@ -275,7 +263,6 @@ func TestProtectedInterviewUsesAuthenticatedUserID(t *testing.T) {
}
request := httptest.NewRequest(http.MethodGet, "/api/scheduled-interviews/9", nil)
withTenant(request)
withAPIKey(request)
request.Header.Set("Authorization", "Bearer "+token)
response := httptest.NewRecorder()
api.ServeHTTP(response, request)
@ -310,6 +297,50 @@ func TestParticipantMeetingDoesNotExposeInternalCandidateData(t *testing.T) {
}
}
func TestOpenAPIDoesNotRequireTenant(t *testing.T) {
api := New(
newTestHandler(t, nil),
security.NewTokenManager("01234567890123456789012345678901", time.Hour),
"http://localhost:5173",
)
response := httptest.NewRecorder()
api.ServeHTTP(response, httptest.NewRequest(http.MethodGet, "/api/openapi.json", nil))
if response.Code != http.StatusOK || !bytes.Contains(response.Body.Bytes(), []byte(`"openapi"`)) {
t.Fatalf("expected OpenAPI document, got %d %s", response.Code, response.Body.Bytes())
}
}
func TestTenantHostLoginRedirectsToMatchingGoLooseClient(t *testing.T) {
h := newTestHandler(t, nil)
browser, err := golooseauth.New(config.GoLooseConfig{
AuthDomain: "auth.dev",
AppDomain: "guess.dev",
Tenants: map[string]config.GoLooseTenant{
"nmbs": {ClientID: "glc_nmbs", ClientSecret: "secret"},
"ypto": {ClientID: "glc_ypto", ClientSecret: "secret"},
},
})
if err != nil {
t.Fatal(err)
}
h.SetBrowserAuth(browser)
api := New(h, security.NewTokenManager("01234567890123456789012345678901", time.Hour), "http://localhost:5173")
for _, slug := range []string{"nmbs", "ypto"} {
request := httptest.NewRequest(http.MethodGet, "/api/auth/login", nil)
request.Host = slug + ".guess.dev"
response := httptest.NewRecorder()
api.ServeHTTP(response, request)
location := response.Header().Get("Location")
if response.Code != http.StatusFound || !strings.HasPrefix(location, "https://"+slug+".auth.dev/connect/authorize?") {
t.Fatalf("%s login redirect = %d %s", slug, response.Code, location)
}
if !strings.Contains(location, "redirect_uri=https%3A%2F%2F"+slug+".guess.dev%2Fapi%2Fauth%2Fcallback") {
t.Fatalf("%s callback missing from %s", slug, location)
}
}
}
type stubDriver struct{}
func (stubDriver) Open(string) (driver.Conn, error) { return stubConn{}, nil }