okms

package module
v0.3.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 15, 2024 License: Apache-2.0 Imports: 32 Imported by: 8 modules, 4 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

okms-sdk-go

Go Reference license test Go Report Card

The Golang SDK to interact with your OVHcloud KMS services.

NOTE: THIS PROJECT IS CURRENTLY UNDER DEVELOPMENT AND SUBJECT TO BREAKING CHANGES.

How to use

Add it to your project by running

go get github.com/ovh/okms-sdk-go@latest

Then you can connect to your KMS service

cert, err := tls.LoadX509KeyPair(os.Getenv("KMS_CLIENT_CERT_FILE"), os.Getenv("KMS_CLIENT_KEY_FILE"))
if err != nil {
    panic(err)
}
httpClient := http.Client{
    Transport: &http.Transport{TLSClientConfig: &tls.Config{
        Certificates: []tls.Certificate{cert},
        MinVersion:   tls.VersionTLS12,
    }},
}
kmsClient, err := okms.NewRestAPIClientWithHttp("https://eu-west-rbx.okms.ovh.net", &httpClient)
if err != nil {
    panic(err)
}

// Then start using the kmsClient

See examples for more.

If you don't have any KMS service yet, you can follow the OVHcloud KMS quick start guide.

Features

Current SDK allows you to manipulate and consume keys through the KMS REST API. Implemented operations are

  • Keys and Key Pairs lifecycle:
    • Create keys and key pairs
    • Import keys and key pairs
    • Activate and Deactivate keys and key pairs
    • Update keys and key pairs
    • Destroy keys and key pairs
    • Update keys and key pairs metadata
    • List keys and key pairs
    • Export key pair's public keys
    • Read keys and key pairs metadata
  • Symmetric Key operations
    • Encrypt / Decrypt data
    • Generate data keys
    • Decrypt data keys
  • Assymetric Key Pair operations
    • Sign / Verify data

Documentation

Overview

Package okms is a client for interacting with OVHcloud KMS REST-API.

Index

Examples

Constants

View Source
const DefaultHTTPClientTimeout = 30 * time.Second

Variables

This section is empty.

Functions

func DebugTransport added in v0.2.1

func DebugTransport(out io.Writer) func(http.RoundTripper) http.RoundTripper

DebugTransport creates an http client middleware that will dump all the HTTP resquests and responses to the giver io.Writer. It can be passed to ClientConfig.Middleware.

func ErrStatusCode

func ErrStatusCode(err error) int

ErrStatusCode returns the status code of the HTTP response that caused this error, if any. If err is nil, or if it was not caused by an http response (for example if it was in fact caused by a connectivity issue), then it returns 0.

The returned status code will be 0, or a value >= 400.

func WithContextHeader

func WithContextHeader(ctx context.Context, key, value string) context.Context

WithContextHeader adds some custom headers to the request's context.

Types

type API added in v0.3.0

type API interface {
	// RandomApi
	DataKeyApi
	SignatureApi
	EncryptionApi
	ServiceKeyApi
	// SecretApi
	// Ping(ctx context.Context) error
	SetCustomHeader(key, value string)
}

API is the interface abstracting the KMS clients methods.

type BlockSize added in v0.3.0

type BlockSize int

BlockSize enumerates recommended size of blocks for streaming encryption.

const (
	BlockSize32kB    BlockSize = 32 * 1024
	BlockSize4MB     BlockSize = 4096 * 1024
	BlockSizeDefault BlockSize = xcrypto.DEFAULT_BLOCK_SIZE
)

type Category

type Category byte
const (
	CategoryUnspecified Category = iota
	CategoryInternal
	CategoryArgument
	CategoryAuthentication
	CategoryAuthorization
	CategoryNotFound
	CategoryDatabase
	CategoryUnavailable
	CategoryBadArgument
)

func (Category) String

func (c Category) String() string

type Client

type Client struct {
	API
}

func NewRestAPIClient added in v0.2.1

func NewRestAPIClient(endpoint string, clientCfg ClientConfig) (*Client, error)

NewRestAPIClient creates and initializes a new HTTP connection to the KMS at url `endpoint` using the provided client configuration. It allows configuring retries, timeouts and loggers.

func NewRestAPIClientWithHttp

func NewRestAPIClientWithHttp(endpoint string, c *http.Client) (*Client, error)

NewRestAPIClientWithHttp is a lower level constructor to create and initialize a new HTTP connection to the KMS at url `endpoint` using the provided http.Client.

The client must be configured with an appropriate tls.Config using client TLS certificates for authentication.

Example
package main

import (
	"context"
	"crypto/tls"
	"net/http"
	"os"

	"github.com/google/uuid"
	"github.com/ovh/okms-sdk-go"
)

func main() {
	cert, err := tls.LoadX509KeyPair(os.Getenv("KMS_CLIENT_CERT_FILE"), os.Getenv("KMS_CLIENT_KEY_FILE"))
	if err != nil {
		panic(err)
	}
	httpClient := http.Client{
		Transport: &http.Transport{TLSClientConfig: &tls.Config{
			Certificates: []tls.Certificate{cert},
			MinVersion:   tls.VersionTLS12,
		}},
	}
	kmsClient, err := okms.NewRestAPIClientWithHttp("https://eu-west-rbx.okms.ovh.net", &httpClient)
	if err != nil {
		panic(err)
	}

	// Use KMS client, for example to activate a service key
	if err := kmsClient.ActivateServiceKey(context.Background(), uuid.MustParse("2dab95dc-d7d3-482b-a07b-6b4dfae89d58")); err != nil {
		panic(err)
	}
}

func (*Client) DataKeys added in v0.3.0

func (client *Client) DataKeys(serviceKeyID uuid.UUID) *DataKeyProvider

DataKeys creates a new datakey provider for the given service key.

func (*Client) ExportJwkPublicKey added in v0.3.0

func (client *Client) ExportJwkPublicKey(ctx context.Context, keyID uuid.UUID) (*types.JsonWebKey, error)

ExportJwkPublicKey returns the public part of a key pair ans a Json Web Key.

func (*Client) ExportPublicKey added in v0.3.0

func (client *Client) ExportPublicKey(ctx context.Context, keyID uuid.UUID) (crypto.PublicKey, error)

ExportPublicKey returns the public part of a key pair as a crypto.PublicKey.

The returned key can then be cast into *rsa.PublicKey or *ecdsa.PublicKey.

func (*Client) GenerateECKeyPair added in v0.3.0

func (client *Client) GenerateECKeyPair(ctx context.Context, curve types.Curves, name, keyCtx string, ops ...types.CryptographicUsages) (*types.GetServiceKeyResponse, error)

GenerateECKeyPair asks the KMS to generate an EC asymmetric key-pair with the given elliptic curve, name and usage. The keyCtx parameter can be left empty if not needed.

func (*Client) GenerateRSAKeyPair added in v0.3.0

func (client *Client) GenerateRSAKeyPair(ctx context.Context, bitSize types.KeySizes, name, keyCtx string, ops ...types.CryptographicUsages) (*types.GetServiceKeyResponse, error)

GenerateRSAKeyPair asks the KMS to generate an RSA asymmetric key-pair with the given bits length, name and usage. The keyCtx parameter can be left empty if not needed.

func (*Client) GenerateSymmetricKey added in v0.3.0

func (client *Client) GenerateSymmetricKey(ctx context.Context, bitSize types.KeySizes, name, keyCtx string, ops ...types.CryptographicUsages) (*types.GetServiceKeyResponse, error)

GenerateSymmetricKey asks the KMS to generate a symmetric key with the given bits length, name and usage. The keyCtx parameter can be left empty if not needed.

func (*Client) ImportKey added in v0.3.0

func (client *Client) ImportKey(ctx context.Context, key any, name, keyCtx string, ops ...types.CryptographicUsages) (*types.GetServiceKeyResponse, error)

ImportKey imports a key into the KMS. keyCtx can be left empty if not needed.

The accepted types of the key parameter are

  • *rsa.PrivateKey
  • *ecdsa.PrivateKey
  • types.JsonWebKey and *types.JsonWebKey
  • []byte for importing symmetric keys.

func (*Client) ImportKeyPairPEM added in v0.3.0

func (client *Client) ImportKeyPairPEM(ctx context.Context, privateKeyPem []byte, name, keyCtx string, ops ...types.CryptographicUsages) (*types.GetServiceKeyResponse, error)

ImportKeyPairPEM imports a PEM formated key into the KMS. keyCtx can be left empty if not needed.

Supported PEM types are:

  • PKCS8
  • PKCS1 private keys
  • SEC1
  • OpenSSH private keys

func (*Client) ListAllServiceKeys added in v0.3.0

func (client *Client) ListAllServiceKeys(pageSize *int32, state *types.KeyStates) KeyIter

ListAllServiceKeys returns an iterator to go through all the keys without having to deal with pagination.

func (*Client) NewSigner added in v0.3.0

func (client *Client) NewSigner(ctx context.Context, serviceKeyID uuid.UUID) (crypto.Signer, error)

NewSigner creates a new crypto.Signer for the given key-pair.

NewSigner cannot be used with symetric keys.

func (*Client) WithCustomHeader added in v0.3.0

func (client *Client) WithCustomHeader(key, value string) *Client

WithCustomHeader adds additional HTTP headers that will be sent with every outgoing requests.

type ClientConfig added in v0.2.1

type ClientConfig struct {
	Timeout    *time.Duration
	Retry      *RetryConfig
	Logger     LeveledLogger
	TlsCfg     *tls.Config
	Middleware func(http.RoundTripper) http.RoundTripper
}

ClientConfig is used to configure Rest clients created using NewRestAPIClient().

type DataKeyApi

type DataKeyApi interface {
	// GenerateDataKey creates a new data key of the given size, protected by the service key with the ID `keyId`.
	// It returns the plain datakey, and the JWE encrypted version of it, which can be decrypted by calling the DecryptDataKey method.
	GenerateDataKey(ctx context.Context, keyId uuid.UUID, name string, size int32) (plain []byte, encrypted string, err error)
	// DecryptDataKey decrypts a JWE encrypted data key protected by the service key with the ID `keyId`.
	DecryptDataKey(ctx context.Context, keyId uuid.UUID, encryptedKey string) ([]byte, error)
}

DataKeyApi is the client interface used to create and retrieve KMS data keys using a remote symmetric key.

type DataKeyProvider

type DataKeyProvider struct {
	// contains filtered or unexported fields
}

DataKeyProvider is a helper provider that wraps an API client and provides helpers functions to repeatedly generate or decrypt datakeys protected by the same service key.

It also provide helper functions to directly encrypt or decrypt data with a datakey.

Example (Helpers)
package main

import (
	"context"
	"fmt"

	"github.com/google/uuid"
	"github.com/ovh/okms-sdk-go"
)

func main() {
	var kmsClient *okms.Client // Initialize client

	data := "Hello World !!!" // Data to encrypt
	dkProvider := kmsClient.DataKeys(uuid.MustParse("2dab95dc-d7d3-482b-a07b-6b4dfae89d58"))

	// Unless you want to use another algorithm than AES-GCM 256 bits, you can use the 2 following helper methods:
	encryptedData, encryptedKey, nonce, err := dkProvider.EncryptGCM(context.Background(), "Example DK", []byte(data), []byte("Some additional data"))
	if err != nil {
		panic(err)
	}

	plainData, err := dkProvider.DecryptGCM(context.Background(), encryptedKey, encryptedData, nonce, []byte("Some additional data"))
	if err != nil {
		panic(err)
	}
	fmt.Println("Decrypted:", string(plainData))
}

func (*DataKeyProvider) DecryptDataKey

func (sk *DataKeyProvider) DecryptDataKey(ctx context.Context, key []byte) ([]byte, error)

DecryptDataKey decrypts an encrypted datakey like ones returned by DataKeyProvider.GenerateDataKey.

Example
package main

import (
	"context"
	"crypto/aes"
	"crypto/cipher"
	"fmt"

	"github.com/google/uuid"
	"github.com/ovh/okms-sdk-go"
)

func main() {
	var kmsClient *okms.Client // Initialize client
	var encryptedData []byte   // Some encrypted data
	var encryptedKey []byte    // Encrypted datakey
	var nonce []byte           // Nonce used for data encryption
	dkProvider := kmsClient.DataKeys(uuid.MustParse("2dab95dc-d7d3-482b-a07b-6b4dfae89d58"))

	// Decrypt data key
	plain, err := dkProvider.DecryptDataKey(context.Background(), encryptedKey)
	if err != nil {
		panic(err)
	}
	// Initialize AES GCM cipher with the decrypted key
	aesCipher, err := aes.NewCipher(plain)
	if err != nil {
		panic(err)
	}
	gcm, err := cipher.NewGCM(aesCipher)
	if err != nil {
		panic(err)
	}

	// Decrypt text
	plainData, err := gcm.Open(nil, nonce, encryptedData, []byte("Some additional data"))
	if err != nil {
		panic(err)
	}
	fmt.Println("Decrypted:", string(plainData))
}

func (*DataKeyProvider) DecryptGCM

func (sk *DataKeyProvider) DecryptGCM(ctx context.Context, cipherKey, cipherText, nonce, aad []byte) ([]byte, error)

DecryptGCM is a helper function that decrypts the given encrypted datakey, than decrypts the given cipherText using the reulting plain key with the given nonce and aad, using AES-GCM.

It's mostly used to decrypt data encrypted using DataKeyProvider.EncryptGCM.

func (*DataKeyProvider) DecryptStream added in v0.3.0

func (sk *DataKeyProvider) DecryptStream(ctx context.Context, r io.Reader, aad []byte) (io.Reader, error)

DecryptStream wraps the given io.Reader into another io.Reader that decrypts the data read from it. The initialization vector and the encrypted datakey are read from the header. The datakey is then decrypted on KMS and used to decrypt successive blocks of encrypted data using AES-GCM.

The data to decrypt must have been encrypted using DataKeyProvider.EncryptStream.

func (*DataKeyProvider) EncryptGCM

func (sk *DataKeyProvider) EncryptGCM(ctx context.Context, keyName string, data, aad []byte) (cipherText, cipherKey, nonce []byte, err error)

EncryptGCM is a helper function that creates a new 256 bits datakey, and encrypts the given data with AES-GCM.

On success, the function returns the encrypted data, the encrypted key, and the random nonce used. Those 3 values must later be passed to DataKeyProvider.DecryptGCM in order to decrypt the data.

func (*DataKeyProvider) EncryptStream added in v0.3.0

func (sk *DataKeyProvider) EncryptStream(ctx context.Context, w io.Writer, aad []byte, blockSize BlockSize) (io.WriteCloser, error)

EncryptStream wraps the given io.Writer into an io.WriteCloser that encrypts the data written to it with a fresh new datakey. A 256 bits datakey is generated for every new stream, is used to perform an AES-GCM encryption of successive blocks of data. The encrypted stream will start with a header containing the encrypted datakey and a random initialization vector.

The returned io.WriteCloser must be closed to finalize the encryption, but please note that doing so won't close the underlying stream which must also be closed but can be reused first.

func (*DataKeyProvider) GenerateDataKey

func (sk *DataKeyProvider) GenerateDataKey(ctx context.Context, name string, size int) (plain, encrypted []byte, err error)

GenerateDataKey creates a new datakey of bitlen `size` and with name `name`, protected by the provider's service key. The `plain` and `encrypted` form of the datakey are returned.

Acceptable key sizes are 128, 192 and 256. The encrypted key can later be decrypted by calling DataKeyProvider.DecryptDataKey.

Example
package main

import (
	"context"
	"crypto/aes"
	"crypto/cipher"
	"crypto/rand"
	"encoding/base64"
	"fmt"

	"github.com/google/uuid"
	"github.com/ovh/okms-sdk-go"
)

func main() {
	var kmsClient *okms.Client // Initialize client
	data := "Hello World !!!"  // Data to encrypt
	dkProvider := kmsClient.DataKeys(uuid.MustParse("2dab95dc-d7d3-482b-a07b-6b4dfae89d58"))

	// Generate a new datakey
	plain, encrypted, err := dkProvider.GenerateDataKey(context.Background(), "Example DK", 256)
	if err != nil {
		panic(err)
	}

	// Initialize AES GCM cipher with the plain key
	aesCipher, err := aes.NewCipher(plain)
	if err != nil {
		panic(err)
	}
	gcm, err := cipher.NewGCM(aesCipher)
	if err != nil {
		panic(err)
	}

	// Generate random nonce
	nonce := make([]byte, gcm.NonceSize())
	if _, err := rand.Read(nonce); err != nil {
		panic(err)
	}

	// Encrypt the data
	encryptedData := gcm.Seal(nil, nonce, []byte(data), []byte("Some additional data"))

	fmt.Println("EncryptedKey:", encrypted, ", Encrypted data:", base64.StdEncoding.EncodeToString(encryptedData))
}

type EncryptionApi

type EncryptionApi interface {
	// Encrypt encrypts `data` with the remote symmetric key having the ID `keyId`. Returns a JWE (Json Web Encryption) string.
	Encrypt(ctx context.Context, keyId uuid.UUID, keyCtx string, data []byte) (string, error)
	// Decrypt decrypts JWE `data` previously encrypted with the remote symmetric key having the ID `keyId`.
	Decrypt(ctx context.Context, keyId uuid.UUID, keyCtx, data string) ([]byte, error)
}

EncryptionApi is the client interface used to encrypt and decrypt data using a remote symmetric key.

type ErrorCode

type ErrorCode uint32

func (ErrorCode) AppSpecificCode

func (code ErrorCode) AppSpecificCode() uint16

func (ErrorCode) Category

func (code ErrorCode) Category() Category

func (ErrorCode) Major

func (code ErrorCode) Major() Major

func (ErrorCode) Minor

func (code ErrorCode) Minor() Minor

func (ErrorCode) String

func (code ErrorCode) String() string

type InternalHttpClient

type InternalHttpClient = internal.Client

InternalHttpClient is the low level, internal http client generated by oapi-codegen. It may be used as an escape hatch to some low level features. Use at your own risk.

type KeyIter

type KeyIter struct {
	// contains filtered or unexported fields
}

KeyIter is an iterator for service keys. It helps in iterating efficiently over multiple pages without having to deal with the pagination.

func (KeyIter) Iter

Iter returns a go 1.23+ iterator that can be ranged over. The iterator yields 2 values which are the key and an error. The key is null if err is not, and err is null if key is not.

func (*KeyIter) Next

func (it *KeyIter) Next(ctx context.Context) bool

Next checks if there is another key to return, and advance the cursor if so. It returns true if there is another key to get, false otherwise. Once the cursor has advanced, the newt key can be retrieved with a call to Value().

func (*KeyIter) Value

func (it *KeyIter) Value() (*types.GetServiceKeyResponse, error)

Value returns the last key fetched by the iterator after calling Next(), or any error that has occurred internally during the fetch.

Calling Value() multiple times will return the same result unless Next() has been called and has returned true.

type KmsError

type KmsError struct {
	ErrorCode ErrorCode
	ErrorId   string
	Errors    []error
	RequestId string
}

func AsKmsError

func AsKmsError(err error) *KmsError

func NewKmsErrorFromBytes

func NewKmsErrorFromBytes(sbody []byte) *KmsError

func (*KmsError) Error

func (err *KmsError) Error() string

type LeveledLogger added in v0.2.1

type LeveledLogger retryablehttp.LeveledLogger

LeveledLogger represents loggers that can be used inside the client.

type Major

type Major byte
const (
	MajorUndefined Major = iota
	MajorCCM
	MajorSSM
	MajorREST
	MajorKMIP
	MajorDB
	MajorXLIB
)

func (Major) String

func (m Major) String() string

type Minor

type Minor byte
const (
	MinorCCMIAM Minor = iota + 2
	MinorCCMDomain
	MinorCCMDskManager
	MinorCCMSecretManager
	MinorCCMMobManager
	MinorCCMAdminProvider
	MinorCCMAdminAuthProvider
	MinorCCMUserAuthProvider
	MinorCCMSsmProvider
)
const (
	MinorDBFile Minor = iota + 2
	MinorDBS3Provider
	MinorDBNPgSqlProvider
)
const (
	MinorRESTAuthProvider Minor = iota + 2
	MinorRESTServicekeysApi
	MinorRESTSecretsApi
)
const (
	MinorXlibHttpHelper Minor = iota + 2
	MinorXlibIamProvider
	MinorXlibCertProvider
)
const (
	MinorGeneral Minor = iota + 1
)

func (Minor) StringFor

func (m Minor) StringFor(major Major) string

type RetryConfig added in v0.2.1

type RetryConfig struct {
	RetryMax     int
	RetryWaitMin time.Duration
	RetryWaitMax time.Duration
}

type ServiceKeyApi

type ServiceKeyApi interface {
	// ActivateServiceKey activates or re-activates a service key.
	ActivateServiceKey(ctx context.Context, keyId uuid.UUID) error
	// DeactivateServiceKey deactivates a service key with the given deactivation reason.
	DeactivateServiceKey(ctx context.Context, keyId uuid.UUID, reason types.RevocationReasons) error
	// CreateImportServiceKey is used to either generate a new key securely in the KMS, or to import a plain key into the KMS domain.
	CreateImportServiceKey(ctx context.Context, format *types.KeyFormats, body types.CreateImportServiceKeyRequest) (*types.GetServiceKeyResponse, error)
	// DeleteServiceKey deletes a deactivated service key. The key cannot be recovered after deletion.
	// It will fail if the key is not deactivated.
	DeleteServiceKey(ctx context.Context, keyId uuid.UUID) error
	// GetServiceKey returns a key metadata. If format is not nil, then the public key material is also returned.
	GetServiceKey(ctx context.Context, keyId uuid.UUID, format *types.KeyFormats) (*types.GetServiceKeyResponse, error)
	// ListServiceKeys returns a page of service keys. The response contains a continuationToken that must be passed to the
	// subsequent calls in order to get the next page. The state parameter when no nil is used to query keys having a specific state.
	ListServiceKeys(ctx context.Context, continuationToken *string, maxKey *int32, state *types.KeyStates) (*types.ListServiceKeysResponse, error)
	// UpdateServiceKey updates some service key metadata.
	UpdateServiceKey(ctx context.Context, keyId uuid.UUID, body types.PatchServiceKeyRequest) (*types.GetServiceKeyResponse, error)
}

ServiceKeyApi is the client interface used to query and manipulate the remote service keys lifecycle.

type SignatureApi

type SignatureApi interface {
	// Sign signs the given message with the remote private key having the ID `keyId`. The message can be pre-hashed or not.
	Sign(ctx context.Context, keyId uuid.UUID, alg types.DigitalSignatureAlgorithms, preHashed bool, msg []byte) (string, error)
	// Verify checks the signature of given message against the remote public key having the ID `keyId`. The message can be pre-hashed or not.
	Verify(ctx context.Context, keyId uuid.UUID, alg types.DigitalSignatureAlgorithms, preHashed bool, msg []byte, sig string) (bool, error)
}

SignatureApi is the client interface used to sign data and verify signatures using a remote asymmetric key-pair.

Directories

Path Synopsis
Package internal provides primitives to interact with the openapi HTTP API.
Package internal provides primitives to interact with the openapi HTTP API.
Package types holds the REST API type definitions, including requests, responses, and enums.
Package types holds the REST API type definitions, including requests, responses, and enums.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL