Skip to content
Open
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions appinfo/routes.php
Original file line number Diff line number Diff line change
Expand Up @@ -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'],
Expand Down
44 changes: 42 additions & 2 deletions lib/AuditLog/AuditLogger.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@

namespace OCA\AppAPI\AuditLog;

use InvalidArgumentException;
use OCP\EventDispatcher\IEventDispatcher;
use OCP\Log\Audit\CriticalActionPerformedEvent;

Expand All @@ -26,9 +27,48 @@ public function __construct(
* @param array<string, mixed> $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 {
$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 `<appId>.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
* @param array<string, scalar|null> $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 `<appId>.entity.action`, a parameter is not a scalar or null, or the message does not fit the 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 . '.')) {
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ExApp IDs may contain - (app-skeleton-python, our test-deploy), but CriticalActionPerformedEvent only accepts [a-z][a-z0-9_]* parts, so such an ExApp gets 400 for any operation, with or without the hyphen (checked live). Accepting the ID with - replaced by _ as the prefix would fix it; appId still names the real app.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ah, nice catch!
perhaps we should make the change in the server so the value isn't misrepresented and the appId remains exactly what it is?

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');
}
}
$parameters['appId'] = $appId;
try {
$this->dispatch($operation, self::escape($message), $parameters);
Comment thread
kyteinsky marked this conversation as resolved.
Resolved
} catch (\ValueError $e) {
throw new InvalidArgumentException('Message does not fit the parameters: ' . $e->getMessage(), 0, $e);
}
}

private function dispatch(string $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));
$values = array_map(static fn (mixed $value): mixed => is_string($value) ? self::escape($value) : $value, array_values($parameters));
$message = str_replace('%', '%%', vsprintf($message, $values));
$this->eventDispatcher->dispatchTyped(new CriticalActionPerformedEvent($message, $parameters, false, $operation->value));
$this->eventDispatcher->dispatchTyped(new CriticalActionPerformedEvent($message, $parameters, false, $operation));
}

private static function escape(string $value): string {
return strtr($value, ['{' => '(', '}' => ')']);
}
}
28 changes: 28 additions & 0 deletions lib/Controller/OCSApiController.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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);

Expand Down Expand Up @@ -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 `<appId>.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<string, string|int|float|bool|null> $parameters Named values for the placeholders of the message, optionally followed by more context
*
* @return DataResponse<Http::STATUS_OK, list<empty>, 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
*
Expand Down
144 changes: 144 additions & 0 deletions openapi-full.json
Original file line number Diff line number Diff line change
Expand Up @@ -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 `<appId>.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,

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Minor · Data Integrity & Integration · Quick win

Make null valid in a typed schema branch.

The logger accepts parameters={"item":null}, but this schema rejects it. In OpenAPI 3.0.3, nullable needs type in the same Schema Object. None of these anyOf branches permits null. (spec.openapis.org)

Move nullable: true into a typed branch, such as the string branch. Keep the other scalar branches. Correct the generator output and regenerate both OpenAPI documents.

"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",
Expand Down
Loading
Loading