Metadata-Version: 2.4
Name: quaspar-shield-core
Version: 0.5.0a2
Summary: Local per-agent request filtering, file screening, isolated workers, and one host-owned text connector
License-Expression: Apache-2.0
Project-URL: Homepage, https://quaspar.com
Project-URL: Security, https://quaspar.com/security
Classifier: Development Status :: 3 - Alpha
Classifier: Programming Language :: Python :: 3
Classifier: Topic :: Security
Requires-Python: >=3.11
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: cryptography>=46
Dynamic: license-file

# Charavyuha by Quaspar

Charavyuha is an Apache-2.0 Python library for controlling which signed requests reach your agent. A trusted host enrolls senders, defines the exact work each may do, and runs your handler only after the checks pass. Routine authorized work needs zero review prompts. The optional native worker runs a compatible Python file in an isolated Linux process.

## Install and try the signed inbox

Use Python 3.11 or newer. When this version is available on PyPI, install it in your virtual environment with `python -m pip install quaspar-shield-core==0.5.0a2`. To install the downloadable alpha directly, extract its ZIP. On Linux use `sha256sum -c SHA256SUMS` to verify the installation guide and both distribution files. From the directory containing the wheel, create a virtual environment and install the wheel. Pip also installs the cryptography dependency.

**macOS or Linux**

```sh
python3 -m venv .venv
. .venv/bin/activate
python -m pip install ./quaspar_shield_core-0.5.0a2-py3-none-any.whl
quaspar-shield inbox
```

**Windows PowerShell**

```powershell
py -3 -m venv .venv
.\.venv\Scripts\python.exe -m pip install .\quaspar_shield_core-0.5.0a2-py3-none-any.whl
.\.venv\Scripts\quaspar-shield.exe inbox
```

The inbox example uses disposable identities and a local callback. Two signed jobs reach the callback. An unknown sender, a duplicate request, and a request over the shared limit are refused. You can run it without an account, API key or scanner. If you have the source archive instead, pass its `.tar.gz` path to the same pip install command.

## Run your first isolated worker on Linux

The native profile supports 64-bit x86 Linux with Debian-style system Python. On Debian or Ubuntu the relevant packages are `python3`, `python3-venv`, `bubblewrap`, `util-linux` and `libseccomp2`. Your host policy must allow bubblewrap to create its user namespace. A Linux VM with those prerequisites is an option for developers who use another operating system.

```sh
quaspar-shield
```

This verifies the native sandbox and runs the bundled worker on a synthetic note. A successful job reports an automatic decision, zero review prompts and one local fixture exchange. Your agent can make its first protected run without sending a prompt to an external provider. Use `quaspar-shield doctor` to diagnose host prerequisites.

To start from an editable worker, run the following commands anywhere you can write. Open `my_agent.py` to change how it handles the supplied note and response, and run the second command again. The host supplies the attachment and holds the connector credential.

```sh
quaspar-shield init my_agent.py
quaspar-shield quickstart --agent my_agent.py
```

The native model host snapshots the worker once per job. Both stages execute those bytes, even if a deployment replaces the file while the job is running. For an approved deployment, record the reviewed worker's SHA-256 with its release in trusted host configuration. The following command reads that independently provisioned value from the environment. A mismatch refuses the job before its model worker or connector runs.

```sh
quaspar-shield quickstart --agent my_agent.py --worker-sha256 "${APPROVED_WORKER_SHA256:?Set the reviewed release digest}" --json
```

Pinning is optional for local editing. The Python host accepts the same value in `NoteModelHost(..., expected_worker_sha256=...)` with its native worker. A pin authenticates the selected code against a reviewed release. The host continues to treat the text it produces as untrusted.

## Connect your existing agent

Keep a receiver in the trusted process that owns the action. Route incoming signed requests to its `dispatch` method. The handler below reads an assigned note. In your host, replace that handler with the corresponding agent operation. Enroll the sender’s public key in advance and deliver the receiver’s audience to that sender over your trusted setup channel.

```python
import json

from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey
from quaspar_shield import Action, sign_action
from quaspar_shield.firewall_ingress import ReceiverGate

# This runnable example creates the sender's key locally. In deployment,
# the sender keeps its private key and the host enrolls only the public key.
sender = Ed25519PrivateKey.generate()
notes = {"daily-note": "The blue folder is on the second shelf."}
job = Action("my-org", "scheduler", "daily", "note.read", "daily-note", "my-agent")
gate = ReceiverGate(
    receiver="my-agent",
    tenant="my-org",
    sender_keys={"scheduler": sender.public_key()},
    allowed_actions=[job],
    handler=lambda approved: notes[approved.resource],
)
signed_request = sign_action(job, sender, audience=gate.audience)
print(gate.dispatch(json.dumps(signed_request)))
```

Every path to this protected operation needs to pass through the gate. The inbox controls requests within one process. Native worker isolation and attachment scanning each require their own host integration. The managed Quaspar service and its private controls are separate from this alpha.

## What each control protects

| When your agent handles | What the trusted host enforces | What you configure |
| --- | --- | --- |
| A signed request | Sender identity, audience, expiry, exact task permissions, replay protection and per-process traffic limits before the handler | Route every path to the action through the same receiver and keep the handler credentials with the host. |
| A two-stage note job | The assigned note digest, permitted connector, authorization at dispatch, one worker snapshot and a signed decision receipt | Run a compatible worker with the native Linux host. To enforce a reviewed worker version, supply its approved SHA-256. |
| An incoming file | Digest match to the authorized action, a clean verdict from the expected scanner, then delivery of those same bytes | Use `ClamAVFileGate.deliver_verified` in the verified handler with a configured local daemon and updated database. |
| A policy-defined exception | A signed approval for that exact request within its time window | Enroll a separate reviewer key and specify which actions qualify. Routine permitted actions need no prompt. |
| A literal provider credential in a parsed connector reply | Suppression of the reply, a signed incident receipt and a persistent block for that assignment | Retain the model host's database and keys across restarts. Revoke or rotate a genuinely exposed credential. A reviewer signs recovery after a correction is checked. |

A signed authorization describes what may run. Judging the factual accuracy of a summary requires an application-specific check. Keep model output as data and route each subsequent action back through the host. The public package implements these local controls. Behavioral scoring, deception, endpoint rotation and hardware enclave attestation belong to the managed design.

## Check security behavior locally

### Multiple agents sharing one receiver

`python -m quaspar_shield.concurrency_check --identities 1000` enrolls 1,000 distinct synthetic signing keys against one real, in-process receiver. It checks allowed and out-of-scope assignments, holds four handler slots open to test overload, verifies recovery after the burst, and tests a separate shared budget of 32. The report gives observed counts. At saturation, even a valid request can receive `busy`. A quiet authorized job is checked both before and after the burst. The test uses at most 16 threads. Distributed network capacity, availability and fleet-wide rate limiting need separate measurements.

### Compare proposals from ChatGPT or Claude

Run `python -m quaspar_shield.proposal_check cases` and give the four fictional tasks to the model. Save its plain JSON response as `response.json`. In the following command, use `chatgpt` or `claude` for the operator-supplied source label.

```sh
python -m quaspar_shield.proposal_check check --source claude < response.json
```

The receiver controls enrollment, assignments and policy. The model chooses among two fictional note names. The report records each proposal, whether policy allowed it, and whether the harmless local callback actually ran. The verifier makes zero provider calls. A source label records the operator's attribution. `python -m quaspar_shield.proposal_check fixture` runs the same check with a built-in example.

### Contain an incident and verify recovery

`python -m quaspar_shield.containment_check` exercises the model connector, native offline worker and signed SQLite ledger with disposable credentials. It simulates a parsed model reply that contains the host’s configured provider credential. The host withholds that reply and commits a signed event and an exact deny rule. It checks the rule before starting new work and again at the transport handoff. Other enrolled assignments retain their existing policy.

The rule survives a restart and covers the tenant, agent, workflow, operation, resource and destination. A misleading message alone cannot install or remove it. The rule applies to future dispatches. Requests already handed to the transport may finish. If a real shared credential appears, its owner must revoke or rotate it and investigate every caller that shared it.

To release the rule, the trusted host uses `NoteModelHost.active_containment(action)` to obtain the incident ID. The reviewer checks a correction in an isolated environment and signs `containment_release_action(action, incident_id, evidence_sha256)` with the enrolled reviewer key and host audience. The host calls `release_containment` with that authorization. A replay for an earlier incident cannot release a later one. The digest binds the operator's decision to the evidence they reviewed. The drill uses a disposable reviewer and a clean staging fixture to demonstrate this sequence. A deployment keeps the reviewer key separate from the worker. A permanent code change goes through regression tests and normal review.

## Run the firewall demo

From this directory, install in a Python 3.11 or newer virtual environment.

```sh
python -m venv .venv
. .venv/bin/activate
python -m pip install .
quaspar-shield-demo
python -m unittest discover -s tests -v
```

The demo creates one receiving agent, enrolls two senders and admits two signed jobs. An unknown sender, a repeated signed job and a request over the shared budget are refused. The local demo generates its own keys and sends no network traffic.

### Put the receiving gate ahead of the model

Create one `quaspar_shield.firewall_ingress.ReceiverGate` in the trusted host for each receiving agent. Connect the agent's actual message entry point to `gate.dispatch(raw_envelope)`. Enroll trusted sender keys and exact permitted actions during setup, and give enrolled senders the gate's current `audience` through the trusted host. The host owns the callback and its credentials. The gate admits signed requests and invokes only the callback the host configured.

The gate limits the combined request rate before parsing or signature verification. It also checks each verified sender's budget and caps the number of concurrent admissions and callbacks. There is no queue of waiting handlers. Signatures expire and replayed requests are rejected. A restart creates a new audience. A handler failure consumes the attempted request; an application with external effects needs its own durable idempotency and reconciliation. Protect transport connections, request size before buffering, read deadlines and upstream bandwidth separately. Different processes have independent budgets. Overload can also delay legitimate senders.

### Inspect attachments before the agent receives them

On Linux, use `quaspar_shield.firewall_files.ClamAVFileGate` with a host-controlled ClamAV daemon. Pass its absolute Unix socket path and expected service UID. `deliver(content, consumer)` streams the immutable bytes to the scanner and calls the consumer with those same bytes only after an unambiguous clean verdict. A flagged file, missing scanner, wrong daemon UID, timeout, or indeterminate answer withholds the file. Keep all other attachment paths closed to that consumer. The operator provides the scanner, its signature updates, archive handling and size limits.

For a signed attachment, pass the resource digest from the verified action to the scanner. In your receiver's host-owned handler, call `scanner.deliver_verified(content, consumer, expected_sha256=action.resource)`. If the retrieved object has different bytes from the one the sender was authorized to inspect, the scanner and the consumer receive no file. Keep the approved object's digest separate from incoming unsigned metadata.

`quaspar-shield-demo --clamd-socket /absolute/path/to/clamd.sock --clamd-uid UID` runs the receiving demo and checks a harmless, signed file job. Substitute the local service's real socket path and numeric UID. The protocol fixtures in the test suite exercise clear, flagged, and unavailable results. Those fixtures do not measure malware-detection accuracy.

### Run a worker with operating-system isolation

On a compatible 64-bit x86 Linux system with Debian-style system Python, bubblewrap, prlimit and libseccomp, use `quaspar-shield-run --self-test` to verify the local worker boundary. Use `quaspar-shield-run agent.py` for a compatible, standalone offline Python file or `quaspar-shield-demo --offline-worker` for a signed job routed through the receiving gate. Charavyuha supplies a read-only program, private scratch space and a clean environment, limits resources and restricts kernel operations. Worker output is untrusted data. The host must launch the worker through Charavyuha. A worker started directly with `python agent.py` runs with its ordinary operating-system permissions. Hosted-model, browser and online-tool access require a separate connector with its own explicit policy.

With the scanner and the offline runner both configured, `quaspar-shield-demo --offline-worker --clamd-socket /absolute/path/to/clamd.sock --clamd-uid UID` exercises the combined flow. The receiving gate verifies the signed job, the scanner checks the named attachment and the host gives the isolated worker a read-only copy of the cleared bytes.

### What was tested for this alpha

On the development host, an allowed signed job completed in the real Linux worker. The worker could use its own scratch directory. The operating system denied the socket and child-process operations exercised by the self-test, and the host-only fixture stayed outside the worker's filesystem view. The worker could read its attachment but could not modify it. The combined signed-job, file-intake and worker flow was also exercised using harmless synthetic scanner replies on connected Unix sockets. A live ClamAV daemon and signature database were unavailable on that host. Before using attachment screening on a deployment, exercise the combined command against that deployment's actual scanner.

The firewall protects paths that the host routes through it. Treat a sender's identity, permission to perform a task, scanner verdict and isolated execution as separate controls. A permitted sender can still supply misleading text. Maintain tool restrictions after content reaches a model. Provider-side denial-of-service controls remain important for traffic that can exhaust a public connection before it reaches this process.

## Summarize one assigned note

On a supported Linux host, this command enrolls an ephemeral developer key, assigns one synthetic note, and runs a replaceable offline agent through one host-owned text connector. The connector in this checkpoint is the OpenAI chat-completions shape. The command uses a deterministic local fixture and does not call OpenAI. A routine job finishes with no review prompt. The printed receipt omits the note, the prompt, and the credential. `response_source` is `fixture`.

```sh
python -m quaspar_shield.model_job --agent examples/summarize_note.py
```

From a wheel installation, `quaspar-shield init my_agent.py` creates the same sample outside the checkout. `quaspar-shield quickstart --agent my_agent.py --json` prints the structured report.

A routine job prints `response_source=fixture` and `Review prompts: 0.` The JSON `protections` list is the diagnostic for that run. It names only the controls that executed: identity, policy, the dispatch-time authorization recheck, the native sandbox, the signed ledger, and one fixture exchange. Approval and the file scanner are listed as not used. This model command does not open a scanner socket.

On the supported Linux host, `quaspar-shield-run --self-test` must execute the kernel profile. Native CI requires the live file-intake acceptance test, so a missing clamd or signature database fails that job. With a host-controlled ClamAV daemon and signature database, the check records the engine version, signature database version, and database date. It gives the isolated worker the exact clean bytes, withholds the harmless EICAR test file, and launches no worker when the scanner is missing or presents the wrong service identity. The ordinary model command does not open a scanner.

Replace `examples/summarize_note.py` to change the worker. The replacement still runs inside the offline profile. It cannot choose the provider, the model, the HTTPS endpoint, or the credential. The host checks the signed job and the note digest before it allows one text request. A changed or out-of-scope request makes no provider call. A repeated signed request does not make a second call. A timeout is recorded for reconciliation and is not retried.

```sh
python -m quaspar_shield.model_job --agent examples/summarize_note.py --check
```

An action the host enrolls as a reviewable exception uses the existing signed approval. This command does not prompt for one. The per-job cost ceiling is not an account-wide budget.

## Try the protected case queue

Run `python -m quaspar_shield.local_demo` for the existing demonstration of automatic and reviewed actions.

The demo routes synthetic cases to their usual destination. It then simulates a volume exception, applies one exact approval, retries the completed request and attempts a prohibited destination. Each successful request writes one row in SQLite. That row is both the queue entry and the record that the request was used. Restarting the host with the same database preserves that record. The demo uses disposable keys for both roles. The separate `quaspar_shield.review` command below supports interactive human review.

### Configure the job once

This example assumes the host already has its own assignment list and enrolled keys. It derives the routine set from those assignments. Agent input must never populate the trusted lists.

```python
from pathlib import Path
from quaspar_shield import Action
from quaspar_shield.local_queue import LocalCaseQueue, ReviewRequired

normal = [Action("org-a", "worker", "intake", "case.queue", case_id, "staff-queue")
          for case_id in assigned_case_ids]
exception = Action("org-a", "worker", "intake", "case.queue", "case-001", "finance-review")
queue = LocalCaseQueue(
    Path("cases.db"), audience="intake-deployment", allowed_actions=[*normal, exception],
    routine_actions=normal, routine_limit=100, window_seconds=60,
    agent_public_key=worker_public_key, reviewer="supervisor",
    reviewer_public_key=supervisor_public_key,
)
try:
    receipt = queue.enqueue(signed_request_json)
except ReviewRequired as pending:
    # Only this exception is eligible for a review card in the host application.
    show_or_update_review(pending.request_digest, pending.reason)
```

Choose a volume limit from the real workflow's expected load. The example limit of 100 is illustrative. The limit counts successful writes for this deployment, tenant and agent within the rolling window. Each retry is evaluated against the current policy and window. A one-time approval covers the exact request and never widens the routine policy. Setting `routine_limit=None` omits the volume check. Enroll a nonempty routine set to enable automatic execution. Older integrations that supply only `allowed_actions` retain their approval requirements.

The queue returns the same request digest for repeated attempts that still need review, so an application can update the same card. A volume spike may include many distinct requests. A host can group those into one incident notification and still require an exact approval for any individual exception it releases. Authentication failures and actions outside the assigned job are refusals. Present only `ReviewRequired` to a human.

The queue protects one operation with an effect entirely inside SQLite. An agent with direct write access to the database or access to the reviewer’s signing key can act outside that boundary. To use the same approach with an email or payment provider, the provider credentials and dispatch path must be controlled separately, and approvals must cover all details that affect execution.

The host assigns each independent queue a distinct audience and preserves its database. Deleting a queue row or restoring an earlier copy also removes its record of use.

To see the underlying signature protocol on its own, run `python -m quaspar_shield.demo`.

## Use the SDK

```python
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey
from quaspar_shield import Action, sign_action, sign_approval, verify_action, verify_approval

# Disposable keys for this example. Deployment requires separate owners and enrollment.
worker = Ed25519PrivateKey.generate()
reviewer = Ed25519PrivateKey.generate()
action = Action("org-a", "worker", "intake", "record.release", "case-001", "review-queue")
request = sign_action(action, worker)
shown_to_reviewer = verify_action(request, worker.public_key())
# In a real flow, obtain an explicit decision about all six fields here.
approval = sign_approval(request, reviewer, reviewer="operator")
assert verify_approval(approval, request, reviewer.public_key()) == "operator"
```

The SDK defaults to the local audience `quaspar-shield-local`. Each actual deployment needs a unique trusted audience. Pass it as `audience=` to all four action and approval signing and verification functions, and `--audience` to the review CLI. A signature intended for staging must fail in production even if someone accidentally enrolls the same key there.

The verifier needs an independent, tenant-scoped key registry and permission map. The host must verify the agent signature and any necessary approval with its own trusted clock before execution and atomically consume the request at its tool boundary. SDK verification by itself has no side effects and stores no replay state. The two-minute validity window uses wall-clock time, with no grace interval. A reviewer who needs longer can review a fresh request.

### Offline operator review

A reviewer can sign on a separate terminal using an independently provisioned agent public key and their own encrypted Ed25519 PEM. Configure the expected tenant, agent and audience from enrollment. The command displays the audience, six action fields and expiry, then asks the reviewer to type a request-specific confirmation. It writes the signed approval JSON to stdout only after confirmation.

```sh
python -m quaspar_shield.review request.json \
  --tenant org-a --agent worker --reviewer operator \
  --agent-public-key worker-public.pem \
  --reviewer-private-key operator-encrypted.pem > approval.json
```

This authenticates possession of the enrolled review key. Hardware-backed user presence, enterprise login, revocation and org-wide reviewer permissions require a host integration.

## Wire format v1

The signed bytes are ASCII JSON containing every envelope field except `signature`. Sort keys recursively, use comma and colon separators without spaces, and omit a trailing newline. Identifiers use `[a-z0-9][a-z0-9._-]{0,63}`. Each signature is 128 lowercase hex characters. Each nonce is 16 random bytes encoded in lowercase hex. Time fields are integer UTC Unix seconds. Accept a request only where `issued_at <= now < expires_at`; validity intervals are at most 120 seconds. Use `load_envelope` at transport ingress. It bounds input to 4 KiB and rejects duplicate JSON keys. Signature verification rejects extra fields.

| Signed purpose | Additional payload |
| --- | --- |
| `quaspar.action` | `audience` and `action` with tenant, agent, workflow, operation, resource and destination |
| `quaspar.approval` | `reviewer` and `request_digest`, the lowercase SHA-256 digest of the full canonical signed request including its signature |

Both have signed fields `version` (integer 1), `purpose`, `nonce`, `issued_at`, and `expires_at`. An approval's entire validity interval must fit inside the request interval. All semantics of a supported tool action must be determined by the signed fields. An adapter that introduces mutable payloads, recipient lists, amounts or other parameters needs a versioned binding covering that content before it can be supported.

## Add a restrictive check

`layers_allow(action, layers)` applies between one and 32 trusted synchronous Python callables to an already authenticated, in-scope action. Every hook must return the boolean `True`. A veto, an exception or an invalid result blocks the request. For example, a host can add `lambda a: a.destination == "review-queue"` after its own mandatory policy. Hooks run as trusted application code and should return promptly.

## Audit checkpoints

`quaspar_shield.checkpoints.sign_checkpoint(stream, count, head, signing_key)` signs a named journal head. `verify_checkpoint(proof, pinned_public_key, stream=...)` returns the authenticated event count and chain head. An independent verifier must also recompute the journal and compare both values. Pin the expected stream and signing key through a trusted channel, retain checkpoints separately from the journal, and keep a freshness record. An older, valid signature remains valid. The signed checkpoint authenticates a point in history and does not establish the truth of an event, the identity of a person or the completeness of external tool activity.

## Security reports and license

Report vulnerabilities privately at bhavesh@quaspar.com. [Quaspar's security policy](https://quaspar.com/security)

Distributed under the Apache License, Version 2.0. The license is included with the wheel and source archive.
