diff --git a/.woodpecker.star b/.woodpecker.star index 98184bddc5..23bb2a770d 100644 --- a/.woodpecker.star +++ b/.woodpecker.star @@ -60,8 +60,6 @@ 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", @@ -295,10 +293,6 @@ config = { "apiAudit", ], "skip": False, - "auditRecords": True, - "extraTestEnvironment": { - "AUDIT_RECORDS_FILE": dirs["auditRecords"], - }, "extraServerEnvironment": { "OC_AUDIT_ENABLED": True, "OC_ADD_RUN_SERVICES": "audit", @@ -1272,7 +1266,6 @@ def localApiTestPipeline(ctx): "enableWatchFs": False, "ldapNeeded": False, "openSearch": False, - "auditRecords": False, } if "localApiTests" in config: @@ -1333,7 +1326,6 @@ 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 []) + @@ -2435,7 +2427,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, audit_records = False): +def opencloudServer(storage = "decomposed", depends_on = [], deploy_type = "", extra_server_environment = {}, with_wrapper = False, tika_enabled = False, watch_fs_enabled = False): user = "0:0" container_name = OC_SERVER_NAME environment = { @@ -2559,10 +2551,6 @@ 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/TestHelpers/OcConfigHelper.php b/tests/acceptance/TestHelpers/OcConfigHelper.php index 8f06a7e004..6791dc807d 100644 --- a/tests/acceptance/TestHelpers/OcConfigHelper.php +++ b/tests/acceptance/TestHelpers/OcConfigHelper.php @@ -138,4 +138,24 @@ class OcConfigHelper { $url = self::getWrapperUrl() . "/start"; return self::sendRequest($url, "POST"); } + + /** + * the audit records the server wrote since the last clearAuditRecords() + * + * @return ResponseInterface + * @throws GuzzleException + */ + public static function getAuditRecords(): ResponseInterface { + $url = self::getWrapperUrl() . "/audit"; + return self::sendRequest($url, "GET"); + } + + /** + * @return ResponseInterface + * @throws GuzzleException + */ + public static function clearAuditRecords(): ResponseInterface { + $url = self::getWrapperUrl() . "/audit"; + return self::sendRequest($url, "DELETE"); + } } diff --git a/tests/acceptance/bootstrap/AuditContext.php b/tests/acceptance/bootstrap/AuditContext.php index 5e7bbcdfe9..b6f92e1375 100644 --- a/tests/acceptance/bootstrap/AuditContext.php +++ b/tests/acceptance/bootstrap/AuditContext.php @@ -11,20 +11,19 @@ use Behat\Gherkin\Node\TableNode; use Behat\Step\Then; use PHPUnit\Framework\Assert; use TestHelpers\BehatHelper; +use TestHelpers\OcConfigHelper; 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. + * The audit service writes every record as one line of JSON to stdout. The ocwrapper keeps these + * lines and returns them on GET /audit. They are cleared when a scenario starts, so only the + * records of the scenario 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; @@ -40,13 +39,12 @@ class AuditContext implements Context { */ 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' + $response = OcConfigHelper::clearAuditRecords(); + Assert::assertSame( + 200, + $response->getStatusCode(), + 'could not clear the audit records of the ocwrapper: ' . $response->getBody() ); - \clearstatcache(true, $this->recordsFile); - $this->scenarioStart = \is_file($this->recordsFile) ? (int)\filesize($this->recordsFile) : 0; } /** @@ -55,19 +53,19 @@ class AuditContext implements Context { * @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; + $response = OcConfigHelper::getAuditRecords(); + Assert::assertSame( + 200, + $response->getStatusCode(), + 'could not get the audit records from the ocwrapper: ' . $response->getBody() + ); + $records = \json_decode((string)$response->getBody(), true); + return \array_values( + \array_filter( + \is_array($records) ? $records : [], + fn ($record) => \is_array($record) && isset($record['event.name'], $record['schema_version']) + ) + ); } /** diff --git a/tests/ocwrapper/README.md b/tests/ocwrapper/README.md index d7e4047654..ceccda6e4e 100644 --- a/tests/ocwrapper/README.md +++ b/tests/ocwrapper/README.md @@ -124,3 +124,19 @@ Also, see `./bin/ocwrapper help` for more information. - `200 OK` - OpenCloud server is stopped - `500 Internal Server Error` - Unable to stop OpenCloud server + +6. `GET /audit` + + Returns the audit records the OpenCloud server wrote to its output (the lines of JSON with an `event.name`), as a JSON array, since the start of the wrapper or the last `DELETE /audit`. + + Returns: + + - `200 OK` - the records, e.g. `[{"event.name": "opencloud.file.upload", ...}]` + +7. `DELETE /audit` + + Forgets the audit records kept so far, e.g. at the start of a scenario. + + Returns: + + - `200 OK` - the records are cleared diff --git a/tests/ocwrapper/opencloud/audit.go b/tests/ocwrapper/opencloud/audit.go new file mode 100644 index 0000000000..532cb83a60 --- /dev/null +++ b/tests/ocwrapper/opencloud/audit.go @@ -0,0 +1,38 @@ +package opencloud + +import ( + "encoding/json" + "strings" + "sync" +) + +// The audit service writes every audit record as one line of JSON to stdout. +// The wrapper keeps these lines, so that the tests can fetch them (GET /audit). +var ( + auditMu sync.Mutex + auditRecords = []json.RawMessage{} +) + +// collectAuditRecord keeps the line if it is an audit record +func collectAuditRecord(line string) { + if !strings.HasPrefix(line, "{") || !strings.Contains(line, `"event.name"`) || !json.Valid([]byte(line)) { + return + } + auditMu.Lock() + defer auditMu.Unlock() + auditRecords = append(auditRecords, json.RawMessage(line)) +} + +// AuditRecords returns the audit records written since the last ClearAuditRecords +func AuditRecords() []json.RawMessage { + auditMu.Lock() + defer auditMu.Unlock() + return append([]json.RawMessage{}, auditRecords...) +} + +// ClearAuditRecords forgets the audit records kept so far +func ClearAuditRecords() { + auditMu.Lock() + defer auditMu.Unlock() + auditRecords = []json.RawMessage{} +} diff --git a/tests/ocwrapper/opencloud/opencloud.go b/tests/ocwrapper/opencloud/opencloud.go index 983acb8399..20cc14c6a2 100644 --- a/tests/ocwrapper/opencloud/opencloud.go +++ b/tests/ocwrapper/opencloud/opencloud.go @@ -80,6 +80,7 @@ func Start(envMap []string) { // Fetch logs from the channel and print them go func() { for s := range outChan { + collectAuditRecord(s) fmt.Println(s) } }() diff --git a/tests/ocwrapper/wrapper/handlers/handler.go b/tests/ocwrapper/wrapper/handlers/handler.go index c3d1981544..399421fcd5 100644 --- a/tests/ocwrapper/wrapper/handlers/handler.go +++ b/tests/ocwrapper/wrapper/handlers/handler.go @@ -140,6 +140,21 @@ func StopOpencloudHandler(res http.ResponseWriter, req *http.Request) { sendResponse(res, http.StatusInternalServerError, message) } +// AuditHandler returns the audit records of the server output (GET) or forgets them (DELETE) +func AuditHandler(res http.ResponseWriter, req *http.Request) { + switch req.Method { + case http.MethodGet: + res.Header().Set("Content-Type", "application/json") + res.WriteHeader(http.StatusOK) + _ = json.NewEncoder(res).Encode(opencloud.AuditRecords()) + case http.MethodDelete: + opencloud.ClearAuditRecords() + sendResponse(res, http.StatusOK, "audit records cleared") + default: + sendResponse(res, http.StatusMethodNotAllowed, "") + } +} + func StartOpencloudHandler(res http.ResponseWriter, req *http.Request) { if req.Method != http.MethodPost { sendResponse(res, http.StatusMethodNotAllowed, "") diff --git a/tests/ocwrapper/wrapper/wrapper.go b/tests/ocwrapper/wrapper/wrapper.go index 73208c28f9..67b753c46d 100644 --- a/tests/ocwrapper/wrapper/wrapper.go +++ b/tests/ocwrapper/wrapper/wrapper.go @@ -27,6 +27,7 @@ func Start(port string) { mux.HandleFunc("/command", handlers.CommandHandler) mux.HandleFunc("/stop", handlers.StopOpencloudHandler) mux.HandleFunc("/start", handlers.StartOpencloudHandler) + mux.HandleFunc("/audit", handlers.AuditHandler) httpServer.Handler = mux