Skip to content

Compartments API

compartments

Compartments: a code-enforced store for masked information.

A :class:Keeper is the only way in. It enforces grants, encrypts values with an injected :class:Cipher, audits every attempt, and releases a value toward the owner only through a single-use :class:ReleaseTicket.

Keeper

Keeper(
    db_path: str | Path,
    *,
    cipher_for: Callable[[str], Cipher],
    is_owner_turn: Callable[[str], Awaitable[bool]],
    clock: Callable[[], datetime] = _utc_now,
    ticket_ttl_s: float = 300,
)

Grants, encrypted records, an audit trail and single-use release tickets.

Every failure raises. Every refusal is audited in the same transaction that decides it, before the error reaches the caller. Logs name records and actors; values, labels and ticket ids never reach them. Assistant and compartment names must fit the identifier grammar, and a record id the shape the keeper issues; anything else is refused without being repeated anywhere.

The keeper takes every actor name on trust, and does not verify approved_by or confirmed_by. Actor names must come from the runtime, and grant, revoke, redeem and audit must never be model tools.

Parameters:

Name Type Description Default
db_path str | Path

The SQLite file.

required
cipher_for Callable[[str], Cipher]

Returns the cipher for a compartment. Required: there is no plaintext default.

required
is_owner_turn Callable[[str], Awaitable[bool]]

Says whether a turn id is the owner's turn in progress. It must refuse anything else: the keeper does not check freshness, so a callback that accepts any past owner message accepts a stale turn. Anything but a literal True, or an exception, is a refusal.

required
clock Callable[[], datetime]

Returns the current time, timezone-aware.

_utc_now
ticket_ttl_s float

How long a release ticket works.

300

Raises:

Type Description
TypeError

If cipher_for or is_owner_turn is not callable.

ValueError

If ticket_ttl_s is not positive.

Source code in orqest/compartments/keeper.py
def __init__(
    self,
    db_path: str | Path,
    *,
    cipher_for: Callable[[str], Cipher],
    is_owner_turn: Callable[[str], Awaitable[bool]],
    clock: Callable[[], datetime] = _utc_now,
    ticket_ttl_s: float = 300,
) -> None:
    if not callable(cipher_for):
        raise TypeError("cipher_for must be callable: compartments have no plaintext mode")
    if not callable(is_owner_turn):
        raise TypeError("is_owner_turn must be callable")
    if ticket_ttl_s <= 0:
        raise ValueError("ticket_ttl_s must be positive")
    self._db_path = db_path
    self._cipher_for = cipher_for
    self._is_owner_turn = is_owner_turn
    self._clock = clock
    self._ticket_ttl = timedelta(seconds=ticket_ttl_s)
    self._db: aiosqlite.Connection | None = None
    self._lock = asyncio.Lock()
    self._purge_pending = False
grant async
grant(
    assistant: str,
    compartment: str,
    access: Access,
    *,
    approved_by: str,
) -> Grant

Give assistant access to compartment, replacing any earlier grant.

A replacement without read access spends the assistant's open tickets on this compartment.

Raises:

Type Description
CompartmentDenied

If assistant or compartment is malformed.

ValueError

If approved_by is blank or access is unknown.

Source code in orqest/compartments/keeper.py
async def grant(
    self, assistant: str, compartment: str, access: Access, *, approved_by: str
) -> Grant:
    """Give ``assistant`` access to ``compartment``, replacing any earlier grant.

    A replacement without read access spends the assistant's open tickets on
    this compartment.

    Raises:
        CompartmentDenied: If ``assistant`` or ``compartment`` is malformed.
        ValueError: If ``approved_by`` is blank or ``access`` is unknown.
    """
    if not approved_by.strip():
        raise ValueError("approved_by must not be blank")
    grant = Grant(
        assistant=assistant,
        compartment=compartment,
        access=access,
        approved_by=approved_by,
        at=self._now(),
    )
    attempt = _Attempt(approved_by, "grant", compartment)
    async with self._transaction() as db:
        if not (is_valid_identifier(assistant) and is_valid_identifier(compartment)):
            await self._refuse(db, attempt, _MALFORMED, CompartmentDenied(_MALFORMED))
        await db.execute(
            "INSERT OR REPLACE INTO grants (assistant, compartment, access, approved_by, at)"
            " VALUES (?,?,?,?,?)",
            (assistant, compartment, access, approved_by, grant.at.isoformat()),
        )
        if access not in _READS:
            await self._spend_tickets_of(db, assistant, compartment)
        await self._audit(db, attempt, allowed=True, reason=f"{access} for {assistant!r}")
    return grant
revoke async
revoke(assistant: str, compartment: str) -> None

Remove a grant and spend the assistant's open tickets on this compartment.

Effective for the next call, and a later grant does not revive the tickets. No grant to remove is not an error.

Raises:

Type Description
CompartmentDenied

If a name is malformed.

Source code in orqest/compartments/keeper.py
async def revoke(self, assistant: str, compartment: str) -> None:
    """Remove a grant and spend the assistant's open tickets on this compartment.

    Effective for the next call, and a later grant does not revive the
    tickets. No grant to remove is not an error.

    Raises:
        CompartmentDenied: If a name is malformed.
    """
    attempt = _Attempt(assistant, "revoke", compartment)
    async with self._transaction() as db:
        await self._require_well_formed(db, attempt)
        cur = await db.execute(
            "DELETE FROM grants WHERE assistant=? AND compartment=?", (assistant, compartment)
        )
        if cur.rowcount:
            await self._spend_tickets_of(db, assistant, compartment)
            await self._audit(db, attempt, allowed=True, reason="grant revoked")
        else:
            # Neither name has been shown to be real, so neither is recorded as given.
            safe = await self._known_only(db, replace(attempt, actor=None))
            await self._audit(db, safe, allowed=True, reason="no grant to revoke")
grants_for async
grants_for(assistant: str) -> list[Grant]

The grants assistant holds, by compartment name.

Raises:

Type Description
CompartmentDenied

If assistant is malformed, so that an empty list always means a real name holding nothing.

Source code in orqest/compartments/keeper.py
async def grants_for(self, assistant: str) -> list[Grant]:
    """The grants ``assistant`` holds, by compartment name.

    Raises:
        CompartmentDenied: If ``assistant`` is malformed, so that an empty list
            always means a real name holding nothing.
    """
    async with self._transaction() as db:
        await self._require_well_formed(db, _Attempt(assistant, "grants_for", None))
        cur = await db.execute(
            "SELECT * FROM grants WHERE assistant=? ORDER BY compartment", (assistant,)
        )
        return [_grant(row) for row in await cur.fetchall()]
write async
write(
    assistant: str,
    compartment: str,
    label: str,
    value: dict[str, Any],
) -> Pointer

Store a new record. Needs a write grant.

Parameters:

Name Type Description Default
assistant str

The writer.

required
compartment str

Where to store it.

required
label str

A plaintext name, visible without any grant. A label holding one of the value's matchable strings is refused.

required
value dict[str, Any]

Strict-JSON data with string keys, encrypted before it is stored.

required

Raises:

Type Description
CompartmentDenied

Without a write grant, for a malformed name, or if the label holds a string from the value.

TypeError

If value is not a dict.

ValueError

If label is blank or value is not strict JSON.

RuntimeError

If the cipher fails or does not encrypt.

Source code in orqest/compartments/keeper.py
async def write(
    self, assistant: str, compartment: str, label: str, value: dict[str, Any]
) -> Pointer:
    """Store a new record. Needs a write grant.

    Args:
        assistant: The writer.
        compartment: Where to store it.
        label: A plaintext name, visible without any grant. A label holding
            one of the value's matchable strings is refused.
        value: Strict-JSON data with string keys, encrypted before it is stored.

    Raises:
        CompartmentDenied: Without a write grant, for a malformed name, or if
            the label holds a string from the value.
        TypeError: If ``value`` is not a dict.
        ValueError: If ``label`` is blank or ``value`` is not strict JSON.
        RuntimeError: If the cipher fails or does not encrypt.
    """
    attempt = _Attempt(assistant, "write", compartment)
    async with self._transaction() as db:
        await self._require_well_formed(db, attempt)
        await self._require(db, attempt, _WRITES, "write")
        normalized_label = _normalized(label)
        if not normalized_label:
            raise ValueError("label must not be blank")
        if not isinstance(value, dict):
            raise TypeError("value must be a dict")
        bound = {
            "record_id": uuid4().hex,
            "compartment": compartment,
            "label": label,
            "created_at": self._now().isoformat(),
            "created_by": assistant,
        }
        plain = _envelope(bound, value)
        if plain is None:
            raise ValueError("value must be strict JSON with string keys")
        if any(s in normalized_label for s in _matchable_strings(value, keys=False)):
            error = CompartmentDenied("the label holds a string from the value, in plaintext")
            await self._refuse(db, attempt, "label holds a stored value", error)
        sealed = _encrypt(self._cipher_for, compartment, plain)
        if sealed is None:
            raise RuntimeError(f"the cipher for compartment {compartment!r} did not encrypt")
        await db.execute(
            "INSERT INTO records (record_id, compartment, label, created_at, created_by,"
            " sealed) VALUES (?,?,?,?,?,?)",
            (*(bound[c] for c in _BOUND_COLUMNS), sealed),
        )
        await self._audit(
            db,
            replace(attempt, record_id=bound["record_id"]),
            allowed=True,
            reason="write grant",
        )
    if self._purge_pending:
        await self._truncate_wal()
    return _pointer(bound)
read async
read(
    assistant: str,
    compartment: str,
    *,
    record_id: str | None = None,
    limit: int = 20,
) -> list[Record]

Working access: an assistant's own use of a compartment, newest first.

One corrupt record fails the whole read. Each record returned gets its own audit event.

Raises:

Type Description
CompartmentDenied

Without a read grant, or for a malformed name.

KeyError

If record_id is not in this compartment.

CompartmentCorrupt

If a record cannot be decrypted.

ValueError

If limit is below 1.

Source code in orqest/compartments/keeper.py
async def read(
    self, assistant: str, compartment: str, *, record_id: str | None = None, limit: int = 20
) -> list[Record]:
    """Working access: an assistant's own use of a compartment, newest first.

    One corrupt record fails the whole read. Each record returned gets its
    own audit event.

    Raises:
        CompartmentDenied: Without a read grant, or for a malformed name.
        KeyError: If ``record_id`` is not in this compartment.
        CompartmentCorrupt: If a record cannot be decrypted.
        ValueError: If ``limit`` is below 1.
    """
    if limit < 1:
        raise ValueError("limit must be at least 1")
    attempt = _Attempt(assistant, "read", compartment, record_id)
    async with self._transaction() as db:
        await self._require_well_formed(db, attempt)
        await self._require(db, attempt, _READS, "read")
        if record_id is None:
            cur = await db.execute(
                "SELECT * FROM records WHERE compartment=? ORDER BY seq DESC LIMIT ?",
                (compartment, limit),
            )
            rows = await cur.fetchall()
        else:
            row = await self._record_row(db, compartment, record_id)
            if row is None:
                error = _UnknownRecord("no such record")
                await self._refuse(db, attempt, "no such record", error)
            rows = [row]
        records = [await self._open(db, attempt, row) for row in rows]
        for record in records:
            await self._audit(
                db,
                replace(attempt, record_id=record.pointer.record_id),
                allowed=True,
                reason="read grant",
            )
        if not records:
            await self._audit(db, attempt, allowed=True, reason="no records")
    return records
pointers async
pointers(compartment: str) -> list[Pointer]

Labels only, newest first. Needs no grant, and is not audited.

There is no actor to name and no value is touched: knowing that a compartment holds something is allowed by design. Only a refusal is audited.

Raises:

Type Description
CompartmentDenied

If compartment is malformed, so that an empty list always means a real name holding nothing.

CompartmentCorrupt

If a stored timestamp cannot be read. Nothing else is checked here: an altered label shows only on a read through the cipher.

Source code in orqest/compartments/keeper.py
async def pointers(self, compartment: str) -> list[Pointer]:
    """Labels only, newest first. Needs no grant, and is not audited.

    There is no actor to name and no value is touched: knowing that a
    compartment holds something is allowed by design. Only a refusal is audited.

    Raises:
        CompartmentDenied: If ``compartment`` is malformed, so that an empty list
            always means a real name holding nothing.
        CompartmentCorrupt: If a stored timestamp cannot be read. Nothing else is
            checked here: an altered label shows only on a read through the cipher.
    """
    async with self._transaction() as db:
        await self._require_well_formed(db, _Attempt(None, "pointers", compartment))
        cur = await db.execute(
            "SELECT record_id, compartment, label, created_at, created_by FROM records"
            " WHERE compartment=? ORDER BY seq DESC",
            (compartment,),
        )
        return [_pointer(row) for row in await cur.fetchall()]
delete async
delete(actor: str, record_id: str) -> None

Remove a record for real. Needs a write grant on its compartment.

Spends any open ticket on the record, overwrites the freed space (secure_delete) and truncates the write-ahead log, so neither the label nor the ciphertext stays on disk. The audit trail keeps the record's id.

Another connection reading the file can keep the log from being truncated. The record is gone and this still returns, but its bytes stay in the log until the next truncating checkpoint: a later delete (one that finds no such record included), the next write, the next keeper opened on the file, or the last connection closing. An ordinary checkpoint does not remove them. The audit trail says the purge is pending, and a warning names the record.

Raises:

Type Description
CompartmentDenied

Without a write grant, or for a malformed name.

KeyError

If there is no such record.

Source code in orqest/compartments/keeper.py
async def delete(self, actor: str, record_id: str) -> None:
    """Remove a record for real. Needs a write grant on its compartment.

    Spends any open ticket on the record, overwrites the freed space
    (``secure_delete``) and truncates the write-ahead log, so neither the label
    nor the ciphertext stays on disk. The audit trail keeps the record's id.

    Another connection reading the file can keep the log from being truncated.
    The record is gone and this still returns, but its bytes stay in the log
    until the next truncating checkpoint: a later ``delete`` (one that finds no
    such record included), the next ``write``, the next keeper opened on the file,
    or the last connection closing. An ordinary checkpoint does not remove them.
    The audit trail says the purge is pending, and a warning names the record.

    Raises:
        CompartmentDenied: Without a write grant, or for a malformed name.
        KeyError: If there is no such record.
    """
    attempt = _Attempt(actor, "delete", None, record_id)
    try:
        async with self._transaction() as db:
            await self._require_well_formed(db, attempt)
            cur = await db.execute(
                "SELECT compartment FROM records WHERE record_id=?", (record_id,)
            )
            row = await cur.fetchone()
            if row is None:
                await self._refuse(
                    db, attempt, "no such record", _UnknownRecord("no such record")
                )
            attempt = replace(attempt, compartment=row["compartment"])
            await self._require(db, attempt, _WRITES, "write")
            await db.execute("DELETE FROM records WHERE record_id=?", (record_id,))
            await db.execute(
                "UPDATE tickets SET spent_at=? WHERE record_id=? AND spent_at IS NULL",
                (self._now().isoformat(), record_id),
            )
            await self._audit(db, attempt, allowed=True, reason="write grant")
    except _UnknownRecord:
        await self._truncate_wal()  # a caller retrying a delete wants the bytes gone
        raise
    if await self._truncate_wal():
        return
    logger.warning(
        "record {!r} deleted; purge pending: its bytes stay in the log until a"
        " truncating checkpoint",
        record_id,
    )
    try:
        async with self._transaction() as db:
            await self._audit(
                db, attempt, allowed=True, reason="deleted; purge pending: log is in use"
            )
    except (sqlite3.Error, RuntimeError) as e:  # committed: the delete itself succeeded
        logger.warning(
            "record {!r}: could not audit the pending purge: {}", record_id, type(e).__name__
        )
prepare_release async
prepare_release(
    requester: str,
    compartment: str,
    record_id: str,
    *,
    owner_turn_id: str,
) -> ReleaseTicket

Prepare a release to the owner. No value is touched here.

The keeper only stores owner_turn_id and asks is_owner_turn about it. It does not check freshness: refusing anything but the turn in progress is the callback's job, and the caller must take the id from the triggering message, never from a model.

Parameters:

Name Type Description Default
requester str

The assistant asking. Needs a read grant.

required
compartment str

The record's compartment.

required
record_id str

The record.

required
owner_turn_id str

The turn that asked; is_owner_turn must accept it. A refusal's audit reason names it if it fits the identifier grammar.

required

Raises:

Type Description
CompartmentDenied

Without a read grant, for a malformed name, or if this is not an owner turn.

KeyError

If the record is not in this compartment.

Source code in orqest/compartments/keeper.py
async def prepare_release(
    self, requester: str, compartment: str, record_id: str, *, owner_turn_id: str
) -> ReleaseTicket:
    """Prepare a release to the owner. No value is touched here.

    The keeper only stores ``owner_turn_id`` and asks ``is_owner_turn`` about it.
    It does not check freshness: refusing anything but the turn in progress is
    the callback's job, and the caller must take the id from the triggering
    message, never from a model.

    Args:
        requester: The assistant asking. Needs a read grant.
        compartment: The record's compartment.
        record_id: The record.
        owner_turn_id: The turn that asked; ``is_owner_turn`` must accept it.
            A refusal's audit reason names it if it fits the identifier grammar.

    Raises:
        CompartmentDenied: Without a read grant, for a malformed name, or if
            this is not an owner turn.
        KeyError: If the record is not in this compartment.
    """
    attempt = _Attempt(requester, "prepare_release", compartment, record_id)
    turn = f" (turn {owner_turn_id})" if is_valid_identifier(owner_turn_id) else ""
    # Outside the transaction: the check is the caller's code and may be slow.
    is_owner = await self._owner_turn_holds(owner_turn_id)
    ticket_id = secrets.token_urlsafe(32)
    ticket = ReleaseTicket(
        ticket_id=ticket_id,
        compartment=compartment,
        record_id=record_id,
        requester=requester,
        owner_turn_id=owner_turn_id,
        expires_at=self._now() + self._ticket_ttl,
    )
    async with self._transaction() as db:
        await self._require_well_formed(db, attempt)
        await self._require(db, attempt, _READS, "read", note=turn)
        if not is_owner:
            error = CompartmentDenied("a release needs the owner's current turn")
            await self._refuse(db, attempt, f"not an owner turn{turn}", error)
        if await self._record_row(db, compartment, record_id) is None:
            missing = _UnknownRecord("no such record")
            await self._refuse(db, attempt, f"no such record{turn}", missing)
        await db.execute(
            "INSERT INTO tickets (ticket_hash, compartment, record_id, requester,"
            " owner_turn_id, expires_at) VALUES (?,?,?,?,?,?)",
            (
                _ticket_hash(ticket_id),
                compartment,
                record_id,
                requester,
                owner_turn_id,
                ticket.expires_at.isoformat(),
            ),
        )
        await self._audit(db, attempt, allowed=True, reason=f"read grant and owner turn{turn}")
    return ticket
refuse_release async
refuse_release(
    requester: str, compartment: str, record_id: str
) -> None

Audit a release refused before :meth:prepare_release: no owner message at all.

Records the attempt and does nothing else: no ticket, no grant check, no error. A malformed or unknown name is blanked as in any other refusal, and the reason is the keeper's own, so nothing a model typed reaches the audit or logs.

Source code in orqest/compartments/keeper.py
async def refuse_release(self, requester: str, compartment: str, record_id: str) -> None:
    """Audit a release refused before :meth:`prepare_release`: no owner message at all.

    Records the attempt and does nothing else: no ticket, no grant check, no
    error. A malformed or unknown name is blanked as in any other refusal, and the
    reason is the keeper's own, so nothing a model typed reaches the audit or logs.
    """
    attempt = _Attempt(requester, "prepare_release", compartment, record_id)
    async with self._transaction() as db:
        safe = await self._known_only(db, _well_formed_only(attempt))
        await self._audit(db, safe, allowed=False, reason="no owner message")
redeem async
redeem(ticket_id: str, *, confirmed_by: str) -> Record

Release a record. The caller must send it to the screen, never to a model.

The application's own authenticated endpoint returns the value in its response, and nowhere else. It must never go into a view, artifact, state or message: all of them persist, and render_view serves a view or an artifact's snapshot with no ticket and no passkey. Orqest has no release event, so this is on the caller.

The ticket id is a bearer credential and confirmed_by is taken on trust: the keeper verifies neither who holds the id nor who confirmed. The application must verify the owner first, and call this only from its own verified channel. Never expose this as a model tool.

A release spends the ticket in the same transaction as its audit event, so a crash after the commit loses that one release. A refusal for a blank confirmation or a corrupt record leaves the ticket usable until it expires. revoke, a grant without read access and delete also spend tickets.

Parameters:

Name Type Description Default
ticket_id str

From :meth:prepare_release.

required
confirmed_by str

Who confirmed, as the channel verified it.

required

Raises:

Type Description
TicketInvalid

If the ticket is unknown, spent or expired, the confirmation is blank, or the requester's grant is gone.

CompartmentCorrupt

If the record or ticket cannot be read intact.

Source code in orqest/compartments/keeper.py
async def redeem(self, ticket_id: str, *, confirmed_by: str) -> Record:
    """Release a record. The caller must send it to the screen, never to a model.

    The application's own authenticated endpoint returns the value in its response,
    and nowhere else. It must never go into a view, artifact, state or message: all
    of them persist, and ``render_view`` serves a view or an artifact's snapshot with
    no ticket and no passkey. Orqest has no release event, so this is on the caller.

    The ticket id is a bearer credential and ``confirmed_by`` is taken on trust:
    the keeper verifies neither who holds the id nor who confirmed. The
    application must verify the owner first, and call this only from its own
    verified channel. Never expose this as a model tool.

    A release spends the ticket in the same transaction as its audit event, so a
    crash after the commit loses that one release. A refusal for a blank
    confirmation or a corrupt record leaves the ticket usable until it expires.
    ``revoke``, a grant without read access and ``delete`` also spend tickets.

    Args:
        ticket_id: From :meth:`prepare_release`.
        confirmed_by: Who confirmed, as the channel verified it.

    Raises:
        TicketInvalid: If the ticket is unknown, spent or expired, the
            confirmation is blank, or the requester's grant is gone.
        CompartmentCorrupt: If the record or ticket cannot be read intact.
    """
    confirmed = bool(confirmed_by and confirmed_by.strip())
    ticket_hash = _ticket_hash(ticket_id)
    async with self._transaction() as db:
        now = self._now()
        cur = await db.execute("SELECT * FROM tickets WHERE ticket_hash=?", (ticket_hash,))
        ticket = await cur.fetchone()
        if ticket is None:
            actor = confirmed_by if confirmed else "unknown"
            await self._refuse(
                db,
                _Attempt(actor, "redeem", None),
                "unknown ticket",
                TicketInvalid("unknown release ticket"),
            )
        compartment, record_id = ticket["compartment"], ticket["record_id"]
        actor = confirmed_by if confirmed else ticket["requester"]
        attempt = _Attempt(actor, "redeem", compartment, record_id)
        expires_at = _parse_time(ticket["expires_at"])
        if expires_at is None:
            error = CompartmentCorrupt(
                f"the release ticket for record {record_id!r} has a bad timestamp"
            )
            await self._refuse(db, attempt, "corrupt ticket", error, issued=True)
        problem = await self._ticket_problem(
            db, ticket, expired=now >= expires_at, confirmed=confirmed
        )
        row = None if problem else await self._record_row(db, compartment, record_id)
        if row is None:
            reason = problem or "record is gone"
            error = TicketInvalid(f"release ticket refused: {reason}")
            await self._refuse(db, attempt, reason, error, issued=True)
        record = await self._open(db, attempt, row)
        await db.execute(
            "UPDATE tickets SET spent_at=? WHERE ticket_hash=?",
            (now.isoformat(), ticket_hash),
        )
        await self._audit(
            db, attempt, allowed=True, reason=f"confirmed; asked by {ticket['requester']!r}"
        )
    return record
leak_check async
leak_check(
    assistant: str, text: str, *, match_keys: bool = True
) -> list[str]

Labels whose stored strings appear in text.

Looks only in compartments assistant can read, at string values and dict keys of six characters or more. Both sides are compared in NFKC form, casefolded, with runs of whitespace collapsed. Each stored string must appear whole: a fragment of a longer value passes, as do paraphrases and numbers. A short common value also hits inside a longer word, so active refuses inactive. A hit is audited against its record. A corrupt record raises rather than passing the text.

Parameters:

Name Type Description Default
assistant str

Whose compartments to look in.

required
text str

The text to check.

required
match_keys bool

Whether a record's dict keys count as stored strings. Leave this on for anything crossing to someone else. Off suits a text full of structural words, where a record's status key would refuse every status field; a key alone then goes unmatched.

True

Raises:

Type Description
CompartmentDenied

If assistant is malformed, so that an empty list always means a real name with nothing found.

CompartmentCorrupt

If a record cannot be decrypted.

Source code in orqest/compartments/keeper.py
async def leak_check(self, assistant: str, text: str, *, match_keys: bool = True) -> list[str]:
    """Labels whose stored strings appear in ``text``.

    Looks only in compartments ``assistant`` can read, at string values and
    dict keys of six characters or more. Both sides are compared in NFKC form,
    casefolded, with runs of whitespace collapsed. Each stored string must
    appear whole: a fragment of a longer value passes, as do paraphrases and
    numbers. A short common value also hits inside a longer word, so ``active``
    refuses ``inactive``. A hit is audited against its record. A corrupt record
    raises rather than passing the text.

    Args:
        assistant: Whose compartments to look in.
        text: The text to check.
        match_keys: Whether a record's dict keys count as stored strings. Leave
            this on for anything crossing to someone else. Off suits a text full
            of structural words, where a record's ``status`` key would refuse
            every ``status`` field; a key alone then goes unmatched.

    Raises:
        CompartmentDenied: If ``assistant`` is malformed, so that an empty list
            always means a real name with nothing found.
        CompartmentCorrupt: If a record cannot be decrypted.
    """
    normalized = _normalized(text)
    labels: set[str] = set()
    async with self._transaction() as db:
        await self._require_well_formed(db, _Attempt(assistant, "leak_check", None))
        cur = await db.execute(
            "SELECT r.*, g.access FROM records r"
            " JOIN grants g ON g.compartment = r.compartment WHERE g.assistant=?",
            (assistant,),
        )
        for row in await cur.fetchall():
            if row["access"] not in _READS:
                continue
            attempt = _Attempt(assistant, "leak_check", row["compartment"], row["record_id"])
            record = await self._open(db, attempt, row)
            if any(s in normalized for s in _matchable_strings(record.value, keys=match_keys)):
                labels.add(record.pointer.label)
                await self._audit(
                    db, attempt, allowed=False, reason="text holds a stored value"
                )
    return sorted(labels)
audit async
audit(
    *, compartment: str | None = None, limit: int = 100
) -> list[AccessEvent]

Audited attempts, newest first, optionally for one compartment.

Raises:

Type Description
ValueError

If limit is below 1.

Source code in orqest/compartments/keeper.py
async def audit(self, *, compartment: str | None = None, limit: int = 100) -> list[AccessEvent]:
    """Audited attempts, newest first, optionally for one compartment.

    Raises:
        ValueError: If ``limit`` is below 1.
    """
    if limit < 1:
        raise ValueError("limit must be at least 1")
    async with self._transaction() as db:
        if compartment is None:
            cur = await db.execute("SELECT * FROM audit ORDER BY seq DESC LIMIT ?", (limit,))
        else:
            cur = await db.execute(
                "SELECT * FROM audit WHERE compartment=? ORDER BY seq DESC LIMIT ?",
                (compartment, limit),
            )
        return [_event(row) for row in await cur.fetchall()]

AccessEvent

One audited attempt, allowed or denied.

Attributes:

Name Type Description
at datetime

When it happened.

actor str | None

Who attempted it, as the caller named them. For revoke, the assistant losing the grant. None if the name was malformed, or for a revoke that removed nothing.

action str

grant, revoke, read, write, delete, prepare_release, redeem or leak_check, or grants_for or pointers for a lookup refused over a malformed name.

compartment str | None

The compartment. None if the name was malformed or unknown, or for an unknown ticket.

record_id str | None

The record, when the attempt concerned one that exists or one named on the keeper's own ticket.

allowed bool

Whether it went ahead. A leak_check event is a hit, so it reads as not allowed.

reason str

Why, in the keeper's own words. Never contains a value.

Cipher

Encrypts one compartment's values, and must be authenticated.

decrypt must raise on a wrong key or altered bytes (cryptography.fernet.Fernet fits as it is). Without that, only the JSON envelope stands between damaged data and a garbage value, and it can be forged. Give each compartment its own key.

encrypt
encrypt(data: bytes) -> bytes

Encrypt data.

Source code in orqest/compartments/models.py
def encrypt(self, data: bytes) -> bytes:
    """Encrypt ``data``."""
    ...
decrypt
decrypt(data: bytes) -> bytes

Decrypt data, raising if it cannot be done.

Source code in orqest/compartments/models.py
def decrypt(self, data: bytes) -> bytes:
    """Decrypt ``data``, raising if it cannot be done."""
    ...

CompartmentCorrupt

A stored record cannot be decrypted (wrong key or altered data).

Names the record and never carries any of its content.

CompartmentDenied

The actor may not do this. The attempt has been audited.

Grant

Permission for one assistant to use one compartment.

Attributes:

Name Type Description
assistant str

The assistant holding the grant.

compartment str

The compartment it covers.

access Access

"read", "write" or "read_write".

approved_by str

Who approved it.

at datetime

When it was granted.

Pointer

What may be known about a record without any access to it.

Attributes:

Name Type Description
record_id str

The record's id.

compartment str

Its compartment.

label str

A plaintext name. Labels must not contain the secret.

created_at datetime

When it was written.

created_by str

The assistant that wrote it.

Record

A decrypted record.

value is left out of repr and str, so logging a record or showing one in a traceback does not reveal it. Dumping the model does.

Attributes:

Name Type Description
pointer Pointer

The record's pointer.

value dict[str, Any]

The decrypted value.

ReleaseTicket

A single-use, time-limited permission to release one record to the owner.

ticket_id is left out of repr and str: it is a bearer credential.

Attributes:

Name Type Description
ticket_id str

The credential to pass to Keeper.redeem.

compartment str

The record's compartment.

record_id str

The record to release.

requester str

The assistant that prepared the release.

owner_turn_id str

The owner turn it was prepared in.

expires_at datetime

The moment the ticket stops working.

TicketInvalid

A release ticket cannot be redeemed. The attempt has been audited.