From 81bd485bf6a90bd296e1498f01b85fcfc67a184a Mon Sep 17 00:00:00 2001 From: Michael Barz Date: Mon, 30 Nov 2026 09:55:34 +0100 Subject: [PATCH] test: acceptance tests for the audit log (#4152) * test: acceptance tests for the audit log Assisted-by: Claude Code:claude-opus-5-5 * test: author tag in the audit context Assisted-by: Claude Code:claude-opus-5-5 --- .woodpecker.star | 24 +- tests/acceptance/bootstrap/AuditContext.php | 242 ++++++++++++++++++ tests/acceptance/config/behat.yml | 16 ++ .../features/apiAudit/auditLog.feature | 102 ++++++++ tests/acceptance/scripts/run_api_tests.sh | 1 + 5 files changed, 384 insertions(+), 1 deletion(-) create mode 100644 tests/acceptance/bootstrap/AuditContext.php create mode 100644 tests/acceptance/features/apiAudit/auditLog.feature diff --git a/.woodpecker.star b/.woodpecker.star index 68cbb10ff9..98184bddc5 100644 --- a/.woodpecker.star +++ b/.woodpecker.star @@ -60,6 +60,8 @@ dirs = { "opencloudConfig": "tests/config/woodpecker/opencloud-config.json", "opencloudRevaDataRoot": "/woodpecker/src/github.com/%s/srv/app/tmp/ocis/owncloud/data" % repo_slug, "multiServiceOcBaseDataPath": "/woodpecker/src/github.com/%s/multiServiceData" % repo_slug, + # a copy of the server output for the audit log tests, the audit records are lines of it + "auditRecords": "/woodpecker/src/github.com/%s/audit-records.jsonl" % repo_slug, "ocWrapper": "/woodpecker/src/github.com/%s/tests/ocwrapper" % repo_slug, "bannedPasswordList": "tests/config/woodpecker/banned-password-list.txt", "ocmProviders": "tests/config/woodpecker/providers.json", @@ -288,6 +290,20 @@ config = { "ANTIVIRUS_DEBUG_ADDR": "0.0.0.0:9297", }, }, + "audit": { + "suites": [ + "apiAudit", + ], + "skip": False, + "auditRecords": True, + "extraTestEnvironment": { + "AUDIT_RECORDS_FILE": dirs["auditRecords"], + }, + "extraServerEnvironment": { + "OC_AUDIT_ENABLED": True, + "OC_ADD_RUN_SERVICES": "audit", + }, + }, "searchContent": { "suites": [ "apiSearchContent", @@ -1256,6 +1272,7 @@ def localApiTestPipeline(ctx): "enableWatchFs": False, "ldapNeeded": False, "openSearch": False, + "auditRecords": False, } if "localApiTests" in config: @@ -1316,6 +1333,7 @@ def localApiTestPipeline(ctx): with_wrapper = True, tika_enabled = params["tikaNeeded"], watch_fs_enabled = run_with_watch_fs, + audit_records = params["auditRecords"], ) + (opencloudServer(storage, deploy_type = "federation", extra_server_environment = params["extraServerEnvironment"], watch_fs_enabled = run_with_watch_fs) if params["federationServer"] else []) + ((wopiCollaborationService("fakeoffice") + wopiCollaborationService("collabora") + wopiCollaborationService("onlyoffice")) if params["collaborationServiceNeeded"] else []) + @@ -2417,7 +2435,7 @@ def notifyMatrixCheckSteps(ctx, depends_on): return result -def opencloudServer(storage = "decomposed", depends_on = [], deploy_type = "", extra_server_environment = {}, with_wrapper = False, tika_enabled = False, watch_fs_enabled = False): +def opencloudServer(storage = "decomposed", depends_on = [], deploy_type = "", extra_server_environment = {}, with_wrapper = False, tika_enabled = False, watch_fs_enabled = False, audit_records = False): user = "0:0" container_name = OC_SERVER_NAME environment = { @@ -2541,6 +2559,10 @@ def opencloudServer(storage = "decomposed", depends_on = [], deploy_type = "", e "%s server" % dirs["opencloudBin"], ) + # the audit records are lines of the server output, keep a copy for the tests + if audit_records: + server_commands[-1] += " | tee %s" % dirs["auditRecords"] + wait_for_opencloud = { "name": "wait-for-%s" % container_name, "image": OC_CI_ALPINE, diff --git a/tests/acceptance/bootstrap/AuditContext.php b/tests/acceptance/bootstrap/AuditContext.php new file mode 100644 index 0000000000..5e7bbcdfe9 --- /dev/null +++ b/tests/acceptance/bootstrap/AuditContext.php @@ -0,0 +1,242 @@ + + * @copyright Copyright (c) 2026 OpenCloud GmbH + * SPDX-License-Identifier: Apache-2.0 + */ + +use Behat\Behat\Context\Context; +use Behat\Behat\Hook\Scope\BeforeScenarioScope; +use Behat\Gherkin\Node\TableNode; +use Behat\Step\Then; +use PHPUnit\Framework\Assert; +use TestHelpers\BehatHelper; + +require_once 'bootstrap.php'; + +/** + * Checks the records of the audit log. + * + * The audit service writes every record as one line of JSON to stdout. The server's output goes + * into the file AUDIT_RECORDS_FILE; lines that are not an audit record, e.g. log lines, are + * skipped. Only the records written after the scenario started count. + */ +class AuditContext implements Context { + private FeatureContext $featureContext; + private string $recordsFile; + private int $scenarioStart = 0; + + // the audit service writes a record shortly after the request, the steps wait that long for it + private const WAIT_SECONDS = 10; + // how long a step waits for records that must not come, or for more than the expected ones + private const SETTLE_SECONDS = 3; + + /** + * @BeforeScenario + * + * @param BeforeScenarioScope $scope + * + * @return void + */ + public function before(BeforeScenarioScope $scope): void { + $this->featureContext = BehatHelper::getContext($scope, $scope->getEnvironment(), 'FeatureContext'); + $this->recordsFile = (string)\getenv('AUDIT_RECORDS_FILE'); + Assert::assertNotEmpty( + $this->recordsFile, + 'AUDIT_RECORDS_FILE must name the file the server writes its output to' + ); + \clearstatcache(true, $this->recordsFile); + $this->scenarioStart = \is_file($this->recordsFile) ? (int)\filesize($this->recordsFile) : 0; + } + + /** + * the audit records written since the scenario started + * + * @return array> + */ + private function records(): array { + \clearstatcache(true, $this->recordsFile); + if (!\is_file($this->recordsFile)) { + return []; + } + $content = (string)\file_get_contents($this->recordsFile, false, null, $this->scenarioStart); + $records = []; + foreach (\explode("\n", $content) as $line) { + $record = \json_decode($line, true); + if (\is_array($record) && isset($record['event.name'], $record['schema_version'])) { + $records[] = $record; + } + } + return $records; + } + + /** + * the value of a field of a record; change.before. and change.after. look into the + * changed attributes + * + * @param array $record + * @param string $field + * + * @return string|null + */ + private function field(array $record, string $field): ?string { + if (\array_key_exists($field, $record)) { + $value = $record[$field]; + } elseif (\preg_match('/^(change\.(?:before|after))\.(.+)$/', $field, $m) + && isset($record[$m[1]]) && \is_array($record[$m[1]]) && \array_key_exists($m[2], $record[$m[1]]) + ) { + $value = $record[$m[1]][$m[2]]; + } else { + return null; + } + if (\is_bool($value)) { + return $value ? 'true' : 'false'; + } + return \is_scalar($value) ? (string)$value : \json_encode($value); + } + + /** + * the records of the event that have all the given field values + * + * @param string $event + * @param array $fields + * + * @return array> + */ + private function matching(string $event, array $fields): array { + return \array_values( + \array_filter( + $this->records(), + function (array $record) use ($event, $fields): bool { + if ($record['event.name'] !== "opencloud.$event") { + return false; + } + foreach ($fields as $field => $value) { + if ($this->field($record, $field) !== $value) { + return false; + } + } + return true; + } + ) + ); + } + + /** + * the id of a user the scenario created, e.g. "Alice" + * + * @param string $user + * + * @return string + */ + private function userId(string $user): string { + $id = $this->featureContext->getAttributeOfCreatedUser($user, 'id'); + Assert::assertNotEmpty($id, "the scenario did not create the user '$user'"); + return (string)$id; + } + + /** + * the expected field values of a table with the columns field and value; actor.id takes the + * name of a user of the scenario, e.g. "Alice". actor.name is the display name of a user, or + * the login name of a failed login + * + * @param TableNode $table + * + * @return array + */ + private function expectedFields(TableNode $table): array { + $this->featureContext->verifyTableNodeColumns($table, ['field', 'value']); + $fields = []; + foreach ($table->getHash() as $row) { + $value = $row['value']; + if ($row['field'] === 'actor.id') { + $value = $this->userId($value); + } + $fields[$row['field']] = $value; + } + return $fields; + } + + /** + * waits until there are at least $count matching records. With $exact, it waits a moment + * longer to see whether more come, and checks that there are exactly $count + * + * @param int $count + * @param string $event + * @param array $fields + * @param bool $exact + * + * @return void + */ + private function assertRecordCount(int $count, string $event, array $fields, bool $exact): void { + $deadline = \microtime(true) + self::WAIT_SECONDS; + while (\count($this->matching($event, $fields)) < $count && \microtime(true) < $deadline) { + \usleep(200000); + } + if ($exact) { + \sleep(self::SETTLE_SECONDS); + } + $found = \count($this->matching($event, $fields)); + $message = ($exact ? "expected exactly" : "expected at least") + . " $count audit record(s) '$event' with " . \json_encode($fields) . ", found $found." + . " Records of this scenario:\n" . \implode("\n", \array_map('json_encode', $this->records())); + if ($exact) { + Assert::assertSame($count, $found, $message); + } else { + Assert::assertGreaterThanOrEqual($count, $found, $message); + } + } + + /** + * at least one such record; the test framework itself sends requests too, e.g. a download + * after each upload to wait for its postprocessing + * + * @param string $event + * @param string $outcome + * @param string $user + * + * @return void + */ + #[Then('there should be an audit record :event with outcome :outcome by user :user')] + public function thereShouldBeAnAuditRecordByUser(string $event, string $outcome, string $user): void { + $this->assertRecordCount( + 1, + $event, + ['outcome' => $outcome, 'actor.id' => $this->userId($user)], + false + ); + } + + /** + * @param string $event + * @param TableNode $table + * + * @return void + */ + #[Then('there should be an audit record :event with these fields:')] + public function thereShouldBeAnAuditRecordWithTheseFields(string $event, TableNode $table): void { + $this->assertRecordCount(1, $event, $this->expectedFields($table), false); + } + + /** + * @param int $count + * @param string $event + * @param TableNode $table + * + * @return void + */ + #[Then('there should be :count audit records :event with these fields:')] + public function thereShouldBeAuditRecordsWithTheseFields(int $count, string $event, TableNode $table): void { + $this->assertRecordCount($count, $event, $this->expectedFields($table), true); + } + + /** + * @param string $event + * + * @return void + */ + #[Then('there should be no audit record :event')] + public function thereShouldBeNoAuditRecord(string $event): void { + $this->assertRecordCount(0, $event, [], true); + } +} diff --git a/tests/acceptance/config/behat.yml b/tests/acceptance/config/behat.yml index d226cf53ba..50033030bd 100644 --- a/tests/acceptance/config/behat.yml +++ b/tests/acceptance/config/behat.yml @@ -219,6 +219,22 @@ default: - PublicWebDavContext: - SharingNgContext: + apiAudit: + paths: + - "%paths.base%/../features/apiAudit" + context: *common_ldap_suite_context + contexts: + - FeatureContext: *common_feature_context_params + - AuditContext: + - AuthContext: + - SpacesContext: + - OCSContext: + - GraphContext: + - SettingsContext: + - OcConfigContext: + - PublicWebDavContext: + - SharingNgContext: + apiDownloads: paths: - "%paths.base%/../features/apiDownloads" diff --git a/tests/acceptance/features/apiAudit/auditLog.feature b/tests/acceptance/features/apiAudit/auditLog.feature new file mode 100644 index 0000000000..16518140c4 --- /dev/null +++ b/tests/acceptance/features/apiAudit/auditLog.feature @@ -0,0 +1,102 @@ +Feature: audit log + As an administrator + I want every relevant action to be recorded in the audit log + So that I can find out who did what and when + + Background: + Given these users have been created with default attributes: + | username | + | Alice | + | Brian | + And using spaces DAV path + And using SharingNG + + + Scenario: uploading and downloading a file is recorded + When user "Alice" uploads file with content "audit" to "/audit.txt" using the WebDAV API + And user "Alice" downloads file "/audit.txt" using the WebDAV API + Then there should be an audit record "file.upload" with these fields: + | field | value | + | outcome | success | + | actor.id | Alice | + | target.type | file | + | target.path | ./audit.txt | + And there should be an audit record "file.download" with these fields: + | field | value | + | outcome | success | + | actor.id | Alice | + | target.path | ./audit.txt | + + + Scenario: a login with a wrong password is recorded as failure + When user "Alice" requests these endpoints with "PROPFIND" using password "invalid" about user "Alice" + | endpoint | + | /dav/files/%username%/ | + Then there should be an audit record "auth.login" with these fields: + | field | value | + | outcome | failure | + | outcome.reason | invalid_credentials | + | actor.name | Alice | + + + Scenario: creating, declining and accepting a share is recorded, hiding it is not + Given user "Alice" has created folder "folderToShare" + When user "Alice" sends the following resource share invitation using the Graph API: + | resource | folderToShare | + | space | Personal | + | sharee | Brian | + | shareType | user | + | permissionsRole | Viewer | + Then there should be an audit record "share.create" with outcome "success" by user "Alice" + When user "Brian" hides the shared resource "folderToShare" using the Graph API + Then there should be no audit record "share.update" + And there should be no audit record "share.decline" + When user "Brian" disables sync of share "folderToShare" using the Graph API + Then there should be "1" audit records "share.decline" with these fields: + | field | value | + | outcome | success | + | actor.id | Brian | + When user "Brian" enables sync of share "folderToShare" offered by "Alice" from "Personal" space using the Graph API + Then there should be "1" audit records "share.accept" with these fields: + | field | value | + | outcome | success | + | actor.id | Brian | + + + Scenario: every wrong public link password is recorded, a successful access once per client + Given user "Alice" has created folder "linkFolder" + And user "Alice" has uploaded file with content "audit" to "/linkFolder/test.txt" + And user "Alice" has created the following resource link share: + | resource | linkFolder | + | space | Personal | + | permissionsRole | view | + | password | %public% | + When the public downloads file "/test.txt" from inside the last public link shared folder with password "wrong" using the public WebDAV API + And the public downloads file "/test.txt" from inside the last public link shared folder with password "wrong" using the public WebDAV API + And the public downloads file "/test.txt" from inside the last public link shared folder with password "%public%" using the public WebDAV API + And the public downloads file "/test.txt" from inside the last public link shared folder with password "%public%" using the public WebDAV API + Then there should be "2" audit records "public_link.access" with these fields: + | field | value | + | outcome | denied | + And there should be "1" audit records "public_link.access" with these fields: + | field | value | + | outcome | success | + + + Scenario: adding members with a PATCH and renaming a group is recorded + Given the administrator has assigned the role "Admin" to user "Alice" using the Graph API + And user "Alice" has created a group "grp1" using the Graph API + When the administrator "Alice" adds the following users to a group "grp1" at once using the Graph API + | username | + | Brian | + Then there should be an audit record "group.member.add" with these fields: + | field | value | + | outcome | success | + | actor.id | Alice | + When user "Alice" renames group "grp1" to "grp2" using the Graph API + Then there should be an audit record "group.update" with these fields: + | field | value | + | outcome | success | + | actor.id | Alice | + | target.name | grp1 | + | change.after.displayname | grp2 | diff --git a/tests/acceptance/scripts/run_api_tests.sh b/tests/acceptance/scripts/run_api_tests.sh index 6228420a83..9d1a04eb24 100755 --- a/tests/acceptance/scripts/run_api_tests.sh +++ b/tests/acceptance/scripts/run_api_tests.sh @@ -99,6 +99,7 @@ CORE_SUITES=( EXTRA_SUITE=( "apiAntivirus" + "apiAudit" "apiOcm" "apiCollaboration" "apiAuthApp"