Skip to main content
ALTCHA®

Backend & API protection

Your own APIs are called without a browser form: by mobile apps, single-page apps, partners and scripts. This page covers both sides of protecting them: screening requests to your API with Sentinel's detection APIs, and locking down the restricted key your backend uses for those calls, so a leaked key is useless elsewhere.

Prerequisites: a running Sentinel with an active license, and an admin user who can edit security groups and API keys. See API keys & access levels for which credential each endpoint accepts.

What you're defending against

ThreatWhat stops it
Scraping and abuse of your API from data centers, proxies and TorThe IP rules (HOSTING, PROXY, TOR, MALICIOUS) and the threat verdict, checked per request from your backend.
Scripts that hammer an endpoint, per token or per userThe classifier's rateLimit, keyed by whatever identifies the caller in your API.
Requests from known-bad IPsPOST /v2/threat, which reads only Sentinel's own threat lists and entries, without calling an IP resolver.
A leaked restricted key used from elsewhereAn IP allow-list in the key's security group: every other IP gets 403 ACCESS_DENIED.
A server key copied into a web page or appThe api_key_browser and api_key_bearer alerts, and Sentinel refusing a restricted key sent without its secret.
Sentinel's management and detection endpoints reachable from the internetA separate public listener that serves only the widget endpoints.

Backend group and key

Create a restricted security group for your backend and apply the Backend API (allowed IPs) preset (server) from Templates. As Networks, enter the IPs or CIDR ranges your servers connect to Sentinel from: their private addresses if they reach Sentinel over a private network. It writes two rules:

RuleEffect
preset:server:gateallow only from the listed networks; every other IP gets 403 ACCESS_DENIED with IP not allowed..
preset:server:base600/1m(key=uid) with rateLimit.scope account: one budget for all of the account's server keys, whatever IP they come from.

Then add a rule after the preset that tunes the classifier for API traffic. If your mobile app calls your API with its own User-Agent token, trust it, so the device rules don't flag it as a script:

{
  "name": "api-classifier",
  "action": "set",
  "set": [
    { "field": "classifier.trustedApps", "value": "altcha-app altcha-rn altcha-flutter exampleapp" }
  ]
}

With this, a User-Agent containing exampleapp/<version> scores 0 on USER_AGENT_HEADER_UNCOMMON, CLI and LIBRARY. The default list holds the three ALTCHA native widgets; list them again if you use them. If your API's callers are other servers, disable those three rules with classifier.disableRules instead. See Classifier set fields.

Create a restricted API key in this group. Use one key per backend service, so you can rotate or delete one without touching the others; the preset's rate limit is shared by all of them. See Managing API keys.

Server configuration

[server]
host = "10.0.0.5"                       # main listener on the private network your backends use

[server.public_api]
enabled = true                          # widget endpoints only, published to the internet
port = 3003

[rate_limit]
global = "5000/1m"                      # per client IP; raise it above your backend's request rate
  • Two listeners. The main listener serves every /v2 route, including detection, management and POST /v2/verify/signature. Keep it on the private network your backends use, and publish only [server.public_api], which serves the widget endpoints and GET /v2/inspect. See Listeners & reverse proxy.
  • Global limit. [rate_limit] global (default 100/1m) counts every request per client IP before any rule, and all your backend's calls come from a few IPs. Below your request rate, your backend gets 429 RATE_LIMITED long before the preset's 600/1m. See Rate limiting & penalty.
  • Client IP. If a proxy sits between your backends and Sentinel, list it in [server] trusted_proxies; otherwise the allow-list compares the proxy's address. See Client IP.

Alerts

These alerts watch restricted and full keys and are on by default:

AlertRaised when
api_key_deniedA key with a valid secret is denied by its group, for example from an IP outside the allow-list. Whoever sent it holds the secret.
api_key_networksA key is used from too many distinct networks within the window.
api_key_wrong_secretA key gets repeated wrong secrets.
api_key_browserA key is sent with an Origin or Referer header, that is, from a web page.
api_key_bearerA key id is sent without its secret.

Send them to your incident channel with a webhook. See Alerts.

Integration steps

Step 1 — Check that the key works only from your servers

Call GET /v2/inspect with the backend key from one of your servers, and from a machine outside the allow-list:

curl -s 'https://sentinel.internal.example.com/v2/inspect' -u 'key_…:sec_…'

From your server, the response is 200 with the inspect data. From elsewhere:

{ "code": "ACCESS_DENIED", "error": "IP not allowed.", "statusCode": 403, "data": { … } }

The denied call also raises api_key_denied, which shows the alert works. See Restrict a backend key to your servers.

Step 2 — Screen requests to your API

Call POST /v2/classifier from your API, with the caller's IP and headers and a rate limit keyed by the caller. This Express middleware refuses rate-limited callers and callers from malicious or blocked IPs, and passes the classification on to your handlers:

import type { NextFunction, Request, Response } from 'express';

const SENTINEL_AUTH =
  'Basic ' + Buffer.from(`key_…:${process.env.SENTINEL_API_KEY_SECRET}`).toString('base64');

export async function screenApiRequest(req: Request, res: Response, next: NextFunction) {
  const caller = req.get('authorization') ?? req.ip; // your API token, user id or IP
  let data;
  try {
    const r = await fetch('https://sentinel.internal.example.com/v2/classifier', {
      method: 'POST',
      headers: { Authorization: SENTINEL_AUTH, 'Content-Type': 'application/json' },
      body: JSON.stringify({
        ip: req.ip,
        headers: {
          'user-agent': req.get('user-agent') ?? '',
          accept: req.get('accept') ?? '',
          'accept-language': req.get('accept-language') ?? '',
        },
        rateLimit: { limit: '60/1m,1000/1h', customKey: hashOf(caller) }, // hashOf: your SHA-256 helper
      }),
      signal: AbortSignal.timeout(1500),
    });
    if (!r.ok) throw new Error(`Sentinel: ${r.status}`);
    ({ data } = await r.json());
  } catch {
    return next(); // fail open: Sentinel is unreachable or slow
  }

  if (data.rateLimit?.triggeredRules.includes('RATE_LIMIT')) {
    res.set('Retry-After', String(data.rateLimit.resetInSec));
    return res.status(429).json({ error: 'Too many requests.' });
  }
  if (data.ip?.action === 'block' || data.ip?.triggeredRules.includes('MALICIOUS')) {
    return res.status(403).json({ error: 'Access denied.' });
  }
  res.locals.sentinel = data; // e.g. require extra verification when classification is BAD
  next();
}
  • Fail open or closed. The middleware lets requests through when Sentinel doesn't answer within 1.5 seconds. For endpoints where abuse is costly, such as payments or sign-up, fail closed instead.
  • IP lookups have a cost. The IP category resolves the client IP through the [ip_resolver] providers. A remote provider such as ip-api adds a network call and has its own rate limit; a local MaxMind database doesn't. See IP resolvers.
  • Screen what matters. For high-volume read endpoints, call Sentinel only for unauthenticated or first requests, or use the faster IP-only check below.

For an IP-only check without the IP resolvers, call POST /v2/threat:

curl -X POST https://sentinel.internal.example.com/v2/threat \
  -u 'key_…:sec_…' \
  -H 'Content-Type: application/json' \
  -d '{ "ip": "81.2.69.142" }'
{ "data": { "threats": [ { "source": "firehol_level1", "kind": "malicious", "action": "block", "threatScore": null, "match": "81.2.69.0/24" } ], "action": "block", "time": 0.14 } }

Refuse the request when action is block. See Check an IP.

Step 3 — Put the widget in front of your own clients

When the API is called by your own web or mobile app, a valid widget payload is stronger evidence than any header: send the widget's altcha payload with the API request and verify it in your API with POST /v2/verify/signature, as in Verifying submissions. The widget's public key goes in a public group of its own, with a base preset such as Recommended.

The ALTCHA mobile widgets (altcha-app, altcha-rn, altcha-flutter) are trusted apps by default, so their non-browser User-Agent doesn't count against them. See Native apps.

Monitoring & tuning

  • Log the backend key. Set its Request logging to All. Every authenticated call is then logged with its status and triggeredRules, including calls the gate denies; filter the logs by the key and Status 4xx to find them. Rate-limited calls (429) aren't logged. See Request logs & analytics.
  • Read the rate-limit headers. Allowed calls with a restricted key carry X-RateLimit-Limit, X-RateLimit-Window and X-RateLimit-Remaining for the preset's limit, so your backend sees when it approaches 600/1m. Raise the preset's rateLimit.limits if your traffic needs more.
  • Add a server. Add its IP to the gate's Networks and re-apply the preset, or edit preset:server:gate on the JSON tab. Do this before the new server sends traffic.
  • Rotate after an alert. After api_key_denied or api_key_browser, assume the secret leaked: create a new key, deploy it, and delete the old one. See Managing API keys.
  • Don't block your own backend. The server preset has no threats rule, because your backend's IP can get an automatic threat entry, for example after a burst of 429 RATE_LIMITED. Keep it that way, and give your servers' IPs manual allow threat entries. See Threat intelligence: Tuning.

Start typing to search...

↑ ↓ Navigate ↵ Select