xaizek / rocketgit (License: AGPLv3+) (since 2018-12-09)
Light and fast Git hosting solution suitable to serve both as a hub or as a personal code storage with its tickets, pull requests, API and much more.
<root> / tests / helpers.inc.php (e1e33b254222b08b608509f096b2026178e03679) (12KiB) (mode 100644) [raw]
1 2 3 4 5 6 7 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 76 77 78 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 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 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 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 266 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 320 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 375 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 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 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 512 513
<?php
// Some helper functions dealing with users/repos/bugs/etc.

include_once('totp.inc.php');

/*
 * Creating a user
 */
$_user_id = time() . '-' . rg_id(8);
$_testns = 'main';
function rg_test_create_user($db, &$rg_ui)
{
	global $_testns;
	global $_user_id;

	if (!isset($_user_id))
		$_user_id = time() . '-' . rg_id(8);

	if (!is_array($rg_ui))
		$rg_ui = array();

	$username = $_testns . '-user-' . $_user_id . '<xss>e';

	$new = array();
	$new['uid'] = 0;
	$new['organization'] = 0;
	$new['username'] = $username;
	$new['realname'] = 'realname-' . $_user_id . '<xss>';
	$new['email'] = 'email-' . $_user_id . '@embedromix.ro';
	$new['is_admin'] = 0;
	$new['rights'] = 'C';
	$new['session_time'] = 3600;
	$new['confirm_token'] = '';
	$new['confirmed'] = 0;
	$new['plan_id'] = 0;
	$new['pass'] = 'pass-' . $_user_id . ':';
	$new['pass2'] = 'pass-' . $_user_id . ':';
	$new['disk_used_mb'] = 0;
	$new['git_mb'] = 0;
	$new['artifacts_mb'] = 0;
	$new['last_ip'] = '?';
	$_user_id++;

	// Delete old user
	$sql = 'DELETE FROM users WHERE username = @@username@@';
	$res = rg_sql_query_params($db, $sql, $new);
	if ($res === FALSE) {
		rg_log("Cannot delete old user: " . rg_sql_error());
		exit(1);
	}
	rg_sql_free_result($res);

	rg_cache_unset('username_to_uid::' . $username, RG_SOCKET_NO_WAIT);

	$rg_ui = array_merge($new, $rg_ui);
	$r = rg_user_edit($db, $rg_ui);
	if ($r === FALSE) {
		rg_log("Cannot create user (" . rg_user_error() . ")!");
		exit(1);
	}
	$rg_ui['uid'] = $r;

	// delete associated bugs
	$sql = "SELECT * FROM repos WHERE uid = " . $rg_ui['uid'];
	$res = rg_sql_query($db, $sql);
	while (($row = rg_sql_fetch_array($res))) {
		$_t = array('bug_labels', 'bug_notes', 'bug_search', 'bugs',
			'merge_requests', 'watch_bug', 'watch_repo');
		foreach ($_t as $_table) {
			$sql = "DELETE FROM $_table WHERE repo_id = " . $row['repo_id'];
			$res2 = rg_sql_query($db, $sql);
			rg_sql_free_result($res2);
		}

		$sql = "DELETE FROM rights WHERE type = 'repo' AND obj_id = " . $row['repo_id'];
		$res2 = rg_sql_query($db, $sql);
		rg_sql_free_result($res2);
	}
	rg_sql_free_result($res);

	// delete associated repos
	$sql = "DELETE FROM repos WHERE uid = " . $rg_ui['uid'];
	$res = rg_sql_query($db, $sql);
	rg_sql_free_result($res);

	// Delete associated keys
	$sql = "DELETE FROM keys WHERE uid = " . $rg_ui['uid'];
	$res = rg_sql_query($db, $sql);
	rg_sql_free_result($res);

	// Delete given rights
	$sql = "DELETE FROM rights WHERE uid = " . $rg_ui['uid'];
	$res = rg_sql_query($db, $sql);
	rg_sql_free_result($res);

	// Delete login tokens
	$sql = "DELETE FROM login_tokens WHERE uid = " . $rg_ui['uid'];
	$res = rg_sql_query($db, $sql);
	rg_sql_free_result($res);

	// Delete login tokens ips
	$sql = "DELETE FROM login_tokens_ip WHERE uid = " . $rg_ui['uid'];
	$res = rg_sql_query($db, $sql);
	rg_sql_free_result($res);
}

/*
 * Creating a repo helper; see rg_test_create_repo()
 */
$_repo_id = 1;
function rg_test_create_repo_no_dir($db, $rg_ui, &$extra)
{
	global $_testns;
	global $_repo_id;

	if (!is_array($extra))
		$extra = array();

	$repo_id = isset($extra['repo_id']) ? $extra['repo_id'] : 0;

	rg_log('Creating a repo with id ' . $repo_id);
	$new = array();
	$new['master'] = 0;
	if (isset($extra['name']))
		$new['name'] = $extra['name'];
	else
		$new['name'] = $_testns . '-repo-' . $_repo_id . '<xss>' . rand();
	$new['max_commit_size'] = 0;
	$new['description'] = 'desc line1\ndesc line2' . '<xss>';
	$new['git_dir_done'] = 0;
	$new['public'] = 1;
	$new['license'] = 'GPL <xss>';
	$new['template'] = 'template here <xss>';
	$_repo_id++;

	rg_log("Deleting repo " . $repo_id . "/" . $new['name']);
	$sql = 'DELETE FROM repos WHERE repo_id = ' . $repo_id
		. ' OR name = @@name@@';
	$res = rg_sql_query_params($db, $sql, $new);
	if ($res === FALSE) {
		rg_log("Cannot delete old repo: " . rg_sql_error());
		exit(1);
	}
	rg_sql_free_result($res);

	$extra = array_merge($new, $extra);
	$extra['repo_id'] = 0;

	$r = rg_repo_edit($db, $rg_ui, $extra);
	if ($r === FALSE) {
		rg_log("Cannot insert a repo (" . rg_repo_error() . ")!");
		exit(1);
	}
	rg_repo_cosmetic($db, $extra);
	rg_log_ml('extra: ' . print_r($extra, TRUE));

	if ($repo_id > 0) {
		$sql = "UPDATE repos SET repo_id = $repo_id"
			. " WHERE repo_id = " . $extra['repo_id'];
		$res = rg_sql_query($db, $sql);
		rg_sql_free_result($res);
		$new['repo_id'] = $repo_id;
		// TODO: this is strange
		rg_cache_unset('repo_by_name::' . $rg_ui['uid'],
			RG_SOCKET_NO_WAIT);
	}
}

/*
 * Creating a repo helper
 * You can enforce a repo-name/repo-id by setting extra['name/repo_id'].
 */
function rg_test_create_repo($db, $rg_ui, &$extra)
{
	rg_test_create_repo_no_dir($db, $rg_ui, $extra);

	$key = 'repo_by_id' . '::' . $extra['repo_id'];
	rg_log('Waiting for the repo git dir to be created (key [' . $key . '])...');
	$tries = 50;
	while ($tries > 0) {
		$tries--;

		rg_cache_core_unset($key);
		$r = rg_cache_get($key);
		if ($r === FALSE) {
			sleep(1);
			continue;
		}

		//rg_log_ml('DEBUG: r: ' . print_r($r, TRUE));

		if ($r['git_dir_done'] == 1)
			break;

		sleep(1);
	}
	if ($tries === 0) {
		rg_log('Seems that the git folder was not created!');
		exit(1);
	}
}

/*
 * Creating a ssh key helper
 */
function rg_test_create_key($db, $rg_ui)
{
	rg_log("Creating a key");
	// spaces are on purpose, to test that we remove them correctly
	$skey = 'ssh-rsa AAAAB3Nz  aC1yc2EAAAADA  QABAAABAQDgy8QSbr13izfGxO0sqOsxu4faw6hF1LLrlcBobT5zzO4wzbokjliRiZ9sfA0zd0WEfdQJ6W01hVNf9QpJlUiGM4OyXBKOc8JLfCyjtcfRcC48hPQ22IY9TtfrxGK38IgwdS7+Ophjs8u0RlqHd8eMtYWcmxlHwdIEb6+IZ6kyA2srmFGN6DQCnOvyYSd+iZ8u4DQBEuWxzsKvrat9gR5H6KNTYisSB9rjLKQd4rFbu6Tl217wJY1LWjH7hlFPxioMCg0Fzv6AkQXWnAr1GrCVgIQDC5dEVUrw2NSVElEC+eaG6OZnkq7CP0B8pSj3BV2TNhSgnQb9Ojo9xNHc2Pwx aaa@aaa.aaa';

	$r = rg_keys_add($db, $rg_ui, $skey);
	if ($r === FALSE) {
		rg_log("Cannot add a key (" . rg_keys_error() . ")!");
		exit(1);
	}

	return $r;
}

/*
 * Helper to add some rights
 */
function rg_test_create_rights($db, $rg_ui, $ri, &$extra)
{
	if (!is_array($extra))
		$extra = array();

	$a = array();
	$a['right_id'] = 0;
	$a['who'] = 90;
	$a['obj_id'] = $ri['repo_id'];
	$a['uid'] = $rg_ui['uid'];
	$a['rights'] = "abc";
	$a['misc'] = "misc1/@USER@/";
	$a['ip'] = "1.1.1.1 2.2.2.2 10.0.0.0/8";
	$a['prio'] = 13;
	$a['description'] = "desc1";
	$r = rg_rights_set($db, "type1", $a);
	if ($r !== TRUE) {
		rg_log("Seems I cannot set rights 1 (" . rg_rights_error() . ")");
		exit(1);
	}

	return $r;
}

/*
 * Helper to add a bug
 */
function rg_test_create_bug($db, $rg_ui, $ri, &$extra)
{
	if (!is_array($extra))
		$extra = array();

	$a = array();
	$a['bug_id'] = 0;
	$a['itime'] = time() - 600;
	$a['utime'] = time() - 300;
	$a['uid'] = 30;
	$a['ip'] = '1.1.1.1 <xss>';
	$a['title'] = 'a nice title <xss>';
	$a['body'] = 'a nice body <xss>';
	$a['assigned_uid'] = 0;
	$a['deleted'] = 0;
	$a['deleted_who'] = 0;
	$a['state'] = 1;
	$r = rg_bug_edit($db, $rg_ui, $ri, $a);
	if ($r === FALSE) {
		rg_log('Seems I cannot add bug: ' . rg_bug_error() . ")");
		exit(1);
	}

	return $r;
}

/*
 * Helper for creating and uploading a ssh key
 * Returns the key.
 */
function rg_test_upload_ssh_key($db, $rg_ui, $key_suffix, &$key_name)
{
	global $test_url;

	$key_name = $rg_ui['uid'] . $key_suffix;
	putenv('RG_SSH_KEY=' . $key_name);

	// we must regenerate the key because else we will not be the correct user
	rg_log_enter("Generating a SSH key [$key_name]");
	if (file_exists('keys/' . $key_name))
		unlink('keys/' . $key_name);
	if (file_exists('keys/' . $key_name . '.pub'))
		unlink('keys/' . $key_name . '.pub');
	$r = rg_exec("ssh-keygen -t rsa -N '' -b 4096 -C \"Key for RocketGit\""
		. " -f keys/" . escapeshellarg($key_name) . " </dev/null",
		'', FALSE, FALSE, FALSE);
	if ($r['ok'] != 1) {
		rg_log('Cannot generate key: ' . $r['stderr']);
		exit(1);
	}
	if (!file_exists("keys/" . $key_name . ".pub")) {
		rg_log("Could not find the ssh key!");
		exit(1);
	}

	$key = file_get_contents("keys/" . $key_name . ".pub");

	rg_log("Loading ssh key form...");
	$data = array();
	$headers = array();
	$r = do_req($test_url . "/op/settings/keys?t=load_key_form", $data, $headers);
	if ($r === FALSE) {
		rg_log("Cannot load form!");
		exit(1);
	}
	if (empty($r['tokens']['keys'])) {
		rg_log_ml('r: ' . print_r($r, TRUE));
		rg_log('token not found!');
		exit(1);
	}

	rg_log("Uploading the key...");
	$data = array('add' => 1, 'token' => $r['tokens']['keys'], 'key' => $key);
	$headers = array();
	$r = do_req($test_url . '/op/settings/keys?t=upload_ssh_key', $data, $headers);
	if ($r === FALSE) {
		rg_log_ml('r: ' . print_r($r, TRUE));
		rg_log_ml("Cannot upload key!");
		exit(1);
	}

	$akp = rg_state_get($db, 'AuthorizedKeysCommand');
	if ($akp == 0) {
		rg_log("Waiting for key to be added to the authorized_keys file");
		while (1) {
			$c = file_get_contents("/home/rocketgit/.ssh/authorized_keys");
			if (strstr($c, $key))
				break;

			sleep(1);
		}
	}
	rg_log("Uploading done");
	rg_log_exit();

	return $key;
}

/*
 * Helper for generating scratch codes
 * Returns the scratch codes.
 */
function rg_test_sc_generate($db, $rg_ui)
{
	global $test_url;

	rg_log("Loading generate scratch codes form...");
	$data = array();
	$headers = array();
	$r = do_req($test_url . "/op/settings/totp/sc", $data, $headers);
	if ($r === FALSE) {
		rg_log("Cannot load form!");
		exit(1);
	}
	if (empty($r['tokens']['sc'])) {
		rg_log_ml('r: ' . print_r($r, TRUE));
		rg_log('token not found!');
		exit(1);
	}

	rg_log("Generating scratch codes...");
	$data = array('generate' => 1, 'token' => $r['tokens']['sc']);
	$headers = array();
	$r = do_req($test_url . '/op/settings/totp/sc', $data, $headers);
	if ($r === FALSE) {
		rg_log_ml('r: ' . print_r($r, TRUE));
		rg_log_ml('Cannot generate scratch codes!');
		exit(1);
	}

	rg_log("Generation done");

	$t = explode('<div class="secret_token">', $r['body']);
	$t = explode('</div>', $t[1]);
	$t = explode("\n", $t[0]);
	$sc = explode(' ', trim($t[1]));

	rg_log_ml('DEBUG: sc: ' . print_r($sc, TRUE));

	return $sc;
}

/*
 * Helper for adding a webhook
 */
function rg_test_wh_add_edit($db, $rg_ui, $htype, $hsubtype, $extra)
{
	global $test_url;

	rg_log_enter('Loading webhook add form...');
	$headers = array();

	if (!isset($extra['wh::id']))
		$extra['wh::id'] = 0;

	if ($extra['wh::id'] == 0)
		$url = 'add/' . $htype . '/' . $hsubtype;
	else
		$url = 'edit/' . $extra['wh::id'];
	$r = do_req($test_url . "/op/settings/wh/" . $url, $data, $headers);
	if ($r === FALSE) {
		rg_log("Cannot load form!");
		exit(1);
	}
	if (empty($r['tokens']['wh_add'])) {
		rg_log_ml('r: ' . print_r($r, TRUE));
		rg_log_ml('Token not found!');
		exit(1);
	}

	rg_log("Adding webhook...");
	$data = array('doit' => 1, 'token' => $r['tokens']['wh_add']);
	$data = array_merge($data, $extra);
	$headers = array();
	$r = do_req($test_url . '/op/settings/wh/' . $url, $data, $headers);
	if ($r === FALSE) {
		rg_log_ml('r: ' . print_r($r, TRUE));
		rg_log_ml('Cannot add webhook!');
		exit(1);
	}

	if (!strstr($r['body'], 'success')) {
		rg_log_ml('r[body]: ' . print_r($r['body'], TRUE));
		rg_log('Cannot add webhook (no \'with success\' message)!');
		exit(1);
	}

	rg_log_exit();
}

/*
 * Check if a merge request hit the database
 * Returns the row or exits
 */
function rg_test_mr_info($db, $repo_id, $nr)
{
	rg_log_enter('Check if the merge request ' . $nr . ' is in database...');
	$tries = 10;
	while ($tries > 0) {
		$params = array('nr' => $nr);
		$sql = 'SELECT * FROM merge_requests'
			. ' WHERE repo_id = ' . $repo_id
			. ' AND id = @@nr@@';
		$res = rg_sql_query_params($db, $sql, $params);
		$rows = rg_sql_num_rows($res);
		if ($rows > 0)
			$row = rg_sql_fetch_array($res);
		rg_sql_free_result($res);
		if ($rows > 0)
			break;

		sleep(1);
		$tries--;
	}
	if ($rows == 0) {
		rg_log('Seems the merge request did not hit the database!');
		exit(1);
	}

	rg_log_exit();
	return $row;
}

/*
 * Run ssh command, using a generated key
 */
function test_ssh($uid, $extra)
{
	global $rg_ssh_host, $rg_ssh_port;

	$kn = getenv('RG_SSH_KEY');

	$cmd = 'ssh -v'
		. ' -i keys/' . $kn
		. ' -p ' . $rg_ssh_port
		. ' -o ControlMaster=no'
		. ' -o ControlPath=' . __DIR__ . '/jars/ssh-' . $uid
		. ' rocketgit@' . $rg_ssh_host;

	return rg_exec($cmd . ' ' . $extra, '', FALSE, FALSE, FALSE);
}

/*
 * Wait for a value in cache
 */
function test_wait_cache($key)
{
	for ($i = 0; $i < 50; $i++) {
		rg_cache_core_unset($key);
		$r = rg_cache_get($key);
		if ($r !== FALSE)
			break;
		sleep(1);
	}

	if ($r === FALSE) {
		rg_log('Could not obtain a value from cache for key [' . $key . ']!');
		exit(1);
	}

	return $r;
}

Hints

Before first commit, do not forget to setup your git environment:
git config --global user.name "your_name_here"
git config --global user.email "your@email_here"

Clone this repository using HTTP(S):
git clone https://code.reversed.top/user/xaizek/rocketgit

Clone this repository using ssh (do not forget to upload a key first):
git clone ssh://rocketgit@code.reversed.top/user/xaizek/rocketgit

You are allowed to anonymously push to this repository.
This means that your pushed commits will automatically be transformed into a pull request:
... clone the repository ...
... make some changes and some commits ...
git push origin master