diff --git a/configs/project-config.example.yaml b/configs/project-config.example.yaml index 57f8010a0..7e0de8cb5 100644 --- a/configs/project-config.example.yaml +++ b/configs/project-config.example.yaml @@ -4,6 +4,10 @@ allowed_profiles: [code, review] budget: max_turns: 20 max_tool_calls: 10 +browser_limits: + max_origins: 4 + max_requests: 200 + timeout_ms: 180000 exclude_paths: - fixtures - "secrets/**" diff --git a/configs/project-config.schema.json b/configs/project-config.schema.json index 609d12cd7..ba182877e 100644 --- a/configs/project-config.schema.json +++ b/configs/project-config.schema.json @@ -41,6 +41,45 @@ } } }, + "browser_limits": { + "type": "object", + "additionalProperties": false, + "description": "Operator-narrowed browser session budget. Zero or absent fields keep the builtin profile value; present values may only narrow it (a widening value fails when the browser session plan is built). At least one positive bound is required.", + "properties": { + "max_origins": { + "type": "integer", + "minimum": 0 + }, + "max_url_bytes": { + "type": "integer", + "minimum": 0 + }, + "max_requests": { + "type": "integer", + "minimum": 0 + }, + "max_response_bytes": { + "type": "integer", + "minimum": 0 + }, + "max_download_bytes": { + "type": "integer", + "minimum": 0 + }, + "timeout_ms": { + "type": "integer", + "minimum": 0 + } + }, + "anyOf": [ + { "required": ["max_origins"], "properties": { "max_origins": { "minimum": 1 } } }, + { "required": ["max_url_bytes"], "properties": { "max_url_bytes": { "minimum": 1 } } }, + { "required": ["max_requests"], "properties": { "max_requests": { "minimum": 1 } } }, + { "required": ["max_response_bytes"], "properties": { "max_response_bytes": { "minimum": 1 } } }, + { "required": ["max_download_bytes"], "properties": { "max_download_bytes": { "minimum": 1 } } }, + { "required": ["timeout_ms"], "properties": { "timeout_ms": { "minimum": 1 } } } + ] + }, "exclude_paths": { "description": "Pinned root-relative file-tool exclusions. Supports *, ?, character classes and whole ** segments; matching directories excludes descendants. Not an OS command sandbox.", "type": "array", diff --git a/docs/adr/0069-go-owned-browser-profiles-target-scope-and-session-plan.md b/docs/adr/0069-go-owned-browser-profiles-target-scope-and-session-plan.md index b8cb96c37..215339c0a 100644 --- a/docs/adr/0069-go-owned-browser-profiles-target-scope-and-session-plan.md +++ b/docs/adr/0069-go-owned-browser-profiles-target-scope-and-session-plan.md @@ -45,6 +45,16 @@ resolve an explicitly approved target to private space, but cloud metadata, link multicast, unspecified, and reserved address classes remain blocked. Literal-IP targets must resolve to the identical address. +Operator narrowing adds optional `max_origins` and `max_url_bytes` to the target scope. +Zero/absent fields retain the builtin ceiling and keep existing v1 JSON and fingerprints +unchanged. Positive bounds cannot exceed the builtin ceiling and enter the scope digest; +construction, validation, navigation, redirects, and intercepted requests enforce them. +The URL byte bound covers both the supplied URL and its canonical form. A session plan +requires its scope bounds to match its effective limits. Older readers discard the new +fields and reject narrowed scopes on fingerprint mismatch; new readers accept existing +default scopes. Previously built plans with narrowed origin/URL limits but no matching +scope bounds must be rebuilt. The builtin profile descriptor and fingerprint stay fixed. + `browser_session_plan.v1` binds Session, Run, Workspace, fixed profile fingerprint, target scope fingerprint, proxy endpoint, optional system credential reference, requested tooling, isolation, evidence class, limits, backend class, and sorted launch blockers. Proxy URL diff --git a/docs/reviews/browser-limits-config/README.md b/docs/reviews/browser-limits-config/README.md new file mode 100644 index 000000000..cc090b8a4 --- /dev/null +++ b/docs/reviews/browser-limits-config/README.md @@ -0,0 +1,71 @@ +# 浏览器会话预算的 .prayu 窄化:OCR delegate 复审 + +日期:2026-11-05。基线:`6a10b7c8`(origin/main,含 #519–#524 与其他会话对隔离区的改进)。 +评审对象:PR 分支 Qiyuanqiii/browser-limits-config(单提交,9 文件 / 331 行)。 +主题:#491 P2 的预算运维项(issue 问题 #7:"5 分钟 / 500 请求 / 8 origin 对'调一个 +bug'不够")。`.prayu/config.yaml` 新增 `browser_limits` 段——操作者对 builtin profile +预算(8 origins / 4096B URL / 500 req / 8 MiB 响应 / 16 MiB 下载 / 300000 ms)的窄化: +零值/缺省字段保留 profile 值、至少一个正整数、只窄不宽(widen 在 session plan 构建 +时以命名错误失败;恰等于 ceiling 合法为 no-op——与 budget.max_turns 的 strictly-lower +差异已注释锚定并有测试)。SessionPlan 新增 `limits_override`(进 plan 指纹),验证器 +从 override+profile 重算期望 limits,篡改变宽即使重签指纹仍被拒(不可超越 builtin +ceiling 的不变量无条件成立,信任模型已注释)。 + +OCR 负责文件选择(`ocr delegate preview --from origin/main --to HEAD`:7 个可审生产 +文件)与规则解析(Rule Group 1 system Go),主 agent 与独立评审子代理实际阅读判断。 + +## 覆盖范围 + +纳入审查 10 个(评审记录不计入): +- 生产代码(7 个,OCR 检出):`internal/browserruntime/plan.go`、 + `internal/projectconfig/projectconfig.go`、`internal/application/browser_runtime.go` + (browserLimitsOverrideForRun 解码 helper + safe-web 接线)、 + `internal/application/full_cdp_runtime_service.go` 与 `full_cdp_service.go` + (另两个调用方接线)、`configs/project-config.schema.json` + example.yaml。 +- 测试(2 个,人工补入):`internal/browserruntime/plan_test.go` + (窄化矩阵/篡改拒绝/ProfileToken 不变性/等值 no-op)、 + `internal/projectconfig/projectconfig_test.go`(TestBrowserLimitsValidateAndNarrowPassthrough)。 +- 工作树中其他会话遗留的 gofmt 残留(dependency_wait.go、child_task_*.go 等)不在 + 本提交内,不在评审范围。 + +具体明细见 [coverage.json](coverage.json)。 + +## 发现与修复(评审子代理报告,全部已修复并复测) + +| 发现 | 具体问题 | 最终处理 | +| --- | --- | --- | +| F1,P3 | schema 自相矛盾:description 写 "zero/absent fields keep the profile value" 但字段 `minimum: 1` 拒绝 0;且缺 `minProperties: 1`(空对象过 schema 但被 Go 拒)。 | schema 改 `minimum: 0` + `minProperties: 1`,description 补"至少一个正整数、widen 在 plan 构建时失败",与 Go 语义对齐。 | +| F2,P3 | override 恰等于 profile ceiling 被静默接受为 no-op(`> base` 才拒),与 budget.max_turns 的 strictly-lower(`>=` 拒)语义不同,且无注释锚定与边界测试。 | 注释写明"等于 ceiling 合法且为 no-op"及理由(浏览器 ceiling 即 profile 本身,等值既不宽也不窄);补等值通过用例。 | +| F3,P3 | 指纹为无密钥 sha256:同时篡改 override+limits 并重签指纹可使 Validate 通过(回到 builtin ceiling);"篡改 override 变宽→拒绝"仅在超 profile 时成立。 | LimitsOverride 注释写明信任模型(篡改上限=builtin ceiling,不变量无条件成立;plan 仅在构建时同步验证,无不可信存储回读路径)。 | +| F4,P3 | usage.md 的 .prayu 章节声称 "Any widening attempt aborts Run creation",但 browser_limits 的 widening 在 plan 构建时才失败;且 browser_limits 未见于该章节。 | 章节补 browser_limits 语义(零值=保留、只窄化、ceiling 检查发生在 plan 构建)并修正表述(browser_limits 的 widening 在 plan 构建时以命名错误失败)。 | + +评审确认(No blocking findings):ProfileLimits 6 字段全覆盖、builtin 三 profile 共享 +严格为正的 baseLimits(无 base=0 边界);LimitsOverride 经 `json.Marshal` 整 plan 自动 +入指纹;`Validate` 从 override+profile 重算 expectedLimits 并复验指纹/Token/isolation/ +scope/backend;ProfileToken 不含预算(token 标识一次性 profile 目录身份,预算不影响 +profile 内容,测试断言该不变性);执行侧消费窄化后的 session.Limits(cdp.go、 +full_cdp_transport.go),LimitsOverride 仅为验证溯源;三个调用方统一经 +browserLimitsOverrideForRun 解码(空/畸形/缺段 nil 回退 builtin ceiling 兜底); +projectconfig validate 镜像 budget 分支(负值/全零拒绝)、Narrow 透传、schema/example +一致;go test browserruntime+projectconfig 全过。 + +## 验证 + +- `gofmt -l` 无输出(改动包);`go vet` 三包无告警;`go build ./internal/...` 通过。 +- `go test ./internal/browserruntime/ ./internal/projectconfig/ -count=1` 全过(窄化矩阵、 + 篡改拒绝、等值 no-op、ProfileToken 不变性、projectconfig 解析校验)。 +- `go test -race ./internal/application/ -run "TestAgentBrowserUpload| + TestAgentBrowserDownload|TestBrowserHeaded|TestBrowserSessionLifetime"` 通过 + (相邻浏览器功能无回归)。 + +## 复审附记(2026-11-05,第二轮) + +独立复审发现 F2 的"最终处理"与代码不符:plan_test.go 此前只有"全零 override = no-op" +用例,恰等 profile ceiling 的通过分支没有任何测试锚定(上文覆盖范围里"等值 no-op"的 +表述实际指全零用例,不准确)。F2 所述的注释锚定确实存在,本轮已补上恰等 ceiling 的 +通过用例并断言其仍进入 plan 指纹。另按复审意见补两处: +`browserLimitsOverrideForRun` 对畸形 pinned 快照的静默回退改为 `slog.Warn` 留痕(快照 +在 Run 创建时已 validate + 指纹固定,触发即存储损坏,但操作者窄化意图被静默忽略应可 +观察);usage.md 补写作用面——browser_limits 只约束走 BuildSessionPlan 的会话面 +(Safe Web 与两个 Full CDP 产品),agent-managed browser 工具链不在该预算内。 +验证:`go test ./internal/browserruntime/ ./internal/projectconfig/ -count=1` 全过。 diff --git a/docs/reviews/browser-limits-config/coverage.json b/docs/reviews/browser-limits-config/coverage.json new file mode 100644 index 000000000..a100bad55 --- /dev/null +++ b/docs/reviews/browser-limits-config/coverage.json @@ -0,0 +1,35 @@ +{ + "schema_version": "1", + "mode": "ocr_delegate", + "base": "6a10b7c8", + "reviewed_head": "HEAD", + "review_metadata_excluded": [ + "docs/reviews/browser-limits-config/README.md", + "docs/reviews/browser-limits-config/coverage.json" + ], + "reviewers": [ + "主 agent:四层实现(plan 窄化+验证器、projectconfig、三调用方接线、schema/example)与测试", + "review_delegate:OCR delegate 规则检查(Rule Group 1 system Go)与独立全文复审,含指纹篡改信任模型与 schema/Go 语义一致性专项" + ], + "summary": { + "total_git_changed_files": 11, + "review_scope_files": 10, + "ocr_selected_production": 7, + "manually_added_tests": 2, + "review_metadata_excluded_count": 2, + "unread_in_scope": 0, + "coverage_rate": 1.0 + }, + "files": [ + { "path": "internal/browserruntime/plan.go", "coverage": "full", "reviewer": "primary_and_delegate" }, + { "path": "internal/projectconfig/projectconfig.go", "coverage": "full", "reviewer": "primary_and_delegate" }, + { "path": "internal/application/browser_runtime.go", "coverage": "full", "reviewer": "primary_and_delegate" }, + { "path": "internal/application/full_cdp_runtime_service.go", "coverage": "full", "reviewer": "primary_and_delegate" }, + { "path": "internal/application/full_cdp_service.go", "coverage": "full", "reviewer": "primary_and_delegate" }, + { "path": "configs/project-config.schema.json", "coverage": "full", "reviewer": "primary_and_delegate" }, + { "path": "configs/project-config.example.yaml", "coverage": "full", "reviewer": "primary_and_delegate" }, + { "path": "internal/browserruntime/plan_test.go", "coverage": "full", "reviewer": "primary_and_delegate" }, + { "path": "internal/projectconfig/projectconfig_test.go", "coverage": "full", "reviewer": "primary_and_delegate" }, + { "path": "docs/usage.md", "coverage": "full", "reviewer": "primary_and_delegate" } + ] +} diff --git a/docs/usage.md b/docs/usage.md index c5220f2c8..4e4bfdc97 100644 --- a/docs/usage.md +++ b/docs/usage.md @@ -1969,7 +1969,7 @@ cyberagent project-config validate cyberagent project-config show --profile code --max-turns 100 --max-tool-calls 100 ``` -The file uses `project_config.v1` (JSON schema in `configs/project-config.schema.json`, example in `configs/project-config.example.yaml`). It is untrusted input: it can only reduce the operator/process/policy limits, never widen them. `budget.max_turns`/`budget.max_tool_calls` must be strictly lower than the requested ceiling; `allowed_profiles` may only shrink the set; `read_only: true` forbids write-capable profiles (`code`/`script`); `exclude_paths` are workspace-relative paths without escapes; `skill_suggestions` use the signed Skill identity contract (`name@version`); `test_command_id`/`format_command_id` may only reference registered Tool Gateway typed action IDs — never Shell text. Unknown fields, duplicate keys, type errors, YAML aliases/anchors, files over 64 KiB, nesting deeper than 32, more than 4096 nodes, symlinks/junctions/reparse points, and oversized path lists all fail closed. Any widening attempt aborts Run creation with the offending field named. +The file uses `project_config.v1` (JSON schema in `configs/project-config.schema.json`, example in `configs/project-config.example.yaml`). It is untrusted input: it can only reduce the operator/process/policy limits, never widen them. `budget.max_turns`/`budget.max_tool_calls` must be strictly lower than the requested ceiling; `allowed_profiles` may only shrink the set; `read_only: true` forbids write-capable profiles (`code`/`script`); `exclude_paths` are workspace-relative paths without escapes; `skill_suggestions` use the signed Skill identity contract (`name@version`); `test_command_id`/`format_command_id` may only reference registered Tool Gateway typed action IDs — never Shell text. `browser_limits` narrows the browser session budget (`max_origins`, `max_url_bytes`, `max_requests`, `max_response_bytes`, `max_download_bytes`, `timeout_ms`): zero or absent fields keep the builtin profile value, at least one positive bound is required, and widening values fail when the browser session plan is built (values equal to the profile ceiling are accepted as no-ops). The budget applies to the session-plan surfaces (Safe Web and the Full CDP products); the agent-managed browser tools run under their own runtime budget and are not affected by `browser_limits`. Unknown fields, duplicate keys, type errors, YAML aliases/anchors, files over 64 KiB, nesting deeper than 32, more than 4096 nodes, symlinks/junctions/reparse points, and oversized path lists all fail closed. Any widening attempt aborts Run creation with the offending field named (browser_limits widening aborts when the browser session plan is built). At Run creation the normalized effective view and its SHA-256 fingerprint are pinned into the Run config snapshot; editing `.prayu/config.yaml` afterwards never changes a running Run. diff --git a/internal/application/browser_runtime.go b/internal/application/browser_runtime.go index 17ac380bc..72fd0a3d4 100644 --- a/internal/application/browser_runtime.go +++ b/internal/application/browser_runtime.go @@ -3,12 +3,15 @@ package application import ( "context" "errors" + "log/slog" "strings" "time" "cyberagent-workbench/internal/browserruntime" "cyberagent-workbench/internal/domain" "cyberagent-workbench/internal/idgen" + "cyberagent-workbench/internal/projectconfig" + "encoding/json" ) // BrowserRuntimeStore supplies the durable browser launch preparation, review, @@ -103,6 +106,37 @@ func (s *BrowserRuntimeService) LaunchUIEvidence(ctx context.Context, return s.launch(ctx, request, true) } +// browserLimitsOverrideForRun decodes the run's pinned project config and +// returns the operator-narrowed browser limits, if any. The stored snapshot is +// the marshaled projectconfig.Effective; a missing, malformed, or absent +// browser_limits section yields nil (keep the builtin profile limits). +func browserLimitsOverrideForRun(run domain.Run) *browserruntime.ProfileLimits { + if len(run.Config.ProjectConfig) == 0 { + return nil + } + var effective projectconfig.Effective + if json.Unmarshal(run.Config.ProjectConfig, &effective) != nil { + // The pinned snapshot was validated and fingerprint-bound at Run + // creation, so reaching this branch means stored state was corrupted. + // The builtin profile limits are the safe fallback, but the operator's + // narrowing intent silently disappearing deserves a record. + slog.Warn("browser limits override snapshot is malformed; using the builtin profile limits", "run_id", run.ID) + return nil + } + if effective.BrowserLimits == nil { + return nil + } + limits := effective.BrowserLimits + return &browserruntime.ProfileLimits{ + MaxOrigins: limits.MaxOrigins, + MaxURLBytes: limits.MaxURLBytes, + MaxRequests: limits.MaxRequests, + MaxResponseBytes: limits.MaxResponseBytes, + MaxDownloadBytes: limits.MaxDownloadBytes, + TimeoutMS: limits.TimeoutMS, + } +} + func (s *BrowserRuntimeService) launch(ctx context.Context, request BrowserRuntimeLaunchRequest, uiEvidence bool, ) (*BrowserRuntimeHandle, error) { @@ -148,6 +182,7 @@ func (s *BrowserRuntimeService) launch(ctx context.Context, session, err := browserruntime.BuildSessionPlan(browserruntime.NewSessionPlanRequest{ SessionID: run.SessionID, RunID: run.ID, WorkspaceID: mission.WorkspaceID, ProfileID: browserruntime.ProfileSafeWeb, Targets: []string{request.Target}, + LimitsOverride: browserLimitsOverrideForRun(run), }) if err != nil { return nil, err diff --git a/internal/application/full_cdp_runtime_service.go b/internal/application/full_cdp_runtime_service.go index 7425ca1d8..429480022 100644 --- a/internal/application/full_cdp_runtime_service.go +++ b/internal/application/full_cdp_runtime_service.go @@ -490,6 +490,7 @@ func (s *FullCDPProductionService) openReservedEntry(ctx context.Context, session, err := browserruntime.BuildSessionPlan(browserruntime.NewSessionPlanRequest{ SessionID: run.SessionID, RunID: run.ID, WorkspaceID: mission.WorkspaceID, ProfileID: browserruntime.ProfileCTFLab, Targets: []string{request.Target}, + LimitsOverride: browserLimitsOverrideForRun(run), Features: browserruntime.FeatureRequest{InterceptRequests: true, ModifyRequests: true, ReplayRequests: true, EditCookies: true}, }) diff --git a/internal/application/full_cdp_service.go b/internal/application/full_cdp_service.go index 0d9efb505..755b22cf1 100644 --- a/internal/application/full_cdp_service.go +++ b/internal/application/full_cdp_service.go @@ -149,6 +149,7 @@ func (s *FullCDPService) Open(ctx context.Context, session, err := browserruntime.BuildSessionPlan(browserruntime.NewSessionPlanRequest{ SessionID: run.SessionID, RunID: run.ID, WorkspaceID: mission.WorkspaceID, ProfileID: browserruntime.ProfileCTFLab, Targets: []string{request.Target}, + LimitsOverride: browserLimitsOverrideForRun(run), Features: browserruntime.FeatureRequest{ InterceptRequests: true, ModifyRequests: true, ReplayRequests: true, EditCookies: true, diff --git a/internal/browserruntime/plan.go b/internal/browserruntime/plan.go index c75e284bc..a48020fba 100644 --- a/internal/browserruntime/plan.go +++ b/internal/browserruntime/plan.go @@ -81,18 +81,27 @@ type SessionIsolation struct { } type SessionPlan struct { - ProtocolVersion string `json:"protocol_version"` - SessionID string `json:"session_id"` - RunID string `json:"run_id"` - WorkspaceID string `json:"workspace_id"` - ProfileID ProfileID `json:"profile_id"` - ProfileFingerprint string `json:"profile_fingerprint"` - ProfileToken string `json:"profile_token"` - Scope TargetScope `json:"scope"` - Proxy ProxyConfig `json:"proxy"` - Features PlannedFeatures `json:"features"` - Isolation SessionIsolation `json:"isolation"` - Limits ProfileLimits `json:"limits"` + ProtocolVersion string `json:"protocol_version"` + SessionID string `json:"session_id"` + RunID string `json:"run_id"` + WorkspaceID string `json:"workspace_id"` + ProfileID ProfileID `json:"profile_id"` + ProfileFingerprint string `json:"profile_fingerprint"` + ProfileToken string `json:"profile_token"` + Scope TargetScope `json:"scope"` + Proxy ProxyConfig `json:"proxy"` + Features PlannedFeatures `json:"features"` + Isolation SessionIsolation `json:"isolation"` + Limits ProfileLimits `json:"limits"` + // LimitsOverride is the operator-narrowed ceiling from the pinned project + // config, when one was supplied. It is part of the fingerprint; the + // verifier recomputes the narrowed limits from it and the profile. The + // fingerprint is an unkeyed digest, so a tamperer who rewrites both the + // override and the limits can re-sign them — but only back to the builtin + // profile ceiling: narrowing-only validation never accepts a wider value, + // and the plan is validated when it is built, not read back from + // untrusted storage. + LimitsOverride *ProfileLimits `json:"limits_override,omitempty"` EvidenceClass string `json:"evidence_class"` ApprovalRequired bool `json:"approval_required"` InstrumentedRiskAcknowledged bool `json:"instrumented_risk_acknowledged"` @@ -113,6 +122,7 @@ type NewSessionPlanRequest struct { ProxyCredentialRef string Features FeatureRequest InstrumentedRiskAcknowledged bool + LimitsOverride *ProfileLimits } func NewProxyConfig(rawURL string, credentialRef string) (ProxyConfig, error) { @@ -229,7 +239,14 @@ func BuildSessionPlan(request NewSessionPlanRequest) (SessionPlan, error) { if request.InstrumentedRiskAcknowledged != (request.ProfileID == ProfileCTFInstrumented) { return SessionPlan{}, errors.New("ctf-instrumented requires an explicit, profile-specific risk acknowledgement") } - scope, err := NewTargetScope(request.ProfileID, request.Targets) + limits := profile.Limits + if request.LimitsOverride != nil { + if err := validateLimitsOverride(profile.Limits, *request.LimitsOverride); err != nil { + return SessionPlan{}, err + } + limits = narrowProfileLimits(profile.Limits, *request.LimitsOverride) + } + scope, err := newTargetScope(profile, limits, request.Targets) if err != nil { return SessionPlan{}, err } @@ -256,8 +273,9 @@ func BuildSessionPlan(request NewSessionPlanRequest) (SessionPlan, error) { ProtocolVersion: SessionPlanProtocolVersion, SessionID: request.SessionID, RunID: request.RunID, WorkspaceID: request.WorkspaceID, ProfileID: profile.ID, ProfileFingerprint: profileFingerprint, Scope: scope, Proxy: proxy, Features: features, - Isolation: fixedSessionIsolation(), Limits: profile.Limits, - EvidenceClass: profile.EvidenceClass, ApprovalRequired: profile.ApprovalRequired, + Isolation: fixedSessionIsolation(), Limits: limits, + LimitsOverride: request.LimitsOverride, + EvidenceClass: profile.EvidenceClass, ApprovalRequired: profile.ApprovalRequired, InstrumentedRiskAcknowledged: request.InstrumentedRiskAcknowledged, RequiredBackend: requiredBackend, StartBlocked: true, BlockingGates: blockingGates(profile), @@ -309,7 +327,19 @@ func (plan SessionPlan) Validate() error { if profile.Isolation.ContainerRequired { expectedBackend = "containerized_browser_worker" } - if plan.Limits != profile.Limits || plan.EvidenceClass != profile.EvidenceClass || + expectedLimits := profile.Limits + if plan.LimitsOverride != nil { + if err := validateLimitsOverride(profile.Limits, *plan.LimitsOverride); err != nil { + return err + } + expectedLimits = narrowProfileLimits(profile.Limits, *plan.LimitsOverride) + } + scopeLimits, err := plan.Scope.effectiveLimits(profile) + if err != nil || scopeLimits.MaxOrigins != expectedLimits.MaxOrigins || + scopeLimits.MaxURLBytes != expectedLimits.MaxURLBytes { + return errors.New("browser session target scope limits do not match the session limits") + } + if plan.Limits != expectedLimits || plan.EvidenceClass != profile.EvidenceClass || plan.ApprovalRequired != profile.ApprovalRequired || plan.InstrumentedRiskAcknowledged != (plan.ProfileID == ProfileCTFInstrumented) || plan.RequiredBackend != expectedBackend { @@ -390,6 +420,62 @@ func blockingGates(profile ProfileDescriptor) []string { return gates } +// narrowProfileLimits applies operator narrowing to the builtin profile +// limits: every positive override field takes min(base, override); zero +// fields keep the profile value. Narrowing-only is enforced by +// validateLimitsOverride before this runs. +func narrowProfileLimits(base, override ProfileLimits) ProfileLimits { + narrowed := base + if override.MaxOrigins > 0 && override.MaxOrigins < narrowed.MaxOrigins { + narrowed.MaxOrigins = override.MaxOrigins + } + if override.MaxURLBytes > 0 && override.MaxURLBytes < narrowed.MaxURLBytes { + narrowed.MaxURLBytes = override.MaxURLBytes + } + if override.MaxRequests > 0 && override.MaxRequests < narrowed.MaxRequests { + narrowed.MaxRequests = override.MaxRequests + } + if override.MaxResponseBytes > 0 && override.MaxResponseBytes < narrowed.MaxResponseBytes { + narrowed.MaxResponseBytes = override.MaxResponseBytes + } + if override.MaxDownloadBytes > 0 && override.MaxDownloadBytes < narrowed.MaxDownloadBytes { + narrowed.MaxDownloadBytes = override.MaxDownloadBytes + } + if override.TimeoutMS > 0 && override.TimeoutMS < narrowed.TimeoutMS { + narrowed.TimeoutMS = override.TimeoutMS + } + return narrowed +} + +// validateLimitsOverride rejects negative fields and any field that would +// widen the builtin profile ceiling; zero fields mean "keep the profile +// value". A value exactly equal to the ceiling is accepted as a no-op — +// unlike budget.max_turns, which requires a strictly lower bound — because +// the browser ceiling is the profile itself and equal budgets neither widen +// nor narrow anything. +func validateLimitsOverride(base, override ProfileLimits) error { + fields := []struct { + name string + override, base int + }{ + {"max_origins", override.MaxOrigins, base.MaxOrigins}, + {"max_url_bytes", override.MaxURLBytes, base.MaxURLBytes}, + {"max_requests", override.MaxRequests, base.MaxRequests}, + {"max_response_bytes", override.MaxResponseBytes, base.MaxResponseBytes}, + {"max_download_bytes", override.MaxDownloadBytes, base.MaxDownloadBytes}, + {"timeout_ms", override.TimeoutMS, base.TimeoutMS}, + } + for _, field := range fields { + if field.override < 0 { + return fmt.Errorf("browser limits override %s cannot be negative", field.name) + } + if field.override > field.base { + return fmt.Errorf("browser limits override %s must narrow the profile ceiling (%d)", field.name, field.base) + } + } + return nil +} + func profileToken(plan SessionPlan) string { digest := sha256.Sum256([]byte(strings.Join([]string{ "browser-profile-token.v1", plan.SessionID, plan.RunID, plan.WorkspaceID, diff --git a/internal/browserruntime/plan_test.go b/internal/browserruntime/plan_test.go index 0e52f2663..103523b0b 100644 --- a/internal/browserruntime/plan_test.go +++ b/internal/browserruntime/plan_test.go @@ -1,6 +1,9 @@ package browserruntime -import "testing" +import ( + "strings" + "testing" +) func TestSafeWebSessionPlanIsIsolatedAndNonAuthorizing(t *testing.T) { plan, err := BuildSessionPlan(NewSessionPlanRequest{ @@ -174,3 +177,125 @@ func FuzzProxyConfiguration(f *testing.F) { } }) } + +func TestSessionPlanLimitsOverrideNarrowsAndEntersFingerprint(t *testing.T) { + base, err := BuildSessionPlan(NewSessionPlanRequest{ + SessionID: "browser-session-one", RunID: "run-one", WorkspaceID: "ws-demo", + ProfileID: ProfileSafeWeb, Targets: []string{"https://example.com"}, + }) + if err != nil { + t.Fatal(err) + } + narrowed, err := BuildSessionPlan(NewSessionPlanRequest{ + SessionID: "browser-session-one", RunID: "run-one", WorkspaceID: "ws-demo", + ProfileID: ProfileSafeWeb, Targets: []string{"https://example.com"}, + LimitsOverride: &ProfileLimits{MaxRequests: 200, TimeoutMS: 180000}, + }) + if err != nil { + t.Fatal(err) + } + if err := narrowed.Validate(); err != nil { + t.Fatal(err) + } + if narrowed.Limits.MaxRequests != 200 || narrowed.Limits.TimeoutMS != 180000 { + t.Fatalf("narrowed fields not applied: %+v", narrowed.Limits) + } + if narrowed.Limits.MaxOrigins != base.Limits.MaxOrigins || + narrowed.Limits.MaxResponseBytes != base.Limits.MaxResponseBytes || + narrowed.Limits.MaxDownloadBytes != base.Limits.MaxDownloadBytes || + narrowed.Limits.MaxURLBytes != base.Limits.MaxURLBytes { + t.Fatalf("unset override fields must keep profile values: %+v", narrowed.Limits) + } + // The fingerprint covers the whole plan (limits and override). Request + // count and timeout overrides preserve the scope and profile token. + if narrowed.Fingerprint == base.Fingerprint { + t.Fatal("override must change the plan fingerprint") + } + if narrowed.ProfileToken != base.ProfileToken { + t.Fatal("profile token must not depend on the budget override") + } + if narrowed.LimitsOverride == nil || narrowed.LimitsOverride.MaxRequests != 200 { + t.Fatalf("override not carried on the plan: %+v", narrowed.LimitsOverride) + } + + // Zero-field overrides keep every profile value. + noOp, err := BuildSessionPlan(NewSessionPlanRequest{ + SessionID: "browser-session-one", RunID: "run-one", WorkspaceID: "ws-demo", + ProfileID: ProfileSafeWeb, Targets: []string{"https://example.com"}, + LimitsOverride: &ProfileLimits{}, + }) + if err != nil || noOp.Limits != base.Limits { + t.Fatalf("zero-field override: %v %+v", err, noOp.Limits) + } + + // An override exactly equal to the profile ceiling is a legal no-op: unlike + // budget.max_turns, the browser ceiling IS the profile itself, so equality + // neither widens nor narrows. + equal, err := BuildSessionPlan(NewSessionPlanRequest{ + SessionID: "browser-session-one", RunID: "run-one", WorkspaceID: "ws-demo", + ProfileID: ProfileSafeWeb, Targets: []string{"https://example.com"}, + LimitsOverride: &ProfileLimits{MaxRequests: base.Limits.MaxRequests, TimeoutMS: base.Limits.TimeoutMS}, + }) + if err != nil || equal.Limits != base.Limits || equal.LimitsOverride == nil || + equal.LimitsOverride.MaxRequests != base.Limits.MaxRequests { + t.Fatalf("ceiling-equal override: %v %+v", err, equal.Limits) + } + if equal.Fingerprint == base.Fingerprint { + t.Fatal("ceiling-equal override must still enter the fingerprint") + } +} + +func TestSessionPlanLimitsOverrideRejectsWideningAndNegative(t *testing.T) { + base := BuiltinRegistry() + profile, ok := base.Lookup(ProfileSafeWeb) + if !ok { + t.Fatal("safe-web profile missing") + } + cases := []struct { + name string + version ProfileLimits + wantErr string + }{ + {"widen requests", ProfileLimits{MaxRequests: profile.Limits.MaxRequests + 1}, "must narrow the profile ceiling"}, + {"widen timeout", ProfileLimits{TimeoutMS: profile.Limits.TimeoutMS + 1}, "must narrow the profile ceiling"}, + {"negative origins", ProfileLimits{MaxOrigins: -1}, "cannot be negative"}, + } + for _, testCase := range cases { + _, err := BuildSessionPlan(NewSessionPlanRequest{ + SessionID: "browser-session-one", RunID: "run-one", WorkspaceID: "ws-demo", + ProfileID: ProfileSafeWeb, Targets: []string{"https://example.com"}, + LimitsOverride: &testCase.version, + }) + if err == nil || !strings.Contains(err.Error(), testCase.wantErr) { + t.Fatalf("%s: err=%v want %q", testCase.name, err, testCase.wantErr) + } + } +} + +func TestSessionPlanLimitsOverrideTamperFailsClosed(t *testing.T) { + narrowed, err := BuildSessionPlan(NewSessionPlanRequest{ + SessionID: "browser-session-one", RunID: "run-one", WorkspaceID: "ws-demo", + ProfileID: ProfileSafeWeb, Targets: []string{"https://example.com"}, + LimitsOverride: &ProfileLimits{MaxRequests: 200}, + }) + if err != nil { + t.Fatal(err) + } + profile, ok := BuiltinRegistry().Lookup(ProfileSafeWeb) + if !ok { + t.Fatal("safe-web profile missing") + } + // A tamperer widens the limits back to the profile values and re-signs the + // fingerprint; the verifier must still catch the mismatch against the + // narrowing the override authorizes. + tampered := narrowed + tampered.Limits = profile.Limits + tampered.Fingerprint, err = sessionPlanFingerprint(tampered) + if err != nil { + t.Fatal(err) + } + if err := tampered.Validate(); err == nil || + !strings.Contains(err.Error(), "browser session controls do not match") { + t.Fatalf("widened tamper accepted: %v", err) + } +} diff --git a/internal/browserruntime/scope.go b/internal/browserruntime/scope.go index 3f426aaf5..8dac845bf 100644 --- a/internal/browserruntime/scope.go +++ b/internal/browserruntime/scope.go @@ -56,6 +56,10 @@ type TargetScope struct { ResolvedAddressRevalidation bool `json:"resolved_address_revalidation"` Authority ScopeAuthority `json:"authority"` Fingerprint string `json:"fingerprint"` + // Zero keeps the builtin ceiling. Omission preserves existing v1 scope + // fingerprints; narrowed bounds travel with the scope to CDP request checks. + MaxOrigins int `json:"max_origins,omitempty"` + MaxURLBytes int `json:"max_url_bytes,omitempty"` } type NavigationDecision struct { @@ -77,14 +81,18 @@ func NewTargetScope(profileID ProfileID, rawTargets []string) (TargetScope, erro if !ok { return TargetScope{}, fmt.Errorf("unsupported browser profile %q", profileID) } - if len(rawTargets) == 0 || len(rawTargets) > profile.Limits.MaxOrigins { + return newTargetScope(profile, profile.Limits, rawTargets) +} + +func newTargetScope(profile ProfileDescriptor, limits ProfileLimits, rawTargets []string) (TargetScope, error) { + if len(rawTargets) == 0 || len(rawTargets) > limits.MaxOrigins { return TargetScope{}, fmt.Errorf("browser target scope requires between 1 and %d targets", - profile.Limits.MaxOrigins) + limits.MaxOrigins) } unique := make(map[string]Origin, len(rawTargets)) for _, rawTarget := range rawTargets { - origin, _, err := parseTarget(profile, rawTarget) + origin, _, err := parseTarget(profile, limits, rawTarget) if err != nil { return TargetScope{}, err } @@ -101,10 +109,16 @@ func NewTargetScope(profileID ProfileID, rawTargets []string) (TargetScope, erro return TargetScope{}, err } scope := TargetScope{ - ProtocolVersion: TargetScopeProtocolVersion, ProfileID: profileID, + ProtocolVersion: TargetScopeProtocolVersion, ProfileID: profile.ID, ProfileFingerprint: profileFingerprint, Origins: origins, DefaultDeny: true, RedirectRevalidation: true, ResolvedAddressRevalidation: true, } + if limits.MaxOrigins != profile.Limits.MaxOrigins { + scope.MaxOrigins = limits.MaxOrigins + } + if limits.MaxURLBytes != profile.Limits.MaxURLBytes { + scope.MaxURLBytes = limits.MaxURLBytes + } scope.Fingerprint, err = targetScopeFingerprint(scope) if err != nil { return TargetScope{}, err @@ -127,7 +141,11 @@ func (scope TargetScope) Validate() error { if err != nil || scope.ProfileFingerprint != profileFingerprint { return errors.New("browser target scope profile fingerprint mismatch") } - if len(scope.Origins) == 0 || len(scope.Origins) > profile.Limits.MaxOrigins { + limits, err := scope.effectiveLimits(profile) + if err != nil { + return err + } + if len(scope.Origins) == 0 || len(scope.Origins) > limits.MaxOrigins { return errors.New("browser target scope origin count is out of bounds") } if !scope.DefaultDeny || !scope.RedirectRevalidation || !scope.ResolvedAddressRevalidation { @@ -138,7 +156,7 @@ func (scope TargetScope) Validate() error { } last := "" for _, origin := range scope.Origins { - rebuilt, _, parseErr := parseTarget(profile, origin.String()) + rebuilt, _, parseErr := parseTarget(profile, limits, origin.String()) if parseErr != nil || rebuilt != origin { return errors.New("browser target scope contains a non-canonical origin") } @@ -155,12 +173,21 @@ func (scope TargetScope) Validate() error { return nil } +func (scope TargetScope) effectiveLimits(profile ProfileDescriptor) (ProfileLimits, error) { + override := ProfileLimits{MaxOrigins: scope.MaxOrigins, MaxURLBytes: scope.MaxURLBytes} + if err := validateLimitsOverride(profile.Limits, override); err != nil { + return ProfileLimits{}, err + } + return narrowProfileLimits(profile.Limits, override), nil +} + func (scope TargetScope) AuthorizeNavigation(rawURL string) NavigationDecision { if err := scope.Validate(); err != nil { return NavigationDecision{Code: "invalid_scope"} } profile, _ := BuiltinRegistry().Lookup(scope.ProfileID) - origin, canonicalURL, err := parseTarget(profile, rawURL) + limits, _ := scope.effectiveLimits(profile) // Validate checked the narrowed bounds. + origin, canonicalURL, err := parseTarget(profile, limits, rawURL) if err != nil { return NavigationDecision{Code: "invalid_or_forbidden_url"} } @@ -224,9 +251,9 @@ func (scope TargetScope) AuthorizeResolvedAddress(origin Origin, rawAddress stri return AddressDecision{Code: "resolved_address_out_of_scope", Class: class} } -func parseTarget(profile ProfileDescriptor, rawTarget string) (Origin, string, error) { +func parseTarget(profile ProfileDescriptor, limits ProfileLimits, rawTarget string) (Origin, string, error) { rawTarget = strings.TrimSpace(rawTarget) - if rawTarget == "" || len([]byte(rawTarget)) > profile.Limits.MaxURLBytes || + if rawTarget == "" || len(rawTarget) > limits.MaxURLBytes || !utf8.ValidString(rawTarget) || containsControl(rawTarget) || strings.Contains(rawTarget, "\\") { return Origin{}, "", errors.New("browser target URL is empty, oversized, or malformed") } @@ -266,7 +293,11 @@ func parseTarget(profile ProfileDescriptor, rawTarget string) (Origin, string, e parsed.Scheme = scheme parsed.Host = net.JoinHostPort(host, strconv.Itoa(int(port))) parsed.User = nil - return origin, parsed.String(), nil + canonicalURL := parsed.String() + if len(canonicalURL) > limits.MaxURLBytes { + return Origin{}, "", errors.New("canonical browser target URL exceeds its byte limit") + } + return origin, canonicalURL, nil } func normalizeHost(rawHost string) (string, error) { diff --git a/internal/browserruntime/scope_limits_test.go b/internal/browserruntime/scope_limits_test.go new file mode 100644 index 000000000..734f72409 --- /dev/null +++ b/internal/browserruntime/scope_limits_test.go @@ -0,0 +1,293 @@ +package browserruntime + +import ( + "context" + "encoding/json" + "strings" + "testing" + "time" + + "github.com/gorilla/websocket" +) + +func scopeLimitsPlanRequest() NewSessionPlanRequest { + return NewSessionPlanRequest{ + SessionID: "scope-limits-session", RunID: "scope-limits-run", WorkspaceID: "scope-limits-workspace", + ProfileID: ProfileSafeWeb, Targets: []string{"https://example.com"}, + } +} + +func TestSessionPlanEnforcesNarrowedScopeBounds(t *testing.T) { + t.Run("initial URL", func(t *testing.T) { + request := scopeLimitsPlanRequest() + request.Targets = []string{"https://example.com/" + strings.Repeat("a", 100)} + request.LimitsOverride = &ProfileLimits{MaxURLBytes: 32} + if _, err := BuildSessionPlan(request); err == nil { + t.Fatal("accepted oversized initial target") + } + }) + t.Run("origin count", func(t *testing.T) { + request := scopeLimitsPlanRequest() + request.Targets = append(request.Targets, "https://example.org") + request.LimitsOverride = &ProfileLimits{MaxOrigins: 1} + if _, err := BuildSessionPlan(request); err == nil { + t.Fatal("accepted more than one origin") + } + }) + t.Run("later navigation", func(t *testing.T) { + request := scopeLimitsPlanRequest() + request.LimitsOverride = &ProfileLimits{MaxURLBytes: 32} + plan, err := BuildSessionPlan(request) + if err != nil { + t.Fatal(err) + } + if decision := plan.Scope.AuthorizeNavigation("https://example.com/" + strings.Repeat("a", 100)); decision.Allowed { + t.Fatal("accepted oversized later navigation") + } + }) +} + +func TestDefaultScopePlanLegacyFingerprints(t *testing.T) { + plan, err := BuildSessionPlan(scopeLimitsPlanRequest()) + if err != nil { + t.Fatal(err) + } + // Captured at c2c21a97 before adding optional scope bounds. + if plan.ProfileFingerprint != "d09849dad3b43c055d8c51cd49e46b350c5d7c1ce9af9a70e99ca17844353bc6" || + plan.Scope.Fingerprint != "406dd13d45451e6a56ba9d121afbcb0df30592ef0581fe97c1d75aa227f37e9e" || + plan.ProfileToken != "c95397c6915a624ce7c23830be49ed0bddc031a04aa4cc52d7e3f21420d9c2d3" || + plan.Fingerprint != "6ab3075e8f0df83bf33a06c57c00b445a3407100a06b0beb5f0305a07b0c3b8b" { + t.Fatalf("legacy default plan fingerprints changed: %+v", plan) + } + raw, err := json.Marshal(plan) + if err != nil { + t.Fatal(err) + } + var restored SessionPlan + if err := json.Unmarshal(raw, &restored); err != nil { + t.Fatal(err) + } + if err := restored.Validate(); err != nil { + t.Fatal(err) + } +} + +func TestNarrowedScopeRoundTripAndURLBoundary(t *testing.T) { + request := scopeLimitsPlanRequest() + request.LimitsOverride = &ProfileLimits{MaxOrigins: 1, MaxURLBytes: 32} + plan, err := BuildSessionPlan(request) + if err != nil { + t.Fatal(err) + } + raw, err := json.Marshal(plan) + if err != nil { + t.Fatal(err) + } + var restored SessionPlan + if err := json.Unmarshal(raw, &restored); err != nil { + t.Fatal(err) + } + if err := restored.Validate(); err != nil { + t.Fatal(err) + } + baseURL := "https://example.com:443/" + boundary := baseURL + strings.Repeat("a", 32-len(baseURL)) + for _, tc := range []struct { + name, url string + allowed bool + }{ + {"at byte limit", boundary, true}, + {"above byte limit", boundary + "a", false}, + {"port normalization exceeds limit", "https://example.com/" + strings.Repeat("a", 32-len("https://example.com/")), false}, + {"UTF-8 escaping exceeds limit", "https://example.com/éé", false}, + } { + t.Run(tc.name, func(t *testing.T) { + decision := restored.Scope.AuthorizeNavigation(tc.url) + if decision.Allowed != tc.allowed { + t.Fatalf("navigation decision=%+v, want allowed=%t", decision, tc.allowed) + } + request.Targets = []string{tc.url} + if _, err := BuildSessionPlan(request); (err == nil) != tc.allowed { + t.Fatalf("initial target err=%v, want allowed=%t", err, tc.allowed) + } + }) + } + if restored.ProfileFingerprint != plan.ProfileFingerprint || restored.Scope.MaxOrigins != 1 || + restored.Scope.MaxURLBytes != 32 || restored.Scope.Authority != (ScopeAuthority{}) { + t.Fatalf("scope bounds or authority changed during round trip: %+v", restored.Scope) + } +} + +func TestNarrowedScopeValidationAndPlanBinding(t *testing.T) { + request := scopeLimitsPlanRequest() + request.LimitsOverride = &ProfileLimits{MaxOrigins: 1, MaxURLBytes: 32} + plan, err := BuildSessionPlan(request) + if err != nil { + t.Fatal(err) + } + profile, _ := BuiltinRegistry().Lookup(plan.ProfileID) + for _, tc := range []struct { + name string + mutate func(*TargetScope) + }{ + {"negative origins", func(scope *TargetScope) { scope.MaxOrigins = -1 }}, + {"negative URL bytes", func(scope *TargetScope) { scope.MaxURLBytes = -1 }}, + {"widen builtin origins", func(scope *TargetScope) { scope.MaxOrigins = profile.Limits.MaxOrigins + 1 }}, + {"widen builtin URL bytes", func(scope *TargetScope) { scope.MaxURLBytes = profile.Limits.MaxURLBytes + 1 }}, + {"too many origins", func(scope *TargetScope) { + second := scope.Origins[0] + second.Host = "example.org" + scope.Origins = append(scope.Origins, second) + }}, + {"oversized stored origin", func(scope *TargetScope) { scope.MaxURLBytes = len(scope.Origins[0].String()) - 1 }}, + } { + t.Run(tc.name, func(t *testing.T) { + scope := plan.Scope + scope.Origins = append([]Origin(nil), scope.Origins...) + tc.mutate(&scope) + scope.Fingerprint, err = targetScopeFingerprint(scope) + if err != nil { + t.Fatal(err) + } + if err := scope.Validate(); err == nil { + t.Fatal("re-signed invalid scope was accepted") + } + if scope.AuthorizeNavigation(request.Targets[0]).Allowed || + scope.AuthorizeResolvedAddress(scope.Origins[0], "93.184.216.34").Allowed { + t.Fatal("invalid scope authorized navigation or a resolved address") + } + }) + } + for _, tc := range []struct { + name string + mutate func(*TargetScope) + }{ + {"remove narrowed origins", func(scope *TargetScope) { scope.MaxOrigins = 0 }}, + {"remove narrowed URL bytes", func(scope *TargetScope) { scope.MaxURLBytes = 0 }}, + {"change narrowed URL bytes", func(scope *TargetScope) { scope.MaxURLBytes++ }}, + } { + t.Run(tc.name, func(t *testing.T) { + candidate := plan + tc.mutate(&candidate.Scope) + candidate.Scope.Fingerprint, err = targetScopeFingerprint(candidate.Scope) + if err != nil { + t.Fatal(err) + } + if err := candidate.Scope.Validate(); err != nil { + t.Fatalf("expected independently valid scope: %v", err) + } + candidate.ProfileToken = profileToken(candidate) + candidate.Fingerprint, err = sessionPlanFingerprint(candidate) + if err != nil { + t.Fatal(err) + } + if err := candidate.Validate(); err == nil || !strings.Contains(err.Error(), "scope limits") { + t.Fatalf("plan accepted mismatched scope limits after re-signing: %v", err) + } + }) + } +} + +func TestLegacyScopeReaderRejectsNarrowedPayload(t *testing.T) { + request := scopeLimitsPlanRequest() + request.LimitsOverride = &ProfileLimits{MaxOrigins: 1, MaxURLBytes: 32} + plan, err := BuildSessionPlan(request) + if err != nil { + t.Fatal(err) + } + raw, err := json.Marshal(plan.Scope) + if err != nil { + t.Fatal(err) + } + // A pre-bound reader discards unknown JSON fields before recomputing its + // fingerprint. Emulate that projection with both optional fields removed. + var legacyFields map[string]json.RawMessage + if err := json.Unmarshal(raw, &legacyFields); err != nil { + t.Fatal(err) + } + delete(legacyFields, "max_origins") + delete(legacyFields, "max_url_bytes") + raw, err = json.Marshal(legacyFields) + if err != nil { + t.Fatal(err) + } + var legacyScope TargetScope + if err := json.Unmarshal(raw, &legacyScope); err != nil { + t.Fatal(err) + } + if err := legacyScope.Validate(); err == nil || !strings.Contains(err.Error(), "fingerprint mismatch") { + t.Fatalf("legacy scope reader did not fail closed: %v", err) + } +} + +func TestCDPRequestEnforcesNarrowedURLBytes(t *testing.T) { + _, executable, _, runtimeRoot := profileLifecycleFixture(t) + input := scopeLimitsPlanRequest() + input.LimitsOverride = &ProfileLimits{MaxURLBytes: 32} + session, err := BuildSessionPlan(input) + if err != nil { + t.Fatal(err) + } + ownership, err := BuildProfileOwnershipPlan(session, executable, runtimeRoot) + if err != nil { + t.Fatal(err) + } + url := "https://example.com:443/" + strings.Repeat("a", 32-len("https://example.com:443/")) + request, err := BuildCDPRequest(session, executable, ownership, "at-limit", CDPActionNavigate, url) + if err != nil { + t.Fatal(err) + } + if _, err := BuildCDPRequest(session, executable, ownership, "over-limit", CDPActionNavigate, url+"a"); err == nil { + t.Fatal("CDP request builder accepted oversized URL") + } + request.CanonicalURL += "a" + request.Fingerprint, err = cdpRequestFingerprint(request) + if err != nil { + t.Fatal(err) + } + if err := ValidateCDPRequest(request, session, executable, ownership); err == nil { + t.Fatal("CDP request validator accepted re-signed oversized URL") + } +} + +func TestCDPInterceptedRequestsEnforceNarrowedURLBytes(t *testing.T) { + input := scopeLimitsPlanRequest() + input.LimitsOverride = &ProfileLimits{MaxURLBytes: 32} + session, err := BuildSessionPlan(input) + if err != nil { + t.Fatal(err) + } + server := newScriptedCDPServer(t, input.Targets[0]) + defer server.Close(t) + ctx, cancel := context.WithTimeout(t.Context(), 5*time.Second) + defer cancel() + connection, _, err := websocket.DefaultDialer.DialContext(ctx, "ws://"+server.listener.Addr().String()+server.path, nil) + if err != nil { + t.Fatal(err) + } + defer connection.Close() + client := restrictedCDPClient{conn: connection, sessionID: "session-test", scope: session.Scope, + maxRequests: session.Limits.MaxRequests} + for _, url := range []string{"https://example.com:443/a", "https://example.com:443/" + strings.Repeat("a", 100)} { + params, err := json.Marshal(map[string]any{ + "requestId": "request-test", "resourceType": "Script", + "request": map[string]any{"url": url, "method": "GET"}, + }) + if err != nil { + t.Fatal(err) + } + if err := client.handleEvent(ctx, cdpWireMessage{ + SessionID: client.sessionID, Method: "Fetch.requestPaused", Params: params, + }); err != nil { + t.Fatal(err) + } + if _, err := client.readMessage(ctx); err != nil { + t.Fatal(err) + } + } + methods := server.Methods() + if len(methods) != 2 || methods[0] != "Fetch.continueRequest" || methods[1] != "Fetch.failRequest" || + client.allowedRequests != 1 || client.blockedRequests != 1 { + t.Fatalf("intercepted URL bounds not enforced: methods=%v allowed=%d blocked=%d", methods, client.allowedRequests, client.blockedRequests) + } +} diff --git a/internal/projectconfig/browser_limits_schema_test.go b/internal/projectconfig/browser_limits_schema_test.go new file mode 100644 index 000000000..dc8024e0a --- /dev/null +++ b/internal/projectconfig/browser_limits_schema_test.go @@ -0,0 +1,62 @@ +package projectconfig + +import ( + "bytes" + "encoding/json" + "os" + "path/filepath" + "testing" + + "github.com/santhosh-tekuri/jsonschema/v5" +) + +func TestBrowserLimitsSchemaMatchesConfigValidation(t *testing.T) { + raw, err := os.ReadFile(filepath.Join("..", "..", "configs", "project-config.schema.json")) + if err != nil { + t.Fatal(err) + } + compiler := jsonschema.NewCompiler() + if err := compiler.AddResource("project-config.json", bytes.NewReader(raw)); err != nil { + t.Fatal(err) + } + schema, err := compiler.Compile("project-config.json") + if err != nil { + t.Fatal(err) + } + type testCase struct { + name, limits string + valid bool + } + tests := []testCase{ + {"absent", "", true}, + {"empty", `{}`, false}, + {"all zero", `{"max_origins":0,"max_url_bytes":0,"max_requests":0,"max_response_bytes":0,"max_download_bytes":0,"timeout_ms":0}`, false}, + {"zero and positive", `{"max_origins":0,"max_requests":1}`, true}, + {"negative and positive", `{"max_origins":-1,"max_requests":1}`, false}, + } + for _, field := range []string{"max_origins", "max_url_bytes", "max_requests", "max_response_bytes", "max_download_bytes", "timeout_ms"} { + tests = append(tests, + testCase{field + " zero", `{"` + field + `":0}`, false}, + testCase{field + " positive", `{"` + field + `":1}`, true}) + } + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + content := `{"protocol":"project_config.v1"` + if tc.limits != "" { + content += `,"browser_limits":` + tc.limits + } + content += `}` + var value any + if err := json.Unmarshal([]byte(content), &value); err != nil { + t.Fatal(err) + } + if err := schema.Validate(value); (err == nil) != tc.valid { + t.Fatalf("schema validation err=%v, want valid=%t", err, tc.valid) + } + path := writeConfig(t, t.TempDir(), content) + if _, err := Load(t.Context(), path); (err == nil) != tc.valid { + t.Fatalf("Go config validation err=%v, want valid=%t", err, tc.valid) + } + }) + } +} diff --git a/internal/projectconfig/projectconfig.go b/internal/projectconfig/projectconfig.go index 158a48629..4c4ffe70a 100644 --- a/internal/projectconfig/projectconfig.go +++ b/internal/projectconfig/projectconfig.go @@ -45,6 +45,22 @@ type Config struct { TestCommandID string `yaml:"test_command_id,omitempty"` FormatCommandID string `yaml:"format_command_id,omitempty"` Hooks *CommandHooks `yaml:"hooks,omitempty"` + + BrowserLimits *BrowserLimitsConfig `yaml:"browser_limits,omitempty"` +} + +// BrowserLimitsConfig is the operator-narrowed browser session budget. Every +// field is optional; zero keeps the builtin profile value. The narrowing +// against the profile ceiling happens when the session plan is built, so a +// value that would widen the profile is a silent no-op here and a named +// error at plan construction. +type BrowserLimitsConfig struct { + MaxOrigins int `yaml:"max_origins,omitempty"` + MaxURLBytes int `yaml:"max_url_bytes,omitempty"` + MaxRequests int `yaml:"max_requests,omitempty"` + MaxResponseBytes int `yaml:"max_response_bytes,omitempty"` + MaxDownloadBytes int `yaml:"max_download_bytes,omitempty"` + TimeoutMS int `yaml:"timeout_ms,omitempty"` } type Budget struct { @@ -64,6 +80,8 @@ type Effective struct { TestCommandID string `json:"test_command_id,omitempty"` FormatCommandID string `json:"format_command_id,omitempty"` Hooks *CommandHooks `json:"hooks,omitempty"` + + BrowserLimits *BrowserLimitsConfig `json:"browser_limits,omitempty"` } // Rejection names one fail-closed field with its reason. @@ -233,6 +251,23 @@ func (c Config) validate() error { return errors.New("project budget must narrow at least one positive bound") } } + if c.BrowserLimits != nil { + fields := []int{c.BrowserLimits.MaxOrigins, c.BrowserLimits.MaxURLBytes, + c.BrowserLimits.MaxRequests, c.BrowserLimits.MaxResponseBytes, + c.BrowserLimits.MaxDownloadBytes, c.BrowserLimits.TimeoutMS} + narrowed := 0 + for _, value := range fields { + if value < 0 { + return errors.New("project browser_limits values cannot be negative") + } + if value > 0 { + narrowed++ + } + } + if narrowed == 0 { + return errors.New("project browser_limits must narrow at least one positive bound") + } + } if len(c.ExcludePaths) > MaxExcludePaths { return fmt.Errorf("exclude_paths exceeds %d entries", MaxExcludePaths) } @@ -322,6 +357,11 @@ func (c Config) Narrow(ceiling Ceiling) (Effective, []Rejection, error) { effective.AllowedProfiles = append([]string{}, c.AllowedProfiles...) } } + // Browser limits are operator ceilings over the builtin profile; the + // profile-level narrowing (and any widening attempt) is enforced when the + // session plan is built, where the builtin profile is looked up. + effective.BrowserLimits = c.BrowserLimits + // Budget bounds may only decrease. effective.MaxTurns = ceiling.MaxTurns effective.MaxToolCalls = ceiling.MaxToolCalls diff --git a/internal/projectconfig/projectconfig_test.go b/internal/projectconfig/projectconfig_test.go index fe7d26e0c..fb0fc2168 100644 --- a/internal/projectconfig/projectconfig_test.go +++ b/internal/projectconfig/projectconfig_test.go @@ -190,3 +190,33 @@ func TestProjectConfigRejectsAnchorAndParentIndirection(t *testing.T) { t.Fatal("project config followed an outside parent symlink") } } + +func TestBrowserLimitsValidateAndNarrowPassthrough(t *testing.T) { + // At least one positive bound is required. + allZero := Config{Protocol: ProtocolVersion, BrowserLimits: &BrowserLimitsConfig{}} + if err := allZero.validate(); err == nil || !strings.Contains(err.Error(), "must narrow at least one") { + t.Fatalf("all-zero browser_limits accepted: %v", err) + } + negative := Config{Protocol: ProtocolVersion, BrowserLimits: &BrowserLimitsConfig{MaxRequests: -1}} + if err := negative.validate(); err == nil || !strings.Contains(err.Error(), "cannot be negative") { + t.Fatalf("negative browser_limits accepted: %v", err) + } + + // The effective result carries the operator ceilings verbatim; the + // narrowing against the builtin profile happens when the session plan is + // built, where widening attempts become named errors. + config := Config{Protocol: ProtocolVersion, + BrowserLimits: &BrowserLimitsConfig{MaxOrigins: 4, MaxRequests: 200, TimeoutMS: 180000}} + effective, rejections, err := config.Narrow(Ceiling{AllowedProfiles: []string{"code"}, + MaxTurns: 100, MaxToolCalls: 100, RegisteredCommands: map[string]struct{}{"test.go": {}}}) + if err != nil || len(rejections) != 0 { + t.Fatalf("narrow: %v %v", rejections, err) + } + if effective.BrowserLimits == nil || effective.BrowserLimits.MaxOrigins != 4 || + effective.BrowserLimits.MaxRequests != 200 || effective.BrowserLimits.TimeoutMS != 180000 { + t.Fatalf("browser limits passthrough lost: %+v", effective.BrowserLimits) + } + if effective.MaxTurns != 100 || effective.MaxToolCalls != 100 { + t.Fatalf("unrelated ceilings changed: %+v", effective) + } +}