Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
76 changes: 76 additions & 0 deletions packages/code/src/checkpoint-mount.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { assertPrivateMountIsolation } from './environment-mount.js';

const base = '1 0 8:1 / / rw - ext4 /dev/root rw\n';
const storage = '/private/stage';
const grant = '/workspace';

test('private storage and workspace grants must be disjoint in both directions', () => {
for (const path of [storage, '/private', `${storage}/child`, '/']) {
assert.throws(
() => assertPrivateMountIsolation(base, storage, [path]),
/overlaps/
);
}
assert.doesNotThrow(() =>
assertPrivateMountIsolation(base, storage, [
grant,
'/private/stage-other',
])
);
});

test('private storage checks backing coordinates and descendant mounts on either side', () => {
for (const mount of [
`2 1 8:1 ${storage}/child ${grant} rw - ext4 /dev/root rw`,
`2 1 8:1 ${grant}/child ${storage} rw - ext4 /dev/root rw`,
`2 1 8:1 ${storage}/child ${grant}/alias rw - ext4 /dev/root rw`,
`2 1 8:1 ${grant}/child ${storage}/alias rw - ext4 /dev/root rw`,
`2 1 8:1 ${storage}/my\\040dir ${grant}/alias rw - ext4 /dev/root rw`,
`2 1 9:1 / ${storage}/volume rw - ext4 /dev/volume rw\n3 1 9:1 /child ${grant}/alias rw - ext4 /dev/volume rw`,
]) {
assert.throws(
() => assertPrivateMountIsolation(base + mount, storage, [grant]),
/overlaps/
);
}
assert.doesNotThrow(() =>
assertPrivateMountIsolation(
base + `2 1 9:1 / ${grant} rw - ext4 /dev/volume rw`,
storage,
[grant]
)
);
});

test('private storage refuses incomplete, malformed and unbounded inventories', () => {
for (const grants of [
[],
['relative'],
['/a/../b'],
['/a/'],
['/a\0b'],
Array(256).fill(grant),
]) {
assert.throws(
() => assertPrivateMountIsolation(base, storage, grants),
/Invalid private mount/
);
}
assert.throws(
() => assertPrivateMountIsolation('invalid', storage, [grant]),
/Invalid environment mount/
);
const many = Array.from(
{ length: 256 },
(_, index) =>
`${
index + 2
} 1 9:1 / ${storage}/vol${index} rw - ext4 /dev/volume rw`
).join('\n');
assert.throws(
() => assertPrivateMountIsolation(base + many, storage, [grant]),
/Too many workspace mount boundaries/
);
});
98 changes: 71 additions & 27 deletions packages/code/src/environment-mount.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,14 +12,18 @@ const decode = (path: string): string => {
if (!path.startsWith('/') || /\\(?!040|011|012|134)/.test(path))
throw new Error('Invalid environment mount table');
return path.replace(/\\(040|011|012|134)/g, (_, octal: string) =>
String.fromCharCode(parseInt(octal, 8)),
String.fromCharCode(parseInt(octal, 8))
);
};

/** Compare filesystem coordinates, not mount aliases. Include mounted descendants of each grant. */
export function createEnvironmentMountIsolation(
table: string,
): (controls: readonly string[], roots: readonly string[]) => void {
table: string
): (
controls: readonly string[],
roots: readonly string[],
disjoint?: boolean
) => void {
if (Buffer.byteLength(table) > 4 * 1024 * 1024)
throw new Error('Environment mount table exceeds limit');
const mounts: Mount[] = table
Expand All @@ -38,7 +42,8 @@ export function createEnvironmentMountIsolation(
// nsfs file mounts report a namespace handle rather than a path.
// Preserve its identity so repeated mounts of the handle still alias.
const namespace =
fields[separator + 1] === 'nsfs' && /^[a-z][a-z0-9_]*:\[\d+\]$/.test(root);
fields[separator + 1] === 'nsfs' &&
/^[a-z][a-z0-9_]*:\[\d+\]$/.test(root);
return {
device: fields[2],
root: namespace ? `/${root}` : decode(root),
Expand All @@ -59,48 +64,87 @@ export function createEnvironmentMountIsolation(
}));
if (!result.length || result.length > 256)
throw new Error(
'Environment path has an unsupported mount mapping',
'Environment path has an unsupported mount mapping'
);
cache.set(path, result);
return result;
};
return (controls, roots) => {
const expand = (roots: readonly string[]) => {
const points = new Set(roots);
for (const mount of mounts)
if (roots.some(root => inside(root, mount.point)))
points.add(mount.point);
if (points.size > 256)
throw new Error('Too many workspace mount boundaries');
const exposed = [...points].flatMap(coordinate);
if (exposed.length > 1024)
throw new Error('Too many workspace mount mappings');
for (const control of controls) {
const target = coordinate(control);
for (const mount of mounts) {
if (!roots.some(root => inside(root, mount.point))) continue;
points.add(mount.point);
if (points.size > 256)
throw new Error('Too many workspace mount boundaries');
}
const exposed: ReturnType<typeof coordinate> = [];
for (const point of points) {
const entries = coordinate(point);
if (exposed.length + entries.length > 1024)
throw new Error('Too many workspace mount mappings');
exposed.push(...entries);
}
return exposed;
};
return (controls, roots, disjoint = false) => {
if (disjoint) {
if (
target.some(target =>
exposed.some(
root =>
root.device === target.device &&
inside(root.path, target.path),
),
!controls.length ||
!roots.length ||
controls.length + roots.length > 256
)
throw new Error('Invalid private mount isolation inventory');
for (const path of [...controls, ...roots]) {
if (
!path.startsWith('/') ||
path.includes('\0') ||
path !== posix.normalize(path) ||
(path !== '/' && path.endsWith('/'))
)
) {
throw new Error(
'Environment control path is writable through a workspace mount alias',
);
throw new Error('Invalid private mount isolation path');
}
}
const exposed = expand(roots);
const overlaps = (target: { device: string; path: string }): boolean =>
exposed.some(
root =>
root.device === target.device &&
(inside(root.path, target.path) ||
(disjoint && inside(target.path, root.path)))
);
if (
disjoint
? expand(controls).some(overlaps)
: controls.some(path => coordinate(path).some(overlaps))
) {
throw new Error(
disjoint
? 'Private storage overlaps a workspace mount grant'
: 'Environment control path is writable through a workspace mount alias'
);
}
};
}

export function assertEnvironmentMountIsolation(
table: string,
controls: readonly string[],
roots: readonly string[],
roots: readonly string[]
): void {
createEnvironmentMountIsolation(table)(controls, roots);
}

/** Checks a single canonical inventory in one mount snapshot. Callers must separately pin paths and prevent topology changes. */
export function assertPrivateMountIsolation(
table: string,
storage: string,
grants: readonly string[]
): void {
createEnvironmentMountIsolation(table)([storage], grants, true);
}

export async function readEnvironmentMountTable(): Promise<string | undefined> {
if (process.platform !== 'linux') return undefined;
const handle = await open('/proc/self/mountinfo', 'r');
Expand All @@ -112,15 +156,15 @@ export async function readEnvironmentMountTable(): Promise<string | undefined> {
buffer,
length,
buffer.length - length,
null,
null
);
if (!result.bytesRead) break;
length += result.bytesRead;
}
if (length === buffer.length)
throw new Error('Environment mount table exceeds limit');
return new TextDecoder('utf-8', { fatal: true }).decode(
buffer.subarray(0, length),
buffer.subarray(0, length)
);
} finally {
await handle.close();
Expand Down
Loading