diff --git a/appinfo/routes.php b/appinfo/routes.php index 2d4b7144..e8d68f75 100644 --- a/appinfo/routes.php +++ b/appinfo/routes.php @@ -66,6 +66,7 @@ 'ocs' => [ // Logging ['name' => 'OCSApi#log', 'url' => '/api/v1/log', 'verb' => 'POST'], + ['name' => 'OCSApi#auditLog', 'url' => '/api/v1/audit_log', 'verb' => 'POST'], ['name' => 'OCSApi#getNCUsersList', 'url' => '/api/v1/users', 'verb' => 'GET'], ['name' => 'OCSApi#setAppInitProgressDeprecated', 'url' => '/apps/status/{appId}', 'verb' => 'PUT'], diff --git a/lib/AuditLog/AuditLogger.php b/lib/AuditLog/AuditLogger.php index c20e6ba4..e2a6a941 100644 --- a/lib/AuditLog/AuditLogger.php +++ b/lib/AuditLog/AuditLogger.php @@ -9,6 +9,7 @@ namespace OCA\AppAPI\AuditLog; +use InvalidArgumentException; use OCP\EventDispatcher\IEventDispatcher; use OCP\Log\Audit\CriticalActionPerformedEvent; @@ -26,9 +27,55 @@ public function __construct( * @param array $parameters named values for the placeholders of $message, in order, optionally followed by more context */ public function log(Operation $operation, string $message, array $parameters = []): void { - // The logger replaces `{placeholders}` in the message and admin_audit formats it again, so values are escaped here - $values = array_map(static fn (mixed $value): mixed => is_string($value) ? strtr($value, ['{' => '(', '}' => ')']) : $value, array_values($parameters)); - $message = str_replace('%', '%%', vsprintf($message, $values)); - $this->eventDispatcher->dispatchTyped(new CriticalActionPerformedEvent($message, $parameters, false, $operation->value)); + $this->dispatch($operation->value, $message, $parameters); + } + + /** + * Writes an entry on behalf of an ExApp, whose ID is added as the `appId` parameter + * + * @param string $operation operation in the form `.entity.action`, the first part being the ID of the ExApp + * @param string $message message with a `%s` placeholder for each of the first parameters; `%%` writes a `%`, other directives are rejected + * @param array $parameters named values for the placeholders of $message, in order, optionally followed by more context + * @throws InvalidArgumentException if the app ID is empty, the operation does not start with the app ID or is not in the form `.entity.action`, a parameter is not a scalar or null, or the message has a directive other than `%s` and `%%` or more placeholders than parameters + */ + public function logForExApp(string $appId, string $operation, string $message, array $parameters = []): void { + if ($appId === '') { + throw new InvalidArgumentException('App ID must not be empty'); + } + if (!str_starts_with($operation, $appId . '.')) { + throw new InvalidArgumentException(sprintf('Operation must be in the form %s.entity.action', $appId)); + } + if (array_key_exists('appId', $parameters)) { + throw new InvalidArgumentException('Parameter appId is reserved'); + } + foreach ($parameters as $name => $value) { + if (!is_string($name) || ($value !== null && !is_scalar($value))) { + throw new InvalidArgumentException('Parameters must be named and be scalars or null'); + } + } + // Directives like `%c` or `%1073741824s` would write braces past the escaping or exhaust the memory + $directives = str_replace('%%', '', $message); + if (preg_match('/%(?!s)/', $directives)) { + throw new InvalidArgumentException('Message must only contain %s and %% directives'); + } + // Counted before appId is added, which would otherwise fill a missing placeholder + if (substr_count($directives, '%s') > count($parameters)) { + throw new InvalidArgumentException('Message has more placeholders than parameters'); + } + $parameters['appId'] = $appId; + $this->dispatch($operation, $message, $parameters); + } + + private function dispatch(string $operation, string $message, array $parameters): void { + $message = self::escape(vsprintf($message, array_values($parameters))); + $this->eventDispatcher->dispatchTyped(new CriticalActionPerformedEvent($message, $parameters, false, $operation)); + } + + /** + * The logger replaces `{placeholders}` in the message, so braces become parentheses, and admin_audit + * formats the message again, so values are escaped here + */ + private static function escape(string $value): string { + return strtr($value, ['{' => '(', '}' => ')', '%' => '%%']); } } diff --git a/lib/Controller/OCSApiController.php b/lib/Controller/OCSApiController.php index 8659c3dd..fb0b3896 100644 --- a/lib/Controller/OCSApiController.php +++ b/lib/Controller/OCSApiController.php @@ -12,6 +12,7 @@ use OCA\AppAPI\AppInfo\Application; use OCA\AppAPI\Attribute\AppAPIAuth; use OCA\AppAPI\Attribute\MaintenanceModeAvailable; +use OCA\AppAPI\AuditLog\AuditLogger; use OCA\AppAPI\Service\AppAPIService; use OCA\AppAPI\Service\ExAppService; use OCP\AppFramework\Http; @@ -37,6 +38,7 @@ public function __construct( private IConfig $config, private readonly ExAppService $exAppService, private readonly IURLGenerator $urlGenerator, + private readonly AuditLogger $auditLogger, ) { parent::__construct(Application::APP_ID, $request); @@ -71,6 +73,32 @@ public function log(int $level, string $message): DataResponse { } } + /** + * Write an entry to the admin audit log on behalf of an ExApp + * + * The entry carries the ID of the ExApp as the `appId` parameter. + * + * @param string $operation Stable identifier of the action in the form `.entity.action`, starting with the ID of the ExApp, e.g. `my_app.item.created` + * @param string $message Message with a `%s` placeholder for each of the first parameters, in order + * @param array $parameters Named values for the placeholders of the message, optionally followed by more context + * + * @return DataResponse, array{}> + * @throws OCSBadRequestException Invalid operation, parameters or message + * + * 200: Entry written to the audit log + */ + #[AppAPIAuth] + #[PublicPage] + #[NoCSRFRequired] + public function auditLog(string $operation, string $message, array $parameters = []): DataResponse { + try { + $this->auditLogger->logForExApp($this->request->getHeader('ex-app-id'), $operation, $message, $parameters); + } catch (\InvalidArgumentException $e) { + throw new OCSBadRequestException($e->getMessage()); + } + return new DataResponse(); + } + /** * Get a list of all Nextcloud user IDs * diff --git a/openapi-full.json b/openapi-full.json index e18b1cfd..4f1eb409 100644 --- a/openapi-full.json +++ b/openapi-full.json @@ -4470,6 +4470,150 @@ } } }, + "/ocs/v2.php/apps/app_api/api/v1/audit_log": { + "post": { + "operationId": "ocs_api-audit-log", + "summary": "Write an entry to the admin audit log on behalf of an ExApp", + "description": "The entry carries the ID of the ExApp as the `appId` parameter.", + "tags": [ + "ocs_api" + ], + "security": [ + {}, + { + "bearer_auth": [] + }, + { + "basic_auth": [] + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "required": [ + "operation", + "message" + ], + "properties": { + "operation": { + "type": "string", + "description": "Stable identifier of the action in the form `.entity.action`, starting with the ID of the ExApp, e.g. `my_app.item.created`" + }, + "message": { + "type": "string", + "description": "Message with a `%s` placeholder for each of the first parameters, in order" + }, + "parameters": { + "type": "object", + "default": {}, + "description": "Named values for the placeholders of the message, optionally followed by more context", + "additionalProperties": { + "nullable": true, + "anyOf": [ + { + "type": "string" + }, + { + "type": "integer", + "format": "int64" + }, + { + "type": "number", + "format": "double" + }, + { + "type": "boolean" + } + ] + } + } + } + } + } + } + }, + "parameters": [ + { + "name": "ex-app-id", + "in": "header", + "schema": { + "type": "string" + } + }, + { + "name": "OCS-APIRequest", + "in": "header", + "description": "Required to be true for the API request to pass", + "required": true, + "schema": { + "type": "boolean", + "default": true + } + } + ], + "responses": { + "200": { + "description": "Entry written to the audit log", + "content": { + "application/json": { + "schema": { + "type": "object", + "required": [ + "ocs" + ], + "properties": { + "ocs": { + "type": "object", + "required": [ + "meta", + "data" + ], + "properties": { + "meta": { + "$ref": "#/components/schemas/OCSMeta" + }, + "data": {} + } + } + } + } + } + } + }, + "400": { + "description": "Invalid operation, parameters or message", + "content": { + "application/json": { + "schema": { + "type": "object", + "required": [ + "ocs" + ], + "properties": { + "ocs": { + "type": "object", + "required": [ + "meta", + "data" + ], + "properties": { + "meta": { + "$ref": "#/components/schemas/OCSMeta" + }, + "data": {} + } + } + } + } + } + } + } + } + } + }, "/ocs/v2.php/apps/app_api/api/v1/users": { "get": { "operationId": "ocs_api-getnc-users-list", diff --git a/openapi.json b/openapi.json index 9f281206..3c334f97 100644 --- a/openapi.json +++ b/openapi.json @@ -621,6 +621,150 @@ } } }, + "/ocs/v2.php/apps/app_api/api/v1/audit_log": { + "post": { + "operationId": "ocs_api-audit-log", + "summary": "Write an entry to the admin audit log on behalf of an ExApp", + "description": "The entry carries the ID of the ExApp as the `appId` parameter.", + "tags": [ + "ocs_api" + ], + "security": [ + {}, + { + "bearer_auth": [] + }, + { + "basic_auth": [] + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "required": [ + "operation", + "message" + ], + "properties": { + "operation": { + "type": "string", + "description": "Stable identifier of the action in the form `.entity.action`, starting with the ID of the ExApp, e.g. `my_app.item.created`" + }, + "message": { + "type": "string", + "description": "Message with a `%s` placeholder for each of the first parameters, in order" + }, + "parameters": { + "type": "object", + "default": {}, + "description": "Named values for the placeholders of the message, optionally followed by more context", + "additionalProperties": { + "nullable": true, + "anyOf": [ + { + "type": "string" + }, + { + "type": "integer", + "format": "int64" + }, + { + "type": "number", + "format": "double" + }, + { + "type": "boolean" + } + ] + } + } + } + } + } + } + }, + "parameters": [ + { + "name": "ex-app-id", + "in": "header", + "schema": { + "type": "string" + } + }, + { + "name": "OCS-APIRequest", + "in": "header", + "description": "Required to be true for the API request to pass", + "required": true, + "schema": { + "type": "boolean", + "default": true + } + } + ], + "responses": { + "200": { + "description": "Entry written to the audit log", + "content": { + "application/json": { + "schema": { + "type": "object", + "required": [ + "ocs" + ], + "properties": { + "ocs": { + "type": "object", + "required": [ + "meta", + "data" + ], + "properties": { + "meta": { + "$ref": "#/components/schemas/OCSMeta" + }, + "data": {} + } + } + } + } + } + } + }, + "400": { + "description": "Invalid operation, parameters or message", + "content": { + "application/json": { + "schema": { + "type": "object", + "required": [ + "ocs" + ], + "properties": { + "ocs": { + "type": "object", + "required": [ + "meta", + "data" + ], + "properties": { + "meta": { + "$ref": "#/components/schemas/OCSMeta" + }, + "data": {} + } + } + } + } + } + } + } + } + } + }, "/ocs/v2.php/apps/app_api/api/v1/users": { "get": { "operationId": "ocs_api-getnc-users-list", diff --git a/tests/php/AuditLog/AuditLoggerTest.php b/tests/php/AuditLog/AuditLoggerTest.php index ef0b1820..8d77647a 100644 --- a/tests/php/AuditLog/AuditLoggerTest.php +++ b/tests/php/AuditLog/AuditLoggerTest.php @@ -13,6 +13,7 @@ use OCA\AppAPI\AuditLog\Operation; use OCP\EventDispatcher\IEventDispatcher; use OCP\Log\Audit\CriticalActionPerformedEvent; +use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\TestCase; class AuditLoggerTest extends TestCase { @@ -45,4 +46,58 @@ public function testLogKeepsValuesFromChangingTheEntry(): void { (new AuditLogger($eventDispatcher))->log(Operation::DaemonRegistered, 'Deploy daemon %s on %s was registered', $parameters); } + + public function testLogForExAppAddsTheAppId(): void { + $eventDispatcher = $this->createMock(IEventDispatcher::class); + $eventDispatcher->expects(self::once()) + ->method('dispatchTyped') + ->with(self::callback(static function (CriticalActionPerformedEvent $event): bool { + self::assertSame('Item (x) was created by 100%%s', $event->getLogMessage()); + self::assertSame(['item' => '{x}', 'user' => '100%s', 'appId' => 'test_app'], $event->getParameters()); + self::assertSame('test_app.item.created', $event->getOperation()); + return true; + })); + + (new AuditLogger($eventDispatcher))->logForExApp('test_app', 'test_app.item.created', 'Item %s was created by %s', ['item' => '{x}', 'user' => '100%s']); + } + + public function testLogForExAppKeepsTheMessageFromAddingPlaceholders(): void { + $eventDispatcher = $this->createMock(IEventDispatcher::class); + $eventDispatcher->expects(self::once()) + ->method('dispatchTyped') + ->with(self::callback(static function (CriticalActionPerformedEvent $event): bool { + self::assertSame('(appId) is 100%% (params)', $event->getLogMessage()); + return true; + })); + + (new AuditLogger($eventDispatcher))->logForExApp('test_app', 'test_app.item.created', '{appId} is 100%% %s', ['item' => '{params}']); + } + + public static function dataInvalidExAppEntries(): array { + return [ + 'empty app ID' => ['', 'test_app.item.created', 'Created', []], + 'operation of another app' => ['test_app', 'app_api.ex_app.enabled', 'ExApp enabled', []], + 'operation of an app whose ID starts the same' => ['test', 'test_app.item.created', 'Created', []], + 'operation without entity' => ['test_app', 'test_app.created', 'Created', []], + 'reserved parameter' => ['test_app', 'test_app.item.created', 'Created for %s', ['appId' => 'other_app']], + 'nested parameter' => ['test_app', 'test_app.item.created', 'Created %s', ['item' => ['a']]], + 'unnamed parameter' => ['test_app', 'test_app.item.created', 'Created %s', ['a']], + 'too many placeholders' => ['test_app', 'test_app.item.created', 'Created %s by %s at %s', ['item' => 'a']], + 'one placeholder more than parameters' => ['test_app', 'test_app.item.created', 'Created %s by %s', ['item' => 'a']], + 'character directive' => ['test_app', 'test_app.item.created', '%cparams%c', ['open' => 123, 'close' => 125]], + 'width' => ['test_app', 'test_app.item.created', '%1073741824s', ['item' => 'a']], + 'padding character' => ['test_app', 'test_app.item.created', "%'{5s", ['item' => 'a']], + 'numbered argument' => ['test_app', 'test_app.item.created', '%1$s', ['item' => 'a']], + 'trailing percent' => ['test_app', 'test_app.item.created', 'Created %s 100%', ['item' => 'a']], + ]; + } + + #[DataProvider('dataInvalidExAppEntries')] + public function testLogForExAppRejectsInvalidEntries(string $appId, string $operation, string $message, array $parameters): void { + $eventDispatcher = $this->createMock(IEventDispatcher::class); + $eventDispatcher->expects(self::never())->method('dispatchTyped'); + + $this->expectException(\InvalidArgumentException::class); + (new AuditLogger($eventDispatcher))->logForExApp($appId, $operation, $message, $parameters); + } }