Make AuthGuard integration decouple from knowing the URL at startup
Every language's AuthGuard client/service used "no URL at construction" to mean "auth disabled forever" - a live SetBaseUrl/setBaseUrl push from ProjectConfigurator could only ever retarget an *already-enabled* client, never turn one on for the first time. That made AUTHGUARD_URL a de-facto required env var everywhere, even though ProjectConfigurator can push it live after startup. - Go: shared/backend/auth's New/NewWithStore now default to a "pending" Service (still enabled, fails closed until a URL arrives) instead of disabled when authGuardURL is empty; add an explicit Disabled() option for the genuine standalone/local-dev opt-out. - Python/Node/Java: add setBaseUrl/set_base_url to each AuthClient so a client built with an empty base URL can be retargeted in place once a URL is pushed, the same as the Go client already supported. - Python/Node: add a coreconfig module (Info/Store), the framework-agnostic equivalent of shared/backend/coreconfig (Go), for services in those languages to receive ProjectConfigurator's core-services push at all. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
1 parent
c09957189f
commit
dcfdb3d7af
18 files changed
+747
-46
No files matched your search
@@ -0,0 +1,5 @@
|
|||||||
|
---
|
||||||
|
"@gabriel20xx/node-backend": minor
|
||||||
|
---
|
||||||
|
|
||||||
|
Add a `coreconfig` module (`Info`/`Store`), the Node equivalent of `shared/backend/coreconfig` (Go) and `shared_backend.coreconfig` (Python): lets a service receive AuthGuard's/CarrierNode's current URL(s) pushed live from ProjectConfigurator instead of hardcoding them in its own env vars. `AuthClient` also gains `setBaseUrl(url)`, mirroring the Go/Python/Java clients, so a service can construct it once with an empty/unknown base URL and retarget it live once a URL is pushed, rather than needing the URL to be known at construction time.
|
||||||
+94
-37
@@ -112,29 +112,45 @@
|
|||||||
// frontend (webui) confirms neither field was ever actually read
|
// frontend (webui) confirms neither field was ever actually read
|
||||||
// or set by any UI - they were dead weight even before this migration.
|
// or set by any UI - they were dead weight even before this migration.
|
||||||
//
|
//
|
||||||
// Auth-disabled mode (AUTHGUARD_URL unset)
|
// Auth-disabled mode (the Disabled() option)
|
||||||
// -----------------------------------------
|
// -------------------------------------------
|
||||||
// AUTHGUARD_URL is optional. When it is unset, Service.authGuard is nil
|
// Passing Disabled() to New/NewWithStore turns authentication off entirely
|
||||||
// (Service.enabled() reports false) and this service runs with
|
// for a Service: Service.authGuard is nil (Service.enabled() reports false),
|
||||||
// authentication turned off entirely: CurrentUser always resolves to
|
// CurrentUser always resolves to localProfile (a fixed placeholder
|
||||||
// localProfile (a fixed placeholder superadmin identity), so every request
|
// superadmin identity), so every request is treated as already authenticated
|
||||||
// is treated as already authenticated regardless of the `auth_required`
|
// regardless of the `auth_required` setting - there is no login screen and
|
||||||
// setting - there is no login screen and nothing gated. This is an explicit
|
// nothing gated. This is an explicit mode for local development or a
|
||||||
// mode for local development or a standalone deployment that doesn't want
|
// standalone deployment that doesn't want centralized identity at all; it is
|
||||||
// centralized identity, matching every other AuthGuard-migrated project's
|
// not an error condition, and there is no degraded/partial "local auth"
|
||||||
// exact convention; it is not an error condition, and there is no
|
// fallback state.
|
||||||
// degraded/partial "local auth" fallback state.
|
//
|
||||||
|
// Without Disabled(), a Service is always "enabled" - including when
|
||||||
|
// authGuardURL is empty at construction. That used to also mean disabled,
|
||||||
|
// but made AUTHGUARD_URL a de-facto requirement: a Service built with no URL
|
||||||
|
// could never start authenticating later, since a live retarget
|
||||||
|
// (SetAuthGuardBaseURL, wired as ProjectConfigurator's coreconfig push) had
|
||||||
|
// no client to retarget. Now an empty authGuardURL just means "pending": the
|
||||||
|
// Service still gates every request, but its calls to AuthGuard fail (with
|
||||||
|
// errAuthGuardUnavailable, a 401) until a URL arrives - normally within
|
||||||
|
// ProjectConfigurator's periodic re-push window (coreconfig's doc comment),
|
||||||
|
// converging on its own with no restart needed, the same way a live
|
||||||
|
// AuthGuard URL *change* already did before this pending mode existed. A
|
||||||
|
// project that wants no AuthGuard integration at all (the old meaning of an
|
||||||
|
// unset AUTHGUARD_URL) must now say so explicitly via Disabled().
|
||||||
//
|
//
|
||||||
// Features that need a *real* backing identity rather than just an access
|
// Features that need a *real* backing identity rather than just an access
|
||||||
// gate - TOTP (initiate/verify/disable), self-service profile editing, and
|
// gate - TOTP (initiate/verify/disable), self-service profile editing, and
|
||||||
// admin user-management's mutating calls - have nothing meaningful to do
|
// admin user-management's mutating calls - have nothing meaningful to do
|
||||||
// without AuthGuard (there is no account to attach a TOTP secret to, no
|
// in Disabled() mode (there is no account to attach a TOTP secret to, no
|
||||||
// profile to edit, no user store to create/update/delete against) and
|
// profile to edit, no user store to create/update/delete against) and
|
||||||
// return a clear errFeatureRequiresAuthGuard error instead of silently
|
// return a clear errFeatureRequiresAuthGuard error instead of silently
|
||||||
// no-opping or faking data. GET /api/auth/users is the one exception:
|
// no-opping or faking data. GET /api/auth/users is the one exception:
|
||||||
// consistent with "nothing gated", it returns an empty list rather than an
|
// consistent with "nothing gated", it returns an empty list rather than an
|
||||||
// error, since listing (unlike mutating) has an honest, unsurprising answer
|
// error, since listing (unlike mutating) has an honest, unsurprising answer
|
||||||
// when there is no user store: there are no managed users to show.
|
// when there is no user store: there are no managed users to show. In
|
||||||
|
// pending mode (enabled, but no URL yet) these same calls are attempted for
|
||||||
|
// real and fail closed with errAuthGuardUnavailable instead, since AuthGuard
|
||||||
|
// integration genuinely is turned on here - it just isn't reachable yet.
|
||||||
//
|
//
|
||||||
// No local admin-reset flow
|
// No local admin-reset flow
|
||||||
// --------------------------
|
// --------------------------
|
||||||
@@ -191,9 +207,10 @@ var (
|
|||||||
ErrForbidden = errors.New("administrator access required")
|
ErrForbidden = errors.New("administrator access required")
|
||||||
ErrInvalidLogin = errors.New("Invalid username or password.")
|
ErrInvalidLogin = errors.New("Invalid username or password.")
|
||||||
// errFeatureRequiresAuthGuard is returned by the handlers that need a
|
// errFeatureRequiresAuthGuard is returned by the handlers that need a
|
||||||
// real backing identity (not just an access gate) when AUTHGUARD_URL is
|
// real backing identity (not just an access gate) when this Service was
|
||||||
// unset; see the top-of-file doc comment's "Auth-disabled mode" section.
|
// constructed with Disabled(); see the top-of-file doc comment's
|
||||||
errFeatureRequiresAuthGuard = errors.New("This feature requires AUTHGUARD_URL to be configured.")
|
// "Auth-disabled mode" section.
|
||||||
|
errFeatureRequiresAuthGuard = errors.New("This feature requires AuthGuard to be enabled.")
|
||||||
// errAuthGuardUnavailable is returned whenever CurrentUser/currentProfile
|
// errAuthGuardUnavailable is returned whenever CurrentUser/currentProfile
|
||||||
// propagate a non-nil error: by construction that only happens when
|
// propagate a non-nil error: by construction that only happens when
|
||||||
// AuthGuard could not be reached or gave an unusable response - a real
|
// AuthGuard could not be reached or gave an unusable response - a real
|
||||||
@@ -215,7 +232,7 @@ const (
|
|||||||
)
|
)
|
||||||
|
|
||||||
// localProfile is the fixed placeholder identity CurrentUser/Signup/Login
|
// localProfile is the fixed placeholder identity CurrentUser/Signup/Login
|
||||||
// report when auth is disabled (AUTHGUARD_URL unset). Role is superadmin so
|
// report when auth is disabled (Disabled()). Role is superadmin so
|
||||||
// CanManageUsers reports true, consistent with "nothing gated": the
|
// CanManageUsers reports true, consistent with "nothing gated": the
|
||||||
// frontend's own admin-only UI sections become visible too, even though the
|
// frontend's own admin-only UI sections become visible too, even though the
|
||||||
// underlying admin endpoints have nothing to manage.
|
// underlying admin endpoints have nothing to manage.
|
||||||
@@ -250,11 +267,34 @@ type Service struct {
|
|||||||
store ProxyStore
|
store ProxyStore
|
||||||
cookieName string
|
cookieName string
|
||||||
secureCookies bool
|
secureCookies bool
|
||||||
// authGuard is nil when AUTHGUARD_URL is unset; see the top-of-file doc
|
// authGuard is nil only when this Service was built with Disabled(); see
|
||||||
// comment's "Auth-disabled mode" section.
|
// the top-of-file doc comment's "Auth-disabled mode" section. A "pending"
|
||||||
|
// Service (auth turned on, but no URL known yet) still has a non-nil
|
||||||
|
// client, just one whose calls fail until SetAuthGuardBaseURL supplies a
|
||||||
|
// real base URL.
|
||||||
authGuard *authclient.Client
|
authGuard *authclient.Client
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ServiceOption configures optional New/NewWithStore construction behavior.
|
||||||
|
// Variadic and trailing, so every existing call site keeps compiling
|
||||||
|
// unchanged; only a project that wants Disabled() needs to pass one.
|
||||||
|
type ServiceOption func(*serviceOptions)
|
||||||
|
|
||||||
|
type serviceOptions struct {
|
||||||
|
disabled bool
|
||||||
|
}
|
||||||
|
|
||||||
|
// Disabled explicitly builds a Service in auth-disabled mode (see the
|
||||||
|
// package doc comment's "Auth-disabled mode" section): nothing gated, a
|
||||||
|
// fixed superadmin placeholder identity for every request, regardless of
|
||||||
|
// authGuardURL. This is the explicit opt-out for a genuine standalone/
|
||||||
|
// local-dev deployment that doesn't want centralized identity at all -
|
||||||
|
// without it, an empty authGuardURL now means "pending" (auth integration
|
||||||
|
// is on, but no URL is known yet), not disabled.
|
||||||
|
func Disabled() ServiceOption {
|
||||||
|
return func(o *serviceOptions) { o.disabled = 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"
|
||||||
@@ -262,12 +302,15 @@ type Service struct {
|
|||||||
// pre-migration session cookie on logout (see the package doc comment's
|
// pre-migration session cookie on logout (see the package doc comment's
|
||||||
// "Session cookie / token model" section) - the live session cookie this
|
// "Session cookie / token model" section) - the live session cookie this
|
||||||
// service actually reads/sets is always AuthGuard's own
|
// service actually reads/sets is always AuthGuard's own
|
||||||
// authclient.DefaultCookieName. authGuardURL is AUTHGUARD_URL; empty means
|
// authclient.DefaultCookieName. authGuardURL is this project's currently
|
||||||
// auth-disabled mode. projectKey identifies this project to AuthGuard for
|
// known AuthGuard base URL - typically empty at construction now that
|
||||||
// per-user project-access restriction; see the "Unified auth proxy" section
|
// ProjectConfigurator pushes it live (coreconfig.Store.OnUpdate ->
|
||||||
// above.
|
// SetAuthGuardBaseURL); see the "Auth-disabled mode" section for what an
|
||||||
func New(db *pgxpool.Pool, cookieName string, secureCookies bool, authGuardURL, projectKey string) *Service {
|
// empty authGuardURL means without Disabled(). projectKey identifies this
|
||||||
service := NewWithStore(pgSettingsStore{db: db}, cookieName, secureCookies, authGuardURL, projectKey)
|
// project to AuthGuard for per-user project-access restriction; see the
|
||||||
|
// "Unified auth proxy" section above.
|
||||||
|
func New(db *pgxpool.Pool, cookieName string, secureCookies bool, authGuardURL, projectKey string, opts ...ServiceOption) *Service {
|
||||||
|
service := NewWithStore(pgSettingsStore{db: db}, cookieName, secureCookies, authGuardURL, projectKey, opts...)
|
||||||
service.db = db
|
service.db = db
|
||||||
return service
|
return service
|
||||||
}
|
}
|
||||||
@@ -278,10 +321,20 @@ func New(db *pgxpool.Pool, cookieName string, secureCookies bool, authGuardURL,
|
|||||||
// Its resulting Service has no db (the "moderatable platform users" section
|
// Its resulting Service has no db (the "moderatable platform users" section
|
||||||
// is unavailable - a project adopting this package fresh has no such
|
// is unavailable - a project adopting this package fresh has no such
|
||||||
// feature to preserve).
|
// feature to preserve).
|
||||||
func NewWithStore(store ProxyStore, cookieName string, secureCookies bool, authGuardURL, projectKey string) *Service {
|
func NewWithStore(store ProxyStore, cookieName string, secureCookies bool, authGuardURL, projectKey string, opts ...ServiceOption) *Service {
|
||||||
|
var options serviceOptions
|
||||||
|
for _, opt := range opts {
|
||||||
|
opt(&options)
|
||||||
|
}
|
||||||
var client *authclient.Client
|
var client *authclient.Client
|
||||||
if strings.TrimSpace(authGuardURL) != "" {
|
if !options.disabled {
|
||||||
client = authclient.New(authGuardURL, authclient.WithProjectKey(projectKey))
|
// authclient.New/SetBaseURL/Validate/call all tolerate an empty base
|
||||||
|
// URL (every call fails cleanly with "client has no base URL" rather
|
||||||
|
// than panicking or building a malformed request), which is exactly
|
||||||
|
// what makes "pending" mode safe: a Service constructed with no URL
|
||||||
|
// yet still has a real, non-nil client ready to be retargeted the
|
||||||
|
// moment one arrives.
|
||||||
|
client = authclient.New(strings.TrimSpace(authGuardURL), authclient.WithProjectKey(projectKey))
|
||||||
}
|
}
|
||||||
return &Service{store: store, cookieName: cookieName, secureCookies: secureCookies, authGuard: client}
|
return &Service{store: store, cookieName: cookieName, secureCookies: secureCookies, authGuard: client}
|
||||||
}
|
}
|
||||||
@@ -347,8 +400,10 @@ func (s pgSettingsStore) UnclaimSetup(ctx context.Context) error {
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
// enabled reports whether AUTHGUARD_URL was configured. See the top-of-file
|
// enabled reports whether this Service was NOT built with Disabled() - true
|
||||||
// doc comment's "Auth-disabled mode" section.
|
// for both a fully-configured Service and a "pending" one still waiting for
|
||||||
|
// its first AuthGuard URL. See the top-of-file doc comment's "Auth-disabled
|
||||||
|
// mode" section.
|
||||||
func (s *Service) enabled() bool {
|
func (s *Service) enabled() bool {
|
||||||
return s.authGuard != nil
|
return s.authGuard != nil
|
||||||
}
|
}
|
||||||
@@ -357,12 +412,14 @@ func (s *Service) enabled() bool {
|
|||||||
// internal authclient.Client calls, taking effect on its very next call -
|
// internal authclient.Client calls, taking effect on its very next call -
|
||||||
// wire it as a coreconfig.Store's OnUpdate callback (see
|
// wire it as a coreconfig.Store's OnUpdate callback (see
|
||||||
// ProjectConfigurator/README.md's "Pushing core service info to other
|
// ProjectConfigurator/README.md's "Pushing core service info to other
|
||||||
// projects" section) so a live authguard_url change applies without a
|
// projects" section) so a live authguard_url push applies without a
|
||||||
// restart, the same as a project holding its own *authclient.Client
|
// restart, whether it's the very first URL a "pending" Service ever
|
||||||
// directly. A no-op if this Service was constructed in auth-disabled mode
|
// receives or a later change to one already configured, the same as a
|
||||||
// (AUTHGUARD_URL unset at startup - see the "Auth-disabled mode" section):
|
// project holding its own *authclient.Client directly. A no-op only if this
|
||||||
// there is no client to retarget, and this package has no path to start
|
// Service was constructed with Disabled() (see the "Auth-disabled mode"
|
||||||
// authenticating requests it previously always let through.
|
// section): there is no client to retarget, and this package has no path to
|
||||||
|
// start authenticating requests it was explicitly told to always let
|
||||||
|
// through.
|
||||||
func (s *Service) SetAuthGuardBaseURL(baseURL string) {
|
func (s *Service) SetAuthGuardBaseURL(baseURL string) {
|
||||||
if s.authGuard != nil {
|
if s.authGuard != nil {
|
||||||
s.authGuard.SetBaseURL(baseURL)
|
s.authGuard.SetBaseURL(baseURL)
|
||||||
|
|||||||
@@ -1,6 +1,69 @@
|
|||||||
package auth
|
package auth
|
||||||
|
|
||||||
import "testing"
|
import (
|
||||||
|
"context"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
// fakeProxyStore is a minimal in-memory ProxyStore for constructing a
|
||||||
|
// Service in tests without a real database.
|
||||||
|
type fakeProxyStore struct {
|
||||||
|
loginRequired bool
|
||||||
|
setupClaimed bool
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *fakeProxyStore) LoginRequired(context.Context) (bool, error) { return s.loginRequired, nil }
|
||||||
|
func (s *fakeProxyStore) SetLoginRequired(_ context.Context, v bool) error {
|
||||||
|
s.loginRequired = v
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
func (s *fakeProxyStore) IsSetupClaimed(context.Context) (bool, error) { return s.setupClaimed, nil }
|
||||||
|
func (s *fakeProxyStore) TryClaimSetup(context.Context) (bool, error) {
|
||||||
|
if s.setupClaimed {
|
||||||
|
return false, nil
|
||||||
|
}
|
||||||
|
s.setupClaimed = true
|
||||||
|
return true, nil
|
||||||
|
}
|
||||||
|
func (s *fakeProxyStore) UnclaimSetup(context.Context) error {
|
||||||
|
s.setupClaimed = false
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestPendingModeStillGatesRequests locks in the fix that made an empty
|
||||||
|
// authGuardURL at construction mean "pending" (auth still enabled, calls
|
||||||
|
// fail closed until a real URL arrives via SetAuthGuardBaseURL) instead of
|
||||||
|
// "disabled" (nothing gated, a fixed superadmin identity) - the bug that
|
||||||
|
// made AUTHGUARD_URL a de-facto requirement even though ProjectConfigurator
|
||||||
|
// can push it live after startup.
|
||||||
|
func TestPendingModeStillGatesRequests(t *testing.T) {
|
||||||
|
service := NewWithStore(&fakeProxyStore{}, "session", false, "", "testproject")
|
||||||
|
if !service.enabled() {
|
||||||
|
t.Fatal("Service with no authGuardURL and no Disabled() option should still be enabled (pending), not disabled")
|
||||||
|
}
|
||||||
|
|
||||||
|
req := httptest.NewRequest(http.MethodGet, "/", nil)
|
||||||
|
req.AddCookie(&http.Cookie{Name: "auth_session", Value: "sometoken"})
|
||||||
|
if _, err := service.CurrentUser(req); err == nil {
|
||||||
|
t.Fatal("pending Service (no AuthGuard URL yet) should fail closed on a real session cookie, not silently resolve a user")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestDisabledOptionSkipsGating confirms the explicit opt-out still works
|
||||||
|
// exactly like the old "empty authGuardURL" behavior.
|
||||||
|
func TestDisabledOptionSkipsGating(t *testing.T) {
|
||||||
|
service := NewWithStore(&fakeProxyStore{}, "session", false, "", "testproject", Disabled())
|
||||||
|
if service.enabled() {
|
||||||
|
t.Fatal("Service built with Disabled() should report enabled() == false")
|
||||||
|
}
|
||||||
|
req := httptest.NewRequest(http.MethodGet, "/", nil)
|
||||||
|
user, err := service.CurrentUser(req)
|
||||||
|
if err != nil || user == nil || user.Username != "local" {
|
||||||
|
t.Fatalf("Disabled() Service should resolve the fixed local superadmin profile, got user=%+v err=%v", user, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func TestNormalizeProxyCredentials(t *testing.T) {
|
func TestNormalizeProxyCredentials(t *testing.T) {
|
||||||
email, username, password, err := normalizeProxyCredentials(" User@Example.com ", "user", "correct horse battery staple")
|
email, username, password, err := normalizeProxyCredentials(" User@Example.com ", "user", "correct horse battery staple")
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ Shared account-management, TOTP, admin reset-code, and AuthGuard client primitiv
|
|||||||
- `Roles` - shared account-management roles (`superadmin`/`admin`/`user`) and permission checks;
|
- `Roles` - shared account-management roles (`superadmin`/`admin`/`user`) and permission checks;
|
||||||
- `Totp` - RFC 6238 TOTP secret generation, provisioning URIs, and verification;
|
- `Totp` - RFC 6238 TOTP secret generation, provisioning URIs, and verification;
|
||||||
- `ResetManager` - a short-lived, one-time admin reset-code primitive printed to the server console;
|
- `ResetManager` - a short-lived, one-time admin reset-code primitive printed to the server console;
|
||||||
- `AuthClient` - a client for a centralized AuthGuard instance's `GET /api/session/validate`, for services that want one shared identity instead of their own local user table. Mirrors `shared/backend/authclient` (Go) and `shared/packages/node-backend/src/authclient.js` (Node) - keep the three in sync if any of them changes shape. Additive: no project is wired up to use it just because this class exists.
|
- `AuthClient` - a client for a centralized AuthGuard instance's `GET /api/session/validate`, for services that want one shared identity instead of their own local user table. Mirrors `shared/backend/authclient` (Go) and `shared/packages/node-backend/src/authclient.js` (Node) - keep the three in sync if any of them changes shape. Additive: no project is wired up to use it just because this class exists. `setBaseUrl(url)` retargets an existing client's AuthGuard URL in place - the natural target for a ProjectConfigurator core-services push handler - so a client can be constructed with `new AuthClient("")` (usable right away, failing closed with `IllegalStateException` until a real URL arrives) rather than needing one known up front. Unlike the Go/Python/Node siblings, this package has no `coreconfig` module of its own: MegaBasterd, its only consumer, wires the `PUT /api/core-services/internal` route directly against a plain field holding the current `AuthGuardUrl`.
|
||||||
|
|
||||||
## How this package is actually consumed
|
## How this package is actually consumed
|
||||||
|
|
||||||
|
|||||||
@@ -115,7 +115,15 @@ public final class AuthClient {
|
|||||||
/** Used only by the full-proxy methods below; see the class javadoc's Jackson tradeoff note. */
|
/** Used only by the full-proxy methods below; see the class javadoc's Jackson tradeoff note. */
|
||||||
private static final ObjectMapper JSON = new ObjectMapper();
|
private static final ObjectMapper JSON = new ObjectMapper();
|
||||||
|
|
||||||
private final String baseUrl;
|
/**
|
||||||
|
* Not final: {@link #setBaseUrl} retargets it live (e.g. from a project's own
|
||||||
|
* coreconfig-equivalent push handler), so a Service holding this client can start with
|
||||||
|
* baseUrl empty ("pending" - see {@link #setBaseUrl}'s doc comment) and still be usable
|
||||||
|
* once a URL is pushed, without discarding and rebuilding the whole client. {@code volatile}
|
||||||
|
* since HTTP requests happen on arbitrary threads and String is immutable, so a plain
|
||||||
|
* volatile field is enough for safe publication without a lock.
|
||||||
|
*/
|
||||||
|
private volatile String baseUrl;
|
||||||
private final String cookieName;
|
private final String cookieName;
|
||||||
private final int timeoutMillis;
|
private final int timeoutMillis;
|
||||||
private final String projectKey;
|
private final String projectKey;
|
||||||
@@ -155,6 +163,24 @@ public final class AuthClient {
|
|||||||
this.projectKey = projectKey == null ? "" : projectKey.trim().toLowerCase();
|
this.projectKey = projectKey == null ? "" : projectKey.trim().toLowerCase();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Atomically replaces the AuthGuard base URL this client calls, normalizing it the same way
|
||||||
|
* the constructor does. Mirrors Go's {@code authclient.Client.SetBaseURL} and Python's
|
||||||
|
* {@code AuthClient.set_base_url}: the intended use is a project's own coreconfig-equivalent
|
||||||
|
* push handler calling this on its live {@code AuthClient} instance so a freshly pushed
|
||||||
|
* AuthGuard URL takes effect on the client's very next call with no restart - including the
|
||||||
|
* very first URL a client constructed with {@code baseUrl == ""} (a "pending" client, not yet
|
||||||
|
* configured but still meant to be used, as opposed to one a project deliberately built with
|
||||||
|
* no AuthGuard integration at all) ever receives. A blank {@code baseUrl} is ignored (leaving
|
||||||
|
* the previous value in place) rather than leaving the client unable to reach AuthGuard at all.
|
||||||
|
*/
|
||||||
|
public void setBaseUrl(String baseUrl) {
|
||||||
|
String normalized = normalizeBaseUrl(baseUrl);
|
||||||
|
if (!normalized.isEmpty()) {
|
||||||
|
this.baseUrl = normalized;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Calls AuthGuard's {@code GET /api/session/validate} with {@code token} as a Bearer credential and
|
* Calls AuthGuard's {@code GET /api/session/validate} with {@code token} as a Bearer credential and
|
||||||
* returns the resolved user. Throws {@link InvalidSessionException} when AuthGuard reports the session
|
* returns the resolved user. Throws {@link InvalidSessionException} when AuthGuard reports the session
|
||||||
@@ -164,7 +190,8 @@ public final class AuthClient {
|
|||||||
* is not the same fact as "this visitor is unauthenticated".
|
* is not the same fact as "this visitor is unauthenticated".
|
||||||
*/
|
*/
|
||||||
public User validate(String token) throws IOException {
|
public User validate(String token) throws IOException {
|
||||||
if (baseUrl.isEmpty()) {
|
String currentBaseUrl = baseUrl;
|
||||||
|
if (currentBaseUrl.isEmpty()) {
|
||||||
throw new IllegalStateException("authclient: client has no base URL");
|
throw new IllegalStateException("authclient: client has no base URL");
|
||||||
}
|
}
|
||||||
String trimmed = token == null ? "" : token.trim();
|
String trimmed = token == null ? "" : token.trim();
|
||||||
@@ -172,7 +199,7 @@ public final class AuthClient {
|
|||||||
throw new InvalidSessionException();
|
throw new InvalidSessionException();
|
||||||
}
|
}
|
||||||
|
|
||||||
HttpURLConnection connection = openConnection(trimmed);
|
HttpURLConnection connection = openConnection(currentBaseUrl, trimmed);
|
||||||
int status;
|
int status;
|
||||||
String body;
|
String body;
|
||||||
try {
|
try {
|
||||||
@@ -598,11 +625,12 @@ public final class AuthClient {
|
|||||||
* {@code Client.call}/Node's {@code AuthClient#_call}/Python's {@code AuthClient._call} exactly.
|
* {@code Client.call}/Node's {@code AuthClient#_call}/Python's {@code AuthClient._call} exactly.
|
||||||
*/
|
*/
|
||||||
private CallResult call(String method, String path, String token, Object body) throws IOException {
|
private CallResult call(String method, String path, String token, Object body) throws IOException {
|
||||||
if (baseUrl.isEmpty()) {
|
String currentBaseUrl = baseUrl;
|
||||||
|
if (currentBaseUrl.isEmpty()) {
|
||||||
throw new IllegalStateException("authclient: client has no base URL");
|
throw new IllegalStateException("authclient: client has no base URL");
|
||||||
}
|
}
|
||||||
|
|
||||||
URL url = new URL(baseUrl + path);
|
URL url = new URL(currentBaseUrl + path);
|
||||||
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
|
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
|
||||||
connection.setRequestMethod(method);
|
connection.setRequestMethod(method);
|
||||||
connection.setConnectTimeout(timeoutMillis);
|
connection.setConnectTimeout(timeoutMillis);
|
||||||
@@ -696,8 +724,8 @@ public final class AuthClient {
|
|||||||
return "";
|
return "";
|
||||||
}
|
}
|
||||||
|
|
||||||
private HttpURLConnection openConnection(String token) throws IOException {
|
private HttpURLConnection openConnection(String currentBaseUrl, String token) throws IOException {
|
||||||
URL url = new URL(baseUrl + "/api/session/validate");
|
URL url = new URL(currentBaseUrl + "/api/session/validate");
|
||||||
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
|
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
|
||||||
connection.setRequestMethod("GET");
|
connection.setRequestMethod("GET");
|
||||||
if (!projectKey.isEmpty()) {
|
if (!projectKey.isEmpty()) {
|
||||||
|
|||||||
@@ -158,6 +158,37 @@ class AuthClientTest {
|
|||||||
assertThrows(InvalidSessionException.class, () -> client.validate("bad-token"));
|
assertThrows(InvalidSessionException.class, () -> client.validate("bad-token"));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void validateFailsClosedOnAClientWithNoBaseUrlYet() {
|
||||||
|
// A client constructed with "" (pending - no AuthGuard URL known yet, e.g. before a
|
||||||
|
// coreconfig-equivalent push arrives) must fail closed rather than silently letting
|
||||||
|
// every request through; see AuthClient's setBaseUrl doc comment.
|
||||||
|
AuthClient client = new AuthClient("");
|
||||||
|
|
||||||
|
assertThrows(IllegalStateException.class, () -> client.validate("some-token"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void setBaseUrlRetargetsAPendingClientToItsFirstRealUrl() throws Exception {
|
||||||
|
server = fakeAuthGuard(200, "{\"valid\":true,\"user_id\":7,\"username\":\"gabriel\",\"role\":\"admin\"}");
|
||||||
|
AuthClient client = new AuthClient("");
|
||||||
|
assertThrows(IllegalStateException.class, () -> client.validate("good-token"));
|
||||||
|
|
||||||
|
client.setBaseUrl(baseUrl(server));
|
||||||
|
|
||||||
|
AuthClient.User user = client.validate("good-token");
|
||||||
|
assertEquals("gabriel", user.username);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void setBaseUrlIgnoresABlankValue() {
|
||||||
|
AuthClient client = new AuthClient("https://auth.example.com");
|
||||||
|
|
||||||
|
client.setBaseUrl(" ");
|
||||||
|
|
||||||
|
assertEquals("https://auth.example.com", client.baseUrlForTest());
|
||||||
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void extractTokenPrefersAuthorizationHeaderOverCookie() {
|
void extractTokenPrefersAuthorizationHeaderOverCookie() {
|
||||||
AuthClient client = new AuthClient("https://auth.example.com");
|
AuthClient client = new AuthClient("https://auth.example.com");
|
||||||
|
|||||||
@@ -18,3 +18,36 @@ Pass a service-specific `tableName` to `runMigrations` when multiple services
|
|||||||
share one PostgreSQL database, so their migration histories cannot collide.
|
share one PostgreSQL database, so their migration histories cannot collide.
|
||||||
|
|
||||||
Run `npm test` from this package or `npm run test --workspace=@gabriel20xx/node-backend` from `shared`.
|
Run `npm test` from this package or `npm run test --workspace=@gabriel20xx/node-backend` from `shared`.
|
||||||
|
|
||||||
|
## `authclient`/`coreconfig`: adopting AuthGuard instead of local auth
|
||||||
|
|
||||||
|
`AuthClient` (`src/authclient.js`) trades a service's own local user table for
|
||||||
|
HTTP calls to a centralized AuthGuard instance, mirroring the Go/Python/Java
|
||||||
|
clients. `client.setBaseUrl(url)` retargets an existing client's AuthGuard
|
||||||
|
URL in place, so a client can be constructed with `new AuthClient('')`
|
||||||
|
(usable right away, failing closed until a real URL arrives) and be handed a
|
||||||
|
URL later, rather than needing one known up front.
|
||||||
|
|
||||||
|
`coreconfig` (`src/coreconfig.js`, the Node equivalent of
|
||||||
|
`shared/backend/coreconfig` and `shared_backend.coreconfig`) is a small
|
||||||
|
`Store` that holds AuthGuard's/CarrierNode's current base URL(s) and updates
|
||||||
|
live whenever ProjectConfigurator pushes a fresh
|
||||||
|
`PUT /api/core-services/internal` - wire `store.onUpdate` to
|
||||||
|
`authClient.setBaseUrl` so a project never needs to hardcode `AUTHGUARD_URL`:
|
||||||
|
|
||||||
|
```js
|
||||||
|
import { AuthClient, CoreConfigStore } from '@gabriel20xx/node-backend';
|
||||||
|
|
||||||
|
const authClient = new AuthClient('');
|
||||||
|
const coreConfig = new CoreConfigStore({ authGuardUrl: '' });
|
||||||
|
coreConfig.onUpdate((info) => authClient.setBaseUrl(info.authGuardUrl));
|
||||||
|
|
||||||
|
// in your own route for PUT /api/core-services/internal:
|
||||||
|
app.put('/api/core-services/internal', (req, res) => {
|
||||||
|
if (req.get('X-Internal-Auth') !== process.env.INTERNAL_SERVICE_SECRET) {
|
||||||
|
return res.status(401).json({ error: 'internal service authentication required' });
|
||||||
|
}
|
||||||
|
const info = coreConfig.set(req.body);
|
||||||
|
res.json({ ok: true, info: info.toJSON() });
|
||||||
|
});
|
||||||
|
```
|
||||||
@@ -14,6 +14,7 @@
|
|||||||
"./config": "./src/config.js",
|
"./config": "./src/config.js",
|
||||||
"./db": "./src/db.js",
|
"./db": "./src/db.js",
|
||||||
"./auth": "./src/auth.js",
|
"./auth": "./src/auth.js",
|
||||||
|
"./coreconfig": "./src/coreconfig.js",
|
||||||
"./migrate": "./src/migrate.js",
|
"./migrate": "./src/migrate.js",
|
||||||
"./package.json": "./package.json"
|
"./package.json": "./package.json"
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -87,6 +87,27 @@ export class AuthClient {
|
|||||||
return this.projectKey ? { [PROJECT_KEY_HEADER]: this.projectKey } : {};
|
return this.projectKey ? { [PROJECT_KEY_HEADER]: this.projectKey } : {};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Atomically replaces the AuthGuard base URL this client calls,
|
||||||
|
* normalizing it the same way the constructor does. Mirrors Go's
|
||||||
|
* authclient.Client.SetBaseURL / Python's AuthClient.set_base_url / Java's
|
||||||
|
* AuthClient#setBaseUrl: the intended use is a project's own
|
||||||
|
* coreconfig-equivalent push handler calling this on its live AuthClient
|
||||||
|
* instance so a freshly pushed AuthGuard URL takes effect on the client's
|
||||||
|
* very next call with no restart - including the very first URL a client
|
||||||
|
* constructed with baseUrl "" (a "pending" client, not yet configured but
|
||||||
|
* still meant to be used) ever receives. A blank baseUrl is ignored
|
||||||
|
* (leaving the previous value in place) rather than leaving the client
|
||||||
|
* unable to reach AuthGuard at all.
|
||||||
|
* @param {string} baseUrl
|
||||||
|
*/
|
||||||
|
setBaseUrl(baseUrl) {
|
||||||
|
const normalized = AuthClient._normalizeBaseUrl(baseUrl);
|
||||||
|
if (normalized) {
|
||||||
|
this.baseUrl = normalized;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
static _normalizeBaseUrl(baseUrl) {
|
static _normalizeBaseUrl(baseUrl) {
|
||||||
const trimmed = String(baseUrl ?? '').trim().replace(/\/+$/, '');
|
const trimmed = String(baseUrl ?? '').trim().replace(/\/+$/, '');
|
||||||
if (!trimmed) return trimmed;
|
if (!trimmed) return trimmed;
|
||||||
|
|||||||
@@ -0,0 +1,145 @@
|
|||||||
|
/**
|
||||||
|
* Lets any Node service in this workspace receive AuthGuard's and
|
||||||
|
* CarrierNode's current base URL(s) pushed from ProjectConfigurator, instead
|
||||||
|
* of hardcoding them in its own env vars. Mirrors shared/backend/coreconfig
|
||||||
|
* (Go) and shared/packages/python-backend/src/shared_backend/coreconfig.py
|
||||||
|
* (Python) exactly - same Info shape, same Store semantics - translated to
|
||||||
|
* Node idioms; keep all three in sync if any changes shape. See
|
||||||
|
* ProjectConfigurator/README.md's "Pushing core service info to other
|
||||||
|
* projects" section for the wire contract this module implements the
|
||||||
|
* receiving end of.
|
||||||
|
*
|
||||||
|
* Framework-agnostic: this module has no HTTP server of its own. A service
|
||||||
|
* wires the actual `PUT /api/core-services/internal` route in its own
|
||||||
|
* framework (Express, plain `http`, ...), gated behind its own
|
||||||
|
* INTERNAL_SERVICE_SECRET check the same way its other internal-service
|
||||||
|
* routes already are, decodes the JSON body with `Info.fromJSON`, and calls
|
||||||
|
* `store.set(info)` - see `Store.set`'s doc comment for a minimal Express
|
||||||
|
* example.
|
||||||
|
*/
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @typedef {{authGuardUrl?: string, carrierNodeUrl?: string, carrierNodeUrls?: string[]}} InfoLike
|
||||||
|
*/
|
||||||
|
|
||||||
|
export class Info {
|
||||||
|
/**
|
||||||
|
* @param {InfoLike} [fields]
|
||||||
|
*/
|
||||||
|
constructor({ authGuardUrl = '', carrierNodeUrl = '', carrierNodeUrls = [] } = {}) {
|
||||||
|
this.authGuardUrl = authGuardUrl;
|
||||||
|
this.carrierNodeUrl = carrierNodeUrl;
|
||||||
|
this.carrierNodeUrls = carrierNodeUrls;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Decodes the JSON body ProjectConfigurator's push carries (coreServiceInfo). */
|
||||||
|
static fromJSON(data) {
|
||||||
|
const raw = data ?? {};
|
||||||
|
let urls = Array.isArray(raw.carrierNodeUrls)
|
||||||
|
? raw.carrierNodeUrls.map((u) => String(u ?? '').trim()).filter(Boolean)
|
||||||
|
: [];
|
||||||
|
if (urls.length === 0) {
|
||||||
|
const single = String(raw.carrierNodeUrl ?? '').trim();
|
||||||
|
if (single) urls = [single];
|
||||||
|
}
|
||||||
|
return new Info({
|
||||||
|
authGuardUrl: String(raw.authGuardUrl ?? '').trim(),
|
||||||
|
carrierNodeUrl: urls[0] ?? '',
|
||||||
|
carrierNodeUrls: urls,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
toJSON() {
|
||||||
|
return {
|
||||||
|
authGuardUrl: this.authGuardUrl,
|
||||||
|
carrierNodeUrl: this.carrierNodeUrl,
|
||||||
|
carrierNodeUrls: [...this.carrierNodeUrls],
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function normalize(info) {
|
||||||
|
let cleaned = (info.carrierNodeUrls ?? []).map((u) => String(u ?? '').trim()).filter(Boolean);
|
||||||
|
if (cleaned.length === 0 && String(info.carrierNodeUrl ?? '').trim()) {
|
||||||
|
cleaned = [String(info.carrierNodeUrl).trim()];
|
||||||
|
}
|
||||||
|
return new Info({
|
||||||
|
authGuardUrl: String(info.authGuardUrl ?? '').trim(),
|
||||||
|
carrierNodeUrl: cleaned[0] ?? '',
|
||||||
|
carrierNodeUrls: cleaned,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
export class Store {
|
||||||
|
/**
|
||||||
|
* Holds the most recently pushed Info, defaulting to whatever fallback was
|
||||||
|
* given (typically this service's own AUTHGUARD_URL/CARRIERNODE_URL env
|
||||||
|
* vars, or "" now that they're optional) until ProjectConfigurator's first
|
||||||
|
* push arrives - or forever, if this deployment isn't registered with a
|
||||||
|
* ProjectConfigurator instance at all, in which case those env vars (if
|
||||||
|
* set) keep working exactly as before.
|
||||||
|
* @param {InfoLike} [fallback]
|
||||||
|
*/
|
||||||
|
constructor(fallback = {}) {
|
||||||
|
this._info = normalize(fallback instanceof Info ? fallback : new Info(fallback));
|
||||||
|
this._onUpdate = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
get() {
|
||||||
|
return this._info;
|
||||||
|
}
|
||||||
|
|
||||||
|
get authGuardUrl() {
|
||||||
|
return this._info.authGuardUrl;
|
||||||
|
}
|
||||||
|
|
||||||
|
get carrierNodeUrl() {
|
||||||
|
return this._info.carrierNodeUrl;
|
||||||
|
}
|
||||||
|
|
||||||
|
get carrierNodeUrls() {
|
||||||
|
return this._info.carrierNodeUrls;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Registers fn to be called (synchronously, so keep it fast) with the new
|
||||||
|
* Info after every set() - e.g. an AuthClient's setBaseUrl for a client
|
||||||
|
* that isn't already reading through Store on every call. Only one
|
||||||
|
* callback is kept; a second registration replaces the first.
|
||||||
|
* @param {(info: Info) => void} fn
|
||||||
|
*/
|
||||||
|
onUpdate(fn) {
|
||||||
|
this._onUpdate = fn;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Replaces the current Info, field by field, ignoring a blank/empty field
|
||||||
|
* so a partial push (e.g. only carrierNodeUrl(s) changed) never clobbers
|
||||||
|
* the other value. Returns the resulting Info. Minimal Express usage:
|
||||||
|
*
|
||||||
|
* app.put('/api/core-services/internal', (req, res) => {
|
||||||
|
* if (req.get('X-Internal-Auth') !== process.env.INTERNAL_SERVICE_SECRET) {
|
||||||
|
* return res.status(401).json({ error: 'internal service authentication required' });
|
||||||
|
* }
|
||||||
|
* const info = coreConfigStore.set(Info.fromJSON(req.body));
|
||||||
|
* res.json({ ok: true, info: info.toJSON() });
|
||||||
|
* });
|
||||||
|
*
|
||||||
|
* @param {InfoLike | Info} nextInfo
|
||||||
|
* @returns {Info}
|
||||||
|
*/
|
||||||
|
set(nextInfo) {
|
||||||
|
const next = normalize(nextInfo instanceof Info ? nextInfo : new Info(nextInfo));
|
||||||
|
if (next.authGuardUrl) {
|
||||||
|
this._info.authGuardUrl = next.authGuardUrl;
|
||||||
|
}
|
||||||
|
if (next.carrierNodeUrls.length > 0) {
|
||||||
|
this._info.carrierNodeUrls = next.carrierNodeUrls;
|
||||||
|
this._info.carrierNodeUrl = next.carrierNodeUrls[0];
|
||||||
|
}
|
||||||
|
if (this._onUpdate) {
|
||||||
|
this._onUpdate(this._info);
|
||||||
|
}
|
||||||
|
return this._info;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -32,3 +32,4 @@ export {
|
|||||||
} from './totp.js';
|
} from './totp.js';
|
||||||
export { runMigrations } from './migrate.js';
|
export { runMigrations } from './migrate.js';
|
||||||
export { APIError, AuthClient, InvalidSessionError, createAuthClient } from './authclient.js';
|
export { APIError, AuthClient, InvalidSessionError, createAuthClient } from './authclient.js';
|
||||||
|
export { Info as CoreConfigInfo, Store as CoreConfigStore } from './coreconfig.js';
|
||||||
@@ -68,6 +68,25 @@ test('constructor trims whitespace and leaves an empty base URL empty', () => {
|
|||||||
assert.equal(new AuthClient('').baseUrl, '');
|
assert.equal(new AuthClient('').baseUrl, '');
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test('setBaseUrl retargets a pending client (constructed with "") to its first real URL', async () => {
|
||||||
|
const client = new AuthClient('', {
|
||||||
|
fetchImpl: fakeFetch([{ status: 200, body: { valid: true, user_id: 7, username: 'gabriel', role: 'admin' } }]),
|
||||||
|
});
|
||||||
|
await assert.rejects(() => client.validate('good-token'), /no base URL/);
|
||||||
|
|
||||||
|
client.setBaseUrl('https://auth.example.com');
|
||||||
|
|
||||||
|
assert.equal(client.baseUrl, 'https://auth.example.com');
|
||||||
|
const user = await client.validate('good-token');
|
||||||
|
assert.deepEqual(user, { id: 7, username: 'gabriel', role: 'admin' });
|
||||||
|
});
|
||||||
|
|
||||||
|
test('setBaseUrl ignores a blank value, leaving the previous URL in place', () => {
|
||||||
|
const client = new AuthClient('https://auth.example.com');
|
||||||
|
client.setBaseUrl(' ');
|
||||||
|
assert.equal(client.baseUrl, 'https://auth.example.com');
|
||||||
|
});
|
||||||
|
|
||||||
test('validate resolves the user on a valid session', async () => {
|
test('validate resolves the user on a valid session', async () => {
|
||||||
const client = new AuthClient('https://auth.example.com', {
|
const client = new AuthClient('https://auth.example.com', {
|
||||||
fetchImpl: fakeFetch([{ status: 200, body: { valid: true, user_id: 7, username: 'gabriel', role: 'admin' } }]),
|
fetchImpl: fakeFetch([{ status: 200, body: { valid: true, user_id: 7, username: 'gabriel', role: 'admin' } }]),
|
||||||
|
|||||||
@@ -0,0 +1,50 @@
|
|||||||
|
import test from 'node:test';
|
||||||
|
import assert from 'node:assert/strict';
|
||||||
|
import { Info, Store } from '../src/coreconfig.js';
|
||||||
|
|
||||||
|
test('store seeds from the fallback Info', () => {
|
||||||
|
const store = new Store({ authGuardUrl: 'http://auth.example.com', carrierNodeUrl: 'http://carrier.example.com' });
|
||||||
|
assert.equal(store.authGuardUrl, 'http://auth.example.com');
|
||||||
|
assert.equal(store.carrierNodeUrl, 'http://carrier.example.com');
|
||||||
|
assert.deepEqual(store.carrierNodeUrls, ['http://carrier.example.com']);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('store defaults to empty with no fallback', () => {
|
||||||
|
const store = new Store();
|
||||||
|
assert.equal(store.authGuardUrl, '');
|
||||||
|
assert.deepEqual(store.carrierNodeUrls, []);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('set ignores a blank authGuardUrl rather than clobbering the existing one', () => {
|
||||||
|
const store = new Store({ authGuardUrl: 'http://auth.example.com' });
|
||||||
|
store.set({ authGuardUrl: '', carrierNodeUrl: 'http://carrier.example.com' });
|
||||||
|
assert.equal(store.authGuardUrl, 'http://auth.example.com');
|
||||||
|
assert.equal(store.carrierNodeUrl, 'http://carrier.example.com');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('set only replaces carrierNodeUrls when the push actually carries one', () => {
|
||||||
|
const store = new Store({ carrierNodeUrl: 'http://carrier.example.com' });
|
||||||
|
store.set({ authGuardUrl: 'http://auth.example.com' });
|
||||||
|
assert.equal(store.carrierNodeUrl, 'http://carrier.example.com');
|
||||||
|
assert.equal(store.authGuardUrl, 'http://auth.example.com');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('onUpdate is called with the resulting Info after set', () => {
|
||||||
|
const store = new Store();
|
||||||
|
const seen = [];
|
||||||
|
store.onUpdate((info) => seen.push(info));
|
||||||
|
store.set({ authGuardUrl: 'http://auth.example.com' });
|
||||||
|
assert.equal(seen.length, 1);
|
||||||
|
assert.equal(seen[0].authGuardUrl, 'http://auth.example.com');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('Info.fromJSON/toJSON round-trip the wire shape', () => {
|
||||||
|
const payload = {
|
||||||
|
authGuardUrl: 'http://auth.example.com',
|
||||||
|
carrierNodeUrl: 'http://carrier.example.com',
|
||||||
|
carrierNodeUrls: ['http://carrier.example.com', 'http://carrier2.example.com'],
|
||||||
|
};
|
||||||
|
const info = Info.fromJSON(payload);
|
||||||
|
assert.deepEqual(info.carrierNodeUrls, ['http://carrier.example.com', 'http://carrier2.example.com']);
|
||||||
|
assert.equal(info.toJSON().carrierNodeUrl, 'http://carrier.example.com');
|
||||||
|
});
|
||||||
@@ -69,6 +69,41 @@ async def require_session(request: Request):
|
|||||||
...
|
...
|
||||||
```
|
```
|
||||||
|
|
||||||
|
`auth_client.set_base_url(url)` retargets an existing client's AuthGuard
|
||||||
|
base URL in place — the natural callback for `coreconfig.Store.on_update`
|
||||||
|
(see below), so a live `authGuardUrl` push from ProjectConfigurator takes
|
||||||
|
effect on the client's very next call with no restart. This also means a
|
||||||
|
service no longer needs to know its AuthGuard URL at construction time: a
|
||||||
|
client built with `AuthClient("")` is usable right away (it just fails
|
||||||
|
closed, with a clear error, until a real URL arrives), so a service that
|
||||||
|
gets its `AUTHGUARD_URL` from ProjectConfigurator's push doesn't need the
|
||||||
|
env var set at all — see `coreconfig` below.
|
||||||
|
|
||||||
|
## `coreconfig`: receiving AuthGuard's/CarrierNode's URL(s) from ProjectConfigurator
|
||||||
|
|
||||||
|
`shared_backend.coreconfig` is the Python equivalent of
|
||||||
|
`shared/backend/coreconfig` (Go): a small, framework-agnostic `Store` that
|
||||||
|
holds AuthGuard's and CarrierNode's current base URL(s), seeded from
|
||||||
|
whatever fallback (e.g. this service's own env vars, or nothing at all) you
|
||||||
|
give it, and updated live whenever ProjectConfigurator pushes a fresh
|
||||||
|
`PUT /api/core-services/internal`. A service wires the actual route itself:
|
||||||
|
|
||||||
|
```python
|
||||||
|
from shared_backend import AuthClient, CoreConfigInfo, CoreConfigStore
|
||||||
|
|
||||||
|
auth_client = AuthClient("") # pending: no URL yet, still safe to use
|
||||||
|
core_config = CoreConfigStore(CoreConfigInfo(auth_guard_url=""))
|
||||||
|
core_config.on_update(lambda info: auth_client.set_base_url(info.auth_guard_url))
|
||||||
|
|
||||||
|
# in your framework's route for PUT /api/core-services/internal:
|
||||||
|
async def push_core_services(request):
|
||||||
|
if request.headers.get("X-Internal-Auth") != INTERNAL_SERVICE_SECRET:
|
||||||
|
raise HTTPException(status_code=401)
|
||||||
|
body = await request.json()
|
||||||
|
info = core_config.set(CoreConfigInfo.from_json(body))
|
||||||
|
return {"ok": True, "info": info.to_json()}
|
||||||
|
```
|
||||||
|
|
||||||
## `authproxy`: a ready-to-mount FastAPI router (optional)
|
## `authproxy`: a ready-to-mount FastAPI router (optional)
|
||||||
|
|
||||||
Wiring up `authclient` still leaves each service reimplementing the same
|
Wiring up `authclient` still leaves each service reimplementing the same
|
||||||
|
|||||||
@@ -23,6 +23,8 @@ from .authclient import (
|
|||||||
token_from_request,
|
token_from_request,
|
||||||
)
|
)
|
||||||
from .config import DatabaseConfig, database_url_from_env
|
from .config import DatabaseConfig, database_url_from_env
|
||||||
|
from .coreconfig import Info as CoreConfigInfo
|
||||||
|
from .coreconfig import Store as CoreConfigStore
|
||||||
from .postgres import Database
|
from .postgres import Database
|
||||||
from .tokens import hash_token, new_session_token
|
from .tokens import hash_token, new_session_token
|
||||||
from .totp import generate_totp_secret, totp_provisioning_uri, verify_totp
|
from .totp import generate_totp_secret, totp_provisioning_uri, verify_totp
|
||||||
@@ -36,6 +38,8 @@ __all__ = [
|
|||||||
"InvalidSessionError",
|
"InvalidSessionError",
|
||||||
"resolve_user",
|
"resolve_user",
|
||||||
"token_from_request",
|
"token_from_request",
|
||||||
|
"CoreConfigInfo",
|
||||||
|
"CoreConfigStore",
|
||||||
"ROLE_ADMIN",
|
"ROLE_ADMIN",
|
||||||
"ROLE_SUPERADMIN",
|
"ROLE_SUPERADMIN",
|
||||||
"ROLE_USER",
|
"ROLE_USER",
|
||||||
|
|||||||
@@ -234,6 +234,21 @@ class AuthClient:
|
|||||||
# matching the key ProjectConfigurator registers it under.
|
# matching the key ProjectConfigurator registers it under.
|
||||||
self.project_key = (project_key or "").strip().lower()
|
self.project_key = (project_key or "").strip().lower()
|
||||||
|
|
||||||
|
def set_base_url(self, base_url: str) -> None:
|
||||||
|
"""Atomically replaces the AuthGuard base URL this client calls,
|
||||||
|
normalizing it the same way __init__ does. Mirrors Go's
|
||||||
|
authclient.Client.SetBaseURL: the intended use is a project's own
|
||||||
|
coreconfig-equivalent push handler calling this on its live
|
||||||
|
AuthClient instance so a freshly pushed authGuardUrl takes effect on
|
||||||
|
the client's very next call with no restart -- including the very
|
||||||
|
first URL a client constructed with base_url="" (a "pending" client,
|
||||||
|
not yet configured but still meant to be used) ever receives. A
|
||||||
|
blank base_url is ignored (leaving the previous value in place)
|
||||||
|
rather than leaving the client unable to reach AuthGuard at all."""
|
||||||
|
normalized = _normalize_base_url(base_url)
|
||||||
|
if normalized:
|
||||||
|
self.base_url = normalized
|
||||||
|
|
||||||
# --- session validation (the original, minimal surface) ----------------
|
# --- session validation (the original, minimal surface) ----------------
|
||||||
|
|
||||||
async def validate(self, token: str) -> AuthGuardUser:
|
async def validate(self, token: str) -> AuthGuardUser:
|
||||||
|
|||||||
@@ -0,0 +1,139 @@
|
|||||||
|
"""Lets any Python service in this workspace receive AuthGuard's and
|
||||||
|
CarrierNode's current base URL(s) pushed from ProjectConfigurator, instead of
|
||||||
|
hardcoding them in its own env vars. Mirrors shared/backend/coreconfig (Go)
|
||||||
|
exactly -- same Info shape, same Store semantics -- translated to Python
|
||||||
|
idioms; keep both in sync if either changes shape. See
|
||||||
|
ProjectConfigurator/README.md's "Pushing core service info to other
|
||||||
|
projects" section for the wire contract this module implements the
|
||||||
|
receiving end of.
|
||||||
|
|
||||||
|
Framework-agnostic, like the rest of this package (see the top-level
|
||||||
|
README's "HTTP framework adapters stay in each service" note): this module
|
||||||
|
has no HTTP server of its own. A service wires the actual
|
||||||
|
PUT /api/core-services/internal route in its own framework (FastAPI,
|
||||||
|
aiohttp, ...), gated behind its own INTERNAL_SERVICE_SECRET check the same
|
||||||
|
way its other internal-service routes already are, decodes the JSON body
|
||||||
|
into an `Info`, and calls `Store.set(info)` -- see `Store.set`'s doc comment
|
||||||
|
for a minimal FastAPI example.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import threading
|
||||||
|
from dataclasses import dataclass, field
|
||||||
|
from typing import Callable, Optional
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class Info:
|
||||||
|
"""AuthGuard's and CarrierNode's current base URL(s), as pushed by
|
||||||
|
ProjectConfigurator. Field names match the JSON wire shape
|
||||||
|
(coreServiceInfo in ProjectConfigurator/backend/cmd/projectconfigurator/settings.go
|
||||||
|
and coreconfig.Info in shared/backend/coreconfig) exactly."""
|
||||||
|
|
||||||
|
auth_guard_url: str = ""
|
||||||
|
# carrier_node_url is the primary CarrierNode instance's URL
|
||||||
|
# (carrier_node_urls[0], if any) -- kept for a service that only ever
|
||||||
|
# talks to one CarrierNode instance.
|
||||||
|
carrier_node_url: str = ""
|
||||||
|
# carrier_node_urls is every CarrierNode instance ProjectConfigurator has
|
||||||
|
# registered, in priority order (the first entry is the same as
|
||||||
|
# carrier_node_url).
|
||||||
|
carrier_node_urls: list = field(default_factory=list)
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def from_json(cls, data: dict) -> "Info":
|
||||||
|
urls = [str(u).strip() for u in (data.get("carrierNodeUrls") or []) if str(u).strip()]
|
||||||
|
if not urls:
|
||||||
|
single = str(data.get("carrierNodeUrl") or "").strip()
|
||||||
|
if single:
|
||||||
|
urls = [single]
|
||||||
|
return cls(
|
||||||
|
auth_guard_url=str(data.get("authGuardUrl") or "").strip(),
|
||||||
|
carrier_node_url=urls[0] if urls else "",
|
||||||
|
carrier_node_urls=urls,
|
||||||
|
)
|
||||||
|
|
||||||
|
def to_json(self) -> dict:
|
||||||
|
return {
|
||||||
|
"authGuardUrl": self.auth_guard_url,
|
||||||
|
"carrierNodeUrl": self.carrier_node_url,
|
||||||
|
"carrierNodeUrls": list(self.carrier_node_urls),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
class Store:
|
||||||
|
"""Holds the most recently pushed Info, defaulting to whatever fallback
|
||||||
|
__init__ was given (typically this service's own AUTHGUARD_URL/
|
||||||
|
CARRIERNODE_URL env vars, or "" now that they're optional) until
|
||||||
|
ProjectConfigurator's first push arrives -- or forever, if this
|
||||||
|
deployment isn't registered with a ProjectConfigurator instance at all,
|
||||||
|
in which case those env vars (if set) keep working exactly as before."""
|
||||||
|
|
||||||
|
def __init__(self, fallback: Optional[Info] = None) -> None:
|
||||||
|
self._lock = threading.Lock()
|
||||||
|
self._info = _normalize(fallback or Info())
|
||||||
|
self._on_update: Optional[Callable[[Info], None]] = None
|
||||||
|
|
||||||
|
def get(self) -> Info:
|
||||||
|
with self._lock:
|
||||||
|
return self._info
|
||||||
|
|
||||||
|
@property
|
||||||
|
def auth_guard_url(self) -> str:
|
||||||
|
return self.get().auth_guard_url
|
||||||
|
|
||||||
|
@property
|
||||||
|
def carrier_node_url(self) -> str:
|
||||||
|
return self.get().carrier_node_url
|
||||||
|
|
||||||
|
@property
|
||||||
|
def carrier_node_urls(self) -> list:
|
||||||
|
return self.get().carrier_node_urls
|
||||||
|
|
||||||
|
def on_update(self, fn: Callable[[Info], None]) -> None:
|
||||||
|
"""Registers fn to be called (synchronously, so keep it fast) with
|
||||||
|
the new Info after every set() -- e.g. an AuthClient's set_base_url
|
||||||
|
for a client that isn't already reading through Store on every call.
|
||||||
|
Only one callback is kept; a second registration replaces the
|
||||||
|
first."""
|
||||||
|
with self._lock:
|
||||||
|
self._on_update = fn
|
||||||
|
|
||||||
|
def set(self, next_info: Info) -> Info:
|
||||||
|
"""Replaces the current Info, field by field, ignoring a
|
||||||
|
blank/empty field so a partial push (e.g. only carrierNodeUrl(s)
|
||||||
|
changed) never clobbers the other value. Returns the resulting
|
||||||
|
Info. Minimal FastAPI usage:
|
||||||
|
|
||||||
|
@app.put("/api/core-services/internal")
|
||||||
|
async def push_core_services(request: Request):
|
||||||
|
if request.headers.get("X-Internal-Auth") != INTERNAL_SERVICE_SECRET:
|
||||||
|
raise HTTPException(status_code=401)
|
||||||
|
body = await request.json()
|
||||||
|
info = core_config_store.set(Info.from_json(body))
|
||||||
|
return {"ok": True, "info": info.to_json()}
|
||||||
|
"""
|
||||||
|
next_info = _normalize(next_info)
|
||||||
|
with self._lock:
|
||||||
|
if next_info.auth_guard_url:
|
||||||
|
self._info.auth_guard_url = next_info.auth_guard_url
|
||||||
|
if next_info.carrier_node_urls:
|
||||||
|
self._info.carrier_node_urls = next_info.carrier_node_urls
|
||||||
|
self._info.carrier_node_url = next_info.carrier_node_urls[0]
|
||||||
|
current = self._info
|
||||||
|
callback = self._on_update
|
||||||
|
if callback is not None:
|
||||||
|
callback(current)
|
||||||
|
return current
|
||||||
|
|
||||||
|
|
||||||
|
def _normalize(info: Info) -> Info:
|
||||||
|
cleaned = [str(u).strip() for u in (info.carrier_node_urls or []) if str(u).strip()]
|
||||||
|
if not cleaned and info.carrier_node_url.strip():
|
||||||
|
cleaned = [info.carrier_node_url.strip()]
|
||||||
|
return Info(
|
||||||
|
auth_guard_url=info.auth_guard_url.strip(),
|
||||||
|
carrier_node_url=cleaned[0] if cleaned else "",
|
||||||
|
carrier_node_urls=cleaned,
|
||||||
|
)
|
||||||
@@ -0,0 +1,54 @@
|
|||||||
|
import unittest
|
||||||
|
|
||||||
|
from shared_backend.coreconfig import Info, Store
|
||||||
|
|
||||||
|
|
||||||
|
class StoreDefaultsTests(unittest.TestCase):
|
||||||
|
def test_seeds_from_fallback(self):
|
||||||
|
store = Store(Info(auth_guard_url="http://auth.example.com", carrier_node_url="http://carrier.example.com"))
|
||||||
|
info = store.get()
|
||||||
|
self.assertEqual(info.auth_guard_url, "http://auth.example.com")
|
||||||
|
self.assertEqual(info.carrier_node_url, "http://carrier.example.com")
|
||||||
|
self.assertEqual(info.carrier_node_urls, ["http://carrier.example.com"])
|
||||||
|
|
||||||
|
def test_defaults_to_empty(self):
|
||||||
|
store = Store()
|
||||||
|
info = store.get()
|
||||||
|
self.assertEqual(info.auth_guard_url, "")
|
||||||
|
self.assertEqual(info.carrier_node_urls, [])
|
||||||
|
|
||||||
|
|
||||||
|
class StoreSetTests(unittest.TestCase):
|
||||||
|
def test_partial_push_does_not_clobber_other_field(self):
|
||||||
|
store = Store(Info(auth_guard_url="http://auth.example.com", carrier_node_url="http://carrier.example.com"))
|
||||||
|
store.set(Info(carrier_node_url="http://carrier2.example.com"))
|
||||||
|
info = store.get()
|
||||||
|
self.assertEqual(info.auth_guard_url, "http://auth.example.com")
|
||||||
|
self.assertEqual(info.carrier_node_url, "http://carrier2.example.com")
|
||||||
|
|
||||||
|
def test_blank_auth_guard_url_ignored(self):
|
||||||
|
store = Store(Info(auth_guard_url="http://auth.example.com"))
|
||||||
|
store.set(Info(auth_guard_url=""))
|
||||||
|
self.assertEqual(store.auth_guard_url, "http://auth.example.com")
|
||||||
|
|
||||||
|
def test_on_update_called_with_resulting_info(self):
|
||||||
|
store = Store()
|
||||||
|
seen = []
|
||||||
|
store.on_update(seen.append)
|
||||||
|
store.set(Info(auth_guard_url="http://auth.example.com"))
|
||||||
|
self.assertEqual(len(seen), 1)
|
||||||
|
self.assertEqual(seen[0].auth_guard_url, "http://auth.example.com")
|
||||||
|
|
||||||
|
def test_from_json_round_trip(self):
|
||||||
|
payload = {
|
||||||
|
"authGuardUrl": "http://auth.example.com",
|
||||||
|
"carrierNodeUrl": "http://carrier.example.com",
|
||||||
|
"carrierNodeUrls": ["http://carrier.example.com", "http://carrier2.example.com"],
|
||||||
|
}
|
||||||
|
info = Info.from_json(payload)
|
||||||
|
self.assertEqual(info.carrier_node_urls, ["http://carrier.example.com", "http://carrier2.example.com"])
|
||||||
|
self.assertEqual(info.to_json()["carrierNodeUrl"], "http://carrier.example.com")
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
unittest.main()
|
||||||
Reference in new issue
Block a user