Metadata-Version: 2.5
Name: ragleap-security
Version: 0.4.0
Summary: Small, auditable security primitives for the ragleap libraries: immutable tenant scopes, a tamper-evident hash-chained audit log, secret handling and redaction, hard input limits, rate limits, keys with rotation, file integrity manifests, SSRF-safe outbound HTTP, canary tokens that detect and trace leaks (they never prevent them) and optional authenticated encryption. Standard library only, except optional AES-256-GCM encryption (extra: crypto). Not independently audited.
Project-URL: Homepage, https://github.com/ragleap/ragleap-core
Project-URL: Repository, https://github.com/ragleap/ragleap-core
Project-URL: Issues, https://github.com/ragleap/ragleap-core/issues
Author: RagLeap
License-Expression: MIT
Keywords: audit-log,encryption,integrity,llm,multi-tenant,rate-limit,redaction,secrets,security,self-hosted
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Topic :: Security
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Requires-Python: >=3.10
Provides-Extra: crypto
Requires-Dist: cryptography>=42.0.0; extra == 'crypto'
Provides-Extra: test
Requires-Dist: pytest>=8.0.0; extra == 'test'
Description-Content-Type: text/markdown

# ragleap-security

Small, auditable security primitives for the ragleap libraries. The core is standard library only; encryption is an optional extra. Alpha. **Not independently audited**: see `docs/threat-model.md` for exactly what is and is not defended.

## What is in 0.4.0

From 0.1.0:

- `Scope`: an immutable tenant scope (tenant, subject, agent, session) with an unambiguous key, `covers`, `narrow` and `require_scope`, so stores can refuse to work without one.
- `AuditLog`: an append-only JSON Lines log with a SHA-256 hash chain and `verify()`. Tamper-evident, not tamper-proof (see the threat model).
- `SecretStr`, `from_env`, `redact`: secrets that do not print themselves, read from the environment by name, and a heuristic redactor for logs.
- `check_size`, `check_json_shape`, `bounded_read`, `Deadline`: hard limits for untrusted input.

New in 0.2.0:

- `Key`, `KeyRing`: a 32-byte key with an id that never prints its value, and a ring of keys for rotation.
- `ragleap_security.crypto` (needs `pip install ragleap-security[crypto]`): `encrypt`, `decrypt`, `encrypt_with_passphrase`, `decrypt_with_passphrase`, `reencrypt`, `key_id`. AES-256-GCM through the `cryptography` package, a versioned envelope, and a context (for example a `Scope`) that must match on decrypt.
- `RateLimiter`, `SQLiteRateLimiter`: a token bucket per key, in memory or shared between processes on one machine. They refuse when they cannot decide.
- `build_manifest`, `verify_manifest`, `Manifest`, `file_digest`: detect that files changed, with an optional HMAC so the manifest itself cannot be edited unnoticed.

New in 0.3.0 and 0.4.0 (standard library only, each imported on its own):

- `ragleap_security.net`: `SafeFetcher`, `FetchPolicy`. Outbound HTTP (GET and HEAD) that an attacker cannot point at your own network: a per-tenant host allowlist (deny by default), strict URL parsing, every resolved address checked, the connection pinned to the checked address, redirects re-checked on every hop, one deadline, a body cap, TLS verification always on, no proxy from the environment. Every refusal is a fixed reason code; the audit record never holds a path, query, header or body.

    fetcher = SafeFetcher(lambda scope: FetchPolicy(allow_hosts=("api.example.com",)), audit=log)
    res = fetcher.get(Scope("acme"), "https://api.example.com/v1/items")   # NetError(reason) on any refusal

- `ragleap_security.canary` (0.4.0): `CanaryIssuer`, `MemoryCanaryStore`, `SQLiteCanaryStore`. Tripwire tokens that **detect and trace a leak; they never prevent copying**. You plant a token (`rlc1_` plus 26 characters: a random id and a MAC) in a system prompt, a memory entry, a tool description or a document, and scan model answers, outbound tool arguments, logs or exports for it. A token belongs to one `Scope`. A hit is `own` (a canary of this scope or a narrower one) or `foreign` (another scope's valid canary in this scope's data: a cross-tenant leak signal that reveals neither the owner nor the id to the caller). Lookalikes are rejected by the MAC before any store lookup; matching survives a changed case, fullwidth forms and hidden characters. The token is never stored. Audit events hold ids, labels and source names, never text or tokens, and a failed audit write fails the call.

    from ragleap_security.canary import CanaryIssuer, MemoryCanaryStore

    issuer = CanaryIssuer(key, MemoryCanaryStore(), audit=log)
    canary = issuer.issue(Scope("acme"), label="system-prompt")      # plant canary.token somewhere
    hits = issuer.scan(model_answer, Scope("acme"), source="model-output")   # [CanaryHit(kind="own", ...)]

What a hit proves: the string reached the place you scanned. Not who put it there. A missing hit proves nothing: a model may paraphrase or drop a token, and an attacker may transform or filter it. There is no network beacon.

Nothing in 0.1.0, 0.2.0 or 0.3.0 changed. The new modules are additive.

## Examples

Encrypt data for one tenant and rotate keys:

    from ragleap_security import Key, KeyRing, Scope
    from ragleap_security.crypto import decrypt, encrypt, reencrypt

    scope = Scope("acme", subject="alice")
    old = Key.generate("2026-10")
    box = encrypt(old, b"private notes", scope)           # the scope is authenticated too
    assert decrypt(old, box, scope) == b"private notes"   # a different scope would fail

    new = Key.generate("2026-11")
    ring = KeyRing([new, old])                             # the first key is active
    box = reencrypt(ring, box, scope)                      # now encrypted with "2026-11"

Keys come from the environment by variable name (base64), never from code:

    key = Key.from_env("MY_APP_KEY", "2026-11")

Rate limit by scope:

    from ragleap_security import RateLimiter, Scope

    limiter = RateLimiter(rate=5, burst=10)               # 5 per second, bursts of 10
    limiter.require(Scope("acme", subject="alice"))       # raises RateLimitError when refused

Detect changed files:

    from ragleap_security import Key, build_manifest, verify_manifest

    key = Key.from_env("MY_APP_KEY", "manifest")
    manifest = build_manifest("app/", key=key, exclude=["__pycache__"])
    result = verify_manifest("app/", manifest, key=key, exclude=["__pycache__"])
    assert result.ok, (result.changed, result.missing, result.extra)

## What this does not do

Encryption does not protect data while the program is running, and does not help against someone who has the key. Rate limits do not stop attacks spread over many machines. An integrity check detects changes; it does not prevent anyone from copying your code, models or data. The threat model lists the rest.

## Verifying it yourself

    pip install -e ".[test,crypto]"
    pytest
    python scripts/mutation_check.py   # breaks one protection at a time; every mutation must be killed

Without the `cryptography` package the crypto tests are skipped and everything else still runs.

## Not in 0.4.0

Watermarks and network beacons for canaries (deliberately not built: weak evidence, and no infrastructure for beacons), `pin`, POST and other methods in `net`, public-key signatures, streaming encryption for very large files, a policy engine, output detectors and a red-team harness are planned (issue #899) and not available yet.
