Skip to content

fix(kas): fail loud when the loopback port is taken, harden caller check - #44847

Open
nodomain wants to merge 1 commit into
kirodotdev:mainfrom
nodomain:fix/kas-loopback-review-followups
Open

nodomain wants to merge 1 commit into
kirodotdev:mainfrom
nodomain:fix/kas-loopback-review-followups

Conversation

@nodomain

Copy link
Copy Markdown
Contributor

Problem / Motivation

Goal: Kiro Crew's registry loopback site cannot hand Crew's tool calls to another program, and it fails loudly when it cannot hold its port.

Follow-up to #44376 (which carried #44165). A review of the matching catalog entries (11 static kirocrew-* entries at http://127.0.0.1:5470/mcp/<server>, in an organization's MCP registry) raised these against the loopback site:

  1. Blocking: a bind failure on 5470 only logged a warning. fix(kas): keep Crew's own tools on KAS under an MCP registry #44376 already marks pointers only while the listener is held, but a governed host that loses the port says nothing to the user.
  2. Windows: a reused pid could inherit a dead session's record, and the listener had no SO_EXCLUSIVEADDRUSE.
  3. macOS: the peer lookup runs lsof; it is off the loop since fix(kas): keep Crew's own tools on KAS under an MCP registry #44376 but unbounded, so a local process opening connections can tie up the shared executor.
  4. A reloaded chat registering a second token on the same pid (fixed in fix(kas): keep Crew's own tools on KAS under an MCP registry #44376: a load replaces the session's record; a test is added here).

Why it matters

With those catalog entries live for every user of an account, "whoever holds 127.0.0.1:5470 serves Crew's tools" must never be true, and a host that cannot serve them must say so instead of quietly losing Crew's tools.

Not a goal

  • A different port or discovery scheme for the catalog entry.
  • The kiro-cli relay on Windows (still unmarked, unchanged).

What changed (motivation → approach → change)

  • Port taken, loud (dashboard/registry_loopback_site.py, kas_registry_loopback.py, acp/kas_withheld_notice.py): a failed bind is logged at error with the holder's pid (find_listening_pids, off the loop, bounded) and recorded as listener_refusal(). marks_pointers stays false, so nothing is sent as a pointer and no call reaches the holder. Every governed KAS session's start notice then names the port, the holder and the fix. A later successful start clears it.
  • Exclusive listener: the site binds its own socket (_exclusive_listener): SO_REUSEADDR on POSIX (a live listener still refuses a second bind; only TIME_WAIT is skipped), SO_EXCLUSIVEADDRUSE on Windows. The web-entries listener on port 0 too.
  • Pid reuse fails closed: register() reads the start id when the caller has none and records nothing without one; _is_process answers False when either start id is unknown (it answered True before).
  • Bounded peer lookup: one lookup per TCP connection (_ATTESTED, a weak map on the transport; the engine is re-checked against the in-memory table on every request, and the one-session rule still runs per request), at most 4 lookups at once (more are refused), 3 s each.

Backwards compatibility

Compatible: a host without agent.mcp_registry_mode never binds the site; a governed host that holds the port behaves as before.

Reader: src/kiro_crew/kas_registry_loopback.py:_is_process -- chat -- a record with an unknown start id is now pruned; every real runtime records _start_time from get_process_start_id at spawn, and test/test_kas_sandbox_rule_web_entries.py's fake runtime now sets one.

Tests

test/test_kas_registry_loopback_listener.py (10 tests, each on a free port, never 5470): a taken port marks nothing and the notice names it; a restart that loses the port stops marking and clears once the port is free; a second bind beside the held listener fails; the Windows socket option; a pid without a start id is not recorded; an unreadable start id prunes a record; one lookup per connection, dropped with the session; a hanging lookup is refused while the loop keeps running; lookups past the cap are refused; a reload keeps one session.

Proof: PROVEN test/test_kas_registry_loopback_listener.py::test_a_pid_without_a_start_id_is_not_recorded, test/test_kas_registry_loopback_listener.py::test_an_unreadable_start_id_later_prunes_the_record, test/test_kas_registry_loopback_listener.py::test_one_peer_lookup_per_connection (head 628bb96)

Local: 249 related test files, 12,430 passed; the 5 failures are opencode tests that need a local opencode binary (one fails the same on main here). flake8, black, isort, mypy and docs lint clean.

Manual verification

N/A for the bind and caller paths beyond the tests above (they bind real sockets on Linux). macOS and Windows paths: parser and option tests only.

Real-machine verification

Machine: own computer, Ubuntu 24.04, x86_64, 16 vCPU / 64 GiB.
Before (main a9f991f): pytest test/test_kas_registry_loopback_listener.py -> fails (no listener_refusal, unknown start id passes).
After (head 628bb96): same command -> 10 passed.
Cleanup: own computer.

Related Issues

Refs #44376, #44165, kirodotdev/Kiro#12231

Sibling sweep

Swept: git grep -n "web.TCPSite(" -- src/kiro_crew/dashboard/registry_loopback_site.py
Sibling: src/kiro_crew/dashboard/registry_loopback_site.py -- changed here (both listeners)

Pattern harvest

Not generalizable: specific to a listener whose address a shared catalog names.

Checklist

  • A Conventional Commits title
  • Existing tests pass and new tests added for new functionality
  • Self-review completed; code follows project style guidelines
  • Documentation updated (guide KAS section, acp-client spec)
  • No secrets, credentials, or internal references in the diff

Contribution License Agreement

Contributed under the project's Apache-2.0 license.

@nodomain
nodomain requested review from a team and KiroCrewCaptain as code owners November 30, 2026 07:22
@github-actions github-actions Bot added fork Pull request from a fork (external contributor) readiness: action required A blocking check or review needs attention labels Nov 30, 2026
@nodomain

Copy link
Copy Markdown
Contributor Author

@kirodotdev maintainers: could you approve the workflow runs for this fork PR? Only the label and description checks have run so far, and PR Readiness waits on the rest.

This is the hardening a reviewer of the matching registry entries asked for on top of #44376 (fail loud on a taken loopback port, exclusive listener on Windows, fail-closed start ids, bounded peer lookup). Locally: 10 new tests, 12,430 related tests pass at head 628bb96.

@nodomain

nodomain commented Dec 1, 2026

Copy link
Copy Markdown
Contributor Author

Added f07bc6d9: registry mode no longer needs agent.mcp_registry_mode. A governed profile should work with vanilla settings.

  • A KAS start whose Crew servers the engine filters under a registry (accessModeFilteredServers), while this gateway does not hold the loopback listener, raises RegistryFilterRefusal. retried_over_loopback binds 127.0.0.1:5470, writes a marker in the data home and runs the start once more with Crew's servers marked. The next gateway start binds the site at boot from the marker.
  • Port busy: the start fails loudly, naming the holder; nothing is marked.
  • No registry: unchanged (no port, no marking, no marker).
  • agent.mcp_registry_mode stays as an optional explicit declaration.
  • Tests: test/test_kas_registry_auto.py (auto mode with the setting unset, no-registry unchanged, busy port, one retry only); test_kas_governed_mcp_drop.py updated for the new message.

Known limit (commented as a shortcut): the marker is not keyed by profile, so a host that later moves to a profile without a registry keeps binding the port; the engine then runs Crew's marked servers from their own launch.

@github-actions github-actions Bot added the merge conflict Branch has merge conflicts with its base — author must resolve before merge label Dec 4, 2026
@iamwhatever

Copy link
Copy Markdown
Contributor

Benchmark data for the per-connection attest cache in this PR, offered as data only; the decision is yours.

I measured main (6624356) against a branch that adds only a per-connection cache of the attested engine pid (weak map on the transport, pass-only, candidate_pids() still checked on every request). No concurrency cap, no timeout.

Case main per-connection cache
Attest cost, requests 2..N on one connection (median) 24.2 ms 0.09 ms
Wall, 100 requests over 1 connection 2.46 s 0.058 s
Wall, 100 requests over 6 concurrent connections 4.39 s 0.30 s
Wall, 600 requests over 6 concurrent connections 25.9 s 0.40 s
subprocess_executor() busy worker-seconds, 600 req / 6 conn 154.6 1.66
Owner lookups, 600 req / 6 conn 600 6

How it was measured (Linux, ~480-495 processes, median of 3 runs each):

  • Server: the real site app (registry_loopback_site.build_app()) on 127.0.0.1, the real platform_compat.get_tcp_peer_pid (/proc scan) and the real 8-worker subprocess_executor(). Only kas_registry_loopback.candidate_pids was stubbed to answer the client process pid.
  • Client: a separate process, one thread per keep-alive http.client connection. Each request is a GET with no MCP session, which the site answers 405 right after attesting, so only the attest step is timed.
  • Busy workers = threads inside _engine_behind, integrated over the run.

Reading: with the cache, executor time stays flat (1.65 -> 1.66 worker-seconds) from 100 to 600 requests; only each connection first lookup costs anything. By these numbers the concurrency cap of 4 is not needed for repeated requests on kept-alive connections.

Not measured: a burst of many new connections (each still pays one ~25 ms scan, ~260 ms when six run at once), a real KAS engine and MCP traffic, macOS lsof, Windows, and other gateway work sharing the executor.

@iamwhatever

Copy link
Copy Markdown
Contributor

Taking this over to land it: it has been idle since 2026-12-01 and now conflicts with main. I will rebase the three commits on current main, resolve conflicts keeping every upstream change, push to this branch (maintainer edits are allowed) and drive CI green. Authorship stays with @nodomain; no scope change beyond what the rebase needs.

Follow-ups to the registry loopback site (kirodotdev#44376) from Christoph Lumme's
review of the dashboard's catalog entries:

- A bind of 127.0.0.1:5470 that fails is logged at error with the holder's
  pid where it can be read, recorded as listener_refusal(), and named in
  every governed KAS session's start notice. Pointers stay unmarked while
  the listener is not held, so no call reaches the holder.
- The listener binds its own socket: SO_REUSEADDR on POSIX (a live
  listener still refuses a second bind), SO_EXCLUSIVEADDRUSE on Windows, so
  no other program can bind beside it. The web entries' listener too.
- A recorded runtime is matched by its start id as well as its pid, and an
  unknown start id now refuses instead of passing: register() reads the
  start id when none is given and records nothing without one. A reused pid
  (fast on Windows) never inherits a dead chat's record.
- The peer lookup (lsof on macOS) runs once per TCP connection, at most
  four at a time and three seconds each, so a local process opening
  connections cannot stall the gateway or its shared executor.
- The loopback site turns on by itself: a start whose Crew servers the
  engine filters under a registry, while this gateway does not hold the
  listener, raises RegistryFilterRefusal; retried_over_loopback binds
  127.0.0.1:5470, writes a marker in the data home and runs the start once
  more with Crew's servers marked. The next gateway start binds the site at
  boot from the marker. A busy port fails the start loudly, naming the
  holder. agent.mcp_registry_mode and the security policy's
  mcp_registry_mode stay as explicit declarations.

Tests cover a taken port, a restart that loses the port, a second bind
beside the held listener, the Windows socket option, a pid without a start
id, the per-connection cache, a lookup that hangs, the concurrency cap, a
reload on the same engine and the registry-filter retry.

Co-authored-by: Joe Guo <zejiangg@amazon.com>
@iamwhatever
iamwhatever force-pushed the fix/kas-loopback-review-followups branch from f07bc6d to b80b935 Compare December 5, 2026 20:52
@github-actions github-actions Bot removed the merge conflict Branch has merge conflicts with its base — author must resolve before merge label Dec 5, 2026

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

fork Pull request from a fork (external contributor) readiness: action required A blocking check or review needs attention

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants