306 lines
11 KiB
Go
306 lines
11 KiB
Go
package stage
|
|
|
|
import (
|
|
"fmt"
|
|
"path/filepath"
|
|
"regexp"
|
|
"strings"
|
|
)
|
|
|
|
// ArtifactAccess is runtime-only, server-derived access to artifact visits.
|
|
// Write is the current turn's private directory; WriteShared is the run-level
|
|
// public directory. Read is limited to the current turn and public/, so a later
|
|
// stage never receives an earlier turn's private/ files. Empty fields
|
|
// deliberately grant nothing outside the workspace.
|
|
type ArtifactAccess struct {
|
|
Write string
|
|
WriteShared 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")
|
|
}
|
|
if _, none := ChecksNone(text); none {
|
|
return nil, fmt.Errorf("delivery stages run their checks before landing; list the check commands instead of none")
|
|
}
|
|
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
|
|
}
|
|
|
|
// ChecksNone reports whether a checks block uses the explicit
|
|
// "none: <reason>" form. It matches on the leading none: alone, so a malformed
|
|
// declaration (no reason, extra lines) is rejected rather than run as a command.
|
|
func ChecksNone(text string) (reason string, ok bool) {
|
|
text = strings.TrimSpace(text)
|
|
if !strings.HasPrefix(strings.ToLower(text), "none:") {
|
|
return "", false
|
|
}
|
|
return strings.TrimSpace(text[len("none:"):]), true
|
|
}
|
|
|
|
// ValidateChecksBlock is the checks syntax shared by stored and new
|
|
// definitions. Only a delivery stage executes commands (the server's delivery
|
|
// gate); every other stage may declare only "none: <reason>", so a listed
|
|
// command is never accepted and then silently left unexecuted.
|
|
func ValidateChecksBlock(def Definition) error {
|
|
text, present := def.Blocks["checks"]
|
|
if !present {
|
|
return nil
|
|
}
|
|
if reason, none := ChecksNone(text); none {
|
|
if strings.Contains(strings.TrimSpace(text), "\n") {
|
|
return fmt.Errorf("checks none must be a single line: none: <reason>")
|
|
}
|
|
if len(reason) < 3 || len(reason) > 300 {
|
|
return fmt.Errorf("checks none needs a short reason (3-300 bytes), for example \"none: read-only review\"")
|
|
}
|
|
if def.Configs["delivery"] == "true" {
|
|
return fmt.Errorf("delivery stages run their checks before landing; list the check commands instead of none")
|
|
}
|
|
return nil
|
|
}
|
|
if def.Configs["delivery"] != "true" {
|
|
return fmt.Errorf("checks commands run only on delivery stages (delivery=true); write \"none: <reason>\" here and declare the commands on the delivery stage")
|
|
}
|
|
_, err := DeliveryChecks(def)
|
|
return err
|
|
}
|
|
|
|
// 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 writeArtifacts && artifactDirectory(c.ArtifactAccess.WriteShared) {
|
|
allow("external_directory", filepath.ToSlash(filepath.Join(c.ArtifactAccess.WriteShared, "*")))
|
|
allow("edit", filepath.ToSlash(filepath.Join(c.ArtifactAccess.WriteShared, "*")))
|
|
}
|
|
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
|
|
}
|