mirror of
https://github.com/bytedance/deer-flow.git
synced 2026-09-14 16:08:41 +00:00
* feat(extensions): add gateway services and routers * feat(extensions): add standalone reference extension * fix(extensions): harden contributed gateway routes * docs(extensions): document gateway contribution points * feat(extensions): add operator CLI for packaged extension management Add `deerflow extensions install/list/enable/disable/remove` plus the root `make extension-*` wrappers, backed by an `ExtensionManager` that owns one transaction over backend/pyproject.toml, backend/uv.lock, the managed source snapshot, the uv environment, and the `plugins:` block in config.yaml. Install accepts a package requirement, a public HTTPS Git URL, or a local directory. Local directories are copied to backend/extensions/sources/ as deployable snapshots rather than editable installs, and the root .dockerignore re-includes that tree so snapshots reach the backend builder. Remote sources are HTTPS-only; SSH Git, file:// and local wheels are rejected because the stock Docker builder cannot reproduce them. Because environment configuration can still resolve a plain package name to a local wheel (a UV_FIND_LINKS wheelhouse, say), every uv add/remove is followed by an audit of the new lock: any local reference the stock image build cannot reproduce rolls back the whole transaction. A config carrying duplicate top-level `plugins:` keys is rejected outright rather than managed against one block while the Gateway reads another. Dependency synchronization now has one lock authority. The `extensions` dependency group joins [tool.uv].default-groups, every startup path syncs the same lock with --locked and launches with --no-sync, and the Docker images move to uv 0.11.1 for the --no-workspace boundary the manager needs. Loader gains `enabled`, `name` and `package` fields so a disabled extension is skipped before resolution and import. Co-authored-by: Codex <codex@openai.com> * fix(extensions): stop the managed plugins rewrite from destroying config Two data-safety defects in the managed `plugins:` block writer. The "next top-level key" boundary was a regex matching only `[A-Za-z_][A-Za-z0-9_-]*` or a quoted key. `AppConfig` is `extra="allow"`, so a config may legally carry any top-level key, and a key the pattern cannot recognize did not fail loudly — it read as "no next section", and the rewrite replaced that neighbour and its entire subtree with the managed block. `my.key`, `2fa`, `$schema`, `my key` and non-ASCII keys were all silently deleted by a plain `extension-enable`/`disable`. Both boundaries now come from the YAML parser's node marks, so key shape is irrelevant. The file-final branch never consulted the trailing-comment scan the has-next-key branch used, so any comment below the block was dropped. Since the manager appends `plugins:` at end of file, that is the steady-state shape for most installs: an operator note below the block was destroyed on the next toggle. Separately, every managed install wrote `required: true` while the loader defaults to false. That turned any later load failure — broken wheel, missing native library, deleted snapshot — into a Gateway startup abort recoverable only with shell access. New records are now written `required: false`, with an explicit `install --required` opt-in; adopting an existing hand-written record still preserves the operator's own choice. * fix(extensions): harden the manager transaction and correct its docs Follow-up hardening on the extension package manager. Security posture, which the docs already claimed: - Scrub `UV_PYTHON`, `UV_INSECURE_HOST`, `UV_CONSTRAINT` and `UV_NO_BUILD_ISOLATION` from the controlled uv environment. `UV_PYTHON` swaps the interpreter that the entry-point probe then imports and calls, and every later `uv run --no-sync` startup uses; `UV_INSECURE_HOST` removes the TLS validation the HTTPS-only source rule depends on. Neither is an index, proxy, cache or credential-provider setting, so neither was covered by the carve-out. - Recognize run-together and all-caps secret query parameters (`accesstoken`, `ACCESSTOKEN`, `key`, `pw`, `sas`, `code`). The camel-case splitter only fires on case transitions, so only the separated spellings were caught. Short generic words stay boundary-anchored, so `?keyword=` remains installable. - Validate the config before running any uv command. `uv add`/`uv sync` execute the package's build backend, so a config the manager could never write to must fail before that code runs rather than afterwards through rollback. Transaction integrity: - Run the second dependency-file restore from a `finally`. The recovery sync runs without `--locked` when the checkout had no lock, so uv writes one while resolving; if that sync then failed, the restore was skipped and the operator kept a lock file they never had. A failing recovery sync now also reports the original failure instead of replacing it. - Skip the recovery sync on cancellation. Answering Ctrl-C with a full dependency resolve invites a second interrupt that escapes the handler and strands the checkout mid-transaction; the declarations are already restored and the next locked startup sync reconciles the environment. - Retry a non-blocking lock on Windows instead of using `msvcrt.LK_LOCK`, which gives up after ~10s — far shorter than a real `uv add` plus `uv sync`, so contention surfaced as `Permission denied` rather than serializing. - Locate the entry-point probe's JSON payload instead of parsing stdout's first line, so a `sitecustomize`/`.pth` banner cannot roll back a good install. - Warn when the lock records a loopback source. `127.0.0.1` inside the image builder is a different machine, but unlike an environment-driven wheelhouse resolution this is a source the operator typed deliberately, so it is reported rather than rolled back. Private-network indexes are untouched: a builder on that network can reach them. Docs: the blanket claim that failed operations restore the config file was wrong — the conflict branches deliberately preserve a concurrent external edit and leave `remove` deactivated. Document that, the `required: false` default, the config preflight, the interrupt behaviour, and where the plugins-block boundaries come from. * test(gateway): pin the request-path projection agreement `get_request_route_path()` imports the private `starlette._utils.get_route_path` so the auth and CSRF predicates classify the exact string Starlette's router matches on. Its requirement is not "strip root_path correctly" but "return what the dispatcher is matching", so delegating to the router's own implementation keeps the two in lockstep by construction. Keep the private import rather than vendoring a copy: an import that disappears fails loudly at startup, while a stale copy diverges silently at a security boundary. Cover the property directly instead of the mechanism, so the tests survive a future reimplementation: - projection edge cases, including the segment-boundary guard that keeps root_path="/api" from slicing "/apifoo/models" into a string the router would never match - agreement with the router under nested mounts - the two bypasses these predicates exist to prevent: a protected route mounted under the "/health" public prefix must still 401, and a POST mounted under "/api/webhooks" must still require a CSRF token Both are verified to fail when the projection is reverted to `request.url.path` (9/13 red) and when a plausible vendored copy omits the boundary guard (the 2 boundary cases red). Declare starlette as a bounded direct dependency so a bump — which is security-relevant here — shows up in review rather than arriving silently through FastAPI. * ci: pin uv to the version production ships ExtensionManager is not a consumer of uv the build tool -- it is a program whose whole job is driving `uv` as a subprocess, depending on its CLI behavior (`--no-workspace`, `--no-sync`, what `uv add` writes into `[dependency-groups] extensions`) and on the `uv.lock` serialization format. uv is closer to a runtime dependency with a contract than to incidental tooling. backend/Dockerfile pins that binary to 0.11.1, but all eight astral-sh/setup-uv steps installed whatever was latest at run time, so CI exercised the manager against a uv that is not the uv production runs. The sharpest failure that allows: a newer uv bumps uv.lock's `revision`, CI stays green because the same uv reads back what it wrote, and the pinned uv in the production image cannot read the committed lock. `uv lock --check` is version-sensitive for the same reason -- it verifies the lock is what *this* uv would produce, and two versions can emit equivalent but non-identical output. Pin every step to 0.11.1 and lift the one lingering setup-uv@v3 to v7 so the steps share input and caching behavior. Pinning alone drifts apart again on the next bump, so add a constraint test in the style of test_compose_default_bind_host.py: the Dockerfile's UV_IMAGE tag is the single source of truth, and both compose defaults plus every setup-uv step must match it. Verified to fail when a pin drifts, when a step omits `version`, and -- the real scenario -- when the Dockerfile is bumped alone, which lights up the workflows and both compose files at once. * fix(gateway): state the extension route auth limit and abort a failed dev sync Two scoped review follow-ups. README: contributed routers cannot enter the host's reserved public prefixes, which makes every extension endpoint session-authenticated -- there is no way to expose an unauthenticated route. The rejection rule was documented but its consequence was not, so inbound provider webhooks and public status endpoints read as merely undocumented rather than out of scope for this release. docker/dev-entrypoint.sh: the self-heal retry reuses `--locked`, so it repairs a corrupt .venv but never a lock that disagrees with pyproject.toml. `set -e` already stopped the script there -- uvicorn was not being started against a stale environment -- but it exited on a bare uv exit code with no indication of what to do. Abort explicitly with the cause and the fix. Tests slice the sync block out of the real script and run it against a stub uv, so they exercise the shipped code rather than a copy of it (/app/backend only exists inside the container). They cover the success path, the retry that recovers, the abort, and the guidance. Verified against the pre-fix script: only the guidance case goes red, confirming the abort itself was already correct. * fix(extensions): point Git SSH shorthand at the HTTPS correction Git's SCP-like shorthand carries no URL scheme, so `git+git@host:org/repo.git` reached the scheme rules looking like a bare path and was rejected with "local path references are not deployable; pass a local directory so DeerFlow can snapshot it". The operator asked for a remote source, so that guidance points at the wrong fix. Detect the shorthand ahead of the scheme rules and report the public-HTTPS correction instead. The bare `git@host:org/repo.git` spelling took a different wrong turn: packaging parses it as a direct reference named `git`, leaving `host:org/repo.git`, whose `host` reads as a URL scheme and produced the generic HTTPS message. Both spellings now share one message, as does the PEP 508 named form. * docs: keep the root extension summary within its new budget #4799 split the depth out of the module guides and added a size gate; the root file's job is now orientation, and this branch had pushed it 192 bytes past the soft limit. The manager transaction, source rules, and lock discipline are already stated in full in the extensions guide, so the root keeps the one-line orientation and points there instead of restating them. --------- Co-authored-by: Codex <codex@openai.com>
496 lines
14 KiB
Python
496 lines
14 KiB
Python
"""Tests for the global AuthMiddleware (fail-closed safety net)."""
|
|
|
|
import pytest
|
|
from starlette.testclient import TestClient
|
|
|
|
from app.gateway.auth_middleware import AuthMiddleware, _is_public
|
|
from app.gateway.csrf_middleware import CSRFMiddleware
|
|
from deerflow.config.authorization_config import AuthorizationConfig
|
|
|
|
|
|
@pytest.fixture(autouse=True)
|
|
def _default_route_authorization_config(monkeypatch):
|
|
"""Keep minimal middleware apps independent of a repository config.yaml."""
|
|
monkeypatch.setattr(
|
|
"app.gateway.authz._get_route_authorization_config",
|
|
lambda: AuthorizationConfig(),
|
|
)
|
|
|
|
|
|
# ── _is_public unit tests ─────────────────────────────────────────────────
|
|
|
|
|
|
@pytest.mark.parametrize(
|
|
"path",
|
|
[
|
|
"/health",
|
|
"/health/",
|
|
"/docs",
|
|
"/docs/",
|
|
"/redoc",
|
|
"/openapi.json",
|
|
"/api/v1/auth/login/local",
|
|
"/api/v1/auth/register",
|
|
"/api/v1/auth/logout",
|
|
"/api/v1/auth/setup-status",
|
|
],
|
|
)
|
|
def test_public_paths(path: str):
|
|
assert _is_public(path) is True
|
|
|
|
|
|
@pytest.mark.parametrize(
|
|
"path",
|
|
[
|
|
"/api/models",
|
|
"/api/mcp/config",
|
|
"/api/mcp/cache/reset",
|
|
"/api/memory",
|
|
"/api/skills",
|
|
"/api/threads/123",
|
|
"/api/threads/123/uploads",
|
|
"/api/agents",
|
|
"/api/channels",
|
|
"/api/channels/providers",
|
|
"/api/channels/slack/connect",
|
|
"/api/runs/stream",
|
|
"/api/threads/123/runs",
|
|
"/api/v1/auth/me",
|
|
"/api/v1/auth/change-password",
|
|
],
|
|
)
|
|
def test_protected_paths(path: str):
|
|
assert _is_public(path) is False
|
|
|
|
|
|
# ── Trailing slash / normalization edge cases ─────────────────────────────
|
|
|
|
|
|
@pytest.mark.parametrize(
|
|
"path",
|
|
[
|
|
"/api/v1/auth/login/local/",
|
|
"/api/v1/auth/register/",
|
|
"/api/v1/auth/logout/",
|
|
"/api/v1/auth/setup-status/",
|
|
],
|
|
)
|
|
def test_public_auth_paths_with_trailing_slash(path: str):
|
|
assert _is_public(path) is True
|
|
|
|
|
|
@pytest.mark.parametrize(
|
|
"path",
|
|
[
|
|
"/api/models/",
|
|
"/api/v1/auth/me/",
|
|
"/api/v1/auth/change-password/",
|
|
],
|
|
)
|
|
def test_protected_paths_with_trailing_slash(path: str):
|
|
assert _is_public(path) is False
|
|
|
|
|
|
def test_unknown_api_path_is_protected():
|
|
"""Fail-closed: any new /api/* path is protected by default."""
|
|
assert _is_public("/api/new-feature") is False
|
|
assert _is_public("/api/v2/something") is False
|
|
assert _is_public("/api/v1/auth/new-endpoint") is False
|
|
|
|
|
|
# ── Middleware integration tests ──────────────────────────────────────────
|
|
|
|
|
|
def _make_app():
|
|
"""Create a minimal FastAPI app with AuthMiddleware for testing."""
|
|
from fastapi import FastAPI, Request
|
|
|
|
from deerflow.runtime.user_context import get_effective_user_id
|
|
|
|
app = FastAPI()
|
|
app.add_middleware(AuthMiddleware)
|
|
|
|
@app.get("/health")
|
|
async def health():
|
|
return {"status": "ok"}
|
|
|
|
@app.get("/api/v1/auth/me")
|
|
async def auth_me(request: Request):
|
|
from app.gateway.deps import get_current_user_from_request
|
|
|
|
user = await get_current_user_from_request(request)
|
|
return {
|
|
"id": str(user.id),
|
|
"email": user.email,
|
|
"system_role": user.system_role,
|
|
"needs_setup": user.needs_setup,
|
|
}
|
|
|
|
@app.get("/api/v1/auth/setup-status")
|
|
async def setup_status():
|
|
return {"needs_setup": False}
|
|
|
|
@app.get("/api/models")
|
|
async def models_get():
|
|
return {"models": []}
|
|
|
|
@app.get("/api/whoami")
|
|
async def whoami(request: Request):
|
|
user = request.state.user
|
|
return {
|
|
"id": str(user.id),
|
|
"email": getattr(user, "email", None),
|
|
"system_role": getattr(user, "system_role", None),
|
|
"context_user_id": get_effective_user_id(),
|
|
}
|
|
|
|
@app.get("/api/current-user-from-dep")
|
|
async def current_user_from_dep(request: Request):
|
|
from app.gateway.deps import get_current_user_from_request
|
|
|
|
user = await get_current_user_from_request(request)
|
|
state_user = request.state.user
|
|
return {
|
|
"id": str(user.id),
|
|
"state_id": str(state_user.id),
|
|
"auth_source": request.state.auth_source,
|
|
"context_user_id": get_effective_user_id(),
|
|
}
|
|
|
|
@app.put("/api/mcp/config")
|
|
async def mcp_put():
|
|
return {"ok": True}
|
|
|
|
@app.post("/api/mcp/cache/reset")
|
|
async def mcp_cache_reset():
|
|
return {"ok": True}
|
|
|
|
@app.delete("/api/threads/abc")
|
|
async def thread_delete():
|
|
return {"ok": True}
|
|
|
|
@app.patch("/api/threads/abc")
|
|
async def thread_patch():
|
|
return {"ok": True}
|
|
|
|
@app.post("/api/threads/abc/runs/stream")
|
|
async def stream():
|
|
return {"ok": True}
|
|
|
|
@app.get("/api/future-endpoint")
|
|
async def future():
|
|
return {"ok": True}
|
|
|
|
return app
|
|
|
|
|
|
def _make_auth_csrf_app():
|
|
"""Create a minimal app with production middleware ordering."""
|
|
from fastapi import FastAPI
|
|
|
|
app = FastAPI()
|
|
app.add_middleware(AuthMiddleware)
|
|
app.add_middleware(CSRFMiddleware)
|
|
|
|
@app.post("/api/threads/abc/runs/stream")
|
|
async def protected_mutation():
|
|
return {"ok": True}
|
|
|
|
return app
|
|
|
|
|
|
@pytest.fixture
|
|
def client(monkeypatch):
|
|
monkeypatch.setenv("DEER_FLOW_AUTH_DISABLED", "")
|
|
return TestClient(_make_app())
|
|
|
|
|
|
def test_public_path_no_cookie(client):
|
|
res = client.get("/health")
|
|
assert res.status_code == 200
|
|
|
|
|
|
def test_public_auth_path_no_cookie(client):
|
|
"""Public auth endpoints (login/register) pass without cookie."""
|
|
res = client.get("/api/v1/auth/setup-status")
|
|
assert res.status_code == 200
|
|
|
|
|
|
@pytest.mark.parametrize(
|
|
"encoded_path",
|
|
[
|
|
"/api/v1/auth/setup-sta%0Atus",
|
|
"/api/v1/auth/setup-sta%0Dtus",
|
|
"/api/v1/auth/setup-sta%09tus",
|
|
"/api/v1/auth/setup-status%23private",
|
|
"/api/v1/auth/setup-status%3Fprivate",
|
|
],
|
|
)
|
|
def test_url_reconstruction_cannot_turn_a_protected_route_path_public(
|
|
monkeypatch,
|
|
encoded_path,
|
|
):
|
|
from fastapi import FastAPI
|
|
|
|
monkeypatch.setenv("DEER_FLOW_AUTH_DISABLED", "")
|
|
app = FastAPI()
|
|
app.add_middleware(AuthMiddleware)
|
|
|
|
@app.get("/api/v1/auth/setup-sta{gap}tus")
|
|
async def control_gap(gap: str):
|
|
return {"gap": gap}
|
|
|
|
@app.get("/api/v1/auth/setup-status{suffix}")
|
|
async def delimiter_suffix(suffix: str):
|
|
return {"suffix": suffix}
|
|
|
|
response = TestClient(app).get(encoded_path)
|
|
|
|
assert response.status_code == 401
|
|
|
|
|
|
def test_auth_uses_the_same_root_path_projection_as_the_router(monkeypatch):
|
|
from fastapi import FastAPI
|
|
|
|
monkeypatch.setenv("DEER_FLOW_AUTH_DISABLED", "")
|
|
child = FastAPI()
|
|
child.add_middleware(AuthMiddleware)
|
|
|
|
@child.get("/health")
|
|
async def health():
|
|
return {"ok": True}
|
|
|
|
parent = FastAPI()
|
|
parent.mount("/prefix", child)
|
|
|
|
response = TestClient(parent).get("/prefix/health")
|
|
|
|
assert response.status_code == 200
|
|
|
|
|
|
def test_protected_auth_path_no_cookie(client):
|
|
"""/auth/me requires cookie even though it's under /api/v1/auth/."""
|
|
res = client.get("/api/v1/auth/me")
|
|
assert res.status_code == 401
|
|
|
|
|
|
def test_protected_path_no_cookie_returns_401(client):
|
|
res = client.get("/api/models")
|
|
assert res.status_code == 401
|
|
body = res.json()
|
|
assert body["detail"]["code"] == "not_authenticated"
|
|
|
|
|
|
def test_auth_disabled_allows_protected_path_without_cookie(monkeypatch):
|
|
monkeypatch.setenv("DEER_FLOW_AUTH_DISABLED", "1")
|
|
client = TestClient(_make_app())
|
|
|
|
res = client.get("/api/models")
|
|
|
|
assert res.status_code == 200
|
|
assert res.json() == {"models": []}
|
|
|
|
|
|
def test_auth_disabled_stamps_default_admin_user_without_cookie(monkeypatch):
|
|
monkeypatch.setenv("DEER_FLOW_AUTH_DISABLED", "1")
|
|
client = TestClient(_make_app())
|
|
|
|
res = client.get("/api/whoami")
|
|
|
|
assert res.status_code == 200
|
|
assert res.json() == {
|
|
"id": "default",
|
|
"email": "default@test.local",
|
|
"system_role": "admin",
|
|
"context_user_id": "default",
|
|
}
|
|
|
|
|
|
def test_auth_disabled_auth_me_reuses_middleware_user_without_cookie(monkeypatch):
|
|
monkeypatch.setenv("DEER_FLOW_AUTH_DISABLED", "1")
|
|
client = TestClient(_make_app())
|
|
|
|
res = client.get("/api/v1/auth/me")
|
|
|
|
assert res.status_code == 200
|
|
assert res.json() == {
|
|
"id": "default",
|
|
"email": "default@test.local",
|
|
"system_role": "admin",
|
|
"needs_setup": False,
|
|
}
|
|
|
|
|
|
def test_auth_disabled_does_not_clobber_valid_session_cookie(monkeypatch):
|
|
from types import SimpleNamespace
|
|
|
|
async def fake_current_user(request):
|
|
return SimpleNamespace(
|
|
id="session-user",
|
|
email="session@test.local",
|
|
system_role="user",
|
|
needs_setup=False,
|
|
)
|
|
|
|
monkeypatch.setenv("DEER_FLOW_AUTH_DISABLED", "1")
|
|
monkeypatch.setattr("app.gateway.deps.get_current_user_from_request", fake_current_user)
|
|
client = TestClient(_make_app())
|
|
|
|
res = client.get("/api/whoami", cookies={"access_token": "valid-session"})
|
|
|
|
assert res.status_code == 200
|
|
assert res.json() == {
|
|
"id": "session-user",
|
|
"email": "session@test.local",
|
|
"system_role": "user",
|
|
"context_user_id": "session-user",
|
|
}
|
|
|
|
|
|
def test_auth_disabled_does_not_clobber_internal_auth_identity(monkeypatch):
|
|
from app.gateway.internal_auth import create_internal_auth_headers
|
|
from deerflow.runtime.user_context import DEFAULT_USER_ID
|
|
|
|
monkeypatch.setenv("DEER_FLOW_AUTH_DISABLED", "1")
|
|
client = TestClient(_make_app())
|
|
|
|
res = client.get(
|
|
"/api/current-user-from-dep",
|
|
headers=create_internal_auth_headers(),
|
|
)
|
|
|
|
assert res.status_code == 200
|
|
assert res.json() == {
|
|
"id": DEFAULT_USER_ID,
|
|
"state_id": DEFAULT_USER_ID,
|
|
"auth_source": "internal",
|
|
"context_user_id": DEFAULT_USER_ID,
|
|
}
|
|
|
|
|
|
def test_auth_disabled_skips_csrf_for_state_changing_requests(monkeypatch):
|
|
monkeypatch.setenv("DEER_FLOW_AUTH_DISABLED", "1")
|
|
client = TestClient(_make_auth_csrf_app())
|
|
|
|
res = client.post("/api/threads/abc/runs/stream")
|
|
|
|
assert res.status_code == 200
|
|
assert res.json() == {"ok": True}
|
|
|
|
|
|
def test_auth_disabled_is_ignored_in_explicit_production_env(monkeypatch):
|
|
monkeypatch.setenv("DEER_FLOW_AUTH_DISABLED", "1")
|
|
monkeypatch.setenv("DEER_FLOW_ENV", "production")
|
|
client = TestClient(_make_app())
|
|
|
|
res = client.get("/api/models")
|
|
|
|
assert res.status_code == 401
|
|
|
|
|
|
def test_auth_disabled_startup_warning_when_effective(monkeypatch, caplog):
|
|
from app.gateway.auth_disabled import warn_if_auth_disabled_enabled
|
|
|
|
monkeypatch.setenv("DEER_FLOW_AUTH_DISABLED", "1")
|
|
monkeypatch.delenv("DEER_FLOW_ENV", raising=False)
|
|
monkeypatch.delenv("ENVIRONMENT", raising=False)
|
|
|
|
with caplog.at_level("WARNING", logger="app.gateway.auth_disabled"):
|
|
warn_if_auth_disabled_enabled()
|
|
|
|
assert "authentication is bypassed" in caplog.text
|
|
assert "default" in caplog.text
|
|
|
|
|
|
def test_auth_disabled_startup_warning_suppressed_in_explicit_production_env(monkeypatch, caplog):
|
|
from app.gateway.auth_disabled import warn_if_auth_disabled_enabled
|
|
|
|
monkeypatch.setenv("DEER_FLOW_AUTH_DISABLED", "1")
|
|
monkeypatch.setenv("ENVIRONMENT", "production")
|
|
|
|
with caplog.at_level("WARNING", logger="app.gateway.auth_disabled"):
|
|
warn_if_auth_disabled_enabled()
|
|
|
|
assert "authentication is bypassed" not in caplog.text
|
|
|
|
|
|
def test_protected_path_with_junk_cookie_rejected(client):
|
|
"""Junk cookie → 401. Middleware strictly validates the JWT now
|
|
(AUTH_TEST_PLAN test 7.5.8); it no longer silently passes bad
|
|
tokens through to the route handler."""
|
|
client.cookies.set("access_token", "some-token")
|
|
res = client.get("/api/models")
|
|
assert res.status_code == 401
|
|
|
|
|
|
def test_protected_post_no_cookie_returns_401(client):
|
|
res = client.post("/api/threads/abc/runs/stream")
|
|
assert res.status_code == 401
|
|
|
|
|
|
def test_mcp_cache_reset_post_no_cookie_returns_401(client):
|
|
res = client.post("/api/mcp/cache/reset")
|
|
assert res.status_code == 401
|
|
|
|
|
|
def test_protected_post_with_internal_auth_header_passes():
|
|
from app.gateway.internal_auth import create_internal_auth_headers
|
|
|
|
app = _make_app()
|
|
client = TestClient(app)
|
|
|
|
res = client.post(
|
|
"/api/threads/abc/runs/stream",
|
|
headers=create_internal_auth_headers(),
|
|
)
|
|
|
|
assert res.status_code == 200
|
|
|
|
|
|
# ── Method matrix: PUT/DELETE/PATCH also protected ────────────────────────
|
|
|
|
|
|
def test_protected_put_no_cookie(client):
|
|
res = client.put("/api/mcp/config")
|
|
assert res.status_code == 401
|
|
|
|
|
|
def test_protected_delete_no_cookie(client):
|
|
res = client.delete("/api/threads/abc")
|
|
assert res.status_code == 401
|
|
|
|
|
|
def test_protected_patch_no_cookie(client):
|
|
res = client.patch("/api/threads/abc")
|
|
assert res.status_code == 401
|
|
|
|
|
|
def test_put_with_junk_cookie_rejected(client):
|
|
"""Junk cookie on PUT → 401 (strict JWT validation in middleware)."""
|
|
client.cookies.set("access_token", "tok")
|
|
res = client.put("/api/mcp/config")
|
|
assert res.status_code == 401
|
|
|
|
|
|
def test_delete_with_junk_cookie_rejected(client):
|
|
"""Junk cookie on DELETE → 401 (strict JWT validation in middleware)."""
|
|
client.cookies.set("access_token", "tok")
|
|
res = client.delete("/api/threads/abc")
|
|
assert res.status_code == 401
|
|
|
|
|
|
# ── Fail-closed: unknown future endpoints ─────────────────────────────────
|
|
|
|
|
|
def test_unknown_endpoint_no_cookie_returns_401(client):
|
|
"""Any new /api/* endpoint is blocked by default without cookie."""
|
|
res = client.get("/api/future-endpoint")
|
|
assert res.status_code == 401
|
|
|
|
|
|
def test_unknown_endpoint_with_junk_cookie_rejected(client):
|
|
"""New endpoints are also protected by strict JWT validation."""
|
|
client.cookies.set("access_token", "tok")
|
|
res = client.get("/api/future-endpoint")
|
|
assert res.status_code == 401
|