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.
This commit is contained in:
parent
6be21597d5
commit
5449cd3d8d
52 changed files with 1927 additions and 434 deletions
|
|
@ -653,8 +653,10 @@ 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") ||
|
||||
strings.EqualFold(parsed.Hostname(), tenant+".guess.dev") {
|
||||
// Only trust the Origin when it is the browser origin of the requesting
|
||||
// tenant, so an invitation link cannot be pointed at another host.
|
||||
if strings.EqualFold(parsed.Hostname(), tenant+"."+h.AppDomain()) ||
|
||||
strings.EqualFold(parsed.Hostname(), tenant+".guess.local") {
|
||||
return origin
|
||||
}
|
||||
return h.frontendURL
|
||||
|
|
|
|||
|
|
@ -1,17 +1,22 @@
|
|||
package handler
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"github.com/danyel/go-loose/client"
|
||||
"github.com/danyel/go-guess/backend/internal/config"
|
||||
"github.com/danyel/go-guess/backend/internal/golooseauth"
|
||||
servicemodel "github.com/danyel/go-guess/backend/internal/service/model"
|
||||
webmapper "github.com/danyel/go-guess/backend/internal/web/mapper"
|
||||
goloose "github.com/danyel/go-loose/client"
|
||||
)
|
||||
|
||||
func TestFrontendURLForTenantRequest(t *testing.T) {
|
||||
handler := &Handler{frontendURL: "http://localhost:5173"}
|
||||
request := httptest.NewRequest("GET", "/api/jobs/2/invitations", nil)
|
||||
request.Header.Set("Origin", "http://ypto.guess.local:5173")
|
||||
request.Header.Set(client.XTenantId, "ypto")
|
||||
request.Header.Set(goloose.XTenantId, "ypto")
|
||||
|
||||
if value := handler.frontendURLForRequest(request); value != "http://ypto.guess.local:5173" {
|
||||
t.Fatalf("unexpected frontend URL %q", value)
|
||||
|
|
@ -22,7 +27,7 @@ func TestFrontendURLRejectsDifferentTenantOrigin(t *testing.T) {
|
|||
handler := &Handler{frontendURL: "http://localhost:5173"}
|
||||
request := httptest.NewRequest("GET", "/api/jobs/2/invitations", nil)
|
||||
request.Header.Set("Origin", "http://nmbs.guess.local:5173")
|
||||
request.Header.Set(client.XTenantId, "ypto")
|
||||
request.Header.Set(goloose.XTenantId, "ypto")
|
||||
|
||||
if value := handler.frontendURLForRequest(request); value != handler.frontendURL {
|
||||
t.Fatalf("expected configured frontend URL, got %q", value)
|
||||
|
|
@ -32,10 +37,87 @@ func TestFrontendURLRejectsDifferentTenantOrigin(t *testing.T) {
|
|||
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")
|
||||
request.Header.Set("Origin", "https://ypto."+config.DefaultAppDomain)
|
||||
request.Header.Set(goloose.XTenantId, "ypto")
|
||||
|
||||
if value := handler.frontendURLForRequest(request); value != "https://ypto.guess.dev" {
|
||||
if value := handler.frontendURLForRequest(request); value != "https://ypto."+config.DefaultAppDomain {
|
||||
t.Fatalf("expected tenant dev origin, got %q", value)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFrontendURLAcceptsConfiguredProductionDomain(t *testing.T) {
|
||||
browser, err := golooseauth.New(config.GoLooseConfig{
|
||||
AuthDomain: config.DefaultProdAuthDomain,
|
||||
AppDomain: config.DefaultProdAppDomain,
|
||||
Tenants: map[string]config.GoLooseTenant{
|
||||
"nmbs": {ClientID: "glc_nmbs", ClientSecret: "secret"},
|
||||
},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
handler := &Handler{frontendURL: "https://nmbs.guess.urpi.be"}
|
||||
handler.SetBrowserAuth(browser)
|
||||
|
||||
request := httptest.NewRequest("GET", "/api/jobs/2/invitations", nil)
|
||||
request.Header.Set("Origin", "https://nmbs."+config.DefaultProdAppDomain)
|
||||
request.Header.Set(goloose.XTenantId, "nmbs")
|
||||
if value := handler.frontendURLForRequest(request); value != "https://nmbs."+config.DefaultProdAppDomain {
|
||||
t.Fatalf("expected tenant production origin, got %q", value)
|
||||
}
|
||||
|
||||
// The development domain is not the configured app domain in production.
|
||||
request = httptest.NewRequest("GET", "/api/jobs/2/invitations", nil)
|
||||
request.Header.Set("Origin", "https://nmbs."+config.DefaultAppDomain)
|
||||
request.Header.Set(goloose.XTenantId, "nmbs")
|
||||
if value := handler.frontendURLForRequest(request); value != handler.frontendURL {
|
||||
t.Fatalf("expected configured frontend URL, got %q", value)
|
||||
}
|
||||
}
|
||||
|
||||
// TestExternalIdentityCarriesThePicture pins that the picture Go Loose serves is
|
||||
// handed to the service and ends up in the session payload. The URL is resolved on
|
||||
// every sign-in rather than stored, so it must survive the whole way through
|
||||
// rather than being dropped at the first boundary.
|
||||
func TestExternalIdentityCarriesThePicture(t *testing.T) {
|
||||
identity := externalIdentity(goloose.User{
|
||||
Email: "ada@example.test",
|
||||
DisplayName: "Ada Lovelace",
|
||||
AvatarURL: "https://auth.example.test/api/v1/avatars/kZ3abc",
|
||||
Role: "developer",
|
||||
})
|
||||
if identity.Email != "ada@example.test" {
|
||||
t.Errorf("email = %q", identity.Email)
|
||||
}
|
||||
if identity.DisplayName != "Ada Lovelace" {
|
||||
t.Errorf("display name = %q", identity.DisplayName)
|
||||
}
|
||||
if identity.AvatarURL != "https://auth.example.test/api/v1/avatars/kZ3abc" {
|
||||
t.Errorf("avatar URL = %q", identity.AvatarURL)
|
||||
}
|
||||
|
||||
// A person without a picture yields an empty URL rather than a broken one, so
|
||||
// the frontend can fall back to initials.
|
||||
without := externalIdentity(goloose.User{Email: "bob@example.test"})
|
||||
if without.AvatarURL != "" {
|
||||
t.Errorf("avatar URL = %q, want empty", without.AvatarURL)
|
||||
}
|
||||
}
|
||||
|
||||
// TestUserToWebIncludesTheAvatar pins the JSON field name the frontend reads.
|
||||
func TestUserToWebIncludesTheAvatar(t *testing.T) {
|
||||
encoded, err := json.Marshal(webmapper.UserToWeb(servicemodel.User{
|
||||
ID: 7, Email: "ada@example.test", DisplayName: "Ada", Role: "interviewer",
|
||||
AvatarURL: "https://auth.example.test/api/v1/avatars/kZ3abc",
|
||||
}))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var payload map[string]any
|
||||
if err := json.Unmarshal(encoded, &payload); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if payload["avatarUrl"] != "https://auth.example.test/api/v1/avatars/kZ3abc" {
|
||||
t.Errorf("avatarUrl = %v, payload %s", payload["avatarUrl"], encoded)
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -9,6 +9,7 @@ import (
|
|||
|
||||
"github.com/danyel/go-guess/backend/internal/config"
|
||||
"github.com/danyel/go-guess/backend/internal/golooseauth"
|
||||
"github.com/danyel/go-guess/backend/internal/service"
|
||||
webmapper "github.com/danyel/go-guess/backend/internal/web/mapper"
|
||||
webmodel "github.com/danyel/go-guess/backend/internal/web/model"
|
||||
)
|
||||
|
|
@ -26,7 +27,7 @@ func (h *Handler) SetBrowserAuth(auth *golooseauth.Registry) {
|
|||
|
||||
func (h *Handler) AppDomain() string {
|
||||
if h.browser == nil {
|
||||
return "guess.dev"
|
||||
return config.DefaultAppDomain
|
||||
}
|
||||
return h.browser.AppDomain()
|
||||
}
|
||||
|
|
@ -74,7 +75,7 @@ func (h *Handler) ExternalSession(w http.ResponseWriter, r *http.Request) {
|
|||
writeError(w, http.StatusForbidden, errTenantMismatch)
|
||||
return
|
||||
}
|
||||
token, local, err := h.auth.EstablishExternalSession(r.Context(), user.Email, user.DisplayName)
|
||||
token, local, err := h.auth.EstablishExternalSession(r.Context(), externalIdentity(user))
|
||||
if err != nil {
|
||||
internalError(w, r, err)
|
||||
return
|
||||
|
|
@ -83,6 +84,17 @@ func (h *Handler) ExternalSession(w http.ResponseWriter, r *http.Request) {
|
|||
})).ServeHTTP(w, r)
|
||||
}
|
||||
|
||||
// externalIdentity is what Go Loose reports about the person signing in. The
|
||||
// picture URL is carried through rather than looked up: Go Loose serves it
|
||||
// publicly, so the browser can render it without another round trip.
|
||||
func externalIdentity(user goloose.User) service.ExternalIdentity {
|
||||
return service.ExternalIdentity{
|
||||
Email: user.Email,
|
||||
DisplayName: user.DisplayName,
|
||||
AvatarURL: user.AvatarURL,
|
||||
}
|
||||
}
|
||||
|
||||
func (h *Handler) externalAuth(r *http.Request) (*goloose.BrowserAuth, bool) {
|
||||
auth, _, ok := h.externalAuthWithSlug(r)
|
||||
return auth, ok
|
||||
|
|
@ -92,7 +104,7 @@ func (h *Handler) externalAuthWithSlug(r *http.Request) (*goloose.BrowserAuth, s
|
|||
if h.browser == nil {
|
||||
return nil, "", false
|
||||
}
|
||||
return h.browser.ForHost(r.Host)
|
||||
return h.browser.ForHost(golooseauth.Host(r))
|
||||
}
|
||||
|
||||
func writeExternalAuthError(w http.ResponseWriter, h *Handler, slug string) {
|
||||
|
|
|
|||
|
|
@ -94,6 +94,7 @@ func InvitationToWeb(value servicemodel.Invitation, frontendURL string) webmodel
|
|||
func UserToWeb(value servicemodel.User) webmodel.User {
|
||||
return webmodel.User{
|
||||
ID: value.ID, Email: value.Email, DisplayName: value.DisplayName, Role: value.Role,
|
||||
AvatarURL: value.AvatarURL,
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -11,11 +11,18 @@ import (
|
|||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/danyel/go-guess/backend/internal/config"
|
||||
"github.com/danyel/go-loose/client"
|
||||
)
|
||||
|
||||
const guessApplication = "guess"
|
||||
|
||||
// defaultBaseURLPattern is the Go Loose identity domain used when
|
||||
// GO_LOOSE_BASE_URL is unset.
|
||||
func defaultBaseURLPattern() string {
|
||||
return "https://%s." + config.DefaultAuthDomain
|
||||
}
|
||||
|
||||
// A tenant used in the Go Loose host must be one DNS label.
|
||||
var safeTenantLabel = regexp.MustCompile(`^[A-Za-z0-9](?:[A-Za-z0-9_-]{0,62})?$`)
|
||||
|
||||
|
|
@ -23,11 +30,12 @@ var safeTenantLabel = regexp.MustCompile(`^[A-Za-z0-9](?:[A-Za-z0-9_-]{0,62})?$`
|
|||
// from the X-Tenant-Id header, not from process configuration.
|
||||
//
|
||||
// GO_LOOSE_BASE_URL may contain one %s placeholder for that tenant. The
|
||||
// default is https://%s.auth.dev. A URL without %s is used as-is.
|
||||
// default is the development identity domain, https://%s.auth-dev.urpi.be.
|
||||
// A URL without %s is used as-is.
|
||||
func GoLooseMiddleware() func(http.Handler) http.Handler {
|
||||
pattern := os.Getenv("GO_LOOSE_BASE_URL")
|
||||
if pattern == "" {
|
||||
pattern = "https://%s.auth.dev"
|
||||
pattern = defaultBaseURLPattern()
|
||||
}
|
||||
httpClient := &http.Client{Timeout: 2 * time.Second}
|
||||
var (
|
||||
|
|
|
|||
|
|
@ -7,6 +7,7 @@ import (
|
|||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"github.com/danyel/go-guess/backend/internal/config"
|
||||
"github.com/danyel/go-loose/client"
|
||||
)
|
||||
|
||||
|
|
@ -79,8 +80,22 @@ func TestGoLooseMiddlewareRejectsMissingTenantAndKey(t *testing.T) {
|
|||
}
|
||||
}
|
||||
|
||||
func TestGoLooseMiddlewareDefaultsToTheDevelopmentIdentityDomain(t *testing.T) {
|
||||
t.Setenv("GO_LOOSE_BASE_URL", "")
|
||||
baseURL, err := goLooseBaseURL(defaultBaseURLPattern(), "nmbs")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if baseURL != "https://nmbs."+config.DefaultAuthDomain {
|
||||
t.Fatalf("default base URL = %q", baseURL)
|
||||
}
|
||||
if defaultBaseURLPattern() != "https://%s.auth-dev.urpi.be" {
|
||||
t.Fatalf("default pattern = %q", defaultBaseURLPattern())
|
||||
}
|
||||
}
|
||||
|
||||
func TestGoLooseMiddlewareRejectsUnsafeTenantInHost(t *testing.T) {
|
||||
t.Setenv("GO_LOOSE_BASE_URL", "https://%s.auth.dev")
|
||||
t.Setenv("GO_LOOSE_BASE_URL", "https://%s.auth-dev.urpi.be")
|
||||
handler := GoLooseMiddleware()(http.HandlerFunc(func(http.ResponseWriter, *http.Request) {
|
||||
t.Fatal("handler reached for unsafe tenant")
|
||||
}))
|
||||
|
|
|
|||
|
|
@ -28,7 +28,7 @@ func TenantSchemaMiddleware(db *gorm.DB, appDomain string) func(http.Handler) ht
|
|||
}
|
||||
tenantID := r.Header.Get(client.XTenantId)
|
||||
if tenantID == "" {
|
||||
tenantID = golooseauth.TenantFromHost(r.Host, appDomain)
|
||||
tenantID = golooseauth.TenantFromHost(golooseauth.Host(r), appDomain)
|
||||
}
|
||||
if tenantID == "" || db == nil {
|
||||
next.ServeHTTP(w, r)
|
||||
|
|
|
|||
|
|
@ -21,6 +21,9 @@ type User struct {
|
|||
Email string `json:"email"`
|
||||
DisplayName string `json:"displayName"`
|
||||
Role string `json:"role"`
|
||||
// AvatarURL is an absolute, publicly fetchable picture URL served by Go Loose,
|
||||
// or an empty string when the person has not uploaded one.
|
||||
AvatarURL string `json:"avatarUrl"`
|
||||
}
|
||||
|
||||
type CreateUserRequest struct {
|
||||
|
|
|
|||
|
|
@ -21,7 +21,7 @@ func New(h *handler.Handler, tokens security.ITokenManager, frontendURL string)
|
|||
router := chi.NewRouter()
|
||||
spec := openapi.New()
|
||||
router.Use(middleware.RequestID, middleware.RealIP, middleware.Recoverer, middleware.Compress(5))
|
||||
router.Use(cors(frontendURL))
|
||||
router.Use(cors(frontendURL, h.AppDomain()))
|
||||
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,
|
||||
|
|
@ -164,11 +164,11 @@ func authenticate(tokens security.ITokenManager) func(http.Handler) http.Handler
|
|||
}
|
||||
}
|
||||
|
||||
func cors(origin string) func(http.Handler) http.Handler {
|
||||
func cors(origin, appDomain string) func(http.Handler) http.Handler {
|
||||
return func(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
requestOrigin := r.Header.Get("Origin")
|
||||
if allowedCORSOrigin(requestOrigin, origin) {
|
||||
if allowedCORSOrigin(requestOrigin, origin, appDomain) {
|
||||
w.Header().Set("Access-Control-Allow-Origin", requestOrigin)
|
||||
}
|
||||
w.Header().Set("Access-Control-Allow-Headers", "Authorization, Content-Type, X-API-Key, X-Tenant-Id")
|
||||
|
|
@ -183,7 +183,11 @@ func cors(origin string) func(http.Handler) http.Handler {
|
|||
}
|
||||
}
|
||||
|
||||
func allowedCORSOrigin(requestOrigin, configuredOrigin string) bool {
|
||||
// allowedCORSOrigin accepts the configured frontend origin plus any tenant host
|
||||
// of the configured application domain, which is what the Vite dev server on
|
||||
// http://<tenant>.<appDomain>:5173 sends. *.guess.local stays allowed for the
|
||||
// offline BDD and local password-only setups.
|
||||
func allowedCORSOrigin(requestOrigin, configuredOrigin, appDomain string) bool {
|
||||
if requestOrigin == "" {
|
||||
return false
|
||||
}
|
||||
|
|
@ -194,5 +198,11 @@ func allowedCORSOrigin(requestOrigin, configuredOrigin string) bool {
|
|||
if err != nil || (parsed.Scheme != "http" && parsed.Scheme != "https") {
|
||||
return false
|
||||
}
|
||||
return strings.HasSuffix(strings.ToLower(parsed.Hostname()), ".guess.local")
|
||||
hostname := strings.ToLower(parsed.Hostname())
|
||||
for _, suffix := range []string{"." + appDomain, ".guess.local"} {
|
||||
if suffix != "." && strings.HasSuffix(hostname, suffix) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
|
|
|||
|
|
@ -69,7 +69,7 @@ func (authStub) Login(context.Context, string, string) (string, model.User, erro
|
|||
return "", model.User{}, service.ErrInvalidCredentials
|
||||
}
|
||||
|
||||
func (authStub) EstablishExternalSession(context.Context, string, string) (string, model.User, error) {
|
||||
func (authStub) EstablishExternalSession(context.Context, service.ExternalIdentity) (string, model.User, error) {
|
||||
return "", model.User{}, service.ErrInvalidCredentials
|
||||
}
|
||||
|
||||
|
|
@ -313,8 +313,8 @@ func TestOpenAPIDoesNotRequireTenant(t *testing.T) {
|
|||
func TestTenantHostLoginRedirectsToMatchingGoLooseClient(t *testing.T) {
|
||||
h := newTestHandler(t, nil)
|
||||
browser, err := golooseauth.New(config.GoLooseConfig{
|
||||
AuthDomain: "auth.dev",
|
||||
AppDomain: "guess.dev",
|
||||
AuthDomain: config.DefaultAuthDomain,
|
||||
AppDomain: config.DefaultAppDomain,
|
||||
Tenants: map[string]config.GoLooseTenant{
|
||||
"nmbs": {ClientID: "glc_nmbs", ClientSecret: "secret"},
|
||||
"ypto": {ClientID: "glc_ypto", ClientSecret: "secret"},
|
||||
|
|
@ -328,14 +328,14 @@ func TestTenantHostLoginRedirectsToMatchingGoLooseClient(t *testing.T) {
|
|||
|
||||
for _, slug := range []string{"nmbs", "ypto"} {
|
||||
request := httptest.NewRequest(http.MethodGet, "/api/auth/login", nil)
|
||||
request.Host = slug + ".guess.dev"
|
||||
request.Host = slug + ".guess-dev.urpi.be"
|
||||
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?") {
|
||||
if response.Code != http.StatusFound || !strings.HasPrefix(location, "https://"+slug+".auth-dev.urpi.be/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") {
|
||||
if !strings.Contains(location, "redirect_uri=https%3A%2F%2F"+slug+".guess-dev.urpi.be%2Fapi%2Fauth%2Fcallback") {
|
||||
t.Fatalf("%s callback missing from %s", slug, location)
|
||||
}
|
||||
}
|
||||
|
|
@ -344,8 +344,8 @@ func TestTenantHostLoginRedirectsToMatchingGoLooseClient(t *testing.T) {
|
|||
func TestTenantHostLoginExplainsUnconfiguredGoLooseTenant(t *testing.T) {
|
||||
h := newTestHandler(t, nil)
|
||||
browser, err := golooseauth.New(config.GoLooseConfig{
|
||||
AuthDomain: "auth.dev",
|
||||
AppDomain: "guess.dev",
|
||||
AuthDomain: config.DefaultAuthDomain,
|
||||
AppDomain: config.DefaultAppDomain,
|
||||
Tenants: map[string]config.GoLooseTenant{"nmbs": {ClientID: "glc_nmbs", ClientSecret: "secret"}},
|
||||
})
|
||||
if err != nil {
|
||||
|
|
@ -355,7 +355,7 @@ func TestTenantHostLoginExplainsUnconfiguredGoLooseTenant(t *testing.T) {
|
|||
api := New(h, security.NewTokenManager("01234567890123456789012345678901", time.Hour), "http://localhost:5173")
|
||||
|
||||
request := httptest.NewRequest(http.MethodGet, "/api/auth/login", nil)
|
||||
request.Host = "ypto.guess.dev"
|
||||
request.Host = "ypto.guess-dev.urpi.be"
|
||||
response := httptest.NewRecorder()
|
||||
api.ServeHTTP(response, request)
|
||||
if response.Code != http.StatusServiceUnavailable ||
|
||||
|
|
@ -364,7 +364,7 @@ func TestTenantHostLoginExplainsUnconfiguredGoLooseTenant(t *testing.T) {
|
|||
}
|
||||
|
||||
request = httptest.NewRequest(http.MethodGet, "/api/auth/login", nil)
|
||||
request.Host = "guess.dev"
|
||||
request.Host = "guess-dev.urpi.be"
|
||||
response = httptest.NewRecorder()
|
||||
api.ServeHTTP(response, request)
|
||||
if response.Code != http.StatusNotFound || !strings.Contains(response.Body.String(), "tenant") {
|
||||
|
|
@ -379,7 +379,7 @@ func TestLoginWithoutGoLooseRegistryIsNotFound(t *testing.T) {
|
|||
"http://localhost:5173",
|
||||
)
|
||||
request := httptest.NewRequest(http.MethodGet, "/api/auth/login", nil)
|
||||
request.Host = "nmbs.guess.dev"
|
||||
request.Host = "nmbs.guess-dev.urpi.be"
|
||||
response := httptest.NewRecorder()
|
||||
api.ServeHTTP(response, request)
|
||||
if response.Code != http.StatusNotFound || !strings.Contains(response.Body.String(), "not enabled") {
|
||||
|
|
@ -387,6 +387,125 @@ func TestLoginWithoutGoLooseRegistryIsNotFound(t *testing.T) {
|
|||
}
|
||||
}
|
||||
|
||||
// The frontend falls back to password sign-in only when it can tell that Go
|
||||
// Loose login is unavailable, so a host without a registry must answer 404
|
||||
// rather than 401 even when the request carries no session cookie.
|
||||
func TestSessionWithoutGoLooseRegistryIsNotFound(t *testing.T) {
|
||||
api := New(
|
||||
newTestHandler(t, nil),
|
||||
security.NewTokenManager("01234567890123456789012345678901", time.Hour),
|
||||
"http://localhost:5173",
|
||||
)
|
||||
request := httptest.NewRequest(http.MethodGet, "/api/auth/session", nil)
|
||||
request.Host = "nmbs.guess-dev.urpi.be"
|
||||
response := httptest.NewRecorder()
|
||||
api.ServeHTTP(response, request)
|
||||
if response.Code != http.StatusNotFound || !strings.Contains(response.Body.String(), "not enabled") {
|
||||
t.Fatalf("session without registry = %d %s", response.Code, response.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestSessionOnAnUnconfiguredTenantHostIsNotFound(t *testing.T) {
|
||||
h := newTestHandler(t, nil)
|
||||
browser, err := golooseauth.New(config.GoLooseConfig{
|
||||
AuthDomain: config.DefaultAuthDomain,
|
||||
AppDomain: config.DefaultAppDomain,
|
||||
Tenants: map[string]config.GoLooseTenant{"nmbs": {ClientID: "glc_nmbs", ClientSecret: "secret"}},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
h.SetBrowserAuth(browser)
|
||||
api := New(h, security.NewTokenManager("01234567890123456789012345678901", time.Hour), "http://localhost:5173")
|
||||
|
||||
request := httptest.NewRequest(http.MethodGet, "/api/auth/session", nil)
|
||||
request.Host = "ypto.guess-dev.urpi.be"
|
||||
response := httptest.NewRecorder()
|
||||
api.ServeHTTP(response, request)
|
||||
if response.Code != http.StatusServiceUnavailable ||
|
||||
!strings.Contains(response.Body.String(), "GO_LOOSE_YPTO_CLIENT_ID") {
|
||||
t.Fatalf("unconfigured tenant session = %d %s", response.Code, response.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestSessionWithoutCookieIsUnauthorizedOnATenantHost(t *testing.T) {
|
||||
h := newTestHandler(t, nil)
|
||||
browser, err := golooseauth.New(config.GoLooseConfig{
|
||||
AuthDomain: config.DefaultAuthDomain,
|
||||
AppDomain: config.DefaultAppDomain,
|
||||
Tenants: map[string]config.GoLooseTenant{"nmbs": {ClientID: "glc_nmbs", ClientSecret: "secret"}},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
h.SetBrowserAuth(browser)
|
||||
api := New(h, security.NewTokenManager("01234567890123456789012345678901", time.Hour), "http://localhost:5173")
|
||||
|
||||
request := httptest.NewRequest(http.MethodGet, "/api/auth/session", nil)
|
||||
request.Host = "nmbs.guess-dev.urpi.be"
|
||||
response := httptest.NewRecorder()
|
||||
api.ServeHTTP(response, request)
|
||||
if response.Code != http.StatusUnauthorized || !strings.Contains(response.Body.String(), "missing Go Loose session") {
|
||||
t.Fatalf("session without cookie = %d %s", response.Code, response.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
// An ingress proxy may replace the request Host, so the tenant has to be read
|
||||
// from X-Forwarded-Host when it is present.
|
||||
func TestTenantHostLoginHonorsTheForwardedHost(t *testing.T) {
|
||||
h := newTestHandler(t, nil)
|
||||
browser, err := golooseauth.New(config.GoLooseConfig{
|
||||
AuthDomain: config.DefaultProdAuthDomain,
|
||||
AppDomain: config.DefaultProdAppDomain,
|
||||
Tenants: map[string]config.GoLooseTenant{"nmbs": {ClientID: "glc_nmbs", ClientSecret: "secret"}},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
h.SetBrowserAuth(browser)
|
||||
api := New(h, security.NewTokenManager("01234567890123456789012345678901", time.Hour), "https://nmbs.guess.urpi.be")
|
||||
|
||||
request := httptest.NewRequest(http.MethodGet, "/api/auth/login", nil)
|
||||
request.Host = "go-guess-api.go-insane-production.svc.cluster.local:8080"
|
||||
request.Header.Set("X-Forwarded-Host", "nmbs.guess.urpi.be")
|
||||
response := httptest.NewRecorder()
|
||||
api.ServeHTTP(response, request)
|
||||
|
||||
location := response.Header().Get("Location")
|
||||
if response.Code != http.StatusFound || !strings.HasPrefix(location, "https://nmbs.auth.urpi.be/connect/authorize?") {
|
||||
t.Fatalf("forwarded host login redirect = %d %s", response.Code, location)
|
||||
}
|
||||
if !strings.Contains(location, "redirect_uri=https%3A%2F%2Fnmbs.guess.urpi.be%2Fapi%2Fauth%2Fcallback") {
|
||||
t.Fatalf("forwarded host callback missing from %s", location)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCORSAllowsTheConfiguredTenantOrigin(t *testing.T) {
|
||||
api := New(
|
||||
newTestHandler(t, nil),
|
||||
security.NewTokenManager("01234567890123456789012345678901", time.Hour),
|
||||
"https://nmbs.guess.urpi.be",
|
||||
)
|
||||
for _, tc := range []struct {
|
||||
origin string
|
||||
allow string
|
||||
}{
|
||||
{origin: "https://nmbs.guess.urpi.be", allow: "https://nmbs.guess.urpi.be"},
|
||||
{origin: "http://nmbs.guess-dev.urpi.be:5173", allow: "http://nmbs.guess-dev.urpi.be:5173"},
|
||||
{origin: "http://ypto.guess.local:5173", allow: "http://ypto.guess.local:5173"},
|
||||
{origin: "https://evil.test", allow: ""},
|
||||
{origin: "https://nmbs.guess.urpi.be.evil.test", allow: ""},
|
||||
} {
|
||||
request := httptest.NewRequest(http.MethodOptions, "/api/jobs", nil)
|
||||
request.Header.Set("Origin", tc.origin)
|
||||
response := httptest.NewRecorder()
|
||||
api.ServeHTTP(response, request)
|
||||
if got := response.Header().Get("Access-Control-Allow-Origin"); got != tc.allow {
|
||||
t.Fatalf("CORS allow origin for %q = %q, want %q", tc.origin, got, tc.allow)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
type stubDriver struct{}
|
||||
|
||||
func (stubDriver) Open(string) (driver.Conn, error) { return stubConn{}, nil }
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue