Skip to content
Closed
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
204 changes: 204 additions & 0 deletions backend/__tests__/integration/self-serve-install.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,204 @@
/**
* ADR-006 Phase 1 — self-serve webhook install integration test.
*
* Walks the full self-serve flow:
* authed pod-member POSTs /install with runtimeType:'webhook' and NO
* pre-published manifest → backend synthesizes ephemeral AgentRegistry row
* → mints runtime token → token authorizes /events + posting messages
* → ephemeral row is excluded from marketplace catalog browse
* → non-webhook installs without manifest still 404.
*/

const express = require('express');
const request = require('supertest');
const jwt = require('jsonwebtoken');

const { setupMongoDb, closeMongoDb } = require('../utils/testUtils');

const User = require('../../models/User');
const Pod = require('../../models/Pod');
const { AgentRegistry, AgentInstallation } = require('../../models/AgentRegistry');

const registryRoutes = require('../../routes/registry');
const agentsRuntimeRoutes = require('../../routes/agentsRuntime');

const JWT_SECRET = 'test-jwt-secret-self-serve-install';

jest.setTimeout(60000);

describe('ADR-006 self-serve webhook install', () => {
let app;
let podMember;
let outsider;
let memberToken;
let outsiderToken;
let pod;

beforeAll(async () => {
process.env.JWT_SECRET = JWT_SECRET;
await setupMongoDb();

app = express();
app.use(express.json());
app.use('/api/registry', registryRoutes);
app.use('/api/agents/runtime', agentsRuntimeRoutes);

podMember = await User.create({
username: 'pod-member',
email: 'pod-member@test.com',
password: 'password123',
});
outsider = await User.create({
username: 'outsider',
email: 'outsider@test.com',
password: 'password123',
});
memberToken = jwt.sign({ id: podMember._id.toString() }, JWT_SECRET);
outsiderToken = jwt.sign({ id: outsider._id.toString() }, JWT_SECRET);

pod = await Pod.create({
name: 'Self-Serve Test Pod',
type: 'chat',
createdBy: podMember._id,
members: [podMember._id],
});
});

afterAll(async () => {
await closeMongoDb();
});

beforeEach(async () => {
await AgentInstallation.deleteMany({});
// Wipe both ephemeral self-serve rows AND any non-ephemeral fixtures
// created by individual tests, so order/parallelism doesn't leak.
await AgentRegistry.deleteMany({ agentName: { $regex: /^(public-|my-|outsider-|fallback-|collide|bad-|research-)/ } });
await AgentRegistry.deleteMany({ ephemeral: true });
});

it('installs a webhook agent with no published manifest and returns a runtime token', async () => {
const installRes = await request(app)
.post('/api/registry/install')
.set('Authorization', `Bearer ${memberToken}`)
.send({
agentName: 'my-research-bot',
podId: pod._id.toString(),
displayName: 'My Research Bot',
version: '1.0.0',
config: {
runtime: {
runtimeType: 'webhook',
},
},
scopes: ['context:read', 'messages:write'],
});

expect(installRes.status).toBe(200);
expect(installRes.body.success).toBe(true);
expect(installRes.body.installation.agentName).toBe('my-research-bot');

// Synthesized registry row marked ephemeral, owned by installer.
const reg = await AgentRegistry.findOne({ agentName: 'my-research-bot' });
expect(reg).toBeTruthy();
expect(reg.ephemeral).toBe(true);
expect(reg.publisher.userId.toString()).toBe(podMember._id.toString());
expect(reg.registry).toBe('private');

// Mint runtime token + verify it can poll events.
const tokenRes = await request(app)
.post(`/api/registry/pods/${pod._id}/agents/my-research-bot/runtime-tokens`)
.set('Authorization', `Bearer ${memberToken}`)
.send({ label: 'self-serve-test' });
const runtimeToken = tokenRes.body.token;
expect(runtimeToken).toMatch(/^cm_agent_/);

const eventsRes = await request(app)
.get('/api/agents/runtime/events')
.set('Authorization', `Bearer ${runtimeToken}`);
expect(eventsRes.status).toBe(200);
expect(Array.isArray(eventsRes.body.events)).toBe(true);
});

it('non-webhook installs without published manifest still 404', async () => {
const res = await request(app)
.post('/api/registry/install')
.set('Authorization', `Bearer ${memberToken}`)
.send({
agentName: 'unknown-native-agent',
podId: pod._id.toString(),
config: { runtime: { runtimeType: 'native' } },
scopes: ['context:read'],
});
expect(res.status).toBe(404);
expect(res.body.error).toMatch(/not found in registry/i);
});

it('rejects malformed agentName with 400 (not 500 from schema validation)', async () => {
const res = await request(app)
.post('/api/registry/install')
.set('Authorization', `Bearer ${memberToken}`)
.send({
agentName: 'has spaces',
podId: pod._id.toString(),
config: { runtime: { runtimeType: 'webhook' } },
scopes: ['context:read'],
});
expect(res.status).toBe(400);
expect(res.body.error).toMatch(/Invalid agentName/);
// No row should have been created on validation failure.
const reg = await AgentRegistry.findOne({ agentName: 'has spaces' });
expect(reg).toBeNull();
});

it('rejects self-serve install when caller is not a pod member', async () => {
const res = await request(app)
.post('/api/registry/install')
.set('Authorization', `Bearer ${outsiderToken}`)
.send({
agentName: 'outsider-bot',
podId: pod._id.toString(),
config: { runtime: { runtimeType: 'webhook' } },
scopes: ['context:read'],
});
expect(res.status).toBe(403);
// No ephemeral row should have been created.
const reg = await AgentRegistry.findOne({ agentName: 'outsider-bot' });
expect(reg).toBeNull();
});

it('marketplace catalog excludes ephemeral self-serve agents', async () => {
// Create one published agent and one ephemeral via self-serve.
await AgentRegistry.create({
agentName: 'public-marketplace-bot',
displayName: 'Public Bot',
description: 'Catalog-visible',
registry: 'commonly-community',
manifest: {
name: 'public-marketplace-bot',
version: '1.0.0',
capabilities: [],
context: { required: [] },
runtime: { type: 'standalone', connection: 'rest' },
},
latestVersion: '1.0.0',
versions: [{ version: '1.0.0', publishedAt: new Date() }],
});
await request(app)
.post('/api/registry/install')
.set('Authorization', `Bearer ${memberToken}`)
.send({
agentName: 'my-private-webhook',
podId: pod._id.toString(),
config: { runtime: { runtimeType: 'webhook' } },
scopes: ['context:read'],
});

const catalogRes = await request(app)
.get('/api/registry/agents')
.set('Authorization', `Bearer ${memberToken}`);
expect(catalogRes.status).toBe(200);
const names = (catalogRes.body.agents || []).map((a) => a.name);
expect(names).toContain('public-marketplace-bot');
expect(names).not.toContain('my-private-webhook');
});
});
10 changes: 9 additions & 1 deletion backend/models/AgentRegistry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,7 @@ export interface IAgentRegistry extends Document {
};
status: RegistryStatus;
iconUrl?: string;
ephemeral?: boolean;
createdAt: Date;
updatedAt: Date;
}
Expand Down Expand Up @@ -140,6 +141,11 @@ const AgentRegistrySchema = new Schema<IAgentRegistry>(
},
status: { type: String, enum: ['active', 'deprecated', 'unpublished', 'pending-review'], default: 'active' },
iconUrl: String,
// ADR-006: self-serve webhook installs synthesize an ephemeral registry
// row owned by the installing user. Excluded from the marketplace catalog
// (search() filters by default), still resolvable by name for install/
// uninstall flows. GC of orphan ephemerals is deferred (ADR-006 OQ #1).
ephemeral: { type: Boolean, default: false },
},
{ timestamps: true },
);
Expand All @@ -156,7 +162,9 @@ AgentRegistrySchema.statics.search = function (
options: { limit?: number; offset?: number; category?: string | null; registry?: string | null; verified?: boolean | null } = {},
) {
const { limit = 20, offset = 0, category = null, registry = null, verified = null } = options;
const filter: Record<string, unknown> = { status: 'active' };
// Self-serve / ephemeral rows are private to their installer — never appear
// in marketplace browse. Direct getByName() lookup still resolves them.
const filter: Record<string, unknown> = { status: 'active', ephemeral: { $ne: true } };
if (query) filter.$text = { $search: query };
if (category) filter.categories = category;
if (registry) filter.registry = registry;
Expand Down
64 changes: 59 additions & 5 deletions backend/routes/registry/install.ts
Original file line number Diff line number Diff line change
Expand Up @@ -82,11 +82,6 @@ installRouter.post('/install', auth, async (req: any, res: any) => {
return res.status(401).json({ error: 'Unauthorized' });
}

const agent = await AgentRegistry.getByName(agentName);
if (!agent) {
return res.status(404).json({ error: 'Agent not found in registry' });
}

const pod = await Pod.findById(podId).lean();
if (!pod) {
return res.status(404).json({ error: 'Pod not found' });
Expand All @@ -103,6 +98,65 @@ installRouter.post('/install', auth, async (req: any, res: any) => {
return res.status(403).json({ error: 'You must be a member of this pod' });
}

let agent = await AgentRegistry.getByName(agentName);

// ADR-006 §Self-serve install: when a pod member installs a webhook-typed
// agent that has no published manifest, synthesize an ephemeral registry
// row owned by them. Marketplace catalog excludes ephemeral rows; only
// direct getByName() resolves them. Membership check above is the gate.
if (!agent) {
const requestedRuntimeType = String(
(config && config.runtime && (config.runtime as any).runtimeType) || '',
).toLowerCase();
if (requestedRuntimeType !== 'webhook') {
return res.status(404).json({ error: 'Agent not found in registry' });
}
// ADR-006 §invariant 7 — self-serve is pod-scope only. The route
// already requires `podId` (pod 404 above guards this), but the
// explicit check here keeps the invariant in source so a future
// refactor that adds instance/user/dm scope can't bypass it.
if (!podId) {
return res.status(400).json({ error: 'podId is required for self-serve install' });
}
// The AgentRegistry schema enforces /^[a-z0-9-]+$/ at write time, so
// a malformed name would surface as a Mongoose 500. Reject upstream.
if (!/^[a-z0-9-]+$/.test(String(agentName).toLowerCase())) {
return res.status(400).json({
error: 'Invalid agentName: must match /^[a-z0-9-]+$/',
});
}
// manifest.runtime.type is the registry-level deployment shape
// (enum: 'standalone' | 'commonly-hosted' | 'hybrid'). Self-serve
// webhook agents run outside Commonly so they map to 'standalone'.
// The actual webhook routing is driven by config.runtime.runtimeType
// on the AgentInstallation, not on the registry manifest.
const synthManifest = {
name: String(agentName).toLowerCase(),
version: String(version || '1.0.0'),
description: String(displayName || agentName),
capabilities: [],
context: { required: [], optional: [] },
runtime: { type: 'standalone', connection: 'rest' },
};
agent = await AgentRegistry.create({
agentName: synthManifest.name,
displayName: String(displayName || agentName),
description: synthManifest.description,
manifest: synthManifest,
latestVersion: synthManifest.version,
versions: [{ version: synthManifest.version, manifest: synthManifest, publishedAt: new Date() }],
registry: 'private',
publisher: { userId, name: req.user?.username },
ephemeral: true,
});
console.log('[cap self-serve-install]', {
user: String(userId),
pod: String(podId),
agent: synthManifest.name,
runtime: 'webhook',
});
}

let normalizedInstanceId;
if (instanceId) {
normalizedInstanceId = normalizeInstanceId(instanceId);
Expand Down
4 changes: 4 additions & 0 deletions backend/routes/registry/pod-agents.ts
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,10 @@ podAgentsRouter.delete('/agents/:name/pods/:podId', auth, async (req: any, res:
await AgentInstallation.uninstall(name, podId, instanceId);
await AgentProfile.deleteOne({ agentId: buildAgentProfileId(name, instanceId), podId });

// ADR-006 OQ #1: ephemeral self-serve registry rows whose only
// installation was just removed are leaked here. v1 punts; the GC
// janitor lands when orphan-row volume warrants it.

try {
const resolvedType = AgentIdentityService.resolveAgentType(name);
await AgentIdentityService.removeAgentFromPod(
Expand Down
Loading
Loading