Batteries

Security (Sentinel)

Every Grit project ships with Sentinel -- a production-grade security intelligence suite that provides a Web Application Firewall, rate limiting, brute-force protection, anomaly detection, security headers, and a real-time threat dashboard. Security is not an afterthought.

Incoming requestSentinel WAFOutcomeinspectcleanthreatlogRequestclient / attackerSentinel WAFrate · brute · anomalyAllow→ handlerBlock429 / 403Threat dashboardreal-time
AllowedBlockedStreamed to dashboard
Every request passes Sentinel's WAF; threats are blocked and streamed to the dashboard

Every feature, in detail

What each part actually covers, and where it stops. The lists below are the ones Sentinel compiles in, not a summary of them: if a threat class or a behavioural check is not named here, Sentinel does not look for it.

Web Application Firewall

Every request is matched against fourteen threat classes before your handler runs. The matching covers the path, the query string, headers, cookies and the body, and payloads are decoded first, so an attack hidden in URL encoding, double encoding, base64 or mixed case is compared in the same form as a plain one.

SQLi

SQL injection, including UNION, boolean and time-based forms

XSS

Script injection in markup, attributes and javascript: URLs

PathTraversal

../ and its encodings, reaching outside the intended directory

CommandInjection

Shell metacharacters that would run a second command

SSRF

URLs aimed back at your own network or cloud metadata

XXE

XML external entities, which read files or make requests for you

LFI

Local file inclusion: reading a file the handler never meant to serve

OpenRedirect

A redirect target an attacker chose, used to make a phish look like you

PrototypePollution

__proto__ and constructor keys that rewrite object behaviour

Scanning

The shape of an automated probe rather than one bad request

RateLimitExceeded

Raised by the limiter below, recorded as a threat like any other

BruteForce

Raised by Auth Shield

AnomalyDetected

Raised by the behavioural checks

CSPViolation

Reported by the browser, back to your own endpoint

Each rule has a sensitivity of off, low, medium or strict, so a rule that costs you false positives can be loosened or turned off without turning off the WAF. What happens on a match is the WAF mode: log it, block it, or challenge the caller. Your own patterns go in custom rules, and what the WAF does not inspect is worth reading before you rely on it.

Rate Limiting

Limits apply per IP, per authenticated user, per route, and globally, and the four compose: a route limit does not replace the global one. Three counting strategies are available, and the difference between them matters at the edges.

  • fixed_window: counts per clock window. Cheapest, and lets through up to twice the limit across a window boundary.
  • sliding_window: counts the last N seconds continuously. No boundary burst, which is why it is the default.
  • token_bucket: refills at a steady rate and allows a burst up to the bucket size. The right one when normal traffic is bursty by nature.

A limited response is a 429 carrying Retry-After, and every response carries X-RateLimit-Limit and X-RateLimit-Remaining, so a client can back off before it is refused rather than after. Exceeding a limit is recorded as a RateLimitExceeded threat against that actor, which is how a scraper shows up on the dashboard as one caller rather than as noise.

Auth Shield

Sign-in gets its own protection, because the generic limiter cannot tell a wrong password from a slow typist. Two things are watched: repeated failures against one account, and one password tried across many accounts, which is credential stuffing and looks nothing like brute force from the account's side.

A lockout bars the (address, account) pair rather than the address. Behind an office or a carrier NAT one address is thousands of people, and barring it meant one person's typing locked out everybody sharing that egress. Addresses that are known to be shared can be exempted from the per-address bar entirely with SENTINEL_LOCKOUT_EXEMPT_IPS, and they are still counted and still subject to the pair lockout.

Between "no friction" and "you are barred" there is a challenge tier, which asks for a CAPTCHA instead of refusing. It needs a provider configured (Turnstile, hCaptcha or reCAPTCHA); with none set the tier exists and can never fire.

Auto-block

Everything above detects and records. Auto-block is what stops the address doing it again: ten threats of High severity or worse from one address inside ten minutes bars that address for a day. On outside development, off in development, where the thing it would block is you.

It acts on behaviour rather than reputation. IPReputation asks a third party what is already known about an address; this asks what the address has just done to your application, which is the only thing that catches a scanner nobody has reported yet. Counting runs through the same Redis counters as the rate limits, so threats spread over replicas add up to one total and a block made anywhere is enforced everywhere.

The severity floor is what keeps it from turning on your users. High is what the scanner patterns score (path traversal, SQL injection, env-file probes), so a lone medium-severity oddity does not accumulate towards a block, and each threat counts once by its own id. Every automatic block is audited like a manual one, and liftable from the dashboard.

Loopback and the private ranges are never blocked, and the reason is worth knowing because it decides whether this feature is safe on your deployment. Auto-block bars an address, and the address is only the attacker's when Sentinel is reading the real client. Behind a reverse proxy it has not been told to trust, every request carries the proxy's address instead, so ten probes through that proxy would bar the proxy: every user, for a day, from one scanner. Set SENTINEL_TRUSTED_PROXIES to the proxy's address and the real client is read, after which the exemption stops applying to anybody who matters.

SENTINEL_AUTOBLOCK_EXEMPT_IPS adds to that list: your own monitoring, a partner's integration, an office range. Left unset it follows SENTINEL_LOCKOUT_EXEMPT_IPS, because both answer the same question and a project that answered it once should not have to answer it twice.

Auto-block only sees threats from the moment it is on. For the addresses already in your threat log, the dashboard's IP Management page has a Block repeat offenders panel, which takes a minimum threat count and a window and supports a dry run that blocks nobody.

The scheduled ban sweep

Auto-block answers a burst. It cannot answer patience: four high-severity threats an hour, every hour, for a week never trips ten in ten minutes, and that is what most real scanning looks like. One deployment's threat log held 18,405 rows, nearly all of them env-file probes from a handful of addresses, every one detected and recorded, and not one of them stopped.

So there is a second rule that reads the window instead of the burst. Every six hours it counts each address's high-severity threats over the last day and bans the ones over the line. The two are complements: one answers in seconds, the other catches everything slow enough to avoid it.

.env
# More than three high-severity threats in 24 hours, swept every 6 hours.
# MIN_THREATS is exceeded, not met: at 3, an address is banned on its fourth.
SECURITY_AUTO_BAN=true
SECURITY_AUTO_BAN_MIN_THREATS=3
SECURITY_AUTO_BAN_WINDOW_HOURS=24
AUTO_BAN_INTERVAL_HOURS=6
SECURITY_AUTO_BAN_PERMANENT=true

High severity only, which is the part worth understanding. An actor's total threat count includes every low-severity heuristic it ever tripped, so a client that trips one forty times would be banned by a number that says nothing about intent. High is what the scanner patterns score: path traversal, SQL injection, env-file probes.

Loopback and the private ranges are never banned, for the same reason auto-block exempts them: behind a proxy Sentinel has not been told to trust, every request carries the proxy's address. Addresses already banned are skipped, one sweep is capped, and each ban is written with a reason that says what it counted, which is also how the dashboard tells an automatic ban from a manual one.

The Security page

The admin panel reads all of this through the API rather than embedding Sentinel's own console, because the two answer different questions. The console is for investigating one address. The Security page is for the question an operator actually arrives with, which is whether anything is happening and whether they need to do something.

  • The graded score, with what the grades mean. It measures posture, not compromise: heavy scanning against a WAF in log-only mode pulls it down without anything having been breached.
  • Threats, unique addresses, critical count and blocked count over 24 hours, and the hourly shape of them.
  • What is being tried, which routes, and by whom, over seven days.
  • The threat log itself: filtered by severity, searched by address or path, and paged. A log of 18,000 rows cannot be acted on ten at a time.
  • Who is banned, whether automatically or by hand, and the way back out. The unban button matters more than the ban one.
  • Ban high-threat IPs, which runs the sweep now on the same policy the schedule uses. The schedule only sees what arrives after it is turned on, and the log it is turned on in front of is usually already full.

Every panel is sourced. When a call to Sentinel fails, the page says which one rather than rendering a zero, because a zero on a security dashboard reads as "you are safe", and that is the one wrong answer it must never give.

Security Headers

Six response headers, set on every response:

  • Content-Security-Policy: which origins may supply scripts, styles, images and frames. There is a report-only variant, so you can watch what a policy would have blocked before it blocks anything.
  • Strict-Transport-Security: this host is HTTPS only, for the next N seconds, remembered by the browser.
  • X-Frame-Options: DENY: your pages cannot be put in someone else's iframe, which is what clickjacking needs.
  • X-Content-Type-Options: nosniff: the browser believes your Content-Type instead of guessing, so an uploaded file cannot be guessed into a script.
  • Referrer-Policy: how much of the current URL is sent when a user follows a link away. The default leaks the path to third parties.
  • Permissions-Policy: which browser features (camera, microphone, geolocation) the page and its frames may ask for.

CSP is the one with a feedback loop: browsers post violations back, and Sentinel records them as CSPViolation findings. A sudden run of them usually means a policy that is too tight rather than an attack, and either way you learn it from the dashboard rather than from a user.

Anomaly Detection

The WAF asks whether a request looks like an attack. These six ask whether this account is behaving like itself, which catches the case where every individual request is perfectly valid, because the credentials are real and stolen.

impossible_travel

Signed in from two places further apart than anyone could travel between in the time elapsed

unusual_access

Reaching records or endpoints this account has never touched

data_exfiltration

Reading far more rows than this account normally reads

off_hours_access

Activity outside this account’s established working pattern

velocity_anomaly

Acting faster than a person does, without tripping a rate limit

credential_stuffing

One password tried across many accounts, seen across the whole application

Sensitivity is low, medium or high. These checks compare against a baseline, so they are quiet on a new deployment and get sharper as there is more history to be unlike. A match is recorded as an AnomalyDetected threat with the check that fired.

IP Geolocation

Every request is resolved to a country and city, from GeoLite2 (free) or GeoIP2 (paid). This is less a feature than a prerequisite: impossible travel cannot be computed without it, and a threat actor on the dashboard reads very differently with a country beside it.

The address it resolves is the one Sentinel decided to trust. Behind a proxy that means SENTINEL_TRUSTED_PROXIES: with it unset, forwarded headers are ignored entirely and every request geolocates to your load balancer.

Threat Dashboard

A dashboard at /sentinel/ui, updating over a WebSocket as requests arrive. It is organised by actor rather than by event: an address or account accumulates findings and carries a status of Active, Blocked or Whitelisted, so the question "what is this one caller doing" has an answer, and whitelisting the pen-tester is one action rather than a config change.

Findings are Low, Medium, High or Critical. They are kept in the store you point Sentinel at: sqlite, postgres, mysql or memory. Memory is genuinely in-memory, so a restart loses the history, which is a reasonable choice on a laptop and the wrong one in production.

Performance Monitoring

Per-route latency as p50, p95 and p99. It is here because the WAF is already in the request path and already knows which route this was, so the measurement is free; it is not a replacement for Pulse, which traces a request through its queries and tells you which line issued them. Use these numbers to notice that something got slower, and Pulse to find out why.

Configuration

Sentinel is enabled by default in every Grit project. Configure it through your .env file:

.env
# Security — Sentinel WAF, rate limiting, threat detection
SENTINEL_ENABLED=true
SENTINEL_USERNAME=admin
SENTINEL_PASSWORD=sentinel
SENTINEL_SECRET_KEY=change-me-in-production
SENTINEL_AUDIT_KEY=change-me-in-production
VariableDefaultDescription
SENTINEL_ENABLEDtrueSet to "false" to disable Sentinel entirely
SENTINEL_USERNAMEadminDashboard login username
SENTINEL_PASSWORDsentinelDashboard login password
SENTINEL_SECRET_KEYsentinel-secret...Secret for dashboard JWT sessions
SENTINEL_AUDIT_KEY(generated)Keys the audit log hash chain, so an entry edited with database access alone fails verification

Replicas, the audit key and the caller

A project scaffolded from v3.226.0 counts rate limits and AuthShield lockouts in Redis when Redis is configured, so every replica counts against the same numbers: counted per process, N replicas gave a client N times every limit. It keys the audit log with SENTINEL_AUDIT_KEY, and it tells Sentinel who made each request, which anomaly detection needs to see anything at all.

An older project gets the new Sentinel from grit upgrade, but its routes.go is its own, so these are yours to add to the sentinel.MountE call (and SentinelAuditKey to the config, read from SENTINEL_AUDIT_KEY):

apps/api/internal/routes/routes.go
import "github.com/MUKE-coder/sentinel/v2/redisstore"
sentinelStorage.AuditKey = cfg.SentinelAuditKey
// Shared by every replica. Without Redis, each process counts alone.
var sentinelCounters sentinel.CounterStore
if svc.Cache != nil {
sentinelCounters = redisstore.New(svc.Cache.Client())
}
err := sentinel.MountE(r, db, sentinel.Config{
Storage: sentinelStorage,
Counters: sentinelCounters,
// Read after the handler chain, when the auth middleware has set the caller.
UserExtractor: func(c *gin.Context) *sentinel.UserContext {
id := c.GetString("user_id")
if id == "" {
return nil
}
return &sentinel.UserContext{ID: id, Email: c.GetString("user_email"), Role: c.GetString("user_role")}
},
// ...the rest of the config as it was
})

How It Works

Sentinel is mounted in your routes.go Setup function, right after the global middleware (Logger, Recovery, CORS) and before any route registrations. This means every request passes through Sentinel's security middleware:

internal/routes/routes.go
// Mount Sentinel security suite. MountE returns an error so a bad
// config fails fast at boot instead of silently running unprotected.
if cfg.SentinelEnabled {
if err := sentinel.MountE(r, db, sentinel.Config{
Dashboard: sentinel.DashboardConfig{
Username: cfg.SentinelUsername,
Password: cfg.SentinelPassword,
SecretKey: cfg.SentinelSecretKey,
// Only dev may run on default creds; prod (gin.ReleaseMode) refuses them.
AllowInsecureDefaults: isDev,
},
WAF: sentinel.WAFConfig{
Enabled: true,
// Log-only in dev, block in production — set automatically.
Mode: func() sentinel.WAFMode {
if isDev { return sentinel.ModeLog }
return sentinel.ModeBlock
}(),
MaxBodyBytes: 1 * 1024 * 1024, // 1 MB (richtext payloads)
RejectOversizedBody: true,
TrustedProxies: cfg.SentinelTrustedProxies,
},
RateLimit: sentinel.RateLimitConfig{
Enabled: true,
ByIP: &sentinel.Limit{Requests: 100, Window: 1 * time.Minute},
ByRoute: map[string]sentinel.Limit{
"/api/auth/login": {Requests: 5, Window: 15 * time.Minute},
"/api/auth/register": {Requests: 3, Window: 15 * time.Minute},
},
},
AuthShield: sentinel.AuthShieldConfig{
Enabled: true,
LoginRoute: "/api/auth/login",
},
AutoBlock: sentinel.AutoBlockConfig{
Enabled: true,
// Sentinel's defaults: 10 threats of High or worse in 10 minutes
// bars the address for 24 hours.
//
// Loopback and the private ranges, because behind a proxy that
// Sentinel has not been told to trust, every request carries the
// proxy's address and blocking it blocks everybody.
ExemptIPs: autoBlockExempt(cfg),
},
Anomaly: sentinel.AnomalyConfig{
Enabled: true,
},
Geo: sentinel.GeoConfig{
Enabled: true,
},
}); err != nil {
log.Fatalf("mounting Sentinel: %v", err)
}
}

The middleware execution order is: Auth Shield (intercepts login attempts) → WAF (inspects all input vectors) → Rate Limiter (enforces request limits) → Security Headers (injects response headers) → Performance Monitor (tracks latency).

What the WAF does not inspect

A few routes have to be exempt from body inspection, and wafExcludedRoutes() in internal/routes/routes.go is the list. A photograph is larger than the inspection cap by design. And a richtext body is <p>, <strong> and <img> by definition, so the XSS heuristics flag ordinary markup, and a post whose body quotes a shell command trips the traversal and command-injection rules on the ../ and the $( inside a code block.

internal/routes/routes.go
paths := []string{
"/blogs", "/blogs/*",
"/admin/blogs", "/admin/blogs/*",
"/uploads", "/uploads/*",
"/*/import", // a spreadsheet is over the body cap
"/public/forms/*",
// grit generate resource adds a resource here when it emits a richtext field.
// grit:waf:richtext
}

Every richtext resource is listed twice, at its public path and again under /admin. A body is inspected on the way in, so it is the writes that carry the markup, and the admin panel writes through the /admin prefix. With only the public path listed, a post could be published once and then never edited: every PUT from the admin was answered 403 and logged as a critical threat. That was issue 90, fixed in v3.335.0; grit upgrade adds the missing entries to a project generated before it.

Exclusion is from body inspection only. These routes still pass through authentication, RBAC, binding validation, sanitize:"html" and the rate limits. The HTML is cleaned on every write whether the WAF looked at it or not, which is what actually protects the reader: a WAF pattern match is a guess about intent, and an allowlist sanitizer is not.

Only richtext fields earn an entry, never text. Nearly every resource has a description or a note, and exempting all of them would leave the WAF inspecting nothing worth inspecting. If a plain text column does carry code, add that resource to the list by hand above the grit:waf:richtext marker.

In development the WAF runs in log mode, so a body it dislikes is recorded and served anyway. It blocks outside development. That is worth knowing when a payload works on your laptop and returns 403 in staging: set APP_ENV to anything but development to reproduce it locally, and read the evidence in /sentinel/ui, which names the pattern and the substring that matched.

Security Dashboard

Sentinel ships with an embedded React dashboard at /sentinel/ui. Log in with the username and password from your .env file (default: admin / sentinel).

The dashboard provides:

  • Threat feed -- real-time threat events via WebSocket with severity, type, and source IP
  • Threat actors -- automatic profiling with risk scores, attack types, and geolocation
  • Security score -- weighted score across 5 dimensions with actionable recommendations
  • Analytics -- attack trends, geographic distribution, top targeted routes
  • WAF rules -- view and configure rules, test payloads, add custom patterns
  • Rate limits -- view active limits and live counter states
  • IP management -- block/unblock IPs, view blocked list
  • Audit logs -- GORM-level CREATE/UPDATE/DELETE audit trail with before/after diffs
  • Performance -- per-route latency metrics (p50/p95/p99) and error rates
  • Compliance reports -- generate GDPR, PCI-DSS, and SOC2 reports

The dashboard is also embedded in the admin panel under System → Security for convenience.

WAF Modes

The Web Application Firewall has two modes:

ModeLogdev default

Detects and logs threats but does not block requests. Use during development and initial deployment to identify false positives before switching to block mode.

ModeBlockproduction

Detects threats and blocks malicious requests with a 403 response. Switch to this mode in production after verifying no false positives in log mode.

Grit picks the mode for you: ModeLog in development and ModeBlock in production (gin.ReleaseMode), so you log-and-review locally and block for real once deployed. Override the Mode in routes.go if you want a fixed mode, or toggle it at runtime from the dashboard.

The WAF detects the following attack types with configurable sensitivity per rule (off, low, medium, strict):

✓SQL Injection (basic, blind, stacked)
✓Cross-Site Scripting (XSS)
✓Path Traversal
✓Command Injection
✓Server-Side Request Forgery (SSRF)
✓XML External Entity (XXE)
✓Local File Inclusion (LFI)
✓Open Redirect

Rate Limiting

Grit configures sensible rate limits out of the box. You can customize them in routes.go:

internal/routes/routes.go
RateLimit: sentinel.RateLimitConfig{
Enabled: true,
ByIP: &sentinel.Limit{Requests: 100, Window: 1 * time.Minute},
ByRoute: map[string]sentinel.Limit{
"/api/auth/login": {Requests: 5, Window: 15 * time.Minute},
"/api/auth/register": {Requests: 3, Window: 15 * time.Minute},
"/api/uploads": {Requests: 10, Window: 1 * time.Minute},
},
// Optional: per-user and global limits
// ByUser: &sentinel.Limit{Requests: 200, Window: 1 * time.Minute},
// Global: &sentinel.Limit{Requests: 1000, Window: 1 * time.Minute},
Strategy: sentinel.SlidingWindow, // or FixedWindow, TokenBucket
},

Auth Shield

The auth shield protects your login endpoint from brute-force attacks. When enabled, it automatically tracks failed login attempts per IP address and locks out attackers after too many failures.

internal/routes/routes.go
AuthShield: sentinel.AuthShieldConfig{
Enabled: true,
LoginRoute: "/api/auth/login",
MaxFailedAttempts: 5, // Lock after 5 failures (default)
LockoutDuration: 15 * time.Minute, // 15-minute lockout (default)
CredentialStuffingDetection: true, // Detect credential lists
BruteForceDetection: true, // Detect brute-force patterns
},

Locked-out users can be unblocked from the dashboard or via the API.

Custom WAF Rules

You can add custom WAF rules to detect application-specific attack patterns:

internal/routes/routes.go
WAF: sentinel.WAFConfig{
Enabled: true,
Mode: sentinel.ModeBlock,
CustomRules: []sentinel.WAFRule{
{
ID: "block-admin-enum",
Name: "Block admin enumeration",
Pattern: `(?i)/(wp-admin|phpmyadmin|administrator)`,
AppliesTo: []string{"path"},
Severity: sentinel.SeverityMedium,
Action: "block",
Enabled: true,
},
},
ExcludeRoutes: []string{"/api/health"}, // Skip WAF for health checks
},

Custom rules can also be managed at runtime from the dashboard without redeploying.

AI-Powered Analysis

If you have an AI API key configured (Claude, OpenAI, or Gemini), Sentinel can use it for intelligent threat analysis:

internal/routes/routes.go
AI: &sentinel.AIConfig{
Provider: sentinel.Claude, // or sentinel.OpenAI, sentinel.Gemini
APIKey: cfg.AIAPIKey, // Reuse your existing AI API key
DailySummary: true, // Generate daily threat summaries
},
  • Threat analysis -- AI evaluates individual threats and provides context
  • Actor assessment -- AI profiles threat actors and predicts intent
  • Daily summaries -- automated security briefings
  • Natural language queries -- ask questions about your security data
  • WAF recommendations -- AI suggests new rules based on attack patterns

Alerts

Sentinel can send real-time alerts when threats are detected. Configure one or more channels:

internal/routes/routes.go
Alerts: sentinel.AlertConfig{
MinSeverity: sentinel.SeverityHigh,
Slack: &sentinel.SlackConfig{
WebhookURL: "https://hooks.slack.com/services/...",
},
Email: &sentinel.EmailConfig{
SMTPHost: "smtp.example.com",
SMTPPort: 587,
Username: "alerts@example.com",
Password: "smtp-password",
Recipients: []string{"security@example.com"},
},
Webhook: &sentinel.WebhookConfig{
URL: "https://your-siem.example.com/webhook",
Headers: map[string]string{"X-Token": "your-token"},
},
},

Production Checklist

Before deploying to production, make sure to:

1Change SENTINEL_PASSWORD and SENTINEL_SECRET_KEY to strong, unique values
2Switch WAF mode from ModeLog to ModeBlock after reviewing logs for false positives
3Configure at least one alert channel (Slack, email, or webhook)
4Review rate limits and adjust for your expected traffic
5Set up IP reputation checking with an AbuseIPDB API key for auto-blocking known bad actors
6Consider enabling AI-powered analysis for automated threat intelligence

Disabling Sentinel

If you don't need Sentinel, set SENTINEL_ENABLED=false in your .env file. The app will run normally without any security middleware or dashboard -- no code changes needed.