Skip to content
Merged
Show file tree
Hide file tree
Changes from all 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
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,10 @@ and this project adheres to [Semantic Versioning](http://semver.org/).

## [Unreleased]

### Added

- ExApp, deploy daemon and AppAPI settings changes and failed ExApp, HaRP or Talk bot authentication are written to the admin audit log. #1130

### Changed

- `POST /ocs/v2.php/apps/app_api/api/v1/notification` now answers `404` when the `notifications` app is not enabled, instead of `200` for a notification that nobody delivers.
Expand All @@ -19,6 +23,7 @@ and this project adheres to [Semantic Versioning](http://semver.org/).
- HaRP receives the verb of each ExApp route, so HaRP 0.4.8 and newer check the HTTP method of a request as the ExApp proxy does. #1138
- The ExApp proxy accepts `HEAD` on routes that list `GET` and reads a route's verb as a list of methods, as HaRP does. #1144
- The HaRP version check in the admin overview warns about HaRP older than 0.4.8, which checks the HTTP method of requests to ExApps. #1149
- Failed HaRP shared key checks answer 429 after too many attempts. #1130

### Fixed

Expand All @@ -28,6 +33,7 @@ and this project adheres to [Semantic Versioning](http://semver.org/).
- The ExApp proxy refuses requests to the `/heartbeat`, `/init` and `/enabled` endpoints of ExApps, as HaRP does. #1168
- The ExApp proxy also applies a stricter route that matches the path as an ExApp may read it, as HaRP 0.4.8 does. #1182
- The ExApp proxy returns an ExApp's redirect to the browser instead of following it, as HaRP does. #1195
- `occ app_api:app:unregister --rm-data` also removes the volume of a Kubernetes ExApp whose deployment is already gone. #1130

## [34.0.0]

Expand Down
10 changes: 5 additions & 5 deletions composer.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

34 changes: 34 additions & 0 deletions lib/AuditLog/AuditLogger.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
<?php

declare(strict_types=1);

/**
* SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
*/

namespace OCA\AppAPI\AuditLog;

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

/**
* Writes entries to the admin audit log
*/
class AuditLogger {
public function __construct(
private readonly IEventDispatcher $eventDispatcher,
) {
}

/**
* @param string $message message with a `%s` placeholder for each of the first parameters
* @param array<string, mixed> $parameters named values for the placeholders of $message, in order, optionally followed by more context
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
*/
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));
}
}
65 changes: 65 additions & 0 deletions lib/AuditLog/Operation.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
<?php

declare(strict_types=1);

/**
* SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
*/

namespace OCA\AppAPI\AuditLog;

/**
* Operations AppAPI writes to the admin audit log; log consumers match the values, so they never change
*/
enum Operation: string {
// ExApps
case ExAppInstallRequested = 'app_api.ex_app.install_requested';
case ExAppRegistered = 'app_api.ex_app.registered';
case ExAppUpdateRequested = 'app_api.ex_app.update_requested';
case ExAppUpdated = 'app_api.ex_app.updated';
case ExAppEnabled = 'app_api.ex_app.enabled';
case ExAppDisabled = 'app_api.ex_app.disabled';
case ExAppUninstallRequested = 'app_api.ex_app.uninstall_requested';
case ExAppUnregistered = 'app_api.ex_app.unregistered';
case ExAppDataDeleted = 'app_api.ex_app_data.deleted';
case ExAppAuthFailed = 'app_api.ex_app_auth.failed';
case HarpAuthFailed = 'app_api.harp_auth.failed';
case TalkBotAuthFailed = 'app_api.talk_bot_auth.failed';

// Deploy daemons
case DaemonRegistered = 'app_api.daemon.registered';
case DaemonUpdated = 'app_api.daemon.updated';
case DaemonUnregistered = 'app_api.daemon.unregistered';
case DaemonRegistryAdded = 'app_api.daemon_registry.added';
case DaemonRegistryRemoved = 'app_api.daemon_registry.removed';

// Settings
case AdminConfigUpdated = 'app_api.admin_config.updated';

/**
* Short description of when the operation is logged, used for the documentation
*/
public function description(): string {
return match ($this) {
self::ExAppInstallRequested => 'The installation of an ExApp was started in the web interface, with the names of its environment variables and its mounts',
self::ExAppRegistered => 'An ExApp was registered and given its secret to authenticate to Nextcloud, before its deployment',
self::ExAppUpdateRequested => 'The update of an ExApp was started in the web interface',
self::ExAppUpdated => 'The version of an ExApp changed, at an update before the deployment of that version, or when the ExApp reported a newer one',
self::ExAppEnabled => 'An ExApp was enabled and started',
self::ExAppDisabled => 'An ExApp was disabled',
self::ExAppUninstallRequested => 'The removal of the test deploy ExApp was started in the deploy daemon settings',
self::ExAppUnregistered => 'An ExApp was removed from Nextcloud',
self::ExAppDataDeleted => 'The deploy daemon confirmed that the data volume of an ExApp is removed',
self::ExAppAuthFailed => 'A request with AppAPI authentication was rejected for an unknown ExApp or a wrong secret',
self::HarpAuthFailed => 'A request made as HaRP was rejected for a missing or wrong shared key, logged with the user whose request HaRP forwarded',
self::TalkBotAuthFailed => 'A message for the Talk bot of an ExApp was rejected for a wrong signature',
self::DaemonRegistered => 'A deploy daemon that ExApps can be installed on was registered',
self::DaemonUpdated => 'The configuration of a deploy daemon was changed',
self::DaemonUnregistered => 'A deploy daemon was unregistered',
self::DaemonRegistryAdded => 'A Docker registry mapping was added to a deploy daemon',
self::DaemonRegistryRemoved => 'A Docker registry mapping was removed from a deploy daemon',
self::AdminConfigUpdated => 'An AppAPI admin setting, such as the default deploy daemon, was changed or removed',
};
}
}
5 changes: 3 additions & 2 deletions lib/Command/Daemon/RegisterDaemon.php
Original file line number Diff line number Diff line change
Expand Up @@ -225,8 +225,9 @@ protected function execute(InputInterface $input, OutputInterface $output): int
return 1;
}

if ($input->getOption('set-default')) {
$this->config->setValueString(Application::APP_ID, 'default_daemon_config', $daemonConfig->getName(), lazy: true);
if ($input->getOption('set-default')
&& $this->config->setValueString(Application::APP_ID, 'default_daemon_config', $daemonConfig->getName(), lazy: true)) {
$this->daemonConfigService->logDefaultDaemonConfigChanged($daemonConfig->getName());
}

$output->writeln('Daemon config successfully registered.');
Expand Down
15 changes: 13 additions & 2 deletions lib/Command/ExApp/Unregister.php
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,9 @@ protected function execute(InputInterface $input, OutputInterface $output): int
return 1;
}
} else {
if ($rmData) {
$this->exAppService->logExAppDataDeleted($exApp);
}
if (!$silent) {
$output->writeln(sprintf('ExApp %s successfully removed', $appId));
}
Expand All @@ -137,6 +140,9 @@ protected function execute(InputInterface $input, OutputInterface $output): int
$removeVolumeResult = $this->dockerActions->removeVolume(
$this->dockerActions->buildDockerUrl($daemonConfig), $volumeName
);
if (!isset($removeVolumeResult['error'])) {
$this->exAppService->logExAppDataDeleted($exApp);
}
if (!$silent) {
if (isset($removeVolumeResult['error'])) {
$output->writeln(sprintf('Failed to remove ExApp %s volume: %s', $appId, $volumeName));
Expand Down Expand Up @@ -171,8 +177,13 @@ protected function execute(InputInterface $input, OutputInterface $output): int
if (!$force) {
return 1;
}
} elseif (!$silent) {
$output->writeln(sprintf('ExApp %s K8s resources successfully removed', $appId));
} else {
if ($rmData) {
$this->exAppService->logExAppDataDeleted($exApp);
}
if (!$silent) {
$output->writeln(sprintf('ExApp %s K8s resources successfully removed', $appId));
}
}
}
}
Expand Down
14 changes: 13 additions & 1 deletion lib/Controller/ConfigController.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@
namespace OCA\AppAPI\Controller;

use OCA\AppAPI\AppInfo\Application;
use OCA\AppAPI\AuditLog\AuditLogger;
use OCA\AppAPI\AuditLog\Operation;
use OCP\AppFramework\Controller;
use OCP\AppFramework\Http;
use OCP\AppFramework\Http\Attribute\NoCSRFRequired;
Expand All @@ -20,11 +22,14 @@

#[OpenAPI(OpenAPI::SCOPE_ADMINISTRATION)]
class ConfigController extends Controller {
/** Settings whose value is written to the audit log; any other key could hold a secret, so only its name is */
private const AUDITED_VALUE_KEYS = ['default_daemon_config', 'init_timeout', 'container_restart_policy', 'docker_api_version'];

public function __construct(
string $appName,
IRequest $request,
private readonly IAppConfig $appConfig,
private readonly AuditLogger $auditLogger,
) {
parent::__construct($appName, $request);
}
Expand All @@ -41,7 +46,14 @@ public function __construct(
#[NoCSRFRequired]
public function setAdminConfig(array $values): DataResponse {
foreach ($values as $key => $value) {
$this->appConfig->setValueString(Application::APP_ID, $key, $value, lazy: true);
if (!$this->appConfig->setValueString(Application::APP_ID, $key, $value, lazy: true)) {
continue;
}
if (in_array($key, self::AUDITED_VALUE_KEYS, true)) {
$this->auditLogger->log(Operation::AdminConfigUpdated, 'AppAPI setting %s was changed to %s', ['key' => $key, 'value' => $value]);
} else {
$this->auditLogger->log(Operation::AdminConfigUpdated, 'AppAPI setting %s was changed', ['key' => $key]);
}
}
return new DataResponse(1);
}
Expand Down
10 changes: 7 additions & 3 deletions lib/Controller/DaemonConfigController.php
Original file line number Diff line number Diff line change
Expand Up @@ -85,8 +85,9 @@ public function registerDaemonConfig(array $daemonConfigParams, bool $defaultDae
]);
}
$daemonConfig = $this->daemonConfigService->registerDaemonConfig($daemonConfigParams);
if ($daemonConfig !== null && $defaultDaemon) {
$this->appConfig->setValueString(Application::APP_ID, 'default_daemon_config', $daemonConfig->getName(), lazy: true);
if ($daemonConfig !== null && $defaultDaemon
&& $this->appConfig->setValueString(Application::APP_ID, 'default_daemon_config', $daemonConfig->getName(), lazy: true)) {
$this->daemonConfigService->logDefaultDaemonConfigChanged($daemonConfig->getName());
}
return new JSONResponse([
'success' => $daemonConfig !== null,
Expand Down Expand Up @@ -144,7 +145,7 @@ public function updateDaemonConfig(string $name, array $daemonConfigParams): Res
// Create and update DaemonConfig instance
$updatedDaemonConfig = new DaemonConfig($daemonConfigParams);
$updatedDaemonConfig->setId($daemonConfig->getId());
$updatedDaemonConfig = $this->daemonConfigService->updateDaemonConfig($updatedDaemonConfig);
$updatedDaemonConfig = $this->daemonConfigService->updateDaemonConfig($updatedDaemonConfig, $daemonConfig);

// Check if update was successful before proceeding
if ($updatedDaemonConfig === null) {
Expand Down Expand Up @@ -183,6 +184,7 @@ public function unregisterDaemonConfig(string $name): Response {
$this->service->removeExAppsByDaemonConfigName($daemonConfig);
if ($daemonConfig->getName() === $defaultDaemonConfig) {
$this->appConfig->deleteKey(Application::APP_ID, 'default_daemon_config');
$this->daemonConfigService->logDefaultDaemonConfigChanged('');
}
$daemonConfig = $this->daemonConfigService->unregisterDaemonConfig($daemonConfig);
return new JSONResponse([
Expand Down Expand Up @@ -300,6 +302,7 @@ public function startTestDeploy(string $name): Response {
Application::TEST_DEPLOY_INFO_XML,
'--test-deploy-mode',
];
$this->exAppService->logExAppInstallRequested(Application::TEST_DEPLOY_APPID, $daemonConfig->getName());
if (!$this->service->runOccCommand($commandParts)) {
return new JSONResponse(['error' => $this->l10n->t('Error starting install of ExApp')], Http::STATUS_INTERNAL_SERVER_ERROR);
}
Expand Down Expand Up @@ -338,6 +341,7 @@ public function stopTestDeploy(string $name): Response {
'--force',
Application::TEST_DEPLOY_APPID,
];
$this->exAppService->logExAppUninstallRequested($exApp);
$this->service->runOccCommand($commandParts);
$elapsedTime = 0;
while ($elapsedTime < 5000000 && $this->exAppService->getExApp(Application::TEST_DEPLOY_APPID) !== null) {
Expand Down
20 changes: 16 additions & 4 deletions lib/Controller/ExAppsPageController.php
Original file line number Diff line number Diff line change
Expand Up @@ -351,11 +351,14 @@ public function enableApp(string $appId, string $daemonId, array $deployOptions
}

$mountOptions = $deployOptions['mounts'] ?? [];
$mounts = [];
$mountArgs = [];
foreach ($mountOptions as $mountOption) {
$readonlyModifier = $mountOption['readonly'] ? 'ro' : 'rw';
$mount = sprintf('%s:%s:%s', $mountOption['hostPath'], $mountOption['containerPath'], $readonlyModifier);
$mounts[] = $mount;
$mountArgs[] = '--mount';
$mountArgs[] = sprintf('%s:%s:%s', $mountOption['hostPath'], $mountOption['containerPath'], $readonlyModifier);
$mountArgs[] = $mount;
}

// If ExApp is not registered - then it's a "Deploy and Enable" action.
Expand All @@ -370,6 +373,7 @@ public function enableApp(string $appId, string $daemonId, array $deployOptions
$envArgs,
$mountArgs
);
$this->exAppService->logExAppInstallRequested($appId, $daemonId, $envOptions, $mounts);
if (!$this->service->runOccCommand($commandParts)) {
return new JSONResponse(['data' => ['message' => $this->l10n->t('Error starting install of ExApp')]], Http::STATUS_INTERNAL_SERVER_ERROR);
}
Expand Down Expand Up @@ -443,12 +447,14 @@ public function updateApp(string $appId): JSONResponse {
return new JSONResponse(['data' => ['message' => $this->l10n->t('Could not update ExApp')]], Http::STATUS_INTERNAL_SERVER_ERROR);
}

$exAppOldVersion = $this->exAppService->getExApp($appId)->getVersion();
$exApp = $this->exAppService->getExApp($appId);
$exAppOldVersion = $exApp->getVersion();
$commandParts = [
'app_api:app:update',
'--silent',
$appId,
];
$this->exAppService->logExAppUpdateRequested($exApp);
if (!$this->service->runOccCommand($commandParts)) {
return new JSONResponse(['data' => ['message' => $this->l10n->t('Error starting update of ExApp')]], Http::STATUS_INTERNAL_SERVER_ERROR);
}
Expand Down Expand Up @@ -491,12 +497,18 @@ public function uninstallApp(string $appId, bool $removeContainer = true, bool $
if ($daemonConfig->getAcceptsDeployId() === $this->dockerActions->getAcceptsDeployId()) {
$this->dockerActions->initGuzzleClient($daemonConfig);
if (boolval($exApp->getDeployConfig()['harp'] ?? false)) {
$this->dockerActions->removeExApp($this->dockerActions->buildDockerUrl($daemonConfig), $exApp->getAppid(), removeData: $removeData);
$removeError = $this->dockerActions->removeExApp($this->dockerActions->buildDockerUrl($daemonConfig), $exApp->getAppid(), removeData: $removeData);
if ($removeData && $removeError === '') {
$this->exAppService->logExAppDataDeleted($exApp);
}
} else {
if ($removeContainer) {
$this->dockerActions->removeContainer($this->dockerActions->buildDockerUrl($daemonConfig), $this->dockerActions->buildExAppContainerName($appId));
if ($removeData) {
$this->dockerActions->removeVolume($this->dockerActions->buildDockerUrl($daemonConfig), $this->dockerActions->buildExAppVolumeName($appId));
$removeVolumeResult = $this->dockerActions->removeVolume($this->dockerActions->buildDockerUrl($daemonConfig), $this->dockerActions->buildExAppVolumeName($appId));
if (isset($removeVolumeResult['success'])) {
$this->exAppService->logExAppDataDeleted($exApp);
}
}
}
}
Expand Down
7 changes: 7 additions & 0 deletions lib/Controller/HarpController.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@

use OCA\AppAPI\AppInfo\Application;
use OCA\AppAPI\Attribute\MaintenanceModeAvailable;
use OCA\AppAPI\AuditLog\AuditLogger;
use OCA\AppAPI\AuditLog\Operation;
use OCA\AppAPI\Db\ExApp;
use OCA\AppAPI\Service\ExAppService;
use OCA\AppAPI\Service\HarpService;
Expand Down Expand Up @@ -41,6 +43,7 @@ public function __construct(
private readonly ICrypto $crypto,
private readonly ?string $userId,
private readonly HarpService $harpService,
private readonly AuditLogger $auditLogger,
) {
parent::__construct(Application::APP_ID, $request);

Expand All @@ -65,6 +68,10 @@ private function validateHarpSharedKey(ExApp $exApp): bool {
$this->throttler->registerAttempt(Application::APP_ID, $this->request->getRemoteAddress(), [
'appid' => $exApp->getAppid(),
]);
$this->throttler->sleepDelayOrThrowOnMax($this->request->getRemoteAddress(), Application::APP_ID);
$this->auditLogger->log(Operation::HarpAuthFailed, 'Failed HaRP authentication for ExApp %s', [
'appId' => $exApp->getAppid(),
]);
return false;
}
return true;
Expand Down
Loading
Loading