From c79abc28fe345019695fbc60394db9cfcfd480ef Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 1 Dec 2026 23:05:15 -0600 Subject: [PATCH 1/8] Flag routes refuse a scoped caller before validating; scoped readers see no rule ids or labels BACKLOG #6638 items 1 to 6. - GET /security/posture labels a credential-reminder-silencing alert rule by its position alone for a channel-scoped reader (item 1), as GET /alerts/rules shows that reader no id. - POST /connections/{name}/flag now reads its own body and runs the scope refusal on the raw name and direction before it validates either (item 2). BEHAVIOUR CHANGE: a channel-scoped caller's malformed request (a direction naming neither side, a body that is not JSON or is empty, a name failing the connection-name rule) was an unaudited 422; it is now the 403 and auth.channel_denied row any other out-of-scope target gets. An all-channels caller still gets the 422. - The refusal is one function, _refuse_connection_flag, exposed to the console as CoreHandlers.refuse_connection_flag (item 4). The console's flag route calls it on the raw form before validating, takes its name unannotated and checks the name rule after (item 3), and no longer imports CONNECTION_DENIED_DETAIL. Seam digest regenerated with scripts/webconsole_seam_snapshot.py --write (4033184244d47e90 to 649e40ac2b7f6902); SUPPORTED_ENGINE_SEAMS bumped to match. - AlertRuleInfo gains id_withheld, so a null id no longer means both unlabelled and withheld (item 5). - GET /connections/{name}/metadata withholds the metadata labels from a channel-scoped reader, with metadata_withheld true (item 6). Verified-by: tests --- messagefoundry/api/_ui_seam.py | 12 +- messagefoundry/api/app.py | 161 ++++++++++++++---- messagefoundry/api/models.py | 12 +- messagefoundry_webconsole/__init__.py | 2 +- .../routes/connection_writes.py | 25 ++- .../tests/golden/ui_input_rules.txt | 2 +- .../tests/test_ui_object_scope.py | 32 ++++ tests/golden/webconsole_seam.snapshot | 5 +- ...test_channel_scope_posture_users_reload.py | 58 +++++++ tests/test_console_seam_inventory.py | 19 ++- .../test_object_scope_flag_and_alert_rules.py | 78 ++++++++- tests/test_security_doc_drift.py | 2 + 12 files changed, 338 insertions(+), 70 deletions(-) diff --git a/messagefoundry/api/_ui_seam.py b/messagefoundry/api/_ui_seam.py index fca7544d2b..1afef307c7 100644 --- a/messagefoundry/api/_ui_seam.py +++ b/messagefoundry/api/_ui_seam.py @@ -1011,12 +1011,18 @@ #: failure is what refuses that pair. Re-derived with ``--write``, from ``605d329d7e840bb8`` to #: ``4033184244d47e90``. #: +#: BACKLOG #6638: ``CoreHandlers`` gained ``refuse_connection_flag``, the engine's one flag-route +#: scope refusal, which the console's flag route now calls in place of its own copy, so the console +#: no longer imports ``api.message_scope.CONNECTION_DENIED_DETAIL`` (the blind spot the #3378 entry +#: above names). ``AlertRuleInfo`` gained ``id_withheld``. Re-derived with ``--write``, from +#: ``4033184244d47e90`` to ``649e40ac2b7f6902``. +#: #: The digest below covers the surface DISCOVERED from the console's own imports and uses, which is #: strictly larger than the five hand-maintained tuples it replaced -- those had drifted, and the #: proof is that commit 40a4d5d9 added a REQUIRED ``UploadedFileList.scope`` field the console renders #: unconditionally while touching no seam file at all. Regenerate with #: ``python scripts/webconsole_seam_snapshot.py --write``; never hand-edit it to silence a gate. -ENGINE_UI_SEAM: str = "4033184244d47e90" +ENGINE_UI_SEAM: str = "649e40ac2b7f6902" @dataclass(frozen=True, slots=True) @@ -1112,6 +1118,10 @@ class CoreHandlers: # arrives once a shutdown's drain has begun or reaches the engine's write lock after that. One # still queued for that lock when its wait runs out is refused 503 instead. set_connection_flag: Callable[..., Awaitable[Any]] + # BACKLOG #6638: the flag routes' one scope refusal (``_refuse_connection_flag``), which the + # console runs on the form's raw direction before it validates the form, so a channel-scoped + # caller's bad name or direction is the audited 403 the JSON route gives. + refuse_connection_flag: Callable[..., Awaitable[Any]] # Dual-control approvals (ASVS 2.3.5, BACKLOG #1982): the console's Approvals page. The JSON # gates are require(APPROVALS_APPROVE) on the list and require_paced(APPROVALS_APPROVE) on # reject, so those /ui routes assert approvals:approve through require_ui, which paces a /ui diff --git a/messagefoundry/api/app.py b/messagefoundry/api/app.py index d2d994c527..2880fbd25d 100644 --- a/messagefoundry/api/app.py +++ b/messagefoundry/api/app.py @@ -637,6 +637,31 @@ _CONNECTION_NAME_ADAPTER: TypeAdapter[str] = TypeAdapter(ConnectionName) +#: What :func:`_parse_json_body` returns for a body that is not JSON, and for an empty one. +_UNPARSEABLE: Final = object() +_EMPTY_BODY: Final = object() + +#: The request body ``POST /connections/{name}/flag`` reads itself (BACKLOG #6638), declared to +#: OpenAPI as FastAPI would have declared the model it used to take. +_FLAG_REQUEST_OPENAPI: Final[dict[str, Any]] = { + "requestBody": { + "required": True, + "content": {"application/json": {"schema": ConnectionFlagRequest.model_json_schema()}}, + } +} + + +def _parse_json_body(raw: bytes) -> object: + """``raw`` decoded as JSON, :data:`_EMPTY_BODY` when it is empty, or :data:`_UNPARSEABLE`. One + parse, so a route's scope check and its model read the same value (a duplicated key included). + A body over the size limit never reaches here (``_limit_request_body``).""" + if not raw: + return _EMPTY_BODY + try: + return json.loads(raw) + except (ValueError, RecursionError): + return _UNPARSEABLE + def _valid_connection_name(value: str) -> bool: """Whether ``value`` passes the ``ConnectionName`` rule the ``reveal`` query is validated by. @@ -2525,6 +2550,15 @@ def _posture_loosenings( # stash-or-default pattern — settings-scoped, so this route reports it completely even with no # graph loaded, unlike the connection-scoped cleartext_accepted set below. alerts_settings = getattr(state, "alerts_settings", None) or AlertsSettings() + if visible is not None and any(rule.id is not None for rule in alerts_settings.rules): + # BACKLOG #6638 item 1: a rule's id is operator free text that may name a connection, and + # GET /alerts/rules shows a channel-scoped caller no id, so the reminder entry labels each + # rule by its position alone for such a reader. + alerts_settings = alerts_settings.model_copy( + update={ + "rules": [rule.model_copy(update={"id": None}) for rule in alerts_settings.rules] + } + ) # BACKLOG #1004: [secret_rotation] carries the store DEK's calendar-expiry opt-out. Same # stash-or-default pattern — settings-scoped, so this route reports it completely with no graph. secret_rotation_settings = ( @@ -5911,8 +5945,9 @@ async def security_posture( only for an inbound in its own scope that the graph holds, in at least ``loosenings``, ``static_credential_hops``, ``security``'s static-credential opt-outs and the audit row. ``loosenings_scope`` and ``static_credential_hops_scope`` then say the reading is narrowed. - The rest is shown whole, and some of it is operator free text, such as an alert rule's id or - an attestation reason, which may name a connection.""" + An alert rule is labelled by its position alone, with no ``id``, as ``GET /alerts/rules`` + shows it no id (BACKLOG #6638). The rest is shown whole, and some of it is operator free + text, such as an attestation reason, which may name a connection.""" # The live cipher posture (on/off + key fingerprint only). cipher_info() is the public Store # accessor — the route never touches engine.store._cipher. info = engine.store.cipher_info() @@ -6748,7 +6783,76 @@ async def restart_connection( engine, identity, name, "restart", client=client_ip(request) ) - @app.post("/connections/{name}/flag") + async def _refuse_connection_flag( + engine: Engine, identity: Identity, name: str, direction: object, client: str | None + ) -> None: + """The flag routes' one scope refusal: :func:`_deny_connection` for a channel-scoped + caller's target it may not flag, and nothing for any other caller (BACKLOG #1152, #3378). + + ``direction`` is whatever the request carried, unvalidated, so a caller's direction that + names neither side is refused here, audited, before any validation can answer 422 (BACKLOG + #6638). The JSON route and the web console's flag route both call this, the console across + the seam, so the refusal is written once.""" + if identity.allowed_channels is None: + return + rr = engine.registry_runner + wrong_direction = direction != "inbound" + if ( + wrong_direction + or not identity.can_access_channel(name) + # inbound_names(), as the engine's own guard reads it: an engine shard's view holds only + # its own inbounds, and a caller's in-scope inbound on a sibling is no denial. + or (rr is not None and name not in rr.registry.inbound_names()) + ): + await _deny_connection( + engine, + identity, + name, + client, + # The row's marker, for a row that names an in-scope inbound (BACKLOG #3378). + flag_direction_not_inbound=wrong_direction, + ) + + @app.post("/connections/{name}/flag", openapi_extra=_FLAG_REQUEST_OPENAPI) + async def connection_flag_route( + # Not annotated, and the body is read here rather than declared: FastAPI validates both + # before the handler runs, so a channel-scoped caller's malformed name or body answered 422 + # with no denial row (BACKLOG #6638). The scope refusal runs first; the name rule and the + # body model then answer the 422 they answered before. + name: str, + request: Request, + engine: Engine = Depends(_get_engine), + identity: Identity = Depends(require_paced(Permission.CONFIG_DEPLOY)), + ) -> dict[str, object]: + """``POST /connections/{name}/flag``: the scope refusal, then the request's validation, + then :func:`set_connection_flag`, which says what the toggle does.""" + body = _parse_json_body(await request.body()) + direction = body.get("direction") if isinstance(body, dict) else None + await _refuse_connection_flag(engine, identity, name, direction, client_ip(request)) + errors: list[Any] = [] + try: + _CONNECTION_NAME_ADAPTER.validate_python(name) + except ValidationError as exc: + errors += [ + {**err, "loc": ("path", "name", *err["loc"])} + for err in exc.errors(include_url=False) + ] + req: ConnectionFlagRequest | None = None + if body is _EMPTY_BODY: + errors.append({"type": "missing", "loc": ("body",), "msg": "Field required"}) + elif body is _UNPARSEABLE: + errors.append({"type": "json_invalid", "loc": ("body",), "msg": "JSON decode error"}) + else: + try: + req = ConnectionFlagRequest.model_validate(body) + except ValidationError as exc: + errors += [ + {**err, "loc": ("body", *err["loc"])} for err in exc.errors(include_url=False) + ] + if errors or req is None: + raise RequestValidationError(errors) + return await set_connection_flag(name, req, request, engine=engine, identity=identity) + async def set_connection_flag( name: ConnectionName, req: ConnectionFlagRequest, @@ -6771,37 +6875,23 @@ async def set_connection_flag( A channel-scoped caller may flag only an inbound in its own scope (BACKLOG #1152). Every other target gets :func:`_deny_connection`, the per-name routes' one refusal, before the - engine looks the name up, so a 200 against a 409 cannot tell it which names exist. - - The test is written here rather than through :func:`_resolve_connection`, which the other - per-name routes share, because the two ask whether a name exists in different sets - (BACKLOG #3378). Those routes act on this process's runner, so they read its own inbounds. - The flag lives in the store, so this one reads ``inbound_names()``, every inbound in the - deployment, and a caller's in-scope inbound on a sibling engine shard is no denial. Both - give the same refusal for an outbound and for a name outside the scope, and so does the web - console's flag route for a direction that names neither side. A change to that refusal has - to be made in at least those three places. :func:`alerts_rules` reads the same + engine looks the name up, so a 200 against a 409 cannot tell it which names exist. The JSON + route and the console's flag route give it before they validate the request + (:func:`_refuse_connection_flag`, BACKLOG #6638). + + That test is written in :func:`_refuse_connection_flag` rather than through + :func:`_resolve_connection`, which the other per-name routes share, because the two ask + whether a name exists in different sets (BACKLOG #3378). Those routes act on this process's + runner, so they read its own inbounds. The flag lives in the store, so this one reads + ``inbound_names()``, every inbound in the deployment, and a caller's in-scope inbound on a + sibling engine shard is no denial. Both give the same refusal for an outbound and for a + name outside the scope. :func:`alerts_rules` reads the same ``inbound_names()`` set for a scoped caller in its own code. The two differ at least with no graph loaded, where this route lets an in-scope name reach the engine and that one withholds every rule naming a connection, and on a name the runner also knows as an outbound, which that one withholds and this one admits for ``direction=inbound``.""" - rr = engine.registry_runner - wrong_direction = req.direction != "inbound" - if identity.allowed_channels is not None and ( - wrong_direction - or not identity.can_access_channel(name) - # inbound_names(), as the engine's own guard reads it: an engine shard's view holds only - # its own inbounds, and a caller's in-scope inbound on a sibling is no denial. - or (rr is not None and name not in rr.registry.inbound_names()) - ): - await _deny_connection( - engine, - identity, - name, - client_ip(request), - # The row's marker, for a row that names an in-scope inbound (BACKLOG #3378). - flag_direction_not_inbound=wrong_direction, - ) + # Again here, though the JSON route ran it already: the console calls this handler directly. + await _refuse_connection_flag(engine, identity, name, req.direction, client_ip(request)) try: await engine.set_connection_flag( name, @@ -6869,6 +6959,9 @@ async def _connection_metadata_row( """The UNREDACTED metadata row for ``name``, after the per-channel scope check. Only :func:`connection_metadata` calls it, and it redacts the row before returning it.""" rr, direction = await _guarded_direction(engine, identity, name, client_ip(request)) + # BACKLOG #6638: the labels are operator free text, which may name a connection outside a + # channel-scoped caller's scope, so such a caller is shown none, and told they were withheld. + withheld = identity.allowed_channels is not None if direction == "in": ic = rr.registry.inbound[name] in_failed, in_filtered = rr.inbound_failed(name), rr.inbound_filtered(name) @@ -6878,7 +6971,8 @@ async def _connection_metadata_row( method=ic.spec.type.value, running=rr.inbound_running(name), router=ic.router, - metadata=dict(ic.metadata) if ic.metadata else None, + metadata=None if withheld or not ic.metadata else dict(ic.metadata), + metadata_withheld=withheld, settings=redacted_settings(ic.spec.settings), # ADR 0031 failure reason, or the #61 (ADR 0048) DR-parked reason — whichever applies. error=in_failed or in_filtered, @@ -6893,7 +6987,8 @@ async def _connection_metadata_row( # BACKLOG #5762: the lane's display state, as the graph node reads it, not the graph's # running flag alone, which read running for a lane that delivers nothing. running=_outbound_display_status(rr, name, oc) == "running", - metadata=dict(oc.metadata) if oc.metadata else None, + metadata=None if withheld or not oc.metadata else dict(oc.metadata), + metadata_withheld=withheld, settings=redacted_settings(oc.spec.settings), simulated=rr.outbound_simulated(name), # ADR 0031 failure reason, or the #61 (ADR 0048) DR-parked reason — whichever applies. @@ -11255,6 +11350,7 @@ def visible(rule: AlertRule) -> bool: recipient_count=len(r.recipients) if r.recipients else 0, # #138 — the operator rule label ({rule_id}); withheld per the docstring (#3378) id=r.id if show_ids else None, + id_withheld=not show_ids, control_action=r.control_action, # #144 — auto-remediation action control_target=r.control_target, mute=r.mute, # #143 — static per-rule notification mute @@ -12508,6 +12604,7 @@ def _oidc_authorization_host(endpoint: str) -> str: metrics_history=metrics_history, graph_edges=graph_edges, set_connection_flag=set_connection_flag, + refuse_connection_flag=_refuse_connection_flag, list_approvals=list_approvals, approve_action=approve_action, reject_action=reject_action, diff --git a/messagefoundry/api/models.py b/messagefoundry/api/models.py index c62b478490..224f808188 100644 --- a/messagefoundry/api/models.py +++ b/messagefoundry/api/models.py @@ -1818,7 +1818,10 @@ class ConnectionMetadata(PhiGatedModel): method: str # connector type, e.g. "mllp" / "file" / "rest" running: bool router: str | None = None # inbound only - metadata: dict[str, Any] | None = None # operator labels + metadata: dict[str, Any] | None = None # operator labels; None = none, unless metadata_withheld + # True when ``metadata`` is null because it was withheld from a channel-scoped caller: it is + # operator free text, which may name a connection outside that caller's scope (BACKLOG #6638). + metadata_withheld: bool = False settings: dict[str, Any] # secret-scrubbed view simulated: bool | None = None # outbound only; True = egress-suppressed shadow lane (#15) # Why this connection failed to start (ADR 0031) or was DR-parked (ADR 0048). Rated in @@ -1846,9 +1849,12 @@ class AlertRuleInfo(BaseModel): recipient_count: int = ( 0 # #146 — per-rule email recipients (count only; 0 = uses global email_to) ) - # #138 — operator rule label ({rule_id} template var); None = unlabelled, or withheld from the - # caller (docs/SECURITY.md, GET /alerts/rules; #3378). + # #138 — operator rule label ({rule_id} template var). None = unlabelled, unless ``id_withheld``. id: str | None = None + # True when ``id`` is null because it was withheld from the caller, not because the rule has none + # (docs/SECURITY.md, GET /alerts/rules; #3378, #6638). Set on every rule a channel-scoped caller + # is shown, labelled or not, so the flag does not tell it which rules carry a label. + id_withheld: bool = False control_action: str | None = ( None # #144 — restart_inbound/restart_outbound fired on match (None = none) ) diff --git a/messagefoundry_webconsole/__init__.py b/messagefoundry_webconsole/__init__.py index 603ff5201b..d746bf7352 100644 --- a/messagefoundry_webconsole/__init__.py +++ b/messagefoundry_webconsole/__init__.py @@ -45,7 +45,7 @@ # If cross-seam support is ever genuinely wanted, re-widen this set AND add the CI matrix that # installs the MIN and MAX supported engine builds — the claim and its test land together, or not # at all. -SUPPORTED_ENGINE_SEAMS: frozenset[str] = frozenset({"4033184244d47e90"}) +SUPPORTED_ENGINE_SEAMS: frozenset[str] = frozenset({"649e40ac2b7f6902"}) #: The vendored static assets shipped in THIS wheel (mounted at /ui/static by :func:`mount_ui`). STATIC_DIR = Path(__file__).parent / "static" diff --git a/messagefoundry_webconsole/routes/connection_writes.py b/messagefoundry_webconsole/routes/connection_writes.py index 37ab28d403..2cc91a515d 100644 --- a/messagefoundry_webconsole/routes/connection_writes.py +++ b/messagefoundry_webconsole/routes/connection_writes.py @@ -12,7 +12,6 @@ from fastapi.responses import HTMLResponse, RedirectResponse from messagefoundry.api._ui_seam import UiDeps -from messagefoundry.api.message_scope import CONNECTION_DENIED_DETAIL from messagefoundry.api.models import ( ConnectionFlagRequest, PendingApprovalResponse, @@ -214,10 +213,11 @@ async def ui_bulk_control( @app.post("/ui/connections/{name}/flag") async def ui_set_connection_flag( - # Annotated like the other per-name routes (BACKLOG #1740). This one is the reason not to - # leave it for later: it is the only one of the five that WRITES, reaching the store through - # core.set_connection_flag. - name: ConnectionName, + # NOT annotated, unlike the other per-name routes, for the reason ui_purge_confirm's dest + # is not: FastAPI would answer a bad name 422 before the scope refusal below, so a + # channel-scoped caller's probe wrote no denial row (BACKLOG #6638). The name rule + # (BACKLOG #1740) is checked in the body instead, after that refusal. + name: str, request: Request, engine: Any = Depends(deps.get_engine), identity: Identity = Depends(require_ui(Permission.CONFIG_DEPLOY)), @@ -230,16 +230,13 @@ async def ui_set_connection_flag( assert_same_origin(request) form = dict(parse_qsl((await request.body()).decode("utf-8", "replace"))) direction = form.get("direction", "") + # BACKLOG #3378, #6638: the engine's one flag refusal, on the raw name and direction, before + # either is validated, so a channel-scoped caller's bad name or direction is the audited + # 403 the JSON route gives, not the 422 or 404 below. It returns for any other caller. + await core.refuse_connection_flag(engine, identity, name, direction, client_ip(request)) + if refuse(CONNECTION_RULE, name) is not None: + raise HTTPException(422, CONNECTION_RULE.refusal) if direction not in ("inbound", "outbound"): - # BACKLOG #3378: for a bad direction, a channel-scoped caller gets the audited 403 the - # API handler gives a non-inbound target, not the 404 below. That 404 returns before the - # handler's scope check, so on a first deployment such a caller's probe here would leave - # no denial row. The row's marker is the handler's; docs/SECURITY.md says what it tells. - if identity.allowed_channels is not None: - await core.audit_channel_denied( - engine, identity, name, client_ip(request), flag_direction_not_inbound=True - ) - raise HTTPException(403, CONNECTION_DENIED_DETAIL) raise HTTPException(404, "unknown connection direction") req = ConnectionFlagRequest( flagged=form.get("flagged") == "true", diff --git a/packaging/messagefoundry-webconsole/tests/golden/ui_input_rules.txt b/packaging/messagefoundry-webconsole/tests/golden/ui_input_rules.txt index 3659c42092..802f1d6a33 100644 --- a/packaging/messagefoundry-webconsole/tests/golden/ui_input_rules.txt +++ b/packaging/messagefoundry-webconsole/tests/golden/ui_input_rules.txt @@ -64,7 +64,7 @@ POST /ui/approvals/{approval_id}/approve approval_id path - - POST /ui/approvals/{approval_id}/reject approval_id path - - POST /ui/approvals/{approval_id}/resolve/{outcome} approval_id path - - POST /ui/approvals/{approval_id}/resolve/{outcome} outcome path - - -POST /ui/connections/{name}/flag name path connection 422 +POST /ui/connections/{name}/flag name path - - POST /ui/connections/{name}/purge/{scope} name path connection 422 POST /ui/connections/{name}/purge/{scope} scope path - - POST /ui/connections/{name}/restart name path connection 422 diff --git a/packaging/messagefoundry-webconsole/tests/test_ui_object_scope.py b/packaging/messagefoundry-webconsole/tests/test_ui_object_scope.py index b86454faf0..6bffc36a3a 100644 --- a/packaging/messagefoundry-webconsole/tests/test_ui_object_scope.py +++ b/packaging/messagefoundry-webconsole/tests/test_ui_object_scope.py @@ -140,6 +140,38 @@ async def test_ui_flag_bad_direction_from_a_scoped_caller_is_the_audited_403( assert await engine.store.list_connection_flags() == set() +async def test_ui_flag_bad_name_from_a_scoped_caller_is_the_audited_403(engine: Engine) -> None: + """BACKLOG #6638: the name was annotated, so a bad one answered 422 before the scope refusal and + a scoped caller's probe wrote no denial row. It now gets the audited 403, whose row names no + channel (BACKLOG #3031). The control: an all-channels caller still gets the 422, with no row.""" + service = await auth_service(engine) + await _scoped(service, "dep", Role.DEPLOYMENT, ["IB_A"]) + await provision(service, "wide", [Role.DEPLOYMENT.value]) + async with ui_client(engine, service) as c: + await cookie_login(c, "dep") + r = await c.post( + "/ui/connections/IB A/flag", + data={"direction": "inbound", "flagged": "true"}, + headers=SAME_ORIGIN, + ) + assert r.status_code == 403, r.text[:300] + assert CONNECTION_DENIED_DETAIL in r.text, r.text[:300] + rows = await engine.store.list_audit(actor="dep", action="auth.channel_denied") + assert [(row["channel_id"], json.loads(row["detail"])) for row in rows] == [ + (None, {"channel": None, "malformed_name": True}) + ] + async with ui_client(engine, service) as c: + await cookie_login(c, "wide") + r = await c.post( + "/ui/connections/IB A/flag", + data={"direction": "inbound", "flagged": "true"}, + headers=SAME_ORIGIN, + ) + assert r.status_code == 422, r.text[:300] + assert await engine.store.list_audit(actor="wide", action="auth.channel_denied") == [] + assert await engine.store.list_connection_flags() == set() + + async def test_ui_alerts_page_lists_only_rules_inside_the_scope( engine: Engine, monkeypatch: pytest.MonkeyPatch ) -> None: diff --git a/tests/golden/webconsole_seam.snapshot b/tests/golden/webconsole_seam.snapshot index ec4b374410..7853e99db2 100644 --- a/tests/golden/webconsole_seam.snapshot +++ b/tests/golden/webconsole_seam.snapshot @@ -7,7 +7,7 @@ # by hand (BACKLOG #1220) - so a newly rendered DTO is covered with nobody editing a list. ## ENGINE_UI_SEAM -4033184244d47e90 +649e40ac2b7f6902 ## dataclass messagefoundry.api._ui_seam.UiDeps engine_seam @@ -74,6 +74,7 @@ layered_search metrics_history graph_edges set_connection_flag +refuse_connection_flag list_approvals approve_action reject_action @@ -276,7 +277,7 @@ messagefoundry.api.auth_models.UserSummary: auth_provider, channel_scope, channe messagefoundry.api.auth_models.UserUpdateRequest: disabled, display_name, email, notify_email messagefoundry.api.models.AlertInstanceInfo: acked_at, acked_by, connection, count, event_type, first_seen, id, last_seen, reason, resolved_at, severity, status, suspended_until messagefoundry.api.models.AlertInstanceList: alerts, total, worst_severity -messagefoundry.api.models.AlertRuleInfo: connection, control_action, control_target, cooldown_seconds, escalate_tiers, event_type, id, min_depth, min_oldest_seconds, mute, recipient_count, schedule_configured, severity, transports +messagefoundry.api.models.AlertRuleInfo: connection, control_action, control_target, cooldown_seconds, escalate_tiers, event_type, id, id_withheld, min_depth, min_oldest_seconds, mute, recipient_count, schedule_configured, severity, transports messagefoundry.api.models.AlertSuspendRequest: minutes messagefoundry.api.models.AlertsConfig: email_body_template_configured, email_configured, email_html_template_configured, email_recipient_count, email_smtp_port, email_subject_template_configured, email_use_tls, realert_seconds, rules, smtp_allowed_hosts, webhook_allowed_hosts, webhook_configured, webhook_timeout messagefoundry.api.models.ApprovalDecisionResult: approved_by, operation, rejected_by, requested_by, result diff --git a/tests/test_channel_scope_posture_users_reload.py b/tests/test_channel_scope_posture_users_reload.py index 3f24c45728..9330713a3b 100644 --- a/tests/test_channel_scope_posture_users_reload.py +++ b/tests/test_channel_scope_posture_users_reload.py @@ -35,6 +35,8 @@ from messagefoundry.auth.service import AuthService from messagefoundry.config.models import ConnectorType from messagefoundry.config.settings import ( + AlertRule, + AlertsSettings, ApprovalsSettings, AuthSettings, EgressSettings, @@ -242,6 +244,62 @@ async def test_posture_with_no_graph_still_says_it_is_narrowed(engine: Engine) - assert POSTURE_NARROWED_TO_SCOPE not in wide.json()["static_credential_hops_scope"] +async def test_posture_labels_an_alert_rule_by_position_alone_for_a_scoped_reader( + engine: Engine, +) -> None: + """BACKLOG #6638 item 1: a rule's id is operator free text, so it may name a connection outside + the reader's scope, and GET /alerts/rules shows such a reader no id. The credential-reminder + entry labels the rule by its position alone for that reader, so no byte of its answer holds the + other channel's name. The control: an all-channels reader reads the id whole.""" + alerts = AlertsSettings( + rules=[AlertRule(id=f"hush {THEIRS} certs", event_type="cert_expiry", mute=True)] + ) + service = await _service(engine) + await _user(service, "scoped", [Role.VIEWER.value], [MINE]) + await _user(service, "wide", [Role.VIEWER.value], [ALL_CHANNELS]) + async with _client(engine, service, alerts_settings=alerts) as c: + scoped = await c.get("/security/posture", headers=await _login(c, "scoped")) + wide = await c.get("/security/posture", headers=await _login(c, "wide")) + assert scoped.status_code == 200 and wide.status_code == 200 + wide_risk = {e["switch"]: e["risk"] for e in wide.json()["loosenings"]}["alerts.rules"] + scoped_risk = {e["switch"]: e["risk"] for e in scoped.json()["loosenings"]}["alerts.rules"] + assert THEIRS in wide_risk and "rules[0] (id " in wide_risk + assert "rules[0]" in scoped_risk and "(id " not in scoped_risk + assert THEIRS not in scoped.text + + +async def test_connection_metadata_withholds_the_labels_from_a_scoped_reader( + engine: Engine, +) -> None: + """BACKLOG #6638 item 6: a connection's metadata labels are operator free text, which may name a + connection outside the reader's scope, so a channel-scoped reader of its own inbound is shown + none, with ``metadata_withheld`` saying why. The control: an all-channels reader reads them + whole, and its flag is false.""" + reg = Registry() + reg.add_inbound( + build_inbound_connection( + MINE, + ConnectionSpec(ConnectorType.FILE, {"directory": "./mine"}), + router="r", + metadata={"runbook": f"if this stalls, check {THEIRS}"}, + ) + ) + engine.add_registry(reg) + service = await _service(engine) + await _user(service, "scoped", [Role.VIEWER.value], [MINE]) + await _user(service, "wide", [Role.VIEWER.value], [ALL_CHANNELS]) + async with _client(engine, service) as c: + scoped = await c.get(f"/connections/{MINE}/metadata", headers=await _login(c, "scoped")) + wide = await c.get(f"/connections/{MINE}/metadata", headers=await _login(c, "wide")) + assert scoped.status_code == 200, scoped.text + assert wide.status_code == 200, wide.text + assert wide.json()["metadata"] == {"runbook": f"if this stalls, check {THEIRS}"} + assert wide.json()["metadata_withheld"] is False + assert scoped.json()["metadata"] is None + assert scoped.json()["metadata_withheld"] is True + assert THEIRS not in scoped.text + + # --- GET /users ---------------------------------------------------------------------------------- diff --git a/tests/test_console_seam_inventory.py b/tests/test_console_seam_inventory.py index 234edcedd5..e30cc6cad9 100644 --- a/tests/test_console_seam_inventory.py +++ b/tests/test_console_seam_inventory.py @@ -425,9 +425,10 @@ def _core(*ops: str) -> Field: return Field("core", ops) -#: Every ``CoreHandlers`` and ``AdminHandlers`` field. 66 endpoints by identity, as ADR 0215 -#: slice 1 measured (ADR 0207 moved one to a core and added one of each), 18 cores a JSON route runs -#: past its gate (BACKLOG #5559 added ``admin.checked_user``), 2 sharing a helper with a JSON +#: Every ``CoreHandlers`` and ``AdminHandlers`` field. 65 endpoints by identity, as ADR 0215 +#: slice 1 measured (ADR 0207 moved one to a core and added one of each; BACKLOG #6638 moved +#: ``core.set_connection_flag`` to a core), 20 cores a JSON route runs past its gate (BACKLOG #5559 +#: added ``admin.checked_user``, #6638 ``core.refuse_connection_flag``), 2 sharing a helper with a JSON #: route, and 3 with no JSON route that carries the console's use. _SEAM_FIELDS: dict[str, Field] = { "core.list_connections": _endpoint("GET /connections"), @@ -495,7 +496,10 @@ def _core(*ops: str) -> Field: "core.layered_search": _endpoint("GET /search/layered"), "core.metrics_history": _endpoint("GET /metrics/history"), "core.graph_edges": _endpoint("GET /graph/edges"), - "core.set_connection_flag": _endpoint("POST /connections/{name}/flag"), + # BACKLOG #6638: the JSON route runs the scope refusal, then validates, then this core. + "core.set_connection_flag": _core("POST /connections/{name}/flag"), + # The flag routes' one scope refusal, which the JSON route runs before it validates. + "core.refuse_connection_flag": _core("POST /connections/{name}/flag"), "core.list_approvals": _endpoint("GET /approvals"), "core.approve_action": _endpoint("POST /approvals/{approval_id}/approve"), "core.reject_action": _endpoint("POST /approvals/{approval_id}/reject"), @@ -1075,7 +1079,8 @@ def _J(authority: str, reach: str) -> Ui: f"core.audit_channel_denied core.dual_role_control {_E}", ), "POST /ui/connections/{name}/flag": _J( - "POST /connections/{name}/flag", f"core.audit_channel_denied core.set_connection_flag {_E}" + "POST /connections/{name}/flag", + f"core.refuse_connection_flag core.set_connection_flag {_E}", ), "GET /ui/connections/purge-confirm": _J( "ADD GET /connections/quiesced;GET /auth/check/messages:purge", @@ -1518,9 +1523,9 @@ def test_every_seam_field_is_classified_as_the_app_holds(live: _Live) -> None: def test_the_seam_field_counts_are_the_measured_ones() -> None: """ADR 0215 slice 1 measured 86 fields, 66 of them a JSON route's endpoint by identity. ADR 0207 moved one endpoint to a core and added one endpoint and one core, and BACKLOG #5559 added - one core: 89 in all.""" + one core: 89 in all. BACKLOG #6638 moved one endpoint to a core and added one core: 90.""" counts = Counter(f.kind for f in _SEAM_FIELDS.values()) - assert counts == {"endpoint": 66, "core": 18, "shared": 2, "helper": 3}, counts + assert counts == {"endpoint": 65, "core": 20, "shared": 2, "helper": 3}, counts def test_every_ui_deps_field_is_classified() -> None: diff --git a/tests/test_object_scope_flag_and_alert_rules.py b/tests/test_object_scope_flag_and_alert_rules.py index 9aaca3ffb1..c13e6614fd 100644 --- a/tests/test_object_scope_flag_and_alert_rules.py +++ b/tests/test_object_scope_flag_and_alert_rules.py @@ -125,8 +125,8 @@ async def test_flag_direction_refusal_row_carries_its_marker( """BACKLOG #3378: a flag request refused for its direction can name an inbound inside the actor's own scope, which a wrong-engine-shard request does too. Its denial row carries ``flag_direction_not_inbound`` so the two are told apart. The control: an out-of-scope inbound - refused with the right direction carries no marker. A direction that is neither side is a 422 - with no denial row, before any scope check.""" + refused with the right direction carries no marker. A direction that is neither side is the + same audited 403, before any validation could answer 422 (BACKLOG #6638).""" service = await _service(toml_engine, admin_write_rate_limit=False) await _user(service, "own", Role.DEPLOYMENT, ["IB_TOML"]) async with httpx.AsyncClient( @@ -136,16 +136,73 @@ async def test_flag_direction_refusal_row_carries_its_marker( h = await _login(c, "own") assert (await _flag(c, toml_engine, h, "IB_TOML", "outbound"))[:2] == (403, _DENIED) assert (await _flag(c, toml_engine, h, "IB_NOPE", "inbound"))[:2] == (403, _DENIED) - status, _, audit = await _flag(c, toml_engine, h, "IB_TOML", "sideways") + assert (await _flag(c, toml_engine, h, "IB_TOML", "sideways"))[:2] == (403, _DENIED) + rows = await toml_engine.store.list_audit(actor="own", action="auth.channel_denied") + details = sorted( + (json.loads(row["detail"]) for row in rows), key=lambda d: json.dumps(d, sort_keys=True) + ) + marked = {"channel": "IB_TOML", "flag_direction_not_inbound": True} + assert details == [{"channel": "IB_NOPE"}, marked, marked], details + assert await toml_engine.store.list_connection_flags() == set() + + +async def _raw_flag( + c: httpx.AsyncClient, eng: Engine, h: dict[str, str], name: str, content: bytes +) -> tuple[int, list[tuple[str, str | None]]]: + """A flag request with a raw body, its status and the audit rows it wrote.""" + latest = await eng.store.list_audit(limit=1) + last_id = latest[0]["id"] if latest else 0 + r = await c.post( + f"/connections/{name}/flag", + headers={**h, "content-type": "application/json"}, + content=content, + ) + rows = [row for row in await eng.store.list_audit(limit=50) if row["id"] > last_id] + return r.status_code, [(row["action"], row["channel_id"]) for row in rows] + + +async def test_flag_scope_refusal_runs_before_request_validation( + toml_engine: Engine, # noqa: F811 +) -> None: + """BACKLOG #6638: a channel-scoped caller's malformed request is the audited 403, not an + unaudited 422. That covers a body that is not JSON, an empty one, a direction that is not a + string, a missing direction, and a name that fails the connection-name rule, whose row names no + channel. The control: an all-channels caller still gets the 422 for each, with no denial row, + and a scoped caller's well-formed request on its own inbound with a bad ``flagged`` is a 422, + since nothing there is refused.""" + service = await _service(toml_engine, admin_write_rate_limit=False) + await _user(service, "own", Role.DEPLOYMENT, ["IB_TOML"]) + await _user(service, "wide", Role.DEPLOYMENT, [ALL_CHANNELS]) + cases = [ + ("IB_TOML", b"{not json"), + ("IB_TOML", b""), + ("IB_TOML", b'{"direction": 7, "flagged": true}'), + ("IB_TOML", b'{"flagged": true}'), + ("IB_TOML", b"[]"), + ("IB-%20BAD", b'{"direction": "inbound", "flagged": true}'), + ] + async with httpx.AsyncClient( + transport=httpx.ASGITransport(app=create_app(toml_engine, auth=service)), + base_url="http://t", + ) as c: + h = await _login(c, "own") + for name, content in cases: + status, audit = await _raw_flag(c, toml_engine, h, name, content) + assert status == 403, (name, content) + assert [a for a in audit if a[0] == "auth.channel_denied"], (name, content, audit) + status, audit = await _raw_flag( + c, toml_engine, h, "IB_TOML", b'{"direction": "inbound", "flagged": "maybe"}' + ) assert status == 422 assert not [a for a in audit if a[0] == "auth.channel_denied"], audit + hw = await _login(c, "wide") + for name, content in cases: + status, audit = await _raw_flag(c, toml_engine, hw, name, content) + assert status == 422, (name, content) + assert not [a for a in audit if a[0] == "auth.channel_denied"], audit + # The malformed name's row names no channel (BACKLOG #3031). rows = await toml_engine.store.list_audit(actor="own", action="auth.channel_denied") - assert len(rows) == 2, rows - details = {row["channel_id"]: json.loads(row["detail"]) for row in rows} - assert details == { - "IB_TOML": {"channel": "IB_TOML", "flag_direction_not_inbound": True}, - "IB_NOPE": {"channel": "IB_NOPE"}, - } + assert sum(json.loads(row["detail"]).get("malformed_name") is True for row in rows) == 1 assert await toml_engine.store.list_connection_flags() == set() @@ -267,9 +324,12 @@ async def test_alert_rules_id_cannot_name_a_connection_outside_the_scope( async with httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url="http://t") as c: wide = await c.get("/alerts/rules", headers=await _login(c, "wide")) assert [r["id"] for r in wide.json()["rules"]] == ["page OB_SECRET on IB_A"] + # BACKLOG #6638: a null id says whether it was withheld or the rule has none. + assert [r["id_withheld"] for r in wide.json()["rules"]] == [False] scoped = await c.get("/alerts/rules", headers=await _login(c, "scoped")) assert scoped.status_code == 200, scoped.text assert [(r["id"], r["connection"]) for r in scoped.json()["rules"]] == [(None, "IB_A")] + assert [r["id_withheld"] for r in scoped.json()["rules"]] == [True] assert "OB_SECRET" not in scoped.text # The rule itself is shown, so nothing was withheld and no count row is written. assert await engine.store.list_audit(action="alert_rules_withheld") == [] diff --git a/tests/test_security_doc_drift.py b/tests/test_security_doc_drift.py index d98ce4b126..fa1cd934a3 100644 --- a/tests/test_security_doc_drift.py +++ b/tests/test_security_doc_drift.py @@ -357,6 +357,8 @@ "direction", "fault", "metadata", + # A boolean: whether a scoped reader's labels were withheld (BACKLOG #6638). + "metadata_withheld", "method", "name", "router", From ea37c8e48af1df9f06958a68e93b762ab1a78d1d Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 1 Dec 2026 23:06:44 -0600 Subject: [PATCH 2/8] SECURITY.md and both CHANGELOGs state the flag refusal order and the withheld ids and labels BACKLOG #6638 items 1 to 7, doc limb. - docs/SECURITY.md: the posture bullet no longer lists an alert rule's id as free text a scoped reader is shown; the flag paragraphs say both routes refuse a scoped caller before validating, and that a scoped reader's null rule id carries id_withheld. - CHANGELOG.md and the web console CHANGELOG record the change. The console's 0.5.3 BACKLOG #3378 entry read "the handshake will not catch an older engine", which understated the protection (item 7, the merge review's comment); it is corrected in place, naming the old text. BEHAVIOUR CHANGE (stated for the Lander's routing): a channel-scoped caller's malformed POST /connections/{name}/flag now answers 403 and is audited, where it answered an unaudited 422. Not changed: item 7's three other nits (an app.py comment scope, a restated docstring, SECURITY.md sentence order) name no line, and the text they pointed at has since been rewritten. Proposed PR title: Flag routes refuse a scoped caller before validating; scoped readers see no rule ids or labels (BACKLOG #6638) Proposed vault banner: BUILT on engine branch b20056-6638 (batch 20056 Builder F): items 1-6 fixed with tests; item 7 CHANGELOG line corrected, its three unlocated nits left; one behaviour change, a scoped caller's malformed flag request goes from an unaudited 422 to the audited 403. Verified-by: tests --- CHANGELOG.md | 12 +++++++++ docs/SECURITY.md | 25 +++++++++++-------- .../messagefoundry-webconsole/CHANGELOG.md | 16 +++++++++++- 3 files changed, 41 insertions(+), 12 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index dc7e9dd4c1..ceb6533c7a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,6 +12,18 @@ All notable changes to MessageFoundry are documented here. The format follows `LIN` or `PAT` in a 270), was kept in `X12SegmentError.segment_id` and `message`, as the 0.5.3 notes said. It is now `None`, shown as `?`, and `line` still locates it. Sender text the walk accepts as a segment at that point is still kept. (`BACKLOG #5370`) +- **A channel-scoped caller's malformed flag request is refused 403, and audited, before it is + validated.** `POST /connections/{name}/flag` answered such a caller's direction that names + neither side, a body that is not JSON, and a name that fails the connection-name rule with a 422 + and no `auth.channel_denied` row. It now answers each with the 403 and the row it gives any other + target outside the caller's scope. **This turns those 422s into 403s for such a caller.** An + all-channels caller still gets the 422. (`BACKLOG #6638`) +- **A channel-scoped reader sees no alert rule id or connection labels.** `GET /security/posture` + labels a credential-reminder-silencing alert rule by its position alone for such a reader, as + `GET /alerts/rules` shows it no id. `GET /connections/{name}/metadata` returns that reader no + `metadata` labels, with the new `metadata_withheld` true. Both are operator free text, which may + name a connection outside the reader's scope. `AlertRuleInfo` gained `id_withheld`, so a null id + no longer means both "unlabelled" and "withheld". (`BACKLOG #6638`) ## [0.5.3] — 2026-11-27 — Early Access diff --git a/docs/SECURITY.md b/docs/SECURITY.md index d04af36033..3f9a96ffe8 100644 --- a/docs/SECURITY.md +++ b/docs/SECURITY.md @@ -2532,8 +2532,8 @@ the same permission set on the same method reds CI until it is listed here. > A row naming an in-scope inbound has at least one more cause, on any deployment: a > flag request refused for its direction. Such a row's detail carries > `"flag_direction_not_inbound": true`, so a row without that marker was not refused for its -> direction (BACKLOG #3378). `POST /connections/{name}/flag` writes it for a direction of -> `outbound`, and the web console's flag route for any direction other than `inbound`. +> direction (BACKLOG #3378). Both flag routes write it for any direction other than `inbound`, +> a request that names none or a malformed one included (BACKLOG #6638). > With an engine bound but not started there is no graph and no name exists. Every route still > checks the scope first, so a name outside it gets the 403. A name inside it gets 503 from the > first three routes and 404 from the control routes, with no denial row. With no engine bound at @@ -2546,11 +2546,12 @@ the same permission set on the same method reds CI until it is listed here. > whole config, so unlike the routes above, an in-scope inbound that a sibling engine shard holds is > not refused by this one: the scope check does not refuse it, and `Engine.set_connection_flag` writes the flag > and its `connection_flag_set` row to the shared store. What that method refuses is in its -> docstring. The JSON -> route validates the body before any of this, so a direction other than `inbound` or `outbound` -> gets a 422 there with no denial row, scoped caller or not. The web console's twin reads the -> direction itself: for such a direction it gives a scoped caller the 403 and a denial row, and an -> all-channels caller 404 with no row (BACKLOG #3378). +> docstring. Both flag routes, the JSON route and the web console's twin, run this refusal on +> the request's raw name and direction before they validate either (BACKLOG #3378, #6638). So a +> scoped caller's malformed request, such as a body that is not JSON, a direction that names +> neither side, or a name that fails the connection-name rule, gets the 403 and a denial row, the +> last naming no channel. An all-channels caller gets the 422 for a malformed name or body, and on +> the console 404 for a direction that names neither side, with no row. > `GET /alerts/rules` shows a scoped caller > only the rules that name no connection outside its scope: `connection` is `*` or a name in its > scope, and `control_target` is unset or in it. Each name a rule carries must also be an inbound @@ -2573,7 +2574,8 @@ the same permission set on the same method reds CI until it is listed here. > purpose. The batch Manager decided this on 2026-11-22. It read the owner's ruling as covering > rules and flagging, not instances. What the ack, resolve, suspend and resume routes admit is in their bullet under > *Single-route data rules*, below. Each rule it shows has a null `id` -> (BACKLOG #3378). The id is the operator's free-text label, so whoever writes `[alerts]` can put any +> and `id_withheld: true`, labelled or not, so a null `id` there means "not shown" (BACKLOG #3378, +> #6638). The id is the operator's free-text label, so whoever writes `[alerts]` can put any > connection name in it, and nothing here reliably tells a label that names one from one that > does not. An > all-channels caller reads every id. A withheld id writes no audit row, since the rule itself is @@ -2735,9 +2737,10 @@ the same permission set on the same method reds CI until it is listed here. > own scope that the graph holds. That covers the loosenings, the static-credential hops and > their opt-outs, and the audit row. `loosenings_scope` and `static_credential_hops_scope` then > say the reading is narrowed, with or without a loaded graph. The audit row carries -> `loosenings_scope` too, and the console's status page shows it. The rest is shown whole. Some -> of it is operator free text, such as an alert rule's id or an attestation reason, which may -> name a connection. +> `loosenings_scope` too, and the console's status page shows it. An alert rule is labelled by +> its position alone, with no `id`, as `GET /alerts/rules` shows such a reader no `id` (BACKLOG +> #6638). The rest is shown whole. Some of it is operator free text, such as an attestation +> reason, which may name a connection. > - `GET /users` sends each account's `channel_scope` and `channel_scope_source` only to a > `users:manage` holder, the tier `GET /users/{user_id}/channel-scope` reads on. Everyone else > gets null for both and `channel_scope_withheld: true`, so a null there means "not shown". The diff --git a/packaging/messagefoundry-webconsole/CHANGELOG.md b/packaging/messagefoundry-webconsole/CHANGELOG.md index 75b69bf3df..7d7ca8c794 100644 --- a/packaging/messagefoundry-webconsole/CHANGELOG.md +++ b/packaging/messagefoundry-webconsole/CHANGELOG.md @@ -54,6 +54,18 @@ this line.** `api.security.is_account_read_refusal`, which replaces `account_read_errors`. A seam change. (`BACKLOG #5559`) +### Security + +- **A channel-scoped caller's bad flag name is the audited 403 too.** `POST + /ui/connections/{name}/flag` took its name as an annotated path parameter, so a name that failed + the connection-name rule answered 422 before the scope refusal and wrote no `auth.channel_denied` + row. The route now calls the engine's one flag refusal, `CoreHandlers.refuse_connection_flag`, on + the raw name and direction before it validates either, in place of the copy it carried. Such a + caller gets the 403 and a row naming no channel, marked `"malformed_name": true`. An all-channels + caller still gets the 422 for a bad name and the 404 for a bad direction. The console no longer + imports `CONNECTION_DENIED_DETAIL`. The new seam field moves the seam digest, so the handshake + refuses an engine without it. (BACKLOG #6638) + ## [0.5.3] — 2026-11-27 — Early Access **Requires engine 0.5.3. Supported engine UI seam: `2fdef0ec34ace13d`**, the value engine 0.5.3 @@ -321,7 +333,9 @@ it 0.6.0 before it was published; no console 0.6.0 was ever published. has `CONNECTION_DENIED_DETAIL` and whose `audit_channel_denied` takes `flag_direction_not_inbound`, engine 0.5.3 or later. As for BACKLOG #1624 above, this release's `messagefoundry>=0.5.3` floor requires them: the seam digest covers neither a module constant nor - that callback's signature, so the handshake will not catch an older engine. (BACKLOG #3378) + that callback's signature, so the handshake does not catch this skew by itself. It does refuse + every engine published before this release, whose seam digest differs for other reasons + (corrected under BACKLOG #6638; this read "will not catch an older engine"). (BACKLOG #3378) - **On a GET, the same-origin check reads `Origin` when `Sec-Fetch-Site` is empty or unknown.** Such a value now counts as absent there, so a foreign `Origin` beside it is refused. Before, any present value settled a GET and `Origin` was never read. A value an intermediary folded from two From 305d58188641440aefbd7e7fff896331d277ecfa Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 1 Dec 2026 23:50:28 -0600 Subject: [PATCH 3/8] Flag route keeps its declared name and body; the scope refusal runs as a dependency BACKLOG #6638, review round 1 repair (code). The first commit read the flag route's body by hand. The review found that this dropped FastAPI's strict JSON content-type check (an all-channels caller's text/plain body flagged a connection where main answered 422), took ConnectionFlagRequest out of the request-model census (test_api_request_models_forbid_extra failed), and charged the pacing gate before a malformed body's 422. The route is set_connection_flag again, with name: ConnectionName and req: ConnectionFlagRequest declared. The scope refusal runs in _flag_scope_gate, a dependency after the gate: FastAPI raises a path or body validation error only after the route's dependencies run, so a channel-scoped caller's bad direction, missing direction or bad name is still the audited 403. A body that is not JSON at all is refused by FastAPI before any dependency, so it stays an unaudited 422 for every caller; a test pins that. The gate and the handler share one require_paced object, so one admission and one pacing charge. Comments the review found false are corrected (_common.py's list of unannotated names, test_ui_input_rules.py's "the one name", the handler's reason for its second refusal). Verified-by: tests --- messagefoundry/api/app.py | 93 ++++++------------- messagefoundry_webconsole/routes/_common.py | 5 +- .../tests/test_ui_input_rules.py | 2 +- tests/test_console_seam_inventory.py | 18 ++-- .../test_object_scope_flag_and_alert_rules.py | 16 ++-- 5 files changed, 54 insertions(+), 80 deletions(-) diff --git a/messagefoundry/api/app.py b/messagefoundry/api/app.py index 2880fbd25d..8057ba65af 100644 --- a/messagefoundry/api/app.py +++ b/messagefoundry/api/app.py @@ -637,31 +637,6 @@ _CONNECTION_NAME_ADAPTER: TypeAdapter[str] = TypeAdapter(ConnectionName) -#: What :func:`_parse_json_body` returns for a body that is not JSON, and for an empty one. -_UNPARSEABLE: Final = object() -_EMPTY_BODY: Final = object() - -#: The request body ``POST /connections/{name}/flag`` reads itself (BACKLOG #6638), declared to -#: OpenAPI as FastAPI would have declared the model it used to take. -_FLAG_REQUEST_OPENAPI: Final[dict[str, Any]] = { - "requestBody": { - "required": True, - "content": {"application/json": {"schema": ConnectionFlagRequest.model_json_schema()}}, - } -} - - -def _parse_json_body(raw: bytes) -> object: - """``raw`` decoded as JSON, :data:`_EMPTY_BODY` when it is empty, or :data:`_UNPARSEABLE`. One - parse, so a route's scope check and its model read the same value (a duplicated key included). - A body over the size limit never reaches here (``_limit_request_body``).""" - if not raw: - return _EMPTY_BODY - try: - return json.loads(raw) - except (ValueError, RecursionError): - return _UNPARSEABLE - def _valid_connection_name(value: str) -> bool: """Whether ``value`` passes the ``ConnectionName`` rule the ``reveal`` query is validated by. @@ -6813,52 +6788,42 @@ async def _refuse_connection_flag( flag_direction_not_inbound=wrong_direction, ) - @app.post("/connections/{name}/flag", openapi_extra=_FLAG_REQUEST_OPENAPI) - async def connection_flag_route( - # Not annotated, and the body is read here rather than declared: FastAPI validates both - # before the handler runs, so a channel-scoped caller's malformed name or body answered 422 - # with no denial row (BACKLOG #6638). The scope refusal runs first; the name rule and the - # body model then answer the 422 they answered before. - name: str, + # One dependency object, so the scope gate below and the handler share one admission and one + # pacing charge: FastAPI runs a dependency once per request, keyed by the callable. + flag_caller = require_paced(Permission.CONFIG_DEPLOY) + + async def _flag_scope_gate( request: Request, engine: Engine = Depends(_get_engine), - identity: Identity = Depends(require_paced(Permission.CONFIG_DEPLOY)), - ) -> dict[str, object]: - """``POST /connections/{name}/flag``: the scope refusal, then the request's validation, - then :func:`set_connection_flag`, which says what the toggle does.""" - body = _parse_json_body(await request.body()) - direction = body.get("direction") if isinstance(body, dict) else None - await _refuse_connection_flag(engine, identity, name, direction, client_ip(request)) - errors: list[Any] = [] + identity: Identity = Depends(flag_caller), + ) -> None: + """Run :func:`_refuse_connection_flag` on the request's raw name and direction (BACKLOG + #6638). FastAPI raises a path or body validation error only after a route's dependencies + have run, so a channel-scoped caller's malformed name or direction is the audited 403 here, + not the 422. A body that is not JSON at all is refused before any dependency runs, so that + one is still a 422. This only ever refuses; validation follows for anything it lets by.""" + if identity.allowed_channels is None: + return try: - _CONNECTION_NAME_ADAPTER.validate_python(name) - except ValidationError as exc: - errors += [ - {**err, "loc": ("path", "name", *err["loc"])} - for err in exc.errors(include_url=False) - ] - req: ConnectionFlagRequest | None = None - if body is _EMPTY_BODY: - errors.append({"type": "missing", "loc": ("body",), "msg": "Field required"}) - elif body is _UNPARSEABLE: - errors.append({"type": "json_invalid", "loc": ("body",), "msg": "JSON decode error"}) - else: - try: - req = ConnectionFlagRequest.model_validate(body) - except ValidationError as exc: - errors += [ - {**err, "loc": ("body", *err["loc"])} for err in exc.errors(include_url=False) - ] - if errors or req is None: - raise RequestValidationError(errors) - return await set_connection_flag(name, req, request, engine=engine, identity=identity) + body = await request.json() + except (ValueError, RecursionError): + body = None + direction = body.get("direction") if isinstance(body, dict) else None + await _refuse_connection_flag( + engine, identity, request.path_params.get("name", ""), direction, client_ip(request) + ) + @app.post("/connections/{name}/flag") async def set_connection_flag( name: ConnectionName, req: ConnectionFlagRequest, request: Request, engine: Engine = Depends(_get_engine), - identity: Identity = Depends(require_paced(Permission.CONFIG_DEPLOY)), + identity: Identity = Depends(flag_caller), + # After the gate, so it runs once the caller is admitted, and still before FastAPI raises + # the name's or the body's validation error (BACKLOG #6638). Unused on a direct call: the + # console runs core.refuse_connection_flag itself. + _scope_gate: None = Depends(_flag_scope_gate), ) -> dict[str, object]: """Set the object-of-interest flag on a connection in the running graph (#131, BACKLOG #2623). The store holds the flag, so a toggle runs no config module and writes no file, and @@ -6890,7 +6855,9 @@ async def set_connection_flag( graph loaded, where this route lets an in-scope name reach the engine and that one withholds every rule naming a connection, and on a name the runner also knows as an outbound, which that one withholds and this one admits for ``direction=inbound``.""" - # Again here, though the JSON route ran it already: the console calls this handler directly. + # Again here, though the JSON route's gate and the console's flag route each ran it first: + # defence in depth for any other caller of this handler, which takes the name and the + # direction already validated. await _refuse_connection_flag(engine, identity, name, req.direction, client_ip(request)) try: await engine.set_connection_flag( diff --git a/messagefoundry_webconsole/routes/_common.py b/messagefoundry_webconsole/routes/_common.py index 4eeedda3f6..09b7736332 100644 --- a/messagefoundry_webconsole/routes/_common.py +++ b/messagefoundry_webconsole/routes/_common.py @@ -116,7 +116,10 @@ class FilterRule(NamedTuple): #: makes FastAPI answer a bare 422 and discard the submission; these answer 400 and re-render the #: form carrying what the operator typed. The /ui routes whose values the console itself mints -- #: ``/ui/dead-letters``, the per-name controls, the purge pages -- are annotated instead, and so are -#: absent here. +#: absent here. At least two are left unannotated, so a channel-scoped caller's bad value reaches +#: the audited scope refusal: the purge confirm page's ``dest`` and the flag route's ``name``, which +#: that route checks against ``CONNECTION_RULE`` in its body (BACKLOG #6638). Neither is listed here, +#: since neither re-renders a form, so the input-rule golden shows no rule for either. UI_BODY_FILTER_RULES: Final[dict[str, dict[str, FilterRule]]] = { # Keyed as ``pages.messages`` / ``pages.message_search`` / ``pages.events`` key their echo # keywords, so the dict a route checks IS the dict it renders back. diff --git a/packaging/messagefoundry-webconsole/tests/test_ui_input_rules.py b/packaging/messagefoundry-webconsole/tests/test_ui_input_rules.py index 03e681931a..76b8624589 100644 --- a/packaging/messagefoundry-webconsole/tests/test_ui_input_rules.py +++ b/packaging/messagefoundry-webconsole/tests/test_ui_input_rules.py @@ -305,7 +305,7 @@ async def test_dead_letter_replay_reaches_the_handler_for_a_valid_name( async def test_purge_confirm_never_arms_a_name_no_outbound_has(admin: httpx.AsyncClient) -> None: - """``dest`` is the one name on this surface left unannotated, so this is what guards it instead. + """``dest`` is left unannotated, as the flag route's ``name`` is, so this is what guards it. The handler intersects the requested ``dest`` with ``rr.outbound_quiesced(d)``, which admits only live outbound names -- strictly narrower than the connection-name rule, so nothing is lost. The diff --git a/tests/test_console_seam_inventory.py b/tests/test_console_seam_inventory.py index e30cc6cad9..a5daf4a8ae 100644 --- a/tests/test_console_seam_inventory.py +++ b/tests/test_console_seam_inventory.py @@ -425,10 +425,10 @@ def _core(*ops: str) -> Field: return Field("core", ops) -#: Every ``CoreHandlers`` and ``AdminHandlers`` field. 65 endpoints by identity, as ADR 0215 -#: slice 1 measured (ADR 0207 moved one to a core and added one of each; BACKLOG #6638 moved -#: ``core.set_connection_flag`` to a core), 20 cores a JSON route runs past its gate (BACKLOG #5559 -#: added ``admin.checked_user``, #6638 ``core.refuse_connection_flag``), 2 sharing a helper with a JSON +#: Every ``CoreHandlers`` and ``AdminHandlers`` field. 66 endpoints by identity, as ADR 0215 +#: slice 1 measured (ADR 0207 moved one to a core and added one of each), 19 cores a JSON route runs +#: past its gate (BACKLOG #5559 added ``admin.checked_user``, #6638 ``core.refuse_connection_flag``), +#: 2 sharing a helper with a JSON #: route, and 3 with no JSON route that carries the console's use. _SEAM_FIELDS: dict[str, Field] = { "core.list_connections": _endpoint("GET /connections"), @@ -496,9 +496,9 @@ def _core(*ops: str) -> Field: "core.layered_search": _endpoint("GET /search/layered"), "core.metrics_history": _endpoint("GET /metrics/history"), "core.graph_edges": _endpoint("GET /graph/edges"), - # BACKLOG #6638: the JSON route runs the scope refusal, then validates, then this core. - "core.set_connection_flag": _core("POST /connections/{name}/flag"), - # The flag routes' one scope refusal, which the JSON route runs before it validates. + "core.set_connection_flag": _endpoint("POST /connections/{name}/flag"), + # The flag routes' one scope refusal (BACKLOG #6638), which the JSON route runs in a dependency + # before its validation errors are raised, and again in its handler. "core.refuse_connection_flag": _core("POST /connections/{name}/flag"), "core.list_approvals": _endpoint("GET /approvals"), "core.approve_action": _endpoint("POST /approvals/{approval_id}/approve"), @@ -1523,9 +1523,9 @@ def test_every_seam_field_is_classified_as_the_app_holds(live: _Live) -> None: def test_the_seam_field_counts_are_the_measured_ones() -> None: """ADR 0215 slice 1 measured 86 fields, 66 of them a JSON route's endpoint by identity. ADR 0207 moved one endpoint to a core and added one endpoint and one core, and BACKLOG #5559 added - one core: 89 in all. BACKLOG #6638 moved one endpoint to a core and added one core: 90.""" + one core: 89 in all. BACKLOG #6638 added one core: 90.""" counts = Counter(f.kind for f in _SEAM_FIELDS.values()) - assert counts == {"endpoint": 65, "core": 20, "shared": 2, "helper": 3}, counts + assert counts == {"endpoint": 66, "core": 19, "shared": 2, "helper": 3}, counts def test_every_ui_deps_field_is_classified() -> None: diff --git a/tests/test_object_scope_flag_and_alert_rules.py b/tests/test_object_scope_flag_and_alert_rules.py index c13e6614fd..e0213c0d63 100644 --- a/tests/test_object_scope_flag_and_alert_rules.py +++ b/tests/test_object_scope_flag_and_alert_rules.py @@ -165,16 +165,17 @@ async def test_flag_scope_refusal_runs_before_request_validation( toml_engine: Engine, # noqa: F811 ) -> None: """BACKLOG #6638: a channel-scoped caller's malformed request is the audited 403, not an - unaudited 422. That covers a body that is not JSON, an empty one, a direction that is not a - string, a missing direction, and a name that fails the connection-name rule, whose row names no - channel. The control: an all-channels caller still gets the 422 for each, with no denial row, - and a scoped caller's well-formed request on its own inbound with a bad ``flagged`` is a 422, - since nothing there is refused.""" + unaudited 422. That covers an empty body, a body that is not an object, a direction that is not + a string, a missing direction, and a name that fails the connection-name rule, whose row names + no channel. The control: an all-channels caller still gets the 422 for each, with no denial + row, and a scoped caller's well-formed request on its own inbound with a bad ``flagged`` is a + 422, since nothing there is refused. A body that is not JSON at all is refused by FastAPI + before any dependency runs, so it stays an unaudited 422 for every caller; pinned here so a + change to that is seen.""" service = await _service(toml_engine, admin_write_rate_limit=False) await _user(service, "own", Role.DEPLOYMENT, ["IB_TOML"]) await _user(service, "wide", Role.DEPLOYMENT, [ALL_CHANNELS]) cases = [ - ("IB_TOML", b"{not json"), ("IB_TOML", b""), ("IB_TOML", b'{"direction": 7, "flagged": true}'), ("IB_TOML", b'{"flagged": true}'), @@ -195,6 +196,9 @@ async def test_flag_scope_refusal_runs_before_request_validation( ) assert status == 422 assert not [a for a in audit if a[0] == "auth.channel_denied"], audit + status, audit = await _raw_flag(c, toml_engine, h, "IB_NOPE", b"{not json") + assert status == 422 + assert not [a for a in audit if a[0] == "auth.channel_denied"], audit hw = await _login(c, "wide") for name, content in cases: status, audit = await _raw_flag(c, toml_engine, hw, name, content) From cfe183d031c814fee2ea32b0832de0c2f8809766 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 1 Dec 2026 23:51:41 -0600 Subject: [PATCH 4/8] SECURITY.md states the metadata rule; flag-refusal text names the non-JSON residual BACKLOG #6638, review round 1 repair (docs). - docs/SECURITY.md: the GET /connections/{name}/metadata row states that a channel-scoped reader gets no metadata labels and metadata_withheld true (the review found the rule stated only in a model comment). - docs/SECURITY.md and CHANGELOG.md: the flag paragraphs no longer list a body that is not JSON among the scoped refusals; such a body is still an unaudited 422 for every caller, and both say so. BEHAVIOUR CHANGE (stated for the Lander's routing): a channel-scoped caller's POST /connections/{name}/flag with a direction naming neither side or missing, or a name failing the connection-name rule, now answers the audited 403 where it answered an unaudited 422. Proposed PR title: Flag routes refuse a scoped caller before validating; scoped readers see no rule ids or labels (BACKLOG #6638) Proposed vault banner: BUILT on engine branch b20056-6638 (batch 20056 Builder F): items 1-6 fixed with tests; item 7's CHANGELOG line corrected, its three unlocated nits left; one behaviour change, a scoped caller's malformed flag request goes from an unaudited 422 to the audited 403 (a body that is not JSON stays an unaudited 422). Verified-by: none --- CHANGELOG.md | 9 +++++---- docs/SECURITY.md | 12 +++++++----- 2 files changed, 12 insertions(+), 9 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index ceb6533c7a..3faecb1359 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -14,10 +14,11 @@ All notable changes to MessageFoundry are documented here. The format follows accepts as a segment at that point is still kept. (`BACKLOG #5370`) - **A channel-scoped caller's malformed flag request is refused 403, and audited, before it is validated.** `POST /connections/{name}/flag` answered such a caller's direction that names - neither side, a body that is not JSON, and a name that fails the connection-name rule with a 422 - and no `auth.channel_denied` row. It now answers each with the 403 and the row it gives any other - target outside the caller's scope. **This turns those 422s into 403s for such a caller.** An - all-channels caller still gets the 422. (`BACKLOG #6638`) + neither side or is missing, and a name that fails the connection-name rule, with a 422 and no + `auth.channel_denied` row. It now answers each with the 403 and the row it gives any other + target outside the caller's scope. **This turns those 422s into 403s for such a caller.** A JSON + body that does not parse is still a 422 with no row. An all-channels caller still gets the 422. + (`BACKLOG #6638`) - **A channel-scoped reader sees no alert rule id or connection labels.** `GET /security/posture` labels a credential-reminder-silencing alert rule by its position alone for such a reader, as `GET /alerts/rules` shows it no id. `GET /connections/{name}/metadata` returns that reader no diff --git a/docs/SECURITY.md b/docs/SECURITY.md index 3f9a96ffe8..6575123c76 100644 --- a/docs/SECURITY.md +++ b/docs/SECURITY.md @@ -1879,7 +1879,7 @@ exempt like any other, and the save re-seals the row as it always has. | `GET` | `/security/posture` | `monitoring:read` | `require` | | `GET` | `/channels` | `monitoring:read` | `require` | | `GET` | `/connections` | `monitoring:read` | `require_monitoring_read` — `error` gated on `messages:view_summary` and masked; the `reveal=` act also needs `messages:view_summary` (BACKLOG #2443) | -| `GET` | `/connections/{name}/metadata` | `monitoring:read` | `require` — per-channel for inbound; a shared outbound is barred to scoped users; credentials scrubbed unconditionally; `error` gated on `messages:view_summary` and masked; the `reveal=true` act also needs `messages:view_summary` (BACKLOG #2443) | +| `GET` | `/connections/{name}/metadata` | `monitoring:read` | `require` — per-channel for inbound; a shared outbound is barred to scoped users; a channel-scoped reader gets no `metadata` labels, which are operator free text that may name another connection, and `metadata_withheld: true`, so a null `metadata` there means "not shown" (BACKLOG #6638); credentials scrubbed unconditionally; `error` gated on `messages:view_summary` and masked; the `reveal=true` act also needs `messages:view_summary` (BACKLOG #2443) | | `GET` | `/events` | `monitoring:read` | `require` — data rule: *Single-route data rules* below (BACKLOG #1151) | | `GET` | `/connections/{name}/events` | `monitoring:read` | `require` | | `GET` | `/stats` | `monitoring:read` | `require_monitoring_read` | @@ -2548,10 +2548,12 @@ the same permission set on the same method reds CI until it is listed here. > and its `connection_flag_set` row to the shared store. What that method refuses is in its > docstring. Both flag routes, the JSON route and the web console's twin, run this refusal on > the request's raw name and direction before they validate either (BACKLOG #3378, #6638). So a -> scoped caller's malformed request, such as a body that is not JSON, a direction that names -> neither side, or a name that fails the connection-name rule, gets the 403 and a denial row, the -> last naming no channel. An all-channels caller gets the 422 for a malformed name or body, and on -> the console 404 for a direction that names neither side, with no row. +> scoped caller's malformed request, such as a direction that names neither side or is missing, +> or a name that fails the connection-name rule, gets the 403 and a denial row, the last naming +> no channel. A JSON body that does not parse is still a 422 with no row, for every caller: the +> framework refuses it before the JSON route's refusal runs. An all-channels caller gets the 422 +> for a malformed name or body, and on the console 404 for a direction that names neither side, +> with no row. > `GET /alerts/rules` shows a scoped caller > only the rules that name no connection outside its scope: `connection` is `*` or a name in its > scope, and `control_target` is unset or in it. Each name a rule carries must also be an inbound From e020169dbbae5f0d6cc30d8de69a433fb228d2a4 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Wed, 2 Dec 2026 00:29:28 -0600 Subject: [PATCH 5/8] Flag scope gate reads only a body sent as JSON; the tests pin the direction marker BACKLOG #6638, review round 2 repair (code). - _flag_scope_gate reads the direction only from a non-empty body sent as JSON, FastAPI's own test, so it reads FastAPI's cached parse and never parses a body FastAPI would not. A body sent as another type names no direction, so a scoped caller is refused; an all-channels caller still gets FastAPI's 422. A test pins both. - The test checks each denial row's detail: the marker on the four bad bodies, the malformed-name row naming no channel. - ui_purge_confirm's comment no longer calls dest the only unannotated name. Verified-by: tests --- messagefoundry/api/app.py | 17 +++++++++++----- .../routes/connection_writes.py | 3 ++- .../test_object_scope_flag_and_alert_rules.py | 20 +++++++++++++++++-- 3 files changed, 32 insertions(+), 8 deletions(-) diff --git a/messagefoundry/api/app.py b/messagefoundry/api/app.py index 8057ba65af..898c322af6 100644 --- a/messagefoundry/api/app.py +++ b/messagefoundry/api/app.py @@ -6800,14 +6800,21 @@ async def _flag_scope_gate( """Run :func:`_refuse_connection_flag` on the request's raw name and direction (BACKLOG #6638). FastAPI raises a path or body validation error only after a route's dependencies have run, so a channel-scoped caller's malformed name or direction is the audited 403 here, - not the 422. A body that is not JSON at all is refused before any dependency runs, so that - one is still a 422. This only ever refuses; validation follows for anything it lets by.""" + not the 422. A body sent as JSON that does not parse is refused by FastAPI before any + dependency runs, so that one is still a 422 with no row. A body not sent as JSON is not + parsed there or here: it names no direction, so this refuses it. This only ever refuses; + validation follows for anything it lets by.""" if identity.allowed_channels is None: return - try: + body: object = None + # FastAPI's own test for a JSON body, so a body it would not parse is not parsed here. + media = request.headers.get("content-type", "").split(";")[0].strip().lower() + is_json = media == "application/json" or ( + media.startswith("application/") and media.endswith("+json") + ) + if is_json and await request.body(): + # FastAPI parsed a non-empty JSON body already, so this reads its cached result. body = await request.json() - except (ValueError, RecursionError): - body = None direction = body.get("direction") if isinstance(body, dict) else None await _refuse_connection_flag( engine, identity, request.path_params.get("name", ""), direction, client_ip(request) diff --git a/messagefoundry_webconsole/routes/connection_writes.py b/messagefoundry_webconsole/routes/connection_writes.py index 2cc91a515d..3c7f24f24c 100644 --- a/messagefoundry_webconsole/routes/connection_writes.py +++ b/messagefoundry_webconsole/routes/connection_writes.py @@ -271,7 +271,8 @@ async def ui_purge_confirm( reauth_next=_purge_confirm_continuation, ) ), - # NOT annotated, unlike every other name on this surface, and the reason is an audit + # NOT annotated, like the flag route's name and unlike the other names on this surface, + # and the reason is an audit # row. FastAPI validates a query parameter before the handler body, so a 422 here would # return BEFORE the channel-scope branch below that calls core.audit_channel_denied -- # measured: a channel-scoped operator sending a malformed dest got 422 and zero audit rows, diff --git a/tests/test_object_scope_flag_and_alert_rules.py b/tests/test_object_scope_flag_and_alert_rules.py index e0213c0d63..1c4d672917 100644 --- a/tests/test_object_scope_flag_and_alert_rules.py +++ b/tests/test_object_scope_flag_and_alert_rules.py @@ -199,14 +199,30 @@ async def test_flag_scope_refusal_runs_before_request_validation( status, audit = await _raw_flag(c, toml_engine, h, "IB_NOPE", b"{not json") assert status == 422 assert not [a for a in audit if a[0] == "auth.channel_denied"], audit + # A body not sent as JSON is not parsed, so it names no direction: refused for a scoped + # caller, and the framework's 422 for an all-channels one. + good = b'{"direction": "inbound", "flagged": true}' + plain = {"content-type": "text/plain"} + r = await c.post("/connections/IB_TOML/flag", headers={**h, **plain}, content=good) + assert r.status_code == 403, r.text hw = await _login(c, "wide") + r = await c.post("/connections/IB_TOML/flag", headers={**hw, **plain}, content=good) + assert r.status_code == 422, r.text for name, content in cases: status, audit = await _raw_flag(c, toml_engine, hw, name, content) assert status == 422, (name, content) assert not [a for a in audit if a[0] == "auth.channel_denied"], audit - # The malformed name's row names no channel (BACKLOG #3031). + # The malformed name's row names no channel (BACKLOG #3031), and its direction is inbound, + # so it carries no direction marker. The four bad bodies and the text/plain one name no + # inbound direction, so each of those rows carries the marker. rows = await toml_engine.store.list_audit(actor="own", action="auth.channel_denied") - assert sum(json.loads(row["detail"]).get("malformed_name") is True for row in rows) == 1 + details = [json.loads(row["detail"]) for row in rows] + assert len(details) == 6, details + assert [d for d in details if d.get("malformed_name") is True] == [ + {"channel": None, "malformed_name": True} + ], details + marked = {"channel": "IB_TOML", "flag_direction_not_inbound": True} + assert details.count(marked) == 5, details assert await toml_engine.store.list_connection_flags() == set() From c3151dfc03a6544422737f058b00600140618021 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Wed, 2 Dec 2026 00:30:27 -0600 Subject: [PATCH 6/8] Docs say which flag faults are refused first, and that scoped readers get no metadata labels BACKLOG #6638, review round 2 repair (docs). - docs/SECURITY.md: the flag paragraph says only the name and direction are read first, so other faults stay a 422, and how a body not sent as JSON is handled; the console's rule-check sentence names the flag route as the exception, where record_channel_denied is the only bound. - docs/CONNECTIONS.md: GET /connections/{name}/metadata gives a channel-scoped user no metadata labels. - CHANGELOG.md: the same narrowing of the flag entry. BEHAVIOUR CHANGE (stated for the Lander's routing): a channel-scoped caller's POST /connections/{name}/flag whose direction names neither side or is missing, or whose name fails the connection-name rule, now answers the audited 403 where it answered an unaudited 422. Proposed PR title: Flag routes refuse a scoped caller before validating; scoped readers see no rule ids or labels (BACKLOG #6638) Proposed vault banner: BUILT on engine branch b20056-6638 (batch 20056 Builder F): items 1-6 fixed with tests; item 7's CHANGELOG line corrected, its three unlocated nits left; one behaviour change, a scoped caller's malformed flag name or direction goes from an unaudited 422 to the audited 403. Residuals filed in the report: other per-name routes keep the unaudited 422; posture still lists a withheld silencing rule by position. Verified-by: tests --- CHANGELOG.md | 5 +++-- docs/CONNECTIONS.md | 4 +++- docs/SECURITY.md | 20 +++++++++++++------- 3 files changed, 19 insertions(+), 10 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 3faecb1359..95507a47bf 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -16,8 +16,9 @@ All notable changes to MessageFoundry are documented here. The format follows validated.** `POST /connections/{name}/flag` answered such a caller's direction that names neither side or is missing, and a name that fails the connection-name rule, with a 422 and no `auth.channel_denied` row. It now answers each with the 403 and the row it gives any other - target outside the caller's scope. **This turns those 422s into 403s for such a caller.** A JSON - body that does not parse is still a 422 with no row. An all-channels caller still gets the 422. + target outside the caller's scope. **This turns those 422s into 403s for such a caller.** A body + sent as JSON that does not parse is still a 422 with no row, as is any other fault in a request + whose name and direction pass. An all-channels caller still gets the 422. (`BACKLOG #6638`) - **A channel-scoped reader sees no alert rule id or connection labels.** `GET /security/posture` labels a credential-reminder-silencing alert rule by its position alone for such a reader, as diff --git a/docs/CONNECTIONS.md b/docs/CONNECTIONS.md index c6e2f540d7..3570211c1a 100644 --- a/docs/CONNECTIONS.md +++ b/docs/CONNECTIONS.md @@ -659,7 +659,9 @@ Two read/diagnostic endpoints back the console's connection view (auth + per-cha - **`GET /connections/{name}/metadata`** (`monitoring:read`) — the connector type, the operator `metadata` labels, running state, and a **secret-scrubbed** settings view (`env()` refs show as `{"env": key}` and are never resolved; credential fields render as `"***"`). Inbound is per-channel; - a shared outbound is barred to channel-scoped users. + a shared outbound is barred to channel-scoped users. A channel-scoped user gets no `metadata` + labels, since they are free text that may name another connection, and `metadata_withheld: true` + (BACKLOG #6638), so put a runbook such a user needs somewhere it can read. - **`POST /connections/{name}/test`** (`connections:test`) — a **reachability probe** that builds a *fresh* connector (never the live one), honors the `[egress]` allowlist fail-closed, and **sends no real message** — a socket connect (MLLP/TCP/X12), `SELECT 1` (Database), an HTTP `HEAD` (REST/SOAP), diff --git a/docs/SECURITY.md b/docs/SECURITY.md index 6575123c76..3d562795a0 100644 --- a/docs/SECURITY.md +++ b/docs/SECURITY.md @@ -2488,7 +2488,9 @@ the same permission set on the same method reds CI until it is listed here. > `auth.gate_refused` and `auth.mfa_denied`). An admitted caller's grant row is written under the > shipped default of `[security].audit_all_authorization_decisions`; with that switch off it is > written on the POST routes, whose permissions are in the sensitive set, and not on the GET routes. -> The console checks the rule before it calls in. `record_channel_denied` +> The console checks the rule before it calls in, except on its flag route, which hands a +> channel-scoped caller's raw name to `refuse_connection_flag` first so the refusal is audited +> (BACKLOG #6638); there the bound below is the only one. `record_channel_denied` > in `messagefoundry/api/message_scope.py`, which writes every `auth.channel_denied` row the API and > the console seam record (`audit_channel_denied` and `refuse_a_channel_scoped_reader` call it), checks the name it is given against the rule too, and records a name > that fails it as no channel, so `audit_log.channel_id` never holds a caller-chosen string of @@ -2548,12 +2550,16 @@ the same permission set on the same method reds CI until it is listed here. > and its `connection_flag_set` row to the shared store. What that method refuses is in its > docstring. Both flag routes, the JSON route and the web console's twin, run this refusal on > the request's raw name and direction before they validate either (BACKLOG #3378, #6638). So a -> scoped caller's malformed request, such as a direction that names neither side or is missing, -> or a name that fails the connection-name rule, gets the 403 and a denial row, the last naming -> no channel. A JSON body that does not parse is still a 422 with no row, for every caller: the -> framework refuses it before the JSON route's refusal runs. An all-channels caller gets the 422 -> for a malformed name or body, and on the console 404 for a direction that names neither side, -> with no row. +> scoped caller whose direction names neither side or is missing, or whose name fails the +> connection-name rule, gets the 403 and a denial row marked `"flag_direction_not_inbound": true` +> for the direction, the row naming no channel for a bad name. Only the name and the direction +> are read first: a scoped caller's request on its own inbound with any other fault, such as a +> `flagged` that is not a boolean or an unknown key, is still a 422 with no row. So is a body +> sent as JSON (`application/json` or `+json`) that does not parse, for every caller, since the +> framework refuses it before the JSON route's refusal runs; a body sent as any other type names +> no direction to a scoped caller, so it is refused. An all-channels caller gets the 422 for a +> malformed name or body, and on the console 404 for a direction that names neither side, with no +> row. > `GET /alerts/rules` shows a scoped caller > only the rules that name no connection outside its scope: `connection` is `*` or a name in its > scope, and `control_target` is unset or in it. Each name a rule carries must also be an inbound From 8d38a8b09cf38cf08336721d0297534e3519a3b7 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Wed, 2 Dec 2026 01:39:50 -0600 Subject: [PATCH 7/8] Flag scope gate reads JSON by FastAPI's test and never 500s; scoped readers get no reply_from BACKLOG #6638 repair round. - _flag_scope_gate decides whether a body is JSON with FastAPI's own test (email.message parse, application/json or a +json subtype), and catches a decode failure, so a scoped caller's application/x/y+json body that does not parse is the audited 403, not a 500 with no row. - A body not read as JSON is still refused for a scoped caller, but its row no longer carries flag_direction_not_inbound, since its direction was never read (_refuse_connection_flag gains direction_read). - GET /connections/{name}/metadata gives a channel-scoped reader an inbound's settings.reply_from as null, with the new ConnectionMetadata.reply_from_withheld true; an all-channels reader still reads it. The route's docstring says what such a reader gets. - Tests: the +json and text/plain cases and their row markers, and the reply_from withholding with an all-channels control. Verified-by: tests --- messagefoundry/api/app.py | 79 ++++++++++++++----- messagefoundry/api/models.py | 4 + ...test_channel_scope_posture_users_reload.py | 31 ++++++++ .../test_object_scope_flag_and_alert_rules.py | 23 ++++-- tests/test_security_doc_drift.py | 2 + 5 files changed, 114 insertions(+), 25 deletions(-) diff --git a/messagefoundry/api/app.py b/messagefoundry/api/app.py index 898c322af6..c5ef996fc1 100644 --- a/messagefoundry/api/app.py +++ b/messagefoundry/api/app.py @@ -37,6 +37,7 @@ import asyncio import base64 import binascii +import email.message import json import logging import os @@ -6759,7 +6760,13 @@ async def restart_connection( ) async def _refuse_connection_flag( - engine: Engine, identity: Identity, name: str, direction: object, client: str | None + engine: Engine, + identity: Identity, + name: str, + direction: object, + client: str | None, + *, + direction_read: bool = True, ) -> None: """The flag routes' one scope refusal: :func:`_deny_connection` for a channel-scoped caller's target it may not flag, and nothing for any other caller (BACKLOG #1152, #3378). @@ -6767,7 +6774,10 @@ async def _refuse_connection_flag( ``direction`` is whatever the request carried, unvalidated, so a caller's direction that names neither side is refused here, audited, before any validation can answer 422 (BACKLOG #6638). The JSON route and the web console's flag route both call this, the console across - the seam, so the refusal is written once.""" + the seam, so the refusal is written once. ``direction_read`` is false when the request's + body was not read as JSON, so its direction is unknown: the request is still refused, but + its row carries no ``flag_direction_not_inbound`` marker, since it may have asked for + ``inbound`` (BACKLOG #6638).""" if identity.allowed_channels is None: return rr = engine.registry_runner @@ -6784,8 +6794,9 @@ async def _refuse_connection_flag( identity, name, client, - # The row's marker, for a row that names an in-scope inbound (BACKLOG #3378). - flag_direction_not_inbound=wrong_direction, + # The row's marker, for a row that names an in-scope inbound (BACKLOG #3378), set + # only for a direction actually read (BACKLOG #6638). + flag_direction_not_inbound=wrong_direction and direction_read, ) # One dependency object, so the scope gate below and the handler share one admission and one @@ -6800,24 +6811,45 @@ async def _flag_scope_gate( """Run :func:`_refuse_connection_flag` on the request's raw name and direction (BACKLOG #6638). FastAPI raises a path or body validation error only after a route's dependencies have run, so a channel-scoped caller's malformed name or direction is the audited 403 here, - not the 422. A body sent as JSON that does not parse is refused by FastAPI before any - dependency runs, so that one is still a 422 with no row. A body not sent as JSON is not - parsed there or here: it names no direction, so this refuses it. This only ever refuses; - validation follows for anything it lets by.""" + not the 422. A body whose Content-Type FastAPI reads as JSON and that does not parse is + refused by FastAPI before any dependency runs, so that one is still a 422 with no row. A + body of any other type is not parsed there or here: its direction is unknown, so this + refuses it, with a row that carries no direction marker. A parse failure here is caught the + same way, so this never answers 500. This only ever refuses; validation follows for + anything it lets by.""" if identity.allowed_channels is None: return body: object = None - # FastAPI's own test for a JSON body, so a body it would not parse is not parsed here. - media = request.headers.get("content-type", "").split(";")[0].strip().lower() - is_json = media == "application/json" or ( - media.startswith("application/") and media.endswith("+json") - ) - if is_json and await request.body(): - # FastAPI parsed a non-empty JSON body already, so this reads its cached result. - body = await request.json() + read = False + body_bytes = await request.body() + content_type = request.headers.get("content-type") + if body_bytes and content_type: + # FastAPI's own test for a JSON body (fastapi.routing, strict content type), so a body + # it would not parse is not parsed here. + message = email.message.Message() + message["content-type"] = content_type + subtype = message.get_content_subtype() + if message.get_content_maintype() == "application" and ( + subtype == "json" or subtype.endswith("+json") + ): + try: + body = json.loads(body_bytes) + read = True + except ValueError: + # JSONDecodeError and UnicodeDecodeError: FastAPI answers such a body 422 + # before this runs, so this is defence in depth, and it refuses, never 500s. + body = None + elif not body_bytes: + # No body names no direction, as a JSON body without one does. + read = True direction = body.get("direction") if isinstance(body, dict) else None await _refuse_connection_flag( - engine, identity, request.path_params.get("name", ""), direction, client_ip(request) + engine, + identity, + request.path_params.get("name", ""), + direction, + client_ip(request), + direction_read=read, ) @app.post("/connections/{name}/flag") @@ -6897,6 +6929,11 @@ async def connection_metadata( """Static metadata for one connection (operability Tier 4): operator labels + a secret-scrubbed settings view. No live probe — see ``POST /connections/{name}/test``. + A channel-scoped reader gets no labels, with ``metadata_withheld`` true, and an inbound's + ``settings["reply_from"]`` as null, with ``reply_from_withheld`` true: the labels are + operator free text and ``reply_from`` names an outbound, so either may name a connection + outside its scope (BACKLOG #6638). + ``error`` is gated and masked as on ``GET /connections`` (BACKLOG #2443): null without ``messages:view_summary``, the fixed mask with it. ``reveal=true`` returns it whole; that needs ``messages:view_summary``, charges the PHI-read budget, and is audited as @@ -6939,6 +6976,11 @@ async def _connection_metadata_row( if direction == "in": ic = rr.registry.inbound[name] in_failed, in_filtered = rr.inbound_failed(name), rr.inbound_filtered(name) + settings = redacted_settings(ic.spec.settings) + if withheld and settings.get("reply_from") is not None: + # BACKLOG #6638: an Http inbound's reply_from names an outbound, which a + # channel-scoped caller may not reach, so it is withheld as the labels are. + settings["reply_from"] = None return ConnectionMetadata( name=name, direction="in", @@ -6947,7 +6989,8 @@ async def _connection_metadata_row( router=ic.router, metadata=None if withheld or not ic.metadata else dict(ic.metadata), metadata_withheld=withheld, - settings=redacted_settings(ic.spec.settings), + reply_from_withheld=withheld, + settings=settings, # ADR 0031 failure reason, or the #61 (ADR 0048) DR-parked reason — whichever applies. error=in_failed or in_filtered, fault=_fault(in_failed, in_filtered), diff --git a/messagefoundry/api/models.py b/messagefoundry/api/models.py index 224f808188..cbe75eefa2 100644 --- a/messagefoundry/api/models.py +++ b/messagefoundry/api/models.py @@ -1822,6 +1822,10 @@ class ConnectionMetadata(PhiGatedModel): # True when ``metadata`` is null because it was withheld from a channel-scoped caller: it is # operator free text, which may name a connection outside that caller's scope (BACKLOG #6638). metadata_withheld: bool = False + # True when an inbound's ``settings["reply_from"]``, if the inbound has one, is null because it + # was withheld from a channel-scoped caller: it names an outbound, which that caller may not + # reach (BACKLOG #6638). Set on every inbound row such a caller is shown, with or without one. + reply_from_withheld: bool = False settings: dict[str, Any] # secret-scrubbed view simulated: bool | None = None # outbound only; True = egress-suppressed shadow lane (#15) # Why this connection failed to start (ADR 0031) or was DR-parked (ADR 0048). Rated in diff --git a/tests/test_channel_scope_posture_users_reload.py b/tests/test_channel_scope_posture_users_reload.py index 9330713a3b..23ecd0c76e 100644 --- a/tests/test_channel_scope_posture_users_reload.py +++ b/tests/test_channel_scope_posture_users_reload.py @@ -300,6 +300,37 @@ async def test_connection_metadata_withholds_the_labels_from_a_scoped_reader( assert THEIRS not in scoped.text +async def test_connection_metadata_withholds_reply_from_from_a_scoped_reader( + engine: Engine, +) -> None: + """BACKLOG #6638: an Http inbound's ``reply_from`` setting names an outbound, which a + channel-scoped reader may not reach, so such a reader of its own inbound gets it null, with + ``reply_from_withheld`` saying why. The control: an all-channels reader reads the name whole, + and its flag is false.""" + reg = Registry() + reg.add_inbound( + build_inbound_connection( + MINE, + ConnectionSpec(ConnectorType.HTTP, {"port": 0, "reply_from": SHARED}), + router="r", + ) + ) + engine.add_registry(reg) + service = await _service(engine) + await _user(service, "scoped", [Role.VIEWER.value], [MINE]) + await _user(service, "wide", [Role.VIEWER.value], [ALL_CHANNELS]) + async with _client(engine, service) as c: + scoped = await c.get(f"/connections/{MINE}/metadata", headers=await _login(c, "scoped")) + wide = await c.get(f"/connections/{MINE}/metadata", headers=await _login(c, "wide")) + assert scoped.status_code == 200, scoped.text + assert wide.status_code == 200, wide.text + assert wide.json()["settings"]["reply_from"] == SHARED + assert wide.json()["reply_from_withheld"] is False + assert scoped.json()["settings"]["reply_from"] is None + assert scoped.json()["reply_from_withheld"] is True + assert SHARED not in scoped.text + + # --- GET /users ---------------------------------------------------------------------------------- diff --git a/tests/test_object_scope_flag_and_alert_rules.py b/tests/test_object_scope_flag_and_alert_rules.py index 1c4d672917..f771d7adfd 100644 --- a/tests/test_object_scope_flag_and_alert_rules.py +++ b/tests/test_object_scope_flag_and_alert_rules.py @@ -169,9 +169,11 @@ async def test_flag_scope_refusal_runs_before_request_validation( a string, a missing direction, and a name that fails the connection-name rule, whose row names no channel. The control: an all-channels caller still gets the 422 for each, with no denial row, and a scoped caller's well-formed request on its own inbound with a bad ``flagged`` is a - 422, since nothing there is refused. A body that is not JSON at all is refused by FastAPI - before any dependency runs, so it stays an unaudited 422 for every caller; pinned here so a - change to that is seen.""" + 422, since nothing there is refused. A body sent as ``application/json`` that does not parse is + refused by FastAPI before any dependency runs, so it stays an unaudited 422 for every caller; + pinned here so a change to that is seen. A body sent as any other type is not parsed, so a + scoped caller gets the audited 403 for it, and its row carries no direction marker, since its + direction was never read (BACKLOG #6638).""" service = await _service(toml_engine, admin_write_rate_limit=False) await _user(service, "own", Role.DEPLOYMENT, ["IB_TOML"]) await _user(service, "wide", Role.DEPLOYMENT, [ALL_CHANNELS]) @@ -205,6 +207,11 @@ async def test_flag_scope_refusal_runs_before_request_validation( plain = {"content-type": "text/plain"} r = await c.post("/connections/IB_TOML/flag", headers={**h, **plain}, content=good) assert r.status_code == 403, r.text + # A type that looks like +json but that FastAPI does not read as JSON, with a body that + # does not parse: the audited 403, never a 500 (BACKLOG #6638). + odd = {"content-type": "application/x/y+json"} + r = await c.post("/connections/IB_TOML/flag", headers={**h, **odd}, content=b"{not json") + assert r.status_code == 403, r.text hw = await _login(c, "wide") r = await c.post("/connections/IB_TOML/flag", headers={**hw, **plain}, content=good) assert r.status_code == 422, r.text @@ -213,16 +220,18 @@ async def test_flag_scope_refusal_runs_before_request_validation( assert status == 422, (name, content) assert not [a for a in audit if a[0] == "auth.channel_denied"], audit # The malformed name's row names no channel (BACKLOG #3031), and its direction is inbound, - # so it carries no direction marker. The four bad bodies and the text/plain one name no - # inbound direction, so each of those rows carries the marker. + # so it carries no direction marker. The four bad bodies name no inbound direction, so each of + # those rows carries the marker. The text/plain and application/x/y+json bodies were never + # read, so their direction is unknown and their rows carry no marker (BACKLOG #6638). rows = await toml_engine.store.list_audit(actor="own", action="auth.channel_denied") details = [json.loads(row["detail"]) for row in rows] - assert len(details) == 6, details + assert len(details) == 7, details assert [d for d in details if d.get("malformed_name") is True] == [ {"channel": None, "malformed_name": True} ], details marked = {"channel": "IB_TOML", "flag_direction_not_inbound": True} - assert details.count(marked) == 5, details + assert details.count(marked) == 4, details + assert details.count({"channel": "IB_TOML"}) == 2, details assert await toml_engine.store.list_connection_flags() == set() diff --git a/tests/test_security_doc_drift.py b/tests/test_security_doc_drift.py index fa1cd934a3..5978891842 100644 --- a/tests/test_security_doc_drift.py +++ b/tests/test_security_doc_drift.py @@ -361,6 +361,8 @@ "metadata_withheld", "method", "name", + # A boolean: whether a scoped reader's reply_from was withheld (BACKLOG #6638). + "reply_from_withheld", "router", "running", "settings", From f2ac5c18f0f904853fd0ce5eeee0046d2097ed1d Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Wed, 2 Dec 2026 01:40:29 -0600 Subject: [PATCH 8/8] Docs: the flag refusal's row and marker, and the withheld reply_from BACKLOG #6638 repair round. - CHANGELOG: the flag entry names the row a bad name gets (no channel, malformed_name) instead of "the row it gives any other target", and says a body of another type is refused with no direction marker; the metadata entry adds reply_from_withheld. - SECURITY.md: the marker is written for a direction the route read, and a body of another type is refused without it; "sent as JSON" is stated as the framework's own test; the metadata route row lists reply_from. - CONNECTIONS.md: the metadata route lists reply_from. Proposed PR title: Flag routes refuse a scoped caller before validating; scoped readers see no rule ids, labels or reply_from Proposed vault banner: BUILT on branch b20056-6638 (repair round): items 1-7 fixed with tests; flag gate fails closed on any body, reply_from withheld from scoped readers. Verified-by: none --- CHANGELOG.md | 15 ++++++++++----- docs/CONNECTIONS.md | 4 +++- docs/SECURITY.md | 16 ++++++++++------ 3 files changed, 23 insertions(+), 12 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 95507a47bf..360983f5a7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -15,16 +15,21 @@ All notable changes to MessageFoundry are documented here. The format follows - **A channel-scoped caller's malformed flag request is refused 403, and audited, before it is validated.** `POST /connections/{name}/flag` answered such a caller's direction that names neither side or is missing, and a name that fails the connection-name rule, with a 422 and no - `auth.channel_denied` row. It now answers each with the 403 and the row it gives any other - target outside the caller's scope. **This turns those 422s into 403s for such a caller.** A body - sent as JSON that does not parse is still a 422 with no row, as is any other fault in a request - whose name and direction pass. An all-channels caller still gets the 422. + `auth.channel_denied` row. It now answers each with the 403 and an `auth.channel_denied` row, as + for a target outside the caller's scope; for a bad name the row names no channel and carries + `"malformed_name": true`. **This turns those 422s into 403s for such a caller.** A body sent as + JSON that does not parse is still a 422 with no row, as is any other fault in a request whose + name and direction pass. A body sent as any other type is refused too, with a row that carries + no `flag_direction_not_inbound` marker, since its direction was not read. An all-channels caller + still gets the 422. (`BACKLOG #6638`) - **A channel-scoped reader sees no alert rule id or connection labels.** `GET /security/posture` labels a credential-reminder-silencing alert rule by its position alone for such a reader, as `GET /alerts/rules` shows it no id. `GET /connections/{name}/metadata` returns that reader no `metadata` labels, with the new `metadata_withheld` true. Both are operator free text, which may - name a connection outside the reader's scope. `AlertRuleInfo` gained `id_withheld`, so a null id + name a connection outside the reader's scope. That route also gives such a reader an inbound's + `settings.reply_from`, which names an outbound, as null, with the new `reply_from_withheld` + true. `AlertRuleInfo` gained `id_withheld`, so a null id no longer means both "unlabelled" and "withheld". (`BACKLOG #6638`) ## [0.5.3] — 2026-11-27 — Early Access diff --git a/docs/CONNECTIONS.md b/docs/CONNECTIONS.md index 3570211c1a..a02a99e7ee 100644 --- a/docs/CONNECTIONS.md +++ b/docs/CONNECTIONS.md @@ -661,7 +661,9 @@ Two read/diagnostic endpoints back the console's connection view (auth + per-cha `{"env": key}` and are never resolved; credential fields render as `"***"`). Inbound is per-channel; a shared outbound is barred to channel-scoped users. A channel-scoped user gets no `metadata` labels, since they are free text that may name another connection, and `metadata_withheld: true` - (BACKLOG #6638), so put a runbook such a user needs somewhere it can read. + (BACKLOG #6638), so put a runbook such a user needs somewhere it can read. Such a user also gets + an inbound's `settings.reply_from`, which names an outbound, as null, with + `reply_from_withheld: true`. - **`POST /connections/{name}/test`** (`connections:test`) — a **reachability probe** that builds a *fresh* connector (never the live one), honors the `[egress]` allowlist fail-closed, and **sends no real message** — a socket connect (MLLP/TCP/X12), `SELECT 1` (Database), an HTTP `HEAD` (REST/SOAP), diff --git a/docs/SECURITY.md b/docs/SECURITY.md index 3d562795a0..d615030c9d 100644 --- a/docs/SECURITY.md +++ b/docs/SECURITY.md @@ -1879,7 +1879,7 @@ exempt like any other, and the save re-seals the row as it always has. | `GET` | `/security/posture` | `monitoring:read` | `require` | | `GET` | `/channels` | `monitoring:read` | `require` | | `GET` | `/connections` | `monitoring:read` | `require_monitoring_read` — `error` gated on `messages:view_summary` and masked; the `reveal=` act also needs `messages:view_summary` (BACKLOG #2443) | -| `GET` | `/connections/{name}/metadata` | `monitoring:read` | `require` — per-channel for inbound; a shared outbound is barred to scoped users; a channel-scoped reader gets no `metadata` labels, which are operator free text that may name another connection, and `metadata_withheld: true`, so a null `metadata` there means "not shown" (BACKLOG #6638); credentials scrubbed unconditionally; `error` gated on `messages:view_summary` and masked; the `reveal=true` act also needs `messages:view_summary` (BACKLOG #2443) | +| `GET` | `/connections/{name}/metadata` | `monitoring:read` | `require` — per-channel for inbound; a shared outbound is barred to scoped users; a channel-scoped reader gets no `metadata` labels, which are operator free text that may name another connection, and `metadata_withheld: true`, so a null `metadata` there means "not shown"; nor an inbound's `settings.reply_from`, which names an outbound such a reader may not reach, so it is null with `reply_from_withheld: true` (BACKLOG #6638); credentials scrubbed unconditionally; `error` gated on `messages:view_summary` and masked; the `reveal=true` act also needs `messages:view_summary` (BACKLOG #2443) | | `GET` | `/events` | `monitoring:read` | `require` — data rule: *Single-route data rules* below (BACKLOG #1151) | | `GET` | `/connections/{name}/events` | `monitoring:read` | `require` | | `GET` | `/stats` | `monitoring:read` | `require_monitoring_read` | @@ -2534,8 +2534,10 @@ the same permission set on the same method reds CI until it is listed here. > A row naming an in-scope inbound has at least one more cause, on any deployment: a > flag request refused for its direction. Such a row's detail carries > `"flag_direction_not_inbound": true`, so a row without that marker was not refused for its -> direction (BACKLOG #3378). Both flag routes write it for any direction other than `inbound`, -> a request that names none or a malformed one included (BACKLOG #6638). +> direction (BACKLOG #3378). Both flag routes write it for any direction they read other than +> `inbound`, a request that names none or a malformed one included. The JSON route reads a +> direction only from a body sent as JSON, so a scoped caller's body of any other type is refused +> with a row that carries no marker, since it may have asked for `inbound` (BACKLOG #6638). > With an engine bound but not started there is no graph and no name exists. Every route still > checks the scope first, so a name outside it gets the 403. A name inside it gets 503 from the > first three routes and 404 from the control routes, with no denial row. With no engine bound at @@ -2555,9 +2557,11 @@ the same permission set on the same method reds CI until it is listed here. > for the direction, the row naming no channel for a bad name. Only the name and the direction > are read first: a scoped caller's request on its own inbound with any other fault, such as a > `flagged` that is not a boolean or an unknown key, is still a 422 with no row. So is a body -> sent as JSON (`application/json` or `+json`) that does not parse, for every caller, since the -> framework refuses it before the JSON route's refusal runs; a body sent as any other type names -> no direction to a scoped caller, so it is refused. An all-channels caller gets the 422 for a +> sent as JSON that does not parse, for every caller, since the framework refuses it before the +> JSON route's refusal runs. Sent as JSON means the framework's own test: a Content-Type whose type +> is `application` and whose subtype is `json` or ends `+json`. A body of any other type, such as +> `application/x/y+json`, is not parsed, so it names no direction to a scoped caller and is +> refused, with a row that carries no direction marker. An all-channels caller gets the 422 for a > malformed name or body, and on the console 404 for a direction that names neither side, with no > row. > `GET /alerts/rules` shows a scoped caller