fix installer
This commit is contained in:
parent
46030a5b14
commit
c2091e746a
19 changed files with 264 additions and 73 deletions
|
|
@ -32,10 +32,11 @@ type Config struct {
|
|||
}
|
||||
|
||||
func Load() (Config, error) {
|
||||
baseURL := strings.TrimRight(env("GO_LOOSE_BASE_URL", "http://localhost:8080"), "/")
|
||||
cfg := Config{
|
||||
Addr: env("GO_LOOSE_ADDR", ":8080"),
|
||||
BaseURL: strings.TrimRight(env("GO_LOOSE_BASE_URL", "http://localhost:8080"), "/"),
|
||||
AuthDomain: strings.TrimPrefix(strings.ToLower(env("GO_LOOSE_AUTH_DOMAIN", "auth.local")), "."),
|
||||
BaseURL: baseURL,
|
||||
AuthDomain: strings.TrimPrefix(strings.ToLower(env("GO_LOOSE_AUTH_DOMAIN", "auth.dev")), "."),
|
||||
DatabaseURL: env("GO_LOOSE_DATABASE_URL", "postgres://goloose:goloose@localhost:5432/goloose?sslmode=disable"),
|
||||
SessionSecret: os.Getenv("GO_LOOSE_SESSION_SECRET"),
|
||||
DevLogin: envBool("GO_LOOSE_DEV_LOGIN", false),
|
||||
|
|
@ -46,7 +47,7 @@ func Load() (Config, error) {
|
|||
OIDCIssuer: strings.TrimRight(os.Getenv("GO_LOOSE_OIDC_ISSUER"), "/"),
|
||||
OIDCClientID: os.Getenv("GO_LOOSE_OIDC_CLIENT_ID"),
|
||||
OIDCClientSecret: os.Getenv("GO_LOOSE_OIDC_CLIENT_SECRET"),
|
||||
OIDCRedirectURL: env("GO_LOOSE_OIDC_REDIRECT_URL", "http://localhost:8080/auth/callback"),
|
||||
OIDCRedirectURL: env("GO_LOOSE_OIDC_REDIRECT_URL", baseURL+"/auth/callback"),
|
||||
AllowedEmailDomains: csv(os.Getenv("GO_LOOSE_ALLOWED_EMAIL_DOMAINS")),
|
||||
AllowPrivateContractURL: envBool("GO_LOOSE_ALLOW_PRIVATE_CONTRACT_URLS", false),
|
||||
BootstrapTenant: env("GO_LOOSE_BOOTSTRAP_TENANT", "default"),
|
||||
|
|
@ -57,7 +58,7 @@ func Load() (Config, error) {
|
|||
return Config{}, errors.New("GO_LOOSE_SESSION_SECRET must contain at least 32 characters")
|
||||
}
|
||||
if cfg.AuthDomain == "" || strings.ContainsAny(cfg.AuthDomain, "/:") {
|
||||
return Config{}, errors.New("GO_LOOSE_AUTH_DOMAIN must be a hostname such as auth.local")
|
||||
return Config{}, errors.New("GO_LOOSE_AUTH_DOMAIN must be a hostname such as auth.dev")
|
||||
}
|
||||
oidcConfigured := cfg.OIDCIssuer != "" && cfg.OIDCClientID != "" && cfg.OIDCClientSecret != ""
|
||||
if cfg.LocalAdminPassword != "" && len(cfg.LocalAdminPassword) < 12 {
|
||||
|
|
|
|||
|
|
@ -43,3 +43,17 @@ func TestLoadAllowsDatabaseLoginWithoutBootstrapAccount(t *testing.T) {
|
|||
t.Fatalf("Load() error = %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoadDerivesOIDCRedirectURLFromBaseURL(t *testing.T) {
|
||||
t.Setenv("GO_LOOSE_SESSION_SECRET", "01234567890123456789012345678901")
|
||||
t.Setenv("GO_LOOSE_BASE_URL", "http://auth.dev:18080/")
|
||||
t.Setenv("GO_LOOSE_OIDC_REDIRECT_URL", "")
|
||||
|
||||
cfg, err := Load()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if cfg.OIDCRedirectURL != "http://auth.dev:18080/auth/callback" {
|
||||
t.Fatalf("OIDC redirect URL = %q", cfg.OIDCRedirectURL)
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -100,10 +100,10 @@ func buildDemoUsers() ([]store.DemoUser, error) {
|
|||
specs := []struct {
|
||||
email, name, password, tenant string
|
||||
}{
|
||||
{"interview@nmbs.auth.local", "NMBS Interview", "admin123", "nmbs"},
|
||||
{"interview@ypto.auth.local", "YPTO Interview", "admin123", "ypto"},
|
||||
{"reviewer@nmbs.auth.local", "NMBS Reviewer", "Demo-Nmbs-2026!", "nmbs"},
|
||||
{"reviewer@ypto.auth.local", "YPTO Reviewer", "Demo-Ypto-2026!", "ypto"},
|
||||
{"interview@nmbs.auth.dev", "NMBS Interview", "admin123", "nmbs"},
|
||||
{"interview@ypto.auth.dev", "YPTO Interview", "admin123", "ypto"},
|
||||
{"reviewer@nmbs.auth.dev", "NMBS Reviewer", "Demo-Nmbs-2026!", "nmbs"},
|
||||
{"reviewer@ypto.auth.dev", "YPTO Reviewer", "Demo-Ypto-2026!", "ypto"},
|
||||
}
|
||||
result := make([]store.DemoUser, 0, len(specs))
|
||||
for _, spec := range specs {
|
||||
|
|
|
|||
|
|
@ -1,6 +1,7 @@
|
|||
package server
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
|
|
@ -8,11 +9,11 @@ import (
|
|||
)
|
||||
|
||||
func TestOAuthStateCookieDomain(t *testing.T) {
|
||||
server := &Server{cfg: config.Config{AuthDomain: "auth.local"}}
|
||||
server := &Server{cfg: config.Config{AuthDomain: "auth.dev"}}
|
||||
|
||||
tenantRequest := httptest.NewRequest("GET", "http://nmbs.auth.local/auth/start", nil)
|
||||
if domain := server.oauthStateCookieDomain(tenantRequest); domain != "auth.local" {
|
||||
t.Fatalf("tenant cookie domain = %q, want auth.local", domain)
|
||||
tenantRequest := httptest.NewRequest("GET", "http://nmbs.auth.dev/auth/start", nil)
|
||||
if domain := server.oauthStateCookieDomain(tenantRequest); domain != "auth.dev" {
|
||||
t.Fatalf("tenant cookie domain = %q, want auth.dev", domain)
|
||||
}
|
||||
|
||||
localRequest := httptest.NewRequest("GET", "http://localhost:8080/auth/start", nil)
|
||||
|
|
@ -20,3 +21,27 @@ func TestOAuthStateCookieDomain(t *testing.T) {
|
|||
t.Fatalf("local cookie domain = %q, want host-only cookie", domain)
|
||||
}
|
||||
}
|
||||
|
||||
func TestManagementSSOIsRejectedOnTenantHost(t *testing.T) {
|
||||
server := &Server{cfg: config.Config{AuthDomain: "auth.dev"}}
|
||||
request := httptest.NewRequest(http.MethodGet, "http://nmbs.auth.dev/auth/start", nil)
|
||||
response := httptest.NewRecorder()
|
||||
|
||||
server.authStart(response, request)
|
||||
|
||||
if response.Code != http.StatusNotFound {
|
||||
t.Fatalf("status = %d, want %d", response.Code, http.StatusNotFound)
|
||||
}
|
||||
}
|
||||
|
||||
func TestClientSSOIsRejectedOnSystemHost(t *testing.T) {
|
||||
server := &Server{cfg: config.Config{AuthDomain: "auth.dev"}}
|
||||
request := httptest.NewRequest(http.MethodGet, "http://auth.dev/auth/start?return=client", nil)
|
||||
response := httptest.NewRecorder()
|
||||
|
||||
server.authStart(response, request)
|
||||
|
||||
if response.Code != http.StatusNotFound {
|
||||
t.Fatalf("status = %d, want %d", response.Code, http.StatusNotFound)
|
||||
}
|
||||
}
|
||||
|
|
|
|||
41
internal/server/origin_test.go
Normal file
41
internal/server/origin_test.go
Normal file
|
|
@ -0,0 +1,41 @@
|
|||
package server
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"github.com/danyel/go-loose/internal/config"
|
||||
)
|
||||
|
||||
func TestRequireSameOriginAcceptsTenantHost(t *testing.T) {
|
||||
server := &Server{cfg: config.Config{BaseURL: "https://auth.dev"}}
|
||||
handler := server.requireSameOrigin(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}))
|
||||
request := httptest.NewRequest(http.MethodPost, "https://nmbs.auth.dev/api/v1/keys", nil)
|
||||
request.Header.Set("Origin", "https://nmbs.auth.dev")
|
||||
response := httptest.NewRecorder()
|
||||
|
||||
handler.ServeHTTP(response, request)
|
||||
|
||||
if response.Code != http.StatusNoContent {
|
||||
t.Fatalf("status = %d, want %d", response.Code, http.StatusNoContent)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRequireSameOriginRejectsDifferentTenantHost(t *testing.T) {
|
||||
server := &Server{cfg: config.Config{BaseURL: "https://auth.dev"}}
|
||||
handler := server.requireSameOrigin(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
t.Fatal("handler reached for cross-origin request")
|
||||
}))
|
||||
request := httptest.NewRequest(http.MethodPost, "https://nmbs.auth.dev/api/v1/keys", nil)
|
||||
request.Header.Set("Origin", "https://ypto.auth.dev")
|
||||
response := httptest.NewRecorder()
|
||||
|
||||
handler.ServeHTTP(response, request)
|
||||
|
||||
if response.Code != http.StatusForbidden {
|
||||
t.Fatalf("status = %d, want %d", response.Code, http.StatusForbidden)
|
||||
}
|
||||
}
|
||||
|
|
@ -70,6 +70,11 @@ func (s *Server) passwordLogin(w http.ResponseWriter, r *http.Request) {
|
|||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
tenantSlug := s.requestTenantSlug(r.Host)
|
||||
if tenantSlug == "" {
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
r.Body = http.MaxBytesReader(w, r.Body, 16<<10)
|
||||
if err := r.ParseForm(); err != nil {
|
||||
writeError(w, http.StatusBadRequest, "invalid login request")
|
||||
|
|
@ -107,6 +112,14 @@ func (s *Server) passwordLogin(w http.ResponseWriter, r *http.Request) {
|
|||
if err != nil {
|
||||
password.Verify(s.loginGuard.dummyHash, passwordValue)
|
||||
}
|
||||
if valid {
|
||||
tenantAllowed, accessErr := s.store.HasTenantAccess(r.Context(), user.ID, tenantSlug)
|
||||
if accessErr != nil {
|
||||
s.internalError(w, "check password user tenant access", accessErr)
|
||||
return
|
||||
}
|
||||
valid = tenantAllowed
|
||||
}
|
||||
if !valid {
|
||||
s.loginGuard.fail(guardKey, now)
|
||||
var userID *string
|
||||
|
|
|
|||
|
|
@ -1,8 +1,12 @@
|
|||
package server
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/danyel/go-loose/internal/config"
|
||||
)
|
||||
|
||||
func TestLoginGuardLocksAfterFiveFailures(t *testing.T) {
|
||||
|
|
@ -22,3 +26,19 @@ func TestLoginGuardLocksAfterFiveFailures(t *testing.T) {
|
|||
t.Fatal("successful login did not clear failures")
|
||||
}
|
||||
}
|
||||
|
||||
func TestPasswordLoginIsRejectedOnSystemHost(t *testing.T) {
|
||||
server := &Server{
|
||||
cfg: config.Config{AuthDomain: "auth.dev", LocalLogin: true},
|
||||
loginGuard: newLoginGuard(),
|
||||
}
|
||||
server.installed.Store(true)
|
||||
request := httptest.NewRequest(http.MethodPost, "http://auth.dev/auth/password", nil)
|
||||
response := httptest.NewRecorder()
|
||||
|
||||
server.passwordLogin(response, request)
|
||||
|
||||
if response.Code != http.StatusNotFound {
|
||||
t.Fatalf("status = %d, want %d", response.Code, http.StatusNotFound)
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -195,15 +195,11 @@ func (s *Server) serveEmbedded(w http.ResponseWriter, name string) {
|
|||
}
|
||||
|
||||
func (s *Server) authStart(w http.ResponseWriter, r *http.Request) {
|
||||
target := "/"
|
||||
if requested := r.URL.Query().Get("return"); requested != "" {
|
||||
validated, err := s.validateLoginReturn(r.Context(), requested)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusBadRequest, "invalid client login return URL")
|
||||
return
|
||||
}
|
||||
target = validated
|
||||
if r.URL.Query().Get("return") != "" || s.requestTenantSlug(r.Host) != "" {
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
target := "/"
|
||||
state, err := s.newLoginState(target)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "could not start login")
|
||||
|
|
@ -610,7 +606,8 @@ func (s *Server) requireSameOrigin(next http.Handler) http.Handler {
|
|||
}
|
||||
sourceURL, sourceErr := url.Parse(source)
|
||||
baseURL, baseErr := url.Parse(s.cfg.BaseURL)
|
||||
if sourceErr != nil || baseErr != nil || sourceURL.Scheme != baseURL.Scheme || sourceURL.Host != baseURL.Host {
|
||||
if sourceErr != nil || baseErr != nil || sourceURL.Scheme != baseURL.Scheme ||
|
||||
!strings.EqualFold(sourceURL.Host, r.Host) {
|
||||
writeError(w, http.StatusForbidden, "same-origin request required")
|
||||
return
|
||||
}
|
||||
|
|
|
|||
|
|
@ -26,6 +26,22 @@ func (s *Server) tenantAuthURL(tenantSlug, requestURI string) string {
|
|||
return base.Scheme + "://" + s.tenantAuthHost(tenantSlug) + requestURI
|
||||
}
|
||||
|
||||
func (s *Server) requestTenantSlug(host string) string {
|
||||
hostname := strings.ToLower(host)
|
||||
if parsedHost, _, err := net.SplitHostPort(host); err == nil {
|
||||
hostname = strings.ToLower(parsedHost)
|
||||
}
|
||||
suffix := "." + s.cfg.AuthDomain
|
||||
if !strings.HasSuffix(hostname, suffix) {
|
||||
return ""
|
||||
}
|
||||
slug := strings.TrimSuffix(hostname, suffix)
|
||||
if slug == "" || strings.Contains(slug, ".") {
|
||||
return ""
|
||||
}
|
||||
return slug
|
||||
}
|
||||
|
||||
func (s *Server) validateLoginReturn(ctx context.Context, raw string) (string, error) {
|
||||
target, err := url.Parse(raw)
|
||||
if err != nil || !target.IsAbs() || target.Path != "/connect/authorize" || target.Fragment != "" || target.User != nil {
|
||||
|
|
@ -103,13 +119,13 @@ func (s *Server) renderClientLogin(w http.ResponseWriter, r *http.Request) {
|
|||
"{{RETURN_URL}}", html.EscapeString(validatedReturn),
|
||||
"{{CSRF_TOKEN}}", html.EscapeString(csrfToken),
|
||||
"{{LOCAL_STYLE}}", hiddenStyle(!s.cfg.LocalLogin),
|
||||
"{{SSO_STYLE}}", hiddenStyle(!s.hasOIDC()),
|
||||
"{{SSO_STYLE}}", hiddenStyle(true),
|
||||
).Replace(string(content))
|
||||
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
||||
w.Write([]byte(page))
|
||||
}
|
||||
|
||||
func (s *Server) renderManagementLogin(w http.ResponseWriter, _ *http.Request) {
|
||||
func (s *Server) renderManagementLogin(w http.ResponseWriter, r *http.Request) {
|
||||
content, err := web.Files.ReadFile("login.html")
|
||||
if err != nil {
|
||||
http.Error(w, "login page unavailable", http.StatusInternalServerError)
|
||||
|
|
@ -120,10 +136,23 @@ func (s *Server) renderManagementLogin(w http.ResponseWriter, _ *http.Request) {
|
|||
http.Error(w, "could not prepare login", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
tenantSlug := s.requestTenantSlug(r.Host)
|
||||
tenantLogin := tenantSlug != ""
|
||||
loginContext := "SYSTEM ADMINISTRATION"
|
||||
loginMessage := "Sign in through the configured identity provider. System administration is not tied to a tenant."
|
||||
passwordButton := "LOGIN"
|
||||
if tenantLogin {
|
||||
loginContext = strings.ToUpper(tenantSlug) + " · TENANT ADMINISTRATION"
|
||||
loginMessage = "Sign in with your tenant database account."
|
||||
passwordButton = "LOGIN TO " + strings.ToUpper(tenantSlug)
|
||||
}
|
||||
page := strings.NewReplacer(
|
||||
"{{CSRF_TOKEN}}", html.EscapeString(csrfToken),
|
||||
"{{LOCAL_STYLE}}", hiddenStyle(!s.cfg.LocalLogin),
|
||||
"{{SSO_STYLE}}", hiddenStyle(!s.hasOIDC()),
|
||||
"{{LOGIN_CONTEXT}}", html.EscapeString(loginContext),
|
||||
"{{LOGIN_MESSAGE}}", html.EscapeString(loginMessage),
|
||||
"{{PASSWORD_BUTTON}}", html.EscapeString(passwordButton),
|
||||
"{{LOCAL_STYLE}}", hiddenStyle(!tenantLogin || !s.cfg.LocalLogin),
|
||||
"{{SSO_STYLE}}", hiddenStyle(tenantLogin || !s.hasOIDC()),
|
||||
).Replace(string(content))
|
||||
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
||||
w.Write([]byte(page))
|
||||
|
|
|
|||
29
internal/server/tenantauth_test.go
Normal file
29
internal/server/tenantauth_test.go
Normal file
|
|
@ -0,0 +1,29 @@
|
|||
package server
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/danyel/go-loose/internal/config"
|
||||
)
|
||||
|
||||
func TestRequestTenantSlug(t *testing.T) {
|
||||
server := &Server{cfg: config.Config{AuthDomain: "auth.dev"}}
|
||||
tests := []struct {
|
||||
host string
|
||||
want string
|
||||
}{
|
||||
{host: "auth.dev", want: ""},
|
||||
{host: "auth.dev:8080", want: ""},
|
||||
{host: "nmbs.auth.dev", want: "nmbs"},
|
||||
{host: "NMBS.auth.dev:8080", want: "nmbs"},
|
||||
{host: "nested.nmbs.auth.dev", want: ""},
|
||||
{host: "localhost:8080", want: ""},
|
||||
}
|
||||
for _, test := range tests {
|
||||
t.Run(test.host, func(t *testing.T) {
|
||||
if got := server.requestTenantSlug(test.host); got != test.want {
|
||||
t.Fatalf("requestTenantSlug(%q) = %q, want %q", test.host, got, test.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
|
@ -34,6 +34,18 @@ func (s *Store) PasswordUser(ctx context.Context, email string) (User, string, e
|
|||
return user, passwordHash.String, err
|
||||
}
|
||||
|
||||
func (s *Store) HasTenantAccess(ctx context.Context, userID, tenantSlug string) (bool, error) {
|
||||
var allowed bool
|
||||
err := s.db.QueryRowContext(ctx, `
|
||||
SELECT EXISTS(
|
||||
SELECT 1
|
||||
FROM memberships m
|
||||
JOIN tenants t ON t.id = m.tenant_id
|
||||
WHERE m.user_id = $1 AND t.slug = $2
|
||||
)`, userID, tenantSlug).Scan(&allowed)
|
||||
return allowed, err
|
||||
}
|
||||
|
||||
func (s *Store) RecordLogin(ctx context.Context, userID *string, email, remoteAddress string, successful bool, reason string) error {
|
||||
_, err := s.db.ExecContext(ctx, `
|
||||
INSERT INTO user_login_events(user_id, email, remote_address, successful, reason)
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue