Skip to content
Merged
8 changes: 6 additions & 2 deletions .agents/flow/issues/m10-candidate-launch-override.en.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ English | [中文](m10-candidate-launch-override.md)
kind: issue
milestone: m10
priority: P0
status: ready
status: in-progress
scope:
- .agents/flow/issues/m10-candidate-launch-override.md
- .agents/flow/issues/m10-candidate-launch-override.en.md
Expand All @@ -18,16 +18,20 @@ scope:
- backend/app/api/dependencies.py
- backend/app/models/evaluation.py
- backend/app/models/identity.py
- backend/app/models/__init__.py
- backend/app/services/service_tokens.py
- backend/app/api/service_tokens.py
- backend/app/main.py
- backend/migrations/**
- tests/backend/test_eval_templates.py
- tests/backend/test_results.py
- tests/backend/test_service_tokens.py
- tests/backend/test_operations.py
- tests/backend/test_deployment_migration.py
- docs/design/eval-platform-architecture.md
- docs/design/eval-platform-architecture.en.md
- docs/design/eval-platform-architecture.i18n.yaml
- scripts/doc-budgets.manifest.json
adr: []
github:
number: 429
Expand Down Expand Up @@ -168,7 +172,7 @@ GET /api/v1/eval-runs/{run_id}/results
- Cross-repository injection: an unregistered `repo_url` answers 422 `asset_source_unresolved`; after registration the same request succeeds.
- Empty selection or a missing path after override: 422 `asset_selection_empty / asset_path_not_found`, and no run is created.
- Console one-click launches without `asset_override` behave unchanged: no `asset` block in the response, and permission, idempotency, and validation semantics stay the same.
- Service token: no token, wrong scope, or a template outside the allowlist → 403; audit records `created_by=svc:<name>`; an idempotent replay returns the same run; `npm test`, `npm run verify:flow`, `npm run lint:docs`, `npm run verify:docs`, and PR CI pass.
- Service token: no valid credential (no token, invalid, revoked, or expired) → 401 `unauthenticated`; an insufficient scope or a template outside the allowlist → 403 `forbidden`; reaching the concurrency or daily-budget cap → 429 `service_token_limit_exceeded`; audit records `created_by=svc:<name>`; an idempotent replay returns the same run; `npm test`, `npm run verify:flow`, `npm run lint:docs`, `npm run verify:docs`, and PR CI pass.

## Non-goals

Expand Down
4 changes: 2 additions & 2 deletions .agents/flow/issues/m10-candidate-launch-override.i18n.yaml
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
# 双语配对一致性记录(docs/i18n/README.md):两侧在最后一次确认一致状态下的
# git blob hash。两种语言同等权威;编辑任一侧后带上另一侧,然后重录:
# pnpm run record:i18n -- .agents/flow/issues/m10-candidate-launch-override.md
m10-candidate-launch-override.md: 9764f3009c23d705bbecae7081ae01b748b7a7d5
m10-candidate-launch-override.en.md: 4b39ff374064102e9802e4a7d4be099c7a450975
m10-candidate-launch-override.md: 05a694ce6dfe42d38b60a8fc9a47121d7a1b23d1
m10-candidate-launch-override.en.md: 20064471002bebb0e0458da82c4c60eca63376bc
8 changes: 6 additions & 2 deletions .agents/flow/issues/m10-candidate-launch-override.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
kind: issue
milestone: m10
priority: P0
status: ready
status: in-progress
scope:
- .agents/flow/issues/m10-candidate-launch-override.md
- .agents/flow/issues/m10-candidate-launch-override.en.md
Expand All @@ -18,16 +18,20 @@ scope:
- backend/app/api/dependencies.py
- backend/app/models/evaluation.py
- backend/app/models/identity.py
- backend/app/models/__init__.py
- backend/app/services/service_tokens.py
- backend/app/api/service_tokens.py
- backend/app/main.py
- backend/migrations/**
- tests/backend/test_eval_templates.py
- tests/backend/test_results.py
- tests/backend/test_service_tokens.py
- tests/backend/test_operations.py
- tests/backend/test_deployment_migration.py
- docs/design/eval-platform-architecture.md
- docs/design/eval-platform-architecture.en.md
- docs/design/eval-platform-architecture.i18n.yaml
- scripts/doc-budgets.manifest.json
adr: []
github:
number: 429
Expand Down Expand Up @@ -168,7 +172,7 @@ GET /api/v1/eval-runs/{run_id}/results
- 跨仓注入:`repo_url` 未登记时 422 `asset_source_unresolved`;登记后同一请求成功。
- 覆盖后选择为空或路径不存在:422 `asset_selection_empty / asset_path_not_found`,不创建 run。
- 不带 `asset_override` 的控制台一键启动行为不变:响应无 `asset` 块,权限、幂等与校验语义不变。
- 服务令牌:无令牌/错 scope/模板不在白名单 → 403;审计记录 `created_by=svc:<name>`;幂等重放返回同一 run;`npm test`、`npm run verify:flow`、`npm run lint:docs`、`npm run verify:docs` 与 PR CI 通过。
- 服务令牌:无有效凭据(无令牌/无效/已撤销/已过期)→ 401 `unauthenticated`;scope 不足或模板不在白名单 → 403 `forbidden`;达到并发或当日预算上限 → 429 `service_token_limit_exceeded`;审计记录 `created_by=svc:<name>`;幂等重放返回同一 run;`npm test`、`npm run verify:flow`、`npm run lint:docs`、`npm run verify:docs` 与 PR CI 通过。

## 非目标

Expand Down
104 changes: 103 additions & 1 deletion backend/app/api/dependencies.py
Original file line number Diff line number Diff line change
@@ -1,20 +1,47 @@
"""FastAPI dependencies for console session and role enforcement."""
"""FastAPI dependencies for console session and role enforcement.

M10 (#429) adds the machine-identity path: ``require_session_or_service``
accepts either the console session cookie or ``Authorization: Bearer hev_...``.
A service token must carry the scope the route declares and, for launches, the
requested template must be inside the token's allowlist. A present but
malformed ``Authorization`` header is always a 401 — it never silently falls
back to the cookie, so a caller cannot mistake a broken machine credential for
a working console session.
"""

from __future__ import annotations

from collections.abc import Callable
from dataclasses import dataclass
from typing import Annotated

from fastapi import Depends, HTTPException, Request
from sqlalchemy.orm import Session

from ..config import Settings, get_settings
from ..db import get_session
from ..models import SERVICE_TOKEN_SCOPES, ServiceToken
from ..services import identity
from ..services import service_tokens as token_service
from .errors import error_detail

SessionDep = Annotated[Session, Depends(get_session)]
SettingsDep = Annotated[Settings, Depends(get_settings)]

SCOPE_EVAL_LAUNCH = "eval:launch"
SCOPE_EVAL_READ = "eval:read"


@dataclass(frozen=True)
class Actor:
"""The authenticated principal of a stable execution API call."""

label: str
is_admin: bool
is_service: bool
scopes: frozenset[str] = frozenset()
service_token: ServiceToken | None = None


def _unauthenticated(message: str = "登录已失效,请重新登录。") -> HTTPException:
return HTTPException(
Expand All @@ -23,6 +50,13 @@ def _unauthenticated(message: str = "登录已失效,请重新登录。") -> H
)


def _forbidden(message: str) -> HTTPException:
return HTTPException(
status_code=403,
detail=error_detail("forbidden", message),
)


def _resolve(
request: Request,
session: Session,
Expand Down Expand Up @@ -64,3 +98,71 @@ def require_admin(
detail=error_detail("forbidden", "当前账号没有写入权限。"),
)
return context


def _service_actor(
request: Request,
session: Session,
header: str,
*,
scope: str,
) -> Actor:
parts = header.strip().split(None, 1)
if len(parts) != 2 or parts[0].lower() != "bearer":
raise _unauthenticated("服务令牌格式不正确,请使用 Bearer hev_... 认证。")
raw_token = parts[1].strip()
if not raw_token.startswith(token_service.TOKEN_PREFIX):
raise _unauthenticated("服务令牌格式不正确,请使用 Bearer hev_... 认证。")
token = token_service.authenticate(session, raw_token)
if token is None:
raise _unauthenticated("服务令牌无效、已撤销或已过期。")
scopes = frozenset(str(item) for item in (token.scopes_json or []))
if scope not in scopes:
raise _forbidden("服务令牌缺少所需权限。")
if scope == SCOPE_EVAL_LAUNCH:
allowlist = [str(item) for item in (token.template_allowlist_json or [])]
if allowlist:
template_id = str(request.path_params.get("template_id") or "")
if template_id not in allowlist:
raise _forbidden("服务令牌无权启动该模板。")
return Actor(
label=token_service.actor_label(token),
is_admin=False,
is_service=True,
scopes=scopes,
service_token=token,
)


def require_session_or_service(scope: str) -> Callable[..., Actor]:
"""Build the dependency for a stable execution route.

``scope`` is one of ``SERVICE_TOKEN_SCOPES``: ``eval:launch`` additionally
requires the admin role for a console session, while ``eval:read`` accepts
any authenticated role.
"""

if scope not in SERVICE_TOKEN_SCOPES:
raise ValueError(f"unknown service token scope: {scope}")

def dependency(
request: Request,
session: SessionDep,
settings: SettingsDep,
) -> Actor:
header = request.headers.get("Authorization")
if header is not None:
return _service_actor(request, session, header, scope=scope)
context = _resolve(request, session, settings)
if context is None:
raise _unauthenticated()
request.state.auth = context
if scope == SCOPE_EVAL_LAUNCH and context.role != identity.ROLE_ADMIN:
raise _forbidden("当前账号没有写入权限。")
return Actor(
label=context.user.email,
is_admin=context.role == identity.ROLE_ADMIN,
is_service=False,
)

return dependency
71 changes: 64 additions & 7 deletions backend/app/api/eval_templates.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,8 @@
from ..db import get_session
from ..services import eval_templates as template_service
from ..services import identity
from .dependencies import require_admin, require_session
from ..services import service_tokens as token_service
from .dependencies import Actor, require_admin, require_session, require_session_or_service
from .errors import error_detail
from .evaluations import CaseSelectionRequest, ExecutionPolicyRequest

Expand Down Expand Up @@ -86,12 +87,41 @@ class TemplateUpdateRequest(BaseModel):
enabled: bool | None = None


class AssetOverrideRequest(BaseModel):
"""M10 (#429): optional candidate asset selection for a machine launch.

Whole-field replacement semantics: a field that is absent inherits the
template; a field that is present replaces the template value entirely (no
merging). ``commit`` is the authoritative identity and ``ref`` is display
and audit only, so a candidate is always pinned by commit.
"""

repo_url: str | None = Field(default=None, max_length=500)
ref: str | None = Field(default=None, max_length=200)
commit: str | None = Field(default=None, pattern="^[0-9a-f]{40}$")
asset_paths: list[str] | None = None
asset_types: dict[str, str] | None = None


class LaunchLineageRequest(BaseModel):
"""Caller provenance stored on the run; never part of evaluation semantics."""

evolutionRunId: str | None = Field(default=None, max_length=64)
evolutionRoundId: str | None = Field(default=None, max_length=64)
roundSeq: int | None = Field(default=None, ge=1)
parentCommit: str | None = Field(default=None, max_length=40)


class LaunchTemplateRequest(BaseModel):
idempotency_key: str | None = Field(default=None, max_length=128)
name: str | None = Field(default=None, max_length=200)
asset_override: AssetOverrideRequest | None = None
lineage: LaunchLineageRequest | None = None


def _http_error(error: template_service.TemplateError) -> HTTPException:
def _http_error(
error: template_service.TemplateError | token_service.ServiceTokenError,
) -> HTTPException:
details = dict(error.details or {})
if error.field:
fields = dict(details.get("fields") or {})
Expand Down Expand Up @@ -238,26 +268,53 @@ def launch_eval_template(
payload: LaunchTemplateRequest,
idempotency_header: Annotated[str | None, Header(alias="Idempotency-Key")] = None,
session: Session = Depends(get_session),
context: identity.AuthContext = Depends(require_admin),
context: Actor = Depends(require_session_or_service("eval:launch")),
) -> dict:
key = (idempotency_header or payload.idempotency_key or "").strip()
if not key:
key = str(uuid.uuid4())
asset_override = (
payload.asset_override.model_dump(exclude_unset=True)
if payload.asset_override is not None
else None
)
lineage = (
payload.lineage.model_dump(exclude_unset=True)
if payload.lineage is not None
else None
)
try:
run, created = template_service.launch_template(
run, created, launch_meta = template_service.launch_template(
session,
template_id,
idempotency_key=key,
created_by=context.user.email,
created_by=context.label,
name=(payload.name or "").strip() or None,
asset_override=asset_override,
lineage=lineage,
service_token=context.service_token,
)
except template_service.TemplateError as error:
except (
template_service.TemplateError,
token_service.ServiceTokenError,
) as error:
raise _http_error(error) from error
return {
body = {
"run_id": run.id,
"template_id": template_id,
"status": run.status,
"status_url": f"/api/v1/eval-runs/{run.id}/status",
"result_url": f"/api/v1/eval-runs/{run.id}/results",
"created": created,
}
# Console compatibility: the one-click launch never received an override,
# so its 202 body stays byte-for-byte identical to the pre-#429 contract.
# An empty override object carries no intent and is normalized to absent by
# the service, so keying off the resolved identity (not the request field)
# also keeps a mismatched replay from emitting ``"asset": null``.
if launch_meta.get("asset") is not None:
body["asset"] = launch_meta["asset"]
warnings = launch_meta.get("warnings") or []
if warnings:
body["warnings"] = warnings
return body
Loading
Loading