From ae4638e4dd4877073cdf35a636a8af152b266369 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Roberto=20Trevi=C3=B1o?= Date: Sun, 29 Nov 2026 01:32:08 -0600 Subject: [PATCH] API workers share startup and OAuth sign-ins through the data folder --- tests/test_sources.py | 3 ++- webapi/sources.py | 49 ++++++++++++++++++++++++++++++++++--------- webapi/users.py | 13 +++++++++++- 3 files changed, 53 insertions(+), 12 deletions(-) diff --git a/tests/test_sources.py b/tests/test_sources.py index 000bf32..f9e9177 100644 --- a/tests/test_sources.py +++ b/tests/test_sources.py @@ -106,7 +106,7 @@ def test_a_sign_in_button_without_an_app_registration_says_who_must_register_one assert found.status_code == 503 and "GOOGLE_CLIENT_ID" in found.json()["detail"] -def test_signing_in_hands_the_account_to_the_dialog(client, monkeypatch): +def test_signing_in_hands_the_account_to_the_dialog(client, monkeypatch, tmp_path): from authlib.integrations.httpx_client import OAuth2Client, oauth2_client httpx = oauth2_client.httpx2 # the HTTP library this authlib is built on @@ -126,6 +126,7 @@ def test_signing_in_hands_the_account_to_the_dialog(client, monkeypatch): transport=httpx.MockTransport(provider)) # fmt: skip monkeypatch.setattr(sources, "_client", client_for) + monkeypatch.setattr(sources, "PENDING", tmp_path / "pending") # any worker's callback monkeypatch.setattr(sources, "account", lambda p, token, env: { "user": "ana@hospital.mx", "drive_id": "d1", "oauth2_client_params": {"client_id": env["client_id"], "token": token}}) # fmt: skip diff --git a/webapi/sources.py b/webapi/sources.py index d9de5a0..525c0e0 100644 --- a/webapi/sources.py +++ b/webapi/sources.py @@ -213,10 +213,43 @@ def upload(files: list[UploadFile], folder: Annotated[str | None, Form()] = None # Sign-in buttons: OAuth 2.0 authorization code flow with PKCE (authlib). The dialog opens # `start`'s address in a window; the provider sends the user back to `callback`, which -# hands the account to the dialog (window.opener) and closes. Pending sign-ins live in this -# process for ten minutes. -PENDING: dict[str, dict[str, Any]] = {} +# hands the account to the dialog (window.opener) and closes. A pending sign-in is a file +# in the data folder for ten minutes, so whichever API worker gets the callback finds it. +PENDING = DATA_DIR / "oauth_pending" PENDING_SECONDS = 600 +STATE = re.compile(r"[A-Za-z0-9_-]{8,128}") + + +def _pend(state: str, pending: dict[str, Any]) -> None: + import json + import time + + PENDING.mkdir(parents=True, exist_ok=True) + for old in PENDING.glob("*.json"): + if time.time() - old.stat().st_mtime > PENDING_SECONDS: + old.unlink(missing_ok=True) + path = PENDING / f"{state}.json" + path.write_text(json.dumps(pending)) + path.chmod(0o600) + + +def _claimed(state: str) -> dict[str, Any] | None: + """The pending sign-in of `state`, taken once (by an atomic rename), if still fresh.""" + import json + import time + + if not STATE.fullmatch(state): + return None + taken = PENDING / f"{state}.{uuid.uuid4().hex}.taken" + try: + (PENDING / f"{state}.json").rename(taken) + except FileNotFoundError: + return None + try: + fresh = time.time() - taken.stat().st_mtime <= PENDING_SECONDS + return json.loads(taken.read_text()) if fresh else None + finally: + taken.unlink(missing_ok=True) def _registration(provider: str) -> tuple[sources.Provider, dict[str, str]]: @@ -254,7 +287,6 @@ def oauth_start(provider: str, origin: str) -> SignIn: """The provider's sign-in address. `origin` is the web app's (where the user returns: `{origin}/api/…/callback`, the address IT registered).""" import secrets - import time found, env = _registration(provider) redirect_uri = f"{origin.rstrip('/')}/api/ingest/sources/oauth/{provider}/callback" @@ -262,11 +294,8 @@ def oauth_start(provider: str, origin: str) -> SignIn: url, state = _client(found, env, redirect_uri).create_authorization_url( _endpoint(found.authorize_url, env), code_verifier=verifier, **found.authorize_params ) - now = time.monotonic() - for old in [k for k, v in PENDING.items() if now - v["at"] > PENDING_SECONDS]: - PENDING.pop(old, None) - PENDING[state] = {"provider": provider, "verifier": verifier, "redirect_uri": redirect_uri, - "origin": origin.rstrip("/"), "at": now} # fmt: skip + _pend(state, {"provider": provider, "verifier": verifier, "redirect_uri": redirect_uri, + "origin": origin.rstrip("/")}) # fmt: skip return SignIn(url=url, state=state) @@ -306,7 +335,7 @@ def oauth_callback(provider: str, state: str, code: str | None = None, error: st from fastapi.responses import HTMLResponse - pending = PENDING.pop(state, None) + pending = _claimed(state) if pending is None or pending["provider"] != provider: return HTMLResponse("

La solicitud de inicio de sesión venció. Cierre esta ventana " "e inténtelo de nuevo.

", status_code=400) # fmt: skip diff --git a/webapi/users.py b/webapi/users.py index 9852ef1..7e7528f 100644 --- a/webapi/users.py +++ b/webapi/users.py @@ -154,5 +154,16 @@ async def first_admin() -> None: @asynccontextmanager async def lifespan(_app: FastAPI) -> AsyncIterator[None]: - await first_admin() + """Each API worker starts here; one at a time (a lock in the data folder), so the + users table, the first administrator and the session secret are made once.""" + import fcntl + + DATA_DIR.mkdir(parents=True, exist_ok=True) + with open(DATA_DIR / "startup.lock", "w") as lock: + fcntl.flock(lock, fcntl.LOCK_EX) + try: + _secret() + await first_admin() + finally: + fcntl.flock(lock, fcntl.LOCK_UN) yield