Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion orchestrator/routes/anchors.py
Original file line number Diff line number Diff line change
Expand Up @@ -288,7 +288,10 @@ def gc_anchors(pipeline_id: str) -> tuple[Response, int]:
For completed pipelines: archive to checkpoint then clear from Redis.
For failed pipelines: set 7-day TTL.
"""
body = request.get_json() or {}
raw = request.get_json()
if raw is not None and not isinstance(raw, dict):
return _make_error("Request body must be a JSON object")
body = raw if raw is not None else {}
pipeline_status = body.get("status", "completed")

r = _get_redis()
Expand Down
10 changes: 8 additions & 2 deletions orchestrator/routes/containers.py
Original file line number Diff line number Diff line change
Expand Up @@ -128,7 +128,10 @@ def spawn_container(pipeline_id: str) -> tuple[Response, int]:
}
}
"""
data = request.get_json() or {}
raw = request.get_json()
if raw is not None and not isinstance(raw, dict):
return make_error_response("Request body must be a JSON object")
data = raw if raw is not None else {}

# Parse agent role
agent_role = None
Expand Down Expand Up @@ -375,7 +378,10 @@ def stop_container(pipeline_id: str, container_id: str) -> tuple[Response, int]:
}
}
"""
data = request.get_json() or {}
raw = request.get_json()
if raw is not None and not isinstance(raw, dict):
return make_error_response("Request body must be a JSON object")
data = raw if raw is not None else {}
timeout = data.get("timeout", 10)

try:
Expand Down
5 changes: 4 additions & 1 deletion orchestrator/routes/health.py
Original file line number Diff line number Diff line change
Expand Up @@ -365,7 +365,10 @@ def resolve_pipeline_health_alerts(pipeline_id: str) -> tuple[Response, int]:
if monitor is None:
return jsonify({"success": False, "error": "Health monitor not initialized"}), 503

data = request.get_json() or {}
raw = request.get_json()
if raw is not None and not isinstance(raw, dict):
return jsonify({"success": False, "error": "Request body must be a JSON object"}), 400
data = raw if raw is not None else {}
agent_id = data.get("agent_id")
alert_type = data.get("alert_type")

Expand Down
9 changes: 7 additions & 2 deletions orchestrator/routes/messages.py
Original file line number Diff line number Diff line change
Expand Up @@ -155,8 +155,10 @@ def send_message(pipeline_id: str) -> tuple[Response, int]:
questions atomically with the review verdict.
"""
body = request.get_json()
if not body:
if body is None:
return _make_error("Missing request body")
if not isinstance(body, dict):
return _make_error("Request body must be a JSON object")

from_role = body.get("from_role")
if not from_role:
Expand Down Expand Up @@ -571,7 +573,10 @@ def post_heartbeat(pipeline_id: str) -> tuple[Response, int]:
TASK-3-4. Slice-scoping (#2471) keeps sibling slices that
share a role from sharing each other's rate budget.
"""
body = request.get_json() or {}
raw = request.get_json()
if raw is not None and not isinstance(raw, dict):
return _make_error("Request body must be a JSON object")
body = raw if raw is not None else {}

from_role = body.get("from_role")
if not from_role:
Expand Down
21 changes: 21 additions & 0 deletions orchestrator/tests/test_anchors_routes.py
Original file line number Diff line number Diff line change
Expand Up @@ -309,3 +309,24 @@ def test_gc_failed_pipeline_sets_ttl(self, client, mock_redis):
)
assert response.status_code == 200
mock_redis.expire.assert_called()

@pytest.mark.parametrize(
"raw_body",
["[1, 2, 3]", '"a string body"', "42", "true"],
ids=["array", "string", "number", "bool"],
)
def test_gc_non_object_body_returns_400(self, client, raw_body):
"""Fix for #2673: non-object JSON bodies must 400, not 500.

Mirrors the #2656 fix on the decisions route. Without the guard,
``body.get("status", ...)`` raises ``AttributeError`` for a
list/scalar body and the generic handler returns 500.
"""
response = client.post(
"/api/v1/anchors/gc/issue-1032",
data=raw_body,
content_type="application/json",
)
assert response.status_code == 400, response.data
body = json.loads(response.data)
assert body["success"] is False
92 changes: 92 additions & 0 deletions orchestrator/tests/test_containers_routes.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
"""Unit tests for container API routes (orchestrator/routes/containers.py).

Covers the body-validation guard on the lifecycle-authed POST routes
(``/spawn``, ``/containers/<id>/stop``) — the #2673 sweep of the
``request.get_json() or {}`` + ``.get(...)`` pattern that was leaking
500s for non-object JSON bodies.
"""

import json
import sys
from pathlib import Path

import pytest

_orchestrator_path = Path(__file__).parent.parent
if str(_orchestrator_path) not in sys.path:
sys.path.insert(0, str(_orchestrator_path))

_shared_path = Path(__file__).parent.parent.parent / "shared"
if _shared_path.exists() and str(_shared_path) not in sys.path:
sys.path.insert(0, str(_shared_path))


_LIFECYCLE_SECRET = "test-secret"


@pytest.fixture
def app(monkeypatch):
"""Create a test Flask app with the containers blueprint."""
monkeypatch.setenv("EGG_LIFECYCLE_SECRET", _LIFECYCLE_SECRET)

from flask import Flask
from routes.containers import containers_bp

app = Flask(__name__)
app.register_blueprint(containers_bp)
app.config["TESTING"] = True
yield app


@pytest.fixture
def client(app):
"""Create a test client."""
return app.test_client()


@pytest.fixture
def auth_headers():
"""Bearer header valid for the lifecycle decorator under test."""
return {"Authorization": f"Bearer {_LIFECYCLE_SECRET}"}


class TestNonObjectJsonBodyReturns400:
"""Fix for #2673: non-object JSON bodies must 400, not 500.

Mirrors the #2656 fix on the decisions route. Previously
``data = request.get_json() or {}`` left a list / scalar in
``data`` and ``data.get(...)`` raised ``AttributeError`` →
the generic exception handler returned 500.
"""

@pytest.mark.parametrize(
"raw_body",
["[1, 2, 3]", '"a string body"', "42", "true"],
ids=["array", "string", "number", "bool"],
)
def test_spawn_non_object_body_returns_400(self, client, auth_headers, raw_body):
response = client.post(
"/api/v1/pipelines/test-pipeline/spawn",
data=raw_body,
content_type="application/json",
headers=auth_headers,
)
assert response.status_code == 400, response.data
body = json.loads(response.data)
assert body["success"] is False

@pytest.mark.parametrize(
"raw_body",
["[1, 2, 3]", '"a string body"', "42", "true"],
ids=["array", "string", "number", "bool"],
)
def test_stop_non_object_body_returns_400(self, client, auth_headers, raw_body):
response = client.post(
"/api/v1/pipelines/test-pipeline/containers/abc123/stop",
data=raw_body,
content_type="application/json",
headers=auth_headers,
)
assert response.status_code == 400, response.data
body = json.loads(response.data)
assert body["success"] is False
24 changes: 24 additions & 0 deletions orchestrator/tests/test_health_routes.py
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,30 @@ def test_happy_path_returns_200(self, mock_get_monitor, client):
assert data["resolved"] is True
mock_monitor.resolve_alerts.assert_called_once_with("coder", "heartbeat_timeout")

@pytest.mark.parametrize(
"raw_body",
["[1, 2, 3]", '"a string body"', "42", "true"],
ids=["array", "string", "number", "bool"],
)
@patch("health_monitor.get_health_monitor")
def test_non_object_body_returns_400(self, mock_get_monitor, client, raw_body):
"""Fix for #2673: non-object JSON bodies must 400, not 500.

Mirrors the #2656 fix on the decisions route. Without the guard,
``data.get("agent_id")`` raises ``AttributeError`` for a
list/scalar body and Flask's default handler returns 500.
"""
mock_get_monitor.return_value = MagicMock()

response = client.post(
"/api/v1/pipelines/test-pipeline/health/alerts/resolve",
data=raw_body,
content_type="application/json",
)
assert response.status_code == 400, response.data
data = response.get_json()
assert data["success"] is False


class TestHealthEndpointIsolationFromMessageStore:
"""Issue #1897 TASK-4-3 (regression lock): ``GET /api/v1/health`` MUST
Expand Down
41 changes: 41 additions & 0 deletions orchestrator/tests/test_messages.py
Original file line number Diff line number Diff line change
Expand Up @@ -2951,3 +2951,44 @@ def test_timeout_zero_coerced_to_1s_minimum(self, client, app):
"per routes/messages.py:382-385. If this drops to ~0s, "
"the silent floor has been removed — update the docstring."
)


class TestNonObjectJsonBodyReturns400:
"""Fix for #2673: non-object JSON bodies must 400, not 500.

Mirrors the #2656 fix on the decisions route. Previously
``body = request.get_json() or {}`` (heartbeat) or
``body = request.get_json(); if not body`` (messages) left a
list/scalar in ``body``, so ``body.get(...)`` raised
``AttributeError`` and the generic handler returned 500.
"""

@pytest.mark.parametrize(
"raw_body",
["[1, 2, 3]", '"a string body"', "42", "true"],
ids=["array", "string", "number", "bool"],
)
def test_send_message_non_object_body_returns_400(self, client, raw_body):
response = client.post(
"/api/v1/pipelines/test-pipeline/messages",
data=raw_body,
content_type="application/json",
)
assert response.status_code == 400, response.data
body = json.loads(response.data)
assert body["success"] is False

@pytest.mark.parametrize(
"raw_body",
["[1, 2, 3]", '"a string body"', "42", "true"],
ids=["array", "string", "number", "bool"],
)
def test_heartbeat_non_object_body_returns_400(self, client, raw_body):
response = client.post(
"/api/v1/pipelines/test-pipeline/heartbeat",
data=raw_body,
content_type="application/json",
)
assert response.status_code == 400, response.data
body = json.loads(response.data)
assert body["success"] is False
Loading