Writing function code
This guide is for the person who writes the function's code. It describes the function folder, every setting in
function.json, the data your code receives, what it must print, the helper library (the SDK), how to test on your own
computer, and the limits on the LEA server.
Before you start
- Read What functions are for the concepts.
- Start from a starter: New function in Settings → Functions, or
lea functions init. Do not start from an empty folder. The starter contains the SDK and a sample event. - You need Python 3.9 or later on your computer to run functions locally. Nothing else.
The function folder
A function is a folder. Its name is the function's name.
failure_note/
├── function.json settings: how to start the code, timeout, arguments, secrets
├── main.py your code (main.sh for a shell function)
├── lib/
│ └── lea_function.py the SDK, a single file, standard library only
├── sample_event.json an example of the data your code receives, for local runs
└── README.md notes for the people who maintain the function
Rules for the folder:
function.jsonmust be at the top of the folder. When you upload an archive with one top folder that containsfunction.json, that top folder is removed automatically.- The function name: lowercase letters, digits and
_, 1 to 64 characters. It must be the same infunction.json, in the upload, and (for the command line) as the folder name. These names are reserved:policy,uploads,runtime,starters,manifest,test. .git/,__pycache__/,__MACOSX/,.DS_Storeand._*files are ignored.- Links (symlinks), device files, absolute paths and paths with
..are refused. - Anything else in the folder (more Python files, libraries, templates, data files) is uploaded with it.
function.json
{
"name": "open_ticket",
"description": "Opens a ticket in the service desk when a rule fails",
"entrypoint": ["python3", "main.py"],
"timeout": 30,
"args": [
{"name": "queue", "type": "string", "default": "SECOPS", "description": "Service desk queue"},
{"name": "dry_run", "type": "boolean", "default": false, "description": "Do not create the ticket, only show it"}
],
"secrets": ["TICKET_API_URL", "TICKET_API_TOKEN"],
"env": ["HTTPS_PROXY", "NO_PROXY"],
"ai_settings": false
}
| Field | Required | Meaning |
|---|---|---|
name | Yes | The function name (see above) |
description | No | One line, shown on the function card and in the rule editor list |
entrypoint | Yes | The command that starts your code, as a list of words. It runs inside the function folder. Use ["python3", "main.py"] or ["sh", "main.sh"] |
timeout | No | Seconds before the function is stopped, 1 to 600. Default 60 |
args | No | Arguments a rule can set. Each has a name, a type (string, number or boolean), and optionally a default and a description. A rule can set only declared arguments, with the right type |
secrets | No | Names of secrets. Each becomes an environment variable for your code. You set the values in Settings → Functions |
env | No | Names of environment variables of the LEA server to pass to your code. Only HTTP_PROXY, HTTPS_PROXY, NO_PROXY (and their lowercase forms) and TZ, plus names your operator allowed. Others are dropped, and the upload report warns about them |
ai_settings | No | true passes LEA Platform's AI provider settings, including its API key, to your code. Leave false unless the function needs it |
Names for secrets and env: letters, digits and _, not starting with a digit. Names the system uses are refused,
for example PATH, HOME, LANG, TMPDIR, and anything starting with LD_, PYTHON, NODE_ or LEA_.
Important: Always start shell scripts through their interpreter (
["sh", "main.sh"]), never as["./main.sh"]. Uploads from a browser folder lose the "executable" file permission, and the script would not start.
The event your code receives
When the function runs, your code gets one JSON object on standard input. This is a complete example:
{
"event": "rule_failed",
"verdict": "fail",
"trigger": "validation",
"delivery": "none",
"artifact_id": 5821,
"rule": {
"id": 42,
"name": "SSH Root Login Disabled",
"description": "Ensures direct SSH login as the root user is disabled",
"severity": "high",
"tags": ["cat:access_control"],
"validation": [{"command": "cat /etc/ssh/sshd_config", "system": ["Linux"]}],
"expect": [{"re": {"stdout": "(?mi)^[ \\t]*PermitRootLogin[ \\t]+no\\b"}, "err": "root login is allowed"}],
"remedy": [],
"actions": []
},
"client": {
"id": 7,
"uuid": "6f1c2b9e-3d4a-4f5e-8a7b-0c1d2e3f4a5b",
"hostname": "web-01",
"info": {}
},
"result": {
"cmd_results_id": 1001,
"ts": "2026-10-28T08:00:00Z",
"stdout": "Port 22\nPermitRootLogin yes\n",
"stderr": "",
"return_code": 0,
"expect_err": "root login is allowed",
"expect_err_obj": [{"type": "re", "stream": "stdout", "pattern": "(?mi)^[ \\t]*PermitRootLogin[ \\t]+no\\b"}]
},
"args": {"queue": "SECOPS", "dry_run": false}
}
| Field | Meaning |
|---|---|
event | rule_failed, rule_passed, or rule_result (a rule without expectations, so no verdict) |
verdict | fail, pass or null |
trigger | What produced the result: validation (a normal check), remedy (the host ran the remediation or an action, then the check), or test (a test run from the console or CLI) |
delivery | What the hook does with your answer: none (Record only), remedy (Run the remediation with the output) or action (Let the function pick an action). none in test runs |
artifact_id | The number of this run. Useful in logs and ticket texts |
rule.id, rule.name, rule.description, rule.severity, rule.tags | The rule, as in the console |
rule.validation, rule.expect, rule.remedy | The rule's commands, expectations and remediation |
rule.actions | The names of the rule's actions, sorted. Your code can return one of them |
client.id, client.uuid | The host's number and its unique LEA identity |
client.hostname | The host name |
client.info | The details the LEA agent reports about the host (operating system, distribution and more). Look at Event sent in a test run to see the exact content on your hosts |
result.cmd_results_id | The number of the host's result |
result.ts | When the host reported it (UTC) |
result.stdout, result.stderr | The raw output of the validation command(s). Usually text. For rules that use built-in agent checks it can be a JSON object |
result.return_code | The command's return code |
result.expect_err | The reason the rule failed (the expectation's error text). Empty when it passed |
result.expect_err_obj | Each expectation that failed, with its type (re, not_re, returncode, ...), stream and pattern |
args | The arguments: the defaults from function.json, replaced by the values set on the rule's hook |
ai | Only when ai_settings is true: provider, model, base_url and api_key, or null when the AI assistant is off. Always null (or hidden) in test runs of a staged upload |
Tip: The best way to see real events is a test run: Test run on the function card shows the Event sent.
What your code returns
Your code must print exactly one JSON object on standard output and exit with code 0. Nothing else may be printed to standard output. Write log messages to standard error instead.
{
"summary": "Ticket INC0012345 opened for web-01",
"markdown": "**Owner:** team-linux\n\n[Open the ticket](https://servicedesk.example.internal/INC0012345)",
"ticket": "INC0012345",
"action": null,
"files": {"site.conf": "server ntp1.corp.example iburst\n"}
}
| Key | Meaning |
|---|---|
summary | One line, shown in bold on the result |
markdown | Longer text in Markdown, shown on the result (images are not shown; links open in a new tab) |
action | Only used with Let the function pick an action: the name of one of the rule's actions, "remedy" for the rule's remediation, or null (or no action key) to send nothing |
files | Files for the host: {"file name": "text content"}. Each one is written into the working folder of the host's command, next to lea_artifact.json. Names: start with a letter or digit, then letters, digits, ., _ or -, at most 64 characters, no folders. lea_artifact.json is reserved |
| anything else | Any other keys are stored and shown on the result as JSON |
The whole answer may be at most 256 KB.
Warning: Every console user can read the artifact, and with a delivering hook the host receives it too. Never return secrets, passwords or tokens.
What the host receives
With Run the remediation with the output or Let the function pick an action, the host's command finds two kinds of files in its working folder:
- Every file from
files, with exactly the content you returned. lea_artifact.json, which wraps your whole answer:
{
"artifact_id": 5821,
"function": "open_ticket",
"status": "ok",
"artifact": {"summary": "...", "files": {"site.conf": "..."}},
"error": null
}
When the function failed, status is error or timeout, artifact is null, and error says why. The file
contents are plain files; using files is usually easier than reading lea_artifact.json on the host.
The SDK
The SDK is the file lib/lea_function.py in every starter. It uses only the Python standard library, so nothing has to
be installed on the server. Your main.py loads it like this:
import os
import sys
sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), 'lib'))
import lea_function as lea
ev = lea.event()
| Call | What it does |
|---|---|
lea.event() | Reads the event from standard input and returns it. Use dots to read fields: ev.verdict, ev.client.hostname, ev.result.stdout, ev.rule.actions. A missing field gives None. ev.args.get('queue') also works |
ev.failed, ev.passed | True when the verdict is fail or pass |
lea.secret('NAME', default=None) | The value of a secret (or default when it is not set) |
lea.ok(summary, **data) | Prints {"summary": summary, ...data} and ends the program successfully |
lea.action(name, files=None, summary=None, **data) | Asks the host to run the rule's action name (or "remedy"), with optional files. Ends the program |
lea.nothing(summary=None, **data) | Sends nothing to the host ("action": null) but still records a summary and data. Ends the program |
lea.fail(message, code=1) | Writes message to standard error and ends the program with an error. The run is recorded as failed |
ok, action and nothing check your answer with the same rules as the server (action name, file names, 256 KB) before
printing it. A wrong answer stops your code with an error, so you find the mistake in a test run, not on a host.
A complete example:
import os
import sys
sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), 'lib'))
import lea_function as lea
ev = lea.event()
if not ev.failed:
lea.nothing(f'{ev.rule.name} is {ev.verdict or "informational"} on {ev.client.hostname}')
lea.ok(f'{ev.rule.name} fails on {ev.client.hostname}',
reason=ev.result.expect_err or None, host=ev.client.hostname)
The SDK from a shell script
Shell functions use the same file as a command. The server has no jq, so read event fields with the SDK:
| Command | What it does |
|---|---|
python3 lib/lea_function.py field PATH | Reads an event from standard input and prints one field, for example client.hostname or rule.actions.0. Prints nothing for a missing field |
python3 lib/lea_function.py ok "SUMMARY" key=value ... | Prints a result with a summary and extra values |
python3 lib/lea_function.py action NAME --summary "TEXT" --file NAME=@PATH | Asks the host to run an action. --file host.crt=@/path/file takes the content from a file; --file NAME=TEXT uses the text itself |
python3 lib/lea_function.py nothing --summary "TEXT" | Sends nothing to the host |
python3 lib/lea_function.py fail "MESSAGE" | Ends with an error |
Standard input can be read only once, so save the event first:
#!/bin/sh
set -eu
LEA="python3 lib/lea_function.py"
EVENT=$(cat)
field() { printf '%s' "$EVENT" | $LEA field "$1"; }
host=$(field client.hostname)
rule=$(field rule.name)
verdict=$(field verdict)
if [ "$verdict" != "fail" ]; then
$LEA nothing --summary "$rule is ${verdict:-informational} on $host"
exit 0
fi
$LEA ok "$rule fails on $host" host="$host" reason="$(field result.expect_err)"
Secrets are environment variables in shell too: $TICKET_API_TOKEN.
Important: Commands such as
curlprint to standard output by default. Send their output to a file or to/dev/null(curl -o /dev/null ...), or your function's answer is no longer valid JSON.
Run it on your computer
The SDK can run your function the way the LEA server does: event on standard input, a clean environment, the timeout from
function.json, and the same checks on the answer.
python3 lib/lea_function.py run . --event sample_event.json
Options:
| Option | Meaning |
|---|---|
--event FILE | The event to send. Default: sample_event.json in the folder |
--secret NAME=VALUE | A secret value. Repeat for several. Use test values, not production secrets |
--arg NAME=VALUE | An argument value, as a rule would set it. Repeat for several |
--timeout SECONDS | Override the timeout |
Example with a secret and an argument:
python3 lib/lea_function.py run . --event sample_event.json --secret TICKET_API_TOKEN=test-token --arg queue=TEST --arg dry_run=true
You should see "status": "ok" and your artifact. Warnings tell you about secrets that are declared but not given, or
given but not declared.
To test with a real event, copy the Event sent of a test run into a file and pass it with --event.
Note: A local run does not use the server's sandbox and uses your computer's network. A real test run on the server (Test run on the function card, or
lea functions test) is the final check.
The runtime on the LEA server
Your code runs with what the LEA server has installed. You see it in Settings → Functions under
Runtime (bottom of the page), or with lea functions runtime:
- Python: the version of
python3. - Binaries: which of
python3,sh,bash,openssl,curlandwgetexist. - Show N Python packages: the Python packages installed on the server. Your code may use them, for example the
cryptographypackage used by themtls_castarter. - Environment allow-list: which
envnames are passed. - Timeouts, output and bundle limits, and the number of Workers.
There is no pip and usually no internet. Anything not listed must be inside your function folder.
Your code runs:
- inside the function folder (it is read-only: do not write there);
- with an empty temporary folder of its own in the
HOMEandTMPDIRenvironment variables, deleted after the run. Write temporary files there (Python'stempfilemodule does this by default); - with only these environment variables:
PATH,LANG,HOME,TMPDIR,LEA_FUNCTION_NAME, its secrets and the allowedenvnames.
Libraries without internet
LEA Platform sites are often air-gapped. Plan for it:
- Prefer the Python standard library:
urllib.requestfor HTTPS calls,json,ssl,re,base64,hashlib. - If you need another pure-Python library, put it inside the function folder, for example in
lib/, on a computer that has it. A Python wheel (.whl) is a zip file: unzip it and copy the package folder intolib/. Yourmain.pyalready addslib/to the search path. - Libraries with compiled parts must match the server's Python version and processor type. Check Runtime first; prefer a package that is already installed there.
- Keep the folder under 10 MB packed.
- If your internal systems use certificates from your own CA, give the CA certificate to the function as a secret (for
example
CA_BUNDLE) and load it:ssl.create_default_context(cadata=lea.secret('CA_BUNDLE')). Do not turn off certificate checks. - A proxy is used only if your operator set
HTTPS_PROXYon the LEA function runner and yourfunction.jsonlists it inenv.urllib.requestuses it automatically. List internal hosts inNO_PROXY.
Limits
| Limit | Value |
|---|---|
| Timeout | 1 to 600 seconds (default 60). The function and every process it started are stopped |
| Answer (standard output) | 256 KB |
| Upload size | 10 MB packed, 64 MB unpacked, 10,000 files |
| Processes the function may start | 64 |
| Size of a file the function writes | 64 MB |
| Secret value | 32 KB |
| Error text kept from standard error | The last 4 KB |
| Hooks per rule | 8 (each function once) |
| Actions per rule | 16 |
| Runs per host, rule and function | 12 per hour (operator setting) |
| Functions running at the same time | 2 by default (operator setting, see Workers under Runtime) |
| Artifacts kept | 30 days (operator setting) |
Check host data before you use it
Everything in result comes from the host. A compromised host can send anything. Your function holds secrets and can
reach internal systems, so check host data before you use it:
- Check the format before you put a value in a URL, a file name or a command. For example, accept a host name only if it
matches
^[A-Za-z0-9.-]{1,253}$, and encode it withurllib.parse.quote. - Never run host output as a command or as code (
eval,exec,sh -c). - Check that what the host sends belongs to that host. The
mtls_castarter only signs a certificate request whose name is the host's ownclient.uuid. - Limit sizes: cut long output before you send it to another system.
- Hosts check what they receive (files and
lea_artifact.json) before they use it too.
Exit codes, timeouts and retries
| What happens | How the run is recorded |
|---|---|
| Exit code 0 and one valid JSON object on standard output | OK. The artifact is stored |
| Any other exit code | ERROR, with exit N: and the end of standard error |
Still running after timeout seconds | TIMEOUT. The function and all its processes are stopped |
Exit code 0 but no output, not JSON, not an object, more than 256 KB, or an invalid action or files | ERROR, with the reason (for example output is not valid JSON or invalid output: ...) |
Secret values in standard error are replaced with *** before they are stored.
After an error or timeout:
- Administrators get a Function failed notification.
- With Run the remediation with the output, the remediation is still sent, with the error in
lea_artifact.json. With Let the function pick an action, nothing is sent. - The function is tried again when the host sends the same output again, after a waiting time: 1 minute after the first failure, then 2, 4, 8 minutes and so on, up to 1 hour. When the output changes, it runs at once.
Test runs never send anything to hosts, do not count towards the hourly limit, and raise no notification.
If something goes wrong
output is not valid JSON: something else printed to standard output. Moveprintcalls for logging to standard error (print(..., file=sys.stderr)), and redirect command output in shell scripts.could not start entrypoint: the program inentrypointdoes not exist on the server, or a script is started directly. Use["python3", "main.py"]or["sh", "main.sh"].ModuleNotFoundError: the library is not installed on the server. Put it in the function folder.- More symptoms: When a function does not work.
Related
- Function recipes
- Your first function
- Functions reference: event and output