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:
Daniel Noulet 2026-10-05 21:50:06 +02:00
parent 6be21597d5
commit 5449cd3d8d
52 changed files with 1927 additions and 434 deletions

View file

@ -3,7 +3,7 @@ module github.com/danyel/go-guess/backend
go 1.27.1
require (
github.com/danyel/go-loose v0.0.0-20261002194542-c2091e746a14
github.com/danyel/go-loose v0.0.0-20261005194805-49ab89ae46fd
github.com/go-chi/chi/v5 v5.2.3
github.com/golang-jwt/jwt/v5 v5.3.0
github.com/google/uuid v1.6.0

View file

@ -22,8 +22,8 @@ github.com/cpuguy83/dockercfg v0.3.2 h1:DlJTyZGBDlXqUZ2Dk2Q3xHs/FtnooJJVaad2S9GK
github.com/cpuguy83/dockercfg v0.3.2/go.mod h1:sugsbF4//dDlL/i+S+rtpIWp+5h0BHJHfjj5/jFyUJc=
github.com/creack/pty v1.1.24 h1:bJrF4RRfyJnbTJqzRLHzcGaZK1NeM5kTC9jGgovnR1s=
github.com/creack/pty v1.1.24/go.mod h1:08sCNb52WyoAwi2QDyzUCTgcvVFhUzewun7wtTfvcwE=
github.com/danyel/go-loose v0.0.0-20261002194542-c2091e746a14 h1:kX0zybG4E3VLB4QpOsyJEBu4HoXx33CY2x8rtACHRRM=
github.com/danyel/go-loose v0.0.0-20261002194542-c2091e746a14/go.mod h1:qOO4ay0c2MWiiLwz7WHCXCqDwxxA3sKTKKUnqbFgsOk=
github.com/danyel/go-loose v0.0.0-20261005194805-49ab89ae46fd h1:YCvHmqMNr0cfEqdAzRyVe4MOn+yYyMh8/FLSMydvYQM=
github.com/danyel/go-loose v0.0.0-20261005194805-49ab89ae46fd/go.mod h1:qOO4ay0c2MWiiLwz7WHCXCqDwxxA3sKTKKUnqbFgsOk=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=

View file

@ -31,6 +31,20 @@ type GoLooseTenant struct {
ClientSecret string
}
const (
// DefaultAuthDomain is the Go Loose identity domain used for local
// development. Production signs in through DefaultProdAuthDomain.
DefaultAuthDomain = "auth-dev.urpi.be"
// DefaultProdAuthDomain is the Go Loose identity domain used in production.
DefaultProdAuthDomain = "auth.urpi.be"
// DefaultAppDomain is the public application domain used for local
// development, matching deploy/helm/go-guess/values-dev.yaml.
DefaultAppDomain = "guess-dev.urpi.be"
// DefaultProdAppDomain is the public application domain used in production,
// matching deploy/helm/go-guess/values.yaml.
DefaultProdAppDomain = "guess.urpi.be"
)
// GoLooseCredentialEnv returns the environment variable names holding the Go
// Loose client credentials of a tenant.
func GoLooseCredentialEnv(slug string) (idEnv, secretEnv string) {
@ -63,10 +77,17 @@ func Load() (Config, error) {
return cfg, nil
}
// loadGoLoose reads the Go Loose browser login configuration. Both domains are
// single host suffixes: a tenant named "nmbs" signs in through
// https://nmbs.<AuthDomain> and is served from https://nmbs.<AppDomain>.
//
// The defaults are the development domains, matching the rest of the local
// defaults in Load. Production deployments set GO_LOOSE_AUTH_DOMAIN and
// GO_LOOSE_APP_DOMAIN explicitly (see deploy/helm/go-guess/values.yaml).
func loadGoLoose() GoLooseConfig {
cfg := GoLooseConfig{
AuthDomain: env("GO_LOOSE_AUTH_DOMAIN", "auth.dev"),
AppDomain: env("GO_LOOSE_APP_DOMAIN", "guess.dev"),
AuthDomain: env("GO_LOOSE_AUTH_DOMAIN", DefaultAuthDomain),
AppDomain: env("GO_LOOSE_APP_DOMAIN", DefaultAppDomain),
CAFile: os.Getenv("GO_LOOSE_CA_FILE"),
Tenants: map[string]GoLooseTenant{},
}

View file

@ -24,16 +24,13 @@ type Registry struct {
func New(cfg config.GoLooseConfig) (*Registry, error) {
registry := &Registry{
appDomain: strings.TrimPrefix(strings.ToLower(cfg.AppDomain), "."),
appDomain: domain(cfg.AppDomain),
bySlug: map[string]*goloose.BrowserAuth{},
}
if registry.appDomain == "" {
registry.appDomain = "guess.dev"
}
if len(cfg.Tenants) == 0 {
return registry, nil
}
authDomain := strings.TrimPrefix(strings.ToLower(cfg.AuthDomain), ".")
authDomain := domain(cfg.AuthDomain)
if authDomain == "" {
return nil, fmt.Errorf("GO_LOOSE_AUTH_DOMAIN is required when client credentials are configured")
}
@ -42,7 +39,7 @@ func New(cfg config.GoLooseConfig) (*Registry, error) {
return nil, err
}
for slug, tenant := range cfg.Tenants {
slug = strings.ToLower(strings.TrimSpace(slug))
slug = domain(slug)
if slug == "" || strings.Contains(slug, ".") {
return nil, fmt.Errorf("invalid Go Loose tenant slug %q", slug)
}
@ -68,11 +65,13 @@ func New(cfg config.GoLooseConfig) (*Registry, error) {
func (r *Registry) AppDomain() string {
if r == nil || r.appDomain == "" {
return "guess.dev"
return config.DefaultAppDomain
}
return r.appDomain
}
// ForHost resolves the Go Loose client of the tenant that owns host. Ingress
// proxies may replace the request Host, so X-Forwarded-Host wins when present.
func (r *Registry) ForHost(host string) (*goloose.BrowserAuth, string, bool) {
if r == nil {
return nil, "", false
@ -82,16 +81,21 @@ func (r *Registry) ForHost(host string) (*goloose.BrowserAuth, string, bool) {
return auth, slug, ok
}
// Host returns the host that identifies the tenant of a request, preferring the
// proxy-supplied X-Forwarded-Host over the request Host.
func Host(r *http.Request) string {
if forwarded := strings.TrimSpace(r.Header.Get("X-Forwarded-Host")); forwarded != "" {
return forwarded
}
return r.Host
}
func TenantFromHost(host, appDomain string) string {
hostname := strings.ToLower(host)
hostname := strings.ToLower(strings.TrimSuffix(strings.TrimSpace(host), "."))
if parsed, _, err := net.SplitHostPort(host); err == nil {
hostname = strings.ToLower(parsed)
hostname = strings.ToLower(strings.TrimSuffix(parsed, "."))
}
appDomain = strings.TrimPrefix(strings.ToLower(appDomain), ".")
if appDomain == "" {
appDomain = "guess.dev"
}
suffix := "." + appDomain
suffix := "." + domain(appDomain)
if !strings.HasSuffix(hostname, suffix) {
return ""
}
@ -102,6 +106,11 @@ func TenantFromHost(host, appDomain string) string {
return slug
}
// domain normalizes a configured host suffix or tenant slug.
func domain(value string) string {
return strings.Trim(strings.ToLower(strings.TrimSpace(value)), ".")
}
func client(caFile string) (*http.Client, error) {
transport := http.DefaultTransport.(*http.Transport).Clone()
if caFile != "" {

View file

@ -0,0 +1,181 @@
package golooseauth
import (
"net/http"
"net/http/httptest"
"strings"
"testing"
"github.com/danyel/go-guess/backend/internal/config"
)
func tenants() map[string]config.GoLooseTenant {
return map[string]config.GoLooseTenant{
"nmbs": {ClientID: "glc_nmbs", ClientSecret: "secret"},
"ypto": {ClientID: "glc_ypto", ClientSecret: "secret"},
}
}
func TestNewUsesDevelopmentDomainsByDefault(t *testing.T) {
registry, err := New(config.GoLooseConfig{AuthDomain: config.DefaultAuthDomain, AppDomain: config.DefaultAppDomain, Tenants: tenants()})
if err != nil {
t.Fatal(err)
}
if registry.AppDomain() != "guess-dev.urpi.be" {
t.Fatalf("app domain = %q", registry.AppDomain())
}
location := loginRedirect(t, registry, "nmbs.guess-dev.urpi.be")
if !strings.HasPrefix(location, "https://nmbs.auth-dev.urpi.be/connect/authorize?") {
t.Fatalf("development login redirect = %q", location)
}
if !strings.Contains(location, "redirect_uri=https%3A%2F%2Fnmbs.guess-dev.urpi.be%2Fapi%2Fauth%2Fcallback") {
t.Fatalf("development callback missing from %q", location)
}
}
func TestNewUsesProductionDomains(t *testing.T) {
registry, err := New(config.GoLooseConfig{
AuthDomain: config.DefaultProdAuthDomain,
AppDomain: config.DefaultProdAppDomain,
Tenants: tenants(),
})
if err != nil {
t.Fatal(err)
}
location := loginRedirect(t, registry, "nmbs.guess.urpi.be")
if !strings.HasPrefix(location, "https://nmbs.auth.urpi.be/connect/authorize?") {
t.Fatalf("production login redirect = %q", location)
}
if !strings.Contains(location, "redirect_uri=https%3A%2F%2Fnmbs.guess.urpi.be%2Fapi%2Fauth%2Fcallback") {
t.Fatalf("production callback missing from %q", location)
}
}
func TestNewRequiresAnAuthDomainWithCredentials(t *testing.T) {
if _, err := New(config.GoLooseConfig{Tenants: tenants()}); err == nil {
t.Fatal("expected an error when GO_LOOSE_AUTH_DOMAIN is empty")
}
}
func TestNewNormalizesConfiguredDomains(t *testing.T) {
registry, err := New(config.GoLooseConfig{
AuthDomain: " .Auth-Dev.Urpi.Be. ",
AppDomain: ".Guess-Dev.Urpi.Be.",
Tenants: map[string]config.GoLooseTenant{"NMBS": {ClientID: "glc_nmbs", ClientSecret: "secret"}},
})
if err != nil {
t.Fatal(err)
}
if registry.AppDomain() != "guess-dev.urpi.be" {
t.Fatalf("app domain = %q", registry.AppDomain())
}
if location := loginRedirect(t, registry, "nmbs.guess-dev.urpi.be"); !strings.HasPrefix(location, "https://nmbs.auth-dev.urpi.be/connect/authorize?") {
t.Fatalf("normalized login redirect = %q", location)
}
}
func TestNewRejectsMultiLabelTenantSlug(t *testing.T) {
_, err := New(config.GoLooseConfig{
AuthDomain: config.DefaultAuthDomain,
AppDomain: config.DefaultAppDomain,
Tenants: map[string]config.GoLooseTenant{"nmbs.eu": {ClientID: "id", ClientSecret: "secret"}},
})
if err == nil {
t.Fatal("expected an error for a tenant slug containing a dot")
}
}
func TestAppDomainFallsBackToTheDevelopmentDomain(t *testing.T) {
var missing *Registry
if missing.AppDomain() != config.DefaultAppDomain {
t.Fatalf("nil registry app domain = %q", missing.AppDomain())
}
empty, err := New(config.GoLooseConfig{})
if err != nil {
t.Fatal(err)
}
if empty.AppDomain() != config.DefaultAppDomain {
t.Fatalf("empty registry app domain = %q", empty.AppDomain())
}
}
func TestForHostResolvesTheTenantOfTheHost(t *testing.T) {
registry, err := New(config.GoLooseConfig{
AuthDomain: config.DefaultAuthDomain,
AppDomain: config.DefaultAppDomain,
Tenants: tenants(),
})
if err != nil {
t.Fatal(err)
}
for _, tc := range []struct {
host string
slug string
ok bool
}{
{host: "nmbs.guess-dev.urpi.be", slug: "nmbs", ok: true},
{host: "ypto.guess-dev.urpi.be", slug: "ypto", ok: true},
{host: "NMBS.Guess-Dev.Urpi.Be:8443", slug: "nmbs", ok: true},
// The apex host identifies no tenant.
{host: "guess-dev.urpi.be", slug: "", ok: false},
// Another environment's domain has no configured Go Loose client here.
{host: "nmbs.guess.urpi.be", slug: "", ok: false},
{host: "guess.urpi.be", slug: "", ok: false},
{host: "localhost:5173", slug: "", ok: false},
{host: "", slug: "", ok: false},
} {
auth, slug, ok := registry.ForHost(tc.host)
if slug != tc.slug || ok != tc.ok {
t.Fatalf("ForHost(%q) = %q, %v, want %q, %v", tc.host, slug, ok, tc.slug, tc.ok)
}
if ok && auth == nil {
t.Fatalf("ForHost(%q) returned no client", tc.host)
}
}
}
func TestHostPrefersTheForwardedHost(t *testing.T) {
request := httptest.NewRequest(http.MethodGet, "/api/auth/session", nil)
request.Host = "api:8080"
if Host(request) != "api:8080" {
t.Fatalf("host = %q", Host(request))
}
request.Header.Set("X-Forwarded-Host", "nmbs.guess-dev.urpi.be")
if Host(request) != "nmbs.guess-dev.urpi.be" {
t.Fatalf("forwarded host = %q", Host(request))
}
}
func TestTenantFromHost(t *testing.T) {
for _, tc := range []struct {
host string
want string
}{
{host: "nmbs.guess-dev.urpi.be", want: "nmbs"},
{host: "ypto.guess-dev.urpi.be:443", want: "ypto"},
{host: "nmbs.guess-dev.urpi.be.", want: "nmbs"},
{host: "deep.nmbs.guess-dev.urpi.be", want: ""},
{host: "guess-dev.urpi.be", want: ""},
{host: "nmbs.evil.test", want: ""},
} {
if got := TenantFromHost(tc.host, config.DefaultAppDomain); got != tc.want {
t.Fatalf("TenantFromHost(%q) = %q, want %q", tc.host, got, tc.want)
}
}
}
func loginRedirect(t *testing.T, registry *Registry, host string) string {
t.Helper()
auth, _, ok := registry.ForHost(host)
if !ok {
t.Fatalf("no Go Loose client for %q", host)
}
request := httptest.NewRequest(http.MethodGet, "/api/auth/login", nil)
request.Host = host
response := httptest.NewRecorder()
auth.LoginHandler(response, request)
if response.Code != http.StatusFound {
t.Fatalf("login for %q = %d, want 302", host, response.Code)
}
return response.Header().Get("Location")
}

View file

@ -8,6 +8,10 @@ type User struct {
PasswordHash string
DisplayName string
Role string
// AvatarURL is the picture Go Loose serves for this person. It is resolved
// from the identity provider on every sign-in rather than stored, because a
// stored key stops resolving once the picture is replaced or removed.
AvatarURL string
}
type Trait struct {

View file

@ -28,7 +28,7 @@ const CandidateThreshold = 60.0
type IAuthService interface {
Login(context.Context, string, string) (string, model.User, error)
EstablishExternalSession(context.Context, string, string) (string, model.User, error)
EstablishExternalSession(context.Context, ExternalIdentity) (string, model.User, error)
}
type IJobService interface {
@ -89,9 +89,19 @@ func (s *AuthService) Login(ctx context.Context, email, password string) (string
return token, user, nil
}
func (s *AuthService) EstablishExternalSession(ctx context.Context, email, displayName string) (string, model.User, error) {
email = strings.ToLower(strings.TrimSpace(email))
displayName = strings.TrimSpace(displayName)
// ExternalIdentity is what Go Loose reports about the person signing in. The
// avatar URL is deliberately not persisted: Go Loose retires a picture key when
// the picture changes, so a stored copy would eventually point at nothing. It is
// read from the live identity on every session instead.
type ExternalIdentity struct {
Email string
DisplayName string
AvatarURL string
}
func (s *AuthService) EstablishExternalSession(ctx context.Context, identity ExternalIdentity) (string, model.User, error) {
email := strings.ToLower(strings.TrimSpace(identity.Email))
displayName := strings.TrimSpace(identity.DisplayName)
if email == "" {
return "", model.User{}, ErrValidation
}
@ -116,6 +126,7 @@ func (s *AuthService) EstablishExternalSession(ctx context.Context, email, displ
return "", model.User{}, err
}
user.PasswordHash = ""
user.AvatarURL = strings.TrimSpace(identity.AvatarURL)
return token, user, nil
}

View file

@ -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

View file

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

View file

@ -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) {

View file

@ -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,
}
}

View file

@ -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 (

View file

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

View file

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

View file

@ -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 {

View file

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

View file

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