summaryrefslogtreecommitdiff
path: root/src/mongo/shell/keyvault.js
blob: 4563cca98c5b699ebaa1125d3408d29fca1b976f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
//  Class that allows the mongo shell to talk to the mongodb KeyVault.
//  Loaded only into the enterprise module.

Mongo.prototype.getKeyVault = function() {
    return new KeyVault(this);
};

class KeyVault {
    _runCommand(client, func, args) {
        let numRetries = 3;
        do {
            try {
                const result = func.apply(client, args);
                return result;
            } catch (e) {
                numRetries--;
                if (!isNetworkError(e) || numRetries == 0) {
                    jsTest.log("KeyVault: We have exceeded the number of retries. Throwing.");
                    throw e;
                }

                const res = this.mongo.getDB('admin')._helloOrLegacyHello();
                if (!res) {
                    jsTest.log("KeyVault: We do not have a connection to the database. Throwing.");
                    throw e;
                }
                this.keyColl = this.mongo.getDataKeyCollection();
            }
        } while (true);
    }

    constructor(mongo) {
        this.mongo = mongo;
        var collection = this._runCommand(this.mongo, this.mongo.getDataKeyCollection, {});
        this.keyColl = collection;
        this._runCommand(this.keyColl, this.keyColl.createIndex, [
            {keyAltNames: 1},
            {unique: true, partialFilterExpression: {keyAltNames: {$exists: true}}}
        ]);
    }

    createKey(kmsProvider, param2 = undefined, param3 = undefined) {
        if (Array.isArray(param2) && param3 === undefined) {
            if (kmsProvider !== "local") {
                return "ValueError: customerMasterKey must be defined if kmsProvider is not local.";
            }
            return this._createKey(kmsProvider, '', param2);
        }

        return this._createKey(kmsProvider, param2, param3);
    }

    _createKey(kmsProvider, customerMasterKey, keyAltNames) {
        if (typeof kmsProvider !== "string") {
            return "TypeError: kmsProvider must be of String type.";
        }

        if (typeof customerMasterKey !== "string" && typeof customerMasterKey !== "object") {
            return "TypeError: customer master key must be of String type.";
        }

        var masterKeyAndMaterial = this._runCommand(
            this.mongo, this.mongo.generateDataKey, [kmsProvider, customerMasterKey]);
        var masterKey = masterKeyAndMaterial.masterKey;

        var current = ISODate();
        var uuid = UUID();

        var doc = {
            "_id": uuid,
            "keyMaterial": masterKeyAndMaterial.keyMaterial,
            "creationDate": current,
            "updateDate": current,
            "status": NumberInt(0),
            "version": NumberLong(0),
            "masterKey": masterKey,
        };

        if (keyAltNames) {
            if (!Array.isArray(keyAltNames)) {
                return "TypeError: key alternate names must be of Array type.";
            }

            let i = 0;
            for (i = 0; i < keyAltNames.length; i++) {
                if (typeof keyAltNames[i] !== "string") {
                    return "TypeError: items in key alternate names must be of String type.";
                }
            }

            doc.keyAltNames = keyAltNames;
        }

        let insertCmdObj = {
            insert: this.keyColl.getName(),
            documents: [doc],
            writeConcern: {w: "majority"}
        };

        assert.commandWorked(this._runCommand(
            this.keyColl.getDB(), this.keyColl.getDB().runCommand, [insertCmdObj]));
        return uuid;
    }

    getKey(keyId) {
        return this._runCommand(this.keyColl, this.keyColl.find, [{"_id": keyId}]);
    }

    getKeyByAltName(keyAltName) {
        return this._runCommand(this.keyColl, this.keyColl.find, [{"keyAltNames": keyAltName}]);
    }

    deleteKey(keyId) {
        return this._runCommand(this.keyColl, this.keyColl.deleteOne, [{"_id": keyId}]);
    }

    getKeys() {
        return this._runCommand(this.keyColl, this.keyColl.find, []);
    }

    addKeyAlternateName(keyId, keyAltName) {
        // keyAltName is not allowed to be an array or an object. In javascript,
        // typeof array is object.
        if (typeof keyAltName === "object") {
            return "TypeError: key alternate name cannot be object or array type.";
        }
        return this._runCommand(
            this.keyColl, this.keyColl.findAndModify, [{
                query: {"_id": keyId},
                update: {$push: {"keyAltNames": keyAltName}, $currentDate: {"updateDate": true}},
            }]);
    }

    removeKeyAlternateName(keyId, keyAltName) {
        if (typeof keyAltName === "object") {
            return "TypeError: key alternate name cannot be object or array type.";
        }

        const ret = this._runCommand(
            this.keyColl, this.keyColl.findAndModify, [{
                query: {"_id": keyId},
                update: {$pull: {"keyAltNames": keyAltName}, $currentDate: {"updateDate": true}}
            }]);

        if (ret != null && ret.keyAltNames.length === 1 && ret.keyAltNames[0] === keyAltName) {
            // Remove the empty array to prevent duplicate key violations
            return this._runCommand(
                this.keyColl, this.keyColl.findAndModify, [{
                    query: {"_id": keyId, "keyAltNames": undefined},
                    update: {$unset: {"keyAltNames": ""}, $currentDate: {"updateDate": true}}
                }]);
        }
        return ret;
    }
}

class ClientEncryption {
    constructor(mongo) {
        this.mongo = mongo;
    }

    encrypt() {
        return this.mongo.encrypt.apply(this.mongo, arguments);
    }

    decrypt() {
        return this.mongo.decrypt.apply(this.mongo, arguments);
    }
}

Mongo.prototype.getClientEncryption = function() {
    return new ClientEncryption(this);
};