Scope stage artifact access by run visit
Derive validated same-run visit artifact capabilities in the runner and pass them to OpenCode and Pi clients. Permit supported file tools to read completed prior visits and write only the current visit, preserving workspace, secret, database, and shell restrictions.\n\nChecked packaged templates and authoring skill references: neither needs updating in this item; docs/notes/scoped-artifact-access.md records the shared documentation staleness for the docs-fold writer.
This commit is contained in:
+10
-7
@@ -14,13 +14,16 @@ import (
|
||||
// before any prompt is admitted, so restart recovery can interrupt the agent.
|
||||
type AgentClient struct {
|
||||
OpenCodeClient
|
||||
WritePaths []string
|
||||
Tools []string // nil is the legacy manual approval bundle; empty denies all
|
||||
OnSession func(string, bool) error
|
||||
SessionID string
|
||||
Transcript string
|
||||
Policy ToolPolicy
|
||||
WorkStarted bool
|
||||
WritePaths []string
|
||||
Tools []string // nil is the legacy manual approval bundle; empty denies all
|
||||
// ArtifactAccess is supplied only by the runner. Write is this visit's
|
||||
// directory; Read contains this and completed earlier visits in the same run.
|
||||
ArtifactAccess ArtifactAccess
|
||||
OnSession func(string, bool) error
|
||||
SessionID string
|
||||
Transcript string
|
||||
Policy ToolPolicy
|
||||
WorkStarted bool
|
||||
}
|
||||
|
||||
func (c OpenCodeClient) Interrupt(ctx context.Context, id string) error {
|
||||
|
||||
@@ -28,6 +28,7 @@ type PiClient struct {
|
||||
// ArtifactsDir is exported to the spawned Pi process as
|
||||
// PIPELINES_ARTIFACTS_DIR so its tools can write stage artifacts.
|
||||
ArtifactsDir string
|
||||
ArtifactAccess ArtifactAccess
|
||||
Policy ToolPolicy
|
||||
OnSession func(string, bool) error
|
||||
OnOwnership func(string, string, bool) error
|
||||
@@ -128,7 +129,7 @@ func (c *PiClient) Generate(ctx context.Context, config ModelConfig, prompt stri
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
policy := map[string]any{"directory": c.Directory, "tools": tools, "paths": c.WritePaths, "edit": c.Policy.Edit, "shell": c.Policy.Shell}
|
||||
policy := map[string]any{"directory": c.Directory, "tools": tools, "paths": c.WritePaths, "edit": c.Policy.Edit, "shell": c.Policy.Shell, "artifact_write": c.ArtifactAccess.Write, "artifact_read": c.ArtifactAccess.Read}
|
||||
if c.WritePaths == nil {
|
||||
policy["paths"] = []string{}
|
||||
}
|
||||
|
||||
@@ -8,6 +8,24 @@ export function permit(policy, tool, args) {
|
||||
if (policy.shell !== null && !policy.shell.includes(args.command)) return "Shell command is not permitted";
|
||||
return null;
|
||||
}
|
||||
const artifact = (absolute, write) => {
|
||||
const permitted = write ? [policy.artifact_write] : policy.artifact_read;
|
||||
for (const directory of permitted) {
|
||||
if (typeof directory !== "string" || !path.isAbsolute(directory)) continue;
|
||||
let parent = absolute;
|
||||
while (!fs.existsSync(parent)) {
|
||||
const next = path.dirname(parent);
|
||||
if (next === parent) break;
|
||||
parent = next;
|
||||
}
|
||||
if (!fs.existsSync(parent)) continue;
|
||||
const resolved = fs.realpathSync(parent);
|
||||
const target = path.join(resolved, path.relative(parent, absolute));
|
||||
const root = fs.realpathSync(directory);
|
||||
if (target === root || target.startsWith(root + path.sep)) return true;
|
||||
}
|
||||
return false;
|
||||
};
|
||||
if (tool === "edit" || tool === "write") {
|
||||
if (typeof args.path !== "string") return "Missing file path";
|
||||
if (args.path.startsWith("~") || args.path.startsWith("@")) return "Use a literal path, not a harness path shortcut";
|
||||
@@ -20,7 +38,10 @@ export function permit(policy, tool, args) {
|
||||
}
|
||||
const resolved = fs.realpathSync(parent);
|
||||
const root = fs.realpathSync(policy.directory);
|
||||
if (resolved !== root && !resolved.startsWith(root + path.sep)) return "Edit escapes run directory";
|
||||
if (resolved !== root && !resolved.startsWith(root + path.sep)) {
|
||||
if (!artifact(absolute, true)) return "Edit escapes run directory";
|
||||
return null;
|
||||
}
|
||||
const relative = path.relative(path.resolve(policy.directory), absolute).split(path.sep).join("/");
|
||||
const canonical = path.relative(root, path.join(resolved, path.relative(parent, absolute))).split(path.sep).join("/");
|
||||
if (relative.startsWith("../") || path.isAbsolute(relative)) return "Edit escapes run directory";
|
||||
@@ -31,9 +52,19 @@ export function permit(policy, tool, args) {
|
||||
});
|
||||
if (policy.edit !== null && (!matches(relative) || !matches(canonical))) return "Edit is outside stage patterns";
|
||||
}
|
||||
if (tool === "read" && typeof args.path === "string") {
|
||||
if (["read", "grep", "find"].includes(tool) && typeof args.path === "string") {
|
||||
const name = path.basename(args.path);
|
||||
if (/^(.*\.env(?:\..*)?|pipelines\.db.*)$/.test(name)) return "Protected file cannot be read";
|
||||
const absolute = path.resolve(policy.directory, args.path);
|
||||
let parent = absolute;
|
||||
while (!fs.existsSync(parent)) {
|
||||
const next = path.dirname(parent);
|
||||
if (next === parent) return "Cannot resolve read path";
|
||||
parent = next;
|
||||
}
|
||||
const resolved = fs.realpathSync(parent);
|
||||
const root = fs.realpathSync(policy.directory);
|
||||
if (resolved !== root && !resolved.startsWith(root + path.sep) && !artifact(absolute, false)) return "Read escapes run directory";
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
package stage
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestPiPolicyArtifactScope(t *testing.T) {
|
||||
if _, err := exec.LookPath("node"); err != nil {
|
||||
t.Skip("node is required to exercise the Pi policy extension")
|
||||
}
|
||||
root := t.TempDir()
|
||||
workspace := filepath.Join(root, "workspace")
|
||||
current := filepath.Join(root, "artifacts [7]", "2")
|
||||
prior := filepath.Join(root, "artifacts [7]", "1")
|
||||
sibling := filepath.Join(root, "artifacts [7]", "3")
|
||||
for _, directory := range []string{workspace, current, prior, sibling} {
|
||||
if err := os.MkdirAll(directory, 0700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
policy := map[string]any{
|
||||
"directory": workspace,
|
||||
"tools": []string{"read", "grep", "find", "edit"},
|
||||
"paths": []string{},
|
||||
"edit": nil,
|
||||
"shell": nil,
|
||||
"artifact_write": current,
|
||||
"artifact_read": []string{current, prior},
|
||||
}
|
||||
policyJSON, err := json.Marshal(policy)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
policyFile := filepath.Join(root, "policy.mjs")
|
||||
if err := os.WriteFile(policyFile, piPolicy, 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
script := `const { permit } = await import(process.argv[1]);
|
||||
const policy = JSON.parse(process.argv[2]);
|
||||
const checks = JSON.parse(process.argv[3]);
|
||||
console.log(JSON.stringify(checks.map(([tool, path]) => permit(policy, tool, {path}))));`
|
||||
checks := [][2]string{
|
||||
{"edit", filepath.Join(current, "report.md")},
|
||||
{"edit", filepath.Join(prior, "report.md")},
|
||||
{"read", filepath.Join(prior, "report.md")},
|
||||
{"grep", filepath.Join(prior, "report.md")},
|
||||
{"find", filepath.Join(current, "reports")},
|
||||
{"read", filepath.Join(sibling, "report.md")},
|
||||
{"grep", filepath.Join(root, "other-run", "1", "report.md")},
|
||||
{"find", filepath.Join(current, "..", "3", "report.md")},
|
||||
{"read", filepath.Join(prior, ".env")},
|
||||
}
|
||||
checksJSON, err := json.Marshal(checks)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
output, err := exec.Command("node", "--input-type=module", "--eval", script, "file://"+policyFile, string(policyJSON), string(checksJSON)).Output()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var got []any
|
||||
if err := json.Unmarshal(output, &got); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(got) != len(checks) || got[0] != nil || got[1] == nil || got[2] != nil || got[3] != nil || got[4] != nil || got[5] == nil || got[6] == nil || got[7] == nil || got[8] == nil {
|
||||
t.Fatalf("Pi artifact policy results = %#v", got)
|
||||
}
|
||||
}
|
||||
@@ -7,6 +7,13 @@ import (
|
||||
"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
|
||||
}
|
||||
|
||||
// ToolNames validates model-stage permissions, not general graph semantics.
|
||||
// A present empty block explicitly denies all tools.
|
||||
func ToolNames(def Definition) ([]string, bool, error) {
|
||||
@@ -128,12 +135,39 @@ func (c *AgentClient) permissionRules() []map[string]string {
|
||||
}
|
||||
}
|
||||
}
|
||||
// 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, "*")))
|
||||
}
|
||||
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.
|
||||
|
||||
@@ -139,3 +139,38 @@ func TestDefaultEditScopeIsLanguageIndependentRunDirectory(t *testing.T) {
|
||||
t.Fatal("external directories were enabled")
|
||||
}
|
||||
}
|
||||
|
||||
func TestArtifactPermissionsAreExactAndToolScoped(t *testing.T) {
|
||||
current := "/artifacts/run [7]/2"
|
||||
prior := "/artifacts/run [7]/1"
|
||||
sibling := "/artifacts/run 7/3"
|
||||
otherRun := "/artifacts/run 8/1"
|
||||
client := &AgentClient{OpenCodeClient: OpenCodeClient{Directory: "/repo"}, Tools: []string{"read", "edit"}, ArtifactAccess: ArtifactAccess{Write: current, Read: []string{current, prior}}}
|
||||
rules := client.permissionRules()
|
||||
for _, path := range []string{current + "/report.md", prior + "/report.md"} {
|
||||
if permissionEffect(rules, "external_directory", path) != "allow" {
|
||||
t.Fatalf("artifact directory denied: %q", path)
|
||||
}
|
||||
}
|
||||
if permissionEffect(rules, "edit", current+"/report.md") != "allow" || permissionEffect(rules, "edit", prior+"/report.md") != "deny" {
|
||||
t.Fatal("artifact writes were not limited to the current visit")
|
||||
}
|
||||
for _, path := range []string{sibling + "/report.md", otherRun + "/report.md", current + "/../3/report.md", "/artifacts/run 7/20/report.md"} {
|
||||
if permissionEffect(rules, "external_directory", path) != "deny" {
|
||||
t.Fatalf("unapproved artifact scope allowed: %q", path)
|
||||
}
|
||||
}
|
||||
client.Tools = []string{}
|
||||
if permissionEffect(client.permissionRules(), "external_directory", current+"/report.md") != "deny" {
|
||||
t.Fatal("no-tool stage gained artifact access")
|
||||
}
|
||||
client.Tools = []string{"read"}
|
||||
rules = client.permissionRules()
|
||||
if permissionEffect(rules, "external_directory", prior+"/report.md") != "allow" || permissionEffect(rules, "edit", current+"/report.md") != "deny" {
|
||||
t.Fatal("read-only artifact stage gained write access")
|
||||
}
|
||||
client.ArtifactAccess = ArtifactAccess{}
|
||||
if permissionEffect(client.permissionRules(), "external_directory", current+"/report.md") != "deny" {
|
||||
t.Fatal("missing artifact scope enabled an external directory")
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user