Skip to content

Commit 8bbd01b

Browse files
committed
Prove a stored capability reason has one masked source on every surface
The #3278 mask is only half the guarantee: the stored reason is printed by four readers, and nothing tested them. Two fixtures saved before the fix (stdio argv plus env, and an http header) take one new start failure and assert the literal is absent from the status answer, the list_capabilities text, the prompt line and the log; the first three must repeat the same masked sentence, and detaching the item empties them, which shows they read one stored reason built at one place.
1 parent 56db822 commit 8bbd01b

6 files changed

Lines changed: 448 additions & 20 deletions

File tree

‎changelog.d/3278.fixed.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
A capability's stored failure reason no longer repeats a credential the user typed into the capability's own command or arguments, or under a header or environment name that promises one: a value after a credential-looking flag in a stdio server's `command`/`args` (the next token, the `--flag=value` form, or a `NAME=value` token), and the value of a header or environment name such as `sig`, `hmac` or `pass` — with `sig` and `pass` matched as whole segments, so `assign`, `compass` and `bypass` keep their values — is masked with `[hidden]` before the stored reason is cut at 300 characters, longest value first and a value under six characters left alone, so a failed server's own error line can no longer print that credential into the Bot's system prompt every turn ([#3278](https://github.com/ThinkFlowLab/FlyBot/issues/3278)).

‎core/src/host/capabilities.js‎

Lines changed: 33 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -48,20 +48,45 @@ const withoutUserinfo = text => text.replace(/([a-z][a-z0-9+.-]*:\/\/)[^/\s@]+@/
4848
// value under six characters is left alone: replacing it everywhere would eat the words around it.
4949
// The literal is not refused at input instead — it is legal today, an entry saved before this exists
5050
// in the field, and what such a value may be kept at rest is the separate open question in #3276.
51-
// `pat` counts as a whole segment: `X-Github-Pat` is a credential while `X-Patch-Id` and `X-Path-Id`
52-
// are ordinary names that merely begin with the same three letters.
53-
const CREDENTIAL_NAME = /(key|token|secret|auth|password|passwd|credential|signature|cookie|session|bearer)|(?<![a-z0-9])pat(?![a-z0-9])/i
51+
// `pat`, `sig` and `pass` count as a whole segment: `X-Github-Pat` is a credential while `X-Patch-Id`
52+
// and `X-Path-Id` are ordinary names that merely begin with the same three letters, and `X-Sig` /
53+
// `X-Pass` are credentials while `assign`, `compass` and `bypass` are ordinary names.
54+
// #3278: a stdio server is started with the literal on its argv, and a failure to start quotes that
55+
// argv back, so the values are read from the command and the args as well — a token after a
56+
// credential-looking flag is the literal, `--flag=value` is the same pair, and a `NAME=value` token is
57+
// read as an assignment. A bare token is never a literal: `node` or `server.js` cannot be told from a
58+
// program name, but a literal that is also a header or environment value is masked wherever the
59+
// body repeats it, the command position included.
60+
const CREDENTIAL_NAME = /(key|token|secret|auth|password|passwd|credential|signature|cookie|session|bearer|hmac)|(?<![a-z0-9])(pat|sig|pass)(?![a-z0-9])/i
61+
const FLAG = /^--?([\w-]+)$/
62+
const INLINE_FLAG = /^--?([^=]+)=(.*)$/
63+
const ASSIGNMENT = /^([A-Za-z_][\w-]*)=(.*)$/
5464
const withoutCredentialValues = (text, config) => {
65+
const values = []
66+
const collect = (name, value) => {
67+
if (typeof value === 'string' && value.length >= 6 && CREDENTIAL_NAME.test(name)) values.push(value)
68+
}
69+
for (const [name, value] of Object.entries({ ...config?.headers, ...config?.env })) collect(name, value)
70+
const argv = [config?.command, ...(Array.isArray(config?.args) ? config.args : [])]
71+
for (let index = 0; index < argv.length; index += 1) {
72+
const token = argv[index]
73+
if (typeof token !== 'string') continue
74+
const inline = INLINE_FLAG.exec(token)
75+
if (inline) { collect(inline[1], inline[2]); continue }
76+
const assignment = ASSIGNMENT.exec(token)
77+
if (assignment) { collect(assignment[1], assignment[2]); continue }
78+
const flag = FLAG.exec(token)
79+
const next = argv[index + 1]
80+
if (!flag || !CREDENTIAL_NAME.test(flag[1]) || typeof next !== 'string' || next.startsWith('-')) continue
81+
collect(flag[1], next)
82+
index += 1
83+
}
5584
// Longest value first, the way `secrets.js` sorts its own before it builds one pattern: one
5685
// credential can contain another (`Bearer abc123XYZ` carries the `abc123` of the key beside it),
5786
// and replacing the short one first would leave the longer one's tail in the stored sentence.
5887
// Sorting makes the answer the same whichever order the two entries were written in.
59-
const values = Object.entries({ ...config?.headers, ...config?.env })
60-
.filter(([name, value]) => CREDENTIAL_NAME.test(name) && typeof value === 'string' && value.length >= 6)
61-
.map(([, value]) => value)
62-
.sort((a, b) => b.length - a.length)
6388
let out = text
64-
for (const value of values) out = out.split(value).join('[hidden]')
89+
for (const value of [...new Set(values)].sort((a, b) => b.length - a.length)) out = out.split(value).join('[hidden]')
6590
return out
6691
}
6792

‎core/test/capabilities.test.js‎

Lines changed: 186 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import assert from 'node:assert/strict'
2-
import { mkdtempSync, rmSync, writeFileSync } from 'node:fs'
2+
import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
33
import { tmpdir } from 'node:os'
44
import { join } from 'node:path'
55
import { test } from 'node:test'
@@ -648,3 +648,188 @@ test('a plain reason is stored exactly as the transport gave it', async t => {
648648
assert.equal(status.state, 'error')
649649
assert.equal(status.error, '401 bad credentials')
650650
})
651+
652+
// #3278: a stdio server is started with the literal on its argv, and a failure to start quotes that
653+
// argv back, so the mask reads the command and the args the way it reads a header: the token after a
654+
// credential-looking flag is the literal, `--flag=value` is the same pair, and a `NAME=value` token is
655+
// read as an assignment. An ordinary flag in the same argv keeps its value.
656+
test('an error that quotes a stdio server argv stores the credential literal masked', async t => {
657+
const state = team()
658+
state.capabilities = {
659+
items: {
660+
stdio: {
661+
name: 'stdio', kind: 'mcp', description: 'Local server', transport: 'stdio', command: 'node',
662+
args: ['server.js', '--api-key', 'sk-live-abcdef123456', '-e', 'SERVICE_TOKEN=tok-abcdef123', '--password=hunter2-secret', '--verbose'],
663+
env: {}, approved: true, createdBy: 'worker', createdAt: 1, updatedAt: 1,
664+
},
665+
},
666+
}
667+
const env = await setup({ state })
668+
t.after(() => env.dispose())
669+
const { ctx, rt, mounts, skills } = env
670+
await rt.changeCapabilityAttachment('attach', { name: 'stdio' }, 'worker')
671+
const quoted = 'server exited: node server.js --api-key sk-live-abcdef123456 -e SERVICE_TOKEN=tok-abcdef123 --password=hunter2-secret --verbose'
672+
ctx.emit('agent/created', { agent: testAgent('worker', mounts, skills, { awaitMount: async () => { throw new Error(quoted) } }) })
673+
await rt.scheduleCapabilitiesReconcile()
674+
const status = rt.capabilityStatusesView().worker.stdio
675+
assert.equal(status.state, 'error')
676+
assert.equal(
677+
status.error,
678+
'server exited: node server.js --api-key [hidden] -e SERVICE_TOKEN=[hidden] --password=[hidden] --verbose',
679+
'every argv literal is masked; the program and the ordinary flag survive',
680+
)
681+
const stored = JSON.stringify(rt.capabilityStatusesView())
682+
assert.equal(stored.includes('sk-live-abcdef123456'), false)
683+
assert.equal(stored.includes('tok-abcdef123'), false)
684+
assert.equal(stored.includes('hunter2-secret'), false)
685+
})
686+
687+
// #3278, from the security read at `48f1eb43`: `sig`, `hmac` and `pass` were still missing from the
688+
// name list, so a body echoing `X-Sig: …`, `X-Hmac: …` or `X-Pass: …` stored the value verbatim.
689+
// `sig` and `pass` count as a whole segment the way `pat` does, so `assign`, `compass` and `bypass` are
690+
// ordinary names that keep their values.
691+
test('a sig, hmac or pass header name masks its value while assign, compass and bypass keep theirs', async t => {
692+
const state = team()
693+
state.capabilities = quoting('name-echo', {
694+
'X-Sig': 'sig-abcdef123', 'X-Hmac': 'hmac-abcdef123', 'X-Pass': 'pass-abcdef123',
695+
'X-Assign': 'assign-9000', 'X-Compass': 'compass-9000', 'X-Bypass': 'bypass-9000',
696+
})
697+
const env = await setup({ state })
698+
t.after(() => env.dispose())
699+
const { ctx, rt, mounts, skills } = env
700+
await rt.changeCapabilityAttachment('attach', { name: 'name-echo' }, 'worker')
701+
const quoted = 'Error POSTing to endpoint: {"sig":"sig-abcdef123","hmac":"hmac-abcdef123","pass":"pass-abcdef123","assign":"assign-9000","compass":"compass-9000","bypass":"bypass-9000"}'
702+
ctx.emit('agent/created', { agent: testAgent('worker', mounts, skills, { awaitMount: async () => { throw new Error(quoted) } }) })
703+
await rt.scheduleCapabilitiesReconcile()
704+
const status = rt.capabilityStatusesView().worker['name-echo']
705+
assert.equal(status.state, 'error')
706+
assert.equal(
707+
status.error,
708+
'Error POSTing to endpoint: {"sig":"[hidden]","hmac":"[hidden]","pass":"[hidden]","assign":"assign-9000","compass":"compass-9000","bypass":"bypass-9000"}',
709+
'the three new names mask; the three lookalike names keep their values',
710+
)
711+
const stored = JSON.stringify(rt.capabilityStatusesView())
712+
assert.equal(stored.includes('sig-abcdef123'), false)
713+
assert.equal(stored.includes('hmac-abcdef123'), false)
714+
assert.equal(stored.includes('pass-abcdef123'), false)
715+
})
716+
717+
// #3278: the two things #3275 fixed stay fixed — a value under six characters is left alone rather
718+
// than eating the words around it, and the mask still runs before the 300-character cut, so a literal
719+
// inside the kept part is gone and only the tail past the cut is dropped.
720+
test('an argv literal under six characters stays and an argv literal is masked before the three-hundred cut', async t => {
721+
const state = team()
722+
state.capabilities = {
723+
items: {
724+
long: {
725+
name: 'long', kind: 'mcp', description: 'Local server', transport: 'stdio', command: 'node',
726+
args: ['server.js', '--pin', 'abcde', '--api-key', 'sk-live-abcdef123456'],
727+
env: {}, approved: true, createdBy: 'worker', createdAt: 1, updatedAt: 1,
728+
},
729+
},
730+
}
731+
const env = await setup({ state })
732+
t.after(() => env.dispose())
733+
const { ctx, rt, mounts, skills } = env
734+
await rt.changeCapabilityAttachment('attach', { name: 'long' }, 'worker')
735+
const quoted = `server exited: --pin abcde ${'x'.repeat(170)} --api-key sk-live-abcdef123456 ${'z'.repeat(200)}`
736+
ctx.emit('agent/created', { agent: testAgent('worker', mounts, skills, { awaitMount: async () => { throw new Error(quoted) } }) })
737+
await rt.scheduleCapabilitiesReconcile()
738+
const status = rt.capabilityStatusesView().worker.long
739+
assert.equal(status.state, 'error')
740+
assert.equal(status.error.length, 300, 'the stored reason is still cut at 300 characters')
741+
assert.equal(status.error.startsWith('server exited: --pin abcde '), true, 'a five-character value is left alone')
742+
assert.equal(status.error.includes('--api-key [hidden]'), true, 'the mask ran before the cut')
743+
assert.equal(status.error.includes('sk-live-abcdef123456'), false)
744+
})
745+
746+
// #3278 acceptance 2: the entry that fails here may have been saved before this fix, so the tests
747+
// start from a store written by the old version and make one new start failure. The literal must be
748+
// gone from every surface a reader can see — the status answer, the `list_capabilities` text, the
749+
// system-prompt line and the log — and the first three must repeat the same masked sentence, which
750+
// is what proves they read one stored reason built at one place (`capabilities.js:370`) instead of
751+
// masking it four times. The saved config keeps the literal: the Settings editor reads it back by
752+
// design, and #3276 owns that question.
753+
const surfacesFor = async (env, name, warnings) => {
754+
const status = env.rt.capabilityStatusesView().worker[name] ?? {}
755+
return {
756+
status: JSON.stringify(status),
757+
listed: await env.ctx.registeredTools.get('list_capabilities').execute({}, { agent: { id: 'worker' } }),
758+
prompt: env.ctx.sections.get('bot-capabilities').text({ agent: { id: 'worker' } }),
759+
warnings: warnings.join('\n'),
760+
}
761+
}
762+
763+
test('a stdio capability saved before this fix shows no argv or env literal on any surface', async t => {
764+
const state = team()
765+
state.capabilities = {
766+
items: {
767+
legacy: {
768+
name: 'legacy', kind: 'mcp', description: 'Saved before this fix', transport: 'stdio',
769+
command: 'node', args: ['server.js', '--api-key', 'sk-live-abcdef123456'],
770+
env: { SERVICE_TOKEN: 'tok-abcdef123' }, approved: true, createdBy: 'worker', createdAt: 1, updatedAt: 1,
771+
},
772+
},
773+
}
774+
state.bots.worker.capabilities = ['legacy']
775+
const warnings = []
776+
const env = await setup({ state, beforeLoad: ({ ctx }) => { ctx.logger.warn = (...args) => warnings.push(args.join(' ')) } })
777+
t.after(() => env.dispose())
778+
const { ctx, rt, mounts, skills } = env
779+
const quoted = 'server exited: node server.js --api-key sk-live-abcdef123456 -e SERVICE_TOKEN=tok-abcdef123'
780+
ctx.emit('agent/created', { agent: testAgent('worker', mounts, skills, { awaitMount: async () => { throw new Error(quoted) } }) })
781+
await rt.scheduleCapabilitiesReconcile()
782+
const masked = 'server exited: node server.js --api-key [hidden] -e SERVICE_TOKEN=[hidden]'
783+
const surfaces = await surfacesFor(env, 'legacy', warnings)
784+
for (const [surface, text] of Object.entries(surfaces)) {
785+
for (const literal of ['sk-live-abcdef123456', 'tok-abcdef123']) {
786+
assert.equal(text.includes(literal), false, `${surface} carries no literal`)
787+
}
788+
}
789+
const status = rt.capabilityStatusesView().worker.legacy
790+
assert.equal(status.state, 'error')
791+
assert.equal(status.error, masked, 'one masked sentence, built once')
792+
assert.equal(surfaces.listed.includes(masked), true, 'the tool listing repeats the stored reason')
793+
assert.equal(surfaces.prompt.includes(masked), true, 'the prompt line repeats the stored reason')
794+
// The reason is not part of the team state, so nothing rewrites it at rest and no migration exists.
795+
await rt.save()
796+
const saved = JSON.parse(readFileSync(join(env.home, 'state.json'), 'utf8'))
797+
assert.equal(JSON.stringify(saved).includes('[hidden]'), false, 'the masked reason is memory-only')
798+
assert.deepEqual(saved.capabilities.items.legacy.args, ['server.js', '--api-key', 'sk-live-abcdef123456'], 'the config itself is unchanged')
799+
// Detaching the item empties every line, which is the proof that the store is their only source.
800+
await rt.changeCapabilityAttachment('detach', { name: 'legacy', bot: 'Worker' }, 'chief')
801+
await rt.scheduleCapabilitiesReconcile()
802+
assert.equal(JSON.stringify(rt.capabilityStatusesView()).includes(masked), false)
803+
assert.equal(ctx.sections.get('bot-capabilities').text({ agent: { id: 'worker' } }), '')
804+
})
805+
806+
test('an http capability saved before this fix shows no header literal on any surface', async t => {
807+
const state = team()
808+
state.capabilities = {
809+
items: {
810+
legacy: {
811+
name: 'legacy', kind: 'mcp', description: 'Saved before this fix', transport: 'streamable-http',
812+
url: 'https://host/mcp', headers: { 'X-Sig': 'sig-abcdef123', Accept: 'application/json' },
813+
approved: true, createdBy: 'worker', createdAt: 1, updatedAt: 1,
814+
},
815+
},
816+
}
817+
state.bots.worker.capabilities = ['legacy']
818+
const warnings = []
819+
const env = await setup({ state, beforeLoad: ({ ctx }) => { ctx.logger.warn = (...args) => warnings.push(args.join(' ')) } })
820+
t.after(() => env.dispose())
821+
const { ctx, rt, mounts, skills } = env
822+
const quoted = 'Error POSTing to endpoint: {"sig":"sig-abcdef123","accept":"application/json"}'
823+
ctx.emit('agent/created', { agent: testAgent('worker', mounts, skills, { awaitMount: async () => { throw new Error(quoted) } }) })
824+
await rt.scheduleCapabilitiesReconcile()
825+
const masked = 'Error POSTing to endpoint: {"sig":"[hidden]","accept":"application/json"}'
826+
const surfaces = await surfacesFor(env, 'legacy', warnings)
827+
for (const [surface, text] of Object.entries(surfaces)) {
828+
assert.equal(text.includes('sig-abcdef123'), false, `${surface} carries no literal`)
829+
}
830+
const status = rt.capabilityStatusesView().worker.legacy
831+
assert.equal(status.state, 'error')
832+
assert.equal(status.error, masked, 'one masked sentence, built once; an ordinary header survives')
833+
assert.equal(surfaces.listed.includes(masked), true)
834+
assert.equal(surfaces.prompt.includes(masked), true)
835+
})

0 commit comments

Comments
 (0)