go mod vendor

+ move k8s.io/apimachinery fork from go.work to go.mod
(and include it in vendor)
This commit is contained in:
2022-11-07 00:16:27 +02:00
parent d08bbf250a
commit e45bf4739b
1366 changed files with 469062 additions and 45 deletions

View File

@@ -0,0 +1,56 @@
// Copyright (C) MongoDB, Inc. 2017-present.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may
// not use this file except in compliance with the License. You may obtain
// a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
//go:build cse
// +build cse
package mongocrypt
// #include <mongocrypt.h>
import "C"
import (
"unsafe"
)
// binary is a wrapper type around a mongocrypt_binary_t*
type binary struct {
wrapped *C.mongocrypt_binary_t
}
// newBinary creates an empty binary instance.
func newBinary() *binary {
return &binary{
wrapped: C.mongocrypt_binary_new(),
}
}
// newBinaryFromBytes creates a binary instance from a byte buffer.
func newBinaryFromBytes(data []byte) *binary {
if len(data) == 0 {
return newBinary()
}
// We don't need C.CBytes here because data cannot go out of scope. Any mongocrypt function that takes a
// mongocrypt_binary_t will make a copy of the data so the data can be garbage collected after calling.
addr := (*C.uint8_t)(unsafe.Pointer(&data[0])) // uint8_t*
dataLen := C.uint32_t(len(data)) // uint32_t
return &binary{
wrapped: C.mongocrypt_binary_new_from_data(addr, dataLen),
}
}
// toBytes converts the given binary instance to []byte.
func (b *binary) toBytes() []byte {
dataPtr := C.mongocrypt_binary_data(b.wrapped) // C.uint8_t*
dataLen := C.mongocrypt_binary_len(b.wrapped) // C.uint32_t
return C.GoBytes(unsafe.Pointer(dataPtr), C.int(dataLen))
}
// close cleans up any resources associated with the given binary instance.
func (b *binary) close() {
C.mongocrypt_binary_destroy(b.wrapped)
}

View File

@@ -0,0 +1,44 @@
// Copyright (C) MongoDB, Inc. 2017-present.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may
// not use this file except in compliance with the License. You may obtain
// a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
//go:build cse
// +build cse
package mongocrypt
// #include <mongocrypt.h>
import "C"
import (
"fmt"
)
// Error represents an error from an operation on a MongoCrypt instance.
type Error struct {
Code int32
Message string
}
// Error implements the error interface.
func (e Error) Error() string {
return fmt.Sprintf("mongocrypt error %d: %v", e.Code, e.Message)
}
// errorFromStatus builds a Error from a mongocrypt_status_t object.
func errorFromStatus(status *C.mongocrypt_status_t) error {
cCode := C.mongocrypt_status_code(status) // uint32_t
// mongocrypt_status_message takes uint32_t* as its second param to store the length of the returned string.
// pass nil because the length is handled by C.GoString
cMsg := C.mongocrypt_status_message(status, nil) // const char*
var msg string
if cMsg != nil {
msg = C.GoString(cMsg)
}
return Error{
Code: int32(cCode),
Message: msg,
}
}

View File

@@ -0,0 +1,21 @@
// Copyright (C) MongoDB, Inc. 2017-present.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may
// not use this file except in compliance with the License. You may obtain
// a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
//go:build !cse
// +build !cse
package mongocrypt
// Error represents an error from an operation on a MongoCrypt instance.
type Error struct {
Code int32
Message string
}
// Error implements the error interface
func (Error) Error() string {
panic(cseNotSupportedMsg)
}

View File

@@ -0,0 +1,416 @@
// Copyright (C) MongoDB, Inc. 2017-present.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may
// not use this file except in compliance with the License. You may obtain
// a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
//go:build cse
// +build cse
package mongocrypt
// #cgo linux solaris darwin pkg-config: libmongocrypt
// #cgo windows CFLAGS: -I"c:/libmongocrypt/include"
// #cgo windows LDFLAGS: -lmongocrypt -Lc:/libmongocrypt/bin
// #include <mongocrypt.h>
// #include <stdlib.h>
import "C"
import (
"errors"
"fmt"
"unsafe"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/x/bsonx/bsoncore"
"go.mongodb.org/mongo-driver/x/mongo/driver/mongocrypt/options"
)
type MongoCrypt struct {
wrapped *C.mongocrypt_t
kmsProviders bsoncore.Document
}
// Version returns the version string for the loaded libmongocrypt, or an empty string
// if libmongocrypt was not loaded.
func Version() string {
str := C.GoString(C.mongocrypt_version(nil))
return str
}
// NewMongoCrypt constructs a new MongoCrypt instance configured using the provided MongoCryptOptions.
func NewMongoCrypt(opts *options.MongoCryptOptions) (*MongoCrypt, error) {
// create mongocrypt_t handle
wrapped := C.mongocrypt_new()
if wrapped == nil {
return nil, errors.New("could not create new mongocrypt object")
}
crypt := &MongoCrypt{
wrapped: wrapped,
kmsProviders: opts.KmsProviders,
}
// set options in mongocrypt
if err := crypt.setProviderOptions(opts.KmsProviders); err != nil {
return nil, err
}
if err := crypt.setLocalSchemaMap(opts.LocalSchemaMap); err != nil {
return nil, err
}
if err := crypt.setEncryptedFieldsMap(opts.EncryptedFieldsMap); err != nil {
return nil, err
}
if opts.BypassQueryAnalysis {
C.mongocrypt_setopt_bypass_query_analysis(wrapped)
}
// If loading the crypt_shared library isn't disabled, set the default library search path "$SYSTEM"
// and set a library override path if one was provided.
if !opts.CryptSharedLibDisabled {
systemStr := C.CString("$SYSTEM")
defer C.free(unsafe.Pointer(systemStr))
C.mongocrypt_setopt_append_crypt_shared_lib_search_path(crypt.wrapped, systemStr)
if opts.CryptSharedLibOverridePath != "" {
cryptSharedLibOverridePathStr := C.CString(opts.CryptSharedLibOverridePath)
defer C.free(unsafe.Pointer(cryptSharedLibOverridePathStr))
C.mongocrypt_setopt_set_crypt_shared_lib_path_override(crypt.wrapped, cryptSharedLibOverridePathStr)
}
}
C.mongocrypt_setopt_use_need_kms_credentials_state(crypt.wrapped)
// initialize handle
if !C.mongocrypt_init(crypt.wrapped) {
return nil, crypt.createErrorFromStatus()
}
return crypt, nil
}
// CreateEncryptionContext creates a Context to use for encryption.
func (m *MongoCrypt) CreateEncryptionContext(db string, cmd bsoncore.Document) (*Context, error) {
ctx := newContext(C.mongocrypt_ctx_new(m.wrapped))
if ctx.wrapped == nil {
return nil, m.createErrorFromStatus()
}
cmdBinary := newBinaryFromBytes(cmd)
defer cmdBinary.close()
dbStr := C.CString(db)
defer C.free(unsafe.Pointer(dbStr))
if ok := C.mongocrypt_ctx_encrypt_init(ctx.wrapped, dbStr, C.int32_t(-1), cmdBinary.wrapped); !ok {
return nil, ctx.createErrorFromStatus()
}
return ctx, nil
}
// CreateDecryptionContext creates a Context to use for decryption.
func (m *MongoCrypt) CreateDecryptionContext(cmd bsoncore.Document) (*Context, error) {
ctx := newContext(C.mongocrypt_ctx_new(m.wrapped))
if ctx.wrapped == nil {
return nil, m.createErrorFromStatus()
}
cmdBinary := newBinaryFromBytes(cmd)
defer cmdBinary.close()
if ok := C.mongocrypt_ctx_decrypt_init(ctx.wrapped, cmdBinary.wrapped); !ok {
return nil, ctx.createErrorFromStatus()
}
return ctx, nil
}
// lookupString returns a string for the value corresponding to the given key in the document.
// if the key does not exist or the value is not a string, the empty string is returned.
func lookupString(doc bsoncore.Document, key string) string {
strVal, _ := doc.Lookup(key).StringValueOK()
return strVal
}
func setAltName(ctx *Context, altName string) error {
// create document {"keyAltName": keyAltName}
idx, doc := bsoncore.AppendDocumentStart(nil)
doc = bsoncore.AppendStringElement(doc, "keyAltName", altName)
doc, _ = bsoncore.AppendDocumentEnd(doc, idx)
keyAltBinary := newBinaryFromBytes(doc)
defer keyAltBinary.close()
if ok := C.mongocrypt_ctx_setopt_key_alt_name(ctx.wrapped, keyAltBinary.wrapped); !ok {
return ctx.createErrorFromStatus()
}
return nil
}
func setKeyMaterial(ctx *Context, keyMaterial []byte) error {
// Create document {"keyMaterial": keyMaterial} using the generic binary sybtype 0x00.
idx, doc := bsoncore.AppendDocumentStart(nil)
doc = bsoncore.AppendBinaryElement(doc, "keyMaterial", 0x00, keyMaterial)
doc, err := bsoncore.AppendDocumentEnd(doc, idx)
if err != nil {
return err
}
keyMaterialBinary := newBinaryFromBytes(doc)
defer keyMaterialBinary.close()
if ok := C.mongocrypt_ctx_setopt_key_material(ctx.wrapped, keyMaterialBinary.wrapped); !ok {
return ctx.createErrorFromStatus()
}
return nil
}
func rewrapDataKey(ctx *Context, filter []byte) error {
filterBinary := newBinaryFromBytes(filter)
defer filterBinary.close()
if ok := C.mongocrypt_ctx_rewrap_many_datakey_init(ctx.wrapped, filterBinary.wrapped); !ok {
return ctx.createErrorFromStatus()
}
return nil
}
// CreateDataKeyContext creates a Context to use for creating a data key.
func (m *MongoCrypt) CreateDataKeyContext(kmsProvider string, opts *options.DataKeyOptions) (*Context, error) {
ctx := newContext(C.mongocrypt_ctx_new(m.wrapped))
if ctx.wrapped == nil {
return nil, m.createErrorFromStatus()
}
// Create a masterKey document of the form { "provider": <provider string>, other options... }.
var masterKey bsoncore.Document
switch {
case opts.MasterKey != nil:
// The original key passed into the top-level API was already transformed into a raw BSON document and passed
// down to here, so we can modify it without copying. Remove the terminating byte to add the "provider" field.
masterKey = opts.MasterKey[:len(opts.MasterKey)-1]
masterKey = bsoncore.AppendStringElement(masterKey, "provider", kmsProvider)
masterKey, _ = bsoncore.AppendDocumentEnd(masterKey, 0)
default:
masterKey = bsoncore.NewDocumentBuilder().AppendString("provider", kmsProvider).Build()
}
masterKeyBinary := newBinaryFromBytes(masterKey)
defer masterKeyBinary.close()
if ok := C.mongocrypt_ctx_setopt_key_encryption_key(ctx.wrapped, masterKeyBinary.wrapped); !ok {
return nil, ctx.createErrorFromStatus()
}
for _, altName := range opts.KeyAltNames {
if err := setAltName(ctx, altName); err != nil {
return nil, err
}
}
if opts.KeyMaterial != nil {
if err := setKeyMaterial(ctx, opts.KeyMaterial); err != nil {
return nil, err
}
}
if ok := C.mongocrypt_ctx_datakey_init(ctx.wrapped); !ok {
return nil, ctx.createErrorFromStatus()
}
return ctx, nil
}
const (
IndexTypeUnindexed = 1
IndexTypeIndexed = 2
)
// CreateExplicitEncryptionContext creates a Context to use for explicit encryption.
func (m *MongoCrypt) CreateExplicitEncryptionContext(doc bsoncore.Document, opts *options.ExplicitEncryptionOptions) (*Context, error) {
ctx := newContext(C.mongocrypt_ctx_new(m.wrapped))
if ctx.wrapped == nil {
return nil, m.createErrorFromStatus()
}
if opts.KeyID != nil {
keyIDBinary := newBinaryFromBytes(opts.KeyID.Data)
defer keyIDBinary.close()
if ok := C.mongocrypt_ctx_setopt_key_id(ctx.wrapped, keyIDBinary.wrapped); !ok {
return nil, ctx.createErrorFromStatus()
}
}
if opts.KeyAltName != nil {
if err := setAltName(ctx, *opts.KeyAltName); err != nil {
return nil, err
}
}
algoStr := C.CString(opts.Algorithm)
defer C.free(unsafe.Pointer(algoStr))
if ok := C.mongocrypt_ctx_setopt_algorithm(ctx.wrapped, algoStr, -1); !ok {
return nil, ctx.createErrorFromStatus()
}
if opts.QueryType != "" {
queryStr := C.CString(opts.QueryType)
defer C.free(unsafe.Pointer(queryStr))
if ok := C.mongocrypt_ctx_setopt_query_type(ctx.wrapped, queryStr, -1); !ok {
return nil, ctx.createErrorFromStatus()
}
}
if opts.ContentionFactor != nil {
if ok := C.mongocrypt_ctx_setopt_contention_factor(ctx.wrapped, C.int64_t(*opts.ContentionFactor)); !ok {
return nil, ctx.createErrorFromStatus()
}
}
docBinary := newBinaryFromBytes(doc)
defer docBinary.close()
if ok := C.mongocrypt_ctx_explicit_encrypt_init(ctx.wrapped, docBinary.wrapped); !ok {
return nil, ctx.createErrorFromStatus()
}
return ctx, nil
}
// CreateExplicitDecryptionContext creates a Context to use for explicit decryption.
func (m *MongoCrypt) CreateExplicitDecryptionContext(doc bsoncore.Document) (*Context, error) {
ctx := newContext(C.mongocrypt_ctx_new(m.wrapped))
if ctx.wrapped == nil {
return nil, m.createErrorFromStatus()
}
docBinary := newBinaryFromBytes(doc)
defer docBinary.close()
if ok := C.mongocrypt_ctx_explicit_decrypt_init(ctx.wrapped, docBinary.wrapped); !ok {
return nil, ctx.createErrorFromStatus()
}
return ctx, nil
}
// CryptSharedLibVersion returns the version number for the loaded crypt_shared library, or 0 if the
// crypt_shared library was not loaded.
func (m *MongoCrypt) CryptSharedLibVersion() uint64 {
return uint64(C.mongocrypt_crypt_shared_lib_version(m.wrapped))
}
// CryptSharedLibVersionString returns the version string for the loaded crypt_shared library, or an
// empty string if the crypt_shared library was not loaded.
func (m *MongoCrypt) CryptSharedLibVersionString() string {
// Pass in a pointer for "len", but ignore the value because C.GoString can determine the string
// length without it.
len := C.uint(0)
str := C.GoString(C.mongocrypt_crypt_shared_lib_version_string(m.wrapped, &len))
return str
}
// Close cleans up any resources associated with the given MongoCrypt instance.
func (m *MongoCrypt) Close() {
C.mongocrypt_destroy(m.wrapped)
}
// RewrapDataKeyContext create a Context to use for rewrapping a data key.
func (m *MongoCrypt) RewrapDataKeyContext(filter []byte, opts *options.RewrapManyDataKeyOptions) (*Context, error) {
const masterKey = "masterKey"
const providerKey = "provider"
ctx := newContext(C.mongocrypt_ctx_new(m.wrapped))
if ctx.wrapped == nil {
return nil, m.createErrorFromStatus()
}
if opts.Provider != nil {
// If a provider has been specified, create an encryption key document for creating a data key or for rewrapping
// datakeys. If a new provider is not specified, then the filter portion of this logic returns the data as it
// exists in the collection.
idx, mongocryptDoc := bsoncore.AppendDocumentStart(nil)
mongocryptDoc = bsoncore.AppendStringElement(mongocryptDoc, providerKey, *opts.Provider)
if opts.MasterKey != nil {
mongocryptDoc = opts.MasterKey[:len(opts.MasterKey)-1]
mongocryptDoc = bsoncore.AppendStringElement(mongocryptDoc, providerKey, *opts.Provider)
}
mongocryptDoc, err := bsoncore.AppendDocumentEnd(mongocryptDoc, idx)
if err != nil {
return nil, err
}
mongocryptBinary := newBinaryFromBytes(mongocryptDoc)
defer mongocryptBinary.close()
// Add new masterKey to the mongocrypt context.
if ok := C.mongocrypt_ctx_setopt_key_encryption_key(ctx.wrapped, mongocryptBinary.wrapped); !ok {
return nil, ctx.createErrorFromStatus()
}
}
return ctx, rewrapDataKey(ctx, filter)
}
func (m *MongoCrypt) setProviderOptions(kmsProviders bsoncore.Document) error {
providersBinary := newBinaryFromBytes(kmsProviders)
defer providersBinary.close()
if ok := C.mongocrypt_setopt_kms_providers(m.wrapped, providersBinary.wrapped); !ok {
return m.createErrorFromStatus()
}
return nil
}
// setLocalSchemaMap sets the local schema map in mongocrypt.
func (m *MongoCrypt) setLocalSchemaMap(schemaMap map[string]bsoncore.Document) error {
if len(schemaMap) == 0 {
return nil
}
// convert schema map to BSON document
schemaMapBSON, err := bson.Marshal(schemaMap)
if err != nil {
return fmt.Errorf("error marshalling SchemaMap: %v", err)
}
schemaMapBinary := newBinaryFromBytes(schemaMapBSON)
defer schemaMapBinary.close()
if ok := C.mongocrypt_setopt_schema_map(m.wrapped, schemaMapBinary.wrapped); !ok {
return m.createErrorFromStatus()
}
return nil
}
// setEncryptedFieldsMap sets the encryptedfields map in mongocrypt.
func (m *MongoCrypt) setEncryptedFieldsMap(encryptedfieldsMap map[string]bsoncore.Document) error {
if len(encryptedfieldsMap) == 0 {
return nil
}
// convert encryptedfields map to BSON document
encryptedfieldsMapBSON, err := bson.Marshal(encryptedfieldsMap)
if err != nil {
return fmt.Errorf("error marshalling EncryptedFieldsMap: %v", err)
}
encryptedfieldsMapBinary := newBinaryFromBytes(encryptedfieldsMapBSON)
defer encryptedfieldsMapBinary.close()
if ok := C.mongocrypt_setopt_encrypted_field_config_map(m.wrapped, encryptedfieldsMapBinary.wrapped); !ok {
return m.createErrorFromStatus()
}
return nil
}
// createErrorFromStatus creates a new Error based on the status of the MongoCrypt instance.
func (m *MongoCrypt) createErrorFromStatus() error {
status := C.mongocrypt_status_new()
defer C.mongocrypt_status_destroy(status)
C.mongocrypt_status(m.wrapped, status)
return errorFromStatus(status)
}
// GetKmsProviders returns the originally configured KMS providers.
func (m *MongoCrypt) GetKmsProviders() bsoncore.Document {
return m.kmsProviders
}

View File

@@ -0,0 +1,115 @@
// Copyright (C) MongoDB, Inc. 2017-present.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may
// not use this file except in compliance with the License. You may obtain
// a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
//go:build cse
// +build cse
package mongocrypt
// #include <mongocrypt.h>
import "C"
import (
"go.mongodb.org/mongo-driver/x/bsonx/bsoncore"
)
// Context represents a mongocrypt_ctx_t handle
type Context struct {
wrapped *C.mongocrypt_ctx_t
}
// newContext creates a Context wrapper around the given C type.
func newContext(wrapped *C.mongocrypt_ctx_t) *Context {
return &Context{
wrapped: wrapped,
}
}
// State returns the current State of the Context.
func (c *Context) State() State {
return State(int(C.mongocrypt_ctx_state(c.wrapped)))
}
// NextOperation gets the document for the next database operation to run.
func (c *Context) NextOperation() (bsoncore.Document, error) {
opDocBinary := newBinary() // out param for mongocrypt_ctx_mongo_op to fill in operation
defer opDocBinary.close()
if ok := C.mongocrypt_ctx_mongo_op(c.wrapped, opDocBinary.wrapped); !ok {
return nil, c.createErrorFromStatus()
}
return opDocBinary.toBytes(), nil
}
// AddOperationResult feeds the result of a database operation to mongocrypt.
func (c *Context) AddOperationResult(result bsoncore.Document) error {
resultBinary := newBinaryFromBytes(result)
defer resultBinary.close()
if ok := C.mongocrypt_ctx_mongo_feed(c.wrapped, resultBinary.wrapped); !ok {
return c.createErrorFromStatus()
}
return nil
}
// CompleteOperation signals a database operation has been completed.
func (c *Context) CompleteOperation() error {
if ok := C.mongocrypt_ctx_mongo_done(c.wrapped); !ok {
return c.createErrorFromStatus()
}
return nil
}
// NextKmsContext returns the next KmsContext, or nil if there are no more.
func (c *Context) NextKmsContext() *KmsContext {
ctx := C.mongocrypt_ctx_next_kms_ctx(c.wrapped)
if ctx == nil {
return nil
}
return newKmsContext(ctx)
}
// FinishKmsContexts signals that all KMS contexts have been completed.
func (c *Context) FinishKmsContexts() error {
if ok := C.mongocrypt_ctx_kms_done(c.wrapped); !ok {
return c.createErrorFromStatus()
}
return nil
}
// Finish performs the final operations for the context and returns the resulting document.
func (c *Context) Finish() (bsoncore.Document, error) {
docBinary := newBinary() // out param for mongocrypt_ctx_finalize to fill in resulting document
defer docBinary.close()
if ok := C.mongocrypt_ctx_finalize(c.wrapped, docBinary.wrapped); !ok {
return nil, c.createErrorFromStatus()
}
return docBinary.toBytes(), nil
}
// Close cleans up any resources associated with the given Context instance.
func (c *Context) Close() {
C.mongocrypt_ctx_destroy(c.wrapped)
}
// createErrorFromStatus creates a new Error based on the status of the MongoCrypt instance.
func (c *Context) createErrorFromStatus() error {
status := C.mongocrypt_status_new()
defer C.mongocrypt_status_destroy(status)
C.mongocrypt_ctx_status(c.wrapped, status)
return errorFromStatus(status)
}
// ProvideKmsProviders provides the KMS providers when in the NeedKmsCredentials state.
func (c *Context) ProvideKmsProviders(kmsProviders bsoncore.Document) error {
kmsProvidersBinary := newBinaryFromBytes(kmsProviders)
defer kmsProvidersBinary.close()
if ok := C.mongocrypt_ctx_provide_kms_providers(c.wrapped, kmsProvidersBinary.wrapped); !ok {
return c.createErrorFromStatus()
}
return nil
}

View File

@@ -0,0 +1,62 @@
// Copyright (C) MongoDB, Inc. 2017-present.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may
// not use this file except in compliance with the License. You may obtain
// a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
//go:build !cse
// +build !cse
package mongocrypt
import (
"go.mongodb.org/mongo-driver/x/bsonx/bsoncore"
)
// Context represents a mongocrypt_ctx_t handle
type Context struct{}
// State returns the current State of the Context.
func (c *Context) State() State {
panic(cseNotSupportedMsg)
}
// NextOperation gets the document for the next database operation to run.
func (c *Context) NextOperation() (bsoncore.Document, error) {
panic(cseNotSupportedMsg)
}
// AddOperationResult feeds the result of a database operation to mongocrypt.
func (c *Context) AddOperationResult(result bsoncore.Document) error {
panic(cseNotSupportedMsg)
}
// CompleteOperation signals a database operation has been completed.
func (c *Context) CompleteOperation() error {
panic(cseNotSupportedMsg)
}
// NextKmsContext returns the next KmsContext, or nil if there are no more.
func (c *Context) NextKmsContext() *KmsContext {
panic(cseNotSupportedMsg)
}
// FinishKmsContexts signals that all KMS contexts have been completed.
func (c *Context) FinishKmsContexts() error {
panic(cseNotSupportedMsg)
}
// Finish performs the final operations for the context and returns the resulting document.
func (c *Context) Finish() (bsoncore.Document, error) {
panic(cseNotSupportedMsg)
}
// Close cleans up any resources associated with the given Context instance.
func (c *Context) Close() {
panic(cseNotSupportedMsg)
}
// ProvideKmsProviders provides the KMS providers when in the NeedKmsCredentials state.
func (c *Context) ProvideKmsProviders(kmsProviders bsoncore.Document) error {
panic(cseNotSupportedMsg)
}

View File

@@ -0,0 +1,76 @@
// Copyright (C) MongoDB, Inc. 2017-present.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may
// not use this file except in compliance with the License. You may obtain
// a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
//go:build cse
// +build cse
package mongocrypt
// #include <mongocrypt.h>
import "C"
// KmsContext represents a mongocrypt_kms_ctx_t handle.
type KmsContext struct {
wrapped *C.mongocrypt_kms_ctx_t
}
// newKmsContext creates a KmsContext wrapper around the given C type.
func newKmsContext(wrapped *C.mongocrypt_kms_ctx_t) *KmsContext {
return &KmsContext{
wrapped: wrapped,
}
}
// HostName gets the host name of the KMS.
func (kc *KmsContext) HostName() (string, error) {
var hostname *C.char // out param for mongocrypt function to fill in hostname
if ok := C.mongocrypt_kms_ctx_endpoint(kc.wrapped, &hostname); !ok {
return "", kc.createErrorFromStatus()
}
return C.GoString(hostname), nil
}
// KMSProvider gets the KMS provider of the KMS context.
func (kc *KmsContext) KMSProvider() string {
kmsProvider := C.mongocrypt_kms_ctx_get_kms_provider(kc.wrapped, nil)
return C.GoString(kmsProvider)
}
// Message returns the message to send to the KMS.
func (kc *KmsContext) Message() ([]byte, error) {
msgBinary := newBinary()
defer msgBinary.close()
if ok := C.mongocrypt_kms_ctx_message(kc.wrapped, msgBinary.wrapped); !ok {
return nil, kc.createErrorFromStatus()
}
return msgBinary.toBytes(), nil
}
// BytesNeeded returns the number of bytes that should be received from the KMS.
// After sending the message to the KMS, this message should be called in a loop until the number returned is 0.
func (kc *KmsContext) BytesNeeded() int32 {
return int32(C.mongocrypt_kms_ctx_bytes_needed(kc.wrapped))
}
// FeedResponse feeds the bytes received from the KMS to mongocrypt.
func (kc *KmsContext) FeedResponse(response []byte) error {
responseBinary := newBinaryFromBytes(response)
defer responseBinary.close()
if ok := C.mongocrypt_kms_ctx_feed(kc.wrapped, responseBinary.wrapped); !ok {
return kc.createErrorFromStatus()
}
return nil
}
// createErrorFromStatus creates a new Error from the status of the KmsContext instance.
func (kc *KmsContext) createErrorFromStatus() error {
status := C.mongocrypt_status_new()
defer C.mongocrypt_status_destroy(status)
C.mongocrypt_kms_ctx_status(kc.wrapped, status)
return errorFromStatus(status)
}

View File

@@ -0,0 +1,39 @@
// Copyright (C) MongoDB, Inc. 2017-present.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may
// not use this file except in compliance with the License. You may obtain
// a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
//go:build !cse
// +build !cse
package mongocrypt
// KmsContext represents a mongocrypt_kms_ctx_t handle.
type KmsContext struct{}
// HostName gets the host name of the KMS.
func (kc *KmsContext) HostName() (string, error) {
panic(cseNotSupportedMsg)
}
// Message returns the message to send to the KMS.
func (kc *KmsContext) Message() ([]byte, error) {
panic(cseNotSupportedMsg)
}
// KMSProvider gets the KMS provider of the KMS context.
func (kc *KmsContext) KMSProvider() string {
panic(cseNotSupportedMsg)
}
// BytesNeeded returns the number of bytes that should be received from the KMS.
// After sending the message to the KMS, this message should be called in a loop until the number returned is 0.
func (kc *KmsContext) BytesNeeded() int32 {
panic(cseNotSupportedMsg)
}
// FeedResponse feeds the bytes received from the KMS to mongocrypt.
func (kc *KmsContext) FeedResponse(response []byte) error {
panic(cseNotSupportedMsg)
}

View File

@@ -0,0 +1,83 @@
// Copyright (C) MongoDB, Inc. 2017-present.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may
// not use this file except in compliance with the License. You may obtain
// a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
//go:build !cse
// +build !cse
package mongocrypt
import (
"go.mongodb.org/mongo-driver/x/bsonx/bsoncore"
"go.mongodb.org/mongo-driver/x/mongo/driver/mongocrypt/options"
)
const cseNotSupportedMsg = "client-side encryption not enabled. add the cse build tag to support"
// MongoCrypt represents a mongocrypt_t handle.
type MongoCrypt struct{}
// Version returns the version string for the loaded libmongocrypt, or an empty string
// if libmongocrypt was not loaded.
func Version() string {
return ""
}
// NewMongoCrypt constructs a new MongoCrypt instance configured using the provided MongoCryptOptions.
func NewMongoCrypt(opts *options.MongoCryptOptions) (*MongoCrypt, error) {
panic(cseNotSupportedMsg)
}
// CreateEncryptionContext creates a Context to use for encryption.
func (m *MongoCrypt) CreateEncryptionContext(db string, cmd bsoncore.Document) (*Context, error) {
panic(cseNotSupportedMsg)
}
// CreateDecryptionContext creates a Context to use for decryption.
func (m *MongoCrypt) CreateDecryptionContext(cmd bsoncore.Document) (*Context, error) {
panic(cseNotSupportedMsg)
}
// CreateDataKeyContext creates a Context to use for creating a data key.
func (m *MongoCrypt) CreateDataKeyContext(kmsProvider string, opts *options.DataKeyOptions) (*Context, error) {
panic(cseNotSupportedMsg)
}
// CreateExplicitEncryptionContext creates a Context to use for explicit encryption.
func (m *MongoCrypt) CreateExplicitEncryptionContext(doc bsoncore.Document, opts *options.ExplicitEncryptionOptions) (*Context, error) {
panic(cseNotSupportedMsg)
}
// RewrapDataKeyContext creates a Context to use for rewrapping a data key.
func (m *MongoCrypt) RewrapDataKeyContext(filter []byte, opts *options.RewrapManyDataKeyOptions) (*Context, error) {
panic(cseNotSupportedMsg)
}
// CreateExplicitDecryptionContext creates a Context to use for explicit decryption.
func (m *MongoCrypt) CreateExplicitDecryptionContext(doc bsoncore.Document) (*Context, error) {
panic(cseNotSupportedMsg)
}
// CryptSharedLibVersion returns the version number for the loaded crypt_shared library, or 0 if the
// crypt_shared library was not loaded.
func (m *MongoCrypt) CryptSharedLibVersion() uint64 {
panic(cseNotSupportedMsg)
}
// CryptSharedLibVersionString returns the version string for the loaded crypt_shared library, or an
// empty string if the crypt_shared library was not loaded.
func (m *MongoCrypt) CryptSharedLibVersionString() string {
panic(cseNotSupportedMsg)
}
// Close cleans up any resources associated with the given MongoCrypt instance.
func (m *MongoCrypt) Close() {
panic(cseNotSupportedMsg)
}
// GetKmsProviders returns the originally configured KMS providers.
func (m *MongoCrypt) GetKmsProviders() bsoncore.Document {
panic(cseNotSupportedMsg)
}

View File

@@ -0,0 +1,139 @@
// Copyright (C) MongoDB, Inc. 2017-present.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may
// not use this file except in compliance with the License. You may obtain
// a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
package options
import (
"go.mongodb.org/mongo-driver/bson/primitive"
"go.mongodb.org/mongo-driver/x/bsonx/bsoncore"
)
// DataKeyOptions specifies options for creating a new data key.
type DataKeyOptions struct {
KeyAltNames []string
KeyMaterial []byte
MasterKey bsoncore.Document
}
// DataKey creates a new DataKeyOptions instance.
func DataKey() *DataKeyOptions {
return &DataKeyOptions{}
}
// SetKeyAltNames specifies alternate key names.
func (dko *DataKeyOptions) SetKeyAltNames(names []string) *DataKeyOptions {
dko.KeyAltNames = names
return dko
}
// SetMasterKey specifies the master key.
func (dko *DataKeyOptions) SetMasterKey(key bsoncore.Document) *DataKeyOptions {
dko.MasterKey = key
return dko
}
// SetKeyMaterial specifies the key material.
func (dko *DataKeyOptions) SetKeyMaterial(keyMaterial []byte) *DataKeyOptions {
dko.KeyMaterial = keyMaterial
return dko
}
// QueryType describes the type of query the result of Encrypt is used for.
type QueryType int
// These constants specify valid values for QueryType
const (
QueryTypeEquality QueryType = 1
)
// ExplicitEncryptionOptions specifies options for configuring an explicit encryption context.
type ExplicitEncryptionOptions struct {
KeyID *primitive.Binary
KeyAltName *string
Algorithm string
QueryType string
ContentionFactor *int64
}
// ExplicitEncryption creates a new ExplicitEncryptionOptions instance.
func ExplicitEncryption() *ExplicitEncryptionOptions {
return &ExplicitEncryptionOptions{}
}
// SetKeyID sets the key identifier.
func (eeo *ExplicitEncryptionOptions) SetKeyID(keyID primitive.Binary) *ExplicitEncryptionOptions {
eeo.KeyID = &keyID
return eeo
}
// SetKeyAltName sets the key alternative name.
func (eeo *ExplicitEncryptionOptions) SetKeyAltName(keyAltName string) *ExplicitEncryptionOptions {
eeo.KeyAltName = &keyAltName
return eeo
}
// SetAlgorithm specifies an encryption algorithm.
func (eeo *ExplicitEncryptionOptions) SetAlgorithm(algorithm string) *ExplicitEncryptionOptions {
eeo.Algorithm = algorithm
return eeo
}
// SetQueryType specifies the query type.
func (eeo *ExplicitEncryptionOptions) SetQueryType(queryType string) *ExplicitEncryptionOptions {
eeo.QueryType = queryType
return eeo
}
// SetContentionFactor specifies the contention factor.
func (eeo *ExplicitEncryptionOptions) SetContentionFactor(contentionFactor int64) *ExplicitEncryptionOptions {
eeo.ContentionFactor = &contentionFactor
return eeo
}
// RewrapManyDataKeyOptions represents all possible options used to decrypt and encrypt all matching data keys with a
// possibly new masterKey.
type RewrapManyDataKeyOptions struct {
// Provider identifies the new KMS provider. If omitted, encrypting uses the current KMS provider.
Provider *string
// MasterKey identifies the new masterKey. If omitted, rewraps with the current masterKey.
MasterKey bsoncore.Document
}
// RewrapManyDataKey creates a new RewrapManyDataKeyOptions instance.
func RewrapManyDataKey() *RewrapManyDataKeyOptions {
return new(RewrapManyDataKeyOptions)
}
// SetProvider sets the value for the Provider field.
func (rmdko *RewrapManyDataKeyOptions) SetProvider(provider string) *RewrapManyDataKeyOptions {
rmdko.Provider = &provider
return rmdko
}
// SetMasterKey sets the value for the MasterKey field.
func (rmdko *RewrapManyDataKeyOptions) SetMasterKey(masterKey bsoncore.Document) *RewrapManyDataKeyOptions {
rmdko.MasterKey = masterKey
return rmdko
}
// MergeRewrapManyDataKeyOptions combines the given RewrapManyDataKeyOptions instances into a single
// RewrapManyDataKeyOptions in a last one wins fashion.
func MergeRewrapManyDataKeyOptions(opts ...*RewrapManyDataKeyOptions) *RewrapManyDataKeyOptions {
rmdkOpts := RewrapManyDataKey()
for _, rmdko := range opts {
if rmdko == nil {
continue
}
if provider := rmdko.Provider; provider != nil {
rmdkOpts.Provider = provider
}
if masterKey := rmdko.MasterKey; masterKey != nil {
rmdkOpts.MasterKey = masterKey
}
}
return rmdkOpts
}

View File

@@ -0,0 +1,63 @@
// Copyright (C) MongoDB, Inc. 2017-present.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may
// not use this file except in compliance with the License. You may obtain
// a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
package options
import (
"go.mongodb.org/mongo-driver/x/bsonx/bsoncore"
)
// MongoCryptOptions specifies options to configure a MongoCrypt instance.
type MongoCryptOptions struct {
KmsProviders bsoncore.Document
LocalSchemaMap map[string]bsoncore.Document
BypassQueryAnalysis bool
EncryptedFieldsMap map[string]bsoncore.Document
CryptSharedLibDisabled bool
CryptSharedLibOverridePath string
}
// MongoCrypt creates a new MongoCryptOptions instance.
func MongoCrypt() *MongoCryptOptions {
return &MongoCryptOptions{}
}
// SetKmsProviders specifies the KMS providers map.
func (mo *MongoCryptOptions) SetKmsProviders(kmsProviders bsoncore.Document) *MongoCryptOptions {
mo.KmsProviders = kmsProviders
return mo
}
// SetLocalSchemaMap specifies the local schema map.
func (mo *MongoCryptOptions) SetLocalSchemaMap(localSchemaMap map[string]bsoncore.Document) *MongoCryptOptions {
mo.LocalSchemaMap = localSchemaMap
return mo
}
// SetBypassQueryAnalysis skips the NeedMongoMarkings state.
func (mo *MongoCryptOptions) SetBypassQueryAnalysis(bypassQueryAnalysis bool) *MongoCryptOptions {
mo.BypassQueryAnalysis = bypassQueryAnalysis
return mo
}
// SetEncryptedFieldsMap specifies the encrypted fields map.
func (mo *MongoCryptOptions) SetEncryptedFieldsMap(efcMap map[string]bsoncore.Document) *MongoCryptOptions {
mo.EncryptedFieldsMap = efcMap
return mo
}
// SetCryptSharedLibDisabled explicitly disables loading the crypt_shared library if set to true.
func (mo *MongoCryptOptions) SetCryptSharedLibDisabled(disabled bool) *MongoCryptOptions {
mo.CryptSharedLibDisabled = disabled
return mo
}
// SetCryptSharedLibOverridePath sets the override path to the crypt_shared library file. Setting
// an override path disables the default operating system dynamic library search path.
func (mo *MongoCryptOptions) SetCryptSharedLibOverridePath(path string) *MongoCryptOptions {
mo.CryptSharedLibOverridePath = path
return mo
}

View File

@@ -0,0 +1,47 @@
// Copyright (C) MongoDB, Inc. 2017-present.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may
// not use this file except in compliance with the License. You may obtain
// a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
package mongocrypt
// State represents a state that a MongocryptContext can be in.
type State int
// These constants are valid values for the State type.
// The values must match the values defined in the mongocrypt_ctx_state_t enum in libmongocrypt.
const (
StateError State = 0
NeedMongoCollInfo State = 1
NeedMongoMarkings State = 2
NeedMongoKeys State = 3
NeedKms State = 4
Ready State = 5
Done State = 6
NeedKmsCredentials State = 7
)
// String implements the Stringer interface.
func (s State) String() string {
switch s {
case StateError:
return "Error"
case NeedMongoCollInfo:
return "NeedMongoCollInfo"
case NeedMongoMarkings:
return "NeedMongoMarkings"
case NeedMongoKeys:
return "NeedMongoKeys"
case NeedKms:
return "NeedKms"
case Ready:
return "Ready"
case Done:
return "Done"
case NeedKmsCredentials:
return "NeedKmsCredentials"
default:
return "Unknown State"
}
}