feat(multiuser): phase 3, ownership threading + scoping

Threads per-user ownership through sessions, cases, cron, and the permission
policy. All scoping is a no-op in single-user mode (isMultiUserMode() guards).

Sessions
- Session.owner stamped at every create path from req.authUser / job.owner:
  POST /api/sessions, /api/run, /api/quick-start, ralph start, cron launch,
  plan generation. Round-trips through recovery (MuxSession.owner mirror, read
  muxSession.owner ?? savedState?.owner) and the mux layer.
- findSessionOrFail(ctx, id, req) now does a NOT_FOUND owner check (never 403, so
  other users' session existence is not leaked); wired at ~50 call sites.
- List endpoints filtered by owner: GET /api/sessions, /api/sessions/unified
  (live+persisted+lifecycle scoped, host-wide transcripts admin-only), cron jobs.

Permission policy (section 6.3)
- resolveClaudeModeForUsername wraps getClaudeModeConfig at every spawn site so a
  non-granted user is forced to --permission-mode auto (bypass -> auto), including
  recovery (or a reboot would un-downgrade). buildPromptArgs now respects the
  session's claudeMode, closing the one-shot (runPrompt) bypass hole.
- Shell mode and cron launchCommand require canBypassPermissions: 403 at
  POST /api/sessions, /api/quick-start create, cron job create, AND cron fire time
  (re-checked against the owner's current grant).

Cases
- resolveCasesDir(user): per-user ~/codeman-users/<name>/cases in multi-user, the
  shared ~/codeman-cases otherwise. All case CRUD + ralph + plan + quick-start
  resolve through it. resolveCasePath is owner-aware.
- GET /api/cases scoped per user (own folders; legacy linked cases admin-only;
  remote/docker cases owner-filtered). RemoteCase/DockerCase gain owner, stamped
  at link/quickcreate/import.
- Remote + Docker host CRUD is admin-only.
- Non-admin workingDir confinement (the linchpin): realpath must resolve inside the
  user's space, enforced at POST /api/sessions and /api/run BEFORE any disk write.

Limits
- sessionCapacityState / sessionCapacityMessage centralize the global + per-user
  cap (CODEMAN_MAX_SESSIONS_PER_USER, default global/2), replacing the 6 copy-pasted
  MAX_CONCURRENT_SESSIONS checks.

Tests: test/ownership-scoping.test.ts (case isolation, host-CRUD gate, workingDir +
shell gates, and the scoping helpers). Deferred to phase 4: WS owner gate, SSE
fan-out filtering, file-route preview/thumbnail helper scoping, push routing.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
Codeman maintainer
2026-07-20 04:02:46 +02:00
parent 4d8857f72a
commit 453605a58f
19 changed files with 680 additions and 164 deletions
+99 -47
View File
@@ -28,9 +28,21 @@ import {
import { exportDockerCase, importDockerBundle, listDockerExports, exportBundleName } from '../../docker-export.js';
import { generateClaudeMd } from '../../templates/claude-md.js';
import { writeHooksConfig } from '../../hooks-config.js';
import { CASES_DIR, SETTINGS_PATH, validatePathWithinBase, parseBody, readJsonConfig } from '../route-helpers.js';
import {
canAccessOwned,
getAuthUser,
isAdmin,
ownerFor,
resolveCasesDir,
SETTINGS_PATH,
validatePathWithinBase,
parseBody,
readJsonConfig,
} from '../route-helpers.js';
import type { AuthUser } from '../../types.js';
import { SseEvent } from '../sse-events.js';
import type { EventPort, ConfigPort } from '../ports/index.js';
import type { FastifyRequest } from 'fastify';
import { dataPath, getDataDir } from '../../config/instance.js';
import {
checkDockerAvailable,
@@ -78,11 +90,14 @@ async function readLinkedCases(): Promise<Record<string, string>> {
return readJsonConfig<Record<string, string>>(LINKED_CASES_FILE, 'linked cases', {});
}
/** Resolve a case name to its directory path, checking linked cases first, then CASES_DIR. */
async function resolveCasePath(name: string): Promise<string> {
/**
* Resolve a case name to its directory path, checking linked cases first, then the
* user's case space (per-user in multi-user mode, the shared CASES_DIR otherwise).
*/
async function resolveCasePath(name: string, user?: AuthUser): Promise<string> {
const linkedCases = await readLinkedCases();
if (linkedCases[name]) return linkedCases[name];
return join(CASES_DIR, name);
return join(resolveCasesDir(user), name);
}
/**
@@ -134,47 +149,54 @@ export function registerCaseRoutes(app: FastifyInstance, ctx: EventPort & Config
// ========== List Cases ==========
app.get('/api/cases', async (): Promise<CaseInfo[]> => {
app.get('/api/cases', async (req): Promise<CaseInfo[]> => {
const cases: CaseInfo[] = [];
const user = getAuthUser(req);
const admin = isAdmin(req);
// Non-admins enumerate their OWN case space; admins see the shared CASES_DIR.
const listBase = resolveCasesDir(user);
// Get cases from CASES_DIR
// Get cases from the user's (or shared) cases dir
try {
const entries = await fs.readdir(CASES_DIR, { withFileTypes: true });
const entries = await fs.readdir(listBase, { withFileTypes: true });
for (const e of entries) {
if (e.isDirectory() && SAFE_CASE_NAME.test(e.name)) {
cases.push({
name: e.name,
path: join(CASES_DIR, e.name),
hasClaudeMd: existsSync(join(CASES_DIR, e.name, 'CLAUDE.md')),
path: join(listBase, e.name),
hasClaudeMd: existsSync(join(listBase, e.name, 'CLAUDE.md')),
location: 'local',
});
}
}
} catch {
// CASES_DIR may not exist yet
// dir may not exist yet
}
// Get linked cases
// Linked cases (v1 registry has no owner) are admin-only in multi-user mode.
const linkedCases = await readLinkedCases();
const existingNames = new Set(cases.map((c) => c.name));
for (const [name, path] of Object.entries(linkedCases)) {
if (!existingNames.has(name) && SAFE_CASE_NAME.test(name) && existsSync(path)) {
cases.push({
name,
path,
hasClaudeMd: existsSync(join(path, 'CLAUDE.md')),
linked: true,
location: 'linked-local',
});
if (admin) {
for (const [name, path] of Object.entries(linkedCases)) {
if (!existingNames.has(name) && SAFE_CASE_NAME.test(name) && existsSync(path)) {
cases.push({
name,
path,
hasClaudeMd: existsSync(join(path, 'CLAUDE.md')),
linked: true,
location: 'linked-local',
});
}
}
}
// Get remote cases
// Get remote cases (owner-scoped; legacy no-owner = admin-only)
const remoteHosts = await readRemoteHosts(CODEMAN_CONFIG_DIR);
const remoteHostMap = new Map(remoteHosts.map((host) => [host.id, host]));
for (const remoteCase of await readRemoteCases(CODEMAN_CONFIG_DIR)) {
const host = remoteHostMap.get(remoteCase.hostId);
if (!host || !SAFE_CASE_NAME.test(remoteCase.name)) continue;
if (!admin && !canAccessOwned(user, remoteCase.owner)) continue;
existingNames.add(remoteCase.name);
const remoteCaseInfo: CaseInfo = {
name: remoteCase.name,
@@ -202,6 +224,7 @@ export function registerCaseRoutes(app: FastifyInstance, ctx: EventPort & Config
for (const dockerCase of await readDockerCases(CODEMAN_CONFIG_DIR)) {
const host = dockerHostMap.get(dockerCase.hostId);
if (!host || !SAFE_CASE_NAME.test(dockerCase.name)) continue;
if (!admin && !canAccessOwned(user, dockerCase.owner)) continue;
existingNames.add(dockerCase.name);
const container = dockerCase.container ?? dockerContainerName(dockerCase.name);
const dockerCaseInfo: CaseInfo = {
@@ -243,7 +266,7 @@ export function registerCaseRoutes(app: FastifyInstance, ctx: EventPort & Config
app.post('/api/cases', async (req): Promise<ApiResponse<{ case: { name: string; path: string } }>> => {
const { name, description } = parseBody(CreateCaseSchema, req.body);
const casePath = validatePathWithinBase(name, CASES_DIR);
const casePath = validatePathWithinBase(name, resolveCasesDir(getAuthUser(req)));
if (!casePath) {
return createErrorResponse(ApiErrorCode.INVALID_INPUT, 'Invalid case path');
}
@@ -274,7 +297,15 @@ export function registerCaseRoutes(app: FastifyInstance, ctx: EventPort & Config
app.get('/api/remote-hosts', async () => readRemoteHosts(CODEMAN_CONFIG_DIR));
app.post('/api/remote-hosts', async (req): Promise<ApiResponse<{ host: unknown }>> => {
// Hosts are machine-level resources: only admins may define them in multi-user mode.
const adminOnly = (req: FastifyRequest, reply: { code: (n: number) => unknown }): ApiResponse<never> | null =>
isAdmin(req)
? null
: (reply.code(403), createErrorResponse(ApiErrorCode.FORBIDDEN, 'Admin only in multi-user mode'));
app.post('/api/remote-hosts', async (req, reply): Promise<ApiResponse<{ host: unknown }>> => {
const denied = adminOnly(req, reply);
if (denied) return denied;
const host = parseBody(RemoteHostSchema, req.body);
const hosts = await readRemoteHosts(CODEMAN_CONFIG_DIR);
if (hosts.some((item) => item.id === host.id)) {
@@ -284,7 +315,9 @@ export function registerCaseRoutes(app: FastifyInstance, ctx: EventPort & Config
return { success: true, data: { host } };
});
app.put('/api/remote-hosts/:id', async (req): Promise<ApiResponse<{ host: unknown }>> => {
app.put('/api/remote-hosts/:id', async (req, reply): Promise<ApiResponse<{ host: unknown }>> => {
const denied = adminOnly(req, reply);
if (denied) return denied;
const { id } = req.params as { id: string };
const host = parseBody(RemoteHostSchema, { ...(req.body as object), id });
const hosts = await readRemoteHosts(CODEMAN_CONFIG_DIR);
@@ -296,7 +329,9 @@ export function registerCaseRoutes(app: FastifyInstance, ctx: EventPort & Config
return { success: true, data: { host } };
});
app.delete('/api/remote-hosts/:id', async (req): Promise<ApiResponse<{ id: string }>> => {
app.delete('/api/remote-hosts/:id', async (req, reply): Promise<ApiResponse<{ id: string }>> => {
const denied = adminOnly(req, reply);
if (denied) return denied;
const { id } = req.params as { id: string };
const cases = await readRemoteCases(CODEMAN_CONFIG_DIR);
if (cases.some((item) => item.hostId === id)) {
@@ -311,7 +346,7 @@ export function registerCaseRoutes(app: FastifyInstance, ctx: EventPort & Config
});
app.post('/api/cases/remote-link', async (req): Promise<ApiResponse<{ case: unknown }>> => {
const remoteCase = { ...parseBody(RemoteCaseLinkSchema, req.body), type: 'remote' as const };
const remoteCase = { ...parseBody(RemoteCaseLinkSchema, req.body), type: 'remote' as const, owner: ownerFor(req) };
const hosts = await readRemoteHosts(CODEMAN_CONFIG_DIR);
const host = hosts.find((item) => item.id === remoteCase.hostId);
if (!host) return createErrorResponse(ApiErrorCode.NOT_FOUND, 'Remote host not found');
@@ -321,7 +356,7 @@ export function registerCaseRoutes(app: FastifyInstance, ctx: EventPort & Config
if (
remoteCases.some((item) => item.name === remoteCase.name) ||
linkedCases[remoteCase.name] ||
existsSync(join(CASES_DIR, remoteCase.name))
existsSync(join(resolveCasesDir(getAuthUser(req)), remoteCase.name))
) {
return createErrorResponse(ApiErrorCode.ALREADY_EXISTS, 'Case already exists');
}
@@ -343,7 +378,9 @@ export function registerCaseRoutes(app: FastifyInstance, ctx: EventPort & Config
app.get('/api/docker-hosts', async () => readDockerHosts(CODEMAN_CONFIG_DIR));
app.post('/api/docker-hosts', async (req): Promise<ApiResponse<{ host: unknown }>> => {
app.post('/api/docker-hosts', async (req, reply): Promise<ApiResponse<{ host: unknown }>> => {
const denied = adminOnly(req, reply);
if (denied) return denied;
const host = parseBody(DockerHostSchema, req.body);
const hosts = await readDockerHosts(CODEMAN_CONFIG_DIR);
if (hosts.some((item) => item.id === host.id)) {
@@ -353,7 +390,9 @@ export function registerCaseRoutes(app: FastifyInstance, ctx: EventPort & Config
return { success: true, data: { host } };
});
app.put('/api/docker-hosts/:id', async (req): Promise<ApiResponse<{ host: unknown }>> => {
app.put('/api/docker-hosts/:id', async (req, reply): Promise<ApiResponse<{ host: unknown }>> => {
const denied = adminOnly(req, reply);
if (denied) return denied;
const { id } = req.params as { id: string };
const host = parseBody(DockerHostSchema, { ...(req.body as object), id });
const hosts = await readDockerHosts(CODEMAN_CONFIG_DIR);
@@ -365,7 +404,9 @@ export function registerCaseRoutes(app: FastifyInstance, ctx: EventPort & Config
return { success: true, data: { host } };
});
app.delete('/api/docker-hosts/:id', async (req): Promise<ApiResponse<{ id: string }>> => {
app.delete('/api/docker-hosts/:id', async (req, reply): Promise<ApiResponse<{ id: string }>> => {
const denied = adminOnly(req, reply);
if (denied) return denied;
const { id } = req.params as { id: string };
const cases = await readDockerCases(CODEMAN_CONFIG_DIR);
if (cases.some((item) => item.hostId === id)) {
@@ -386,7 +427,11 @@ export function registerCaseRoutes(app: FastifyInstance, ctx: EventPort & Config
): Promise<
ApiResponse<{ case: unknown; capsEnforced?: boolean; isDesktop?: boolean; imageBuilding?: boolean }>
> => {
const dockerCase = { ...parseBody(DockerCaseLinkSchema, req.body), type: 'docker' as const };
const dockerCase = {
...parseBody(DockerCaseLinkSchema, req.body),
type: 'docker' as const,
owner: ownerFor(req),
};
const hosts = await readDockerHosts(CODEMAN_CONFIG_DIR);
const host = hosts.find((item) => item.id === dockerCase.hostId);
if (!host) return createErrorResponse(ApiErrorCode.NOT_FOUND, 'Docker host not found');
@@ -396,7 +441,7 @@ export function registerCaseRoutes(app: FastifyInstance, ctx: EventPort & Config
if (
dockerCases.some((item) => item.name === dockerCase.name) ||
linkedCases[dockerCase.name] ||
existsSync(join(CASES_DIR, dockerCase.name))
existsSync(join(resolveCasesDir(getAuthUser(req)), dockerCase.name))
) {
return createErrorResponse(ApiErrorCode.ALREADY_EXISTS, 'Case already exists');
}
@@ -460,7 +505,7 @@ export function registerCaseRoutes(app: FastifyInstance, ctx: EventPort & Config
> => {
const body = parseBody(DockerQuickCreateSchema, req.body);
const { name, description } = body;
const casePath = validatePathWithinBase(name, CASES_DIR);
const casePath = validatePathWithinBase(name, resolveCasesDir(getAuthUser(req)));
if (!casePath) return createErrorResponse(ApiErrorCode.INVALID_INPUT, 'Invalid case path');
// Collision across every case kind.
@@ -525,7 +570,13 @@ export function registerCaseRoutes(app: FastifyInstance, ctx: EventPort & Config
availability.error || 'docker daemon is not available'
);
}
const dockerCase = { name, type: 'docker' as const, hostId: host.id, hostWorkspacePath: casePath };
const dockerCase = {
name,
type: 'docker' as const,
hostId: host.id,
hostWorkspacePath: casePath,
owner: ownerFor(req),
};
const imageGate = await ensureCaseImage(ctx.broadcast, toSessionDocker(host, dockerCase), name);
if (!imageGate.ok) {
return createErrorResponse(ApiErrorCode.OPERATION_FAILED, imageGate.error);
@@ -644,7 +695,7 @@ export function registerCaseRoutes(app: FastifyInstance, ctx: EventPort & Config
if (
dockerCases.some((item) => item.name === newCaseName) ||
linkedCases[newCaseName] ||
existsSync(join(CASES_DIR, newCaseName))
existsSync(join(resolveCasesDir(getAuthUser(req)), newCaseName))
) {
return createErrorResponse(ApiErrorCode.ALREADY_EXISTS, 'Case already exists');
}
@@ -681,6 +732,7 @@ export function registerCaseRoutes(app: FastifyInstance, ctx: EventPort & Config
hostId,
hostWorkspacePath: destWorkspacePath,
containerWorkdir: result.manifest.containerWorkdir,
owner: ownerFor(req),
};
await writeDockerCases(CODEMAN_CONFIG_DIR, [...dockerCases, newCase]);
ctx.broadcast(SseEvent.DockerImportComplete, { name: newCaseName, path: destWorkspacePath, type: 'docker' });
@@ -700,7 +752,7 @@ export function registerCaseRoutes(app: FastifyInstance, ctx: EventPort & Config
}
// Check if case name already exists in CASES_DIR
const casePath = join(CASES_DIR, name);
const casePath = join(resolveCasesDir(getAuthUser(req)), name);
if (existsSync(casePath)) {
return createErrorResponse(ApiErrorCode.ALREADY_EXISTS, 'A case with this name already exists in codeman-cases.');
}
@@ -736,7 +788,7 @@ export function registerCaseRoutes(app: FastifyInstance, ctx: EventPort & Config
app.delete('/api/cases/:name', async (req): Promise<ApiResponse<{ name: string }>> => {
const { name } = req.params as { name: string };
if (!validatePathWithinBase(name, CASES_DIR)) {
if (!validatePathWithinBase(name, resolveCasesDir(getAuthUser(req)))) {
return createErrorResponse(ApiErrorCode.INVALID_INPUT, 'Invalid case name');
}
@@ -790,7 +842,7 @@ export function registerCaseRoutes(app: FastifyInstance, ctx: EventPort & Config
}
// Case in CASES_DIR — delete the entire directory
const casePath = join(CASES_DIR, name);
const casePath = join(resolveCasesDir(getAuthUser(req)), name);
if (!existsSync(casePath)) {
return createErrorResponse(ApiErrorCode.NOT_FOUND, `Case "${name}" not found`);
}
@@ -832,7 +884,7 @@ export function registerCaseRoutes(app: FastifyInstance, ctx: EventPort & Config
app.get('/api/cases/:name', async (req) => {
const { name } = req.params as { name: string };
if (!validatePathWithinBase(name, CASES_DIR)) {
if (!validatePathWithinBase(name, resolveCasesDir(getAuthUser(req)))) {
return createErrorResponse(ApiErrorCode.INVALID_INPUT, 'Invalid case name');
}
@@ -875,13 +927,13 @@ export function registerCaseRoutes(app: FastifyInstance, ctx: EventPort & Config
};
}
const casePath = await resolveCasePath(name);
const casePath = await resolveCasePath(name, getAuthUser(req));
if (!existsSync(casePath)) {
return createErrorResponse(ApiErrorCode.NOT_FOUND, 'Case not found');
}
const linked = casePath !== join(CASES_DIR, name);
const linked = casePath !== join(resolveCasesDir(getAuthUser(req)), name);
return {
name,
path: casePath,
@@ -894,12 +946,12 @@ export function registerCaseRoutes(app: FastifyInstance, ctx: EventPort & Config
app.get('/api/cases/:name/fix-plan', async (req) => {
const { name } = req.params as { name: string };
if (!validatePathWithinBase(name, CASES_DIR)) {
if (!validatePathWithinBase(name, resolveCasesDir(getAuthUser(req)))) {
return createErrorResponse(ApiErrorCode.INVALID_INPUT, 'Invalid case name');
}
// Get case path (check linked cases first, then CASES_DIR)
const casePath = await resolveCasePath(name);
const casePath = await resolveCasePath(name, getAuthUser(req));
const fixPlanPath = join(casePath, '@fix_plan.md');
@@ -999,11 +1051,11 @@ export function registerCaseRoutes(app: FastifyInstance, ctx: EventPort & Config
app.get('/api/cases/:caseName/ralph-wizard/files', async (req) => {
const { caseName } = req.params as { caseName: string };
if (!validatePathWithinBase(caseName, CASES_DIR)) {
if (!validatePathWithinBase(caseName, resolveCasesDir(getAuthUser(req)))) {
return createErrorResponse(ApiErrorCode.INVALID_INPUT, 'Invalid case name');
}
const casePath = await resolveCasePath(caseName);
const casePath = await resolveCasePath(caseName, getAuthUser(req));
const wizardDir = join(casePath, 'ralph-wizard');
@@ -1042,7 +1094,7 @@ export function registerCaseRoutes(app: FastifyInstance, ctx: EventPort & Config
// Cache disabled to ensure fresh prompts when starting new plan generations
app.get('/api/cases/:caseName/ralph-wizard/file/:filePath', async (req, reply) => {
const { caseName, filePath } = req.params as { caseName: string; filePath: string };
if (!validatePathWithinBase(caseName, CASES_DIR)) {
if (!validatePathWithinBase(caseName, resolveCasesDir(getAuthUser(req)))) {
return createErrorResponse(ApiErrorCode.INVALID_INPUT, 'Invalid case name');
}
@@ -1051,7 +1103,7 @@ export function registerCaseRoutes(app: FastifyInstance, ctx: EventPort & Config
reply.header('Pragma', 'no-cache');
reply.header('Expires', '0');
const casePath = await resolveCasePath(caseName);
const casePath = await resolveCasePath(caseName, getAuthUser(req));
const wizardDir = join(casePath, 'ralph-wizard');