monoblok docs
Docs menu · Filtering and privacy

Examples

Filtering and privacy

Most examples reshape a stream. These decide what is allowed through: a WAF for NATS that scans payloads with a regular expression, holds back readings above the rolling p99 and flags a flooding subject, and a patchbay that strips and masks identifiers in patient records before they are forwarded.

A WAF for NATS#

Intermediate A web application firewall sits in front of a web server and decides which requests get through. This patchbay does the same job for a NATS cluster. Publishers connect to monoblok instead of the cluster and publish under in.>; three rules decide what continues as clean.> and what is reported on waf.>.

examples/waf.edn
;; A WAF for NATS: three rules that decide which messages are allowed
;; through to the cluster.
;;
;; Publishers connect to monoblok instead of the cluster and publish
;; under `in.>`:
;;   in.event.<source>    free-form or JSON events
;;   in.reading.<device>  numeric readings
;;
;; Only `clean.>` and `waf.>` are meant to leave this box. Pair the file
;; with (export :export ["clean.>" "waf.>"]) or an (import ...) tap and
;; the raw `in.>` traffic never reaches the far side.

;; Payload scan. An event carrying a known-bad fragment is not
;; forwarded; its subject (never its payload) is reported on
;; `waf.blocked`. Everything else moves from in.event.* to clean.event.*.
;; The test is one case-insensitive regular expression (the regex forms
;; are experimental): a script tag, a `${jndi:` lookup, or DROP TABLE
;; with any run of whitespace between the words. #"..." is EDN's raw
;; string, so backslashes are written as the regex wants them.
(on "in.event.*"
  (if (matches? #"(?i)<script|\$\{jndi:|drop\s+table" payload)
    (publish! "waf.blocked" subject)
    (publish! (subject-with "clean.event" (subject-token 2)) payload)))

;; Outlier gate. Forward a reading only while it sits at or below the
;; p99 of the last 100 readings from that device. The window includes
;; the current sample, so a reading that sets a new window maximum is
;; held back: about one message in a hundred on a steady device, every
;; message on a device whose readings only climb.
(on "in.reading.*"
  (when (<= payload-float (percentile 100 0.99 payload-float))
    (publish! (subject-with "clean.reading" (subject-token 2)) payload)))

;; Flood detection. State is per subject, so every publisher subject
;; gets its own five-second window for free. More than ten messages in
;; that window (a rate above 2 per second) publishes one "block"; the
;; first message after the subject has slowed down publishes one
;; "clear". The numbers are demo-sized; raise them for real traffic.
(on "in.*.*"
  (transition (> (rate :ms 5000 payload) 2)
    (publish! (subject-with "waf.flood" subject) "block")
    (publish! (subject-with "waf.flood" subject) "clear")))
shell
examples/waf.sh

Rules see a message's subject and payload. They do not see which connection published it, so every decision here is per subject, not per client.

Payload scan#

Experimental. The regex forms used here, matches?, re-capture and re-replace, are new; the forms and pattern syntax may change between releases.

The first rule is stateless. matches? tests the payload against one case-insensitive pattern, and if sends the message one of two ways. The (?i) prefix ignores case, \s+ accepts any run of whitespace between drop and table, and the three alternatives are a script tag, a ${jndi: lookup and a table drop. A blocked event is not forwarded and its payload is not repeated: waf.blocked carries only the subject it arrived on, so one subscriber sees every block without receiving the content that caused it.

soundcheck · examples/waf.edn
in   in.event.orders  {"note":"leave at the door"}
out  clean.event.orders  {"note":"leave at the door"}
in   in.event.orders  {"note":"<script>alert(1)</script>"}
out  waf.blocked  in.event.orders
in   in.event.signup  {"name":"Ada"}
out  clean.event.signup  {"name":"Ada"}
in   in.event.signup  {"name":"x; DROP TABLE users"}
out  waf.blocked  in.event.signup
in   in.event.orders  {"note":"<SCRIPT src=x>"}
out  waf.blocked  in.event.orders
in   in.event.signup  {"name":"x; drop   table users"}
out  waf.blocked  in.event.signup
in   in.event.orders  {"note":"${jndi:ldap://host/a}"}
out  waf.blocked  in.event.orders

The pattern is a string literal, written #"\s+" in EDN and '\s+' in a .yml file. There is no decoding, so a payload that hides <script behind URL or HTML escapes passes. Treat the rule as a cheap first filter, not a full inspection layer.

Outlier gate#

The second rule forwards a reading only while it is at or below the percentile of the last 100 readings from that device. There is no fixed limit to maintain: each device learns its own normal, because state is per subject.

soundcheck · examples/waf.edn
in   in.reading.pump7  412
out  clean.reading.pump7  412
in   in.reading.pump7  398
out  clean.reading.pump7  398
in   in.reading.pump7  405
out  clean.reading.pump7  405
in   in.reading.pump7  391
out  clean.reading.pump7  391
in   in.reading.pump7  388
out  clean.reading.pump7  388
in   in.reading.pump7  9000
in   in.reading.pump7  402
out  clean.reading.pump7  402
in   in.reading.pump7  395
out  clean.reading.pump7  395
in   in.reading.pump7  64000
in   in.reading.pump7  399
out  clean.reading.pump7  399

Ten readings in, eight out. Two things to know before relying on it:

  • The window includes the current sample. A reading that sets a new maximum for the window is above the p99 by definition, so it is held back. On a steady device that is about one message in a hundred. On a device whose readings only climb, it is every message.
  • Held-back samples still count. The 9000 above stays in the window for the next 100 samples and raises the p99 a little. A sustained run of large values therefore becomes the new normal. Add a fixed ceiling with (and (< payload-float 8192) ...) when there is a hard limit as well.

Flood detection#

The third rule watches how fast each subject publishes. rate counts messages per second over a five-second window, and transition turns the comparison into two messages: one block when the rate rises above 2 per second (more than ten messages in five seconds) and one clear when it falls back.

soundcheck · examples/waf.edn
in   in.event.chatty  tick 1
out  clean.event.chatty  tick 1
in   in.event.chatty  tick 2
out  clean.event.chatty  tick 2
in   in.event.chatty  tick 3
out  clean.event.chatty  tick 3
in   in.event.chatty  tick 4
out  clean.event.chatty  tick 4
in   in.event.chatty  tick 5
out  clean.event.chatty  tick 5
in   in.event.chatty  tick 6
out  clean.event.chatty  tick 6
in   in.event.chatty  tick 7
out  clean.event.chatty  tick 7
in   in.event.chatty  tick 8
out  clean.event.chatty  tick 8
in   in.event.chatty  tick 9
out  clean.event.chatty  tick 9
in   in.event.chatty  tick 10
out  clean.event.chatty  tick 10
in   in.event.chatty  tick 11
out  clean.event.chatty  tick 11
out  waf.flood.in.event.chatty  block
in   in.event.quiet  hello
out  clean.event.quiet  hello

The eleventh message from in.event.chatty crosses the threshold; in.event.quiet has its own window and stays quiet.

  • One window per subject, with no bookkeeping. State is per call site and subject. Each subject that has ever published holds one slot, so keep the subject space bounded.
  • The verdict does not stop the traffic. The ticks above are still forwarded as clean.event.chatty. waf.flood.<subject> is advice for something that can act on it, such as revoking the publisher's credentials. To cap the flow in the rule itself, put throttle in the forwarding thread.
  • clear needs a message. A rule runs when a message arrives, so clear is published on the first message after the subject has slowed down, not at the moment the window empties.

De-identifying records#

Intermediate A bedside gateway publishes one JSON frame per reading on ward.<ward>.<patient>, with the patient's name and record number alongside the measurements. The reporting system needs the measurements and must not receive the identifiers.

examples/deidentify.edn
;; De-identify patient telemetry before it leaves the ward network.
;;
;; A bedside gateway publishes one JSON frame per reading on
;; ward.<ward>.<patient>:
;;   {"name":"Ada Example","mrn":"000-11-2222","age":47,"hr":72,"spo2":97}
;; and nurses' free-text notes on notes.<ward>.
;;
;; Structured frames are de-identified by leaving things out: the rules
;; name the fields that may leave, coarsen the ones that identify, and
;; drop the patient token from the subject. Anything not named stays
;; behind, including fields added to the frame later. Free-text notes
;; cannot be allow-listed, so they are masked with regular expressions
;; instead (experimental, see the last two rules). Patchbay has no
;; hashing form, so no value is turned into a pseudonym.
;;
;; Only `clean.>` and `phi.>` are meant to leave this box. Pair the file
;; with (export :export ["clean.>" "phi.>"]) or an (import ...) tap.

;; Allow-list. Pull the clinical fields out by name and publish them
;; under the ward only: ward.icu.p4471 becomes clean.icu.hr. name and
;; mrn are never read, so they are never forwarded.
(on "ward.*.*" :reentrant true
  (do
    (-> payload (json-get "hr")   (publish! (subject-with "clean" (subject-token 1) "hr")))
    (-> payload (json-get "spo2") (publish! (subject-with "clean" (subject-token 1) "spo2")))))

;; Generalise. An exact age narrows a small ward down to one person, so
;; forward it snapped to the nearest ten.
(on "ward.*.*"
  (-> payload
      (json-get "age")
      (quantize 10)
      (publish! (subject-with "clean" (subject-token 1) "age-band"))))

;; Aggregate. The ward-level heart rate is the mean of the last 20
;; readings across every patient on that ward (the funnel pattern: the
;; first rule is re-entrant, so its output feeds this one).
(on "clean.*.hr"
  (publish! (subject-append "avg") :dp 0 (moving-avg 20 payload-float)))

;; Mask. Free text cannot be allow-listed field by field, so replace
;; the identifier shapes we know about: a record number like
;; 000-11-2222 becomes [MRN], and a date like 3/4/1980 becomes [DATE].
;; The regex forms are experimental. Masking only catches the shapes
;; written here: a name, an address or a record number in another format
;; passes straight through. The rule is re-entrant so the masked text,
;; published on `masked.notes.<ward>` (which is not exported), feeds the
;; next rule.
(on "notes.*" :reentrant true
  (-> payload
      (re-replace #"\b\d{3}-\d{2}-\d{4}\b" "[MRN]")
      (re-replace #"\b\d{1,2}/\d{1,2}/\d{2,4}\b" "[DATE]")
      (publish! (subject-with "masked.notes" (subject-token 1)))))

;; Tripwire. A note that still names an identifier label followed by
;; something the masks did not cover ("MRN 4471", "DOB: unknown") is
;; held whole, and only its subject is reported. Otherwise the masked
;; note is forwarded.
(on "masked.notes.*"
  (if (matches? #"(?i)\b(?:mrn|dob|nhs)[ :=#]*[a-z0-9]" payload)
    (publish! "phi.held" (subject-with "notes" (subject-token 2)))
    (publish! (subject-with "clean.notes" (subject-token 2)) payload)))
soundcheck · examples/deidentify.edn
in   ward.icu.p4471  {"name":"Ada Example","mrn":"000-11-2222","age":47,"hr":72,"spo2":97}
out  clean.icu.hr  72
out  clean.icu.hr.avg  72
out  clean.icu.spo2  97
out  clean.icu.age-band  50
in   ward.icu.p9020  {"name":"Bo Sample","mrn":"000-33-4444","age":81,"hr":90,"spo2":93}
out  clean.icu.hr  90
out  clean.icu.hr.avg  81
out  clean.icu.spo2  93
out  clean.icu.age-band  80
in   notes.icu  Comfortable overnight, obs stable
out  masked.notes.icu  Comfortable overnight, obs stable
out  clean.notes.icu  Comfortable overnight, obs stable
in   notes.icu  Call family re MRN 000-11-2222
out  masked.notes.icu  Call family re MRN [MRN]
out  clean.notes.icu  Call family re MRN [MRN]
in   notes.icu  Discharge review booked, born 3/4/1980
out  masked.notes.icu  Discharge review booked, born [DATE]
out  clean.notes.icu  Discharge review booked, born [DATE]
in   notes.icu  MRN 4471, check chart
out  masked.notes.icu  MRN 4471, check chart
out  phi.held  notes.icu

What to notice:

  • An allow-list, not a block-list. json-get reads the fields the rule names. name and mrn are not removed; they are never read. A field the gateway starts sending next month is left behind too, where a pattern that hunts for identifiers would have to learn about it first.
  • The subject is data too. ward.icu.p4471 identifies a patient as surely as the name does. The rules publish under clean.<ward>.…, so every patient on a ward shares one output subject.
  • Coarsen what identifies. quantize 10 snaps age to the nearest ten. round does the same job for coordinates.
  • Aggregate where a total is enough. The ward average is a funnel: the first rule is :reentrant true, so its clean.icu.hr output feeds the moving-avg rule.
  • Free text gets masked, then checked. A note cannot be allow-listed field by field. The first notes rule uses re-replace (an experimental form) to swap a record number shaped like 000-11-2222 for [MRN] and a date like 3/4/1980 for [DATE], then hands the masked text to a second rule through masked.notes.<ward>. That second rule holds any note that still names MRN, DOB or NHS followed by something the masks did not cover, such as MRN 4471, and reports only the subject.
  • Masking only catches the shapes it is given. A name, an address, or a record number in another format passes straight through. The allow-list above is still the stronger tool wherever the data has fields.

Structured frames are de-identified by omission, not obfuscation. Patchbay has no hashing or tokenising form, so it cannot turn a record number into a stable pseudonym. If downstream needs to follow one patient across messages, issue the pseudonym at the gateway and put it in the subject. Rules like these reduce what leaves the ward; they are not a compliance control by themselves.

shell
examples/deidentify.sh

Making it a gate#

The rules above only decide. What makes the patchbay a gate is that downstream consumers can reach only the approved output. Where publishers and subscribers connect determines how to arrange that:

  • Front door. Publishers send raw messages to an isolated monoblok instance, where the rules produce clean output. A top-level export relays only the selected output subjects to NATS, where downstream consumers subscribe. Keep raw subjects out of the export filters and give publishers no direct path to the cluster:
EDN
(export
  :servers ["nats://nats.internal:4222"]
  :export  ["clean.>" "waf.>" "phi.>"])
  • Alongside the cluster, with local consumers. With import, monoblok subscribes to raw subjects on NATS. Downstream consumers connect to monoblok, where imported messages are private patchbay input: local subscribers see only what the rules publish. No export is needed for these local consumers.
  • Alongside the cluster, with results sent back. Use both import and export: import reads the raw subjects into the rules, and export forwards the approved output back to NATS on separate subjects such as clean.>. Publishers and downstream consumers stay connected to NATS. Import alone does not send the results back. The import example shows the combined configuration.

In either alongside arrangement, the raw messages are already on NATS. Import does not hide them from other clients on that cluster. To make this a gate, restrict downstream consumers to the approved output subjects with NATS permissions and prevent them from accessing the raw subjects. When importing and exporting on the same cluster, keep input and output subjects separate and set :origin-header true on both forms to avoid consuming your own exports.

Both are described in Export, import and JetStream, with runnable versions in NATS integration.

MIT licensed · © 2026 Alex Reid
Lexvica offers solutions built with monoblok.