Skip to content

Secrets

The secrets interface is the same for every secrets service of Grow Codes. You get a SecretsProvider from the OpenBao client (see Functions for the accessor and for service options such as mounts, paths or projects); the examples below call it secrets.

Secret values come back as SecretValue, a redacting wrapper: printing or serialising it shows SecretValue([REDACTED]). Read the content explicitly with reveal() (text), revealBytes() or json().

Functions

Function Returns Notes
get(name, opts?) SecretValue or null opts: version, path
getString(name) / getJson(name) text / decoded JSON or null VALIDATION for non-UTF-8 or non-JSON
getNumber(name) / getBool(name) number / boolean or null booleans: true/false/1/0/yes/no/on/off
require(name) SecretValue NOT_FOUND when missing
exists(name) boolean
getMany(names) map name → value missing names omitted, request order kept
getAll(path?) map name → value every secret directly under path (non-recursive)
list(prefixOrPath?) SecretMetadata[] sorted by name names and metadata, no values
set(name, value, opts?) new version ("" without versions) value: text, bytes or an object (JSON-encoded); opts: path, cas, tags, description
delete(name, opts?) — NOT_FOUND when missing; opts: path, versions, permanent
metadata(name) SecretMetadata or null name, path, version, createdAt, updatedAt, tags, versions, extra
loadEnv(pathOrMapping, opts?) variables set (names only) opts: override (default false), prefix
watch(name, interval, onChange, opts?) WatchHandle (stop()) polls; onChange(newValue, oldValue), deletion → newValue = null

Read secrets

const dbPassword = await secrets.require("db-password");
connect({ password: dbPassword.reveal() });

const apiUrl = await secrets.getString("api-url");             // string | null
const limits = await secrets.getJson<{ rps: number }>("limits"); // object | null
const debug = (await secrets.getBool("debug")) ?? false;
const many = await secrets.getMany(["a", "b", "missing"]);     // Map with a, b
const all = await secrets.getAll("app/prod");
const old = await secrets.get("db-password", { version: "3" });
console.log(String(dbPassword)); // SecretValue([REDACTED])
use grow_openbao::secrets::{GetOptions, SecretsProvider};

let db_password = secrets.require("db-password", None).await?;
connect(db_password.reveal()?);

let api_url: Option<String> = secrets.get_string("api-url", None).await?;
let debug = secrets.get_bool("debug", None).await?.unwrap_or(false);
let many = secrets.get_many(&["a", "b", "missing"], None).await?;
let all = secrets.get_all(Some("app/prod")).await?;
let old = secrets
    .get("db-password", Some(&GetOptions { version: Some("3".into()), ..Default::default() }))
    .await?;
println!("{db_password:?}"); // SecretValue([REDACTED])
dbPassword, err := secrets.Require(ctx, "db-password", nil)
if err != nil {
    return err // errors.Is(err, openbao.ErrNotFound) when missing
}
connect(dbPassword.Reveal())

apiURL, ok, err := secrets.GetString(ctx, "api-url", nil)
var limits struct{ RPS int }
found, err := secrets.GetJSON(ctx, "limits", &limits, nil)
debug, _, err := secrets.GetBool(ctx, "debug", nil)
many, err := secrets.GetMany(ctx, []string{"a", "b", "missing"}, nil)
all, err := secrets.GetAll(ctx, "app/prod")
old, err := secrets.Get(ctx, "db-password", &openbao.GetOptions{Version: "3"})
fmt.Println(dbPassword) // SecretValue([REDACTED])
db_password = secrets.require("db-password")
connect(password=db_password.reveal())

api_url = secrets.get_string("api-url")          # str | None
limits = secrets.get_json("limits")              # Any | None
debug = secrets.get_bool("debug") or False
many = secrets.get_many(["a", "b", "missing"])   # dict with a, b
everything = secrets.get_all("app/prod")
old = secrets.get("db-password", version="3")
print(db_password)  # SecretValue([REDACTED])
SecretValue dbPassword = secrets.require("db-password");
connect(dbPassword.reveal());

Optional<String> apiUrl = secrets.getString("api-url");
Optional<Limits> limits = secrets.getJson("limits", Limits.class);
boolean debug = secrets.getBool("debug").orElse(false);
Map<String, SecretValue> many = secrets.getMany(List.of("a", "b", "missing"));
Map<String, SecretValue> all = secrets.getAll("app/prod");
System.out.println(dbPassword); // SecretValue([REDACTED])

Every method also has an …Async variant returning CompletableFuture.

Write, list and delete

const version = await secrets.set("api-key", "s3cr3t", { tags: { team: "payments" } });
await secrets.set("limits", { rps: 50 });              // JSON-encoded
await secrets.set("api-key", "rotated", { cas: 1 });   // CONFLICT if the version moved
for (const meta of await secrets.list("app/")) console.log(meta.name, meta.version);
const meta = await secrets.metadata("api-key");
await secrets.delete("api-key");
use grow_openbao::secrets::SecretData;

let version = secrets.set("api-key", SecretData::Text("s3cr3t".into()), None).await?;
secrets.set("limits", SecretData::Json(serde_json::json!({"rps": 50})), None).await?;
for meta in secrets.list(Some("app/")).await? {
    println!("{} {:?}", meta.name, meta.version);
}
let meta = secrets.metadata("api-key", None).await?;
secrets.delete("api-key", None).await?;
version, err := secrets.Set(ctx, "api-key", "s3cr3t", &openbao.SetOptions{Tags: map[string]string{"team": "payments"}})
_, err = secrets.Set(ctx, "limits", map[string]int{"rps": 50}, nil) // JSON-encoded
list, err := secrets.List(ctx, "app/")
meta, err := secrets.Metadata(ctx, "api-key", nil)
err = secrets.Delete(ctx, "api-key", nil)
version = secrets.set("api-key", "s3cr3t", tags={"team": "payments"})
secrets.set("limits", {"rps": 50})               # JSON-encoded
for meta in secrets.list("app/"):
    print(meta.name, meta.version)
meta = secrets.metadata("api-key")
secrets.delete("api-key")
String version = secrets.set("api-key", "s3cr3t", SetOptions.none());
secrets.set("limits", Map.of("rps", 50), SetOptions.none()); // JSON-encoded
for (SecretMetadata meta : secrets.list("app/")) {
  System.out.println(meta.name() + " " + meta.version());
}
secrets.delete("api-key", DeleteOptions.none());

Load secrets into the environment

loadEnv(path) sets one variable per secret directly under path: the name is upper-cased and every character outside [A-Z0-9_] becomes _ (db-password → DB_PASSWORD), prefixed with prefix. loadEnv(mapping) sets each variable from the named secret (NOT_FOUND when one is missing). Existing variables are kept unless override is true. The result lists the variables that were set — never the values.

await secrets.loadEnv("app/prod", { prefix: "APP_" });       // process.env.APP_DB_PASSWORD
await secrets.loadEnv({ DATABASE_URL: "db-url" }, { override: true });
use grow_openbao::secrets::{EnvSource, LoadEnvOptions};

let set = secrets
    .load_env(&EnvSource::Path("app/prod".into()), &LoadEnvOptions { prefix: "APP_".into(), ..Default::default() })
    .await?;
set, err := secrets.LoadEnv(ctx, "app/prod", &openbao.LoadEnvOptions{Prefix: "APP_"})
set, err = secrets.LoadEnvMapping(ctx, map[string]string{"DATABASE_URL": "db-url"}, &openbao.LoadEnvOptions{Override: true})
secrets.load_env("app/prod", prefix="APP_")                 # os.environ["APP_DB_PASSWORD"]
secrets.load_env({"DATABASE_URL": "db-url"}, override=True)

Java cannot change the process environment, so loadEnv sets system properties and returns the names it set.

Map<String, String> set = secrets.loadEnv("app/prod", LoadEnvOptions.builder().prefix("APP_").build());
String dbPassword = System.getProperty("APP_DB_PASSWORD");

Watch for changes

watch polls every interval and compares the version (or a SHA-256 of the value when the service has no versions). Errors go to onError and polling continues. stop() is idempotent and closing the client stops every watcher.

const handle = secrets.watch("api-key", 30_000, (next, prev) => rotate(next?.reveal()), {
  onError: (err) => console.warn(err.message),
});
handle.stop();
use grow_openbao::secrets::{watch, WatchOptions};

let handle = watch(Arc::new(secrets), "api-key", Duration::from_secs(30),
    |next, _prev| rotate(next), WatchOptions::default());
handle.stop();
handle := secrets.Watch(ctx, "api-key", 30*time.Second, func(next, prev *openbao.SecretValue) {
    rotate(next)
}, &openbao.WatchOptions{OnError: func(err error) { log.Print(err) }})
defer handle.Stop()
handle = secrets.watch("api-key", 30.0, lambda new, old: rotate(new), on_error=print)
handle.stop()
WatchHandle handle = secrets.watch("api-key", Duration.ofSeconds(30),
    (next, prev) -> rotate(next), WatchOptions.none());
handle.stop();

Cache

SecretCache wraps a provider and caches reads (get*, require, exists, getMany) with LRU eviction; writes pass through and invalidate. Missing secrets are cached too.

Option Default Meaning
ttl 60 s lifetime of an entry
maxEntries 1000 LRU capacity
refreshAheadFactor 0.8 a hit after ttl × factor starts one background refresh
staleWhileRevalidate 0 within ttl + staleWhileRevalidate a stale value is returned while one refresh runs
clock system injectable for tests

invalidate(name), clear() and stats() (hits, misses, evictions, refreshes, size) are available in every language.

import { SecretCache } from "@grow-codes/openbao";

const cached = new SecretCache(secrets, { ttlMs: 300_000, staleWhileRevalidateMs: 30_000 });
const key = await cached.require("api-key");
console.log(cached.stats());
use grow_openbao::secrets::{SecretCache, SecretCacheOptions};

let cached = SecretCache::with_options(
    Arc::new(secrets),
    SecretCacheOptions { ttl: Duration::from_secs(300), ..Default::default() },
);
let key = cached.require("api-key", None).await?;
cached := openbao.NewSecretCache(secrets, &openbao.CacheOptions{TTL: 5 * time.Minute})
key, err := cached.Require(ctx, "api-key", nil)
fmt.Printf("%+v\n", cached.Stats())
from grow_openbao import SecretCache

cached = SecretCache(secrets, ttl_s=300.0, stale_while_revalidate_s=30.0)
key = cached.require("api-key")
print(cached.stats())
SecretCache cached = new SecretCache(secrets,
    SecretCache.Options.builder().ttl(Duration.ofMinutes(5)).build());
SecretValue key = cached.require("api-key");

Testing

The testing module (see Docker testing) has an in-memory SecretsProvider with the same behaviour, so application tests run without the service.