Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion docs/feature-map/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ this area is reached from inside it unless stated otherwise.
| Feature | What it is | Reach it | Page | Handler | Endpoints |
|---|---|---|---|---|---|
| Shared Crew backend | Fair-admission capacity and accepted work, collaboration state and capability reporting | API only: `/api/shared-crew/*` | None (backend only) | `shared_crew/routes_admission.py`, `shared_crew/routes_collab.py`, `shared_crew/routes_capabilities.py` | `GET /api/shared-crew/capacity`, `GET /api/shared-crew/work`, `POST /api/shared-crew/work/{work_id}/cancel`, `GET /api/shared-crew/presence`, `GET /api/shared-crew/capabilities` |
| Redaction cards | A removed credential renders as a lock tag and a suspicious URL as a Blocked link chip; each opens a card explaining the removal, naming the credential's source (Open in Terminal pre-fills without running) or showing the link's full address (Copy URL, Open once, Allow for this host). Resting the mouse on a tag or chip, or focusing it from the keyboard, shows a read-only preview stating the rule in plain words; every action stays on the card. No key is taken, a focus-opened preview stays under a passing mouse, the preview closes when its marker scrolls out of view, and a tap opens the card directly. The first reply with removed values in a session carries a one-time coach. Allowed hosts are listed and revoked in Settings → Security → Redaction | Inside an assistant reply that had a value or link removed | `components/RedactionCards.tsx`, `pages/settings/SecurityPanel.tsx` (the Redaction section: `SecurityPanelRedaction.tsx`) | `handlers/redaction.py` | `GET,POST,DELETE /api/redaction/allowed-hosts` |
| Redaction cards | A removed credential renders as a lock tag and a suspicious URL as a Blocked link chip; each opens a card explaining the removal, naming the credential's source (Open in Terminal pre-fills without running) or showing the link's full address (Copy URL, Open once, Allow for this host). Resting the mouse on a tag or chip, or focusing it from the keyboard, shows a read-only preview stating the rule in plain words; every action stays on the card. No key is taken, a focus-opened preview stays under a passing mouse, the preview closes when its marker scrolls out of view, and a tap opens the card directly. The first reply with removed values in a session carries a one-time coach. The credential card offers the owner Show / Copy / Hide for the removed value while the gateway holds it in memory (owner browser only; every reveal audited; gone after a restart or 24 h). Allowed hosts are listed and revoked in Settings → Security → Redaction | Inside an assistant reply that had a value or link removed | `components/RedactionCards.tsx` (shared controls: `components/redactionPrimitives.tsx`; owner reveal: `components/RedactedValueReveal.tsx`), `pages/settings/SecurityPanel.tsx` (the Redaction section: `SecurityPanelRedaction.tsx`) | `handlers/redaction.py`, `handlers/redacted_reveal.py` (store: `security/reveal_store.py`) | `GET,POST,DELETE /api/redaction/allowed-hosts`, `POST /api/security/redacted-value` |
| Remote media gate | A remote image, video or audio in an assistant reply loads only when the reader clicks it, so rendering never fetches an agent-chosen URL; media pointing at the gateway's own routes is refused | Inside an assistant reply that embeds remote media | `components/markdown/remoteMedia.tsx`, `components/markdown/ImgWithFallback.tsx` (composed by `components/MarkdownRenderer.tsx`) | — | — |
| Loaded skill card | A skill selected through the `$` picker appears as a collapsed transcript card with a book icon. A one-skill card expands to its detail line and capped body. A card with several skills expands to one detail line and one row per skill; each saved body's native row button opens only that skill's keyboard-scrollable capped body, so every other row header stays reachable. A structured skill with an empty body stays non-interactive and states that the skill has no instructions. Each saved body has a bottom fade that clears at the scroll end, and compact headings keep skill instructions below assistant answers in the transcript hierarchy. Name-only rows from older gateways remain non-interactive and state that instructions were not recorded for older turns | Session transcript → composer `$` picker → select and send a skill | `pages/chat/SkillLoadCard.tsx`, `pages/chat/MarkdownDisclosureCard.tsx` (shared disclosure shell with `pages/chat/CompactionCard.tsx`), `pages/chat/transcriptRenderers.tsx`, `app-sdk/messageRenderers.tsx` | `chat_turn/prompt_assembly.py` (`_expand_dollar_skills` snapshots the loaded names and bodies) | `POST /api/chat`, `GET /api/ws` (`chat_message` row with `meta.kind=skill_load`) |
| Crew dispatch notice | A one-per-person-turn product notice row the gateway writes into a Crew Mode conductor's own chat when it dispatches a crew member with `session_create`, so a dispatch that is otherwise only a folded tool line stays visible where it happened. The row names the right-panel **Board** (view `workers`) and carries an **Open Board** button with the Board's bolt glyph that reveals the panel (the single host reveal `handleOpenCrewTab`). It is written, not model text, so it always appears independent of what the conductor said: only on a successful dispatch, only from a Crew Mode root (a worker's own sub-dispatch writes nothing), and only on a turn the person sent in the dashboard (an automated conductor turn writes nothing); N dispatches in one person-turn collapse to one notice. The row's English `content` is a fallback for channel mirrors and SSE readers; the dashboard keys its localized copy and the button on `meta.kind=crew_dispatch_notice` | Inside a Crew Mode conductor's transcript, after it dispatches a crew member on a person-sent turn | `pages/chat/CrewDispatchNoticeCard.tsx`, `pages/chat/page/transcriptRendering.tsx`, `pages/chat/transcriptRenderers.tsx`, `pages/chat/useChatPageResourcesController.tsx` (`handleOpenCrewTab`, the host reveal threaded down), `components/ChatPane.tsx`, `components/ChatPaneTranscript.tsx`, `components/SessionGridView.tsx`, `pages/ChatPage.tsx` | `crew_dispatch_notice.py` (`maybe_write_dispatch_notice`, the writer and its one-per-turn gate), `handlers/session_control.py` (`_write_crew_dispatch_notice`, called after a committed `session_create`) | `POST /api/session-control/create`, `GET /api/ws` (`chat_message` row with `meta.kind=crew_dispatch_notice`) |
Expand Down
2 changes: 2 additions & 0 deletions docs/system-specs/modules/security.md

Large diffs are not rendered by default.

80 changes: 74 additions & 6 deletions src/kiro_crew/dashboard/chat_turn/segment_flush.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,11 @@
from kiro_crew.messaging.empty_turn_copy import EMPTY_TURN_NOTICE, EMPTY_TURN_NOTICE_AFTER_WORK

# Read when the module loads (the placeholder pattern), so imported plainly.
from kiro_crew.security import EXFILTRATION_REDACTION_TAG_PREFIX, redact, redact_and_truncate
from kiro_crew.security import (
EXFILTRATION_REDACTION_TAG_PREFIX,
redact,
redact_and_truncate,
)
from kiro_crew.security.credential_sources import credential_records
from kiro_crew.security.redaction import redact_credentials_with_records
from kiro_crew.sel import SecurityEvent
Expand Down Expand Up @@ -402,6 +406,24 @@ def _give_back_run(

def _redact_segment(
slot: _ChatSlot, text: str, *, _ordered_out: list[bool] | None = None
) -> tuple[str, list[dict], list[dict]]:
""":func:`_redact_segment_unkept`, keeping only the saved records' values.

Every pass inside mints handles into one pending map; only the handles in
the records this returns are kept in ``security.reveal_store``.
"""
pending: dict[str, str] = {}
out = _redact_segment_unkept(slot, text, _ordered_out=_ordered_out, _reveal_pending=pending)
_commit_reveals(slot, out[2], pending)
return out


def _redact_segment_unkept(
slot: _ChatSlot,
text: str,
*,
_ordered_out: list[bool] | None = None,
_reveal_pending: dict[str, str] | None = None,
) -> tuple[str, list[dict], list[dict]]:
"""Redact one assistant segment as one text and describe every placeholder.

Expand Down Expand Up @@ -451,7 +473,9 @@ def _redact_segment(
_reset_segment_copy(slot)
shown = _reflow_label_and_audit(slot, text)
if raw == "":
return _redact_segment_text(slot, shown, _ordered_out=_ordered_out)
return _redact_segment_text(
slot, shown, _ordered_out=_ordered_out, _reveal_pending=_reveal_pending
)
if not text:
# Streamed deltas with no streamed text left: nothing was shown.
return "", [], []
Expand All @@ -464,7 +488,9 @@ def _redact_segment(
try:
whole = reflow_and_label_glued_option_marker(raw)[0]
order: list[bool] = []
saved = _redact_segment_text(slot, whole, _ordered_out=order)
saved = _redact_segment_text(
slot, whole, _ordered_out=order, _reveal_pending=_reveal_pending
)
if removed:
per_delta, _, _ = _redact_segment_text(slot, shown)
# Never edit the raw copy to drop such a value: a mask changes
Expand All @@ -481,7 +507,11 @@ def _redact_segment(
and saved[0]
!= (
strict := _redact_segment_text(
slot, whole, tuple(removed), _ordered_out=strict_order
slot,
whole,
tuple(removed),
_ordered_out=strict_order,
_reveal_pending=_reveal_pending,
)
)[0]
):
Expand Down Expand Up @@ -668,11 +698,15 @@ def _redact_segment_text(
judged_sri_values: Collection[str] = (),
*,
_ordered_out: list[bool] | None = None,
_reveal_pending: dict[str, str] | None = None,
) -> tuple[str, list[dict], list[dict]]:
"""Both removers over ``text``, with the records each placeholder needs.

``_ordered_out`` gets ``[True]``, or ``[False]`` when a record has no
placeholder of its own, so the records do not pair with them by order.
``_reveal_pending``, when given, gets each removed value under the
``reveal_id`` its record carries; nothing is kept until
:func:`_commit_reveals` keeps the ones whose records are saved.
"""
if _ordered_out is not None:
_ordered_out[:] = [True]
Expand All @@ -698,7 +732,37 @@ def _redact_segment_text(
for w in cred_warnings:
# nosemgrep: python.lang.security.audit.logging.logger-credential-leak.python-logger-credential-disclosure -- the redactor's warning names the pattern class, never the matched value; moved verbatim
logger.warning("Credential redacted in chat segment: %s", w)
return redacted, blocked_links, credential_records(matches, slot.credential_evidence)
return (
redacted,
blocked_links,
credential_records(matches, slot.credential_evidence, reveal_pending=_reveal_pending),
)


def _commit_reveals(slot: _ChatSlot, records: Iterable[Any], pending: dict[str, str]) -> None:
"""Keep in gateway memory the removed values of the records being SAVED.

Only these: a pass whose records are thrown away (the per-delta check, a
strict retry that lost, a flush that failed closed) leaves nothing behind
in ``security.reveal_store``. A value the store refuses (too large, no
slot) leaves its record with ``reveal_id`` None, which reads as not kept.
"""
# Imported here: this module's functions also run from the chat_runner
# facade's namespace, which does not carry these names.
from kiro_crew.security import reveal_store
from kiro_crew.security.credential_sources import REVEAL_KEY

scope = str(getattr(slot, "key", "") or "")
for record in records:
if not isinstance(record, dict):
continue
handle = record.get(REVEAL_KEY)
if not isinstance(handle, str):
continue
value = pending.get(handle)
if value is None or not reveal_store.STORE.stash_as(handle, value, scope=scope):
record[REVEAL_KEY] = None
pending.clear()


def _append_command_reply(slot: _ChatSlot, text: str) -> None:
Expand All @@ -718,7 +782,11 @@ def _append_command_reply(slot: _ChatSlot, text: str) -> None:
turn, not to a command answered without one.
"""
ordered: list[bool] = []
redacted, blocked_links, redactions = _redact_segment_text(slot, text, _ordered_out=ordered)
pending: dict[str, str] = {}
redacted, blocked_links, redactions = _redact_segment_text(
slot, text, _ordered_out=ordered, _reveal_pending=pending
)
_commit_reveals(slot, redactions, pending)
meta: dict[str, Any] = {}
if blocked_links:
meta["blocked_links"] = blocked_links
Expand Down
6 changes: 6 additions & 0 deletions src/kiro_crew/dashboard/handlers/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -1112,6 +1112,12 @@ def _build_prompt_base() -> list[dict[str, Any]]:
api_portability_import,
api_portability_preview,
)

# Owner reveal of a removed credential -- the ONE reader of the in-memory
# ``security.reveal_store``; refuses every agent, app and non-owner caller.
from kiro_crew.dashboard.handlers.redacted_reveal import ( # noqa: E402, F401
api_owner_value_reveal,
)
from kiro_crew.dashboard.handlers.security import ( # noqa: E402, F401
api_denied_command_builtin_toggle,
api_denied_command_user_add,
Expand Down
132 changes: 132 additions & 0 deletions src/kiro_crew/dashboard/handlers/redacted_reveal.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,132 @@
"""``POST /api/security/redacted-value`` -- the owner reveals a removed credential.

The credential redactor removes a secret from an agent reply before it is
saved; ``security.reveal_store`` keeps that value in gateway memory, and this
route is its ONE reader. The rule it enforces (RFC *Owner reveal*): redacted
values may be revealed only to the owner through the browser; no
agent-reachable path may ever return them; originals never touch disk.

So the gate refuses, before anything is read:

- an internal caller (the loopback secret every MCP tool, agent, crewmate,
sub-agent and cron uses), whatever identity it claims;
- an app token or an app-scoped request;
- anything that is not a dashboard-user credential;
- a dashboard user who is not the owner (an allow-listed Slack teammate
running ``!dashboard``, a relay teammate).

Every allowed reveal is written to the security event log SYNCHRONOUSLY
before the value is returned; when the record cannot be written the value is
not returned. The record names who, when and which handle -- never the value.

Known limit, the same one the redaction switch states: the owner gate is an
identity check, not proof a human clicked. An agent driving the owner's own
logged-in browser through computer use could press Show; that reveal is still
audited. An agent the owner runs without the sandbox can already read the
owner's dashboard credential from disk, so it is out of reach of any route.
"""

from __future__ import annotations

import asyncio
import logging

from aiohttp import web

from kiro_crew.dashboard.handlers._shared import _owner_denial_response
from kiro_crew.dashboard.handlers.source_providers import is_owner_dashboard_request
from kiro_crew.security import reveal_store

logger = logging.getLogger(__name__)

_SOURCE = "redacted-reveal"
_MAX_SLOT_CHARS = 512
_NO_STORE = {"Cache-Control": "no-store", "Pragma": "no-cache"}


def _refusal(request: web.Request) -> str:
"""Why this caller may not reveal, or ``""`` for the owner's browser."""
if request.get("internal_auth") is True or "X-Internal-Secret" in request.headers:
return "internal caller"
if request.get("app"):
return "app caller"
if request.get("is_dashboard_user") is not True:
return "not a dashboard user"
if not is_owner_dashboard_request(request):
return "not the owner"
return ""


def _audit(*, caller: str, outcome: str, detail: str, critical: bool) -> bool:
"""One SEL row for a reveal or a refusal; never carries the value."""
try:
from kiro_crew.sel import sel

sel().log_api_access(
caller=caller,
operation="redacted_value.reveal",
outcome=outcome,
source=_SOURCE,
resources=detail[:200],
critical=critical,
)
return True
except Exception:
logger.debug("could not write the reveal audit event", exc_info=True)
return False


def _gone() -> web.Response:
return web.json_response(
{
"error": "this value is no longer available; check its source",
"code": "reveal_unavailable",
},
status=410,
headers=_NO_STORE,
)


async def api_owner_value_reveal(request: web.Request) -> web.Response:
"""Return ``{"value": ...}`` for one handle, to the owner's browser only."""
caller = str(request.get("user") or "anonymous")
why = _refusal(request)
if why:
logger.warning("refused a redacted-value reveal: %s (app=%s)", why, request.get("app"))
await asyncio.to_thread(_audit, caller=caller, outcome="denied", detail=why, critical=False)
return _owner_denial_response(
request, "dashboard owner required", "dashboard_owner_required"
)
try:
body = await request.json()
except Exception:
return web.json_response({"error": "invalid JSON", "code": "invalid_json"}, status=400)
slot = body.get("slot") if isinstance(body, dict) else None
handle = body.get("id") if isinstance(body, dict) else None
if (
not isinstance(slot, str)
or not slot
or len(slot) > _MAX_SLOT_CHARS
or not isinstance(handle, str)
or not reveal_store.REVEAL_ID_RE.match(handle)
):
return web.json_response({"error": "invalid body", "code": "invalid_body"}, status=400)
value = reveal_store.STORE.reveal(handle, scope=slot)
if value is None:
await asyncio.to_thread(
_audit, caller=caller, outcome="unavailable", detail=f"id={handle}", critical=False
)
return _gone()
recorded = await asyncio.to_thread(
_audit, caller=caller, outcome="allowed", detail=f"id={handle} slot={slot}", critical=True
)
if not recorded:
return web.json_response(
{
"error": "the security event log is unavailable, so the value stays hidden",
"code": "reveal_audit_unavailable",
},
status=503,
headers=_NO_STORE,
)
return web.json_response({"value": value}, headers=_NO_STORE)
1 change: 1 addition & 0 deletions src/kiro_crew/dashboard/routes/system.py
Original file line number Diff line number Diff line change
Expand Up @@ -223,6 +223,7 @@ def register(app: web.Application) -> None:
# legitimate caller is the owner's browser.
app.router.add_get("/api/security/credential-redaction", handlers.api_credential_redaction_get)
app.router.add_put("/api/security/credential-redaction", handlers.api_credential_redaction_put)
app.router.add_post("/api/security/redacted-value", handlers.api_owner_value_reveal)
app.router.add_get("/api/approvals", handlers.api_approvals)
app.router.add_post("/api/approvals/{id}/{action}", handlers.api_approval_resolve)

Expand Down
Loading
Loading