Remove unused StandardMethods and improve session logic

This commit is contained in:
netkas 2024-12-12 04:33:10 -05:00
parent 86435a3d0b
commit 701acfde35
30 changed files with 1032 additions and 704 deletions

View file

@ -35,7 +35,7 @@ class Configuration
$config->setDefault('instance.domain', null);
$config->setDefault('instance.rpc_endpoint', null);
$config->setDefault('instance.encryption_keys_count', 5);
$config->setDefault('instance.encryption_record_count', 5);
$config->setDefault('instance.encryption_records_count', 5);
$config->setDefault('instance.private_key', null);
$config->setDefault('instance.public_key', null);
$config->setDefault('instance.encryption_keys', null);

View file

@ -16,6 +16,7 @@ class Cryptography
private const int PADDING = OPENSSL_PKCS1_OAEP_PADDING;
private const string PEM_PRIVATE_HEADER = 'PRIVATE';
private const string PEM_PUBLIC_HEADER = 'PUBLIC';
private const string TRANSPORT_ENCRYPTION = 'aes-256-cbc';
/**
* Generates a new public-private key pair.
@ -307,4 +308,74 @@ class Cryptography
return $keys;
}
public static function generateEncryptionKey(): string
{
try
{
return base64_encode(random_bytes(32));
}
catch (RandomException $e)
{
throw new CryptographyException('Failed to generate encryption key: ' . $e->getMessage());
}
}
/**
* Encrypts the given content for transport using the provided encryption key.
*
* @param string $content The content to be encrypted.
* @param string $encryptionKey The encryption key used for encrypting the content.
* @return string The Base64 encoded string containing the IV and the encrypted content.
* @throws CryptographyException If the IV generation or encryption process fails.
*/
public static function encryptTransport(string $content, string $encryptionKey): string
{
try
{
$iv = random_bytes(openssl_cipher_iv_length('aes-256-cbc'));
}
catch (RandomException $e)
{
throw new CryptographyException('Failed to generate IV: ' . $e->getMessage());
}
$encrypted = openssl_encrypt($content, self::TRANSPORT_ENCRYPTION, base64_decode($encryptionKey), OPENSSL_RAW_DATA, $iv);
if($encrypted === false)
{
throw new CryptographyException('Failed to encrypt transport content: ' . openssl_error_string());
}
return base64_encode($iv . $encrypted);
}
/**
* Decrypts the given encrypted transport content using the provided encryption key.
*
* @param string $encryptedContent The Base64 encoded encrypted content to be decrypted.
* @param string $encryptionKey The Base64 encoded encryption key used for decryption.
* @return string The decrypted content as a string.
* @throws CryptographyException If the decryption process fails.
*/
public static function decryptTransport(string $encryptedContent, string $encryptionKey): string
{
$decodedData = base64_decode($encryptedContent);
$ivLength = openssl_cipher_iv_length(self::TRANSPORT_ENCRYPTION);
// Perform decryption
$decryption = openssl_decrypt(substr($decodedData, $ivLength),
self::TRANSPORT_ENCRYPTION,
base64_decode($encryptionKey),
OPENSSL_RAW_DATA,
substr($decodedData, 0, $ivLength)
);
if($decryption === false)
{
throw new CryptographyException('Failed to decrypt transport content: ' . openssl_error_string());
}
return $decryption;
}
}

View file

@ -7,10 +7,11 @@ use InvalidArgumentException;
use RuntimeException;
use Socialbox\Enums\StandardHeaders;
use Socialbox\Exceptions\DatabaseOperationException;
use Socialbox\Exceptions\RequestException;
use Socialbox\Exceptions\RpcException;
use Socialbox\Exceptions\StandardException;
use Socialbox\Managers\SessionManager;
use Socialbox\Objects\ClientRequest;
use Socialbox\Objects\ClientRequestOld;
use Socialbox\Objects\RpcRequest;
class RpcHandler
@ -19,16 +20,12 @@ class RpcHandler
* Gets the incoming ClientRequest object, validates if the request is valid & if a session UUID is provided
* checks if the request signature matches the client's provided public key.
*
* @return ClientRequest The parsed ClientRequest object
* @return ClientRequestOld The parsed ClientRequest object
* @throws RequestException
* @throws RpcException Thrown if the request is invalid
*/
public static function getClientRequest(): ClientRequest
public static function getClientRequest(): ClientRequestOld
{
if($_SERVER['REQUEST_METHOD'] !== 'POST')
{
throw new RpcException('Invalid Request Method, expected POST', 400);
}
try
{
$headers = Utilities::getRequestHeaders();
@ -36,7 +33,7 @@ class RpcHandler
{
if (!isset($headers[$header]))
{
throw new RpcException("Missing required header: $header", 400);
throw new RequestException("Missing required header: $header", 400);
}
// Validate the headers
@ -73,7 +70,7 @@ class RpcHandler
throw new RpcException("Failed to parse request: " . $e->getMessage(), 400, $e);
}
$clientRequest = new ClientRequest($headers, self::getRpcRequests(), self::getRequestHash());
$clientRequest = new ClientRequestOld($headers, self::getRpcRequests(), self::getRequestHash());
// Verify the session & request signature
if($clientRequest->getSessionUuid() !== null)

View file

@ -1,50 +0,0 @@
<?php
namespace Socialbox\Classes\StandardMethods;
use Socialbox\Abstracts\Method;
use Socialbox\Enums\FirstLevelAuthentication;
use Socialbox\Enums\StandardError;
use Socialbox\Interfaces\SerializableInterface;
use Socialbox\Objects\ClientRequest;
use Socialbox\Objects\RpcRequest;
use Socialbox\Objects\RpcResponse;
class Authenticate extends Method
{
/**
* @inheritDoc
*/
public static function execute(ClientRequest $request, RpcRequest $rpcRequest): ?SerializableInterface
{
if(!isset($rpcRequest->getParameters()['type']))
{
return $rpcRequest->produceError(StandardError::RPC_INVALID_ARGUMENTS, 'Missing required parameter \'type\'');
}
if(strlen($rpcRequest->getParameters()['type']) == 0)
{
return $rpcRequest->produceError(StandardError::RPC_INVALID_ARGUMENTS, 'Parameter \'type\' cannot be empty');
}
return match (FirstLevelAuthentication::tryFrom($rpcRequest->getParameters()['type']))
{
FirstLevelAuthentication::PASSWORD => self::handlePassword($request),
default => $rpcRequest->produceError(StandardError::UNSUPPORTED_AUTHENTICATION_TYPE,
sprintf('Unsupported authentication type: %s', $rpcRequest->getParameters()['type'])
),
};
}
/**
* Handles the password authentication phase for the peer
*
* @param ClientRequest $request
* @return SerializableInterface
*/
private static function handlePassword(ClientRequest $request): SerializableInterface
{
}
}

View file

@ -1,45 +0,0 @@
<?php
namespace Socialbox\Classes\StandardMethods;
use InvalidArgumentException;
use Socialbox\Abstracts\Method;
use Socialbox\Enums\StandardError;
use Socialbox\Exceptions\DatabaseOperationException;
use Socialbox\Interfaces\SerializableInterface;
use Socialbox\Managers\SessionManager;
use Socialbox\Objects\ClientRequest;
use Socialbox\Objects\RpcRequest;
class CreateSession extends Method
{
/**
* Executes the session creation process based on the provided public key.
*
* @param ClientRequest $request The client request object.
* @param RpcRequest $rpcRequest The RPC request containing parameters for execution.
* @return SerializableInterface|null Returns a response with the session UUID or an error.
*/
public static function execute(ClientRequest $request, RpcRequest $rpcRequest): ?SerializableInterface
{
if(!$rpcRequest->containsParameter('public_key'))
{
return $rpcRequest->produceError(StandardError::RPC_INVALID_ARGUMENTS, 'Missing parameter \'public_key\'');
}
try
{
$uuid = SessionManager::createSession($rpcRequest->getParameter('public_key'));
}
catch(DatabaseOperationException $e)
{
return $rpcRequest->produceError(StandardError::INTERNAL_SERVER_ERROR, 'There was an error while trying to create a new session: ' . $e->getMessage());
}
catch(InvalidArgumentException $e)
{
return $rpcRequest->produceError(StandardError::RPC_INVALID_ARGUMENTS, $e->getMessage());
}
return $rpcRequest->produceResponse($uuid);
}
}

View file

@ -1,47 +0,0 @@
<?php
namespace Socialbox\Classes\StandardMethods;
use Socialbox\Abstracts\Method;
use Socialbox\Classes\Logger;
use Socialbox\Enums\StandardError;
use Socialbox\Exceptions\DatabaseOperationException;
use Socialbox\Exceptions\StandardException;
use Socialbox\Interfaces\SerializableInterface;
use Socialbox\Managers\RegisteredPeerManager;
use Socialbox\Managers\SessionManager;
use Socialbox\Objects\ClientRequest;
use Socialbox\Objects\RpcRequest;
class GetMe extends Method
{
/**
* @inheritDoc
*/
public static function execute(ClientRequest $request, RpcRequest $rpcRequest): ?SerializableInterface
{
// Check if the request has a Session UUID
if($request->getSessionUuid() === null)
{
return $rpcRequest->produceError(StandardError::SESSION_REQUIRED);
}
try
{
// Get the session and check if it's already authenticated
$session = SessionManager::getSession($request->getSessionUuid());
if($session->getPeerUuid() === null)
{
return $rpcRequest->produceError(StandardError::AUTHENTICATION_REQUIRED);
}
// Get the peer and return it
return $rpcRequest->produceResponse(RegisteredPeerManager::getPeer($session->getPeerUuid())->toSelfUser());
}
catch(DatabaseOperationException $e)
{
throw new StandardException("There was an unexpected error while trying to register", StandardError::INTERNAL_SERVER_ERROR, $e);
}
}
}

View file

@ -1,40 +0,0 @@
<?php
namespace Socialbox\Classes\StandardMethods;
use Socialbox\Abstracts\Method;
use Socialbox\Enums\StandardError;
use Socialbox\Exceptions\DatabaseOperationException;
use Socialbox\Exceptions\StandardException;
use Socialbox\Interfaces\SerializableInterface;
use Socialbox\Managers\RegisteredPeerManager;
use Socialbox\Managers\SessionManager;
use Socialbox\Objects\ClientRequest;
use Socialbox\Objects\RpcRequest;
class GetSession extends Method
{
/**
* @inheritDoc
*/
public static function execute(ClientRequest $request, RpcRequest $rpcRequest): ?SerializableInterface
{
if($request->getSessionUuid() === null)
{
return $rpcRequest->produceError(StandardError::SESSION_REQUIRED);
}
try
{
// Get the session
$session = SessionManager::getSession($request->getSessionUuid());
}
catch(DatabaseOperationException $e)
{
throw new StandardException("There was an unexpected error while trying to retrieve the session", StandardError::INTERNAL_SERVER_ERROR, $e);
}
}
}

View file

@ -1,73 +0,0 @@
<?php
namespace Socialbox\Classes\StandardMethods;
use Socialbox\Abstracts\Method;
use Socialbox\Classes\Configuration;
use Socialbox\Classes\Validator;
use Socialbox\Enums\StandardError;
use Socialbox\Exceptions\DatabaseOperationException;
use Socialbox\Exceptions\StandardException;
use Socialbox\Interfaces\SerializableInterface;
use Socialbox\Managers\RegisteredPeerManager;
use Socialbox\Managers\SessionManager;
use Socialbox\Objects\ClientRequest;
use Socialbox\Objects\RpcRequest;
class Identify extends Method
{
/**
* @inheritDoc
*/
public static function execute(ClientRequest $request, RpcRequest $rpcRequest): ?SerializableInterface
{
// Check if the username parameter exists
if(!$rpcRequest->containsParameter('username'))
{
return $rpcRequest->produceError(StandardError::RPC_INVALID_ARGUMENTS, 'Missing parameter \'username\'');
}
// Check if the username is valid
if(!Validator::validateUsername($rpcRequest->getParameter('username')))
{
return $rpcRequest->produceError(StandardError::INVALID_USERNAME, StandardError::INVALID_USERNAME->getMessage());
}
// Check if the request has a Session UUID
if($request->getSessionUuid() === null)
{
return $rpcRequest->produceError(StandardError::SESSION_REQUIRED);
}
try
{
// Get the session and check if it's already authenticated
$session = SessionManager::getSession($request->getSessionUuid());
// If the session is already authenticated, return an error
if($session->getPeerUuid() !== null)
{
return $rpcRequest->produceError(StandardError::ALREADY_AUTHENTICATED);
}
// If the username does not exist, return an error
if(!RegisteredPeerManager::usernameExists($rpcRequest->getParameter('username')))
{
return $rpcRequest->produceError(StandardError::NOT_REGISTERED, StandardError::NOT_REGISTERED->getMessage());
}
// Create session to be identified as the provided username
SessionManager::updatePeer($session->getUuid(), $rpcRequest->getParameter('username'));
// Set the required session flags
$initialFlags = [];
}
catch(DatabaseOperationException $e)
{
throw new StandardException("There was an unexpected error while trying to register", StandardError::INTERNAL_SERVER_ERROR, $e);
}
// Return true to indicate the operation was a success
return $rpcRequest->produceResponse(true);
}
}

View file

@ -1,19 +1,20 @@
<?php
namespace Socialbox\Classes\StandardMethods;
namespace Socialbox\Classes\StandardMethods;
use Socialbox\Abstracts\Method;
use Socialbox\Interfaces\SerializableInterface;
use Socialbox\Objects\ClientRequest;
use Socialbox\Objects\RpcRequest;
use Socialbox\Abstracts\Method;
use Socialbox\Interfaces\SerializableInterface;
use Socialbox\Objects\ClientRequest;
use Socialbox\Objects\ClientRequestOld;
use Socialbox\Objects\RpcRequest;
class Ping extends Method
{
/**
* @inheritDoc
*/
public static function execute(ClientRequest $request, RpcRequest $rpcRequest): ?SerializableInterface
class Ping extends Method
{
return $rpcRequest->produceResponse(true);
}
}
/**
* @inheritDoc
*/
public static function execute(ClientRequest $request, RpcRequest $rpcRequest): ?SerializableInterface
{
return $rpcRequest->produceResponse(true);
}
}

View file

@ -1,80 +0,0 @@
<?php
namespace Socialbox\Classes\StandardMethods;
use Socialbox\Abstracts\Method;
use Socialbox\Classes\Configuration;
use Socialbox\Classes\Validator;
use Socialbox\Enums\StandardError;
use Socialbox\Exceptions\DatabaseOperationException;
use Socialbox\Exceptions\StandardException;
use Socialbox\Interfaces\SerializableInterface;
use Socialbox\Managers\RegisteredPeerManager;
use Socialbox\Managers\SessionManager;
use Socialbox\Objects\ClientRequest;
use Socialbox\Objects\RpcRequest;
class Register extends Method
{
/**
* @inheritDoc
*/
public static function execute(ClientRequest $request, RpcRequest $rpcRequest): ?SerializableInterface
{
if(!Configuration::getRegistrationConfiguration()->isRegistrationEnabled())
{
return $rpcRequest->produceError(StandardError::REGISTRATION_DISABLED, StandardError::REGISTRATION_DISABLED->getMessage());
}
// Check if the username parameter exists
if(!$rpcRequest->containsParameter('username'))
{
return $rpcRequest->produceError(StandardError::RPC_INVALID_ARGUMENTS, 'Missing parameter \'username\'');
}
// Check if the username is valid
if(!Validator::validateUsername($rpcRequest->getParameter('username')))
{
return $rpcRequest->produceError(StandardError::INVALID_USERNAME, StandardError::INVALID_USERNAME->getMessage());
}
// Check if the username exists already
try
{
if (RegisteredPeerManager::usernameExists($rpcRequest->getParameter('username')))
{
return $rpcRequest->produceError(StandardError::USERNAME_ALREADY_EXISTS, StandardError::USERNAME_ALREADY_EXISTS->getMessage());
}
}
catch (DatabaseOperationException $e)
{
throw new StandardException("There was an unexpected error while trying to check the username existence", StandardError::INTERNAL_SERVER_ERROR, $e);
}
// Check if the request has a Session UUID
if($request->getSessionUuid() === null)
{
return $rpcRequest->produceError(StandardError::SESSION_REQUIRED);
}
try
{
// Get the session and check if it's already authenticated
$session = SessionManager::getSession($request->getSessionUuid());
if($session->getPeerUuid() !== null)
{
return $rpcRequest->produceError(StandardError::ALREADY_AUTHENTICATED);
}
// Create the peer & set the current's session authenticated peer as the newly created peer
SessionManager::updatePeer($session->getUuid(), RegisteredPeerManager::createPeer($rpcRequest->getParameter('username')));
}
catch(DatabaseOperationException $e)
{
throw new StandardException("There was an unexpected error while trying to register", StandardError::INTERNAL_SERVER_ERROR, $e);
}
// Return true to indicate the operation was a success
return $rpcRequest->produceResponse(true);
}
}

View file

@ -11,7 +11,7 @@ use Socialbox\Interfaces\SerializableInterface;
use Socialbox\Managers\CaptchaManager;
use Socialbox\Managers\RegisteredPeerManager;
use Socialbox\Managers\SessionManager;
use Socialbox\Objects\ClientRequest;
use Socialbox\Objects\ClientRequestOld;
use Socialbox\Objects\RpcRequest;
class VerificationAnswerImageCaptcha extends Method
@ -20,7 +20,7 @@ class VerificationAnswerImageCaptcha extends Method
/**
* @inheritDoc
*/
public static function execute(ClientRequest $request, RpcRequest $rpcRequest): ?SerializableInterface
public static function execute(ClientRequestOld $request, RpcRequest $rpcRequest): ?SerializableInterface
{
// Check if the request has a Session UUID
if($request->getSessionUuid() === null)

View file

@ -13,7 +13,7 @@ use Socialbox\Interfaces\SerializableInterface;
use Socialbox\Managers\CaptchaManager;
use Socialbox\Managers\RegisteredPeerManager;
use Socialbox\Managers\SessionManager;
use Socialbox\Objects\ClientRequest;
use Socialbox\Objects\ClientRequestOld;
use Socialbox\Objects\RpcRequest;
use Socialbox\Objects\Standard\ImageCaptcha;
@ -22,7 +22,7 @@ class VerificationGetImageCaptcha extends Method
/**
* @inheritDoc
*/
public static function execute(ClientRequest $request, RpcRequest $rpcRequest): ?SerializableInterface
public static function execute(ClientRequestOld $request, RpcRequest $rpcRequest): ?SerializableInterface
{
// Check if the request has a Session UUID
if($request->getSessionUuid() === null)

View file

@ -7,6 +7,7 @@ use InvalidArgumentException;
use JsonException;
use RuntimeException;
use Socialbox\Enums\StandardHeaders;
use Socialbox\Objects\PeerAddress;
use Throwable;
class Utilities