Files
pipelines/internal/stage/tools.go
T
alan 2cdb9a9e93 Stabilize guarded model delivery
Add validated OpenCode-only delivery capabilities, canonical linked-worktree access checks, isolated candidate verification, and guarded main settlement.

Wire the bounded reconnect-foreground controlled HTTP fixture through ordinary server construction so target verification obtains server-controlled provenance and rejects unknown or incompatible fixture evidence.

Checked packaged templates and packaged authoring skill references; no updates are needed because this draft-only infrastructure activates no definition. Recorded the stale reference and activation guidance in docs/notes/delivery-stabilization.md for the docs fold.
2026-10-18 14:50:18 +01:00

256 lines
8.8 KiB
Go

package stage
import (
"fmt"
"path/filepath"
"regexp"
"strings"
)
// ArtifactAccess is runtime-only, server-derived access to artifact visits.
// Empty fields deliberately grant nothing outside the workspace.
type ArtifactAccess struct {
Write string
Read []string
}
// LandingAccess is the server-derived external capability for a verified
// delivery operation. Empty or malformed values grant nothing.
type LandingAccess struct {
MainWorktree string
GitMetadata string
LockPath string
}
func (a LandingAccess) valid() bool {
for _, path := range []string{a.MainWorktree, a.GitMetadata, a.LockPath} {
if path == "" || !filepath.IsAbs(path) || filepath.Clean(path) != path || strings.ContainsAny(path, "*?\\") {
return false
}
}
// The server grants the canonical repository metadata directory as OpenCode
// V2's smallest external-directory unit. Keep the lock inside that directory
// so a caller cannot turn a valid metadata capability into access elsewhere.
return a.GitMetadata == filepath.Join(a.MainWorktree, ".git") &&
a.LockPath == filepath.Join(a.GitMetadata, "pipelines-landing.lock")
}
// DeliveryEnabled is the narrow, declarative capability check used before the
// runner supplies any landing paths. Only a validated model definition can ask
// for it; runtime paths are still derived by the server.
func DeliveryEnabled(def Definition) (bool, error) {
delivery := def.Configs["delivery"]
if delivery == "" {
return false, nil
}
if delivery != "true" {
return false, fmt.Errorf("delivery must be true when set")
}
if EffectiveType(def.Type) != ModelType {
return false, fmt.Errorf("delivery is supported only by model stages")
}
if _, err := (ModelStage{}).Spec(def); err != nil {
return false, fmt.Errorf("invalid delivery model stage: %w", err)
}
if _, err := DeliveryChecks(def); err != nil {
return false, err
}
return true, nil
}
// DeliveryChecks returns the bounded, definition-declared checks that the
// runner executes against a committed delivery candidate before canonical main
// is changed. They
// are intentionally a block rather than a generic runner setting: each
// workflow owns its repository-specific verification commands.
func DeliveryChecks(def Definition) ([]string, error) {
text := strings.TrimSpace(def.Blocks["checks"])
if text == "" {
return nil, fmt.Errorf("delivery stages require a nonempty checks block")
}
var checks []string
for _, line := range strings.Split(text, "\n") {
check := strings.TrimSpace(line)
if check == "" {
continue
}
if len(check) > 4096 {
return nil, fmt.Errorf("delivery check exceeds 4096 bytes")
}
checks = append(checks, check)
}
if len(checks) == 0 || len(checks) > 20 {
return nil, fmt.Errorf("delivery stages require 1 to 20 checks")
}
return checks, nil
}
// ToolNames validates model-stage permissions, not general graph semantics.
// A present empty block explicitly denies all tools.
func ToolNames(def Definition) ([]string, bool, error) {
text, present := def.Blocks["tools"]
if !present {
return nil, false, nil
}
tools := []string{}
seen := map[string]bool{}
for _, line := range strings.Split(text, "\n") {
name := strings.TrimSpace(line)
if name == "" {
continue
}
switch name {
case "websearch", "webfetch", "read", "glob", "grep", "edit", "shell":
default:
return nil, true, fmt.Errorf("unsupported tool %q", name)
}
if seen[name] {
return nil, true, fmt.Errorf("duplicate tool %s", name)
}
seen[name] = true
tools = append(tools, name)
}
return tools, true, nil
}
// legacyTools is the single declaration of the implicit tool set for a stage
// with no tools block: the mutating read/glob/grep/edit/shell bundle. It is
// never nil or empty, so an absent block is never represented as a read-only or
// text-only stage.
var legacyTools = []string{"read", "glob", "grep", "edit", "shell"}
// effectiveTools is the single materialisation point for the tools a model
// stage is permitted. A present tools block (including an explicit empty block)
// is returned exactly as parsed by ToolNames; an absent block yields the legacy
// mutating bundle so it is never silently narrowed to an empty or read-only set.
func effectiveTools(def Definition) ([]string, error) {
tools, explicit, err := ToolNames(def)
if err != nil {
return nil, err
}
if !explicit {
return legacyTools, nil
}
return tools, nil
}
// safeToReplay is the single definition of which post-admission work may be
// automatically retried. Only an explicit tools block that selects neither
// "edit" nor "shell" is side-effect free. An absent block is the legacy
// read/glob/grep/edit/shell bundle and is treated as mutating, matching the
// runner's useAgent/permissionRules semantics.
func safeToReplay(def Definition) bool {
tools, explicit, err := ToolNames(def)
if err != nil || !explicit {
return false
}
for _, tool := range tools {
if tool == "edit" || tool == "shell" {
return false
}
}
return true
}
func (c *AgentClient) permissionRules() []map[string]string {
rules := []map[string]string{{"action": "*", "resource": "*", "effect": "deny"}}
tools := c.Tools
// A missing block gets normal local agent tools. Explicit stage blocks still
// select which tools are available, including an empty block for text-only work.
if tools == nil {
tools = legacyTools
}
allow := func(action, resource string) {
rules = append(rules, map[string]string{"action": action, "resource": resource, "effect": "allow"})
}
for _, tool := range tools {
switch tool {
case "websearch", "webfetch", "read", "glob", "grep":
allow(tool, "*")
case "edit":
if len(c.WritePaths) == 0 && c.Policy.Edit == nil {
allow("edit", "*")
rules = append(rules, map[string]string{"action": "edit", "resource": "/*", "effect": "deny"})
if c.Directory != "" {
allow("edit", filepath.ToSlash(filepath.Join(c.Directory, "*")))
}
} else {
paths := c.WritePaths
if len(paths) == 0 {
paths = c.Policy.Edit
}
// Relative patterns may also match absolute paths. Deny those first,
// then grant only absolute equivalents inside the run directory.
for _, path := range paths {
if c.Policy.Edit == nil || matchesEditPolicy(c.Policy.Edit, path) {
allow("edit", filepath.ToSlash(path))
}
}
rules = append(rules, map[string]string{"action": "edit", "resource": "/*", "effect": "deny"})
for _, path := range paths {
if c.Directory != "" && (c.Policy.Edit == nil || matchesEditPolicy(c.Policy.Edit, path)) {
allow("edit", filepath.ToSlash(filepath.Join(c.Directory, path)))
}
}
}
for _, pattern := range []string{"../*", "*/../*"} {
rules = append(rules, map[string]string{"action": "edit", "resource": pattern, "effect": "deny"})
}
case "shell":
if c.Policy.Shell == nil {
allow("shell", "*")
} else {
for _, command := range c.Policy.Shell {
allow("shell", command)
}
}
}
}
// OpenCode V2 resolves an external file to its containing directory and
// checks external_directory against <directory>/*. Do not grant a parent:
// each visit is deliberately an independent capability.
readArtifacts := false
writeArtifacts := false
for _, tool := range tools {
readArtifacts = readArtifacts || tool == "read" || tool == "glob" || tool == "grep"
writeArtifacts = writeArtifacts || tool == "edit"
}
if readArtifacts {
for _, directory := range c.ArtifactAccess.Read {
if artifactDirectory(directory) {
allow("external_directory", filepath.ToSlash(filepath.Join(directory, "*")))
}
}
}
if writeArtifacts && artifactDirectory(c.ArtifactAccess.Write) {
allow("external_directory", filepath.ToSlash(filepath.Join(c.ArtifactAccess.Write, "*")))
allow("edit", filepath.ToSlash(filepath.Join(c.ArtifactAccess.Write, "*")))
}
if c.LandingAccess.valid() {
allow("external_directory", filepath.ToSlash(filepath.Join(c.LandingAccess.MainWorktree, "*")))
allow("external_directory", filepath.ToSlash(filepath.Join(c.LandingAccess.GitMetadata, "*")))
}
for _, pattern := range []string{"../*", "*/../*"} {
rules = append(rules, map[string]string{"action": "external_directory", "resource": pattern, "effect": "deny"})
}
for _, pattern := range []string{"*.env", "*.env.*", "pipelines.db*"} {
rules = append(rules, map[string]string{"action": "read", "resource": pattern, "effect": "deny"})
}
return rules
}
func artifactDirectory(directory string) bool {
return directory != "" && filepath.IsAbs(directory) && filepath.Clean(directory) == directory && !strings.ContainsAny(directory, "*?\\")
}
func matchesEditPolicy(patterns []string, path string) bool {
for _, pattern := range patterns {
// OpenCode resource wildcards match across directory separators.
re := strings.ReplaceAll(strings.ReplaceAll(regexp.QuoteMeta(pattern), `\*`, ".*"), `\?`, ".")
if ok, _ := regexp.MatchString("^"+re+"$", filepath.ToSlash(path)); ok {
return true
}
}
return false
}