Mask audit entries before they are written

Merged
YO
4d ago
+1223-141

Summary

Audit entries keep the text of requests as typed: a terminal command with a password, a username typed into the sign-in form, a Git remote with a token. Nothing masked them, so secret values stayed in the local audit files and on the server's Audit page. This is task D1 of RFC 021 (tracker dagucloud/cloud#51): entries are masked when written, and every entry that records a failure carries result, so a later release can send masked entries to Dagu Console.

Changes

  • The audit store's Append masks every field except the ones Dagu generates or picks from a fixed set (id, timestamp, category, action, source, surface, result, resource_type, credential_type, credential_id, correlation_id). A text field added to Entry later is masked by default.
  • It masks the current values of dagu-managed secrets (disabled ones included) and GitHub, AWS access key, and Slack token formats in one pass, and marks the entry "masked": true. Matches that overlap are masked as one span, so a token inside a stored credential cannot leave the rest of the credential visible.
  • details stays valid JSON: a match inside a string is masked in place, and any other match, such as a secret that is a number or a whole object, masks the smallest value that holds it.
  • If the secret values fail to load, the entry is still written, masked with the values loaded last, but without the marker, so it is never sent. The load is retried 10 seconds later, or on the next entry after this server changes a secret, so a broken record is not read on every entry. A secret record that cannot be read, decoded, or decrypted counts as a failed load. A masker without a secret source, which is also the store's default without WithMasker, marks no entry either.
  • The values reload on the next entry after this server changes a secret, and within a minute of a change made by dagu profile or another server.
  • dagu secret resolve and the cleaner's audit_cleanup entry go through Append, so they are masked too.
  • MCP stops cutting resource IDs, error text, paths, client names, and argument names before Append, and Append cuts nothing.
  • login_failed entries now carry "result": "failed".
  • The audit reader skips a line that outgrows its 10 MiB buffer, as it skips a malformed line. Before, such a line made the Audit page fail for its whole day.
  • masking.Masker builds a trie of its values when it is created and masks every span any value matches, joining overlaps, instead of sorting the values on each MaskString call and replacing them one after another. Run logs and outputs change too: with secrets x-t and token-password, x-token-password was masked as x-******* and is now *******.
  • Run outputs and audit details share Masker.MaskJSON, which masks a document as written instead of decoding and re-encoding it. Stored outputs keep their key order and spacing.

On-disk entry, before and after, for a terminal command with a stored secret:

{"category":"terminal","action":"command","details":"{\"command\":\"export TOKEN=s3cr3t\"}", ...}
{"category":"terminal","action":"command","details":"{\"command\":\"export TOKEN=*******\"}", ..., "masked":true}

Core change

Append masks a copy of the entry before writing it, so the caller's entry is unchanged (internal/persis/file/audit/store.go:109). The audit masker walks the text fields of Entry by reflection, skipping the control fields, so a new field cannot be left out by mistake (internal/audit/mask.go:106). The secret masker finds the longest stored value at every offset with a trie, adds the token pattern matches, and joins the spans that overlap before masking each once (internal/cmn/masking/masker.go:132):

for i := range len(text) {
	if !m.values.starts(text[i]) {
		continue
	}
	if n := m.values.longestPrefix(text[i:]); n > 0 {
		spans = append(spans, span{start: i, end: i + n})
	}
}
for _, pattern := range m.patterns {
	for _, match := range pattern.FindAllStringIndex(text, -1) {
		spans = append(spans, span{start: match[0], end: match[1]})
	}
}
return joinSpans(spans)

For JSON, a span inside a string stays, and any other span widens to the smallest value holding it, written as the masked string (internal/cmn/masking/json.go:62).

The values reload when the secret store's in-process revision changes or after a minute, or 10 seconds when the last load failed (internal/audit/mask.go:131):

revision, now := m.source.Revision(), m.now()
maxAge := secretsMaxAge
if !m.loaded {
	maxAge = secretsRetryInterval
}
if !m.checkedAt.IsZero() && revision == m.revision && now.Sub(m.checkedAt) < maxAge {
	return m.secrets, m.loaded
}
values, err := m.source.CurrentValues(ctx)
m.revision, m.checkedAt, m.loaded = revision, now, err == nil

Testing

  • TestFailedSignInIsMaskedAndFailed (API, real server): creates a secret after the server started, fails a sign-in with its value as the username, and reads back a masked username and result: failed. It fails without the auth.go and stores.go changes.
  • TestMaskHidesSecretsOutsideControlFields: every text field but the control fields is masked. A secret whose value is denied leaves "result": "denied" intact, and details stays valid JSON (RFC 021 Verification 15).
  • TestMaskReloadsChangedSecrets: a change in this process is masked on the next entry; one made elsewhere is masked a minute later.
  • TestMaskHidesOverlappingTokensAndStoredValues: a stored value inside a token, a token inside a stored AWS key pair, and a stored value past a token's end are each masked whole. Before the fix, the key pair kept its secret access key in plain text.
  • TestMaskKeepsDetailsJSON, TestMaskMarksNothingWhenSecretsFailToLoad: details stays JSON with a numeric, quoted, or object-valued secret, including a key pair whose keys are not sorted (it kept the secret access key before the fix); an entry masked without the secret values carries no marker, and a failing store is read again only after 10 seconds or a change in this process. It read the store on every entry before the fix.
  • TestMaskMarksNothingWithoutSource: a masker without a secret source hides token formats and marks nothing. It marked the entry before the fix.
  • TestMasker_MaskString (overlap cases), TestMasker_MaskJSON: secrets overlapping at different offsets are masked whole; they left *******oken-password before the fix. JSON masking keeps the document's text outside the masked values.
  • TestSecretCurrentValuesFailsOnUnreadableRecord: a record file that cannot be parsed fails the load. It returned no error before the fix.
  • TestStore_QuerySkipsOversizedLines: entries around a line over 10 MiB still read. It failed before the fix with bufio.Scanner: token too long.
  • TestStore_AppendMasksTheEntryOnDisk and TestStore_CleanupEntryIsMasked: the file holds the whole masked entry with "masked": true, and so does the cleaner's entry (Verification 13 and 17, on-disk part).
  • TestResourceAuditDetailsKeepLongURIsWhole: a 300-byte URI with a token across byte 256 is kept whole (Verification 14, on-disk part).
  • TestSecretCurrentValues: current values only, disabled secrets included, and the revision changes on writes and deletes.
  • BenchmarkMaskWith5000Secrets: 6 µs per entry with 5,000 secrets on an M-series laptop. RFC 021 Verification 18 asks for under 1 ms.
  • Ran the touched packages with -race: masking, audit, persis/file/audit, persis/store, secret/..., service/mcp, service/frontend/file, service/frontend/api/v1, plus the masking and secret tests of runtime, runtime/agent, and cmd, and the other masker users in runtime/builtin and browserhost/writegate.

Performance

  • Per entry: one regexp pass and one trie scan per non-empty masked field, about 6 µs per entry with 5,000 secrets. details is scanned for JSON values only when a secret matches it. Audit entries come from user actions, not runs, so nothing grows with DAGs, runs, or workers.
  • Reload: one read per secret record (record IDs, then each record, so an unreadable record fails the load), only when an entry is written. It runs on the next entry after a secret changes in this process, and at most once a minute otherwise, or every 10 seconds while loads fail. Idle servers do no reload. There is no new ticker or watcher.
  • Memory: the trie holds one 12-byte node per byte of each secret value and its JSON-escaped forms, about 2.5 MB for 5,000 secrets of 40 bytes.
  • Run output masking: builds its trie once per masker instead of sorting the values on every call. On 64 KiB of log text it masks at about 2.2 GB/s with 10 or 5,000 secrets; main masks the same text at 330 MB/s with 10 secrets and 0.7 MB/s with 5,000. Building a masker of 5,000 secrets takes about 4 ms.
  • Stored: each entry gains "masked":true (14 bytes). MCP fields that were cut at 256 or 512 characters are stored whole.
  • Upgrade: none. Existing entries are left as they are.

Compatibility

  • Local audit files: new entries are masked and carry "masked": true. Older entries are unchanged and keep no marker, so the shipper in a later release never sends them. An older binary reads the new entries; it ignores masked.
  • Filters: a filter on a masked field, such as username, matches the masked text.
  • API: the audit API returns masked entries. Its schema does not change.
  • secret.Store: this internal interface gains CurrentValues and Revision.

Security

  • Secret values stop reaching audit files, the server's Audit page, and its API. Entries written before this release keep any secrets they hold.
  • Secrets from external providers (Vault, AWS Secrets Manager, and the others) are not masked, as RFC 021 states: they resolve only when a run starts.
  • Run logs and outputs mask secrets that overlap in the text as one span. Before, the secret that started later kept the part past the earlier one.

Review guide

  • Mechanical: the MCP sanitizeAuditString removal, maskOutputDocument calling Masker.MaskJSON, the test fake's two new methods, and the RFC sentences.
  • Judgment calls:
    • The control-field list in internal/audit/mask.go.
    • The one-minute reload for changes made by other processes, and the 10-second retry after a failed load.
    • Failing the whole load in CurrentValues on one record it cannot read, decode, or decrypt: entries stay unmarked, so unsent, until the record is fixed, rather than marked masked without that secret.
    • The trie and span join in internal/cmn/masking/trie.go and masker.go, and the JSON value widening in json.go, which replace the decode and re-encode of run outputs.
    • Writing an entry without the marker, rather than rejecting it, when the secret values fail to load.

Out of scope

  • Masking again at upload, and cutting fields to the upload limits: D4.