Securing credentials and webhooks¶
Whoever holds a server's key sends email as your domain. This guide shows how to store the key, how to protect the endpoint that receives webhooks and how to reduce the damage if something leaks.
Protect the credentials¶
The server key is used for the API (X-Server-API-Key header), for SMTP (password) and for the SES-compatible interface (secret key). Treat it as a production password.
Where to keep it¶
| Place | Recommendation |
|---|---|
| Secret manager (HashiCorp Vault, AWS Secrets Manager, Google Secret Manager, Azure Key Vault, Kubernetes Secrets) | Preferred. The application reads the key at run time |
| Environment variable injected by the deploy platform | Suitable |
Local .env file, outside version control | Suitable for development |
| Source code, Git repository, container image | Never |
| Mobile app, browser JavaScript, distributed desktop application | Never |
| Email, chat, ticket, screenshot | Never |
Never on the client side
Any key embedded in a mobile app or a web page can be extracted by whoever uses the app. Sending must always start from your backend. If the browser or the app needs to trigger an email, it calls your API, and your API calls FrontEngine.
In transit¶
- The API must only be called over
https://. - SMTP requires TLS to authenticate: use port
587with STARTTLS or465with implicit TLS. The minimum version is TLS 1.2. - Do not turn off certificate verification in the client (
verify=False,rejectUnauthorized: false,InsecureSkipVerify). If verification fails, fix the cause. See Troubleshooting.
In your logs¶
- Do not write the key to logs. Watch out for HTTP libraries in debug mode, which log request headers.
- Do not include the key in error reports sent to third-party services.
- On an
InvalidServerAPIKeyerror, the API answer repeats the value it received in thetokenfield. Do not log that answer's body without masking the field.
Rotation¶
The key is shown once and cannot be recovered. Rotation goes through support, without interruption, because a server can have two active credentials at the same time. The procedure is in Account, servers and credentials.
Replace the key:
- at regular intervals, set by your internal policy;
- when someone with access to the key leaves the team;
- immediately, on any suspicion of exposure.
If the key leaked, write to [email protected] or [email protected] asking for the credential to be disabled. Do not send the key in the request.
Least privilege: one server per application¶
In FrontEngine, the unit of isolation is the server. Each server has its own credentials, domains, webhooks and suppression list.
- One server per application. If application A's key leaks, application B is not affected and only A's credential has to be replaced.
- One server per environment. Staging and production with different keys keep a test from sending to real customers.
- One credential per sending system. If two services use the same server, ask for one credential each. You can then disable one without stopping the other.
- Only the domains needed. Link to each server only the domains that application uses in
From:.
Not available yet
Restricting a credential by source IP address, two-factor authentication and credentials with partial permissions (for example, send only) do not exist today. Separation by server is the control available.
Protect the webhook endpoint¶
The endpoint that receives events is a public URL. Anyone who discovers it can send forged requests. The signature is what lets you tell the real ones apart.
Verify the signature¶
Each request carries three headers:
| Header | Content |
|---|---|
X-Postal-Signature-256 | RSA PKCS#1 v1.5 signature with SHA-256 of the request body, in Base64 |
X-Postal-Signature | The same signature with SHA-1, kept for compatibility |
X-Postal-Signature-KID | Identifier of the key that signed |
The public key is published in JWKS format at https://api.frontengine.net/.well-known/jwks.json. Use X-Postal-Signature-256.
The signature is computed over the exact bytes of the body. Verify before parsing the JSON. If your framework re-serializes the body, verification fails.
import base64
import requests
from cryptography.exceptions import InvalidSignature
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.asymmetric import padding, rsa
from flask import Flask, abort, request
JWKS_URL = "https://api.frontengine.net/.well-known/jwks.json"
app = Flask(__name__)
_keys = {}
def _b64url_int(value: str) -> int:
padded = value + "=" * (-len(value) % 4)
return int.from_bytes(base64.urlsafe_b64decode(padded), "big")
def public_key(kid: str):
if kid not in _keys:
for jwk in requests.get(JWKS_URL, timeout=10).json()["keys"]:
numbers = rsa.RSAPublicNumbers(_b64url_int(jwk["e"]), _b64url_int(jwk["n"]))
_keys[jwk["kid"]] = numbers.public_key()
return _keys.get(kid)
@app.post("/webhooks/frontengine")
def webhook():
body = request.get_data() # exact bytes, before any parsing
key = public_key(request.headers.get("X-Postal-Signature-KID", ""))
signature = request.headers.get("X-Postal-Signature-256", "")
if key is None or not signature:
abort(401)
try:
key.verify(base64.b64decode(signature), body, padding.PKCS1v15(), hashes.SHA256())
except (InvalidSignature, ValueError):
abort(401)
event = request.get_json()
# store event["uuid"] and discard repeats; process later, in a queue
return "", 200
import crypto from "node:crypto";
import express from "express";
const JWKS_URL = "https://api.frontengine.net/.well-known/jwks.json";
const keys = new Map();
async function publicKey(kid) {
if (!keys.has(kid)) {
const { keys: jwks } = await (await fetch(JWKS_URL)).json();
for (const jwk of jwks) {
keys.set(jwk.kid, crypto.createPublicKey({ key: jwk, format: "jwk" }));
}
}
return keys.get(kid);
}
const app = express();
// express.raw keeps the exact bytes of the body
app.post("/webhooks/frontengine", express.raw({ type: "application/json" }), async (req, res) => {
const key = await publicKey(req.get("X-Postal-Signature-KID") ?? "");
const signature = req.get("X-Postal-Signature-256") ?? "";
if (!key || !signature) return res.sendStatus(401);
const valid = crypto.verify("RSA-SHA256", req.body, key, Buffer.from(signature, "base64"));
if (!valid) return res.sendStatus(401);
const event = JSON.parse(req.body.toString("utf8"));
// store event.uuid and discard repeats; process later, in a queue
res.sendStatus(200);
});
app.listen(3000);
Cache the public key and fetch the JWKS again when an unknown kid shows up.
Other protections¶
- Use
https://with a valid certificate. - Use a hard-to-guess path in the URL, as a complement. It does not replace the signature.
- Discard repeats by
uuid. Delivery is at least once: a retry carries the sameuuid. - Answer fast. FrontEngine waits 5 seconds for the answer. Any
2xxcounts as delivered. Store the event, answer and process afterwards. - Expect a limited number of retries. There are 6 attempts in total. After that the event is dropped.
- Do not act on event data without validating it. Treat the fields as external input: validate types and sizes and do not build SQL queries or commands from them.
- Limit the size and rate of the requests the endpoint accepts, so that it does not bring your application down if it is abused.
- Expose only that path. The webhook endpoint does not need access to your application's administrative routes.
The webhook URL must resolve to a public address. Destinations on private networks are refused and redirects are not followed.
The same rules apply to the endpoint that receives email. See Inbound email to HTTP endpoints.
Checklist¶
- The key is in a secret manager or an environment variable, outside the repository.
- No key in a mobile app or in browser code.
- One server per application and per environment.
- TLS certificate verification on in every client.
- Logs record neither the key nor authentication headers.
- The webhook endpoint verifies
X-Postal-Signature-256over the raw body. - Repeated events are discarded by
uuid. - There is an owner and a procedure for replacing the key.