Go SDK

Detailed Go SDK docs for Keeper Secrets Manager

Download and Installation

Install from GitHub

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

$ go get 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.

package main

import (	
    ksm "github.com/keeper-security/secrets-manager-go/core"	
)

func main() {
	clientOptions := &ksm.ClientOptions{
		Token:  "[One Time Access Token]",
		Config: ksm.NewFileKeyValueStorage("ksm-config.json")}
	sm := ksm.NewSecretsManager(clientOptions)
	// Using token only to generate a config (for later usage)
	// requires at least one access operation to bind the token
	//sm.GetSecrets([]string{})
}

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

secretsManager := NewSecretsManager(options)

Retrieve Secrets

records, err := sm.GetSecrets([]string{})

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

package main

import (	
    ksm "github.com/keeper-security/secrets-manager-go/core"	
)

func main() {
	clientOptions := &ksm.ClientOptions{
		Token:  "[One Time Access Token]",
		Config: ksm.NewFileKeyValueStorage("ksm-config.json")}
	sm := ksm.NewSecretsManager(clientOptions)
	allRecords, err := sm.GetSecrets([]string{})
}

Retrieve Secrets with a Filter

package main

import (	
    ksm "github.com/keeper-security/secrets-manager-go/core"	
)

func main() {
	clientOptions := &ksm.ClientOptions{
		Token:  "[One Time Access Token]",
		Config: ksm.NewFileKeyValueStorage("ksm-config.json")}
	sm := ksm.NewSecretsManager(clientOptions)
	records, err := sm.GetSecrets([]string{"[Secret UID]"})
}

Retrieve Secrets by Title

// get all matching records
GetSecretsByTitle(recordTitle string) (records []*Record, err error)

// get only the first matching record
GetSecretByTitle(recordTitle string) (records *Record, err error)

Example Usage

package main

// Import Secrets Manager
import ksm "github.com/keeper-security/secrets-manager-go/core"

func main() {

	options := &ksm.ClientOptions{
		// One time tokens can be used only once - afterwards use the generated config file
		Config: ksm.NewFileKeyValueStorage("ksm-config.json")}

	sm := ksm.NewSecretsManager(options)

	// Retrieve the first matching record by title
	aRecord, _ := ksm.GetSecretByTitle("My Credentials")

	// Retrieve all matching records by title
	allRecords, _ := ksm.GetSecretsByTitle("My Credentials")
	for _, record := range allRecords {
		println("UID", record.Uid, ", title [", record.Title(), "]")
	}
}

Get Values From a Secret

Get a Password

secret.GetFieldsByType("password")

Fields are found by type, for a list of field types see the Record Types documentation.

Retrieve Values using Keeper Notation

sm.GetNotation(query)

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

Returns

Type: []interface{}

The value of the queried field

Retrieve TOTP Code

GetTotpCode(url)

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

(r *Record) SetPassword(password string) 

Update Other Fields

(r *Record) SetFieldValueSingle(field string, value string) 

Update Secret in Vault

Save the record to make the changes made appear in the

(c *secretsManager) Save(record *Record) (err error) 

Example Usage

Update Password

package main

import (	
    ksm "github.com/keeper-security/secrets-manager-go/core"	
)

func main() {
	clientOptions := &ksm.ClientOptions{
		Token:  "[One Time Access Token]",
		Config: ksm.NewFileKeyValueStorage("ksm-config.json")}
	sm := ksm.NewSecretsManager(clientOptions)
	records, err := sm.GetSecrets([]string{"[Record UID]"})

	// get record to update
	record := records[0]

	// set new password
	record.SetPassword("NewPassword123$")

	// save changes
	ksm.Save(record)

	// Transactional updates
	// rotate password on the record
	record.SetPassword("NewPassword1234$")
	// start a transaction
	ksm.SaveBeginTransaction(secret, ksm.TransactionTypeRotation)
	// rotate password on remote host
	success := rotateRemoteSshPassword("NewPassword1234$")
	// complete the transaction - commit or rollback
	ksm.CompleteTransaction(secret.Uid, !success)
}

Update other fields

package main

import (	
    ksm "github.com/keeper-security/secrets-manager-go/core"	
)

func main() {
	clientOptions := &ksm.ClientOptions{
		Token:  "[One Time Access Token]",
		Config: ksm.NewFileKeyValueStorage("ksm-config.json")}
	sm := ksm.NewSecretsManager(clientOptions)
	records, err := sm.GetSecrets([]string{"[Record UID]"})

	// get record to update
	record := records[0]

	// set login field to a new value
	record.SetFieldValueSingle("login", "New Login Value")

	// save changes
	ksm.Save(record)
}

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

GeneratePassword(length, lowercase, uppercase, digits, specialCharaters)

Each parameter indicates the minimum number of a type of character to include. For example, uppercase indicates the minimum uppercase letters to include.

Download a File

(r *Record) DownloadFileByTitle(title string, path string) bool

Response

Type: bool

Did the file save succeed

Example Usage

import (	
    ksm "github.com/keeper-security/secrets-manager-go/core"	
)
clientOptions := &ksm.ClientOptions{
	Token:  "[One Time Access Token]",
	Config: ksm.NewFileKeyValueStorage("ksm-config.json")}
sm := ksm.NewSecretsManager(clientOptions)

// get record to update
record, err := sm.GetSecrets([]string{"[Record UID]"})

// download a file attached to the record
record.DownloadFileByTitle("certs.txt","secret_files/certs.txt")

Upload a File

UploadFile(record *Record, file *KeeperFileUpload) (uid string, err error)
type KeeperFileUpload struct {
	Name  string
	Title string
	Type  string
	Data  []byte
}

Example Usage

package main

// Import Secrets Manager
import ksm "github.com/keeper-security/secrets-manager-go/core"

func main() {

	options := &ksm.ClientOptions{
		// One time tokens can be used only once - afterwards use the generated config file
		Config: ksm.NewFileKeyValueStorage("ksm-config.json")}

	sm := ksm.NewSecretsManager(options)

	// Get a record to upload the file to
	allRecords, _ := sm.GetSecrets([]string{"[Record UID]"})
	ownerRecord := allRecords[0]
	
	// get file data and prepare for upload
	dat, err := ioutil.ReadFile("/myFile.json")
	var myFile := KeeperFileUpload{
		Name: "myFile.json",
		Title: "My File",
		Type: "application/json",
		Data: dat
	}
	
	// upload file to selected record
	sm.UploadFile(ownerRecord, myFile)
}

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

secretsManager.CreateSecretWithRecordData(recordUid, folderUid, record)

Delete a Secret

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

secretsManager.DeleteSecrets(recordUids)

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.

type ICache interface {
	SaveCachedValue(data []byte) error
	GetCachedValue() ([]byte, error)
	Purge() error
}

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

options := &ksm.ClientOptions{Config: ksm.NewFileKeyValueStorage("ksm-config.json")}
sm := ksm.NewSecretsManager(options)

// Memory based cache
memCache := ksm.NewMemoryCache()
sm.SetCache(memCache)

// File based cache
fileCache := ksm.NewFileCache("ksm_cache.bin")
sm.SetCache(fileCache)

Folders

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

Read Folders

Downloads full folder hierarchy.

GetFolders() ([]*KeeperFolder, error)

Response

Type: []*KeeperFolder, error

Example Usage

package main

import ksm "github.com/keeper-security/secrets-manager-go/core"

func main() {
	options := &ksm.ClientOptions{Config: ksm.NewFileKeyValueStorage("ksm-config.json")}
	sm := ksm.NewSecretsManager(options)
	folders, err := sm.GetFolders()
}

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.

CreateFolder(createOptions CreateOptions, folderName string, folders []*KeeperFolder) (folderUid string, err error)
type CreateOptions struct {
	FolderUid    string
	SubFolderUid string
}
type KeeperFolder struct {
	FolderKey []byte
	FolderUid string
	ParentUid string
	Name      string
}

Example Usage

package main

import ksm "github.com/keeper-security/secrets-manager-go/core"

func main() {
	options := &ksm.ClientOptions{Config: ksm.NewFileKeyValueStorage("ksm-config.json")}
	sm := ksm.NewSecretsManager(options)

	co := ksm.CreateOptions{FolderUid: "[PARENT_SHARED_FOLDER_UID]", SubFolderUid: ""}
	uid, err := sm.CreateFolder(co, "new_folder", nil)
}

Update a Folder

Updates the folder metadata - currently folder name only.

UpdateFolder(folderUid, folderName string, folders []*KeeperFolder) (err error)

Example Usage

package main

import ksm "github.com/keeper-security/secrets-manager-go/core"

func main() {
	options := &ksm.ClientOptions{Config: ksm.NewFileKeyValueStorage("ksm-config.json")}
	sm := ksm.NewSecretsManager(options)

	err := sm.UpdateFolder("[FOLDER_UID]", "new_folder_name", nil)
}

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.

DeleteFolder(folderUids []string, forceDeletion bool) (statuses map[string]string, err error)

Example Usage

package main

import ksm "github.com/keeper-security/secrets-manager-go/core"

func main() {
	options := &ksm.ClientOptions{Config: ksm.NewFileKeyValueStorage("ksm-config.json")}
	sm := ksm.NewSecretsManager(options)

	stats, err := sm.DeleteFolder([]string{"[FOLDER_UID1]", "[FOLDER_UID2]"}, true)
}

Last updated