d2_cfg_mgr_unittests.cc 40.6 KB
Newer Older
1
// Copyright (C) 2013-2020 Internet Systems Consortium, Inc. ("ISC")
2
//
3 4 5
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
6

7 8
#include <config.h>

9 10
#include <d2/d2_config.h>
#include <d2/d2_cfg_mgr.h>
11 12 13
#include <d2/d2_simple_parser.h>
#include <d2/parser_context.h>
#include <d2/tests/parser_unittest.h>
14 15
#include <dhcpsrv/testutils/config_result_check.h>
#include <process/testutils/d_test_stubs.h>
16
#include <test_data_files_config.h>
17
#include <util/encode/base64.h>
18 19

#include <boost/foreach.hpp>
20
#include <boost/scoped_ptr.hpp>
21 22 23 24 25
#include <gtest/gtest.h>

using namespace std;
using namespace isc;
using namespace isc::d2;
26
using namespace isc::process;
27 28 29

namespace {

30 31 32 33 34 35
/// @brief Function to create full path to test data file
///
/// The full path is dependent upon the value of D2_TEST_DATA_DIR which
/// whose value is generated from test_data_files_config.h.in
///
/// @param name file name to which the path should be prepended
36 37 38 39
std::string testDataFile(const std::string& name) {
    return (std::string(D2_TEST_DATA_DIR) + "/" + name);
}

40 41 42 43 44 45 46 47
/// @brief Test fixture class for testing D2CfgMgr class.
/// It maintains an member instance of D2CfgMgr and provides methods for
/// converting JSON strings to configuration element sets, checking parse
/// results, and accessing the configuration context.
class D2CfgMgrTest : public ConfigParseTest {
public:

    /// @brief Constructor
48
    D2CfgMgrTest():cfg_mgr_(new D2CfgMgr()), d2_params_() {
49 50 51 52 53 54 55 56
    }

    /// @brief Destructor
    ~D2CfgMgrTest() {
    }

    /// @brief Configuration manager instance.
    D2CfgMgrPtr cfg_mgr_;
57 58 59

    /// @brief Build JSON configuration string for a D2Params element
    ///
Andrei Pavel's avatar
Andrei Pavel committed
60
    /// Constructs a JSON string for "params" element using replaceable
61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77
    /// parameters.
    ///
    /// @param ip_address string to insert as ip_address value
    /// @param port integer to insert as port value
    /// @param dns_server_timeout integer to insert as dns_server_timeout value
    /// @param ncr_protocol string to insert as ncr_protocol value
    /// @param ncr_format string to insert as ncr_format value
    ///
    /// @return std::string containing the JSON configuration text
    std::string makeParamsConfigString(const std::string& ip_address,
                                       const int port,
                                       const int dns_server_timeout,
                                       const std::string& ncr_protocol,
                                       const std::string& ncr_format) {
        std::ostringstream config;
        config <<
            "{"
78
            " \"ip-address\": \"" << ip_address << "\" , "
79
            " \"port\": " << port << " , "
80 81 82
            " \"dns-server-timeout\": " << dns_server_timeout << " , "
            " \"ncr-protocol\": \"" << ncr_protocol << "\" , "
            " \"ncr-format\": \"" << ncr_format << "\", "
83 84 85
            " \"tsig-keys\": [], "
            " \"forward-ddns\" : {}, "
            " \"reverse-ddns\" : {} "
86 87 88 89
            "}";

        return (config.str());
    }
90

91 92
    /// @brief Enumeration to select between expected configuration outcomes
    enum RunConfigMode {
93 94 95
        NO_ERROR,
        SYNTAX_ERROR,
        LOGIC_ERROR
96 97
    };

98 99 100
    /// @brief Parses a configuration string and tests against a given outcome
    ///
    /// Convenience method which accepts JSON text and an expected pass or fail
101 102 103 104
    /// outcome.  It uses the D2ParserContext to parse the text under the
    /// PARSE_SUB_DHCPDDNS context, then adds the D2 defaults to the resultant
    /// element tree. Assuming that's successful the element tree is passed
    /// to D2CfgMgr::parseConfig() method.
105 106
    ///
    /// @param config_str the JSON configuration text to parse
107 108 109 110
    /// @param error_type  indicates the type error expected, NONE, SYNTAX,
    /// or LOGIC. SYNTAX errors are emitted by JSON parser, logic errors
    /// are emitted by element parser(s).
    /// @param exp_error exact text of the error message expected
111 112
    /// defaults to SHOULD_PASS.
    ///
113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132
    /// @return AssertionSuccess if test passes, AssertionFailure otherwise
    ::testing::AssertionResult runConfigOrFail(const std::string& json,
                                               const RunConfigMode mode,
                                               const std::string& exp_error) {

        try {
            // Invoke the JSON parser, casting the returned element tree
            // into mutable form.
            D2ParserContext parser_context;
            data::ElementPtr elem =
                boost::const_pointer_cast<Element>
                (parser_context.parseString(json, D2ParserContext::
                                                  PARSER_SUB_DHCPDDNS));

            // If parsing succeeded when we expected a syntax error, then fail.
            if (mode == SYNTAX_ERROR) {
               return ::testing::AssertionFailure()
                             << "Unexpected  JSON parsing success"
                             << "\njson: [" << json << " ]";
            }
133

134 135 136 137 138 139 140 141 142 143 144
            // JSON parsed ok, so add the defaults to the element tree it produced.
            D2SimpleParser::setAllDefaults(elem);
            config_set_ = elem;
        } catch (const std::exception& ex) {
            // JSON Parsing failed
            if (exp_error.empty()) {
                // We did not expect an error, so fail.
                return ::testing::AssertionFailure()
                          << "Unexpected syntax error:" << ex.what()
                          << "\njson: [" << json << " ]";
            }
145

146 147 148 149 150 151 152
            if (ex.what() != exp_error) {
                // Expected an error not the one we got, so fail
                return ::testing::AssertionFailure()
                          << "Wrong syntax error detected, expected: "
                          << exp_error << ", got: " << ex.what()
                          << "\njson: [" << json << " ]";
            }
153

154 155 156
            // We go the syntax error we expected, so return success
            return ::testing::AssertionSuccess();
        }
157

158 159
        // The JSON parsed ok and we've added the defaults, pass the config
        // into the Element parser and check for the expected outcome.
160
        data::ConstElementPtr answer;
161
        answer = cfg_mgr_->simpleParseConfig(config_set_, false);
162 163

        // Extract the result and error text from the answer.
164 165 166 167
        int rcode = 0;
        isc::data::ConstElementPtr comment;
        comment = isc::config::parseAnswer(rcode, answer);

168 169 170 171 172 173 174
        if (rcode != 0) {
            // Element Parsing failed.
            if (exp_error.empty()) {
                // We didn't expect it to, fail the test.
                return ::testing::AssertionFailure()
                              << "Unexpected logic error: " << *comment
                              << "\njson: [" << json << " ]";
175 176
            }

177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192
            if (comment->stringValue() != exp_error) {
                // We 't expect a different error, fail the test.
                return ::testing::AssertionFailure()
                              << "Wrong logic error detected, expected: "
                              << exp_error << ", got: " << *comment
                              << "\njson: [" << json << " ]";
            }
        } else {
            // Element parsing succeeded.
            if (!exp_error.empty()) {
                // It was supposed to fail, so fail the test.
                return ::testing::AssertionFailure()
                              << "Unexpected logic success, expected error:"
                              << exp_error
                              << "\njson: [" << json << " ]";
            }
193 194
        }

195 196 197 198 199
        // Verify that the D2 context can be retrieved and is not null.
        D2CfgContextPtr context;
        context = cfg_mgr_->getD2CfgContext();
        if (!context) {
            return ::testing::AssertionFailure() << "D2CfgContext is null";
200 201
        }

202 203 204 205
        // Verify that the global scalar container has been created.
        d2_params_ = context->getD2Params();
        if (!d2_params_) {
            return ::testing::AssertionFailure() << "D2Params is null";
206 207
        }

208
        return ::testing::AssertionSuccess();
209 210
    }

211

212
    /// @brief Pointer the D2Params most recently parsed.
213
    D2ParamsPtr d2_params_;
214 215
};

216 217 218 219 220
/// @brief Convenience macros for invoking runOrConfig()
#define RUN_CONFIG_OK(a) (runConfigOrFail(a, NO_ERROR, ""))
#define SYNTAX_ERROR(a,b) ASSERT_TRUE(runConfigOrFail(a,SYNTAX_ERROR,b))
#define LOGIC_ERROR(a,b) ASSERT_TRUE(runConfigOrFail(a,LOGIC_ERROR,b))

221 222 223 224 225
/// @brief Tests a basic valid configuration for D2Param.
TEST_F(D2CfgMgrTest, validParamsEntry) {
    // Verify that ip_address can be valid v4 address.
    std::string config = makeParamsConfigString ("192.0.0.1", 777, 333,
                                           "UDP", "JSON");
226
    RUN_CONFIG_OK(config);
227 228 229 230 231 232 233 234 235 236

    EXPECT_EQ(isc::asiolink::IOAddress("192.0.0.1"),
              d2_params_->getIpAddress());
    EXPECT_EQ(777, d2_params_->getPort());
    EXPECT_EQ(333, d2_params_->getDnsServerTimeout());
    EXPECT_EQ(dhcp_ddns::NCR_UDP, d2_params_->getNcrProtocol());
    EXPECT_EQ(dhcp_ddns::FMT_JSON, d2_params_->getNcrFormat());

    // Verify that ip_address can be valid v6 address.
    config = makeParamsConfigString ("3001::5", 777, 333, "UDP", "JSON");
237
    RUN_CONFIG_OK(config);
238 239 240 241

    // Verify that the global scalars have the proper values.
    EXPECT_EQ(isc::asiolink::IOAddress("3001::5"),
              d2_params_->getIpAddress());
242 243

    // Verify the configuration summary.
244
    EXPECT_EQ("listening on 3001::5, port 777, using UDP",
245
              d2_params_->getConfigSummary());
246 247 248 249 250 251 252 253
}

/// @brief Tests default values for D2Params.
/// It verifies that D2Params is populated with default value for optional
/// parameter if not supplied in the configuration.
/// Currently they are all optional.
TEST_F(D2CfgMgrTest, defaultValues) {

254 255 256
    ElementPtr defaults = isc::d2::test::parseJSON("{ }");
    ASSERT_NO_THROW(D2SimpleParser::setAllDefaults(defaults));

257 258 259 260
    // Check that omitting ip_address gets you its default
    std::string config =
            "{"
            " \"port\": 777 , "
261 262 263
            " \"dns-server-timeout\": 333 , "
            " \"ncr-protocol\": \"UDP\" , "
            " \"ncr-format\": \"JSON\", "
264 265 266
            " \"tsig-keys\": [], "
            " \"forward-ddns\" : {}, "
            " \"reverse-ddns\" : {} "
267 268
            "}";

269 270 271 272 273
    RUN_CONFIG_OK(config);
    ConstElementPtr deflt;
    ASSERT_NO_THROW(deflt = defaults->get("ip-address"));
    ASSERT_TRUE(deflt);
    EXPECT_EQ(deflt->stringValue(), d2_params_->getIpAddress().toText());
274 275 276 277

    // Check that omitting port gets you its default
    config =
            "{"
278 279 280 281
            " \"ip-address\": \"192.0.0.1\" , "
            " \"dns-server-timeout\": 333 , "
            " \"ncr-protocol\": \"UDP\" , "
            " \"ncr-format\": \"JSON\", "
282 283 284
            " \"tsig-keys\": [], "
            " \"forward-ddns\" : {}, "
            " \"reverse-ddns\" : {} "
285 286
            "}";

287 288 289 290
    RUN_CONFIG_OK(config);
    ASSERT_NO_THROW(deflt = defaults->get("port"));
    ASSERT_TRUE(deflt);
    EXPECT_EQ(deflt->intValue(), d2_params_->getPort());
291 292 293 294

    // Check that omitting timeout gets you its default
    config =
            "{"
295
            " \"ip-address\": \"192.0.0.1\" , "
296
            " \"port\": 777 , "
297 298
            " \"ncr-protocol\": \"UDP\" , "
            " \"ncr-format\": \"JSON\", "
299 300 301
            " \"tsig-keys\": [], "
            " \"forward-ddns\" : {}, "
            " \"reverse-ddns\" : {} "
302 303
            "}";

304 305 306 307
    RUN_CONFIG_OK(config);
    ASSERT_NO_THROW(deflt = defaults->get("dns-server-timeout"));
    ASSERT_TRUE(deflt);
    EXPECT_EQ(deflt->intValue(), d2_params_->getDnsServerTimeout());
308

309
    // Check that omitting protocol gets you its default
310 311
    config =
            "{"
312
            " \"ip-address\": \"192.0.0.1\" , "
313
            " \"port\": 777 , "
314 315
            " \"dns-server-timeout\": 333 , "
            " \"ncr-format\": \"JSON\", "
316 317 318
            " \"tsig-keys\": [], "
            " \"forward-ddns\" : {}, "
            " \"reverse-ddns\" : {} "
319 320
            "}";

321 322 323 324
    RUN_CONFIG_OK(config);
    ASSERT_NO_THROW(deflt = defaults->get("ncr-protocol"));
    ASSERT_TRUE(deflt);
    EXPECT_EQ(dhcp_ddns::stringToNcrProtocol(deflt->stringValue()),
325 326
              d2_params_->getNcrProtocol());

327
    // Check that omitting format gets you its default
328 329
    config =
            "{"
330
            " \"ip-address\": \"192.0.0.1\" , "
331
            " \"port\": 777 , "
332 333
            " \"dns-server-timeout\": 333 , "
            " \"ncr-protocol\": \"UDP\", "
334 335 336
            " \"tsig-keys\": [], "
            " \"forward-ddns\" : {}, "
            " \"reverse-ddns\" : {} "
337 338
            "}";

339 340 341 342
    RUN_CONFIG_OK(config);
    ASSERT_NO_THROW(deflt = defaults->get("ncr-format"));
    ASSERT_TRUE(deflt);
    EXPECT_EQ(dhcp_ddns::stringToNcrFormat(deflt->stringValue()),
343 344 345
              d2_params_->getNcrFormat());
}

346 347 348 349 350
/// @brief Tests the unsupported scalar parameters and objects are detected.
TEST_F(D2CfgMgrTest, unsupportedTopLevelItems) {
    // Check that an unsupported top level parameter fails.
    std::string config =
            "{"
351
            " \"ip-address\": \"127.0.0.1\", "
352
            " \"port\": 777 , "
353 354 355
            " \"dns-server-timeout\": 333 , "
            " \"ncr-protocol\": \"UDP\" , "
            " \"ncr-format\": \"JSON\", "
356 357 358 359
            " \"tsig-keys\": [], "
            " \"forward-ddns\" : {}, "
            " \"reverse-ddns\" : {}, "
            " \"bogus-param\" : true "
360 361
            "}";

362
    SYNTAX_ERROR(config, "<string>:1.185-197: got unexpected "
363
                         "keyword \"bogus-param\" in DhcpDdns map.");
364 365 366 367 368

    // Check that unsupported top level objects fails.  For
    // D2 these fail as they are not in the parse order.
    config =
            "{"
369
            " \"ip-address\": \"127.0.0.1\", "
370
            " \"port\": 777 , "
371 372 373
            " \"dns-server-timeout\": 333 , "
            " \"ncr-protocol\": \"UDP\" , "
            " \"ncr-format\": \"JSON\", "
374 375 376 377 378
            " \"tsig-keys\": [], "
            " \"bogus-object-one\" : {}, "
            " \"forward-ddns\" : {}, "
            " \"reverse-ddns\" : {}, "
            " \"bogus-object-two\" : {} "
379 380
            "}";

381
    SYNTAX_ERROR(config, "<string>:1.141-158: got unexpected"
382
                         " keyword \"bogus-object-one\" in DhcpDdns map.");
383 384 385
}


386 387 388 389 390
/// @brief Tests the enforcement of data validation when parsing D2Params.
/// It verifies that:
/// -# ip_address cannot be "0.0.0.0"
/// -# ip_address cannot be "::"
/// -# port cannot be 0
Andrei Pavel's avatar
Andrei Pavel committed
391
/// -# dns_server_timeout cannot be 0
392 393 394 395 396 397
/// -# ncr_protocol must be valid
/// -# ncr_format must be valid
TEST_F(D2CfgMgrTest, invalidEntry) {
    // Cannot use IPv4 ANY address
    std::string config = makeParamsConfigString ("0.0.0.0", 777, 333,
                                           "UDP", "JSON");
398
    LOGIC_ERROR(config, "IP address cannot be \"0.0.0.0\" (<string>:1:17)");
399 400 401

    // Cannot use IPv6 ANY address
    config = makeParamsConfigString ("::", 777, 333, "UDP", "JSON");
402
    LOGIC_ERROR(config, "IP address cannot be \"::\" (<string>:1:17)");
403 404 405

    // Cannot use port  0
    config = makeParamsConfigString ("127.0.0.1", 0, 333, "UDP", "JSON");
406
    SYNTAX_ERROR(config, "<string>:1.40: port must be greater than zero but less than 65536");
407 408 409

    // Cannot use dns server timeout of 0
    config = makeParamsConfigString ("127.0.0.1", 777, 0, "UDP", "JSON");
410 411
    SYNTAX_ERROR(config, "<string>:1.69: dns-server-timeout"
                         " must be greater than zero");
412 413 414

    // Invalid protocol
    config = makeParamsConfigString ("127.0.0.1", 777, 333, "BOGUS", "JSON");
415 416
    SYNTAX_ERROR(config, "<string>:1.92-98: syntax error,"
                         " unexpected constant string, expecting UDP or TCP");
417

418 419
    // Unsupported protocol
    config = makeParamsConfigString ("127.0.0.1", 777, 333, "TCP", "JSON");
420
    LOGIC_ERROR(config, "ncr-protocol : TCP is not yet supported"
421
                        " (<string>:1:92)");
422

423 424
    // Invalid format
    config = makeParamsConfigString ("127.0.0.1", 777, 333, "UDP", "BOGUS");
425 426
    SYNTAX_ERROR(config, "<string>:1.115-121: syntax error,"
                         " unexpected constant string, expecting JSON");
427 428
}

429 430
// Control socket tests in d2_process_unittests.cc

431
// DdnsDomainList and TSIGKey tests moved to d2_simple_parser_unittest.cc
432 433 434 435

/// @brief Tests construction of D2CfgMgr
/// This test verifies that a D2CfgMgr constructs properly.
TEST(D2CfgMgr, construction) {
436
    boost::scoped_ptr<D2CfgMgr> cfg_mgr;
437 438

    // Verify that configuration manager constructions without error.
439
    ASSERT_NO_THROW(cfg_mgr.reset(new D2CfgMgr()));
440 441 442 443 444 445 446 447 448 449 450 451 452

    // Verify that the context can be retrieved and is not null.
    D2CfgContextPtr context;
    ASSERT_NO_THROW(context = cfg_mgr->getD2CfgContext());
    EXPECT_TRUE(context);

    // Verify that the forward manager can be retrieved and is not null.
    EXPECT_TRUE(context->getForwardMgr());

    // Verify that the reverse manager can be retrieved and is not null.
    EXPECT_TRUE(context->getReverseMgr());

    // Verify that the manager can be destructed without error.
453
    EXPECT_NO_THROW(cfg_mgr.reset());
454 455 456 457 458 459
}

/// @brief Tests the parsing of a complete, valid DHCP-DDNS configuration.
/// This tests passes the configuration into an instance of D2CfgMgr just
/// as it would be done by d2_process in response to a configuration update
/// event.
460
TEST_F(D2CfgMgrTest, fullConfig) {
461 462 463 464
    // Create a configuration with all of application level parameters, plus
    // both the forward and reverse ddns managers.  Both managers have two
    // domains with three servers per domain.
    std::string config = "{ "
465
                        "\"ip-address\" : \"192.168.1.33\" , "
466
                        "\"port\" : 88 , "
467 468 469 470 471 472 473
                        "\"dns-server-timeout\": 333 , "
                        "\"ncr-protocol\": \"UDP\" , "
                        "\"ncr-format\": \"JSON\", "
                        "\"control-socket\" : {"
                        " \"socket-type\" : \"unix\" ,"
                        " \"socket-name\" : \"/tmp/d2-ctrl-channel\" "
                        "},"
474
                        "\"tsig-keys\": ["
475
                        "{"
476
                        "  \"name\": \"d2_key.example.com\" , "
477
                        "  \"algorithm\": \"hmac-md5\" , "
478
                        "   \"secret\": \"LSWXnfkKZjdPJI5QxlpnfQ==\" "
479 480 481
                        "},"
                        "{"
                        "  \"name\": \"d2_key.billcat.net\" , "
482
                        "  \"algorithm\": \"hmac-md5\" , "
483
                        " \"digest-bits\": 120 , "
484
                        "   \"secret\": \"LSWXnfkKZjdPJI5QxlpnfQ==\" "
485 486
                        "}"
                        "],"
487 488
                        "\"forward-ddns\" : {"
                        "\"ddns-domains\": [ "
489 490
                        "{ \"name\": \"example.com\" , "
                        "  \"key-name\": \"d2_key.example.com\" , "
491 492 493 494
                        "  \"dns-servers\" : [ "
                        "  { \"ip-address\": \"127.0.0.1\" } , "
                        "  { \"ip-address\": \"127.0.0.2\" } , "
                        "  { \"ip-address\": \"127.0.0.3\"} "
495 496 497
                        "  ] } "
                        ", "
                        "{ \"name\": \"billcat.net\" , "
498 499 500 501 502
                        "  \"key-name\": \"d2_key.billcat.net\" , "
                        "  \"dns-servers\" : [ "
                        "  { \"ip-address\": \"127.0.0.4\" } , "
                        "  { \"ip-address\": \"127.0.0.5\" } , "
                        "  { \"ip-address\": \"127.0.0.6\" } "
503 504
                        "  ] } "
                        "] },"
505 506
                        "\"reverse-ddns\" : {"
                        "\"ddns-domains\": [ "
507
                        "{ \"name\": \" 0.168.192.in.addr.arpa.\" , "
508
                        "  \"key-name\": \"d2_key.example.com\" , "
509 510 511 512
                        "  \"dns-servers\" : [ "
                        "  { \"ip-address\": \"127.0.1.1\" } , "
                        "  { \"ip-address\": \"127.0.2.1\" } , "
                        "  { \"ip-address\": \"127.0.3.1\" } "
513 514 515
                        "  ] } "
                        ", "
                        "{ \"name\": \" 0.247.106.in.addr.arpa.\" , "
516 517 518 519 520
                        "  \"key-name\": \"d2_key.billcat.net\" , "
                        "  \"dns-servers\" : [ "
                        "  { \"ip-address\": \"127.0.4.1\" }, "
                        "  { \"ip-address\": \"127.0.5.1\" } , "
                        "  { \"ip-address\": \"127.0.6.1\" } "
521 522
                        "  ] } "
                        "] } }";
523

524 525
    // Should parse without error.
    RUN_CONFIG_OK(config);
526 527 528 529 530

    // Verify that the D2 context can be retrieved and is not null.
    D2CfgContextPtr context;
    ASSERT_NO_THROW(context = cfg_mgr_->getD2CfgContext());

531 532 533
    // Verify that the global scalars have the proper values.
    D2ParamsPtr& d2_params = context->getD2Params();
    ASSERT_TRUE(d2_params);
534

535 536 537 538 539 540
    EXPECT_EQ(isc::asiolink::IOAddress("192.168.1.33"),
              d2_params->getIpAddress());
    EXPECT_EQ(88, d2_params->getPort());
    EXPECT_EQ(333, d2_params->getDnsServerTimeout());
    EXPECT_EQ(dhcp_ddns::NCR_UDP, d2_params->getNcrProtocol());
    EXPECT_EQ(dhcp_ddns::FMT_JSON, d2_params->getNcrFormat());
541

542 543 544 545 546 547 548 549 550 551
    // Verify that the control socket can be retrieved.
    ConstElementPtr ctrl_sock = context->getControlSocketInfo();
    ASSERT_TRUE(ctrl_sock);
    ASSERT_EQ(Element::map, ctrl_sock->getType());
    EXPECT_EQ(2, ctrl_sock->size());
    ASSERT_TRUE(ctrl_sock->get("socket-type"));
    EXPECT_EQ("\"unix\"", ctrl_sock->get("socket-type")->str());
    ASSERT_TRUE(ctrl_sock->get("socket-name"));
    EXPECT_EQ("\"/tmp/d2-ctrl-channel\"", ctrl_sock->get("socket-name")->str());

552 553 554
    // Verify that the forward manager can be retrieved.
    DdnsDomainListMgrPtr mgr = context->getForwardMgr();
    ASSERT_TRUE(mgr);
555
    EXPECT_EQ("forward-ddns", mgr->getName());
556 557

    // Verify that the forward manager has the correct number of domains.
558
    DdnsDomainMapPtr domains = mgr->getDomains();
559 560
    ASSERT_TRUE(domains);
    int count =  domains->size();
561
    EXPECT_EQ(2, count);
562 563 564 565 566

    // Verify that the server count in each of the forward manager domains.
    // NOTE that since prior tests have validated server parsing, we are are
    // assuming that the servers did in fact parse correctly if the correct
    // number of them are there.
567
    DdnsDomainMapPair domain_pair;
568 569 570 571 572
    BOOST_FOREACH(domain_pair, (*domains)) {
        DdnsDomainPtr domain = domain_pair.second;
        DnsServerInfoStoragePtr servers = domain->getServers();
        count = servers->size();
        EXPECT_TRUE(servers);
573
        EXPECT_EQ(3, count);
574 575 576 577 578
    }

    // Verify that the reverse manager can be retrieved.
    mgr = context->getReverseMgr();
    ASSERT_TRUE(mgr);
579
    EXPECT_EQ("reverse-ddns", mgr->getName());
580 581 582 583

    // Verify that the reverse manager has the correct number of domains.
    domains = mgr->getDomains();
    count =  domains->size();
584
    EXPECT_EQ(2, count);
585 586 587 588 589 590 591 592 593 594

    // Verify that the server count in each of the reverse manager domains.
    // NOTE that since prior tests have validated server parsing, we are are
    // assuming that the servers did in fact parse correctly if the correct
    // number of them are there.
    BOOST_FOREACH(domain_pair, (*domains)) {
        DdnsDomainPtr domain = domain_pair.second;
        DnsServerInfoStoragePtr servers = domain->getServers();
        count = servers->size();
        EXPECT_TRUE(servers);
595
        EXPECT_EQ(3, count);
596
    }
597

598 599 600 601
    // Test directional update flags.
    EXPECT_TRUE(cfg_mgr_->forwardUpdatesEnabled());
    EXPECT_TRUE(cfg_mgr_->reverseUpdatesEnabled());

602
    // Verify that parsing the exact same configuration a second time
603
    // does not cause a duplicate value errors.
604
    answer_ = cfg_mgr_->simpleParseConfig(config_set_, false);
605
    ASSERT_TRUE(checkAnswer(0));
606 607 608 609 610 611 612 613 614 615 616
}

/// @brief Tests the basics of the D2CfgMgr FQDN-domain matching
/// This test uses a valid configuration to exercise the D2CfgMgr
/// forward FQDN-to-domain matching.
/// It verifies that:
/// 1. Given an FQDN which exactly matches a domain's name, that domain is
/// returned as match.
/// 2. Given a FQDN for sub-domain in the list, returns the proper match.
/// 3. Given a FQDN that matches no domain name, returns the wild card domain
/// as a match.
617
TEST_F(D2CfgMgrTest, forwardMatch) {
618 619 620
    // Create  configuration with one domain, one sub domain, and the wild
    // card.
    std::string config = "{ "
621
                        "\"ip-address\" : \"192.168.1.33\" , "
622
                        "\"port\" : 88 , "
623 624 625
                        "\"tsig-keys\": [] ,"
                        "\"forward-ddns\" : {"
                        "\"ddns-domains\": [ "
626
                        "{ \"name\": \"example.com\" , "
627 628
                        "  \"dns-servers\" : [ "
                        "  { \"ip-address\": \"127.0.0.1\" } "
629 630
                        "  ] } "
                        ", "
631
                        "{ \"name\": \"one.example.com\" , "
632 633
                        "  \"dns-servers\" : [ "
                        "  { \"ip-address\": \"127.0.0.2\" } "
634 635 636
                        "  ] } "
                        ", "
                        "{ \"name\": \"*\" , "
637 638
                        "  \"dns-servers\" : [ "
                        "  { \"ip-address\": \"127.0.0.3\" } "
639
                        "  ] } "
640
                        "] }, "
641
                        "\"reverse-ddns\" : {} "
642 643
                        "}";

644
    // Verify that we can parse the configuration.
645
    RUN_CONFIG_OK(config);
646 647 648 649 650

    // Verify that the D2 context can be retrieved and is not null.
    D2CfgContextPtr context;
    ASSERT_NO_THROW(context = cfg_mgr_->getD2CfgContext());

651 652 653 654
    // Test directional update flags.
    EXPECT_TRUE(cfg_mgr_->forwardUpdatesEnabled());
    EXPECT_FALSE(cfg_mgr_->reverseUpdatesEnabled());

655 656
    DdnsDomainPtr match;
    // Verify that an exact match works.
657 658
    EXPECT_TRUE(cfg_mgr_->matchForward("example.com", match));
    EXPECT_EQ("example.com", match->getName());
659

660 661 662
    // Verify that search is case insensitive.
    EXPECT_TRUE(cfg_mgr_->matchForward("EXAMPLE.COM", match));
    EXPECT_EQ("example.com", match->getName());
663

664
    // Verify that an exact match works.
665 666
    EXPECT_TRUE(cfg_mgr_->matchForward("one.example.com", match));
    EXPECT_EQ("one.example.com", match->getName());
667 668

    // Verify that a FQDN for sub-domain matches.
669 670
    EXPECT_TRUE(cfg_mgr_->matchForward("blue.example.com", match));
    EXPECT_EQ("example.com", match->getName());
671 672

    // Verify that a FQDN for sub-domain matches.
673 674
    EXPECT_TRUE(cfg_mgr_->matchForward("red.one.example.com", match));
    EXPECT_EQ("one.example.com", match->getName());
675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690

    // Verify that an FQDN with no match, returns the wild card domain.
    EXPECT_TRUE(cfg_mgr_->matchForward("shouldbe.wildcard", match));
    EXPECT_EQ("*", match->getName());

    // Verify that an attempt to match an empty FQDN throws.
    ASSERT_THROW(cfg_mgr_->matchForward("", match), D2CfgError);
}

/// @brief Tests domain matching when there is no wild card domain.
/// This test verifies that matches are found only for FQDNs that match
/// some or all of a domain name.  FQDNs without matches should not return
/// a match.
TEST_F(D2CfgMgrTest, matchNoWildcard) {
    // Create a configuration with one domain, one sub-domain, and NO wild card.
    std::string config = "{ "
691
                        "\"ip-address\" : \"192.168.1.33\" , "
692
                        "\"port\" : 88 , "
693 694 695
                        "\"tsig-keys\": [] ,"
                        "\"forward-ddns\" : {"
                        "\"ddns-domains\": [ "
696
                        "{ \"name\": \"example.com\" , "
697 698
                        "  \"dns-servers\" : [ "
                        "  { \"ip-address\": \"127.0.0.1\" } "
699 700
                        "  ] } "
                        ", "
701
                        "{ \"name\": \"one.example.com\" , "
702 703
                        "  \"dns-servers\" : [ "
                        "  { \"ip-address\": \"127.0.0.2\" } "
704
                        "  ] } "
705
                        "] }, "
706
                        "\"reverse-ddns\" : {} "
707
                        " }";
708 709

    // Verify that we can parse the configuration.
710
    RUN_CONFIG_OK(config);
711 712 713 714 715 716 717

    // Verify that the D2 context can be retrieved and is not null.
    D2CfgContextPtr context;
    ASSERT_NO_THROW(context = cfg_mgr_->getD2CfgContext());

    DdnsDomainPtr match;
    // Verify that full or partial matches, still match.
718 719
    EXPECT_TRUE(cfg_mgr_->matchForward("example.com", match));
    EXPECT_EQ("example.com", match->getName());
720

721 722
    EXPECT_TRUE(cfg_mgr_->matchForward("blue.example.com", match));
    EXPECT_EQ("example.com", match->getName());
723

724 725
    EXPECT_TRUE(cfg_mgr_->matchForward("red.one.example.com", match));
    EXPECT_EQ("one.example.com", match->getName());
726 727 728 729 730 731 732 733 734

    // Verify that a FQDN with no match, fails to match.
    EXPECT_FALSE(cfg_mgr_->matchForward("shouldbe.wildcard", match));
}

/// @brief Tests domain matching when there is ONLY a wild card domain.
/// This test verifies that any FQDN matches the wild card.
TEST_F(D2CfgMgrTest, matchAll) {
    std::string config = "{ "
735
                        "\"ip-address\" : \"192.168.1.33\" , "
736
                        "\"port\" : 88 , "
737 738 739
                        "\"tsig-keys\": [] ,"
                        "\"forward-ddns\" : {"
                        "\"ddns-domains\": [ "
740
                        "{ \"name\": \"*\" , "
741 742
                        "  \"dns-servers\" : [ "
                        "  { \"ip-address\": \"127.0.0.1\" } "
743
                        "  ] } "
744
                        "] }, "
745
                        "\"reverse-ddns\" : {} "
746
                        "}";
747 748

    // Verify that we can parse the configuration.
749
    RUN_CONFIG_OK(config);
750 751 752 753 754 755 756

    // Verify that the D2 context can be retrieved and is not null.
    D2CfgContextPtr context;
    ASSERT_NO_THROW(context = cfg_mgr_->getD2CfgContext());

    // Verify that wild card domain is returned for any FQDN.
    DdnsDomainPtr match;
757
    EXPECT_TRUE(cfg_mgr_->matchForward("example.com", match));
758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777
    EXPECT_EQ("*", match->getName());
    EXPECT_TRUE(cfg_mgr_->matchForward("shouldbe.wildcard", match));
    EXPECT_EQ("*", match->getName());

    // Verify that an attempt to match an empty FQDN still throws.
    ASSERT_THROW(cfg_mgr_->matchReverse("", match), D2CfgError);

}

/// @brief Tests the basics of the D2CfgMgr reverse FQDN-domain matching
/// This test uses a valid configuration to exercise the D2CfgMgr's
/// reverse FQDN-to-domain matching.
/// It verifies that:
/// 1. Given an FQDN which exactly matches a domain's name, that domain is
/// returned as match.
/// 2. Given a FQDN for sub-domain in the list, returns the proper match.
/// 3. Given a FQDN that matches no domain name, returns the wild card domain
/// as a match.
TEST_F(D2CfgMgrTest, matchReverse) {
    std::string config = "{ "
778
                        "\"ip-address\" : \"192.168.1.33\" , "
779
                        "\"port\" : 88 , "
780 781 782 783
                        "\"tsig-keys\": [] ,"
                        "\"forward-ddns\" : {}, "
                        "\"reverse-ddns\" : {"
                        "\"ddns-domains\": [ "
784
                        "{ \"name\": \"5.100.168.192.in-addr.arpa.\" , "
785 786
                        "  \"dns-servers\" : [ "
                        "  { \"ip-address\": \"127.0.0.1\" } "
787
                        "  ] }, "
788
                        "{ \"name\": \"100.200.192.in-addr.arpa.\" , "
789 790
                        "  \"dns-servers\" : [ "
                        "  { \"ip-address\": \"127.0.0.1\" } "
791
                        "  ] }, "
792
                        "{ \"name\": \"170.192.in-addr.arpa.\" , "
793 794
                        "  \"dns-servers\" : [ "
                        "  { \"ip-address\": \"127.0.0.1\" } "
795
                        "  ] }, "
796 797
                        // Note mixed case to test case insensitivity.
                        "{ \"name\": \"2.0.3.0.8.b.d.0.1.0.0.2.IP6.ARPA.\" , "
798 799
                        "  \"dns-servers\" : [ "
                        "  { \"ip-address\": \"127.0.0.1\" } "
800
                        "  ] },"
801
                        "{ \"name\": \"*\" , "
802 803
                        "  \"dns-servers\" : [ "
                        "  { \"ip-address\": \"127.0.0.1\" } "
804 805 806 807
                        "  ] } "
                        "] } }";

    // Verify that we can parse the configuration.
808
    RUN_CONFIG_OK(config);
809 810 811 812 813

    // Verify that the D2 context can be retrieved and is not null.
    D2CfgContextPtr context;
    ASSERT_NO_THROW(context = cfg_mgr_->getD2CfgContext());

814 815 816 817
    // Test directional update flags.
    EXPECT_FALSE(cfg_mgr_->forwardUpdatesEnabled());
    EXPECT_TRUE(cfg_mgr_->reverseUpdatesEnabled());

818
    DdnsDomainPtr match;
819

820
    // Verify an exact match.
821 822
    EXPECT_TRUE(cfg_mgr_->matchReverse("192.168.100.5", match));
    EXPECT_EQ("5.100.168.192.in-addr.arpa.", match->getName());
823 824

    // Verify a sub-domain match.
825 826
    EXPECT_TRUE(cfg_mgr_->matchReverse("192.200.100.27", match));
    EXPECT_EQ("100.200.192.in-addr.arpa.", match->getName());
827 828

    // Verify a sub-domain match.
829 830
    EXPECT_TRUE(cfg_mgr_->matchReverse("192.170.50.30", match));
    EXPECT_EQ("170.192.in-addr.arpa.", match->getName());
831 832

    // Verify a wild card match.
833
    EXPECT_TRUE(cfg_mgr_->matchReverse("1.1.1.1", match));
834 835
    EXPECT_EQ("*", match->getName());

836 837
    // Verify a IPv6 match.
    EXPECT_TRUE(cfg_mgr_->matchReverse("2001:db8:302:99::",match));
838
    EXPECT_EQ("2.0.3.0.8.b.d.0.1.0.0.2.IP6.ARPA.", match->getName());
839

840
    // Verify a IPv6 wild card match.
841 842 843 844
    EXPECT_TRUE(cfg_mgr_->matchReverse("2001:db8:99:302::",match));
    EXPECT_EQ("*", match->getName());

    // Verify that an attempt to match an invalid IP address throws.
845 846 847
    ASSERT_THROW(cfg_mgr_->matchReverse("", match), D2CfgError);
}

848
/// @brief Tests D2 config parsing against a wide range of config permutations.
849 850 851 852 853
///
/// It tests for both syntax errors that the JSON parsing (D2ParserContext)
/// should detect as well as post-JSON parsing logic errors generated by
/// the Element parsers (i.e...SimpleParser/DhcpParser derivations)
///
854 855 856 857 858 859 860 861 862 863 864 865 866 867 868
/// It iterates over all of the test configurations described in given file.
/// The file content is JSON specialized to this test. The format of the file
/// is:
///
/// @code
/// # The file must open with a list. It's name is arbitrary.
///
/// { "test_list" :
/// [
///
/// #    Test one starts here:
///      {
///
/// #    Each test has:
/// #      1. description - optional text description
869 870 871
/// #      2. syntax-error - error JSON parser should emit (omit if none)
/// #      3. logic-error - error element parser(s) should emit (omit if none)
/// #      4. data - configuration text to parse
872 873
/// #
///      "description" : "<text describing test>",
874 875
///      "syntax-error" : "<exact text from JSON parser including position>" ,
///      "logic-error" : "<exact text from element parser including position>" ,
876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908
///      "data" :
///          {
/// #        configuration elements here
///          "bool_val" : false,
///          "some_map" :  {}
/// #         :
///          }
///      }
///
/// #    Next test would start here
///      ,
///      {
///      }
///
/// ]}
///
/// @endcode
///
/// (The file supports comments per Element::fromJSONFile())
///
TEST_F(D2CfgMgrTest, configPermutations) {
    std::string test_file = testDataFile("d2_cfg_tests.json");
    isc::data::ConstElementPtr tests;

    // Read contents of the file and parse it as JSON. Note it must contain
    // all valid JSON, we aren't testing JSON parsing.
    try {
        tests = isc::data::Element::fromJSONFile(test_file, true);
    } catch (const std::exception& ex) {
        FAIL() << "ERROR parsing file : " << test_file << " : " << ex.what();
    }

    // Read in each test For each test, read:
909
    //
910
    //  1. description - optional text description
911
    //  2. syntax-error or logic-error or neither
912
    //  3. data - configuration text to parse
913 914
    //  4. convert data into JSON text
    //  5. submit JSON for parsing
915
    isc::data::ConstElementPtr test;
916 917
    ASSERT_TRUE(tests->get("test-list"));
    BOOST_FOREACH(test, tests->get("test-list")->listValue()) {
918 919 920 921 922 923 924
        // Grab the description.
        std::string description = "<no desc>";
        isc::data::ConstElementPtr elem = test->get("description");
        if (elem) {
            elem->getValue(description);
        }

925 926 927 928 929 930 931 932 933 934 935 936 937
        // Grab the expected error message, if there is one.
        std::string expected_error = "";
        RunConfigMode mode = NO_ERROR;
        elem = test->get("syntax-error");
        if (elem) {
            elem->getValue(expected_error);
            mode = SYNTAX_ERROR;
        } else {
            elem = test->get("logic-error");
            if (elem) {
                elem->getValue(expected_error);
                mode = LOGIC_ERROR;
            }
938 939 940 941
        }

        // Grab the test's configuration data.
        isc::data::ConstElementPtr data = test->get("data");
942
        ASSERT_TRUE(data) << "No data for test: " << test->getPosition();
943

944 945 946 947 948
        // Convert the test data back to JSON text, then submit it for parsing.
        stringstream os;
        data->toJSON(os);
        EXPECT_TRUE(runConfigOrFail(os.str(), mode, expected_error))
            << " failed for test: " << test->getPosition() << std::endl;
949 950 951
    }
}

Francis Dupont's avatar
Francis Dupont committed
952 953 954 955 956 957
/// @brief Tests comments.
TEST_F(D2CfgMgrTest, comments) {
    std::string config = "{ "
                        "\"comment\": \"D2 config\" , "
                        "\"ip-address\" : \"192.168.1.33\" , "
                        "\"port\" : 88 , "
958 959 960 961 962
                        "\"control-socket\": {"
                        " \"comment\": \"Control channel\" , "
                        " \"socket-type\": \"unix\" ,"
                        " \"socket-name\": \"/tmp/d2-ctrl-channel\" "
                        "},"
Francis Dupont's avatar
Francis Dupont committed
963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997
                        "\"tsig-keys\": ["
                        "{"
                        "  \"user-context\": { "
                        "    \"comment\": \"Indirect comment\" } , "
                        "  \"name\": \"d2_key.example.com\" , "
                        "  \"algorithm\": \"hmac-md5\" , "
                        "  \"secret\": \"LSWXnfkKZjdPJI5QxlpnfQ==\" "
                        "}"
                        "],"
                        "\"forward-ddns\" : {"
                        "\"ddns-domains\": [ "
                        "{ \"comment\": \"A DDNS domain\" , "
                        "  \"name\": \"example.com\" , "
                        "  \"key-name\": \"d2_key.example.com\" , "
                        "  \"dns-servers\" : [ "
                        "  { \"ip-address\": \"127.0.0.1\" , "
                        "    \"user-context\": { \"version\": 1 } } "
                        "  ] } "
                        "] } }";

    // Should parse without error.
    RUN_CONFIG_OK(config);

    // Check the D2 context.
    D2CfgContextPtr d2_context;
    ASSERT_NO_THROW(d2_context = cfg_mgr_->getD2CfgContext());
    ASSERT_TRUE(d2_context);

    // Check global user context.
    ConstElementPtr ctx = d2_context->getContext();
    ASSERT_TRUE(ctx);
    ASSERT_EQ(1, ctx->size());
    ASSERT_TRUE(ctx->get("comment"));
    EXPECT_EQ("\"D2 config\"", ctx->get("comment")->str());

998 999 1000 1001 1002 1003 1004
    // Check control socket.
    ConstElementPtr ctrl_sock = d2_context->getControlSocketInfo();
    ASSERT_TRUE(ctrl_sock);
    ASSERT_TRUE(ctrl_sock->get("user-context"));
    EXPECT_EQ("{ \"comment\": \"Control channel\" }",
              ctrl_sock->get("user-context")->str());

Francis Dupont's avatar
Francis Dupont committed
1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050
    // Check TSIG keys.
    TSIGKeyInfoMapPtr keys = d2_context->getKeys();
    ASSERT_TRUE(keys);
    ASSERT_EQ(1, keys->size());

    // Check the TSIG key.
    TSIGKeyInfoMap::iterator gotkey = keys->find("d2_key.example.com");
    ASSERT_TRUE(gotkey != keys->end());
    TSIGKeyInfoPtr key = gotkey->second;
    ASSERT_TRUE(key);

    // Check the TSIG key user context.
    ConstElementPtr key_ctx = key->getContext();
    ASSERT_TRUE(key_ctx);
    ASSERT_EQ(1, key_ctx->size());
    ASSERT_TRUE(key_ctx->get("comment"));
    EXPECT_EQ("\"Indirect comment\"", key_ctx->get("comment")->str());

    // Check the forward manager.
    DdnsDomainListMgrPtr mgr = d2_context->getForwardMgr();
    ASSERT_TRUE(mgr);
    EXPECT_EQ("forward-ddns", mgr->getName());
    DdnsDomainMapPtr domains = mgr->getDomains();
    ASSERT_TRUE(domains);
    ASSERT_EQ(1, domains->size());

    // Check the DDNS domain.
    DdnsDomainMap::iterator gotdns = domains->find("example.com");
    ASSERT_TRUE(gotdns != domains->end());
    DdnsDomainPtr domain = gotdns->second;
    ASSERT_TRUE(domain);

    // Check the DNS server.
    DnsServerInfoStoragePtr servers = domain->getServers();
    ASSERT_TRUE(servers);
    ASSERT_EQ(1, servers->size());
    DnsServerInfoPtr server = (*servers)[0];
    ASSERT_TRUE(server);

    // Check the DNS server user context.
    ConstElementPtr srv_ctx = server->getContext();
    ASSERT_TRUE(srv_ctx);
    ASSERT_EQ(1, srv_ctx->size());
    ASSERT_TRUE(srv_ctx->get("version"));
    EXPECT_EQ("1", srv_ctx->get("version")->str());
}