fix: isolate agent key usage write failures

Co-Authored-By: Paperclip <noreply@paperclip.ing>
This commit is contained in:
DottaandPaperclip committed 2026-07-22 18:48:52 +00:00
1 parent 8b288dbc1e
commit 08a6c8edaf
2 files changed
+50 -10

No files matched your search

@@ -384,6 +384,39 @@ describe("agent auth middleware", () => {
]);
});
it("keeps agent-key authentication available when the last-used update fails", async () => {
const companyId = randomUUID();
const agentId = randomUUID();
const token = "pcp_test_agent_key_update_failure";
const { db } = createDbState({
agent: { id: agentId, companyId },
agentKey: {
id: randomUUID(),
agentId,
companyId,
keyHash: hashToken(token),
responsibleUserId: "user-key",
},
});
db.update = () => ({
set: () => ({
where: () => Promise.reject(new Error("database unavailable")),
}),
});
const res = await request(createApp(db))
.get("/actor")
.set("Authorization", `Bearer ${token}`);
expect(res.status).toBe(200);
expect(res.body).toMatchObject({
type: "agent",
agentId,
companyId,
source: "agent_key",
});
});
it("rejects agent keys that lack a responsible user binding and audits the denial", async () => {
const companyId = randomUUID();
const agentId = randomUUID();
+17 -10
View File
@@ -363,16 +363,23 @@ export function actorMiddleware(db: Db, opts: ActorMiddlewareOptions): RequestHa
});
const authenticatedAt = new Date();
if (shouldUpdateAgentApiKeyLastUsed(key.lastUsedAt, authenticatedAt)) {
await db
.update(agentApiKeys)
.set({ lastUsedAt: authenticatedAt })
.where(and(
eq(agentApiKeys.id, key.id),
or(
isNull(agentApiKeys.lastUsedAt),
lt(agentApiKeys.lastUsedAt, new Date(authenticatedAt.getTime() - AGENT_API_KEY_LAST_USED_THROTTLE_MS)),
),
));
try {
await db
.update(agentApiKeys)
.set({ lastUsedAt: authenticatedAt })
.where(and(
eq(agentApiKeys.id, key.id),
or(
isNull(agentApiKeys.lastUsedAt),
lt(agentApiKeys.lastUsedAt, new Date(authenticatedAt.getTime() - AGENT_API_KEY_LAST_USED_THROTTLE_MS)),
),
));
} catch (err) {
logger.warn(
{ err, companyId: key.companyId, agentId: key.agentId, keyId: key.id },
"Failed to update agent API key last-used timestamp",
);
}
}
req.actor = {