Compare commits
2
Commits
803c3ab3ce
...
6e13364ebd
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
6e13364ebd | ||
|
|
aae8d3807d |
No files matched your search
+134
-976
File diff suppressed because it is too large.
Load diff
+41
-170
@@ -1,194 +1,65 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"context"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
authclient "repos.gfranz.ch/Gabriel20xx/shared/backend/authclient"
|
||||
)
|
||||
|
||||
// unreachableAuthGuardClient returns an authclient.Client pointed at a real
|
||||
// address that is guaranteed to refuse the connection: an httptest.Server
|
||||
// that has already been closed. This exercises a genuine transport-level
|
||||
// failure (connection refused), the same failure mode as "AUTHGUARD_URL is
|
||||
// configured but AuthGuard is down/unreachable", rather than simulating it by
|
||||
// hand.
|
||||
func unreachableAuthGuardClient(t *testing.T) *authclient.Client {
|
||||
t.Helper()
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(http.ResponseWriter, *http.Request) {}))
|
||||
url := srv.URL
|
||||
srv.Close()
|
||||
return authclient.New(url)
|
||||
}
|
||||
// The bulk of what auth_test.go used to cover (username/email normalization,
|
||||
// session-cookie parsing, AuthGuard-unreachable error surfacing, AuthGuard
|
||||
// error forwarding) is now sharedauth's own responsibility and covered by
|
||||
// that package's tests (shared/backend/auth). What's left to test here is
|
||||
// CollabTable's own tiny addition: the collabTableAuthStore adapter wired
|
||||
// into newAuthService (see auth.go).
|
||||
|
||||
func TestAuthNormalization(t *testing.T) {
|
||||
username, err := normalizeUsername(" admin ")
|
||||
if err != nil || username != "admin" {
|
||||
t.Fatalf("normalizeUsername() = %q, %v", username, err)
|
||||
}
|
||||
|
||||
email, err := normalizeEmail(" Admin@Example.COM ")
|
||||
if err != nil || email != "admin@example.com" {
|
||||
t.Fatalf("normalizeEmail() = %q, %v", email, err)
|
||||
}
|
||||
|
||||
if err := validatePassword("short"); err == nil {
|
||||
t.Fatal("validatePassword() accepted a short password")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSessionTokenReadsAuthGuardCookie(t *testing.T) {
|
||||
a := &AuthService{}
|
||||
req := httptest.NewRequest(http.MethodGet, "/api/auth/status", nil)
|
||||
req.AddCookie(&http.Cookie{Name: authclient.DefaultCookieName, Value: "sometoken"})
|
||||
|
||||
if got := a.sessionToken(req); got != "sometoken" {
|
||||
t.Fatalf("sessionToken() = %q, want %q", got, "sometoken")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSessionTokenIgnoresLegacyCookieName(t *testing.T) {
|
||||
// The pre-migration collabtable_session cookie is no longer read as a
|
||||
// session credential; only AuthGuard's own auth_session cookie is.
|
||||
a := &AuthService{}
|
||||
req := httptest.NewRequest(http.MethodGet, "/api/auth/status", nil)
|
||||
req.AddCookie(&http.Cookie{Name: legacySessionCookieName, Value: "stale-value"})
|
||||
|
||||
if got := a.sessionToken(req); got != "" {
|
||||
t.Fatalf("sessionToken() = %q, want empty for a legacy-only cookie", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestWriteAuthGuardErrorForwardsAPIError(t *testing.T) {
|
||||
rec := httptest.NewRecorder()
|
||||
writeAuthGuardError(rec, &authclient.APIError{StatusCode: http.StatusConflict, Message: "username or email is already in use"}, "fallback")
|
||||
|
||||
if rec.Code != http.StatusConflict {
|
||||
t.Fatalf("status = %d, want %d", rec.Code, http.StatusConflict)
|
||||
}
|
||||
if body := rec.Body.String(); body == "" {
|
||||
t.Fatal("response body was empty")
|
||||
}
|
||||
}
|
||||
|
||||
func TestWriteAuthGuardErrorFallsBackForTransportFailures(t *testing.T) {
|
||||
rec := httptest.NewRecorder()
|
||||
writeAuthGuardError(rec, errors.New("dial tcp: connection refused"), "unable to reach AuthGuard")
|
||||
|
||||
if rec.Code != http.StatusInternalServerError {
|
||||
t.Fatalf("status = %d, want %d", rec.Code, http.StatusInternalServerError)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCurrentUserIDUsesPlaceholderWhenAuthDisabled(t *testing.T) {
|
||||
a := &AuthService{}
|
||||
req := httptest.NewRequest(http.MethodGet, "/api/auth/token/status", nil)
|
||||
|
||||
id, ok, err := a.currentUserID(req)
|
||||
func TestCollabTableAuthStoreLoginRequiredAlwaysTrue(t *testing.T) {
|
||||
store := collabTableAuthStore{}
|
||||
required, err := store.LoginRequired(context.Background())
|
||||
if err != nil {
|
||||
t.Fatalf("currentUserID() error = %v, want nil in disabled mode", err)
|
||||
t.Fatalf("LoginRequired() error = %v", err)
|
||||
}
|
||||
if !ok {
|
||||
t.Fatal("currentUserID() ok = false, want true in disabled mode (every request shares the placeholder identity)")
|
||||
}
|
||||
if id != localProfile.ID {
|
||||
t.Fatalf("currentUserID() id = %d, want %d (localProfile.ID)", id, localProfile.ID)
|
||||
if !required {
|
||||
t.Fatal("LoginRequired() = false, want true: CollabTable always requires a session when AuthGuard is configured")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRequireSessionLetsRequestThroughWhenAuthDisabled(t *testing.T) {
|
||||
a := &AuthService{}
|
||||
nextCalled := false
|
||||
handler := a.requireSession(http.HandlerFunc(func(http.ResponseWriter, *http.Request) {
|
||||
nextCalled = true
|
||||
}))
|
||||
|
||||
req := httptest.NewRequest(http.MethodGet, "/api/tech-stack", nil)
|
||||
rec := httptest.NewRecorder()
|
||||
handler.ServeHTTP(rec, req)
|
||||
|
||||
if !nextCalled {
|
||||
t.Fatal("requireSession did not let the request through despite auth being disabled (AUTHGUARD_URL unset)")
|
||||
func TestCollabTableAuthStoreSetLoginRequiredIsNoOp(t *testing.T) {
|
||||
store := collabTableAuthStore{}
|
||||
if err := store.SetLoginRequired(context.Background(), false); err != nil {
|
||||
t.Fatalf("SetLoginRequired() error = %v, want nil (CollabTable has no such toggle)", err)
|
||||
}
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("status = %d, want %d", rec.Code, http.StatusOK)
|
||||
// Confirm it really didn't change anything observable.
|
||||
required, err := store.LoginRequired(context.Background())
|
||||
if err != nil {
|
||||
t.Fatalf("LoginRequired() error = %v", err)
|
||||
}
|
||||
if !required {
|
||||
t.Fatal("SetLoginRequired(false) unexpectedly changed LoginRequired()'s answer")
|
||||
}
|
||||
}
|
||||
|
||||
// The following tests cover the specific failure mode of AUTHGUARD_URL being
|
||||
// configured but AuthGuard being unreachable (connection refused). This must
|
||||
// never be silently treated as "no session" (which would either let an
|
||||
// unauthenticated request through, for requireSession, or show a bare "please
|
||||
// log in" screen with no indication anything is wrong, for handleStatus) --
|
||||
// it must surface as a distinct, visible error. See currentUser/
|
||||
// currentProfile's doc comments and errAuthGuardUnavailable.
|
||||
|
||||
func TestCurrentUserSurfacesErrorWhenAuthGuardUnreachable(t *testing.T) {
|
||||
a := &AuthService{authGuard: unreachableAuthGuardClient(t)}
|
||||
req := httptest.NewRequest(http.MethodGet, "/api/status", nil)
|
||||
req.AddCookie(&http.Cookie{Name: authclient.DefaultCookieName, Value: "sometoken"})
|
||||
|
||||
user, err := a.currentUser(req)
|
||||
if err == nil {
|
||||
t.Fatal("currentUser() returned no error for an unreachable AuthGuard; want a transport error")
|
||||
}
|
||||
if errors.Is(err, authclient.ErrInvalidSession) {
|
||||
t.Fatal("currentUser() classified a transport failure as ErrInvalidSession -- this would make requireSession treat 'AuthGuard is down' as 'not logged in' instead of a 500")
|
||||
}
|
||||
if user != nil {
|
||||
t.Fatalf("currentUser() returned a user (%+v) despite AuthGuard being unreachable", user)
|
||||
func TestNewAuthServiceBuildsAService(t *testing.T) {
|
||||
// newAuthService must not panic given a nil *DB and no AuthGuard URL
|
||||
// (auth-disabled mode) -- the store adapter's IsSetupClaimed/
|
||||
// TryClaimSetup/UnclaimSetup only get called once a real request comes in
|
||||
// and AuthGuard is enabled, so construction alone must be safe.
|
||||
if service := newAuthService(nil, "", false); service == nil {
|
||||
t.Fatal("newAuthService() returned nil")
|
||||
}
|
||||
}
|
||||
|
||||
func TestCurrentProfileSurfacesErrorWhenAuthGuardUnreachable(t *testing.T) {
|
||||
a := &AuthService{authGuard: unreachableAuthGuardClient(t)}
|
||||
req := httptest.NewRequest(http.MethodGet, "/api/auth/status", nil)
|
||||
req.AddCookie(&http.Cookie{Name: authclient.DefaultCookieName, Value: "sometoken"})
|
||||
func TestExtractBearerRequiresBearerPrefix(t *testing.T) {
|
||||
req := httptest.NewRequest(http.MethodGet, "/api/lists", nil)
|
||||
req.Header.Set("Authorization", "Bearer sometoken")
|
||||
if got := extractBearer(req); got != "sometoken" {
|
||||
t.Fatalf("extractBearer() = %q, want %q", got, "sometoken")
|
||||
}
|
||||
|
||||
profile, token, err := a.currentProfile(req)
|
||||
if err == nil {
|
||||
t.Fatal("currentProfile() returned no error for an unreachable AuthGuard; want a transport error")
|
||||
}
|
||||
if profile != nil {
|
||||
t.Fatalf("currentProfile() returned a profile (%+v) despite AuthGuard being unreachable", profile)
|
||||
}
|
||||
if token != "" {
|
||||
t.Fatalf("currentProfile() returned a token (%q) alongside an error", token)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCurrentUserIDSurfacesErrorWhenAuthGuardUnreachable(t *testing.T) {
|
||||
a := &AuthService{authGuard: unreachableAuthGuardClient(t)}
|
||||
req := httptest.NewRequest(http.MethodGet, "/api/auth/token/status", nil)
|
||||
req.AddCookie(&http.Cookie{Name: authclient.DefaultCookieName, Value: "sometoken"})
|
||||
|
||||
if _, ok, err := a.currentUserID(req); err == nil || ok {
|
||||
t.Fatalf("currentUserID() = (ok=%v, err=%v), want ok=false and a non-nil transport error", ok, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRequireSessionReturns500RatherThanLettingRequestThroughWhenAuthGuardUnreachable(t *testing.T) {
|
||||
a := &AuthService{authGuard: unreachableAuthGuardClient(t)}
|
||||
nextCalled := false
|
||||
handler := a.requireSession(http.HandlerFunc(func(http.ResponseWriter, *http.Request) {
|
||||
nextCalled = true
|
||||
}))
|
||||
|
||||
req := httptest.NewRequest(http.MethodGet, "/api/status", nil)
|
||||
req.AddCookie(&http.Cookie{Name: authclient.DefaultCookieName, Value: "sometoken"})
|
||||
rec := httptest.NewRecorder()
|
||||
handler.ServeHTTP(rec, req)
|
||||
|
||||
if nextCalled {
|
||||
t.Fatal("requireSession let the request through to the wrapped handler despite AuthGuard being unreachable")
|
||||
}
|
||||
if rec.Code != http.StatusInternalServerError {
|
||||
t.Fatalf("status = %d, want %d (must not be 401 'please log in' or 200)", rec.Code, http.StatusInternalServerError)
|
||||
}
|
||||
if body := rec.Body.String(); !strings.Contains(strings.ToLower(body), "authentication service") {
|
||||
t.Fatalf("response body = %q, want a message identifying the authentication service as the problem", body)
|
||||
req = httptest.NewRequest(http.MethodGet, "/api/lists", nil)
|
||||
req.Header.Set("Authorization", "sometoken")
|
||||
if got := extractBearer(req); got != "" {
|
||||
t.Fatalf("extractBearer() = %q, want empty for a header missing the Bearer prefix", got)
|
||||
}
|
||||
}
|
||||
+20
-38
@@ -152,16 +152,16 @@ func (d *DB) initSchema(ctx context.Context) error {
|
||||
CHECK (id = 1)
|
||||
);
|
||||
|
||||
-- authguard_totp_cache is a best-effort, locally-cached mirror of "does
|
||||
-- this AuthGuard account have TOTP enabled", keyed by AuthGuard's own
|
||||
-- numeric user id. AuthGuard's HTTP API (deliberately not modified by
|
||||
-- this migration) has no endpoint to query current TOTP status, only to
|
||||
-- enable/verify/disable it, so CollabTable keeps this cache updated
|
||||
-- itself at every point it can observe the true state (successful TOTP
|
||||
-- verify/disable calls, and a successful login attempted without a TOTP
|
||||
-- token, which AuthGuard would have rejected had TOTP been enabled). See
|
||||
-- handleTOTPStatus's doc comment in auth.go for the full reasoning and
|
||||
-- its known staleness caveat.
|
||||
-- authguard_totp_cache is RETIRED as of the migration onto
|
||||
-- shared/backend/auth (sharedauth.Service): it used to be a
|
||||
-- best-effort, locally-cached mirror of "does this AuthGuard account
|
||||
-- have TOTP enabled", keyed by AuthGuard's own numeric user id, needed
|
||||
-- because AuthGuard's HTTP API had no endpoint to query current TOTP
|
||||
-- status, only to enable/verify/disable it. sharedauth.Service's
|
||||
-- Me/Status/TOTPStatus now read TOTP-enabled status live from
|
||||
-- AuthGuard's GET /api/me on every request instead, so no Go code
|
||||
-- reads or writes this table anymore. Left in place rather than
|
||||
-- dropped, same as auth_users/auth_sessions above.
|
||||
CREATE TABLE IF NOT EXISTS authguard_totp_cache (
|
||||
authguard_user_id BIGINT PRIMARY KEY,
|
||||
totp_enabled BOOLEAN NOT NULL DEFAULT FALSE,
|
||||
@@ -276,34 +276,16 @@ func (d *DB) UnclaimSetup(ctx context.Context) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetCachedTOTPEnabled returns the best-effort locally-cached TOTP-enabled
|
||||
// state for an AuthGuard account, or false if this instance has never
|
||||
// observed that account's TOTP state. See handleTOTPStatus's doc comment in
|
||||
// auth.go.
|
||||
func (d *DB) GetCachedTOTPEnabled(ctx context.Context, authGuardUserID int64) (bool, error) {
|
||||
var enabled bool
|
||||
err := d.pool.QueryRow(ctx, `SELECT totp_enabled FROM authguard_totp_cache WHERE authguard_user_id = $1`, authGuardUserID).Scan(&enabled)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return false, nil
|
||||
}
|
||||
if err != nil {
|
||||
return false, fmt.Errorf("get cached totp state: %w", err)
|
||||
}
|
||||
return enabled, nil
|
||||
}
|
||||
|
||||
// SetCachedTOTPEnabled upserts the best-effort locally-cached TOTP-enabled
|
||||
// state for an AuthGuard account.
|
||||
func (d *DB) SetCachedTOTPEnabled(ctx context.Context, authGuardUserID int64, enabled bool) error {
|
||||
_, err := d.pool.Exec(ctx, `
|
||||
INSERT INTO authguard_totp_cache (authguard_user_id, totp_enabled, updated_at) VALUES ($1, $2, now())
|
||||
ON CONFLICT (authguard_user_id) DO UPDATE SET totp_enabled = $2, updated_at = now()
|
||||
`, authGuardUserID, enabled)
|
||||
if err != nil {
|
||||
return fmt.Errorf("set cached totp state: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
// Note: this instance used to also keep a local best-effort cache of each
|
||||
// AuthGuard account's TOTP-enabled state (GetCachedTOTPEnabled/
|
||||
// SetCachedTOTPEnabled, backed by the authguard_totp_cache table above) --
|
||||
// that existed only because the pre-migration code believed AuthGuard could
|
||||
// not report TOTP status live. It can (GET /api/me), so sharedauth.Service's
|
||||
// Me/Status/TOTPStatus now read it live from AuthGuard directly and this
|
||||
// cache's Go code was deleted along with the migration onto that shared
|
||||
// package. The authguard_totp_cache table itself (and any rows already in
|
||||
// it) is left in place rather than dropped, same as auth_users/auth_sessions
|
||||
// above.
|
||||
|
||||
func (d *DB) hasAPIToken(ctx context.Context, userID int64) (bool, error) {
|
||||
var exists bool
|
||||
|
||||
@@ -6,6 +6,6 @@ import (
|
||||
)
|
||||
|
||||
func TestRegisterRoutes(t *testing.T) {
|
||||
server := &Server{auth: &AuthService{}}
|
||||
server := &Server{auth: newAuthService(nil, "", false)}
|
||||
server.registerRoutes(http.NewServeMux(), webFS)
|
||||
}
|
||||
+31
-31
@@ -16,7 +16,7 @@ import (
|
||||
|
||||
_ "github.com/joho/godotenv/autoload"
|
||||
|
||||
authclient "repos.gfranz.ch/Gabriel20xx/shared/backend/authclient"
|
||||
sharedauth "repos.gfranz.ch/Gabriel20xx/shared/backend/auth"
|
||||
"repos.gfranz.ch/Gabriel20xx/shared/backend/carriernodeclient"
|
||||
"repos.gfranz.ch/Gabriel20xx/shared/backend/coreconfig"
|
||||
)
|
||||
@@ -30,7 +30,7 @@ var webFS embed.FS
|
||||
|
||||
type Server struct {
|
||||
db *DB
|
||||
auth *AuthService
|
||||
auth *sharedauth.Service
|
||||
startTime time.Time
|
||||
internalServiceSecret string
|
||||
coreConfig *coreconfig.Store
|
||||
@@ -57,38 +57,38 @@ func main() {
|
||||
go database.pruneExpiredSessions(ctx)
|
||||
go database.cleanupNotifications(ctx)
|
||||
|
||||
// AuthGuard is optional (see auth.go's top-of-file "Auth-disabled mode"
|
||||
// section): a nil client means every request is treated as already
|
||||
// authenticated, with nothing gated -- an explicit choice for local
|
||||
// development or a standalone deployment, not a degraded fallback.
|
||||
// AuthGuard is optional (see auth.go's top-of-file doc comment and
|
||||
// sharedauth's own "Auth-disabled mode" section): an unset AUTHGUARD_URL
|
||||
// means every request is treated as already authenticated, with nothing
|
||||
// gated -- an explicit choice for local development or a standalone
|
||||
// deployment, not a degraded fallback.
|
||||
authGuardURL := strings.TrimSpace(os.Getenv("AUTHGUARD_URL"))
|
||||
var authGuard *authclient.Client
|
||||
if authGuardURL != "" {
|
||||
authGuard = authclient.New(authGuardURL)
|
||||
fmt.Printf("auth: AuthGuard at %s\n", authGuardURL)
|
||||
} else {
|
||||
fmt.Println("auth: DISABLED (AUTHGUARD_URL not set) -- every request is treated as authenticated")
|
||||
}
|
||||
auth := newAuthService(database, authGuardURL, strings.EqualFold(os.Getenv("COOKIE_SECURE"), "true"))
|
||||
|
||||
// coreConfig holds the AuthGuard/CarrierNode URLs ProjectConfigurator pushes once this project
|
||||
// is registered there (PUT /api/core-services/internal, see registerRoutes) -- AUTHGUARD_URL and
|
||||
// CARRIERNODE_URL above/below are only the bootstrap fallback used until the first push arrives.
|
||||
// See Core/ProjectConfigurator/README.md's "Pushing core service info to other projects".
|
||||
// auth.SetAuthGuardBaseURL retargets the live AuthGuard client sharedauth.Service holds
|
||||
// internally on every push, so AuthGuard moving to a new URL takes effect without a restart -- it
|
||||
// is a no-op when this service was constructed in auth-disabled mode (AUTHGUARD_URL unset above).
|
||||
internalServiceSecret := strings.TrimSpace(os.Getenv("INTERNAL_SERVICE_SECRET"))
|
||||
carrierNodeURL := strings.TrimSpace(os.Getenv("CARRIERNODE_URL"))
|
||||
coreConfig := coreconfig.NewStore(coreconfig.Info{AuthGuardURL: authGuardURL, CarrierNodeURL: carrierNodeURL})
|
||||
if authGuard != nil {
|
||||
coreConfig.OnUpdate(func(info coreconfig.Info) {
|
||||
if info.AuthGuardURL != "" {
|
||||
authGuard.SetBaseURL(info.AuthGuardURL)
|
||||
auth.SetAuthGuardBaseURL(info.AuthGuardURL)
|
||||
}
|
||||
})
|
||||
}
|
||||
carrierNode := carriernodeclient.New(internalServiceSecret, func(context.Context) string {
|
||||
return coreConfig.CarrierNodeURL()
|
||||
})
|
||||
|
||||
auth := newAuthService(authGuard, database, strings.EqualFold(os.Getenv("COOKIE_SECURE"), "true"))
|
||||
server := &Server{
|
||||
db: database,
|
||||
auth: auth,
|
||||
@@ -165,27 +165,27 @@ func (s *Server) registerRoutes(mux *http.ServeMux, webRoot fs.FS) {
|
||||
// X-Internal-Auth-gated, not browser-session-gated -- ProjectConfigurator calls this directly
|
||||
// to push a fresh AuthGuard/CarrierNode URL (see coreConfig's construction in main above).
|
||||
mux.Handle("PUT /api/core-services/internal", coreconfig.Handler(s.internalServiceSecret, s.coreConfig))
|
||||
mux.HandleFunc("GET /api/auth/status", s.auth.handleStatus)
|
||||
mux.HandleFunc("POST /api/auth/setup", s.auth.handleSetup)
|
||||
mux.HandleFunc("POST /api/auth/login", s.auth.handleLogin)
|
||||
mux.Handle("POST /api/auth/logout", s.auth.requireSession(http.HandlerFunc(s.auth.handleLogout)))
|
||||
mux.Handle("POST /api/auth/credentials", s.auth.requireSession(http.HandlerFunc(s.auth.handleUpdateCredentials)))
|
||||
mux.Handle("GET /api/auth/users", s.auth.requireSession(http.HandlerFunc(s.auth.handleUsers)))
|
||||
mux.Handle("POST /api/auth/users", s.auth.requireSession(http.HandlerFunc(s.auth.handleUsers)))
|
||||
mux.Handle("PUT /api/auth/users/{id}", s.auth.requireSession(http.HandlerFunc(s.auth.handleUser)))
|
||||
mux.Handle("PATCH /api/auth/users/{id}", s.auth.requireSession(http.HandlerFunc(s.auth.handleUser)))
|
||||
mux.Handle("DELETE /api/auth/users/{id}", s.auth.requireSession(http.HandlerFunc(s.auth.handleUser)))
|
||||
mux.Handle("GET /api/auth/totp/status", s.auth.requireSession(http.HandlerFunc(s.auth.handleTOTPStatus)))
|
||||
mux.Handle("POST /api/auth/totp/setup", s.auth.requireSession(http.HandlerFunc(s.auth.handleTOTPSetup)))
|
||||
mux.Handle("POST /api/auth/totp/enable", s.auth.requireSession(http.HandlerFunc(s.auth.handleTOTPEnable)))
|
||||
mux.Handle("POST /api/auth/totp/disable", s.auth.requireSession(http.HandlerFunc(s.auth.handleTOTPDisable)))
|
||||
mux.Handle("GET /api/auth/token/status", s.auth.requireSession(http.HandlerFunc(s.auth.handleTokenStatus)))
|
||||
mux.Handle("POST /api/auth/token/regenerate", s.auth.requireSession(http.HandlerFunc(s.auth.handleTokenRegenerate)))
|
||||
mux.HandleFunc("GET /api/auth/status", s.auth.Status)
|
||||
mux.HandleFunc("POST /api/auth/setup", s.auth.Signup)
|
||||
mux.HandleFunc("POST /api/auth/login", s.auth.Login)
|
||||
mux.Handle("POST /api/auth/logout", s.auth.Require(http.HandlerFunc(s.auth.Logout)))
|
||||
mux.Handle("POST /api/auth/credentials", s.auth.Require(http.HandlerFunc(s.auth.UpdateMe)))
|
||||
mux.Handle("GET /api/auth/users", s.auth.Require(http.HandlerFunc(s.auth.ManagedUsers)))
|
||||
mux.Handle("POST /api/auth/users", s.auth.Require(http.HandlerFunc(s.auth.ManagedCreateUser)))
|
||||
mux.Handle("PUT /api/auth/users/{id}", s.auth.Require(http.HandlerFunc(s.auth.ManagedUpdateUser)))
|
||||
mux.Handle("PATCH /api/auth/users/{id}", s.auth.Require(http.HandlerFunc(s.auth.ManagedUpdateUser)))
|
||||
mux.Handle("DELETE /api/auth/users/{id}", s.auth.Require(http.HandlerFunc(s.auth.ManagedDeleteUser)))
|
||||
mux.Handle("GET /api/auth/totp/status", s.auth.Require(http.HandlerFunc(s.auth.TOTPStatus)))
|
||||
mux.Handle("POST /api/auth/totp/setup", s.auth.Require(http.HandlerFunc(s.auth.TOTPInitiate)))
|
||||
mux.Handle("POST /api/auth/totp/enable", s.auth.Require(http.HandlerFunc(s.auth.TOTPVerify)))
|
||||
mux.Handle("POST /api/auth/totp/disable", s.auth.Require(http.HandlerFunc(s.auth.TOTPDisable)))
|
||||
mux.Handle("GET /api/auth/token/status", s.auth.Require(http.HandlerFunc(s.handleTokenStatus)))
|
||||
mux.Handle("POST /api/auth/token/regenerate", s.auth.Require(http.HandlerFunc(s.handleTokenRegenerate)))
|
||||
|
||||
// Sync/collaboration API routes use a long-lived bearer token shared by the
|
||||
// user's devices. This is deliberately separate from browser sessions.
|
||||
api := func(handler http.Handler) http.Handler {
|
||||
return s.auth.requireAPIToken(handler)
|
||||
return requireAPIToken(s.db)(handler)
|
||||
}
|
||||
mux.Handle("GET /api/lists", api(http.HandlerFunc(s.handleListCollection)))
|
||||
mux.Handle("POST /api/lists", api(http.HandlerFunc(s.handleListCollection)))
|
||||
@@ -210,8 +210,8 @@ func (s *Server) registerRoutes(mux *http.ServeMux, webRoot fs.FS) {
|
||||
|
||||
// The dashboard is a public SPA shell, but its data and tech-stack endpoints
|
||||
// are protected by the browser session.
|
||||
mux.Handle("GET /api/tech-stack", s.auth.requireSession(http.HandlerFunc(s.handleTechStack)))
|
||||
mux.Handle("GET /web/data", s.auth.requireSession(http.HandlerFunc(s.handleWebData)))
|
||||
mux.Handle("GET /api/tech-stack", s.auth.Require(http.HandlerFunc(s.handleTechStack)))
|
||||
mux.Handle("GET /web/data", s.auth.Require(http.HandlerFunc(s.handleWebData)))
|
||||
mux.Handle("/", spaFileServer(webRoot))
|
||||
}
|
||||
|
||||
|
||||
+60
-7
@@ -37,42 +37,95 @@ export async function fetchHealth() {
|
||||
return { up: res.ok };
|
||||
}
|
||||
|
||||
// flattenAuthStatus adapts sharedauth.Service's Status/Signup/Login response
|
||||
// shape (a nested `user: {id, email, username, role, canManageUsers,
|
||||
// mfaEnabled}`, since CollabTable's AuthGuard migration onto
|
||||
// shared/backend/auth) back into the flat shape this frontend already
|
||||
// expects (AppShell.svelte reads status.username/.email/.setupRequired/
|
||||
// .authenticated directly) - keeping the rest of the frontend from needing to
|
||||
// change shape, the same translation GameStream/OmniLogger's frontends made
|
||||
// for the same migration.
|
||||
function flattenAuthStatus(payload) {
|
||||
return {
|
||||
setupRequired: payload?.setupRequired ?? false,
|
||||
authenticated: payload?.authenticated ?? false,
|
||||
authRequired: payload?.authRequired ?? true,
|
||||
id: payload?.user?.id,
|
||||
username: payload?.user?.username,
|
||||
email: payload?.user?.email,
|
||||
role: payload?.user?.role,
|
||||
canManageUsers: payload?.user?.canManageUsers,
|
||||
totpEnabled: payload?.user?.mfaEnabled,
|
||||
};
|
||||
}
|
||||
|
||||
export async function fetchAuthStatus() {
|
||||
return getJson('/api/auth/status');
|
||||
return flattenAuthStatus(await getJson('/api/auth/status'));
|
||||
}
|
||||
|
||||
export async function setupAccount(username, email, password) {
|
||||
return request('/api/auth/setup', { method: 'POST', body: JSON.stringify({ username, email, password }) });
|
||||
const { user } = await request('/api/auth/setup', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ username, email, password }),
|
||||
});
|
||||
return user;
|
||||
}
|
||||
|
||||
export async function login(identifier, password, totpToken = '') {
|
||||
return request('/api/auth/login', { method: 'POST', body: JSON.stringify({ identifier, password, totpToken }) });
|
||||
const { user } = await request('/api/auth/login', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ identifier, password, totpToken }),
|
||||
});
|
||||
return user;
|
||||
}
|
||||
|
||||
export async function fetchTotpStatus() {
|
||||
return request('/api/auth/totp/status');
|
||||
}
|
||||
|
||||
// setupTotp/enableTotp/disableTotp proxy to sharedauth.Service's
|
||||
// TOTPInitiate/TOTPVerify/TOTPDisable, whose response bodies nest their
|
||||
// payload under a `data` key (`{"data": {...}}`) instead of the pre-migration
|
||||
// flat shape - unwrapped here so TotpSettings.svelte (@gabriel20xx/web-ui),
|
||||
// which reads setup.secret/setup.otpauthUrl directly, needs no changes.
|
||||
export async function setupTotp() {
|
||||
return request('/api/auth/totp/setup', { method: 'POST' });
|
||||
const { data } = await request('/api/auth/totp/setup', { method: 'POST' });
|
||||
return { secret: data.secret, otpauthUrl: data.otpauthUrl, enabled: data.enabled };
|
||||
}
|
||||
|
||||
export async function enableTotp(token) {
|
||||
return request('/api/auth/totp/enable', { method: 'POST', body: JSON.stringify({ token }) });
|
||||
const { data } = await request('/api/auth/totp/enable', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ token }),
|
||||
});
|
||||
return { enabled: data.enabled };
|
||||
}
|
||||
|
||||
export async function disableTotp(token) {
|
||||
return request('/api/auth/totp/disable', { method: 'POST', body: JSON.stringify({ token }) });
|
||||
const { data } = await request('/api/auth/totp/disable', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ token }),
|
||||
});
|
||||
return { enabled: data.enabled };
|
||||
}
|
||||
|
||||
export async function logout() {
|
||||
return request('/api/auth/logout', { method: 'POST' });
|
||||
}
|
||||
|
||||
// updateCredentials proxies to sharedauth.Service's UpdateMe
|
||||
// (POST /api/auth/credentials), which requires a valid, non-empty email on
|
||||
// every call (it has no concept of "leave this field unchanged" for email the
|
||||
// way CollabTable's pre-migration handler did) - newUsername/newEmail must
|
||||
// always be the account's current values when the caller isn't actually
|
||||
// changing them. ProfileDialog's form (@gabriel20xx/web-ui) always pre-fills
|
||||
// and requires both fields, so AppShell.svelte's saveProfile always has them
|
||||
// on hand. newPassword remains genuinely optional (omitted/blank leaves the
|
||||
// password unchanged).
|
||||
export async function updateCredentials({ newUsername, newEmail, newPassword }) {
|
||||
return request('/api/auth/credentials', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ newUsername, newEmail, newPassword }),
|
||||
body: JSON.stringify({ username: newUsername, email: newEmail, password: newPassword }),
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -20,9 +20,15 @@
|
||||
let credentialsOpen = $state(false);
|
||||
|
||||
async function saveProfile(input) {
|
||||
// The backend's UpdateMe (POST /api/auth/credentials) requires a valid,
|
||||
// non-empty email on every call - it has no concept of "leave this field
|
||||
// unchanged" for email - so both username and email are always sent
|
||||
// as-is; ProfileDialog's form always pre-fills and requires both fields,
|
||||
// so they're never empty here. Only password is genuinely optional
|
||||
// (blank means unchanged).
|
||||
await auth.updateCredentials({
|
||||
newUsername: input.username.trim() || undefined,
|
||||
newEmail: input.email.trim() || undefined,
|
||||
newUsername: input.username.trim(),
|
||||
newEmail: input.email.trim(),
|
||||
newPassword: input.password || undefined,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
"@gabriel20xx/node-backend": patch
|
||||
---
|
||||
|
||||
`AuthClient` accepts a `projectKey` option, sent as `X-Project-Key` on every request, so AuthGuard can enforce per-user project-access restriction for Node consumers the same way the Go and Python clients already do.
|
||||
+30
@@ -98,6 +98,14 @@ public final class AuthClient {
|
||||
public static final String DEFAULT_COOKIE_NAME = "auth_session";
|
||||
public static final int DEFAULT_TIMEOUT_MILLIS = 5000;
|
||||
|
||||
/**
|
||||
* Header attached to every request when the client is constructed with a projectKey,
|
||||
* identifying the calling project to AuthGuard so it can enforce per-user project-access
|
||||
* restriction (see AuthGuard's project-scope admin UI). Mirrors Go's
|
||||
* {@code authclient.ProjectKeyHeader}.
|
||||
*/
|
||||
public static final String PROJECT_KEY_HEADER = "X-Project-Key";
|
||||
|
||||
private static final Pattern VALID_PATTERN = Pattern.compile("\"valid\"\\s*:\\s*(true|false)");
|
||||
private static final Pattern USER_ID_PATTERN = Pattern.compile("\"user_id\"\\s*:\\s*(-?\\d+)");
|
||||
private static final Pattern USERNAME_PATTERN = Pattern.compile("\"username\"\\s*:\\s*\"((?:[^\"\\\\]|\\\\.)*)\"");
|
||||
@@ -110,6 +118,7 @@ public final class AuthClient {
|
||||
private final String baseUrl;
|
||||
private final String cookieName;
|
||||
private final int timeoutMillis;
|
||||
private final String projectKey;
|
||||
|
||||
public AuthClient(String baseUrl) {
|
||||
this(baseUrl, DEFAULT_COOKIE_NAME, DEFAULT_TIMEOUT_MILLIS);
|
||||
@@ -126,9 +135,24 @@ public final class AuthClient {
|
||||
* @param timeoutMillis connect and read timeout used by {@link #validate(String)}.
|
||||
*/
|
||||
public AuthClient(String baseUrl, String cookieName, int timeoutMillis) {
|
||||
this(baseUrl, cookieName, timeoutMillis, "");
|
||||
}
|
||||
|
||||
/**
|
||||
* @param baseUrl AuthGuard's base URL (e.g. {@code https://auth.example.com}), no trailing slash required.
|
||||
* @param cookieName cookie {@link #extractToken} falls back to when there is no Authorization header;
|
||||
* blank/null defaults to {@link #DEFAULT_COOKIE_NAME}.
|
||||
* @param timeoutMillis connect and read timeout used by {@link #validate(String)}.
|
||||
* @param projectKey identifies this project to AuthGuard on every request (see
|
||||
* {@link #PROJECT_KEY_HEADER}), enabling per-user project-access
|
||||
* restriction. Normally a project's own lowercase identifier, matching
|
||||
* the key ProjectConfigurator registers it under. Blank/null disables it.
|
||||
*/
|
||||
public AuthClient(String baseUrl, String cookieName, int timeoutMillis, String projectKey) {
|
||||
this.baseUrl = normalizeBaseUrl(baseUrl);
|
||||
this.cookieName = cookieName == null || cookieName.trim().isEmpty() ? DEFAULT_COOKIE_NAME : cookieName.trim();
|
||||
this.timeoutMillis = timeoutMillis;
|
||||
this.projectKey = projectKey == null ? "" : projectKey.trim().toLowerCase();
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -583,6 +607,9 @@ public final class AuthClient {
|
||||
connection.setRequestMethod(method);
|
||||
connection.setConnectTimeout(timeoutMillis);
|
||||
connection.setReadTimeout(timeoutMillis);
|
||||
if (!projectKey.isEmpty()) {
|
||||
connection.setRequestProperty(PROJECT_KEY_HEADER, projectKey);
|
||||
}
|
||||
if (token != null && !token.isEmpty()) {
|
||||
connection.setRequestProperty("Authorization", BEARER_PREFIX + token);
|
||||
}
|
||||
@@ -673,6 +700,9 @@ public final class AuthClient {
|
||||
URL url = new URL(baseUrl + "/api/session/validate");
|
||||
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
|
||||
connection.setRequestMethod("GET");
|
||||
if (!projectKey.isEmpty()) {
|
||||
connection.setRequestProperty(PROJECT_KEY_HEADER, projectKey);
|
||||
}
|
||||
connection.setRequestProperty("Authorization", BEARER_PREFIX + token);
|
||||
connection.setConnectTimeout(timeoutMillis);
|
||||
connection.setReadTimeout(timeoutMillis);
|
||||
|
||||
@@ -25,6 +25,12 @@
|
||||
const DEFAULT_COOKIE_NAME = 'auth_session';
|
||||
const DEFAULT_TIMEOUT_MS = 5000;
|
||||
|
||||
// PROJECT_KEY_HEADER is the header AuthClient attaches to every request when
|
||||
// constructed with a projectKey, identifying the calling project to
|
||||
// AuthGuard so it can enforce per-user project-access restriction (see
|
||||
// AuthGuard's project-scope admin UI). Mirrors Go's authclient.ProjectKeyHeader.
|
||||
export const PROJECT_KEY_HEADER = 'X-Project-Key';
|
||||
|
||||
export class InvalidSessionError extends Error {
|
||||
constructor(message = 'authclient: invalid or missing session') {
|
||||
super(message);
|
||||
@@ -63,13 +69,22 @@ export class AuthClient {
|
||||
* AuthGuard on a local network is the common case for those), anything else
|
||||
* defaults to "https://". An explicit "http://" or "https://" is always left
|
||||
* as-is, overriding the inference.
|
||||
* @param {{cookieName?: string, timeoutMs?: number, fetchImpl?: typeof fetch}} [options]
|
||||
* @param {{cookieName?: string, timeoutMs?: number, fetchImpl?: typeof fetch, projectKey?: string}} [options]
|
||||
*/
|
||||
constructor(baseUrl, options = {}) {
|
||||
this.baseUrl = AuthClient._normalizeBaseUrl(baseUrl);
|
||||
this.cookieName = options.cookieName ?? DEFAULT_COOKIE_NAME;
|
||||
this.timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
|
||||
this.fetchImpl = options.fetchImpl ?? fetch;
|
||||
// projectKey identifies this project to AuthGuard on every request (see
|
||||
// PROJECT_KEY_HEADER), enabling per-user project-access restriction.
|
||||
// Normally a project's own lowercase identifier, matching the key
|
||||
// ProjectConfigurator registers it under.
|
||||
this.projectKey = String(options.projectKey ?? '').trim().toLowerCase();
|
||||
}
|
||||
|
||||
_projectKeyHeaders() {
|
||||
return this.projectKey ? { [PROJECT_KEY_HEADER]: this.projectKey } : {};
|
||||
}
|
||||
|
||||
static _normalizeBaseUrl(baseUrl) {
|
||||
@@ -142,7 +157,7 @@ export class AuthClient {
|
||||
let response;
|
||||
try {
|
||||
response = await this.fetchImpl(`${this.baseUrl}/api/session/validate`, {
|
||||
headers: { Authorization: `Bearer ${trimmed}` },
|
||||
headers: { Authorization: `Bearer ${trimmed}`, ...this._projectKeyHeaders() },
|
||||
signal: controller.signal,
|
||||
});
|
||||
} catch (err) {
|
||||
@@ -220,7 +235,7 @@ export class AuthClient {
|
||||
if (!this.baseUrl) {
|
||||
throw new Error('authclient: client has no base URL');
|
||||
}
|
||||
const headers = {};
|
||||
const headers = { ...this._projectKeyHeaders() };
|
||||
if (body !== undefined) headers['Content-Type'] = 'application/json';
|
||||
if (token) headers.Authorization = `Bearer ${token}`;
|
||||
|
||||
|
||||
@@ -61,6 +61,12 @@ DEFAULT_TIMEOUT = 5.0
|
||||
|
||||
_BEARER_PREFIX = "Bearer "
|
||||
|
||||
# PROJECT_KEY_HEADER is the header AuthClient attaches to every request when
|
||||
# constructed with project_key, identifying the calling project to AuthGuard
|
||||
# so it can enforce per-user project-access restriction (see AuthGuard's
|
||||
# project-scope admin UI). Mirrors Go's authclient.ProjectKeyHeader.
|
||||
PROJECT_KEY_HEADER = "X-Project-Key"
|
||||
|
||||
|
||||
def _normalize_base_url(base_url: str) -> str:
|
||||
trimmed = str(base_url or "").strip().rstrip("/")
|
||||
@@ -205,6 +211,7 @@ class AuthClient:
|
||||
*,
|
||||
cookie_name: str = DEFAULT_COOKIE_NAME,
|
||||
timeout: float = DEFAULT_TIMEOUT,
|
||||
project_key: str = "",
|
||||
) -> None:
|
||||
"""base_url is AuthGuard's base URL, e.g. "https://auth.example.com"
|
||||
(no trailing slash required). May be given without a scheme (e.g.
|
||||
@@ -221,6 +228,11 @@ class AuthClient:
|
||||
self.base_url = _normalize_base_url(base_url)
|
||||
self.cookie_name = cookie_name
|
||||
self.timeout = timeout
|
||||
# project_key identifies this project to AuthGuard on every request
|
||||
# (see PROJECT_KEY_HEADER), enabling per-user project-access
|
||||
# restriction. Normally a project's own lowercase identifier,
|
||||
# matching the key ProjectConfigurator registers it under.
|
||||
self.project_key = (project_key or "").strip().lower()
|
||||
|
||||
# --- session validation (the original, minimal surface) ----------------
|
||||
|
||||
@@ -238,9 +250,12 @@ class AuthClient:
|
||||
return await asyncio.to_thread(self._validate_sync, trimmed)
|
||||
|
||||
def _validate_sync(self, token: str) -> AuthGuardUser:
|
||||
headers = {"Authorization": f"{_BEARER_PREFIX}{token}"}
|
||||
if self.project_key:
|
||||
headers[PROJECT_KEY_HEADER] = self.project_key
|
||||
request = urllib.request.Request(
|
||||
f"{self.base_url}/api/session/validate",
|
||||
headers={"Authorization": f"{_BEARER_PREFIX}{token}"},
|
||||
headers=headers,
|
||||
)
|
||||
try:
|
||||
with urllib.request.urlopen(request, timeout=self.timeout) as response:
|
||||
@@ -301,6 +316,8 @@ class AuthClient:
|
||||
) -> tuple[dict[str, Any], list[str]]:
|
||||
data = None
|
||||
headers: dict[str, str] = {}
|
||||
if self.project_key:
|
||||
headers[PROJECT_KEY_HEADER] = self.project_key
|
||||
if body is not None:
|
||||
data = json.dumps(body).encode()
|
||||
headers["Content-Type"] = "application/json"
|
||||
|
||||
Reference in new issue
Block a user