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

+1 -1
View File
@@ -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;
- `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;
- `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
@@ -115,7 +115,15 @@ public final class AuthClient {
/** Used only by the full-proxy methods below; see the class javadoc's Jackson tradeoff note. */
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 int timeoutMillis;
private final String projectKey;
@@ -155,6 +163,24 @@ public final class AuthClient {
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
* 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".
*/
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");
}
String trimmed = token == null ? "" : token.trim();
@@ -172,7 +199,7 @@ public final class AuthClient {
throw new InvalidSessionException();
}
HttpURLConnection connection = openConnection(trimmed);
HttpURLConnection connection = openConnection(currentBaseUrl, trimmed);
int status;
String body;
try {
@@ -598,11 +625,12 @@ public final class AuthClient {
* {@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 {
if (baseUrl.isEmpty()) {
String currentBaseUrl = baseUrl;
if (currentBaseUrl.isEmpty()) {
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();
connection.setRequestMethod(method);
connection.setConnectTimeout(timeoutMillis);
@@ -696,8 +724,8 @@ public final class AuthClient {
return "";
}
private HttpURLConnection openConnection(String token) throws IOException {
URL url = new URL(baseUrl + "/api/session/validate");
private HttpURLConnection openConnection(String currentBaseUrl, String token) throws IOException {
URL url = new URL(currentBaseUrl + "/api/session/validate");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
if (!projectKey.isEmpty()) {
@@ -158,6 +158,37 @@ class AuthClientTest {
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
void extractTokenPrefersAuthorizationHeaderOverCookie() {
AuthClient client = new AuthClient("https://auth.example.com");
+33
View File
@@ -18,3 +18,36 @@ Pass a service-specific `tableName` to `runMigrations` when multiple services
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`.
## `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",
"./db": "./src/db.js",
"./auth": "./src/auth.js",
"./coreconfig": "./src/coreconfig.js",
"./migrate": "./src/migrate.js",
"./package.json": "./package.json"
},
@@ -87,6 +87,27 @@ export class AuthClient {
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) {
const trimmed = String(baseUrl ?? '').trim().replace(/\/+$/, '');
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';
export { runMigrations } from './migrate.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, '');
});
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 () => {
const client = new AuthClient('https://auth.example.com', {
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');
});
+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()