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
@@ -23,6 +23,8 @@ from .authclient import (
|
||||
token_from_request,
|
||||
)
|
||||
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 .tokens import hash_token, new_session_token
|
||||
from .totp import generate_totp_secret, totp_provisioning_uri, verify_totp
|
||||
@@ -36,6 +38,8 @@ __all__ = [
|
||||
"InvalidSessionError",
|
||||
"resolve_user",
|
||||
"token_from_request",
|
||||
"CoreConfigInfo",
|
||||
"CoreConfigStore",
|
||||
"ROLE_ADMIN",
|
||||
"ROLE_SUPERADMIN",
|
||||
"ROLE_USER",
|
||||
|
||||
@@ -234,6 +234,21 @@ class AuthClient:
|
||||
# matching the key ProjectConfigurator registers it under.
|
||||
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) ----------------
|
||||
|
||||
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,
|
||||
)
|
||||
Reference in new issue
Block a user