Remove outdated test files and update peer registration logic

This commit is contained in:
netkas 2024-12-23 19:25:21 -05:00
parent 1108711eb7
commit 7e4b02bc04
18 changed files with 362 additions and 819 deletions

View file

@ -113,20 +113,26 @@
if($response === false)
{
curl_close($ch);
throw new RpcException('Failed to create the session, no response received');
throw new RpcException(sprintf('Failed to create the session at %s, no response received', $this->rpcEndpoint));
}
$responseCode = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
if($responseCode !== 201)
{
curl_close($ch);
throw new RpcException('Failed to create the session, server responded with ' . $responseCode . ': ' . $response);
if(empty($response))
{
throw new RpcException(sprintf('Failed to create the session at %s, server responded with ' . $responseCode, $this->rpcEndpoint));
}
throw new RpcException(sprintf('Failed to create the session at %s, server responded with ' . $responseCode . ': ' . $response, $this->rpcEndpoint));
}
if(empty($response))
{
curl_close($ch);
throw new RpcException('Failed to create the session, server did not return a session UUID');
throw new RpcException(sprintf('Failed to create the session at %s, server did not return a session UUID', $this->rpcEndpoint));
}
curl_close($ch);

View file

@ -1,340 +1,354 @@
<?php
namespace Socialbox\Managers;
namespace Socialbox\Managers;
use PDO;
use PDOException;
use Socialbox\Classes\Configuration;
use Socialbox\Classes\Database;
use Socialbox\Classes\Logger;
use Socialbox\Enums\Flags\PeerFlags;
use Socialbox\Enums\StandardError;
use Socialbox\Exceptions\DatabaseOperationException;
use Socialbox\Exceptions\StandardException;
use Socialbox\Objects\Database\RegisteredPeerRecord;
use Socialbox\Objects\Database\SecurePasswordRecord;
use Symfony\Component\Uid\Uuid;
use PDO;
use PDOException;
use Socialbox\Classes\Configuration;
use Socialbox\Classes\Database;
use Socialbox\Classes\Logger;
use Socialbox\Enums\Flags\PeerFlags;
use Socialbox\Exceptions\DatabaseOperationException;
use Socialbox\Objects\Database\RegisteredPeerRecord;
use Socialbox\Objects\Database\SecurePasswordRecord;
use Socialbox\Objects\PeerAddress;
use Symfony\Component\Uid\Uuid;
class RegisteredPeerManager
{
/**
* Checks if a username already exists in the database.
*
* @param string $username The username to check.
* @return bool True if the username exists, false otherwise.
* @throws DatabaseOperationException If the operation fails.
*/
public static function usernameExists(string $username): bool
class RegisteredPeerManager
{
Logger::getLogger()->verbose(sprintf("Checking if username %s already exists", $username));
try
/**
* Checks if a username already exists in the database.
*
* @param string $username The username to check.
* @return bool True if the username exists, false otherwise.
* @throws DatabaseOperationException If the operation fails.
*/
public static function usernameExists(string $username): bool
{
$statement = Database::getConnection()->prepare('SELECT COUNT(*) FROM `registered_peers` WHERE username=?');
$statement->bindParam(1, $username);
$statement->execute();
Logger::getLogger()->verbose(sprintf("Checking if username %s already exists", $username));
$result = $statement->fetchColumn();
return $result > 0;
}
catch(PDOException $e)
{
throw new DatabaseOperationException('Failed to check if the username exists', $e);
}
}
/**
* Creates a new peer with the given username.
*
* @param string $username The username to associate with the new peer.
* @param bool $enabled True if the peer should be enabled, false otherwise.
* @return string The UUID of the newly created peer.
* @throws DatabaseOperationException If the operation fails.
*/
public static function createPeer(string $username, bool $enabled=false): string
{
Logger::getLogger()->verbose(sprintf("Creating a new peer with username %s", $username));
$uuid = Uuid::v4()->toRfc4122();
try
{
$statement = Database::getConnection()->prepare('INSERT INTO `registered_peers` (uuid, username, enabled) VALUES (?, ?, ?)');
$statement->bindParam(1, $uuid);
$statement->bindParam(2, $username);
$statement->bindParam(3, $enabled, PDO::PARAM_BOOL);
$statement->execute();
}
catch(PDOException $e)
{
throw new DatabaseOperationException('Failed to create the peer in the database', $e);
}
return $uuid;
}
/**
* Deletes a peer from the database based on the given UUID or RegisteredPeerRecord.
* WARNING: This operation is cascading and will delete all associated data.
*
* @param string|RegisteredPeerRecord $uuid The UUID or RegisteredPeerRecord instance representing the peer to be deleted.
* @return void
* @throws DatabaseOperationException If the operation fails.
*/
public static function deletePeer(string|RegisteredPeerRecord $uuid): void
{
if($uuid instanceof RegisteredPeerRecord)
{
$uuid = $uuid->getUuid();
}
Logger::getLogger()->verbose(sprintf("Deleting peer %s", $uuid));
try
{
$statement = Database::getConnection()->prepare('DELETE FROM `registered_peers` WHERE uuid=?');
$statement->bindParam(1, $uuid);
$statement->execute();
}
catch(PDOException $e)
{
throw new DatabaseOperationException('Failed to delete the peer from the database', $e);
}
}
/**
* Retrieves a registered peer record based on the given unique identifier or RegisteredPeerRecord object.
*
* @param string|RegisteredPeerRecord $uuid The unique identifier of the registered peer, or an instance of RegisteredPeerRecord.
* @return RegisteredPeerRecord Returns a RegisteredPeerRecord object containing the peer's information.
* @throws DatabaseOperationException If there is an error during the database operation.
*/
public static function getPeer(string|RegisteredPeerRecord $uuid): RegisteredPeerRecord
{
if($uuid instanceof RegisteredPeerRecord)
{
$uuid = $uuid->getUuid();
}
Logger::getLogger()->verbose(sprintf("Retrieving peer %s from the database", $uuid));
try
{
$statement = Database::getConnection()->prepare('SELECT * FROM `registered_peers` WHERE uuid=?');
$statement->bindParam(1, $uuid);
$statement->execute();
$result = $statement->fetch(PDO::FETCH_ASSOC);
if($result === false)
try
{
throw new DatabaseOperationException(sprintf("The requested peer '%s' does not exist", $uuid));
$statement = Database::getConnection()->prepare('SELECT COUNT(*) FROM `registered_peers` WHERE username=?');
$statement->bindParam(1, $username);
$statement->execute();
$result = $statement->fetchColumn();
return $result > 0;
}
return new RegisteredPeerRecord($result);
}
catch(PDOException | \DateMalformedStringException $e)
{
throw new DatabaseOperationException('Failed to get the peer from the database', $e);
}
}
/**
* Retrieves a peer record by the given username.
*
* @param string $username The username of the peer to be retrieved.
* @return RegisteredPeerRecord|null The record of the peer associated with the given username.
* @throws DatabaseOperationException If there is an error while querying the database.
*/
public static function getPeerByUsername(string $username): ?RegisteredPeerRecord
{
Logger::getLogger()->verbose(sprintf("Retrieving peer %s from the database", $username));
try
{
$statement = Database::getConnection()->prepare('SELECT * FROM `registered_peers` WHERE username=?');
$statement->bindParam(1, $username);
$statement->execute();
$result = $statement->fetch(PDO::FETCH_ASSOC);
if($result === false)
catch(PDOException $e)
{
return null;
}
return new RegisteredPeerRecord($result);
}
catch(PDOException | \DateMalformedStringException $e)
{
throw new DatabaseOperationException('Failed to get the peer from the database', $e);
}
}
/**
* Enables a peer identified by the given UUID or RegisteredPeerRecord.
*
* @param string|RegisteredPeerRecord $uuid The UUID or RegisteredPeerRecord instance representing the peer to be enabled.
* @return void
* @throws DatabaseOperationException If there is an error while updating the database.
*/
public static function enablePeer(string|RegisteredPeerRecord $uuid): void
{
if($uuid instanceof RegisteredPeerRecord)
{
$uuid = $uuid->getUuid();
}
Logger::getLogger()->verbose(sprintf("Enabling peer %s", $uuid));
try
{
$statement = Database::getConnection()->prepare('UPDATE `registered_peers` SET enabled=1 WHERE uuid=?');
$statement->bindParam(1, $uuid);
$statement->execute();
}
catch(PDOException $e)
{
throw new DatabaseOperationException('Failed to enable the peer in the database', $e);
}
}
/**
* Disables the peer identified by the given UUID or RegisteredPeerRecord.
*
* @param string|RegisteredPeerRecord $uuid The UUID or RegisteredPeerRecord instance representing the peer.
* @return void
* @throws DatabaseOperationException If there is an error while updating the peer's status in the database.
*/
public static function disablePeer(string|RegisteredPeerRecord $uuid): void
{
if($uuid instanceof RegisteredPeerRecord)
{
$uuid = $uuid->getUuid();
}
Logger::getLogger()->verbose(sprintf("Disabling peer %s", $uuid));
try
{
$statement = Database::getConnection()->prepare('UPDATE `registered_peers` SET enabled=0 WHERE uuid=?');
$statement->bindParam(1, $uuid);
$statement->execute();
}
catch(PDOException $e)
{
throw new DatabaseOperationException('Failed to disable the peer in the database', $e);
}
}
/**
* Adds a specific flag to the peer identified by the given UUID or RegisteredPeerRecord.
*
* @param string|RegisteredPeerRecord $uuid The UUID or RegisteredPeerRecord instance representing the peer.
* @param PeerFlags|array $flags The flag or array of flags to be added to the peer.
* @return void
* @throws DatabaseOperationException If there is an error while updating the database.
*/
public static function addFlag(string|RegisteredPeerRecord $uuid, PeerFlags|array $flags): void
{
if($uuid instanceof RegisteredPeerRecord)
{
$uuid = $uuid->getUuid();
}
Logger::getLogger()->verbose(sprintf("Adding flag(s) %s to peer %s", implode(',', $flags), $uuid));
$peer = self::getPeer($uuid);
$existingFlags = $peer->getFlags();
$flags = is_array($flags) ? $flags : [$flags];
foreach($flags as $flag)
{
if(!in_array($flag, $existingFlags))
{
$existingFlags[] = $flag;
throw new DatabaseOperationException('Failed to check if the username exists', $e);
}
}
try
/**
* Creates a new peer with the given username.
*
* @param PeerAddress $peerAddress The address of the peer to be created.
* @param bool $enabled True if the peer should be enabled, false otherwise.
* @return string The UUID of the newly created peer.
* @throws DatabaseOperationException If the operation fails.
*/
public static function createPeer(PeerAddress $peerAddress, bool $enabled=false): string
{
$implodedFlags = implode(',', array_map(fn($flag) => $flag->name, $existingFlags));
$statement = Database::getConnection()->prepare('UPDATE `registered_peers` SET flags=? WHERE uuid=?');
$statement->bindParam(1, $implodedFlags);
$statement->bindParam(2, $uuid);
$statement->execute();
}
catch(PDOException $e)
{
throw new DatabaseOperationException('Failed to add the flag to the peer in the database', $e);
}
}
Logger::getLogger()->verbose(sprintf("Registering peer %s", $peerAddress->getAddress()));
$uuid = Uuid::v4()->toRfc4122();
$server = $peerAddress->getDomain();
/**
* Removes a specific flag from the peer identified by the given UUID or RegisteredPeerRecord.
*
* @param string|RegisteredPeerRecord $peer
* @param PeerFlags $flag The flag to be removed from the peer.
* @return void
* @throws DatabaseOperationException If there is an error while updating the database.
*/
public static function removeFlag(string|RegisteredPeerRecord $peer, PeerFlags $flag): void
{
if(is_string($peer))
{
$peer = self::getPeer($peer);
}
Logger::getLogger()->verbose(sprintf("Removing flag %s from peer %s", $flag->value, $peer->getUuid()));
if(!$peer->flagExists($flag))
{
return;
}
$peer->removeFlag($flag);
try
{
$implodedFlags = PeerFlags::toString($peer->getFlags());
$statement = Database::getConnection()->prepare('UPDATE `registered_peers` SET flags=? WHERE uuid=?');
$statement->bindParam(1, $implodedFlags);
$statement->bindParam(2, $registeredPeer);
$statement->execute();
}
catch(PDOException $e)
{
throw new DatabaseOperationException('Failed to remove the flag from the peer in the database', $e);
}
}
/**
*
*/
public static function getPasswordAuthentication(string|RegisteredPeerRecord $peerUuid): ?SecurePasswordRecord
{
if($peerUuid instanceof RegisteredPeerRecord)
{
$peerUuid = $peerUuid->getUuid();
}
try
{
$statement = Database::getConnection()->prepare('SELECT * FROM `authentication_passwords` WHERE peer_uuid=?');
$statement->bindParam(1, $peerUuid);
$statement->execute();
$result = $statement->fetch(PDO::FETCH_ASSOC);
if($result === false)
if($server === Configuration::getInstanceConfiguration()->getDomain())
{
return null;
$server = 'host';
}
return new SecurePasswordRecord($result);
try
{
$statement = Database::getConnection()->prepare('INSERT INTO `registered_peers` (uuid, username, server, enabled) VALUES (?, ?, ?, ?)');
$statement->bindParam(1, $uuid);
$username = $peerAddress->getUsername();
$statement->bindParam(2, $username);
$statement->bindParam(3, $server);
$statement->bindParam(4, $enabled, PDO::PARAM_BOOL);
$statement->execute();
}
catch(PDOException $e)
{
throw new DatabaseOperationException('Failed to create the peer in the database', $e);
}
return $uuid;
}
catch(PDOException | \DateMalformedStringException $e)
/**
* Deletes a peer from the database based on the given UUID or RegisteredPeerRecord.
* WARNING: This operation is cascading and will delete all associated data.
*
* @param string|RegisteredPeerRecord $uuid The UUID or RegisteredPeerRecord instance representing the peer to be deleted.
* @return void
* @throws DatabaseOperationException If the operation fails.
*/
public static function deletePeer(string|RegisteredPeerRecord $uuid): void
{
throw new DatabaseOperationException('Failed to get the secure password record from the database', $e);
if($uuid instanceof RegisteredPeerRecord)
{
$uuid = $uuid->getUuid();
}
Logger::getLogger()->verbose(sprintf("Deleting peer %s", $uuid));
try
{
$statement = Database::getConnection()->prepare('DELETE FROM `registered_peers` WHERE uuid=?');
$statement->bindParam(1, $uuid);
$statement->execute();
}
catch(PDOException $e)
{
throw new DatabaseOperationException('Failed to delete the peer from the database', $e);
}
}
}
}
/**
* Retrieves a registered peer record based on the given unique identifier or RegisteredPeerRecord object.
*
* @param string|RegisteredPeerRecord $uuid The unique identifier of the registered peer, or an instance of RegisteredPeerRecord.
* @return RegisteredPeerRecord Returns a RegisteredPeerRecord object containing the peer's information.
* @throws DatabaseOperationException If there is an error during the database operation.
*/
public static function getPeer(string|RegisteredPeerRecord $uuid): RegisteredPeerRecord
{
if($uuid instanceof RegisteredPeerRecord)
{
$uuid = $uuid->getUuid();
}
Logger::getLogger()->verbose(sprintf("Retrieving peer %s from the database", $uuid));
try
{
$statement = Database::getConnection()->prepare('SELECT * FROM `registered_peers` WHERE uuid=?');
$statement->bindParam(1, $uuid);
$statement->execute();
$result = $statement->fetch(PDO::FETCH_ASSOC);
if($result === false)
{
throw new DatabaseOperationException(sprintf("The requested peer '%s' does not exist", $uuid));
}
return new RegisteredPeerRecord($result);
}
catch(PDOException | \DateMalformedStringException $e)
{
throw new DatabaseOperationException('Failed to get the peer from the database', $e);
}
}
/**
* Retrieves a peer record by the given username.
*
* @param PeerAddress $address The address of the peer to be retrieved.
* @return RegisteredPeerRecord|null The record of the peer associated with the given username.
* @throws DatabaseOperationException If there is an error while querying the database.
*/
public static function getPeerByAddress(PeerAddress $address): ?RegisteredPeerRecord
{
Logger::getLogger()->verbose(sprintf("Retrieving peer %s from the database", $address->getAddress()));
try
{
$statement = Database::getConnection()->prepare('SELECT * FROM `registered_peers` WHERE username=? AND server=?');
$username = $address->getUsername();
$statement->bindParam(1, $username);
$server = $address->getDomain();
$statement->bindParam(2, $server);
$statement->execute();
$result = $statement->fetch(PDO::FETCH_ASSOC);
if($result === false)
{
return null;
}
return new RegisteredPeerRecord($result);
}
catch(PDOException | \DateMalformedStringException $e)
{
throw new DatabaseOperationException('Failed to get the peer from the database', $e);
}
}
/**
* Enables a peer identified by the given UUID or RegisteredPeerRecord.
*
* @param string|RegisteredPeerRecord $uuid The UUID or RegisteredPeerRecord instance representing the peer to be enabled.
* @return void
* @throws DatabaseOperationException If there is an error while updating the database.
*/
public static function enablePeer(string|RegisteredPeerRecord $uuid): void
{
if($uuid instanceof RegisteredPeerRecord)
{
$uuid = $uuid->getUuid();
}
Logger::getLogger()->verbose(sprintf("Enabling peer %s", $uuid));
try
{
$statement = Database::getConnection()->prepare('UPDATE `registered_peers` SET enabled=1 WHERE uuid=?');
$statement->bindParam(1, $uuid);
$statement->execute();
}
catch(PDOException $e)
{
throw new DatabaseOperationException('Failed to enable the peer in the database', $e);
}
}
/**
* Disables the peer identified by the given UUID or RegisteredPeerRecord.
*
* @param string|RegisteredPeerRecord $uuid The UUID or RegisteredPeerRecord instance representing the peer.
* @return void
* @throws DatabaseOperationException If there is an error while updating the peer's status in the database.
*/
public static function disablePeer(string|RegisteredPeerRecord $uuid): void
{
if($uuid instanceof RegisteredPeerRecord)
{
$uuid = $uuid->getUuid();
}
Logger::getLogger()->verbose(sprintf("Disabling peer %s", $uuid));
try
{
$statement = Database::getConnection()->prepare('UPDATE `registered_peers` SET enabled=0 WHERE uuid=?');
$statement->bindParam(1, $uuid);
$statement->execute();
}
catch(PDOException $e)
{
throw new DatabaseOperationException('Failed to disable the peer in the database', $e);
}
}
/**
* Adds a specific flag to the peer identified by the given UUID or RegisteredPeerRecord.
*
* @param string|RegisteredPeerRecord $uuid The UUID or RegisteredPeerRecord instance representing the peer.
* @param PeerFlags|array $flags The flag or array of flags to be added to the peer.
* @return void
* @throws DatabaseOperationException If there is an error while updating the database.
*/
public static function addFlag(string|RegisteredPeerRecord $uuid, PeerFlags|array $flags): void
{
if($uuid instanceof RegisteredPeerRecord)
{
$uuid = $uuid->getUuid();
}
Logger::getLogger()->verbose(sprintf("Adding flag(s) %s to peer %s", implode(',', $flags), $uuid));
$peer = self::getPeer($uuid);
$existingFlags = $peer->getFlags();
$flags = is_array($flags) ? $flags : [$flags];
foreach($flags as $flag)
{
if(!in_array($flag, $existingFlags))
{
$existingFlags[] = $flag;
}
}
try
{
$implodedFlags = implode(',', array_map(fn($flag) => $flag->name, $existingFlags));
$statement = Database::getConnection()->prepare('UPDATE `registered_peers` SET flags=? WHERE uuid=?');
$statement->bindParam(1, $implodedFlags);
$statement->bindParam(2, $uuid);
$statement->execute();
}
catch(PDOException $e)
{
throw new DatabaseOperationException('Failed to add the flag to the peer in the database', $e);
}
}
/**
* Removes a specific flag from the peer identified by the given UUID or RegisteredPeerRecord.
*
* @param string|RegisteredPeerRecord $peer
* @param PeerFlags $flag The flag to be removed from the peer.
* @return void
* @throws DatabaseOperationException If there is an error while updating the database.
*/
public static function removeFlag(string|RegisteredPeerRecord $peer, PeerFlags $flag): void
{
if(is_string($peer))
{
$peer = self::getPeer($peer);
}
Logger::getLogger()->verbose(sprintf("Removing flag %s from peer %s", $flag->value, $peer->getUuid()));
if(!$peer->flagExists($flag))
{
return;
}
$peer->removeFlag($flag);
try
{
$implodedFlags = PeerFlags::toString($peer->getFlags());
$statement = Database::getConnection()->prepare('UPDATE `registered_peers` SET flags=? WHERE uuid=?');
$statement->bindParam(1, $implodedFlags);
$statement->bindParam(2, $registeredPeer);
$statement->execute();
}
catch(PDOException $e)
{
throw new DatabaseOperationException('Failed to remove the flag from the peer in the database', $e);
}
}
/**
* Retrieves the password authentication record associated with the given unique peer identifier or a RegisteredPeerRecord object.
*
* @param string|RegisteredPeerRecord $peerUuid The unique identifier of the peer, or an instance of RegisteredPeerRecord.
* @return SecurePasswordRecord|null Returns a SecurePasswordRecord object if a password authentication record exists, otherwise null.
* @throws DatabaseOperationException If there is an error during the database operation.
*/
public static function getPasswordAuthentication(string|RegisteredPeerRecord $peerUuid): ?SecurePasswordRecord
{
if($peerUuid instanceof RegisteredPeerRecord)
{
$peerUuid = $peerUuid->getUuid();
}
try
{
$statement = Database::getConnection()->prepare('SELECT * FROM `authentication_passwords` WHERE peer_uuid=?');
$statement->bindParam(1, $peerUuid);
$statement->execute();
$result = $statement->fetch(PDO::FETCH_ASSOC);
if($result === false)
{
return null;
}
return new SecurePasswordRecord($result);
}
catch(PDOException | \DateMalformedStringException $e)
{
throw new DatabaseOperationException('Failed to get the secure password record from the database', $e);
}
}
}

View file

@ -70,19 +70,9 @@
$flags[] = SessionFlags::SET_DISPLAY_NAME;
}
if(Configuration::getRegistrationConfiguration()->isEmailVerificationRequired())
if(Configuration::getRegistrationConfiguration()->isDisplayPictureRequired())
{
$flags[] = SessionFlags::VER_EMAIL;
}
if(Configuration::getRegistrationConfiguration()->isSmsVerificationRequired())
{
$flags[] = SessionFlags::VER_SMS;
}
if(Configuration::getRegistrationConfiguration()->isPhoneCallVerificationRequired())
{
$flags[] = SessionFlags::VER_PHONE_CALL;
$flags[] = SessionFlags::SET_DISPLAY_PICTURE;
}
if(Configuration::getRegistrationConfiguration()->isImageCaptchaVerificationRequired())
@ -109,6 +99,11 @@
{
$flags[] = SessionFlags::VER_TERMS_OF_SERVICE;
}
if(Configuration::getRegistrationConfiguration()->isAcceptCommunityGuidelinesRequired())
{
$flags[] = SessionFlags::VER_COMMUNITY_GUIDELINES;
}
}
if(count($flags) > 0)

View file

@ -116,11 +116,21 @@
return;
}
// TODO: Check if the peer address points to the domain of this server, if not we can't accept the request
// If the peer is identifying as the same domain
if($clientRequest->getIdentifyAs()->getDomain() === Configuration::getInstanceConfiguration()->getDomain())
{
// Prevent the peer from identifying as the host unless it's coming from an external domain
if($clientRequest->getIdentifyAs()->getUsername() === 'host')
{
http_response_code(403);
print('Unauthorized: The requested peer is not allowed to identify as the host');
return;
}
}
try
{
$registeredPeer = RegisteredPeerManager::getPeerByUsername($clientRequest->getIdentifyAs()->getUsername());
$registeredPeer = RegisteredPeerManager::getPeerByAddress($clientRequest->getIdentifyAs());
// If the peer is registered, check if it is enabled
if($registeredPeer !== null && !$registeredPeer->isEnabled())
@ -143,7 +153,7 @@
}
// Register the peer if it is not already registered
$peerUuid = RegisteredPeerManager::createPeer(PeerAddress::fromAddress($clientRequest->getHeader(StandardHeaders::IDENTIFY_AS))->getUsername());
$peerUuid = RegisteredPeerManager::createPeer(PeerAddress::fromAddress($clientRequest->getHeader(StandardHeaders::IDENTIFY_AS)));
// Retrieve the peer object
$registeredPeer = RegisteredPeerManager::getPeer($peerUuid);
}

View file

@ -1,219 +0,0 @@
<?php
namespace Socialbox\Classes;
use PHPUnit\Framework\TestCase;
use Socialbox\Exceptions\CryptographyException;
class CryptographyTest extends TestCase
{
/**
* Testing `Cryptography::generateKeyPair` method
* @throws CryptographyException
*/
public function testGenerateKeyPair()
{
$keyPair = Cryptography::generateKeyPair();
$this->assertIsObject($keyPair);
$this->assertObjectHasProperty('publicKey', $keyPair);
$this->assertObjectHasProperty('privateKey', $keyPair);
$this->assertIsString($keyPair->getPublicKey());
$this->assertIsString($keyPair->getPrivateKey());
print_r($keyPair);
}
/**
* Testing `Cryptography::signContent` method
* @throws CryptographyException
*/
public function testSignContent()
{
$content = "My secret content";
$keyPair = Cryptography::generateKeyPair();
$signature = Cryptography::signContent($content, $keyPair->getPrivateKey());
$this->assertIsString($signature);
}
/**
* Testing `Cryptography::verifyContent` method
* @throws CryptographyException
*/
public function testVerifyContent()
{
$content = "My secret content";
$keyPair = Cryptography::generateKeyPair();
// Sign the content
$signature = Cryptography::signContent($content, $keyPair->getPrivateKey());
// Verify the content
$result = Cryptography::verifyContent($content, $signature, $keyPair->getPublicKey());
$this->assertTrue($result);
}
/**
* Testing `Cryptography::temporarySignature` method
* @throws CryptographyException
*/
public function testTemporarySignature()
{
$content = "Test Content";
$keyPair = Cryptography::generateKeyPair();
$tempSignature = Cryptography::temporarySignContent($content, $keyPair->getPrivateKey());
$this->assertIsString($tempSignature);
}
/**
* Testing `Cryptography::verifyTemporarySignature` method
* @throws CryptographyException
*/
public
function testVerifyTemporarySignature()
{
$content = "Test Content";
$keyPair = Cryptography::generateKeyPair();
$frames = 2;
// Generate a temporary signature
$tempSignature = Cryptography::temporarySignContent($content, $keyPair->getPrivateKey());
// Verify the temporary signature
$result = Cryptography::verifyTemporarySignature($content, $tempSignature, $keyPair->getPublicKey(), $frames);
$this->assertTrue($result);
}
/**
* Testing `Cryptography::encrypt` method
* @throws CryptographyException
*/
public function testEncrypt()
{
$content = "Test Content";
$keyPair = Cryptography::generateKeyPair();
// Encrypt the content
$encryptedContent = Cryptography::encryptContent($content, $keyPair->getPublicKey());
$this->assertIsString($encryptedContent);
}
/**
* Testing `Cryptography::decrypt` method
* @throws CryptographyException
*/
public function testDecrypt()
{
$content = "Test Content";
$keyPair = Cryptography::generateKeyPair();
// Encrypt the content
$encryptedContent = Cryptography::encryptContent($content, $keyPair->getPublicKey());
// Decrypt the content
$decryptedContent = Cryptography::decryptContent($encryptedContent, $keyPair->getPrivateKey());
$this->assertIsString($decryptedContent);
$this->assertEquals($content, $decryptedContent);
}
public function testEncryptFromFile()
{
$file_path = __DIR__ . DIRECTORY_SEPARATOR . 'server_public.der';
$content = "Test Content";
$encryptedContent = Cryptography::encryptContent($content, file_get_contents($file_path));
$this->assertIsString($encryptedContent);
$this->assertNotEquals($content, $encryptedContent);
print_r($encryptedContent);
}
public function testDecryptFromFile()
{
$private_key_file = __DIR__ . DIRECTORY_SEPARATOR . 'server_private.der';
$content = file_get_contents(__DIR__ . DIRECTORY_SEPARATOR . 'server_secret.txt');
try
{
$decryptedContent = Cryptography::decryptContent($content, file_get_contents($private_key_file));
}
catch(CryptographyException $e)
{
$this->fail($e->getMessage());
}
$this->assertIsString($decryptedContent);
$this->assertEquals($decryptedContent, 'Test Content');
}
/**
* Testing `Cryptography::validatePublicKey` method
*/
public function testValidatePublicKey()
{
$keyPair = Cryptography::generateKeyPair();
$result = Cryptography::validatePublicKey($keyPair->getPublicKey());
$this->assertTrue($result);
$resultWithInValidKey = Cryptography::validatePublicKey('invalidKey');
$this->assertFalse($resultWithInValidKey);
}
public function testValidateInvalidPublicKey()
{
$result = Cryptography::validatePublicKey('Bogus Key');
$this->assertFalse($result);
$result = Cryptography::validatePublicKey(Utilities::base64encode('Bogus Key'));
$this->assertFalse($result);
}
public function testValidatePrivateKey()
{
$keyPair = Cryptography::generateKeyPair();
$result = Cryptography::validatePrivateKey($keyPair->getPrivateKey());
$this->assertTrue($result);
$resultWithInValidKey = Cryptography::validatePublicKey('invalidKey');
$this->assertFalse($resultWithInValidKey);
}
public function testValidateInvalidPrivateKey()
{
$result = Cryptography::validatePublicKey('Bogus Key');
$this->assertFalse($result);
$result = Cryptography::validatePrivateKey(Utilities::base64encode('Bogus Key'));
$this->assertFalse($result);
}
public function testRequestSigning()
{
$client_private_der = __DIR__ . DIRECTORY_SEPARATOR . 'client_private.der';
$client_public_der = __DIR__ . DIRECTORY_SEPARATOR . 'client_public.der';
$content_file = __DIR__ . DIRECTORY_SEPARATOR . 'content.txt';
$hash = hash('sha1', file_get_contents($content_file));
$this->assertEquals('fa2415f0735a8aa151195688852178e8fd6e77c5', $hash);
$signature = Cryptography::signContent($hash, file_get_contents($client_private_der));
$this->assertEquals("Gcnijq7V8AYXgdk/eP9IswXN7831FevlBNDTKN60Ku7xesPDuPX8e55+38WFGCQ87DbeiIr+61XIDoN4+bTM4Wl0YSUe7oHV9BBnBqGhyZTntDPedUYUomrF3IRcpVRK0SbQSRaYucIp/ZsSHdbQgQBtDCvH5pK1+5g+VK9ZFT16Isvk0PhMjZiLkUYxUklFuzak7agWiS3wllFPqYSM6ri0RF+5I5JbnR9fUAOfhOceax//5H7d2WsdLj6DwtuY+eL5WyHxSmGA04YeQF3JgOGJ3WX2DSH8L0zA7pkGOjz5y1Nu6+0U6KRUXcezU/iM4zy5OJOnD5eJH4pYZizkiA==", $signature);
$result = Cryptography::verifyContent($hash, $signature, file_get_contents($client_public_der));
$this->assertTrue($result);
}
}

View file

@ -1,21 +0,0 @@
<?php
namespace Socialbox\Classes;
use PHPUnit\Framework\TestCase;
use Socialbox\Managers\EncryptionRecordsManager;
class SecuredPasswordTest extends TestCase
{
public function testVerifyPassword()
{
print("Getting random encryption record\n");
$encryptionRecord = EncryptionRecordsManager::getRandomRecord();
print("Securing password\n");
$securedPassword = SecuredPassword::securePassword('123-123-123', 'password!', $encryptionRecord);
print("Verifying password\n");
$this->assertTrue(SecuredPassword::verifyPassword('password!', $securedPassword, EncryptionRecordsManager::getAllRecords()));
}
}

View file

@ -1,21 +0,0 @@
<?php
namespace Socialbox\Classes;
use PHPUnit\Framework\TestCase;
use Socialbox\Exceptions\ResolutionException;
use Socialbox\Objects\ResolvedServer;
class ServerResolverTest extends TestCase
{
/**
* Test for the function resolveDomain of the class ServerResolver
*/
public function testResolveDomain(): void
{
// successful resolution
$resolvedServer = ServerResolver::resolveDomain('n64.cc');
self::assertNotEmpty($resolvedServer->getEndpoint());
self::assertNotEmpty($resolvedServer->getPublicKey());
}
}

View file

@ -1 +0,0 @@
MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQDZb4K+28kKYe1CvHPWHJALJFS396HOFmBv+anpAVWMDGBUyAWbWEqxmTAV17cBHiICjDDCNFBpOZLWzIiUpdWKA0Jo+Vu9zgWSPUyGe/Lik4GFNZ38gfolfdKGnLNFnn4nFR/fsZQ7hg4wWDarJmhJ+ZSLShOz2uIb4LaKk2qy12c6Zepufgrbk9TwWZQiXkzqBWbrZDpw0pp50CzoIwEnYJ+a7vhb98jpeS+Jjnp5zWlFjv9RgzOQUOwwOK4We2gNAVeFC5BP9trklpTh1bJlit4CECH68fCGjgoTOU92UbgucgyA4O5FVPGQYPAMuiZMGFaqXE2E7z1XwYIMAL4VAgMBAAECggEAAKiJz3CYuO+gGnL+F7qjaSXCUE8VvPfoCwuNYHNEFXo9DJBmnL7EU2WrYG+wARCP7O7qd0dEidx9u36ytjyCcKT4nYni8lM1zU7rVvbnLbsuRZS/4RO/RaYfPxig94fDfSeJ2ma0i7G56onj+MBbyTZarZ7Bf8hpcmKg9pkNEcEVcklNIwwbXKBOGq75Vka/+W56JZKJD3G9YmfrAO5RGF1prh93MRXlxlN/91k/m2pqkN9xYofepn0ePmI8Ci18jrMpJbmeu8BkypzgvC/5EfHipn7y/yJ215o/EtB575muz2zngRXe+GVO5lB5d5PuEwmXoaV5o3BqkIcb3aiz4QKBgQD7P1AE2/3oATNUF1FwlXzvdCS7M2BB28jQWjzJvHus1d1+qA2StWPgCPG2D/YTtHPI3xefBnAmeSIFCFEub0YLONbRvtQAZdTt5SAaZuUyMprqD1sCUHCizyVO0wHxo3DS0sIFmo/Lpc+j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kCtbW05aE2NwarRIm/RK2b45WgduhmW1d9pDbD58B1wIDAQAB

View file

@ -1 +0,0 @@
HHxV3e+igdTJIaBOT4340WBcJjBgjUPoP2SifAq0xuS1EjnTCWXeg6jr1pUX9HkUlMwTrZNFwye6gUIowGqsc1QrC4PReoZfBmTGR3dWXWvW01KHXbTodlnRjUFcHBUzNPpMDsE6d2J5+Mb+HGAsxXR9i4eN2jRGfO5YZ1It40vS4PCdbCtdQJ21bwnNnvHWq9+tMJRTnJ1M+niFjil9MKgS0fCLpwpG+fumnh0iRlS7wyN+y12IDSalvGEAJaX7iSN/tcWfLaQMXjIbYEsi9RMEXUibZWYQV7pkllqM5wqZpmNv52GeUPEbowtdnczA1IpsSyaj5MV4Q8DNqCoaXg==

View file

@ -1,78 +0,0 @@
<?php
namespace Socialbox\Managers;
use PHPUnit\Framework\TestCase;
use Socialbox\Enums\Flags\PeerFlags;
class RegisteredPeerManagerTest extends TestCase
{
private static $peerUuid;
public static function setUpBeforeClass(): void
{
if(RegisteredPeerManager::usernameExists('test_peer'))
{
RegisteredPeerManager::deletePeer(RegisteredPeerManager::getPeerByUsername('test_peer')->getUuid());
}
self::$peerUuid = RegisteredPeerManager::createPeer('test_peer', true);
}
public static function tearDownAfterClass(): void
{
if(RegisteredPeerManager::usernameExists('test_peer'))
{
RegisteredPeerManager::deletePeer(RegisteredPeerManager::getPeerByUsername('test_peer')->getUuid());
}
}
public function testEnablePeer()
{
RegisteredPeerManager::enablePeer(self::$peerUuid);
$peer = RegisteredPeerManager::getPeer(self::$peerUuid);
$this->assertTrue($peer->isEnabled());
}
public function testGetPeer()
{
$peer = RegisteredPeerManager::getPeer(self::$peerUuid);
$this->assertEquals('test_peer', $peer->getUsername());
}
public function testGetPeerByUsername()
{
$peer = RegisteredPeerManager::getPeerByUsername('test_peer');
$this->assertEquals(self::$peerUuid, $peer->getUuid());
}
public function testUsernameExists()
{
$this->assertTrue(RegisteredPeerManager::usernameExists('test_peer'));
}
public function testDisablePeer()
{
RegisteredPeerManager::disablePeer(self::$peerUuid);
$peer = RegisteredPeerManager::getPeer(self::$peerUuid);
$this->assertFalse($peer->isEnabled());
}
public function testRemoveFlag()
{
RegisteredPeerManager::addFlag(self::$peerUuid, PeerFlags::ADMIN);
$peer = RegisteredPeerManager::getPeer(self::$peerUuid);
$this->assertTrue($peer->flagExists(PeerFlags::ADMIN));
RegisteredPeerManager::removeFlag(self::$peerUuid, PeerFlags::ADMIN);
$peer = RegisteredPeerManager::getPeer(self::$peerUuid);
$this->assertFalse($peer->flagExists(PeerFlags::ADMIN));
}
}

View file

@ -1,43 +0,0 @@
<?php
namespace Socialbox\Managers;
use DateTime;
use ncc\Utilities\Resolver;
use PHPUnit\Framework\TestCase;
use Socialbox\Classes\ServerResolver;
class ResolvedServersManagerTest extends TestCase
{
public function setUp(): void
{
if(ResolvedServersManager::resolvedServerExists('n64.cc'))
{
ResolvedServersManager::deleteResolvedServer('n64.cc');
}
}
public function testGetResolvedServerUpdated()
{
ResolvedServersManager::addResolvedServer('n64.cc', ServerResolver::resolveDomain('n64.cc'));
$this->assertInstanceOf(DateTime::class, ResolvedServersManager::getResolvedServerUpdated('n64.cc'));
}
public function testResolvedServerExists()
{
ResolvedServersManager::addResolvedServer('n64.cc', ServerResolver::resolveDomain('n64.cc'));
$this->assertTrue(ResolvedServersManager::resolvedServerExists('n64.cc'));
}
public function testGetResolvedServer()
{
ResolvedServersManager::addResolvedServer('n64.cc', ServerResolver::resolveDomain('n64.cc'));
$resolvedServer = ResolvedServersManager::getResolvedServer('n64.cc');
$this->assertEquals('n64.cc', $resolvedServer->getDomain());
$this->assertIsString($resolvedServer->getEndpoint());
$this->assertIsString($resolvedServer->getPublicKey());
$this->assertInstanceOf(DateTime::class, $resolvedServer->getUpdated());
}
}

View file

@ -1,40 +0,0 @@
<?php
namespace Socialbox\Managers;
use InvalidArgumentException;
use PHPUnit\Framework\TestCase;
use Socialbox\Classes\Cryptography;
use Socialbox\Classes\Utilities;
use Socialbox\Objects\Database\SessionRecord;
class SessionManagerTest extends TestCase
{
public function testCreateSessionWithEmptyPublicKey(): void
{
$publicKey = '';
$this->expectException(InvalidArgumentException::class);
SessionManager::createSession($publicKey);
}
public function testCreateSession(): void
{
$keyPair = Cryptography::generateKeyPair();
$uuid = SessionManager::createSession($keyPair->getPublicKey());
$this->assertTrue(SessionManager::sessionExists($uuid));
}
public function testGetSessionWithValidUuid(): void
{
$keyPair = Cryptography::generateKeyPair();
$uuid = SessionManager::createSession($keyPair->getPublicKey());
$session = SessionManager::getSession($uuid);
$this->assertInstanceOf(SessionRecord::class, $session);
$this->assertEquals($uuid, $session->getUuid());
$this->assertEquals($keyPair->getPublicKey(), $session->getPublicKey());
}
}

View file

@ -1,34 +0,0 @@
<?php
namespace Socialbox\Managers;
use PDOException;
use PHPUnit\Framework\TestCase;
use Socialbox\Abstracts\CacheLayer;
use Socialbox\Exceptions\DatabaseOperationException;
use Socialbox\Managers\VariableManager;
class VariableManagerTest extends TestCase
{
/**
* Test the setter method for a variable in the VariableManager class.
*
*/
public function testSetVariable(): void
{
CacheLayer::getInstance()->clear();
VariableManager::deleteVariable('test_name');
VariableManager::setVariable('test_name', 'test_value');
$this->assertTrue(VariableManager::variableExists('test_name'));
$this->assertEquals('test_value', VariableManager::getVariable('test_name'));
VariableManager::deleteVariable('test_name');
VariableManager::deleteVariable('test_name2');
VariableManager::setVariable('test_name2', 'test_value2');
$this->assertTrue(VariableManager::variableExists('test_name2'));
$this->assertEquals('test_value2', VariableManager::getVariable('test_name2'));
VariableManager::deleteVariable('test_name2');
}
}

View file

@ -1,17 +0,0 @@
<?php
namespace Socialbox\Other;
use Gregwar\Captcha\CaptchaBuilder;
use PHPUnit\Framework\TestCase;
class CaptchaTest extends TestCase
{
public function testCaptchaRendering()
{
$builder = new CaptchaBuilder("Foo Bar");
$builder->build();
$builder->save(__DIR__ . DIRECTORY_SEPARATOR . 'test.png');
}
}