Log Masking¶
Guide: an elective filter for the application log, with its rules in a configuration file.
At a glance
- What - the extension crate
mercury-log-masking(extensions/log-masking): a logger that wraps the engine's and applies the rules of yourlog-masking.yamlto a line before the engine's logger writes it.- How - add the crate, put a
log-masking.yamlinto your resources, and calllog_masking::install()before the engine starts. A rule is a name, a regular expression and a replacement.- Elective - nothing is masked until you adopt it, and it costs time on every line.
- A best effort - it masks what your rules match, in what it reads, and nothing else. It is not a detector of credentials or of personal data, and no rule set is complete.
- For an installation whose log must not hold certain values that its own lines, or its users' data, may carry.
Everything on this page describes this repository's engine. It is the twin of the Java engine's
extensions/log-masking: the same rule file, the same rules for what a rule replaces, and a vector file that
the two repositories share. What differs is how the filter is put in place, since the Java engine logs through
log4j2 and this engine through the log crate.
The engine masks what it writes itself where it can tell that a value is a credential: the user id and
password of a URL, four credential headers of the API fetcher, the value of a refused setting. It does not know
what your own lines hold. A line such as log::info!("customer {} granted with premium class", customer_email)
is yours, and so is the decision whether an e-mail address may be in the log. This crate is the place for that
decision: a small filter that you adopt as it is, extend with rules of your own, or replace with a logger of
your own.
It is a best effort. A rule masks the text that its pattern matches. A value that no rule matches is written as it is, and so is everything that the filter does not read (below). Treat it as one layer: the first is not to log a secret at all.
Adopt it¶
1. The dependency.
x.y.z denotes the current Mercury version shown in the root Cargo.toml.
2. The rule file. Copy the sample extensions/log-masking/sample/log-masking.yaml into the resources
folder of your application and make it yours. The sample is a few labelled rules to start from. It is not a
list of what is personal data: what the lines of your installation hold is for you to know.
3. The call. Write the application's main yourself, in place of platform_core::auto_start_main!(), and
install the masking logger before the engine starts:
fn main() -> Result<(), platform_core::AppError> {
// the application's own resources/ folder, as auto_start_main!() sets it
platform_core::resources::prepend_resource_root(concat!(env!("CARGO_MANIFEST_DIR"), "/resources"));
// reads classpath:/log-masking.yaml; an error here stops the start
log_masking::install()?;
platform_core::AutoStart::run()
}
The log crate takes one logger for a process, and the engine's logging::init() does nothing when one is in
place. So install() comes first: it builds the engine's logger as init() does, from log.format and
log.level, puts the masking logger around it, and sets the process's maximum level from it.
install_from(location) names another rule file, with the prefix classpath: or file:.
When the application starts, one line says what is in force:
A logger of your own¶
The engine's logger, platform_core::logging::PlatformLogger, is public for this purpose. An application that
wants another step than masking, or masking of its own design, writes a logger with the engine's inside and
installs it the same way:
let inner = PlatformLogger::from_config();
let level = inner.max_level();
log::set_boxed_logger(Box::new(MyLogger { inner }))?;
// the maximum level of the process, which init() sets only for its own logger
log::set_max_level(level);
MyLogger implements log::Log: it asks inner.enabled(..), reads or rewrites the record, and hands it to
inner.log(..), which writes the line in the configured format. log_masking::MaskingLogger is that shape
with the rules applied, and it wraps any log::Log.
The rule file¶
log-masking.yaml is written in YAML 1.2.2.
masking:
max.length: 8192
rules:
- name: 'bearer token'
pattern: 'Bearer\s+([A-Za-z0-9._~+/=-]+)'
- name: 'secret in name=value text'
pattern: '(?:password|passwd|secret|token|api[_-]?key)["'']?\s*[=:]\s*["'']?([^\s"'',;&]+)'
ignore.case: true
- name: 'e-mail address'
pattern: '[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}'
replacement: '<e-mail>'
- name: 'card number in groups of four digits'
pattern: '\b\d{4}[ -]\d{4}[ -]\d{4}[ -]\d{4}\b'
replacement: '<card number>'
| Key | Meaning | Default |
|---|---|---|
masking.max.length |
The longest text, in characters, that a pattern runs against | 8192 |
masking.rules[] |
The rules, applied in the file's order, each to the result of the one before | at least one |
name |
What the rule is for; an error text names the rule by it | required |
pattern |
A regular expression | required |
replacement |
The text written in place of what the rule replaces; a literal text, not a template | *** |
ignore.case |
true to match letters in either case |
false |
What a rule replaces. What its pattern matches or, when the pattern has a capture group, its first group
only. So a rule can keep a name and mask its value: with the second rule above, password=sample-word is
written password=***. A match in which the first group took no part is left as it is, and so is a span of no
characters.
The order matters. Each rule reads what the rules before it wrote. In the sample the rule for a named
secret comes before the rule for an e-mail address, so token=someone@example.com is written token=***.
max.length. A text of more than max.length characters is cut at that length before the rules read it,
and a mark follows what is written:
What the rules did not read is not written as if they had. The regular-expression engine of this runtime reads a text in a time that grows with its length and no faster, so the bound matters less here than in the Java engine; it is the same key in the same file, and it bounds what a line costs.
Writing a pattern¶
The same rule file is read by the Java engine's module, so keep a pattern to what the regular-expression engines of the runtimes share:
- In: literals, character classes,
\d,\w,\s,\b,., quantifiers (greedy and lazy), alternation, groups - capturing and(?:...)- and the anchors^and$. - Not in: look-ahead and look-behind, back-references, possessive quantifiers and atomic groups, named
groups, inline flags such as
(?i), Unicode property classes such as\p{L}, and set operations inside a class (&&,--,~~). Write a literal{,},[or]with a backslash.
The subset is declared here and not enforced by a check. This runtime's engine, the regex crate, has no
look-around and no back-reference at all, so a pattern with one does not compile and stops the start; it accepts
some of the rest, and a rule that uses it is a rule for this runtime only.
Where the engines differ, write the rule so that it does not depend on it:
- Outside ASCII.
\d,\w,\sand\bare Unicode in this engine and ASCII in the Java engine. A rule that must match a letter or a digit outside ASCII names its characters in a class of its own. - A line break. A pattern is written for a text on one line.
.matches any character but a line feed, in both engines.$matches only at the end of the text in this engine, and also before a line feed at the end in the Java engine.
What it reads, and what it does not reach¶
It reads:
- A line's message as a text.
log::info!("customer {} granted with premium class", customer_email)is writtencustomer <e-mail> granted with premium classwith the sample rules. - Each text value of a structured message, at any depth. In this runtime a structured message is a message
that is a JSON object, which the JSON formats write as an object, and the trace record is one. With
log::info!("{}", json!({"customer": customer_email, "class": "premium"}))every format writes the object with"customer": "<e-mail>". The message keeps its shape and its keys. A structured message that a rule changed is written again from its values, so its keys are in the order of the JSON formats and its spacing is the compact one.
It does not reach:
- The key of a value in a structured message. A rule sees each text value on its own. The sample's rule
for a named secret masks
password=sample-wordin a text and does not see an object's entrypasswordwith the valuesample-word. Mask such a value by a rule for its shape, or do not log it. - A value in a structured message that is no text: a number,
trueorfalse. - The
contextblock of the JSON formats, which the engine's logger adds after the step: the correlation id, the trace ids, the trace path and the keys ofupdate_context. A path parameter and a value that the application puts into the context are written there as they are. - A line that does not pass through the logger: what a crate or the application prints to the console itself.
- What leaves the application by another way: the spans that the OpenTelemetry forwarder exports, an error response.
An error has no place of its own in a record of the log crate: its text is part of the message, and is read
with it.
The trace record passes through the step. distributed.tracing hands its record to the installed logger,
whatever the level, so your rules read the record's values, the annotations among them, and the record keeps
its shape (see Observability).
When the rules cannot be used¶
A rule file that is not there, that is not a YAML document, or that holds a rule the crate cannot use is an
error of install(), and nothing is installed. Returned from main, as above, it stops the start of the
application. A filter that quietly filters nothing is worse than none. The error names the file, the key at
fault and the rule:
log-masking: classpath:/log-masking.yaml: 'masking.rules[1]' (card number) has a pattern that does not compile - unclosed group
Refused: a file without the masking section or without a rule; a rule without a name or a pattern; a pattern
that does not compile; a key that is not one of the file's, such as a rule option with a slip in its name; a
max.length that is not a whole number of 1 or more; a replacement that is not a text; an ignore.case that
is not true or false.
What it costs¶
The step runs on every line that the engine's logger would write; a line that the level drops costs no rule. Measured on a developer's laptop with a release build, through a logger that formats each message and writes nowhere, with an even mix of a plain line, a line with an e-mail address and a trace record:
| Lines per second | |
|---|---|
| Without the masking logger | about 26,000,000 |
| With the four sample rules | about 850,000 |
That is about 1 microsecond for a line. A logger that writes to a console spends more than that on a line of its own accord. The figures depend on your rules and on your lines; the measurement is the crate's test:
Design notes¶
- Why elective. A detector of credentials or personal data in the engine would be a set of patterns that is never complete, it would run on every line of every installation, and it would read as a promise. What a line may hold is an installation's decision, so the rules are its file.
- Why a public logger. The
logcrate has one logger for a process and no chain of filters. A logger that wraps the engine's is the extension point, and it serves any other step an application wants on its lines. - Why the first group. A log is read by people who search it.
password=***says that a password was there; a line with the whole match replaced does not. - The same file in the Java engine. Its module
log-maskingreads the samelog-masking.yaml, andlog-masking-vectors.json, byte for byte the same in the two repositories, holds the sample rules to the same result in both.
Related¶
- Observability - the trace record, the log formats and the application log context.
- Configuration Keys -
log.formatandlog.level. - Built-in Skills - Credentials - security by design: what the engine masks in its own lines.