File
Blob: src/workerd/api/crypto/impl-test.c++
| 1 | // Copyright (c) 2023 Cloudflare, Inc. |
| 2 | // Licensed under the Apache 2.0 license found in the LICENSE file or at: |
| 3 | // https://opensource.org/licenses/Apache-2.0 |
| 4 | |
| 5 | #include "impl.h" |
| 6 | |
| 7 | #include <openssl/ec.h> |
| 8 | #include <openssl/err.h> |
| 9 | #include <openssl/rsa.h> |
| 10 | |
| 11 | #include <kj/test.h> |
| 12 | |
| 13 | namespace workerd::api { |
| 14 | namespace { |
| 15 | |
| 16 | KJ_TEST("Crypto error conversion") { |
| 17 | ClearErrorOnReturn clearErrorOnReturn; |
| 18 | |
| 19 | // Intentionally provide an error type not handled in throwOpensslError() |
| 20 | // (RSA_R_CANNOT_RECOVER_MULTI_PRIME_KEY) that overlaps with an EC error that we do handle |
| 21 | // (EC_R_INVALID_ENCODING). This test will fail if we do not check the library code of the error. |
| 22 | // This test needs to be updated (e.g. with a different error code) if |
| 23 | // RSA_R_CANNOT_RECOVER_MULTI_PRIME_KEY is added to the error types provided to users in |
| 24 | // throwOpensslError(). |
| 25 | |
| 26 | OPENSSL_PUT_ERROR(RSA, RSA_R_CANNOT_RECOVER_MULTI_PRIME_KEY); |
| 27 | // Throw an exception based on BoringSSL error queue, expecting to get an internal error instead |
| 28 | // of a DOMException |
| 29 | KJ_EXPECT_THROW_MESSAGE("OpenSSL call failed", OSSLCALL(0)); |
| 30 | |
| 31 | // EC_R_INVALID_ENCODING is one of the errors converted to user errors, test that it is converted |
| 32 | // to a DOMException. |
| 33 | OPENSSL_PUT_ERROR(EC, EC_R_INVALID_ENCODING); |
| 34 | KJ_EXPECT_THROW_MESSAGE("jsg.DOMException(OperationError): Invalid point encoding.", OSSLCALL(0)); |
| 35 | } |
| 36 | |
| 37 | KJ_TEST("RSA_R_KEY_SIZE_TOO_SMALL is a user-facing error") { |
| 38 | ClearErrorOnReturn clearErrorOnReturn; |
| 39 | |
| 40 | // RSA_R_KEY_SIZE_TOO_SMALL should be converted to a DOMException(OperationError) rather than |
| 41 | // an internal error (which would generate Sentry noise). |
| 42 | OPENSSL_PUT_ERROR(RSA, RSA_R_KEY_SIZE_TOO_SMALL); |
| 43 | KJ_EXPECT_THROW_MESSAGE( |
| 44 | "jsg.DOMException(OperationError): RSA key size is too small.", OSSLCALL(0)); |
| 45 | } |
| 46 | |
| 47 | KJ_TEST("RSA_R_INTERNAL_ERROR is a user-facing error") { |
| 48 | ClearErrorOnReturn clearErrorOnReturn; |
| 49 | |
| 50 | // RSA_R_INTERNAL_ERROR should be converted to a DOMException(OperationError) rather than |
| 51 | // an internal error. This error occurs during RSA signing when the private key computation |
| 52 | // or post-sign verification fails (e.g. due to corrupted key material). |
| 53 | OPENSSL_PUT_ERROR(RSA, RSA_R_INTERNAL_ERROR); |
| 54 | KJ_EXPECT_THROW_MESSAGE("jsg.DOMException(OperationError): RSA operation failed.", OSSLCALL(0)); |
| 55 | } |
| 56 | |
| 57 | } // namespace |
| 58 | } // namespace workerd::api |