Handle missing SECRET in auth flow
Lint / Lint (push) Successful in 44s
Tests / Go backend (push) Successful in 39s
Docker / Docker Build & Push (push) Successful in 3m30s
Tests / Dashboard checks (push) Successful in 46s

This commit is contained in:
Gabriel20xx committed 2026-09-15 23:27:42 +02:00
1 parent 07e25a3cf3
commit eb67f251d8
4 files changed
+43 -7

No files matched your search

+1
View File
@@ -117,6 +117,7 @@ func newAuthService(database *DB, authGuardURL string, secureCookies bool, authD
if authDisabled { if authDisabled {
opts = append(opts, sharedauth.Disabled()) opts = append(opts, sharedauth.Disabled())
} }
opts = append(opts, sharedauth.RequireSecret())
return sharedauth.NewWithStore(collabTableAuthStore{db: database}, legacySessionCookieName, secureCookies, authGuardURL, "collabtable", opts...) return sharedauth.NewWithStore(collabTableAuthStore{db: database}, legacySessionCookieName, secureCookies, authGuardURL, "collabtable", opts...)
} }
-4
View File
@@ -45,10 +45,6 @@ func main() {
os.Exit(1) os.Exit(1)
} }
internalServiceSecret := strings.TrimSpace(os.Getenv("SECRET")) internalServiceSecret := strings.TrimSpace(os.Getenv("SECRET"))
if internalServiceSecret == "" {
fmt.Fprintln(os.Stderr, "SECRET environment variable is required")
os.Exit(1)
}
ctx, cancel := context.WithCancel(context.Background()) ctx, cancel := context.WithCancel(context.Background())
defer cancel() defer cancel()
+34 -3
View File
@@ -169,6 +169,7 @@ import (
"errors" "errors"
"io" "io"
"net/http" "net/http"
"os"
"strconv" "strconv"
"strings" "strings"
"time" "time"
@@ -219,6 +220,7 @@ var (
// message rather than a generic "internal error" that would be // message rather than a generic "internal error" that would be
// indistinguishable from any other server bug. // indistinguishable from any other server bug.
errAuthGuardUnavailable = errors.New("Unable to reach the authentication service. Please try again shortly.") errAuthGuardUnavailable = errors.New("Unable to reach the authentication service. Please try again shortly.")
errSecretNotSet = errors.New("SECRET environment variable is not set.")
errSelfServiceProfile = errors.New("Self-service profile editing is only available to administrator accounts; ask an administrator to update this account.") errSelfServiceProfile = errors.New("Self-service profile editing is only available to administrator accounts; ask an administrator to update this account.")
) )
@@ -272,7 +274,8 @@ type Service struct {
// Service (auth turned on, but no URL known yet) still has a non-nil // Service (auth turned on, but no URL known yet) still has a non-nil
// client, just one whose calls fail until SetAuthGuardBaseURL supplies a // client, just one whose calls fail until SetAuthGuardBaseURL supplies a
// real base URL. // real base URL.
authGuard *authclient.Client authGuard *authclient.Client
configurationError error
} }
// ServiceOption configures optional New/NewWithStore construction behavior. // ServiceOption configures optional New/NewWithStore construction behavior.
@@ -281,7 +284,8 @@ type Service struct {
type ServiceOption func(*serviceOptions) type ServiceOption func(*serviceOptions)
type serviceOptions struct { type serviceOptions struct {
disabled bool disabled bool
requireSecret bool
} }
// Disabled explicitly builds a Service in auth-disabled mode (see the // Disabled explicitly builds a Service in auth-disabled mode (see the
@@ -295,6 +299,14 @@ func Disabled() ServiceOption {
return func(o *serviceOptions) { o.disabled = true } return func(o *serviceOptions) { o.disabled = true }
} }
// RequireSecret keeps the service available when SECRET is omitted, but makes
// the public auth status/me endpoints report the configuration error so the
// frontend can show it in the auth screen. Internal-service routes remain
// fail-closed until a secret is configured.
func RequireSecret() ServiceOption {
return func(o *serviceOptions) { o.requireSecret = true }
}
// New constructs a Service backed by the media family's shared `settings` // New constructs a Service backed by the media family's shared `settings`
// table (pgSettingsStore) for the login-required toggle and setup-claim // table (pgSettingsStore) for the login-required toggle and setup-claim
// flag, and by db directly for the unrelated "moderatable platform users" // flag, and by db directly for the unrelated "moderatable platform users"
@@ -336,7 +348,11 @@ func NewWithStore(store ProxyStore, cookieName string, secureCookies bool, authG
// moment one arrives. // moment one arrives.
client = authclient.New(strings.TrimSpace(authGuardURL), authclient.WithProjectKey(projectKey)) client = authclient.New(strings.TrimSpace(authGuardURL), authclient.WithProjectKey(projectKey))
} }
return &Service{store: store, cookieName: cookieName, secureCookies: secureCookies, authGuard: client} var configurationError error
if options.requireSecret && !options.disabled && strings.TrimSpace(os.Getenv("SECRET")) == "" {
configurationError = errSecretNotSet
}
return &Service{store: store, cookieName: cookieName, secureCookies: secureCookies, authGuard: client, configurationError: configurationError}
} }
// pgSettingsStore is the default ProxyStore New builds over the media // pgSettingsStore is the default ProxyStore New builds over the media
@@ -479,6 +495,9 @@ func (s *Service) currentProfile(ctx context.Context, token string) (*authclient
// RequireAdminIfLoginRequired) resolves a session through - none of them // RequireAdminIfLoginRequired) resolves a session through - none of them
// needed to change for this migration, only what CurrentUser itself does. // needed to change for this migration, only what CurrentUser itself does.
func (s *Service) CurrentUser(r *http.Request) (*ProxyUser, error) { func (s *Service) CurrentUser(r *http.Request) (*ProxyUser, error) {
if s.configurationError != nil {
return nil, s.configurationError
}
if !s.enabled() { if !s.enabled() {
user := localProfile user := localProfile
return &user, nil return &user, nil
@@ -603,6 +622,10 @@ func IsAdmin(user *ProxyUser) bool {
} }
func (s *Service) Me(w http.ResponseWriter, r *http.Request) { func (s *Service) Me(w http.ResponseWriter, r *http.Request) {
if s.configurationError != nil {
writeProxyError(w, http.StatusInternalServerError, s.configurationError.Error())
return
}
user, err := s.CurrentUser(r) user, err := s.CurrentUser(r)
if err != nil { if err != nil {
writeProxyError(w, http.StatusInternalServerError, errAuthGuardUnavailable.Error()) writeProxyError(w, http.StatusInternalServerError, errAuthGuardUnavailable.Error())
@@ -682,6 +705,10 @@ func (s *Service) UpdateMe(w http.ResponseWriter, r *http.Request) {
// AdminNeeded answers GET /auth/bootstrap/admin-needed. See the package doc // AdminNeeded answers GET /auth/bootstrap/admin-needed. See the package doc
// comment's "Setup flow" section. // comment's "Setup flow" section.
func (s *Service) AdminNeeded(w http.ResponseWriter, r *http.Request) { func (s *Service) AdminNeeded(w http.ResponseWriter, r *http.Request) {
if s.configurationError != nil {
writeProxyError(w, http.StatusInternalServerError, s.configurationError.Error())
return
}
if !s.enabled() { if !s.enabled() {
writeProxyJSON(w, http.StatusOK, map[string]bool{"adminNeeded": false}) writeProxyJSON(w, http.StatusOK, map[string]bool{"adminNeeded": false})
return return
@@ -741,6 +768,10 @@ func (s *Service) SetLoginRequired(ctx context.Context, required bool) error {
} }
func (s *Service) Status(w http.ResponseWriter, r *http.Request) { func (s *Service) Status(w http.ResponseWriter, r *http.Request) {
if s.configurationError != nil {
writeProxyError(w, http.StatusInternalServerError, s.configurationError.Error())
return
}
if !s.enabled() { if !s.enabled() {
user := localProfile user := localProfile
writeProxyJSON(w, http.StatusOK, map[string]any{"setupRequired": false, "authenticated": true, "authRequired": true, "user": &user}) writeProxyJSON(w, http.StatusOK, map[string]any{"setupRequired": false, "authenticated": true, "authRequired": true, "user": &user})
@@ -92,6 +92,7 @@ ERR_FEATURE_REQUIRES_AUTHGUARD = "This feature requires AUTHGUARD_URL to be conf
# never this error - so every caller can safely report this same message # never this error - so every caller can safely report this same message
# rather than a generic "internal error" indistinguishable from any other bug. # rather than a generic "internal error" indistinguishable from any other bug.
ERR_AUTHGUARD_UNAVAILABLE = "Unable to reach the authentication service. Please try again shortly." ERR_AUTHGUARD_UNAVAILABLE = "Unable to reach the authentication service. Please try again shortly."
ERR_SECRET_NOT_SET = "SECRET environment variable is not set."
# _LOCAL_PROFILE is the fixed placeholder identity every handler reports when # _LOCAL_PROFILE is the fixed placeholder identity every handler reports when
# auth is disabled (get_client(request) returns None, i.e. AUTHGUARD_URL was # auth is disabled (get_client(request) returns None, i.e. AUTHGUARD_URL was
@@ -242,6 +243,7 @@ def build_auth_router(
legacy_cookie_name: str = "", legacy_cookie_name: str = "",
secure_cookie: bool = False, secure_cookie: bool = False,
cookie_name: str = DEFAULT_COOKIE_NAME, cookie_name: str = DEFAULT_COOKIE_NAME,
configuration_error: str | None = None,
) -> APIRouter: ) -> APIRouter:
"""Builds a ready-to-mount APIRouter implementing the full standardized """Builds a ready-to-mount APIRouter implementing the full standardized
AuthGuard-proxy surface (no prefix baked in - mount it at "/api/auth", AuthGuard-proxy surface (no prefix baked in - mount it at "/api/auth",
@@ -250,6 +252,10 @@ def build_auth_router(
router = APIRouter() router = APIRouter()
def _ensure_configured() -> None:
if configuration_error:
raise HTTPException(status_code=500, detail=configuration_error)
def _enabled(client: Optional[AuthClient]) -> bool: def _enabled(client: Optional[AuthClient]) -> bool:
return client is not None return client is not None
@@ -328,6 +334,7 @@ def build_auth_router(
store: ProxyStore = Depends(get_store), # noqa: B008 store: ProxyStore = Depends(get_store), # noqa: B008
client: Optional[AuthClient] = Depends(get_client), # noqa: B008 client: Optional[AuthClient] = Depends(get_client), # noqa: B008
) -> dict[str, Any]: ) -> dict[str, Any]:
_ensure_configured()
login_required = await store.login_required() login_required = await store.login_required()
if not _enabled(client): if not _enabled(client):
return {"user": _user_payload(_LOCAL_PROFILE), "authRequired": login_required} return {"user": _user_payload(_LOCAL_PROFILE), "authRequired": login_required}
@@ -363,6 +370,7 @@ def build_auth_router(
store: ProxyStore = Depends(get_store), # noqa: B008 store: ProxyStore = Depends(get_store), # noqa: B008
client: Optional[AuthClient] = Depends(get_client), # noqa: B008 client: Optional[AuthClient] = Depends(get_client), # noqa: B008
) -> dict[str, Any]: ) -> dict[str, Any]:
_ensure_configured()
if not _enabled(client): if not _enabled(client):
return { return {
"setupRequired": False, "setupRequired": False,