feat(permissions): add scoped process capture elicitation

This commit is contained in:
morluto
2026-07-18 04:50:22 +00:00
parent 37f4ac6d70
commit e6cfce3902
21 changed files with 1260 additions and 118 deletions
+95 -18
View File
@@ -110,9 +110,22 @@ const errorReason = (error: unknown): PermissionPathError["reason"] =>
/** Stateful owner for permission evaluation, consumption, reload, and revoke. */
export class PermissionAuthority {
private policy: PermissionPolicy;
private readonly configuredAuthority: PermissionAuthority | undefined;
constructor(policy: PermissionPolicy) {
constructor(
policy: PermissionPolicy,
configuredAuthority?: PermissionAuthority,
) {
this.policy = policy;
this.configuredAuthority = configuredAuthority;
}
/** Create a connection-owned overlay for once and session grants. */
createConnectionAuthority(): PermissionAuthority {
return new PermissionAuthority(
createPermissionPolicy([]),
this.configuredAuthority ?? this,
);
}
/** Canonicalize and authorize one exact operation before its side effect. */
@@ -132,11 +145,13 @@ export class PermissionAuthority {
PermissionPathError | PermissionRequiredError
>
> {
const evaluated = await this.explain(request, access, options);
const canonical = await canonicalizePermissionRequest(request, access);
if (!canonical.ok) return canonical;
const evaluated = this.evaluateCanonical(canonical.value, options);
if (!evaluated.ok) return evaluated;
const decision = evaluated.value;
this.policy = consumePermission(this.policy, decision);
return ok(decision);
const { decision, owner } = evaluated.value;
owner.policy = consumePermission(owner.policy, decision);
return ok({ ...decision, request: canonical.value });
}
/** Dry-run the exact shared evaluation without consuming a once grant. */
@@ -158,23 +173,22 @@ export class PermissionAuthority {
> {
const canonical = await canonicalizePermissionRequest(request, access);
if (!canonical.ok) return canonical;
const decision = evaluatePermission(this.policy, canonical.value);
if (!decision.allowed)
return err(
new PermissionRequiredError(
canonical.value,
decision.missing,
ceilingFor(this.policy, canonical.value.capability),
options.elicitationSupported ?? false,
options.restartRequired ?? false,
),
);
return ok({ ...decision, request: canonical.value });
const evaluated = this.evaluateCanonical(canonical.value, options);
return evaluated.ok
? ok({ ...evaluated.value.decision, request: canonical.value })
: evaluated;
}
/** Add authority beneath the administrator ceiling. */
grant(grant: PermissionGrant): ReturnType<typeof grantPermission> {
const result = grantPermission(this.policy, grant);
const policy =
this.configuredAuthority === undefined
? this.policy
: {
...this.policy,
ceilings: this.configuredAuthority.effectivePolicy().ceilings,
};
const result = grantPermission(policy, grant);
if (result.ok) this.policy = result.value;
return result;
}
@@ -189,6 +203,69 @@ export class PermissionAuthority {
this.policy = clearSessionPermissions(this.policy);
}
private effectivePolicy(): PermissionPolicy {
if (this.configuredAuthority === undefined) return this.policy;
const configured = this.configuredAuthority.effectivePolicy();
return {
ceilings: configured.ceilings,
grants: [...configured.grants, ...this.policy.grants],
revoked_grant_ids: new Set([
...configured.revoked_grant_ids,
...this.policy.revoked_grant_ids,
]),
consumed_grant_ids: new Set([
...configured.consumed_grant_ids,
...this.policy.consumed_grant_ids,
]),
};
}
private evaluateCanonical(
request: PermissionRequest,
options: {
readonly elicitationSupported?: boolean;
readonly restartRequired?: boolean;
},
): Result<
{
readonly decision: Extract<
PermissionDecision,
{ readonly allowed: true }
>;
readonly owner: PermissionAuthority;
},
PermissionRequiredError
> {
const configured = this.configuredAuthority;
if (configured !== undefined) {
const configuredDecision = evaluatePermission(
configured.effectivePolicy(),
request,
);
if (configuredDecision.allowed)
return ok({ decision: configuredDecision, owner: configured });
}
const localPolicy =
configured === undefined
? this.policy
: { ...this.policy, ceilings: configured.effectivePolicy().ceilings };
const localDecision = evaluatePermission(localPolicy, request);
if (localDecision.allowed)
return ok({ decision: localDecision, owner: this });
const effective = this.effectivePolicy();
const denied = evaluatePermission(effective, request);
if (denied.allowed) return ok({ decision: denied, owner: this });
return err(
new PermissionRequiredError(
request,
denied.missing,
ceilingFor(effective, request.capability),
options.elicitationSupported ?? false,
options.restartRequired ?? false,
),
);
}
/** Atomically replace optional persisted project grants. */
async replaceProjectGrants(
grants: readonly PermissionGrant[],
@@ -0,0 +1,18 @@
import type { PermissionRequest } from "../domain/permissionPolicy.js";
import type { ProcessScenario } from "../domain/processCapture.js";
/** Build the exact permission request shared by process-capture adapters. */
export const processCapturePermissionRequest = (
scenario: ProcessScenario,
): PermissionRequest => ({
capability: "process_capture",
roots: [scenario.working_directory, ...scenario.filesystem_roots],
executables: [scenario.executable],
environment_names: [
...Object.keys(scenario.environment),
...scenario.inherit_environment,
],
network: scenario.network_access === "host" ? "external" : "none",
mount: false,
operation_identity: `capture_process_scenario:${scenario.executable}`,
});
+57 -9
View File
@@ -1,11 +1,11 @@
import { createHash } from "node:crypto";
import { constants } from "node:fs";
import {
lstat,
mkdir,
open,
readFile,
realpath,
stat,
unlink,
type FileHandle,
} from "node:fs/promises";
@@ -35,6 +35,7 @@ const grantSchema = z.object({
"native_mount",
"reference_read",
"javascript_replay",
"managed_runtime",
]),
roots: z.array(z.string()),
executables: z.array(z.string()),
@@ -102,11 +103,15 @@ export const readProjectPermissionStore = async (
> => {
const project = await identifyPermissionProject(projectRoot);
if (!project.ok) return project;
if (process.getuid === undefined)
return err(new ProjectPermissionStoreError("not_owner_only"));
let handle: FileHandle | undefined;
try {
const metadata = await stat(path);
if ((metadata.mode & 0o077) !== 0)
return err(new ProjectPermissionStoreError("not_owner_only"));
const encoded = await readFile(path, "utf8");
const opened = await openPrivateStore(path);
if (!opened.ok) return opened;
if (opened.value === null) return ok(null);
handle = opened.value;
const encoded = await handle.readFile("utf8");
let decoded: unknown;
try {
decoded = JSON.parse(encoded);
@@ -124,6 +129,8 @@ export const readProjectPermissionStore = async (
} catch (cause: unknown) {
if (isNotFound(cause)) return ok(null);
return err(new ProjectPermissionStoreError("io", { cause }));
} finally {
await handle?.close().catch(() => undefined);
}
};
@@ -145,6 +152,8 @@ export const writeProjectPermissionStore = async (
return err(
new ProjectPermissionStoreError("invalid", { cause: candidate.error }),
);
if (process.getuid === undefined)
return err(new ProjectPermissionStoreError("not_owner_only"));
try {
await mkdir(dirname(path), { recursive: true, mode: 0o700 });
await writeFileAtomic(
@@ -155,10 +164,13 @@ export const writeProjectPermissionStore = async (
mode: 0o600,
},
);
const metadata = await stat(path);
if ((metadata.mode & 0o077) !== 0) {
return err(new ProjectPermissionStoreError("not_owner_only"));
}
const verified = await readProjectPermissionStore(path, projectRoot);
if (!verified.ok) return verified;
if (
verified.value === null ||
JSON.stringify(verified.value) !== JSON.stringify(candidate.data)
)
return err(new ProjectPermissionStoreError("invalid"));
return ok(candidate.data);
} catch (cause: unknown) {
return err(new ProjectPermissionStoreError("io", { cause }));
@@ -269,6 +281,39 @@ const releasePermissionStoreLock = async (
const isNotFound = (cause: unknown): boolean => errorCode(cause) === "ENOENT";
const openPrivateStore = async (
path: string,
): Promise<Result<FileHandle | null, ProjectPermissionStoreError>> => {
let handle: FileHandle | undefined;
try {
handle = await open(path, constants.O_RDONLY | constants.O_NOFOLLOW);
const metadata = await handle.stat();
if (!privateRegularFile(metadata)) {
await handle.close();
return err(new ProjectPermissionStoreError("not_owner_only"));
}
return ok(handle);
} catch (cause: unknown) {
await handle?.close().catch(() => undefined);
if (isNotFound(cause)) return ok(null);
return err(
new ProjectPermissionStoreError(
isSymlinkRefusal(cause) ? "not_owner_only" : "io",
{ cause },
),
);
}
};
const privateRegularFile = (
metadata: Awaited<ReturnType<typeof lstat>>,
): boolean =>
metadata.isFile() &&
!metadata.isSymbolicLink() &&
(Number(metadata.mode) & 0o077) === 0 &&
process.getuid !== undefined &&
metadata.uid === process.getuid();
const isAlreadyExists = (cause: unknown): boolean =>
errorCode(cause) === "EEXIST";
@@ -276,3 +321,6 @@ const errorCode = (cause: unknown): unknown =>
typeof cause === "object" && cause !== null && "code" in cause
? cause.code
: undefined;
const isSymlinkRefusal = (cause: unknown): boolean =>
errorCode(cause) === "ELOOP" || errorCode(cause) === "EMLINK";