Runtime

Sensitive Data Lineage

@axiljs/runtime tracks tSensitive and tRedact values loaded by the ORM and reports a violation when one reaches a response, log, event, queue job or AI request that was not allowed.

9 min readUpdated DocumentationEdit this page
On this page13

A field marked @tSensitive('PII') is a promise: this value does not leave the service by accident. Sensitive data lineage checks that promise. Once the ORM loads such a value, @axiljs/runtime remembers it for the rest of the request. If the value then reaches an exit that has not been allowed (an HTTP response, a log entry, an event, a queue job or an AI request), the runtime reports a tSensitive intent violation. An email address that ends up in a log line or an LLM prompt fails a test instead of reaching a third party.

Note

New in 0.4.0. Lineage is part of @axiljs/runtime; the other packages report to it through optional hooks and do not depend on it.

TypeScript
TS
1import { tSensitive } from '@axiljs/decorator'
2import { BaseModel, Column, Entity, PrimaryKey } from '@axiljs/orm'
3import { requestContext } from '@axiljs/runtime'
4
5@Entity('users')
6class User extends BaseModel {
7  @PrimaryKey() id!: number
8  @Column() @tSensitive('PII') email!: string
9}
10
11app.use(requestContext())   // lineage is per request; nothing is tracked outside a context
12
13app.get('/users/:id/summary', async (req, res) => {
14  const user = await User.find(req.params.id)       // user.email is now tracked
15  logger.info('summary', { email: user.email })     // violation: User.email (PII) reached log
16  res.success({ id: user.id, email: user.email })   // violation: User.email (PII) reached response
17})

How it works

ORM loads an entity or row
tSensitive / tRedact values tracked in the request context
Exit checks its payload with checkSink()
Sink allowed or value masked
Payload leaves
Tracked value found
tSensitive violation
Values are tracked per request and compared verbatim at each exit.
  1. Sources. A value is tracked when it is loaded from a field that carries @tSensitive(classification) or @tRedact(...) metadata.
  2. Request scope. Tracked values live in the request context of the current request. Without requestContext() (or runWithContext()), nothing is tracked.
  3. Sinks. Each exit scans the payload it is about to send for tracked values.
  4. Report. A match that is not allowed becomes a tSensitive intent violation, handled according to the intent mode.

What is tracked

Field metadataClassification in the report
@tSensitive('PII'), 'PHI', 'PCI', 'SECRET', 'INTERNAL'The given classification
@tRedact(...)REDACT

The origin of a value is Class.property, for example User.email. Array-valued fields track each item.

Only values that are specific enough to match reliably are tracked:

  • Strings of at least 4 characters after trimming.
  • Numbers (and bigints) with at least 4 digits. Numbers match only on digit boundaries, so 1234 does not match inside 912345.

Sources

@axiljs/orm reports every entity a BaseModel hydrates and every row a BaseRepository loads. Column names are mapped back to property names, so a column email_address on the property email is still recognised. Objects, arrays, maps and nested entities (eager-loaded relations, wrapper objects) are walked with a depth limit and are cycle-safe.

Values from anywhere else (an HTTP client, a cache, an object built in code) are not tracked automatically. Report them with trackSensitive():

TypeScript
TS
1import { trackSensitive } from '@axiljs/runtime'
2
3const profile = await crm.getProfile(id)   // a class instance with tSensitive fields
4trackSensitive(profile)
5
6// Plain objects carry no metadata: describe them with an entity class,
7// and map properties to keys when the keys are column names
8trackSensitive(rows, { entity: User, columns: { email: 'email_address' } })

trackSensitive(value, hint?) is a no-op outside a request context, when lineage is disabled, or when value is not an object.

HintDescription
entityEntity class whose tSensitive / tRedact property metadata describes plain rows
columnsProperty name to column name, for rows keyed by column

Sinks

Each exit calls checkSink(sink, payload, target?) before anything is sent:

SinkWhere it is checked
response@axiljs/core: res.json(), res.text(), res.html(), res.send() and every envelope helper (res.success(), …) before the body is serialized
log@axiljs/observability: ConsoleTransport and FileTransport; redactingTransport() after redaction
event@axiljs/events: EventBus.emit()
queue@axiljs/queue: Queue.add() and addMany()
ai@axiljs/ai: provider requests (OpenAI, Anthropic, Gemini, Ollama; completions, streams and embeddings)

The payload is scanned for tracked values in nested strings, numbers, object keys, toJSON() output, buffers and already-serialized JSON text. A value masked or hashed by redact() no longer matches and passes.

Custom sinks

checkSink() returns the leaks it found (SensitiveLeak[], each { origin, classification, sink }, never the value), so your own exits can use it with their own sink name:

TypeScript
TS
1import { checkSink } from '@axiljs/runtime'
2
3async function sendMail(to: string, body: string) {
4  checkSink('email', { to, body })   // reports a tSensitive violation if a tracked value is inside
5  await mailer.send(to, body)
6}

The optional target names the violation; by default it is the current route (GET /users/42/summary), else the sink name. An empty array is returned when nothing tracked reached the sink, when the sink is allowed, when the intent mode is off, or outside a request context.

Modes

Lineage uses the intent mode: configureIntent({ mode }) or the AXIL_INTENT_MODE environment variable.

ModeBehaviourDefault
enforceThe sink throws IntentViolationError before anything is written: a response becomes the app's error response, emit() and Queue.add() reject, the AI request is not sent. Loggers never throw, so the leaking log entry is dropped and the violation recordedWhen NODE_ENV is not production
warnThe violation is recorded, emitted as runtime.intent.violation and printed once per target and leak; the payload is sentWhen NODE_ENV=production
offNo sink checks

configureLineage({ enabled: false }) turns off tracking as well as the checks.

Terminal
AXIL_INTENT_MODE=warn npm start # record leaks without failing requests

What the client sees

In enforce mode a leaking response is replaced by the error response of @axiljs/core: status 500, code INTENT_VIOLATION. Outside production the message names the route, the origin and the sink:

JSON
JSON
1{
2  "error": {
3    "code": "INTENT_VIOLATION",
4    "message": "GET /users/42/summary violates tSensitive: User.email (PII) reached response"
5  }
6}

In production the default error handler hides the message of 500 errors (Internal server error). The value itself never appears in the violation, the error or the warning. Violations are also listed by getIntentViolations() and runtimeReport().

Allowing an exit

Returning a user's own email from a profile endpoint is legitimate. Say so explicitly, in one of three ways.

For one call tree. allowSensitive(sinks, fn) allows the sinks only inside fn (synchronous or asynchronous) and returns its result:

TypeScript
TS
1import { allowSensitive, getContext } from '@axiljs/runtime'
2
3app.get('/me', async (req, res) => {
4  const me = await User.find(getContext()!.user!.id)
5  allowSensitive('response', () => res.success(me))
6})

For the rest of the request. Without fn, the sinks stay allowed until the request ends, for example from a route middleware. Outside a request context this form does nothing.

TypeScript
TS
const allowResponse: MiddlewareFn = (_req, _res, next) => { allowSensitive('response'); next() }

app.get('/me', authenticate(jwt), allowResponse, getMe)

sinks is one sink name or an array; '*' allows every sink.

By origin, without code at the call site. configureLineage({ allow }) takes a list per sink:

TypeScript
TS
1import { configureLineage } from '@axiljs/runtime'
2
3configureLineage({
4  allow: {
5    response: ['User.email'],   // one field
6    log: ['User.*'],            // every field of a class
7    ai: ['INTERNAL']            // a classification
8  }
9})

An entry matches an origin label (User.email), every field of a class (User.*), a classification (PII) or everything (*). Entries listed under the sink name '*' apply to every sink. Each call with allow replaces the previous allow-list.

Options

configureLineage(options) changes the settings that are passed and keeps the others:

OptionDefaultDescription
enabledtrueTurn tracking and sink checks on or off
allownoneOrigins allowed per sink (see above). Replaces the previous allow-list
minLength4Minimum string length, or number of digits, to track
maxValues500Maximum values tracked per request
maxDepth8How deep sources and payloads are walked

resetLineage() restores the defaults and clears the allow-list (mainly for tests).

trackedSensitiveOrigins() lists the origin labels tracked in the current request, never the values:

TypeScript
TS
import { trackedSensitiveOrigins } from '@axiljs/runtime'

trackedSensitiveOrigins()   // ['User.email', 'User.phone']

Lineage and redaction

Redaction and lineage use the same metadata and work together:

  • redactingTransport() masks tSensitive fields before the entry is written, then checks the redacted entry. A masked value no longer matches, so redacted logs pass.
  • redactResponses() keeps tSensitive fields in responses by default. Since 0.4.0 such a response is a lineage violation unless the exit is allowed. Allow it where the value belongs in the response, or mask the field.
  • A partial mask (visibleChars) or a hash is a different value from the original and passes.

Upgrading from 0.3.x

Apps that use @axiljs/runtime and return a @tSensitive field in a response now get a tSensitive violation for that response, which fails the request in enforce mode (the default outside production). For each such endpoint:

  • allow the exit where it is intended, with allowSensitive('response', …) or configureLineage({ allow });
  • mask the field with redact(); or
  • set AXIL_INTENT_MODE=warn while migrating, and work through the recorded violations.

@axiljs/* ranges move to ^0.4.0. In 0.x versions ^0.3.x does not include 0.4, so update all @axiljs/* packages together.

Limitations

  • Only strings of at least 4 characters and numbers with at least 4 digits are tracked; shorter values would match too much.
  • Tracking is by exact value. A value that is transformed (hashed, encrypted, split, re-encoded, lower-cased, base64) is not recognised.
  • A value that leaves through an exit without a check (raw sockets, fetch, files written directly, res.raw) is not seen.
  • Tracked values live in the request context of one process. They do not follow a value into a queue worker or another service, and they are capped per request (maxValues).
  • Thrown errors are not a checked sink: an error message carrying a tracked value is caught only when it is written as a response or log entry.
  • Custom log transports are checked only when wrapped in redactingTransport() or when they call checkSink('log', entry) themselves.
  • Packages report through globalThis[Symbol.for('axiljs.sensitive.observe')] and globalThis[Symbol.for('axiljs.sensitive.sink')], so lineage is active only when @axiljs/runtime is loaded in the process.

Was this page helpful?

Help improve the documentation

AxilJS is open source and documentation improvements are welcome.

AxilJS DocumentationMIT License · Built by SyntaxilitY