mirror of
https://github.com/anomalyco/opencode.git
synced 2026-11-26 23:28:43 +00:00
1191 lines
47 KiB
TypeScript
1191 lines
47 KiB
TypeScript
import { describe, expect, test } from "bun:test"
|
|
import { Cause, Deferred, Effect, Fiber, Layer, Schema } from "effect"
|
|
import { Agent } from "@opencode/core/agent"
|
|
import { Database } from "@opencode/core/database/database"
|
|
import { AppNodeBuilder } from "@opencode/core/effect/app-node-builder"
|
|
import { LayerNode } from "@opencode/util/effect/layer-node"
|
|
import { Bus } from "@opencode/core/bus"
|
|
import { Location } from "@opencode/core/location"
|
|
import { Permission } from "@opencode/core/permission"
|
|
import { PermissionTable } from "@opencode/core/permission/sql"
|
|
import { PermissionSaved } from "@opencode/core/permission/saved"
|
|
import { PluginHooks } from "@opencode/core/plugin/hooks"
|
|
import { Project } from "@opencode/core/project"
|
|
import { ProjectTable } from "@opencode/core/project/sql"
|
|
import { AbsolutePath } from "@opencode/core/schema"
|
|
import { Session } from "@opencode/core/session"
|
|
import { SessionTable } from "@opencode/core/session/sql"
|
|
import { SessionStore } from "@opencode/core/session/store"
|
|
import { ShellParse } from "@opencode/core/shell/parse"
|
|
import { Tool } from "@opencode/core/tool"
|
|
import { Wildcard } from "@opencode/core/util/wildcard"
|
|
import { eq } from "drizzle-orm"
|
|
import { location } from "./fixture/location"
|
|
import { testEffect } from "./lib/effect"
|
|
|
|
const current = Layer.succeed(
|
|
Location.Service,
|
|
Location.Service.of(location({ directory: AbsolutePath.make("/project") })),
|
|
)
|
|
const it = testEffect(
|
|
AppNodeBuilder.build(
|
|
LayerNode.group([
|
|
Database.node,
|
|
Bus.node,
|
|
SessionStore.node,
|
|
PermissionSaved.node,
|
|
Agent.node,
|
|
PluginHooks.node,
|
|
Permission.node,
|
|
]),
|
|
[Location.node.replace(current)],
|
|
),
|
|
)
|
|
|
|
function setup(rules: Permission.Ruleset = [], sessionID = Session.ID.make("ses_test")) {
|
|
return Effect.gen(function* () {
|
|
const { db } = yield* Database.Service
|
|
yield* db
|
|
.insert(ProjectTable)
|
|
.values({ id: Project.ID.global, worktree: AbsolutePath.make("/project"), sandboxes: [] })
|
|
.onConflictDoNothing()
|
|
.run()
|
|
.pipe(Effect.orDie)
|
|
yield* db
|
|
.insert(SessionTable)
|
|
.values({
|
|
id: sessionID,
|
|
project_id: Project.ID.global,
|
|
slug: "test",
|
|
directory: "/project",
|
|
title: "test",
|
|
version: "test",
|
|
agent: Agent.ID.make("test"),
|
|
})
|
|
.onConflictDoNothing()
|
|
.run()
|
|
.pipe(Effect.orDie)
|
|
yield* setRules(rules)
|
|
})
|
|
}
|
|
|
|
function setRules(rules: Permission.Ruleset) {
|
|
return Effect.gen(function* () {
|
|
const agents = yield* Agent.Service
|
|
yield* agents.transform((editor) =>
|
|
editor.update(Agent.ID.make("test"), (agent) => {
|
|
agent.permissions = [...rules]
|
|
}),
|
|
)
|
|
})
|
|
}
|
|
|
|
function assertion(input: Partial<Permission.AssertInput> = {}) {
|
|
return {
|
|
id: Permission.ID.create("per_test"),
|
|
sessionID: Session.ID.make("ses_test"),
|
|
action: "read",
|
|
resources: ["src/index.ts"],
|
|
...input,
|
|
} satisfies Permission.AssertInput
|
|
}
|
|
|
|
function waitForRequest(input: Partial<Permission.AssertInput> = {}) {
|
|
return Effect.gen(function* () {
|
|
const value = assertion(input)
|
|
const service = yield* Permission.Service
|
|
const bus = yield* Bus.Service
|
|
const asked = yield* Deferred.make<Permission.Request>()
|
|
const unsubscribe = yield* bus.listen((event) => {
|
|
if (event.type !== Permission.Event.Asked.type) return Effect.void
|
|
const request = event.data as Permission.Request
|
|
return request.id === value.id ? Deferred.succeed(asked, request).pipe(Effect.asVoid) : Effect.void
|
|
})
|
|
yield* Effect.addFinalizer(() => unsubscribe)
|
|
const fiber = yield* service.assert(value).pipe(Effect.forkScoped)
|
|
const request = yield* Deferred.await(asked)
|
|
return { service, fiber, request }
|
|
})
|
|
}
|
|
|
|
test("Permission.site saves a web URL's site as written, and only the URL itself when its site isn't plain", () => {
|
|
expect(Permission.site("https://opencode.ai/docs/x?y#z")).toEqual(["https://opencode.ai", "https://opencode.ai/*"])
|
|
expect(Permission.site("HTTPS://OpenCode.ai:8443")).toEqual([
|
|
"HTTPS://OpenCode.ai:8443",
|
|
"HTTPS://OpenCode.ai:8443/*",
|
|
])
|
|
// URL parsers end the site at a backslash, so this goes to evil.com.
|
|
expect(Permission.site("https://evil.com\\@opencode.ai/x")).toEqual(["https://evil.com", "https://evil.com/*"])
|
|
for (const url of ["https://opencode.ai@evil.com/x", "https://opencode.ai\t.evil.com/", "ftp://opencode.ai/x"])
|
|
expect(Permission.site(url)).toEqual([url])
|
|
for (const url of ["https://*/x", "https://*.com/x", "https://opencode.ai@evil.com/x?y"])
|
|
expect(Permission.site(url)).toEqual([])
|
|
})
|
|
|
|
describe("Permission.isActionDenied", () => {
|
|
const rule = (action: string, resource: string, effect: Permission.Rule["effect"]): Permission.Rule => ({
|
|
action,
|
|
resource,
|
|
effect,
|
|
})
|
|
|
|
test("never reports an action as denied when evaluate leaves a resource reachable", () => {
|
|
const cases = [
|
|
{ action: "skill", witness: "any", rulesets: [[]] },
|
|
{ action: "bash", witness: "abc", rulesets: [[rule("bash", "?", "deny")]] },
|
|
{
|
|
action: "skill",
|
|
witness: "browser",
|
|
rulesets: [[rule("skill", "*", "deny"), rule("skill", "browser", "ask")]],
|
|
},
|
|
{
|
|
action: "bash",
|
|
witness: "abcde",
|
|
rulesets: [[rule("bash", "*", "deny"), rule("bash", "ab*", "allow"), rule("bash", "ab?", "deny")]],
|
|
},
|
|
{
|
|
action: "skill",
|
|
witness: "browser",
|
|
rulesets: [[rule("skill", "*", "deny"), rule("skill", "browser", "deny")], [rule("skill", "browser", "allow")]],
|
|
},
|
|
]
|
|
|
|
for (const item of cases) {
|
|
expect(Permission.evaluate(item.action, item.witness, ...item.rulesets).effect).not.toBe("deny")
|
|
expect(Permission.isActionDenied(item.action, ...item.rulesets)).toBe(false)
|
|
}
|
|
})
|
|
|
|
test("reports an action as denied when a blanket deny is only followed by narrow denies", () => {
|
|
const cases = [
|
|
{
|
|
action: "skill",
|
|
rules: [rule("skill", "*", "deny"), rule("browser", "*", "deny"), rule("skill", "browser", "deny")],
|
|
},
|
|
{ action: "shell", rules: [rule("*", "*", "deny"), rule("shell", "git *", "deny")] },
|
|
{ action: "skill", rules: [rule("skill", "browser", "allow"), rule("skill", "*", "deny")] },
|
|
]
|
|
|
|
for (const item of cases) {
|
|
expect(Permission.isActionDenied(item.action, item.rules)).toBe(true)
|
|
}
|
|
})
|
|
|
|
test("composes override, restrict, and fallback with sound algebraic laws", () => {
|
|
const base = Permission.Policy.fromRules([
|
|
rule("read", "*", "ask"),
|
|
rule("read", ".env", "deny"),
|
|
rule("read", "README.md", "allow"),
|
|
])
|
|
const withSaved = Permission.Policy.fallback(base, Permission.Policy.fromRules([rule("read", "*", "allow")]))
|
|
|
|
// fallback settles ask, never overrides deny or allow
|
|
expect(Permission.Policy.evaluate(withSaved, "read", "src/index.ts").effect).toBe("allow")
|
|
expect(Permission.Policy.evaluate(withSaved, "read", ".env").effect).toBe("deny")
|
|
expect(Permission.Policy.evaluate(withSaved, "read", "README.md").effect).toBe("allow")
|
|
|
|
// evaluateAll follows the deny > ask > allow lattice
|
|
expect(Permission.Policy.evaluateAll(base, "read", ["README.md", "src/index.ts"])).toBe("ask")
|
|
expect(Permission.Policy.evaluateAll(base, "read", ["README.md", ".env"])).toBe("deny")
|
|
expect(Permission.Policy.evaluateAll(withSaved, "read", ["README.md", "src/index.ts"])).toBe("allow")
|
|
|
|
// fallback left/right identity & secondary denial reachability
|
|
const denyAll = Permission.Policy.fromRules([rule("*", "*", "deny")])
|
|
expect(
|
|
Permission.Policy.isActionDenied(Permission.Policy.fallback(Permission.Policy.empty, denyAll), "execute"),
|
|
).toBe(true)
|
|
expect(
|
|
Permission.Policy.isActionDenied(
|
|
Permission.Policy.fallback(Permission.Policy.fromRules([rule("read", ".env", "deny")]), denyAll),
|
|
"read",
|
|
),
|
|
).toBe(true)
|
|
|
|
// universal wildcards (**, * *) behave like *
|
|
expect(Permission.Policy.isUniversalPattern("*")).toBe(true)
|
|
expect(Permission.Policy.isUniversalPattern("**")).toBe(true)
|
|
expect(Permission.Policy.isUniversalPattern("* *")).toBe(true)
|
|
expect(Permission.Policy.isUniversalPattern(" *")).toBe(false)
|
|
expect(Permission.Policy.isUniversalPattern("* **")).toBe(false)
|
|
expect(
|
|
Permission.Policy.isActionDenied(
|
|
Permission.Policy.restrict(Permission.Policy.empty, [{ action: "*", resource: "**" }]),
|
|
"read",
|
|
),
|
|
).toBe(true)
|
|
expect(Permission.Policy.scopedRules(Permission.Policy.fromRules([rule("read", "**", "ask")]), "read")).toEqual([])
|
|
|
|
// hasDeny ignores overridden denies and unreachable fallback branches
|
|
expect(
|
|
Permission.Policy.hasDeny(
|
|
Permission.Policy.fromRules([rule("*", "*", "deny"), rule("shell", "*", "allow")]),
|
|
"shell",
|
|
),
|
|
).toBe(false)
|
|
expect(
|
|
Permission.Policy.hasDeny(
|
|
Permission.Policy.fallback(
|
|
Permission.Policy.fromRules([rule("shell", "*", "allow")]),
|
|
Permission.Policy.fromRules([rule("shell", "*", "deny")]),
|
|
),
|
|
"shell",
|
|
),
|
|
).toBe(false)
|
|
|
|
// restrict is immutable (copies caller array) and monotone under both override and fallback
|
|
const denies = [{ action: "skill", resource: "browser" }]
|
|
const restricted = Permission.Policy.override(
|
|
Permission.Policy.fallback(
|
|
Permission.Policy.restrict(Permission.Policy.fromRules([rule("skill", "*", "allow")]), denies),
|
|
Permission.Policy.fromRules([rule("skill", "*", "allow")]),
|
|
),
|
|
[rule("skill", "*", "allow")],
|
|
)
|
|
denies.push({ action: "*", resource: "*" })
|
|
expect(Permission.Policy.evaluate(restricted, "skill", "browser").effect).toBe("deny")
|
|
expect(Permission.Policy.evaluate(restricted, "skill", "other").effect).toBe("allow")
|
|
expect(Permission.Policy.isActionDenied(restricted, "skill")).toBe(false)
|
|
expect(Permission.Policy.hasDeny(restricted, "skill")).toBe(true)
|
|
|
|
// relevant does not put fallback.secondary after base, and scopedRules drops dead overridden scoped rules
|
|
const fallbackWithDeny = Permission.Policy.fallback(
|
|
Permission.Policy.fromRules([rule("read", ".env", "deny")]),
|
|
Permission.Policy.fromRules([rule("read", "*", "allow")]),
|
|
)
|
|
expect(Permission.evaluate("read", ".env", Permission.Policy.relevant(fallbackWithDeny, "read")).effect).toBe(
|
|
"deny",
|
|
)
|
|
expect(
|
|
Permission.Policy.scopedRules(
|
|
Permission.Policy.fromRules([rule("read", ".env", "deny"), rule("read", "*", "ask")]),
|
|
"read",
|
|
),
|
|
).toEqual([])
|
|
})
|
|
})
|
|
|
|
describe("Permission", () => {
|
|
it.effect("returns the evaluated effect and only queues prompts", () =>
|
|
Effect.gen(function* () {
|
|
yield* setup([{ action: "read", resource: "*", effect: "allow" }])
|
|
const service = yield* Permission.Service
|
|
expect(yield* service.ask(assertion())).toEqual({ id: Permission.ID.create("per_test"), effect: "allow" })
|
|
expect(yield* service.list()).toEqual([])
|
|
yield* setRules([{ action: "read", resource: "*", effect: "deny" }])
|
|
expect(yield* service.ask(assertion())).toEqual({ id: Permission.ID.create("per_test"), effect: "deny" })
|
|
expect(yield* service.list()).toEqual([])
|
|
yield* setRules([])
|
|
expect(yield* service.ask(assertion())).toEqual({ id: Permission.ID.create("per_test"), effect: "ask" })
|
|
expect(yield* service.get(Permission.ID.create("per_test"))).toBeDefined()
|
|
}),
|
|
)
|
|
|
|
it.effect("denies when Unattended is empty and an evaluate hook downgrades allow to ask", () =>
|
|
Effect.gen(function* () {
|
|
yield* setup([{ action: "read", resource: "*", effect: "allow" }])
|
|
const hooks = yield* PluginHooks.Service
|
|
const service = yield* Permission.Service
|
|
yield* hooks.register("permission", "evaluate", (event) =>
|
|
Effect.sync(() => {
|
|
event.effect = "ask"
|
|
}),
|
|
)
|
|
const error = yield* service
|
|
.assert(assertion())
|
|
.pipe(Effect.provideService(Permission.Unattended, []), Effect.flip)
|
|
expect(error).toBeInstanceOf(Permission.BlockedError)
|
|
}),
|
|
)
|
|
|
|
it.effect("evaluates against an explicit agent", () =>
|
|
Effect.gen(function* () {
|
|
yield* setup([{ action: "read", resource: "*", effect: "allow" }])
|
|
const agents = yield* Agent.Service
|
|
yield* agents.transform((editor) =>
|
|
editor.update(Agent.ID.make("reviewer"), (agent) => {
|
|
agent.permissions.push({ action: "read", resource: "*", effect: "deny" })
|
|
}),
|
|
)
|
|
const service = yield* Permission.Service
|
|
|
|
expect(yield* service.ask(assertion())).toMatchObject({ effect: "allow" })
|
|
expect(yield* service.ask(assertion({ agent: Agent.ID.make("reviewer") }))).toMatchObject({ effect: "deny" })
|
|
yield* agents.transform((editor) =>
|
|
editor.update(Agent.ID.make("reviewer"), (agent) => {
|
|
agent.permissions = []
|
|
}),
|
|
)
|
|
expect(yield* service.ask(assertion({ agent: Agent.ID.make("reviewer") }))).toMatchObject({ effect: "ask" })
|
|
expect(yield* service.get(Permission.ID.create("per_test"))).not.toHaveProperty("agent")
|
|
}),
|
|
)
|
|
|
|
it.effect("allows and denies from explicit rules without asking", () =>
|
|
Effect.gen(function* () {
|
|
yield* setup([{ action: "read", resource: "*", effect: "allow" }])
|
|
const service = yield* Permission.Service
|
|
yield* service.assert(assertion())
|
|
yield* setRules([{ action: "read", resource: "*", effect: "deny" }])
|
|
const blocked = yield* service.assert(assertion()).pipe(Effect.flip)
|
|
expect(blocked).toBeInstanceOf(Permission.BlockedError)
|
|
expect(yield* service.list()).toEqual([])
|
|
}),
|
|
)
|
|
|
|
it.effect("checks for a deny without asking", () =>
|
|
Effect.gen(function* () {
|
|
yield* setup([])
|
|
const service = yield* Permission.Service
|
|
yield* service.assertNotDenied(assertion())
|
|
expect(yield* service.list()).toEqual([])
|
|
yield* setRules([{ action: "read", resource: "*", effect: "deny" }])
|
|
expect(yield* service.assertNotDenied(assertion()).pipe(Effect.flip)).toBeInstanceOf(Permission.BlockedError)
|
|
}),
|
|
)
|
|
|
|
it.effect("reports whether a request is already allowed without asking", () =>
|
|
Effect.gen(function* () {
|
|
yield* setup([])
|
|
const service = yield* Permission.Service
|
|
expect(yield* service.allows(assertion())).toBe(false)
|
|
expect(yield* service.list()).toEqual([])
|
|
yield* setRules([{ action: "read", resource: "*", effect: "allow" }])
|
|
expect(yield* service.allows(assertion())).toBe(true)
|
|
yield* setRules([{ action: "read", resource: "*", effect: "deny" }])
|
|
expect(yield* service.allows(assertion())).toBe(false)
|
|
}),
|
|
)
|
|
|
|
test("matches Windows rule resources against slash-normalized file access resources", () => {
|
|
const rules: Permission.Ruleset = [
|
|
{ action: "external_directory", resource: "C:\\Users\\x\\proj\\*", effect: "allow" },
|
|
]
|
|
expect(Permission.evaluate("external_directory", "C:/Users/x/proj/src/*", rules).effect).toBe("allow")
|
|
expect(Permission.evaluate("external_directory", "C:/Users/x/other/*", rules).effect).toBe("ask")
|
|
})
|
|
|
|
test("matches machine paths with the same rules as local paths", () => {
|
|
const allow = (resource: string): Permission.Ruleset => [{ action: "read", resource, effect: "allow" }]
|
|
const files = process.platform === "darwin" || process.platform === "win32"
|
|
expect(Permission.evaluate("read", "gpu:/work/a", allow("*")).effect).toBe("allow")
|
|
expect(Permission.evaluate("read", "gpu:/work/a", allow("**/work/*")).effect).toBe("allow")
|
|
expect(Permission.evaluate("read", "gpu:/work/a", allow("gpu:/work/*")).effect).toBe("allow")
|
|
expect(Permission.evaluate("read", "gpu:/work/a", allow("gpu:*")).effect).toBe("allow")
|
|
expect(Permission.evaluate("read", "cpu:/work/a", allow("gpu:/work/*")).effect).toBe("ask")
|
|
expect(Permission.evaluate("read", "/work/a", allow("gpu:/work/*")).effect).toBe("ask")
|
|
// The machine's name follows the same letter-case rule as the rest of a file rule.
|
|
expect(Permission.evaluate("read", "gpu:/work/a", allow("GPU:/work/*")).effect).toBe(files ? "allow" : "ask")
|
|
// A bare deny still reaches every machine.
|
|
expect(Permission.evaluate("edit", "gpu:/work/a", [{ action: "*", resource: "*", effect: "deny" }]).effect).toBe(
|
|
"deny",
|
|
)
|
|
// Local paths, drive letters included, match as before, and resources that are not files are untouched.
|
|
expect(Permission.evaluate("read", "/work/a", allow("*")).effect).toBe("allow")
|
|
expect(Permission.evaluate("read", "C:/work/a", allow("*")).effect).toBe("allow")
|
|
expect(Permission.evaluate("read", "C:\\work\\a", allow("C:/work/*")).effect).toBe("allow")
|
|
expect(Permission.evaluate("read", "C:/work/a", allow("**/work/*")).effect).toBe("allow")
|
|
expect(
|
|
Permission.evaluate("shell", "gpu:/bin/x", [{ action: "shell", resource: "*", effect: "allow" }]).effect,
|
|
).toBe("allow")
|
|
})
|
|
|
|
test("matches file rules without case where file systems ignore it by default", () => {
|
|
const rules: Permission.Ruleset = [
|
|
{ action: "*", resource: "*", effect: "allow" },
|
|
{ action: "edit", resource: ".opencode/*", effect: "ask" },
|
|
{ action: "read", resource: "*.env", effect: "deny" },
|
|
{ action: "shell", resource: "git push*", effect: "ask" },
|
|
]
|
|
const files = process.platform === "darwin" || process.platform === "win32"
|
|
expect(Permission.evaluate("edit", ".OPENCODE/plugins/guard.ts", rules).effect).toBe(files ? "ask" : "allow")
|
|
expect(Permission.evaluate("read", "Secrets.ENV", rules).effect).toBe(files ? "deny" : "allow")
|
|
// Commands and other resources keep their case outside Windows.
|
|
expect(Permission.evaluate("shell", "GIT PUSH origin dev", rules).effect).toBe(
|
|
process.platform === "win32" ? "ask" : "allow",
|
|
)
|
|
expect(Wildcard.match(".OPENCODE/x", ".opencode/*", true)).toBe(true)
|
|
expect(Wildcard.match(".OPENCODE/x", ".opencode/*")).toBe(process.platform === "win32")
|
|
})
|
|
|
|
for (const action of ["read", "edit", "external_directory"]) {
|
|
it.effect(`asks for machine-specific ${action} rules`, () =>
|
|
Effect.gen(function* () {
|
|
yield* setup([
|
|
...Agent.Info.default(Agent.ID.make("test")).permissions,
|
|
{ action, resource: "gpu:*", effect: "ask" },
|
|
])
|
|
const { service, fiber, request } = yield* waitForRequest({ action, resources: ["gpu:/work/a"] })
|
|
expect(request.resources).toEqual(["gpu:/work/a"])
|
|
expect(yield* service.list()).toHaveLength(1)
|
|
yield* service.reply({ requestID: request.id, reply: "once" })
|
|
yield* Fiber.join(fiber)
|
|
}),
|
|
)
|
|
|
|
it.effect(`refuses machine-specific ${action} rules`, () =>
|
|
Effect.gen(function* () {
|
|
yield* setup([
|
|
...Agent.Info.default(Agent.ID.make("test")).permissions,
|
|
{ action, resource: "gpu:*", effect: "deny" },
|
|
])
|
|
const service = yield* Permission.Service
|
|
expect(
|
|
yield* service.assert(assertion({ action, resources: ["gpu:/work/a"] })).pipe(Effect.flip),
|
|
).toBeInstanceOf(Permission.BlockedError)
|
|
expect(yield* service.list()).toEqual([])
|
|
}),
|
|
)
|
|
}
|
|
|
|
it.effect("applies default environment-file exceptions equally to local and machine paths", () =>
|
|
Effect.gen(function* () {
|
|
yield* setup(Agent.Info.default(Agent.ID.make("test")).permissions)
|
|
const service = yield* Permission.Service
|
|
for (const prefix of ["", "gpu:/work/"]) {
|
|
expect(yield* service.ask(assertion({ resources: [`${prefix}.env.production`] }))).toMatchObject({
|
|
effect: "ask",
|
|
})
|
|
yield* service.reply({ requestID: Permission.ID.create("per_test"), reply: "once" })
|
|
expect(yield* service.ask(assertion({ resources: [`${prefix}.env.example`] }))).toMatchObject({
|
|
effect: "allow",
|
|
})
|
|
}
|
|
expect(yield* service.list()).toEqual([])
|
|
}),
|
|
)
|
|
|
|
for (const [action, resource] of [
|
|
["edit", "gpu:/work/a"],
|
|
["shell", "pwd"],
|
|
])
|
|
it.effect(`preserves global ${action} asks and denies`, () =>
|
|
Effect.gen(function* () {
|
|
yield* setup([
|
|
...Agent.Info.default(Agent.ID.make("test")).permissions,
|
|
{ action, resource: "*", effect: "ask" },
|
|
])
|
|
const { service, fiber, request } = yield* waitForRequest({ action, resources: [resource] })
|
|
expect(request.action).toBe(action)
|
|
yield* service.reply({ requestID: request.id, reply: "once" })
|
|
yield* Fiber.join(fiber)
|
|
yield* setRules([{ action, resource: "*", effect: "deny" }])
|
|
expect(yield* service.assert(assertion({ action, resources: [resource] })).pipe(Effect.flip)).toBeInstanceOf(
|
|
Permission.BlockedError,
|
|
)
|
|
}),
|
|
)
|
|
|
|
it.effect("applies saved broad approvals to machine paths with normal configured deny precedence", () =>
|
|
Effect.gen(function* () {
|
|
yield* setup([{ action: "read", resource: "gpu:*", effect: "ask" }])
|
|
const saved = yield* PermissionSaved.Service
|
|
yield* saved.add({ projectID: Project.ID.global, action: "read", resources: ["*"] })
|
|
const service = yield* Permission.Service
|
|
expect(yield* service.ask(assertion({ resources: ["gpu:/work/a"] }))).toMatchObject({ effect: "allow" })
|
|
yield* setRules([{ action: "read", resource: "gpu:*", effect: "deny" }])
|
|
expect(yield* service.ask(assertion({ resources: ["gpu:/work/a"] }))).toMatchObject({ effect: "deny" })
|
|
expect(yield* service.list()).toEqual([])
|
|
}),
|
|
)
|
|
|
|
it.effect("allows managed output reads without granting external directory access", () =>
|
|
Effect.gen(function* () {
|
|
yield* setup([
|
|
{ action: "*", resource: "*", effect: "deny" },
|
|
{ action: "read", resource: "*", effect: "allow" },
|
|
])
|
|
const service = yield* Permission.Service
|
|
|
|
expect(yield* service.ask(assertion({ resources: ["tool_123"] }))).toMatchObject({ effect: "allow" })
|
|
expect(
|
|
yield* service.ask(assertion({ action: "external_directory", resources: ["/tmp/tool-output/*"] })),
|
|
).toMatchObject({ effect: "deny" })
|
|
}),
|
|
)
|
|
|
|
it.effect("uses build permissions when the Session agent is omitted", () =>
|
|
Effect.gen(function* () {
|
|
yield* setup()
|
|
const { db } = yield* Database.Service
|
|
yield* db
|
|
.update(SessionTable)
|
|
.set({ agent: null })
|
|
.where(eq(SessionTable.id, Session.ID.make("ses_test")))
|
|
.run()
|
|
.pipe(Effect.orDie)
|
|
const agents = yield* Agent.Service
|
|
yield* agents.transform((editor) =>
|
|
editor.update(Agent.ID.make("build"), (agent) => {
|
|
agent.permissions = [{ action: "custom", resource: "*", effect: "allow" }]
|
|
}),
|
|
)
|
|
|
|
const service = yield* Permission.Service
|
|
expect(yield* service.ask(assertion({ action: "custom", resources: ["*"] }))).toEqual({
|
|
id: Permission.ID.create("per_test"),
|
|
effect: "allow",
|
|
})
|
|
expect(yield* service.list()).toEqual([])
|
|
}),
|
|
)
|
|
|
|
it.effect("denies omitted-agent permissions when no primary default agent exists", () =>
|
|
Effect.gen(function* () {
|
|
yield* setup()
|
|
const { db } = yield* Database.Service
|
|
yield* db
|
|
.update(SessionTable)
|
|
.set({ agent: null })
|
|
.where(eq(SessionTable.id, Session.ID.make("ses_test")))
|
|
.run()
|
|
.pipe(Effect.orDie)
|
|
const agents = yield* Agent.Service
|
|
yield* agents.transform((editor) => {
|
|
editor.remove(Agent.ID.make("test"))
|
|
editor.remove(Agent.ID.make("build"))
|
|
})
|
|
|
|
const service = yield* Permission.Service
|
|
expect(yield* service.ask(assertion())).toEqual({ id: Permission.ID.create("per_test"), effect: "deny" })
|
|
expect(yield* service.list()).toEqual([])
|
|
}),
|
|
)
|
|
|
|
it.effect("evaluates bash with the normal configured-rule semantics", () =>
|
|
Effect.gen(function* () {
|
|
yield* setup([{ action: "*", resource: "*", effect: "allow" }])
|
|
const service = yield* Permission.Service
|
|
const bash = assertion({ action: "bash", resources: ["pwd"] })
|
|
expect(yield* service.ask(bash)).toEqual({ id: Permission.ID.create("per_test"), effect: "allow" })
|
|
|
|
yield* setRules([])
|
|
expect(yield* service.ask(bash)).toEqual({ id: Permission.ID.create("per_test"), effect: "ask" })
|
|
expect(yield* service.get(Permission.ID.create("per_test"))).toBeDefined()
|
|
}),
|
|
)
|
|
|
|
it.effect("merges session rules after agent rules and before saved approvals", () =>
|
|
Effect.gen(function* () {
|
|
yield* setup([{ action: "*", resource: "*", effect: "allow" }])
|
|
const { db } = yield* Database.Service
|
|
const service = yield* Permission.Service
|
|
const setSession = (permission: Permission.Ruleset) =>
|
|
db
|
|
.update(SessionTable)
|
|
.set({ permission })
|
|
.where(eq(SessionTable.id, Session.ID.make("ses_test")))
|
|
.run()
|
|
.pipe(Effect.orDie)
|
|
|
|
yield* setSession([{ action: "edit", resource: "/original/**", effect: "deny" }])
|
|
expect(yield* service.ask(assertion({ action: "edit", resources: ["/original/src/index.ts"] }))).toMatchObject({
|
|
effect: "deny",
|
|
})
|
|
|
|
yield* setRules([])
|
|
const saved = yield* PermissionSaved.Service
|
|
yield* saved.add({ projectID: Project.ID.global, action: "bash", resources: ["pwd"] })
|
|
yield* setSession([{ action: "bash", resource: "*", effect: "deny" }])
|
|
expect(yield* service.ask(assertion({ action: "bash", resources: ["pwd"] }))).toMatchObject({ effect: "deny" })
|
|
yield* setSession([{ action: "bash", resource: "*", effect: "ask" }])
|
|
expect(yield* service.ask(assertion({ action: "bash", resources: ["pwd"] }))).toMatchObject({ effect: "allow" })
|
|
}),
|
|
)
|
|
|
|
it.effect("uses saved bash approvals while preserving configured deny precedence", () =>
|
|
Effect.gen(function* () {
|
|
yield* setup()
|
|
const saved = yield* PermissionSaved.Service
|
|
yield* saved.add({ projectID: Project.ID.global, action: "bash", resources: ["pwd"] })
|
|
|
|
const service = yield* Permission.Service
|
|
expect(yield* service.ask(assertion({ action: "bash", resources: ["pwd"] }))).toEqual({
|
|
id: Permission.ID.create("per_test"),
|
|
effect: "allow",
|
|
})
|
|
expect(yield* service.list()).toEqual([])
|
|
|
|
yield* setRules([{ action: "bash", resource: "*", effect: "deny" }])
|
|
expect(yield* service.ask(assertion({ action: "bash", resources: ["pwd"] }))).toEqual({
|
|
id: Permission.ID.create("per_test"),
|
|
effect: "deny",
|
|
})
|
|
}),
|
|
)
|
|
|
|
it.effect("resolves an asked permission once", () =>
|
|
Effect.gen(function* () {
|
|
yield* setup()
|
|
const { service, fiber, request } = yield* waitForRequest()
|
|
expect(yield* service.list()).toEqual([request])
|
|
expect(yield* service.forSession(request.sessionID)).toEqual([request])
|
|
expect(yield* service.forSession(Session.ID.make("ses_other"))).toEqual([])
|
|
expect(yield* service.get(request.id)).toEqual(request)
|
|
yield* service.reply({ requestID: request.id, reply: "once" })
|
|
yield* Fiber.join(fiber)
|
|
expect(yield* service.list()).toEqual([])
|
|
expect(yield* service.get(request.id)).toBeUndefined()
|
|
}),
|
|
)
|
|
|
|
it.effect("shows a nested call's request on its parent's row until the scope closes", () =>
|
|
Effect.gen(function* () {
|
|
yield* setup()
|
|
const service = yield* Permission.Service
|
|
const source = { type: "tool" as const, messageID: "msg_test", id: "call_child" }
|
|
const ask = (id: string) => service.ask(assertion({ id: Permission.ID.create(id), source }))
|
|
yield* service
|
|
.nested(Tool.CallID.make("call_child"), Tool.CallID.make("call_parent"))
|
|
.pipe(Effect.andThen(ask("per_nested")), Effect.scoped)
|
|
yield* ask("per_after")
|
|
expect((yield* service.get(Permission.ID.create("per_nested")))?.source).toEqual({ ...source, id: "call_parent" })
|
|
expect((yield* service.get(Permission.ID.create("per_after")))?.source).toEqual(source)
|
|
}),
|
|
)
|
|
|
|
it.effect("drops undefined metadata values so pending requests encode as JSON", () =>
|
|
Effect.gen(function* () {
|
|
yield* setup()
|
|
// Tools copy optional model inputs straight into metadata, so omitted inputs arrive as undefined values.
|
|
const { service, request } = yield* waitForRequest({
|
|
action: "glob",
|
|
resources: ["/project"],
|
|
metadata: {
|
|
root: "/project",
|
|
path: undefined,
|
|
hidden: undefined,
|
|
limit: undefined,
|
|
trigger: { type: "at", at: "2026-11-25T12:00:00.000Z", tz: undefined },
|
|
},
|
|
})
|
|
expect(request.metadata).toStrictEqual({
|
|
root: "/project",
|
|
trigger: { type: "at", at: "2026-11-25T12:00:00.000Z" },
|
|
})
|
|
expect(yield* service.forSession(request.sessionID)).toEqual([request])
|
|
// HttpApi encodes JSON success bodies through Schema.toCodecJson, which rejects undefined values in Unknown.
|
|
const encode = Schema.encodeEffect(Schema.toCodecJson(Schema.Struct({ data: Schema.Array(Permission.Request) })))
|
|
expect(yield* encode({ data: yield* service.forSession(request.sessionID) })).toEqual({
|
|
data: [
|
|
{
|
|
id: request.id,
|
|
sessionID: request.sessionID,
|
|
action: "glob",
|
|
resources: ["/project"],
|
|
metadata: {
|
|
root: "/project",
|
|
trigger: { type: "at", at: "2026-11-25T12:00:00.000Z" },
|
|
},
|
|
},
|
|
],
|
|
})
|
|
}),
|
|
)
|
|
|
|
it.effect("defects when an asked permission is declined", () =>
|
|
Effect.gen(function* () {
|
|
yield* setup()
|
|
const { service, fiber, request } = yield* waitForRequest()
|
|
yield* service.reply({ requestID: request.id, reply: "reject" })
|
|
const exit = yield* Fiber.await(fiber)
|
|
|
|
expect(exit._tag).toBe("Failure")
|
|
if (exit._tag === "Failure")
|
|
expect(
|
|
exit.cause.reasons.some(
|
|
(reason) => Cause.isDieReason(reason) && reason.defect instanceof Permission.DeclinedError,
|
|
),
|
|
).toBe(true)
|
|
expect(yield* service.list()).toEqual([])
|
|
}),
|
|
)
|
|
|
|
it.effect("rejects sibling requests in the same step and leaves another step's request pending", () =>
|
|
Effect.gen(function* () {
|
|
yield* setup()
|
|
const service = yield* Permission.Service
|
|
const ask = (call: string, messageID: string) =>
|
|
service.ask(
|
|
assertion({
|
|
id: Permission.ID.create(`per_${call}`),
|
|
source: { type: "tool", messageID, id: `call_${call}` },
|
|
}),
|
|
)
|
|
const first = yield* ask("first", "msg_one")
|
|
yield* ask("sibling", "msg_one")
|
|
const other = yield* ask("other", "msg_two")
|
|
yield* service.reply({ requestID: first.id, reply: "reject" })
|
|
expect((yield* service.list()).map((request) => request.id)).toEqual([other.id])
|
|
}),
|
|
)
|
|
|
|
it.effect("stores and removes saved resources for a project", () =>
|
|
Effect.gen(function* () {
|
|
yield* setup()
|
|
const service = yield* Permission.Service
|
|
const asked = yield* Deferred.make<Permission.Request>()
|
|
const bus = yield* Bus.Service
|
|
const unsubscribe = yield* bus.listen((event) =>
|
|
event.type === Permission.Event.Asked.type
|
|
? Deferred.succeed(asked, event.data as Permission.Request).pipe(Effect.asVoid)
|
|
: Effect.void,
|
|
)
|
|
yield* Effect.addFinalizer(() => unsubscribe)
|
|
const fiber = yield* service.assert(assertion({ save: ["src/*"] })).pipe(Effect.forkScoped)
|
|
const request = yield* Deferred.await(asked)
|
|
yield* service.reply({ requestID: request.id, reply: "always" })
|
|
yield* Fiber.join(fiber)
|
|
|
|
const { db } = yield* Database.Service
|
|
expect(
|
|
yield* db.select().from(PermissionTable).where(eq(PermissionTable.project_id, Project.ID.global)).all(),
|
|
).toMatchObject([{ action: "read", resource: "src/*" }])
|
|
const saved = yield* PermissionSaved.Service
|
|
const id = (yield* saved.list())[0]!.id
|
|
expect(yield* saved.list()).toMatchObject([
|
|
{ id, projectID: Project.ID.global, action: "read", resource: "src/*" },
|
|
])
|
|
yield* service.assert(assertion({ id: Permission.ID.create("per_next"), resources: ["src/next.ts"] }))
|
|
yield* saved.remove(id)
|
|
expect(yield* saved.list()).toEqual([])
|
|
}),
|
|
)
|
|
|
|
it.effect("edits saved approvals and enforces the edited rule", () =>
|
|
Effect.gen(function* () {
|
|
yield* setup()
|
|
const saved = yield* PermissionSaved.Service
|
|
const service = yield* Permission.Service
|
|
yield* saved.add({ projectID: Project.ID.global, action: "read", resources: ["src/*", "docs/*"] })
|
|
const src = (yield* saved.list()).find((item) => item.resource === "src/*")
|
|
|
|
expect(yield* saved.update({ id: src!.id, resource: "src/allowed.ts" })).toMatchObject({
|
|
id: src!.id,
|
|
projectID: Project.ID.global,
|
|
action: "read",
|
|
resource: "src/allowed.ts",
|
|
})
|
|
expect(
|
|
yield* service.ask(assertion({ id: Permission.ID.create("per_allowed"), resources: ["src/allowed.ts"] })),
|
|
).toMatchObject({ effect: "allow" })
|
|
expect(
|
|
yield* service.ask(assertion({ id: Permission.ID.create("per_other"), resources: ["src/other.ts"] })),
|
|
).toMatchObject({ effect: "ask" })
|
|
|
|
expect(yield* saved.update({ id: src!.id, resource: "docs/*" }).pipe(Effect.flip)).toMatchObject({
|
|
_tag: "PermissionSaved.ConflictError",
|
|
id: src!.id,
|
|
resource: "docs/*",
|
|
})
|
|
expect(
|
|
yield* saved.update({ id: PermissionSaved.ID.make("psv_missing"), action: "edit" }).pipe(Effect.flip),
|
|
).toMatchObject({ _tag: "PermissionSaved.NotFoundError" })
|
|
}),
|
|
)
|
|
|
|
for (const guard of ["configured deny", "missing Session"] as const) {
|
|
it.effect(`skips pending auto-approval after always for ${guard}`, () =>
|
|
Effect.gen(function* () {
|
|
yield* setup()
|
|
yield* setup([], Session.ID.make("ses_other"))
|
|
const agents = yield* Agent.Service
|
|
yield* agents.transform((editor) =>
|
|
editor.update(Agent.ID.make("reviewer"), (agent) => {
|
|
agent.permissions = []
|
|
}),
|
|
)
|
|
const selected = yield* waitForRequest({ save: ["src/*"] })
|
|
const other = yield* waitForRequest({
|
|
id: Permission.ID.create("per_other"),
|
|
sessionID: Session.ID.make("ses_other"),
|
|
agent: Agent.ID.make("reviewer"),
|
|
})
|
|
if (guard === "configured deny") {
|
|
yield* agents.transform((editor) =>
|
|
editor.update(Agent.ID.make("reviewer"), (agent) => {
|
|
agent.permissions = [{ action: "read", resource: "*", effect: "deny" }]
|
|
}),
|
|
)
|
|
}
|
|
if (guard === "missing Session") {
|
|
const { db } = yield* Database.Service
|
|
yield* db.delete(SessionTable).where(eq(SessionTable.id, other.request.sessionID)).run().pipe(Effect.orDie)
|
|
}
|
|
yield* selected.service.reply({ requestID: selected.request.id, reply: "always" })
|
|
yield* Fiber.join(selected.fiber)
|
|
expect(yield* selected.service.list()).toEqual([other.request])
|
|
expect(other.fiber.pollUnsafe()).toBeUndefined()
|
|
yield* Fiber.interrupt(other.fiber)
|
|
expect(yield* selected.service.list()).toEqual([])
|
|
}),
|
|
)
|
|
}
|
|
})
|
|
|
|
describe("shell scanner permission impact", () => {
|
|
// Fixed cases require matching outcomes; remaining differences are investigation snapshots, not contracts.
|
|
// These service-level cases all have command resources; tool tests cover skipped checks and directories.
|
|
// Outcome pairs are [legacy, native].
|
|
for (const fixture of [
|
|
{
|
|
name: "timed command preserves wrapper approvals",
|
|
shell: "bash",
|
|
command: "time -p git status",
|
|
approved: ["time *"],
|
|
exact: ["time -p git status"],
|
|
denied: "time -p git status",
|
|
savedEffect: ["allow", "allow"],
|
|
exactEffect: ["allow", "allow"],
|
|
deniedEffect: ["deny", "deny"],
|
|
},
|
|
{
|
|
name: "coprocess command preserves wrapper approvals",
|
|
shell: "bash",
|
|
command: "coproc git status",
|
|
approved: ["coproc *"],
|
|
exact: ["coproc git status"],
|
|
denied: "coproc git status",
|
|
savedEffect: ["allow", "allow"],
|
|
exactEffect: ["allow", "allow"],
|
|
deniedEffect: ["deny", "deny"],
|
|
},
|
|
{
|
|
name: "declarations and unset",
|
|
shell: "bash",
|
|
command: "export X=value; unset X; git status",
|
|
approved: ["git status *"],
|
|
exact: ["git status"],
|
|
denied: "export *",
|
|
savedEffect: ["allow", "allow"],
|
|
exactEffect: ["allow", "allow"],
|
|
deniedEffect: ["allow", "allow"],
|
|
},
|
|
{
|
|
name: "export with an approved command substitution",
|
|
shell: "bash",
|
|
command: "export VERSION=$(git describe --tags); npm run build",
|
|
approved: ["git describe *", "npm run build *"],
|
|
exact: ["git describe --tags", "npm run build"],
|
|
denied: "export *",
|
|
savedEffect: ["allow", "allow"],
|
|
exactEffect: ["allow", "allow"],
|
|
deniedEffect: ["allow", "allow"],
|
|
},
|
|
{
|
|
name: "export retains checks on the command substitution",
|
|
shell: "bash",
|
|
command: "export VERSION=$(git describe --tags); npm run build",
|
|
approved: ["git describe *", "npm run build *"],
|
|
exact: ["git describe --tags", "npm run build"],
|
|
denied: "git describe *",
|
|
savedEffect: ["allow", "allow"],
|
|
exactEffect: ["allow", "allow"],
|
|
deniedEffect: ["deny", "deny"],
|
|
},
|
|
{
|
|
name: "redirect after a conditional list",
|
|
shell: "bash",
|
|
command: "printf ok && git status > output",
|
|
approved: ["printf *", "git status *"],
|
|
exact: ["printf ok", "git status"],
|
|
denied: "git status *",
|
|
savedEffect: ["allow", "allow"],
|
|
exactEffect: ["allow", "ask"],
|
|
deniedEffect: ["deny", "deny"],
|
|
},
|
|
{
|
|
name: "redirect after a pipeline",
|
|
shell: "bash",
|
|
command: "printf ok | cat < input > output",
|
|
approved: ["printf *", "cat *"],
|
|
exact: ["printf ok", "cat"],
|
|
denied: "cat *",
|
|
savedEffect: ["allow", "allow"],
|
|
exactEffect: ["allow", "ask"],
|
|
deniedEffect: ["deny", "deny"],
|
|
},
|
|
{
|
|
name: "assignment redirect followed by a command",
|
|
shell: "bash",
|
|
command: "FOO=bar > output; printf done",
|
|
approved: ["printf *"],
|
|
exact: ["printf done"],
|
|
denied: "FOO=bar > output",
|
|
savedEffect: ["ask", "ask"],
|
|
exactEffect: ["ask", "ask"],
|
|
deniedEffect: ["deny", "deny"],
|
|
},
|
|
{
|
|
name: "assignment redirect with an approved command substitution",
|
|
shell: "bash",
|
|
command: "VERSION=$(git describe --tags) > build/version.txt",
|
|
approved: ["git describe *"],
|
|
exact: ["git describe --tags"],
|
|
denied: "VERSION=$(git describe --tags) > build/version.txt",
|
|
savedEffect: ["ask", "ask"],
|
|
exactEffect: ["ask", "ask"],
|
|
deniedEffect: ["deny", "deny"],
|
|
},
|
|
{
|
|
name: "substitution in a saved prefix",
|
|
shell: "bash",
|
|
command: "git $(printf diff) --stat",
|
|
approved: ["git *", "printf *"],
|
|
exact: ["git $(printf diff) --stat", "printf diff"],
|
|
denied: "git $(printf diff) --stat",
|
|
savedEffect: ["allow", "allow"],
|
|
exactEffect: ["allow", "allow"],
|
|
deniedEffect: ["deny", "deny"],
|
|
},
|
|
{
|
|
name: "standalone PowerShell scriptblock caller",
|
|
shell: "pwsh",
|
|
command: "ForEach-Object { Write-Output value }",
|
|
approved: ["Write-Output *"],
|
|
exact: ["Write-Output value"],
|
|
denied: "ForEach-Object *",
|
|
savedEffect: ["allow", "allow"],
|
|
exactEffect: ["allow", "allow"],
|
|
deniedEffect: ["allow", "allow"],
|
|
},
|
|
{
|
|
name: "tab-separated PowerShell command",
|
|
shell: "pwsh",
|
|
command: "git\tstatus; Write-Output done",
|
|
approved: ["git status *", "Write-Output *"],
|
|
exact: ["git status", "Write-Output done"],
|
|
denied: "git\tstatus",
|
|
savedEffect: ["allow", "ask"],
|
|
exactEffect: ["allow", "ask"],
|
|
deniedEffect: ["allow", "deny"],
|
|
},
|
|
{
|
|
name: "PowerShell equals-joined argument",
|
|
shell: "pwsh",
|
|
command: "git --work-tree=src status",
|
|
approved: ["git --work-tree *"],
|
|
exact: ["git --work-tree"],
|
|
denied: "git --work-tree",
|
|
savedEffect: ["allow", "ask"],
|
|
exactEffect: ["allow", "ask"],
|
|
deniedEffect: ["deny", "allow"],
|
|
},
|
|
{
|
|
name: "trailing redirect after list operator",
|
|
shell: "bash",
|
|
command: "true && cat > secret",
|
|
approved: ["true *", "cat *"],
|
|
exact: ["true", "cat"],
|
|
denied: "* > secret*",
|
|
savedEffect: ["allow", "allow"],
|
|
exactEffect: ["allow", "ask"],
|
|
deniedEffect: ["allow", "deny"],
|
|
},
|
|
{
|
|
name: "commandless redirect write",
|
|
shell: "zsh",
|
|
command: ">> ~/.zshrc <<< 'x'",
|
|
approved: [">> *"],
|
|
exact: [">> ~/.zshrc <<< 'x'"],
|
|
denied: ">> *",
|
|
savedEffect: ["allow", "allow"],
|
|
exactEffect: ["allow", "allow"],
|
|
deniedEffect: ["deny", "deny"],
|
|
},
|
|
{
|
|
name: "PowerShell .NET method invocation",
|
|
shell: "pwsh",
|
|
command: '[IO.File]::Delete("C:\\victim")',
|
|
approved: ["[IO.File]::Delete(*"],
|
|
exact: ['[IO.File]::Delete("C:\\victim")'],
|
|
denied: "*Delete(*",
|
|
savedEffect: ["allow", "allow"],
|
|
exactEffect: ["allow", "allow"],
|
|
deniedEffect: ["deny", "deny"],
|
|
},
|
|
] as const) {
|
|
for (const scenario of [
|
|
{ name: "no approval", saved: [], rules: [], expected: ["ask", "ask"] },
|
|
{ name: "saved wildcard", saved: ["*"], rules: [], expected: ["allow", "allow"] },
|
|
{ name: "saved command approvals", saved: fixture.approved, rules: [], expected: fixture.savedEffect },
|
|
{
|
|
name: "exact configured approvals",
|
|
saved: [],
|
|
rules: fixture.exact.map((resource): Permission.Rule => ({ action: "shell", resource, effect: "allow" })),
|
|
expected: fixture.exactEffect,
|
|
},
|
|
{
|
|
name: "exact saved approvals",
|
|
saved: fixture.exact,
|
|
rules: [],
|
|
expected: fixture.exactEffect,
|
|
},
|
|
{
|
|
name: "configured deny despite saved wildcard",
|
|
saved: ["*"],
|
|
rules: [{ action: "shell", resource: fixture.denied, effect: "deny" }] satisfies Permission.Ruleset,
|
|
expected: fixture.deniedEffect,
|
|
},
|
|
] as const) {
|
|
it.live(`${fixture.name}: ${scenario.name}`, () =>
|
|
Effect.gen(function* () {
|
|
yield* setup(scenario.rules)
|
|
const saved = yield* PermissionSaved.Service
|
|
yield* saved.add({ projectID: Project.ID.global, action: "shell", resources: scenario.saved })
|
|
const service = yield* Permission.Service
|
|
|
|
const parsed = yield* ShellParse.scan(fixture.command, fixture.shell, "/project")
|
|
expect(parsed.commands.length).toBeGreaterThan(0)
|
|
expect(parsed.directories).toEqual([])
|
|
const result = yield* service.ask(
|
|
assertion({
|
|
action: "shell",
|
|
resources: parsed.commands.map((command) => command.resource),
|
|
save: parsed.commands.map((command) => command.save),
|
|
}),
|
|
)
|
|
expect(result.effect).toBe(scenario.expected[1])
|
|
const pending = yield* service.list()
|
|
expect(pending).toHaveLength(result.effect === "ask" ? 1 : 0)
|
|
if (result.effect === "ask") {
|
|
expect(pending[0]?.resources).toEqual(parsed.commands.map((command) => command.resource))
|
|
expect(pending[0]?.save).toEqual(parsed.commands.map((command) => command.save))
|
|
yield* service.reply({ requestID: result.id, reply: "once" })
|
|
expect(yield* service.list()).toEqual([])
|
|
}
|
|
}),
|
|
)
|
|
}
|
|
}
|
|
|
|
// Grant/repeat rows select the granting parser; repeat columns select the parser used afterwards.
|
|
for (const fixture of [
|
|
{
|
|
name: "numeric npm script prefix",
|
|
shell: "bash",
|
|
command: "npm run 123",
|
|
grants: [["npm run *"], ["npm run 123 *"]],
|
|
repeat: [
|
|
["allow", "allow"],
|
|
["allow", "allow"],
|
|
],
|
|
next: "npm run build",
|
|
nextEffect: ["allow", "ask"],
|
|
},
|
|
{
|
|
name: "numeric AWS option prefix",
|
|
shell: "bash",
|
|
command: "aws --cli-read-timeout 60 s3 ls",
|
|
grants: [["aws --cli-read-timeout s3 *"], ["aws --cli-read-timeout 60 *"]],
|
|
repeat: [
|
|
["ask", "ask"],
|
|
["allow", "allow"],
|
|
],
|
|
next: "aws --cli-read-timeout 60 ec2 describe-instances",
|
|
nextEffect: ["ask", "allow"],
|
|
},
|
|
{
|
|
name: "substitution prefix",
|
|
shell: "bash",
|
|
command: "git $(printf diff) --stat",
|
|
grants: [
|
|
["git --stat *", "printf *"],
|
|
["git $(printf diff) *", "printf *"],
|
|
],
|
|
repeat: [
|
|
["ask", "ask"],
|
|
["allow", "allow"],
|
|
],
|
|
next: "git --stat",
|
|
nextEffect: ["allow", "ask"],
|
|
},
|
|
{
|
|
name: "redirect prefix",
|
|
shell: "bash",
|
|
command: "printf ok && git status > output",
|
|
grants: [
|
|
["printf *", "git status *"],
|
|
["printf *", "git status *"],
|
|
],
|
|
repeat: [
|
|
["allow", "allow"],
|
|
["allow", "allow"],
|
|
],
|
|
next: "git status --short",
|
|
nextEffect: ["allow", "allow"],
|
|
},
|
|
{
|
|
name: "assignment redirect prefix",
|
|
shell: "bash",
|
|
command: "FOO=bar > output; printf done",
|
|
grants: [["printf *"], ["FOO=bar > *", "printf *"]],
|
|
repeat: [
|
|
["ask", "allow"],
|
|
["ask", "allow"],
|
|
],
|
|
next: "FOO=bar rm -rf /",
|
|
nextEffect: ["ask", "ask"],
|
|
},
|
|
{
|
|
name: "PowerShell method prefix",
|
|
shell: "pwsh",
|
|
command: '[IO.File]::Delete("C:\\first")',
|
|
grants: [["[IO.File]::Delete(*"], ["[IO.File]::Delete(*"]],
|
|
repeat: [
|
|
["allow", "allow"],
|
|
["allow", "allow"],
|
|
],
|
|
next: '[IO.File]::WriteAllText("C:\\first", "x")',
|
|
nextEffect: ["ask", "ask"],
|
|
},
|
|
{
|
|
name: "PowerShell tab prefix",
|
|
shell: "pwsh",
|
|
command: "git\tstatus; Write-Output done",
|
|
grants: [["Write-Output *"], ["git\tstatus *", "Write-Output *"]],
|
|
repeat: [
|
|
["allow", "ask"],
|
|
["allow", "allow"],
|
|
],
|
|
next: "git status",
|
|
nextEffect: ["ask", "ask"],
|
|
},
|
|
] as const) {
|
|
it.live(`${fixture.name}: always allow covers repeat execution and narrows prefix scope`, () =>
|
|
Effect.gen(function* () {
|
|
yield* setup()
|
|
const service = yield* Permission.Service
|
|
const saved = yield* PermissionSaved.Service
|
|
const parsed = yield* ShellParse.scan(fixture.command, fixture.shell, "/project")
|
|
const first = yield* service.ask(
|
|
assertion({
|
|
action: "shell",
|
|
resources: parsed.commands.map((command) => command.resource),
|
|
save: parsed.commands.map((command) => command.save),
|
|
}),
|
|
)
|
|
expect(first.effect).toBe("ask")
|
|
expect(yield* service.list()).toHaveLength(1)
|
|
yield* service.reply({ requestID: first.id, reply: "always" })
|
|
expect(yield* service.list()).toEqual([])
|
|
expect((yield* saved.list({ projectID: Project.ID.global })).map((rule) => rule.resource).sort()).toEqual(
|
|
[...fixture.grants[1]].sort(),
|
|
)
|
|
|
|
for (const command of [fixture.command, fixture.next]) {
|
|
const parsed = yield* ShellParse.scan(command, fixture.shell, "/project")
|
|
const result = yield* service.ask(
|
|
assertion({
|
|
action: "shell",
|
|
resources: parsed.commands.map((command) => command.resource),
|
|
save: parsed.commands.map((command) => command.save),
|
|
}),
|
|
)
|
|
expect(result.effect, command).toBe(command === fixture.next ? fixture.nextEffect[1] : fixture.repeat[1]?.[1])
|
|
if (result.effect === "ask") yield* service.reply({ requestID: result.id, reply: "once" })
|
|
expect(yield* service.list()).toEqual([])
|
|
}
|
|
}),
|
|
)
|
|
}
|
|
})
|