mirror of
https://github.com/headroomlabs-ai/headroom.git
synced 2026-11-22 13:29:19 +08:00
## Description
`plugins/headroom-oauth2/SPEC.md:67` promised that a missing or invalid
config at
startup makes `install()` raise and the proxy **fail closed** ("won't
start
mis-auth'd"), and its `CHANGELOG.md:25` said "Fails closed on
misconfiguration".
`install()` does raise. But the loader that calls it, `install_all()` in
`headroom/proxy/extensions.py`, wrapped every `install(app, config)` in
`except Exception`, logged a warning, and continued. So with `oauth2`
enabled and
a bad config the proxy started **without** `OAuth2Middleware` — and
since that
middleware is what replaces the client's `Authorization` with the minted
bearer,
the proxy relayed the client's own `Authorization` header upstream
unchanged.
The only signals were a log warning and one stderr line.
Skip-and-continue is the right default and stays the default: an
optional plugin
must not brick the proxy, and a licence-gate failure should leave the
feature
absent rather than fatal. It is the wrong rule for an extension that
*is* the
upstream credential. That is a per-extension property, so the extension
declares
it:
```python
def install(app, config): ...
install.fail_closed = True
```
`install_all` re-raises instead of swallowing when the failing `install`
carries
the marker, so `create_app` raises and the process never serves.
Everything
unmarked keeps today's behaviour exactly, including extensions installed
before
the failing one (none after it run). Reading the marker off the loaded
callable
costs the extension one line and core no per-name allowlist; an older
core that
does not know the marker ignores it and behaves as before — the plugin
documents
that.
Closes #4737
## Type of Change
- [x] Bug fix (non-breaking change that fixes an issue)
- [ ] New feature (non-breaking change that adds functionality)
- [ ] Breaking change
- [ ] Documentation update
- [ ] Performance improvement
- [ ] Code refactoring (no functional changes)
## Changes Made
- `headroom/proxy/extensions.py`: new `fail_closed` marker on the
`install`
callable; `install_all` re-raises a marked extension's failure (chained
from
the original exception) instead of logging and skipping. Module
docstring
gains a "Failing closed" section covering when the marker is
appropriate.
- `headroom/proxy/server.py`: the comment at the `install_all` call site
said the
process never fails on an extension install; it now names the exception.
- `plugins/headroom-oauth2/src/headroom_oauth2/__init__.py`: set
`install.fail_closed = True`, with a comment on why skipping would be
worse
than not starting.
- `plugins/headroom-oauth2`: `SPEC.md` failure-mode row now matches
reality (plus
a paragraph on the marker and old cores), `README.md` gains a
**Startup** note,
`CHANGELOG.md` 0.2.0 entry, version bumped in `pyproject.toml` +
`__version__`.
- `docs/content/docs/oauth2-upstream.mdx`: one line under **Notes**.
- `CHANGELOG.md` is **not** touched — release-please owns it.
## Testing
- [x] Unit tests pass (`pytest`)
- [x] Linting passes (`ruff check .`)
- [x] Type checking passes (`mypy headroom`)
- [x] New tests added for new functionality
- [x] Manual testing performed
### Test Output
```
$ pytest tests/test_proxy_extensions.py -q
6 passed
$ PYTHONPATH=.:plugins/headroom-oauth2/src pytest plugins/headroom-oauth2/tests/test_oauth2.py -q
41 passed in 10.81s
$ ruff check headroom/proxy/extensions.py headroom/proxy/server.py \
tests/test_proxy_extensions.py plugins/headroom-oauth2/
All checks passed!
$ ruff format --check <same files>
11 files already formatted
$ mypy headroom # 19 pre-existing errors in unrelated modules (astgrep, mcp_server,
# model_metadata) from this Windows/mypy version; none in extensions.py
```
Both new tests fail without the fix, for the right reason:
```
$ git stash push -- headroom/proxy/extensions.py
$ pytest tests/test_proxy_extensions.py plugins/headroom-oauth2/tests/test_oauth2.py -q
FAILED tests/test_proxy_extensions.py::test_install_all_aborts_startup_when_fail_closed_extension_fails
FAILED plugins/headroom-oauth2/tests/test_oauth2.py::test_install_all_aborts_startup_on_bad_config
2 failed, 45 passed
```
## Real Behavior Proof
- Environment: Windows 11, Python 3.13.11, this PR's branch checked out,
`PYTHONPATH` pointing at the checkout and `plugins/headroom-oauth2/src`
(no
package install needed). No proxy request was sent; the extension's own
`OAuth2Middleware` behaviour is already covered by its existing ASGI
tests.
- Exact command / steps: the reporter's own script shape — real
`install_all`,
real `headroom_oauth2.install`, config from `os.environ`, `discover()`
replaced
by a one-entry list — plus a second script that goes through the real
`create_app(ProxyConfig(proxy_extensions=["oauth2"]))`.
```python
os.environ["HEADROOM_OAUTH2_TOKEN_URL"] = "http://idp.example.com/token"
os.environ["HEADROOM_OAUTH2_CLIENT_ID"] = "c"
os.environ["HEADROOM_OAUTH2_CLIENT_SECRET"] = "s"
ext.discover = lambda: iter([("oauth2", headroom_oauth2.install)])
create_app(ProxyConfig(optimize=False, cache_enabled=False,
rate_limit_enabled=False, cost_tracking_enabled=False,
proxy_extensions=["oauth2"]))
```
- Observed result: `create_app` raises, and with a valid config installs
the
middleware. After the patch:
```
ok misconfigured: create_app raised RuntimeError: proxy extension
'oauth2' failed
to install and is marked fail_closed, so the proxy will no...
ok valid config: app.user_middleware = ['ActivityMiddleware',
'WebSocketAuthMiddleware',
'BaseHTTPMiddleware', 'RequestBodyLimitMiddleware', 'OAuth2Middleware',
'BaseHTTPMiddleware', 'CORSMiddleware',
'WebSocketProjectPrefixMiddleware']
```
With the plugin's own message preserved as `__cause__`:
```
install_all raised: RuntimeError: proxy extension 'oauth2' failed to
install and is
marked fail_closed, so the proxy will not start: headroom-oauth2
misconfigured:
token_url must be https (loopback http allowed for tests; set
allow_insecure=True /
HEADROOM_OAUTH2_ALLOW_INSECURE=1 to override)
__cause__: RuntimeError headroom-oauth2 misconfigured: token_url must be
https (...)
proxy would NOT start (create_app raises before uvicorn serves)
```
Before the patch (same script, `extensions.py` + plugin stashed):
```
[headroom] proxy extensions SKIPPED: oauth2 (install failed - running
without them; see logs)
FAIL: create_app returned; proxy would start without the middleware
```
which is exactly the issue's reported behaviour.
- Not tested: a real `headroom proxy` process start through uvicorn with
a
live IdP, and the request path at the wire level (the client's
`Authorization`
reaching an upstream). A multi-worker start (`--workers N`) was not
exercised
either; `create_app_from_env` goes through the same `create_app`, so
each
worker that cannot install the extension should exit.
`tests/test_proxy_extension_ordering.py` and two
`test_scope_and_proxy_token.py` cases fail on this machine with or
without the
patch (they need the compiled Rust core, which is not built here) —
verified
pre-existing by stashing the patch.
## Runtime Rollout Safety
- Rollout-managed feature(s): none. No flag, no staged rollout.
- Minimum rollout channel: any; the marker is inert unless an extension
sets it.
- Stable/default behavior changed: **no** for core — an unmarked
extension that
raises is still skipped with the same warning and stderr line. For
`headroom-oauth2` 0.2.0, yes and deliberately: a bad config now stops
startup.
- Kill switch / disable path: drop `--proxy-extension oauth2` /
`HEADROOM_PROXY_EXTENSIONS`, or fix the config. Both need no code
change.
- Unsafe override required: no. `HEADROOM_OAUTH2_ALLOW_INSECURE=1` still
lets an
operator opt into a non-loopback `http` token URL explicitly.
- Qualification impact: none beyond `headroom-oauth2` 0.2.0's own notes.
- Rollback path: revert the commit, or pin `headroom-oauth2<0.2.0` (its
marker is
ignored by any core, so downgrading the plugin alone restores old
behaviour).
## Review Readiness
- [x] I have performed a self-review
- [x] This PR is ready for human review
## Checklist
- [x] My code follows the project's style guidelines
- [x] I have performed a self-review of my code
- [x] I have commented my code, particularly in hard-to-understand areas
- [x] I have made corresponding changes to the documentation
- [x] My changes generate no new warnings
- [x] I have added tests that prove my fix is effective or that my
feature works
- [x] New and existing unit tests pass locally with my changes
- [x] I did **not** edit `CHANGELOG.md`
## Additional Notes
Two decisions a reviewer may want to weigh in on:
1. **Marker vs. core allowlist.** Reading `fail_closed` off the entry
point means
core guarantees nothing about *which* extensions are security-critical,
and a
malicious/broken plugin can also opt into aborting startup. The
alternative was
a hard-coded list of vetted names in core, which makes every new
security-critical extension a core change. Happy to switch if
maintainers
prefer that trade.
2. **Not covered here:** a `fail_closed` extension that is *not
discovered at
all* (typo in the name, package not installed) is still only a warning,
and
that has the same fail-open effect. Closing it needs a way to know the
intended
marker for a name that cannot be loaded — the allowlist in (1), or an
env
opt-in — so I left it out of scope and mention it here rather than
inventing a
mechanism.
Co-authored-by: JD Davis <mxjerrett@gmail.com>
This commit is contained in:
@@ -32,4 +32,5 @@ Environment variables (no-op unless `HEADROOM_OAUTH2_TOKEN_URL` is set):
|
||||
|
||||
- **Effective backends**: the injected bearer reaches the upstream only for OpenAI-compatible / passthrough litellm providers. `bedrock` / `vertex` / `sagemaker` authenticate from env and ignore it — the extension is a no-op there (it logs a warning at startup).
|
||||
- **Transport**: `token_url` must be `https` (loopback `http` allowed for tests; set `HEADROOM_OAUTH2_ALLOW_INSECURE=1` to override).
|
||||
- **Startup**: an invalid config makes the proxy refuse to start rather than run without the middleware and relay the client's own `Authorization` upstream.
|
||||
- **TLS**: tokens are minted with the standard library (`urllib`, system cert store), so a corporate-injected CA is trusted without bundling roots — this works behind corporate SSL-inspection where bundled-root TLS stacks fail.
|
||||
|
||||
@@ -18,6 +18,30 @@ Each ``install`` callable is invoked with the FastAPI ``app`` and the
|
||||
OSS makes no assumptions about what extensions do. The interface is
|
||||
deliberately minimal; extensions own the complexity behind it.
|
||||
|
||||
Failing closed
|
||||
--------------
|
||||
|
||||
The default above is right when an extension is a *feature*: a broken optional
|
||||
plugin must not stop the proxy. It is wrong when an extension is the thing
|
||||
standing between the client and an upstream it is not allowed to reach
|
||||
unauthenticated — an extension that mints the upstream credential, for example.
|
||||
Skipping it there does not disable a feature, it changes who can call the
|
||||
upstream.
|
||||
|
||||
Such an extension declares itself by setting ``fail_closed`` on its
|
||||
``install`` callable::
|
||||
|
||||
def install(app, config):
|
||||
...
|
||||
|
||||
install.fail_closed = True # a failed install aborts proxy startup
|
||||
|
||||
``install_all`` then lets the exception out instead of logging and continuing,
|
||||
so ``create_app`` fails and the process exits (uvicorn refuses to serve). The
|
||||
marker is read off the loaded callable, so it costs the extension one line and
|
||||
core no per-name allowlist. Everything not marked keeps the skip-and-continue
|
||||
behaviour.
|
||||
|
||||
Where extension middleware sits
|
||||
-------------------------------
|
||||
|
||||
@@ -111,7 +135,19 @@ ENTRY_POINT_GROUP = "headroom.proxy_extension"
|
||||
ENV_VAR = "HEADROOM_PROXY_EXTENSIONS"
|
||||
|
||||
ProxyExtension = Callable[[Any, Any], None]
|
||||
"""Signature: ``install(app: FastAPI, config: ProxyConfig) -> None``."""
|
||||
"""Signature: ``install(app: FastAPI, config: ProxyConfig) -> None``.
|
||||
|
||||
Set ``install.fail_closed = True`` to make a failed install abort startup
|
||||
instead of disabling the extension (see "Failing closed" above).
|
||||
"""
|
||||
|
||||
#: Attribute an ``install`` callable sets to opt into aborting startup on failure.
|
||||
FAIL_CLOSED_ATTR = "fail_closed"
|
||||
|
||||
|
||||
def _is_fail_closed(install: ProxyExtension) -> bool:
|
||||
"""True when ``install`` declares that its failure must abort startup."""
|
||||
return bool(getattr(install, FAIL_CLOSED_ATTR, False))
|
||||
|
||||
|
||||
def discover() -> Iterator[tuple[str, ProxyExtension]]:
|
||||
@@ -120,7 +156,8 @@ def discover() -> Iterator[tuple[str, ProxyExtension]]:
|
||||
Entry-point load failures are logged and skipped — a broken third-party
|
||||
package must not prevent the proxy from starting. An extension that fails
|
||||
its environment/auth check raises from ``install()``; ``install_all`` logs
|
||||
and skips it, so it is disabled rather than aborting startup.
|
||||
and skips it, so it is disabled rather than aborting startup — unless the
|
||||
extension marks itself ``fail_closed`` (see the module docstring).
|
||||
"""
|
||||
try:
|
||||
entries = importlib.metadata.entry_points(group=ENTRY_POINT_GROUP)
|
||||
@@ -175,7 +212,11 @@ def install_all(
|
||||
Returns the names of successfully installed extensions. If an extension
|
||||
raises inside ``install()`` it is logged, skipped, and recorded as failed —
|
||||
a single broken extension is disabled rather than aborting proxy startup for
|
||||
every other extension.
|
||||
every other extension. The exception is an extension marked ``fail_closed``
|
||||
(see the module docstring): its failure is re-raised, so startup stops.
|
||||
|
||||
Raises:
|
||||
RuntimeError: when a ``fail_closed`` extension's ``install()`` raised.
|
||||
"""
|
||||
enabled_set = _resolve_enabled(enabled)
|
||||
discovered = list(discover())
|
||||
@@ -208,6 +249,14 @@ def install_all(
|
||||
try:
|
||||
install(app, config)
|
||||
except Exception as exc: # noqa: BLE001 — one bad extension must not brick the proxy
|
||||
if _is_fail_closed(install):
|
||||
# The extension is the proxy's upstream auth (or equivalent):
|
||||
# running without it would serve requests it was meant to
|
||||
# refuse, so a skip is not a smaller failure than no start.
|
||||
raise RuntimeError(
|
||||
f"proxy extension {name!r} failed to install and is marked "
|
||||
f"fail_closed, so the proxy will not start: {exc}"
|
||||
) from exc
|
||||
# A failing extension disables *itself* and the proxy keeps running
|
||||
# without it — covers environment/auth failures and compatibility
|
||||
# errors (e.g. a plugin built against a core API this version lacks).
|
||||
|
||||
@@ -4495,6 +4495,11 @@ def create_app(config: ProxyConfig | None = None) -> FastAPI:
|
||||
# whose licence gate raises is absent, not fatal — the feature fails closed,
|
||||
# the process does not.
|
||||
#
|
||||
# The exception is an extension that marks its install() `fail_closed`
|
||||
# (e.g. one that mints the upstream credential): running without it would
|
||||
# relay the client's own Authorization upstream, so `install_all` re-raises
|
||||
# and create_app fails instead of serving mis-authenticated. See #4737.
|
||||
#
|
||||
# Installed HERE, before the body limit and the security gate are
|
||||
# registered, so any middleware an extension adds sits INSIDE both (see the
|
||||
# ordering contract above). Routes an extension registers are unaffected
|
||||
|
||||
@@ -1,5 +1,16 @@
|
||||
# Changelog
|
||||
|
||||
## 0.2.0
|
||||
|
||||
- A misconfigured `install()` now stops the proxy instead of being skipped by
|
||||
the extension loader. With `oauth2` enabled and a bad config, the proxy starts
|
||||
without `OAuth2Middleware` -- so the client's own `Authorization` was relayed
|
||||
upstream -- while `SPEC.md` promised it "fails closed". The extension now sets
|
||||
`install.fail_closed = True`, which makes the loader abort startup (#4737).
|
||||
Needs a headroom-ai core that honours the marker; older cores keep the
|
||||
previous behaviour.
|
||||
- Tests cover the real `install_all` seam, not just `install()` raising.
|
||||
|
||||
## 0.1.1
|
||||
|
||||
- Inject the upstream bearer only on requests that go upstream. Local routes
|
||||
|
||||
@@ -42,6 +42,12 @@ ignore it, so this extension is a no-op there (it logs a warning at startup).
|
||||
`HEADROOM_OAUTH2_ALLOW_INSECURE=1` to override). Tokens are minted with the standard library
|
||||
(`urllib`, system cert store), so a corporate-injected CA is trusted without bundling roots.
|
||||
|
||||
**Startup:** with `HEADROOM_OAUTH2_TOKEN_URL` set but the rest of the config invalid (non-`https`
|
||||
token URL, missing client id/secret, unparseable `TIMEOUT`/`SKEW`), the proxy **refuses to
|
||||
start** rather than running without the middleware and relaying the client's own `Authorization`
|
||||
upstream. The extension marks its `install()` `fail_closed` for that; a core too old to honour
|
||||
the marker logs a warning and starts without it.
|
||||
|
||||
## What gets the upstream bearer
|
||||
|
||||
The minted token is injected only on requests that **go upstream**. Routes the
|
||||
|
||||
@@ -64,12 +64,20 @@ Public Python API: `OAuth2ClientCredentials`, `OAuth2Middleware`, `OAuth2Error`,
|
||||
|
||||
| Failure | Behavior |
|
||||
|---|---|
|
||||
| Missing/invalid config at startup | `install()` raises -> proxy **fails closed** (won't start mis-auth'd) |
|
||||
| Missing/invalid config at startup | `install()` raises and is marked `fail_closed` -> **proxy refuses to start** (won't start mis-auth'd) |
|
||||
| Token endpoint unreachable / non-2xx / non-JSON / no `access_token` | `OAuth2Error` -> `502`, per-request, proxy stays up, retried next request |
|
||||
| `expires_in` = 0/negative/absent | clamped to a positive TTL (never stale, never per-request mint) |
|
||||
| Concurrent first requests | single-flight lock -> exactly one mint per refresh |
|
||||
| Malformed `HEADROOM_OAUTH2_HEADERS` (CR/LF) | offending pair dropped with a warning (no header injection) |
|
||||
|
||||
Core's default is to log a failed `install()` and keep serving without that
|
||||
extension — right for an optional feature, wrong here: skipping this middleware
|
||||
leaves the proxy relaying the client's own `Authorization` upstream. The
|
||||
extension therefore sets `install.fail_closed = True`, which makes `install_all`
|
||||
re-raise so startup aborts. That needs a headroom-ai whose
|
||||
`headroom/proxy/extensions.py` honours the marker; on an older core the flag is
|
||||
ignored and the proxy starts without the middleware, as it did before #4737.
|
||||
|
||||
## Resilience (Docker / native / wrappers / providers / multi-process)
|
||||
|
||||
- **Native & Docker:** identical; pure env-driven, std-lib only. Token minted via `urllib` against
|
||||
|
||||
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
|
||||
|
||||
[project]
|
||||
name = "headroom-oauth2"
|
||||
version = "0.1.1"
|
||||
version = "0.2.0"
|
||||
description = "Generic OAuth2 client-credentials upstream-auth extension for the Headroom proxy"
|
||||
readme = "README.md"
|
||||
requires-python = ">=3.10"
|
||||
|
||||
@@ -15,7 +15,7 @@ from .middleware import OAuth2Middleware
|
||||
from .provider import OAuth2ClientCredentials, OAuth2Error
|
||||
|
||||
__all__ = ["OAuth2ClientCredentials", "OAuth2Error", "OAuth2Middleware", "install", "parse_headers"]
|
||||
__version__ = "0.1.1"
|
||||
__version__ = "0.2.0"
|
||||
log = logging.getLogger("headroom_oauth2")
|
||||
|
||||
|
||||
@@ -159,3 +159,12 @@ def install(app: Any, config: Any) -> None:
|
||||
_redact_url(provider.token_url),
|
||||
provider.auth_style,
|
||||
)
|
||||
|
||||
|
||||
# Core would otherwise log a failed install and serve the proxy WITHOUT this
|
||||
# middleware, relaying the client's own Authorization upstream unchanged. This
|
||||
# extension exists to stop that, so a bad config must abort startup (issue
|
||||
# #4737). Honoured by cores that support the `fail_closed` marker -- see
|
||||
# headroom/proxy/extensions.py "Failing closed"; older cores keep the old
|
||||
# skip-and-continue behaviour.
|
||||
install.fail_closed = True # type: ignore[attr-defined]
|
||||
|
||||
@@ -350,6 +350,41 @@ def test_install_fail_closed_on_bad_timeout(monkeypatch):
|
||||
install(object(), _cfg("litellm-openai"))
|
||||
|
||||
|
||||
# --- install_all() (the real loader) -------------------------------------------
|
||||
# issue #4737: install() raising is only half the promise. The loader used to
|
||||
# swallow it, so the proxy started WITHOUT the middleware with `oauth2` enabled
|
||||
# and relayed the client's own Authorization upstream. These go through the real
|
||||
# install_all seam rather than calling install() directly.
|
||||
def test_install_all_aborts_startup_on_bad_config(monkeypatch):
|
||||
headroom_extensions = pytest.importorskip("headroom.proxy.extensions")
|
||||
monkeypatch.setenv("HEADROOM_OAUTH2_TOKEN_URL", "http://idp.example.com/token") # plain http
|
||||
monkeypatch.setenv("HEADROOM_OAUTH2_CLIENT_ID", "c")
|
||||
monkeypatch.setenv("HEADROOM_OAUTH2_CLIENT_SECRET", "s")
|
||||
monkeypatch.setattr(headroom_extensions, "discover", lambda: iter([("oauth2", install)]))
|
||||
|
||||
with pytest.raises(RuntimeError, match="fail_closed"):
|
||||
headroom_extensions.install_all(object(), _cfg("litellm-openai"), enabled=["oauth2"])
|
||||
|
||||
|
||||
def test_install_all_installs_middleware_with_valid_config(monkeypatch):
|
||||
headroom_extensions = pytest.importorskip("headroom.proxy.extensions")
|
||||
monkeypatch.setenv("HEADROOM_OAUTH2_TOKEN_URL", "https://idp.example.com/token")
|
||||
monkeypatch.setenv("HEADROOM_OAUTH2_CLIENT_ID", "c")
|
||||
monkeypatch.setenv("HEADROOM_OAUTH2_CLIENT_SECRET", "s")
|
||||
monkeypatch.delenv("HEADROOM_OAUTH2_HEADERS", raising=False)
|
||||
monkeypatch.setattr(headroom_extensions, "discover", lambda: iter([("oauth2", install)]))
|
||||
added = []
|
||||
|
||||
class App:
|
||||
def add_middleware(self, *a, **k):
|
||||
added.append(a[0])
|
||||
|
||||
installed = headroom_extensions.install_all(App(), _cfg("litellm-openai"), enabled=["oauth2"])
|
||||
|
||||
assert installed == ["oauth2"]
|
||||
assert added == [OAuth2Middleware]
|
||||
|
||||
|
||||
def test_parse_headers_rejects_bad_keys():
|
||||
assert parse_headers("Bad Key=v,Ok=1") == {"Ok": "1"} # space in key dropped
|
||||
assert parse_headers("X:Y=v,Ok=1") == {"Ok": "1"} # colon in key dropped
|
||||
|
||||
@@ -3,6 +3,8 @@ from __future__ import annotations
|
||||
import logging
|
||||
from typing import Any
|
||||
|
||||
import pytest
|
||||
|
||||
from headroom.proxy import extensions
|
||||
|
||||
|
||||
@@ -46,6 +48,56 @@ def test_install_all_warns_for_missing_requested_extension(caplog, monkeypatch)
|
||||
assert "proxy extensions requested but not found: missing_ext" in caplog.text
|
||||
|
||||
|
||||
def test_install_all_aborts_startup_when_fail_closed_extension_fails(
|
||||
monkeypatch,
|
||||
) -> None:
|
||||
"""A ``fail_closed`` extension's failure must stop startup, not be skipped.
|
||||
|
||||
Skipping an extension that mints the upstream credential would leave the
|
||||
proxy serving with the client's own ``Authorization`` relayed upstream
|
||||
(issue #4737). Every other extension keeps the skip-and-continue default,
|
||||
including the ones installed before the failing one.
|
||||
"""
|
||||
|
||||
def auth_ext(app: Any, config: Any) -> None:
|
||||
raise RuntimeError("headroom-oauth2 misconfigured: token_url must be https")
|
||||
|
||||
auth_ext.fail_closed = True # type: ignore[attr-defined]
|
||||
|
||||
def good(app: Any, config: Any) -> None:
|
||||
raise AssertionError("must not install extensions after a fatal one")
|
||||
|
||||
monkeypatch.setattr(
|
||||
extensions,
|
||||
"discover",
|
||||
lambda: iter([("oauth2", auth_ext), ("good_ext", good)]),
|
||||
)
|
||||
|
||||
with pytest.raises(RuntimeError) as excinfo:
|
||||
extensions.install_all(object(), object(), enabled=["oauth2", "good_ext"])
|
||||
|
||||
assert "'oauth2'" in str(excinfo.value)
|
||||
assert "fail_closed" in str(excinfo.value)
|
||||
# The plugin's own message survives as the cause, so the operator sees why.
|
||||
assert "token_url must be https" in str(excinfo.value.__cause__)
|
||||
|
||||
|
||||
def test_install_all_skips_fail_closed_extension_when_it_succeeds(
|
||||
monkeypatch,
|
||||
) -> None:
|
||||
"""The marker only changes the failure path — a healthy install is unaffected."""
|
||||
calls: list[str] = []
|
||||
|
||||
def auth_ext(app: Any, config: Any) -> None:
|
||||
calls.append("auth")
|
||||
|
||||
auth_ext.fail_closed = True # type: ignore[attr-defined]
|
||||
monkeypatch.setattr(extensions, "discover", lambda: iter([("oauth2", auth_ext)]))
|
||||
|
||||
assert extensions.install_all(object(), object(), enabled=["oauth2"]) == ["oauth2"]
|
||||
assert calls == ["auth"]
|
||||
|
||||
|
||||
class _Capture(logging.Handler):
|
||||
def __init__(self) -> None:
|
||||
super().__init__(logging.DEBUG)
|
||||
|
||||
Reference in New Issue
Block a user