Enhance authentication handling in FederationServer and GetOperator classes to support optional authentication requirement and improved permission checks

This commit is contained in:
netkas 2025-06-03 17:06:41 -04:00
parent 235a404351
commit 005bf2e1f8
Signed by: netkas
GPG key ID: 4D8629441B76E4CC
3 changed files with 22 additions and 15 deletions

View file

@ -196,16 +196,16 @@
* This method retrieves the API key from the request headers or query parameters,
* validates it, and returns the corresponding OperatorRecord object if found and enabled.
*
* @return OperatorRecord Returns the authenticated OperatorRecord object or null if not found or disabled.
* @return OperatorRecord|null Returns the authenticated OperatorRecord object or null if not found or disabled.
* @throws RequestException If the API key is missing, invalid, or the operator is disabled.
*/
protected static function getAuthenticatedOperator(): OperatorRecord
protected static function getAuthenticatedOperator(): ?OperatorRecord
{
// First obtain the API key from the request headers or query parameters.
$apiKey = $_SERVER['HTTP_API_KEY'] ?? $_GET['api_key'] ?? null;
$apiKey = $_SERVER['HTTP_API_KEY'] ?? $_GET['api_key'] ?? $_POST['api_key'] ?? null;
if (empty($apiKey))
{
throw new RequestException('API key is required', 401);
return null;
}
if(strlen($apiKey) > 32)

View file

@ -119,8 +119,14 @@
/**
* @inheritDoc
*/
public static function getAuthenticatedOperator(): OperatorRecord
public static function getAuthenticatedOperator(bool $requireAuthentication=true): ?OperatorRecord
{
return parent::getAuthenticatedOperator();
$authenticatedOperator = parent::getAuthenticatedOperator();
if($requireAuthentication && $authenticatedOperator === null)
{
throw new RequestException('Unauthorized: No authenticated operator found', 401);
}
return $authenticatedOperator;
}
}

View file

@ -17,13 +17,7 @@
*/
public static function handleRequest(): void
{
$authenticatedOperator = FederationServer::getAuthenticatedOperator();
// Ensure the authenticated operator has permission to delete operators.
if(!$authenticatedOperator->canManageOperators())
{
throw new RequestException('Unauthorized: Insufficient permissions to get operators', 403);
}
$authenticatedOperator = FederationServer::getAuthenticatedOperator(false);
if(!preg_match('#^/operators/([a-fA-F0-9\-]{36,})$#', FederationServer::getPath(), $matches))
{
@ -50,7 +44,14 @@
throw new RequestException('Internal Server Error: Unable to get operator', 500, $e);
}
// Respond with the UUID of the newly created operator.
self::successResponse($existingOperator->toArray());
if($authenticatedOperator?->canManageOperators())
{
// If the authenticated operator can manage operators, return the full record
self::successResponse($existingOperator->toArray());
return;
}
// Respond with public record if the authenticated operator cannot manage operators
self::successResponse($existingOperator->toPublicRecord()->toArray());
}
}