Documentation
¶
Overview ¶
Package bws is a thin pure-Go REST client for Bitwarden Secrets Manager (BWS) machine accounts — the first secret.Source implementation. It speaks the live wire contract directly (no SDK: the official Go SDK is CGO and would break the CGO_ENABLED=0 cross-compile), with arbitrary instance bases (dedicated api.<host> and path-prefixed vault.<host>/api) and stdlib-only crypto.
Index ¶
- Variables
- func CachedInstances() ([]string, error)
- func DeleteCredential(apiURL string) (bool, error)
- func IsUUIDRef(s string) bool
- func NormalizeURL(raw string) (string, error)
- func ParseAccessToken(token string) (clientID, clientSecret string, seed []byte, err error)
- func SaveCredential(cred Credential) error
- type Client
- func (c *Client) Exchange(ctx context.Context) (*TokenResponse, error)
- func (c *Client) GetSecretByRef(ctx context.Context, ref string) (*Secret, error)
- func (c *Client) ListSecrets(ctx context.Context) ([]Secret, error)
- func (c *Client) UpdateSecret(ctx context.Context, req SecretUpdateRequest) error
- type Credential
- type EncString
- type Project
- type Secret
- type SecretUpdateRequest
- type Source
- type TokenResponse
Constants ¶
This section is empty.
Variables ¶
ErrUnauthorized is the sentinel wrapped by every Exchange 401 error: the identity server rejected the machine-account token. Callers match it with errors.Is — never by string-matching the unioned message, whose text is pinned by goldens and docs and must stay verbatim.
Functions ¶
func CachedInstances ¶
CachedInstances returns the normalized API URLs of every cached instance login, sorted — the offline enumeration logout's truth table rides (zero, one or many cached instances). Deliberately env-free: unlike ResolveCredential it never consults MCPCLI_BWS_API_URL, because the env selects credentials for the reading verbs, it is not a cache target.
func DeleteCredential ¶
DeleteCredential removes the credential for apiURL (normalized). A missing instance reports (false, nil) — but unlike a silently-nil delete, callers can distinguish it from a real removal.
func IsUUIDRef ¶
IsUUIDRef reports whether s has the shape of a UUID: 36 characters with hyphens at positions 8/13/18/23 and hex digits (in BOTH cases — uuid.Parse parity) elsewhere. It routes bws:// refs — a uuid ref is fetched by id directly, anything else is treated as a secret name — and shape-checks org ids before path interpolation.
shortcut: a secret NAMED like a UUID is unreachable by name (its ref is routed to the by-id GET); upgrade when namespaced refs exist.
func NormalizeURL ¶
NormalizeURL canonicalizes an instance base URL for both the API and the identity endpoints. An absolute URL with an http/https scheme and a non-empty hostname is required; trailing slashes are trimmed, the host is lowercased and the scheme's own default port is stripped (443 for https, 80 for http — scheme-matched, so :443 on http survives); a path prefix is kept. URLs carrying userinfo, a query/fragment, or an empty hostname — bare or port-bearing, e.g. http://:8080 — are rejected (fail-closed-minimal; an empty hostname would dial the local system). There is no scheme defaulting and no hostname rewriting.
func ParseAccessToken ¶
ParseAccessToken splits a machine-account access token "0.<api-key-id>.<client-secret>:<b64 16-byte seed>" into its parts. The seed never leaves the process (it derives the key that decrypts the exchange response's encrypted_payload). Version and seed errors carry the OBSERVED version/length: Bitwarden has demonstrably rotated wire formats.
func SaveCredential ¶
func SaveCredential(cred Credential) error
SaveCredential upserts the credential under sha256 of its normalized APIURL. The URL is also normalized into the stored value: hash keys are not reversible, and every error listing renders the stored form.
Types ¶
type Client ¶
type Client struct {
// contains filtered or unexported fields
}
Client is a thin BWS REST client for one instance. It is deliberately single-goroutine per run: the exchange memo below is a plain field, not a sync.Once, and a Client (or its wrapping Source) must not be shared across goroutines.
func NewClient ¶
NewClient builds a Client for one instance. Both URLs are caller-supplied (zero domain knowledge: dedicated and path-prefixed bases are equally valid); they are assumed pre-normalized — SaveCredential and the Source normalize — but NewClient normalizes defensively so a raw input still yields working request URLs. A normalization failure keeps the raw form and the request-time URL parse fails loudly. NewClient never fails: a malformed access token surfaces on first use.
func (*Client) Exchange ¶
func (c *Client) Exchange(ctx context.Context) (*TokenResponse, error)
Exchange performs the client-credentials exchange against the identity server: POST {identity}/connect/token with form-encoded grant_type/client_id/client_secret/scope. A 401 carries the runtime unioned message naming both causes (stale/rotated token or identity-URL mismatch); other non-2xx statuses carry the status and a bounded body; a 2xx parse failure is a shape error WITHOUT the body.
func (*Client) GetSecretByRef ¶
GetSecretByRef resolves one ref to a secret — the shared leaf used by both Source.Resolve and the CLI. A uuid ref is fetched by id; anything else is a name resolved against the org's secret list (decrypted-key match, exactly one). Fail-closed: CanRead=false (grant-read cause) or an empty decrypted value (content cause) is an error naming the ref, the two causes distinguished. A NUL-bearing value is rejected naming the decrypted KEY.
func (*Client) ListSecrets ¶
ListSecrets lists the org's secrets (metadata only, values absent from the wire) and decrypts each listed key. A non-empty continuationToken fails loud with its value: pagination is unsupported this round.
func (*Client) UpdateSecret ¶
func (c *Client) UpdateSecret(ctx context.Context, req SecretUpdateRequest) error
UpdateSecret PUTs the updated secret: key/value/note are encrypted with the org key, the body carries exactly the wire fields {id, organizationId, key, value, note, projectIds, valueChanged}.
type Credential ¶
type Credential struct {
APIToken string `json:"api_token"`
OrgID string `json:"org_id"`
APIURL string `json:"api_url"`
IdentityURL string `json:"identity_url"`
}
Credential is one stored Bitwarden machine-account login: the machine-account access token (NOT the short-lived exchange JWT — that is per-run and never persisted), the org id for name refs, and the two instance URLs. The field name APIToken (vs NewClient's accessToken parameter) is deliberate: it names what is stored — the long-lived machine-account token — as opposed to the per-run exchange JWT.
func ResolveCredential ¶
func ResolveCredential(apiURLFlag string) (Credential, error)
ResolveCredential resolves the Bitwarden instance to use, consult-in-order: the --api-url flag beats the MCPCLI_BWS_API_URL environment variable beats the cache. An empty flag slot is UNSET, not invalid (the expansion path calls ResolveCredential("")). The env is never examined when the flag wins. Every failure names its input; a valid-but-uncached selector fails closed naming the cached instances and the remediation. Resolution never validates the credential against the network — a token rejected later at Exchange is the caller's 401 message.
type EncString ¶
type EncString string
EncString is a Bitwarden encrypted string: "2.<iv b64>|<ct b64>|<mac b64>" — AES-256-CBC with HMAC-SHA256 over iv‖ct.
type Project ¶
Project is one project association on a Secret. The live wire (re-proved against the real EU instance) carries an array of these objects — not id strings — with Name an EncString decrypted in place under the same policy as the Secret fields. Exported because the CLI layer's fakes and outputs construct and read it by name.
type Secret ¶
type Secret struct {
ID string `json:"id"`
OrganizationID string `json:"organizationId"`
Key string `json:"key"`
Value string `json:"value"`
Note string `json:"note"`
CanRead bool `json:"read"`
CanWrite bool `json:"write"`
RevisionDate time.Time `json:"revisionDate"`
Projects []Project `json:"projects"`
}
Secret is one BWS secret. It doubles as the wire-decode shape (json tags keep the wire's lowercase read/write; there is deliberately no CreationDate field — nothing pins it) and the decrypted result: Key, Value, Note and each Project Name hold EncStrings after decode and are decrypted in place.
type SecretUpdateRequest ¶
type SecretUpdateRequest struct {
ID string `json:"id"`
OrganizationID string `json:"organizationId"`
Key string `json:"key"`
Value string `json:"value"`
Note string `json:"note"`
ProjectIDs []string `json:"projectIds"`
ValueChanged bool `json:"valueChanged"`
}
SecretUpdateRequest is the body for PUT /secrets/{id}. ID, OrganizationID, Key, Value and Note carry plaintext; UpdateSecret encrypts key/value/note with the org key so the wire form is EncStrings (the org key is unexported, so no caller could pre-encrypt). The explicit json tags on every field are load-bearing: the server rejects unknown fields and untagged fields would silently drop out of the request.
type Source ¶
type Source struct {
// contains filtered or unexported fields
}
Source resolves bws:// references against a Bitwarden Secrets Manager instance. It is the first secret.Source implementation: the Resolver hands it whatever follows "bws://" (or "BWS://" — the scheme is lowercased before dispatch) and this type owns the ref grammar.
func (*Source) Resolve ¶
Resolve resolves ref (a secret uuid or name) to its decrypted value. The credential is loaded lazily via ResolveCredential("") — the expansion path's empty-flag call form — and the Client is constructed once for the run. Fail-closed throughout: an unresolvable credential, a CanRead=false grant or an empty value is an error naming the ref.
type TokenResponse ¶
type TokenResponse struct {
AccessToken string `json:"access_token"`
EncryptedPayload EncString `json:"encrypted_payload"`
}
TokenResponse is the decoded POST {identity}/connect/token envelope. The explicit json tags are load-bearing: underscores break encoding/json's case-insensitive fallback and untagged fields would silently decode empty.