Go SDK

Detailed Go SDK docs for Keeper Secrets Manager

Requirements

The Go SDK requires Go 1.16 or higher.

To check your Go version:

If you need to upgrade Go, visit https://go.dev/dl/arrow-up-right

circle-exclamation

Download and Installation

Install from GitHub

Find the latest Go SDK release at: https://github.com/Keeper-Security/secrets-manager-goarrow-up-right

For more information, see https://pkg.go.dev/github.com/keeper-security/secrets-manager-go/corearrow-up-right

Source Code

Find the Go source code in the GitHub repositoryarrow-up-right

Using the SDK

Initialize

circle-info

Using token only to generate a new config (for later usage) requires at least one read operation to bind the token and fully populate config.json

In order to retrieve secrets, you must first initialize the secrets manager client.

ClientOptions Parameters:

Parameter
Type
Required
Default
Description

Token

string

First run only

-

One-Time Access Token with region prefix (e.g., US:...). Required for initial binding.

Config

IKeyValueStorage

Yes

-

Storage implementation for configuration persistence (file or memory-based).

HostName

string

No

Derived from token

Override server hostname. Automatically set based on token region prefix.

VerifySslCerts

bool

No

true

Enable/disable SSL certificate verification.*

The NewSecretsManager function will initialize Secrets Manager from provided parameters and store settings from ClientOptions struct.

Retrieve Secrets

Parameter
Type
Description

uids

[]string

Record UIDs to retrieve. Pass empty slice []string{} to retrieve all records

Response

Type: []*Record

Records with the specified UIDs, or all records shared with the Secrets Manager client if no UIDs are provided

Example Usage

Retrieve all Secrets

Retrieve Secrets with a Filter

Retrieve Secrets by Title

Parameter
Type
Description

recordTitle

string

Record title to search for

Example Usage

Get Values From a Secret

Get a Password

Returns the password field value for login type records. Returns an empty string for other record types.

Get a Password by Field Value

Parameter
Type
Description

fieldType

string

Field type (e.g. login, url)

Returns the first value of the matching standard field as a string. Returns an empty string if the field does not exist. For multi-value fields or structured fields, use GetFieldsByType.

Field types are based on the Keeper Record Type. For a detailed list of available fields based on the Keeper Record Type, see the record-type-info command in Keeper Commander.

Retrieve Values using Keeper Notation

GetNotation

circle-info

See Keeper Notation documentation to learn about Keeper Notation format and capabilities

Parameter
Type
Description

query

string

Keeper Notation query for getting a value from a specified field

Returns

Type: []interface{}

The value of the queried field

GetNotationResults

Parameter
Type
Description

notation

string

Keeper Notation query

GetNotationResults returns field values as []string. Use this instead of GetNotation when the field value is a string. TryGetNotationResults is the error-suppressing variant. It returns an empty slice instead of propagating the error.

Example Usage

Retrieve TOTP Code

Parameter
Type
Description

url

string

TOTP URL string

Update a Secret

circle-exclamation

Update Password

Parameter
Type
Description

password

string

New password to set to the record

Update Other Fields

Parameter
Type
Description

field

string

Name of the field to update

value

string

Value to set the field to

Update Secret in Vault

Save the record to make the changes made appear in the Keeper Vault.

Parameter
Type
Description

record

*Record

Record with updated field to save changes for

Example Usage

Update Password

circle-info

CompleteTransaction(uid, rollback bool) passes false to commit the rotation, true to roll back. The example passes !success which evaluates to true (rollback) when your rotation function returns false (failed).

Update other fields

circle-info

v1.7.0: SetNotes now uses UPSERT behavior. It creates the notes field if it does not exist on the record. In v1.6.x and earlier, calling SetNotes on a record without an existing notes field was a silent no-op.

Each record field type is represented by a class. Cast the field to the corresponding class in order to correctly access the field's value. Check the Record Types documentation for a list of field types.

Generate a Random Password

Parameter
Type
Description

length

int

Password length. Pass 0 or negative to use default (32 characters)

lowercase

string

Minimum lowercase letters. Pass "" for no minimum

uppercase

string

Minimum uppercase letters. Pass "" for no minimum

digits

string

Minimum digits. Pass "" for no minimum

specialCharacters

string

Minimum special characters. Pass "" for no minimum

specialCharacterSet

string

Custom special character set. Pass "" to use default: "!@#$%()+;<>=?[]{}^.,"

Download a File

DownloadFileByTitle

Parameter
Type
Description

title

string

Name of file to download

path

string

Path to save the file to

Response

Type: error

Returns nil on success. Returns an error describing the failure: file title not found, directory does not exist, or write failure. Pass the error to your logger or wrap it for the caller.

Example Usage


DownloadFile

Parameter
Type
Description

fileUid

string

UID of the file to download

path

string

Path to save the file to

Response

Type: error

Returns nil on success. Returns an error if no file with the given UID is attached to the record, the directory does not exist, or the write fails.

Example Usage


SaveFile

Parameter
Type
Description

path

string

Full file path to write to

createFolders

bool

If true, creates missing parent directories

Response

Type: error

Returns nil on success. Returns an error if the directory does not exist (and createFolders is false) or the write fails. Use when you have a *KeeperFile directly from record.Files.

Example Usage

Upload a File

Parameter
Type
Description

ownerRecord

Record

The record to attach the uploaded file to

file

KeeperFileUpload

The file to upload

Field
Type
Description

Name

string

Required. File name in Keeper once uploaded

Title

string

Required. File title in Keeper once uploaded

Type

string

Required. MIME type of the file data (e.g., application/octet-stream)

Data

[]byte

Required. File data as bytes

Example Usage

Upload a File from Path

Parameter
Type
Description

record

*Record

The record to attach the uploaded file to

filePath

string

Local path of the file to upload

Response

Type: string, error

Returns the UID of the uploaded file attachment. Use this instead of UploadFile when uploading directly from disk — it reads the file, infers the MIME type, and calls UploadFile internally.

Example Usage

Removing Files from Records

To remove files from a record, specify the file UIDs in the LinksToRemove field when calling SaveWithOptions():

Removing multiple files:

UpdateOptions

UpdateOptions controls optional behavior for SaveWithOptions and SaveBeginTransaction.

Field
Type
Description

TransactionType

UpdateTransactionType

Set to Rotation for two-phase transactional updates. Omit for standard saves.

LinksToRemove

[]string

File UIDs to detach from the record on save.

Create a Secret

Prerequisites:

  • Shared folder UID

    • Shared folder must be accessible by the Secrets Manager Application

    • You and the Secrets Manager application must have edit permission

    • There must be at least one record in the shared folder

  • Created records and record fields must be formatted correctly

    • See the documentation for expected field formats for each record type

  • TOTP fields accept only URL generated outside of the KSM SDK

  • After record creation, you can upload file attachments using UploadFile

Parameter
Type
Required
Default

recordUid

string

No

auto generated random UID

folderUid

string

Yes

record

*RecordCreate

Yes

recordUid is optional. Pass "" and the SDK generates a UID automatically.

Delete a Secret

The Go KSM SDK can delete records in the Keeper Vault.

Parameter
Type
Description

recordUids

[]string

UIDs of records to delete

Return
Type
Description

statuses

map[string]string

Per-UID deletion status

err

error

Error, if any

UIDs not found in the vault or not accessible to the KSM Application are silently skipped and do not produce an error.

Caching

To protect against losing access to your secrets when network access is lost, the Go SDK allows caching of secrets to the local machine in an encrypted file.

Setup and Configure Cache

In order to setup caching in the Go SDK, use the function SetCache(cache ICache) to set the cache to either one of the built-in memory or file based caches or use your own implementation.

For a complete working ICache implementation demonstrating offline-fallback semantics, see example/custom-cache/main.goarrow-up-right in the SDK repository.

The Go SDK includes a memory based cache and a file based cache for convenience.

The SDK always attempts a live network request first. The cache is consulted as a fallback in two situations: when the server returns a non-200 HTTP response, and when the request fails at the transport layer (DNS resolution failure, connection refused, TLS handshake failure, or timeout). When cached records are served because of a network-level error, a warning is logged. On every successful GetSecrets call, the cache is updated with the latest response.

circle-exclamation
circle-exclamation

Folders

Folders have full CRUD support - create, read, update and delete operations.

Read Folders

Downloads full folder hierarchy.

Response

Type: []*KeeperFolder, error

Example Usage

Create a Folder

Requires CreateOptions and folder name to be provided. The folder UID parameter in CreateOptions is required - UID of a shared folder, while sub-folder UID is optional and if missing new regular folder is created directly under the parent (shared folder). There's no requirement for the sub-folder to be a direct descendant of the parent shared folder - it could be many levels deep.

Parameter
Type
Description

createOptions

CreateOptions

Parent and sub-folder UIDs

folderName

string

Folder name

folders

[]*KeeperFolder

Optional: List of folders for search. Pass nil to fetch automatically

Example Usage

Update a Folder

Updates the folder metadata - currently folder name only.

Parameter
Type
Description

folderUid

string

UID of the folder to update

folderName

string

New folder name

folders

[]*KeeperFolder

Optional: List of folders for search. Pass nil to fetch automatically

Example Usage

Delete Folders

Removes a list of folders. Use forceDeletion flag to remove non-empty folders.

circle-info

When using forceDeletion avoid sending parent with its children folder UIDs. Depending on the delete order you may get an error - ex. if parent force-deleted child first. There's no guarantee that list will always be processed in FIFO order.

circle-info

Any folders UIDs missing from the vault or not shared to the KSM Application will not result in error.

Parameter
Type
Description

folderUids

[]string

UIDs of folders to delete

forceDeletion

bool

Set to true to delete non-empty folders

Example Usage

Advanced Configuration

Token Region Prefixes

Tokens include a region prefix to automatically connect to the correct Keeper data center:

Region Code
Data Center
Hostname

US

United States

keepersecurity.com

EU

Europe

keepersecurity.eu

AU

Australia

keepersecurity.com.au

GOV

US Government Cloud

govcloud.keepersecurity.us

JP

Japan

keepersecurity.jp

CA

Canada

keepersecurity.ca

Example tokens:

The SDK automatically parses the region prefix and connects to the appropriate server. If your token does not include a region prefix, you must specify the Hostname parameter explicitly in ClientOptions.

HTTP Proxy Configuration

The Go SDK automatically detects proxy settings from standard environment variables:

Environment Variables:

The SDK checks the following environment variables (in order of precedence):

  1. HTTPS_PROXY or https_proxy - Preferred for HTTPS traffic

  2. HTTP_PROXY or http_proxy - Fallback proxy configuration

  3. NO_PROXY or no_proxy - Comma-separated list of hosts to bypass proxy

Examples:

Basic proxy:

Authenticated proxy:

Proxy with bypass list:

Example:

circle-exclamation

KSM_CONFIG Environment Variable

For CI/CD pipelines and containerized environments, the SDK automatically loads configuration from the KSM_CONFIG environment variable when no Config is provided in ClientOptions.

Set the environment variable to the base64-encoded JSON config generated after initial device binding:

Then initialize without a config file:

circle-info

Generate the base64 config value from an existing ksm-config.json file:

circle-exclamation

Configuration File Security

When using NewFileKeyValueStorage(), the SDK automatically:

  1. Creates new configuration files with permissions 0600 (user read/write only)

  2. Restricts access to the file owner, preventing other users from reading credentials

  3. Stores encrypted keys and device tokens securely

Check file permissions:

The rw------- (0600) permissions ensure only the file owner can read or write the configuration.

Security best practices:

  • Never commit configuration files to version control (add *.json to .gitignore)

  • Use separate configurations for development, staging, and production environments

  • Rotate One-Time Access Tokens every 90 days

  • Store configuration files in secure, encrypted directories

Error Handling

circle-info

Improved in v1.7.0: HTTP errors are now returned as a typed *core.KeeperHTTPError with StatusCode, ResultCode, and Message fields. Use errors.As to inspect them programmatically rather than parsing error strings. Error message strings also consistently include the HTTP status code on all error paths.

Common HTTP status codes:

Status Code
Error Type
Recommended Action

401

Unauthorized

Re-initialize with new One-Time Token

403

Forbidden

Check application permissions in Secrets Manager

404

Not Found

Verify UID is correct and accessible

429

Too Many Requests

Implement exponential backoff retry logic

500

Internal Server Error

Retry with exponential backoff

503

Service Unavailable

Retry after delay

circle-exclamation
circle-exclamation

Typed HTTP errors

All HTTP errors from GetSecrets and related calls are returned as *core.KeeperHTTPError. Use errors.As to extract structured information instead of parsing error strings.

Error() formats as:

  • JSON response: HTTPStatus=403 Error: access_denied, message=Unable to validate application access

  • Non-JSON response: HTTPStatus=502 HTTPError: Bad Gateway

When returned from GetSecrets, the caller sees: POST Error: HTTPStatus=403 Error: access_denied, message=...

Basic error handling:

Checking for specific HTTP status codes:

Graceful handling of broken records:

circle-info

Resilience Improvement in v1.7.0: The SDK now gracefully handles broken encryption in records, files, and folders instead of failing completely.

If the SDK encounters records or files with broken encryption:

  • Broken records are skipped with a warning logged

  • Broken files are excluded from the file list

  • Broken folders are handled without causing complete failure

  • Valid records are still returned successfully

Last updated

Was this helpful?