Expressions¶
All rule expressions use the expr expression language.
The expr playground can be used to test various expressions and to familiarize yourself with the syntax.
Expr provides various built-in functions and operators which can be used inside all expressions.
Expression Fields¶
This section documents how events can be interacted with in the different expression fields.
Match¶
The first expression evaluated for each incoming event. Events that don't match are dropped and won't be processed further.
Supported rule types:
| Event | Aggregation |
|---|---|
Event fields are accessible via the event prefix. The expression must return a bool value.
Helper functions:
| Function | Returns | Description |
|---|---|---|
iEqual(s string, t string) |
bool |
Case-insensitive string equality. |
iHasPrefix(s string, prefix string) |
bool |
Case-insensitive prefix check. |
iHasSuffix(s string, suffix string) |
bool |
Case-insensitive suffix check. |
iContains(s string, substr string) |
bool |
Case-insensitive substring search. |
iWildcard(s string, pattern string) |
bool |
Case-insensitive wildcard match. Supports * as wildcard. |
isValidIP(ip string) |
bool |
Check if string is a valid IP address. |
isPrivateIP(ip string) |
bool |
Check if IP address is not globally reachable. Returns false on parse error. |
isPublicIP(ip string) |
bool |
Check if IP address is globally reachable. Returns false on parse error. |
ipInCIDRs(ip string, cidrs ...string) |
bool |
Check if IP address is within any of the given CIDR ranges. Returns false on parse error. |
ipNotInCIDRs(ip string, cidrs ...string) |
bool |
Check if IP address is not within any of the given CIDR ranges. Returns false on parse error. |
| Lite functions | any |
Config-defined functions (requires environments: [match]). |
Extended Match¶
Optional secondary expression(s) evaluated after match. Provides access to additional helper functions.
Supported rule types:
| Event | Aggregation |
|---|---|
Event fields are accessible via event prefix. Expressions must return a bool value.
Expressions are evaluated in definition order. If an expression returns false, the evaluation stops.
extended_match:
- isPublicIP(event.source.ip)
- |
let logins = kvAdd(event.user.name, 1, duration("1h"));
project(logins, "user_logins");
logins > 5
Helper functions:
| Function | Returns | Description |
|---|---|---|
project(value any, field string) |
any |
Add a top-level field to the resulting alert. Dot notation is not supported. Returns the value. |
logDebug(format string, args ...any) |
bool |
Log a formatted message at debug level. Returns true. |
strFormat(format string, args ...any) |
string |
Format and return a string. Uses Go fmt.Sprintf - see formatting. |
setLocal(value any, field string) |
any |
Store value in evaluation-scoped storage (shared across extended_match). Returns the value. Use local.key_name to retrieve values. |
kvGet(key string) |
any |
Retrieve value from KV store. Returns nil if not found or on error. |
kvSet(key string, value any, ttl duration) |
bool |
Store value with TTL. Returns false on error. |
kvExists(key string) |
bool |
Check if key exists. Returns false if not found or on error. |
kvDelete(key string) |
bool |
Delete key. Returns false on error. |
kvAdd(key string, value number, ttl duration) |
float64 |
Add numeric value to stored value. The ttl defines a tumbling window: the counter resets to 0 when ttl has elapsed since the first write. Returns new total, or 0 on error. |
kvSwap(key string, value any, ttl duration) |
any |
Atomic get-and-set operation. Returns old value, or nil if key didn't exist. |
isValidIP(ip string) |
bool |
Check if string is a valid IP address. |
isPrivateIP(ip string) |
bool |
Check if IP address is not globally reachable. Returns false on parse error. |
isPublicIP(ip string) |
bool |
Check if IP address is globally reachable. Returns false on parse error. |
ipInCIDRs(ip string, cidrs ...string) |
bool |
Check if IP address is within any of the given CIDR ranges. Returns false on parse error. |
ipNotInCIDRs(ip string, cidrs ...string) |
bool |
Check if IP address is not within any of the given CIDR ranges. Returns false on parse error. |
geoIP(ip string) |
map |
Lookup GeoIP data for IP address. Returns map with country, timezone, lat, lon, acc fields. Returns nil if GeoIP not configured or lookup fails. |
geoDistance(lat1 float64, lon1 float64, lat2 float64, lon2 float64) |
float64 |
Calculate distance between two coordinates in kilometers using Haversine formula. |
iEqual(s string, t string) |
bool |
Case-insensitive string equality. |
iHasPrefix(s string, prefix string) |
bool |
Case-insensitive prefix check. |
iHasSuffix(s string, suffix string) |
bool |
Case-insensitive suffix check. |
iContains(s string, substr string) |
bool |
Case-insensitive substring search. |
iWildcard(s string, pattern string) |
bool |
Case-insensitive wildcard match. Supports * as wildcard. |
parsePath(path string) |
map |
Parse a file path. Returns map with directory, filename, extension, ads (Alternate Data Stream) fields. |
parseURL(url string) |
map |
Parse a URL. Returns map with scheme, host, port, path, user, password fields. Returns nil on parse error. |
fromHex(s string) |
string |
Decode a hex-encoded string. Returns "" on invalid input. |
strDist(s string, t string) |
int |
Damerau-Levenshtein distance between strings (Unicode-aware). Use lower() for case-insensitive comparison. |
getPath(m map, path string) |
any |
Get a nested value using dot notation (e.g. "user.name"). Returns nil if any segment is missing. |
minVal(a []any) |
float64 |
Returns the minimum numeric value. Returns 0 for empty arrays. |
maxVal(a []any) |
float64 |
Returns the maximum numeric value. Returns 0 for empty arrays. |
isRiskLow(entityType string, entityValue string) |
bool |
Check if entity's risk level is at least low. Returns false if no thresholds configured or no score. |
isRiskMedium(entityType string, entityValue string) |
bool |
Check if entity's risk level is at least medium. Returns false if no thresholds configured or no score. |
isRiskHigh(entityType string, entityValue string) |
bool |
Check if entity's risk level is at least high. Returns false if no thresholds configured or no score. |
isRiskCritical(entityType string, entityValue string) |
bool |
Check if entity's risk level is critical. Returns false if no thresholds configured or no score. |
riskLevel(entityType string, entityValue string) |
string |
Get entity's current risk level. Returns "", "low", "medium", "high", or "critical". Returns "" if no thresholds configured or score is below low. |
riskScore(entityType string, entityValue string) |
float64 |
Get entity's accumulated risk score. Returns 0 if no contributions exist. |
riskRules(entityType string, entityValue string) |
[]int |
Get deduplicated list of rule IDs contributing to the entity's risk score. Returns nil if no contributions exist. |
udf.* |
any |
Go user-defined functions. See Go UDFs. |
| Lite functions | any |
Config-defined functions (default environment). |
Read Writing Expressions for patterns on variable scoping, case-insensitive matching, guard clauses, and handling missing fields.
Aggregation¶
Expression evaluated on grouped events within a time window. Determines whether the group should trigger an alert.
Supported rule types:
| Event | Aggregation |
|---|---|
Events are available in the events array. Event fields are accessed directly, e.g., events[0].field_name. The expression must return a bool value.
Helper functions:
| Function | Returns | Description |
|---|---|---|
logDebug(format string, args ...any) |
bool |
Log a formatted message at debug level. Returns true. |
getPath(m map, path string) |
any |
Get a nested value using dot notation (e.g. "user.name"). Returns nil if any segment is missing. |
minVal(a []any) |
float64 |
Returns the minimum numeric value. Returns 0 for empty arrays. |
maxVal(a []any) |
float64 |
Returns the maximum numeric value. Returns 0 for empty arrays. |
udf.* |
any |
Go user-defined functions. See Go UDFs. |
| Lite functions | any |
Config-defined functions (requires environments: [aggregation]). |
Standard expr-lang built-ins such as len(), map(), filter(), uniq(), sum(), min(), max() are also available. See the expr language definition for the full list.
Projections¶
Map of named expressions that add computed fields to alerts.
Supported rule types:
| Event | Aggregation |
|---|---|
Events are available in the events array. The expressions can return any JSON serializable values.
Helper functions:
| Function | Returns | Description |
|---|---|---|
project(value any, field string) |
any |
Add a top-level field to the resulting alert. Dot notation is not supported. Returns the value. |
logDebug(format string, args ...any) |
bool |
Log a formatted message at debug level. Returns true. |
getPath(m map, path string) |
any |
Get a nested value using dot notation (e.g. "user.name"). Returns nil if any segment is missing. |
minVal(a []any) |
float64 |
Returns the minimum numeric value. Returns 0 for empty arrays. |
maxVal(a []any) |
float64 |
Returns the maximum numeric value. Returns 0 for empty arrays. |
udf.* |
any |
Go user-defined functions. See Go UDFs. |
| Lite functions | any |
Config-defined functions (requires environments: [projections]). |
Risk Normalize¶
Expression used to canonicalize entity values in risk entries before storage. Ensures different representations of the same entity are tracked under a single identity.
Supported rule types:
| Event | Aggregation |
|---|---|
The extracted field must contain a string or a numeric value. The value is available as value (string) in the normalize expression, which itself must return a string. Standard expr built-in functions and lite functions targeting the normalize environment are available.
Complex normalization
For cases that require event context (conditional logic based on source type, combining multiple fields, or performing lookups), use extended_match with project() to compute the canonical entity value, then point the risk entry's field at the projected field:
extended_match:
# Combine fields into a single entity value
- project(lower(event.user.name + "@" + event.user.domain), "_user_email") != ""
risk:
- entity_type: user
field: _user_email
score: 10
This gives you full access to the event, UDFs, and all helper functions for normalization logic that goes beyond simple value transforms (e.g., conditional logic, multi-field composition, or UDF lookups for entity resolution).
Writing Expressions¶
Variable Scoping¶
let, local, and kv* cover different lifetimes:
let- scoped to a single expression. Use for intermediate calculations; cleared when the expression completes.local- scoped to the current event evaluation. Use to share computed values across multipleextended_matchexpressions.kv*- persistent across events. Use for tracking state over time (counters, previous values, etc.). Keys are automatically scoped to the current rule and isolated from other rules.
extended_match:
# let: temporary calculation
- let ip = event.source.ip; isPublicIP(ip)
# local: share between expressions
- geoIP(event.source.ip) | setLocal("geo") != nil
- iEqual(local.geo.country, "US")
# kv: track across events
- kvAdd(event.user.name, 1, duration("1h")) > 5
Case Sensitivity¶
Built-in expr string comparisons (==, !=) and string functions (startsWith, endsWith, hasPrefix, hasSuffix, contains) are case-sensitive.
When field values may differ in case, use the i* helper functions (iEqual, iHasPrefix, iHasSuffix, iContains, iWildcard).
The built-in expr lower() and upper() functions can also be used, but the i* helpers are slightly more efficient as they compare bytes directly.
Missing Fields and Type Errors¶
Accessing a field that does not exist on an event returns nil.
Accessing a subfield of nil (e.g. event.missing.sub) causes a runtime error: the error is logged, a metric is incremented, and the event is dropped.
- If a field can be missing, you can guard against
nilbefore accessing subfields:event.field != nil and event.field.sub == "x" - Alternatively, use the nil-safe operator
?.:event.field?.sub == "x"
Guard Clause Pattern¶
Expressions are evaluated in order and stop at the first false. Structure extended_match so that cheap or broad checks come first and expensive or narrow checks come last.
This also naturally handles nil safety: compute a value, verify it in one expression, then access its fields in the next.
extended_match:
- isPublicIP(event.source.ip) # early exit if IP is not public
- parsePath(event.file.path) | setLocal("p") != nil # compute and guard on nil
- iHasSuffix(local.p.filename, ".exe") # safe to access now
Example Rules¶
The repository contains example rules in the examples/rules/ directory.