# Rust

Documentation version: 0.3.1.

> [!NOTE]
> SDKs are read-only. The CLI creates vaults and sets secret values;
> applications do not need a CLI process running alongside them.

## Project setup options

1. **Option 1: Set up with the CLI.** Follow the [CLI installation guide](https://sourceorrery.ai/getting-started/#install),
   then create the vault and set its secret values in your own terminal.
2. **Option 2: Set up with an AI coding agent.** Run
   `sourceorrery init --integration all`, then ask your agent to set up
   SourceOrrery for the project without showing values. You keep vault
   keys and new values private. [The agent setup guide](https://sourceorrery.ai/guides/ai-agents/)
   works with an existing CLI installation.

## Install




### From crates.io

```bash
cargo add sourceorrery@0.3.1
```

or, in `Cargo.toml`:

```toml
[dependencies]
sourceorrery = "0.3.1"
```

[`sourceorrery` on crates.io](https://crates.io/crates/sourceorrery) is
the read-only client every other SDK is built on. It depends on
`sourceorrery-storage` directly (no C ABI in between), so it needs what
the CLI needs to build: Rust 1.91.1 or newer and a C compiler for the
bundled SQLite, and on Linux `pkg-config` and `libdbus-1-dev` for the
Secret Service. The `os-keyring` feature (default) enables the OS
credential store and `remote` (default) the providers; for headless
servers that open vaults with their recovery keys only, turn them off with
`cargo add sourceorrery --no-default-features`, which also drops the D-Bus
requirement.

### From the v0.3.1 tag

Depend on the tag the
[v0.3.1 release](https://github.com/Netizine/sourceorrery/releases/tag/v0.3.1)
was cut from:

```toml
[dependencies]
sourceorrery = { git = "https://github.com/Netizine/sourceorrery", tag = "v0.3.1" }
```

### From source

See [Building from source](https://sourceorrery.ai/sdks/rust/#building-from-source) below.

## Get a secret

```rust
use sourceorrery::SecretReader;

let reader = SecretReader::open("development")?;
let secret = reader.get("database-password")?;
connect(secret.value.expose());
// `secret.value` is a SecretBytes: zeroised on drop, redacted in Debug, no Serialize
```

With the default options, `SOURCEORRERY_HOME` locates the vault;
this machine's key in the OS credential store opens it, else the
recovery key: `recovery_key`, `SOURCEORRERY_RECOVERY_KEY`, then
`recovery_key_file` or `SOURCEORRERY_RECOVERY_KEY_FILE`; there is never a
prompt and never the vault's view check. `OpenOptions::new()` takes a
`home`, a `recovery_key`, a `recovery_key_file` and `environment(false)`
to ignore the two variables.

A secret the vault keeps at a provider
([HashiCorp Vault](https://sourceorrery.ai/providers/hashicorp-vault/),
[AWS Secrets Manager](https://sourceorrery.ai/providers/aws-secrets-manager/),
[Azure Key Vault](https://sourceorrery.ai/providers/azure-key-vault/)) is read there through
the vault's connection, with the same calls: the connection signs in with
the credentials it stores, or with the provider's own sign-in on the
machine. No provider is contacted until a secret it keeps is read.

| Call | Returns |
|------|---------|
| `reader.get(name)` | `Secret` for the newest accessible version |
| `reader.get_version(name, version)` | `Secret` for exactly that version |
| `reader.properties(name, Some(version))` | `SecretProperties` (policy not applied) |
| `reader.resolve("sourceorrery://development/database-password")` | `Secret` |
| `reader.descriptor()` | `VaultDescriptor` (no values) |

`Secret`, `SecretProperties`, `SecretBytes` and `SecretReference` are the
core's own types, re-exported. A `SecretReader` is `Send + Sync`.

## Errors

Every method returns `sourceorrery::Result<T>`; the error carries the
stable code, an `ErrorKind`, the message and a hint:

```rust
use sourceorrery::{ErrorKind, SecretReader};

match SecretReader::open("development").and_then(|r| r.get("database-password")) {
    Ok(secret) => { /* ... */ }
    Err(err) if err.kind() == ErrorKind::Locked => eprintln!("{}", err.hint()),
    Err(err) if err.kind().is_policy() => eprintln!("{} (retry later: {})", err, err.is_transient()),
    Err(err) => eprintln!("[{}] {err}", err.code()),   // Display = message + hint
}
```

`ErrorKind` has a variant per code (`NotFound`, `VersionNotFound`,
`Deleted`, `Disabled`, `NotYetValid`, `Expired`, `InvalidName`,
`InvalidArgument`, `PermissionDenied`, `Locked`, `VaultNotFound`,
`MigrationRequired`, `VaultMismatch`, `Manifest`, `Crypto`, `Storage`,
`Io`, `Unsupported`) plus `Other` for codes added later. See [the SDK
overview](/sdks/#errors) for what each hint says.

## Load a project

```rust
use sourceorrery::{OpenOptions, Project};

let project = Project::load(Some(std::path::Path::new("sourceorrery.toml")), &OpenOptions::new())?;
for secret in project.secrets() {
    // secret.env, secret.reference, secret.properties, secret.value
}
let pairs = project.into_env();   // Vec<(String, SecretBytes)>
```

`Project::load(None, ..)` discovers the nearest `sourceorrery.toml` above
the current directory. It mirrors `sourceorrery run`: a required secret
that cannot be read fails the load with that secret's error; optional ones
are left out.

## Building from source

You need Git, Rust 1.91.1 or newer installed with rustup, and a C compiler
(on Linux also `pkg-config` and `libdbus-1-dev`);
[Building from source](https://sourceorrery.ai/guides/building-from-source/#what-you-need) has the commands for
each platform.

```bash
git clone https://github.com/Netizine/sourceorrery
cd sourceorrery
git checkout v0.3.1              # or stay on main for the newest changes
cargo build --release -p sourceorrery
```

To use a local checkout from your own crate, depend on it by path:

```toml
[dependencies]
sourceorrery = { path = "../sourceorrery/crates/sourceorrery" }
```

The example reads a secret from any vault you can unlock:

```bash
cargo run --release -p sourceorrery --example get_secret -- development database-password
```

The crate's tests need nothing set up. The conformance harness reads the
test vault that the CLI creates, so build the CLI and run the rest in
Bash (Git Bash on Windows):

```bash
cargo test -p sourceorrery
cargo build --release -p sourceorrery-cli
cargo build --release -p sourceorrery --example conformance
eval "$(bash scripts/ci/fixture-vault.sh)"       # a throwaway vault and the variables the harness reads
python tests/conformance/sdk/harness.py --runner rust
```

What the fixture script creates: [The SDK test vault](https://sourceorrery.ai/guides/building-from-source/#the-sdk-test-vault).
Source: [`crates/sourceorrery`](https://github.com/Netizine/sourceorrery/blob/main/crates/sourceorrery).
