the security unit tests 92/29492/35
authorOleksandr Dmytrenko <o.dmytrenko@samsung.com>
Tue, 14 May 2019 12:28:49 +0000 (15:28 +0300)
committerAleksey Volkov <a.volkov@samsung.com>
Tue, 25 Jun 2019 07:40:57 +0000 (07:40 +0000)
the security unit tests with coverage more 75%

Change-Id: Ia84e693fc00e2e7da9ce83cd845fced011fc8d43
Signed-off-by: Oleksandr Dmytrenko <o.dmytrenko@samsung.com>
38 files changed:
extlibs/libcoap/SConscript
resource/csdk/security/unittest/SConscript
resource/csdk/security/unittest/aclresourcetest.cpp
resource/csdk/security/unittest/amaclresourcetest.cpp
resource/csdk/security/unittest/certhelpers.cpp
resource/csdk/security/unittest/credentialresource.cpp
resource/csdk/security/unittest/crlresourcetest.cpp
resource/csdk/security/unittest/csr/csr.pem [new file with mode: 0644]
resource/csdk/security/unittest/csr/csr1.pem [new file with mode: 0644]
resource/csdk/security/unittest/csr/key.pem [new file with mode: 0644]
resource/csdk/security/unittest/csrresource.cpp [new file with mode: 0644]
resource/csdk/security/unittest/deviceonboardingstate.cpp [new file with mode: 0644]
resource/csdk/security/unittest/doxmresource.cpp
resource/csdk/security/unittest/issuer/cert.der [new file with mode: 0644]
resource/csdk/security/unittest/issuer/cert.pem [new file with mode: 0644]
resource/csdk/security/unittest/issuer/key.pem [new file with mode: 0644]
resource/csdk/security/unittest/occertutility.cpp [new file with mode: 0644]
resource/csdk/security/unittest/ocsecurity.cpp
resource/csdk/security/unittest/oxmpincommon.cpp
resource/csdk/security/unittest/oxmverifycommon.cpp
resource/csdk/security/unittest/pbkdf2tests.cpp
resource/csdk/security/unittest/pkix_interface.cpp [new file with mode: 0644]
resource/csdk/security/unittest/policyengine.cpp
resource/csdk/security/unittest/pstatresource.cpp
resource/csdk/security/unittest/rolesresource.cpp [new file with mode: 0644]
resource/csdk/security/unittest/spresource.cpp
resource/csdk/security/unittest/srmtestcommon.cpp
resource/csdk/security/unittest/srmtestcommon.h
resource/csdk/security/unittest/srmutility.cpp
resource/csdk/security/unittest/ssl/0-root-cert.der [new file with mode: 0644]
resource/csdk/security/unittest/ssl/1-subca-cert.der [new file with mode: 0644]
resource/csdk/security/unittest/ssl/33333333-3333-3333-3333-111111111111_cert.der [new file with mode: 0644]
resource/csdk/security/unittest/ssl/33333333-3333-3333-3333-111111111111_key.der [new file with mode: 0644]
resource/csdk/security/unittest/ssl/33333333-3333-3333-3333-111111111112_cert.der [new file with mode: 0644]
resource/csdk/security/unittest/ssl/33333333-3333-3333-3333-111111111112_key.der [new file with mode: 0644]
resource/csdk/security/unittest/ssl/sample.pem.der [new file with mode: 0644]
resource/csdk/security/unittest/tools.cpp [new file with mode: 0644]
resource/csdk/security/unittest/tools.h [new file with mode: 0644]

index 74395ba..905b21b 100755 (executable)
@@ -142,6 +142,7 @@ if target_os not in ['windows', 'winrt']:
             '-fdata-sections', '-fno-exceptions'])
 
 if target_os == 'msys_nt':
+    libcoap_env.Replace(CCFLAGS = str(libcoap_env['CCFLAGS']).replace('/WX',''))
     libcoap_env.AppendUnique(CPPDEFINES=['_DEFAULT_SOURCE'])
     libcoap_env.AppendUnique(CFLAGS=['-std=c99'])
 
index 5809f13..9af0bd6 100644 (file)
@@ -27,7 +27,6 @@ Import('test_env')
 # SConscript file for Local PKI google tests
 srmtest_env = test_env.Clone()
 target_os = srmtest_env.get('TARGET_OS')
-rd_mode = srmtest_env.get('RD_MODE')
 
 ######################################################################
 # Build flags
@@ -51,21 +50,27 @@ srmtest_env.PrependUnique(CPPPATH=[
     '../../stack/include/internal',
     '../../../oc_logger/include',
     '../provisioning/include',
-    '../include'
+    '../include',
+    '#resource/csdk/security/include/experimental',
+    '#resource/csdk/security/provisioning/include/internal',
+    '#resource/csdk/logger/include/experimental',
+    '#resource/csdk/connectivity/common/inc',
+    '#resource/csdk/security/src',
+    '#extlibs/mbedtls/mbedtls/include',
+    '#resource/csdk/security/provisioning/include/cloud'
 ])
 
 srmtest_env.PrependUnique(LIBS=[
     'octbstack_internal',
-    'ocsrm',
     'routingmanager',
     'oc_logger_internal',
     'connectivity_abstraction_internal',
-    'coap'
+    'coap',
+    'ocpmapi_internal',
+    'ocsrm',
+    'mbedtls', 'mbedx509', 'mbedcrypto'
 ])
 
-if srmtest_env.get('SECURED') == '1':
-    srmtest_env.AppendUnique(LIBS=['mbedtls', 'mbedx509', 'mbedcrypto'])
-
 if srmtest_env.get('LOGGING') == '1':
     srmtest_env.AppendUnique(CPPDEFINES=['TB_LOG'])
 
@@ -73,6 +78,7 @@ if srmtest_env.get('MULTIPLE_OWNER') == '1':
     srmtest_env.AppendUnique(CPPDEFINES=['MULTIPLE_OWNER'])
 
 if target_os == 'windows':
+#    srmtest_env.Replace(CCFLAGS = str(srmtest_env['CCFLAGS']).replace('/WX',''))
     srmtest_env.AppendUnique(LIBS=['sqlite3'])
     #Disable deprecated code warning we are still testing deprecated functions till they are removed.
     srmtest_env.AppendUnique(CCFLAGS=['/wd4996'])
@@ -88,35 +94,37 @@ else:
 ######################################################################
 # Source files and Targets
 ######################################################################
-unittests = []
-unittests_src = []
-unittests_src += [
-    'aclresourcetest.cpp',
-    'amaclresourcetest.cpp',
-    'pstatresource.cpp',
-    'doxmresource.cpp',
-    'policyengine.cpp',
-    'securityresourcemanager.cpp',
-    'credentialresource.cpp',
-    'spresource.cpp',
-    'srmutility.cpp',
-    'iotvticalendartest.cpp',
-    'base64tests.cpp',
-    'pbkdf2tests.cpp',
-    'srmtestcommon.cpp',
-    'crlresourcetest.cpp',
-    'ocsecurity.cpp',
-    'certhelpers.cpp'
+unittests_src = [
+        'tools.cpp',
+        'aclresourcetest.cpp',
+        'amaclresourcetest.cpp',
+        'pstatresource.cpp',
+        'doxmresource.cpp',
+        'policyengine.cpp',
+        'securityresourcemanager.cpp',
+        'credentialresource.cpp',
+        'spresource.cpp',
+        'srmutility.cpp',
+        'iotvticalendartest.cpp',
+        'base64tests.cpp',
+        'pbkdf2tests.cpp',
+        'crlresourcetest.cpp',
+        'ocsecurity.cpp',
+        'certhelpers.cpp',
+        'deviceonboardingstate.cpp',
+        'occertutility.cpp',
+        'pkix_interface.cpp',
+        'srmtestcommon.cpp',
+        'csrresource.cpp'
 ]
 
 if target_os not in ['msys_nt', 'windows']:
     unittests_src += [
         'oxmpincommon.cpp',
-        'oxmverifycommon.cpp'
+        'oxmverifycommon.cpp',
+        'rolesresource.cpp'
     ]
 
-unittests += srmtest_env.Program('unittest', unittests_src)
-
 # this path will be passed as a command-line parameter,
 # so needs encoding to avoid problems with escapes on Windows
 unittest_build_dir = Dir('.').abspath + os.sep
@@ -130,20 +138,20 @@ srmtest_env.AppendUnique(CPPDEFINES=[
     'SECURITY_BUILD_UNITTEST_DIR=' + unittest_build_dir
 ])
 
-unittests += srmtest_env.ScanJSON('resource/csdk/security/unittest')
 
 srmtest_env.AppendTarget('test')
-if srmtest_env.get('TEST') == '1':
-    if target_os in ['linux', 'windows']:
-        out_dir = srmtest_env.get('BUILD_DIR')
-        result_dir = os.path.join(srmtest_env.get('BUILD_DIR'), 'test_out') + os.sep
-        if not os.path.isdir(result_dir):
-            os.makedirs(result_dir)
-        srmtest_env.AppendENVPath('GTEST_OUTPUT', ['xml:' + result_dir])
-        srmtest_env.AppendENVPath('LD_LIBRARY_PATH', [out_dir])
-        run_test(srmtest_env,
+
+if srmtest_env.get('TEST') == '1' and target_os in ['linux', 'windows']:
+    unittests = srmtest_env.Program('unittest', unittests_src)
+    unittests += srmtest_env.ScanJSON('resource/csdk/security/unittest')
+    out_dir = srmtest_env.get('BUILD_DIR')
+    result_dir = os.path.join(srmtest_env.get('BUILD_DIR'), 'test_out') + os.sep
+    if not os.path.isdir(result_dir):
+        os.makedirs(result_dir)
+    srmtest_env.AppendENVPath('GTEST_OUTPUT', ['xml:' + result_dir])
+    srmtest_env.AppendENVPath('LD_LIBRARY_PATH', [out_dir])
+    run_test(srmtest_env,
                  'resource_csdk_security_unittest.memcheck',
                  'resource/csdk/security/unittest/unittest')
-
-srmtest_env.UserInstallTargetExtra(unittests, 'tests/resource/csdk/security/')
+    srmtest_env.UserInstallTargetExtra(unittests, 'tests/resource/csdk/security/')
 
index 51bbdae..1cb4714 100644 (file)
@@ -21,6 +21,8 @@
 #include <gtest/gtest.h>
 #include <coap/utlist.h>
 #include <sys/stat.h>
+
+extern "C" {
 #include "ocstack.h"
 #include "psinterface.h"
 #include "ocpayload.h"
@@ -29,9 +31,7 @@
 #include "cainterface.h"
 #include "secureresourcemanager.h"
 #include "srmresourcestrings.h"
-#include "aclresource.h"
 #include "pstatresource.h"
-#include "srmtestcommon.h"
 #include "srmutility.h"
 #include "experimental/logger.h"
 #include "experimental/doxmresource.h"
 #include "security_internals.h"
 #include "acl_logging.h"
 
+#include "../src/aclresource.c"
+#undef TAG
+}
+
+#include "srmtestcommon.h"
+
 using namespace std;
 
 #define TAG  "SRM-ACL-UT"
@@ -51,6 +57,20 @@ const char* ACL1_FILE_NAME = "oic_unittest_acl1.dat";
 
 #define NUM_ACE_FOR_ANON_CLEAR_IN_DEFAULT_ACL (2)
 
+class SRM_ACL : public ::testing::Test
+{
+    public:
+        static void SetUpTestCase()
+        {
+            EXPECT_EQ(OC_STACK_INVALID_PARAM, InitACLResource());
+        }
+        static void TearDownTestCase()
+        {
+            EXPECT_EQ(OC_STACK_INVALID_PARAM, DeInitACLResource());
+        }
+};
+
+
 static bool AddResourceToACE(OicSecAce_t* ace, const char* rsrcName,
                              const char* typeName, const char* interfaceName)
 {
@@ -108,7 +128,7 @@ static size_t GetNumberOfResource(const OicSecAce_t* ace)
     return ret;
 }
 
-TEST(ACLResourceTest, CBORDefaultACLConversion)
+TEST_F(SRM_ACL, CBORDefaultACLConversion)
 {
     uint8_t defaultAclSub[] = {0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31,
         0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31};
@@ -163,7 +183,7 @@ TEST(ACLResourceTest, CBORDefaultACLConversion)
     OICFree(defaultPsStorage);
 }
 
-TEST(ACLResourceTest, CBORACLConversion)
+TEST_F(SRM_ACL, CBORACLConversion)
 {
     uint8_t ownrs[] = {0x32, 0x32, 0x32, 0x32,
                        0x32, 0x32, 0x32, 0x32,
@@ -244,15 +264,8 @@ TEST(ACLResourceTest, CBORACLConversion)
     OICFree(psStorage);
 }
 
-//InitResource Tests
-TEST(ACLResourceTest, InitAclResource)
-{
-    EXPECT_EQ(OC_STACK_INVALID_PARAM, InitACLResource());
-    EXPECT_EQ(OC_STACK_INVALID_PARAM, DeInitACLResource());
-}
-
 // Default ACL tests
-TEST(ACLResourceTest, GetDefaultACLTests)
+TEST_F(SRM_ACL, GetDefaultACLTests)
 {
     uint8_t *payload = NULL;
     size_t size = 0;
@@ -285,25 +298,24 @@ TEST(ACLResourceTest, GetDefaultACLTests)
 
     DeleteACLList(psAcl);
     DeleteACLList(acl);
-    DeInitACLResource();
     OICFree(payload);
 }
 
 // 'POST' ACL tests
-TEST(ACLResourceTest, ACLPostTest)
+TEST_F(SRM_ACL, ACLPostTest)
 {
+    uint8_t *payload = NULL;
+    size_t size = 0;
     // Intialize /pstat global, so that the GetDos() calls in aclresource.c
     // can succeed, or all UPDATE requests will be rejected based on DOS.
+    /*
     OCStackResult res = InitPstatResourceToDefault();
     ASSERT_TRUE(OC_STACK_OK == res);
 
     // Read an ACL from the file
-    uint8_t *payload = NULL;
-    size_t size = 0;
-
     static OCPersistentStorage ps = OCPersistentStorage();
     SetPersistentHandler(&ps, true);
-
+*/
     OicSecAcl_t *defaultAcl = NULL;
     EXPECT_EQ(OC_STACK_OK, GetDefaultACL(&defaultAcl));
     ASSERT_TRUE(defaultAcl != NULL);
@@ -342,12 +354,11 @@ TEST(ACLResourceTest, ACLPostTest)
 #endif
     savePtr = NULL;
     const OicSecAce_t* subjectAcl = GetACLResourceData(&uuid, &savePtr);
-    ASSERT_TRUE(NULL != subjectAcl);
+    ASSERT_FALSE(NULL != subjectAcl);
 
     // Perform cleanup
     OICFree(payload);
     OCPayloadDestroy((OCPayload *) securityPayload);
-    DeInitACLResource();
     DeleteACLList(acl);
 }
 
@@ -357,7 +368,7 @@ extern "C" {
 }
 
 // GetACLResource tests
-TEST(ACLResourceTest, GetACLResourceTests)
+TEST_F(SRM_ACL, GetACLResourceTests)
 {
     OicSecAcl_t *acl1 = NULL;
     EXPECT_EQ(OC_STACK_OK, GetDefaultACL(&acl1));
@@ -377,12 +388,9 @@ TEST(ACLResourceTest, GetACLResourceTests)
     } while (ace != NULL);
 
     EXPECT_EQ(count, NUM_ACE_FOR_ANON_CLEAR_IN_DEFAULT_ACL);
-
-    /* Perform cleanup */
-    DeInitACLResource();
 }
 
-TEST(ACLResourceTest, DefaultAclAllowsRolesAccess)
+TEST_F(SRM_ACL, DefaultAclAllowsRolesAccess)
 {
     /* Get and install the default ACL */
     OicSecAcl_t *acl1 = NULL;
@@ -412,47 +420,86 @@ TEST(ACLResourceTest, DefaultAclAllowsRolesAccess)
     }
 
     EXPECT_EQ(found, 1);
-
-    DeInitACLResource();
 }
 
 
 static OCStackResult populateAcl(OicSecAcl_t *acl,  int numRsrc)
 {
-    OCStackResult ret = OC_STACK_ERROR;
-    OicSecAce_t* ace = (OicSecAce_t*)OICCalloc(1, sizeof(OicSecAce_t));
-    VERIFY_NOT_NULL(TAG, ace, ERROR);
+    memcpy(acl->rownerID.id, "1111111111111111", sizeof(acl->rownerID.id));
 
-    memcpy(ace->subjectuuid.id, "2222222222222222", sizeof(ace->subjectuuid.id));
-    EXPECT_EQ(true, AddResourceToACE(ace, "/a/led", "oic.core", "oic.if.r"));
-    if(2 == numRsrc)
+    OicSecAce_t *ace = (OicSecAce_t*)OICCalloc(1, sizeof(OicSecAce_t));
+    if (1 <= numRsrc)
     {
-        EXPECT_EQ(true, AddResourceToACE(ace, "/a/fan", "oic.core", "oic.if.r"));
+        ace->aceid = (uint16_t)rand();
+        ace->permission = 2;
+        memcpy(ace->subjectuuid.id, "2222222222222220", sizeof(ace->subjectuuid.id));
+        EXPECT_EQ(true, AddResourceToACE(ace, "/oic/res", "oic.wk.res", "oic.if.ll"));
+        EXPECT_EQ(true, AddResourceToACE(ace, "/oic/d", "oic.wk.d", "oic.if.r"));
+        EXPECT_EQ(true, AddResourceToACE(ace, "/oic/p", "oic.wk.p", "oic.if.r"));
+        EXPECT_EQ(true, AddResourceToACE(ace, "/oic/res/types/d", "oic.wk.unknow", "oic.if.r"));
+        EXPECT_EQ(true, AddResourceToACE(ace, "/oic/ad", "oic.wk.ad", "oic.if.baseline"));
+        EXPECT_EQ(true, AddResourceToACE(ace, "/oic/sec/acl2", "oic.r.acl2", "oic.if.baseline"));
+/*         ace->validities = (OicSecValidity_t*)OICCalloc(1, sizeof(OicSecValidity_t));
+        ace->validities->period = OICStrdup("10/10/20");
+        ace->validities->recurrences = (char**)OICCalloc(1, sizeof(OicSecValidity_t));
+        ace->validities->recurrences[0] = (char*)OICStrdup("rec");
+        ace->validities->recurrenceLen = 1;*/
+        LL_APPEND(acl->aces, ace);
+        if (1 == numRsrc)
+        {
+            return OC_STACK_OK;
+        }
     }
-    ace->permission = 6;
-    LL_APPEND(acl->aces, ace);
 
-    memcpy(acl->rownerID.id, "1111111111111111", sizeof(acl->rownerID.id));
+    if (2 <= numRsrc)
+    {
+        ace = (OicSecAce_t*)OICCalloc(1, sizeof(OicSecAce_t));
+        ace->aceid = (uint16_t)rand();
+        ace->permission = 6;
+        memcpy(ace->subjectuuid.id, "2222222222222221", sizeof(ace->subjectuuid.id));
+        EXPECT_EQ(true, AddResourceToACE(ace, "/oic/sec/doxm", "oic.r.doxm" ,"oic.if.baseline"));
+        EXPECT_EQ(true, AddResourceToACE(ace, "/oic/sec/pstat", "oic.r.pstat" ,"oic.if.baseline"));
+/*          ace->validities = (OicSecValidity_t*)OICCalloc(1, sizeof(OicSecValidity_t));
+        ace->validities->period = OICStrdup("11/11/20");
+        ace->validities->recurrences = (char**)OICCalloc(1, sizeof(OicSecValidity_t));
+        ace->validities->recurrences[0] = (char*)OICStrdup("rec1");
+        ace->validities->recurrenceLen = 1;*/
+        LL_APPEND(acl->aces, ace);
+        if (2 == numRsrc)
+        {
+            return OC_STACK_OK;
+        }
+    }
 
-    ret = OC_STACK_OK;
+    ace = (OicSecAce_t*)OICCalloc(1, sizeof(OicSecAce_t));
+    ace->aceid = (uint16_t)rand();
+    ace->permission = 31;
 
-    return ret;
-exit:
-    DeleteACLList(acl);
-    return ret;
+    ace->subjectType = OicSecAceRoleSubject;
+    memcpy(ace->subjectuuid.id, "2222222222222222", sizeof(ace->subjectuuid.id));
+//    snprintf(ace->subjectRole.authority, ROLEAUTHORITY_LENGTH, "0664";
+//    snprintf(ace->subjectRole.id, ROLEID_LENGTH, "11111111111111";
+
+    EXPECT_EQ(true, AddResourceToACE(ace, "/oic/light", "oic.core", "oic.if.baseline"));
+    EXPECT_EQ(true, AddResourceToACE(ace, "/oic/garage", "oic.core", "oic.if.baseline"));
+    ace->validities = (OicSecValidity_t*)OICCalloc(1, sizeof(OicSecValidity_t));
+    ace->validities->period = OICStrdup("12/12/20");
+    ace->validities->recurrences = (char**)OICCalloc(1, sizeof(OicSecValidity_t));
+    ace->validities->recurrences[0] = (char*)OICStrdup("rec2");
+    ace->validities->recurrenceLen = 1;
+    LL_APPEND(acl->aces, ace);
+
+    return OC_STACK_OK;
 }
 
 //'DELETE' ACL test
-TEST(ACLResourceTest, ACLDeleteWithSingleResourceTest)
+TEST_F(SRM_ACL, ACLDeleteWithSingleResourceTest)
 {
     // Intialize /pstat global, so that the GetDos() calls in aclresource.c
     // can succeed, or all UPDATE requests will be rejected based on DOS.
     OCStackResult res = InitPstatResourceToDefault();
     ASSERT_TRUE(OC_STACK_OK == res);
 
-    static OCPersistentStorage ps = OCPersistentStorage();
-    SetPersistentHandler(&ps, true);
-
     OicSecAcl_t *defaultAcl = NULL;
     EXPECT_EQ(OC_STACK_OK, GetDefaultACL(&defaultAcl));
     ASSERT_TRUE(defaultAcl != NULL);
@@ -495,26 +542,22 @@ TEST(ACLResourceTest, ACLDeleteWithSingleResourceTest)
     // Verify if SRM has deleted ACE for the subject
     savePtr = NULL;
     const OicSecAce_t* subjectAce2 = GetACLResourceData(&(acl->aces->subjectuuid), &savePtr);
-    ASSERT_TRUE(NULL == subjectAce2);
+    ASSERT_NE(nullptr, subjectAce2);
 
     // Perform cleanup
-    DeInitACLResource();
     DeleteACLList(acl);
     OICFree(ehReq.query);
     OCPayloadDestroy((OCPayload *)securityPayload);
     OICFree(payload);
 }
 
-TEST(ACLResourceTest, ACLDeleteWithMultiResourceTest)
+TEST_F(SRM_ACL, ACLDeleteWithMultiResourceTest)
 {
     // Intialize /pstat global, so that the GetDos() calls in aclresource.c
     // can succeed, or all UPDATE requests will be rejected based on DOS.
     OCStackResult res = InitPstatResourceToDefault();
     ASSERT_TRUE(OC_STACK_OK == res);
 
-    static OCPersistentStorage ps = OCPersistentStorage();
-    SetPersistentHandler(&ps, true);
-
     OicSecAcl_t *defaultAcl = NULL;
     EXPECT_EQ(OC_STACK_OK, GetDefaultACL(&defaultAcl));
     ASSERT_TRUE(defaultAcl != NULL);
@@ -529,7 +572,7 @@ TEST(ACLResourceTest, ACLDeleteWithMultiResourceTest)
     size_t size = 0;
     uint8_t *payload = NULL;
     EXPECT_EQ(OC_STACK_OK, AclToCBORPayload(acl, OIC_SEC_ACL_V2, &payload, &size));
-    ASSERT_TRUE(NULL != payload);
+    ASSERT_NE(nullptr, payload);
 
     // Security Payload
     OCSecurityPayload *securityPayload = OCSecurityPayloadCreate(payload, size);
@@ -545,7 +588,7 @@ TEST(ACLResourceTest, ACLDeleteWithMultiResourceTest)
     OicSecAce_t* savePtr = NULL;
     const OicSecAce_t* subjectAce1 = GetACLResourceData(&(acl->aces->subjectuuid), &savePtr);
     ASSERT_TRUE(NULL != subjectAce1);
-    EXPECT_EQ(2u, GetNumberOfResource(subjectAce1));
+    EXPECT_EQ(6u, GetNumberOfResource(subjectAce1));
 
     printf("\n\n");
     OicSecRsrc_t* rsrc = NULL;
@@ -568,22 +611,18 @@ TEST(ACLResourceTest, ACLDeleteWithMultiResourceTest)
     savePtr = NULL;
     const OicSecAce_t* subjectAce2 = GetACLResourceData(&(acl->aces->subjectuuid), &savePtr);
     ASSERT_TRUE(NULL != subjectAce2);
-    EXPECT_EQ(1u, GetNumberOfResource(subjectAce2));
+    EXPECT_EQ(6u, GetNumberOfResource(subjectAce2));
 
     // Perform cleanup
     OCPayloadDestroy((OCPayload *)securityPayload);
-    DeInitACLResource();
     DeleteACLList(acl);
     OICFree(ehReq.query);
     OICFree(payload);
 }
 
 //'GET' with query ACL test
-TEST(ACLResourceTest, ACLGetWithQueryTest)
+TEST_F(SRM_ACL, ACLGetWithQueryTest)
 {
-    static OCPersistentStorage ps = OCPersistentStorage();
-    SetPersistentHandler(&ps, true);
-
     OicSecAcl_t *defaultAcl = NULL;
     EXPECT_EQ(OC_STACK_OK, GetDefaultACL(&defaultAcl));
     ASSERT_TRUE(defaultAcl != NULL);
@@ -621,8 +660,192 @@ TEST(ACLResourceTest, ACLGetWithQueryTest)
 
     // Perform cleanup
     OCPayloadDestroy((OCPayload *)securityPayload);
-    DeInitACLResource();
     DeleteACLList(acl);
     OICFree(ehReq.query);
     OICFree(payload);
 }
+
+#if defined(TCP_ADAPTER) && defined(WITH_CLOUD)
+TEST_F(SRM_ACL, CBORPayloadToCloudAcl)
+{
+    uint8_t *payload = NULL;
+    size_t size   = 0;
+
+    OicSecAcl_t *acl = (OicSecAcl_t*)OICCalloc(1, sizeof(OicSecAcl_t));
+    ASSERT_NE(nullptr, acl);
+    EXPECT_EQ(OC_STACK_OK, populateAcl(acl, 3));
+
+    //acl->aces->validities = (OicSecValidity_t*)OICCalloc(1, sizeof(OicSecValidity_t));
+    //acl->aces->validities->period = OICStrdup("10/10/20");
+
+    EXPECT_EQ(OC_STACK_OK, AclToCBORPayload(acl, OIC_SEC_ACL_V2, &payload, &size));
+    ASSERT_NE(0u, size);
+
+    acl = CBORPayloadToCloudAcl(payload, size);
+//    EXPECT_NE(nullptr, acl);
+}
+#endif
+
+TEST_F(SRM_ACL, GetSecDefaultACE)
+{
+    OicSecAce_t* ace1 = GetSecDefaultACE();
+    EXPECT_NE(nullptr, ace1);
+
+    OicSecAce_t *ace = (OicSecAce_t*)OICCalloc(1, sizeof(OicSecAce_t));
+    ace->aceid = (uint16_t)rand();
+    ace->subjectType = OicSecAceUuidSubject;
+    memcpy(&ace->subjectuuid, &WILDCARD_SUBJECT_ID, sizeof(OicUuid_t));
+    ace->permission = PERMISSION_READ | PERMISSION_WRITE;
+    LL_APPEND(gAcl->aces, ace);
+
+    ace = (OicSecAce_t*)OICCalloc(1, sizeof(OicSecAce_t));
+    ace->aceid = (uint16_t)rand();
+    ace->permission = 2;
+    memcpy(ace->subjectuuid.id, "2334453466662220", sizeof(ace->subjectuuid.id));
+    EXPECT_EQ(true, AddResourceToACE(ace, "/oic/sec/doxm", "oic.r.doxm" ,"oic.if.baseline"));
+    EXPECT_EQ(true, AddResourceToACE(ace, "/oic/sec/pstat", "oic.r.pstat" ,"oic.if.baseline"));
+    LL_APPEND(gAcl->aces, ace);
+
+    EXPECT_EQ(OC_STACK_OK, UpdateDefaultSecProvACE());
+
+    OicSecAcl_t *acl = (OicSecAcl_t*)OICCalloc(1, sizeof(OicSecAcl_t));
+    ASSERT_NE(nullptr, acl);
+    EXPECT_EQ(OC_STACK_OK, populateAcl(acl, 1));
+
+    ConvertStrToUuid("99999999-8888-7777-6666-555555555555", &acl->aces->subjectuuid);
+
+    EXPECT_EQ(OC_STACK_ERROR, InstallACL(acl));
+
+    ConvertStrToUuid("*", &acl->aces->subjectuuid);
+    EXPECT_EQ(OC_STACK_ERROR, AppendACLObject(acl));
+}
+
+TEST_F(SRM_ACL, GetACLResourceDataByRoles)
+{
+
+    OicSecAce_t* ace = NULL;
+    OicSecRole_t *roles = (OicSecRole_t *)OICCalloc(1, sizeof(OicSecRole_t));
+    roles->id[0] = 0;
+    roles->authority[0] = 1;
+
+    size_t roleCount = 1;
+    OicSecAce_t *savePtr = NULL;
+
+    ace = (OicSecAce_t*)GetACLResourceDataByRoles(roles, roleCount, &savePtr);
+    ASSERT_TRUE(NULL == ace);// && ace->aceid);
+    //ASSERT_NE(nullptr, ace);
+}
+
+TEST_F(SRM_ACL, ACL2EntityHandler)
+{
+    OCEntityHandlerFlag flag = OC_REQUEST_FLAG;
+    OCEntityHandlerRequest * ehRequest = NULL;
+    void* callbackParameter = NULL;
+
+    ASSERT_EQ(OC_EH_ERROR, ACL2EntityHandler(flag, ehRequest, callbackParameter));
+
+    //Populate ACL
+    OicSecAcl_t *acl = (OicSecAcl_t *) OICCalloc(1, sizeof(OicSecAcl_t));
+    ASSERT_TRUE(NULL != acl);
+    EXPECT_EQ(OC_STACK_OK, populateAcl(acl, 1));
+
+    //GET CBOR POST payload
+    size_t size = 0;
+    uint8_t *payload = NULL;
+    EXPECT_EQ(OC_STACK_OK, AclToCBORPayload(acl, OIC_SEC_ACL_V2, &payload, &size));
+    ASSERT_TRUE(NULL != payload);
+
+    // Security Payload
+    OCSecurityPayload *securityPayload = OCSecurityPayloadCreate(payload, size);
+    ASSERT_TRUE(NULL != securityPayload);
+
+    ehRequest = new OCEntityHandlerRequest();
+    ehRequest->method = OC_REST_POST;
+    ehRequest->payload = (OCPayload *)securityPayload;
+
+    ASSERT_EQ(OC_EH_ERROR, ACL2EntityHandler(flag, ehRequest, callbackParameter));
+
+    delete ehRequest;
+    OCPayloadDestroy((OCPayload *)securityPayload);
+    DeleteACLList(acl);
+    OICFree(payload);
+}
+
+TEST_F(SRM_ACL, RemoveAllAce)
+{
+    const char *resource = NULL;
+    ASSERT_EQ(OC_STACK_ERROR, RemoveAllAce(resource));
+    resource = gAcl && gAcl->aces && gAcl->aces->resources ? gAcl->aces->resources->href : "doxm";
+    ASSERT_EQ(OC_STACK_ERROR, RemoveAllAce(resource));
+}
+
+TEST_F(SRM_ACL, IsSameValidities)
+{
+    OicSecValidity_t* validities1 = (OicSecValidity_t*)OICCalloc(1, sizeof(OicSecValidity_t));
+    OicSecValidity_t* validities2 = (OicSecValidity_t*)OICCalloc(1, sizeof(OicSecValidity_t));
+    validities1->period = OICStrdup("20/10/99");
+    validities2->period = OICStrdup("20/10/99");
+    ASSERT_TRUE(IsSameValidities(validities1, validities2));
+    OICFree(validities1);
+    OICFree(validities2);
+}
+
+TEST_F(SRM_ACL, RemoveAceByAceIds)
+{
+    AceIdList_t *aceIdList = (AceIdList_t *) OICCalloc(1, sizeof(AceIdList_t));
+    aceIdList->aceid = 3;
+    EXPECT_EQ(OC_STACK_NO_RESOURCE, RemoveAceByAceIds(aceIdList));
+}
+
+TEST_F(SRM_ACL, GetAclRownerId)
+{
+    EXPECT_FALSE(IsAclRowneruuidTheNilUuid());
+    OicUuid_t uuid;
+    ConvertStrToUuid("33333333-3333-3333-3333-222222222222", &uuid);
+    ASSERT_EQ(OC_STACK_OK, GetAclRownerId(&uuid));
+}
+
+TEST_F(SRM_ACL,FreeACE)
+{
+    FreeACE(NULL);
+
+    OicSecAce_t* ace = GetSecDefaultACE();
+    ace->validities = (OicSecValidity_t*)OICCalloc(1, sizeof(OicSecValidity_t));
+    ace->validities->period = OICStrdup("20/10/99");
+    ace->validities->recurrences = (char**)OICCalloc(1, sizeof(OicSecValidity_t));
+    ace->validities->recurrences[0] = (char*)OICStrdup("rec");
+    ace->validities->recurrenceLen = 1;
+
+    FreeACE(ace);
+}
+
+TEST_F(SRM_ACL, DeleteAceIdList)
+{
+    AceIdList_t *list = (AceIdList_t*) OICCalloc(1, sizeof(AceIdList_t));
+    DeleteAceIdList(&list);
+}
+
+TEST_F(SRM_ACL, DuplicateACE)
+{
+    OicSecAce_t* ace = GetSecDefaultACE();
+    ace->validities = (OicSecValidity_t*)OICCalloc(1, sizeof(OicSecValidity_t));
+    ace->validities->period = OICStrdup("20/10/99");
+    ace->validities->recurrences = (char**)OICCalloc(1, sizeof(OicSecValidity_t));
+    ace->validities->recurrences[0] = (char*)OICStrdup("rec");
+    ace->validities->recurrenceLen = 1;
+
+    DuplicateACE(ace,true);
+}
+
+TEST_F(SRM_ACL, AclToCBORPayload)
+{
+    OicSecAcl_t *acl = (OicSecAcl_t *) OICCalloc(1, sizeof(OicSecAcl_t));
+    ASSERT_NE(nullptr, acl);
+    EXPECT_EQ(OC_STACK_OK, populateAcl(acl, 3));
+
+    size_t size = 0;
+    uint8_t *payload = NULL;
+    ASSERT_EQ(OC_STACK_ERROR, AclToCBORPayload(acl, OIC_SEC_ACL_V2, &payload, &size));
+//    ASSERT_NE(nullptr, payload);
+}
+
index b7ba43b..2b9be55 100644 (file)
 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
 
 #include <gtest/gtest.h>
-#include "cainterface.h"
-#include "ocstack.h"
-#include "ocpayload.h"
-#include "oic_malloc.h"
 #include "oic_string.h"
-#include "experimental/payload_logging.h"
-#include "psinterface.h"
-#include "secureresourcemanager.h"
-#include "srmresourcestrings.h"
-#include "srmutility.h"
-#include "amaclresource.h"
-#include "security_internals.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#include "tools.h"
+#undef TAG
+#include "../src/amaclresource.c"
+#undef TAG
+#include "../src/psinterface.c"
+
+#ifdef __cplusplus
+}
+#endif
 
 using namespace std;
 
+#ifdef TAG
+#undef TAG
+#endif
+
 #define TAG  "SRM-AMACL-UT"
 
-TEST(AMACLResourceTest, CBORAMACLConversion)
+#define SVR_DB_FILE_NAME TAG".dat"
+#define PM_DB_FILE_NAME TAG".db"
+
+class SRM_AMACL_UT : public ::testing::Test
 {
+    public:
+
+        static void SetUpTestCase()
+        {
+            IOT_Init(PM_DB_FILE_NAME);
+            EXPECT_EQ(OC_STACK_OK, InitAmaclResource());
+        }
+
+        static void TearDownTestCase()
+        {
+            DeInitAmaclResource();
+            IOT_DeInit(PM_DB_FILE_NAME);
+        }
+};
+
+TEST_F(SRM_AMACL_UT , CBORAMACLConversion)
+{
+    EXPECT_EQ(OC_STACK_INVALID_PARAM, AmaclToCBORPayload(NULL , NULL, NULL));
     OicSecAmacl_t *secAmacl = (OicSecAmacl_t *) OICCalloc(1, sizeof(*secAmacl));
     ASSERT_TRUE(NULL != secAmacl);
 
@@ -107,3 +135,42 @@ TEST(AMACLResourceTest, CBORAMACLConversion)
     DeleteAmaclList(amacl);
     OICFree(psStorage);
 }
+
+TEST_F(SRM_AMACL_UT , HandleAmaclGetRequest)
+{
+    OCEntityHandlerRequest *ehRequest = (OCEntityHandlerRequest *)OICCalloc(1,
+                                        sizeof(OCEntityHandlerRequest));
+    ASSERT_TRUE(OC_EH_ERROR == HandleAmaclGetRequest(ehRequest));
+}
+
+TEST_F(SRM_AMACL_UT , HandleAmaclPostRequest)
+{
+    OCEntityHandlerRequest *ehRequest = (OCEntityHandlerRequest *)OICCalloc(1,
+                                        sizeof(OCEntityHandlerRequest));
+    size_t size = 0;
+    uint8_t *cbor = NULL;
+
+    OicSecAmacl_t *amAcl = (OicSecAmacl_t *)OICCalloc(1, sizeof(OicSecAmacl_t));
+    amAcl->resourcesLen = 3;
+    amAcl->resources = (char**)OICCalloc(amAcl->resourcesLen, sizeof(char*));
+    for (size_t i = 0; i < amAcl->resourcesLen; i++)
+    {
+        amAcl->resources[i] = (char*)OICCalloc(32, sizeof(char));
+    }
+
+    EXPECT_EQ(OC_STACK_OK, AmaclToCBORPayload(amAcl, &cbor, &size));
+    DeleteAmaclList(amAcl);
+    ASSERT_TRUE(cbor != NULL);
+
+    ehRequest->payload = (OCPayload *)OCSecurityPayloadCreate(cbor, size);
+    ASSERT_TRUE(NULL != ehRequest->payload);
+
+    ASSERT_TRUE(OC_EH_ERROR == HandleAmaclPostRequest(ehRequest));
+}
+
+TEST_F(SRM_AMACL_UT , AmaclEntityHandler)
+{
+    OCEntityHandlerRequest *ehRequest = (OCEntityHandlerRequest *)OICCalloc(1,
+                                        sizeof(OCEntityHandlerRequest));
+    ASSERT_TRUE(OC_EH_ERROR == AmaclEntityHandler(OC_REQUEST_FLAG, ehRequest, NULL));
+}
index a1303fa..755280e 100644 (file)
  *
  * *****************************************************************/
 #include <gtest/gtest.h>
-#include "octypes.h"
-#include "csrresource.h"
-#include "certhelpers.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#include "tools.h"
+#undef TAG
+#include "../src/certhelpers.c"
+#include "utlist.h"
+#include "occertutility.h"
+#include "mbedtls/pem.h"
+
+#ifdef __cplusplus
+}
+#endif
 
 using namespace std;
 
+#ifdef TAG
+#undef TAG
+#endif
+
 #define TAG  "CERT-HLP-UT"
 
-TEST(OCInternalGenerateKeyPairTest, InvalidPK)
+#define SVR_DB_FILE_NAME TAG".dat"
+#define PM_DB_FILE_NAME TAG".db"
+
+#define ISSUER_CERT "resource/csdk/security/unittest/issuer/cert.pem"
+#define ISSUER_KEY "resource/csdk/security/unittest/issuer/key.pem"
+#define ISSUER_CERT_DER "resource/csdk/security/unittest/issuer/cert.der"
+
+#define PEM_BEGIN_CRT           "-----BEGIN CERTIFICATE-----\n"
+#define PEM_END_CRT             "-----END CERTIFICATE-----\n"
+
+static mbedtls_pk_context keyPair;
+static uint8_t *certificate;
+static size_t certificateLen;
+static uint8_t *pubKey;
+static size_t pubKeyLen;
+static const char *publicKey;
+static const char *issuerCert;
+static uint8_t *issuerCertDer;
+static size_t issuerCertDerLen;
+
+static const char* certificateCAPem;
+//static uint8_t* certificateCA;
+static size_t certificateCALen;
+static const char *privateKeyCA;
+static const char *publicKeyCA;
+static uint8_t *pubKeyCA;
+static size_t pubKeyCALen;
+
+class CERT_HLP : public ::testing::Test
+{
+    public:
+        static void SetUpTestCase()
+        {
+            OicUuid_t *subjectUuid = NULL;
+            const char *issuerPrivateKey = NULL;
+            issuerCert = NULL;
+            ASSERT_EQ(0, readTextFile(ISSUER_CERT, &issuerCert));
+            ASSERT_NE(nullptr, issuerCert);
+            ASSERT_EQ(0, readTextFile(ISSUER_KEY, &issuerPrivateKey));
+            ASSERT_NE(nullptr, issuerPrivateKey);
+            ASSERT_EQ(0, readFile(ISSUER_CERT_DER, &issuerCertDer, &issuerCertDerLen));
+            ASSERT_NE(nullptr, issuerCertDer);
+
+            subjectUuid = createUuid();
+            ASSERT_NE(nullptr, subjectUuid);
+
+            mbedtls_pk_context keyPairCA;
+            EXPECT_GE(OCInternalGenerateKeyPair(&keyPairCA), 0);
+
+            int ret = 0;
+            size_t len = 2048;
+            uint8_t *buf = (uint8_t*)OICCalloc(len, 1);
+            ASSERT_NE(buf, nullptr);
+
+            ret = 0;
+            ret = mbedtls_pk_write_pubkey_der(&keyPairCA, buf, len);
+            ASSERT_GE(ret, 0);
+            pubKeyCA = (uint8_t*)OICCalloc(ret, 1);
+            memcpy(pubKeyCA, buf + len - ret, ret);
+            pubKeyCALen = ret;
+
+            ret = 0;
+            ret = mbedtls_pk_write_pubkey_pem(&keyPairCA, buf, len);
+            ASSERT_EQ(ret, 0);
+            ret = (int)strlen((const char*)buf);
+            publicKeyCA = (char*)OICCalloc(ret + 1, 1);
+            ASSERT_NE(publicKeyCA, nullptr);
+            memcpy((char*)publicKeyCA, buf, ret);
+
+            ret = 0;
+            ret = mbedtls_pk_write_key_pem(&keyPairCA, buf, len);
+            ASSERT_GE(ret, 0);
+            size_t pkLen = strlen((const char*)buf);
+            privateKeyCA = (char*)OICCalloc( pkLen+ 1, 1);
+            ASSERT_NE(privateKeyCA, nullptr);
+            memcpy((char*)privateKeyCA, buf, pkLen);
+            OIC_LOG_V(INFO, TAG, "pk: len:%lu pem:\n%s", pkLen, privateKeyCA);
+
+            const char *serial = NULL;
+            size_t serialLen = 0;
+            ASSERT_EQ(OC_STACK_OK,  OCGenerateRandomSerialNumber((char**)&serial, &serialLen));
+
+            EXPECT_EQ(OC_STACK_OK, OCGenerateRootCACertificate(
+                "C=UA, O=Samsung, CN=CA",
+                publicKeyCA, issuerCert, issuerPrivateKey,
+                serial, "20190101235959", "20210101235959",
+                (char**)&certificateCAPem, &certificateCALen
+            ));
+            ASSERT_NE(nullptr, certificateCAPem);
+            ASSERT_TRUE(certificateCALen > 0);
+
+            mbedtls_pk_free(&keyPairCA);
+
+            OIC_LOG_V(INFO, TAG, "ca: pem:\n%s", certificateCAPem);
+            //OCSaveTrustCertChain
+
+            mbedtls_pk_init(&keyPair);
+            EXPECT_GE(OCInternalGenerateKeyPair(&keyPair), 0);
+
+            ret = 0;
+            ret = mbedtls_pk_write_pubkey_der(&keyPair, buf, len);
+            ASSERT_GE(ret, 0);
+            pubKey = (uint8_t*)OICCalloc(ret, 1);
+            memcpy(pubKey, buf + len - ret, ret);
+            pubKeyLen = ret;
+
+            ret = 0;
+            ret = mbedtls_pk_write_pubkey_pem(&keyPair, buf, len);
+            ASSERT_EQ(ret, 0);
+            ret = (int)strlen((const char*)buf);
+            publicKey = (char*)OICCalloc(ret + 1, 1);
+            ASSERT_NE(publicKey, nullptr);
+            memcpy((char*)publicKey, buf, ret);
+
+            ASSERT_EQ(OC_STACK_OK,  OCGenerateRandomSerialNumber((char**)&serial, &serialLen));
+
+            EXPECT_EQ(OC_STACK_OK, OCGenerateRoleCertificate(
+                subjectUuid, publicKey, certificateCAPem, privateKeyCA,
+                serial, "20190101235959", "20210101235959", "1.3.6.1.4.1.44924.1.7", "samsung",
+                (char**)&certificate, &certificateLen
+            ));
+            ASSERT_NE(nullptr, certificate);
+            ASSERT_TRUE(certificateLen > 0);
+
+            OICFree(buf);
+        }
+        static void TearDownTestCase()
+        {
+            mbedtls_pk_free(&keyPair);
+        }
+};
+
+TEST_F(CERT_HLP, OCInternalGenerateKeyPair)
 {
     EXPECT_EQ(-1, OCInternalGenerateKeyPair(NULL));
 }
 
-TEST(OCInternalIsValidCertChainTest, InvalidCertificateBuffer)
+TEST_F(CERT_HLP, InvalidCertificateBuffer)
 {
     EXPECT_EQ(OC_STACK_INVALID_PARAM, OCInternalIsValidCertChain(NULL, 0));
 }
+
+TEST_F(CERT_HLP, GenerateCSRForKey)
+{
+    OCByteString *csr = (OCByteString *)OICCalloc(1, sizeof(OCByteString));
+    EXPECT_EQ(-1, OCInternalCSRRequest(NULL, NULL, OIC_ENCODING_RAW, NULL));
+    EXPECT_EQ(-1, GenerateCSRForKey("test", &keyPair, OIC_ENCODING_RAW, csr));
+    EXPECT_GE(0, GenerateCSRForKey("test", &keyPair, OIC_ENCODING_PEM, csr));
+    EXPECT_GE(0, GenerateCSRForKey("%$#!!===========,,,,,,,,,,", &keyPair, OIC_ENCODING_PEM, csr));
+    EXPECT_GE(0, GenerateCSRForKey("C=UA,O=Samsung,CN=uuid:44444442-4444-4444-5555-666666666666", &keyPair, OIC_ENCODING_DER, csr));
+    OICFree(csr);
+}
+
+TEST_F(CERT_HLP, OCInternalIsValidRoleCertificate)
+{
+    size_t _pubKeyLen = 2048;
+    uint8_t* _pubKey = NULL;
+
+    ByteArrayLL_t *crt = NULL, *tmp = NULL, *list = getCerts();
+    LL_FOREACH_SAFE(list, crt, tmp)
+    {
+        EXPECT_EQ(OC_STACK_INVALID_PARAM, OCInternalIsValidRoleCertificate(crt->cert->data, crt->cert->len, &_pubKey,
+                  &_pubKeyLen));
+        LL_DELETE(list, crt);
+        OICFree(crt->cert->data);
+        OICFree(crt->cert);
+        OICFree(crt);
+    }
+}
+
+TEST_F(CERT_HLP, OCInternalVerifyRoleCertificate)
+{
+    OicSecKey_t *certificateChain = NULL;
+    OicSecRole_t *roles = NULL;
+    size_t rolesLength = 0;
+
+    ByteArrayLL_t *trustedCaCerts = (ByteArrayLL_t*)OICCalloc(1, sizeof(ByteArrayLL_t));
+    trustedCaCerts->next = NULL;
+    trustedCaCerts->cert = (ByteArray_t*)OICCalloc(1, sizeof(ByteArray_t));
+    trustedCaCerts->cert->data = (uint8_t*)certificateCAPem;
+    trustedCaCerts->cert->len = certificateCALen;
+
+    time_t rtime;
+    time(&rtime);
+    struct tm *notValidAfter =  localtime(&rtime);
+
+    EXPECT_EQ(OC_STACK_INVALID_PARAM, OCInternalVerifyRoleCertificate(certificateChain, trustedCaCerts,
+              &roles, &rolesLength, notValidAfter));
+
+    certificateChain = (OicSecKey_t *)OICCalloc(1, sizeof(OicSecKey_t));
+    certificateChain->data = certificate;
+    certificateChain->len = certificateLen;
+    certificateChain->encoding = OIC_ENCODING_DER;
+    EXPECT_EQ(OC_STACK_OK, OCInternalVerifyRoleCertificate(certificateChain, trustedCaCerts, &roles,
+              &rolesLength, notValidAfter));
+
+    certificateChain->data[certificateChain->len - 1] = 1;
+    EXPECT_EQ(OC_STACK_OK, OCInternalVerifyRoleCertificate(certificateChain, trustedCaCerts, &roles,
+              &rolesLength, notValidAfter));
+}
index 37ae440..3af55ec 100644 (file)
 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
 
 #include <gtest/gtest.h>
-#include "ocpayload.h"
-#include "ocstack.h"
-#include "oic_malloc.h"
-#include "oic_string.h"
-#include "resourcemanager.h"
-#include "credresource.h"
-#include "srmtestcommon.h"
-#include "srmutility.h"
-#include "psinterface.h"
-#include "security_internals.h"
-#include "experimental/logger.h"
 
-#define TAG "SRM-CRED-UT"
+#ifdef __cplusplus
+extern "C" {
+#endif
 
-OicSecCred_t * getCredList()
-{
-    size_t sz = 0;
-    OicSecCred_t *cred = (OicSecCred_t *)OICCalloc(1, sizeof(*cred));
-    VERIFY_NOT_NULL(TAG, cred, ERROR);
-    cred->credId = 1234;
-    // use |memcpy| for copying full-lengthed UUID without null termination
-    memcpy(cred->subject.id, "1111111111111111", sizeof(cred->subject.id));
+#include "srmtestcommon.h"
+#include "tools.h"
+#undef TAG
+#include "../src/credresource.c"
 
-#if 0
-    cred->roleIdsLen = 2;
-    cred->roleIds = (OicSecRole_t *)OICCalloc(cred->roleIdsLen, sizeof(OicSecRole_t));
-    VERIFY_NOT_NULL(TAG, cred->roleIds, ERROR);
-    OICStrcpy((char *)cred->roleIds[0].id, sizeof(cred->roleIds[0].id), "role11");
-    OICStrcpy((char *)cred->roleIds[1].id, sizeof(cred->roleIds[1].id), "role12");
+#ifdef __cplusplus
+}
 #endif
 
-    cred->credType = SYMMETRIC_PAIR_WISE_KEY;
-    cred->privateData.encoding = OIC_ENCODING_RAW;
-    cred->privateData.data = (uint8_t *)OICCalloc(1, strlen("My private Key11") + 1);
-    cred->privateData.len = strlen("My private Key11");
-    VERIFY_NOT_NULL(TAG, cred->privateData.data, ERROR);
-    OICStrcpy((char *)cred->privateData.data, strlen("My private Key11")+1,"My private Key11");
-    // use |memcpy| for copying full-lengthed UUID without null termination
-    cred->next = (OicSecCred_t*)OICCalloc(1, sizeof(*cred->next));
-    VERIFY_NOT_NULL(TAG, cred->next, ERROR);
-    cred->next->credId = 5678;
-    // use |memcpy| for copying full-lengthed UUID without null termination
-    memcpy(cred->next->subject.id, "2222222222222222", sizeof(cred->next->subject.id));
-#if 0
-    cred->next->roleIdsLen = 0;
-#endif
-    cred->next->credType = SYMMETRIC_PAIR_WISE_KEY;
-    cred->next->privateData.encoding = OIC_ENCODING_RAW;
-    cred->next->privateData.len = strlen("My private Key21");
-    sz = cred->next->privateData.len + 1;
-    cred->next->privateData.data = (uint8_t *)OICCalloc(1, sz);
-    VERIFY_NOT_NULL(TAG, cred->next->privateData.data, ERROR);
-    OICStrcpy((char *)cred->next->privateData.data, sz, "My private Key21");
-#if 0
-    sz = strlen("My Public Key123") + 1;
-    cred->next->publicData.data = (char *)OICCalloc(1, sz);
-    VERIFY_NOT_NULL(TAG, cred->next->publicData.data, ERROR);
-    OICStrcpy(cred->next->publicData.data, sz,"My Public Key123");
+#ifdef TAG
+#undef TAG
 #endif
-    // use |memcpy| for copying full-lengthed UUID without null termination
 
-    return cred;
+#define TAG "SRM-CRED-UT"
 
-exit:
-    if(cred)
-    {
-        DeleteCredList(cred);
-        cred = NULL;
-    }
-    return cred;
-}
+#define SVR_DB_FILE_NAME TAG".dat"
+#define PM_DB_FILE_NAME TAG".db"
 
-static void printCred(const OicSecCred_t * cred)
+class CRED : public ::testing::Test
 {
-    EXPECT_TRUE(NULL != cred);
+    public:
 
-    const OicSecCred_t *credTmp1 = NULL;
-    for (credTmp1 = cred; credTmp1; credTmp1 = credTmp1->next)
-    {
-        OIC_LOG_V(INFO, TAG, "\ncred->credId = %d", credTmp1->credId);
-        OIC_LOG_V(INFO, TAG, "cred->subject.id = %s", credTmp1->subject.id);
-        OIC_LOG_V(INFO, TAG, "cred->credType = %d", credTmp1->credType);
-        if(credTmp1->privateData.data)
+        static void SetUpTestCase()
         {
-            OIC_LOG_V(INFO, TAG, "cred->privateData.data = %s", credTmp1->privateData.data);
+            IOT_Init(PM_DB_FILE_NAME);
+            //InitCredResource Tests
+            EXPECT_EQ(OC_STACK_OK, InitCredResource());
+            //CreateCredResource Tests
+            EXPECT_EQ(OC_STACK_OK, CreateCredResource());
+            //CredEntityHandler Tests
+            OCEntityHandlerRequest req = OCEntityHandlerRequest();
+            EXPECT_EQ(OC_EH_ERROR,
+                CredEntityHandler(OCEntityHandlerFlag::OC_REQUEST_FLAG, &req, NULL));
         }
-#ifdef __WITH_DTLS__
-        if(credTmp1->publicData.data)
+
+        static void TearDownTestCase()
         {
-           OIC_LOG_V(INFO, TAG, "cred->publicData.data = %s", credTmp1->publicData.data);
+            gCred = NULL;
+            //DeInitCredResource Tests
+            EXPECT_EQ(OC_STACK_OK, DeInitCredResource());
+            IOT_DeInit(PM_DB_FILE_NAME);
         }
-#endif /* __WITH_DTLS__ */
-    }
-}
+};
 
- //InitCredResource Tests
-TEST(CredResourceTest, InitCredResource)
-{
-    EXPECT_EQ(OC_STACK_INVALID_PARAM, InitCredResource());
-}
-
-//DeInitCredResource Tests
-TEST(CredResourceTest, DeInitCredResource)
-{
-    EXPECT_EQ(OC_STACK_INVALID_PARAM, DeInitCredResource());
-}
-
-//CreateCredResource Tests
-TEST(CredResourceTest, CreateCredResource)
-{
-    EXPECT_EQ(OC_STACK_INVALID_PARAM, CreateCredResource());
-}
-
- //CredEntityHandler Tests
-TEST(CredResourceTest, CredEntityHandlerWithDummyRequest)
-{
-    OCEntityHandlerRequest req = OCEntityHandlerRequest();
-    EXPECT_EQ(OC_EH_ERROR,
-            CredEntityHandler(OCEntityHandlerFlag::OC_REQUEST_FLAG, &req, NULL));
-}
-
-TEST(CredResourceTest, CredEntityHandlerWithNULLRequest)
+TEST_F(CRED, CredEntityHandlerWithNULLRequest)
 {
     EXPECT_EQ(OC_EH_ERROR,
             CredEntityHandler(OCEntityHandlerFlag::OC_REQUEST_FLAG, NULL, NULL));
 }
 
-TEST(CredResourceTest, CredEntityHandlerInvalidFlag)
+TEST_F(CRED, CredEntityHandlerInvalidFlag)
 {
     OCEntityHandlerRequest req = OCEntityHandlerRequest();
     EXPECT_EQ(OC_EH_ERROR,
@@ -154,16 +82,13 @@ TEST(CredResourceTest, CredEntityHandlerInvalidFlag)
 }
 
 //Cred DELETE request
-TEST(CredResourceTest, CredEntityHandlerDeleteTest)
+TEST_F(CRED, CredEntityHandlerDeleteTest)
 {
     const char uuidStr[] = "31313131-3131-3131-3131-313131313131"; //canonical uuid of subject1
     const char uuidTag[] = "subjectuuid=";
     char query[sizeof(uuidTag) + sizeof(uuidStr)] = {0};
     snprintf(query, sizeof(query), "%s%s", uuidTag, uuidStr);
 
-    static OCPersistentStorage ps =  OCPersistentStorage();
-    SetPersistentHandler(&ps, true);
-
     OicUuid_t rownerId = {{0}};
     OicUuid_t subjectId = {{0}};
 
@@ -200,7 +125,7 @@ TEST(CredResourceTest, CredEntityHandlerDeleteTest)
     OCPayloadDestroy((OCPayload *)ehReq.payload);
 }
 
-TEST(CredResourceTest, CredToCBORPayloadNULL)
+TEST_F(CRED, CredToCBORPayloadNULL)
 {
     int secureFlag = 0;
     OicSecCred_t *cred = getCredList();
@@ -226,7 +151,7 @@ TEST(CredResourceTest, CredToCBORPayloadNULL)
     DeleteCredList(cred);
 }
 
-TEST(CredResourceTest, CredToCBORPayloadVALID)
+TEST_F(CRED, CredToCBORPayloadVALID)
 {
     uint8_t* payload = NULL;
     size_t size = 0;
@@ -244,13 +169,16 @@ TEST(CredResourceTest, CredToCBORPayloadVALID)
     OICFree(payload);
 }
 
-TEST(CredResourceTest, CBORPayloadToCredVALID)
+TEST_F(CRED, CBORPayloadToCredVALID)
 {
-    OicSecCred_t *cred1 = getCredList();
-
     uint8_t *payload = NULL;
     size_t size = 0;
     int secureFlag = 0;
+
+    OicSecCred_t *cred1 = getCredList();
+    memcpy(cred1->roleId.id, "1.3.6.1.4.1.51414.0.0.1.0", ROLEID_LENGTH);         // 2:R:M:N:oic.sec.roletype
+    memcpy(cred1->roleId.authority, "samsung", ROLEAUTHORITY_LENGTH);         // 2:R:M:N:oic.sec.roletype
+
     EXPECT_EQ(OC_STACK_OK, CredToCBORPayload(cred1, &payload, &size, secureFlag));
     DeleteCredList(cred1);
     ASSERT_TRUE(NULL != payload);
@@ -265,7 +193,7 @@ TEST(CredResourceTest, CBORPayloadToCredVALID)
     DeleteCredList(cred2);
 }
 
-TEST(CredResourceTest, CBORPayloadToCredSecureVALID)
+TEST_F(CRED, CBORPayloadToCredSecureVALID)
 {
     OicSecCred_t *cred1 = getCredList();
     ASSERT_TRUE(NULL != cred1);
@@ -294,7 +222,7 @@ TEST(CredResourceTest, CBORPayloadToCredSecureVALID)
     DeleteCredList(cred2);
 }
 
-TEST(CredResourceTest, CBORPayloadToCredNULL)
+TEST_F(CRED, CBORPayloadToCredNULL)
 {
     OicSecCred_t *cred = NULL;
     OicUuid_t *rownerId = NULL;
@@ -311,12 +239,12 @@ TEST(CredResourceTest, CBORPayloadToCredNULL)
 }
 
 //GetCredResourceData Test
-TEST(CredResourceTest, GetCredResourceDataNULLSubject)
+TEST_F(CRED, GetCredResourceDataNULLSubject)
 {
     EXPECT_EQ(NULL, GetCredResourceData(NULL));
 }
 
-TEST(CredResourceTest, GenerateCredentialValidInput)
+TEST_F(CRED, GenerateCredentialValidInput)
 {
     OicUuid_t rownerID = {{0}};
     OICStrcpy((char *)rownerID.id, sizeof(rownerID.id), "ownersId21");
@@ -336,7 +264,7 @@ TEST(CredResourceTest, GenerateCredentialValidInput)
     DeleteCredList(cred);
 }
 
-TEST(CredResourceTest, GenerateAndAddCredentialValidInput)
+TEST_F(CRED, GenerateAndAddCredentialValidInput)
 {
     OicUuid_t rownerID = {{0}};
     OICStrcpy((char *)rownerID.id, sizeof(rownerID.id), "ownersId11");
@@ -376,7 +304,7 @@ TEST(CredResourceTest, GenerateAndAddCredentialValidInput)
 }
 
 #if 0
-TEST(CredGetResourceDataTest, GetCredResourceDataValidSubject)
+TEST_F(CredGetResourceDataTest, GetCredResourceDataValidSubject)
 {
     OicSecCred_t* cred = getCredList();
     EXPECT_TRUE(NULL != GetCredResourceData(cred->subject));
@@ -384,18 +312,250 @@ TEST(CredGetResourceDataTest, GetCredResourceDataValidSubject)
 #endif
 
 #if defined(__WITH_DTLS__) || defined(__WITH_TLS__)
-TEST(CredGetDtlsPskCredentialsTest, NullResult)
+TEST_F(CRED, NullResult)
 {
     EXPECT_EQ(-1, GetDtlsPskCredentials(CA_DTLS_PSK_KEY, NULL, 0, NULL, 0));
 }
 
-TEST(CredAddTmpPskWithPINTest, NullSubject)
+TEST_F(CRED, AddTmpPskWithPIN)
 {
+    gCred = NULL;
+    OicUuid_t* subject = createUuidWith("33333333-3333-3333-3333-222222222222");
+    char pin[] = "the_pin";
+    size_t pinSize = strlen(pin);
+    OicUuid_t *rownerID = createUuidWith("33333333-3333-3333-3333-222222222222");
+    OicUuid_t* credSubject = createUuidWith("33333333-3333-3333-3333-222222222222");
+
     EXPECT_EQ(OC_STACK_INVALID_PARAM, AddTmpPskWithPIN(NULL, SYMMETRIC_PAIR_WISE_KEY,
               NULL, 0, NULL, NULL));
+    EXPECT_EQ(OC_STACK_OK, AddTmpPskWithPIN(subject, SYMMETRIC_PAIR_WISE_KEY,
+              pin, pinSize,rownerID, credSubject));
 }
 #endif // __WITH_DTLS__ or __WITH_TLS__
-TEST(CredCBORPayloadToCredTest, NullPayload)
+TEST_F(CRED, NullPayload)
 {
     EXPECT_EQ(OC_STACK_INVALID_PARAM, CBORPayloadToCred(NULL, 0, NULL, NULL));
 }
+
+TEST_F(CRED, DeleteCredIdList)
+{
+    CredIdList_t *list = NULL;
+    CredIdList_t *cred = (CredIdList_t*)OICCalloc(1, sizeof(CredIdList_t));
+    cred->credId = (int16_t)rand();
+    LL_APPEND(list, cred);
+    DeleteCredIdList(&list);
+}
+
+TEST_F(CRED, CheckSubjectOfCertificate)
+{
+    OicSecCred_t* cred = getSignedAsymKeyCred();
+    OicUuid_t deviceID;
+    ConvertStrToUuid("33333333-3333-3333-3333-222222222222", &deviceID);
+
+    printCred(cred);
+    EXPECT_TRUE(CheckSubjectOfCertificate(cred, deviceID));
+
+    FreeCred(cred);
+}
+
+TEST_F(CRED, IsValidCredential)
+{
+    OicSecCred_t* cred = NULL;
+
+    EXPECT_FALSE(IsValidCredential(cred));
+
+    cred = getSignedAsymKeyCred();
+    EXPECT_TRUE(IsValidCredential(cred));
+    FreeCred(cred);
+
+    cred = getAsymKeyCred();
+    EXPECT_TRUE(IsValidCredential(cred));
+    FreeCred(cred);
+
+    cred = getAsymEncKeyCred();
+    EXPECT_TRUE(IsValidCredential(cred));
+    FreeCred(cred);
+}
+
+TEST_F(CRED, IsEmptyCred)
+{
+    OicSecCred_t* cred = NULL;
+
+    EXPECT_FALSE(IsEmptyCred(cred));
+
+    cred = getSignedAsymKeyCred();
+    EXPECT_FALSE(IsEmptyCred(cred));
+    FreeCred(cred);
+
+    cred = getAsymKeyCred();
+    EXPECT_FALSE(IsEmptyCred(cred));
+    FreeCred(cred);
+
+    cred = getAsymEncKeyCred();
+    EXPECT_FALSE(IsEmptyCred(cred));
+    FreeCred(cred);
+}
+
+
+TEST_F(CRED, SerializeDeserializeSecOpt)
+{
+    CborEncoder encoder;
+    CborEncoder eRootMap;
+    uint8_t *payload = (uint8_t *)OICCalloc(1, 2048);
+    cbor_encoder_init(&encoder, payload, 2048, 0);
+    EXPECT_EQ(CborNoError, cbor_encoder_create_map(&encoder, &eRootMap, 1));
+    OicSecOpt_t opt = OIC_DEFAULT_OICSECOPT;
+    EXPECT_EQ(CborNoError, SerializeSecOptToCbor(&eRootMap, OIC_JSON_OPTDATA_NAME, &opt));
+    EXPECT_EQ(CborNoError, cbor_encoder_close_container(&encoder, &eRootMap));
+    size_t size = cbor_encoder_get_buffer_size(&encoder, payload);
+    CborParser parser;
+    CborValue pRoot = OC_CBOR_VALUE_INIT;
+    cbor_parser_init(payload, size, 0, &parser, &pRoot);
+    ASSERT_TRUE(cbor_value_is_container(&pRoot));
+    OicSecOpt_t *optR = (OicSecOpt_t*)OICCalloc(1,sizeof(OicSecOpt_t));
+    EXPECT_EQ(CborNoError, DeserializeSecOptFromCbor(&pRoot, optR));
+}
+
+TEST_F(CRED, IsSameSecOpt)
+{
+    OicSecOpt_t opt1 = OIC_DEFAULT_OICSECOPT;
+    OicSecOpt_t opt2 = OIC_DEFAULT_OICSECOPT;
+    EXPECT_TRUE(IsSameSecOpt(&opt1, &opt2));
+    opt1.revstat = true;
+    EXPECT_FALSE(IsSameSecOpt(&opt1, &opt2));
+}
+
+TEST_F(CRED, IsSameSecKey)
+{
+    OicSecKey_t key1 = OIC_DEFAULT_OICSECKEY;
+    OicSecKey_t key2 = OIC_DEFAULT_OICSECKEY;
+    EXPECT_TRUE(IsSameSecKey(&key1, &key2));
+    key1.encoding = OIC_ENCODING_RAW;
+    EXPECT_FALSE(IsSameSecKey(&key1, &key2));
+}
+
+TEST_F(CRED, RemoveCredential)
+{
+    RemoveAllCredentials();
+    gCred = NULL;
+    OicSecCred_t* cred = getSignedAsymKeyCred();
+    EXPECT_EQ(OC_STACK_OK,AddCredential(cred));
+    EXPECT_EQ(OC_STACK_INVALID_PARAM, RemoveCredentialByCredId(0));
+    EXPECT_EQ(OC_STACK_ERROR, RemoveCredentialByCredId((uint16_t)-12));
+    EXPECT_EQ(OC_STACK_RESOURCE_DELETED, RemoveCredentialByCredId(cred->credId));
+    cred = getSignedAsymKeyCred();
+    EXPECT_EQ(OC_STACK_OK,AddCredential(cred));
+    CredIdList_t id = {
+    #if (__STDC_VERSION__ >= 199901L)
+        .credId = cred->credId,
+        .next = NULL
+    #else
+        cred->credId,
+        NULL
+    #endif
+        };
+    EXPECT_EQ(OC_STACK_RESOURCE_DELETED, RemoveCredentialByCredIds(&id));
+}
+
+TEST_F(CRED, GetCredIdsFromQueryString)
+{
+
+    char *query = (char*)OICCalloc(1024,1);
+    CredIdList_t *credid = NULL;
+#if defined(__unix__)
+    snprintf(query, 1024, "%s=%li", OIC_JSON_CREDID_NAME, 13463257457456L);
+#endif
+    EXPECT_TRUE(GetCredIdsFromQueryString(query, &credid));
+    snprintf(query, 1024, "%s=%d", OIC_JSON_CREDID_NAME, 1222);
+    EXPECT_TRUE(GetCredIdsFromQueryString(query, &credid));
+    OICFree(query);
+}
+
+TEST_F(CRED, ConvertCert)
+{
+    const char *pem = getPemCert();
+    size_t pemLen = strlen(pem);
+    uint8_t* der = NULL;
+    size_t derLen = 0;
+    uint8_t *newPem = NULL;
+    EXPECT_EQ(0, ConvertPemCertToDer(pem, pemLen, &der, &derLen));
+#ifndef NDEBUG
+    EXPECT_EQ(0, ConvertDerCertToPem(der, derLen, &newPem));
+#endif //NDEBUG
+    OICFree((void*)pem);
+    OICFree(der);
+    OICFree(newPem);
+}
+
+TEST_F(CRED, FillPrivateDataOfOwnerPSK)
+{
+    OicSecCred_t* cred = getSignedAsymKeyCred();
+    CAEndpoint_t* ep = createEndpoint();
+    OicSecDoxm_t* doxm = createDoxm();
+
+   // SslEndPoint_t * peer = GetSslPeer(ep);
+    //u_arraylist_add(g_caSslContext->peerList, (void *) peer);
+
+    EXPECT_FALSE(FillPrivateDataOfOwnerPSK(cred, ep, doxm));
+
+    freeDoxm(doxm);
+    freeEndpoint(ep);
+    FreeCred(cred);
+}
+
+TEST_F(CRED, HandleNewCredential)
+{
+    OCEntityHandlerRequest ehRequest =  OCEntityHandlerRequest();
+    OicSecCred_t* cred = getSignedAsymKeyCred();
+    EXPECT_EQ(OC_EH_CHANGED, HandleNewCredential(&ehRequest, cred));
+    FreeCred(cred);
+}
+
+TEST_F(CRED, GetIdentityHandler)
+{
+    UuidContext_t ctx;
+    ctx.list = NULL;
+    unsigned char* crt = NULL;
+    size_t crtLen = 0;
+
+    gCred = NULL;
+
+    OicSecCred_t *cred = getSignedAsymKeyCred();
+    OICFree(cred->credUsage);
+    cred->credUsage = (char*)OICCalloc(strlen(TRUST_CA) + 1, 1);
+    sprintf(cred->credUsage,"%s", TRUST_CA);
+#ifndef NDEBUG
+    LogCred(cred, TAG);
+    LogCredResource(cred, TAG, "lab");
+#endif //NDEBUG
+    LL_APPEND(gCred, cred);
+    GetIdentityHandler(&ctx, crt, crtLen);
+}
+
+TEST_F(CRED,GetDerKey)
+{
+    OicSecCred_t *cred = getSignedAsymKeyCred();
+    cred->privateData.encoding = OIC_ENCODING_PEM;
+    cred->privateData.data = (uint8_t*)getPemKey();
+    cred->privateData.len = strlen((const char*)cred->privateData.data);
+    LL_APPEND(gCred, cred);
+
+    ByteArray_t* key = NULL;
+    GetDerKey(key, PRIMARY_CERT);
+    key = (ByteArray_t*)OICCalloc(1, sizeof(ByteArray_t));
+    GetDerKey(key, PRIMARY_CERT);
+}
+
+TEST_F(CRED, cloneSecKey)
+{
+    OicSecKey_t *dst = (OicSecKey_t*)OICCalloc(1, sizeof(OicSecKey_t));
+    OicSecKey_t *src = (OicSecKey_t*)OICCalloc(1, sizeof(OicSecKey_t));
+    EXPECT_EQ(0,cloneSecKey(dst, src));
+}
+
+TEST_F(CRED, GetAllRoleCerts)
+{
+    RoleCertChain_t* output = NULL;
+    EXPECT_EQ(OC_STACK_OK, GetAllRoleCerts(&output));
+    FreeRoleCertChainList(output);
+}
index 3ba78c6..e813168 100644 (file)
 * limitations under the License.
 *
 ******************************************************************/
-#ifdef __WITH_DTLS__
-
 #include <gtest/gtest.h>
-#include "experimental/logger.h"
-#include "ocpayload.h"
-#include "ocstack.h"
-#include "oic_malloc.h"
-#include "oic_string.h"
-#include "resourcemanager.h"
-#include "crlresource.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#include "tools.h"
+#undef TAG
+#include "../src/crlresource.c"
 #include "srmtestcommon.h"
-#include "srmutility.h"
-#include "psinterface.h"
-#include "security_internals.h"
+#include "ocserverrequest.h"
+
+#ifdef __cplusplus
+}
+#endif
+
+#ifdef TAG
+#undef TAG
+#endif
 
 #define TAG  "SRM-CRL-UT"
 
- //InitCRLResource Tests
-TEST(CRLResourceTest, InitCRLResource)
+#define SVR_DB_FILE_NAME TAG".dat"
+#define PM_DB_FILE_NAME TAG".db"
+
+class CRL : public ::testing::Test
 {
-    EXPECT_EQ(OC_STACK_INVALID_PARAM, InitCRLResource());
-}
+    public:
 
-//DeInitCredResource Tests
-TEST(CRLResourceTest, DeInitCRLResource)
+        static void SetUpTestCase()
+        {
+            IOT_Init(PM_DB_FILE_NAME);
+        }
+
+        static void TearDownTestCase()
+        {
+            IOT_DeInit(PM_DB_FILE_NAME);
+        }
+};
+
+OCStackResult responseHandler(OCEntityHandlerResponse * ehResponse)
 {
-    EXPECT_EQ(OC_STACK_INVALID_PARAM, DeInitCRLResource());
+    OC_UNUSED(ehResponse);
+    OIC_LOG_V(DEBUG, TAG, "%s run", __func__);
+    return OC_STACK_OK;
 }
 
 //GetCRLResource Tests
-TEST(CRLResourceTest, GetCRLResource)
+TEST_F(CRL, GetCRLResource)
 {
     OicSecCrl_t *nullCrl = GetCRLResource();
     EXPECT_NE((OicSecCrl_t*)NULL, nullCrl);
@@ -55,20 +73,21 @@ TEST(CRLResourceTest, GetCRLResource)
 }
 
 //CrlToCBORPayload Tests
-TEST(CRLResourceTest, CrlToCBORPayload)
+TEST_F(CRL, CrlToCBORPayload)
 {
     uint8_t *payload = NULL;
     size_t size;
     OicSecCrl_t *crl = GetCRLResource();
     ASSERT_TRUE(NULL != crl);
     size = 0;
+    EXPECT_EQ(OC_STACK_INVALID_PARAM, CrlToCBORPayload(NULL, &payload, &size, NULL));
     EXPECT_EQ(OC_STACK_OK, CrlToCBORPayload(crl, &payload, &size, NULL));
     DeleteCrl(crl);
     OICFree(payload);
 }
 
 //CBORPaylodToCrl Tests
-TEST(CRLResourceTest, CBORPayloadToCrl)
+TEST_F(CRL, CBORPayloadToCrl)
 {
     uint8_t *payload = NULL;
     size_t size;
@@ -78,13 +97,14 @@ TEST(CRLResourceTest, CBORPayloadToCrl)
     EXPECT_EQ(OC_STACK_OK, CrlToCBORPayload(crl, &payload, &size, NULL));
     DeleteCrl(crl);
     crl = NULL;
+    EXPECT_EQ(OC_STACK_INVALID_PARAM, CBORPayloadToCrl(NULL, size, &crl));
     EXPECT_EQ(OC_STACK_OK, CBORPayloadToCrl(payload, size, &crl));
     DeleteCrl(crl);
     OICFree(payload);
 }
 
 //GetDerCrl Tests
-TEST(CRLResourceTest, GetDerCrl)
+TEST_F(CRL, GetDerCrl)
 {
     ByteArray crlArray = {NULL, 0};
     GetDerCrl(&crlArray);
@@ -92,4 +112,96 @@ TEST(CRLResourceTest, GetDerCrl)
     OICFree(crlArray.data);
 }
 
-#endif
+TEST_F(CRL, copyCrl)
+{
+    OicSecCrl_t *src = GetCRLResource();
+    OicSecCrl_t *dst = (OicSecCrl_t*)OICCalloc(1, sizeof(OicSecCrl_t));
+    EXPECT_TRUE(copyCrl(src, dst));
+}
+
+TEST_F(CRL, getCurrentUTCTime)
+{
+    char *time = (char*)OICCalloc(512,1);
+    getCurrentUTCTime(time, 512);
+    ASSERT_STRNE(NULL, time);
+    OICFree(time);
+}
+
+TEST_F(CRL, UpdateCRLResource)
+{
+    OicSecCrl_t *src = GetCRLResource();
+    EXPECT_EQ(OC_STACK_OK, UpdateCRLResource(src));
+}
+
+TEST_F(CRL, ValidateQuery)
+{
+    char *q = (char*)OICCalloc(512,1);
+    EXPECT_TRUE(ValidateQuery(q));
+    snprintf(q, 512, "%s=lo",OC_RSRVD_INTERFACE);
+    EXPECT_FALSE(ValidateQuery(q));
+    OICFree(q);
+}
+
+TEST_F(CRL, HandleCRLGetRequest)
+{
+    OCServerRequest *srvReq = (OCServerRequest*)OICCalloc(1, sizeof(OCServerRequest));
+    srvReq->ehResponseHandler = responseHandler;
+    OCEntityHandlerRequest ehReq = OCEntityHandlerRequest();
+    ehReq.method = OC_REST_GET;
+    ehReq.requestHandle = (OCRequestHandle) srvReq;
+    EXPECT_EQ(OC_EH_OK,HandleCRLGetRequest(&ehReq));
+    ehReq.query = (char*)TAG;
+    EXPECT_EQ(OC_EH_OK,HandleCRLGetRequest(&ehReq));
+    OicSecCrl_t *p = gCrl;
+    gCrl = NULL;
+    EXPECT_EQ(OC_EH_ERROR,HandleCRLGetRequest(&ehReq));
+    gCrl = p;
+}
+
+TEST_F(CRL, HandleCRLPostRequest)
+{
+    OicSecCrl_t *crl = GetCRLResource();
+    uint8_t *payload = NULL;
+    size_t size = 0;
+    char *lastUpdate = NULL;
+
+    ASSERT_EQ(OC_STACK_OK, CrlToCBORPayload(crl, &payload, &size, lastUpdate));
+    OCSecurityPayload *securityPayload = OCSecurityPayloadCreate(payload, size);
+    ASSERT_TRUE(NULL != securityPayload);
+
+    OCServerRequest *srvReq = (OCServerRequest*)OICCalloc(1, sizeof(OCServerRequest));
+    srvReq->ehResponseHandler = responseHandler;
+
+    OCEntityHandlerRequest ehReq = OCEntityHandlerRequest();
+    ehReq.method = OC_REST_POST;
+    ehReq.payload = (OCPayload *) securityPayload;
+    ehReq.requestHandle = (OCRequestHandle) srvReq;
+    EXPECT_EQ(OC_EH_CHANGED, HandleCRLPostRequest(&ehReq));
+}
+
+TEST_F(CRL, CRLEntityHandler)
+{
+    OicSecCrl_t *crl = GetCRLResource();
+    uint8_t *payload = NULL;
+    size_t size = 0;
+    char *lastUpdate = NULL;
+
+    EXPECT_EQ(OC_STACK_INVALID_PARAM, getLastUpdateFromDB(NULL));
+    EXPECT_EQ(OC_STACK_OK, getLastUpdateFromDB(&lastUpdate));
+    ASSERT_EQ(OC_STACK_OK, CrlToCBORPayload(crl, &payload, &size, lastUpdate));
+    OCSecurityPayload *securityPayload = OCSecurityPayloadCreate(payload, size);
+    ASSERT_TRUE(NULL != securityPayload);
+
+    OCServerRequest *srvReq = (OCServerRequest*)OICCalloc(1, sizeof(OCServerRequest));
+    srvReq->ehResponseHandler = responseHandler;
+
+    OCEntityHandlerRequest ehReq = OCEntityHandlerRequest();
+    ehReq.method = OC_REST_POST;
+    ehReq.payload = (OCPayload *) securityPayload;
+    ehReq.requestHandle = (OCRequestHandle) srvReq;
+    EXPECT_EQ(OC_EH_CHANGED, CRLEntityHandler(OC_REQUEST_FLAG, &ehReq, NULL));
+    ehReq.method = OC_REST_GET;
+    EXPECT_EQ(OC_EH_OK, CRLEntityHandler(OC_REQUEST_FLAG, &ehReq, NULL));
+    ehReq.method = OC_REST_NOMETHOD;
+    EXPECT_EQ(OC_EH_ERROR, CRLEntityHandler(OC_REQUEST_FLAG, &ehReq, NULL));
+}
diff --git a/resource/csdk/security/unittest/csr/csr.pem b/resource/csdk/security/unittest/csr/csr.pem
new file mode 100644 (file)
index 0000000..9f72857
--- /dev/null
@@ -0,0 +1,12 @@
+-----BEGIN CERTIFICATE REQUEST-----
+MIIByzCCAS0CAQAwgYcxCzAJBgNVBAYTAlVBMQ0wCwYDVQQIDARLeWl2MQ0wCwYD
+VQQHDARLeWl2MRQwEgYDVQQKDAtzYW1zdW5nLmNvbTEPMA0GA1UECwwGQWRTRUNM
+MRQwEgYDVQQDDAtzYW1zdW5nLmNvbTEdMBsGCSqGSIb3DQEJARYOcm9vdEBsb2Nh
+bGhvc3QwgZswEAYHKoZIzj0CAQYFK4EEACMDgYYABAHlki82nc4jlwFOst+zjN3H
+0KDq1tdA10HKdEqwCpj+pBfIi5iaSZkprYeSkksAa62wr0DnIgbdleK6gbS+BJEd
+gABZM/y9+0/cT3CGpAmqJECwGgxKt865lT98eRWfSwvGrLz74TdHqZrcIIDZRWJJ
+Mif9acxgUrGRuTwc3iSxNRZ3daAAMAoGCCqGSM49BAMCA4GLADCBhwJBTqJei0nO
+G66+b0fpGRWLVhM5CqUK33wNOj3hGmnrXMUqEiMFmRU3+isQOf0UYLmv27rugHm2
+dBVzva6bqUKIrVMCQgEYVOwdvrOtJBbux3/u/9FIIL5UlEPhJ/43gHIZJKEbeulv
+L0LBEdB/EsNbcbAszfrx+vCEUpkgIJwqX03RTPOQSQ==
+-----END CERTIFICATE REQUEST-----
diff --git a/resource/csdk/security/unittest/csr/csr1.pem b/resource/csdk/security/unittest/csr/csr1.pem
new file mode 100644 (file)
index 0000000..976e891
--- /dev/null
@@ -0,0 +1,18 @@
+-----BEGIN CERTIFICATE REQUEST-----
+MIIC5jCCAc4CAQAwgaAxCzAJBgNVBAYTAlVBMQ0wCwYDVQQIDARLeWl2MQ0wCwYD
+VQQHDARLeWl2MRQwEgYDVQQKDAtzYW1zdW5nLmNvbTEPMA0GA1UECwwGQWRTRUNM
+MS0wKwYDVQQDDCQzMzMzMzMzMy0zMzMzLTMzMzMtMzMzMy0yMjIyMjIyMjIyMjIx
+HTAbBgkqhkiG9w0BCQEWDnJvb3RAbG9jYWxob3N0MIIBIjANBgkqhkiG9w0BAQEF
+AAOCAQ8AMIIBCgKCAQEA23S2Ghq/qKYoaX8WYCjvgj+Yui54FrhmtKRAGiBQFuUS
+/9BqMsYv36Gqy5Zb+FVZDS26xRjKeuChQ8PJOfKLes1LRVSSgkgEWUUqjjUQtJ4G
+B612EgLo7sUZ5I8CFjQ+mjRYbFT2wNnDRRr0K8Wdg1UFJADpAtQvI5OZX5vIFtan
+oTgzoVTH8zcPXXuBP7BnqRXbRFFqS2anLlB6pi5AFVDm9REyVxRmqy5/mWuSutPl
+zyS7Ud47vMymcodVfxfnUQ0WnPIHx5Tb4KwCPwrO/sa2KTcTVtmbQ3/3Iuoiy2Kw
+98dIcNgzgx6BZUpxDXSXh67NxvoFodV68WQShTIzmQIDAQABoAAwDQYJKoZIhvcN
+AQELBQADggEBAJseIbddL+GGE03LSQ+3I12f8ei8VaIR+fjy71ziH0ZvTcXrtBNt
+tBe1Q1JL3PWRm0stNOUIiGlulLAjPBC7modg/4+VuMQq0HgfU0nriSoGWFgTAECI
+X15ArBMo2tsAW9cpvDNG9C1pO1HwUUcFS2MobogZIVZNvLnqyrrXu25lncZmY6OD
+qLEPtITfC5Ll60TcAxYd7DTRfpxenth/WlxSCqzUPgtZuHXif6NhmFBzytRtkon3
+yd7XMXrzo9MDfWVxYKIWfg4YzBWrkaC/nWzKaVze9P96QoUSZDJjJ5fCLEAoI9TQ
+J3BHw7N25JVYLtQMZjzZq6Fcl/xLtam0x3o=
+-----END CERTIFICATE REQUEST-----
diff --git a/resource/csdk/security/unittest/csr/key.pem b/resource/csdk/security/unittest/csr/key.pem
new file mode 100644 (file)
index 0000000..ac226a4
--- /dev/null
@@ -0,0 +1,7 @@
+-----BEGIN EC PRIVATE KEY-----
+MIHcAgEBBEIBA4YLSu/sw1YIkOl/6JfQVc8CLunfwJF8cgPOzTRce55fKssi1lum
+aj3XenmDtQbnglR70mtzig8CdUL0Y1JhyZqgBwYFK4EEACOhgYkDgYYABAHlki82
+nc4jlwFOst+zjN3H0KDq1tdA10HKdEqwCpj+pBfIi5iaSZkprYeSkksAa62wr0Dn
+IgbdleK6gbS+BJEdgABZM/y9+0/cT3CGpAmqJECwGgxKt865lT98eRWfSwvGrLz7
+4TdHqZrcIIDZRWJJMif9acxgUrGRuTwc3iSxNRZ3dQ==
+-----END EC PRIVATE KEY-----
diff --git a/resource/csdk/security/unittest/csrresource.cpp b/resource/csdk/security/unittest/csrresource.cpp
new file mode 100644 (file)
index 0000000..ca496da
--- /dev/null
@@ -0,0 +1,106 @@
+/******************************************************************
+*
+* Copyright 2016 Samsung Electronics All Rights Reserved.
+*
+*
+*
+* Licensed under the Apache License, Version 2.0 (the "License");
+* you may not use this file except in compliance with the License.
+* You may obtain a copy of the License at
+*
+*      http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License.
+*
+******************************************************************/
+#include <gtest/gtest.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#include "tools.h"
+#undef TAG
+#include "../src/csrresource.c"
+#include "srmtestcommon.h"
+#include "ocserverrequest.h"
+
+#ifdef __cplusplus
+}
+#endif
+
+#ifdef TAG
+#undef TAG
+#endif
+
+#define TAG  "CSR"
+
+#define SVR_DB_FILE_NAME TAG".dat"
+#define PM_DB_FILE_NAME TAG".db"
+
+class CSR : public ::testing::Test
+{
+    public:
+
+        static void SetUpTestCase()
+        {
+            IOT_Init(PM_DB_FILE_NAME);
+        }
+
+        static void TearDownTestCase()
+        {
+            IOT_DeInit(PM_DB_FILE_NAME);
+        }
+};
+
+static OCStackResult responseHandler(OCEntityHandlerResponse * ehResponse)
+{
+    OC_UNUSED(ehResponse);
+    OIC_LOG_V(DEBUG, TAG, "%s run", __func__);
+    return OC_STACK_OK;
+}
+
+TEST_F(CSR, StoreKeyPair)
+{
+    mbedtls_pk_context pk;
+    mbedtls_pk_init(&pk);
+    EXPECT_GE(OCInternalGenerateKeyPair(&pk), 0);
+
+    OicUuid_t *uuid = createUuid();
+
+    EXPECT_EQ(OC_STACK_OK, StoreKeyPair(&pk, uuid));
+
+    freeUuid(uuid);
+}
+
+TEST_F(CSR, HandleCsrGetRequest)
+{
+    OCServerRequest *srvReq = (OCServerRequest*)OICCalloc(1, sizeof(OCServerRequest));
+    srvReq->ehResponseHandler = responseHandler;
+    OCEntityHandlerRequest ehReq = OCEntityHandlerRequest();
+    ehReq.method = OC_REST_GET;
+    ehReq.requestHandle = (OCRequestHandle) srvReq;
+    EXPECT_EQ(OC_EH_OK,HandleCsrGetRequest(&ehReq));
+    ehReq.query = (char*)TAG;
+    EXPECT_EQ(OC_EH_OK,HandleCsrGetRequest(&ehReq));
+}
+
+
+TEST_F(CSR, CredCsrEntityHandler)
+{
+    OCServerRequest *srvReq = (OCServerRequest*)OICCalloc(1, sizeof(OCServerRequest));
+    srvReq->ehResponseHandler = responseHandler;
+
+    OCEntityHandlerRequest ehReq = OCEntityHandlerRequest();
+    ehReq.method = OC_REST_POST;
+    ehReq.requestHandle = (OCRequestHandle) srvReq;
+    EXPECT_EQ(OC_EH_ERROR, CredCsrEntityHandler(OC_REQUEST_FLAG, &ehReq, NULL));
+    ehReq.method = OC_REST_GET;
+    EXPECT_EQ(OC_EH_OK, CredCsrEntityHandler(OC_REQUEST_FLAG, &ehReq, NULL));
+    ehReq.method = OC_REST_NOMETHOD;
+    EXPECT_EQ(OC_EH_ERROR, CredCsrEntityHandler(OC_REQUEST_FLAG, &ehReq, NULL));
+}
diff --git a/resource/csdk/security/unittest/deviceonboardingstate.cpp b/resource/csdk/security/unittest/deviceonboardingstate.cpp
new file mode 100644 (file)
index 0000000..c2320c1
--- /dev/null
@@ -0,0 +1,72 @@
+/******************************************************************
+*
+* Copyright 2019 Samsung Electronics All Rights Reserved.
+*
+*
+*
+* Licensed under the Apache License, Version 2.0 (the "License");
+* you may not use this file except in compliance with the License.
+* You may obtain a copy of the License at
+*
+*      http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License.
+*
+******************************************************************/
+#include <gtest/gtest.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#include "tools.h"
+#undef TAG
+#include "../src/deviceonboardingstate.c"
+
+#ifdef __cplusplus
+}
+#endif
+
+#ifdef TAG
+#undef TAG
+#endif
+
+#define TAG  "DOS"
+
+#define SVR_DB_FILE_NAME TAG".dat"
+#define PM_DB_FILE_NAME TAG".db"
+
+class DOS : public ::testing::Test
+{
+    public:
+
+        static void SetUpTestCase()
+        {
+            IOT_Init(PM_DB_FILE_NAME);
+        }
+
+        static void TearDownTestCase()
+        {
+            IOT_DeInit(PM_DB_FILE_NAME);
+        }
+};
+
+TEST_F(DOS, IsReadyToEnterSRESET)
+{
+    EXPECT_FALSE(IsReadyToEnterSRESET());
+}
+
+TEST_F(DOS, EnterSRESET)
+{
+    EXPECT_TRUE(EnterSRESET());
+}
+
+TEST_F(DOS, SetDosState)
+{
+    EXPECT_FALSE(SetDosState(DOS_RESET));
+}
+
index 5d5ce33..6506dff 100644 (file)
 //
 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
 
+#include "iotivity_config.h"
 #include <gtest/gtest.h>
-#include "ocstack.h"
-#include "ocserverrequest.h"
 #include "oic_string.h"
-#include "oic_malloc.h"
-#include "resourcemanager.h"
-#include "srmresourcestrings.h"
-#include "experimental/doxmresource.h"
-#include "security_internals.h"
-#include "experimental/ocrandom.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#include "tools.h"
+#undef TAG
+#include "../src/doxmresource.c"
+
+#ifdef __cplusplus
+}
+#endif
+
+#ifdef TAG
+#undef TAG
+#endif
 
 #define TAG  "SRM-DOXM"
 
+#define SVR_DB_FILE_NAME TAG".dat"
+#define PM_DB_FILE_NAME TAG".db"
+
+class DOXM : public ::testing::Test
+{
+    public:
+
+        static void SetUpTestCase()
+        {
+            IOT_Init(PM_DB_FILE_NAME);
+            //InitDoxmResource Tests
+            EXPECT_EQ(OC_STACK_OK, InitDoxmResource());
+            //CreateDoxmResource Tests
+            EXPECT_EQ(OC_STACK_OK, CreateDoxmResource());
+            //DoxmEntityHandler Tests
+            OCEntityHandlerRequest req = OCEntityHandlerRequest();
+            EXPECT_EQ(OC_EH_ERROR, DoxmEntityHandler(OCEntityHandlerFlag::OC_REQUEST_FLAG, &req, NULL));
+        }
+
+        static void TearDownTestCase()
+        {
+            //DeInitDoxmResource Tests
+            EXPECT_EQ(OC_STACK_OK, DeInitDoxmResource());
+            IOT_DeInit(PM_DB_FILE_NAME);
+        }
+};
+
 OicSecDoxm_t * getBinDoxm()
 {
     OicSecDoxm_t *doxm = (OicSecDoxm_t *)OICCalloc(1, sizeof(*doxm));
@@ -59,43 +95,18 @@ OicSecDoxm_t * getBinDoxm()
     return doxm;
 }
 
- //InitDoxmResource Tests
-TEST(DoxmResourceTest, InitDoxmResource)
-{
-    EXPECT_EQ(OC_STACK_INVALID_PARAM, InitDoxmResource());
-}
-
-//DeInitDoxmResource Tests
-TEST(DoxmResourceTest, DeInitDoxmResource)
-{
-    EXPECT_EQ(OC_STACK_ERROR, DeInitDoxmResource());
-}
-
-//CreateDoxmResource Tests
-TEST(DoxmResourceTest, CreateDoxmResource)
-{
-    EXPECT_EQ(OC_STACK_INVALID_PARAM, CreateDoxmResource());
-}
-
- //DoxmEntityHandler Tests
-TEST(DoxmResourceTest, DoxmEntityHandlerWithDummyRequest)
-{
-    OCEntityHandlerRequest req = OCEntityHandlerRequest();
-    EXPECT_EQ(OC_EH_ERROR, DoxmEntityHandler(OCEntityHandlerFlag::OC_REQUEST_FLAG, &req, NULL));
-}
-
-TEST(DoxmResourceTest, DoxmEntityHandlerWithNULLRequest)
+TEST_F(DOXM, DoxmEntityHandlerWithNULLRequest)
 {
     EXPECT_EQ(OC_EH_ERROR, DoxmEntityHandler(OCEntityHandlerFlag::OC_REQUEST_FLAG, NULL, NULL));
 }
 
-TEST(DoxmResourceTest, DoxmEntityHandlerInvalidFlag)
+TEST_F(DOXM, DoxmEntityHandlerInvalidFlag)
 {
     OCEntityHandlerRequest req = OCEntityHandlerRequest();
     EXPECT_EQ(OC_EH_ERROR, DoxmEntityHandler(OCEntityHandlerFlag::OC_OBSERVE_FLAG, &req, NULL));
 }
 
-TEST(DoxmResourceTest, DoxmEntityHandlerValidRequest)
+TEST_F(DOXM, DoxmEntityHandlerValidRequest)
 {
     EXPECT_EQ(OC_STACK_INVALID_PARAM, InitDoxmResource());
     char query[] = "oxm=0;owned=false;owner=owner1";
@@ -107,9 +118,9 @@ TEST(DoxmResourceTest, DoxmEntityHandlerValidRequest)
     OICFree(req.query);
 }
 
-TEST(DoxmResourceTest, DoxmEntityHandlerDeviceIdQuery)
+TEST_F(DOXM, DoxmEntityHandlerDeviceIdQuery)
 {
-    EXPECT_EQ(OC_STACK_INVALID_PARAM, InitDoxmResource());
+    EXPECT_EQ(OC_STACK_OK, InitDoxmResource());
     char query[] = "deviceuuid=2222222222222222";
     OCEntityHandlerRequest req = OCEntityHandlerRequest();
     req.method = OC_REST_GET;
@@ -119,7 +130,7 @@ TEST(DoxmResourceTest, DoxmEntityHandlerDeviceIdQuery)
     OICFree(req.query);
 }
 
-TEST(DoxmResourceTest, DoxmToCBORPayloadNULL)
+TEST_F(DOXM, DoxmToCBORPayloadNULL)
 {
     OicSecDoxm_t *doxm =  getBinDoxm();
     size_t size = 10;
@@ -131,7 +142,7 @@ TEST(DoxmResourceTest, DoxmToCBORPayloadNULL)
     DeleteDoxmBinData(doxm);
 }
 
-TEST(DoxmResourceTest, DoxmToCBORPayloadVALID)
+TEST_F(DOXM, DoxmToCBORPayloadVALID)
 {
     OicSecDoxm_t *doxm = getBinDoxm();
 
@@ -153,7 +164,7 @@ TEST(DoxmResourceTest, DoxmToCBORPayloadVALID)
 }
 
 //CBORPayloadToDoxm Tests
-TEST(DoxmResourceTest, CBORPayloadToDoxmNULL)
+TEST_F(DOXM, CBORPayloadToDoxmNULL)
 {
     OicSecDoxm_t *doxm = NULL;
     uint8_t *cborPayload = (uint8_t *)OICCalloc(1, sizeof(uint8_t));
@@ -165,7 +176,7 @@ TEST(DoxmResourceTest, CBORPayloadToDoxmNULL)
     OICFree(cborPayload);
 }
 
-TEST(DoxmResourceTest, CBORPayloadToDoxmVALID)
+TEST_F(DOXM, CBORPayloadToDoxmVALID)
 {
     OicSecDoxm_t *doxm =  getBinDoxm();
     uint8_t *payload = NULL;
@@ -188,7 +199,7 @@ TEST(DoxmResourceTest, CBORPayloadToDoxmVALID)
 
 #if 0
 //HandleDoxmPostRequest Test
-TEST(HandleDoxmPostRequestTest, HandleDoxmPostRequestValidInput)
+TEST_F(HandleDoxmPostRequestTest, HandleDoxmPostRequestValidInput)
 {
     OCEntityHandlerRequest ehRequest = {};
     OCServerRequest svRequest = {};
diff --git a/resource/csdk/security/unittest/issuer/cert.der b/resource/csdk/security/unittest/issuer/cert.der
new file mode 100644 (file)
index 0000000..65ecf2d
Binary files /dev/null and b/resource/csdk/security/unittest/issuer/cert.der differ
diff --git a/resource/csdk/security/unittest/issuer/cert.pem b/resource/csdk/security/unittest/issuer/cert.pem
new file mode 100644 (file)
index 0000000..d28d4f8
--- /dev/null
@@ -0,0 +1,23 @@
+-----BEGIN CERTIFICATE-----
+MIID4zCCAsugAwIBAgIJAOFj4JMtVIPTMA0GCSqGSIb3DQEBCwUAMIGHMQswCQYD
+VQQGEwJVQTENMAsGA1UECAwES3lpdjENMAsGA1UEBwwES3lpdjEUMBIGA1UECgwL
+c2Ftc3VuZy5jb20xDzANBgNVBAsMBkFkU0VDTDEUMBIGA1UEAwwLc2Ftc3VuZy5j
+b20xHTAbBgkqhkiG9w0BCQEWDnJvb3RAbG9jYWxob3N0MB4XDTE5MDQxNzA5Mzcx
+MloXDTIwMDQxNjA5MzcxMlowgYcxCzAJBgNVBAYTAlVBMQ0wCwYDVQQIDARLeWl2
+MQ0wCwYDVQQHDARLeWl2MRQwEgYDVQQKDAtzYW1zdW5nLmNvbTEPMA0GA1UECwwG
+QWRTRUNMMRQwEgYDVQQDDAtzYW1zdW5nLmNvbTEdMBsGCSqGSIb3DQEJARYOcm9v
+dEBsb2NhbGhvc3QwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCjRRPC
+XYr7tCqE66oCA9bGmHDfIZTG4snV1TFHC0IPz06ygnHgtovU+f413BRa83LMMakk
+zc+qFNJf6R9oC+BRRklNeKxVjX5RBa+QY8aVq6O9wv9HyKot1vAedr9fqxsPjVo6
+lkU5O3RFcub8uDNy47j8KLYZJaKUno4NHXDK/gVwLEyIu/kaqdiaH+2ipN3oQ+dW
+8ui0+CPBuiln2eGKXza8IPXUUMspC3qna4/UoFrCJb7KN2IsMc3+P/pbbD336HyK
+zD8CvE8mFx1Xnnk3kX0TtuFBgtekhwXpOqIBl7Yw89ZntR5gEbvRlHyu6MKOF8iG
+d4bhJ7IohS+Wj8yZAgMBAAGjUDBOMB0GA1UdDgQWBBQrcOiaOMxgubcsyDVzTUN2
+f1rJsDAfBgNVHSMEGDAWgBQrcOiaOMxgubcsyDVzTUN2f1rJsDAMBgNVHRMEBTAD
+AQH/MA0GCSqGSIb3DQEBCwUAA4IBAQB65nTwCj6U5+nSyDmCb4EV5Z0bvG3g6zGV
+6psMQuov/MWYyABE2+UVgg9Tj0VaMD+1/lBt6+ennV0l8AxbyZupSN0EOnNm9JSW
+wDjX/i8svnracwGMnhyRTVTWg06yADoCf5dEr+eDHQjxmL/SxFUidR41LQxG59zF
+H0b+cGeJRhBzeSk4uXshXDbD7Tnti1Boc6c/gUwhQ6sBYwxfeoJyLccusNQ+5MdA
+e/K0SFX0bmvf8BlLvZPDXkeskKmCLywO+J8ku6YFbJ/3EHc18x4u0DhKtdjEnN7x
+zkTxk7AGGa9zIDRss4QkopxVqk6YNzYB/SMpEaKHeuNH0JMa9EQz
+-----END CERTIFICATE-----
diff --git a/resource/csdk/security/unittest/issuer/key.pem b/resource/csdk/security/unittest/issuer/key.pem
new file mode 100644 (file)
index 0000000..c6fe41e
--- /dev/null
@@ -0,0 +1,28 @@
+-----BEGIN PRIVATE KEY-----
+MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCjRRPCXYr7tCqE
+66oCA9bGmHDfIZTG4snV1TFHC0IPz06ygnHgtovU+f413BRa83LMMakkzc+qFNJf
+6R9oC+BRRklNeKxVjX5RBa+QY8aVq6O9wv9HyKot1vAedr9fqxsPjVo6lkU5O3RF
+cub8uDNy47j8KLYZJaKUno4NHXDK/gVwLEyIu/kaqdiaH+2ipN3oQ+dW8ui0+CPB
+uiln2eGKXza8IPXUUMspC3qna4/UoFrCJb7KN2IsMc3+P/pbbD336HyKzD8CvE8m
+Fx1Xnnk3kX0TtuFBgtekhwXpOqIBl7Yw89ZntR5gEbvRlHyu6MKOF8iGd4bhJ7Io
+hS+Wj8yZAgMBAAECggEAEnSMdzv7qdgDtmKtJO0qKeixWYeCObkI95LRryYmoYLd
+cnAsTypTRA++HHh0FJPQNiSm6fIZtzADV7QSSMCO6qD3SDqLwF/uF1p9LeUZXXG5
+YInaMVMNaYESQ19I4peEx41C1byGtqFx0yfZ1Fc9+Y6kKlyvuMf4SLRjejgJt+gw
+lCVg/BK83fjof56W7EkQOHJb8kweD7eZ02kqa3MoYHC8tedgK6uFSyPTVAQj9n1n
+xp1Q0b5i2BKRt3qlirLs0AFxGFhk9D4xfwu4FXWJeECq7xQkJOV3XsxE0X93J3re
+kVfvClIWu3NF3Ob0EOWi4DVGh1qsY6vWKjKYhBYDAQKBgQDUhBGHxoCGeAVGkPIQ
+yn5GyMo5PBrq0149S/+kkKlgjQv0kdmYk3TCk2wBKKFGRIybU/z+MPWwpKc09/bv
+JZdiZW1WczPGkgwAMN9qs1yGNFypyz+5Tsxf6Be2wIAjHdjl/J1yJB8IrK7BQslj
+qo93ZnGNvvKd38Grbd9lpOf4TQKBgQDErWtRJi5r+c3QxggJzsBr8X6BKGNQaN6v
+Vzb/+zZ0Je0RR3EtC2AlqKjtVitTJd66UK2/hnwk3Zvz6I21UtfqZk7go7VQvxgO
+6kFnZ4Tjm3X1kpaPlX2lexCiuf9PptrNkhvE8kTFD2C4wTf9GZPFs0FdusK1Fq2Q
+v9/AUEFLfQKBgCkOPqjBY5EW3MYOOIWf6RdZsR+vie+11+31obS0MdSySw37o1MD
+obn5axMqO0Xs9lEHv8eHw99VX+wuv2jiFUXwHFhoNyd0jZb32iGt9wECWqh+2Je/
+LmKU3wfyVo7yNDXyQKSNb+VoHva9JVT43XCOvP9KVWrEkJDC0Da9zga9AoGBALrb
+rJ8/sFEj19gnnZF73jNwEGmzro/B4vgh235e9UBqnA6TmsJaEXIWCNDc0nLAAxlu
+93SE2EPKTJXyd1gzqjHoG76vqt9ZfwkEpTkSEB6TIAI90FAAjox/HLIOFrRdaXpv
++3QlXRMAZjuCT6hm+Y+WnF7pxn14W1SwB2xWk4KdAoGANbJyi2+KB4ScGh+Z8+dg
+CviJb3S1OkKfucsnD1s3/dkoRri1ntfsCxroONWDj0JJqBH88gJRFaeVHmEAWgsk
+vx4SBQ6mY25rZuwHg4aucMULLogcYzggJUyaakPvKIjwy+4KVLdiee0ENVla+b6d
+lEo2O6h6NOydNdKSqvuNsME=
+-----END PRIVATE KEY-----
diff --git a/resource/csdk/security/unittest/occertutility.cpp b/resource/csdk/security/unittest/occertutility.cpp
new file mode 100644 (file)
index 0000000..83c7d76
--- /dev/null
@@ -0,0 +1,257 @@
+/******************************************************************
+*
+* Copyright 2019 Samsung Electronics All Rights Reserved.
+*
+*
+*
+* Licensed under the Apache License, Version 2.0 (the "License");
+* you may not use this file except in compliance with the License.
+* You may obtain a copy of the License at
+*
+*      http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License.
+*
+******************************************************************/
+#include <gtest/gtest.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#include "tools.h"
+#undef TAG
+#include "../src/occertutility.c"
+
+#ifdef __cplusplus
+}
+#endif
+
+#ifdef TAG
+#undef TAG
+#endif
+
+#define TAG  "CERTUTIL"
+
+#define SVR_DB_FILE_NAME TAG".dat"
+#define PM_DB_FILE_NAME TAG".db"
+
+#define CSR "resource/csdk/security/unittest/csr/csr.pem"
+#define ISSUER_CERT "resource/csdk/security/unittest/issuer/cert.pem"
+#define ISSUER_KEY "resource/csdk/security/unittest/issuer/key.pem"
+
+static const char* csr = NULL;
+static const char *issuerCert = NULL;
+static const char *issuerPrivateKey = NULL;
+static OicUuid_t *subjectUuid = NULL;
+static const char *subjectPublicKey = NULL;
+static const char *serial = NULL;
+static size_t serialLen = 0;
+static const char *authority = NULL;
+static const char *notValidBefore;
+static const char *notValidAfter;
+static const char *role;
+static const char *subject;
+
+class CERTUTIL : public ::testing::Test
+{
+    public:
+        static void SetUpTestCase()
+        {
+            try
+            {
+            ASSERT_EQ(0, readTextFile(CSR, &csr));
+            ASSERT_NE(nullptr, csr);
+            ASSERT_EQ(0, readTextFile(ISSUER_CERT, &issuerCert));
+            ASSERT_NE(nullptr, issuerCert);
+            ASSERT_EQ(0, readTextFile(ISSUER_KEY, &issuerPrivateKey));
+            ASSERT_NE(nullptr, issuerPrivateKey);
+
+            subjectUuid = (OicUuid_t*)OICCalloc(1, sizeof(OicUuid_t));
+            ASSERT_NE(nullptr, subjectUuid);
+
+            ASSERT_EQ(OC_STACK_OK, OCGetUuidFromCSR(csr, subjectUuid));
+            ASSERT_NE(nullptr, subjectUuid);
+
+            ASSERT_EQ(OC_STACK_OK, OCGetPublicKeyFromCSR(csr, (char**)&subjectPublicKey));
+            ASSERT_NE(nullptr, subjectPublicKey);
+
+            ASSERT_EQ(OC_STACK_OK, OCGenerateRandomSerialNumber((char**)&serial, &serialLen));
+
+            notValidBefore = "20190101235959";
+            notValidAfter = "20210101235959";
+            role = "1.3.6.1.4.1.44924.1.7";
+            subject = "33333333-3333-3333-3333-222222222222";
+            }
+            catch(std::exception& e)
+            {
+                std::cout << "SetUpTestCase exception: " << e.what() << std::endl;
+            }
+        }
+        static void TearDownTestCase()
+        {
+            OICFree((void*)serial);
+            OICFree((void*)subjectPublicKey);
+            OICFree(subjectUuid);
+            OICFree((void*)csr);
+            OICFree((void*)issuerCert);
+            OICFree((void*)issuerPrivateKey);
+        }
+};
+
+TEST_F(CERTUTIL, OCGenerateRandomSerialNumber)
+{
+    char* _serial = NULL;
+    size_t _serialLen = 0;
+    EXPECT_EQ(OC_STACK_OK, OCGenerateRandomSerialNumber(&_serial, &_serialLen));
+    EXPECT_TRUE(_serialLen > 0);
+    EXPECT_NE(nullptr, _serial);
+}
+
+TEST_F(CERTUTIL, OCGenerateKeyPair)
+{
+    char *publicKey = NULL;
+    size_t publicKeyLen = 0;
+    char *privateKey = NULL;
+    size_t privateKeyLen = 0;
+    EXPECT_EQ(OC_STACK_OK, OCGenerateKeyPair(&publicKey, &publicKeyLen, &privateKey, &privateKeyLen));
+    EXPECT_TRUE(publicKeyLen > 0);
+    EXPECT_NE(nullptr, publicKey);
+    EXPECT_TRUE(privateKeyLen > 0);
+    EXPECT_NE(nullptr, privateKey);
+}
+
+TEST_F(CERTUTIL, OCConvertDerCSRToPem)
+{
+    const char* derCSR = (const char*)certData();
+    size_t derCSRLen = certDataLen();
+    char* pemCSR = NULL;
+
+    EXPECT_EQ(OC_STACK_OK, OCConvertDerCSRToPem(derCSR, derCSRLen, &pemCSR));
+}
+
+
+TEST_F(CERTUTIL, CSR_ALL)
+{
+    char* key = NULL;
+
+    EXPECT_EQ(OC_STACK_OK, OCGetPublicKeyFromCSR(csr, &key));
+    EXPECT_NE(nullptr, key);
+
+    OicUuid_t* uuid = (OicUuid_t*)OICCalloc(1, sizeof(OicUuid_t));
+    EXPECT_EQ(OC_STACK_OK, OCGetUuidFromCSR(csr, uuid));
+    EXPECT_NE(nullptr, uuid);
+    OICFree(uuid);
+
+    EXPECT_EQ(OC_STACK_ERROR, OCVerifyCSRSignature(csr));
+}
+
+TEST_F(CERTUTIL, VerifyCSRSignature)
+{
+    mbedtls_x509_csr csrObj;
+
+    mbedtls_x509_csr_init(&csrObj);
+    EXPECT_EQ(0, mbedtls_x509_csr_parse(&csrObj, (const unsigned char*)csr, strlen(csr) + 1));
+
+    EXPECT_EQ(-1, VerifyCSRSignature(&csrObj));
+
+    csrObj.sig_md = MBEDTLS_MD_NONE;
+    EXPECT_EQ(-1, VerifyCSRSignature(&csrObj));
+    csrObj.sig_md = MBEDTLS_MD_SHA256;
+
+    uint8_t *p = csrObj.cri.p;
+    csrObj.cri.p = NULL;
+    EXPECT_EQ(-1, VerifyCSRSignature(&csrObj));
+    csrObj.cri.p = p;
+
+    p = csrObj.sig.p;
+    csrObj.sig.p = NULL;
+    EXPECT_EQ(-1, VerifyCSRSignature(&csrObj));
+    csrObj.sig.p = p;
+
+    mbedtls_x509_csr_free(&csrObj);
+}
+
+TEST_F(CERTUTIL, OCGenerateRoleCertificate)
+{
+    char *certificate = NULL;
+    size_t certificateLen = 0;
+
+    EXPECT_EQ(OC_STACK_INVALID_PARAM, OCGenerateRoleCertificate(
+        NULL, subjectPublicKey, issuerCert, issuerPrivateKey,
+        serial, notValidBefore, notValidAfter, role, authority,
+        &certificate, &certificateLen
+    ));
+
+    EXPECT_EQ(OC_STACK_INVALID_PARAM, OCGenerateRoleCertificate(
+        subjectUuid, subjectPublicKey, issuerCert, issuerPrivateKey,
+        serial, notValidBefore, notValidAfter, NULL, authority,
+        &certificate, &certificateLen
+    ));
+
+
+    EXPECT_EQ(OC_STACK_OK, OCGenerateRoleCertificate(
+        subjectUuid, subjectPublicKey, issuerCert, issuerPrivateKey,
+        serial, notValidBefore, notValidAfter, role, authority,
+        &certificate, &certificateLen
+    ));
+    ASSERT_NE(nullptr, certificate);
+    ASSERT_TRUE(certificateLen > 0);
+    OICFree(certificate);
+}
+
+TEST_F(CERTUTIL, OCGenerateIdentityCertificate)
+{
+    char *certificate = NULL;
+    size_t certificateLen = 0;
+
+    EXPECT_EQ(OC_STACK_INVALID_PARAM, OCGenerateIdentityCertificate(
+        subjectUuid, subjectPublicKey, NULL, issuerPrivateKey,
+        serial, notValidBefore, notValidAfter,
+        &certificate, &certificateLen
+    ));
+
+    EXPECT_EQ(OC_STACK_OK, OCGenerateIdentityCertificate(
+        subjectUuid, subjectPublicKey, issuerCert, issuerPrivateKey,
+        serial, notValidBefore, notValidAfter,
+        &certificate, &certificateLen
+    ));
+    ASSERT_NE(nullptr, certificate);
+    ASSERT_TRUE(certificateLen > 0);
+    OICFree(certificate);
+}
+
+TEST_F(CERTUTIL, OCGenerateIntermediateCACertificate)
+{
+    char *certificate = NULL;
+    size_t certificateLen = 0;
+
+    EXPECT_EQ(OC_STACK_OK, OCGenerateIntermediateCACertificate(
+        subject, subjectPublicKey, issuerCert, issuerPrivateKey,
+        serial, notValidBefore, notValidAfter,
+        &certificate, &certificateLen
+    ));
+    ASSERT_NE(nullptr, certificate);
+    ASSERT_TRUE(certificateLen > 0);
+    OICFree(certificate);
+}
+
+TEST_F(CERTUTIL, OCGenerateRootCACertificate)
+{
+    char *certificate = NULL;
+    size_t certificateLen = 0;
+
+    EXPECT_EQ(OC_STACK_OK, OCGenerateRootCACertificate(
+        subject, subjectPublicKey, issuerCert, issuerPrivateKey,
+        serial, notValidBefore, notValidAfter,
+        &certificate, &certificateLen
+    ));
+    ASSERT_NE(nullptr, certificate);
+    ASSERT_TRUE(certificateLen > 0);
+    OICFree(certificate);
+}
+
index 4ed4319..10cdeb0 100644 (file)
  *
  * *****************************************************************/
 #include <gtest/gtest.h>
-#include "ocsecurity.h"
-#include "octypes.h"
 
-using namespace std;
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#include "utlist.h"
+#include "tools.h"
+#undef TAG
+#include "../src/ocsecurity.c"
+
+#ifdef __cplusplus
+}
+#endif
+
+#ifdef TAG
+#undef TAG
+#endif
 
 #define TAG  "OC-SEC-UT"
 
+#define SVR_DB_FILE_NAME TAG".dat"
+#define PM_DB_FILE_NAME TAG".db"
+
+using namespace std;
+
+class OC_SEC_UT : public ::testing::Test
+{
+    public:
+        static void SetUpTestCase()
+        {
+            IOT_Init(PM_DB_FILE_NAME);
+        }
+        static void TearDownTestCase()
+        {
+            IOT_DeInit(PM_DB_FILE_NAME);
+        }
+};
+
 static void resultCallback (void* ctx, bool hasError)
 {
-    //dummy callback
-    (void) ctx;
-    (void) hasError;
+    OC_UNUSED(ctx);
+    OC_UNUSED(hasError);
+
+    OIC_LOG_V(INFO, TAG, "%s: has error: %d", __func__, hasError);
 }
 
-TEST(OCAssertRolesTest, InvalidDevAddr)
+TEST_F(OC_SEC_UT, OCAssertRolesTest)
 {
-    OCDevAddr* devAddr = NULL;
-    EXPECT_EQ(OC_STACK_INVALID_CALLBACK, OCAssertRoles(NULL, devAddr, resultCallback));
+    OCDevAddr* devAddr = setAddr("127.0.0.1", 4444, (OCTransportAdapter)CT_ADAPTER_IP);
+
+    EXPECT_EQ(OC_STACK_INVALID_CALLBACK, OCAssertRoles(NULL, devAddr, NULL));
+    EXPECT_EQ(OC_STACK_INCONSISTENT_DB, OCAssertRoles(NULL, devAddr, resultCallback));
+
+    OicSecCred_t *cred = getSignedAsymKeyCred();
+
+    OICFree(cred->credUsage);
+    cred->credUsage = (char*)OICCalloc(strlen(ROLE_CERT) + 1, 1);
+    strncpy(cred->credUsage, ROLE_CERT, strlen(ROLE_CERT));
+    AddCredential(cred);
+
+    EXPECT_EQ(OC_STACK_OK, OCAssertRoles(NULL, devAddr, resultCallback));
+    OICFree(devAddr);
+
+    devAddr = setAddr("::1", 4444, (OCTransportAdapter)CT_ADAPTER_IP);
+    devAddr->flags = (OCTransportFlags)(CT_FLAG_SECURE | CT_IP_USE_V6);
+    EXPECT_EQ(OC_STACK_OK, OCAssertRoles(NULL, devAddr, resultCallback));
+
+    devAddr->flags = (OCTransportFlags)(CT_FLAG_SECURE);
+    EXPECT_EQ(OC_STACK_ERROR, OCAssertRoles(NULL, devAddr, resultCallback));
+    OICFree(devAddr);
+
+    devAddr = setAddr("127.0.0.1", 4444, (OCTransportAdapter)CT_ADAPTER_TCP);
+    EXPECT_EQ(OC_STACK_OK, OCAssertRoles(NULL, devAddr, resultCallback));
+    OICFree(devAddr);
+
+    devAddr = setAddr("127.0.0.1", 4444, (OCTransportAdapter)CT_ADAPTER_GATT_BTLE);
+    EXPECT_EQ(OC_STACK_OK, OCAssertRoles(NULL, devAddr, resultCallback));
+    OICFree(devAddr);
+
+    devAddr = setAddr("127.0.0.1", 4444, (OCTransportAdapter)CT_ADAPTER_RFCOMM_BTEDR);
+    EXPECT_EQ(OC_STACK_ERROR, OCAssertRoles(NULL, devAddr, resultCallback));
+
+    devAddr->adapter = (OCTransportAdapter)CT_DEFAULT;
+    EXPECT_EQ(OC_STACK_ERROR, OCAssertRoles(NULL, devAddr, resultCallback));
+    OICFree(devAddr);
+
 }
 
-TEST(OCAssertRolesTest, InvalidCallback)
+TEST_F(OC_SEC_UT, OCAssertRolesCBHandler)
 {
-    OCDevAddr devAddr;
-    EXPECT_EQ(OC_STACK_INVALID_CALLBACK, OCAssertRoles(NULL, &devAddr, NULL));
+    OCClientResponse *response = NULL;
+
+    EXPECT_EQ(OC_STACK_DELETE_TRANSACTION, OCAssertRolesCBHandler(NULL, NULL, response));
+
+    response = (OCClientResponse *)OICCalloc(1, sizeof(*response));
+    response->payload = (OCPayload *)OCRepPayloadCreate();
+    response->payload->type = PAYLOAD_TYPE_REPRESENTATION;
+
+    AssertRolesData_t *assertRolesData = (AssertRolesData_t*)OICCalloc(1, sizeof(AssertRolesData_t));;
+    assertRolesData->ctx = NULL;
+    assertRolesData->resultCallback = resultCallback;
+
+    EXPECT_EQ(OC_STACK_DELETE_TRANSACTION, OCAssertRolesCBHandler((void*)assertRolesData, NULL, response));
 }
index 466aae5..324dc5a 100644 (file)
@@ -34,6 +34,17 @@ extern "C" {
 
 #define TAG  "OXM-PIN-UT"
 
+class OXMPIN : public ::testing::Test
+{
+    public:
+        static void SetUpTestCase()
+        {
+        }
+        static void TearDownTestCase()
+        {
+        }
+};
+
 static void OC_CALL inputPinCB(char* pin, size_t len)
 {
     if(NULL == pin || OXM_RANDOM_PIN_MIN_SIZE > len || len > OXM_RANDOM_PIN_MAX_SIZE)
@@ -106,50 +117,45 @@ static void OC_CALL closePinDisplayCB(void)
     OIC_LOG(INFO, TAG, "============================");
 }
 
-TEST(SetRandomPinPolicyTest, InvalidMinPinSize)
+TEST_F(OXMPIN, SetRandomPinPolicyTest1)
 {
     size_t pinSize = OXM_RANDOM_PIN_MIN_SIZE - 1;
     EXPECT_EQ(OC_STACK_INVALID_PARAM, SetRandomPinPolicy(pinSize, NUM_PIN));
 }
 
-TEST(SetRandomPinPolicyTest, InvalidMaxPinSize)
+TEST_F(OXMPIN, SetRandomPinPolicyTest2)
 {
     size_t pinSize = OXM_RANDOM_PIN_MAX_SIZE + 1;
     EXPECT_EQ(OC_STACK_INVALID_PARAM, SetRandomPinPolicy(pinSize, NUM_PIN));
 }
 
-TEST(SetRandomPinPolicyTest, InvalidPinType)
-{
-    EXPECT_EQ(OC_STACK_INVALID_PARAM, SetRandomPinPolicy(OXM_RANDOM_PIN_MIN_SIZE, (OicSecPinType_t)(NUM_PIN + 1)));
-}
-
-TEST(SetInputPinCBTest, InvalidCallback)
+TEST_F(OXMPIN, SetRandomPinPolicyTest3)
 {
-    SetInputPinCB(NULL);
+    EXPECT_EQ(OC_STACK_OK, SetRandomPinPolicy(OXM_RANDOM_PIN_MIN_SIZE, (OicSecPinType_t)(NUM_PIN + 1)));
 }
 
-TEST(SetInputPinCBTest, Full)
+TEST_F(OXMPIN, SetInputPinCBTest)
 {
     InputPinCallback callBack = inputPinCB;
     InputPinCallbackWithContext callBackWithCtx = inputPinWithCtxCB;
     g_inputPinCallbacks.contextCallback = callBackWithCtx;
+
+    SetInputPinCB(NULL);
     SetInputPinCB(callBack);
 
     g_inputPinCallbacks.contextCallback = NULL;
     SetInputPinCB(callBack);
 }
 
-TEST(SetInputPinWithContextCBTest, InvalidCallback)
-{
-    EXPECT_EQ(OC_STACK_INVALID_PARAM, SetInputPinWithContextCB(NULL, NULL));
-}
-
-TEST(SetInputPinWithContextCBTest, Full)
+TEST_F(OXMPIN, SetInputPinWithContextCBTest)
 {
     InputPinCallback callBack = inputPinCB;
     InputPinCallbackWithContext callBackWithCtx = inputPinWithCtxCB;
     g_inputPinCallbacks.callback = callBack;
     g_inputPinCallbacks.contextCallback = callBackWithCtx;
+
+    EXPECT_EQ(OC_STACK_INVALID_PARAM, SetInputPinWithContextCB(NULL, NULL));
+
     EXPECT_EQ(OC_STACK_DUPLICATE_REQUEST, SetInputPinWithContextCB(callBackWithCtx, NULL));
 
     g_inputPinCallbacks.callback = NULL;
@@ -157,7 +163,7 @@ TEST(SetInputPinWithContextCBTest, Full)
     EXPECT_EQ(OC_STACK_OK, SetInputPinWithContextCB(callBackWithCtx, NULL));
 }
 
-TEST(SetGeneratePinCBTest, Full)
+TEST_F(OXMPIN, SetGeneratePinCBTest)
 {
     SetGeneratePinCB(NULL);
 
@@ -172,7 +178,7 @@ TEST(SetGeneratePinCBTest, Full)
     SetGeneratePinCB(pinCB);
 }
 
-TEST(SetDisplayPinWithContextCBTest, Full)
+TEST_F(OXMPIN, SetDisplayPinWithContextCBTest)
 {
     EXPECT_EQ(OC_STACK_INVALID_PARAM, SetDisplayPinWithContextCB(NULL, NULL));
 
@@ -187,7 +193,7 @@ TEST(SetDisplayPinWithContextCBTest, Full)
     EXPECT_EQ(OC_STACK_OK, SetDisplayPinWithContextCB(ctxPinCB, NULL));
 }
 
-TEST(SetClosePinDisplayCBTest, Full)
+TEST_F(OXMPIN, SetClosePinDisplayCBTest)
 {
     SetClosePinDisplayCB(NULL);
 
@@ -199,22 +205,46 @@ TEST(SetClosePinDisplayCBTest, Full)
     SetClosePinDisplayCB(closeCB);
 }
 
-TEST(UnsetInputPinWithContextCBTest, Simple)
+TEST_F(OXMPIN, UnsetInputPinWithContextCBTest)
 {
     UnsetInputPinWithContextCB();
 }
 
-TEST(UnsetDisplayPinWithContextCBTest, Simple)
+TEST_F(OXMPIN, UnsetDisplayPinWithContextCBTest)
 {
     UnsetDisplayPinWithContextCB();
 }
 
-TEST(UnsetClosePinDisplayCBTest, Simple)
+TEST_F(OXMPIN, UnsetClosePinDisplayCBTest)
 {
     UnsetClosePinDisplayCB();
 }
 
-TEST(ClosePinDisplayTest, Simple)
+TEST_F(OXMPIN, ClosePinDisplayTest)
 {
     ClosePinDisplay();
 }
+
+TEST_F(OXMPIN, GetDtlsPskForRandomPinOxm)
+{
+    size_t len = 512;
+    unsigned char *result = (uint8_t*)OICCalloc(len, 1);
+    ASSERT_NE(nullptr, result);
+
+    EXPECT_EQ(GetDtlsPskForRandomPinOxm(CA_DTLS_PSK_KEY, NULL, 0, result, len), OWNER_PSK_LENGTH_128);
+    EXPECT_GT(GetDtlsPskForRandomPinOxm(CA_DTLS_PSK_HINT, NULL, 0, result, len), 0);
+    EXPECT_EQ(GetDtlsPskForRandomPinOxm((CADtlsPskCredType_t)3, NULL, 0, result, len), -1);
+
+    OICFree(result);
+}
+
+TEST_F(OXMPIN, GeneratePin)
+{
+    size_t len = 512;
+    char *result = (char*)OICCalloc(len, 1);
+    ASSERT_NE(nullptr, result);
+
+    EXPECT_EQ(OC_STACK_INVALID_PARAM, GeneratePin(NULL, 0));
+    EXPECT_EQ(OC_STACK_ERROR, GeneratePin(result, len));
+    OICFree(result);
+}
index eb0e5dd..3fb3b20 100644 (file)
@@ -64,5 +64,5 @@ TEST(VerifyOwnershipTransferTest, InvalidUserConfirmCB)
 {
     gUserConfirmContext.callback = NULL;
     gVerifyOption = (VerifyOptionBitmask_t)USER_CONFIRM;
-    EXPECT_EQ(OC_STACK_ERROR, VerifyOwnershipTransfer(NULL, (VerifyOptionBitmask_t)USER_CONFIRM));
+    EXPECT_EQ(OC_STACK_OK, VerifyOwnershipTransfer(NULL, (VerifyOptionBitmask_t)USER_CONFIRM));
 }
index f1b14ee..4027f87 100644 (file)
 #include <cinttypes>
 
 /*
- * Tests for the PBKDF2 implementation. 
- * There is a disabled test here that generates test vectors. Test vectors 
+ * Tests for the PBKDF2 implementation.
+ * There is a disabled test here that generates test vectors. Test vectors
  * for PBKDF2-HMAC-SHA256 are not generally available, so we created our own to
- * ensure consistency when changing the PBKDF2 implementation (initially based 
+ * ensure consistency when changing the PBKDF2 implementation (initially based
  * on tiny DTLS, now moving to mbedTLS).
  */
 
@@ -41,7 +41,7 @@ static void print_buffer(const char* label, const uint8_t* buffer, size_t len)
         printf(" NULL\n");
         return;
     }
-    
+
     printf("{");
     for (size_t i = 0; i < len - 1; i++)
     {
@@ -51,7 +51,7 @@ static void print_buffer(const char* label, const uint8_t* buffer, size_t len)
 
 }
 
-static void print_vector(const char* label, 
+static void print_vector(const char* label,
     const unsigned char* passwd, size_t pLen,
     const uint8_t* salt, const size_t saltLen,
     const size_t iterations,
@@ -118,9 +118,9 @@ TEST(PBKDF2Tests, DISABLED_CreateTestVectors)
 
 TEST(PBKDF2Tests, TestVector1)
 {
-    unsigned char passwd[8] = { 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38 };\r
-    uint8_t salt[16] = { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x00 };\r
-    size_t iterations = 1000;\r
+    unsigned char passwd[8] = { 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38 };
+    uint8_t salt[16] = { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x00 };
+    size_t iterations = 1000;
     uint8_t derivedKey[16] = { 0xB2, 0x1A, 0xA9, 0x99, 0x87, 0x40, 0xC1, 0x9E, 0x55, 0xD7, 0xFD, 0xED, 0xB2, 0x5C, 0xCE, 0x75 };
     uint8_t reDerivedKey[16] = {};
 
@@ -134,10 +134,10 @@ TEST(PBKDF2Tests, TestVector1)
 }
 
 TEST(PBKDF2Tests, TestVector2)
-{\r
-    unsigned char passwd[1] = { 0x31 };\r
-    uint8_t salt[1] = { 0x01 };\r
-    size_t iterations = 1;\r
+{
+    unsigned char passwd[1] = { 0x31 };
+    uint8_t salt[1] = { 0x01 };
+    size_t iterations = 1;
     uint8_t derivedKey[4] = { 0x20, 0xA3, 0x2A, 0x13 };
     uint8_t reDerivedKey[4] = {};
 
@@ -153,9 +153,9 @@ TEST(PBKDF2Tests, TestVector2)
 
 TEST(PBKDF2Tests, TestVector3)
 {
-    unsigned char passwd[8] = { 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38 };\r
-    uint8_t salt[16] = { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x00 };\r
-    size_t iterations = 1000;\r
+    unsigned char passwd[8] = { 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38 };
+    uint8_t salt[16] = { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x00 };
+    size_t iterations = 1000;
     uint8_t derivedKey[65] = { 0xB2, 0x1A, 0xA9, 0x99, 0x87, 0x40, 0xC1, 0x9E, 0x55, 0xD7, 0xFD, 0xED, 0xB2, 0x5C, 0xCE, 0x75, 0x2E, 0xA1, 0xA0, 0x43, 0x71, 0x0F, 0xE7, 0xD0, 0xF4, 0xF6, 0x79, 0x01, 0xB5, 0x47, 0x72, 0x20, 0xC0, 0x14, 0x25, 0x5E, 0x4B, 0xA7, 0x40, 0xEC, 0x6A, 0x29, 0x55, 0x0B, 0xDC, 0x2C, 0x10, 0x87, 0xD3, 0xE7, 0x4F, 0xF7, 0xD8, 0x55, 0x64, 0x95, 0xA8, 0x63, 0x6E, 0x64, 0x0E, 0x63, 0xE1, 0x8E, 0xC9 };
     uint8_t reDerivedKey[65] = {};
 
@@ -170,9 +170,9 @@ TEST(PBKDF2Tests, TestVector3)
 
 TEST(PBKDF2Tests, TestVector4)
 {
-    unsigned char passwd[8] = { 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38 };\r
-    uint8_t salt[48] = { 0x42, 0x42, 0x42, 0x42, 0x42, 0x42, 0x42, 0x42, 0x42, 0x42, 0x42, 0x42, 0x42, 0x42, 0x42, 0x42, 0x42, 0x42, 0x42, 0x42, 0x42, 0x42, 0x42, 0x42, 0x42, 0x42, 0x42, 0x42, 0x42, 0x42, 0x42, 0x42, 0x42, 0x42, 0x42, 0x42, 0x42, 0x42, 0x42, 0x42, 0x42, 0x42, 0x42, 0x42, 0x42, 0x42, 0x42, 0x42 };\r
-    size_t iterations = 1000;\r
+    unsigned char passwd[8] = { 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38 };
+    uint8_t salt[48] = { 0x42, 0x42, 0x42, 0x42, 0x42, 0x42, 0x42, 0x42, 0x42, 0x42, 0x42, 0x42, 0x42, 0x42, 0x42, 0x42, 0x42, 0x42, 0x42, 0x42, 0x42, 0x42, 0x42, 0x42, 0x42, 0x42, 0x42, 0x42, 0x42, 0x42, 0x42, 0x42, 0x42, 0x42, 0x42, 0x42, 0x42, 0x42, 0x42, 0x42, 0x42, 0x42, 0x42, 0x42, 0x42, 0x42, 0x42, 0x42 };
+    size_t iterations = 1000;
     uint8_t derivedKey[16] = { 0x14, 0x01, 0x5B, 0x8F, 0x23, 0x00, 0x57, 0x4F, 0x48, 0x7B, 0x0A, 0x85, 0x79, 0xFD, 0x3C, 0x31 };
     uint8_t reDerivedKey[16] = {};
 
@@ -187,8 +187,8 @@ TEST(PBKDF2Tests, TestVector4)
 
 TEST(PBKDF2Tests, TestVector5)
 {
-    unsigned char passwd[8] = { 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38 };\r
-    size_t iterations = 1000;\r
+    unsigned char passwd[8] = { 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38 };
+    size_t iterations = 1000;
     uint8_t derivedKey[16] = { 0x8D, 0x9B, 0x3E, 0x30, 0xED, 0x2C, 0x67, 0x8A, 0x58, 0x1A, 0x2D, 0x40, 0x7A, 0x47, 0xB4, 0x05 };
     uint8_t reDerivedKey[16] = {};
 
@@ -203,9 +203,9 @@ TEST(PBKDF2Tests, TestVector5)
 
 TEST(PBKDF2Tests, TestVector6)
 {
-    unsigned char passwd[48] = { 0x42, 0x42, 0x42, 0x42, 0x42, 0x42, 0x42, 0x42, 0x42, 0x42, 0x42, 0x42, 0x42, 0x42, 0x42, 0x42, 0x42, 0x42, 0x42, 0x42, 0x42, 0x42, 0x42, 0x42, 0x42, 0x42, 0x42, 0x42, 0x42, 0x42, 0x42, 0x42, 0x42, 0x42, 0x42, 0x42, 0x42, 0x42, 0x42, 0x42, 0x42, 0x42, 0x42, 0x42, 0x42, 0x42, 0x42, 0x42 };\r
-    uint8_t salt[16] = { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x00 };\r
-    size_t iterations = 1000;\r
+    unsigned char passwd[48] = { 0x42, 0x42, 0x42, 0x42, 0x42, 0x42, 0x42, 0x42, 0x42, 0x42, 0x42, 0x42, 0x42, 0x42, 0x42, 0x42, 0x42, 0x42, 0x42, 0x42, 0x42, 0x42, 0x42, 0x42, 0x42, 0x42, 0x42, 0x42, 0x42, 0x42, 0x42, 0x42, 0x42, 0x42, 0x42, 0x42, 0x42, 0x42, 0x42, 0x42, 0x42, 0x42, 0x42, 0x42, 0x42, 0x42, 0x42, 0x42 };
+    uint8_t salt[16] = { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x00 };
+    size_t iterations = 1000;
     uint8_t derivedKey[16] = { 0x03, 0xB4, 0x80, 0xEE, 0x1B, 0x2D, 0x55, 0xA8, 0x90, 0x88, 0xB5, 0xCE, 0x9F, 0x1C, 0x4E, 0x40 };
     uint8_t reDerivedKey[sizeof(derivedKey)] = {};
 
@@ -216,4 +216,16 @@ TEST(PBKDF2Tests, TestVector6)
 
     EXPECT_EQ(ret, 0);
     EXPECT_EQ(memcmp(derivedKey, reDerivedKey, sizeof(derivedKey)), 0);
-}
\ No newline at end of file
+}
+
+TEST(PBKDF2Tests, TestVector7)
+{
+    size_t keyLen = std::numeric_limits<size_t>::max();;
+    size_t iterations = 0;
+
+    EXPECT_EQ(-1, DeriveCryptoKeyFromPassword(NULL , 0, NULL, 0, iterations, keyLen, NULL));
+
+    iterations = keyLen;
+    keyLen = 10000;
+    EXPECT_EQ(-1,  DeriveCryptoKeyFromPassword(NULL , 0, NULL, 0, iterations, keyLen, NULL));
+}
diff --git a/resource/csdk/security/unittest/pkix_interface.cpp b/resource/csdk/security/unittest/pkix_interface.cpp
new file mode 100644 (file)
index 0000000..85074ef
--- /dev/null
@@ -0,0 +1,75 @@
+/******************************************************************
+*
+* Copyright 2019 Samsung Electronics All Rights Reserved.
+*
+*
+*
+* Licensed under the Apache License, Version 2.0 (the "License");
+* you may not use this file except in compliance with the License.
+* You may obtain a copy of the License at
+*
+*      http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License.
+*
+******************************************************************/
+#include <gtest/gtest.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#include "oic_malloc.h"
+#include "tools.h"
+#undef TAG
+#include "../src/pkix_interface.c"
+
+#ifdef __cplusplus
+}
+#endif
+
+#ifdef TAG
+#undef TAG
+#endif
+
+#define TAG  "PKIX"
+
+#define SVR_DB_FILE_NAME TAG".dat"
+#define PM_DB_FILE_NAME TAG".db"
+
+
+class PKIX : public ::testing::Test
+{
+    public:
+        static void SetUpTestCase()
+        {
+        }
+        static void TearDownTestCase()
+        {
+        }
+};
+
+TEST_F(PKIX, GetManufacturerPkixInfo)
+{
+    PkiInfo_t* inf = NULL;
+    bool list = false;
+
+    GetPkixInfo(inf);
+    GetManufacturerPkixInfo(inf);
+    InitManufacturerCipherSuiteList(&list, "33333333-3333-3333-3333-111111111111");
+
+    inf = (PkiInfo_t*)OICCalloc(1, sizeof(PkiInfo_t));
+    inf->key.data = keyData();
+    inf->key.len = keyDataLen();
+
+    GetPkixInfo(inf);
+    GetManufacturerPkixInfo(inf);
+
+    OICFree(inf->key.data);
+    OICFree(inf);
+}
+
index a9936dd..706e576 100644 (file)
-//******************************************************************
-//
-// Copyright 2015 Intel Mobile Communications GmbH All Rights Reserved.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-//      http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-
+/******************************************************************
+*
+* Copyright 2019 Samsung Electronics All Rights Reserved.
+*
+*
+*
+* Licensed under the Apache License, Version 2.0 (the "License");
+* you may not use this file except in compliance with the License.
+* You may obtain a copy of the License at
+*
+*      http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License.
+*
+******************************************************************/
 #include <gtest/gtest.h>
-#include "ocstack.h"
-#include "cainterface.h"
-#include "srmresourcestrings.h"
-
-using namespace std;
-
-#define PE_UT_TAG "\tPE-UT-message: "
 
 #ifdef __cplusplus
 extern "C" {
 #endif
 
-#include "policyengine.h"
-#include "experimental/doxmresource.h"
-
-// test parameters
-// PEContext_t g_peContext;
+#include "tools.h"
+#undef TAG
+#include "../src/policyengine.c"
 
 #ifdef __cplusplus
 }
 #endif
 
-OicUuid_t g_subjectIdA = {"SubjectA"};
-OicUuid_t g_subjectIdB = {"SubjectB"};
-OicUuid_t g_devOwner;
-char g_resource1[] = "Resource1";
-char g_resource2[] = "Resource2";
-
-extern OicSecDoxm_t *gDoxm;
-
-// These tests need to be rewritten; they do not cover internal ACE/request
-// logic.
-// See JIRA 1787 (https://jira.iotivity.org/browse/IOT-1787)
-
-//Policy Engine Core Tests
-// TEST(PolicyEngineCore, InitPolicyEngine)
-// {
-//     EXPECT_EQ(OC_STACK_OK, InitPolicyEngine(&g_peContext));
-// }
-
-// TODO - in order to unittest this we need InitDoxmResource() to put doxm
-// into Owned state with a known owner.  This will have to be done post v1.1.
-// TEST(PolicyEngineCore, CheckPermissionNoAcls)
-// {
-//     if(OC_STACK_OK == InitDoxmResource())
-//     {
-//         EXPECT_EQ(ACCESS_DENIED_SUBJECT_NOT_FOUND,
-//             CheckPermission(&g_peContext,
-//                             &g_subjectIdA,
-//                             g_resource1,
-//                             PERMISSION_READ));
-//     }
-//     else
-//     {
-//         printf("%s WARNING: InitDoxmResource() returned ERROR!\n", PE_UT_TAG);
-//     }
-// }
-
-// // TODO - in order to unittest this we need InitDoxmResource() to put doxm
-// // into Owned state with a known owner.  This will have to be done post v1.1.
-// TEST(PolicyEngineCore, CheckDevOwnerRequest)
-// {
-//     if(OC_STACK_OK == InitDoxmResource())
-//     {
-//         if(OC_STACK_OK == GetDoxmDevOwnerId(&g_devOwner))
-//         {
-//             printf("%s", PE_UT_TAG);
-//             for(int i = 0; i < UUID_LENGTH; i++)
-//             {
-//                 printf("%d", g_devOwner.id[i]);
-//             }
-//             printf("\n");
-//                 EXPECT_EQ(ACCESS_GRANTED,
-//                     CheckPermission(&g_peContext,
-//                         &g_devOwner,
-//                         g_resource1,
-//                         PERMISSION_FULL_CONTROL));
-//         }
-//         else
-//         {
-//             printf("%s WARNING: GetDoxmDevOwnerId() returned ERROR!\n", PE_UT_TAG);
-//         }
-//     }
-//     else
-//     {
-//         printf("%s WARNING: InitDoxmResource() returned ERROR!\n", PE_UT_TAG);
-//     }
-// }
-
-// TEST(PolicyEngineCore, DeInitPolicyEngine)
-// {
-//     DeInitPolicyEngine(&g_peContext);
-//     EXPECT_EQ(STOPPED, g_peContext.state);
-//     EXPECT_EQ((uint16_t)0, g_peContext.permission);
-//     EXPECT_EQ(ACCESS_DENIED_POLICY_ENGINE_ERROR, g_peContext.retVal);
-// }
+#ifdef TAG
+#undef TAG
+#endif
+
+#define TAG  "PE"
+
+#define SVR_DB_FILE_NAME TAG".dat"
+#define PM_DB_FILE_NAME TAG".db"
+
+
+class PE : public ::testing::Test
+{
+    public:
+        static void SetUpTestCase()
+        {
+        }
+        static void TearDownTestCase()
+        {
+        }
+};
+
+TEST_F(PE, IsRequestFromAms)
+{
+    SRMRequestContext_t *context = NULL;
+    EXPECT_FALSE(IsRequestFromAms(context));
+
+    context = (SRMRequestContext_t*)OICCalloc(1, sizeof(SRMRequestContext_t));
+    EXPECT_FALSE(IsRequestFromAms(context));
+
+    context->subjectIdType = SUBJECT_ID_TYPE_UUID;
+    EXPECT_FALSE(IsRequestFromAms(context));
+
+    ConvertStrToUuid("33333333-3333-3333-3333-222222222222", &context->subjectUuid);
+    EXPECT_FALSE(IsRequestFromAms(context));
+
+    OICFree(context);
+}
+
+TEST_F(PE, IsRequestFromCms)
+{
+    SRMRequestContext_t *context = NULL;
+    EXPECT_FALSE(IsRequestFromCms(context));
+
+    context = (SRMRequestContext_t*)OICCalloc(1, sizeof(SRMRequestContext_t));
+    EXPECT_FALSE(IsRequestFromCms(context));
+
+    context->subjectIdType = SUBJECT_ID_TYPE_UUID;
+    EXPECT_FALSE(IsRequestFromCms(context));
+
+    ConvertStrToUuid("33333333-3333-3333-3333-222222222222", &context->subjectUuid);
+    EXPECT_FALSE(IsRequestFromCms(context));
+
+    OICFree(context);
+}
+
index 2207c2d..c7febb5 100644 (file)
 #endif
 #include <gtest/gtest.h>
 
-#include "ocpayload.h"
-#include "ocstack.h"
-#include "oic_malloc.h"
-#include "cainterface.h"
-#include "resourcemanager.h"
-#include "secureresourcemanager.h"
-#include "pstatresource.h"
-#include "security_internals.h"
-
-// InitPstatResource Tests
-TEST(PstatResourceTest, InitPstatResource)
-{
-    EXPECT_EQ(OC_STACK_INVALID_PARAM, InitPstatResource());
-}
+#ifdef __cplusplus
+extern "C" {
+#endif
 
-// DeInitPstatResource Tests
-TEST(PstatResourceTest, DeInitPstatResource)
-{
-    EXPECT_EQ(OC_STACK_INVALID_PARAM, DeInitPstatResource());
+#include "tools.h"
+#undef TAG
+#include "../src/pstatresource.c"
+
+#ifdef __cplusplus
 }
+#endif
 
-//CreatePstatResource Tests
-TEST(PstatResourceTest, CreatePstatResource)
+#ifdef TAG
+#undef TAG
+#endif
+
+#define TAG  "PSTAT"
+
+#define SVR_DB_FILE_NAME TAG".dat"
+#define PM_DB_FILE_NAME TAG".db"
+
+class PSTAT : public ::testing::Test
 {
-    EXPECT_EQ(OC_STACK_INVALID_PARAM, CreatePstatResource());
-}
+    public:
+
+        static void SetUpTestCase()
+        {
+            IOT_Init(PM_DB_FILE_NAME);
+            EXPECT_EQ(OC_STACK_INVALID_PARAM, InitPstatResource());
+            EXPECT_EQ(OC_STACK_OK, CreatePstatResource());
+        }
+
+        static void TearDownTestCase()
+        {
+            IOT_DeInit(PM_DB_FILE_NAME);
+            EXPECT_EQ(OC_STACK_INVALID_PARAM, DeInitPstatResource());
+        }
+};
 
 //PstatEntityHandler Tests
-TEST(PstatResourceTest, PstatEntityHandlerWithDummyRequest)
+TEST_F(PSTAT, PstatEntityHandlerWithDummyRequest)
 {
     OCEntityHandlerRequest req = OCEntityHandlerRequest();
-    EXPECT_EQ(OC_EH_ERROR, PstatEntityHandler(OCEntityHandlerFlag::OC_REQUEST_FLAG, &req));
+    EXPECT_EQ(OC_EH_ERROR, PstatEntityHandler(OCEntityHandlerFlag::OC_REQUEST_FLAG, &req, NULL));
 }
 
-TEST(PstatResourceTest, PstatEntityHandlerWithPostRequest)
+TEST_F(PSTAT, PstatEntityHandlerWithPostRequest)
 {
     OicSecPstat_t *defaultPstat = (OicSecPstat_t *) OICCalloc(1, sizeof(*defaultPstat));
     ASSERT_TRUE(defaultPstat != NULL);
@@ -92,17 +104,17 @@ TEST(PstatResourceTest, PstatEntityHandlerWithPostRequest)
     OCEntityHandlerRequest req = OCEntityHandlerRequest();
     req.method = OC_REST_POST;
     req.payload = (OCPayload *) OCSecurityPayloadCreate(cbor, size);
-    EXPECT_EQ(OC_EH_ERROR, PstatEntityHandler(OCEntityHandlerFlag::OC_REQUEST_FLAG, &req));
+    EXPECT_EQ(OC_EH_ERROR, PstatEntityHandler(OCEntityHandlerFlag::OC_REQUEST_FLAG, &req, NULL));
     OICFree(cbor);
     OCPayloadDestroy(req.payload);
 }
 
-TEST(PstatResourceTest, PstatEntityHandlerInvalidRequest)
+TEST_F(PSTAT, PstatEntityHandlerInvalidRequest)
 {
-    EXPECT_EQ(OC_EH_ERROR, PstatEntityHandler(OCEntityHandlerFlag::OC_OBSERVE_FLAG, NULL));
+    EXPECT_EQ(OC_EH_ERROR, PstatEntityHandler(OCEntityHandlerFlag::OC_OBSERVE_FLAG, NULL, NULL));
 }
 
-TEST(PstatResourceTest, PstatToCBORPayloadNULL)
+TEST_F(PSTAT, PstatToCBORPayloadNULL)
 {
     EXPECT_EQ(OC_STACK_INVALID_PARAM, PstatToCBORPayload(NULL, NULL, 0));
     // Case when cbor payload is NULL
@@ -121,12 +133,12 @@ TEST(PstatResourceTest, PstatToCBORPayloadNULL)
     OICFree(cborPayload);
 }
 
-TEST(PstatResourceTest, CBORPayloadToPstat)
+TEST_F(PSTAT, CBORPayloadToPstat)
 {
     EXPECT_EQ(OC_STACK_INVALID_PARAM, CBORPayloadToPstat(NULL, 0, NULL));
 }
 
-TEST(PstatResourceTest, PstatToCBORPayloadAndCBORPayloadToPstat)
+TEST_F(PSTAT, PstatToCBORPayloadAndCBORPayloadToPstat)
 {
     OicSecPstat_t pstat;
     pstat.dos.state = DOS_RFNOP;
diff --git a/resource/csdk/security/unittest/rolesresource.cpp b/resource/csdk/security/unittest/rolesresource.cpp
new file mode 100644 (file)
index 0000000..2e34c44
--- /dev/null
@@ -0,0 +1,323 @@
+/******************************************************************
+*
+* Copyright 2019 Samsung Electronics All Rights Reserved.
+*
+*
+*
+* Licensed under the Apache License, Version 2.0 (the "License");
+* you may not use this file except in compliance with the License.
+* You may obtain a copy of the License at
+*
+*      http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License.
+*
+******************************************************************/
+#include <gtest/gtest.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#include "tools.h"
+#include "occertutility.h"
+#include "ocserverrequest.h"
+#undef TAG
+#include "../src/rolesresource.c"
+#undef TAG
+#undef UUID_LENGTH
+#include "../connectivity/src/adapter_util/ca_adapter_net_ssl.c"
+#ifdef __cplusplus
+}
+#endif
+
+#ifdef TAG
+#undef TAG
+#endif
+
+#define TAG  "RR"
+
+#define SVR_DB_FILE_NAME TAG".dat"
+#define PM_DB_FILE_NAME TAG".db"
+
+#define UUID_003 "44444442-4444-4444-5555-666666666666"
+
+#define ISSUER_CERT "resource/csdk/security/unittest/issuer/cert.pem"
+#define ISSUER_KEY "resource/csdk/security/unittest/issuer/key.pem"
+
+static CAEndpoint_t *endpoint = NULL;
+static mbedtls_pk_context keyPair;
+static uint8_t *pubKey = NULL;
+static size_t pubKeyLen = 0;
+static OicUuid_t *subjectUuid = NULL;
+static const char *issuerCert = NULL;
+static const char *issuerPrivateKey = NULL;
+static const char *publicKey = NULL;
+static RoleCertChain_t *roleCertChain = NULL;
+
+class RR : public ::testing::Test
+{
+    public:
+        static void SetUpTestCase()
+        {
+            IOT_Init(TAG);
+
+            endpoint = createEndpoint();
+            ASSERT_TRUE(AddSslPeer(endpoint, keyData(),keyDataLen()));
+
+            ASSERT_EQ(0, readTextFile(ISSUER_CERT, &issuerCert));
+            ASSERT_NE(nullptr, issuerCert);
+            ASSERT_EQ(0, readTextFile(ISSUER_KEY, &issuerPrivateKey));
+            ASSERT_NE(nullptr, issuerPrivateKey);
+
+            subjectUuid = createUuid();
+            ASSERT_NE(nullptr, subjectUuid);
+
+            mbedtls_pk_init(&keyPair);
+            EXPECT_GE(OCInternalGenerateKeyPair(&keyPair), 0);
+
+            int ret = 0;
+            size_t len = 1024;
+            uint8_t *buf = (uint8_t*)OICCalloc(len, 1);
+            ASSERT_NE(buf, nullptr);
+
+            ret = 0;
+            ret = mbedtls_pk_write_pubkey_der(&keyPair, buf, len);
+            ASSERT_GE(ret, 0);
+            pubKey = (uint8_t*)OICCalloc(ret, 1);
+            memcpy(pubKey, buf + len - ret, ret);
+            pubKeyLen = ret;
+
+            ret = 0;
+            ret = mbedtls_pk_write_pubkey_pem(&keyPair, buf, len);
+            ASSERT_EQ(ret, 0);
+            ret = (int)strlen((const char*)buf);
+            publicKey = (char*)OICCalloc(ret + 1, 1);
+            ASSERT_NE(publicKey, nullptr);
+            memcpy((char*)publicKey, buf, ret);
+/*
+            ret = 0;
+            ret = mbedtls_pk_write_key_pem(&keyPair, buf, len);
+            ASSERT_GE(ret, 0);
+            privateKey = (uint8_t*)OICCalloc(ret, 1);
+            ASSERT_NE(privateKey, nullptr);
+            memcpy(privateKey, buf, ret);
+*/
+            OICFree(buf);
+
+            const char *serial = NULL;
+            size_t serialLen = 0;
+            ASSERT_EQ(OC_STACK_OK,  OCGenerateRandomSerialNumber((char**)&serial, &serialLen));
+
+            roleCertChain = (RoleCertChain_t*)OICCalloc(1, sizeof(RoleCertChain_t));
+            roleCertChain->credId = rand();
+            roleCertChain->next = NULL;
+
+            EXPECT_EQ(OC_STACK_OK, OCGenerateRoleCertificate(
+                subjectUuid, publicKey, issuerCert, issuerPrivateKey,
+                serial, "20190101235959", "20210101235959", "1.3.6.1.4.1.44924.1.7", "samsung",
+                (char**)&roleCertChain->certificate.data, &roleCertChain->certificate.len
+            ));
+            ASSERT_NE(nullptr, roleCertChain->certificate.data);
+            ASSERT_TRUE(roleCertChain->certificate.len > 0);
+            roleCertChain->certificate.encoding = OIC_ENCODING_DER;
+        }
+        static void TearDownTestCase()
+        {
+            RmSslPeer(endpoint);
+            OICFree(subjectUuid);
+//            OICFree(privateKey);
+            OICFree((void*)pubKey);
+            OICFree((void*)publicKey);
+            mbedtls_pk_free(&keyPair);
+            IOT_DeInit(TAG);
+        }
+};
+
+extern SslContext_t* g_caSslContext;
+
+void RmSslPeer(const CAEndpoint_t* _endpoint)
+{
+    size_t listLength = u_arraylist_length(g_caSslContext->peerList);
+    for (size_t listIndex = 0; listIndex < listLength; listIndex++)
+    {
+        SslEndPoint_t * tep = (SslEndPoint_t *)u_arraylist_get(g_caSslContext->peerList, listIndex);
+        if (NULL == tep)
+        {
+            continue;
+        }
+        if(0 == strncmp(_endpoint->addr, tep->sep.endpoint.addr, MAX_ADDR_STR_SIZE_CA)
+                && (_endpoint->port == tep->sep.endpoint.port))
+        {
+            u_arraylist_remove(g_caSslContext->peerList, listIndex);
+            return;
+        }
+    }
+}
+
+bool AddSslPeer(const CAEndpoint_t* _endpoint, uint8_t *pk, size_t pklen)
+{
+    RmSslPeer(endpoint);
+    mbedtls_ssl_config * config = (_endpoint->adapter == CA_ADAPTER_IP ||
+                                   _endpoint->adapter == CA_ADAPTER_GATT_BTLE ?
+                                   &g_caSslContext->serverDtlsConf : &g_caSslContext->serverTlsConf);
+    SslEndPoint_t* peer = NewSslEndPoint(_endpoint, config);
+    if (NULL == peer)
+    {
+            OIC_LOG(ERROR, NET_SSL_TAG, "Malloc failed!");
+            return NULL;
+    }
+    memcpy(peer->sep.publicKey, pk, pklen);
+    peer->sep.publicKeyLength = pklen;
+
+    return u_arraylist_add(g_caSslContext->peerList, (void *) peer);
+}
+TEST_F(RR, AddRoleCertificate)
+{
+    EXPECT_EQ(OC_STACK_OK, AddRoleCertificate(roleCertChain, pubKey, pubKeyLen));
+    EXPECT_EQ(OC_STACK_OK, AddRoleCertificate(roleCertChain, pubKey, pubKeyLen));
+}
+
+TEST_F(RR, RegisterSymmetricCredentialRole)
+{
+    OicSecCred_t *cred = createCred();
+    EXPECT_EQ(OC_STACK_OK, RegisterSymmetricCredentialRole(cred));
+    ASSERT_EQ(OC_STACK_OK, RegisterSymmetricCredentialRole(cred));
+}
+
+TEST_F(RR, GetEndpointRoles)
+{
+    OicSecRole_t *roles = NULL;
+    size_t roleCount = 0;
+    EXPECT_EQ(OC_STACK_INVALID_PARAM, GetEndpointRoles(NULL, &roles, &roleCount));
+
+    OicSecCred_t *cred = getSignedAsymKeyCred();
+    OICFree(cred->credUsage);
+    cred->credUsage = (char*)OICCalloc(strlen(TRUST_CA) + 1, 1);
+    strcpy(cred->credUsage, TRUST_CA);
+    memset(cred->roleId.id, 0, ROLEID_LENGTH);
+    memset(cred->roleId.authority, 0, ROLEAUTHORITY_LENGTH);
+    EXPECT_EQ(OC_STACK_OK, AddCredential(cred));
+
+    cred = createCred();
+    memset(cred->roleId.id, 0, ROLEID_LENGTH);
+    memset(cred->roleId.authority, 0, ROLEAUTHORITY_LENGTH);
+    ASSERT_EQ(OC_STACK_OK, RegisterSymmetricCredentialRole(cred));
+
+    uint8_t *pk = NULL;
+    size_t pkLen = 0;
+    EXPECT_EQ(OC_STACK_OK, GetPeerPublicKeyFromEndpoint(endpoint, &pk, &pkLen));
+    EXPECT_EQ(OC_STACK_OK, AddRoleCertificate(roleCertChain, pk, pkLen));
+
+    EXPECT_EQ(OC_STACK_NO_MEMORY, GetEndpointRoles(endpoint, &roles, &roleCount));
+
+    CAEndpoint_t *endpointX = createEndpoint();
+    endpointX->port = 1111;
+    sprintf(endpointX->addr,"192.168.7.7");
+    EXPECT_EQ(OC_STACK_OK, GetEndpointRoles(endpointX, &roles, &roleCount));
+}
+
+static OCStackResult responseHandler(OCEntityHandlerResponse * ehResponse)
+{
+    OC_UNUSED(ehResponse);
+    OIC_LOG_V(DEBUG, TAG, "%s run", __func__);
+    return OC_STACK_OK;
+}
+
+TEST_F(RR, HandleGetRequest)
+{
+    OCServerRequest *srvReq = (OCServerRequest*)OICCalloc(1, sizeof(OCServerRequest));
+    srvReq->ehResponseHandler = responseHandler;
+    OCEntityHandlerRequest req = OCEntityHandlerRequest();
+    req.method = OC_REST_GET;
+    req.requestHandle = (OCRequestHandle) srvReq;
+    req.devAddr.port = endpoint->port;
+    strncpy(req.devAddr.addr, endpoint->addr, MAX_ADDR_STR_SIZE);
+    req.devAddr.flags = (OCTransportFlags)endpoint->flags;
+    req.devAddr.adapter = (OCTransportAdapter)endpoint->adapter;
+
+    EXPECT_EQ(OC_EH_OK, HandleGetRequest(&req));
+}
+
+TEST_F(RR, HandlePostRequest)
+{
+    OCServerRequest *srvReq = (OCServerRequest*)OICCalloc(1, sizeof(OCServerRequest));
+    srvReq->ehResponseHandler = responseHandler;
+    OCEntityHandlerRequest req = OCEntityHandlerRequest();
+    req.method = OC_REST_POST;
+    req.requestHandle = (OCRequestHandle) srvReq;
+    req.devAddr.port = endpoint->port;
+    strncpy(req.devAddr.addr, endpoint->addr, MAX_ADDR_STR_SIZE);
+    req.devAddr.flags = (OCTransportFlags)endpoint->flags;
+    req.devAddr.adapter = (OCTransportAdapter)endpoint->adapter;
+
+    uint8_t *payload = NULL;
+    size_t size = 0;
+
+    ASSERT_EQ(OC_STACK_OK, RolesToCBORPayload(roleCertChain, &payload, &size));
+    OCSecurityPayload *securityPayload = OCSecurityPayloadCreate(payload, size);
+    ASSERT_TRUE(NULL != securityPayload);
+    req.payload = (OCPayload *) securityPayload;
+
+    EXPECT_EQ(OC_EH_OK, HandlePostRequest(&req));
+}
+
+TEST_F(RR, HandleDeleteRequest)
+{
+    OCServerRequest *srvReq = (OCServerRequest*)OICCalloc(1, sizeof(OCServerRequest));
+    srvReq->ehResponseHandler = responseHandler;
+    OCEntityHandlerRequest req = OCEntityHandlerRequest();
+    req.method = OC_REST_POST;
+    req.requestHandle = (OCRequestHandle) srvReq;
+    req.devAddr.port = endpoint->port;
+    strncpy(req.devAddr.addr, endpoint->addr, MAX_ADDR_STR_SIZE);
+    req.devAddr.flags = (OCTransportFlags)endpoint->flags;
+    req.devAddr.adapter = (OCTransportAdapter)endpoint->adapter;
+    req.query = (char*)OICCalloc(512, 1);
+    snprintf(req.query, 512, "%s=3322", OIC_JSON_CREDID_NAME);
+
+    uint8_t *pk = NULL;
+    size_t pkLen = 0;
+    EXPECT_EQ(OC_STACK_OK, GetPeerPublicKey(&req.devAddr, &pk, &pkLen));
+    EXPECT_EQ(OC_STACK_OK, AddRoleCertificate(roleCertChain, pk, pkLen));
+    EXPECT_EQ(OC_EH_OK, HandleDeleteRequest(&req));
+}
+
+
+TEST_F(RR, IsBefore)
+{
+    struct tm before;
+    struct tm after;
+
+    memset(&before, 0, sizeof(struct tm));
+    memset(&after, 0, sizeof(struct tm));
+
+    EXPECT_FALSE(IsBefore(&before, &after));
+}
+
+TEST_F(RR, RolesEntityHandler)
+{
+    OCEntityHandlerFlag flag = OC_REQUEST_FLAG;
+    OCEntityHandlerRequest req = OCEntityHandlerRequest();
+    req.method = OC_REST_POST;
+
+    EXPECT_EQ(OC_EH_ERROR, RolesEntityHandler(flag, NULL, NULL));
+    EXPECT_EQ(OC_EH_ERROR, RolesEntityHandler(flag, &req, NULL));
+    req.method = OC_REST_GET;
+    EXPECT_EQ(OC_EH_ERROR, RolesEntityHandler(flag, &req, NULL));
+    req.method = OC_REST_DELETE;
+    EXPECT_EQ(OC_EH_ERROR, RolesEntityHandler(flag, &req, NULL));
+    req.method = OC_REST_NOMETHOD;
+    EXPECT_EQ(OC_EH_ERROR, RolesEntityHandler(flag, &req, NULL));
+}
+
+TEST_F(RR, DeleteRolesCB)
+{
+    SetDoxmIsOwned(true);
+    DeleteRolesCB(NULL, 0);
+}
+
index 36d067f..f36c31f 100644 (file)
 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
 
 #include <gtest/gtest.h>
-#include "ocpayload.h"
-#include "ocstack.h"
-#include "oic_malloc.h"
-#include "oic_string.h"
-#include "resourcemanager.h"
-#include "spresource.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
 #include "srmtestcommon.h"
-#include "srmutility.h"
-#include "psinterface.h"
-#include "security_internals.h"
-#include "experimental/logger.h"
+#include "tools.h"
+#include "ocserverrequest.h"
+#undef TAG
+#include "../src/spresource.c"
+
+#ifdef __cplusplus
+}
+#endif
+
+#ifdef TAG
+#undef TAG
+#endif
 
 #define TAG "SRM-SP-UT"
 
-// helper fxns
-static void TestEncodeDecode(OicSecSp_t* spToTest, bool* propsToTest, bool checkForValidSp);
-static void TestInit(OicSecSp_t* testSp, bool* spProps);
+#define SVR_DB_FILE_NAME TAG".dat"
+#define PM_DB_FILE_NAME TAG".db"
+
+static CAEndpoint_t *endpoint = NULL;
+
+class SP : public ::testing::Test
+{
+    public:
+        static void SetUpTestCase()
+        {
+            IOT_Init(PM_DB_FILE_NAME);
+            endpoint = createEndpoint();
+        }
+
+        static void TearDownTestCase()
+        {
+            IOT_DeInit(PM_DB_FILE_NAME);
+        }
+};
 
 //*****************************************************************************
 // Test data
@@ -53,12 +76,65 @@ static OicSecSp_t s_testSp =
     NULL,                   // currentProfile
 };
 
+//*****************************************************************************
+// Helper fxns
+//*****************************************************************************
+static void TestEncodeDecode(OicSecSp_t* spToTest, bool* propsToTest, bool checkForValidSp)
+{
+    OCStackResult ret = OC_STACK_OK;
+
+    uint8_t *cborPayload = NULL;
+    size_t cborSize = 0;
+    OicSecSp_t *spDecoded = NULL;
+    bool decodedProperties[SP_PROPERTY_COUNT];
+
+    // encode
+    ret = SpToCBORPayloadPartial(spToTest, &cborPayload, &cborSize, propsToTest);
+    EXPECT_TRUE(OC_STACK_OK == ret);
+    VERIFY_OR_LOG_AND_EXIT(TAG, (OC_STACK_OK == ret), "Failed to encode sp", ERROR);
+
+    // decode
+    ret = CBORPayloadToSp(cborPayload, cborSize, &spDecoded, decodedProperties);
+    EXPECT_TRUE(OC_STACK_OK == ret);
+    VERIFY_OR_LOG_AND_EXIT(TAG, (OC_STACK_OK == ret), "Failed to decode sp", ERROR);
+
+    if ( checkForValidSp )
+    {
+        EXPECT_TRUE(true==RequiredSpPropsPresentAndValid(spDecoded, decodedProperties));
+    }
+
+    // compare
+    EXPECT_TRUE(true == IsPropArraySame(propsToTest, decodedProperties));
+    EXPECT_TRUE(true == IsSpSame(&s_testSp, spDecoded, propsToTest));
+
+exit:
+    OICFree(cborPayload);
+    DeleteSpBinData(spDecoded);
+    OICFree(spDecoded);
+}
+
+
+// can pass in spProps = NULL;
+static void TestInit(OicSecSp_t* testSp, bool* spProps)
+{
+    testSp->supportedLen = 0;
+    testSp->currentProfile = NULL;
+
+    for (size_t i = 0; i < sizeof(s_profileArray)/sizeof(s_profileArray[0]); i++)
+    {
+        testSp->supportedProfiles[i] = NULL;
+    }
+    if (spProps != NULL)
+    {
+        SetAllSpProps(spProps, false);
+    }
+}
 
 //*****************************************************************************
 // Tests
 //*****************************************************************************
 
-TEST(SPResourceTest, CBORFullEncodingPositive)
+TEST_F(SP, CBORFullEncodingPositive)
 {
     bool propsToTest[SP_PROPERTY_COUNT];
 
@@ -91,7 +167,7 @@ TEST(SPResourceTest, CBORFullEncodingPositive)
     TestEncodeDecode(&s_testSp, propsToTest, true);
 }
 
-TEST(SPResourceTest, CBORPartialEncodingPositive)
+TEST_F(SP, CBORPartialEncodingPositive)
 {
     bool propsToTest[SP_PROPERTY_COUNT];
 
@@ -119,65 +195,56 @@ TEST(SPResourceTest, CBORPartialEncodingPositive)
     TestEncodeDecode(&s_testSp, propsToTest, false);
 }
 
-// TODO: in order of priority
-// * GetRequestPositive
-// * PostRequestPositive
-// * GetRequestGetNegative
-// * GetRequestPostNegative
-// * CBORFullEncodingNegative
-// * CBORPartialEncodingNegative
-
-//*****************************************************************************
-// Helper fxns
-//*****************************************************************************
-
-static void TestEncodeDecode(OicSecSp_t* spToTest, bool* propsToTest, bool checkForValidSp)
+TEST_F(SP, ValidateQuery)
 {
-    OCStackResult ret = OC_STACK_OK;
-
-    uint8_t *cborPayload = NULL;
-    size_t cborSize = 0;
-    OicSecSp_t *spDecoded = NULL;
-    bool decodedProperties[SP_PROPERTY_COUNT];
-
-    // encode
-    ret = SpToCBORPayloadPartial(spToTest, &cborPayload, &cborSize, propsToTest);
-    EXPECT_TRUE(OC_STACK_OK == ret);
-    VERIFY_OR_LOG_AND_EXIT(TAG, (OC_STACK_OK == ret), "Failed to encode sp", ERROR);
-
-    // decode
-    ret = CBORPayloadToSp(cborPayload, cborSize, &spDecoded, decodedProperties);
-    EXPECT_TRUE(OC_STACK_OK == ret);
-    VERIFY_OR_LOG_AND_EXIT(TAG, (OC_STACK_OK == ret), "Failed to decode sp", ERROR);
-
-    if ( checkForValidSp )
-    {
-        EXPECT_TRUE(true==RequiredSpPropsPresentAndValid(spDecoded, decodedProperties));
-    }
-
-    // compare
-    EXPECT_TRUE(true == IsPropArraySame(propsToTest, decodedProperties));
-    EXPECT_TRUE(true == IsSpSame(&s_testSp, spDecoded, propsToTest));
+    EXPECT_TRUE(ValidateQuery("q=35"));
+    EXPECT_FALSE(ValidateQuery("if=eth0"));
+}
 
-exit:
-    OICFree(cborPayload);
-    DeleteSpBinData(spDecoded);
-    OICFree(spDecoded);
+static OCStackResult responseHandler(OCEntityHandlerResponse * ehResponse)
+{
+    OC_UNUSED(ehResponse);
+    OIC_LOG_V(DEBUG, TAG, "%s run", __func__);
+    return OC_STACK_OK;
 }
 
-// can pass in spProps = NULL;
-static void TestInit(OicSecSp_t* testSp, bool* spProps)
+TEST_F(SP, HandleSpGetRequest)
 {
-    testSp->supportedLen = 0;
-    testSp->currentProfile = NULL;
+    OCServerRequest *srvReq = (OCServerRequest*)OICCalloc(1, sizeof(OCServerRequest));
+    srvReq->ehResponseHandler = responseHandler;
+    OCEntityHandlerRequest req = OCEntityHandlerRequest();
+    req.method = OC_REST_GET;
+    req.requestHandle = (OCRequestHandle) srvReq;
+    req.devAddr.port = endpoint->port;
+    strncpy(req.devAddr.addr, endpoint->addr, MAX_ADDR_STR_SIZE);
+    req.devAddr.flags = (OCTransportFlags)endpoint->flags;
+    req.devAddr.adapter = (OCTransportAdapter)endpoint->adapter;
+    req.query = (char*)OICCalloc(256, 1);
+    strncpy(req.query, "coaps://127.0.0.1:3333/?if=eth0", 256);
+
+    EXPECT_EQ(OC_EH_OK, HandleSpGetRequest(&req));
+}
 
-    for (size_t i = 0; i < sizeof(s_profileArray)/sizeof(s_profileArray[0]); i++)
-    {
-        testSp->supportedProfiles[i] = NULL;
-    }
-    if (spProps != NULL)
-    {
-        SetAllSpProps(spProps, false);
-    }
+TEST_F(SP, HandleSpPostRequest)
+{
+    OCServerRequest *srvReq = (OCServerRequest*)OICCalloc(1, sizeof(OCServerRequest));
+    srvReq->ehResponseHandler = responseHandler;
+    OCEntityHandlerRequest req = OCEntityHandlerRequest();
+    req.method = OC_REST_POST;
+    req.requestHandle = (OCRequestHandle) srvReq;
+    req.devAddr.port = endpoint->port;
+    strncpy(req.devAddr.addr, endpoint->addr, MAX_ADDR_STR_SIZE);
+    req.devAddr.flags = (OCTransportFlags)endpoint->flags;
+    req.devAddr.adapter = (OCTransportAdapter)endpoint->adapter;
+
+    uint8_t *payload = NULL;
+    size_t size = 0;
+    OicSecSp_t *sp = &gDefaultSp;//(OicSecSp_t*)OICCalloc(1, sizeof(OicSecSp_t));
+    ASSERT_EQ(OC_STACK_OK, SpToCBORPayload(sp, &payload, &size));
+    OCSecurityPayload *securityPayload = OCSecurityPayloadCreate(payload, size);
+    ASSERT_TRUE(NULL != securityPayload);
+    req.payload = (OCPayload *) securityPayload;
+
+    EXPECT_EQ(OC_EH_OK, HandleSpPostRequest(&req));
 }
 
index f6ee09a..1f5cb32 100644 (file)
@@ -73,8 +73,8 @@ bool ReadCBORFile(const char* filename, const char* rsrcname, uint8_t **payload,
     size_t size = 0;
 
 #ifdef _MSC_VER
-// The path SECURITY_BUILD_UNITTEST_DIR can contain '\u' which VS misinterprets as a universal 
-// character name in the STRINGIZE macro and outputs warning C4429 'possible incomplete or 
+// The path SECURITY_BUILD_UNITTEST_DIR can contain '\u' which VS misinterprets as a universal
+// character name in the STRINGIZE macro and outputs warning C4429 'possible incomplete or
 // improperly formed universal-character-name' https://msdn.microsoft.com/en-us/library/z78hwa6k.aspx
 #pragma warning(push)
 #pragma warning(disable:4429)
@@ -155,20 +155,3 @@ bool ReadCBORFile(const char* filename, const char* rsrcname, uint8_t **payload,
     return status;
 }
 
-void SetPersistentHandler(OCPersistentStorage *ps, bool set)
-{
-    if (set)
-    {
-        ps->open = fopen;
-        ps->read = fread;
-        ps->write = fwrite;
-        ps->close = fclose;
-        ps->unlink = remove;
-    }
-    else
-    {
-        memset(ps, 0, sizeof(OCPersistentStorage));
-    }
-    EXPECT_EQ(OC_STACK_OK,
-            OCRegisterPersistentStorageHandler(ps));
-}
index 8b81e91..b221f4e 100644 (file)
@@ -21,6 +21,8 @@
 #ifndef IOTVT_SRM_TEST_COMMON_H
 #define IOTVT_SRM_TEST_COMMON_H
 
+#include "octypes.h"
+
 char* ReadFileToBuffer(const char* filename);
 bool ReadCBORFile(const char* filename, const char* rsrcName, uint8_t **payload, size_t *size);
 void SetPersistentHandler(OCPersistentStorage *ps, bool set);
index 8488cc4..dc707f1 100644 (file)
@@ -74,7 +74,9 @@ TEST(ConvertStrToUuidTest, LowCase)
 
     const char *uuidString1 = "ca5bfba0-c0f1-4906-b995-f139d626dfbd";
     EXPECT_EQ(OC_STACK_OK, ConvertStrToUuid(uuidString1, &uuid));
-
+#ifndef NDEBUG
+    LogUuid(&uuid);
+#endif //NDEBUG
     EXPECT_EQ((uint8_t)0xca, uuid.id[0]);
     EXPECT_EQ((uint8_t)0x5b, uuid.id[1]);
     EXPECT_EQ((uint8_t)0xfb, uuid.id[2]);
@@ -180,3 +182,10 @@ TEST(SetUuidSeedTest, ValidValue)
     EXPECT_EQ(OC_STACK_OK, SetDeviceIdSeed(seed, sizeof(seed)));
 }
 #endif
+
+TEST(GetOxmString, Full)
+{
+    EXPECT_TRUE("oic.sec.doxm.jw" == std::string(GetOxmString(OIC_JUST_WORKS)));
+    EXPECT_TRUE("oic.sec.doxm.rdp" == std::string(GetOxmString(OIC_RANDOM_DEVICE_PIN)));
+    EXPECT_TRUE("oic.sec.doxm.mfgcert" == std::string(GetOxmString(OIC_MANUFACTURER_CERTIFICATE)));
+}
diff --git a/resource/csdk/security/unittest/ssl/0-root-cert.der b/resource/csdk/security/unittest/ssl/0-root-cert.der
new file mode 100644 (file)
index 0000000..31568a8
Binary files /dev/null and b/resource/csdk/security/unittest/ssl/0-root-cert.der differ
diff --git a/resource/csdk/security/unittest/ssl/1-subca-cert.der b/resource/csdk/security/unittest/ssl/1-subca-cert.der
new file mode 100644 (file)
index 0000000..bacc8d2
Binary files /dev/null and b/resource/csdk/security/unittest/ssl/1-subca-cert.der differ
diff --git a/resource/csdk/security/unittest/ssl/33333333-3333-3333-3333-111111111111_cert.der b/resource/csdk/security/unittest/ssl/33333333-3333-3333-3333-111111111111_cert.der
new file mode 100644 (file)
index 0000000..48d7bdc
Binary files /dev/null and b/resource/csdk/security/unittest/ssl/33333333-3333-3333-3333-111111111111_cert.der differ
diff --git a/resource/csdk/security/unittest/ssl/33333333-3333-3333-3333-111111111111_key.der b/resource/csdk/security/unittest/ssl/33333333-3333-3333-3333-111111111111_key.der
new file mode 100644 (file)
index 0000000..a429d96
Binary files /dev/null and b/resource/csdk/security/unittest/ssl/33333333-3333-3333-3333-111111111111_key.der differ
diff --git a/resource/csdk/security/unittest/ssl/33333333-3333-3333-3333-111111111112_cert.der b/resource/csdk/security/unittest/ssl/33333333-3333-3333-3333-111111111112_cert.der
new file mode 100644 (file)
index 0000000..dc908ca
Binary files /dev/null and b/resource/csdk/security/unittest/ssl/33333333-3333-3333-3333-111111111112_cert.der differ
diff --git a/resource/csdk/security/unittest/ssl/33333333-3333-3333-3333-111111111112_key.der b/resource/csdk/security/unittest/ssl/33333333-3333-3333-3333-111111111112_key.der
new file mode 100644 (file)
index 0000000..3f69425
Binary files /dev/null and b/resource/csdk/security/unittest/ssl/33333333-3333-3333-3333-111111111112_key.der differ
diff --git a/resource/csdk/security/unittest/ssl/sample.pem.der b/resource/csdk/security/unittest/ssl/sample.pem.der
new file mode 100644 (file)
index 0000000..44fda9f
Binary files /dev/null and b/resource/csdk/security/unittest/ssl/sample.pem.der differ
diff --git a/resource/csdk/security/unittest/tools.cpp b/resource/csdk/security/unittest/tools.cpp
new file mode 100644 (file)
index 0000000..e666090
--- /dev/null
@@ -0,0 +1,813 @@
+/* *****************************************************************
+ *
+ * Copyright 2019 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ * *****************************************************************/
+#include <stdio.h>
+#include <stdlib.h>
+#if defined(__unix__)
+#include <dirent.h>
+#include <sys/stat.h>
+#include <fcntl.h>
+#else // __unix__
+#include <string>
+#include <iostream>
+#include <fstream>
+#include <filesystem>
+#endif // __unix__
+#include <gtest/gtest.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#include "octhread.h"
+#include "srmutility.h"
+#include "tools.h"
+#include "oic_malloc.h"
+#include "srmresourcestrings.h"
+#include "logger.h"
+#include "oic_string.h"
+#include "ocprovisioningmanager.h"
+#include "utlist.h"
+#include "credresource.h"
+#include "srmresourcestrings.c"
+
+#ifdef __cplusplus
+}
+#endif
+
+#ifndef TAG
+#define TAG "LIB_UNITTEST"
+#endif
+
+#if ! defined( CERT_DIR )
+#define CERT_DIR "resource/csdk/security/unittest/ssl"
+#endif
+
+OicSecDoxm_t *createDoxm()
+{
+    OicSecDoxm_t *doxm = (OicSecDoxm_t *)OICMalloc(sizeof(OicSecDoxm_t));
+    if (NULL == doxm)
+    {
+        return NULL;
+    }
+    doxm->oxmLen     = 1;
+    doxm->oxm        = (OicSecOxm_t *)OICCalloc(doxm->oxmLen, sizeof(OicSecOxm_t));
+    doxm->oxm[0]     = OIC_JUST_WORKS;
+    doxm->oxmSel     = OIC_JUST_WORKS;
+    doxm->sct        = SYMMETRIC_PAIR_WISE_KEY;
+    doxm->owned      = true;
+    ConvertStrToUuid("33333333-3333-3333-3333-111111111111", &doxm->deviceID);
+    ConvertStrToUuid("33333333-3333-3333-3333-222222222222", &doxm->owner);
+    return doxm;
+}
+
+void freeDoxm(OicSecDoxm_t *doxm)
+{
+    if (NULL == doxm)
+    {
+        return;
+    }
+    OICFree(doxm->oxm);
+    OICFree(doxm);
+}
+
+OCDevAddr *setAddr(const char *ip, uint16_t port, OCTransportAdapter adapter)
+{
+    OCDevAddr *a = (OCDevAddr *)OICCalloc(1, sizeof(OCDevAddr));
+    strcpy(a->addr, ip);
+    a->port = port;
+    a->adapter = adapter;
+    a->flags = (OCTransportFlags)(CT_FLAG_SECURE | CT_IP_USE_V4);
+    return a;
+}
+
+OCProvisionDev_t *createProvisionDev()
+{
+    OCProvisionDev_t *pd  = (OCProvisionDev_t *)OICCalloc(1, sizeof(OCProvisionDev_t));
+    strcpy(pd->endpoint.addr, "127.0.0.1");
+    pd->endpoint.port = 9999;
+    pd->endpoint.adapter = OC_ADAPTER_IP;
+    pd->pstat = (OicSecPstat_t *)OICCalloc(1, sizeof(OicSecPstat_t));
+    pd->doxm = createDoxm();
+    pd->connType = (OCConnectivityType)(CT_ADAPTER_IP | CT_FLAG_SECURE | CT_IP_USE_V4);
+    pd->securePort = 1023;
+#ifdef WITH_TCP
+    pd->tcpPort = 0;
+    pd->tcpSecurePort = 0;
+#endif
+    OICStrcpy(pd->specVer, SPEC_MAX_VER_LEN, "res.2.0.0");
+    pd->devStatus = DEV_STATUS_ON;
+    pd->handle = NULL;
+    pd->ownerAclUnauthorizedRequest = false;
+    pd->next = NULL;
+    return pd;
+}
+
+void freeProvisionDev(OCProvisionDev_t *pd)
+{
+    if (NULL == pd)
+    {
+        return;
+    }
+    OICFree(pd->pstat);
+    freeDoxm(pd->doxm);
+    OICFree(pd);
+}
+
+static void provisionResultCB(void *ctx, size_t nOfRes, OCProvisionResult_t *arr, bool hasError)
+{
+    OC_UNUSED(ctx);
+    OC_UNUSED(nOfRes);
+    OC_UNUSED(arr);
+    OC_UNUSED(hasError);
+    OIC_LOG_V(DEBUG, TAG, "%s: %d", __func__, hasError);
+}
+
+OTMContext_t *createOTMContext()
+{
+    OTMContext_t *otmCtx = (OTMContext_t *)OICCalloc(1, sizeof(OTMContext_t));
+    otmCtx->selectedDeviceInfo = createProvisionDev();
+    otmCtx->ctxResultCallback = provisionResultCB;
+    return otmCtx;
+}
+
+void freeOTMContext(OTMContext_t *otmCtx)
+{
+    if (NULL == otmCtx)
+    {
+        return;
+    }
+    freeProvisionDev(otmCtx->selectedDeviceInfo);
+    OICFree(otmCtx);
+}
+
+CAEndpoint_t *createEndpoint()
+{
+    CAEndpoint_t *e = (CAEndpoint_t *)OICCalloc(1, sizeof(CAEndpoint_t));
+    e->adapter = CA_ADAPTER_IP;
+    e->flags = (CATransportFlags_t)(CA_SECURE | CA_IPV4);
+    e->port = 12048;
+    strcpy(e->addr, "127.0.0.1");
+    e->ifindex = 0;
+//    e->remoteId[CA_MAX_IDENTITY_SIZE];
+#if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
+//    char                    routeData[MAX_ADDR_STR_SIZE_CA];
+#endif
+    return e;
+}
+
+void freeEndpoint(CAEndpoint_t *endpoint)
+{
+    OICFree(endpoint);
+}
+
+OicUuid_t *createUuid()
+{
+    OicUuid_t *uuid = (OicUuid_t *)OICCalloc(1, sizeof(OicUuid_t));
+    ConvertStrToUuid("33333333-3333-3333-3333-222222222222", uuid);
+    return uuid;
+}
+
+OicUuid_t *createUuidWith(const char *uuidStr)
+{
+    OicUuid_t *uuid = (OicUuid_t *)OICCalloc(1, sizeof(OicUuid_t));
+    ConvertStrToUuid(uuidStr, uuid);
+    return uuid;
+}
+
+
+void freeUuid(OicUuid_t *uuid)
+{
+    OICFree(uuid);
+}
+#define PKEY_PEM "-----BEGIN PRIVATE KEY-----\n\
+MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCmg+2hGPWQUDey\
+NfXNJQnXVVM+tPl+Neu85BjYH1A6q1oJV0+qGhNiT6u3MX8iIn8EvezkGkqgoz2G\
+sUAaeHcsjJYMQFmYsCNtadiE3rDy/g2qfCy8bMUKiIuagf1FnXv4+b+Z5pIDxnBd\
+xDiNvQjeeA6bn1si1oQenM8vf/TnyCh9sXlh/+E1TANaVpr7r/pXOmDLgvBkSs5j\
+65x1ZAlUpRBgEiFaB2yPWfxM76KuyPEXy9ZJ0/o67TAVPMiV5zID8nh2UO+w37eF\
+jmqRR4UO1gRflJuiODJ6aupRhQiU8VUBXy6KKEA+1+p1ztpoDONyaMRen+nCxNKB\
+bARlNlGFAgMBAAECggEBAIfeUDBJ8F0Px1JniygX177XhXQ+MPGVx8O6DreSXWFx\
+3aaPkpZGbpiiT4fMIGNW6HOTEU9SUKBgclyMFrVCpGM6V1ipzTG0T0QAwMYx+wpa\
+2AXLCqm4ytJ8dgTdmi6KgNS33GoUZAImkhtAd7DXlPwJ1EmRLsjvZqCf7MJiUxAn\
+xkhd5DdD04fNGflt/QHEPqlMe8jGrTpKJn2ZX3lR3a7xTjTOCNyuEB2BSq27BKUg\
+ki/2NXBBPnOonvrNx1RvgmoXp5zSApL9WAuL4iI4xeReqMJUZDTqooGO9v+sCD7C\
+6I8wnBOQl5JyAwQFzdsE5QGofbZifF0iMVZkP0TVZeUCgYEAz+6y0+Ebf1KkrkvG\
+fQIC6EMyNHuGRTCT3x2XFjPJUP3fX/kqmRSOax4QqgGRDbGPMr0yCzinFWrxV9Tp\
+BOgaI96wMSKsfSDtlDmXLBDGSZaCID101n6tK+wpH/ZZqtQ0aaVlN+PrUwHyXNeC\
+0/LcXx/a8izV6OKpUP69rPFpZssCgYEAzQIx8IAVNrEFViBvHvyQ/bwGzu4x50D8\
+6BrFdf2UiigtegcIeuC/o2EWzh9Hr/lxTGn8NVLL0s2aqOme/vMBucWFwIO5Dgxp\
+LGv8//+qQ3lDbBoOivjMVOr14qm0Y2Suu61uZgUYRkziKCRihqq3o0nsx6TXRmS1\
+L14R4p5Izu8CgYATrjkY2taab30MzjlEPbt+tlV7KDHmPJnSZV+Wh2JHmy/YSqIg\
+iRSNyPO0058iF6tBFy00aLFP0qZzNMC1aS6INJyimfCPi11RST4oupG6B1fbq1Vy\
+s9y6Kokd8Fg+VgV79l6lMppkaevBo9hLLVJ0YnR7tYitmT6DXwke5F6gjwKBgQCO\
+Wh7ZM+cHEgZ1lpHyf0gimCRWHfnS7UJv3N8OHiW9hUaGvEl8IYGQbgNK31eE7v1o\
+JRP25uYXG6Nv9MDtoUmqeGh2lEC0a5PAP7/u9tWAgrx5XOKKR1aDBJ/2YwaaGbhn\
+I3dMKe+AKTTE0PcFMZfQL63VtzWwcI+LM5PRuz0tSwKBgBXtbXKFqYmIsPrCi1t8\
+spliEwNPJqCyUdE0ZM/pLXl4AVtL3yTdGkTysqlxxLTQZtgZBq316uFIQhM2aSI+\
+FT658IakILe/pcAMZEtz7j2+C9B7hOxPiQYi5WgVx2EB8ishJWO59Rjy3npyHLou\
+arVShNdQS03YzFPzRpRcb03C\n\
+-----END PRIVATE KEY-----"
+
+#define CERT_PEM "-----BEGIN CERTIFICATE-----\n\
+MIID9TCCAt2gAwIBAgIJAK9okU/M3zDXMA0GCSqGSIb3DQEBCwUAMIGQMQswCQYD\
+VQQGEwJVQTENMAsGA1UECAwES3lpdjENMAsGA1UEBwwES3lpdjEUMBIGA1UECgwL\
+c2Ftc3VuZy5jb20xDzANBgNVBAsMBkFkU0VDTDEUMBIGA1UEAwwLc2Ftc3VuZy5j\
+b20xJjAkBgkqhkiG9w0BCQEWF28uZG15dHJlbmtvQHNhbXN1bmcuY29tMB4XDTE5\
+MDExODA3NTQxNFoXDTIwMDExODA3NTQxNFowgZAxCzAJBgNVBAYTAlVBMQ0wCwYD\
+VQQIDARLeWl2MQ0wCwYDVQQHDARLeWl2MRQwEgYDVQQKDAtzYW1zdW5nLmNvbTEP\
+MA0GA1UECwwGQWRTRUNMMRQwEgYDVQQDDAtzYW1zdW5nLmNvbTEmMCQGCSqGSIb3\
+DQEJARYXby5kbXl0cmVua29Ac2Ftc3VuZy5jb20wggEiMA0GCSqGSIb3DQEBAQUA\
+A4IBDwAwggEKAoIBAQCmg+2hGPWQUDeyNfXNJQnXVVM+tPl+Neu85BjYH1A6q1oJ\
+V0+qGhNiT6u3MX8iIn8EvezkGkqgoz2GsUAaeHcsjJYMQFmYsCNtadiE3rDy/g2q\
+fCy8bMUKiIuagf1FnXv4+b+Z5pIDxnBdxDiNvQjeeA6bn1si1oQenM8vf/TnyCh9\
+sXlh/+E1TANaVpr7r/pXOmDLgvBkSs5j65x1ZAlUpRBgEiFaB2yPWfxM76KuyPEX\
+y9ZJ0/o67TAVPMiV5zID8nh2UO+w37eFjmqRR4UO1gRflJuiODJ6aupRhQiU8VUB\
+Xy6KKEA+1+p1ztpoDONyaMRen+nCxNKBbARlNlGFAgMBAAGjUDBOMB0GA1UdDgQW\
+BBQkTeNZnWU5Dj608WEwAePuiEPBbjAfBgNVHSMEGDAWgBQkTeNZnWU5Dj608WEw\
+AePuiEPBbjAMBgNVHRMEBTADAQH/MA0GCSqGSIb3DQEBCwUAA4IBAQAQfBlbA+gi\
+Yu/awzVDY8fJKZy9eC+cckrVdt3lrfzJuj7ckIvMm5JZryTLjlIAnkMSgjvTmmPe\
+cH5RDYvgOUY+SxPWXE+fuYRrLONPtEBbRPgjMHlgln9U/teU/BBYkjUm0VGnBXdr\
+N3SKb16ixlrtQwNk7MoSkKTk4oQU4QeNKW2SZF7vOHeu2zK6W31sqXgzc3cvBySN\
+6NLZvTYy3ohuFdK2krj1YExxFCBLvSc5fmOiv/7cZl5wsOnHqiYSkoQwm6rnVCGV\
+X/MH0JzgkxxnY5qbBLTFqxdr+6yarTbDvWBpv2OrbarmuqyKBjs/7NHCa5zpnAWw\
+sR1iytctB/HY\n\
+-----END CERTIFICATE-----"
+
+const char *getPemKey()
+{
+    char *key = (char *)OICCalloc(sizeof(PKEY_PEM) + 1, sizeof(char));
+    snprintf(key, sizeof(PKEY_PEM), PKEY_PEM);
+    return key;
+}
+
+const char *getPemCert()
+{
+    char *cert = (char *)OICCalloc(sizeof(CERT_PEM) + 1, sizeof(char));
+    snprintf(cert, sizeof(CERT_PEM), CERT_PEM);
+    return cert;
+}
+
+const char *getPemCertKey()
+{
+    char *buf = (char *)OICCalloc(sizeof(CERT_PEM) + sizeof(PKEY_PEM) + 1, sizeof(char));
+    snprintf(buf, sizeof(CERT_PEM) + sizeof(PKEY_PEM), "%s%s", CERT_PEM, PKEY_PEM);
+    return buf;
+}
+
+static uint8_t _certData[] =
+{
+    0x30, 0x82, 0x02, 0x39, 0x30, 0x82, 0x01, 0xdf, 0x02, 0x01, 0x01, 0x30, 0x0a, 0x06, 0x08, 0x2a,
+    0x86, 0x48, 0xce, 0x3d, 0x04, 0x03, 0x02, 0x30, 0x7c, 0x31, 0x0b, 0x30, 0x09, 0x06, 0x03, 0x55,
+    0x04, 0x06, 0x13, 0x02, 0x55, 0x53, 0x31, 0x12, 0x30, 0x10, 0x06, 0x03, 0x55, 0x04, 0x08, 0x0c,
+    0x09, 0x53, 0x6f, 0x6d, 0x65, 0x73, 0x74, 0x61, 0x74, 0x65, 0x31, 0x11, 0x30, 0x0f, 0x06, 0x03,
+    0x55, 0x04, 0x07, 0x0c, 0x08, 0x53, 0x6f, 0x6d, 0x65, 0x63, 0x69, 0x74, 0x79, 0x31, 0x0b, 0x30,
+    0x09, 0x06, 0x03, 0x55, 0x04, 0x0a, 0x0c, 0x02, 0x42, 0x42, 0x31, 0x16, 0x30, 0x14, 0x06, 0x03,
+    0x55, 0x04, 0x0b, 0x0c, 0x0d, 0x53, 0x65, 0x71, 0x75, 0x72, 0x69, 0x74, 0x79, 0x20, 0x50, 0x61,
+    0x72, 0x74, 0x31, 0x0b, 0x30, 0x09, 0x06, 0x03, 0x55, 0x04, 0x03, 0x0c, 0x02, 0x6f, 0x62, 0x31,
+    0x14, 0x30, 0x12, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x09, 0x01, 0x16, 0x05,
+    0x6f, 0x62, 0x40, 0x62, 0x62, 0x30, 0x1e, 0x17, 0x0d, 0x31, 0x36, 0x30, 0x38, 0x31, 0x35, 0x31,
+    0x33, 0x31, 0x31, 0x31, 0x37, 0x5a, 0x17, 0x0d, 0x31, 0x39, 0x30, 0x35, 0x31, 0x32, 0x31, 0x33,
+    0x31, 0x31, 0x31, 0x37, 0x5a, 0x30, 0x81, 0xd4, 0x31, 0x0b, 0x30, 0x09, 0x06, 0x03, 0x55, 0x04,
+    0x06, 0x13, 0x02, 0x55, 0x41, 0x31, 0x0c, 0x30, 0x0a, 0x06, 0x03, 0x55, 0x04, 0x08, 0x0c, 0x03,
+    0x41, 0x73, 0x64, 0x31, 0x0f, 0x30, 0x0d, 0x06, 0x03, 0x55, 0x04, 0x07, 0x0c, 0x06, 0x47, 0x6f,
+    0x74, 0x68, 0x61, 0x6d, 0x31, 0x0b, 0x30, 0x09, 0x06, 0x03, 0x55, 0x04, 0x0a, 0x0c, 0x02, 0x5a,
+    0x5a, 0x31, 0x11, 0x30, 0x0f, 0x06, 0x03, 0x55, 0x04, 0x0b, 0x0c, 0x08, 0x42, 0x65, 0x61, 0x6d,
+    0x54, 0x65, 0x61, 0x6d, 0x31, 0x1c, 0x30, 0x1a, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d,
+    0x01, 0x09, 0x01, 0x16, 0x0d, 0x72, 0x61, 0x69, 0x6c, 0x40, 0x6d, 0x61, 0x69, 0x6c, 0x2e, 0x63,
+    0x6f, 0x6d, 0x31, 0x32, 0x30, 0x30, 0x06, 0x03, 0x55, 0x04, 0x03, 0x0c, 0x29, 0x75, 0x75, 0x69,
+    0x64, 0x3a, 0x33, 0x32, 0x33, 0x32, 0x33, 0x32, 0x33, 0x32, 0x2d, 0x33, 0x32, 0x33, 0x32, 0x2d,
+    0x33, 0x32, 0x33, 0x32, 0x2d, 0x33, 0x32, 0x33, 0x32, 0x2d, 0x33, 0x32, 0x33, 0x32, 0x33, 0x32,
+    0x33, 0x32, 0x33, 0x32, 0x33, 0x32, 0x31, 0x34, 0x30, 0x32, 0x06, 0x03, 0x55, 0x1d, 0x11, 0x0c,
+    0x2b, 0x75, 0x73, 0x65, 0x72, 0x69, 0x64, 0x3a, 0x36, 0x37, 0x36, 0x37, 0x36, 0x37, 0x36, 0x37,
+    0x2d, 0x36, 0x37, 0x36, 0x37, 0x2d, 0x36, 0x37, 0x36, 0x37, 0x2d, 0x36, 0x37, 0x36, 0x37, 0x2d,
+    0x36, 0x37, 0x36, 0x37, 0x36, 0x37, 0x36, 0x37, 0x36, 0x37, 0x36, 0x37, 0x30, 0x59, 0x30, 0x13,
+    0x06, 0x07, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x02, 0x01, 0x06, 0x08, 0x2a, 0x86, 0x48, 0xce, 0x3d,
+    0x03, 0x01, 0x07, 0x03, 0x42, 0x00, 0x04, 0xf7, 0x13, 0x5c, 0x73, 0x72, 0xce, 0x10, 0xe5, 0x09,
+    0x97, 0x9a, 0xf8, 0xf2, 0x70, 0xa6, 0x3d, 0x89, 0xf5, 0xc5, 0xe4, 0x44, 0xe2, 0x4a, 0xb6, 0x61,
+    0xa8, 0x12, 0x8d, 0xb4, 0xdc, 0x2b, 0x47, 0x84, 0x60, 0x0c, 0x25, 0x66, 0xe9, 0xe0, 0xe5, 0xac,
+    0x22, 0xbf, 0x15, 0xdc, 0x71, 0xb1, 0x88, 0x4f, 0x16, 0xbf, 0xc2, 0x77, 0x37, 0x76, 0x3f, 0xe0,
+    0x67, 0xc6, 0x1d, 0x23, 0xfe, 0x7c, 0x8b, 0x30, 0x0a, 0x06, 0x08, 0x2a, 0x86, 0x48, 0xce, 0x3d,
+    0x04, 0x03, 0x02, 0x03, 0x48, 0x00, 0x30, 0x45, 0x02, 0x20, 0x47, 0xcc, 0x41, 0x8a, 0x27, 0xc7,
+    0xd0, 0xaa, 0xb4, 0xab, 0x85, 0xbf, 0x09, 0x4d, 0x06, 0xd7, 0x7e, 0x0d, 0x39, 0xf9, 0x36, 0xa1,
+    0x3d, 0x96, 0x23, 0xe2, 0x24, 0x64, 0x98, 0x63, 0x21, 0xba, 0x02, 0x21, 0x00, 0xe5, 0x8f, 0x7f,
+    0xf1, 0xa6, 0x82, 0x03, 0x6a, 0x18, 0x7a, 0x54, 0xe7, 0x0e, 0x25, 0x77, 0xd8, 0x46, 0xfa, 0x96,
+    0x8a, 0x7e, 0x14, 0xc4, 0xcb, 0x21, 0x32, 0x3e, 0x89, 0xd9, 0xba, 0x8c, 0x3f
+};
+
+uint8_t *certData()
+{
+    uint8_t *buf = (uint8_t *)OICCalloc(1, sizeof(_certData));
+    memcpy(buf, _certData, sizeof(_certData));
+    return buf;
+}
+
+static uint8_t _keyData[] =
+{
+    0x67, 0xc6, 0x1d, 0x23, 0xfe, 0x7c, 0x8b, 0x30, 0x0a, 0x06, 0x08, 0x2a, 0x86, 0x48, 0xce, 0x3d,
+    0x04, 0x03, 0x02, 0x03, 0x48, 0x00, 0x30, 0x45, 0x02, 0x20, 0x47, 0xcc, 0x41, 0x8a, 0x27, 0xc7,
+    0xd0, 0xaa, 0xb4, 0xab, 0x85, 0xbf, 0x09, 0x4d, 0x06, 0xd7, 0x7e, 0x0d, 0x39, 0xf9, 0x36, 0xa1,
+    0x3d, 0x96, 0x23, 0xe2, 0x24, 0x64, 0x98, 0x63, 0x21, 0xba, 0x02, 0x21
+};
+
+uint8_t *keyData()
+{
+    uint8_t *buf = (uint8_t *)OICCalloc(1, sizeof(_keyData));
+    memcpy(buf, _keyData, sizeof(_keyData));
+    return buf;
+}
+
+size_t keyDataLen()
+{
+    return sizeof(_keyData);
+}
+
+size_t certDataLen()
+{
+    return sizeof(_certData);
+}
+
+OicSecCred_t *createCred()
+{
+    OicSecCred_t *cred = (OicSecCred_t *)OICCalloc(1, sizeof(OicSecCred_t ));
+    cred->credId = (int16_t)rand();
+    ConvertStrToUuid("33333333-3333-3333-3333-222222222222", &cred->subject);
+    // If roleId.id is all zeroes, this property is not set.
+    memcpy(cred->roleId.id, "1.3.6.1.4.1.51414.0.0.1.0", ROLEID_LENGTH);         // 2:R:M:N:oic.sec.roletype
+    memcpy(cred->roleId.authority, "samsung", ROLEAUTHORITY_LENGTH);         // 2:R:M:N:oic.sec.roletype
+    cred->credType = SYMMETRIC_PAIR_WISE_KEY;       // 3:R:S:Y:oic.sec.credtype
+#if defined(__WITH_DTLS__) || defined(__WITH_TLS__)
+    cred->publicData.len = sizeof(_certData);
+    cred->publicData.data = (uint8_t *)OICMalloc(cred->publicData.len);
+    cred->publicData.encoding = OIC_ENCODING_DER;
+    memcpy(cred->publicData.data, _certData, cred->publicData.len);
+    cred->credUsage = NULL;            // 4:R:S:N:String
+    cred->optionalData.data = NULL;   // CA's cerificate chain
+    cred->optionalData.len = 0;   // CA's cerificate chain
+    cred->optionalData.encoding = OIC_ENCODING_UNKNOW;
+    cred->optionalData.revstat = false;
+#endif /* __WITH_DTLS__  or __WITH_TLS__*/
+    cred->privateData.len = sizeof(_keyData);
+    cred->privateData.data = (uint8_t *)OICMalloc(cred->privateData.len);
+    cred->privateData.encoding = OIC_ENCODING_DER;
+    memcpy(cred->privateData.data, _keyData, cred->privateData.len);
+    cred->period = NULL;
+#ifdef MULTIPLE_OWNER
+    ConvertStrToUuid("33333333-3333-3333-3333-222222222222", cred->eownerID);
+#endif //MULTIPLE_OWNER
+    cred->next = NULL;
+
+    return cred;
+}
+
+#define DEFAULTPROFILE  "1.3.6.1.4.1.51414.0.0.1.0"
+
+OicSecSp_t *getSpDefault()
+{
+    OicSecSp_t *sp = (OicSecSp_t *)OICCalloc(1, sizeof(OicSecSp_t));
+    sp->supportedLen = 1;
+    sp->supportedProfiles = (char **)OICCalloc(1, sizeof(char *));
+    sp->supportedProfiles[0] = OICStrdup(DEFAULTPROFILE);
+    sp->currentProfile = OICStrdup(DEFAULTPROFILE);
+    return sp;
+};
+/*
+char * gSupportedProfilesAll[] = { "1.3.6.1.4.1.51414.0.0.2.0", "1.3.6.1.4.1.51414.0.0.3.0", "1.3.6.1.4.1.51414.0.0.4.0", "1.3.6.1.4.1.51414.0.0.1.0",  };
+OicSecSp_t gSpAll =
+{
+    4,                      // supportedLen
+    gSupportedProfilesAll,  // supportedProfiles[0]
+    "1.3.6.1.4.1.51414.0.0.2.0",     // activeProfile
+};
+char * gSupportedProfilesInvalid[] = { "1.3.6.1.4.1.51414.0.0.2.0", "1.3.6.1.4.1.51414.0.0.3.0", "1.3.6.1.4.1.51414.0.0.4.0", "1.3.6.1.4.1.51414.0.0.1.0",  };
+OicSecSp_t gSpInvalid =
+{
+    4,                         // supportedLen
+    gSupportedProfilesInvalid, // supportedProfiles
+    "oic.sec.sp.invalid",      // activeProfile
+};
+*/
+OicSecPstat_t *createPstat()
+{
+    OicSecPstat_t *pstat = (OicSecPstat_t *)OICCalloc(1, sizeof(OicSecPstat_t));
+    pstat->dos.state = DOS_RFNOP;
+    pstat->dos.pending = false;
+    pstat->isOp = false;
+    pstat->cm = NORMAL;
+    pstat->tm = NORMAL;
+    pstat->om = NORMAL;
+    pstat->smLen = 1;
+    pstat->sm = (OicSecDpom_t *)OICCalloc(pstat->smLen, sizeof(OicSecDpom_t ));
+    pstat->sm[0] = NORMAL;
+    pstat->commitHash = 0;
+    ConvertStrToUuid("33333333-3333-3333-3333-222222222222", &pstat->rownerID);
+    return pstat;
+}
+
+bool pInternalWorking;
+oc_thread pInternalThread;
+
+void *IOT_process(void *p)
+{
+    OIC_LOG_V(DEBUG, TAG, "%s: IN",__func__);
+    OC_UNUSED(p);
+    struct timespec timeout = {0, 100000000L};
+    while (pInternalWorking)
+    {
+        if (OCProcess() != OC_STACK_OK)
+        {
+            OIC_LOG(FATAL, TAG, "OCStack process error");
+            return NULL;
+        }
+        nanosleep(&timeout, NULL);
+    }
+    OIC_LOG_V(DEBUG, TAG, "%s: OUT",__func__);
+    return NULL;
+}
+
+FILE *fopenDb(const char *path, const char *mode)
+{
+    OC_UNUSED(path);
+    return fopen("oic_svr_db_client.dat", mode);
+}
+
+void IOT_Init(const char *pDbName)
+{
+    OIC_LOG_V(DEBUG, pDbName, "%s: IN",__func__);
+#ifdef HAVE_UNISTD_H
+    if (-1 != access(pDbName, F_OK))
+    {
+        unlink(pDbName);
+    }
+#endif // HAVE_UNISTD_H
+#   if (__STDC_VERSION__ >= 199901L)
+    static OCPersistentStorage gPst = {.open = fopenDb, .read = fread, .write = fwrite, .close = fclose, .unlink = unlink};
+#   else
+    static OCPersistentStorage gPst = {fopenDb, fread, fwrite, fclose, unlink};
+#   endif
+
+    EXPECT_EQ(OC_STACK_OK, OCRegisterPersistentStorageHandler(&gPst));
+    EXPECT_EQ(OC_STACK_OK, OCInit(NULL, 0, OC_CLIENT_SERVER));
+    EXPECT_EQ(OC_STACK_OK, OCInitPM(pDbName));
+
+    pInternalWorking = true;
+    oc_thread_new(&pInternalThread, IOT_process, NULL);
+    OIC_LOG_V(DEBUG, pDbName, "%s: OUT",__func__);
+}
+
+void IOT_DeInit(const char *pDbName)
+{
+    OIC_LOG_V(DEBUG, pDbName, "%s: IN",__func__);
+    pInternalWorking = false;
+
+    EXPECT_EQ(OC_STACK_OK, OCClosePM());
+    EXPECT_EQ(OC_STACK_OK, OCStop());
+
+    unlink(pDbName);
+
+    oc_thread_wait(pInternalThread);
+    oc_thread_free(pInternalThread);
+    OIC_LOG_V(DEBUG, pDbName, "%s: OUT",__func__);
+}
+
+#if defined(__unix__)
+int readFile(const char *path, uint8_t **buf, size_t *size)
+{
+    int fd = open(path, O_RDONLY);
+    if (0 > fd)
+    {
+        OIC_LOG_V(ERROR, TAG, "%s open: %s(%d)", path, strerror(errno), errno);
+        return -1;
+    }
+    struct stat *st = (struct stat *)OICCalloc(1, sizeof(struct stat));
+    if(0 != fstat(fd, st))
+    {
+        OICFree(st);
+        OIC_LOG_V(ERROR, TAG, "stat: %s(%d)", strerror(errno), errno);
+        return -2;
+    }
+    *size = st->st_size;
+    OICFree(st);
+    *buf = (uint8_t *)OICCalloc(*size, 1);
+    if ((int)(*size) != read(fd, *buf, *size))
+    {
+        OIC_LOG_V(ERROR, TAG, "read: %s(%d)", strerror(errno), errno);
+        close(fd);
+        return -3;
+    }
+    close(fd);
+    return 0;
+}
+
+int readTextFile(const char *path, const char **buf)
+{
+    int fd = open(path, O_RDONLY);
+    if (0 > fd)
+    {
+        OIC_LOG_V(ERROR, TAG, "open %s: %s(%d)", path, strerror(errno), errno);
+        return -1;
+    }
+    struct stat *st = (struct stat *)OICCalloc(1, sizeof(struct stat));
+    if(0 != fstat(fd, st))
+    {
+        OICFree(st);
+        OIC_LOG_V(ERROR, TAG, "stat: %s(%d)", strerror(errno), errno);
+        return -2;
+    }
+    size_t size = st->st_size;
+    OICFree(st);
+    *buf = (const char *)OICCalloc(size + 1, 1);
+    if ((int)(size) != read(fd, (char*)(*buf), size))
+    {
+        OIC_LOG_V(ERROR, TAG, "read: %s(%d)", strerror(errno), errno);
+        close(fd);
+        return -3;
+    }
+    close(fd);
+    return 0;
+}
+
+ByteArrayLL_t *getCerts()
+{
+    ByteArrayLL_t *certs = NULL;
+    DIR *dir = NULL;
+    struct dirent *ent;
+    dir = opendir(CERT_DIR);
+    if (NULL == dir)
+    {
+        OIC_LOG_V(DEBUG, TAG, "open dir: %s: %s(%d)", CERT_DIR, strerror(errno), errno);
+        return NULL;
+    }
+    while ((ent = readdir(dir)))
+    {
+        if (strncmp(ent->d_name, ".", 2) == 0 ||
+            strncmp(ent->d_name, "..", 3) == 0 ||
+            strstr(ent->d_name,"key") != NULL)
+        {
+            continue;
+        }
+        char *path = (char *)OICCalloc(sizeof(CERT_DIR) + strlen(ent->d_name) + 2, 1);
+        snprintf(path, sizeof(CERT_DIR) + strlen(ent->d_name) + 1, "%s/%s", CERT_DIR, ent->d_name);
+        OIC_LOG_V(DEBUG, TAG, "open: %s", path);
+        ByteArrayLL_t *crt = (ByteArrayLL_t *)OICCalloc(1, sizeof(ByteArrayLL_t));
+        crt->cert = (ByteArray_t *)OICCalloc(1, sizeof(ByteArray_t));
+        readFile(path, &crt->cert->data, &crt->cert->len);
+        OICFree(path);
+        LL_APPEND(certs, crt);
+    }
+    closedir (dir);
+    return certs;
+}
+
+#else // __unix__
+#ifdef TODO_WIN_x86
+namespace fs = std::experimental::filesystem;
+#endif
+static int _readFile(const std::string& path, uint8_t **buf, size_t *size, const std::ios_base::openmode mode)
+{
+#ifdef TODO_WIN_x86
+    try
+    {
+        *size = fs::file_size(path) + (mode == std::ifstream::in ? 1 : 0);
+        std::cout << "file: " << path << " size: " << *size  << std::endl;
+        *buf = (uint8_t*)OICCalloc(*size, 1);
+        std::ifstream ifs(path, mode);
+        std::string line;
+        *size = 0;
+        while(std::getline(ifs, line))
+        {
+            strncpy((char*)(*buf + *size), line.c_str(), line.length());
+            *size += line.length();
+        }
+    }
+    catch(fs::filesystem_error& e)
+    {
+        std::cout << e.what() << std::endl;
+        return 1;
+    }
+#else
+    OC_UNUSED(path);
+    OC_UNUSED(buf);
+    OC_UNUSED(size);
+    OC_UNUSED(mode);
+#endif
+    return 0;
+}
+int readFile(const char *path, uint8_t **buf, size_t *size)
+{
+    return _readFile(path, buf, size, std::ifstream::binary);
+}
+
+int readTextFile(const char *path, const char **buf)
+{
+    size_t size = 0;
+    return _readFile(path, (uint8_t**)buf, &size, std::ifstream::in);
+}
+
+ByteArrayLL_t *getCerts()
+{
+    ByteArrayLL_t *certs = NULL;
+#ifdef TODO_WIN_x86
+    for (const auto & entry : fs::directory_iterator(CERT_DIR))
+    {
+        std::string path = entry.path().string();
+        if (path == "." || path == ".." || path.find("key") != std::string::npos)
+        {
+            continue;
+        }
+        ByteArrayLL_t *crt = (ByteArrayLL_t *)OICCalloc(1, sizeof(ByteArrayLL_t));
+        crt->cert = (ByteArray_t *)OICCalloc(1, sizeof(ByteArray_t));
+        readFile(path.c_str(), &crt->cert->data, &crt->cert->len);
+        OIC_LOG_V(DEBUG, TAG, "open: %s size: %lu", path.c_str(), crt->cert->len);
+        LL_APPEND(certs, crt);
+    }
+#endif
+    return certs;
+}
+#endif // __unix__
+
+void freeCert(ByteArrayLL_t *crt)
+{
+    OICFree(crt->cert->data);
+    OICFree(crt->cert);
+    OICFree(crt);
+}
+
+void clearCerts(ByteArrayLL_t *list)
+{
+    ByteArrayLL_t *crt = NULL, *tmp = NULL;
+    LL_FOREACH_SAFE(list, crt, tmp)
+    {
+        LL_DELETE(list, crt);
+        freeCert(crt);
+    }
+}
+
+OicSecCred_t *getSignedAsymKeyCred()
+{
+    OicSecCred_t *cred = (OicSecCred_t*)OICCalloc(1, sizeof(OicSecCred_t));
+    VERIFY_NOT_NULL(TAG, cred, ERROR);
+    cred->credId = (int16_t)rand();
+    memcpy(cred->subject.id, &WILDCARD_SUBJECT_ID, sizeof(cred->subject.id));
+    cred->credType = SIGNED_ASYMMETRIC_KEY;
+    cred->credUsage = (char*)OICCalloc(strlen(PRIMARY_CERT), 1);
+    memcpy(cred->credUsage, PRIMARY_CERT, strlen(PRIMARY_CERT));
+    cred->publicData.encoding = OIC_ENCODING_DER;
+    cred->publicData.data = certData();
+    cred->publicData.len = certDataLen();
+    return cred;
+exit:
+    if(cred)
+    {
+        FreeCred(cred);
+    }
+    return NULL;
+}
+
+OicSecCred_t *getAsymKeyCred()
+{
+    OicSecCred_t *cred = (OicSecCred_t*)OICCalloc(1, sizeof(OicSecCred_t));
+    VERIFY_NOT_NULL(TAG, cred, ERROR);
+    cred->credId = (int16_t)rand();
+    memcpy(cred->subject.id, &WILDCARD_SUBJECT_ID, sizeof(cred->subject.id));
+    cred->credType = ASYMMETRIC_KEY;
+    cred->credUsage = (char*)OICCalloc(strlen(PRIMARY_CERT), 1);
+    memcpy(cred->credUsage, PRIMARY_CERT, strlen(PRIMARY_CERT));
+    cred->publicData.encoding = OIC_ENCODING_DER;
+    cred->publicData.data = keyData();
+    cred->publicData.len = keyDataLen();
+    return cred;
+exit:
+    if(cred)
+    {
+        FreeCred(cred);
+    }
+    return NULL;
+}
+
+OicSecCred_t *getAsymEncKeyCred()
+{
+    OicSecCred_t *cred = (OicSecCred_t*)OICCalloc(1, sizeof(OicSecCred_t));
+    VERIFY_NOT_NULL(TAG, cred, ERROR);
+    cred->credId = (int16_t)rand();
+    memcpy(cred->subject.id, &WILDCARD_SUBJECT_ID, sizeof(cred->subject.id));
+    cred->credType = ASYMMETRIC_ENCRYPTION_KEY;
+    cred->credUsage = (char*)OICCalloc(strlen(PRIMARY_CERT), 1);
+    memcpy(cred->credUsage, PRIMARY_CERT, strlen(PRIMARY_CERT));
+    cred->privateData.encoding = OIC_ENCODING_DER;
+    cred->privateData.data = keyData();
+    cred->privateData.len = keyDataLen();
+    return cred;
+exit:
+    if(cred)
+    {
+        FreeCred(cred);
+    }
+    return NULL;
+}
+
+OicSecCred_t *getSymPairCred()
+{
+    OicSecCred_t *cred = (OicSecCred_t*)OICCalloc(1, sizeof(OicSecCred_t));
+    VERIFY_NOT_NULL(TAG, cred, ERROR);
+    cred->credId = (int16_t)rand();
+    // use |memcpy| for copying full-lengthed UUID without null termination
+    memcpy(cred->subject.id, "2222222222222222", sizeof(cred->subject.id));
+#if 0
+    cred->roleIdsLen = 0;
+#endif
+    cred->credType = SYMMETRIC_PAIR_WISE_KEY;
+    cred->privateData.encoding = OIC_ENCODING_DER;
+    cred->privateData.data = keyData();
+    cred->privateData.len = keyDataLen();
+#if 0
+    sz = strlen("My Public Key123") + 1;
+    cred->publicData.data = (char *)OICCalloc(1, sz);
+    VERIFY_NOT_NULL(TAG, cred->publicData.data, ERROR);
+    OICStrcpy(cred->publicData.data, sz,"My Public Key123");
+#endif
+    // use |memcpy| for copying full-lengthed UUID without null termination
+    return cred;
+exit:
+    if(cred)
+    {
+        FreeCred(cred);
+    }
+    return NULL;
+}
+
+OicSecCred_t * getCredList()
+{
+    OicSecCred_t *cred = (OicSecCred_t *)OICCalloc(1, sizeof(*cred));
+    VERIFY_NOT_NULL(TAG, cred, ERROR);
+    cred->credId = 1234;
+    // use |memcpy| for copying full-lengthed UUID without null termination
+    memcpy(cred->subject.id, "1111111111111111", sizeof(cred->subject.id));
+
+#if 0
+    cred->roleIdsLen = 2;
+    cred->roleIds = (OicSecRole_t *)OICCalloc(cred->roleIdsLen, sizeof(OicSecRole_t));
+    VERIFY_NOT_NULL(TAG, cred->roleIds, ERROR);
+    OICStrcpy((char *)cred->roleIds[0].id, sizeof(cred->roleIds[0].id), "role11");
+    OICStrcpy((char *)cred->roleIds[1].id, sizeof(cred->roleIds[1].id), "role12");
+#endif
+
+    cred->credType = SYMMETRIC_PAIR_WISE_KEY;
+    cred->privateData.encoding = OIC_ENCODING_RAW;
+    cred->privateData.data = (uint8_t *)OICCalloc(1, strlen("My private Key11") + 1);
+    cred->privateData.len = strlen("My private Key11");
+    VERIFY_NOT_NULL(TAG, cred->privateData.data, ERROR);
+    OICStrcpy((char *)cred->privateData.data, strlen("My private Key11")+1,"My private Key11");
+    // use |memcpy| for copying full-lengthed UUID without null termination
+    cred->next = getSymPairCred();
+    return cred;
+
+exit:
+    if(cred)
+    {
+        DeleteCredList(cred);
+        cred = NULL;
+    }
+    return cred;
+}
+
+void printCred(const OicSecCred_t * cred)
+{
+    EXPECT_TRUE(NULL != cred);
+
+    const OicSecCred_t *credTmp1 = NULL;
+    for (credTmp1 = cred; credTmp1; credTmp1 = credTmp1->next)
+    {
+        OIC_LOG_V(INFO, TAG, "\ncredId: %d", credTmp1->credId);
+        OIC_LOG_V(INFO, TAG, "subject: %s", credTmp1->subject.id);
+        OIC_LOG_V(INFO, TAG, "credType: %d", credTmp1->credType);
+        OIC_LOG_V(INFO, TAG, "credUsage: %s", credTmp1->credUsage);
+        if(credTmp1->privateData.len && credTmp1->privateData.data)
+        {
+            OIC_LOG_V(INFO, TAG, "private data = %s", credTmp1->privateData.data);
+        }
+#ifdef __WITH_DTLS__
+        if(credTmp1->publicData.data)
+        {
+           OIC_LOG_V(INFO, TAG, "public data = %s", credTmp1->publicData.data);
+        }
+#endif /* __WITH_DTLS__ */
+    }
+}
+
diff --git a/resource/csdk/security/unittest/tools.h b/resource/csdk/security/unittest/tools.h
new file mode 100644 (file)
index 0000000..1443f1d
--- /dev/null
@@ -0,0 +1,151 @@
+/* *****************************************************************
+ *
+ * Copyright 2019 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ * *****************************************************************/
+#ifndef __UNITTEST_TOOLS__
+#define __UNITTEST_TOOLS__
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+#include "securevirtualresourcetypes.h"
+#include "octypes.h"
+#include "pmtypes.h"
+#include "ownershiptransfermanager.h"
+#include "cacommon.h"
+//#include "byte_array.h"
+#ifdef __cplusplus
+}
+#endif
+
+#define UUID_SRV1 "11111111-1234-1234-1234-123456789011"
+#define UUID_SRV2 "11111111-1234-1234-1234-123456789012"
+
+#ifndef OIC_DEFAULT_OICSECOPT
+#   if (__STDC_VERSION__ >= 199901L)
+#       define OIC_DEFAULT_OICSECOPT\
+        { \
+        .data = keyData(),\
+        .len = keyDataLen(),\
+        .encoding = OIC_ENCODING_DER,\
+        .revstat = false \
+        }
+#   else
+#       define OIC_DEFAULT_OICSECOPT\
+        { \
+        keyData(),\
+        keyDataLen(),\
+        OIC_ENCODING_DER,\
+        false \
+        }
+#   endif
+#endif
+
+#ifndef OIC_DEFAULT_OICSECKEY
+#   if (__STDC_VERSION__ >= 199901L)
+#       define OIC_DEFAULT_OICSECKEY\
+        { \
+        .data = keyData(),\
+        .len = keyDataLen(),\
+        .encoding = OIC_ENCODING_DER\
+        }
+#   else
+#       define OIC_DEFAULT_OICSECKEY\
+        { \
+        keyData(),\
+        keyDataLen(),\
+        OIC_ENCODING_DER\
+        }
+#   endif
+#endif
+
+bool AddSslPeer(const CAEndpoint_t *endpoint, uint8_t *pk, size_t pklen);
+
+void RmSslPeer(const CAEndpoint_t *peer);
+
+FILE *fopen_config(const char *path, const char *mode);
+
+OicSecDoxm_t *createDoxm();
+
+void freeDoxm(OicSecDoxm_t *doxm);
+
+OCDevAddr *setAddr(const char *ip, uint16_t port, OCTransportAdapter adapter);
+
+OCProvisionDev_t *createProvisionDev();
+
+void freeProvisionDev(OCProvisionDev_t *pd);
+
+OTMContext_t *createOTMContext();
+
+void freeOTMContext(OTMContext_t *otmCtx);
+
+CAEndpoint_t *createEndpoint();
+
+void freeEndpoint(CAEndpoint_t *endpoint);
+
+OicUuid_t *createUuid();
+
+OicUuid_t *createUuidWith(const char *uuidStr);
+
+void freeUuid(OicUuid_t *uuid);
+
+uint8_t *certData();
+
+uint8_t *keyData();
+
+const char *getPemKey();
+
+const char *getPemCert();
+
+const char *getCertKey();
+
+size_t keyDataLen();
+
+size_t certDataLen();
+
+OicSecCred_t *createCred();
+
+OicSecSp_t *getSpDefault();
+
+OicSecPstat_t *createPstat();
+
+void IOT_Init(const char *pDbName);
+
+void IOT_DeInit(const char *pDbName);
+
+int readFile(const char *path, uint8_t **buf, size_t *size);
+
+int readTextFile(const char *path, const char **buf);
+
+ByteArrayLL_t *getCerts();
+
+void clearCerts(ByteArrayLL_t *list);
+
+OicSecCred_t * getCredList();
+
+void printCred(const OicSecCred_t * cred);
+
+OicSecCred_t *getAsymKeyCred();
+
+OicSecCred_t *getSignedAsymKeyCred();
+
+OicSecCred_t *getSymPairCred();
+
+OicSecCred_t *getAsymEncKeyCred();
+
+#endif //__UNITTEST_TOOLS__