workloadsecrets

package module
v0.2.0-preview.1 Latest Latest
Warning

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

Go to latest
Published: Nov 19, 2026 License: MIT Imports: 29 Imported by: 0

README

Delinea Workload Secrets Vault SDK for Go

Read secrets from Delinea Workload Secrets Vault in a Go application.

  • Go 1.26 or later.

  • Module github.com/DelineaXPM/workload-secrets-sdk-go, package workloadsecrets:

    go get github.com/DelineaXPM/workload-secrets-sdk-go
    
  • Reference documentation and examples: pkg.go.dev.

Quick start

import "github.com/DelineaXPM/workload-secrets-sdk-go"

client, err := workloadsecrets.New(workloadsecrets.ClientOptions{
	BaseURL:       "https://example.delinea.app/workload-secrets",
	TokenEndpoint: "https://example.delinea.app/identity/oauth2/token/xpmplatform",
	ClientID:      "my-service-user@example",
	ClientSecret:  clientSecret, // from your secret store or environment, never from source code
})
if err != nil {
	return err
}

secret, err := client.GetSecret(ctx, "ci/payments/api")
if err != nil {
	return err
}

apiKey := secret.Data["apiKey"].(string)

secret.Data holds the secret's values as plain Go values, the way encoding/json decodes JSON: string, bool, float64, []any and map[string]any. Use the values in your application. Never print or log them.

secret.Version and secret.CreatedTime describe the version you read. To read an older version, use client.GetSecretVersion(ctx, path, version).

The client is safe to use from many goroutines. Create one and reuse it.

Dynamic secrets

A dynamic secret holds no stored values. Each call to MintSecret creates a new credential with a lease, and the credential stops working when the lease expires. Dynamic secrets are available from the December 10, 2026 private preview.

credential, err := client.MintSecret(ctx, "ci/payments/pg-db")
if err != nil {
	return err
}

username := credential.Data["username"].(string)
password := credential.Data["password"].(string)
expiresAt := credential.Lease.ExpiresAt // a time.Time

credential.Data["type"] says which values it holds:

type Values
database username, password
azure tenantId, clientId, clientSecret

Mint once and reuse the credential until its lease is close to expiring: every call creates another credential. Reading a dynamic secret with GetSecret fails with ErrConflict, and so does minting a secret that is not dynamic.

Bring your own token

Instead of a client ID and secret, give the client a TokenSource: any value with a Token method that returns an access token, without the Bearer prefix.

type myTokenSource struct{}

func (myTokenSource) Token(ctx context.Context) (string, error) {
	return getTokenFromMyPlatform(ctx) // cache it, and refresh it before it expires
}

client, err := workloadsecrets.New(workloadsecrets.ClientOptions{
	BaseURL:     "https://example.delinea.app/workload-secrets",
	TokenSource: myTokenSource{},
})

The SDK calls Token once per request, so cache the token in your source. Add an Invalidate(rejected string) method if your source can renew a token early: when the API rejects a token with 401, the SDK calls it, asks for a token again, and resends the request once if the token changed.

Errors

Error When
ErrNotFound 404: no secret at that path or version
ErrForbidden 403: signed in, but not allowed. Check the roles and Workload Secrets Vault policies
ErrUnauthorized 401: the credentials or token were not accepted
ErrConflict 409: for example, reading a dynamic secret, which must be minted

Test for them with errors.Is:

secret, err := client.GetSecret(ctx, path)
if errors.Is(err, workloadsecrets.ErrNotFound) {
	// no secret at that path
}

Every error the API returns is an *APIError. Use errors.As to read its StatusCode, ErrorCode and Title. Any other error means the call could not complete: the API was unreachable, the call timed out, or sign-in failed. No error message contains a response body or a secret value.

Behavior

  • Retries. Reads are retried on 408, 429, 502, 503 and 504 and on connection failures, up to 4 attempts, with exponential backoff and jitter. Retry-After is honoured up to 30 seconds. A request that changes data, such as a mint, is retried only when the API proves it did nothing: the connection was never made, 429, or 503 with Retry-After.
  • Timeouts. 15 seconds per attempt and 60 seconds for the whole call, including retries. Change them with Behavior.PerAttemptTimeout and Behavior.TotalTimeout. The ctx you pass can end a call sooner.
  • Redirects. 307 and 308 are followed to the same host only, so your token is never sent to another host.
  • HTTPS only. New refuses a plain http:// address, except localhost, 127.0.0.1 or ::1 for local testing, so a token or the client secret is never sent in clear text.
  • Logging. Set Logger to an *slog.Logger to get a debug record for each retry: method, path, attempt, wait, status and error text, never headers or bodies.

TLS and proxies

By default the SDK sends requests through http.DefaultTransport, which honours HTTPS_PROXY and NO_PROXY and verifies the server certificate against the operating system's trusted certificates. If your network inspects TLS traffic, pass a transport that trusts your company's certificate:

pem, err := os.ReadFile("/path/to/company-ca.pem")
if err != nil {
	return err
}
roots, err := x509.SystemCertPool()
if err != nil {
	return err
}
roots.AppendCertsFromPEM(pem)

transport := http.DefaultTransport.(*http.Transport).Clone()
transport.TLSClientConfig = &tls.Config{RootCAs: roots, MinVersion: tls.VersionTLS12}

client, err := workloadsecrets.New(workloadsecrets.ClientOptions{
	// ...
	Transport: transport,
})

Security

  • Printing a Secret (with fmt or log/slog) shows its path, version and key names, never its values.
  • Printing ClientOptions (with fmt or log/slog) never shows the client secret.
  • Errors never carry a response body or a secret value.
  • Each statement above is checked by the SDK's tests (secret_test.go, https_only_test.go).

The full API

client.API() is the generated client for the whole Workload Secrets Vault API, for calls this SDK does not wrap. It uses the same credentials, retries and timeouts.

Development

go build ./...
go test ./...
go vet ./...

The generated package is produced by scripts/regen-go-client.sh from the API contract. Do not edit it by hand.

Documentation

Overview

Package workloadsecrets reads secrets from Delinea Workload Secrets Vault in a Go application.

Create one Client with New and reuse it: it is safe for concurrent use.

client, err := workloadsecrets.New(workloadsecrets.ClientOptions{
	BaseURL:       "https://example.delinea.app/workload-secrets",
	TokenEndpoint: "https://example.delinea.app/identity/oauth2/token/xpmplatform",
	ClientID:      "my-service-user@example",
	ClientSecret:  os.Getenv("WS_CLIENT_SECRET"), // never from source code
})
if err != nil {
	return err
}
secret, err := client.GetSecret(ctx, "ci/payments/api")
if err != nil {
	return err
}
apiKey := secret.Data["apiKey"].(string)

Reading and minting

Client.GetSecret reads the latest version of a secret and Client.GetSecretVersion reads one version. Client.MintSecret creates a new credential for a dynamic secret and returns it with its Lease; every call creates another credential, so mint once and reuse it until the lease is close to expiring. Dynamic secrets are available from the December 10, 2026 private preview.

Signing in

By default the client signs in with a client ID and secret at TokenEndpoint. To use a token you already have, for example from workload identity federation, set ClientOptions.TokenSource instead.

Errors

Failures from the API are *APIError and match ErrNotFound, ErrForbidden, ErrUnauthorized or ErrConflict with errors.Is. No error message contains a response body or a secret value.

Security

  • Only https addresses are accepted, except plain http to localhost, 127.0.0.1 or ::1 for local testing, so a token or the client secret is never sent in clear text.
  • Printing a Secret shows its path, version and key names, never its values.
  • Printing ClientOptions never shows the client secret.
  • Redirects are followed to the same host only, so a token never reaches another host.

Behavior

Reads are retried on 408, 429, 502, 503, 504 and connection failures, up to 4 attempts with backoff and jitter; a mint is retried only when the API proves it did nothing. Each attempt is limited to 15 seconds and the whole call to 60 seconds; change them with ClientOptions.Behavior.

The full API

Client.API returns the generated client for every Workload Secrets Vault API operation, with the same credentials, retries and timeouts.

Example (Errors)

Handle the usual failures with errors.Is, and read the details of any API error with errors.As.

client := newClient()

_, err := client.GetSecret(context.Background(), "ci/payments/api")
switch {
case err == nil:
	// use the secret
case errors.Is(err, workloadsecrets.ErrNotFound):
	fmt.Println("no secret at that path")
case errors.Is(err, workloadsecrets.ErrForbidden):
	fmt.Println("signed in, but a policy does not allow this read")
default:
	var apiErr *workloadsecrets.APIError
	if errors.As(err, &apiErr) {
		fmt.Println(apiErr.StatusCode, apiErr.ErrorCode)
	}
	log.Fatal(err)
}

Index

Examples

Constants

This section is empty.

Variables

View Source
var (
	// ErrUnauthorized: the API rejected the token (401). Check the credentials, tenant and token endpoint.
	ErrUnauthorized = errors.New("workload secrets: unauthorized")
	// ErrForbidden: an authorization policy denies the call (403).
	ErrForbidden = errors.New("workload secrets: forbidden")
	// ErrNotFound: nothing exists at the path, or that version (404).
	ErrNotFound = errors.New("workload secrets: not found")
	// ErrConflict: the request conflicts with the current state (409), for example an engine that must be upgraded.
	ErrConflict = errors.New("workload secrets: conflict")
)

Sentinel errors for the failures a caller usually handles. Test with errors.Is; an *APIError matches the one for its status code.

Functions

func NewClient

NewClient builds a WorkloadSecretsApiClient wired with retry and the tenant header, authenticated either via OAuth2 client-credentials (the default) or via options.TokenSource when set.

func NewHTTPClient

func NewHTTPClient(options ClientOptions) *http.Client

NewHTTPClient builds the same authenticated (retry + tenant header + bearer/OAuth2) *http.Client NewClient wires internally, for callers that need to issue requests the generated SDK can't express (e.g. a multipart/form-data body) against the same tenant/credentials. It carries no base URL — callers resolve request URLs themselves.

Types

type APIError

type APIError struct {
	StatusCode int
	// ErrorCode is the API's machine-readable code (for example "secret_not_found"); empty when the response had no
	// Problem Details body.
	ErrorCode string
	Title     string
	// contains filtered or unexported fields
}

APIError is an error response from the Workload Secrets API. Its message carries the status, the API's errorCode and title, never a response body or a secret value. Unwrap returns the generated client's error.

func (*APIError) Error

func (e *APIError) Error() string

func (*APIError) Is

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

Is reports whether target is the sentinel error for e's status code.

func (*APIError) Unwrap

func (e *APIError) Unwrap() error

type Behavior

type Behavior struct {
	// PerAttemptTimeout bounds one attempt, including reading the response headers. Default 15 s.
	PerAttemptTimeout time.Duration
	// TotalTimeout bounds the whole call: every attempt and every wait between attempts. Default 60 s.
	TotalTimeout time.Duration
}

Behavior tunes the SDK's resilience. A zero value keeps the default.

type Client

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

Client reads secrets and mints dynamic credentials with one call each. Anything else the API offers is on API(), the generated client, which uses the same credentials, retries and timeouts.

func New

func New(options ClientOptions) (*Client, error)

New builds a Client from options. It wires the same transport chain as NewClient: tenant header, retries that obey the API's retry-safety flags, the bearer token and same-origin redirects.

Example

Sign in with a client ID and secret. The secret comes from the environment, never from source code.

client, err := workloadsecrets.New(workloadsecrets.ClientOptions{
	BaseURL:       "https://example.delinea.app/workload-secrets",
	TokenEndpoint: "https://example.delinea.app/identity/oauth2/token/xpmplatform",
	ClientID:      "my-service-user@example",
	ClientSecret:  os.Getenv("WS_CLIENT_SECRET"),
})
if err != nil {
	log.Fatal(err)
}
_ = client // create one client and reuse it

func (*Client) API

API returns the generated client, for the operations Client has no call for.

func (*Client) GetSecret

func (c *Client) GetSecret(ctx context.Context, path string) (*Secret, error)

GetSecret reads the latest version of the secret at path. Reading changes nothing. A dynamic secret holds no values to read: the API refuses it with a conflict, and MintSecret creates its credential. Failures from the API are *APIError and match ErrNotFound, ErrForbidden, ErrUnauthorized or ErrConflict with errors.Is.

Example

Read the latest version of a secret and use one of its values.

client := newClient()

secret, err := client.GetSecret(context.Background(), "ci/payments/api")
if err != nil {
	log.Fatal(err)
}
fmt.Println(secret) // safe: shows the path, version and key names, never the values

apiKey := secret.Data["apiKey"].(string)
_ = apiKey // use the value; never print or log it

func (*Client) GetSecretVersion

func (c *Client) GetSecretVersion(ctx context.Context, path string, version int) (*Secret, error)

GetSecretVersion reads one version of the secret at path. Otherwise it behaves like GetSecret.

Example

Read one version of a secret.

client := newClient()

secret, err := client.GetSecretVersion(context.Background(), "ci/payments/api", 2)
if err != nil {
	log.Fatal(err)
}
fmt.Println(secret.Version, secret.CreatedTime.Format(time.RFC3339))

func (*Client) MintSecret

func (c *Client) MintSecret(ctx context.Context, path string) (*Secret, error)

MintSecret creates a credential for the dynamic secret at path and returns it with its Lease. Every call creates another credential, so the call is never resent once the request may have reached the API (see the retry rules). A secret that is not dynamic is refused with a conflict. Dynamic secrets are available from the December 10, 2026 private preview. Failures from the API are *APIError and match ErrNotFound, ErrForbidden, ErrUnauthorized or ErrConflict with errors.Is.

Example

Mint a database credential from a dynamic secret. Every call creates another credential, so mint once and reuse it until its lease is close to expiring. Dynamic secrets are available from the December 10, 2026 private preview.

client := newClient()

credential, err := client.MintSecret(context.Background(), "ci/payments/pg-db")
if err != nil {
	log.Fatal(err)
}
if credential.Data["type"] == "database" {
	username := credential.Data["username"].(string)
	password := credential.Data["password"].(string)
	_, _ = username, password // connect to the database with them
}
fmt.Println("expires", credential.Lease.ExpiresAt.Format(time.RFC3339))

type ClientOptions

type ClientOptions struct {
	BaseURL       string
	TenantID      string
	ClientID      string
	ClientSecret  string
	TokenEndpoint string

	// TokenSource, when set, bypasses the ClientID/ClientSecret/TokenEndpoint
	// OAuth2 client-credentials flow and supplies the bearer token directly —
	// the seam a caller with its own token-acquisition flow (e.g. the CLI's
	// device-code login) uses to feed NewClient a token it acquired itself.
	TokenSource TokenSource

	// Behavior overrides the default timeouts.
	Behavior Behavior

	// Transport is the base round tripper requests are finally sent through, for a proxy or custom TLS settings.
	// Default http.DefaultTransport.
	Transport http.RoundTripper

	// Logger receives a debug record for each retry. Nil logs nothing. Records carry the method, path, attempt,
	// wait, status and error text, never headers or bodies.
	Logger *slog.Logger
}

ClientOptions is per-environment configuration for the Workload Secrets Public API SDK.

Example (TokenSource)

Use a token you already have, for example from workload identity federation, instead of a client ID and secret.

client, err := workloadsecrets.New(workloadsecrets.ClientOptions{
	BaseURL:     "https://example.delinea.app/workload-secrets",
	TokenSource: platformTokenSource{},
})
if err != nil {
	log.Fatal(err)
}
_ = client

func (ClientOptions) GoString

func (o ClientOptions) GoString() string

GoString is String, so %#v hides the client secret too.

func (ClientOptions) LogValue

func (o ClientOptions) LogValue() slog.Value

LogValue keeps the client secret out of log/slog records.

func (ClientOptions) String

func (o ClientOptions) String() string

String shows the options without the client secret, so printing or logging them never leaks it.

type Lease

type Lease struct {
	ID        string
	ExpiresAt time.Time
}

Lease identifies the credential a mint created, and when it expires.

type RedirectNotFollowedError

type RedirectNotFollowedError struct {
	StatusCode int
	Location   string
}

RedirectNotFollowedError is returned when the API answers with a redirect to a different origin. The request is not sent there, so neither the request nor its credentials leave the configured origin. Without an error, the generated client would treat the bodyless 3xx as a successful empty result.

func (*RedirectNotFollowedError) Error

func (e *RedirectNotFollowedError) Error() string

type Secret

type Secret struct {
	Path string
	// Version and CreatedTime describe the version a read returned. They are zero for a minted credential.
	Version     int
	CreatedTime time.Time
	// Data holds the secret's values as plain Go values, the way encoding/json decodes JSON. Nested objects are kept; a
	// top-level key whose value is JSON null is absent. A minted credential holds "type" ("database" or "azure") and
	// its strings: username and password, or tenantId, clientId and clientSecret.
	Data map[string]any
	// Lease is set by MintSecret: the credential in Data stops working at Lease.ExpiresAt. Nil for a static secret.
	Lease *Lease
}

Secret is one version of a secret, or the credential a mint created. Printing it (fmt, or slog) shows the path, version and key names, never the values: read a value from Data explicitly.

func (*Secret) GoString

func (s *Secret) GoString() string

GoString keeps %#v from printing values.

func (*Secret) LogValue

func (s *Secret) LogValue() slog.Value

LogValue keeps slog from printing values.

func (*Secret) String

func (s *Secret) String() string

String shows the path, version and key names, never a value.

type TokenSource

type TokenSource interface {
	Token(ctx context.Context) (string, error)
}

TokenSource supplies a bearer access token for outgoing API requests. Implementations may cache and refresh the token internally; NewClient calls Token once per outgoing request.

Directories

Path Synopsis
api

Jump to

Keyboard shortcuts

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