diff --git a/lib/api/cap.js b/lib/api/cap.js new file mode 100644 index 0000000..fd33c81 --- /dev/null +++ b/lib/api/cap.js @@ -0,0 +1,31 @@ +import { canAct } from '../auth/capability.js'; +import * as pendingChanges from '../db/repos/pending_changes.js'; +import { ForbiddenError } from './errors.js'; + +const METHOD_TO_ACTION = { POST: 'create', PATCH: 'update', PUT: 'update', DELETE: 'delete' }; + +export function requireWrite(entity_type) { + return (req, _res, next) => { + const action = METHOD_TO_ACTION[req.method] || 'update'; + const tier = canAct(req.actor, action, entity_type); + if (tier === 'allow') { req.capTier = 'allow'; return next(); } + if (tier === 'suggest') { req.capTier = 'suggest'; return next(); } + return next(new ForbiddenError(`agent not permitted to ${action} ${entity_type}`)); + }; +} + +export function requireOwner(req, _res, next) { + if (req.actor?.kind !== 'user') { + return next(new ForbiddenError('owner-only endpoint')); + } + next(); +} + +export async function divertToPending(req, res, { entity_type, entity_id = null, action, payload, reason = null }) { + const change = await pendingChanges.create({ + agent_id: req.actor.id, + entity_type, entity_id, action, payload, + reason: reason ?? req.headers['x-reason'] ?? null + }); + res.status(202).json({ pending: true, change_id: change.id }); +} diff --git a/lib/api/routes/pages.js b/lib/api/routes/pages.js index e6c578e..ecf6826 100644 --- a/lib/api/routes/pages.js +++ b/lib/api/routes/pages.js @@ -5,6 +5,7 @@ import * as links from '../../db/repos/links.js'; import { pool } from '../../db/pool.js'; import { validate } from '../validate.js'; import { NotFoundError, ValidationError, asyncWrap } from '../errors.js'; +import { requireWrite, divertToPending } from '../cap.js'; const createSchema = z.object({ slug: z.string().min(1).max(128).regex(/^[a-z0-9-]+$/), @@ -34,10 +35,15 @@ spacesScopedRouter.get('/', ); spacesScopedRouter.post('/', + requireWrite('page'), validate({ params: spaceParams, body: createSchema }), asyncWrap(async (req, res) => { + const payload = { ...req.body, space_id: req.params.space_id }; + if (req.capTier === 'suggest') { + return divertToPending(req, res, { entity_type: 'page', action: 'create', payload }); + } try { - const row = await repo.create({ ...req.body, space_id: req.params.space_id }, req.actor); + const row = await repo.create(payload, req.actor); res.status(201).json(row); } catch (e) { if (e.code === '23503') throw new ValidationError('invalid space or parent', { @@ -68,20 +74,32 @@ router.get('/:id', ); router.patch('/:id', + requireWrite('page'), validate({ params: idParams, body: patchSchema }), asyncWrap(async (req, res) => { const existing = await repo.getById(req.params.id); if (!existing) throw new NotFoundError('page not found'); + if (req.capTier === 'suggest') { + return divertToPending(req, res, { + entity_type: 'page', entity_id: req.params.id, action: 'update', payload: req.body + }); + } const row = await repo.update(req.params.id, req.body, req.actor); res.json(row); }) ); router.delete('/:id', + requireWrite('page'), validate({ params: idParams }), asyncWrap(async (req, res) => { const existing = await repo.getById(req.params.id); if (!existing) throw new NotFoundError('page not found'); + if (req.capTier === 'suggest') { + return divertToPending(req, res, { + entity_type: 'page', entity_id: req.params.id, action: 'delete', payload: {} + }); + } await repo.del(req.params.id, req.actor); res.status(204).end(); }) diff --git a/lib/api/routes/projects.js b/lib/api/routes/projects.js index f9df7f6..4335ccb 100644 --- a/lib/api/routes/projects.js +++ b/lib/api/routes/projects.js @@ -3,6 +3,7 @@ import { z } from 'zod'; import * as repo from '../../db/repos/projects.js'; import { validate } from '../validate.js'; import { NotFoundError, ValidationError, asyncWrap } from '../errors.js'; +import { requireWrite, divertToPending } from '../cap.js'; const STATUSES = ['idea', 'active', 'paused', 'done', 'abandoned']; @@ -37,10 +38,15 @@ spacesScopedRouter.get('/', ); spacesScopedRouter.post('/', + requireWrite('project'), validate({ params: spaceParams, body: createSchema }), asyncWrap(async (req, res) => { + const payload = { ...req.body, space_id: req.params.space_id }; + if (req.capTier === 'suggest') { + return divertToPending(req, res, { entity_type: 'project', action: 'create', payload }); + } try { - const row = await repo.create({ ...req.body, space_id: req.params.space_id }, req.actor); + const row = await repo.create(payload, req.actor); res.status(201).json(row); } catch (e) { if (e.code === '23503') throw new ValidationError('invalid space', { space_id: req.params.space_id }); @@ -59,20 +65,32 @@ router.get('/:id', ); router.patch('/:id', + requireWrite('project'), validate({ params: idParams, body: patchSchema }), asyncWrap(async (req, res) => { const existing = await repo.getById(req.params.id); if (!existing) throw new NotFoundError('project not found'); + if (req.capTier === 'suggest') { + return divertToPending(req, res, { + entity_type: 'project', entity_id: req.params.id, action: 'update', payload: req.body + }); + } const row = await repo.update(req.params.id, req.body, req.actor); res.json(row); }) ); router.delete('/:id', + requireWrite('project'), validate({ params: idParams }), asyncWrap(async (req, res) => { const existing = await repo.getById(req.params.id); if (!existing) throw new NotFoundError('project not found'); + if (req.capTier === 'suggest') { + return divertToPending(req, res, { + entity_type: 'project', entity_id: req.params.id, action: 'delete', payload: {} + }); + } await repo.del(req.params.id, req.actor); res.status(204).end(); }) diff --git a/lib/api/routes/refs.js b/lib/api/routes/refs.js index 9f98fab..d7793ce 100644 --- a/lib/api/routes/refs.js +++ b/lib/api/routes/refs.js @@ -4,6 +4,7 @@ import * as repo from '../../db/repos/refs.js'; import { validate } from '../validate.js'; import { parsePagination } from '../pagination.js'; import { NotFoundError, ValidationError, asyncWrap } from '../errors.js'; +import { requireWrite, divertToPending } from '../cap.js'; const KINDS = ['url', 'video', 'pdf', 'image', 'file']; @@ -56,8 +57,12 @@ router.get('/', ); router.post('/', + requireWrite('ref'), validate({ body: createSchema }), asyncWrap(async (req, res) => { + if (req.capTier === 'suggest') { + return divertToPending(req, res, { entity_type: 'ref', action: 'create', payload: req.body }); + } try { const row = await repo.create(req.body, req.actor); res.status(201).json(row); @@ -69,8 +74,12 @@ router.post('/', ); router.post('/upsert', + requireWrite('ref'), validate({ body: upsertSchema }), asyncWrap(async (req, res) => { + if (req.capTier === 'suggest') { + return divertToPending(req, res, { entity_type: 'ref', action: 'upsert', payload: req.body }); + } try { const row = await repo.upsertByExternal(req.body, req.actor); res.json(row); @@ -91,20 +100,32 @@ router.get('/:id', ); router.patch('/:id', + requireWrite('ref'), validate({ params: idParams, body: patchSchema }), asyncWrap(async (req, res) => { const existing = await repo.getById(req.params.id); if (!existing) throw new NotFoundError('ref not found'); + if (req.capTier === 'suggest') { + return divertToPending(req, res, { + entity_type: 'ref', entity_id: req.params.id, action: 'update', payload: req.body + }); + } const row = await repo.update(req.params.id, req.body, req.actor); res.json(row); }) ); router.delete('/:id', + requireWrite('ref'), validate({ params: idParams }), asyncWrap(async (req, res) => { const existing = await repo.getById(req.params.id); if (!existing) throw new NotFoundError('ref not found'); + if (req.capTier === 'suggest') { + return divertToPending(req, res, { + entity_type: 'ref', entity_id: req.params.id, action: 'delete', payload: {} + }); + } await repo.del(req.params.id, req.actor); res.status(204).end(); }) diff --git a/lib/api/routes/resources.js b/lib/api/routes/resources.js index 3e13008..b667ff0 100644 --- a/lib/api/routes/resources.js +++ b/lib/api/routes/resources.js @@ -5,6 +5,7 @@ import * as sourceDocs from '../../db/repos/source_docs.js'; import * as audit from '../../db/repos/audit.js'; import { validate } from '../validate.js'; import { NotFoundError, ValidationError, ConflictError, asyncWrap } from '../errors.js'; +import { requireWrite, divertToPending } from '../cap.js'; const RUNTIME = ['lxc', 'vm', 'docker', 'bare-metal']; const STATUSES = ['running', 'stopped', 'down', 'unknown']; @@ -45,10 +46,15 @@ spacesScopedRouter.get('/', ); spacesScopedRouter.post('/', + requireWrite('resource'), validate({ params: spaceParams, body: createSchema }), asyncWrap(async (req, res) => { + const payload = { ...req.body, space_id: req.params.space_id }; + if (req.capTier === 'suggest') { + return divertToPending(req, res, { entity_type: 'resource', action: 'create', payload }); + } try { - const row = await repo.create({ ...req.body, space_id: req.params.space_id }, req.actor); + const row = await repo.create(payload, req.actor); res.status(201).json(row); } catch (e) { if (e.code === '23503') throw new ValidationError('invalid space', { space_id: req.params.space_id }); @@ -67,30 +73,48 @@ router.get('/:id', ); router.patch('/:id', + requireWrite('resource'), validate({ params: idParams, body: patchSchema }), asyncWrap(async (req, res) => { const existing = await repo.getById(req.params.id); if (!existing) throw new NotFoundError('resource not found'); + if (req.capTier === 'suggest') { + return divertToPending(req, res, { + entity_type: 'resource', entity_id: req.params.id, action: 'update', payload: req.body + }); + } res.json(await repo.update(req.params.id, req.body, req.actor)); }) ); router.delete('/:id', + requireWrite('resource'), validate({ params: idParams }), asyncWrap(async (req, res) => { const existing = await repo.getById(req.params.id); if (!existing) throw new NotFoundError('resource not found'); + if (req.capTier === 'suggest') { + return divertToPending(req, res, { + entity_type: 'resource', entity_id: req.params.id, action: 'delete', payload: {} + }); + } await repo.del(req.params.id, req.actor); res.status(204).end(); }) ); router.post('/:id/dependencies', + requireWrite('resource'), validate({ params: idParams, body: depBody }), asyncWrap(async (req, res) => { if (req.params.id === req.body.depends_on) { throw new ValidationError('resource cannot depend on itself'); } + if (req.capTier === 'suggest') { + return divertToPending(req, res, { + entity_type: 'resource', entity_id: req.params.id, action: 'add_dependency', payload: req.body + }); + } try { await repo.addDependency(req.params.id, req.body.depends_on, req.body.kind); res.status(201).json({ resource_id: req.params.id, depends_on: req.body.depends_on }); @@ -111,8 +135,15 @@ router.get('/:id/dependencies', ); router.delete('/:id/dependencies/:dep_id', + requireWrite('resource'), validate({ params: depParams }), asyncWrap(async (req, res) => { + if (req.capTier === 'suggest') { + return divertToPending(req, res, { + entity_type: 'resource', entity_id: req.params.id, action: 'remove_dependency', + payload: { depends_on: req.params.dep_id } + }); + } await repo.removeDependency(req.params.id, req.params.dep_id); res.status(204).end(); }) diff --git a/lib/api/routes/source_docs.js b/lib/api/routes/source_docs.js index 0fb2049..0df3ebc 100644 --- a/lib/api/routes/source_docs.js +++ b/lib/api/routes/source_docs.js @@ -3,6 +3,7 @@ import { z } from 'zod'; import * as repo from '../../db/repos/source_docs.js'; import { validate } from '../validate.js'; import { NotFoundError, ValidationError, asyncWrap } from '../errors.js'; +import { requireWrite, divertToPending } from '../cap.js'; const baseFields = { name: z.string().min(1).max(200), @@ -28,10 +29,15 @@ export const router = Router(); export const resourcesScopedRouter = Router({ mergeParams: true }); resourcesScopedRouter.post('/', + requireWrite('source_doc'), validate({ params: resourceParams, body: createSchema }), asyncWrap(async (req, res) => { + const payload = { ...req.body, resource_id: req.params.resource_id }; + if (req.capTier === 'suggest') { + return divertToPending(req, res, { entity_type: 'source_doc', action: 'create', payload }); + } try { - const row = await repo.create({ ...req.body, resource_id: req.params.resource_id }, req.actor); + const row = await repo.create(payload, req.actor); res.status(201).json(row); } catch (e) { if (e.code === '23503') throw new ValidationError('invalid resource', { @@ -52,19 +58,31 @@ router.get('/:id', ); router.patch('/:id', + requireWrite('source_doc'), validate({ params: idParams, body: patchSchema }), asyncWrap(async (req, res) => { const existing = await repo.getById(req.params.id); if (!existing) throw new NotFoundError('source doc not found'); + if (req.capTier === 'suggest') { + return divertToPending(req, res, { + entity_type: 'source_doc', entity_id: req.params.id, action: 'update', payload: req.body + }); + } res.json(await repo.update(req.params.id, req.body, req.actor)); }) ); router.delete('/:id', + requireWrite('source_doc'), validate({ params: idParams }), asyncWrap(async (req, res) => { const existing = await repo.getById(req.params.id); if (!existing) throw new NotFoundError('source doc not found'); + if (req.capTier === 'suggest') { + return divertToPending(req, res, { + entity_type: 'source_doc', entity_id: req.params.id, action: 'delete', payload: {} + }); + } await repo.del(req.params.id, req.actor); res.status(204).end(); }) diff --git a/lib/api/routes/tasks.js b/lib/api/routes/tasks.js index f145161..576bd25 100644 --- a/lib/api/routes/tasks.js +++ b/lib/api/routes/tasks.js @@ -3,6 +3,7 @@ import { z } from 'zod'; import * as repo from '../../db/repos/tasks.js'; import { validate } from '../validate.js'; import { NotFoundError, ValidationError, asyncWrap } from '../errors.js'; +import { requireWrite, divertToPending } from '../cap.js'; const STATUSES = ['todo', 'doing', 'blocked', 'done']; @@ -41,10 +42,15 @@ spacesScopedRouter.get('/', ); spacesScopedRouter.post('/', + requireWrite('task'), validate({ params: spaceParams, body: createSchema }), asyncWrap(async (req, res) => { + const payload = { ...req.body, space_id: req.params.space_id }; + if (req.capTier === 'suggest') { + return divertToPending(req, res, { entity_type: 'task', action: 'create', payload }); + } try { - const row = await repo.create({ ...req.body, space_id: req.params.space_id }, req.actor); + const row = await repo.create(payload, req.actor); res.status(201).json(row); } catch (e) { if (e.code === '23503') throw new ValidationError('invalid space or project', { @@ -72,20 +78,32 @@ router.get('/:id', ); router.patch('/:id', + requireWrite('task'), validate({ params: idParams, body: patchSchema }), asyncWrap(async (req, res) => { const existing = await repo.getById(req.params.id); if (!existing) throw new NotFoundError('task not found'); + if (req.capTier === 'suggest') { + return divertToPending(req, res, { + entity_type: 'task', entity_id: req.params.id, action: 'update', payload: req.body + }); + } const row = await repo.update(req.params.id, req.body, req.actor); res.json(row); }) ); router.delete('/:id', + requireWrite('task'), validate({ params: idParams }), asyncWrap(async (req, res) => { const existing = await repo.getById(req.params.id); if (!existing) throw new NotFoundError('task not found'); + if (req.capTier === 'suggest') { + return divertToPending(req, res, { + entity_type: 'task', entity_id: req.params.id, action: 'delete', payload: {} + }); + } await repo.del(req.params.id, req.actor); res.status(204).end(); }) diff --git a/tests/api/capability_routes.test.js b/tests/api/capability_routes.test.js new file mode 100644 index 0000000..c46d33a --- /dev/null +++ b/tests/api/capability_routes.test.js @@ -0,0 +1,65 @@ +import { describe, it, expect, beforeAll, beforeEach } from 'vitest'; +import request from 'supertest'; +import { setup } from './helpers.js'; +import * as spacesRepo from '../../lib/db/repos/spaces.js'; +import * as agentsRepo from '../../lib/db/repos/agents.js'; +import * as pendingChanges from '../../lib/db/repos/pending_changes.js'; + +let app, ownerHeaders, space; +const owner = { kind: 'user', id: null }; + +async function mintAgent(slug, caps, scopes = {}) { + const a = await agentsRepo.create({ + slug, name: slug, kind: 'claude', model: 'sonnet', + capabilities: caps, scopes + }, owner); + const { token } = await agentsRepo.createToken(a.id, 'test'); + return { agent: a, headers: { Authorization: `Bearer ${token}` } }; +} + +beforeAll(async () => { ({ app, ownerHeaders } = await setup()); }); +beforeEach(async () => { + space = await spacesRepo.create({ slug: `s-${Date.now()}-${Math.random().toString(36).slice(2,5)}`, name: 'S' }, owner); +}); + +describe('capability enforcement on writes', () => { + it('agent at allow tier writes through (201)', async () => { + const { headers } = await mintAgent(`allow-${Date.now()}`, + { read: true, write: true }, { page: true }); + const res = await request(app) + .post(`/api/spaces/${space.id}/pages`).set(headers) + .send({ slug: 'a', title: 'A', body_md: 'hi' }); + expect(res.status).toBe(201); + }); + + it('agent at suggest tier diverts to pending_changes (202)', async () => { + const { agent, headers } = await mintAgent(`sug-${Date.now()}`, + { read: true, suggest: true }); + const res = await request(app) + .post(`/api/spaces/${space.id}/pages`).set(headers) + .send({ slug: 'p', title: 'P', body_md: 'draft' }); + expect(res.status).toBe(202); + expect(res.body.pending).toBe(true); + expect(res.body.change_id).toBeDefined(); + const change = await pendingChanges.getById(res.body.change_id); + expect(change.agent_id).toBe(agent.id); + expect(change.entity_type).toBe('page'); + expect(change.action).toBe('create'); + expect(change.payload.title).toBe('P'); + }); + + it('agent at deny tier → 403', async () => { + const { headers } = await mintAgent(`deny-${Date.now()}`, { read: true }); + const res = await request(app) + .post(`/api/spaces/${space.id}/pages`).set(headers) + .send({ slug: 'p', title: 'P' }); + expect(res.status).toBe(403); + }); + + it('owner still writes through', async () => { + const res = await request(app) + .post(`/api/spaces/${space.id}/pages`).set(ownerHeaders) + .send({ slug: 'owner', title: 'Owner' }); + expect(res.status).toBe(201); + }); +});