Documentation
¶
Overview ¶
Package okms is a client for interacting with OVHcloud KMS REST-API.
Index ¶
- Constants
- func DebugTransport(out io.Writer) func(http.RoundTripper) http.RoundTripper
- func ErrStatusCode(err error) int
- func WithContextHeader(ctx context.Context, key, value string) context.Context
- type API
- type BlockSize
- type Category
- type Client
- func (client *Client) DataKeys(serviceKeyID uuid.UUID) *DataKeyProvider
- func (client *Client) ExportJwkPublicKey(ctx context.Context, keyID uuid.UUID) (*types.JsonWebKeyResponse, error)
- func (client *Client) ExportPublicKey(ctx context.Context, keyID uuid.UUID) (crypto.PublicKey, error)
- func (client *Client) GenerateECKeyPair(ctx context.Context, curve types.Curves, name, keyCtx string, ...) (*types.GetServiceKeyResponse, error)
- func (client *Client) GenerateRSAKeyPair(ctx context.Context, bitSize types.KeySizes, name, keyCtx string, ...) (*types.GetServiceKeyResponse, error)
- func (client *Client) GenerateSymmetricKey(ctx context.Context, bitSize types.KeySizes, name, keyCtx string, ...) (*types.GetServiceKeyResponse, error)
- func (client *Client) ImportKey(ctx context.Context, key any, name, keyCtx string, ...) (*types.GetServiceKeyResponse, error)
- func (client *Client) ImportKeyPairPEM(ctx context.Context, privateKeyPem []byte, name, keyCtx string, ...) (*types.GetServiceKeyResponse, error)
- func (client *Client) ListAllServiceKeys(pageSize *uint32, state *types.KeyStates) KeyIter
- func (client *Client) NewSigner(ctx context.Context, serviceKeyID uuid.UUID) (crypto.Signer, error)
- func (client *Client) WithCustomHeader(key, value string) *Client
- type ClientConfig
- type DataKeyApi
- type DataKeyProvider
- func (sk *DataKeyProvider) DecryptDataKey(ctx context.Context, key []byte) ([]byte, error)
- func (sk *DataKeyProvider) DecryptGCM(ctx context.Context, cipherKey, cipherText, nonce, aad []byte) ([]byte, error)
- func (sk *DataKeyProvider) DecryptStream(ctx context.Context, r io.Reader, aad []byte) (io.Reader, error)
- func (sk *DataKeyProvider) EncryptGCM(ctx context.Context, keyName string, data, aad []byte) (cipherText, cipherKey, nonce []byte, err error)
- func (sk *DataKeyProvider) EncryptStream(ctx context.Context, w io.Writer, aad []byte, blockSize BlockSize) (io.WriteCloser, error)
- func (sk *DataKeyProvider) GenerateDataKey(ctx context.Context, name string, size int) (plain, encrypted []byte, err error)
- type EncryptionApi
- type ErrorCode
- type InternalHttpClient
- type KeyIter
- type KmsError
- type LeveledLogger
- type Major
- type Minor
- type RetryConfig
- type SecretApi
- type SecretApiV2
- type ServiceKeyApi
- type SignatureApi
Examples ¶
Constants ¶
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 ¶
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.
Types ¶
type API ¶ added in v0.3.0
type API interface { // RandomApi DataKeyApi SignatureApi EncryptionApi ServiceKeyApi SecretApi SecretApiV2 // 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 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 ¶
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 ¶
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.JsonWebKeyResponse, error)
ExportJwkPublicKey returns the public part of a key pair as 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
ListAllServiceKeys returns an iterator to go through all the keys without having to deal with pagination.
func (*Client) NewSigner ¶ added in v0.3.0
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
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) ¶
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 ¶
DecryptDataKey decrypts an encrypted datakey like ones returned by DataKeyProvider.GenerateDataKey.
Example ¶
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 ¶
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 InternalHttpClient ¶
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 ¶
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 LeveledLogger ¶ added in v0.2.1
type LeveledLogger retryablehttp.LeveledLogger
LeveledLogger represents loggers that can be used inside the client.
type RetryConfig ¶ added in v0.2.1
type SecretApi ¶ added in v0.4.3
type SecretApi interface { // GetSecretsMetadata returns a secret metadata or a list of secrets if `list` is set to true. GetSecretsMetadata(ctx context.Context, path string, list bool) (*types.GetMetadataResponse, error) // PatchSecretMetadata updates secret metadata. PatchSecretMetadata(ctx context.Context, path string, body types.SecretUpdatableMetadata) error // DeleteSecretMetadata deletes secret metadata and all versions. DeleteSecretMetadata(ctx context.Context, path string) error // PostSecretMetadata updates secret metadata. PostSecretMetadata(ctx context.Context, path string, body types.SecretUpdatableMetadata) error // GetSecretConfig returns secret store configuration. GetSecretConfig(ctx context.Context) (*types.GetConfigResponse, error) // PostSecretConfig configures secret store settings. PostSecretConfig(ctx context.Context, body types.PostConfigRequest) error // GetSecretRequest returns secret version. GetSecretRequest(ctx context.Context, path string, version *uint32) (*types.GetSecretResponse, error) // GetSecretSubkeys returns secret subkeys. GetSecretSubkeys(ctx context.Context, path string, depth, version *uint32) (*types.GetSecretSubkeysResponse, error) // PostSecretRequest creates or updates a secret. PostSecretRequest(ctx context.Context, path string, body types.PostSecretRequest) (*types.PostSecretResponse, error) // PatchSecretRequest patches a secret. PatchSecretRequest(ctx context.Context, path string, body types.PostSecretRequest) (*types.PatchSecretResponse, error) // DeleteSecretRequest deletes the latest version of a secret. This marks the version as deleted but the underlying data will not be removed. DeleteSecretRequest(ctx context.Context, path string) error // DeleteSecretVersions deletes the specified secret version. This marks the versions as deleted but the underlying data will not be removed. DeleteSecretVersions(ctx context.Context, path string, versions []uint32) error // PutSecretDestroy permanently removes the data of the specified versions from the secrets store. PutSecretDestroy(ctx context.Context, path string, versions []uint32) error // PostSecretUndelete undeletes the data of the specified versions. The versions will no longer be marked as deleted. PostSecretUndelete(ctx context.Context, path string, versions []uint32) error }
type SecretApiV2 ¶ added in v0.4.3
type SecretApiV2 interface { // ListSecretV2 returns a page of secrets. ListSecretV2(ctx context.Context, pageSize, pageNumber *uint32) (*types.ListSecretV2Response, error) // PostSecretV2 creates a new secret with metadata. PostSecretV2(ctx context.Context, body types.PostSecretV2Request) (*types.PostSecretV2Response, error) // DeleteSecretV2 deletes a secret and all its versions. DeleteSecretV2(ctx context.Context, path string) error // GetSecretV2 returns a secret and its metadata. If the version is not specified, the current version is returned. GetSecretV2(ctx context.Context, path string, version *uint32, includeData *bool) (*types.GetSecretV2Response, error) // PutSecretV2 updates a secret. If the secret data is updated, a new version will be created. PutSecretV2(ctx context.Context, path string, cas *uint32, body types.PutSecretV2Request) (*types.PutSecretV2Response, error) // ListSecretVersionV2 returns the versions of a secret. ListSecretVersionV2(ctx context.Context, path string) (*types.ListSecretVersionV2Response, error) // PostSecretVersionV2 creates a new secret version. PostSecretVersionV2(ctx context.Context, path string, cas *uint32, body types.PostSecretVersionV2Request) (*types.SecretV2Version, error) // GetSecretVersionV2 returns a secret version. GetSecretVersionV2(ctx context.Context, path string, version uint32, includeData *bool) (*types.SecretV2Version, error) // Updates the status of a secret version. PutSecretVersionV2(ctx context.Context, path string, version uint32, body types.PutSecretVersionV2Request) (*types.SecretV2Version, error) // GetSecretConfigV2 returns the default secrets configuration. GetSecretConfigV2(ctx context.Context) (*types.GetSecretConfigV2Response, error) // PutSecretConfigV2 updated the default secrets configuration. PutSecretConfigV2(ctx context.Context, body types.PutSecretConfigV2Request) (*types.PutSecretConfigV2Response, error) }
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 *uint32, 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, format *types.SignatureFormats, 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.
Source Files
¶
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. |