| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174 |
- import { PermissionV1 } from "@kirincode-ai/core/v1/permission"
- import { test, expect } from "bun:test"
- import os from "os"
- import { Cause, Deferred, Effect, Exit, Fiber, Layer } from "effect"
- import { EventV2Bridge } from "../../src/event-v2-bridge"
- import { CrossSpawnSpawner } from "@kirincode-ai/core/cross-spawn-spawner"
- import { Permission } from "../../src/permission"
- import { InstanceBootstrap } from "../../src/project/bootstrap"
- import { InstanceStore } from "../../src/project/instance-store"
- import { TestInstance, tmpdirScoped } from "../fixture/fixture"
- import { testEffect } from "../lib/effect"
- import { MessageID, SessionID } from "../../src/session/schema"
- import { AppNodeBuilder } from "@kirincode-ai/core/effect/app-node-builder"
- import { LayerNode } from "@kirincode-ai/core/effect/layer-node"
- const noopBootstrap = Layer.succeed(InstanceBootstrap.Service, InstanceBootstrap.Service.of({ run: Effect.void }))
- const env = AppNodeBuilder.build(
- LayerNode.group([Permission.node, EventV2Bridge.node, CrossSpawnSpawner.node, InstanceStore.node]),
- [[InstanceStore.bootstrapNode, noopBootstrap]],
- )
- const it = testEffect(env)
- const rejectAll = (message?: string) =>
- Effect.gen(function* () {
- const permission = yield* Permission.Service
- for (const req of yield* permission.list()) {
- yield* permission.reply({
- requestID: req.id,
- reply: "reject",
- message,
- })
- }
- })
- const waitForPending = (count: number) =>
- Effect.gen(function* () {
- const permission = yield* Permission.Service
- return yield* Effect.gen(function* () {
- while (true) {
- const list = yield* permission.list()
- if (list.length === count) return list
- yield* Effect.sleep("10 millis")
- }
- }).pipe(
- Effect.timeoutOrElse({
- duration: "1 second",
- orElse: () => Effect.fail(new Error(`timed out waiting for ${count} pending permission request(s)`)),
- }),
- )
- })
- const fail = <A, E, R>(self: Effect.Effect<A, E, R>) =>
- Effect.gen(function* () {
- const exit = yield* self.pipe(Effect.exit)
- if (Exit.isFailure(exit)) return Cause.squash(exit.cause)
- throw new Error("expected permission effect to fail")
- })
- const ask = (input: Parameters<Permission.Interface["ask"]>[0]) =>
- Effect.gen(function* () {
- const permission = yield* Permission.Service
- return yield* permission.ask(input)
- })
- const reply = (input: Parameters<Permission.Interface["reply"]>[0]) =>
- Effect.gen(function* () {
- const permission = yield* Permission.Service
- return yield* permission.reply(input)
- })
- const list = () =>
- Effect.gen(function* () {
- const permission = yield* Permission.Service
- return yield* permission.list()
- })
- // fromConfig tests
- test("fromConfig - string value becomes wildcard rule", () => {
- const result = Permission.fromConfig({ bash: "allow" })
- expect(result).toEqual([{ permission: "bash", pattern: "*", action: "allow" }])
- })
- test("fromConfig - object value converts to rules array", () => {
- const result = Permission.fromConfig({ bash: { "*": "allow", rm: "deny" } })
- expect(result).toEqual([
- { permission: "bash", pattern: "*", action: "allow" },
- { permission: "bash", pattern: "rm", action: "deny" },
- ])
- })
- test("fromConfig - mixed string and object values", () => {
- const result = Permission.fromConfig({
- bash: { "*": "allow", rm: "deny" },
- edit: "allow",
- webfetch: "ask",
- })
- expect(result).toEqual([
- { permission: "bash", pattern: "*", action: "allow" },
- { permission: "bash", pattern: "rm", action: "deny" },
- { permission: "edit", pattern: "*", action: "allow" },
- { permission: "webfetch", pattern: "*", action: "ask" },
- ])
- })
- test("fromConfig - empty object", () => {
- const result = Permission.fromConfig({})
- expect(result).toEqual([])
- })
- test("fromConfig - expands tilde to home directory", () => {
- const result = Permission.fromConfig({ external_directory: { "~/projects/*": "allow" } })
- expect(result).toEqual([{ permission: "external_directory", pattern: `${os.homedir()}/projects/*`, action: "allow" }])
- })
- test("fromConfig - expands $HOME to home directory", () => {
- const result = Permission.fromConfig({ external_directory: { "$HOME/projects/*": "allow" } })
- expect(result).toEqual([{ permission: "external_directory", pattern: `${os.homedir()}/projects/*`, action: "allow" }])
- })
- test("fromConfig - expands $HOME without trailing slash", () => {
- const result = Permission.fromConfig({ external_directory: { $HOME: "allow" } })
- expect(result).toEqual([{ permission: "external_directory", pattern: os.homedir(), action: "allow" }])
- })
- test("fromConfig - does not expand tilde in middle of path", () => {
- const result = Permission.fromConfig({ external_directory: { "/some/~/path": "allow" } })
- expect(result).toEqual([{ permission: "external_directory", pattern: "/some/~/path", action: "allow" }])
- })
- // Permission precedence follows config insertion order. `evaluate()` uses the
- // last matching rule, so later config entries intentionally override earlier
- // entries even when a wildcard appears after a specific permission.
- test("fromConfig - preserves top-level config key order", () => {
- const wildcardFirst = Permission.fromConfig({ "*": "deny", bash: "allow" })
- const specificFirst = Permission.fromConfig({ bash: "allow", "*": "deny" })
- expect(wildcardFirst.map((r) => r.permission)).toEqual(["*", "bash"])
- expect(specificFirst.map((r) => r.permission)).toEqual(["bash", "*"])
- expect(Permission.evaluate("bash", "ls", wildcardFirst).action).toBe("allow")
- expect(Permission.evaluate("bash", "ls", specificFirst).action).toBe("deny")
- })
- test("fromConfig - wildcard acts as fallback when it appears before specifics", () => {
- const ruleset = Permission.fromConfig({ "*": "ask", bash: "allow" })
- expect(Permission.evaluate("edit", "foo.ts", ruleset).action).toBe("ask")
- expect(Permission.evaluate("bash", "ls", ruleset).action).toBe("allow")
- })
- test("fromConfig - top-level ordering is not sorted by wildcard specificity", () => {
- const ruleset = Permission.fromConfig({
- bash: "allow",
- "*": "ask",
- edit: "deny",
- "mcp_*": "allow",
- })
- expect(ruleset.map((r) => r.permission)).toEqual(["bash", "*", "edit", "mcp_*"])
- })
- test("fromConfig - sub-pattern insertion order inside a tool key is preserved", () => {
- const ruleset = Permission.fromConfig({ bash: { "*": "deny", "git *": "allow" } })
- expect(ruleset.map((r) => r.pattern)).toEqual(["*", "git *"])
- expect(Permission.evaluate("bash", "rm foo", ruleset).action).toBe("deny")
- expect(Permission.evaluate("bash", "git status", ruleset).action).toBe("allow")
- })
- test("fromConfig - documented fallback-first example", () => {
- const ruleset = Permission.fromConfig({ "*": "ask", bash: "allow", edit: "deny" })
- expect(Permission.evaluate("bash", "ls", ruleset).action).toBe("allow")
- expect(Permission.evaluate("edit", "foo.ts", ruleset).action).toBe("deny")
- expect(Permission.evaluate("read", "foo.ts", ruleset).action).toBe("ask")
- })
- test("fromConfig - expands exact tilde to home directory", () => {
- const result = Permission.fromConfig({ external_directory: { "~": "allow" } })
- expect(result).toEqual([{ permission: "external_directory", pattern: os.homedir(), action: "allow" }])
- })
- test("evaluate - matches expanded tilde pattern", () => {
- const ruleset = Permission.fromConfig({ external_directory: { "~/projects/*": "allow" } })
- const result = Permission.evaluate("external_directory", `${os.homedir()}/projects/file.txt`, ruleset)
- expect(result.action).toBe("allow")
- })
- test("evaluate - matches expanded $HOME pattern", () => {
- const ruleset = Permission.fromConfig({ external_directory: { "$HOME/projects/*": "allow" } })
- const result = Permission.evaluate("external_directory", `${os.homedir()}/projects/file.txt`, ruleset)
- expect(result.action).toBe("allow")
- })
- // merge tests
- test("merge - simple concatenation", () => {
- const result = Permission.merge(
- [{ permission: "bash", pattern: "*", action: "allow" }],
- [{ permission: "bash", pattern: "*", action: "deny" }],
- )
- expect(result).toEqual([
- { permission: "bash", pattern: "*", action: "allow" },
- { permission: "bash", pattern: "*", action: "deny" },
- ])
- })
- test("merge - adds new permission", () => {
- const result = Permission.merge(
- [{ permission: "bash", pattern: "*", action: "allow" }],
- [{ permission: "edit", pattern: "*", action: "deny" }],
- )
- expect(result).toEqual([
- { permission: "bash", pattern: "*", action: "allow" },
- { permission: "edit", pattern: "*", action: "deny" },
- ])
- })
- test("merge - concatenates rules for same permission", () => {
- const result = Permission.merge(
- [{ permission: "bash", pattern: "foo", action: "ask" }],
- [{ permission: "bash", pattern: "*", action: "deny" }],
- )
- expect(result).toEqual([
- { permission: "bash", pattern: "foo", action: "ask" },
- { permission: "bash", pattern: "*", action: "deny" },
- ])
- })
- test("merge - multiple rulesets", () => {
- const result = Permission.merge(
- [{ permission: "bash", pattern: "*", action: "allow" }],
- [{ permission: "bash", pattern: "rm", action: "ask" }],
- [{ permission: "edit", pattern: "*", action: "allow" }],
- )
- expect(result).toEqual([
- { permission: "bash", pattern: "*", action: "allow" },
- { permission: "bash", pattern: "rm", action: "ask" },
- { permission: "edit", pattern: "*", action: "allow" },
- ])
- })
- test("merge - empty ruleset does nothing", () => {
- const result = Permission.merge([{ permission: "bash", pattern: "*", action: "allow" }], [])
- expect(result).toEqual([{ permission: "bash", pattern: "*", action: "allow" }])
- })
- test("merge - preserves rule order", () => {
- const result = Permission.merge(
- [
- { permission: "edit", pattern: "src/*", action: "allow" },
- { permission: "edit", pattern: "src/secret/*", action: "deny" },
- ],
- [{ permission: "edit", pattern: "src/secret/ok.ts", action: "allow" }],
- )
- expect(result).toEqual([
- { permission: "edit", pattern: "src/*", action: "allow" },
- { permission: "edit", pattern: "src/secret/*", action: "deny" },
- { permission: "edit", pattern: "src/secret/ok.ts", action: "allow" },
- ])
- })
- test("merge - config permission overrides default ask", () => {
- const defaults: PermissionV1.Ruleset = [{ permission: "*", pattern: "*", action: "ask" }]
- const config: PermissionV1.Ruleset = [{ permission: "bash", pattern: "*", action: "allow" }]
- const merged = Permission.merge(defaults, config)
- expect(Permission.evaluate("bash", "ls", merged).action).toBe("allow")
- expect(Permission.evaluate("edit", "foo.ts", merged).action).toBe("ask")
- })
- test("merge - config ask overrides default allow", () => {
- const defaults: PermissionV1.Ruleset = [{ permission: "bash", pattern: "*", action: "allow" }]
- const config: PermissionV1.Ruleset = [{ permission: "bash", pattern: "*", action: "ask" }]
- const merged = Permission.merge(defaults, config)
- expect(Permission.evaluate("bash", "ls", merged).action).toBe("ask")
- })
- // evaluate tests
- test("evaluate - exact pattern match", () => {
- const result = Permission.evaluate("bash", "rm", [{ permission: "bash", pattern: "rm", action: "deny" }])
- expect(result.action).toBe("deny")
- })
- test("evaluate - wildcard pattern match", () => {
- const result = Permission.evaluate("bash", "rm", [{ permission: "bash", pattern: "*", action: "allow" }])
- expect(result.action).toBe("allow")
- })
- test("evaluate - last matching rule wins", () => {
- const result = Permission.evaluate("bash", "rm", [
- { permission: "bash", pattern: "*", action: "allow" },
- { permission: "bash", pattern: "rm", action: "deny" },
- ])
- expect(result.action).toBe("deny")
- })
- test("evaluate - last matching rule wins (wildcard after specific)", () => {
- const result = Permission.evaluate("bash", "rm", [
- { permission: "bash", pattern: "rm", action: "deny" },
- { permission: "bash", pattern: "*", action: "allow" },
- ])
- expect(result.action).toBe("allow")
- })
- test("evaluate - glob pattern match", () => {
- const result = Permission.evaluate("edit", "src/foo.ts", [{ permission: "edit", pattern: "src/*", action: "allow" }])
- expect(result.action).toBe("allow")
- })
- test("evaluate - last matching glob wins", () => {
- const result = Permission.evaluate("edit", "src/components/Button.tsx", [
- { permission: "edit", pattern: "src/*", action: "deny" },
- { permission: "edit", pattern: "src/components/*", action: "allow" },
- ])
- expect(result.action).toBe("allow")
- })
- test("evaluate - order matters for specificity", () => {
- const result = Permission.evaluate("edit", "src/components/Button.tsx", [
- { permission: "edit", pattern: "src/components/*", action: "allow" },
- { permission: "edit", pattern: "src/*", action: "deny" },
- ])
- expect(result.action).toBe("deny")
- })
- test("evaluate - unknown permission returns ask", () => {
- const result = Permission.evaluate("unknown_tool", "anything", [
- { permission: "bash", pattern: "*", action: "allow" },
- ])
- expect(result.action).toBe("ask")
- })
- test("evaluate - empty ruleset returns ask", () => {
- const result = Permission.evaluate("bash", "rm", [])
- expect(result.action).toBe("ask")
- })
- test("evaluate - no matching pattern returns ask", () => {
- const result = Permission.evaluate("edit", "etc/passwd", [{ permission: "edit", pattern: "src/*", action: "allow" }])
- expect(result.action).toBe("ask")
- })
- test("evaluate - empty rules array returns ask", () => {
- const result = Permission.evaluate("bash", "rm", [])
- expect(result.action).toBe("ask")
- })
- test("evaluate - multiple matching patterns, last wins", () => {
- const result = Permission.evaluate("edit", "src/secret.ts", [
- { permission: "edit", pattern: "*", action: "ask" },
- { permission: "edit", pattern: "src/*", action: "allow" },
- { permission: "edit", pattern: "src/secret.ts", action: "deny" },
- ])
- expect(result.action).toBe("deny")
- })
- test("evaluate - non-matching patterns are skipped", () => {
- const result = Permission.evaluate("edit", "src/foo.ts", [
- { permission: "edit", pattern: "*", action: "ask" },
- { permission: "edit", pattern: "test/*", action: "deny" },
- { permission: "edit", pattern: "src/*", action: "allow" },
- ])
- expect(result.action).toBe("allow")
- })
- test("evaluate - exact match at end wins over earlier wildcard", () => {
- const result = Permission.evaluate("bash", "/bin/rm", [
- { permission: "bash", pattern: "*", action: "allow" },
- { permission: "bash", pattern: "/bin/rm", action: "deny" },
- ])
- expect(result.action).toBe("deny")
- })
- test("evaluate - wildcard at end overrides earlier exact match", () => {
- const result = Permission.evaluate("bash", "/bin/rm", [
- { permission: "bash", pattern: "/bin/rm", action: "deny" },
- { permission: "bash", pattern: "*", action: "allow" },
- ])
- expect(result.action).toBe("allow")
- })
- // wildcard permission tests
- test("evaluate - wildcard permission matches any permission", () => {
- const result = Permission.evaluate("bash", "rm", [{ permission: "*", pattern: "*", action: "deny" }])
- expect(result.action).toBe("deny")
- })
- test("evaluate - wildcard permission with specific pattern", () => {
- const result = Permission.evaluate("bash", "rm", [{ permission: "*", pattern: "rm", action: "deny" }])
- expect(result.action).toBe("deny")
- })
- test("evaluate - glob permission pattern", () => {
- const result = Permission.evaluate("mcp_server_tool", "anything", [
- { permission: "mcp_*", pattern: "*", action: "allow" },
- ])
- expect(result.action).toBe("allow")
- })
- test("evaluate - specific permission and wildcard permission combined", () => {
- const result = Permission.evaluate("bash", "rm", [
- { permission: "*", pattern: "*", action: "deny" },
- { permission: "bash", pattern: "*", action: "allow" },
- ])
- expect(result.action).toBe("allow")
- })
- test("evaluate - wildcard permission does not match when specific exists", () => {
- const result = Permission.evaluate("edit", "src/foo.ts", [
- { permission: "*", pattern: "*", action: "deny" },
- { permission: "edit", pattern: "src/*", action: "allow" },
- ])
- expect(result.action).toBe("allow")
- })
- test("evaluate - multiple matching permission patterns combine rules", () => {
- const result = Permission.evaluate("mcp_dangerous", "anything", [
- { permission: "*", pattern: "*", action: "ask" },
- { permission: "mcp_*", pattern: "*", action: "allow" },
- { permission: "mcp_dangerous", pattern: "*", action: "deny" },
- ])
- expect(result.action).toBe("deny")
- })
- test("evaluate - wildcard permission fallback for unknown tool", () => {
- const result = Permission.evaluate("unknown_tool", "anything", [
- { permission: "*", pattern: "*", action: "ask" },
- { permission: "bash", pattern: "*", action: "allow" },
- ])
- expect(result.action).toBe("ask")
- })
- test("evaluate - later wildcard permission can override earlier specific permission", () => {
- const result = Permission.evaluate("bash", "rm", [
- { permission: "bash", pattern: "*", action: "allow" },
- { permission: "*", pattern: "*", action: "deny" },
- ])
- expect(result.action).toBe("deny")
- })
- test("evaluate - merges multiple rulesets", () => {
- const config: PermissionV1.Ruleset = [{ permission: "bash", pattern: "*", action: "allow" }]
- const approved: PermissionV1.Ruleset = [{ permission: "bash", pattern: "rm", action: "deny" }]
- const result = Permission.evaluate("bash", "rm", config, approved)
- expect(result.action).toBe("deny")
- })
- // disabled tests
- test("disabled - returns empty set when all tools allowed", () => {
- const result = Permission.disabled(["bash", "edit", "read"], [{ permission: "*", pattern: "*", action: "allow" }])
- expect(result.size).toBe(0)
- })
- test("disabled - disables tool when denied", () => {
- const result = Permission.disabled(
- ["bash", "edit", "read"],
- [
- { permission: "*", pattern: "*", action: "allow" },
- { permission: "bash", pattern: "*", action: "deny" },
- ],
- )
- expect(result.has("bash")).toBe(true)
- expect(result.has("edit")).toBe(false)
- expect(result.has("read")).toBe(false)
- })
- test("disabled - disables edit/write/apply_patch when edit denied", () => {
- const result = Permission.disabled(
- ["edit", "write", "apply_patch", "bash"],
- [
- { permission: "*", pattern: "*", action: "allow" },
- { permission: "edit", pattern: "*", action: "deny" },
- ],
- )
- expect(result.has("edit")).toBe(true)
- expect(result.has("write")).toBe(true)
- expect(result.has("apply_patch")).toBe(true)
- expect(result.has("bash")).toBe(false)
- })
- test("disabled - does not disable when partially denied", () => {
- const result = Permission.disabled(
- ["bash"],
- [
- { permission: "bash", pattern: "*", action: "allow" },
- { permission: "bash", pattern: "rm *", action: "deny" },
- ],
- )
- expect(result.has("bash")).toBe(false)
- })
- test("disabled - does not disable when action is ask", () => {
- const result = Permission.disabled(["bash", "edit"], [{ permission: "*", pattern: "*", action: "ask" }])
- expect(result.size).toBe(0)
- })
- test("disabled - does not disable when specific allow after wildcard deny", () => {
- const result = Permission.disabled(
- ["bash"],
- [
- { permission: "bash", pattern: "*", action: "deny" },
- { permission: "bash", pattern: "echo *", action: "allow" },
- ],
- )
- expect(result.has("bash")).toBe(false)
- })
- test("disabled - does not disable when wildcard allow after deny", () => {
- const result = Permission.disabled(
- ["bash"],
- [
- { permission: "bash", pattern: "rm *", action: "deny" },
- { permission: "bash", pattern: "*", action: "allow" },
- ],
- )
- expect(result.has("bash")).toBe(false)
- })
- test("disabled - disables multiple tools", () => {
- const result = Permission.disabled(
- ["bash", "edit", "webfetch"],
- [
- { permission: "bash", pattern: "*", action: "deny" },
- { permission: "edit", pattern: "*", action: "deny" },
- { permission: "webfetch", pattern: "*", action: "deny" },
- ],
- )
- expect(result.has("bash")).toBe(true)
- expect(result.has("edit")).toBe(true)
- expect(result.has("webfetch")).toBe(true)
- })
- test("disabled - wildcard permission denies all tools", () => {
- const result = Permission.disabled(["bash", "edit", "read"], [{ permission: "*", pattern: "*", action: "deny" }])
- expect(result.has("bash")).toBe(true)
- expect(result.has("edit")).toBe(true)
- expect(result.has("read")).toBe(true)
- })
- test("disabled - specific allow overrides wildcard deny", () => {
- const result = Permission.disabled(
- ["bash", "edit", "read"],
- [
- { permission: "*", pattern: "*", action: "deny" },
- { permission: "bash", pattern: "*", action: "allow" },
- ],
- )
- expect(result.has("bash")).toBe(false)
- expect(result.has("edit")).toBe(true)
- expect(result.has("read")).toBe(true)
- })
- // ask tests
- it.instance(
- "ask - resolves immediately when action is allow",
- () =>
- Effect.gen(function* () {
- const result = yield* ask({
- sessionID: SessionID.make("session_test"),
- permission: "bash",
- patterns: ["ls"],
- metadata: {},
- always: [],
- ruleset: [{ permission: "bash", pattern: "*", action: "allow" }],
- })
- expect(result).toBeUndefined()
- }),
- { git: true },
- )
- it.instance(
- "ask - throws DeniedError when action is deny",
- () =>
- Effect.gen(function* () {
- const err = yield* fail(
- ask({
- sessionID: SessionID.make("session_test"),
- permission: "bash",
- patterns: ["rm -rf /"],
- metadata: {},
- always: [],
- ruleset: [{ permission: "bash", pattern: "*", action: "deny" }],
- }),
- )
- expect(err).toBeInstanceOf(PermissionV1.DeniedError)
- }),
- { git: true },
- )
- it.instance(
- "ask - stays pending when action is ask",
- () =>
- Effect.gen(function* () {
- const fiber = yield* ask({
- sessionID: SessionID.make("session_test"),
- permission: "bash",
- patterns: ["ls"],
- metadata: {},
- always: [],
- ruleset: [{ permission: "bash", pattern: "*", action: "ask" }],
- }).pipe(Effect.forkScoped)
- expect(yield* waitForPending(1)).toHaveLength(1)
- yield* rejectAll()
- yield* Fiber.await(fiber)
- }),
- { git: true },
- )
- it.instance(
- "ask - adds request to pending list",
- () =>
- Effect.gen(function* () {
- const fiber = yield* ask({
- sessionID: SessionID.make("session_test"),
- permission: "bash",
- patterns: ["ls"],
- metadata: { cmd: "ls" },
- always: ["ls"],
- tool: {
- messageID: MessageID.make("msg_test"),
- callID: "call_test",
- },
- ruleset: [],
- }).pipe(Effect.forkScoped)
- const items = yield* waitForPending(1)
- expect(items).toHaveLength(1)
- expect(items[0]).toMatchObject({
- sessionID: SessionID.make("session_test"),
- permission: "bash",
- patterns: ["ls"],
- metadata: { cmd: "ls" },
- always: ["ls"],
- tool: {
- messageID: MessageID.make("msg_test"),
- callID: "call_test",
- },
- })
- yield* rejectAll()
- yield* Fiber.await(fiber)
- }),
- { git: true },
- )
- it.instance(
- "ask - publishes asked event",
- () =>
- Effect.gen(function* () {
- const events = yield* EventV2Bridge.Service
- const seen = yield* Deferred.make<PermissionV1.Request>()
- const unsub = yield* events.listen((event) => {
- if (event.type === Permission.Event.Asked.type)
- Deferred.doneUnsafe(seen, Effect.succeed(event.data as PermissionV1.Request))
- return Effect.void
- })
- yield* Effect.addFinalizer(() => unsub)
- const fiber = yield* ask({
- sessionID: SessionID.make("session_test"),
- permission: "bash",
- patterns: ["ls"],
- metadata: { cmd: "ls" },
- always: ["ls"],
- tool: {
- messageID: MessageID.make("msg_test"),
- callID: "call_test",
- },
- ruleset: [],
- }).pipe(Effect.forkScoped)
- expect(yield* waitForPending(1)).toHaveLength(1)
- expect(
- yield* Deferred.await(seen).pipe(
- Effect.timeoutOrElse({
- duration: "1 second",
- orElse: () => Effect.fail(new Error("timed out waiting for permission asked event")),
- }),
- ),
- ).toMatchObject({
- sessionID: SessionID.make("session_test"),
- permission: "bash",
- patterns: ["ls"],
- })
- yield* rejectAll()
- yield* Fiber.await(fiber)
- }),
- { git: true },
- )
- // reply tests
- it.instance(
- "reply - once resolves the pending ask",
- () =>
- Effect.gen(function* () {
- const fiber = yield* ask({
- id: PermissionV1.ID.make("per_test1"),
- sessionID: SessionID.make("session_test"),
- permission: "bash",
- patterns: ["ls"],
- metadata: {},
- always: [],
- ruleset: [],
- }).pipe(Effect.forkScoped)
- yield* waitForPending(1)
- yield* reply({ requestID: PermissionV1.ID.make("per_test1"), reply: "once" })
- yield* Fiber.join(fiber)
- }),
- { git: true },
- )
- it.instance(
- "reply - reject throws RejectedError",
- () =>
- Effect.gen(function* () {
- const fiber = yield* ask({
- id: PermissionV1.ID.make("per_test2"),
- sessionID: SessionID.make("session_test"),
- permission: "bash",
- patterns: ["ls"],
- metadata: {},
- always: [],
- ruleset: [],
- }).pipe(Effect.forkScoped)
- yield* waitForPending(1)
- yield* reply({ requestID: PermissionV1.ID.make("per_test2"), reply: "reject" })
- const exit = yield* Fiber.await(fiber)
- expect(Exit.isFailure(exit)).toBe(true)
- if (Exit.isFailure(exit)) expect(Cause.squash(exit.cause)).toBeInstanceOf(PermissionV1.RejectedError)
- }),
- { git: true },
- )
- it.instance(
- "reply - reject with message throws CorrectedError",
- () =>
- Effect.gen(function* () {
- const fiber = yield* ask({
- id: PermissionV1.ID.make("per_test2b"),
- sessionID: SessionID.make("session_test"),
- permission: "bash",
- patterns: ["ls"],
- metadata: {},
- always: [],
- ruleset: [],
- }).pipe(Effect.forkScoped)
- yield* waitForPending(1)
- yield* reply({
- requestID: PermissionV1.ID.make("per_test2b"),
- reply: "reject",
- message: "Use a safer command",
- })
- const exit = yield* Fiber.await(fiber)
- expect(Exit.isFailure(exit)).toBe(true)
- if (Exit.isFailure(exit)) {
- const err = Cause.squash(exit.cause)
- expect(err).toBeInstanceOf(PermissionV1.CorrectedError)
- expect(String(err)).toContain("Use a safer command")
- }
- }),
- { git: true },
- )
- it.instance(
- "reply - always persists approval and resolves",
- () =>
- Effect.gen(function* () {
- const fiber = yield* ask({
- id: PermissionV1.ID.make("per_test3"),
- sessionID: SessionID.make("session_test"),
- permission: "bash",
- patterns: ["ls"],
- metadata: {},
- always: ["ls"],
- ruleset: [],
- }).pipe(Effect.forkScoped)
- yield* waitForPending(1)
- yield* reply({ requestID: PermissionV1.ID.make("per_test3"), reply: "always" })
- yield* Fiber.join(fiber)
- const result = yield* ask({
- sessionID: SessionID.make("session_test2"),
- permission: "bash",
- patterns: ["ls"],
- metadata: {},
- always: [],
- ruleset: [],
- })
- expect(result).toBeUndefined()
- }),
- { git: true },
- )
- it.instance(
- "reply - reject cancels all pending for same session",
- () =>
- Effect.gen(function* () {
- const a = yield* ask({
- id: PermissionV1.ID.make("per_test4a"),
- sessionID: SessionID.make("session_same"),
- permission: "bash",
- patterns: ["ls"],
- metadata: {},
- always: [],
- ruleset: [],
- }).pipe(Effect.forkScoped)
- const b = yield* ask({
- id: PermissionV1.ID.make("per_test4b"),
- sessionID: SessionID.make("session_same"),
- permission: "edit",
- patterns: ["foo.ts"],
- metadata: {},
- always: [],
- ruleset: [],
- }).pipe(Effect.forkScoped)
- yield* waitForPending(2)
- yield* reply({ requestID: PermissionV1.ID.make("per_test4a"), reply: "reject" })
- const [ea, eb] = yield* Effect.all([Fiber.await(a), Fiber.await(b)])
- expect(Exit.isFailure(ea)).toBe(true)
- expect(Exit.isFailure(eb)).toBe(true)
- if (Exit.isFailure(ea)) expect(Cause.squash(ea.cause)).toBeInstanceOf(PermissionV1.RejectedError)
- if (Exit.isFailure(eb)) expect(Cause.squash(eb.cause)).toBeInstanceOf(PermissionV1.RejectedError)
- }),
- { git: true },
- )
- it.instance(
- "reply - always resolves matching pending requests in same session",
- () =>
- Effect.gen(function* () {
- const a = yield* ask({
- id: PermissionV1.ID.make("per_test5a"),
- sessionID: SessionID.make("session_same"),
- permission: "bash",
- patterns: ["ls"],
- metadata: {},
- always: ["ls"],
- ruleset: [],
- }).pipe(Effect.forkScoped)
- const b = yield* ask({
- id: PermissionV1.ID.make("per_test5b"),
- sessionID: SessionID.make("session_same"),
- permission: "bash",
- patterns: ["ls"],
- metadata: {},
- always: [],
- ruleset: [],
- }).pipe(Effect.forkScoped)
- yield* waitForPending(2)
- yield* reply({ requestID: PermissionV1.ID.make("per_test5a"), reply: "always" })
- yield* Fiber.join(a)
- yield* Fiber.join(b)
- expect(yield* list()).toHaveLength(0)
- }),
- { git: true },
- )
- it.instance(
- "reply - always keeps other session pending",
- () =>
- Effect.gen(function* () {
- const a = yield* ask({
- id: PermissionV1.ID.make("per_test6a"),
- sessionID: SessionID.make("session_a"),
- permission: "bash",
- patterns: ["ls"],
- metadata: {},
- always: ["ls"],
- ruleset: [],
- }).pipe(Effect.forkScoped)
- const b = yield* ask({
- id: PermissionV1.ID.make("per_test6b"),
- sessionID: SessionID.make("session_b"),
- permission: "bash",
- patterns: ["ls"],
- metadata: {},
- always: [],
- ruleset: [],
- }).pipe(Effect.forkScoped)
- yield* waitForPending(2)
- yield* reply({ requestID: PermissionV1.ID.make("per_test6a"), reply: "always" })
- yield* Fiber.join(a)
- expect((yield* list()).map((item) => item.id)).toEqual([PermissionV1.ID.make("per_test6b")])
- yield* rejectAll()
- yield* Fiber.await(b)
- }),
- { git: true },
- )
- it.instance(
- "reply - publishes replied event",
- () =>
- Effect.gen(function* () {
- const events = yield* EventV2Bridge.Service
- const seen = yield* Deferred.make<{
- sessionID: SessionID
- requestID: PermissionV1.ID
- reply: PermissionV1.Reply
- }>()
- const fiber = yield* ask({
- id: PermissionV1.ID.make("per_test7"),
- sessionID: SessionID.make("session_test"),
- permission: "bash",
- patterns: ["ls"],
- metadata: {},
- always: [],
- ruleset: [],
- }).pipe(Effect.forkScoped)
- yield* waitForPending(1)
- const unsub = yield* events.listen((event) => {
- if (event.type === Permission.Event.Replied.type)
- Deferred.doneUnsafe(
- seen,
- Effect.succeed(
- event.data as { sessionID: SessionID; requestID: PermissionV1.ID; reply: PermissionV1.Reply },
- ),
- )
- return Effect.void
- })
- yield* Effect.addFinalizer(() => unsub)
- yield* reply({ requestID: PermissionV1.ID.make("per_test7"), reply: "once" })
- yield* Fiber.join(fiber)
- expect(
- yield* Deferred.await(seen).pipe(
- Effect.timeoutOrElse({
- duration: "1 second",
- orElse: () => Effect.fail(new Error("timed out waiting for permission replied event")),
- }),
- ),
- ).toEqual({
- sessionID: SessionID.make("session_test"),
- requestID: PermissionV1.ID.make("per_test7"),
- reply: "once",
- })
- }),
- { git: true },
- )
- it.live("permission requests stay isolated by directory", () =>
- Effect.gen(function* () {
- const one = yield* tmpdirScoped({ git: true })
- const two = yield* tmpdirScoped({ git: true })
- const store = yield* InstanceStore.Service
- const a = yield* store
- .provide(
- { directory: one },
- ask({
- id: PermissionV1.ID.make("per_dir_a"),
- sessionID: SessionID.make("session_dir_a"),
- permission: "bash",
- patterns: ["ls"],
- metadata: {},
- always: [],
- ruleset: [],
- }),
- )
- .pipe(Effect.forkScoped)
- const b = yield* store
- .provide(
- { directory: two },
- ask({
- id: PermissionV1.ID.make("per_dir_b"),
- sessionID: SessionID.make("session_dir_b"),
- permission: "bash",
- patterns: ["pwd"],
- metadata: {},
- always: [],
- ruleset: [],
- }),
- )
- .pipe(Effect.forkScoped)
- const onePending = yield* store.provide({ directory: one }, waitForPending(1))
- const twoPending = yield* store.provide({ directory: two }, waitForPending(1))
- expect(onePending).toHaveLength(1)
- expect(twoPending).toHaveLength(1)
- expect(onePending[0].id).toBe(PermissionV1.ID.make("per_dir_a"))
- expect(twoPending[0].id).toBe(PermissionV1.ID.make("per_dir_b"))
- yield* store.provide({ directory: one }, reply({ requestID: onePending[0].id, reply: "reject" }))
- yield* store.provide({ directory: two }, reply({ requestID: twoPending[0].id, reply: "reject" }))
- yield* Fiber.await(a)
- yield* Fiber.await(b)
- }),
- )
- it.instance(
- "pending permission rejects on instance dispose",
- () =>
- Effect.gen(function* () {
- const test = yield* TestInstance
- const store = yield* InstanceStore.Service
- const fiber = yield* ask({
- id: PermissionV1.ID.make("per_dispose"),
- sessionID: SessionID.make("session_dispose"),
- permission: "bash",
- patterns: ["ls"],
- metadata: {},
- always: [],
- ruleset: [],
- }).pipe(Effect.forkScoped)
- expect(yield* waitForPending(1)).toHaveLength(1)
- const ctx = yield* store.load({ directory: test.directory })
- yield* store.dispose(ctx)
- const exit = yield* Fiber.await(fiber)
- expect(Exit.isFailure(exit)).toBe(true)
- if (Exit.isFailure(exit)) expect(Cause.squash(exit.cause)).toBeInstanceOf(PermissionV1.RejectedError)
- }),
- { git: true },
- )
- it.instance(
- "pending permission rejects on instance reload",
- () =>
- Effect.gen(function* () {
- const test = yield* TestInstance
- const store = yield* InstanceStore.Service
- const fiber = yield* ask({
- id: PermissionV1.ID.make("per_reload"),
- sessionID: SessionID.make("session_reload"),
- permission: "bash",
- patterns: ["ls"],
- metadata: {},
- always: [],
- ruleset: [],
- }).pipe(Effect.forkScoped)
- expect(yield* waitForPending(1)).toHaveLength(1)
- yield* store.reload({ directory: test.directory })
- const exit = yield* Fiber.await(fiber)
- expect(Exit.isFailure(exit)).toBe(true)
- if (Exit.isFailure(exit)) expect(Cause.squash(exit.cause)).toBeInstanceOf(PermissionV1.RejectedError)
- }),
- { git: true },
- )
- it.instance(
- "reply - fails for unknown requestID",
- () =>
- Effect.gen(function* () {
- const exit = yield* reply({ requestID: PermissionV1.ID.make("per_unknown"), reply: "once" }).pipe(Effect.exit)
- expect(Exit.isFailure(exit)).toBe(true)
- if (Exit.isFailure(exit)) {
- expect(Cause.squash(exit.cause)).toMatchObject({ _tag: "Permission.NotFoundError", requestID: "per_unknown" })
- }
- expect(yield* list()).toHaveLength(0)
- }),
- { git: true },
- )
- it.instance(
- "ask - checks all patterns and stops on first deny",
- () =>
- Effect.gen(function* () {
- const err = yield* fail(
- ask({
- sessionID: SessionID.make("session_test"),
- permission: "bash",
- patterns: ["echo hello", "rm -rf /"],
- metadata: {},
- always: [],
- ruleset: [
- { permission: "bash", pattern: "*", action: "allow" },
- { permission: "bash", pattern: "rm *", action: "deny" },
- ],
- }),
- )
- expect(err).toBeInstanceOf(PermissionV1.DeniedError)
- }),
- { git: true },
- )
- it.instance(
- "ask - allows all patterns when all match allow rules",
- () =>
- Effect.gen(function* () {
- const result = yield* ask({
- sessionID: SessionID.make("session_test"),
- permission: "bash",
- patterns: ["echo hello", "ls -la", "pwd"],
- metadata: {},
- always: [],
- ruleset: [{ permission: "bash", pattern: "*", action: "allow" }],
- })
- expect(result).toBeUndefined()
- }),
- { git: true },
- )
- it.instance(
- "ask - should deny even when an earlier pattern is ask",
- () =>
- Effect.gen(function* () {
- const err = yield* fail(
- ask({
- sessionID: SessionID.make("session_test"),
- permission: "bash",
- patterns: ["echo hello", "rm -rf /"],
- metadata: {},
- always: [],
- ruleset: [
- { permission: "bash", pattern: "echo *", action: "ask" },
- { permission: "bash", pattern: "rm *", action: "deny" },
- ],
- }),
- )
- expect(err).toBeInstanceOf(PermissionV1.DeniedError)
- expect(yield* list()).toHaveLength(0)
- }),
- { git: true },
- )
- it.instance(
- "ask - abort should clear pending request",
- () =>
- Effect.gen(function* () {
- const test = yield* TestInstance
- const store = yield* InstanceStore.Service
- const fiber = yield* ask({
- id: PermissionV1.ID.make("per_reload"),
- sessionID: SessionID.make("session_reload"),
- permission: "bash",
- patterns: ["ls"],
- metadata: {},
- always: [],
- ruleset: [{ permission: "bash", pattern: "*", action: "ask" }],
- }).pipe(Effect.forkScoped)
- const pending = yield* waitForPending(1)
- expect(pending).toHaveLength(1)
- yield* store.reload({ directory: test.directory })
- const exit = yield* Fiber.await(fiber)
- expect(Exit.isFailure(exit)).toBe(true)
- if (Exit.isFailure(exit)) expect(Cause.squash(exit.cause)).toBeInstanceOf(PermissionV1.RejectedError)
- }),
- { git: true },
- )
|