TEST: Add test to exercise OPENSSL_CTX_set0_default()
authorRichard Levitte <levitte@openssl.org>
Mon, 22 Jun 2020 13:49:55 +0000 (15:49 +0200)
committerRichard Levitte <levitte@openssl.org>
Sun, 28 Jun 2020 08:55:51 +0000 (10:55 +0200)
Reviewed-by: Matt Caswell <matt@openssl.org>
(Merged from https://github.com/openssl/openssl/pull/12228)

test/evp_extra_test2.c

index f4d8b98256134847561ac5e900794f31a1911be9..63380f878a100f2efd4ae842f9cb6b277dd40b7f 100644 (file)
@@ -19,7 +19,7 @@
 #include "testutil.h"
 #include "internal/nelem.h"
 
-static OPENSSL_CTX *libctx = NULL;
+static OPENSSL_CTX *mainctx = NULL;
 static OSSL_PROVIDER *nullprov = NULL;
 
 /*
@@ -198,7 +198,7 @@ static int test_d2i_AutoPrivateKey_ex(int i)
     int expected_id = ak->evptype;
 
     p = input;
-    if (!TEST_ptr(pkey = d2i_AutoPrivateKey_ex(NULL, &p, input_len, libctx,
+    if (!TEST_ptr(pkey = d2i_AutoPrivateKey_ex(NULL, &p, input_len, mainctx,
                                                NULL))
             || !TEST_ptr_eq(p, input + input_len)
             || !TEST_int_eq(EVP_PKEY_id(pkey), expected_id))
@@ -211,20 +211,58 @@ static int test_d2i_AutoPrivateKey_ex(int i)
     return ret;
 }
 
+static int test_alternative_default(void)
+{
+    OPENSSL_CTX *oldctx;
+    EVP_MD *sha256;
+    int ok = 0;
+
+    /*
+     * setup_tests() loaded the "null" provider in the current default, so
+     * we know this fetch should fail.
+     */
+    if (!TEST_ptr_null(sha256 = EVP_MD_fetch(NULL, "SHA2-256", NULL)))
+        goto err;
+
+    /*
+     * Now we switch to our main library context, and try again.  Since no
+     * providers are loaded in this one, it should fall back to the default.
+     */
+    if (!TEST_ptr(oldctx = OPENSSL_CTX_set0_default(mainctx))
+        || !TEST_ptr(sha256 = EVP_MD_fetch(NULL, "SHA2-256", NULL)))
+        goto err;
+    EVP_MD_free(sha256);
+    sha256 = NULL;
+
+    /*
+     * Switching back should give us our main library context back, and
+     * fetching SHA2-256 should fail again.
+     */
+    if (!TEST_ptr_eq(OPENSSL_CTX_set0_default(oldctx), mainctx)
+        || !TEST_ptr_null(sha256 = EVP_MD_fetch(NULL, "SHA2-256", NULL)))
+        goto err;
+
+    ok = 1;
+ err:
+    EVP_MD_free(sha256);
+    return ok;
+}
+
 int setup_tests(void)
 {
-    libctx = OPENSSL_CTX_new();
+    mainctx = OPENSSL_CTX_new();
 
-    if (!TEST_ptr(libctx))
+    if (!TEST_ptr(mainctx))
         return 0;
 
     nullprov = OSSL_PROVIDER_load(NULL, "null");
     if (!TEST_ptr(nullprov)) {
-        OPENSSL_CTX_free(libctx);
-        libctx = NULL;
+        OPENSSL_CTX_free(mainctx);
+        mainctx = NULL;
         return 0;
     }
 
+    ADD_TEST(test_alternative_default);
     ADD_ALL_TESTS(test_d2i_AutoPrivateKey_ex, OSSL_NELEM(keydata));
 
     return 1;
@@ -232,6 +270,6 @@ int setup_tests(void)
 
 void cleanup_tests(void)
 {
-    OPENSSL_CTX_free(libctx);
+    OPENSSL_CTX_free(mainctx);
     OSSL_PROVIDER_unload(nullprov);
 }