Repository navigation
fix(security): bind batch routing jobs to authenticated owners #909
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from 26 commits
f11b66e
e849a38
d3d2e31
e570534
069d5dc
3dd220c
ef12921
1ac0c8e
68a421f
6ce2a82
35e6a73
96c2705
34c5b80
97eb8d5
76d1254
0130f94
54d4091
b6c63b4
eaaa9e2
5f7ae2e
661360d
95dff0e
2323095
0cba666
b87a75c
42fd380
2283f4c
6d0ecba
42959f8
35d9f54
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,60 @@ | ||
| name: Repair PR 909 final contracts | ||
|
|
||
| on: | ||
| push: | ||
| branches: | ||
| - fix/batch-routing-owner-20260829 | ||
|
|
||
| permissions: | ||
| contents: write | ||
|
|
||
| concurrency: | ||
| group: repair-pr-909-final-contracts | ||
| cancel-in-progress: false | ||
|
|
||
| jobs: | ||
| repair: | ||
| runs-on: ubuntu-latest | ||
| timeout-minutes: 20 | ||
| steps: | ||
| - name: Check out exact PR head | ||
| uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 | ||
| with: | ||
| fetch-depth: 0 | ||
|
|
||
| - name: Set up Python | ||
| uses: actions/setup-python@ece7cb06caefa5fff74198d8649806c4678c61a1 | ||
| with: | ||
| python-version: "3.12" | ||
|
|
||
| - name: Set up uv | ||
| uses: astral-sh/setup-uv@d0cc045d04ccac9d8b7881df0226f9e82c39688e | ||
| with: | ||
| version: "0.12.5" | ||
|
|
||
| - name: Apply, validate, and commit the final review contracts | ||
| env: | ||
| EXPECTED_PARENT: b87a75ce807593aa501e643a46906cc8a06b2411 | ||
| BRANCH: fix/batch-routing-owner-20260829 | ||
| shell: bash | ||
| run: | | ||
| set -euo pipefail | ||
| test "$(git branch --show-current)" = "$BRANCH" | ||
| test "$(git rev-parse HEAD^)" = "$EXPECTED_PARENT" | ||
| python scripts/ci/repair_pr_909_final_contracts.py | ||
| rm -f \ | ||
| scripts/ci/repair_pr_909_final_contracts.py \ | ||
| .github/workflows/repair-pr-909-final-contracts.yml | ||
| git add -A | ||
| git diff --cached --check | ||
| uv run --locked --extra api --extra db --extra queue --group dev \ | ||
| python -m pytest -q \ | ||
| tests/test_cost_router_boundaries.py::test_batch_model_identity_error_does_not_capture_backend_value_errors \ | ||
| tests/test_cost_review_server.py::test_batch_routing_rejects_unknown_zdr_model_as_client_error \ | ||
| tests/test_cost_router.py::test_zdr_batch_rejects_an_explicit_non_zdr_configured_model \ | ||
| tests/test_api_contract.py::test_batch_job_openapi_documents_principal_hiding_404s \ | ||
| tests/test_orchestrated_responses_stream.py::test_stream_usage_failure_remains_inside_the_started_sse_protocol | ||
| git config user.name 'github-actions[bot]' | ||
| git config user.email '41898282+github-actions[bot]@users.noreply.github.com' | ||
| git commit -m 'fix: preserve final batch and SSE protocol boundaries' | ||
| git push origin "HEAD:$BRANCH" | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1 @@ | ||
| Bound HTTP-created batch routing jobs to the authenticated principal and preserved cross-owner not-found behavior. An unknown explicit ZDR model is now the non-retryable `400 invalid_model` client error, while a configured model that is ineligible for the requested ZDR policy retains the retryable batch-selection failure contract. |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -269,7 +269,9 @@ def complete( | |
| mode=mode, | ||
| zdr_only=zdr_only, | ||
| ) | ||
| job = self.submit_batch([request], metadata={"routing_reason": decision.reason}) | ||
| job = self.submit_batch( | ||
| [request], metadata={"routing_reason": decision.reason}, owner_id=owner_id | ||
| ) | ||
| return { | ||
| "channel": "batch", | ||
| "routing_reason": decision.reason, | ||
|
|
@@ -652,15 +654,19 @@ def submit_batch( | |
| self, | ||
| requests: List[BatchRequest], | ||
| metadata: Optional[Dict[str, Any]] = None, | ||
| owner_id: Optional[str] = None, | ||
| ) -> BatchJob: | ||
| """Submit a batch of requests to the configured batch backend.""" | ||
| """Submit a batch, resolve its targets, and bind its authenticated owner.""" | ||
| try: | ||
| prepared_requests = [self._resolve_batch_request(request) for request in requests] | ||
| except (RuntimeError, ValueError) as exc: | ||
| except ValueError: | ||
| raise | ||
|
devin-ai-integration[bot] marked this conversation as resolved.
Resolved
|
||
| except RuntimeError as exc: | ||
| raise BatchModelSelectionError( | ||
| "no eligible model-group member is available for this batch request" | ||
| ) from exc | ||
|
seonghobae marked this conversation as resolved.
Resolved
|
||
| job = self.batch_backend.submit(prepared_requests, metadata=metadata) | ||
| job.owner_id = owner_id | ||
| self._batch_jobs[job.job_id] = job | ||
| return job | ||
|
|
||
|
|
@@ -669,7 +675,18 @@ def _resolve_batch_request(self, request: BatchRequest) -> BatchRequest: | |
| if not request.zdr_only: | ||
| return request | ||
| with self.orchestrator.request_policy(request.zdr_only): | ||
| agent = self.orchestrator._requested_agent(request.model) | ||
| try: | ||
| agent = self.orchestrator._requested_agent(request.model) | ||
| except ValueError as exc: | ||
| configured_exact = any( | ||
| candidate.model == request.model | ||
| for candidate in self.orchestrator.candidates | ||
| ) | ||
|
Comment on lines
+685
to
+688
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🟡 Configured ZDR group reported missing When every member of a requested group lacks ZDR eligibility, Prompt for agentsWas this helpful? React with 👍 or 👎 to provide feedback. |
||
| if configured_exact: | ||
| raise RuntimeError( | ||
| "requested model is configured but not eligible for ZDR batch routing" | ||
| ) from exc | ||
| raise | ||
| if agent is None: | ||
| text = self.orchestrator._latest_user_text(request.messages) | ||
| agent = self.orchestrator._select_agent( | ||
|
|
@@ -680,14 +697,14 @@ def _resolve_batch_request(self, request: BatchRequest) -> BatchRequest: | |
| ) | ||
| return replace(request, model=agent.model) | ||
|
|
||
| def poll_batch(self, job_id: str) -> Dict[str, Any]: | ||
| """Poll a previously submitted batch job by id.""" | ||
| job = self._require_job(job_id) | ||
| def poll_batch(self, job_id: str, *, owner_id: Optional[str] = None) -> Dict[str, Any]: | ||
| """Poll a previously submitted batch job owned by ``owner_id``.""" | ||
| job = self._require_job(job_id, owner_id=owner_id) | ||
| return self.batch_backend.poll(job) | ||
|
|
||
| def retrieve_batch(self, job_id: str) -> Dict[str, Any]: | ||
| """Retrieve batch results and record usage + cost for each completion.""" | ||
| job = self._require_job(job_id) | ||
| def retrieve_batch(self, job_id: str, *, owner_id: Optional[str] = None) -> Dict[str, Any]: | ||
| """Retrieve results for a batch owned by ``owner_id`` and record usage.""" | ||
| job = self._require_job(job_id, owner_id=owner_id) | ||
| items: List[BatchResultItem] = self.batch_backend.retrieve(job) | ||
|
seonghobae marked this conversation as resolved.
Resolved
|
||
| recorded: List[Dict[str, Any]] = [] | ||
| for item in items: | ||
|
|
@@ -729,9 +746,9 @@ def _resolve_batch_provider_model(self, item: BatchResultItem) -> tuple[str, str | |
| provider = "unknown" | ||
| return provider, item.model | ||
|
|
||
| def _require_job(self, job_id: str) -> BatchJob: | ||
| def _require_job(self, job_id: str, *, owner_id: Optional[str] = None) -> BatchJob: | ||
| job = self._batch_jobs.get(job_id) | ||
| if job is None: | ||
| if job is None or job.owner_id != owner_id: | ||
| raise KeyError(f"batch job {job_id!r} not found") | ||
| return job | ||
|
seonghobae marked this conversation as resolved.
Resolved
|
||
|
|
||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -346,6 +346,9 @@ class SecurityConfig: | |
| # relying-party adapter). The core deliberately does not decode JWTs with | ||
| # an unsafe hand-rolled parser or own Keycloak admin credentials. | ||
| bearer_verifier: Callable[[str, str], bool] | None = None | ||
| # Optional companion seam for external verifiers that can expose a stable, | ||
| # tenant-scoped principal key without exposing the bearer itself. | ||
| principal_resolver: Callable[[str], str | None] | None = None | ||
| _rate_buckets: dict[str, tuple[int, float]] = field(default_factory=dict, init=False, repr=False) | ||
| _rate_lock: threading.Lock = field(default_factory=threading.Lock, init=False, repr=False) | ||
| _run_semaphore: threading.BoundedSemaphore = field(init=False, repr=False) | ||
|
|
@@ -471,13 +474,27 @@ def principal_id(self, headers: Any) -> str: | |
| if principal: | ||
| return principal | ||
| raise RequestError(401, "unauthorized", "authenticated principal is required") | ||
| return self._principal_digest(token) | ||
|
|
||
| def _principal_digest(self, token: str) -> str: | ||
| """Hash a stable deployment principal without retaining bearer material.""" | ||
| if self.bearer_verifier is None: | ||
| if self.admin_token and self.inference_token: | ||
| principal_material = f"split:{self.admin_token}\x00{self.inference_token}" | ||
| else: | ||
| principal_material = f"single:{self.auth_token}" | ||
| else: | ||
| elif self.principal_resolver is None: | ||
| # Back-compatible fallback for adapters that only return bool; | ||
| # token rotation can intentionally revoke old resource access. | ||
| principal_material = f"bearer:{token}" | ||
|
Comment on lines
+490
to
493
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. |
||
| else: | ||
| try: | ||
| resolved = self.principal_resolver(token) | ||
| except Exception as exc: # noqa: BLE001 - identity adapter failure denies access | ||
| raise RequestError(401, "unauthorized", "authenticated principal is unavailable") from exc | ||
| if not isinstance(resolved, str) or not resolved.strip(): | ||
| raise RequestError(401, "unauthorized", "authenticated principal is unavailable") | ||
| principal_material = f"principal:{resolved}" | ||
| return hashlib.sha256(principal_material.encode("utf-8")).hexdigest() | ||
|
seonghobae marked this conversation as resolved.
Resolved
seonghobae marked this conversation as resolved.
Resolved
|
||
|
|
||
| @staticmethod | ||
|
|
@@ -514,14 +531,7 @@ def establish_admin_session(self, presented_token: str) -> str: | |
| raise RequestError(401, "unauthorized", "bearer token is invalid for this scope") | ||
| session_id = secrets.token_urlsafe(32) | ||
| expires_at = time.monotonic() + float(self.admin_session_ttl_seconds) | ||
| if self.bearer_verifier is None: | ||
| if self.admin_token and self.inference_token: | ||
| principal_material = f"split:{self.admin_token}\x00{self.inference_token}" | ||
| else: | ||
| principal_material = f"single:{self.auth_token}" | ||
| else: | ||
| principal_material = f"bearer:{presented_token}" | ||
| principal = hashlib.sha256(principal_material.encode("utf-8")).hexdigest() | ||
| principal = self._principal_digest(presented_token) | ||
| with self._session_lock: | ||
| self._purge_expired_admin_sessions_locked(time.monotonic()) | ||
| overflow = len(self._admin_sessions) - self.max_admin_sessions + 1 | ||
|
|
@@ -5551,7 +5561,11 @@ def do_GET(self) -> None: # noqa: N802 | |
| if path.startswith("/api/v1/batch_routing_jobs/"): | ||
| job_id = path.rsplit("/", 1)[-1] | ||
| try: | ||
| self._send(coordinator.poll_batch(job_id)) | ||
| self._send( | ||
| coordinator.poll_batch( | ||
| job_id, owner_id=security.principal_id(self.headers) | ||
| ) | ||
|
seonghobae marked this conversation as resolved.
Resolved
|
||
| ) | ||
|
coderabbitai[bot] marked this conversation as resolved.
Resolved
|
||
| except KeyError: | ||
| self._send_error(404, "batch_job_not_found", f"batch job {job_id} not found") | ||
| return | ||
|
seonghobae marked this conversation as resolved.
Resolved
|
||
|
|
@@ -6356,6 +6370,7 @@ def register_video_job(agent: ModelAgent, provider_result: dict[str, Any]) -> di | |
| workflow_run_id=f"run_{uuid.uuid4().hex}", | ||
| cache_bypass=cache_bypass, | ||
| cache_partition=cache_partition, | ||
| owner_id=security.principal_id(self.headers), | ||
|
seonghobae marked this conversation as resolved.
Resolved
|
||
| zdr_only=zdr_only, | ||
| )) | ||
| # Batch-channel Completions return a job handle (202), not a | ||
|
|
@@ -6722,6 +6737,7 @@ def register_video_job(agent: ModelAgent, provider_result: dict[str, Any]) -> di | |
| workflow_run_id=f"run_{uuid.uuid4().hex}", | ||
| cache_bypass=cache_bypass, | ||
| cache_partition=cache_partition, | ||
| owner_id=security.principal_id(self.headers), | ||
| zdr_only=zdr_only, | ||
| )) | ||
| # Latency-tolerant requests get dispatched to the batch backend. | ||
|
|
@@ -6960,7 +6976,16 @@ def register_video_job(agent: ModelAgent, provider_result: dict[str, Any]) -> di | |
| zdr_only=zdr_only, | ||
| ) | ||
| metadata = {"actor_scope": "inference"} | ||
| job = self._run(lambda: coordinator.submit_batch(batch_requests, metadata=metadata)) | ||
| try: | ||
| job = self._run( | ||
| lambda: coordinator.submit_batch( | ||
| batch_requests, | ||
| metadata=metadata, | ||
| owner_id=security.principal_id(self.headers), | ||
| ) | ||
| ) | ||
| except ValueError as exc: | ||
| raise RequestError(400, "invalid_model", str(exc)) from exc | ||
|
coderabbitai[bot] marked this conversation as resolved.
Resolved
devin-ai-integration[bot] marked this conversation as resolved.
Resolved
|
||
| orchestrator.record_analytics_event( | ||
| "batch_routing_job_created", | ||
| { | ||
|
|
@@ -6983,7 +7008,11 @@ def register_video_job(agent: ModelAgent, provider_result: dict[str, Any]) -> di | |
| job_id = path[len("/api/v1/batch_routing_jobs/"):-len("/results")] | ||
| self._authorize_trace_access() | ||
| try: | ||
| retrieved = self._run(lambda: coordinator.retrieve_batch(job_id)) | ||
| retrieved = self._run( | ||
| lambda: coordinator.retrieve_batch( | ||
| job_id, owner_id=security.principal_id(self.headers) | ||
| ) | ||
| ) | ||
| except KeyError: | ||
| self._send_error(404, "batch_job_not_found", f"batch job {job_id} not found") | ||
| return | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -2,7 +2,7 @@ | |
| title: "Streamed Responses usage and cost evidence" | ||
| status: "implemented on feature branch" | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win 병합 후에도 유효한 상태값으로 수정하세요.
🤖 Prompt for AI Agents |
||
| date: "2026-08-29" | ||
| scope: "ADR 0038" | ||
| scope: "ADR 0040" | ||
| --- | ||
|
|
||
| # Streamed Responses usage and cost evidence | ||
|
|
||
Uh oh!
There was an error while loading. Please reload this page.