"use strict";
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
Object.defineProperty(exports, "__esModule", { value: true });
exports._onDecrypt = exports._onEncrypt = void 0;
const material_management_1 = require("@aws-crypto/material-management");
function _onEncrypt(randomBytes) {
    return async function _onEncrypt(material) {
        if (!material.hasUnencryptedDataKey) {
            const trace = {
                keyName: this.keyName,
                keyNamespace: this.keyNamespace,
                flags: material_management_1.KeyringTraceFlag.WRAPPING_KEY_GENERATED_DATA_KEY,
            };
            const udk = await randomBytes(material.suite.keyLengthBytes);
            material.setUnencryptedDataKey(udk, trace);
        }
        return this._wrapKey(material);
    };
}
exports._onEncrypt = _onEncrypt;
function _onDecrypt() {
    return async function _onDecrypt(material, encryptedDataKeys) {
        /* Check for early return (Postcondition): If the material is already valid, attempting to decrypt is a bad idea. */
        if (material.hasValidKey())
            return material;
        const edks = encryptedDataKeys.filter(this._filter, this);
        /* Check for early return (Postcondition): If there are not EncryptedDataKeys for this keyring, do nothing. */
        if (!edks.length)
            return material;
        for (const edk of edks) {
            try {
                return await this._unwrapKey(material, edk);
            }
            catch (e) {
                // there should be some debug here?  or wrap?
                // Failures decrypt should not short-circuit the process
                // If the caller does not have access they may have access
                // through another Keyring.
            }
        }
        return material;
    };
}
exports._onDecrypt = _onDecrypt;
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoicmF3X2tleXJpbmdfZGVjb3JhdG9ycy5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uLy4uL3NyYy9yYXdfa2V5cmluZ19kZWNvcmF0b3JzLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7QUFBQSxvRUFBb0U7QUFDcEUsc0NBQXNDOzs7QUFFdEMseUVBT3dDO0FBVXhDLFNBQWdCLFVBQVUsQ0FHeEIsV0FBbUQ7SUFDbkQsT0FBTyxLQUFLLFVBQVUsVUFBVSxDQUU5QixRQUErQ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