d2_cfg_mgr_unittests.cc 64.4 KB
Newer Older
1
// Copyright (C) 2013-2016 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 11
#include <config/module_spec.h>
#include <d2/d2_config.h>
#include <d2/d2_cfg_mgr.h>
12 13
#include <dhcpsrv/testutils/config_result_check.h>
#include <process/testutils/d_test_stubs.h>
14
#include <test_data_files_config.h>
15
#include <util/encode/base64.h>
16 17

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

using namespace std;
using namespace isc;
using namespace isc::d2;

namespace {

27 28 29 30 31 32
/// @brief Function to create full path to the spec file
///
/// The full path is dependent upon the value of D2_SRC_DIR which
/// whose value is generated from test_data_files_config.h.in
///
/// @param name file name to which the path should be prepended
33 34 35 36
std::string specfile(const std::string& name) {
    return (std::string(D2_SRC_DIR) + "/" + name);
}

37 38 39 40 41 42
/// @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
43 44 45 46
std::string testDataFile(const std::string& name) {
    return (std::string(D2_TEST_DATA_DIR) + "/" + name);
}

47 48 49 50 51 52 53 54
/// @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
55
    D2CfgMgrTest():cfg_mgr_(new D2CfgMgr()), d2_params_() {
56 57 58 59 60 61 62 63
    }

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

    /// @brief Configuration manager instance.
    D2CfgMgrPtr cfg_mgr_;
64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84

    /// @brief Build JSON configuration string for a D2Params element
    ///
    /// Constructs a JSON string for "params" element using replacable
    /// 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 <<
            "{"
85
            " \"ip-address\": \"" << ip_address << "\" , "
86
            " \"port\": " << port << " , "
87 88 89 90 91 92
            " \"dns-server-timeout\": " << dns_server_timeout << " , "
            " \"ncr-protocol\": \"" << ncr_protocol << "\" , "
            " \"ncr-format\": \"" << ncr_format << "\", "
            "\"tsig-keys\": [], "
            "\"forward-ddns\" : {}, "
            "\"reverse-ddns\" : {} "
93 94 95 96
            "}";

        return (config.str());
    }
97 98 99 100 101 102
    /// @brief Enumeration to select between expected configuration outcomes
    enum RunConfigMode {
       SHOULD_PASS,
       SHOULD_FAIL
    };

103 104 105 106 107 108 109 110 111 112
    /// @brief Parses a configuration string and tests against a given outcome
    ///
    /// Convenience method which accepts JSON text and an expected pass or fail
    /// outcome. It converts the text into an ElementPtr and passes that to
    /// configuration manager's parseConfig method.  It then tests the
    /// parse result against the expected outcome  If they do not match it
    /// the method asserts a failure.   If they do match, it refreshes the
    /// the D2Params pointer with the newly parsed instance.
    ///
    /// @param config_str the JSON configuration text to parse
113 114 115 116
    /// @param mode indicator if the parsing should fail or not.  It defaults
    /// defaults to SHOULD_PASS.
    ///
    void runConfig(std::string config_str, RunConfigMode mode=SHOULD_PASS) {
117 118 119 120 121
        // We assume the config string is valid JSON.
        ASSERT_TRUE(fromJSON(config_str));

        // Parse the configuration and verify we got the expected outcome.
        answer_ = cfg_mgr_->parseConfig(config_set_);
122
        ASSERT_TRUE(checkAnswer(mode == SHOULD_FAIL));
123 124 125 126 127 128 129 130 131 132

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

        // Verify that the global scalars have the proper values.
        d2_params_ = context->getD2Params();
        ASSERT_TRUE(d2_params_);
    }

133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176
    /// @brief Check parse result against expected outcome and position info
    ///
    /// This method analyzes the given parsing result against an expected outcome
    /// of SHOULD_PASS or SHOULD_FAIL.  If it is expected to fail, the comment
    /// contained within the result is searched for Element::Position information
    /// which should contain the given file name.  It does not attempt to verify
    /// the numerical values for line number and col.
    ///
    /// @param answer Element set containing an integer result code and string
    /// comment.
    /// @param mode indicator if the parsing should fail or not.
    /// @param file_name name of the file containing the configuration text
    /// parsed. It defaults to "<string>" which is the value present if the
    /// configuration text did not originate from a file. (i.e. one did not use
    /// isc::data::Element::fromJSONFile() to read the JSON text).
    void
    checkAnswerWithError(isc::data::ConstElementPtr answer,
                         RunConfigMode mode, std::string file_name="<string>") {
        int rcode = 0;
        isc::data::ConstElementPtr comment;
        comment = isc::config::parseAnswer(rcode, answer);

        if (mode == SHOULD_PASS) {
            if (rcode == 0) {
                return;
            }

            FAIL() << "Parsing was expected to pass but failed : " << rcode
                   << " comment: " << *comment;
        }

        if (rcode == 0) {
            FAIL() << "Parsing was expected to fail but passed : "
                   << " comment: " << *comment;
        }

        // Parsing was expected to fail, test for position info.
        if (isc::dhcp::test::errorContainsPosition(answer, file_name)) {
            return;
        }

        FAIL() << "Parsing failed as expected but lacks position : " << *comment;
    }

177
    /// @brief Pointer the D2Params most recently parsed.
178
    D2ParamsPtr d2_params_;
179 180 181
};

/// @brief Tests that the spec file is valid.
182
/// Verifies that the DHCP-DDNS configuration specification file
183
//  is valid.
184
TEST(D2SpecTest, basicSpec) {
185 186
    ASSERT_NO_THROW(isc::config::
                    moduleSpecFromFile(specfile("dhcp-ddns.spec")));
187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208
}

/// @brief Convenience function which compares the contents of the given
/// DnsServerInfo against the given set of values.
///
/// It is structured in such a way that each value is checked, and output
/// is generate for all that do not match.
///
/// @param server is a pointer to the server to check against.
/// @param hostname is the value to compare against server's hostname_.
/// @param ip_address is the string value to compare against server's
/// ip_address_.
/// @param port is the value to compare against server's port.
///
/// @return returns true if there is a match across the board, otherwise it
/// returns false.
bool checkServer(DnsServerInfoPtr server, const char* hostname,
                 const char *ip_address, uint32_t port)
{
    // Return value, assume its a match.
    bool result = true;

209
    if (!server) {
210 211 212 213 214 215
        EXPECT_TRUE(server);
        return false;
    }

    // Check hostname.
    if (server->getHostname() != hostname) {
216
        EXPECT_EQ(hostname, server->getHostname());
217 218 219 220 221
        result = false;
    }

    // Check IP address.
    if (server->getIpAddress().toText() != ip_address) {
222
        EXPECT_EQ(ip_address, server->getIpAddress().toText());
223 224 225 226 227
        result = false;
    }

    // Check port.
    if (server->getPort() !=  port) {
228
        EXPECT_EQ (port, server->getPort());
229 230 231 232 233 234
        result = false;
    }

    return (result);
}

235
/// @brief Convenience function which compares the contents of the given
236 237
/// TSIGKeyInfo against the given set of values, and that the TSIGKey
/// member points to a key.
238
///
239
/// @param key is a pointer to the TSIGKeyInfo instance to verify
240 241 242 243 244 245
/// @param name is the value to compare against key's name_.
/// @param algorithm is the string value to compare against key's algorithm.
/// @param secret is the value to compare against key's secret.
///
/// @return returns true if there is a match across the board, otherwise it
/// returns false.
246
bool checkKey(TSIGKeyInfoPtr key, const std::string& name,
Francis Dupont's avatar
Francis Dupont committed
247
              const std::string& algorithm, const std::string& secret,
248
              uint32_t digestbits = 0) {
249
    // Return value, assume its a match.
250 251 252
    return (((key) &&
        (key->getName() == name) &&
        (key->getAlgorithm() == algorithm)  &&
253
        (key->getDigestbits() == digestbits) &&
254 255
        (key->getSecret() ==  secret)  &&
        (key->getTSIGKey())));
256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284
}

/// @brief Test fixture class for testing DnsServerInfo parsing.
class TSIGKeyInfoTest : public ConfigParseTest {
public:

    /// @brief Constructor
    TSIGKeyInfoTest() {
        reset();
    }

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

    /// @brief Wipe out the current storage and parser and replace
    /// them with new ones.
    void reset() {
        keys_.reset(new TSIGKeyInfoMap());
        parser_.reset(new TSIGKeyInfoParser("test", keys_));
    }

    /// @brief Storage for "committing" keys.
    TSIGKeyInfoMapPtr keys_;

    /// @brief Pointer to the current parser instance.
    isc::dhcp::ParserPtr parser_;
};

285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311
/// @brief Test fixture class for testing DnsServerInfo parsing.
class DnsServerInfoTest : public ConfigParseTest {
public:

    /// @brief Constructor
    DnsServerInfoTest() {
        reset();
    }

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

    /// @brief Wipe out the current storage and parser and replace
    /// them with new ones.
    void reset() {
        servers_.reset(new DnsServerInfoStorage());
        parser_.reset(new DnsServerInfoParser("test", servers_));
    }

    /// @brief Storage for "committing" servers.
    DnsServerInfoStoragePtr servers_;

    /// @brief Pointer to the current parser instance.
    isc::dhcp::ParserPtr parser_;
};

312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341

/// @brief Test fixture class for testing DDnsDomain parsing.
class DdnsDomainTest : public ConfigParseTest {
public:

    /// @brief Constructor
    DdnsDomainTest() {
        reset();
    }

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

    /// @brief Wipe out the current storage and parser and replace
    /// them with new ones.
    void reset() {
        keys_.reset(new TSIGKeyInfoMap());
        domains_.reset(new DdnsDomainMap());
        parser_.reset(new DdnsDomainParser("test", domains_, keys_));
    }

    /// @brief Add TSIGKeyInfos to the key map
    ///
    /// @param name the name of the key
    /// @param algorithm the algorithm of the key
    /// @param secret the secret value of the key
    void addKey(const std::string& name, const std::string& algorithm,
                const std::string& secret) {
        TSIGKeyInfoPtr key_info(new TSIGKeyInfo(name, algorithm, secret));
342
        (*keys_)[name]=key_info;
343 344 345 346 347 348 349 350 351 352 353 354
    }

    /// @brief Storage for "committing" domains.
    DdnsDomainMapPtr domains_;

    /// @brief Storage for TSIGKeys
    TSIGKeyInfoMapPtr keys_;

    /// @brief Pointer to the current parser instance.
    isc::dhcp::ParserPtr parser_;
};

355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375
/// @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");
    runConfig(config);

    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");
    runConfig(config);

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

    // Verify the configuration summary.
378
    EXPECT_EQ("listening on 3001::5, port 777, using UDP",
379
              d2_params_->getConfigSummary());
380 381 382 383 384 385 386 387 388 389 390 391
}

/// @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) {

    // Check that omitting ip_address gets you its default
    std::string config =
            "{"
            " \"port\": 777 , "
392 393 394 395 396 397
            " \"dns-server-timeout\": 333 , "
            " \"ncr-protocol\": \"UDP\" , "
            " \"ncr-format\": \"JSON\", "
            "\"tsig-keys\": [], "
            "\"forward-ddns\" : {}, "
            "\"reverse-ddns\" : {} "
398 399 400 401 402 403 404 405 406
            "}";

    runConfig(config);
    EXPECT_EQ(isc::asiolink::IOAddress(D2Params::DFT_IP_ADDRESS),
              d2_params_->getIpAddress());

    // Check that omitting port gets you its default
    config =
            "{"
407 408 409 410 411 412 413
            " \"ip-address\": \"192.0.0.1\" , "
            " \"dns-server-timeout\": 333 , "
            " \"ncr-protocol\": \"UDP\" , "
            " \"ncr-format\": \"JSON\", "
            "\"tsig-keys\": [], "
            "\"forward-ddns\" : {}, "
            "\"reverse-ddns\" : {} "
414 415 416 417 418 419 420 421
            "}";

    runConfig(config);
    EXPECT_EQ(D2Params::DFT_PORT, d2_params_->getPort());

    // Check that omitting timeout gets you its default
    config =
            "{"
422
            " \"ip-address\": \"192.0.0.1\" , "
423
            " \"port\": 777 , "
424 425 426 427 428
            " \"ncr-protocol\": \"UDP\" , "
            " \"ncr-format\": \"JSON\", "
            "\"tsig-keys\": [], "
            "\"forward-ddns\" : {}, "
            "\"reverse-ddns\" : {} "
429 430 431 432 433 434 435 436 437
            "}";

    runConfig(config);
    EXPECT_EQ(D2Params::DFT_DNS_SERVER_TIMEOUT,
              d2_params_->getDnsServerTimeout());

    // Check that protocol timeout gets you its default
    config =
            "{"
438
            " \"ip-address\": \"192.0.0.1\" , "
439
            " \"port\": 777 , "
440 441 442 443 444
            " \"dns-server-timeout\": 333 , "
            " \"ncr-format\": \"JSON\", "
            "\"tsig-keys\": [], "
            "\"forward-ddns\" : {}, "
            "\"reverse-ddns\" : {} "
445 446 447 448 449 450 451 452 453
            "}";

    runConfig(config);
    EXPECT_EQ(dhcp_ddns::stringToNcrProtocol(D2Params::DFT_NCR_PROTOCOL),
              d2_params_->getNcrProtocol());

    // Check that format timeout gets you its default
    config =
            "{"
454
            " \"ip-address\": \"192.0.0.1\" , "
455
            " \"port\": 777 , "
456 457 458 459 460
            " \"dns-server-timeout\": 333 , "
            " \"ncr-protocol\": \"UDP\", "
            "\"tsig-keys\": [], "
            "\"forward-ddns\" : {}, "
            "\"reverse-ddns\" : {} "
461 462 463 464 465 466 467
            "}";

    runConfig(config);
    EXPECT_EQ(dhcp_ddns::stringToNcrFormat(D2Params::DFT_NCR_FORMAT),
              d2_params_->getNcrFormat());
}

468 469 470 471 472
/// @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 =
            "{"
473
            " \"ip-address\": \"127.0.0.1\", "
474
            " \"port\": 777 , "
475 476 477 478 479 480 481
            " \"dns-server-timeout\": 333 , "
            " \"ncr-protocol\": \"UDP\" , "
            " \"ncr-format\": \"JSON\", "
            "\"tsig-keys\": [], "
            "\"forward-ddns\" : {}, "
            "\"reverse-ddns\" : {}, "
            "\"bogus-param\" : true "
482 483 484 485 486 487 488 489
            "}";

    runConfig(config, SHOULD_FAIL);

    // Check that unsupported top level objects fails.  For
    // D2 these fail as they are not in the parse order.
    config =
            "{"
490
            " \"ip-address\": \"127.0.0.1\", "
491
            " \"port\": 777 , "
492 493 494 495 496 497 498 499
            " \"dns-server-timeout\": 333 , "
            " \"ncr-protocol\": \"UDP\" , "
            " \"ncr-format\": \"JSON\", "
            "\"tsig-keys\": [], "
            "\"bogus-object-one\" : {}, "
            "\"forward-ddns\" : {}, "
            "\"reverse-ddns\" : {}, "
            "\"bogus-object-two\" : {} "
500 501 502 503 504 505
            "}";

    runConfig(config, SHOULD_FAIL);
}


506 507 508 509 510 511 512 513 514 515 516 517
/// @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
/// -# dns_server_timeout cannat be 0
/// -# 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");
518
    runConfig(config, SHOULD_FAIL);
519 520 521

    // Cannot use IPv6 ANY address
    config = makeParamsConfigString ("::", 777, 333, "UDP", "JSON");
522
    runConfig(config, SHOULD_FAIL);
523 524 525

    // Cannot use port  0
    config = makeParamsConfigString ("127.0.0.1", 0, 333, "UDP", "JSON");
526
    runConfig(config, SHOULD_FAIL);
527 528 529

    // Cannot use dns server timeout of 0
    config = makeParamsConfigString ("127.0.0.1", 777, 0, "UDP", "JSON");
530
    runConfig(config, SHOULD_FAIL);
531 532 533

    // Invalid protocol
    config = makeParamsConfigString ("127.0.0.1", 777, 333, "BOGUS", "JSON");
534
    runConfig(config, SHOULD_FAIL);
535

536 537 538 539
    // Unsupported protocol
    config = makeParamsConfigString ("127.0.0.1", 777, 333, "TCP", "JSON");
    runConfig(config, SHOULD_FAIL);

540 541
    // Invalid format
    config = makeParamsConfigString ("127.0.0.1", 777, 333, "UDP", "BOGUS");
542
    runConfig(config, SHOULD_FAIL);
543 544
}

545 546 547 548
/// @brief Tests the enforcement of data validation when parsing TSIGKeyInfos.
/// It verifies that:
/// 1. Name cannot be blank.
/// 2. Algorithm cannot be blank.
549
/// 3. Secret cannot be blank.
550
TEST_F(TSIGKeyInfoTest, invalidEntry) {
551 552 553
    // Config with a blank name entry.
    std::string config = "{"
                         " \"name\": \"\" , "
554
                         " \"algorithm\": \"HMAC-MD5\" , "
555
                         "   \"secret\": \"LSWXnfkKZjdPJI5QxlpnfQ==\" "
556
                         "}";
557
    ASSERT_TRUE(fromJSON(config));
558

559 560
    // Verify that build fails on blank name.
    EXPECT_THROW(parser_->build(config_set_), D2CfgError);
561 562 563 564 565

    // Config with a blank algorithm entry.
    config = "{"
                         " \"name\": \"d2_key_one\" , "
                         " \"algorithm\": \"\" , "
566
                         "   \"secret\": \"LSWXnfkKZjdPJI5QxlpnfQ==\" "
567 568
                         "}";

569
    ASSERT_TRUE(fromJSON(config));
570

571 572
    // Verify that build fails on blank algorithm.
    EXPECT_THROW(parser_->build(config_set_), D2CfgError);
573

574 575 576 577
    // Config with an invalid algorithm entry.
    config = "{"
                         " \"name\": \"d2_key_one\" , "
                         " \"algorithm\": \"bogus\" , "
578
                         "   \"secret\": \"LSWXnfkKZjdPJI5QxlpnfQ==\" "
579 580
                         "}";

581
    ASSERT_TRUE(fromJSON(config));
582

583 584
    // Verify that build fails on blank algorithm.
    EXPECT_THROW(parser_->build(config_set_), D2CfgError);
585 586 587 588

    // Config with a blank secret entry.
    config = "{"
                         " \"name\": \"d2_key_one\" , "
589
                         " \"algorithm\": \"HMAC-MD5\" , "
590 591 592
                         " \"secret\": \"\" "
                         "}";

593
    ASSERT_TRUE(fromJSON(config));
594

595 596
    // Verify that build fails blank secret
    EXPECT_THROW(parser_->build(config_set_), D2CfgError);
597 598 599 600

    // Config with an invalid secret entry.
    config = "{"
                         " \"name\": \"d2_key_one\" , "
601
                         " \"algorithm\": \"HMAC-MD5\" , "
602 603 604 605 606 607 608
                         " \"secret\": \"bogus\" "
                         "}";

    ASSERT_TRUE(fromJSON(config));

    // Verify that build fails an invalid secret
    EXPECT_THROW(parser_->build(config_set_), D2CfgError);
609 610 611 612
}

/// @brief Verifies that TSIGKeyInfo parsing creates a proper TSIGKeyInfo
/// when given a valid combination of entries.
613
TEST_F(TSIGKeyInfoTest, validEntry) {
614 615 616
    // Valid entries for TSIG key, all items are required.
    std::string config = "{"
                         " \"name\": \"d2_key_one\" , "
617
                         " \"algorithm\": \"HMAC-MD5\" , "
618
                         " \"digest-bits\": 120 , "
619
                         " \"secret\": \"dGhpcyBrZXkgd2lsbCBtYXRjaA==\" "
620
                         "}";
621
    ASSERT_TRUE(fromJSON(config));
622 623

    // Verify that it builds and commits without throwing.
624 625
    //ASSERT_NO_THROW(parser_->build(config_set_));
    (parser_->build(config_set_));
626 627 628 629
    ASSERT_NO_THROW(parser_->commit());

    // Verify the correct number of keys are present
    int count =  keys_->size();
630
    EXPECT_EQ(1, count);
631 632 633 634 635 636 637

    // Find the key and retrieve it.
    TSIGKeyInfoMap::iterator gotit = keys_->find("d2_key_one");
    ASSERT_TRUE(gotit != keys_->end());
    TSIGKeyInfoPtr& key = gotit->second;

    // Verify the key contents.
638
    EXPECT_TRUE(checkKey(key, "d2_key_one", "HMAC-MD5",
639
                         "dGhpcyBrZXkgd2lsbCBtYXRjaA==", 120));
640 641 642 643 644 645 646 647 648
}

/// @brief Verifies that attempting to parse an invalid list of TSIGKeyInfo
/// entries is detected.
TEST_F(TSIGKeyInfoTest, invalidTSIGKeyList) {
    // Construct a list of keys with an invalid key entry.
    std::string config = "["

                         " { \"name\": \"key1\" , "
649
                         "   \"algorithm\": \"HMAC-MD5\" ,"
650
                         " \"digest-bits\": 120 , "
651
                         "   \"secret\": \"GWG/Xfbju4O2iXGqkSu4PQ==\" "
652
                         " },"
653
                         // this entry has an invalid algorithm
654 655
                         " { \"name\": \"key2\" , "
                         "   \"algorithm\": \"\" ,"
656
                         " \"digest-bits\": 120 , "
657
                         "   \"secret\": \"GWG/Xfbju4O2iXGqkSu4PQ==\" "
658 659
                         " },"
                         " { \"name\": \"key3\" , "
660
                         "   \"algorithm\": \"HMAC-MD5\" ,"
661
                         "   \"secret\": \"GWG/Xfbju4O2iXGqkSu4PQ==\" "
662 663 664
                         " }"
                         " ]";

665
    ASSERT_TRUE(fromJSON(config));
666 667 668 669 670 671

    // Create the list parser.
    isc::dhcp::ParserPtr parser;
    ASSERT_NO_THROW(parser.reset(new TSIGKeyInfoListParser("test", keys_)));

    // Verify that the list builds without errors.
672
    EXPECT_THROW(parser->build(config_set_), D2CfgError);
673 674 675 676 677 678 679 680 681
}

/// @brief Verifies that attempting to parse an invalid list of TSIGKeyInfo
/// entries is detected.
TEST_F(TSIGKeyInfoTest, duplicateTSIGKey) {
    // Construct a list of keys with an invalid key entry.
    std::string config = "["

                         " { \"name\": \"key1\" , "
682
                         "   \"algorithm\": \"HMAC-MD5\" ,"
683
                         " \"digest-bits\": 120 , "
684
                         "   \"secret\": \"GWG/Xfbju4O2iXGqkSu4PQ==\" "
685 686
                         " },"
                         " { \"name\": \"key2\" , "
687
                         "   \"algorithm\": \"HMAC-MD5\" ,"
688
                         " \"digest-bits\": 120 , "
689
                         "   \"secret\": \"GWG/Xfbju4O2iXGqkSu4PQ==\" "
690 691
                         " },"
                         " { \"name\": \"key1\" , "
692
                         "   \"algorithm\": \"HMAC-MD5\" ,"
693
                         "   \"secret\": \"GWG/Xfbju4O2iXGqkSu4PQ==\" "
694 695 696
                         " }"
                         " ]";

697
    ASSERT_TRUE(fromJSON(config));
698 699 700 701 702 703

    // Create the list parser.
    isc::dhcp::ParserPtr parser;
    ASSERT_NO_THROW(parser.reset(new TSIGKeyInfoListParser("test", keys_)));

    // Verify that the list builds without errors.
704
    EXPECT_THROW(parser->build(config_set_), D2CfgError);
705 706 707
}

/// @brief Verifies a valid list of TSIG Keys parses correctly.
708
/// Also verifies that all of the supported algorithm names work.
709
TEST_F(TSIGKeyInfoTest, validTSIGKeyList) {
710
    // Construct a valid list of keys.
711 712 713
    std::string config = "["

                         " { \"name\": \"key1\" , "
714
                         "   \"algorithm\": \"HMAC-MD5\" ,"
715
                         " \"digest-bits\": 80 , "
716
                         "  \"secret\": \"dGhpcyBrZXkgd2lsbCBtYXRjaA==\" "
717 718
                         " },"
                         " { \"name\": \"key2\" , "
719
                         "   \"algorithm\": \"HMAC-SHA1\" ,"
720
                         " \"digest-bits\": 80 , "
721
                         "  \"secret\": \"dGhpcyBrZXkgd2lsbCBtYXRjaA==\" "
722 723
                         " },"
                         " { \"name\": \"key3\" , "
724
                         "   \"algorithm\": \"HMAC-SHA256\" ,"
725
                         " \"digest-bits\": 128 , "
726
                         "  \"secret\": \"dGhpcyBrZXkgd2lsbCBtYXRjaA==\" "
727 728
                         " },"
                         " { \"name\": \"key4\" , "
729
                         "   \"algorithm\": \"HMAC-SHA224\" ,"
730
                         " \"digest-bits\": 112 , "
731
                         "  \"secret\": \"dGhpcyBrZXkgd2lsbCBtYXRjaA==\" "
732 733
                         " },"
                         " { \"name\": \"key5\" , "
734
                         "   \"algorithm\": \"HMAC-SHA384\" ,"
735
                         " \"digest-bits\": 192 , "
736
                         "  \"secret\": \"dGhpcyBrZXkgd2lsbCBtYXRjaA==\" "
737 738
                         " },"
                         " { \"name\": \"key6\" , "
739
                         "   \"algorithm\": \"HMAC-SHA512\" ,"
740
                         " \"digest-bits\": 256 , "
741
                         "   \"secret\": \"dGhpcyBrZXkgd2lsbCBtYXRjaA==\" "
742 743 744
                         " }"
                         " ]";

745
    ASSERT_TRUE(fromJSON(config));
746 747 748 749 750 751 752 753

    // Verify that the list builds and commits without errors.
    // Create the list parser.
    isc::dhcp::ParserPtr parser;
    ASSERT_NO_THROW(parser.reset(new TSIGKeyInfoListParser("test", keys_)));
    ASSERT_NO_THROW(parser->build(config_set_));
    ASSERT_NO_THROW(parser->commit());

754
    std::string ref_secret = "dGhpcyBrZXkgd2lsbCBtYXRjaA==";
755 756
    // Verify the correct number of keys are present
    int count =  keys_->size();
757
    ASSERT_EQ(6, count);
758 759 760 761 762 763 764

    // Find the 1st key and retrieve it.
    TSIGKeyInfoMap::iterator gotit = keys_->find("key1");
    ASSERT_TRUE(gotit != keys_->end());
    TSIGKeyInfoPtr& key = gotit->second;

    // Verify the key contents.
765 766
    EXPECT_TRUE(checkKey(key, "key1", TSIGKeyInfo::HMAC_MD5_STR,
                         ref_secret, 80));
767 768 769 770 771 772 773

    // Find the 2nd key and retrieve it.
    gotit = keys_->find("key2");
    ASSERT_TRUE(gotit != keys_->end());
    key = gotit->second;

    // Verify the key contents.
774 775
    EXPECT_TRUE(checkKey(key, "key2", TSIGKeyInfo::HMAC_SHA1_STR,
                         ref_secret, 80));
776 777 778 779 780 781 782

    // Find the 3rd key and retrieve it.
    gotit = keys_->find("key3");
    ASSERT_TRUE(gotit != keys_->end());
    key = gotit->second;

    // Verify the key contents.
783
    EXPECT_TRUE(checkKey(key, "key3", TSIGKeyInfo::HMAC_SHA256_STR,
784
                         ref_secret, 128));
785 786 787 788 789 790 791

    // Find the 4th key and retrieve it.
    gotit = keys_->find("key4");
    ASSERT_TRUE(gotit != keys_->end());
    key = gotit->second;

    // Verify the key contents.
792
    EXPECT_TRUE(checkKey(key, "key4", TSIGKeyInfo::HMAC_SHA224_STR,
793
                         ref_secret, 112));
794 795 796 797 798 799 800

    // Find the 5th key and retrieve it.
    gotit = keys_->find("key5");
    ASSERT_TRUE(gotit != keys_->end());
    key = gotit->second;

    // Verify the key contents.
801
    EXPECT_TRUE(checkKey(key, "key5", TSIGKeyInfo::HMAC_SHA384_STR,
802
                         ref_secret, 192));
803 804 805 806 807 808 809

    // Find the 6th key and retrieve it.
    gotit = keys_->find("key6");
    ASSERT_TRUE(gotit != keys_->end());
    key = gotit->second;

    // Verify the key contents.
810
    EXPECT_TRUE(checkKey(key, "key6", TSIGKeyInfo::HMAC_SHA512_STR,
811
                         ref_secret, 256));
812 813
}

814 815 816 817 818
/// @brief Tests the enforcement of data validation when parsing DnsServerInfos.
/// It verifies that:
/// 1. Specifying both a hostname and an ip address is not allowed.
/// 2. Specifying both blank a hostname and blank ip address is not allowed.
/// 3. Specifying a negative port number is not allowed.
819
TEST_F(DnsServerInfoTest, invalidEntry) {
820
    // Create a config in which both host and ip address are supplied.
821
    // Verify that build fails.
822
    std::string config = "{ \"hostname\": \"pegasus.tmark\", "
823
                         "  \"ip-address\": \"127.0.0.1\" } ";
824
    ASSERT_TRUE(fromJSON(config));
825
    EXPECT_THROW(parser_->build(config_set_), D2CfgError);
826 827

    // Neither host nor ip address supplied
828
    // Verify that builds fails.
829
    config = "{ \"hostname\": \"\", "
830
             "  \"ip-address\": \"\" } ";
831
    ASSERT_TRUE(fromJSON(config));
832
    EXPECT_THROW(parser_->build(config_set_), D2CfgError);
833 834 835

    // Create a config with a negative port number.
    // Verify that build fails.
836
    config = "{ \"ip-address\": \"192.168.5.6\" ,"
837
             "  \"port\": -100 }";
838
    ASSERT_TRUE(fromJSON(config));
839 840 841
    EXPECT_THROW (parser_->build(config_set_), isc::BadValue);
}

842

843 844 845 846 847 848
/// @brief Verifies that DnsServerInfo parsing creates a proper DnsServerInfo
/// when given a valid combination of entries.
/// It verifies that:
/// 1. A DnsServerInfo entry is correctly made, when given only a hostname.
/// 2. A DnsServerInfo entry is correctly made, when given ip address and port.
/// 3. A DnsServerInfo entry is correctly made, when given only an ip address.
849
TEST_F(DnsServerInfoTest, validEntry) {
850 851 852 853
    /// @todo When resolvable hostname is supported you'll need this test.
    /// // Valid entries for dynamic host
    /// std::string config = "{ \"hostname\": \"pegasus.tmark\" }";
    /// ASSERT_TRUE(fromJSON(config));
854

855 856 857
    /// // Verify that it builds and commits without throwing.
    /// ASSERT_NO_THROW(parser_->build(config_set_));
    /// ASSERT_NO_THROW(parser_->commit());
858

859 860 861
    /// //Verify the correct number of servers are present
    /// int count =  servers_->size();
    /// EXPECT_EQ(1, count);
862

863 864 865 866 867
    /// Verify the server exists and has the correct values.
    /// DnsServerInfoPtr server = (*servers_)[0];
    /// EXPECT_TRUE(checkServer(server, "pegasus.tmark",
    ///                         DnsServerInfo::EMPTY_IP_STR,
    ///                         DnsServerInfo::STANDARD_DNS_PORT));
868

869 870
    /// // Start over for a new test.
    /// reset();
871 872

    // Valid entries for static ip
873
    std::string config = " { \"ip-address\": \"127.0.0.1\" , "
874
                         "  \"port\": 100 }";
875
    ASSERT_TRUE(fromJSON(config));
876 877 878 879 880 881

    // Verify that it builds and commits without throwing.
    ASSERT_NO_THROW(parser_->build(config_set_));
    ASSERT_NO_THROW(parser_->commit());

    // Verify the correct number of servers are present
882
    int count =  servers_->size();
883
    EXPECT_EQ(1, count);
884 885

    // Verify the server exists and has the correct values.
886
    DnsServerInfoPtr server = (*servers_)[0];
887 888 889 890 891 892
    EXPECT_TRUE(checkServer(server, "", "127.0.0.1", 100));

    // Start over for a new test.
    reset();

    // Valid entries for static ip, no port
893
    config = " { \"ip-address\": \"192.168.2.5\" }";
894
    ASSERT_TRUE(fromJSON(config));
895 896 897 898 899 900 901

    // Verify that it builds and commits without throwing.
    ASSERT_NO_THROW(parser_->build(config_set_));
    ASSERT_NO_THROW(parser_->commit());

    // Verify the correct number of servers are present
    count =  servers_->size();
902
    EXPECT_EQ(1, count);
903 904 905 906

    // Verify the server exists and has the correct values.
    server = (*servers_)[0];
    EXPECT_TRUE(checkServer(server, "", "192.168.2.5",
907
                            DnsServerInfo::STANDARD_DNS_PORT));
908 909 910 911 912 913
}

/// @brief Verifies that attempting to parse an invalid list of DnsServerInfo
/// entries is detected.
TEST_F(ConfigParseTest, invalidServerList) {
    // Construct a list of servers with an invalid server entry.
914 915 916
    std::string config = "[ { \"ip-address\": \"127.0.0.1\" }, "
                        "{ \"ip-address\": \"\" }, "
                        "{ \"ip-address\": \"127.0.0.2\" } ]";
917
    ASSERT_TRUE(fromJSON(config));
918 919 920 921 922 923

    // Create the server storage and list parser.
    DnsServerInfoStoragePtr servers(new DnsServerInfoStorage());
    isc::dhcp::ParserPtr parser;
    ASSERT_NO_THROW(parser.reset(new DnsServerInfoListParser("test", servers)));

924 925
    // Verify that build fails.
    EXPECT_THROW(parser->build(config_set_), D2CfgError);
926 927 928 929 930 931
}

/// @brief Verifies that a list of DnsServerInfo entries parses correctly given
/// a valid configuration.
TEST_F(ConfigParseTest, validServerList) {
    // Create a valid list of servers.
932 933 934
    std::string config = "[ { \"ip-address\": \"127.0.0.1\" }, "
                        "{ \"ip-address\": \"127.0.0.2\" }, "
                        "{ \"ip-address\": \"127.0.0.3\" } ]";
935
    ASSERT_TRUE(fromJSON(config));
936 937 938 939 940 941 942 943 944 945 946 947

    // Create the server storage and list parser.
    DnsServerInfoStoragePtr servers(new DnsServerInfoStorage());
    isc::dhcp::ParserPtr parser;
    ASSERT_NO_THROW(parser.reset(new DnsServerInfoListParser("test", servers)));

    // Verfiy that the list builds and commits without error.
    ASSERT_NO_THROW(parser->build(config_set_));
    ASSERT_NO_THROW(parser->commit());

    // Verify that the server storage contains the correct number of servers.
    int count =  servers->size();
948
    EXPECT_EQ(3, count);
949 950 951

    // Verify the first server exists and has the correct values.
    DnsServerInfoPtr server = (*servers)[0];
952
    EXPECT_TRUE(checkServer(server, "", "127.0.0.1",
953
                            DnsServerInfo::STANDARD_DNS_PORT));
954 955 956

    // Verify the second server exists and has the correct values.
    server = (*servers)[1];
957
    EXPECT_TRUE(checkServer(server, "", "127.0.0.2",
958
                            DnsServerInfo::STANDARD_DNS_PORT));
959 960 961

    // Verify the third server exists and has the correct values.
    server = (*servers)[2];
962
    EXPECT_TRUE(checkServer(server, "", "127.0.0.3",
963
                            DnsServerInfo::STANDARD_DNS_PORT));
964 965 966 967 968 969 970 971
}

/// @brief Tests the enforcement of data validation when parsing DdnsDomains.
/// It verifies that:
/// 1. Domain storage cannot be null when constructing a DdnsDomainParser.
/// 2. The name entry is not optional.
/// 3. The server list man not be empty.
/// 4. That a mal-formed server entry is detected.
972 973
/// 5. That an undefined key name is detected.
TEST_F(DdnsDomainTest, invalidDdnsDomainEntry) {
974
    // Verify that attempting to construct the parser with null storage fails.
975 976 977
    DdnsDomainMapPtr domains;
    ASSERT_THROW(isc::dhcp::ParserPtr(
                 new DdnsDomainParser("test", domains, keys_)), D2CfgError);
978 979

    // Create a domain configuration without a name
980 981 982
    std::string config = "{  \"key-name\": \"d2_key.tmark.org\" , "
                         "  \"dns-servers\" : [ "
                         "  {  \"ip-address\": \"127.0.0.1\" , "
983
                         "    \"port\": 100 },"
984
                         "  { \"ip-address\": \"127.0.0.2\" , "
985
                         "    \"port\": 200 },"
986
                         "  {  \"ip-address\": \"127.0.0.3\" , "
987
                         "    \"port\": 300 } ] } ";
988
    ASSERT_TRUE(fromJSON(config));
989

990
    // Verify that the domain configuration builds fails.
991
    EXPECT_THROW(parser_->build(config_set_), D2CfgError);
992 993 994

    // Create a domain configuration with an empty server list.
    config = "{ \"name\": \"tmark.org\" , "
995 996
             "  \"key-name\": \"d2_key.tmark.org\" , "
             "  \"dns-servers\" : [ "
997
             "   ] } ";
998
    ASSERT_TRUE(fromJSON(config));
999 1000

    // Verify that the domain configuration build fails.
1001
    EXPECT_THROW(parser_->build(config_set_), D2CfgError);
1002 1003 1004

    // Create a domain configuration with a mal-formed server entry.
    config = "{ \"name\": \"tmark.org\" , "
1005 1006 1007
             "  \"key-name\": \"d2_key.tmark.org\" , "
             "  \"dns-servers\" : [ "
             "  {  \"ip-address\": \"127.0.0.3\" , "
1008
             "    \"port\": -1 } ] } ";
1009
    ASSERT_TRUE(fromJSON(config));
1010 1011

    // Verify that the domain configuration build fails.
1012
    EXPECT_THROW(parser_->build(config_set_), isc::BadValue);
1013

1014 1015
    // Create a domain configuration without an defined key name
    config = "{ \"name\": \"tmark.org\" , "
1016 1017 1018
             "  \"key-name\": \"d2_key.tmark.org\" , "
             "  \"dns-servers\" : [ "
             "  {  \"ip-address\": \"127.0.0.3\" , "