Metadata-Version: 2.4
Name: envchain-sops
Version: 2.0.0
Summary: Portable SOPS-backed environment profiles for Linux and Windows
Author: Grégoire Compagnon
License-Expression: MIT
Project-URL: Homepage, https://github.com/obeone/envchain-sops
Project-URL: Issues, https://github.com/obeone/envchain-sops/issues
Keywords: envchain,sops,secrets,environment-variables,dotenv,gpg,age
Classifier: Development Status :: 4 - Beta
Classifier: Environment :: Console
Classifier: Intended Audience :: Developers
Classifier: Intended Audience :: System Administrators
Classifier: Programming Language :: Python :: 3
Classifier: Operating System :: Microsoft :: Windows
Classifier: Operating System :: POSIX :: Linux
Classifier: Topic :: Security :: Cryptography
Classifier: Topic :: Utilities
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Dynamic: license-file

# envchain-sops

[![PyPI](https://img.shields.io/pypi/v/envchain-sops)](https://pypi.org/project/envchain-sops/)
[![Tests](https://github.com/obeone/envchain-sops/actions/workflows/test.yml/badge.svg)](https://github.com/obeone/envchain-sops/actions/workflows/test.yml)
![Python](https://img.shields.io/badge/Python-3.10+-blue?logo=python&logoColor=white)
![SOPS](https://img.shields.io/badge/SOPS-3.11+-orange)
![Platforms](https://img.shields.io/badge/platforms-Linux%20%7C%20Windows-lightgrey)
![Dependencies](https://img.shields.io/badge/runtime%20dependencies-none-green)
![License](https://img.shields.io/badge/License-MIT-green)

Run a command with SOPS-encrypted environment profiles on Linux or Windows.
The same Python implementation powers both systems. Installing the package
creates `envchain` on Linux and a native `envchain.exe` launcher on Windows.

---

## 🚀 Features

| | Feature | Details |
| --- | --- | --- |
| 🔐 | Encrypted profiles | SOPS dotenv files, PGP, age or cloud KMS recipients |
| 🧩 | Profile stacking | `first,second` loads left to right, last value wins |
| 🖥️ | One codebase | Same module on Linux and Windows, standard library only |
| 🎯 | No shell in between | Arguments, streams and exit status pass through untouched |
| ✍️ | Safe updates | `--set` locks, stages, verifies and replaces atomically |
| 🧱 | Recipients preserved | Existing profiles keep their recipients on update |
| 🙈 | No plaintext on disk | Decrypted data stays in pipes and memory |

---

## 🤔 Why this version

The original [`envchain`](https://github.com/sorah/envchain) keeps secrets in
the operating system vault: the macOS Keychain, or a D-Bus Secret Service
such as GNOME Keyring on Linux. That design needs a desktop session with an
unlocked keyring, which is exactly what a server, an SSH session, a container
or a Windows machine does not have.

This version keeps the same command line and swaps the vault for
SOPS-encrypted files.

| | Original `envchain` | `envchain-sops` |
| --- | --- | --- |
| Storage | OS vault (Keychain, Secret Service) | SOPS-encrypted dotenv files |
| Headless Linux, SSH, containers | Needs a running, unlocked keyring | Works with a PGP or age key, or a cloud identity |
| Windows | No backend | Supported |
| Moving to another machine | Re-enter every secret | Copy or sync the encrypted files |
| Sharing a profile | Not possible | Add a recipient to the profile |
| Version control | Not possible | Profiles are ciphertext, safe to commit |
| Install | Compiled C, needs libsecret and readline on Linux | One Python file, standard library only |

### Secrets that only exist while you are connected

With PGP recipients, the private key does not have to live on the server at
all. Forward your local `gpg-agent` over SSH: the server holds the encrypted
profiles and your public key, and every decryption is performed by the agent
on your own machine, through the forwarded socket.

| Situation | What the server can do |
| --- | --- |
| You are connected over SSH | Decrypt profiles through your forwarded agent |
| You disconnect | Nothing: the socket is gone, profiles are ciphertext |
| The disk, a backup or a snapshot leaks | Nothing: no private key was ever stored there |
| A cron job or a compromised service runs later | Nothing, for the same reason |

The secrets are usable exactly as long as you are present, and unreachable
the rest of the time. A vault unlocked at boot, or a key file left on the
server, cannot offer that. A hardware token on your machine keeps working
too, with its PIN or touch confirmation.

Find the socket paths, on each side:

```bash
gpgconf --list-dir agent-extra-socket   # on your machine
gpgconf --list-dir agent-socket         # on the server
```

Then forward the first onto the second in `~/.ssh/config`:

```text
Host myserver
    RemoteForward <server agent-socket> <local agent-extra-socket>
```

On the server, import your public key (`gpg --import`) and set
`StreamLocalBindUnlink yes` in `sshd_config`, so a stale socket from a
previous session does not block the next forward.

While the session is open, anyone able to reach the forwarded socket on the
server (root included) can ask your agent to decrypt. Forward only to hosts
you trust, and prefer a key that asks for confirmation on each use.

### On macOS, use the Keychain version

macOS is deliberately not a target here. A Mac user is always logged in, so
the login Keychain is already unlocked and nothing beats it: use
[envchain-xtra](https://envchain-xtra.org/), the maintained Keychain fork,
which installs the same `envchain` command. Keep `envchain-sops` for the
machines where no such vault is open.

---

## ⚡ Quickstart

```bash
uv tool install envchain-sops
envchain --set github GITHUB_TOKEN
envchain github gh repo list
```

---

## 📦 Installation

Requirements: Python 3.10 or newer, SOPS 3.11 or newer in `PATH`, and access
to the keys or cloud identity needed by your existing SOPS profiles. GnuPG is
required for PGP recipients; age recipients do not require GnuPG.

Install SOPS using the
[official installation instructions](https://getsops.io/docs/).

### Linux

Install the released package from PyPI with `uv tool`:

```bash
uv tool install envchain-sops
envchain --version
```

Or with `pipx`:

```bash
pipx install envchain-sops
envchain --version
```

To install a checkout instead, replace `envchain-sops` with `.` in either
command.

Both install `envchain` in an isolated environment and expose it on `PATH`.

For an existing script installation, `envchain_sops.py` is also a standalone
executable script. It only imports the Python standard library. Copied that
way it carries no package metadata, so `--version` prints `0+unknown`.

### Windows

Open PowerShell in the directory that will hold the virtual environment:

```powershell
py -m venv .venv
.\.venv\Scripts\python.exe -m pip install envchain-sops
$env:PATH = "$PWD\.venv\Scripts;$env:PATH"
envchain --version
```

This tool has no Python runtime dependencies.

The `PATH` assignment above lasts for the current PowerShell session. To use
the command in future sessions, add the virtual environment's `Scripts`
directory to your user `PATH`, or use its absolute executable path.

Your PGP or age key must also be available on Windows. Copying encrypted
profiles alone does not provide the ability to decrypt them.

---

## ⚙️ Configuration

| Setting | Default | Purpose |
| --- | --- | --- |
| `ENVCHAIN_DIR` | see below | Directory holding the `PROFILE.env` files |
| `.sops.yaml` | none | Creation rule for new profiles, searched by SOPS from the profile directory |

Without `ENVCHAIN_DIR`, profiles live in the user's configuration directory:

| Platform | Default profile directory |
| --- | --- |
| Linux | `$XDG_CONFIG_HOME/envchain`, which is `~/.config/envchain` unless you moved it |
| Windows | `%APPDATA%\envchain` |

Set `ENVCHAIN_DIR` once, in your shell profile, to keep them elsewhere, for
example in a synced or versioned directory:

```bash
export ENVCHAIN_DIR="$HOME/secrets/shared"
```

```powershell
$env:ENVCHAIN_DIR = 'D:\secrets\shared'
```

Profile names are flat ASCII names. Path traversal, empty comma elements,
Windows device names and trailing dots are rejected on both platforms.

On Linux, newly written profiles use mode `0600`. Windows files inherit their
directory's ACL; keep the profiles directory restricted to your Windows user.
SOPS encryption-selection rules still apply, including rules that
deliberately leave selected fields unencrypted. Configure those rules
consistently with the sensitivity of your environment variables.

---

## 🧰 Commands

```text
envchain PROFILE[,PROFILE...] [--] COMMAND [ARGUMENT...]
envchain --set [--noecho|-n] PROFILE VARIABLE [VARIABLE...]
```

| Command | Effect |
| --- | --- |
| `envchain PROFILE COMMAND` | Run `COMMAND` with the profile's variables |
| `envchain A,B -- COMMAND` | Stack profiles; `--` ends envchain's own options |
| `envchain --set PROFILE VAR...` | Prompt for each value and update the profile |
| `envchain --set --noecho PROFILE VAR` | Same, with hidden input (`-n` for short) |
| `envchain --version` | Print the version |
| `envchain --help` | Print usage |

### Run commands

```bash
envchain aws,cloudflare terraform plan
envchain github gh pr list
envchain staging,postgres -- psql -d app
```

```powershell
envchain aws,cloudflare terraform plan
envchain github pwsh -File .\release.ps1
envchain github powershell.exe -NoProfile -File .\release.ps1
envchain azure pwsh -NoProfile -Command 'Get-AzResourceGroup'
```

Profiles load from left to right. The last value wins when several profiles
define the same variable. Nested invocations remain supported. On Windows,
environment variable names are case-insensitive; a single profile must not
contain two names that differ only in case. When updating an existing name
with `--set`, use the spelling already stored in the profile.

Programs receive arguments directly, without a shell added by envchain.
Normal shell quoting still applies to what you type. PowerShell 7.3 or newer
is recommended for its modern handling of native command arguments. Windows
PowerShell 5.1 can discard empty arguments or alter embedded quotes before
envchain receives them. See Microsoft's
[native argument parsing documentation](https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_parsing).

PowerShell aliases, functions and cmdlets run inside an explicitly launched
PowerShell process, as shown above. For batch files, launch their
interpreter explicitly, for example `envchain github cmd.exe /c build.cmd`.
In that case, `cmd.exe` applies its own parsing rules.

### Update profiles

```text
envchain --set cloudflare CLOUDFLARE_API_TOKEN CLOUDFLARE_ACCOUNT_ID
```

Values are echoed when typed in a terminal, like envchain on macOS, so a
pasted value can be checked before it is saved. Pass `--noecho` (or `-n`) to
hide them. When stdin is redirected, provide one line per variable. Values
are never passed on a command line. Repeated variable names prompt once.
Values must be single lines without NUL characters; empty values are
supported.

New profiles use the matching `.sops.yaml` creation rule. Existing profiles
keep their recipients even when creation rules change. Updates lock the
profile, stage ciphertext in the same directory, verify the decrypted result,
flush the staging file and replace the destination atomically. Failed
operations leave the existing profile unchanged. Lock files persist, but the
operating system releases their locks when the process exits or crashes.

### Development

| Command | Purpose |
| --- | --- |
| `python -m unittest discover -s tests -v` | Run the whole suite |
| `python -m unittest discover -s tests -k NAME` | Run the tests matching `NAME` |
| `python envchain_sops.py --version` | Run from the source tree, no install |
| `uv build` | Build the wheel and the source distribution |

### Releases

The version is the git tag, read at build time by `setuptools-scm`. Nothing
in the source holds a number to bump. Publishing a GitHub release on a tag of
the form `v1.2.3` builds version `1.2.3`, uploads it to PyPI through trusted
publishing and attaches the wheel and the source distribution to the release.
Builds between two tags get a development version on their own, such as
`1.2.4.dev3`.

```bash
gh release create v1.2.3 --generate-notes
```

Integration tests require SOPS and GnuPG in `PATH`. They generate disposable
recipients and never read personal profiles or use personal private keys.

The included GitHub Actions workflow runs Python 3.10 and 3.13 on Ubuntu and
Windows, including a native PowerShell invocation of the installed launcher.
Windows execution has not been validated in the originating Linux session;
the workflow must run on a Windows runner to establish that result. See
`VERIFICATION.md` for what each release actually checked.

---

## 🔒 Security and process behavior

Decrypted data passes through process pipes and memory. The wrapper does not
create plaintext temporary files or print decrypted values. SOPS diagnostics
are suppressed because they may contain sensitive data. The child command's
own output is inherited and remains the command's responsibility.

All profiles must decrypt successfully before the command starts. The
caller's environment is unchanged. Child stdin, stdout, stderr and exit
status pass through. POSIX uses process replacement to retain PID and signal
behavior. Windows waits for the child; console Ctrl+C reaches the child, with
a five second cleanup interval before termination if it remains running.

---

## 🏗️ Architecture

```mermaid
flowchart TB
    CLI[envchain CLI] --> V[Validate profile and variable names]
    V --> RUN{Mode}

    subgraph Run [Run a command]
        D[sops decrypt each profile] --> M[Merge left to right]
        M --> P{Platform}
        P -->|POSIX| X[execvpe, replaces the process]
        P -->|Windows| W[Popen, wait, forward exit status]
    end

    subgraph Set [Update a profile]
        L[Lock profile] --> R[Decrypt current values]
        R --> I[Read new values from terminal or stdin]
        I --> S[Stage ciphertext next to the profile]
        S --> C[Decrypt staging file and compare]
        C --> A[fsync, then atomic replace]
    end

    RUN -->|PROFILE COMMAND| D
    RUN -->|--set| L
    D -.-> SOPS[(SOPS)]
    R -.-> SOPS
    S -.-> SOPS
    C -.-> SOPS
```

---

## 📝 License

MIT, see [LICENSE](LICENSE).

Made by Grégoire Compagnon (obeone)
