scripting

package module
v0.0.0-...-bab2b7d Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 24, 2026 License: Apache-2.0 Imports: 19 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

github.com/sentinez/scripting

⚠️ This is an automatically published staged repository for Sentinez.
Contributions, including issues and pull requests, should be made to the main Sentinez repository: https://github.com/sentinez/sentinez.
This repository is read-only for importing, and not used for direct contributions.

=======================================================================

This module runs the Lua scripts of the edge in a sandbox.

scripting compiles a script (Compile) and calls its hooks (Program.Call). A ---@stage <phase>/<stage> line hooks the global function it precedes, whatever its name, to a stage of the edge handler chain, as SEC("fentry/...") does in eBPF:

---@stage http.request/secrule
---@stage http.request/secruleset
---@param ctx sz.Context
function deny_debug(ctx)
  if ctx:header("X-Debug") == "1" then
    ctx:respond(403, "no")      -- ends the request, http.request only
  end
end

---@stage http.request/router
---@stage http.response/router
---@param ctx sz.Context
function tag(ctx)
  ctx:set_header("X-Edge", "sentinez")
end
  • http.request/<stage>: runs before the stage; ctx:respond ends the request there and the stage is skipped.
  • http.response/<stage>: runs once the stage, and the ones after it, returned. The response is written: it only observes.
  • One stage and phase per line; a function may have several lines.
  • The lines must precede a global function (function name(ctx)), other comments aside, or the script does not compile; so does a line of an unknown phase or stage. A function without one is not a hook, whatever its name.
  • The hooks of a stage run in source order, until one responds.

The stages, in the order of the edge chain (internal/handlers/handlers.go):

Stage (plugin id) Plugin
caching contents.Caching
secratelimit secure.SecLimiter
waitingroom room.WaitingRoom
staticassets contents.StaticAssets
secrule secure.SecRule
secruleset secure.SecRuleset (OWASP CRS)
router routing.StandardRouter, to the upstream

The stages before the namespace of the request is known (tracing, logging, domain) have no hooks. scripting.Stages returns the ids, the ones Has and Call take; a test of the edge (TestScriptStagesAreTheChain) checks them against the chain.

ctx
method(), path(), host(), ip() the request
header(k), query(k) a header or query parameter, "" if absent
has_header(k), has_query(k) whether the request has it, even empty
body(), ja4() the request body, the JA4 fingerprint ("" without TLS)
tls() whether the request came over TLS
ip_in(cidr) whether the client IP is in the prefix, e.g. "10.0.0.0/8"
set_header(k, v) a header of the request sent upstream
set_response_header(k, v) a header of the response
respond(status, body) answers the request (100 to 599)

The global table log writes lines to the logs of the request, with its id and the name of the script: the arguments, joined by tabs like print.

log
log.info(...) a line at the info level
log.debug(...) a line at the debug level, written only when the edge logs debug

log:info(...) and log:debug(...) work too: called with a colon, the log table passed as first argument is left out.

The global table re has re.match(s, pattern): whether s holds a match of pattern, a regular expression of the RE2 syntax of Go (not a Lua pattern); an invalid one raises an error. The first 256 patterns stay compiled.

---@stage http.request/secrule
function audit(ctx)
  log.debug("path", ctx:path(), "ip", ctx:ip())
  if ctx:header("X-Debug") == "1" then
    log:info("denied debug request from", ctx:ip())
    ctx:respond(403, "no")
  end
end

A line is cut at 1024 bytes and a hook call logs 16 lines at most. In the script body, outside of a hook, there is no request: the line is dropped.

Rule scripts

A secrule or a rate limiter of the edge may be a Lua source in place of its expression. It has no ---@stage line: it defines one global function, with a read-only ctx (set_header, set_response_header and respond raise an error). The edge does not call it: it converts the script to its expression when it loads (ParseMatch/ParseKey, below), so the script must be of the declarative form.

A secrule defines match(ctx). It returns nil or false when the request does not match, else the action, as an eBPF program returns XDP_DROP:

---@param ctx sz.Context
function match(ctx)
  if ctx:header("X-Debug") == "1" then
    return SZ_BLOCK
  end
  if ctx:path() == "/old" then
    return {type = SZ_REDIRECT, params = {location = "/new"}}
  end
end
Constant Value
SZ_BLOCK "block"
SZ_CHALLENGE "challenge"
SZ_LOG "log"
SZ_MODIFY_HEADER "modify_header"
SZ_REDIRECT "redirect"
SZ_ROUTE_TO "route_to"
SZ_SET_TAG "set_tag"

The constants hold the action names, so return "block" is the same. A table {type = SZ_REDIRECT, params = {...}} adds the params of the action.

A rate limiter defines key(ctx): the key to count the request under (a string), true for the client IP, nil or false not to count it. The edge holds the declarative form only, return true: it counts under the client IP.

function key(ctx)
  local k = ctx:header("X-Api-Key")
  if k ~= "" then return k end
end

A host that runs the rule as Lua compiles it with Compile, checks it with Hooked (false) and HasFunc(scripting.MatchFunc) (or KeyFunc), then calls Program.Invoke(ctx, "match", ex) for each request: the result is a Value (KindNil, KindBool, KindString, KindTable) free of the Lua types.

ParseMatch and ParseKey read a script of the declarative form, branches of if <conditions> then return <action> end, into a Rule; MatchSource and KeySource write a Rule back as Lua (return SZ_BLOCK). The condition of a Rule is a Node tree: a Leaf of one Cond, or a group of All or Any of its nodes (MaxConditions conditions at most, no group multiplied out). The builders keep the canonical form a script is read to: nested groups of one kind merged, conditions before groups. CondSource writes the condition alone, with the parentheses an or in an and needs. A condition combines with and, or, not and parentheses the comparisons below, field one of ctx:path(), ctx:method(), ctx:host(), ctx:ip(), ctx:header("k"), ctx:query("k"), ctx:body(), ctx:ja4():

Lua Cond
field == "v", field ~= "v" OpEq, OpNe
field:find("v", 1, true) OpContains
field:sub(1, #v) == "v", field:sub(-#v) == "v" OpPrefix, OpSuffix
tonumber(field) > 10 (>=, <, <=) OpGt, OpGte, OpLt, OpLte
re.match(field, "^/a") OpMatches
ctx:ip_in("10.0.0.0/8"), not ctx:ip_in(...) OpWithin, OpNotWithin
ctx:has_header("k"), ctx:has_query("k"), with not OpExists, OpAbsent
ctx:tls(), not ctx:tls() SourceTLS, OpEq/OpNe "true"

not applies to the equalities, ip_in, has_* and tls only. A script out of that form returns ErrNotDeclarative. The edge converts its protobuf expressions with them (core/szrule/rulescript), and its rule scripts to expressions: it refuses a rule script out of that form.

Sandbox

The sandbox opens base, table, string and math only: there is no os, io, load or require. Each call is limited to 50ms (WithTimeout), and a script that fails or times out is skipped by the edge.

Usage

go get github.com/sentinez/scripting
prog, err := scripting.Compile("audit.lua", source,
	scripting.WithTimeout(20*time.Millisecond))
if err != nil {
	return err // syntax error, misplaced ---@stage, or a failing script body
}

// around the stage whose id is "secrule" (secure.SecRule):
if prog.Has(phase.Request, "secrule") {
	responded, err := prog.Call(ctx, phase.Request, "secrule", ex)
	// responded: a hook answered, skip the stage
}
  • Compile parses the script, reads its ---@stage lines and runs the body once, so a broken script fails there, not at the first request.
  • A Program is safe for concurrent use: each call takes a Lua state of its own, kept for reuse unless the call failed or timed out.
  • Call runs the hooks of the stage in source order until one responds, and reports whether one did. The hooks share the time limit (50ms by default).
  • Has is a cheap check to skip the call when the script hooks nothing there.

The host implements exchange.Exchange (the request, SetHeader, SetResponseHeader, String to answer it, Log) and calls Program.Call(ctx, phase.Request, stage, ex) around each stage.

Packages

Package
scripting Compile, Program (Has, Call, Invoke, HasFunc, Hooked, Name, Source), Value, WithTimeout and Stages; the rule forms Rule, ParseMatch, MatchSource, ParseKey, KeySource
scripting/exchange Exchange, the request the host hands a hook, and the log Level
scripting/phase Phase: Request (http.request), Response (http.response)
internal/hooks parses the ---@stage lines into the hooks of a script; the stage table
internal/api the ctx and log APIs and the SZ_ action constants; Run calls the hooks of a stage in a Lua state, Invoke the function of a rule
internal/sandbox the Lua state: the libraries a script may use, no more

Editor support

meta/sentinez.lua declares ctx (sz.Context), log, the stages (sz.Stage), the action constants (sz.Action) and the rule functions (sz.Match, sz.Key) for lua-language-server (LuaLS / EmmyLua): annotate a hook with ---@param ctx sz.Context for completion and type checks. .luarc.json loads it for this directory; elsewhere add the directory to workspace.library. TestMetaMatchesContext keeps it in step with the methods of ctx, the log functions, the stages and the actions.

Documentation

Overview

Package scripting runs the Lua scripts of the edge. A ---@stage line hooks the global function it precedes, whatever its name, to a stage of the edge handler chain, at http.request or http.response:

---@stage http.request/secrule
function deny_debug(ctx)
  if ctx:header("X-Debug") == "1" then ctx:respond(403) end
end

The edge calls it around the stage with a ctx value to read the request, change its headers or answer it. Scripts run in a sandbox without os, io or any way to load code, under a time limit.

A secrule or a rate limiter may also be a Lua source in place of its expression: Program.Invoke calls its global function (match for a secrule, key for a limiter) with a read-only ctx and returns its Value. A match function returns an action constant, as an eBPF program returns XDP_DROP:

function match(ctx)
  if ctx:header("X-Debug") == "1" then return SZ_BLOCK end
end

Index

Constants

View Source
const (
	// MatchFunc the function of a secrule script.
	MatchFunc = "match"
	// KeyFunc the function of a rate limiter script.
	KeyFunc = "key"
)

The global functions of the rule scripts.

View Source
const MaxConditions = 256

MaxConditions the most conditions of a declarative rule, all its groups together.

Variables

View Source
var (
	// ErrNotDeclarative a script outside of the declarative form Parse
	// reads, or a rule the form cannot write.
	ErrNotDeclarative = errors.New("not declarative")
)

Functions

func CondSource

func CondSource(match Node) (string, error)

CondSource the Lua condition match matches, the if of the scripts MatchSource and KeySource write:

ctx:path() == "/login" and (ctx:header("X-A") ~= "" or ctx:ip() == "1")

"and" binds tighter than "or" in Lua, as in a Node: an or group in an and group is put in parentheses. A condition matching every request is "true".

func IsAction

func IsAction(name string) bool

IsAction reports whether a secrule script may return the action name.

func KeySource

func KeySource(match Node) (string, error)

KeySource the source of the rate limiter script counting, under the client IP, the requests match matches: ParseKey reads match back from it.

func MatchSource

func MatchSource(r Rule) (string, error)

MatchSource the source of the secrule script of r: ParseMatch reads r back from it.

func Stages

func Stages() []string

Stages returns the ids of the stages a hook may annotate, in chain order: the ids Has and Call take.

Types

type Action

type Action struct {
	Name string
	// Params string, float64, bool or map[string]any fields.
	Params map[string]any
}

Action the action of a secrule: its name ("block", which a script returns as SZ_BLOCK or "block"), and its params.

type Cond

type Cond struct {
	Source Source
	Key    string
	Op     Op
	Value  string
}

Cond a condition: the field Source (of Key, for a keyed source) compared by Op to Value. A numeric Op takes a decimal Value, e.g. "10" or "0.5".

type Kind

type Kind int

Kind is the type of the Value a rule returned.

const (
	// KindNil nil, or no result.
	KindNil Kind = iota + 1
	// KindBool a boolean.
	KindBool
	// KindString a string.
	KindString
	// KindTable a table with string keys.
	KindTable
)

type Node

type Node struct {
	// And the group needs all its Nodes to match, not only one. An empty
	// And matches every request, an empty Or matches none.
	And   bool
	Nodes []Node
	// Cond the condition of a leaf, nil for a group.
	Cond *Cond
}

Node a condition of a rule: a Cond, or a group of nodes all of which (And) or one of which (not And) must match. Build one with Leaf, All and Any: they keep the groups in the canonical form the parser reads a script to, so a rule written and read back is equal to itself.

func All

func All(nodes ...Node) Node

All the node matching when every one of nodes does: the and groups it holds are merged into it, and its conditions come before its or groups, as the edge evaluates them. A single node is returned as is, none match every request.

func Any

func Any(nodes ...Node) Node

Any the node matching when one of nodes does: the or groups it holds are merged into it. A single node is returned as is, none match no request.

func Leaf

func Leaf(c Cond) Node

Leaf the node of the condition c.

func ParseKey

func ParseKey(source string) (Node, error)

ParseKey reads the condition of a rate limiter script of the form KeySource writes: as ParseMatch, each branch returning true.

func (Node) Branches

func (n Node) Branches() []Node

Branches the nodes one of which n needs: those of an or group, n itself for any other node. A script writes an if for each.

func (Node) IsAnd

func (n Node) IsAnd() bool

IsAnd whether n is a group needing all its nodes.

func (Node) IsOr

func (n Node) IsOr() bool

IsOr whether n is a group needing one of its nodes.

type Op

type Op int

Op the comparison of a condition.

const (
	// OpEq field == "value".
	OpEq Op = iota + 1
	// OpNe field ~= "value".
	OpNe
	// OpContains field:find("value", 1, true).
	OpContains
	// OpPrefix field:sub(1, #value) == "value".
	OpPrefix
	// OpSuffix field:sub(-#value) == "value".
	OpSuffix
	// OpGt tonumber(field) > value.
	OpGt
	// OpGte tonumber(field) >= value.
	OpGte
	// OpLt tonumber(field) < value.
	OpLt
	// OpLte tonumber(field) <= value.
	OpLte
	// OpMatches re.match(field, "value"): value a regular expression of
	// the RE2 syntax of Go.
	OpMatches
	// OpWithin ctx:ip_in("value"): SourceIP in the CIDR prefix value.
	OpWithin
	// OpNotWithin not ctx:ip_in("value").
	OpNotWithin
	// OpExists ctx:has_header(key) or ctx:has_query(key): the request has
	// the field Key of a keyed source, Value empty.
	OpExists
	// OpAbsent not ctx:has_header(key) or not ctx:has_query(key).
	OpAbsent
)

type Option

type Option interface {
	// contains filtered or unexported methods
}

Option configures a Program.

func WithTimeout

func WithTimeout(d time.Duration) Option

WithTimeout limits the time of each Call, 50ms by default.

type Program

type Program struct {
	// contains filtered or unexported fields
}

Program is a compiled script. It is safe for concurrent use: a call takes a Lua state of its own.

func Compile

func Compile(name, source string, opts ...Option) (*Program, error)

Compile parses source, reads the hooks its annotations declare and runs it once. A syntax error, a misplaced annotation or an error of the script body is returned here, not at the first request.

func (*Program) Call

func (p *Program) Call(ctx context.Context, at phase.Phase, stage string,
	ex exchange.Exchange) (bool, error)

Call runs the functions hooking the stage at phase, in source order, until one answers the request, and reports whether one did. They share the time limit. An error, a timeout included, stops there and discards the Lua state.

func (*Program) Has

func (p *Program) Has(at phase.Phase, stage string) bool

Has reports whether a function of the script hooks the stage at the given phase.

func (*Program) HasFunc

func (p *Program) HasFunc(name string) bool

HasFunc reports whether the script body defines the global function name: a rule checks its entry point at load, not at the first request.

func (*Program) Hooked

func (p *Program) Hooked() bool

Hooked reports whether a function of the script hooks a stage.

func (*Program) Invoke

func (p *Program) Invoke(ctx context.Context, fn string,
	ex exchange.Exchange) (Value, error)

Invoke calls the global function fn, a rule, with a read-only ctx on ex and returns its result. An error, a timeout included, discards the Lua state.

func (*Program) Name

func (p *Program) Name() string

Name returns the name the script was compiled with.

func (*Program) Source

func (p *Program) Source() string

Source returns the source the script was compiled from.

type Rule

type Rule struct {
	Match  Node
	Action Action
}

Rule the declarative form of a rule script: it matches a request when Match does. A secrule takes Action, a rate limiter counts the matching requests under the client IP.

MatchSource and KeySource write it as Lua, ParseMatch and ParseKey read it back from a script of that form, hand written or not:

function match(ctx)
  if ctx:path() == "/admin" and not (ctx:ip() == "10.0.0.1") then
    return SZ_BLOCK
  end
  if ctx:has_header("X-Debug") or re.match(ctx:path(), "^/wp-") then
    return SZ_BLOCK
  end
end

func ParseMatch

func ParseMatch(source string) (Rule, error)

ParseMatch reads the declarative Rule of a secrule script (see Rule): one function match(ctx) whose body is a list of

if <condition> then return <action> end

every branch returning the same action, the last statement possibly an unconditional return. A condition combines with and, or, not and parentheses the comparisons MatchSource writes. Any other script returns an error wrapping ErrNotDeclarative, with the line at fault.

type Source

type Source int

Source a field of the request a condition reads, through the ctx method of the same name.

const (
	// SourcePath ctx:path().
	SourcePath Source = iota + 1
	// SourceMethod ctx:method().
	SourceMethod
	// SourceHost ctx:host().
	SourceHost
	// SourceIP ctx:ip().
	SourceIP
	// SourceHeader ctx:header(key).
	SourceHeader
	// SourceQuery ctx:query(key).
	SourceQuery
	// SourceBody ctx:body().
	SourceBody
	// SourceJA4 ctx:ja4().
	SourceJA4
	// SourceTLS ctx:tls(), a boolean: its conditions are OpEq or OpNe to
	// "true" or "false", written ctx:tls() and not ctx:tls().
	SourceTLS
)

func (Source) Keyed

func (s Source) Keyed() bool

keyed reports whether the source takes a key.

type Value

type Value struct {
	Kind Kind
	Bool bool
	Str  string
	// Table the fields of a table: string, float64, bool or
	// map[string]any, as structpb.NewValue takes them.
	Table map[string]any
}

Value the result of a rule function, free of the Lua types.

Directories

Path Synopsis
internal
api

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL
⌂ 换网址