Flask
Monitor a Flask app: an after-request hook logging status, sign-in lines from your login view, and beam monitor with the Flask rules, including the Werkzeug debugger console.
On this page
How Beam reads a Flask app
There's no in-process SDK for this stack, so the app writes what Beam needs to its logs and beam monitor reads them on the same server or container. Only redacted findings leave it. Two kinds of line:
- One JSON line per request, with
method,path(with the query string),status,ip,user_agent,hostandduration_ms. The status is what lets Beam tell an attack your app refused from one it answered. - Security events as plain lines, worded like this (Beam matches the wording and reads
user=andip=):
login failed user=42 ip=203.0.113.7
login succeeded user=42 ip=203.0.113.7
granted admin role to user=99 by user=12
API key created user=12
{"event":"llm_usage","user":"42","model":"gpt-5","total_tokens":1834}
Use an opaque user id, never an email. New outbound hosts are only reported by the Node.js SDK; for this stack, restrict outbound traffic at the network instead.
Before you start
Do steps 1 and 2 of the general cookbook first: App monitoring is on, the app is added, and its beam_app_ token is in your secret store as BEAM_APP_TOKEN. Everything below needs @agent-beam/beam 0.2.32 or newer.
Log each request with its status
# beam_logging.py
import json, logging, time
from flask import g, request
requests_log = logging.getLogger("beam.requests")
security = logging.getLogger("beam.security")
def client_ip():
forwarded = request.headers.get("X-Forwarded-For")
return forwarded.split(",")[0].strip() if forwarded else request.remote_addr
def init_beam(app):
for name, path in (("beam.requests", "/var/log/app/requests.log"), ("beam.security", "/var/log/app/security.log")):
handler = logging.handlers.WatchedFileHandler(path)
handler.setFormatter(logging.Formatter("%(message)s"))
logger = logging.getLogger(name)
logger.addHandler(handler)
logger.setLevel(logging.INFO)
logger.propagate = False
@app.before_request
def start_timer():
g.beam_started = time.monotonic()
@app.after_request
def log_request(response):
requests_log.info(json.dumps({
"method": request.method,
"path": request.full_path.rstrip("?"),
"status": response.status_code,
"ip": client_ip(),
"user_agent": request.headers.get("User-Agent", ""),
"host": request.host,
"duration_ms": round((time.monotonic() - g.get("beam_started", time.monotonic())) * 1000),
}))
return response
Add import logging.handlers at the top, and call init_beam(app) where you create the app.
Log sign-ins, admins and keys
from beam_logging import security, client_ip
@app.post("/login")
def login():
user = verify_password(request.form["username"], request.form["password"])
if not user:
security.warning("login failed user=%s ip=%s", user_id_for(request.form["username"]), client_ip())
return {"error": "Invalid credentials"}, 401
security.info("login succeeded user=%s ip=%s", user.id, client_ip())
login_user(user)
return redirect("/")
Log granted admin role to user=... by user=..., API key created user=... and an llm_usage JSON line in the same way where those happen.
Run beam monitor next to the app
npm install -g @agent-beam/beam
beam monitor --stack flask --file /var/log/app/requests.log --file /var/log/app/security.log --app /srv/app
--stack flask turns on this framework's rules and rolls up attacks on frameworks you don't run; --app also checks the app's lockfiles daily (and would detect the stack on its own). Keep it running with systemd:
# /etc/systemd/system/beam-monitor.service
[Unit]
Description=AgentBeam App monitoring
After=network-online.target
[Service]
EnvironmentFile=/etc/beam/app.env
ExecStart=/usr/bin/env beam monitor --stack flask --file /var/log/app/requests.log --file /var/log/app/security.log --app /srv/app
Restart=always
User=beam
[Install]
WantedBy=multi-user.target
sudo install -m 600 /dev/null /etc/beam/app.env && echo "BEAM_APP_TOKEN=beam_app_..." | sudo tee /etc/beam/app.env >/dev/null
sudo systemctl daemon-reload && sudo systemctl enable --now beam-monitor
In Docker or Kubernetes, run the same command in a sidecar that mounts the log directory read-only, with BEAM_APP_TOKEN from a secret.
Prove it works
beam monitor status # app, level, stack, usage
beam monitor test # a test finding through your alert workflows
curl -s "https://your-app.example.com/?id=1%20UNION%20SELECT%201" -o /dev/null
Within a minute, the SQL injection test shows on App monitoring: under Needs action if the app answered 2xx, or counted under "needed nothing from you" if it refused it. Then sign in to a test account with a wrong password ten times and the right one once: Sign-in succeeded after 10 failed attempts appears as critical.
Check dependencies on every pull request
# .github/workflows/beam-cve.yml
name: Dependency check
on: [pull_request]
jobs:
cve:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- run: npx -y @agent-beam/beam cve check . --fail-on high
env:
BEAM_APP_TOKEN: ${{ secrets.BEAM_APP_TOKEN }}
Pin your Python dependencies so they can be checked.
What Beam watches for on this stack
Besides every built-in rule and the attack-in-progress signals:
| Rule | Means | Severity |
|---|---|---|
| Werkzeug debugger console attempt | A request using __debugger__=yes&cmd=: code execution if the console is reachable | Critical |
| Werkzeug debugger console served | /console answered 2xx | Critical |
Attacks on other frameworks (WordPress probes, Laravel or Spring exploits, and so on) are rolled up as Not your stack when there's no status to say otherwise, and never alert.
Close what Beam would catch
Beam raises these when they're found; better that there's nothing to find:
- Never run
app.run(debug=True)orFLASK_DEBUG=1in production; serve with gunicorn or uWSGI. - Set a strong
SECRET_KEYfrom your secret store, andSESSION_COOKIE_SECURE = True. - Use
ProxyFixwith the exact number of proxies sorequest.remote_addrcan't be spoofed.
Coverage checklist
| Feature | Done when |
|---|---|
| Request log with status | Findings show Answered, Refused or Errored |
| Stack declared | beam monitor prints the stack at start |
| Sign-in events | login failed and login succeeded lines are written |
| Admin and key events | Role grants and new keys are logged |
| LLM spend | An llm_usage line follows each model call |
| Dependency checks | The CI job runs on pull requests |
| Alerts | Critical pages someone, high reaches a channel (step 8) |
| Routine | Someone reads Needs action daily and Attack analytics weekly |
Set this up with your coding agent
Install the agentbeam-setup skill for Claude Code, Codex, Cursor, Gemini CLI, OpenCode and Copilot, then ask your agent to set up AgentBeam on this machine. Beam scans the skill before it installs.
npx -y @agent-beam/beam add skill agentbeam-setup -g --all-agents