Buckets:

download
raw
16.2 kB
"""The posture as the ledger records it — one reader for every surface.
Three in-process recorders — the MCP audit middleware, the executor's gates and
the protected-set funnel — file records that carry the same three facts about
the process they run in: which posture it is under, how that posture was
established, and which audit session it belongs to. All three read them
from the environment the Web Terminal's spawn sites stamp, and all three spell
them the same way, so the answers live here once and each recorder imports
them. This module is a leaf below all three: the middleware and the gates
already depend on the audit package, and nothing here depends on them.
The posture *value* has two sources, and :func:`posture` is the seam between
them. The environment answers first: a process launched read-only is sandboxed
and nothing else has to be read. Otherwise the answer comes from the operator's
narrowing, which is per CONTROL TARGET — "the live machine is read-only, leave
the virtual accelerator alone". No environment variable can carry that, because
setting one would sandbox both targets, so it is a field of the control-context
record, read through :mod:`osprey_connectors.posture_store` and imported lazily
so that the leaf stays a leaf. That record can only NARROW: an environment that
already says sandbox is returned unchanged, and no narrowing has ever granted a
write.
The narrowing belongs to the DEPLOYMENT rather than to a process tree inside
it, so :data:`POSTURE_SESSION_ENV_VAR` does not index it and does not gate it:
a dispatch worker, an ``agent_runner`` child and a CLI run are answered from
the same record as a Web Terminal session's child. That variable is the audit
session id, which is what the ledger joins records on.
:func:`posture` never raises. Three refusal paths call it on every tool call,
and an exception from any of them would cost the call rather than answer it, so
every way of failing to read the record — a missing file, a corrupt one, an
unresolvable target, an import that fails — degrades to the environment answer.
The spellings are the wire contract with the spawn sites
(``interfaces/web_terminal``), which stamp the variables by these names and are
pinned against them by test rather than by import — the interfaces package must
not be dragged behind every MCP server.
"""
from __future__ import annotations
import logging
import os
from osprey.audit.envelope import POSTURE_SOURCE_PROCESS, POSTURE_SOURCES
logger = logging.getLogger("osprey.audit.posture")
__all__ = [
"CONTROL_TARGET_ENV_VAR",
"OSPREY_AGENT_DATA_ROOT",
"CAUSE_DEPLOYMENT_READONLY",
"CAUSE_NARROWED_TARGET",
"POSTURE_ENV_VAR",
"POSTURE_SANDBOX",
"POSTURE_SESSION_ENV_VAR",
"POSTURE_SOURCE_ENV_VAR",
"POSTURE_WRITES",
"SANDBOX_MODE",
"is_readonly_run",
"sandbox_cause",
"posture",
"posture_session",
"posture_source",
"recorded_control_target",
]
#: The session posture, carried into every child of a Web Terminal session,
#: MCP servers included.
POSTURE_ENV_VAR = "OSPREY_EXECUTION_MODE"
#: How the posture in :data:`POSTURE_ENV_VAR` was established, and the audit
#: session id it belongs to. Stamped by the Web Terminal spawn sites and
#: absent everywhere else (a dispatch worker, a CLI run, a container-level
#: execution mode), which is what
#: :data:`~osprey.audit.envelope.POSTURE_SOURCE_PROCESS` is for.
POSTURE_SOURCE_ENV_VAR = "OSPREY_POSTURE_SOURCE"
POSTURE_SESSION_ENV_VAR = "OSPREY_POSTURE_SESSION"
#: The agent-data root the spawning surface resolved, stamped as a PAIR with
#: :data:`POSTURE_SESSION_ENV_VAR` — never one without the other. A session
#: child, the MCP servers below it and the stdlib-only hooks all have to agree
#: on ONE directory for the control-target state file and the control-context
#: record; each deriving it for itself means a deployment that moves
#: ``agent_data.base_dir``, or a hook that can only guess the repo root, reads a
#: different directory from the one the server writes. The spawn sites resolve
#: it once and say so here, so every reader below has an authoritative anchor
#: and only a process with no stamp at all falls back to its own derivation.
#:
#: The name is the value: this is an environment variable's spelling, and the
#: wire contract is the string, not the constant.
OSPREY_AGENT_DATA_ROOT = "OSPREY_AGENT_DATA_ROOT"
#: The control target a RUN was pinned to, stamped into the executor's sandbox
#: subprocess beside its generation and state PID (see
#: :data:`osprey.runtime.ENV_CONTROL_TARGET`, which spells the same string for
#: the reading side of the write pin). Where it is present it is the authority
#: on which target this process's writes are about: the session may have
#: switched since the run started, and the run's writes are still checked
#: against the target it was pinned to. Absent everywhere else — a stamp is
#: never inherited stale, because the executor pops all three variables when it
#: has no target to name.
CONTROL_TARGET_ENV_VAR = "OSPREY_CONTROL_TARGET"
#: The one value of :data:`POSTURE_ENV_VAR` that sandboxes a session. A *value*
#: comparison, never a presence check: the writes posture sets the same
#: variable.
SANDBOX_MODE = "readonly"
#: How the ledger spells the two postures — the Web Terminal's vocabulary, not
#: the environment variable's. Records from surfaces that never see
#: ``OSPREY_EXECUTION_MODE`` join on these.
POSTURE_SANDBOX = "sandbox"
POSTURE_WRITES = "writes"
def posture() -> str:
"""This process's posture, spelled the way the ledger spells it.
The state at decision time, not the reason for any decision: the protected
set and the static executor layers refuse in the writes posture too.
Two sources, in this order:
1. **The environment.** ``OSPREY_EXECUTION_MODE == "readonly"`` is a
sandbox — a *value* comparison, never a presence check, because the
writes posture and a readwrite run set the same variable. It
short-circuits: the record holds narrowings only, so consulting it could
not change that answer.
2. **The control-context record's posture**, indexed by the control target
this process's writes are about (:func:`recorded_control_target`); a
sandbox narrowing there is a sandbox here. A narrowing on any OTHER
target says nothing about this process — narrowing the live machine must
leave a process working on the virtual accelerator alone, which is the
entire point of the feature.
:data:`POSTURE_SESSION_ENV_VAR` is not consulted: the narrowing is the
deployment's, so a process that belongs to no session is answered from the
same record as one that does.
Never raises. See :func:`_target_is_sandboxed` for the degradation rule:
every failure to read the record answers the environment.
"""
env_answer = POSTURE_SANDBOX if is_readonly_run() else POSTURE_WRITES
if env_answer == POSTURE_SANDBOX:
return env_answer
return POSTURE_SANDBOX if _target_is_sandboxed() else env_answer
#: :func:`sandbox_cause`: the deployment itself was started read-only. No chip
#: click lifts it — the run has to be started without the environment variable.
CAUSE_DEPLOYMENT_READONLY = "deployment_readonly"
#: :func:`sandbox_cause`: the operator narrowed a control target from the header
#: chip. That is where it lifts, and the cause carries which machine it is about
#: — ``None`` when no target could be resolved, in which case the record's rule
#: is that the most restrictive narrowing decides and no machine may be named.
CAUSE_NARROWED_TARGET = "narrowed_target"
def is_readonly_run() -> bool:
"""Whether this process was started as a deployment-wide read-only run.
Rung 1 of :func:`posture`, spelled once so the refusal surfaces cannot ask
it differently from the answer they are explaining. A **value** comparison,
never a presence check, deliberately mirroring ``osprey_connectors``'
``is_readonly_run``: the writes posture and a readwrite run set the same
variable, so a presence check would claim a read-only run for every process
whose environment carries it for any other reason.
"""
return os.environ.get(POSTURE_ENV_VAR) == SANDBOX_MODE
def sandbox_cause() -> tuple[str, str | None]:
"""Why :func:`posture` answered ``sandbox``, and which machine it is about.
The two causes send an operator to different places — a deployment started
read-only cannot be lifted from the header chip, and a narrowed target can
— so every surface that refuses under this posture has to decide which one
it is looking at. It is decided here rather than once per surface, so two
refusals for one posture cannot disagree about where the operator should go.
Returns:
``(CAUSE_DEPLOYMENT_READONLY, None)`` for the environment answer, which
short-circuits exactly as it does in :func:`posture`; otherwise
``(CAUSE_NARROWED_TARGET, target)``, where *target* is the control
target this process's writes are about, or ``None`` when none can be
resolved.
Never raises. :func:`recorded_control_target` is documented not to, but this
runs on the refusal path of every clamped call, and a surprise here would
turn a refusal into an internal error — so a failure degrades to the
target-less cause, which names no machine rather than inventing one.
"""
if is_readonly_run():
return CAUSE_DEPLOYMENT_READONLY, None
try:
return CAUSE_NARROWED_TARGET, recorded_control_target()
except Exception: # noqa: BLE001 - the name degrades; the refusal does not
logger.warning(
"Could not name the active control target for the posture refusal",
exc_info=True,
)
return CAUSE_NARROWED_TARGET, None
def posture_source(declared: str | None = None) -> str:
"""The provenance of the posture a decision was made under.
*declared* is the call site's own answer, for a surface that knows it —
a web request belongs to no session and stamps ``app`` whatever the server
process inherited. With no answer the environment ladder is read: a session
child carries the marker its spawn stamped, and anything else is
``process``.
An unrecognised value degrades rather than being carried through, from
either source: :data:`~osprey.audit.envelope.POSTURE_SOURCES` is closed, a
record whose provenance is unrecognised reads as authoritative while
meaning nothing, and the envelope would reject it — which would cost the
record entirely rather than one field of it.
"""
stamped = declared if declared is not None else os.environ.get(POSTURE_SOURCE_ENV_VAR)
return stamped if stamped in POSTURE_SOURCES else POSTURE_SOURCE_PROCESS
def posture_session() -> str | None:
"""The audit session id this process's records belong to, if it was stamped.
An identifier the ledger joins on, and since the narrowing moved into the
control-context record it is nothing more: no reader indexes a posture by
it, and a process without one is narrowed exactly like a process with one.
"""
return (os.environ.get(POSTURE_SESSION_ENV_VAR) or "").strip() or None
# -- the deployment's control target ----------------------------------------
def recorded_control_target() -> str | None:
"""The control target this process's writes are about, or ``None``.
Public because the refusals are per target now: a gate that names the
narrowed target in its message has to resolve the same target
:func:`posture` resolved, and resolving it a second way would let the two
disagree — the refusal would name a machine the clamp did not fire for.
Two readers, in this order:
1. :data:`CONTROL_TARGET_ENV_VAR`, when it names a target readers know.
Only the executor's sandbox subprocess carries it, and there it is the
authority: that run is pinned to that target and its writes are refused
if the session moves off it, so its posture is the posture of the target
it was pinned to, not of the one the deployment has since switched to.
The value is checked against
:data:`~osprey_connectors.types.CONTROL_TARGETS` exactly as the record's
is — a stamp naming something no reader knows can only index the posture
to a key nothing writes, so it is dropped in favour of the record rather
than answered with.
2. Otherwise the deployment's control-context record, through
:func:`osprey_connectors.control_context.read_record`. There is one
record per deployment and one reader for it, so this answer and the
chip's cannot differ. This is the reader for the MCP servers, which is
where :func:`posture` is called from on every tool call.
That reader re-stats the record on every call and re-parses only when its
signature moves, so the per-tool-call cost is a ``stat``. Nothing rests on
the freshness of the answer either: the guarantee that a write cannot land
on a machine nobody selected is the runtime's generation pin, not this
lookup.
``None`` is an honest "not knowable here", and :func:`posture` answers the
environment for it rather than clamping: this gate refuses EVERY write tool
in the process, so firing it on a target nobody could name would refuse
writes to machines the operator never narrowed. The fail-closed layer for
one specific write is the connector's reference monitor, whose
``effective_writes`` takes the most restrictive entry when it cannot name a
target.
Never raises: an unimportable ``osprey_connectors`` (a deployment where the
connector package is not installed) and an unreadable record are both "not
knowable here" — for the stamp too, which is validated against that
package's vocabulary and so cannot be answered without it.
"""
stamped = (os.environ.get(CONTROL_TARGET_ENV_VAR) or "").strip()
try:
# Imported inside the function: this module is a leaf, and every MCP
# server imports it while only a session child ever reaches this line.
from osprey_connectors import control_context
from osprey_connectors.types import CONTROL_TARGETS
if stamped:
if stamped in CONTROL_TARGETS:
return stamped
logger.debug(
"%s names an unknown control target %r; reading the record instead",
CONTROL_TARGET_ENV_VAR,
stamped,
)
record = control_context.read_record()
except Exception: # noqa: BLE001 — an unreadable record is "unknown"
logger.debug(
"Control-context record unavailable; the control target is unknown", exc_info=True
)
return None
return None if record is None else record.target
def _target_is_sandboxed() -> bool:
"""Whether the record narrows this process's control target to the sandbox.
The one place :mod:`osprey_connectors.posture_store` is reached from the
audit package, and the one place the degradation rule lives: ``False`` for
every way of not knowing — no record, a corrupt or unreadable one, a target
that cannot be resolved, a connector package that cannot be imported. The
caller then answers the environment, which is what a deployment with
nothing narrowed has always been answered.
``False`` is not a grant. A narrowing can only refuse, so failing to read
one leaves whatever the deployment and the environment already decided —
including a deployment-wide read-only run, which no reader here can lift.
"""
try:
from osprey_connectors import posture_store
target = recorded_control_target()
if target is None:
return False
return posture_store.target_posture(target) == posture_store.POSTURE_SANDBOX
except Exception: # noqa: BLE001 — posture() is called on every tool call
logger.debug("Control-context record unavailable; answering the environment", exc_info=True)
return False

Xet Storage Details

Size:
16.2 kB
·
Xet hash:
d276e051d351ec99c1116f02bf86241864111074bd9effbc3b080bddecef7eab

Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.