9e98f3e3b2105fadbb8af9411e3f672a018b2678
[platform/core/security/vist.git] / osquery / remote / enroll / tests / enroll_tests.cpp
1 /*
2  *  Copyright (c) 2014, Facebook, Inc.
3  *  All rights reserved.
4  *
5  *  This source code is licensed under the BSD-style license found in the
6  *  LICENSE file in the root directory of this source tree. An additional grant
7  *  of patent rights can be found in the PATENTS file in the same directory.
8  *
9  */
10
11 #include <gtest/gtest.h>
12
13 #include <osquery/core.h>
14 #include <osquery/database.h>
15 #include <osquery/enroll.h>
16
17 #include "osquery/core/test_util.h"
18
19 namespace osquery {
20
21 class EnrollTests : public testing::Test {
22  public:
23   void SetUp() {
24     deleteDatabaseValue(kPersistentSettings, "nodeKey");
25     deleteDatabaseValue(kPersistentSettings, "nodeKeyTime");
26   }
27 };
28
29 class SimpleEnrollPlugin : public EnrollPlugin {
30  public:
31   SimpleEnrollPlugin() : times_forced_(0) {}
32
33  protected:
34   std::string enroll(bool force) {
35     if (force) {
36       forced_response_ = std::to_string(times_forced_);
37       times_forced_++;
38       return forced_response_;
39     }
40     return "fetched_a_node_key";
41   }
42
43  private:
44   std::string forced_response_;
45   size_t times_forced_;
46 };
47
48 // Register our simple enroll plugin.
49 REGISTER(SimpleEnrollPlugin, "enroll", "test_simple");
50
51 TEST_F(EnrollTests, test_enroll_key_retrieval) {
52   FLAGS_disable_enrollment = true;
53   // Without enrollment, and with an empty nodeKey storage value, no node key
54   // will be fetched or returned from cached.
55   EXPECT_EQ(getNodeKey("test_simple"), "");
56
57   // Turn the enrollment features back on and expect a key.
58   FLAGS_disable_enrollment = false;
59   EXPECT_EQ(getNodeKey("test_simple"), "fetched_a_node_key");
60 }
61
62 TEST_F(EnrollTests, test_enroll_key_caching) {
63   // Cause a fetch of the node key.
64   auto node_key = getNodeKey("test_simple");
65
66   // Now fetch the time the node key was last cached from the database.
67   std::string key_time;
68   auto status = getDatabaseValue(kPersistentSettings, "nodeKeyTime", key_time);
69   EXPECT_TRUE(status.ok());
70
71   // A subsequent call to getNodeKey will return the same node key.
72   // But, our simple enroll plugin is not enforcing any secret check and is
73   // always returning the same node key.
74   auto node_key2 = getNodeKey("test_simple");
75   // In most scenarios subsequent calls to EnrollPlugin::enroll and the backing
76   // enrollment service will generate and return different node keys.
77   EXPECT_EQ(node_key2, node_key);
78
79   // To work around our contrived example we make sure the node time was not
80   // updated, meaning no call to EnrollPlugin::enroll occurred.
81   std::string key_time2;
82   getDatabaseValue(kPersistentSettings, "nodeKeyTime", key_time2);
83   EXPECT_EQ(key_time2, key_time);
84 }
85 }