openbao

package module
v0.0.0-...-328a091 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jul 17, 2026 License: BSD-3-Clause Imports: 10 Imported by: 0

README

go-ruby-openbao/openbao

openbao — go-ruby-openbao

Docs License Go Coverage

A pure-Go (no cgo) reimplementation of the deterministic core of Ruby's vault gem — the official OpenBao / HashiCorp Vault client (Vault::Client / OpenBao::Client). It reproduces the client configuration, the Logical / KV / Transit / Sys / Auth endpoint groups, the Secret response model, and the HTTP-status→error mapping the gem performs around a transport — without any Ruby runtime.

It is the OpenBao/Vault client for go-embedded-ruby, but a standalone, reusable module — a sibling of go-ruby-faraday and go-ruby-net-http.

What it is — and isn't. Everything the vault gem does around the wire is deterministic and needs no interpreter, so it lives here as pure Go: resolving the address / token / namespace from config or the environment, building the /v1/ request path, JSON-encoding request bodies, decoding the Secret envelope (data / lease_id / renewable / warnings / auth), and mapping a non-2xx status onto the error tree. The HTTP round-trip itself is a host seam: the terminal Doer performs the transport. The default production Doer is backed by net/http; tests inject a DoerFunc stub — or drive the default Doer against an in-process httptest mock OpenBao — and the core opens no socket of its own. A future rbgo binding wires the seam to Ruby's Net::HTTP.

Features

Faithful port of the vault gem's client core:

  • ClientNewClient(Config{Address, Token, Namespace, Timeout, Doer}) with environment fallback (VAULT_ADDR/BAO_ADDR, VAULT_TOKEN/BAO_TOKEN, VAULT_NAMESPACE/BAO_NAMESPACE), Token()/SetToken, Namespace()/SetNamespace, and AdoptToken(secret) to adopt a login's client_token.
  • LogicalRead/Write/List/Delete on an arbitrary path; the Secret carries Data/LeaseID/LeaseDuration/Renewable/Warnings. A 404 read/list yields a nil secret, mirroring the gem.
  • KV v1 & v2KVv1(mount) (flat) and KVv2(mount) with the version-2 data//metadata//delete//undelete//destroy/ path rewriting and the versioned request bodies: Read/ReadVersion/Write/List/Delete/ DeleteVersions/Undelete/Destroy/ReadMetadata/WriteMetadata/ DeleteMetadata.
  • TransitTransit(mount): Encrypt/Decrypt/Rewrap/Sign/Verify/ GenerateDataKey (base64 handling done for you).
  • SysHealth/SealStatus/Mounts/EnableMount/DisableMount/ Policies/Policy/PutPolicy/DeletePolicy/RenewLease/RevokeLease/ LookupLease.
  • AuthAuth().Token() (LookupSelf/RenewSelf/RevokeSelf), Auth().AppRole(mount).Login(roleID, secretID) and Auth().Userpass(mount).Login(username, password) — each returns a Secret whose Auth.ClientToken the client can adopt.
  • Transport seamDoer/DoerFunc; the default is net/http, the core never opens a socket itself.
  • Error tree — a single VaultError type whose Kind places it in the gem's hierarchy (Vault::VaultErrorHTTPErrorHTTPClientError/HTTPServerError, plus HTTPConnectionError), matched with errors.Is against the Err* sentinels (a superclass matches its subclasses) and carrying the HTTP status and the API errors array.

CGO-free, dependency-free (stdlib only), 100% test coverage, gofmt + go vet clean, and green across the six 64-bit Go targets (amd64, arm64, riscv64, loong64, ppc64le, s390x — big-endian) plus js/wasm and wasip1/wasm.

Install

go get github.com/go-ruby-openbao/openbao

Usage

package main

import (
	"fmt"

	"github.com/go-ruby-openbao/openbao"
)

func main() {
	client := openbao.NewClient(openbao.Config{
		Address: "https://127.0.0.1:8200",
		Token:   "s.sometoken",
	})

	// Arbitrary logical path.
	secret, err := client.Logical().Read("secret/data/foo")
	if err != nil {
		// a *openbao.VaultError: errors.Is(err, openbao.ErrHTTPClientError), etc.
		return
	}
	fmt.Println(secret.Data)

	// KV v2 (rewrites secret/foo -> secret/data/foo, wraps the write body).
	_, _ = client.KVv2("secret").Write("foo", map[string]any{"pw": "s3cr3t"})

	// Transit encryption.
	enc, _ := client.Transit("transit").Encrypt("mykey", []byte("hello"))
	fmt.Println(enc.Data["ciphertext"])

	// AppRole login, then adopt the returned client token.
	login, _ := client.Auth().AppRole("approle").Login("role-id", "secret-id")
	client.AdoptToken(login)
}
Injecting a transport (tests / hosts)
client := openbao.NewClient(openbao.Config{
	Address: "https://vault.example",
	Token:   "t",
	Doer: openbao.DoerFunc(func(req *openbao.Request) (*openbao.Response, error) {
		return &openbao.Response{
			StatusCode: 200,
			Body:       []byte(`{"data":{"foo":"bar"}}`),
		}, nil
	}),
})
secret, _ := client.Logical().Read("secret/data/foo")
// secret.Data["foo"] == "bar"

Value model

gem this package
Vault::Client.new(address:, token:, …) NewClient(Config{Address, Token, Namespace})
client.logical.read/write/list/delete client.Logical().Read/Write/List/Delete
client.kv(mount).read/write/… client.KVv2(mount).Read/Write/…
client.transit.encrypt/decrypt/… client.Transit(mount).Encrypt/Decrypt/…
client.sys.health / mounts / policies client.Sys().Health/Mounts/Policies
client.auth.approle.login(id, secret) client.Auth().AppRole(m).Login(id, secret)
Vault::Secret#data/#lease_id/#auth (*Secret).Data / .LeaseID / .Auth
Vault::HTTPError subtree *VaultError + Err* sentinels (errors.Is)
the Persistent HTTP connection Doer (host seam; DoerFunc in tests)

Tests & coverage

The suite is deterministic and socket-local: an in-process httptest mock OpenBao answers the default net/http transport for the happy-path integration tests, while DoerFunc stubs and a fake net/http client drive every error branch (transport failure, bad JSON, non-2xx status class, 404-to-nil). No test opens a real socket, so the cross-arch qemu lanes and the Windows lane all hold coverage at 100%.

COVERPKG=$(go list ./... | paste -sd, -)
go test -race -coverpkg="$COVERPKG" -coverprofile=cover.out ./...
go tool cover -func=cover.out | tail -1   # 100.0%

WebAssembly

Being pure Go (CGO=0), this library also compiles to WebAssembly — both GOOS=js GOARCH=wasm (browser / Node.js) and GOOS=wasip1 GOARCH=wasm (WASI). CI builds both targets on every push, alongside the six 64-bit native/qemu arches.

GOOS=js     GOARCH=wasm go build ./...   # browser / Node
GOOS=wasip1 GOARCH=wasm go build ./...   # WASI (wasmtime, wasmer, wasmedge, …)

License

BSD-3-Clause — see LICENSE. Copyright the go-ruby-openbao/openbao authors.

Documentation

Overview

Package openbao is a pure-Go (CGO-free) reimplementation of the deterministic core of Ruby's `vault` gem — the official OpenBao / HashiCorp Vault client (Vault::Client / OpenBao::Client). It reproduces the client configuration, the Logical/KV/Transit/Sys/Auth endpoint groups, the Secret response model, and the HTTP-status→error mapping the gem performs around a transport — without any Ruby runtime.

It is the OpenBao/Vault client for [go-embedded-ruby](https://github.com/go-embedded-ruby/ruby), but a standalone, reusable module — a sibling of go-ruby-faraday/faraday and go-ruby-net-http/net-http.

What it is — and isn't

Everything the vault gem does around the wire is deterministic and needs no interpreter, so it lives here as pure Go: resolving the address/token/ namespace from config or the environment, building the /v1/ request path, JSON-encoding request bodies, decoding the Secret response (data/lease_id/renewable/warnings/auth), and mapping a non-2xx status onto the error tree. The HTTP round-trip itself is a host seam: the terminal Doer performs the transport. The default production Doer is backed by net/http; tests inject a DoerFunc stub (or drive the default Doer against an in-process httptest server), and the core opens no socket of its own. This mirrors the gem, whose Persistent HTTP connection is the only piece that touches the network.

Flow

client := openbao.NewClient(openbao.Config{
	Address: "https://127.0.0.1:8200",
	Token:   "s.sometoken",
})

// arbitrary logical path
secret, err := client.Logical().Read("secret/data/foo")

// KV v2 helper (rewrites secret/foo -> secret/data/foo)
secret, err = client.KVv2("secret").Read("foo")

// transit encrypt
enc, err := client.Transit("transit").Encrypt("mykey", []byte("hello"))

// approle login, then adopt the returned client token
login, err := client.Auth().AppRole("approle").Login(roleID, secretID)
client.AdoptToken(login)

Value model

A Secret carries the decoded response fields (Data, LeaseID, LeaseDuration, Renewable, Warnings, Auth). Errors are a single VaultError type whose Kind places it in the gem's error tree (VaultError → HTTPError → HTTPClientError/HTTPServerError, plus HTTPConnectionError), matched with errors.Is against the Err* sentinels so a superclass matches its subclasses. A host (go-embedded-ruby / rbgo) maps its Ruby Vault::Client / Secret / VaultError objects to and from these shapes.

Index

Constants

View Source
const DefaultAddress = "https://127.0.0.1:8200"

DefaultAddress is the address used when neither the config nor the environment supplies one, matching the vault gem's default.

Variables

View Source
var (
	ErrVaultError          = &VaultError{Kind: KindVaultError, Message: string(KindVaultError)}
	ErrHTTPError           = &VaultError{Kind: KindHTTPError, Message: string(KindHTTPError)}
	ErrHTTPConnectionError = &VaultError{Kind: KindHTTPConnectionError, Message: string(KindHTTPConnectionError)}
	ErrHTTPClientError     = &VaultError{Kind: KindHTTPClientError, Message: string(KindHTTPClientError)}
	ErrHTTPServerError     = &VaultError{Kind: KindHTTPServerError, Message: string(KindHTTPServerError)}
	ErrMissingRequired     = &VaultError{Kind: KindMissingRequired, Message: string(KindMissingRequired)}
)

Sentinel errors for errors.Is matching. Each names an error kind; a concrete VaultError with that Kind (or a subtree of it) matches via VaultError.Is.

Functions

func IsHTTPClientError

func IsHTTPClientError(err error) bool

IsHTTPClientError reports whether err is a gem 4xx HTTPClientError.

func IsHTTPError

func IsHTTPError(err error) bool

IsHTTPError reports whether err is any gem HTTPError (client/server/connection).

func IsHTTPServerError

func IsHTTPServerError(err error) bool

IsHTTPServerError reports whether err is a gem 5xx HTTPServerError.

func IsNotFound

func IsNotFound(err error) bool

IsNotFound reports whether err is an HTTPError with a 404 status.

Types

type AppRoleAuth

type AppRoleAuth struct {
	// contains filtered or unexported fields
}

AppRoleAuth is the AppRole login helper rooted at a mount (default "approle").

func (*AppRoleAuth) Login

func (a *AppRoleAuth) Login(roleID, secretID string) (*Secret, error)

Login exchanges a role_id/secret_id for a token (POST auth/<mount>/login). The returned secret's Auth.ClientToken is the issued token.

type Auth

type Auth struct {
	// contains filtered or unexported fields
}

Auth is the auth-method endpoint group (Vault::Client#auth): token self-management and the AppRole / Userpass login flows, each of which yields a Secret whose Auth.ClientToken the client can adopt with Client.AdoptToken.

func (*Auth) AppRole

func (a *Auth) AppRole(mount string) *AppRoleAuth

AppRole returns the AppRole login helper rooted at mount (default "approle").

func (*Auth) Token

func (a *Auth) Token() *TokenAuth

Token returns the token self-management helper (auth/token).

func (*Auth) Userpass

func (a *Auth) Userpass(mount string) *UserpassAuth

Userpass returns the Userpass login helper rooted at mount (default "userpass").

type Client

type Client struct {
	// contains filtered or unexported fields
}

Client is a configured OpenBao/Vault API client (Vault::Client / OpenBao::Client). It carries the resolved address, token and namespace, and the transport Doer; the endpoint groups are reached through Client.Logical, Client.KVv1, Client.KVv2, Client.Transit, Client.Sys and Client.Auth.

func NewClient

func NewClient(cfg Config) *Client

NewClient builds a Client from cfg, resolving unset fields from the environment and the defaults.

func (*Client) Address

func (c *Client) Address() string

Address returns the resolved server address.

func (*Client) AdoptToken

func (c *Client) AdoptToken(s *Secret) *Client

AdoptToken adopts the client_token from a login/auth Secret as the client's token (Vault::Client#token=), returning the client for chaining. A nil secret or one without an auth client token leaves the token unchanged.

func (*Client) Auth

func (c *Client) Auth() *Auth

Auth returns the auth-method endpoint group (Vault::Client#auth).

func (*Client) KVv1

func (c *Client) KVv1(mount string) *KVv1

KVv1 returns a KV version-1 helper rooted at mount (default "secret").

func (*Client) KVv2

func (c *Client) KVv2(mount string) *KVv2

KVv2 returns a KV version-2 helper rooted at mount (default "secret").

func (*Client) Logical

func (c *Client) Logical() *Logical

Logical returns the logical-backend endpoint group (Vault::Client#logical).

func (*Client) Namespace

func (c *Client) Namespace() string

Namespace returns the current Vault namespace.

func (*Client) SetNamespace

func (c *Client) SetNamespace(ns string) *Client

SetNamespace sets the Vault namespace and returns the client for chaining.

func (*Client) SetToken

func (c *Client) SetToken(token string) *Client

SetToken sets the Vault token and returns the client for chaining.

func (*Client) Sys

func (c *Client) Sys() *Sys

Sys returns the system-backend endpoint group (Vault::Client#sys).

func (*Client) Token

func (c *Client) Token() string

Token returns the current Vault token.

func (*Client) Transit

func (c *Client) Transit(mount string) *Transit

Transit returns a transit-backend helper rooted at mount (default "transit").

type Config

type Config struct {
	// Address is the OpenBao/Vault server address (scheme+host+port).
	Address string
	// Token is the Vault token sent as X-Vault-Token.
	Token string
	// Namespace is the Vault namespace sent as X-Vault-Namespace (Enterprise /
	// OpenBao namespaces).
	Namespace string
	// Timeout is the per-request timeout of the default net/http transport; 0
	// means no timeout. Ignored when Doer is set.
	Timeout time.Duration
	// Doer overrides the transport seam. When nil, a net/http-backed Doer is
	// used. Tests and hosts inject their own.
	Doer Doer
}

Config configures a Client. Any zero field is resolved from the environment (Address from VAULT_ADDR/BAO_ADDR, Token from VAULT_TOKEN/BAO_TOKEN, Namespace from VAULT_NAMESPACE/BAO_NAMESPACE) and finally from the built-in defaults.

type Doer

type Doer interface {
	Do(req *Request) (*Response, error)
}

Doer is the transport host seam: given a prepared Request it performs the HTTP round-trip and returns the Response, or a transport error. The default production Doer ([defaultDoer]) is backed by net/http; the core opens no socket of its own, so tests inject a DoerFunc stub (or drive the default Doer against an in-process httptest server). A future rbgo binding wires this to Ruby's Net::HTTP.

type DoerFunc

type DoerFunc func(req *Request) (*Response, error)

DoerFunc adapts a function to the Doer interface — the convenient way to inject a stub transport in tests or a custom transport in a host.

func (DoerFunc) Do

func (f DoerFunc) Do(req *Request) (*Response, error)

Do invokes f(req).

type ErrorKind

type ErrorKind string

ErrorKind identifies a vault-gem error subclass.

const (
	KindVaultError          ErrorKind = "Vault::VaultError"
	KindHTTPError           ErrorKind = "Vault::HTTPError"
	KindHTTPConnectionError ErrorKind = "Vault::HTTPConnectionError"
	KindHTTPClientError     ErrorKind = "Vault::HTTPClientError"
	KindHTTPServerError     ErrorKind = "Vault::HTTPServerError"
	KindMissingRequired     ErrorKind = "Vault::MissingRequiredStateError"
)

The vault-gem error subclasses, named as in the gem.

type KVv1

type KVv1 struct {
	// contains filtered or unexported fields
}

KVv1 is a KV version-1 secrets-engine helper rooted at a mount (default "secret"). Paths are joined under the mount; the payload is stored flat, so the verbs delegate straight to Logical.

func (*KVv1) Delete

func (k *KVv1) Delete(path string) (*Secret, error)

Delete deletes the KV v1 secret at path.

func (*KVv1) List

func (k *KVv1) List(path string) (*Secret, error)

List lists the keys under the KV v1 path.

func (*KVv1) Read

func (k *KVv1) Read(path string) (*Secret, error)

Read reads the KV v1 secret at path.

func (*KVv1) Write

func (k *KVv1) Write(path string, data map[string]any) (*Secret, error)

Write writes the KV v1 secret at path.

type KVv2

type KVv2 struct {
	// contains filtered or unexported fields
}

KVv2 is a KV version-2 secrets-engine helper rooted at a mount (default "secret"). It performs the version-2 path rewriting (data/, metadata/, delete/, undelete/, destroy/) and the versioned request bodies the engine expects.

func (*KVv2) Delete

func (k *KVv2) Delete(path string) (*Secret, error)

Delete soft-deletes the latest version of the KV v2 secret at path (DELETE <mount>/data/<path>).

func (*KVv2) DeleteMetadata

func (k *KVv2) DeleteMetadata(path string) (*Secret, error)

DeleteMetadata deletes the KV v2 metadata (and every version) for path (DELETE <mount>/metadata/<path>).

func (*KVv2) DeleteVersions

func (k *KVv2) DeleteVersions(path string, versions ...int) (*Secret, error)

DeleteVersions soft-deletes specific versions of the KV v2 secret at path (POST <mount>/delete/<path>).

func (*KVv2) Destroy

func (k *KVv2) Destroy(path string, versions ...int) (*Secret, error)

Destroy permanently destroys specific versions of the KV v2 secret at path (POST <mount>/destroy/<path>).

func (*KVv2) List

func (k *KVv2) List(path string) (*Secret, error)

List lists the keys under the KV v2 path (LIST <mount>/metadata/<path>).

func (*KVv2) Read

func (k *KVv2) Read(path string) (*Secret, error)

Read reads the latest version of the KV v2 secret at path (GET <mount>/data/<path>).

func (*KVv2) ReadMetadata

func (k *KVv2) ReadMetadata(path string) (*Secret, error)

ReadMetadata reads the KV v2 metadata for path (GET <mount>/metadata/<path>).

func (*KVv2) ReadVersion

func (k *KVv2) ReadVersion(path string, version int) (*Secret, error)

ReadVersion reads a specific version of the KV v2 secret at path (GET <mount>/data/<path>?version=N).

func (*KVv2) Undelete

func (k *KVv2) Undelete(path string, versions ...int) (*Secret, error)

Undelete restores previously soft-deleted versions of the KV v2 secret at path (POST <mount>/undelete/<path>).

func (*KVv2) Write

func (k *KVv2) Write(path string, data map[string]any) (*Secret, error)

Write writes a new version of the KV v2 secret at path, wrapping data in the version-2 {"data": …} envelope (PUT <mount>/data/<path>); the returned secret carries the new version metadata.

func (*KVv2) WriteMetadata

func (k *KVv2) WriteMetadata(path string, meta map[string]any) (*Secret, error)

WriteMetadata writes the KV v2 metadata for path (PUT <mount>/metadata/<path>).

type Logical

type Logical struct {
	// contains filtered or unexported fields
}

Logical is the logical-backend endpoint group (Vault::Client#logical): the generic read/write/list/delete verbs over an arbitrary API path, the primitive every higher-level helper (KV, transit, sys, auth) builds on.

func (*Logical) Delete

func (l *Logical) Delete(path string) (*Secret, error)

Delete deletes the secret at path (DELETE /v1/<path>, Vault::Logical#delete).

func (*Logical) List

func (l *Logical) List(path string) (*Secret, error)

List lists the keys at path (LIST /v1/<path>, Vault::Logical#list): a 404 yields a nil secret and nil error.

func (*Logical) Read

func (l *Logical) Read(path string) (*Secret, error)

Read reads the secret at path (GET /v1/<path>), mirroring Vault::Logical#read: a 404 yields a nil secret and nil error, so a missing path is not an error.

func (*Logical) Write

func (l *Logical) Write(path string, data map[string]any) (*Secret, error)

Write writes data to path (PUT /v1/<path>, Vault::Logical#write) and returns the response secret (nil for a 204 No Content).

type Request

type Request struct {
	// Method is the upper-case HTTP method ("GET", "PUT", "POST", "DELETE",
	// "LIST").
	Method string
	// URL is the fully-built request URL.
	URL string
	// Headers are the outgoing headers.
	Headers map[string]string
	// Body is the JSON-encoded request body, or nil.
	Body []byte
}

Request is the prepared HTTP request the client hands to a Doer: the fully built URL (Address + "/v1/" + path), the method, the header set (including X-Vault-Token / X-Vault-Namespace when configured) and the JSON-encoded body (nil for a bodyless request). It is a transport-agnostic value so a host can wire it to any HTTP stack.

type Response

type Response struct {
	// StatusCode is the HTTP status code.
	StatusCode int
	// Body is the raw response body.
	Body []byte
	// Header carries the response headers.
	Header map[string][]string
}

Response is the transport result a Doer returns: the HTTP status code, the raw response body, and the response headers. The client decodes the body into a Secret (2xx) or maps the status onto a VaultError (non-2xx).

type Secret

type Secret struct {
	// RequestID is the server-assigned request identifier.
	RequestID string `json:"request_id"`
	// LeaseID is the lease identifier for a leased secret ("" when not leased).
	LeaseID string `json:"lease_id"`
	// LeaseDuration is the lease TTL in seconds.
	LeaseDuration int `json:"lease_duration"`
	// Renewable reports whether the lease can be renewed.
	Renewable bool `json:"renewable"`
	// Data is the secret payload (Vault::Secret#data).
	Data map[string]any `json:"data"`
	// Warnings carries any server-side warnings (Vault::Secret#warnings).
	Warnings []string `json:"warnings"`
	// Auth carries the authentication response for a login/token call
	// (Vault::Secret#auth); nil otherwise.
	Auth *SecretAuth `json:"auth"`
	// WrapInfo carries response-wrapping metadata when the call was wrapped; nil
	// otherwise (Vault::Secret#wrap_info).
	WrapInfo map[string]any `json:"wrap_info"`
}

Secret is the decoded OpenBao/Vault response envelope (Vault::Secret). Reads and writes that return data populate Data; leased secrets populate LeaseID/LeaseDuration/Renewable; login and token responses populate Auth. Any server-side warnings are surfaced in Warnings.

func (*Secret) TokenID

func (s *Secret) TokenID() string

TokenID returns the auth client token carried by the secret, or "" when the secret has no auth block. It is the convenient accessor a host uses to adopt a login's token.

type SecretAuth

type SecretAuth struct {
	// ClientToken is the issued Vault token (auth.client_token).
	ClientToken string `json:"client_token"`
	// Accessor is the token accessor.
	Accessor string `json:"accessor"`
	// Policies are the token's policies.
	Policies []string `json:"policies"`
	// TokenPolicies are the token's token-scoped policies.
	TokenPolicies []string `json:"token_policies"`
	// Metadata is the token metadata map.
	Metadata map[string]any `json:"metadata"`
	// LeaseDuration is the token TTL in seconds.
	LeaseDuration int `json:"lease_duration"`
	// Renewable reports whether the token can be renewed.
	Renewable bool `json:"renewable"`
}

SecretAuth is the authentication half of a Secret (Vault::Secret#auth), populated by login and token endpoints.

type Sys

type Sys struct {
	// contains filtered or unexported fields
}

Sys is the system-backend endpoint group (Vault::Client#sys): server health and seal status, secrets-engine mount management, ACL policy management and lease management.

func (*Sys) DeletePolicy

func (s *Sys) DeletePolicy(name string) error

DeletePolicy deletes the named ACL policy (DELETE sys/policies/acl/<name>).

func (*Sys) DisableMount

func (s *Sys) DisableMount(path string) error

DisableMount unmounts the secrets engine at path (DELETE sys/mounts/<path>).

func (*Sys) EnableMount

func (s *Sys) EnableMount(path, engineType string, opts map[string]any) error

EnableMount mounts a secrets engine of the given type at path (POST sys/mounts/<path>). Extra options (description, config, options) are merged into the request body.

func (*Sys) Health

func (s *Sys) Health() (map[string]any, error)

Health returns the server health (GET sys/health). Its payload is a flat object (initialized/sealed/standby/version/…), so it is returned as a raw map rather than a Secret envelope.

func (*Sys) LookupLease

func (s *Sys) LookupLease(leaseID string) (*Secret, error)

LookupLease looks up a lease by id (PUT sys/leases/lookup).

func (*Sys) Mounts

func (s *Sys) Mounts() (map[string]any, error)

Mounts lists the mounted secrets engines (GET sys/mounts) as a raw map keyed by mount path.

func (*Sys) Policies

func (s *Sys) Policies() (*Secret, error)

Policies lists the ACL policy names (GET sys/policies/acl). The names are in the returned secret's Data under "keys"/"policies".

func (*Sys) Policy

func (s *Sys) Policy(name string) (*Secret, error)

Policy reads the named ACL policy (GET sys/policies/acl/<name>).

func (*Sys) PutPolicy

func (s *Sys) PutPolicy(name, policy string) error

PutPolicy writes the named ACL policy from an HCL/JSON rules string (PUT sys/policies/acl/<name>).

func (*Sys) RenewLease

func (s *Sys) RenewLease(leaseID string, increment int) (*Secret, error)

RenewLease renews a lease by id, requesting increment seconds of additional TTL (PUT sys/leases/renew).

func (*Sys) RevokeLease

func (s *Sys) RevokeLease(leaseID string) error

RevokeLease revokes a lease by id (PUT sys/leases/revoke).

func (*Sys) SealStatus

func (s *Sys) SealStatus() (map[string]any, error)

SealStatus returns the server seal status (GET sys/seal-status) as a raw map (sealed/t/n/progress/version/…).

type TokenAuth

type TokenAuth struct {
	// contains filtered or unexported fields
}

TokenAuth is the token self-management helper (auth/token).

func (*TokenAuth) LookupSelf

func (t *TokenAuth) LookupSelf() (*Secret, error)

LookupSelf looks up the current token (GET auth/token/lookup-self).

func (*TokenAuth) RenewSelf

func (t *TokenAuth) RenewSelf(increment int) (*Secret, error)

RenewSelf renews the current token, requesting increment seconds of additional TTL (POST auth/token/renew-self).

func (*TokenAuth) RevokeSelf

func (t *TokenAuth) RevokeSelf() error

RevokeSelf revokes the current token (POST auth/token/revoke-self).

type Transit

type Transit struct {
	// contains filtered or unexported fields
}

Transit is a transit secrets-engine helper rooted at a mount (default "transit"): encryption, decryption, rewrapping, signing, verification and data-key generation as cryptographic operations performed by the server without exposing the key.

func (*Transit) Decrypt

func (t *Transit) Decrypt(key, ciphertext string, context ...[]byte) (*Secret, error)

Decrypt decrypts ciphertext with the named key (POST <mount>/decrypt/<key>). The returned secret's Data carries "plaintext" (base64-encoded by the engine).

func (*Transit) Encrypt

func (t *Transit) Encrypt(key string, plaintext []byte, context ...[]byte) (*Secret, error)

Encrypt encrypts plaintext with the named key (POST <mount>/encrypt/<key>). The plaintext is base64-encoded as the engine requires; an optional context (for a keyed/derived key) is base64-encoded too. The returned secret's Data carries "ciphertext".

func (*Transit) GenerateDataKey

func (t *Transit) GenerateDataKey(key, keyType string) (*Secret, error)

GenerateDataKey generates a new high-entropy data key wrapped (and optionally returned in plaintext) by the named key (POST <mount>/datakey/<keyType>/<key>). keyType is "plaintext" or "wrapped".

func (*Transit) Rewrap

func (t *Transit) Rewrap(key, ciphertext string, context ...[]byte) (*Secret, error)

Rewrap rewraps ciphertext to the key's latest version (POST <mount>/rewrap/<key>).

func (*Transit) Sign

func (t *Transit) Sign(key string, input []byte) (*Secret, error)

Sign signs input with the named key (POST <mount>/sign/<key>); input is base64-encoded. The returned secret's Data carries "signature".

func (*Transit) Verify

func (t *Transit) Verify(key string, input []byte, signature string) (*Secret, error)

Verify verifies signature over input with the named key (POST <mount>/verify/<key>). The returned secret's Data carries "valid".

type UserpassAuth

type UserpassAuth struct {
	// contains filtered or unexported fields
}

UserpassAuth is the Userpass login helper rooted at a mount (default "userpass").

func (*UserpassAuth) Login

func (u *UserpassAuth) Login(username, password string) (*Secret, error)

Login exchanges a username/password for a token (POST auth/<mount>/login/<username>). The returned secret's Auth.ClientToken is the issued token.

type VaultError

type VaultError struct {
	// Kind names the specific gem error subclass (see the Err* sentinels).
	Kind ErrorKind
	// Message is the error text (VaultError#message).
	Message string
	// StatusCode is the HTTP status for an HTTPError (0 for a connection error).
	StatusCode int
	// Errors is the API "errors" array returned in the response body, if any.
	Errors []string
	// Cause is the underlying transport error for an HTTPConnectionError.
	Cause error
}

VaultError is the root of the vault gem's error tree (Vault::VaultError). Every error carries a human message; errors raised from an HTTP response also carry the response StatusCode and the API "errors" array so callers can inspect what the server reported. Transport failures carry the underlying error as VaultError.Cause.

The concrete kinds are distinguished by VaultError.Kind; the predicate helpers (IsHTTPError, IsHTTPClientError, …) and the sentinel values (ErrHTTPError, …) let callers match with errors.Is, mirroring Ruby's rescue of a Vault::HTTPError subclass.

func (*VaultError) Error

func (e *VaultError) Error() string

Error implements the error interface (VaultError#message).

func (*VaultError) Is

func (e *VaultError) Is(target error) bool

Is reports whether e matches target: true when target is a *VaultError whose Kind is e's Kind or an ancestor of it, so errors.Is(err, ErrHTTPError) matches any client/server/connection error and errors.Is(err, ErrVaultError) matches every gem error — mirroring Ruby's rescue of a superclass.

func (*VaultError) Unwrap

func (e *VaultError) Unwrap() error

Unwrap exposes the underlying transport error for errors.Is/As on the cause.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL