1// Copyright (C) MongoDB, Inc. 2017-present.
2//
3// Licensed under the Apache License, Version 2.0 (the "License"); you may
4// not use this file except in compliance with the License. You may obtain
5// a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
6
7package mongo
8
9import (
10	"context"
11
12	"go.mongodb.org/mongo-driver/x/bsonx/bsoncore"
13)
14
15// keyRetriever gets keys from the key vault collection.
16type keyRetriever struct {
17	coll *Collection
18}
19
20func (kr *keyRetriever) cryptKeys(ctx context.Context, filter bsoncore.Document) ([]bsoncore.Document, error) {
21	cursor, err := kr.coll.Find(ctx, filter)
22	if err != nil {
23		return nil, EncryptionKeyVaultError{Wrapped: err}
24	}
25	defer cursor.Close(ctx)
26
27	var results []bsoncore.Document
28	for cursor.Next(ctx) {
29		cur := make([]byte, len(cursor.Current))
30		copy(cur, cursor.Current)
31		results = append(results, cur)
32	}
33	if err = cursor.Err(); err != nil {
34		return nil, EncryptionKeyVaultError{Wrapped: err}
35	}
36
37	return results, nil
38}
39
40// collInfoRetriever gets info for collections from a database.
41type collInfoRetriever struct {
42	client *Client
43}
44
45func (cir *collInfoRetriever) cryptCollInfo(ctx context.Context, db string, filter bsoncore.Document) (bsoncore.Document, error) {
46	cursor, err := cir.client.Database(db).ListCollections(ctx, filter)
47	if err != nil {
48		return nil, err
49	}
50	defer cursor.Close(ctx)
51
52	if !cursor.Next(ctx) {
53		return nil, cursor.Err()
54	}
55
56	res := make([]byte, len(cursor.Current))
57	copy(res, cursor.Current)
58	return res, nil
59}
60