Verify New Relic webhooks
New Relic doesn't sign webhook requests, so there's no signature to check. Authorization is optional on a Webhook destination, but once you choose Basic Authentication, you decode the Authorization: Basic header and compare the username and password in constant time. That shows the sender knows the credentials, but it doesn't cover the body or stop a replayed request.
The facts
New Relic webhook secret
New Relic doesn't issue a secret. You choose a username and password and enter them on the Webhook destination, under Use authorization. Keep it in an environment variable, not in source code.
- Choose a username and a long random password yourself, then enter them on the Webhook destination: **Alerts**, **Destinations**, **Webhook**, **Use authorization**, **Basic Authentication**.
- The credentials belong to the destination, so every workflow that notifies it sends the same pair.
- The same option offers a Bearer Token, and a destination can also carry encrypted custom headers. Those are alternatives to Basic, and New Relic computes nothing over the body with any of them.
- To rotate, change the value on the destination and in your handler together. New Relic reports a destination whose credentials stopped working with the status
AUTH_ERROR.
Source: New Relic docs ↗
Code
// Generated with: new-relic-webhooks skill
// https://github.com/hookdeck/webhook-skills
require('dotenv').config({ quiet: true });
const crypto = require('crypto');
const express = require('express');
const app = express();
/**
* Constant-time comparison. Hashing both sides first gives equal-length buffers,
* so timingSafeEqual never throws and the credential's length isn't leaked.
*/
function safeEqual(a, b) {
const ha = crypto.createHash('sha256').update(a).digest();
const hb = crypto.createHash('sha256').update(b).digest();
return crypto.timingSafeEqual(ha, hb);
}
/**
* New Relic does not sign webhooks. A Webhook destination can send
* "Authorization: Basic base64(username:password)", which authenticates the sender
* only. It does not cover the body and gives no replay protection.
*/
function verifyNewRelicRequest(
headers,
username = process.env.NEW_RELIC_WEBHOOK_USERNAME,
password = process.env.NEW_RELIC_WEBHOOK_PASSWORD
) {
if (!username || !password) return false; // never accept when unconfigured
const match = /^basic\s+([A-Za-z0-9+/]+={0,2})\s*$/i.exec(headers['authorization'] || '');
if (!match) return false;
const decoded = Buffer.from(match[1], 'base64');
const colon = decoded.indexOf(0x3a); // split on the FIRST colon: passwords may contain ':'
if (colon === -1) return false;
// Evaluate both comparisons before deciding (no short-circuit).
const userOk = safeEqual(decoded.subarray(0, colon), Buffer.from(username));
const passOk = safeEqual(decoded.subarray(colon + 1), Buffer.from(password));
return userOk && passOk;
}
// The payload comes from a Handlebars template you write in the workflow, so there is no
// fixed event field. This handler assumes the illustrative template in references/setup.md,
// which sends issueId, title, state, acknowledged, priority and issuePageUrl. state is New
// Relic's issue life cycle state (CREATED, ACTIVATED, CLOSED); acknowledged is its
// isAcknowledged boolean.
function handleIssue(payload) {
const { issueId, title, priority, issuePageUrl } = payload;
const state = String(payload.state || '').toUpperCase();
const acknowledged = payload.acknowledged === true || payload.acknowledged === 'true';
switch (state) {
case 'CREATED':
case 'ACTIVATED':
if (acknowledged) {
console.log(`Issue acknowledged: ${issueId} ${title}`);
// Your code: mark the ticket as being worked
} else {
console.log(`Issue ${state.toLowerCase()}: ${issueId} ${title} (${priority}) ${issuePageUrl}`);
// Your code: page on-call or open a ticket
}
break;
case 'CLOSED':
console.log(`Issue closed: ${issueId} ${title}`);
// Your code: close the matching ticket
break;
default:
console.log(`Unhandled state: ${payload.state}`);
}
}
// Read the body raw (any content type) so the request is authenticated before parsing.
app.post('/webhooks/new-relic', express.raw({ type: '*/*' }), (req, res) => {
if (!verifyNewRelicRequest(req.headers)) {
return res
.status(401)
.set('WWW-Authenticate', 'Basic realm="new-relic"')
.json({ error: 'Invalid or missing Basic credentials' });
}
let payload;
try {
const raw = Buffer.isBuffer(req.body) ? req.body.toString('utf8') : '';
payload = JSON.parse(raw);
} catch {
return res.status(400).json({ error: 'Invalid JSON body' });
}
if (!payload || typeof payload !== 'object' || Array.isArray(payload)) {
return res.status(400).json({ error: 'Expected a JSON object' });
}
try {
handleIssue(payload);
} catch (err) {
console.error('Error handling New Relic notification:', err);
return res.status(500).json({ error: 'Handler error' });
}
res.status(200).json({ received: true });
});
app.get('/health', (req, res) => {
res.json({ status: 'ok' });
});
module.exports = app;
module.exports.verifyNewRelicRequest = verifyNewRelicRequest;
if (require.main === module) {
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server running on http://localhost:${PORT}`);
console.log(`Webhook endpoint: POST http://localhost:${PORT}/webhooks/new-relic`);
});
} // Generated with: new-relic-webhooks skill
// https://github.com/hookdeck/webhook-skills
import { NextRequest, NextResponse } from 'next/server';
import { verifyNewRelicRequest } from '../../../lib/verify-new-relic';
// Shape of the illustrative Handlebars template in references/setup.md.
// The real payload is whatever template you configure in the workflow. state is New Relic's
// issue life cycle state (CREATED, ACTIVATED, CLOSED); acknowledged is its isAcknowledged boolean.
interface NewRelicIssuePayload {
issueId?: string;
title?: string;
state?: string;
acknowledged?: boolean | string;
priority?: string;
issuePageUrl?: string;
[key: string]: unknown;
}
function handleIssue(payload: NewRelicIssuePayload): void {
const { issueId, title, priority, issuePageUrl } = payload;
const state = String(payload.state || '').toUpperCase();
const acknowledged = payload.acknowledged === true || payload.acknowledged === 'true';
switch (state) {
case 'CREATED':
case 'ACTIVATED':
if (acknowledged) {
console.log(`Issue acknowledged: ${issueId} ${title}`);
// Your code: mark the ticket as being worked
} else {
console.log(`Issue ${state.toLowerCase()}: ${issueId} ${title} (${priority}) ${issuePageUrl}`);
// Your code: page on-call or open a ticket
}
break;
case 'CLOSED':
console.log(`Issue closed: ${issueId} ${title}`);
// Your code: close the matching ticket
break;
default:
console.log(`Unhandled state: ${payload.state}`);
}
}
export async function POST(request: NextRequest) {
// Authenticate before reading or parsing the body.
if (!verifyNewRelicRequest(request.headers)) {
return NextResponse.json(
{ error: 'Invalid or missing Basic credentials' },
{ status: 401, headers: { 'WWW-Authenticate': 'Basic realm="new-relic"' } }
);
}
let payload: unknown;
try {
// Read as text so any content type is accepted.
payload = JSON.parse(await request.text());
} catch {
return NextResponse.json({ error: 'Invalid JSON body' }, { status: 400 });
}
if (!payload || typeof payload !== 'object' || Array.isArray(payload)) {
return NextResponse.json({ error: 'Expected a JSON object' }, { status: 400 });
}
try {
handleIssue(payload as NewRelicIssuePayload);
} catch (err) {
console.error('Error handling New Relic notification:', err);
return NextResponse.json({ error: 'Handler error' }, { status: 500 });
}
return NextResponse.json({ received: true });
} # Generated with: new-relic-webhooks skill
# https://github.com/hookdeck/webhook-skills
import base64
import binascii
import hashlib
import hmac
import json
import os
import re
from dotenv import load_dotenv
from fastapi import Depends, FastAPI, HTTPException, Request
load_dotenv()
app = FastAPI()
_BASIC = re.compile(r"^basic\s+([A-Za-z0-9+/]+={0,2})\s*$", re.IGNORECASE)
def safe_equal(a: bytes, b: bytes) -> bool:
"""Constant-time comparison (compare_digest on equal-length digests of bytes)."""
return hmac.compare_digest(hashlib.sha256(a).digest(), hashlib.sha256(b).digest())
def verify_new_relic_request(headers, username=None, password=None) -> bool:
"""New Relic does not sign webhooks. A Webhook destination can send
"Authorization: Basic base64(username:password)", which authenticates the sender
only. It does not cover the body and gives no replay protection.
"""
username = username if username is not None else os.environ.get("NEW_RELIC_WEBHOOK_USERNAME")
password = password if password is not None else os.environ.get("NEW_RELIC_WEBHOOK_PASSWORD")
if not username or not password:
return False # never accept when unconfigured
match = _BASIC.match(headers.get("authorization") or "")
if not match:
return False
try:
decoded = base64.b64decode(match.group(1), validate=True)
except (binascii.Error, ValueError):
return False
# Split on the FIRST colon: passwords may contain ':'.
user_part, sep, pass_part = decoded.partition(b":")
if not sep:
return False
# Evaluate both comparisons before deciding (no short-circuit). Compare bytes, never str.
user_ok = safe_equal(user_part, username.encode("utf-8"))
pass_ok = safe_equal(pass_part, password.encode("utf-8"))
return user_ok and pass_ok
async def require_new_relic_basic_auth(request: Request) -> None:
"""FastAPI dependency: reject the request before the body is parsed."""
if not verify_new_relic_request(request.headers):
raise HTTPException(
status_code=401,
detail="Invalid or missing Basic credentials",
headers={"WWW-Authenticate": 'Basic realm="new-relic"'},
)
def handle_issue(payload: dict) -> None:
# The payload comes from a Handlebars template you write in the workflow, so there is
# no fixed event field. This handler assumes the illustrative template in
# references/setup.md, which sends issueId, title, state, acknowledged, priority and
# issuePageUrl. state is New Relic's issue life cycle state (CREATED, ACTIVATED, CLOSED);
# acknowledged is its isAcknowledged boolean.
issue_id = payload.get("issueId")
title = payload.get("title")
priority = payload.get("priority")
url = payload.get("issuePageUrl")
state = str(payload.get("state") or "").upper()
acknowledged = payload.get("acknowledged") in (True, "true")
if state in ("CREATED", "ACTIVATED"):
if acknowledged:
print(f"Issue acknowledged: {issue_id} {title}")
# Your code: mark the ticket as being worked
else:
print(f"Issue {state.lower()}: {issue_id} {title} ({priority}) {url}")
# Your code: page on-call or open a ticket
elif state == "CLOSED":
print(f"Issue closed: {issue_id} {title}")
# Your code: close the matching ticket
else:
print(f"Unhandled state: {payload.get('state')}")
@app.post("/webhooks/new-relic", dependencies=[Depends(require_new_relic_basic_auth)])
async def new_relic_webhook(request: Request):
# Read the raw body so any content type is accepted.
raw_body = await request.body()
try:
payload = json.loads(raw_body)
except (json.JSONDecodeError, UnicodeDecodeError):
raise HTTPException(status_code=400, detail="Invalid JSON body")
if not isinstance(payload, dict):
raise HTTPException(status_code=400, detail="Expected a JSON object")
try:
handle_issue(payload)
except Exception as err: # noqa: BLE001
print(f"Error handling New Relic notification: {err}")
raise HTTPException(status_code=500, detail="Handler error")
return {"received": True}
@app.get("/health")
async def health():
return {"status": "ok"}
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=8000) Or install the New Relic webhooks skill:
npx skills add hookdeck/webhook-skills --skill new-relic-webhooks
Common failures
The destination has no authorization
**Use authorization** is optional, so a destination without it sends no credentials to check. Turn it on and choose **Basic Authentication**.
The destination uses another option
A Bearer Token or a custom header doesn't send Basic credentials, so this check rejects the request. Change the destination to Basic Authentication.
The password contains a colon
The decoded header is username:password. Split it on the first colon only, because a password can contain more.
The credentials changed in only one place
Change them on the destination and in your handler together. New Relic shows a destination with bad credentials as AUTH_ERROR.
Let Event Gateway check New Relic credentials.
Event Gateway checks the Basic username and password on each New Relic request, and a request that doesn't match never reaches your service. It queues the rest and retries failures on your schedule.