Send audit entries to Dagu Console

Merged
YO
3d ago
+1110-58

Summary

RFC 021 sends a server's audit entries to Dagu Console, so the record of who did what outlives the server. D3 (#4077) built the loop that reads them in batches, but it had no sender and nothing started it. This is the first half of task D4 (tracker dagucloud/cloud#51). It adds the cloud.audit setting, the upload format, the HTTP sender with Console's status handling, and starts the shipper in dagu server and dagu start-all. The drain on graceful stop and the stopped gap follow in D4b, which changes server shutdown and gets full-ci.

Changes

  • cloud.audit (DAGU_CLOUD_AUDIT) is off (the default), changes, or all. The config schema knows it; the docs come with D5.

  • The shipper starts only when cloud.audit sends, local audit (audit.enabled) is on, and a license manager runs. Otherwise nothing reads the audit files.

  • On each pass it checks, in memory, that the server is connected to Dagu Console with a license whose audit feature is on, and that Console has not refused that license. If not, it reads nothing and frees its lease.

  • Before an entry is sent, it is:

    • masked again with the current secret values, so a secret added after the entry was written does not leave the server;
    • stripped of NUL, which becomes U+FFFD;
    • cut field by field: category and action to 64 bytes, other fields but details to 256, with the cut fields listed in "truncated";
    • cut in details to the longest start that keeps the encoded entry within 16 KiB.
  • If the secret values fail to load, the batch waits 10 seconds unsent.

  • Batches go as gzip JSON to POST {cloud_url}/api/v1/servers/audit, with the heartbeat secret as a Bearer token and the license and server IDs as headers. A batch over 4 MiB goes as several requests, its gap with the first.

  • Console's answers:

    AnswerShipper
    200Saves the position; logs any IDs Console refused
    413Halves the request; a single entry still refused goes as a rejected gap, and the next entries go
    429, 503Holds sending for Retry-After
    401, 410Holds sending until the license or server ID or heartbeat secret changes
    402Asks again in an hour
    Other, or no answerBacks off from a minute to five

    The batch is kept and sent again as built (D3), so a held server reads no files.

{"protocol":1,"entries":[{"id":"…","timestamp":"…","category":"user","action":"login_failed","result":"failed","username":"ops","masked":true,"truncated":["username"]}],"gap":{"id":"…","reason":"deleted","from":"…","to":"…"}}

Core change

A pass sends only while connected and licensed, and a refused batch holds the pass as Console asked (internal/cloudreport/audit.go):

creds, ok := s.connected(ctx)
if !ok {
	// No file I/O, and the lease goes to a process that can send.
	s.release()
	return
}
if !s.hold(ctx) || s.now().Before(s.heldUntil) || !s.load(ctx) {
	return
}
...
if err := s.send(ctx, creds, pass.batch); err != nil {
	s.pending = pass
	s.refused(ctx, creds, err)
	return
}

Each entry is masked again before it is cut, so a cut never leaves part of a secret (internal/cloudreport/audit_upload.go, prepare):

wire := auditWireEntry{Entry: *entry}
u.masker.Mask(ctx, &wire.Entry)
if !wire.Masked {
	return auditUpload{}, false
}
// NUL to U+FFFD, then each field cut to its limit, named in Truncated
...
data, _ := json.Marshal(wire)
if len(data) > auditEntryBytes && wire.Details != "" {
	data = fitDetails(&wire)
}

Testing

All against a fake Console over HTTP that decompresses and records each request:

  • Masking and cutting:
    • TestAuditSenderMasksAgainBeforeCutting (RFC 021 Verification 13 and 14, upload part): a secret added after the entry was written is masked in workspace, username, user_id, details, and a 300-byte URI whose secret crosses byte 256.
    • TestAuditSenderCutsFieldsToTheirLimits (Verification 19): a long username is cut to 256 bytes at a character boundary, action to 64, both are listed in truncated, and NUL becomes U+FFFD.
    • TestAuditSenderCutsDetailsToFitTheEntry (Verification 20): 8 KiB of backslashes, which doubles when encoded, is cut so that the entry encodes to at most 16 KiB and within 64 bytes of it.
  • Splitting:
    • TestAuditSenderHalvesWhatConsoleFindsTooLarge (Verification 21): one oversized entry becomes a rejected gap, and the entries around it are stored.
    • TestAuditSenderSplitsLargeBatches: 600 entries of 10 KiB go as several requests of at most 4 MiB, the gap in the first only.
  • Holds:
    • TestAuditShipperHoldsAsConsoleAnswers (Verification 5): 503, 429, 402, and 500 hold for Retry-After, an hour, or the backoff, and the same entries go after.
    • TestAuditShipperWaitsForANewLicense: 401 and 410 hold until the heartbeat secret changes.
    • TestAuditSenderHoldsWhileSecretsFailToLoad: no request while the secret values fail to load.
  • Gating:
    • TestAuditShipperIdlesWithoutConsole: after the connection, or the license's audit feature, goes away, no feed read happens and the lease is free.
    • TestStartCloudAudit (Verification 8): no shipper at off, unset, with local audit off, or without a license manager; one with a connected license.
  • Config: TestLoad_CloudAudit and TestConfigSchemaCloudAudit.
  • Mutation checks: I broke each rule in turn and a test failed each time. The rules were: no upload mask, dropping a refused entry, ignoring Retry-After, treating 401 as a wait, keeping the lease when disconnected, and keeping NUL.
  • Commands run: go test -race on internal/cloudreport, internal/cmn/config, internal/cmn/schema, internal/persis/file/audit, and internal/audit, plus the cmd tests above, and golangci-lint on the packages for Linux and Windows.

Performance

Risk: a new periodic task and outbound requests, off by default.

  • At off, or without local audit or a license manager: nothing starts.
  • While not connected, not licensed, or refused: a pass every 5 seconds reads two values in memory. It does no file I/O and holds no lease.
  • While sending: the D3 costs apply: one stat every 5 seconds on the lease holder, one listing a minute, and a lease heartbeat every 20 seconds.
    • Requests go only when entries arrive, at most one batch per pass, plus the next batch at once after a full one.
    • About 1.6 KB per entry as JSON, about 80 bytes after gzip. Requests are at most 4 MiB decompressed.
  • While held: no requests until the hold ends: Retry-After for 429 and 503, an hour for 402, until the license changes for 401 and 410, and from one minute up to five otherwise.
  • Masking again: one pass per text field of each entry per attempt, about 5 µs per entry with 5,000 secrets.
  • Scale: nothing grows with DAGs, runs, steps, workers, or browser tabs.
  • Upgrade: none. The state file and lease under <data_dir>/cloud/ appear only once sending starts.

Compatibility

  • cloud.audit is new and off by default, so existing servers change nothing.
  • An older binary ignores the setting and audit-state.json.
  • Console's endpoint (dagucloud/cloud A7) is not live yet. No release ships this before it is (gate GR on the tracker).

Security

  • What leaves the server, only when an administrator sets cloud.audit, the license includes audit logs, and the server is connected: masked audit entries and gaps.
  • Masking: entries are masked at write (#4050) and again before sending with the values current then.
  • Credentials: they travel in headers, so Console can check them before it reads the body.

Review guide

The diff is about 1,100 lines, about half of it tests.

  • Mechanical: the config key, schema, and loader tests; the test updates for the sender's new signature; config.AuditLevel replacing D3's private level type.
  • Judgment calls:
    • New exported API: cloudreport.StartAudit, AuditOptions, and AuditFeed, so cmd can start the shipper.
    • Lease when gated: the shipper releases the lease while it cannot send, so another process that can send takes it.
    • details: cut by a binary search for the longest start that fits, instead of by the encoded excess, which over-cuts escaped text.
    • An entry still over 16 KiB with empty details: only extreme escaping causes this. It is sent anyway, and Console records its own rejected gap for it.
    • Lease threshold: the audit lease's stale threshold is 2 minutes, since a batch can take several requests.

Out of scope

  • The drain on graceful stop and the stopped gap: D4b, with full-ci.
  • The report's backlog, the settings page, and the cloud.audit docs: D5.

Summary by cubic

Sends a server's audit entries to Dagu Console so the audit record survives the server.

  • Adds the cloud.audit setting (DAGU_CLOUD_AUDIT): off (default), changes, or all.
  • The shipper starts in dagu server and dagu start-all only when the level sends, local audit is on, and a connected license includes the audit feature; otherwise nothing reads the audit files. Each batch of a pass re-checks this gate and frees the lease once it fails.
  • Entries are masked again with the current secret values before sending, NUL becomes U+FFFD, and fields are cut to the format's limits.
  • Batches post as gzip JSON to /api/v1/servers/audit, with the heartbeat secret as a Bearer token and license and server IDs as headers.
  • Console's answers drive sending: 413 halves the request, 429/503 wait for Retry-After, 401/410 hold until the license or heartbeat secret changes, 402 waits an hour, and other failures back off from a minute to five.
  • Console's endpoint is not live yet, so nothing ships until it is.

Summary by CodeRabbit

  • New Features
    • Added optional cloud audit reporting with off, changes, and all levels. “Changes” excludes successful reads; “all” includes every audit entry.
    • Cloud reporting requires local auditing to be enabled, a qualifying license, and a connection to Dagu Console. Sensitive values are masked before sending.
    • Reporting pauses or retries after temporary service issues and resumes when required credentials or conditions change.
  • Documentation
    • Added configuration guidance for cloud audit levels and reporting requirements.