mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-12-05 14:35:17 +01:00
Fix user attribution for agent lifecycle verification (#23800)
## Thinking Path > - Paperclip manages work for AI agents. > - An agent must pass execution checks before it can run work. > - Personal AI accounts require the identity of the responsible user. > - An environment change could start those checks without a user identity. > - The manual connection test still passed because it used the signed-in user. > - This pull request records the configuring user and repairs missing identity on an authorized retry. ## Linked Issues or Issue Description **What happened?** An agent could pass its manual connection test and stay paused after an environment change. Background verification had no responsible user and rejected access to the selected personal AI account. Retry now repeated the same failure. **Expected behavior** Verification started by a configuration change uses the configuring user. An authorized retry can repair an older operation that has no responsible user. Existing account sharing and task access checks still apply. **Steps to reproduce** 1. Use an agent with a personal AI connection and no saved lifecycle user or company default responsible user. 2. Move the agent to an environment that requires setup. 3. Run its manual connection test. The test passes under the signed-in user. 4. Observe failed background verification. Retry now does not repair the missing identity. **Paperclip version or commit** Reproduced on base commit `f0d4f6c3eb2e931f2f7a3e8b426f964aeb54aeee`. **Deployment mode** Authenticated hosted server. The local regression uses disposable PostgreSQL databases on macOS arm64, Node 25.6.1, and pnpm 9.15.4. ## What Changed - Record the authenticated responsible user when a configuration change starts a new lifecycle operation. Include the verified human context for an agent acting on behalf of a user. Keep the prior identity for changes without that context. - Pass the authenticated board identity to the existing retry command. Fill only missing responsibility; preserve an operation's recorded owner. - Start a new operation when repairing a missing identity. Repeat the host check under that identity. A prior attempt cannot complete the replacement operation. - Extend the lifecycle owner suites to cover human and delegated configuration attribution, retry repair, existing owners, active leases, readiness, and request-body spoofing. The existing board, agent, and company access checks remain covered. The lifecycle module owns the repair. Its internal store contract now accepts the authenticated retry identity. The routes supply those values after their existing authorization checks. No new API field, migration, provider policy, or credential permission is added. ## Verification - Before the fix, focused regressions failed in four cases: configuration attribution, board retry attribution, and retry identity repair with and without a lease. - The three owner suites passed all 141 tests after the fix. The final retry suite passed all 27 tests, including rejection of a stale host completion after identity repair. - Server typechecking passed with `node scripts/typecheck-layers.mjs` after the Runner and SDK build prerequisites. An initial test-only type error was corrected with the lifecycle operation type. - `pnpm verify --explain` returned exit 2 because the internal port type lies outside the resolved runtime test graph. Required CI will supply the listed broad typecheck, test, build, and end-to-end coverage. No full local suite pass is claimed. - Test budget, module boundaries, runtime push guard, whitespace, and local secret/PII checks passed. - CI found one stale mocked retry expectation in `agent-cross-tenant-authz-routes.test.ts`. It now checks the authenticated board user as well as the agent ID. All 18 tests in that suite pass locally. The interrupted native-runner CI job was stopped by a runner shutdown; the new revision will rerun CI. - Greptile reviewed the final `e5701b3584a57bbdde269b60439c561acca1f9b1` revision at 5/5. There are no unresolved review threads. - GitHub CI passed on `e5701b3584a57bbdde269b60439c561acca1f9b1`: all 68 reported checks are green, including typecheck, build, native Runner, serialized server, general tests, and end-to-end shards. [CI run](https://github.com/paperclipai/paperclip/actions/runs/47452634326). The initial canceled Runner attempt and stale mock failure are superseded by this successful run. - Hosted acceptance remains pending deployment of the reviewed revision. No live provider call is made by the regression tests. ## Risks - Identity repair does not change credential sharing. Verification still fails if the responsible user lacks access to the selected account. - An identity repair starts a replacement operation and fences any old lease. Existing plugin and host work must pass under that operation before readiness. - No schema or migration changes. Background retry behavior without an explicit user keeps the saved identity. ## Model Used - OpenAI `gpt-6.1-sol`, through the Codex harness in T3 Code, with xhigh reasoning and terminal tool access. The harness does not expose the context-window size. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [x] All Paperclip CI gates are green - [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge --------- Co-authored-by: Paperclip <noreply@paperclip.ing>
This commit is contained in:
1 parent
bf49fce70f
commit
f23af2e079
10 files changed
+73
-17
No files matched your search
@@ -779,7 +779,7 @@ describe("agent lifecycle retry authorization", () => {
|
||||
const res = await requestApp(app, base => request(base).post(`/api/agents/${agentId}/lifecycle/retry`).send({}));
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body).toMatchObject({ id: agentId, lifecycleState: "preparing", lifecycleError: null });
|
||||
expect(mockAgentService.retryLifecycle).toHaveBeenCalledWith(agentId);
|
||||
expect(mockAgentService.retryLifecycle).toHaveBeenCalledWith(agentId, "board");
|
||||
expect(mockLogActivity).toHaveBeenCalledWith(expect.anything(), expect.objectContaining({
|
||||
companyId, entityId: agentId, action: "agent.lifecycle_retried", actorType: "user", actorId: "board",
|
||||
}));
|
||||
|
||||
@@ -76,6 +76,7 @@ export interface ClaudeLoginContext {
|
||||
}
|
||||
|
||||
export interface UpdateAgentOptions {
|
||||
responsibleUserId?: string | null;
|
||||
expectedConfigurationRevision?: string;
|
||||
expectedConfiguration?: Pick<AgentConfigurationRecord, "adapterType" | "adapterConfig" | "runtimeConfig" | "defaultEnvironmentId">;
|
||||
recordRevision?: RevisionMetadata;
|
||||
|
||||
@@ -165,13 +165,19 @@ const support = await getEmbeddedPostgresTestSupport();
|
||||
});
|
||||
|
||||
it.each(["idle", "running"])("automatically pauses an %s agent, prepares its new environment, and verifies before readiness", async status => {
|
||||
const id = await agent(otherEnvironmentId, { status, lifecycleRequiredPluginIds: [] });
|
||||
const saved = await agentConfiguration(db).update(id, { defaultEnvironmentId: boundEnvironmentId });
|
||||
const id = await agent(otherEnvironmentId, { status, lifecycleRequiredPluginIds: [],
|
||||
lifecycleOperation: { id: randomUUID(), hostComplete: true, completedPluginIds: [], attempts: 0, responsibleUserId: "earlier-configurer" } });
|
||||
const saved = await agentConfiguration(db).update(id, { defaultEnvironmentId: boundEnvironmentId }, {
|
||||
recordRevision: { createdByUserId: "current-configurer", source: "patch" },
|
||||
});
|
||||
expect(saved).toMatchObject({ defaultEnvironmentId: boundEnvironmentId, lifecycleState: "pausing", status: "paused" });
|
||||
expect(await current(id)).toMatchObject({ lifecycleHolds: [], lifecycleOperation: { resumeState: "verifying" } });
|
||||
|
||||
const phases: string[] = [];
|
||||
const runHost = vi.fn(async (row: LifecycleAgent) => { phases.push(row.lifecycleState); return "complete" as const; });
|
||||
const runHost = vi.fn(async (row: LifecycleAgent) => {
|
||||
expect(row.lifecycleOperation?.responsibleUserId).toBe("current-configurer");
|
||||
phases.push(row.lifecycleState); return "complete" as const;
|
||||
});
|
||||
await worker(runHost).process(id);
|
||||
expect(phases).toEqual(["pausing", "resuming", "verifying"]);
|
||||
expect(call.mock.calls.map(args => args[2].phase)).toEqual(["resuming", "verifying"]);
|
||||
@@ -186,14 +192,22 @@ const support = await getEmbeddedPostgresTestSupport();
|
||||
principalId, membershipRole: "member", status: "active" });
|
||||
await db.insert(principalPermissionGrants).values({ companyId, principalType: type === "board" ? "user" : "agent",
|
||||
principalId, permissionKey: "agents:configure" });
|
||||
const responsibleUserId = type === "board" ? principalId : randomUUID();
|
||||
if (type === "agent") {
|
||||
await db.insert(companyMemberships).values({ companyId, principalType: "user", principalId: responsibleUserId,
|
||||
membershipRole: "member", status: "active" });
|
||||
await db.insert(principalPermissionGrants).values({ companyId, principalType: "user", principalId: responsibleUserId, permissionKey: "agents:configure" });
|
||||
}
|
||||
const actor: Express.Request["actor"] = type === "board"
|
||||
? { type, source: "session", userId: principalId, companyIds: [companyId],
|
||||
memberships: [{ companyId, membershipRole: "member", status: "active" }] }
|
||||
: { type, source: "agent_key", agentId: principalId, companyId };
|
||||
: { type, source: "agent_key", agentId: principalId, companyId, onBehalfOfUserId: responsibleUserId,
|
||||
onBehalfOfMemberships: [{ companyId, membershipRole: "member", status: "active" }] };
|
||||
await request(app(actor)).post(`/api/agents/${id}/pause`).send({}).expect(403);
|
||||
const response = await request(app(actor)).patch(`/api/agents/${id}`).send({ defaultEnvironmentId: boundEnvironmentId });
|
||||
expect(response.status, JSON.stringify(response.body)).toBe(200);
|
||||
expect(await current(id)).toMatchObject({ defaultEnvironmentId: boundEnvironmentId, lifecycleState: "pausing", status: "paused" });
|
||||
expect((await current(id)).lifecycleOperation?.responsibleUserId).toBe(responsibleUserId);
|
||||
});
|
||||
|
||||
it.each(["board", "agent"] as const)("rejects a %s without configuration permission before saving the environment or pausing", async type => {
|
||||
|
||||
@@ -1246,10 +1246,11 @@ const support = external ? { supported: true } : await getEmbeddedPostgresTestSu
|
||||
await db.insert(companyMemberships).values({ companyId, principalType: "user", principalId: "board", membershipRole: "admin" });
|
||||
await db.insert(principalPermissionGrants).values(["agents:create", "agents:configure"].map(permissionKey => ({ companyId, principalType: "user", principalId: "board", permissionKey })));
|
||||
const url = `/api/agents/${agent.id}/lifecycle/retry`;
|
||||
const response = await request(app(board)).post(url).send({});
|
||||
const response = await request(app(board)).post(url).send({ responsibleUserId: "untrusted-user" });
|
||||
expect(response.status, JSON.stringify(response.body)).toBe(200);
|
||||
expect(response.body.lifecycleState).toBe("preparing");
|
||||
expect(response.body).not.toHaveProperty("lifecycleOperation");
|
||||
expect((await current(agent.id)).lifecycleOperation?.responsibleUserId).toBe("board");
|
||||
expect(await db.select().from(activityLog).where(and(eq(activityLog.entityId, agent.id), eq(activityLog.action, "agent.lifecycle_retried"))))
|
||||
.toEqual([expect.objectContaining({ actorType: "user", actorId: "board" })]);
|
||||
await request(app({ type: "agent", source: "agent_key", companyId, agentId: agent.id })).post(url).send({}).expect(403);
|
||||
|
||||
@@ -173,20 +173,47 @@ const support = external ? { supported: true } : await getEmbeddedPostgresTestSu
|
||||
expect(await store.claim(agent!.id, "new-check", new Date())).not.toBeNull();
|
||||
});
|
||||
|
||||
it("permits an explicit retry of the same operation and completes verification before readiness", async () => {
|
||||
it.each([false, true].flatMap(leased => [undefined, "saved-owner"].map(responsibleUserId => ({ leased, responsibleUserId }))))(
|
||||
"repairs missing retry identity and fences older attempts: %j", async ({ leased, responsibleUserId }) => {
|
||||
const operation: NonNullable<LifecycleAgent["lifecycleOperation"]> = { id: randomUUID(), hostComplete: false, completedPluginIds: [], attempts: 0, responsibleUserId,
|
||||
...(leased ? { leaseOwner: "active-verifier", leaseUntil: new Date(Date.now() + 60_000).toISOString() } : { retryRequired: true }) };
|
||||
const [agent] = await db.insert(agents).values({ companyId, name: "Retry identity", status: "paused",
|
||||
lifecycleState: "verifying", lifecycleRequiredPluginIds: [], lifecycleOperation: operation }).returning();
|
||||
const store = createLifecycleStore(db, createAgentLifecycleEffects());
|
||||
await createAgentLifecycle(db).retry(agent.id, "requesting-user");
|
||||
const retried = await current(agent.id);
|
||||
if (!responsibleUserId) {
|
||||
expect(retried.lifecycleOperation).toMatchObject({ responsibleUserId: "requesting-user", hostComplete: false, completedPluginIds: [] });
|
||||
expect(retried.lifecycleOperation).not.toHaveProperty("leaseOwner");
|
||||
expect(retried.lifecycleOperation!.id).not.toBe(operation.id);
|
||||
expect(retried.lifecycleVersion).toBe(agent.lifecycleVersion + 1);
|
||||
expect(await store.completeHost(agent, "active-verifier")).toBe(false);
|
||||
return;
|
||||
}
|
||||
expect(retried.lifecycleOperation).toMatchObject({ id: operation.id,
|
||||
responsibleUserId: responsibleUserId ?? "requesting-user",
|
||||
...(leased ? { leaseOwner: operation.leaseOwner, leaseUntil: operation.leaseUntil, recheckRequested: true } : {}) });
|
||||
expect(retried.lifecycleVersion).toBe(agent.lifecycleVersion);
|
||||
},
|
||||
);
|
||||
|
||||
it("completes verification under the repaired identity before readiness", async () => {
|
||||
const { agent, work, runHost } = await failed();
|
||||
let release!: () => void;
|
||||
const verification = new Promise<void>(resolve => { release = resolve; });
|
||||
runHost.mockImplementation(async () => { await verification; return "complete"; });
|
||||
runHost.mockImplementation(async agent => {
|
||||
expect(agent.lifecycleOperation?.responsibleUserId).toBe("requesting-user");
|
||||
await verification; return "complete";
|
||||
});
|
||||
let processing: Promise<void> | undefined;
|
||||
try {
|
||||
await createAgentLifecycle(db).retry(agent.id);
|
||||
await createAgentLifecycle(db).retry(agent.id, "requesting-user");
|
||||
processing = work.process(agent.id);
|
||||
const retried = await current(agent.id);
|
||||
expect(retried).toMatchObject({ lifecycleState: "verifying", status: "paused" });
|
||||
expect(retried.lifecycleOperation).not.toHaveProperty("retryRequired");
|
||||
expect(retried.lifecycleOperation).not.toHaveProperty("verificationFailures");
|
||||
expect(retried.lifecycleOperation!.id).toBe(agent.lifecycleOperation!.id);
|
||||
expect(retried.lifecycleOperation!.id).not.toBe(agent.lifecycleOperation!.id);
|
||||
} finally {
|
||||
release();
|
||||
await processing;
|
||||
|
||||
@@ -55,7 +55,9 @@ export async function updateAgentConfiguration(tx: Db, effects: LifecycleEffects
|
||||
...(prepareSetup || prepareEnvironment ? { lifecycleState: "preparing" as const } : {}),
|
||||
...(pauseForEnvironment ? { lifecycleState: "pausing" as const, status: "paused", pausedAt: new Date() } : {}),
|
||||
...(stopSetup ? { lifecycleState: "pausing" as const } : {}),
|
||||
lifecycleOperation: { ...current.lifecycleOperation!, id: randomUUID(), hostComplete: false,
|
||||
lifecycleOperation: { ...current.lifecycleOperation!,
|
||||
responsibleUserId: options?.responsibleUserId ?? options?.recordRevision?.createdByUserId ?? current.lifecycleOperation?.responsibleUserId,
|
||||
id: randomUUID(), hostComplete: false,
|
||||
completedPluginIds: [], attempts: 0, leaseOwner: undefined, leaseUntil: undefined, leaseHolder: undefined,
|
||||
retryAt: undefined, retryRequired: undefined, verificationFailures: undefined,
|
||||
waitingForSignal: undefined, recheckRequested: undefined,
|
||||
|
||||
@@ -18,7 +18,7 @@ const LIFECYCLE_PENDING_MAX_MS = 60_000;
|
||||
export function lifecyclePendingRetryDelayMs(passes: number) {
|
||||
return Math.min(LIFECYCLE_PENDING_MAX_MS, LIFECYCLE_PENDING_BASE_MS * 2 ** Math.max(0, passes - 1));
|
||||
}
|
||||
type ChangeOptions = { version?: number; owner?: string; reason?: string };
|
||||
type ChangeOptions = { version?: number; owner?: string; reason?: string; responsibleUserId?: string | null };
|
||||
|
||||
// Prepared drafts wait for the wizard; they have no background verification obligation.
|
||||
export const pendingLifecycleWork = and(
|
||||
@@ -119,6 +119,16 @@ async function changeLockedAgent(tx: Db, effects: LifecycleEffects, agent: Lifec
|
||||
agent.lifecycleRequiredPluginIds.some(id => !agent.lifecycleOperation!.completedPluginIds.includes(id)))) return null;
|
||||
if (command === "retry") {
|
||||
transition(agent.lifecycleState, command);
|
||||
if (options.responsibleUserId && !agent.lifecycleOperation?.responsibleUserId) {
|
||||
await effects.notifyWork(tx);
|
||||
const [restarted] = await tx.update(agents).set({ lifecycleError: null, lifecycleVersion: agent.lifecycleVersion + 1,
|
||||
lifecycleOperation: { ...agent.lifecycleOperation, id: randomUUID(), responsibleUserId: options.responsibleUserId,
|
||||
hostComplete: false, completedPluginIds: [], attempts: 0, leaseOwner: undefined, leaseUntil: undefined, leaseHolder: undefined,
|
||||
retryAt: undefined, retryRequired: undefined, verificationFailures: undefined, waitingForSignal: undefined, recheckRequested: undefined },
|
||||
updatedAt: new Date(),
|
||||
}).where(eq(agents.id, agent.id)).returning();
|
||||
return restarted;
|
||||
}
|
||||
if (agent.lifecycleOperation?.leaseUntil && Date.parse(agent.lifecycleOperation.leaseUntil) > Date.now()) {
|
||||
await effects.notifyWork(tx);
|
||||
const [requested] = await tx.update(agents).set({ lifecycleOperation:
|
||||
|
||||
@@ -14,7 +14,7 @@ export interface LifecycleAgent {
|
||||
|
||||
export interface LifecycleStore {
|
||||
get(id: string): Promise<LifecycleAgent | null>;
|
||||
change(id: string, command: LifecycleCommand, options?: { version?: number; owner?: string; reason?: string }): Promise<LifecycleAgent | null>;
|
||||
change(id: string, command: LifecycleCommand, options?: { version?: number; owner?: string; reason?: string; responsibleUserId?: string | null }): Promise<LifecycleAgent | null>;
|
||||
claim(id: string, owner: string, now: Date): Promise<LifecycleAgent | null>;
|
||||
renew(agent: LifecycleAgent, owner: string, now: Date): Promise<boolean>;
|
||||
setRequiredPlugins(agent: LifecycleAgent, owner: string, pluginIds: string[]): Promise<boolean>;
|
||||
|
||||
@@ -106,8 +106,8 @@ export function createAgentLifecycle(db: Db, effects: LifecycleEffects) {
|
||||
assertRootDatabase(db);
|
||||
const records = agentRecords(db, effects);
|
||||
const store = createLifecycleStore(db, effects);
|
||||
async function change(id: string, command: "pause" | "resume" | "terminate" | "retry", reason?: string) {
|
||||
const result = await store.change(id, command, { reason });
|
||||
async function change(id: string, command: "pause" | "resume" | "terminate" | "retry", reason?: string, responsibleUserId?: string | null) {
|
||||
const result = await store.change(id, command, { reason, responsibleUserId });
|
||||
if (result) scheduleAgentLifecycle(db, id);
|
||||
return result ? records.getById(id) : null;
|
||||
}
|
||||
@@ -153,7 +153,7 @@ export function createAgentLifecycle(db: Db, effects: LifecycleEffects) {
|
||||
pauseAgent: (id: string, reason = "manual") => change(id, "pause", reason),
|
||||
resumeAgent: (id: string, reason = "user") => change(id, "resume", reason),
|
||||
terminateAgent: (id: string) => change(id, "terminate"),
|
||||
retry: (id: string) => change(id, "retry"),
|
||||
retry: (id: string, responsibleUserId?: string | null) => change(id, "retry", undefined, responsibleUserId),
|
||||
clearError: records.clearError,
|
||||
purgeAgent: (id: string) => purgeAgent(db, effects, id),
|
||||
};
|
||||
|
||||
@@ -6053,6 +6053,7 @@ export function agentRoutes(
|
||||
|
||||
const actor = getActorInfo(req);
|
||||
const updateOptions = {
|
||||
responsibleUserId: responsibleUserForAiRequest(req),
|
||||
expectedConfigurationRevision,
|
||||
...(runtimeSettings ? { expectedConfiguration: {
|
||||
adapterType: existing.adapterType, adapterConfig: existing.adapterConfig,
|
||||
@@ -6102,7 +6103,7 @@ export function agentRoutes(
|
||||
const existing = await getAccessibleAgent(req, res, id);
|
||||
if (!existing) return;
|
||||
await assertCanConfigureAgentSetup(req, existing);
|
||||
const agent = await svcLifecycle.retry(id);
|
||||
const agent = await svcLifecycle.retry(id, responsibleUserForAiRequest(req));
|
||||
if (!agent) { res.status(404).json({ error: "Agent not found" }); return; }
|
||||
const actor = getActorInfo(req);
|
||||
await logActivity(db, { companyId: agent.companyId, actorType: actor.actorType, actorId: actor.actorId,
|
||||
|
||||
Reference in new issue
Block a user