Metadata-Version: 2.5
Name: dynv
Version: 0.1.0
Summary: Live, verified environment variables from Dynv, with or without `dynv run`
Project-URL: Homepage, https://dynv.dev
Project-URL: Documentation, https://dynv.dev/docs/sdk/python/
Author: Dynv
License-Expression: MIT
License-File: LICENSE
Keywords: configuration,dynv,environment,secrets,zero-knowledge
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Topic :: Security :: Cryptography
Classifier: Typing :: Typed
Requires-Python: >=3.9
Requires-Dist: cryptography>=42
Description-Content-Type: text/markdown

# Dynv Python SDK

Live, restart-free reads of a process's Dynv environment, in Python. One API, three modes:

- **agent** (preferred): under `dynv run`, the client reads the local agent (`DYNV_AGENT_URL`, `DYNV_AGENT_KEY`). It holds no Dynv token and does no crypto.
- **direct**: with a process token and no `dynv` binary, the client fetches `/v1/self` and decrypts and verifies it in-process, exactly as `dynv run` does ([docs/PROTOCOL.md](../../docs/PROTOCOL.md)): signatures, rollback floors, shared groups, templates, watch, and a ciphertext-only cache.
- **env**: neither configured. `get()` reads the process environment and no events fire, so the same code runs in local development.

Python 3.9 or newer. The only runtime dependency is `cryptography`.

## Install

> **Publishing soon.** `dynv` is not on PyPI yet. Until then, install the package from a repository checkout with `pip install ./sdk/python`.

```sh
pip install dynv
```

## Quick start

```python
import dynv

env = dynv.connect(process="web")

proxy = env.get("PROXY_SERVER")          # None when unset
dsn = env.require("DATABASE_URL")       # raises MissingVariableError when unset

env.on("PROXY_SERVER", lambda value, change: rebuild_proxy(value))
env.on_change(lambda event: print("changed keys:", event.changed))
```

**Agent mode:** start the app with `dynv run -- python app.py`. `connect()` sees `DYNV_AGENT_URL` and reads the agent. A change to a restart-mode variable restarts the app (the supervisor does it).

**Direct mode:** set `DYNV_URL` explicitly (`https://api.dynv.dev` for Dynv Cloud), and give the app a process token and, ideally, a cache file:

```sh
DYNV_URL=https://api.dynv.dev DYNV_TOKEN_FILE=/run/secrets/dynv DYNV_PROCESS=web DYNV_CACHE=/var/cache/web.dynv python app.py
```

A restart-mode change produces a `ChangeEvent` with `restart=True`. Set `on_restart="exit"` to have the client SIGTERM the process so its orchestrator restarts it.

## Rollover values

`all(key)` returns the current value followed by live fallback values, newest first (`[]` when unset). For Django, keep the current key in `SECRET_KEY` and give the older values to `SECRET_KEY_FALLBACKS`:

```python
SECRET_KEY = d.require("SECRET_KEY")
SECRET_KEY_FALLBACKS = d.all("SECRET_KEY")[1:]
```

### The direct-mode tradeoff

In direct mode **the app holds the token**. Anything that can read its memory or environment (a dependency that dumps env, an error reporter, a debugger, a child process) can take it and keep fetching and decrypting this service's variables until you revoke it. Under `dynv run` the token stays with the supervisor and the app only sees a loopback agent key. So: prefer `dynv run`; in direct mode use one token per deployment, prefer `DYNV_TOKEN_FILE` to `DYNV_TOKEN`, and let the client remove `DYNV_TOKEN` from `os.environ` as soon as it is read, even if the token is then refused (the default). Master tokens (`dynv_mt_…`) are refused. See PROTOCOL.md §1.

## Asyncio

`aconnect()` accepts the same options as `connect()` and runs the blocking first fetch in a worker thread. An `async def` callback must be registered from inside a running event loop; it runs on that loop. Synchronous callbacks run on the watcher thread.

```python
import asyncio
import dynv

async def main():
    env = await dynv.aconnect(process="web")

    async def changed(event):
        print("changed keys:", event.changed)

    env.on_change(changed)
    async for event in env.changes():
        print("v", event.version, "restart:", event.restart)

asyncio.run(main())
```

## API

| | |
|---|---|
| `connect(**options) -> Dynv` | picks the mode, loads the first snapshot, starts watching |
| `aconnect(**options) -> Dynv` | the same connection for asyncio; the first fetch runs in a worker thread |
| `get(key, default=None)` | current value, or the default when unset |
| `require(key)`, `env[key]` | current value, or `MissingVariableError` naming the key |
| `key in env` | whether `get(key)` has a value |
| `pick(*keys)` | several keys from one consistent snapshot |
| `source(key)` | the shared group that provides `key`, or `None` |
| `is_template(key)`, `unresolved()` | templates (`${NAME}` references) and those that do not resolve right now |
| `snapshot()` | a copy of the current snapshot in the agent's shape |
| `mode`, `live`, `version` | current mode, whether Dynv supplies values, and the strictly increasing local revision |
| `on(key, fn)` | calls `fn(value, KeyChange)` when `key` changes; `value` is `None` after removal |
| `on_change(fn)` | calls `fn(ChangeEvent)` after every applied change |
| `on_error(fn)` | API or agent errors and refused updates; the client keeps the last good environment and retries |
| `changes()` | async iterator over `ChangeEvent` objects on the calling event loop |
| `close()` | stops watching; values stay readable |

All three event registrations return an unsubscribe function. None fire for the first snapshot. `Dynv` is thread-safe and works as a sync or async context manager. `ChangeEvent` contains `version`, the sorted `changed` key names, and `restart`; `KeyChange` contains `key` and `version`.

A key Dynv has managed (a value or a tombstone) without a value reads as unset, never as the inherited environment. Other keys fall back to `os.environ`. By default the first snapshot mirrors every value into `os.environ` and clears managed tombstones, including restart-mode and dangerous startup/code-loading keys. After that, only hot, non-dangerous keys are mirrored: changes and removals of restart-mode or dangerous keys leave `os.environ` untouched until a restart. `get()`, the other read APIs, and change events still reflect every accepted update immediately.

Mirroring is not a safe live-configuration channel for native code. C extensions, cgo, or libc code may cache values or `environ` pointers and read stale or racy data; mutating the C environment while other threads access it is not generally thread-safe. Native code should use explicit reconfiguration or a restart rather than relying on live `getenv()` reads. Pass `mirror_to_environ=False` to disable all environment mirroring.

Errors: `RefusedError` with a stable `code` (`malformed_id`, `envelope`, `gen_mismatch`, `blob`, `process_name`, `rollback`, `fork`) and `HttpError` with `status`. The client never takes the app down on a refused or failed update: it keeps the last good environment and retries with backoff.

## Options

| Keyword | Default | |
|---|---|---|
| `mode` | `"auto"` | agent if `DYNV_AGENT_URL` is set, else direct if a token is set, else env. Or `"agent"`, `"direct"`, `"env"` |
| `token` | `DYNV_TOKEN`, else the trimmed contents of `DYNV_TOKEN_FILE` | a process token (`dynv_pt_…`) |
| `process` | `DYNV_PROCESS` | expected process name; anything else is refused. Recommended |
| `url` | `DYNV_URL`; required in direct mode (`https://api.dynv.dev` for Dynv Cloud) | HTTPS only; HTTP only to loopback or with `allow_insecure_http`. No credentials, query or fragment |
| `cache` | `DYNV_CACHE` | ciphertext-only cache (`dynv run --cache` format): offline boot and a durable rollback floor. Recommended |
| `require` | `False` | fail `connect()` when Dynv is unreachable and there is no cache |
| `boot_timeout` | `10.0` | seconds for the first live fetch; after it, the client boots on the cache |
| `poll_interval` | `120.0` | seconds between polls with `long_poll=False`, and the longest error backoff |
| `long_poll` | `True` | false polls `GET /v1/self`, for networks that kill idle connections |
| `allow_insecure_http` | `DYNV_ALLOW_INSECURE_HTTP=1` | plain HTTP to a trusted private network |
| `scrub_token_from_env` | `True` | remove `DYNV_TOKEN` from `os.environ` once read |
| `on_restart` | `"ignore"` | `"exit"`: direct mode SIGTERMs self when a restart-mode variable changes |
| `mirror_to_environ` | `True` | mirror the full first snapshot; later mirror only hot, non-dangerous changes and removals. `False` disables all writes to `os.environ` |
| `on_error` | `None` | like `Dynv.on_error`, but also sees errors during `connect()` |
| `log` | warnings on the `dynv` logger | diagnostics: key names and codes only, never values |
| `agent_url`, `agent_key` | `DYNV_AGENT_URL`, `DYNV_AGENT_KEY` | local agent connection |
| `watch` | `True` | false loads the first snapshot without starting the watcher |

## Command-line helper

The package can print the verified environment as JSON in direct or agent mode. It reads the same `DYNV_*` variables as `connect()`:

```sh
python -m dynv env     # one snapshot
python -m dynv watch   # the first snapshot, then one JSON line per change
```

## Development

Install `cryptography` and the package (or set `PYTHONPATH=src`), then run the unit tests:

```sh
cd sdk/python
python -m unittest discover -s tests
```

The tests cover direct, agent and env modes, asyncio, templates, cache and rollback behavior against fake API and agent servers. Cross-SDK and live-server tests are in `tests/e2e/` at the repository root.
