For the complete documentation index, see llms.txt. This page is also available as Markdown.

Ruby SDK

Detailed Ruby SDK docs for Keeper Secrets Manager

Keeper Secrets Manager Ruby SDK

Keeper Secrets Manager (KSM) is a zero-knowledge secrets management platform. The Ruby SDK provides programmatic access to your Keeper Vault from Ruby applications.

Requirements

Ruby 3.1 or higher.

Download and Installation

Installation

For more information, see the RubyGems package page

Install with gem

Or add to your Gemfile

Then run:

Source Code

Find the Ruby source code in the GitHub repository

Using the SDK

Initialize Storage

The SDK requires a One-Time Access Token to initialize storage on a client device. After initialization, the SDK stores the configuration for future use.

Parameter
Type
Required
Default
Description

token

String

Optional

nil

One-Time Access Token for initial binding

config

KeyValueStorage

Yes

-

Storage implementation for configuration persistence

hostname

String

Optional

'keepersecurity.com'

API hostname (e.g., 'keepersecurity.eu' for EU datacenter)

verify_ssl_certs

Boolean

Optional

true

Enable/disable SSL certificate verification

Using a One-Time Access Token requires at least one read operation to bind the token and fully populate the configuration.

Example Usage

Using a One-Time Access Token:

Using File-Based Storage

For persistent configuration across application restarts:

Alternatively connect with the base64 configuration file generated by your vault:

Using a Base64 Config String

KeeperSecretsManager.from_config is a convenience initializer for base64-encoded configuration strings, which is the format produced by Commander's export command or stored in environment variables like KSM_CONFIG.

All keyword options accepted by KeeperSecretsManager.new (:hostname, :verify_ssl_certs, :proxy_url, etc.) are supported as a second argument hash.

Using Environment Variables

For read-only configuration from environment. EnvironmentStorage maps each config key to <prefix><KEY.upcase> with no separators inserted, so the variable names do not match the record's camelCase key names directly:

KSM_APPOWNERPUBLICKEY is required by create_secret and upload_file. EnvironmentStorage is read-only, so this value must be set directly as an environment variable; it cannot be populated by binding a One-Time Access Token the way file- or memory-backed storage is.

Binding Lifecycle

The one-time token is redeemed on the first get_secrets() call, not at construction. If you persist config to an external store (AWS Secrets Manager, Azure Key Vault, etc.), read it back only after that call. For the full explanation, see Binding Lifecycle.

Retrieve Secrets

Get Secrets

Parameter
Type
Required
Default
Description

uids

Array<String>

Optional

nil

Record UIDs to retrieve. nil or empty retrieves all secrets.

request_links

Boolean

Optional

false

When true, each returned record's links array is populated with linked-credential entries accessible via record.get_links.

Response:

Type: Array<KeeperRecord>

Array containing all Keeper records, or records that match the given UID filter.

Example Usage

Retrieve All Secrets:

Retrieve Secrets by UID:

Get Secrets by Title

Parameter
Type
Required
Default
Description

title

String

Yes

-

Record title to search for (exact match)

Response:

Type: Array<KeeperRecord> (for get_secrets_by_title) or KeeperRecord (for get_secret_by_title)

Returns all records matching the title, or the first matching record.

Example Usage

Linked Credentials

When a PAM record has linked credentials, pass request_links: true to get_secrets to include them. Call record.get_links to get a typed Array<KeeperRecordLink> view over the raw links array.

KeeperRecordLink accessors — all non-raising (return false/nil on failure):

Accessor
Returns
Description

record_uid

String

UID of the linked record

path

String or nil

Discriminator: "meta", "ai_settings", "jit_settings", or nil for credential links

admin_user?

Boolean

Link grants admin privileges

launch_credential?

Boolean

Link is a launch credential

iam_user?

Boolean

Link is an IAM user credential

allows_rotation?

Boolean

Rotation allowed (reads allowedSettings)

allows_connections?

Boolean

Connections allowed

allows_session_recording?

Boolean

Session recording allowed

allows_port_forwards?

Boolean

Port forwarding allowed

get_link_data(record_key)

Hash or nil

Full parsed link data payload (plain or decrypted)

get_decrypted_data(record_key)

String or nil

AES-256-GCM decrypted data string (for encrypted paths)

get_meta_data

Hash or nil

PAM rotation/connection settings from a "meta" link

get_ai_settings_data(record_key)

Hash or nil

AI settings from an "ai_settings" link

get_jit_settings_data(record_key)

Hash or nil

JIT settings from a "jit_settings" link

record_key is record.record_key (the decrypted record key bytes) and is required only for encrypted link paths (ai_settings, jit_settings). Plain-JSON links parse without a key.

For the full cross-SDK reference, see Linked Credentials.

Retrieve Values From a Secret

Once a secret is retrieved, individual fields can be accessed using multiple approaches:

Using Dynamic Field Access

Using Explicit Field Methods

Using Keeper Notation

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

Error-Safe Notation: try_get_notation

try_get_notation is a non-raising wrapper around get_notation. It returns an Array on success and an empty array [] on any error, so it is safe to use without a rescue block when a missing field should silently produce no value.

get_notation continues to raise NotationError on invalid input and is the correct choice when an error should halt execution.

Array Notation: get_notation_results and try_get_notation_results

get_notation_results resolves a notation URI and always returns an Array of matching values, preserving all elements for multi-value fields (e.g. multiple hosts in a host field). It raises NotationError on invalid input. Complex (non-string) field values are serialized to JSON strings, not returned as Ruby hashes.

try_get_notation_results is the non-raising variant: it logs errors and returns [] instead of raising.

Contrast with get_notation, which returns a scalar (the first value for most selectors), and try_get_notation, which wraps get_notation in Array(). try_get_notation returns a single-element array even when only one value matches. Use get_notation_results when you need the full set of values for a multi-value field.

Inflating Reference Fields

Some PAM record fields store UIDs that reference other records rather than inline values. inflate_field_value resolves those UIDs by fetching the referenced records and returning their field values directly.

Parameter
Type
Required
Description

uids

Array<String>

Yes

UIDs of reference records to resolve

replace_fields

Array<String>

Yes

Field types to extract from the referenced records (e.g. ['address'])

Response:

Type: Array — one entry per resolved UID, with nil entries removed. Each entry is the resolved field value (a String, Hash, or nested Array depending on the field type).

To look up which field types a reference type resolves to, call get_inflate_ref_types:

Field type
Resolves to

addressRef

['address']

cardRef

['paymentCard', 'text', 'pinCode', 'addressRef']

other

[] (unknown ref types return an empty array)

Example Usage

Retrieve a TOTP Code

To generate a TOTP code, retrieve the TOTP URL from the record and use the KeeperSecretsManager::TOTP module. TOTP generation requires the base32 gem (gem install base32) to decode the secret.

Parameter
Type
Required
Default
Description

secret

String

Yes

-

Base32-encoded TOTP secret

algorithm

String

Optional

'SHA1'

Hash algorithm (SHA1, SHA256, SHA512)

digits

Integer

Optional

6

Number of digits in the code

period

Integer

Optional

30

Time period in seconds

Response:

Type: String

Returns the current Time-Based One-Time Password (TOTP) code for two-factor authentication.

Example Usage

Generate a Random Password

Generate cryptographically secure random passwords with customizable character requirements. This utility function is useful when creating or updating secrets programmatically.

Parameter
Type
Required
Default
Description

length

Integer

Optional

64

Total password length

lowercase

Integer

Optional

0

Minimum number of lowercase letters (a-z)

uppercase

Integer

Optional

0

Minimum number of uppercase letters (A-Z)

digits

Integer

Optional

0

Minimum number of digit characters (0-9)

special_characters

Integer

Optional

0

Minimum number of special characters (!@#$%^&*()_+-=[]{}

Response:

Type: String

Returns a cryptographically secure random password meeting the specified requirements.

This function uses Ruby's SecureRandom for cryptographic-strength randomness and applies Fisher-Yates shuffle to ensure proper character distribution.

Example Usage

Generate a default 64-character password:

Generate password with specific requirements:

Use when creating a new secret:

Use when updating an existing secret:

Password rotation script:

PAM Record Types

Use record.type to identify PAM records.

For field schemas of all 11 PAM record types, see PAM Record Types.

PAM Rotation Transactions

complete_transaction finalizes or rolls back a staged PAM rotation update. It is called after update_secret during a rotation workflow to commit the change to the server.

Parameter
Type
Required
Default
Description

record_uid

String

Yes

-

UID of the record whose staged transaction should be finalized

rollback

Boolean

Optional

false

When true, rolls back the staged update instead of committing it

Response:

Type: Boolean, returns true on success.

Example Usage

update_secret stages the change; complete_transaction is what actually commits or discards it. Omitting complete_transaction leaves the change staged indefinitely.

Update a Secret

Parameter
Type
Required
Default
Description

record

KeeperRecord

Yes

-

The modified record to update in the vault

Response:

Type: void

Updates the secret in the vault with the modified values.

Example Usage

Non-Finalizing Save: save and save_with_options

save posts the record update to the server without calling complete_transaction. Use it in PAM rotation workflows where you need to stage a change and then separately commit or roll back, or when you want to update a record without triggering a finalization round-trip.

Parameter
Type
Required
Default
Description

record

Dto::KeeperRecord, Hash

Yes

-

Record to update (must have been retrieved via get_secrets)

transaction_type

String or nil

Optional

nil

PAM transaction type ('rotation', 'general', or nil)

links_to_remove

Array<String>

Optional

nil

UIDs of linked records to remove from this record

Response:

Type: Boolean — returns true on success.

For full control over UpdateOptions, call save_with_options directly:

update_options is a Dto::UpdateOptions object with transaction_type: and links_to_remove: attributes.

Comparison with update_secret

update_secret

save / save_with_options

Calls complete_transaction

Yes (always)

No

Refreshes record.revision after update

Yes

No

Extra get_secrets round-trip for key

Yes

No (uses existing key)

Use when

Standard CRUD updates

PAM staging, batch updates, manual commit control

Example Usage

Download a File

Parameter
Type
Required
Default
Description

file

KeeperFile

Yes

-

File object from a KeeperRecord to download

Response:

Type: Hash

Returns a hash containing:

  • 'name' - File name

  • 'data' - File contents as binary string

  • 'size' - File size in bytes

  • 'type' - MIME type of the file

Example Usage

Download a File Thumbnail

Parameter
Type
Required
Default
Description

file_data

KeeperFile or Hash

Yes

-

File object from a record, or a raw file metadata hash

Response:

Type: Hash

Returns a hash containing:

  • 'file_uid' - File UID

  • 'data' - Decrypted thumbnail contents as a binary string

  • 'size' - Thumbnail size in bytes

Example Usage

Upload a File

Parameter
Type
Required
Default
Description

owner_record_uid

String

Yes

-

UID of the record to attach the file to

file_data

String

Yes

-

File contents as binary string or text

file_name

String

Yes

-

Name of the file in Keeper

file_title

String

Optional

nil

Title/description of the file in Keeper

Response:

Type: String

Returns the UID of the uploaded file.

Example Usage

Upload from a File Path

upload_file_from_path reads the file from disk automatically, removing the need for a manual File.binread call.

Parameter
Type
Required
Default
Description

owner_record_uid

String

Yes

-

UID of the record to attach the file to

file_path

String

Yes

-

Absolute or relative path to the file on disk

file_title

String

Optional

filename

Title shown in Keeper; defaults to the base filename

Response:

Type: String — UID of the uploaded file.

Create a Secret

Parameter
Type
Required
Default
Description

record_data

Hash

Yes

-

Hash containing record structure (type, title, fields, custom, notes)

options

CreateOptions

Yes

-

CreateOptions object containing folder_uid (required) and optional settings

Response:

Type: String

Returns the UID of the created secret.

Prerequisites:

  • Shared folder UID (if specifying 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

  • Record fields must be formatted correctly (see field type documentation)

Example Usage

Create Custom Type Record

Create with Pre-Fetched Folders

create_secret_with_options accepts a CreateOptions object and an optional pre-fetched folder list. Use it when you are creating multiple records in the same session and already hold the folder list — the method skips the internal get_folders call, saving a round-trip.

Parameter
Type
Required
Default
Description

create_options

Dto::CreateOptions

Yes

-

Options object with folder_uid: (required) and subfolder_uid: (optional)

record_data

Dto::KeeperRecord, Hash

Yes

-

Record to create (same shape accepted by create_secret)

folders

Array<KeeperFolder>

Optional

nil

Pre-fetched folder list; fetched automatically when nil

Response:

Type: String — UID of the newly created record.

create_secret is the convenience wrapper for the common single-create case and calls create_secret_with_options internally.

Delete a Secret

Parameter
Type
Required
Default
Description

uids

String or Array<String>

Yes

-

UID or array of UIDs of secrets to delete

Response:

Type: void

Deletes the specified secret(s) from the vault.

Example Usage

Folders

The Ruby SDK provides full CRUD support for folder operations.

Get Folders

Response:

Type: Array<KeeperFolder>

Returns all folders accessible to the Secrets Manager application.

Example Usage

Get Folder Path

Parameter
Type
Required
Default
Description

folder_uid

String

Yes

-

UID of the folder

Response:

Type: String

Returns the full path to the folder (breadcrumb trail separated by "/").

Example Usage

Find Folder by Name

Parameter
Type
Required
Default
Description

name

String

Yes

-

Name of the folder to find

parent_uid

String

Optional

nil

UID of parent folder to search within

Response:

Type: KeeperFolder or nil

Returns the first folder matching the name, or nil if not found.

Example Usage

Build Folder Tree

Create a Folder

Parameter
Type
Required
Default
Description

name

String

Yes

-

Name of the folder to create

parent_uid

String

Yes

-

UID of the parent shared folder

Response:

Type: String

Returns the UID of the created folder.

Example Usage

Update a Folder

Parameter
Type
Required
Default
Description

folder_uid

String

Yes

-

UID of the folder to update

new_name

String

Yes

-

New name for the folder

Response:

Type: void

Renames the specified folder.

Example Usage

Delete Folders

Parameter
Type
Required
Default
Description

folder_uid

String

Yes

-

UID of the folder to delete

force

Boolean

Optional

false

If true, deletes folder and all its contents. If false, only deletes empty folders.

Response:

Type: void

Deletes the specified folder from the vault.

Example Usage

Caching

Improve performance by caching secrets locally:

Using CachingStorage

Built-in Disaster Recovery Cache

KeeperSecretsManager::CachingPostFunction is a drop-in custom_post_function that saves each successful API response to an encrypted local cache file and falls back to that cache automatically when the network is unavailable. This matches the disaster-recovery caching pattern found in the Python, Java, JavaScript, and .NET SDKs.

The cache file location defaults to ./ksm_cache.bin. Set the KSM_CACHE_DIR environment variable to redirect it to a different directory.

To manage the cache directly:

Custom Caching with custom_post_function

custom_post_function is called only for the read-only get_secret and get_folders paths (create/update/delete always use the SDK's built-in transport), as call(url, transmission_key, encrypted_payload, verify_ssl_certs). It must return a Dto::KSMHttpResponse (status_code:, data:, and an optional http_response:), not a raw response body:

Error Handling

The SDK provides specific exception classes for different error scenarios:

Common Error Scenarios

Advanced Configuration

Custom Hostname

SSL Certificate Verification

Custom Logging

HTTP Proxy

Pass proxy_url: at initialization to route all SDK traffic (API calls, file uploads, file downloads) through an HTTP or HTTPS proxy. Authenticated proxies are supported by embedding credentials in the URL.

If proxy_url: is not provided, the SDK checks the HTTPS_PROXY and https_proxy environment variables automatically.

An invalid proxy_url (malformed URL or missing host) raises ArgumentError at initialization with a descriptive message.

All Configuration Options

Field Type Helpers

Optional convenience methods for creating typed fields:

Dynamic Record Access

The Ruby SDK uses method_missing to provide JavaScript-style dynamic field access:

Last updated