test: get the audit records from the ocwrapper (#4174)

The audit log tests read the audit records from a copy of the server
output, which the CI wrote with "| tee" to a file given to the tests in
AUDIT_RECORDS_FILE. The ocwrapper reads the server output anyway: it now
keeps the audit records, and returns them on GET /audit (DELETE /audit
clears them). The tests clear them when a scenario starts and fetch them
from there, so they need no extra setup in the CI or locally.

Assisted-by: Claude Code:claude-opus-5-5
This commit is contained in:
Viktor Scharf authored and GitHub committed 2026-12-01 14:46:25 +01:00
1 parent 64a44e77ff
commit 0d42e7228f
8 files changed
+114 -37

No files matched your search

+1 -13
View File
@@ -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,
@@ -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");
}
}
+22 -24
View File
@@ -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<int, array<string, mixed>>
*/
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'])
)
);
}
/**
+16
View File
@@ -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
+38
View File
@@ -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{}
}
+1
View File
@@ -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)
}
}()
@@ -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, "")
+1
View File
@@ -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