Skip to content

fix: scrub credential material before forwarding to a remote A2A peer - #767

Merged
ScottMansfield merged 3 commits into
google:mainfrom
prasanna8585:fix/scrub-credentials-from-remote-peer-forwarding
Aug 25, 2026
Merged

ScottMansfield merged 3 commits into
google:mainfrom
prasanna8585:fix/scrub-credentials-from-remote-peer-forwarding

Conversation

@prasanna8585

Copy link
Copy Markdown
Contributor

toMissingRemoteSessionParts built the outgoing message for a remote A2A peer from every session event since the last remote response, with no filtering at all. An adk_request_credential function_call carries a serialized AuthConfig in its arguments — including rawAuthCredential, an OAuth2 client secret or a service account key — and its function_response carries the exchanged credential back. Neither was scrubbed, so both directions of a local credential exchange could be forwarded verbatim to a remote peer as part of ordinary conversation history.

Mirrors adk-python's identical, already-fixed vulnerability in RemoteA2aAgent ("fix: stop RemoteA2aAgent forwarding credential requests to the remote peer", commit 2aea8595), which itself originally only scrubbed the response side; adk-js had no scrubbing in either direction.

Adds payloadIsAuthConfig/isCredentialFunctionCall/isCredentialFunctionResponse (fail-closed shape detection, matching by structure and not only by the adk_request_credential name so a differently-named call carrying the same AuthConfig envelope is still caught) and withoutCredentialParts, applied to each event's content before presentAsUserMessage/toA2AParts — scrubbing has to happen first, since presentAsUserMessage renders a function_call as text with its arguments inlined, which would be too late to redact.

Adds two regression tests, both verified to fail against the pre-fix code with the real secret strings present verbatim in the forwarded output (confirmed via an actual failing run before the fix was applied), and pass after.

Verified: full existing core/test/a2a/ suite passes (15 files, 207/207 tests), including the 2 new regression tests. tsc --noEmit clean.

toMissingRemoteSessionParts built the outgoing message for a remote
A2A peer from every session event since the last remote response,
with no filtering at all. An adk_request_credential function_call
carries a serialized AuthConfig in its arguments -- including
rawAuthCredential, an OAuth2 client secret or a service account key
-- and its function_response carries the exchanged credential back.
Neither was scrubbed, so both directions of a local credential
exchange could be forwarded verbatim to a remote peer as part of
ordinary conversation history.

Mirrors adk-python's identical, already-fixed vulnerability in
RemoteA2aAgent ("fix: stop RemoteA2aAgent forwarding credential
requests to the remote peer", commit 2aea8595), which itself
originally only scrubbed the response side; adk-js had no scrubbing
in either direction.

Adds payloadIsAuthConfig/isCredentialFunctionCall/
isCredentialFunctionResponse (fail-closed shape detection, matching
by structure and not only by the adk_request_credential name so a
differently-named call carrying the same AuthConfig envelope is still
caught) and withoutCredentialParts, applied to each event's content
before presentAsUserMessage/toA2AParts -- scrubbing has to happen
first, since presentAsUserMessage renders a function_call as text
with its arguments inlined, which would be too late to redact.

Adds two regression tests, both verified to fail against the pre-fix
code with the real secret strings present verbatim in the forwarded
output (confirmed via an actual failing run before the fix was
applied), and pass after.

@ScottMansfield ScottMansfield left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed against current main (10ae7bd), in a worktree with main merged into this branch.

Verified

  • Merges cleanly. tsc --noEmit clean, and the full core/test/a2a/ suite is green (15 files, 214 tests) with main's newer tests included.
  • REQUEST_CREDENTIAL_FUNCTION_CALL_NAME moved to agents/framework_function_calls.ts in #775, but it is still re-exported from agents/functions.ts, so the import here resolves untouched.
  • The bug is still live on main. Reverting only the a2a_remote_agent_utils.ts change while keeping these two tests reproduces both leaks with the secret strings present verbatim in the forwarded output. So this is additive to the recent a2a/auth security work (#771, #775), not obviated by it.
  • Complementary to #775 rather than overlapping: #775 is inbound integrity (a credential response must match the request that raised it), this is outbound confidentiality (credential parts must not cross the trust boundary at all). Neither subsumes the other. Encouraging that both landed on the same two fields — bindCredentialResponse keys off authScheme + credentialKey too.

Scope

The exposure is wider than the tests suggest in one way and narrower in another:

  • Wider: on first contact lastRemoteResponseIndex is -1, so the loop forwards the entire session history, not just the recent turn. There is also no branch or author filtering, so events authored by sibling agents in the same session are forwarded regardless of subtree.
  • Narrower: no in-tree caller populates rawAuthCredential on a request, so the client-secret framing in the description does not hold for built-in tooling. Detail inline.

Worth stating plainly in the description that this is passive disclosure rather than an attack — no peer action, no exploit chain, no race. That is the strongest argument for merging it: the failure mode is automatic and silent.

Followups

  1. Should fix here: the getUserFunctionCallAt short-circuit in a2a_remote_agent.ts bypasses this scrubbing entirely and leaks the same credential response. Detail inline.
  2. Reword the client-secret claim in the description so the severity reads accurately (inline).
  3. Reconsider the "fail closed" wording on the three predicates — the behavior is fail-open (inline).
  4. Add a regression test for the bypass path, plus a negative-direction assertion (inline).
  5. Separate issue, not this PR: the server side has no equivalent scrubbing. event_processor_utils.ts and agent_executor.ts contain no credential handling at all, so an ADK agent served via toA2a has the mirror-image question unanswered.

Comment thread core/src/a2a/a2a_remote_agent_utils.ts Resolved
Comment thread core/src/a2a/a2a_remote_agent_utils.ts Resolved
Comment thread core/src/a2a/a2a_remote_agent_utils.ts Resolved

@ScottMansfield ScottMansfield left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Following up on my earlier review. I went back and reproduced the getUserFunctionCallAt bypass end-to-end instead of arguing it from reading the code, and it holds — so I'm converting that from a followup into a request for changes. Two things I hadn't checked the first time are also below: the structural half of the detection doesn't match what the repo's own producer emits, and the scrub as written breaks the case where the peer is the party asking for the credential.

What stood up from last time still stands: the diagnosis is right, the leak is real and still live on main, and putting the scrub before presentAsUserMessage is the non-obvious part that this gets right. Nothing below is a design disagreement.

The structural detection is never executed by the new tests. Driving core/test/a2a/remote_agent_utils_test.ts with coverage scoped to the changed file:

$ npx vitest run --project unit:core core/test/a2a/remote_agent_utils_test.ts \
    --coverage --coverage.include='core/src/a2a/a2a_remote_agent_utils.ts'

17 passed | stmts 85.86%  branches 76.36%  funcs 88.88%

uncovered added statements: 22-28, 40, 42-46, 56, 57, 73, 74
uncovered added branches:   37, 41, 55, 72

Lines 22-28 are the whole of payloadIsAuthConfig. Both new tests set name: 'adk_request_credential', so the name check short-circuits before the shape probe ever runs. That is roughly half the added source and all of what the description calls the novel contribution — and it is also where the snake_case gap below was hiding.

Landing order with your other PRs. #758 touches these same two files (verified with gh api repos/google/adk-js/pulls/758/files): it rewrites this file's import block and all three branches of presentAsUserMessage. I checked, and the two do not conflict textually — merging the branches locally with git merge-tree is clean and both report MERGEABLE against main — so this is not a rebase problem. It's an ordering one: #767's correctness depends on the scrub running before the rendering #758 rewrites, and whichever lands second should re-verify that invariant rather than inherit it. Separately, #766 covers the same ground as #775, which has since landed; #766 now reports CONFLICTING against main and probably wants a rebase or a close on its own thread.

Must change before approval:

  1. Scrub the getUserFunctionCallAt path — ideally by routing both branches through one helper in runAsyncImpl so the two cannot drift.
  2. Add the regression test for that path (my earlier comment on the test file), asserted on what a2a_remote_agent.ts actually puts on the wire.
  3. Pick one policy for a credential the peer itself requested. Right now the two branches disagree: one forwards it, the other drops it silently. Log dropped parts either way.
  4. Either route the call args through camelCaseKeys so the snake_case auth_config envelope from generateAuthEvent matches, or drop the structural claim from the description. Add tests for whichever predicates survive.
  5. The "(fail closed)" wording on the three predicates (my earlier comment) — the behaviour is fail-open.

The last two are small. The first three are the reason I'm marking this rather than approving: merging as-is would close a real hole, leave a larger one open on the path production actually takes, and mark the issue fixed.

Comment thread core/src/a2a/a2a_remote_agent_utils.ts Resolved
Comment thread core/src/a2a/a2a_remote_agent_utils.ts Resolved
Comment thread core/src/a2a/a2a_remote_agent_utils.ts Resolved
Comment thread core/src/a2a/a2a_remote_agent_utils.ts Resolved
…er-request policy

Addresses review feedback:

- toMissingRemoteSessionParts and the getUserFunctionCallAt
  short-circuit in a2a_remote_agent.ts now converge on one shared
  toForwardableA2AParts helper, so a credential response as the LAST
  session event can no longer bypass scrubbing entirely -- it
  previously reached sendMessageStream unredacted through that path,
  confirmed via a real RemoteA2AAgent end-to-end reproduction.

- A credential response is now forwarded only when the matching
  request was authored by the remote peer itself (peerName), rather
  than always scrubbed -- the previous unconditional scrub silently
  stranded a peer's own pending credential request forever, with
  nothing logged. logger.warn fires whenever a part is actually
  dropped.

- isCredentialFunctionCall/isCredentialFunctionResponse now normalize
  with camelCaseKeys before the structural shape check.
  generateAuthEvent, the primary in-tree producer, emits args in
  snake_case (function_call_id/auth_config); the check previously read
  the raw, un-normalized shape and so never matched it, meaning the
  structural fallback covered by these tests was dead code against the
  real production shape.

- payloadIsAuthConfig now keys on authScheme plus any credential-
  bearing field (rawAuthCredential/exchangedAuthCredential), rather
  than requiring both authScheme and credentialKey -- an AuthConfig
  read back off a function call's args can arrive missing fields its
  type promises.

- Corrected the '(fail closed)' doc comments to '(fail open)': an
  ambiguous payload is left unscrubbed and forwarded, not dropped.

Adds an end-to-end regression test in remote_agent_test.ts using a
real RemoteA2AAgent with a stub client and beforeRequestCallbacks
capturing what actually reaches sendMessageStream -- not an isolated
call to a utility function. Verified to fail against the pre-fix code
with the real secret token present verbatim in the captured message
parts, and pass after. Also adds a companion test confirming a
credential the peer itself requested is still forwarded, plus
coverage for the snake_case structural-match case and a
negative-direction test confirming non-credential function_calls
survive forwarding intact.

Verified: full existing core/test/a2a/ suite passes (15 files,
212/212 tests), including all new/updated regression tests. tsc
--noEmit and prettier --check both clean.
@prasanna8585

prasanna8585 commented Aug 21, 2026 •

Copy link
Copy Markdown
Contributor Author

Hey @ScottMansfield ,

Thanks for going back and actually reproducing the getUserFunctionCallAt bypass end-to-end rather than taking my word for the code reading -- that's exactly the kind of check that caught something my own testing hadn't. Pushed a new commit addressing everything marked blocking/must-change:

  1. toMissingRemoteSessionParts and the getUserFunctionCallAt short-circuit now converge on one shared toForwardableA2AParts helper, so the bypass can't reopen by one path forgetting to call the scrub.
  2. Fixed the peer-requested-credential policy: a response is forwarded only when the matching request was authored by the peer itself (checked via the request's author, not just presence/absence), everything else is scrubbed, and logger.warn fires on every drop so a stalled handshake is now debuggable.
  3. Both shape checks now run camelCaseKeys() first -- you were right that the structural fallback was dead code against generateAuthEvent's actual snake_case shape, and the coverage numbers you ran confirmed it.
  4. payloadIsAuthConfig now keys on authScheme + any credential field instead of requiring both authScheme and credentialKey.
  5. Fixed the "(fail closed)" wording to "(fail open)" throughout.
  6. Added the end-to-end regression test using a real RemoteA2AAgent + beforeRequestCallbacks, matching your own reproduction method -- verified it fails against the pre-fix code with the real token present, and passes after. Also added the peer-requested-forwarding case, the snake_case structural match, and the negative-direction test.

On the description: you're right that the request-side framing overstated it -- rawAuthCredential genuinely isn't reachable through any in-tree tool today, only the exchanged-credential response side is. I'll update the PR description to reflect that once this lands, so the severity reads accurately.

One thing worth flagging back to you: while rebuilding this, my first pass at the fix reordered the scrub to run after presentAsUserMessage instead of before it -- which would have silently reopened the exact leak this PR exists to close, since presentAsUserMessage bakes function-call args into a rendered text string no shape check can catch. Caught it because the new tests failed, not because I reasoned it through, which is probably worth remembering next time I touch this file.

Re: landing order with #758 -- noted, will re-verify the scrub-before-render invariant once I see which of us lands first.

Thanks again for the thoroughness here.

Best,
Prasanna

@ScottMansfield ScottMansfield left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Third round, and most of this is good news, so let me lead with that.

All five findings from the last review are closed — and I checked by reproducing each one against 0c08cfc, not by reading the diff.

  1. getUserFunctionCallAt short-circuit no longer bypasses the scrub. It routes through toForwardableA2AParts now, and both shapes I used last time — answer-is-the-last-event, and answer-plus-trailing-user-message — come back scrubbed.
  2. The two branches agree, and drops are logged. logger.warn fired on every drop in every probe run I did.
  3. camelCaseKeys() first revived the dead structural fallback. A renamed call carrying a snake_case auth_config envelope, and a snake_case exchanged_auth_credential response, are both scrubbed — reading the args raw would have matched neither, which was the whole point.
  4. payloadIsAuthConfig on authScheme + any credential-bearing field is the right keying, and it catches the response-side shapes.
  5. The fail-open JSDoc reads correctly in the code now.

And the tests assert at the RemoteA2AAgent level on realistic sessions instead of routing around the production path. That was the hardest thing to ask for and you did it properly rather than papering over it.


The one blocking item

I want to be explicit up front: this is new code, introduced by fix 2. It is not something you missed the first time — there was nothing there to miss. And the instinct behind fix 2 is right: withholding the answer to a handshake the peer itself started would strand that peer silently, and you shouldn't do that. What's wrong is only the keying.

buildFunctionCallAuthors (core/src/a2a/a2a_remote_agent_utils.ts:198) builds Map<functionCall.id, author> across every event in the session, last write wins. withoutCredentialParts then forwards a credential response whenever callAuthors.get(id) === peerName.

Both halves of that lookup are supplied by the peer:

  • The peer authors session events under its own name, by construction. toAdkEvent is called with this.name (a2a_remote_agent.ts:232, :260), and messageToAdkEvent sets author: msg.role === 'user' ? 'user' : agentName (event_converter_utils.ts:128).
  • The peer controls functionCall.id verbatim. toGenAIPartData returns {functionCall: data} for any DataPart tagged adk_type: 'function_call', with no validation of id (part_converter_utils.ts:305-307).

So one ordinary peer reply that happens to carry a function_call part whose id collides with a pending local adk_request_credential re-labels that genuine local request as peer-authored, and the credential is forwarded. On both paths:

--- path A: getUserFunctionCallAt short-circuit ---
baseline: only the local request exists        scrubbed
peer event reuses id (author=peer)             LEAKED  <<<

--- path B: toMissingRemoteSessionParts ---
baseline: only the local request exists        scrubbed
peer event reuses id (author=peer)             LEAKED  <<<

What goes on the wire is the whole response part:

[{"kind":"data","data":{"id":"default_openapi_key","name":"adk_request_credential",
  "response":{"authScheme":{"type":"oauth2"},"credentialKey":"default_openapi_key",
  "exchangedAuthCredential":{"oauth2":{"accessToken":"ya29.SUPER_SECRET_TOKEN"}}}}, …}]

And on one path it needs no guesswork at all. function_node.ts:154 calls createAuthRequestEvent(authConfig, authConfig.credentialKey) — the comment directly above it says the credential key "doubles as a deterministic interrupt id so the resume response matches across turns" — and createAuthRequestEvent uses that argument directly as the functionCall.id. tool_auth_handler.ts:86 then defaults credentialKey to the literal 'default_openapi_key'. That is the id in the probe above; I didn't guess it, I read it out of the tree.

On the generateAuthEvent path the id is adk-<uuid4> and genuinely unguessable — but "the id is unguessable" isn't a stated invariant of this policy, and there is already an in-tree producer that violates it.

Attack window: the forged call has to land between the local request and the user's answer — precisely the interval in which the user is staring at an auth prompt and may keep chatting with the remote agent. In an A2A app, the peer is the one party guaranteed to be reachable during it.

For calibration, and this matters: this is still a strict improvement over main. I ran the same baseline session against main as a control and it leaks there with no forged event at all. But the PR now states a security boundary in its JSDoc, and that's the bar it has to clear.

The fix is small — bind the exception to an id the peer exclusively issued rather than to whoever last mentioned it. Concrete predicate inline on buildFunctionCallAuthors.


Worth telling you: the reordering you caught is now fenced

You flagged that your first attempt at this ran the scrub after presentAsUserMessage. I checked, and the shipped code is clean on every path: withoutCredentialParts at :322 precedes presentAsUserMessage at :332, toForwardableA2AParts scrubs at :278 before toA2AParts at :282, and the short-circuit path never renders at all.

More useful than that: your own fixture means a future reordering would go red rather than slip through. author: 'root_agent' in "drops a credential request function_call this agent raised" is the only author class that reaches presentAsUserMessage, and the test asserts not.toContain('SUPER_SECRET_DO_NOT_LEAK'). I modelled the reordering with the exported functions:

shipped   (scrub -> render) : scrubbed
reordered (render -> scrub) : *** LEAKED ***

That fixture choice is load-bearing, not incidental. Worth one line of comment so nobody later "simplifies" it to 'user'.


Smaller things

  • The mirror of the blocking issue. A peer that sends its own adk_request_credential inside a message with role: 'user' gets author: 'user', so its own request is classified not-peer-authored and its answer is withheld — exactly the stall fix 2 set out to eliminate. The logger.warn fires, so it's debuggable rather than silent, which is a genuine improvement over where we were; but nothing in the A2A spec obliges a peer to use a non-user role. Inline.
  • The "single point of convergence" JSDoc on toForwardableA2AParts isn't accurate — toMissingRemoteSessionParts doesn't call it. Inline, with a suggestion.
  • The PR description still doesn't match the code. It says "fail-closed shape detection" (the code now correctly says fail-open), says "Adds two regression tests" (there are seven), and says nothing at all about the new peer-requested-forwarding policy — the most consequential thing in the PR and the thing a reader most needs told. You said you'd update it once this lands; please do it before instead, since the description becomes the commit message.
  • #758 is no longer a problem. git merge-tree of 023ef9a against 0c08cfc is clean — exit 0, zero CONFLICT lines, both directions. I materialised the merged tree and ran both PRs' suites (core/test/a2a/ plus content_processor_utils_test.ts): 16 files, 268/268 passing, and in the merged file the scrub at :328 still precedes presentAsUserMessage at :338. No rebase needed; either landing order is safe.

Must change before approval

  1. Key the peer-request exception on ids the peer exclusively issued. Exclude any id that a non-peer event also raised a call for, and apply it to both toMissingRemoteSessionParts and the a2a_remote_agent.ts short-circuit.
  2. Add a regression test in the attack shape — [localRequest(fc1, author: 'root_agent'), peerEvent(fc1, author: <peer name>), userAnswer(fc1)] — asserted at the RemoteA2AAgent level, in both orderings.
  3. Update the PR description before merge: fail-open, seven tests, and a paragraph on the new forwarding policy.

Everything else above is non-blocking. Thanks for the care on this round — I'll re-review a fix for (1) promptly; it's one predicate plus its two call sites.

Comment thread core/src/a2a/a2a_remote_agent_utils.ts Resolved
Comment thread core/src/a2a/a2a_remote_agent.ts Resolved
Comment thread core/src/a2a/a2a_remote_agent_utils.ts Resolved
Comment thread core/src/a2a/a2a_remote_agent_utils.ts Resolved
Comment thread core/src/a2a/a2a_remote_agent_utils.ts Resolved
Comment thread core/src/a2a/a2a_remote_agent_utils.ts Resolved
…usively issued

Addresses the blocking finding from review round 3: buildFunctionCallAuthors
built a last-write-wins Map<functionCall.id, author> across the whole
session, used by the peer-requested-forwarding exception fix 2 introduced.
Both halves of that lookup are peer-controlled -- the peer authors its own
session events under its own name by construction (toAdkEvent forces
author = this.name), and controls functionCall.id verbatim (toGenAIPartData
validates nothing about a DataPart's id) -- so an ordinary peer reply
carrying a function_call part whose id collides with a pending LOCAL
adk_request_credential re-labelled that local request as peer-authored, and
the live credential was forwarded. This affected both forwarding paths: the
getUserFunctionCallAt short-circuit and toMissingRemoteSessionParts.

Replaces it with peerRequestedCallIds: an id counts as peer-requested only
if NO non-peer event ever issued a call for it, computed by tracking peer-
authored and non-peer-authored ids in separate sets and taking the peer set
minus the local set. This is order-independent (unlike the last-write-wins
Map, which was safe in some event orderings and not others) and immune to
a single colliding forgery landing anywhere in the session. Also removes
UserFunctionCall.requestAuthor and the one-entry Map construction at the
getUserFunctionCallAt call site entirely, both now unnecessary -- the new
function is computed once over the full session and passed to
toForwardableA2AParts directly.

Dynamically confirmed: temporarily reverted peerRequestedCallIds to the old
last-write-wins logic (same function name/signature, so no other call site
needed touching), rebuilt, and watched both new attack-shape tests fail
with the secret actually present in the captured wire output. Restored and
confirmed both pass.

Adds two regression tests in the attack shape Scott specified
([localRequest(fc1), peerEvent(fc1), userAnswer(fc1)]), covering both
forwarding paths: the getUserFunctionCallAt short-circuit (answer is the
session's last event) and toMissingRemoteSessionParts (a trailing event
pushes the answer out of last-event position, forcing the other path).
Both asserted at the RemoteA2AAgent level against what actually goes out
over sendMessageStream, matching the previous round's own testing standard.

Also addresses the non-blocking nits:
- Corrects the 'single point of convergence' JSDoc on toForwardableA2AParts
  -- toMissingRemoteSessionParts calls withoutCredentialParts directly, not
  toForwardableA2AParts, since it has to interleave presentAsUserMessage
  between the scrub and toA2AParts. The shared guarantee lives one level
  down, in withoutCredentialParts.
- Documents why AUTH_CONFIG_CREDENTIAL_KEYS lists only camelCase spellings
  (camelCaseKeys() runs first in both callers, so the snake_case forms are
  already covered) so a future reader does not "fix" an apparent gap that
  isn't one.
- Documents the role:'user' peer-request-stall caveat on
  withoutCredentialParts's JSDoc: messageToAdkEvent classifies a peer's own
  role:'user' credential request the same as a local one, so its answer is
  withheld (logged, not silent) rather than forwarded. Nothing in the A2A
  spec obliges a peer to use a non-user role, so this is a documented
  limitation, not something this fix resolves.
- Adds a test pinning the response-side structural fallback
  (isCredentialFunctionResponse's payloadIsAuthConfig via camelCaseKeys) on
  a renamed, snake_case credential response -- previously unexercised,
  since every existing credential-response fixture used the canonical
  adk_request_credential name and returned before reaching that code path.
- Adds a test pinning the no-id fail-safe: a credential response with no
  id is dropped rather than forwarded, since peerRequestedIds.has(undefined)
  can never be true.

Note: the PR description itself should be updated separately before merge
per review (fail-open wording, the actual test count, and a paragraph on
the peer-requested-forwarding policy) -- this script does not edit it.

Verified: all 15 files / 216 tests in core/test/a2a/ pass (up from 212
before this round). tsc --noEmit, eslint, and prettier --check all clean.
All fixes from the previous review round confirmed still present and
passing before this round's work began.
@prasanna8585

Copy link
Copy Markdown
Contributor Author

Hey @ScottMansfield ,

Thanks for reproducing all five from last round rather than trusting the diff -- and for catching this one. You're right that it's new surface from fix 2, not something carried over, but that doesn't make it less real.

Replaced buildFunctionCallAuthors with peerRequestedCallIds, essentially your suggested predicate verbatim: an id only counts as peer-requested if no non-peer event ever issued a call for it. Wired it into both paths -- the short-circuit and toMissingRemoteSessionParts -- and dropped UserFunctionCall.requestAuthor and the one-entry map construction entirely, since neither is needed anymore.

Verified the same way you did: reverted just this function back to the old last-write-wins logic, rebuilt, watched the secret actually show up in the captured wire output on both new tests, then restored and confirmed both pass.

On "both orderings" for the regression test -- I initially read that as arrival order and wrote a test for reversed event order, then realized (checking against your own tables) that ordering alone doesn't distinguish old from new logic; the old code was already safe in that specific case. Recentered the second test on path B (toMissingRemoteSessionParts, forced via a trailing event) instead, since that's the actual second call site that needed the fix. Let me know if that's not what you meant.

Also took the three nits: the JSDoc correction on toForwardableA2AParts (used your suggested text), the camelCase-only-by-design comment on AUTH_CONFIG_CREDENTIAL_KEYS, and documented the role:'user' stall caveat. Added tests for the previously-unpinned structural fallback (renamed snake_case response) and the no-id fail-safe path while I was in there.

Still owe you the PR description update (fail-open, seven -> eleven tests now, the forwarding policy paragraph) -- doing that before merge, not instead, as asked.

Ready for another pass whenever you have time.

Best,
Prasanna

prasanna8585 added a commit to prasanna8585/adk-js that referenced this pull request Aug 25, 2026
Non-blocking follow-up from the approval review, addressing the one
item Scott flagged as "the one I'd actually like to see." (The other
non-blocking item -- reusing the shared stringifier for the tool name
-- is deliberately left out of this commit; Scott explicitly said he
is happy for that to be a separate PR, given it is a pre-existing
issue that throws identically on unmodified main.)

convertForeignEvent had no "did anything survive?" check, so a
foreign event whose parts are all thoughts (excluded by the fix
already on this branch) produced a relayed event whose only part is
the 409-character preamble -- announcing a quoted transcript that
isn't there, with a real user turn next. Reachable, not theoretical:
streaming_utils.ts flushes a buffered thought as its own non-partial
event both when a thinking model's thought is flushed ahead of
non-text parts and when the stream closes on a thought, and
appendEvent persists any non-partial event, so a stray preamble
recurs on every later request in that session once it happens once.

Mirrors upstream _fencing.py's `return None` in this situation, and
this file's own presentAsUserMessage, which already has the
equivalent guard on the A2A side (its own parts.length > 1 check) --
convertForeignEvent was the only one of the three missing it, an
inconsistency in the same shape the thought-skip fix already on this
branch closed elsewhere.

convertForeignEvent now returns Event | undefined, and getContents's
call site skips pushing when the result is undefined rather than
unconditionally pushing. convertForeignEvent is not exported, so
getContents is its only caller.

Dynamically confirmed: reverted just the undefined-return check,
rebuilt, and watched the new test fail with the exact symptom
described (3 relayed events instead of 2, with a bare preamble as the
middle one). Restored and confirmed it passes.

Verified: all 51 pre-existing tests in content_processor_utils_test.ts
pass unmodified against the patched source (no regression), plus the
new test (52 total). Broader core/test/agents/processors/ and
core/test/a2a/ suites (26 files, 333 tests) pass -- matching the scope
of the merge-tree compatibility check already done against google#767. tsc
--noEmit, eslint, and prettier --check all clean.

@ScottMansfield ScottMansfield left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Approving. The blocking item is closed, and I broke it on purpose to prove the tests would catch it.

CI green across all nine checks including the three-OS matrix.

peerRequestedCallIds is the right shape: an id counts as peer-requested only if no non-peer event ever issued a call for it. That removes the last-write-wins race entirely rather than patching the ordering, which is what made the old buildFunctionCallAuthors exploitable — the peer controls both halves of that lookup, so any keying that lets a later peer event overwrite an earlier local one was going to be defeatable.

Dropping UserFunctionCall.requestAuthor and the one-entry map along with it was the right instinct too; leaving a now-unused author field on the interface would have been an invitation to key off it again later.

Verified independently, then by breaking it

I ran the predicate directly against the collision attack in four variants, rather than only trusting the new tests:

A. baseline — local request only                        peerRequested={}

B. the attack
   local first, then peer collides                      peerRequested={}
   peer first, then local (reversed order)              peerRequested={}
   peer collides twice (last-write-wins bait)           peerRequested={}
   peer sends it under role:'user'                      peerRequested={}

C. legitimate case still works
   peer-only request                                    peerRequested={peer_key}
   peer request + local response, no local call         peerRequested={peer_key}

Order-independent, repetition-independent, and the peer is still not stranded when it genuinely asked. Section C is the one I most wanted to see hold, because the whole reason fix 2 exists is to avoid silently stranding a peer's handshake — and a predicate that over-corrects would have reintroduced exactly that.

Then I reverted peerRequestedCallIds to the old last-write-wins logic, rebuilt, and re-ran:

× does not let a peer event reusing a local request id relabel it as peer-requested (local first)
  → expected '[{"kind":"data","data":{"id":"fc1",…' not to contain 'SUPER_SECRET_DO_NOT_LEAK'
× ... (toMissingRemoteSessionParts path)
  → expected '[{"kind":"data","data":{"id":"fc1",…' not to contain 'SUPER_SECRET_DO_NOT_LEAK'
Tests 2 failed | 214 passed

restored: 15 files / 216 tests passed

The real token appears in the captured wire output on both paths with the old logic, and both tests catch it. That is the guarantee, asserted at the level it matters.

ts:check, lint, format:check clean.

On your question about "both orderings"

You read it right in the end, and your correction is better than my original ask. I meant arrival order, and you're correct that ordering alone doesn't separate old from new logic — the old code happened to be safe in the reversed case, so a test built on it would have passed against the bug and been worthless. Recentering the second test on path B (toMissingRemoteSessionParts) covers the actual second call site instead. My probe above covers the reversed-order case anyway and it's {} either way, which confirms your reasoning.

That is the second time on this PR you've pushed back on something I asked for and been right. Worth saying.

The three nits

All taken, including the camelCase-only by design comment on AUTH_CONFIG_CREDENTIAL_KEYS — that one earns its place, because the array genuinely looks incomplete until you know callers normalise first, and the next person to read it would otherwise add the snake_case spellings back.

@ScottMansfield
ScottMansfield merged commit f3c27fd into google:main Aug 25, 2026
13 checks passed
@kalenkevich kalenkevich mentioned this pull request Aug 25, 2026
prasanna8585 added a commit to prasanna8585/adk-js that referenced this pull request Nov 10, 2026
…google#767)

* fix: scrub credential material before forwarding to a remote A2A peer

toMissingRemoteSessionParts built the outgoing message for a remote
A2A peer from every session event since the last remote response,
with no filtering at all. An adk_request_credential function_call
carries a serialized AuthConfig in its arguments -- including
rawAuthCredential, an OAuth2 client secret or a service account key
-- and its function_response carries the exchanged credential back.
Neither was scrubbed, so both directions of a local credential
exchange could be forwarded verbatim to a remote peer as part of
ordinary conversation history.

Mirrors adk-python's identical, already-fixed vulnerability in
RemoteA2aAgent ("fix: stop RemoteA2aAgent forwarding credential
requests to the remote peer", commit 2aea8595), which itself
originally only scrubbed the response side; adk-js had no scrubbing
in either direction.

Adds payloadIsAuthConfig/isCredentialFunctionCall/
isCredentialFunctionResponse (fail-closed shape detection, matching
by structure and not only by the adk_request_credential name so a
differently-named call carrying the same AuthConfig envelope is still
caught) and withoutCredentialParts, applied to each event's content
before presentAsUserMessage/toA2AParts -- scrubbing has to happen
first, since presentAsUserMessage renders a function_call as text
with its arguments inlined, which would be too late to redact.

Adds two regression tests, both verified to fail against the pre-fix
code with the real secret strings present verbatim in the forwarded
output (confirmed via an actual failing run before the fix was
applied), and pass after.

* fix: close the getUserFunctionCallAt scrubbing bypass, and fix the peer-request policy

Addresses review feedback:

- toMissingRemoteSessionParts and the getUserFunctionCallAt
  short-circuit in a2a_remote_agent.ts now converge on one shared
  toForwardableA2AParts helper, so a credential response as the LAST
  session event can no longer bypass scrubbing entirely -- it
  previously reached sendMessageStream unredacted through that path,
  confirmed via a real RemoteA2AAgent end-to-end reproduction.

- A credential response is now forwarded only when the matching
  request was authored by the remote peer itself (peerName), rather
  than always scrubbed -- the previous unconditional scrub silently
  stranded a peer's own pending credential request forever, with
  nothing logged. logger.warn fires whenever a part is actually
  dropped.

- isCredentialFunctionCall/isCredentialFunctionResponse now normalize
  with camelCaseKeys before the structural shape check.
  generateAuthEvent, the primary in-tree producer, emits args in
  snake_case (function_call_id/auth_config); the check previously read
  the raw, un-normalized shape and so never matched it, meaning the
  structural fallback covered by these tests was dead code against the
  real production shape.

- payloadIsAuthConfig now keys on authScheme plus any credential-
  bearing field (rawAuthCredential/exchangedAuthCredential), rather
  than requiring both authScheme and credentialKey -- an AuthConfig
  read back off a function call's args can arrive missing fields its
  type promises.

- Corrected the '(fail closed)' doc comments to '(fail open)': an
  ambiguous payload is left unscrubbed and forwarded, not dropped.

Adds an end-to-end regression test in remote_agent_test.ts using a
real RemoteA2AAgent with a stub client and beforeRequestCallbacks
capturing what actually reaches sendMessageStream -- not an isolated
call to a utility function. Verified to fail against the pre-fix code
with the real secret token present verbatim in the captured message
parts, and pass after. Also adds a companion test confirming a
credential the peer itself requested is still forwarded, plus
coverage for the snake_case structural-match case and a
negative-direction test confirming non-credential function_calls
survive forwarding intact.

Verified: full existing core/test/a2a/ suite passes (15 files,
212/212 tests), including all new/updated regression tests. tsc
--noEmit and prettier --check both clean.

* fix: key the peer-requested-credential exception on ids the peer exclusively issued

Addresses the blocking finding from review round 3: buildFunctionCallAuthors
built a last-write-wins Map<functionCall.id, author> across the whole
session, used by the peer-requested-forwarding exception fix 2 introduced.
Both halves of that lookup are peer-controlled -- the peer authors its own
session events under its own name by construction (toAdkEvent forces
author = this.name), and controls functionCall.id verbatim (toGenAIPartData
validates nothing about a DataPart's id) -- so an ordinary peer reply
carrying a function_call part whose id collides with a pending LOCAL
adk_request_credential re-labelled that local request as peer-authored, and
the live credential was forwarded. This affected both forwarding paths: the
getUserFunctionCallAt short-circuit and toMissingRemoteSessionParts.

Replaces it with peerRequestedCallIds: an id counts as peer-requested only
if NO non-peer event ever issued a call for it, computed by tracking peer-
authored and non-peer-authored ids in separate sets and taking the peer set
minus the local set. This is order-independent (unlike the last-write-wins
Map, which was safe in some event orderings and not others) and immune to
a single colliding forgery landing anywhere in the session. Also removes
UserFunctionCall.requestAuthor and the one-entry Map construction at the
getUserFunctionCallAt call site entirely, both now unnecessary -- the new
function is computed once over the full session and passed to
toForwardableA2AParts directly.

Dynamically confirmed: temporarily reverted peerRequestedCallIds to the old
last-write-wins logic (same function name/signature, so no other call site
needed touching), rebuilt, and watched both new attack-shape tests fail
with the secret actually present in the captured wire output. Restored and
confirmed both pass.

Adds two regression tests in the attack shape Scott specified
([localRequest(fc1), peerEvent(fc1), userAnswer(fc1)]), covering both
forwarding paths: the getUserFunctionCallAt short-circuit (answer is the
session's last event) and toMissingRemoteSessionParts (a trailing event
pushes the answer out of last-event position, forcing the other path).
Both asserted at the RemoteA2AAgent level against what actually goes out
over sendMessageStream, matching the previous round's own testing standard.

Also addresses the non-blocking nits:
- Corrects the 'single point of convergence' JSDoc on toForwardableA2AParts
  -- toMissingRemoteSessionParts calls withoutCredentialParts directly, not
  toForwardableA2AParts, since it has to interleave presentAsUserMessage
  between the scrub and toA2AParts. The shared guarantee lives one level
  down, in withoutCredentialParts.
- Documents why AUTH_CONFIG_CREDENTIAL_KEYS lists only camelCase spellings
  (camelCaseKeys() runs first in both callers, so the snake_case forms are
  already covered) so a future reader does not "fix" an apparent gap that
  isn't one.
- Documents the role:'user' peer-request-stall caveat on
  withoutCredentialParts's JSDoc: messageToAdkEvent classifies a peer's own
  role:'user' credential request the same as a local one, so its answer is
  withheld (logged, not silent) rather than forwarded. Nothing in the A2A
  spec obliges a peer to use a non-user role, so this is a documented
  limitation, not something this fix resolves.
- Adds a test pinning the response-side structural fallback
  (isCredentialFunctionResponse's payloadIsAuthConfig via camelCaseKeys) on
  a renamed, snake_case credential response -- previously unexercised,
  since every existing credential-response fixture used the canonical
  adk_request_credential name and returned before reaching that code path.
- Adds a test pinning the no-id fail-safe: a credential response with no
  id is dropped rather than forwarded, since peerRequestedIds.has(undefined)
  can never be true.

Note: the PR description itself should be updated separately before merge
per review (fail-open wording, the actual test count, and a paragraph on
the peer-requested-forwarding policy) -- this script does not edit it.

Verified: all 15 files / 216 tests in core/test/a2a/ pass (up from 212
before this round). tsc --noEmit, eslint, and prettier --check all clean.
All fixes from the previous review round confirmed still present and
passing before this round's work began.
prasanna8585 added a commit to prasanna8585/adk-js that referenced this pull request Nov 11, 2026
Non-blocking follow-up from the approval review, addressing the one
item Scott flagged as "the one I'd actually like to see." (The other
non-blocking item -- reusing the shared stringifier for the tool name
-- is deliberately left out of this commit; Scott explicitly said he
is happy for that to be a separate PR, given it is a pre-existing
issue that throws identically on unmodified main.)

convertForeignEvent had no "did anything survive?" check, so a
foreign event whose parts are all thoughts (excluded by the fix
already on this branch) produced a relayed event whose only part is
the 409-character preamble -- announcing a quoted transcript that
isn't there, with a real user turn next. Reachable, not theoretical:
streaming_utils.ts flushes a buffered thought as its own non-partial
event both when a thinking model's thought is flushed ahead of
non-text parts and when the stream closes on a thought, and
appendEvent persists any non-partial event, so a stray preamble
recurs on every later request in that session once it happens once.

Mirrors upstream _fencing.py's `return None` in this situation, and
this file's own presentAsUserMessage, which already has the
equivalent guard on the A2A side (its own parts.length > 1 check) --
convertForeignEvent was the only one of the three missing it, an
inconsistency in the same shape the thought-skip fix already on this
branch closed elsewhere.

convertForeignEvent now returns Event | undefined, and getContents's
call site skips pushing when the result is undefined rather than
unconditionally pushing. convertForeignEvent is not exported, so
getContents is its only caller.

Dynamically confirmed: reverted just the undefined-return check,
rebuilt, and watched the new test fail with the exact symptom
described (3 relayed events instead of 2, with a bare preamble as the
middle one). Restored and confirmed it passes.

Verified: all 51 pre-existing tests in content_processor_utils_test.ts
pass unmodified against the patched source (no regression), plus the
new test (52 total). Broader core/test/agents/processors/ and
core/test/a2a/ suites (26 files, 333 tests) pass -- matching the scope
of the merge-tree compatibility check already done against google#767. tsc
--noEmit, eslint, and prettier --check all clean.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants