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/
Breaking Change in v1.7.0: The minimum Go version has been upgraded to 1.16+.
Download and Installation
Install from GitHub
Find the latest Go SDK release at: https://github.com/Keeper-Security/secrets-manager-go
For more information, see https://pkg.go.dev/github.com/keeper-security/secrets-manager-go/core
Source Code
Find the Go source code in the GitHub repository
Using the SDK
Initialize
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:
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
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
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
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
See Keeper Notation documentation to learn about Keeper Notation format and capabilities
query
string
Keeper Notation query for getting a value from a specified field
Returns
Type: []interface{}
The value of the queried field
GetNotationResults
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
url
string
TOTP URL string
Update a Secret
Record update commands don't update local record data on success (esp. updated record revision) so any consecutive updates to an already updated record will fail due to revision mismatch. Make sure to reload all updated records after each update batch.
Update Password
password
string
New password to set to the record
Update Other Fields
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.
record
*Record
Record with updated field to save changes for
Example Usage
Update Password
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
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
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
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
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
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
ownerRecord
Record
The record to attach the uploaded file to
file
KeeperFileUpload
The file to upload
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
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.
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
recordUid
string
No
auto generated random UID
folderUid
string
Yes
record
*RecordCreate
Yes
recordUid is optional. Pass "" and the SDK generates a UID automatically.
createOptions
*CreateOptions
Yes
recordData
*RecordCreate
Yes
folders
[]*KeeperFolder
No
Pass nil for folders and the SDK fetches the folder list automatically.
This example creates a login type record with a login value and a generated password.
Replace [FOLDER UID] in the example with the UID of a shared folder that your Secrets Manager has access to.
Replace [FOLDER UID] in the example with the UID of a shared folder that your Secrets Manager has access to.
This example creates a record with a custom record type.
Delete a Secret
The Go KSM SDK can delete records in the Keeper Vault.
recordUids
[]string
UIDs of records to delete
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.go 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.
Last request only: The cache stores only the most recent response. If your last successful call fetched records by UID filter, a cache fallback will return only those records — not all records shared with the application. Design your cache usage accordingly.
After updates: Saving a record changes its revision in the vault. If the SDK falls back to cache after an update, the cached revision is stale and further updates to the same record will fail with a revision mismatch. Always call GetSecrets after saving to refresh the cache.
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.
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.
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.
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.
Any folders UIDs missing from the vault or not shared to the KSM Application will not result in error.
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:
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):
HTTPS_PROXYorhttps_proxy- Preferred for HTTPS trafficHTTP_PROXYorhttp_proxy- Fallback proxy configurationNO_PROXYorno_proxy- Comma-separated list of hosts to bypass proxy
Examples:
Basic proxy:
Authenticated proxy:
Proxy with bypass list:
Example:
Special characters in credentials: URL-encode special characters in usernames and passwords using percent-encoding (e.g., @ becomes %40, ! becomes %21).
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:
Generate the base64 config value from an existing ksm-config.json file:
KSM_CONFIG is only read when ClientOptions.Config is nil. If you pass a Config value explicitly, the environment variable is ignored.
Configuration File Security
When using NewFileKeyValueStorage(), the SDK automatically:
Creates new configuration files with permissions
0600(user read/write only)Restricts access to the file owner, preventing other users from reading credentials
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
*.jsonto.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
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:
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
Breaking Change in v1.7.0: nil returns on decryption failure
The following functions now return nil when decryption fails, instead of returning an empty stub:
NewRecordFromJsonon record key or record data decryption failureNewFolderFromJson/NewKeeperFolderon folder decryption failureNewKeeperFileFromJsonon file key decryption failure
GetSecrets now returns an error when app key decryption fails in the just-bound flow, instead of returning an empty list with a nil error.
If you call these functions directly, add nil checks before dereferencing the return value.
Breaking Change in v1.7.0: HTTP error string format
The error string returned for JSON error responses now includes an HTTPStatus=N prefix (e.g., POST Error: HTTPStatus=403 Error: access_denied, message=...). Previously the JSON-error path returned no status code in the error string. Callers that parse error strings should migrate to errors.As(err, &khe) and inspect khe.StatusCode, khe.ResultCode, and khe.Message directly.
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 accessNon-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:
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?

