200-dbtests.t 15.9 KB
Newer Older
1 2 3 4
use strict;
use warnings;


5
use AWITPT::Util;
6
use Data::Dumper;
7
use Date::Parse;
8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75
use POSIX qw(:sys_wait_h);
use Test::Most;
use Test::Most::Exception 'throw_failure';



#
# Check that database tests are enabled
#

# We need DBTESTS enabled to run this
if (!$ENV{'DBTESTS'}) {
	plan skip_all => 'DBTESTS not set in ENV';
	done_testing();
	exit 0;
}



#
# Load database handling libraries
#

require_ok('AWITPT::DB::DBILayer');
require_ok('AWITPT::DB::DBLayer');

use AWITPT::DB::DBLayer;


#
# Load our server and client
#

require_ok("smradius::daemon");
require_ok("smradius::client");


#
# Daemon help
#

can_ok("smradius::daemon","displayHelp");


#
# Try connect to database
#

my $dbh = AWITPT::DB::DBILayer->new({
	'Username' => 'root',
	'DSN' => 'DBI:mysql:database=smradiustest;host=localhost',
});


# If we cannot connect, just bail out
if ($dbh->connect()) {
	BAIL_OUT("ERROR: Failed to connect to database for testing purposes: ".$dbh->error());
}

AWITPT::DB::DBLayer::setHandle($dbh);


#
# Make sure DB is clean
#

my $sth;

76 77 78
$sth = DBDo("DELETE FROM accounting");
is(AWITPT::DB::DBLayer::error(),"","Clean table 'accounting");

79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147
$sth = DBDo("DELETE FROM user_attributes");
is(AWITPT::DB::DBLayer::error(),"","Clean table 'user_attributes");

$sth = DBDo("DELETE FROM client_attributes");
is(AWITPT::DB::DBLayer::error(),"","Clean table 'client_attributes");

$sth = DBDo("DELETE FROM users");
is(AWITPT::DB::DBLayer::error(),"","Clean table 'users'");

$sth = DBDo("DELETE FROM clients_to_realms");
is(AWITPT::DB::DBLayer::error(),"","Clean table 'clients_to_realms'");

$sth = DBDo("DELETE FROM clients");
is(AWITPT::DB::DBLayer::error(),"","Clean table 'clients'");

$sth = DBDo("DELETE FROM realms");
is(AWITPT::DB::DBLayer::error(),"","Clean table 'realms'");


#
# Run server and client
#

our $child;
if ($child = fork()) {

	# CHLD handler
	local $SIG{CHLD} = sub {
		warn "SIGCHLD TRIGGER";
		waitpid($child,-1);
	};

	# Install signal handlers to cleanup if we get a TERM or INT
	local $SIG{TERM} = local $SIG{INT} = \&cleanup;


	# Wait before starting
	sleep(2);


	# Setup failure handler
	set_failure_handler( sub { my @params = @_; cleanup(); throw_failure } );


	my $res;



	#
	# Make sure basic test without any config does not authenticate users
	#

	$res = smradius::client->run(
		"--raddb","dicts",
		"127.0.0.1",
		"auth",
		"secret123",
		'User-Name=testuser1',
		'User-Password=test123',
	);
	is(ref($res),"","smradclient ref should return ''");
	is($res,1,"smradclient result should be 1");



	#
	# Create test case data
	#

Nigel Kukard's avatar
Nigel Kukard committed
148 149 150
	my $client1_ID = testDBInsert("Create client 'localhost'",
		"INSERT INTO clients (Name,AccessList,Disabled) VALUES ('localhost','127.0.0.0/8',0)"
	);
151

Nigel Kukard's avatar
Nigel Kukard committed
152 153 154 155
	my $client1attr1_ID = testDBInsert("Create client 'localhost' secret",
		"INSERT INTO client_attributes (ClientID,Name,Operator,Value,Disabled) VALUES (?,?,?,?,0)",
			$client1_ID,'SMRadius-Config-Secret',':=','secret123'
	);
156

Nigel Kukard's avatar
Nigel Kukard committed
157 158 159
	my $realm1_ID = testDBInsert("Create realm ''",
		"INSERT INTO realms (Name,Disabled) VALUES ('',0)"
	);
160

Nigel Kukard's avatar
Nigel Kukard committed
161 162 163
	my $clientTOrealm1_ID = testDBInsert("Link client 'localhost' to realm ''",
		"INSERT INTO clients_to_realms (ClientID,RealmID,Disabled) VALUES (?,?,0)",$client1_ID,$realm1_ID
	);
164 165 166 167 168 169 170



	#
	# Check we get an Access-Reject for an unconfigured user
	#

Nigel Kukard's avatar
Nigel Kukard committed
171 172 173
	my $user1_ID = testDBInsert("Create user 'testuser1'",
		"INSERT INTO users (UserName,Disabled) VALUES ('testuser1',0)"
	);
174

Nigel Kukard's avatar
Nigel Kukard committed
175 176 177 178
	my $user1attr1_ID = testDBInsert("Create user 'testuser1' attribute 'User-Password'",
		"INSERT INTO user_attributes (UserID,Name,Operator,Value,Disabled) VALUES (?,?,?,?,0)",
			$user1_ID,'User-Password','==','test123'
	);
179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196

	$res = smradius::client->run(
		"--raddb","dicts",
		"127.0.0.1",
		"auth",
		"secret123",
		'User-Name=testuser1',
		'User-Password=test123',
	);
	is(ref($res),"HASH","smradclient should return a HASH");
	is($res->{'response'}->{'code'},"Access-Reject","Check our return is 'Access-Reject' for unconfigured user");



	#
	# Check we get a Access-Accept for an uncapped usage user
	#

Nigel Kukard's avatar
Nigel Kukard committed
197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214
	my $user2_ID = testDBInsert("Create user 'testuser2'",
		"INSERT INTO users (UserName,Disabled) VALUES ('testuser2',0)"
	);

	my $user2attr1_ID = testDBInsert("Create user 'testuser2' attribute 'User-Password'",
		"INSERT INTO user_attributes (UserID,Name,Operator,Value,Disabled) VALUES (?,?,?,?,0)",
			$user2_ID,'User-Password','==','test123'
	);

	my $user2attr2_ID = testDBInsert("Create user 'testuser2' attribute 'SMRadius-Capping-Traffic-Limit'",
		"INSERT INTO user_attributes (UserID,Name,Operator,Value,Disabled) VALUES (?,?,?,?,0)",
			$user2_ID,'SMRadius-Capping-Traffic-Limit',':=','0'
	);

	my $user2attr3_ID = testDBInsert("Create user 'testuser2' attribute 'SMRadius-Capping-Uptime-Limit'",
		"INSERT INTO user_attributes (UserID,Name,Operator,Value,Disabled) VALUES (?,?,?,?,0)",
			$user2_ID,'SMRadius-Capping-Uptime-Limit',':=','0'
	);
215 216 217 218 219 220 221 222 223 224 225 226 227

	$res = smradius::client->run(
		"--raddb","dicts",
		"127.0.0.1",
		"auth",
		"secret123",
		'User-Name=testuser2',
		'User-Password=test123',
	);
	is(ref($res),"HASH","smradclient should return a HASH");
	is($res->{'response'}->{'code'},"Access-Accept","Check our return is 'Access-Accept' for a basically configured user");


228
	#
229
	# Test accounting START packet
230 231
	#

232
	my $session1_ID = "09d15244";
233 234 235 236
	my $session1_Timestamp = time();
	my $session1_Timestamp_str = DateTime->from_epoch(epoch => $session1_Timestamp,time_zone => 'UTC')
			->strftime('%Y-%m-%d %H:%M:%S');

237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265
	$res = smradius::client->run(
		"--raddb","dicts",
		"127.0.0.1",
		"acct",
		"secret123",
		'NAS-IP-Address=10.0.0.3',
		'Acct-Delay-Time=11',
		'NAS-Identifier=Test-NAS1',
		'Acct-Status-Type=Start',
		'Event-Timestamp='.$session1_Timestamp,
		'Framed-IP-Address=10.0.1.3',
		'Acct-Session-Id='.$session1_ID,
		'NAS-Port-Id=test iface name1',
		'Called-Station-Id=testservice1',
		'Calling-Station-Id=00:00:0C:EE:47:AA',
		'User-Name=testuser1',
		'NAS-Port-Type=Ethernet',
		'NAS-Port=45355555',
		'Framed-Protocol=PPP',
		'Service-Type=Framed-User',
	);
	is(ref($res),"HASH","smradclient should return a HASH");

	testDBResults("Check accounting record is created correctly",'accounting',{'AcctSessionID' => $session1_ID},
		{
			'NASIPAddress' => '10.0.0.3',
			'AcctDelayTime' => '11',
			'NASIdentifier' => 'Test-NAS1',
			'AcctStatusType' => 1,
266
			'EventTimestamp' => sub{ _timestampCheck(shift,$session1_Timestamp_str) },
267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 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 312 313 314 315 316 317 318 319
			'FramedIPAddress' => '10.0.1.3',
			'AcctSessionId' => $session1_ID,
			'NASPortId' => 'test iface name1',
			'CalledStationId' => 'testservice1',
			'CallingStationId' => '00:00:0C:EE:47:AA',
			'Username' => 'testuser1',
			'NASPortType' => 15,
			'NASPort' => '45355555',
			'FramedProtocol' => 1,
			'ServiceType' => 2,
			'AcctOutputPackets' => undef,
			'AcctOutputGigawords' => undef,
			'AcctOutputOctets' => undef,
			'AcctInputPackets' => undef,
			'AcctInputGigawords' => undef,
			'AcctInputOctets' => undef,
			'AcctSessionTime' => undef,
		}
	);


	#
	# Test accounting ALIVE packet
	#

	$res = smradius::client->run(
		"--raddb","dicts",
		"127.0.0.1",
		"acct",
		"secret123",

		'Acct-Status-Type=Interim-Update',
		'Acct-Output-Packets=800000',
		'Acct-Output-Gigawords=0',
		'Acct-Output-Octets=810000000',
		'Acct-Input-Packets=777777',
		'Acct-Input-Gigawords=0',
		'Acct-Input-Octets=123456789',
		'Acct-Session-Time=999',

		'User-Name=testuser1',
		'Acct-Session-Id='.$session1_ID,
		'NAS-IP-Address=10.0.0.3',
		'NAS-Port=45355555',
	);
	is(ref($res),"HASH","smradclient should return a HASH");

	testDBResults("Check accounting record is updated correctly",'accounting',{'AcctSessionID' => $session1_ID},
		{
			'NASIPAddress' => '10.0.0.3',
			'AcctDelayTime' => '11',
			'NASIdentifier' => 'Test-NAS1',
			'AcctStatusType' => 3,
320
			'EventTimestamp' => sub{ _timestampCheck(shift,$session1_Timestamp_str) },
321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374
			'FramedIPAddress' => '10.0.1.3',
			'AcctSessionId' => $session1_ID,
			'NASPortId' => 'test iface name1',
			'CalledStationId' => 'testservice1',
			'CallingStationId' => '00:00:0C:EE:47:AA',
			'Username' => 'testuser1',
			'NASPortType' => 15,
			'NASPort' => '45355555',
			'FramedProtocol' => 1,
			'ServiceType' => 2,
			'AcctOutputPackets' => '800000',
			'AcctOutputGigawords' => '0',
			'AcctOutputOctets' => '810000000',
			'AcctInputPackets' => '777777',
			'AcctInputGigawords' => '0',
			'AcctInputOctets' => '123456789',
			'AcctSessionTime' => '999',
		}
	);


	#
	# Test accounting STOP packet
	#

	$res = smradius::client->run(
		"--raddb","dicts",
		"127.0.0.1",
		"acct",
		"secret123",

		'Acct-Status-Type=Stop',
		'Acct-Output-Packets=999999',
		'Acct-Output-Gigawords=0',
		'Acct-Output-Octets=888888888',
		'Acct-Input-Packets=1111111',
		'Acct-Input-Gigawords=0',
		'Acct-Input-Octets=222222222',
		'Acct-Session-Time=3998',
		'Acct-Terminate-Cause=Session-Timeout',

		'User-Name=testuser1',
		'Acct-Session-Id='.$session1_ID,
		'NAS-IP-Address=10.0.0.3',
		'NAS-Port=45355555',
	);
	is(ref($res),"HASH","smradclient should return a HASH");

	testDBResults("Check accounting record is stopped correctly",'accounting',{'AcctSessionID' => $session1_ID},
		{
			'NASIPAddress' => '10.0.0.3',
			'AcctDelayTime' => '11',
			'NASIdentifier' => 'Test-NAS1',
			'AcctStatusType' => 2,
375
			'EventTimestamp' => sub{ _timestampCheck(shift,$session1_Timestamp_str) },
376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406
			'FramedIPAddress' => '10.0.1.3',
			'AcctSessionId' => $session1_ID,
			'NASPortId' => 'test iface name1',
			'CalledStationId' => 'testservice1',
			'CallingStationId' => '00:00:0C:EE:47:AA',
			'Username' => 'testuser1',
			'NASPortType' => 15,
			'NASPort' => '45355555',
			'FramedProtocol' => 1,
			'ServiceType' => 2,
			'AcctOutputPackets' => '999999',
			'AcctOutputGigawords' => '0',
			'AcctOutputOctets' => '888888888',
			'AcctInputPackets' => '1111111',
			'AcctInputGigawords' => '0',
			'AcctInputOctets' => '222222222',
			'AcctSessionTime' => '3998',
			'AcctTerminateCause' => '5',
		}
	);


	#
	# Test missing accounting START packet
	#

	my $session2_ID = 81700217;
	my $session2_Timestamp = time();
	my $session2_Timestamp_str = DateTime->from_epoch(epoch => $session2_Timestamp,time_zone => 'UTC')
			->strftime('%Y-%m-%d %H:%M:%S');

407 408 409 410 411 412 413 414
	$res = smradius::client->run(
		"--raddb","dicts",
		"127.0.0.1",
		"acct",
		"secret123",
		'User-Name=testuser2',
		'NAS-IP-Address=10.0.0.1',
		'Acct-Delay-Time=12',
415
		'NAS-Identifier=Test-NAS2',
416 417 418 419 420 421 422 423
		'Acct-Status-Type=Interim-Update',
		'Acct-Output-Packets=786933',
		'Acct-Output-Gigawords=0',
		'Acct-Output-Octets=708163705',
		'Acct-Input-Packets=670235',
		'Acct-Input-Gigawords=0',
		'Acct-Input-Octets=102600046',
		'Acct-Session-Time=800',
424
		'Event-Timestamp='.$session2_Timestamp,
425
		'Framed-IP-Address=10.0.1.1',
426
		'Acct-Session-Id='.$session2_ID,
427
		'NAS-Port-Id=wlan1',
428
		'Called-Station-Id=testservice2',
429 430 431 432 433 434 435 436 437
		'Calling-Station-Id=00:00:0C:EE:47:BF',
		'User-Name=testuser2',
		'NAS-Port-Type=Ethernet',
		'NAS-Port=15729175',
		'Framed-Protocol=PPP',
		'Service-Type=Framed-User',
	);
	is(ref($res),"HASH","smradclient should return a HASH");

438
	testDBResults("Check missing accounting record is created correctly",'accounting',{'AcctSessionID' => $session2_ID},
439 440 441 442
		{
			'Username' => 'testuser2',
			'NASIPAddress' => '10.0.0.1',
			'AcctDelayTime' => '12',
443
			'NASIdentifier' => 'Test-NAS2',
444 445 446 447 448 449 450 451
			'AcctStatusType' => 3,
			'AcctOutputPackets' => '786933',
			'AcctOutputGigawords' => '0',
			'AcctOutputOctets' => '708163705',
			'AcctInputPackets' => '670235',
			'AcctInputGigawords' => '0',
			'AcctInputOctets' => '102600046',
			'AcctSessionTime' => '800',
452
			'EventTimestamp' => sub{ _timestampCheck(shift,$session2_Timestamp_str) },
453
			'FramedIPAddress' => '10.0.1.1',
454
			'AcctSessionId' => $session2_ID,
455
			'NASPortId' => 'wlan1',
456
			'CalledStationId' => 'testservice2',
457 458 459 460 461 462 463 464 465
			'CallingStationId' => '00:00:0C:EE:47:BF',
			'NASPortType' => 15,
			'NASPort' => '15729175',
			'FramedProtocol' => 1,
			'ServiceType' => 2,
		}
	);


Nigel Kukard's avatar
Nigel Kukard committed
466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511
	#
	# Check we get a Access-Accept for an uncapped usage user
	#

	my $user3_ID = testDBInsert("Create user 'testuser3'",
		"INSERT INTO users (UserName,Disabled) VALUES ('testuser3',0)"
	);

	my $user3attr1_ID = testDBInsert("Create user 'testuser3' attribute 'User-Password'",
		"INSERT INTO user_attributes (UserID,Name,Operator,Value,Disabled) VALUES (?,?,?,?,0)",
			$user3_ID,'User-Password','==','test456'
	);

	my $user3attr2_ID = testDBInsert("Create user 'testuser3' attribute 'SMRadius-AutoTopup-Traffic-Enabled'",
		"INSERT INTO user_attributes (UserID,Name,Operator,Value,Disabled) VALUES (?,?,?,?,0)",
			$user3_ID,'SMRadius-AutoTopup-Traffic-Enabled',':=','yes'
	);

	my $user3attr3_ID = testDBInsert("Create user 'testuser3' attribute 'SMRadius-AutoTopup-Traffic-Amount'",
		"INSERT INTO user_attributes (UserID,Name,Operator,Value,Disabled) VALUES (?,?,?,?,0)",
			$user3_ID,'SMRadius-AutoTopup-Traffic-Amount',':=','100'
	);

	my $user3attr4_ID = testDBInsert("Create user 'testuser3' attribute 'SMRadius-AutoTopup-Traffic-Limit'",
		"INSERT INTO user_attributes (UserID,Name,Operator,Value,Disabled) VALUES (?,?,?,?,0)",
			$user3_ID,'SMRadius-AutoTopup-Traffic-Limit',':=','500'
	);

	my $user3attr5_ID = testDBInsert("Create user 'testuser3' attribute 'SMRadius-Capping-Uptime-Limit'",
		"INSERT INTO user_attributes (UserID,Name,Operator,Value,Disabled) VALUES (?,?,?,?,0)",
			$user3_ID,'SMRadius-Capping-Uptime-Limit',':=','0'
	);

	$res = smradius::client->run(
		"--raddb","dicts",
		"127.0.0.1",
		"auth",
		"secret123",
		'User-Name=testuser3',
		'User-Password=test456',
	);
	is(ref($res),"HASH","smradclient should return a HASH");
	is($res->{'response'}->{'code'},"Access-Accept","Check our return is 'Access-Accept' for a basically configured user");



512 513
	sleep(5);

514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552

} else {

	smradius::daemon->run(
		"--fg",
		"--debug",
		"--config", "smradiusd.conf.test",
	);

	sleep 4;

	exit 0;
}



cleanup();

done_testing();




# Cleanup function
sub cleanup
{
	if ($child) {
		# Kill the child if it exists
		if (kill(0,$child)) {
			kill('TERM',$child);
		}
		# Wait for it to be reaped
		waitpid($child,-1);
	}

}



Nigel Kukard's avatar
Nigel Kukard committed
553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573
# Function to quickly and easily insert data into the DB and generate 2 tests out of it
sub testDBInsert
{
	my ($name,@params) = @_;


	# Do the work...
	DBDo(@params);
	# Make sure we got no error
	is(AWITPT::DB::DBLayer::error(),"",$name);

	# Grab the last insert ID
	my $id = DBLastInsertID();
	# Make sure its > 0
	is($id > 0,1,"$name, insert ID > 0");

	return $id;
}



574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618
# Test DB select results
sub testDBResults
{
	my ($name,$table,$where,$resultCheck) = @_;


	# Build column list
	my $columnList_str = join(',',keys %{$resultCheck});

	# Create where criteria
	my @whereLines = ();
	my @whereData = ();
	foreach my $columnName (keys %{$where}) {
		# Add template placeholders
		push(@whereLines,"$columnName = ?");
		# Add data for template placeholders
		push(@whereData,$where->{$columnName});
	}
	my $whereLines_str = join(',',@whereLines);

	# Do select
	my $sth = DBSelect("
		SELECT
			$columnList_str
		FROM
			$table
		WHERE
			$whereLines_str
	",@whereData);

	# Make sure we got no error
	is(AWITPT::DB::DBLayer::error(),"","Errors on DBSelect: $name");

	# We should get one result...
	my $row = hashifyLCtoMC($sth->fetchrow_hashref(),keys %{$resultCheck});
	is(defined($row),1,"DBSelect row defined: $name");

	# Loop through results and check if they match
	foreach my $resultName (keys %{$resultCheck}) {
		is($row->{$resultName},$resultCheck->{$resultName},"$name: $resultName check");
	}
}



619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649
sub _timestampCheck
{
	my ($testVal,$rightVal) = @_;


	# Make sure testVal is defined
	return "_timestampCheck: NO \$testVal" if (!defined($testVal));
	# Make sure $testVal_time is returned form str2time
	my $testVal_time = str2time($testVal,'UTC');

	# Check if $rightVal is defined
	my $rightVal_time;
	if (!defined($rightVal)) {
		$rightVal_time = time();
	} elsif ($rightVal =~ /^\d+$/) {
		$rightVal_time = $rightVal;
	} else {
		$rightVal_time = str2time($rightVal,'UTC');
	}

	# Make sure rightVal_time is defined
	return "_timestampCheck: NO \$rightVal_time" if (!defined($rightVal_time));

	# Grab the absolute difference
	my $diff = abs($testVal_time - $rightVal_time);

	return ($diff < 10) // "TIME DEVIATION: $diff";
}