Repository navigation
TASK-397: Log refused agent installs and placements #2522
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
63 changes: 63 additions & 0 deletions
63
backend/__tests__/unit/middleware/logAgentInstallRefusal.test.js
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,63 @@ | ||
| const { logAgentInstallRefusal } = require('../../../middleware/logAgentInstallRefusal'); | ||
|
|
||
| describe('agent install refusal logging', () => { | ||
| let warn; | ||
|
|
||
| beforeEach(() => { warn = jest.spyOn(console, 'warn').mockImplementation(() => {}); }); | ||
| afterEach(() => { warn.mockRestore(); }); | ||
|
|
||
| test('machine placement refusal records wrapper and omits credentials', () => { | ||
| const req = { | ||
| body: { agentName: 'my-agent', instanceId: 'default', machineId: 'machine-1', token: 'secret' }, | ||
| user: { id: 'owner-1' }, | ||
| }; | ||
| const res = { | ||
| statusCode: 200, | ||
| locals: {}, | ||
| json: jest.fn(), | ||
| }; | ||
| const next = jest.fn(); | ||
| logAgentInstallRefusal('/api/agent-binding/request', 'wrapper')(req, res, next); | ||
| expect(next).toHaveBeenCalledTimes(1); | ||
| res.statusCode = 404; | ||
| res.json({ message: 'Agent identity not found' }); | ||
| expect(warn).toHaveBeenCalledTimes(1); | ||
| const line = JSON.parse(warn.mock.calls[0][1]); | ||
| expect(line).toEqual({ | ||
| route: '/api/agent-binding/request', | ||
| agentName: 'my-agent', | ||
| instanceId: 'default', | ||
| runtimeType: 'wrapper', | ||
| reason: 'agent_identity_not_found', | ||
| userId: 'owner-1', | ||
| }); | ||
| expect(warn.mock.calls[0].join(' ')).not.toContain('secret'); | ||
| expect(warn.mock.calls[0].join(' ')).not.toContain('machine-1'); | ||
| }); | ||
|
|
||
| test('credential-shaped values in logged fields are redacted before serialization', () => { | ||
| const credential = 'cm_agent_example123'; | ||
| const req = { | ||
| body: { | ||
| agentName: credential, | ||
| instanceId: credential, | ||
| config: { runtime: { runtimeType: credential } }, | ||
| }, | ||
| user: { id: 'owner-1' }, | ||
| }; | ||
| const res = { statusCode: 404, locals: {}, json: jest.fn() }; | ||
| logAgentInstallRefusal('/api/registry/install')(req, res, () => {}); | ||
| res.json({ error: 'Agent not found in registry' }); | ||
| expect(warn).toHaveBeenCalledTimes(1); | ||
| const fullLine = warn.mock.calls[0].join(' '); | ||
| expect(fullLine).not.toContain(credential); | ||
| expect(JSON.parse(warn.mock.calls[0][1])).toEqual({ | ||
| route: '/api/registry/install', | ||
| agentName: '[redacted]', | ||
| instanceId: '[redacted]', | ||
| runtimeType: 'unknown', | ||
| reason: 'agent_not_found_in_registry', | ||
| userId: 'owner-1', | ||
| }); | ||
| }); | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,74 @@ | ||
| import { NextFunction, Request, Response } from 'express'; | ||
|
|
||
| type RefusalBody = { code?: unknown; error?: unknown; message?: unknown; msg?: unknown }; | ||
|
|
||
| // Only static response text is mapped. Unknown responses retain a bounded HTTP | ||
| // code rather than turning user-supplied error text into a log dimension. | ||
| const reasonByMessage: Record<string, string> = { | ||
| 'Agent not found in registry': 'agent_not_found_in_registry', | ||
| 'Agent identity not found': 'agent_identity_not_found', | ||
| 'Machine not found': 'machine_not_found', | ||
| 'Pod not found': 'pod_not_found', | ||
| Unauthorized: 'unauthorized', | ||
| 'agentName required': 'agent_name_required', | ||
| 'agentName must be a string': 'agent_name_invalid', | ||
| 'machineId required (null to withdraw)': 'machine_id_required', | ||
| }; | ||
|
|
||
| const runtimeTypes = new Set([ | ||
| 'webhook', 'wrapper', 'hosted', 'native', 'moltbot', 'internal', | ||
| 'managed-agents', 'claude-code', 'codex', | ||
| ]); | ||
|
|
||
| const credentialPrefix = /^(?:cm[_-]agent[_-]|gh[opurs][_-]|github[_-]pat[_-]|sk-|xox[abprs]-|bearer|eyj)/i; | ||
|
|
||
| const logIdentity = (value: unknown, allowScopedName = false): string | null => { | ||
| if (typeof value !== 'string') return null; | ||
| const name = value.trim().toLowerCase(); | ||
| const valid = allowScopedName | ||
| ? /^(@[a-z0-9-]+\/)?[a-z0-9-]+$/.test(name) | ||
| : /^[a-z0-9-]+$/.test(name); | ||
| // Refused requests can supply credentials in place of names. Never "clean" | ||
| // an invalid value into something that resembles a safe identity. | ||
| if (!valid || name.length > 64 || credentialPrefix.test(name)) return '[redacted]'; | ||
| return name || null; | ||
| }; | ||
|
|
||
| const logRuntimeType = (value: unknown): string | null => { | ||
| if (typeof value !== 'string') return null; | ||
| const runtimeType = value.trim().toLowerCase(); | ||
| return runtimeTypes.has(runtimeType) ? runtimeType : 'unknown'; | ||
| }; | ||
|
|
||
| const reasonCode = (body: RefusalBody, status: number): string => { | ||
| if (typeof body.code === 'string' | ||
| && /^[a-z][a-z0-9_]{0,79}$/.test(body.code) | ||
| && !credentialPrefix.test(body.code)) return body.code; | ||
| const message = body.error || body.message || body.msg; | ||
| return typeof message === 'string' ? reasonByMessage[message] || `http_${status}` : `http_${status}`; | ||
| }; | ||
|
|
||
| /** Record one structured line for each refused install or machine placement. */ | ||
| export const logAgentInstallRefusal = (route: string, defaultRuntimeType?: string) => ( | ||
| req: Request & { user?: { id?: unknown } }, res: Response, next: NextFunction, | ||
| ): void => { | ||
| const originalJson = res.json.bind(res); | ||
| let logged = false; | ||
| res.json = ((body: RefusalBody) => { | ||
| if (!logged && res.statusCode >= 400) { | ||
| logged = true; | ||
| const requestBody = req.body && typeof req.body === 'object' ? req.body : {}; | ||
| const runtime = requestBody.config?.runtime?.runtimeType || requestBody.runtimeType || defaultRuntimeType; | ||
| console.warn('[agent-install-refused]', JSON.stringify({ | ||
| route, | ||
| agentName: logIdentity(requestBody.agentName, true), | ||
| instanceId: logIdentity(res.locals.agentInstallInstanceId || requestBody.instanceId) || 'default', | ||
| runtimeType: logRuntimeType(runtime), | ||
| reason: reasonCode(body && typeof body === 'object' ? body : {}, res.statusCode), | ||
| userId: req.user?.id == null ? null : String(req.user.id), | ||
| })); | ||
| } | ||
| return originalJson(body); | ||
| }) as Response['json']; | ||
| next(); | ||
| }; | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🔒 Security & Privacy | 🟠 Major | ⚡ Quick win
Redact unprefixed credential values before logging identities.
A 32-character hexadecimal token such as
0123456789abcdef0123456789abcdefpasses this validation. If a requester puts that token inagentNameorinstanceId, a JSON refusal writes the token to the warning log. Reject opaque credential-shaped values or log a non-reversible identifier instead. As per coding guidelines, “No secrets in logs, commits, response bodies, or env vars named to look benign.”🤖 Prompt for AI Agents
Source: Coding guidelines