Sync shared snapshot from dcfdb3d
Docker / Docker Build & Push (push) Successful in 6m0s

This commit is contained in:
Gabriel20xx committed 2026-09-14 09:36:48 +02:00
1 parent 8d7c2f69ff
commit a018f3da4c
18 files changed
+747 -46

No files matched your search

+35
View File
@@ -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)
Wiring up `authclient` still leaves each service reimplementing the same
@@ -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,
)
@@ -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()