Skip to content

Auditing NG Part 1 - #956

Open
micbar wants to merge 10 commits into
mainfrom
auditing-ng
Open

micbar wants to merge 10 commits into
mainfrom
auditing-ng

Conversation

@micbar

@micbar micbar commented Oct 29, 2026 •

Copy link
Copy Markdown
Member

New audit system

Reva part of the audit log from ADR 0006 in opencloud.

The services

  • emit audit records into the JetStream stream audit
  • the OpenCloud audit service writes them out.

Please review commit by commit, each one builds and passes its tests.

1. Audit package

  • pkg/audit: record schema, event catalog, emitter in best_effort or strict mode
  • new action: add it to pkg/audit/catalog.go. Codes never change, the schema only grows
  • target is the object before the action, new values go into change.after
  • never put passwords, tokens or file content into a record
  • tests: audit.Discard{} or a recording emitter

2. Request context between the services

flowchart LR
    client[Client] --> proxy["OpenCloud proxy<br/>sets X-Audit-Context"]
    proxy -- "HTTP header" --> http["ocdav and other<br/>HTTP services"]
    http -- "gRPC metadata" --> grpc["gateway, storage<br/>and share providers"]
    http -- "HTTP header,<br/>client transfers only" --> dp[data provider]
Loading
  • client address, user agent, auth method, session and OIDC client travel in X-Audit-Context
  • an HTTP service calling another one forwards it (audit.Header), requests without it come from OpenCloud itself

3. Storage drivers report the item of a call

  • decomposedfs and posix set type, node ID, name and path in the space with storagespace.ContextSetItem / ContextSetItemPath
  • only with audit on, check ContextWantsItem before an extra lookup

4. Events middleware

  • files, trash bin, versions, locks, shares, links, spaces and members, also failed and denied calls
  • one file per area, a new CS3 response type needs a case in fileEvent, shareEvent, linkEvent or spaceEvent
  • target.path is the path in the owner's space, also through shares and links
  • actions through a public link have the link as actor
  • link access is recorded once per link and client within 30 minutes, failed attempts always
  • records say whether a password is set, never the password
  • config: audit_enabled, audit_mode, audit_service, audit_service_version. Audit on without an events endpoint is an error

5. Uploads and downloads

  • the data provider audits PUT, TUS and downloads when the transfer is done, only for requests a client sent
  • same config as the events middleware. Other code finds the emitter with audit.ContextGetEmitter(ctx), a no-op without audit

6. Archive downloads

  • one download record per file or folder, config in an audit block

Tested with unit tests and with opencloud-eu/opencloud#3864 against a local server.

Needed by opencloud-eu/opencloud#3864.

@micbar micbar mentioned this pull request Oct 30, 2026
4 of 9 tasks
@micbar micbar changed the title Auditing ng - First Part feat: emit audit events Nov 19, 2026
@micbar
micbar force-pushed the auditing-ng branch 3 times, most recently from 1bd747f to e944f14 Compare November 23, 2026 16:23
@micbar
micbar marked this pull request as ready for review November 23, 2026 17:38
@micbar micbar changed the title feat: emit audit events Auditing NG Part 1 Nov 23, 2026
@micbar
micbar requested review from butonic and pbleser-oc November 23, 2026 20:05
@micbar

micbar commented Nov 23, 2026 •

Copy link
Copy Markdown
Member Author

@butonic @pbleser-oc

I restructured my commits into logical independent chunks.

NOTE: The audit context is created in the proxy in opencloud, so there is an important part outside the scope of this PR.

From my POV, we should merge the reva part first.

I added the audit pkg to reva because adding it to opencloud would create a circular go mod import pattern.

@codacy-production

codacy-production Bot commented Nov 23, 2026 •

Copy link
Copy Markdown

Up to standards ✅

🟢 Issues 0 issues

Results:
0 new issues

View in Codacy

🟢 Metrics 503 complexity · 10 duplication

Metric Results
Complexity 503
Duplication 10

View in Codacy

NEW Get contextual insights on your PRs based on Codacy's metrics, along with PR and Jira context, without leaving GitHub. Enable AI reviewer
TIP This summary will be updated as you push new changes.

@pbleser-oc pbleser-oc left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Thanks Michael, splitting it into these six commits made it much easier to follow. I read it commit by commit, built it and ran the tests of the touched packages locally (with -race), and they pass. Thanks also for the note on the proxy part: I checked that the proxy in opencloud-eu/opencloud#3864 drops an X-Audit-Context sent by a client, so the services can trust it.

A few points, the first three look like bugs to me:

1. Hiding an accepted share records a share.accept (audit_share.go, UpdateReceivedShareResponse)

The event is picked from the state in the response. Hiding or unhiding an accepted share, or renaming its mount point, sends an UpdateReceivedShare with the mask hidden or mount_point, and the response still has the state ACCEPTED, so each of them is recorded as an accept. Maybe check that the update mask contains state first?

2. The dedupe of failed link accesses can grow without bound (audit_link.go, firstLinkAccess / onceWithin)

Failed accesses are keyed by the trace ID, so every attempt is a new key, and it is kept for the full 30 minutes. Someone trying passwords on a link (no login needed) adds one entry per attempt. Above 10,000 entries, every new one also scans the whole map under the mutex, and removes only the expired ones, so the map keeps growing and each request gets slower. Since the failure keys are only there to merge the proxy's and ocdav's check of the same request, a window of a few seconds for them, or a bounded LRU, would be enough.

3. An unknown audit_mode drops every record (emitter.go, NewEmitter)

The queue is only created for best_effort. With any other value than strict, e.g. a typo, Emit sends to a nil channel, the select falls through to default, and every record is counted as buffer_full and dropped, silently apart from the log lines. Could NewEmitter (or EmitterFromConfig) reject an unknown mode with an error, like a missing endpoint?

4. What should strict do in the middleware? (question)

In the events middleware, the data provider and the archiver, the event is emitted after the call, and an error is only logged ("failing it now would hide that it happened"), which makes sense. But then strict doesn't refuse anything there, it only makes the call wait for the JetStream ack, up to the 5 s timeout when NATS is slow. Is that what ADR 0006 means by strict, or should these call sites always publish asynchronously? Either way, a sentence on it in the doc comment of ModeStrict would help.

5. Nothing closes the emitter

Close flushes the best_effort buffer, but nothing calls it yet, so up to 1000 records are lost on a shutdown. When something does call it, a request still running at that moment panics in Emit, because a send on a closed channel panics, also inside a select with default. Guarding the send (a closed flag under an RWMutex, or a done channel) would make Close safe to call.

6. Three config shapes for the same emitter

The middleware reads audit_* keys plus the events keys, the data provider audit_* plus the nats_* keys, and the archiver an audit block with EmitterConfig. EmitterFromConfig is only used by the archiver. Using EmitterConfig and EmitterFromConfig everywhere would make them the one way to build an emitter from a config, with the validation (endpoint, and the mode from point 3) in one place. I'd understand if you'd rather keep the existing nats_* keys of the data provider, though.

7. Suggestion: pass the emitter to the data transfer handlers instead of the context

This one is a suggested improvement, not something that has to change. The data provider puts the emitter into the request context, and the download handler and the tus hook take it out with audit.ContextGetEmitter. When it isn't there, they get Discard{}, so if a future handler or a refactoring loses it on the way, the records silently stop, and neither the compiler nor a test would notice.

The events publisher already takes the route the emitter would need: dataprovider.New passes it to datatxregistry.NewFuncs[t], and the simple, spaces and tus managers keep it in their structs. Passing the emitter next to it would touch the NewFunc signature, the three New functions and their structs, and one parameter of download.GetOrHeadFile (two callers), all within pkg/rhttp/datatx. A missing emitter would then be a compile error, and the tus hook would no longer depend on ev.Context still holding the values of the last request.

Nitpicks:

  • storagespace.ContextSetItemType isn't used anywhere, and ItemTypeSlot now carries the ID, the name and the path as well, so ItemSlot / ContextRegisterItemSlot might read better.
  • In Decomposedfs.Move, Delete and the others, the item is set before the permission check, so a denied call has the path of the node in the record. I think that's what we want for denied calls, just mentioning it so it's a conscious choice.

Apart from these, it reads very well. The comments on why each piece is there are really helpful.

@pbleser-oc

Copy link
Copy Markdown
Member

One more thing I forgot in my review, about the metrics in pkg/audit/metrics.go. Having emitted_total by event and outcome is great for dashboards, these are only small additions:

  • events_emitted_total is counted when the event reaches the emitter, before it is published, so in best_effort mode an event can be counted as emitted and later as dropped (buffer_full or publish). The stored events are then emitted - dropped{reason=~"buffer_full|publish"}. Maybe the help text could say "handed to the emitter, including the ones dropped later", so nobody reads it as stored.
  • events_dropped_total has no event label, so when events are dropped, we can't tell which ones, e.g. whether it's only the frequent file.download records when the buffer is full. Since drops should be rare, an event label there would add only a few series.

And a question: would a count per tenant be useful for operators? As a label on emitted_total it would multiply the series by the number of tenants, which has no upper bound with multi-tenancy, so I wouldn't add it by default. Maybe as an option that is off by default, or we leave per-tenant numbers to the audit log itself, since every record has tenant.id and the stream subjects contain the tenant. What do you think?

@micbar

micbar commented Nov 24, 2026

Copy link
Copy Markdown
Member Author

@pbleser-oc Thanks for the thorough review! All points are in, one commit each, so you only need to look at the changes. I will squash them into the six commits before merging.

  1. Fixed. The event needs state in the update mask. That alone was not enough: the OCS hide and the mount point rename in the sharesstorageprovider send the unchanged state along. With audit on, the share provider now adds the state before the update to the response.
  2. Fixed. Failures are kept for 10s, expired keys are removed once per window, and a full map stops growing.
  3. and 4. We dropped strict. The ADR wants it to answer 503, but the middleware only sees a call after it happened. EmitterFromConfig rejects anything but best_effort now. Strict comes back when it can refuse a request before it acts.
  4. Fixed. Emit after Close drops and counts, and the data provider and the archiver close their emitter. The events middleware has no shutdown hook, so it still doesn't flush.
  5. Done, the middleware and the data provider use EmitterFromConfig now. The config keys stay.
  6. Done, good idea.

Nits: renamed to ItemSlot / ContextRegisterItemSlot and removed ContextSetItemType. Setting the item before the permission check is intended, a denied record should name the node.

@micbar

micbar commented Nov 24, 2026

Copy link
Copy Markdown
Member Author

@pbleser-oc Both done in one commit.

  • the help text of events_emitted_total now says it includes the events dropped later. closed belongs to that list too, a request still running at shutdown is counted as emitted and dropped.
  • events_dropped_total has an event label. The names come from the catalog, so it stays bounded.

No tenant label, I agree with you. The number of tenants has no upper bound, and every record has tenant.id and the stream subject contains the tenant. The audit service README in opencloud-eu/opencloud#3864 says that now, together with how to get the stored events from the two counters.

@micbar
micbar requested a review from pbleser-oc November 24, 2026 13:29
The record schema of ADR 0006, the event catalog with its codes and an emitter that writes the records into the JetStream stream `audit`. It publishes in the background and never blocks a call, a record that can't be stored is dropped and counted by event and reason. `best_effort` is the only mode for now. Nothing uses it yet.
The proxy sends client address, user agent, auth method, session and OIDC client in `X-Audit-Context`. A gRPC interceptor and the http auth interceptor put it into the context, ocdav passes it on to the data provider. Without the header nothing changes.
decomposedfs and posix report type, node ID, name and the path in the space through a slot in the context. The slot only exists with audit on, without it the drivers look nothing up.

Trashed nodes get their type when they are read, Type() can't read it at their trash path.
Files, folders, trash bin, versions, locks, shares, space members, public links and spaces, also failed and denied calls. One file per area. Shares, members and links carry recipient, role, expiration and whether a password is set, never the password.

The share providers add the permissions of a removed share to the response, for its role in the record. The user share provider adds the state before an update, so hiding or renaming a received share isn't recorded as an accept.
The data provider reports PUT and TUS uploads and downloads a client sent, marked by the audit header, with the path in the owner's space. A TUS upload keeps the request context and the public link of the request that created it in its session, the data requests carry only a transfer token.
One download record per file or folder in the archive.
@pbleser-oc

Copy link
Copy Markdown
Member

Thanks Michael, I looked at the changes and they all look good to me. For the flush of the events middleware's emitter on shutdown, I opened #1070 as a follow-up, so it doesn't hold up this PR.

@pbleser-oc

Copy link
Copy Markdown
Member

A note from trying to use this for something it doesn't cover yet: the audit entries for the versions the revision cleanup deletes (opencloud-eu/opencloud#4068). The cleanup deletes them inside the storage driver, in a background worker, after a change on disk, or from a CLI command, so the events middleware never sees it, and the driver doesn't get the audit settings. Details and a few questions in opencloud-eu/opencloud#4068 (comment): opencloud-eu/opencloud#4068 (comment)

Nothing that needs to change in this PR, as far as I can tell, but it might affect how storage-users passes the audit settings on, so I thought you'd want to know before merging.

AI assistance: Claude Code (claude-opus-5-5) wrote the first draft of this comment; I reviewed it.

@micbar

micbar commented Nov 25, 2026

Copy link
Copy Markdown
Member Author

@pbleser-oc Thanks! Can you approve the PR then? I will take care of #1070 after the merge.

@pbleser-oc pbleser-oc left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Approving as discussed. The open questions on opencloud-eu/opencloud#4068 are about adding to this, not about changing it.

@butonic butonic left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Read it commit by commit, on top of what @pbleser-oc already found. Three things look like bugs to me (archiver Stat when audit is off, archiver records with a guessed type, quota change hiding other space changes). The rest is not a blocker IMO.

The X-Audit-Context trust is fine, the proxy in opencloud-eu/opencloud#3864 drops what the client sends. AFAICT nothing sets ImpersonatedBy / imp yet though ... is that for a later part, or can it go?

One more, older than this PR so I can't comment inline: in pkg/rhttp/datatx/utils/download/download.go the parse ID error has no return. The 400 is written and we keep going with an empty ResourceId, so we write a second response, and with this PR the new audit code can emit a denied record for an empty target.

		rid, err := storagespace.ParseID(spaceID)
		if err != nil {
			handleError(w, &sublog, err, "parse ID")
			return
		}

@micbar

micbar commented Nov 25, 2026

Copy link
Copy Markdown
Member Author

@butonic Thanks for the review!

ImpersonatedBy and imp are gone. The ADR now has an ID and a name for it, it comes back with the part that fills it.

The return in download.go is added. It can't happen today though, ParseID only fails for an empty ID and that one takes the path branch.

@micbar
micbar requested a review from butonic November 25, 2026 21:26
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants