diff --git a/README.md b/README.md
index b8f015ad2..552433c60 100644
--- a/README.md
+++ b/README.md
@@ -73,6 +73,8 @@ Access the UI at http://localhost:8000. Log in with the default credentials `adm
Source builds of this fork include a [community PromQL query API](docs/promql.md) for OTLP metrics, with instant and range queries and no Enterprise dependency. See the guide for the supported language subset and limits.
+To send firing and recovery events to an automation, see [Generic alert webhook payloads](docs/webhook-alerts.md).
+
For production deployments, refer to the [installation guide ↗︎](https://www.parseable.com/docs/self-hosted/installation) for best practices and hardening tips.
> [!TIP]
diff --git a/docs/webhook-alerts.md b/docs/webhook-alerts.md
new file mode 100644
index 000000000..19722536e
--- /dev/null
+++ b/docs/webhook-alerts.md
@@ -0,0 +1,41 @@
+# Generic alert webhook payloads
+
+Generic webhook targets send the existing plain-text message by default. To receive JSON, set `payloadFormat` to `"json"` when creating a target with `POST /api/v1/targets`. For example, the following target uses a placeholder Bearer token.
+
+```json
+{
+ "name": "checkout-automation",
+ "type": "webhook",
+ "endpoint": "https://automation.example/hook",
+ "payloadFormat": "json",
+ "headers": {"Authorization": "Bearer REPLACE_ME"}
+}
+```
+
+Upgrade the servers that save targets and deliver alerts before enabling JSON. The earlier fork build at `63f9a416` sends the text body.
+
+In the dashboard target editor, choose **Webhook**, select **JSON** under **Payload format**, and enter the Bearer header under **Custom headers**. Older header-only forms can submit `X-Parseable-Payload-Format` with value `json`. Parseable consumes that instruction on save. The target API returns the selection in `payloadFormat` and masks the endpoint and outbound header values. Authorization requires a destination that matches the tenant's outbound allowlist.
+
+To edit a target, use the dashboard form or send its full specification to `PUT /api/v1/targets/{id}`. Supply the actual endpoint and desired outbound header values when replacing a target. Omitting the format keeps the current selection. Set the format to `text` to switch back. Both API and form inputs accept `text` and `json`. If both are supplied, they must agree.
+
+JSON delivery sets `Content-Type: application/json` even when a different content type was configured. In text mode, an explicitly configured content type is sent alongside the original text bytes.
+
+## Events
+
+A grouped SQL alert can report several services in one notification. For example, an alert with a string-valued custom field `service` and a query grouped by `service.name` could produce this recovery event.
+
+```json
+{
+ "status": "resolved",
+ "alertId": "01J00000000000000000000000",
+ "alertName": "Checkout errors",
+ "severity": "High",
+ "service": "storefront",
+ "series": [{"service.name": "checkout"}],
+ "message": "Checkout errors is now `not-triggered` "
+}
+```
+
+PromQL delivers one event per series transition. The `series` array contains the original labels for that instance, including on recovery while other instances are still firing. Outbox retries carry the status of the queued transition.
+
+For SQL, a firing event has status `firing`, the evaluator's readable message, and the group labels that breached the threshold. A recovery event has status `resolved` and carries the labels from the most recent firing evaluation. Recovery applies to the whole alert. Use `alertId` to correlate events across evaluations. Ungrouped alerts and alerts recovering from a firing recorded before this feature have an empty `series` array. The optional alert field `service` appears as `null` when unspecified.
diff --git a/frontend/e2e/alerts.spec.ts b/frontend/e2e/alerts.spec.ts
index 4b7fb5516..3af4d898d 100644
--- a/frontend/e2e/alerts.spec.ts
+++ b/frontend/e2e/alerts.spec.ts
@@ -488,6 +488,8 @@ test('target CRUD masks secrets, requires endpoint re-entry and keeps 409 in the
await status.evaluate((element) => element.setAttribute('data-live-region', 'existing'));
await page.getByRole('button', { name: 'New target', exact: true }).click();
let sheet = page.getByRole('dialog', { name: 'New target', exact: true });
+ await expect(sheet.getByLabel('Payload format')).toHaveValue('text');
+ await sheet.getByLabel('Payload format').selectOption('json');
await sheet.getByLabel('Target name').fill('Test hook');
await sheet.getByLabel('Endpoint URL').fill('https://example.com/secret-token');
await sheet.getByRole('button', { name: 'Add header' }).click();
@@ -504,6 +506,7 @@ test('target CRUD masks secrets, requires endpoint re-entry and keeps 409 in the
await rowAction(page, 'Test hook', 'Edit');
sheet = page.getByRole('dialog', { name: 'Edit target', exact: true });
await expect(sheet.getByLabel('Endpoint URL')).toHaveValue('');
+ await expect(sheet.getByLabel('Payload format')).toHaveValue('json');
await expect(sheet.getByLabel('Header 1 value')).toHaveValue('');
await expect(sheet.getByLabel('Target name')).toHaveAttribute('readonly', '');
await expect(
diff --git a/frontend/src/features/alerts/TargetSheet.tsx b/frontend/src/features/alerts/TargetSheet.tsx
index 516e9a3dd..e322351e0 100644
--- a/frontend/src/features/alerts/TargetSheet.tsx
+++ b/frontend/src/features/alerts/TargetSheet.tsx
@@ -127,6 +127,19 @@ export function TargetSheet({
}
onChange={(event) => update('endpoint', event.target.value)}
/>
+ {draft.type === 'webhook' && (
+
+ update('payloadFormat', event.target.value as TargetDraft['payloadFormat'])
+ }
+ >
+ Plain text
+ JSON
+
+ )}
{draft.type === 'webhook' && (
{
password: 'Enter the real password, not the mask.',
});
});
+ it('defaults webhooks to text and preserves an edited JSON selection', () => {
+ expect(targetDraft().payloadFormat).toBe('text');
+ const form = targetDraft({
+ id: 't',
+ name: 'automation',
+ type: 'webhook',
+ endpoint: '',
+ payloadFormat: 'json',
+ });
+ expect(buildTargetPayload(form)).toHaveProperty('payloadFormat', 'json');
+ form.payloadFormat = 'text';
+ expect(buildTargetPayload(form)).toHaveProperty('payloadFormat', 'text');
+ });
it('omits TLS and auth fields for Slack', () => {
const form = {
...targetDraft(),
diff --git a/frontend/src/features/alerts/targetHelpers.ts b/frontend/src/features/alerts/targetHelpers.ts
index 63f1e6ca7..dc5848178 100644
--- a/frontend/src/features/alerts/targetHelpers.ts
+++ b/frontend/src/features/alerts/targetHelpers.ts
@@ -17,6 +17,7 @@ export type TargetDraft = {
name: string;
type: AlertTargetType;
endpoint: string;
+ payloadFormat: 'text' | 'json';
skipTls: boolean;
username: string;
password: string;
@@ -27,6 +28,7 @@ export function targetDraft(target?: AlertTarget): TargetDraft {
name: target?.name ?? '',
type: target ? targetType(target) : 'webhook',
endpoint: '',
+ payloadFormat: target?.payloadFormat ?? 'text',
skipTls: target?.skipTlsCheck ?? false,
// Credentials come back masked, so both start empty and must be re-entered together.
username: '',
@@ -120,6 +122,7 @@ export function buildTargetPayload(draft: TargetDraft): AlertTargetRequest {
return {
...base,
type: 'webhook',
+ payloadFormat: draft.payloadFormat,
skipTlsCheck: draft.skipTls,
headers: Object.fromEntries(
draft.headers
diff --git a/frontend/src/lib/alertsContract.test.ts b/frontend/src/lib/alertsContract.test.ts
index 90b2309e3..e11e625e6 100644
--- a/frontend/src/lib/alertsContract.test.ts
+++ b/frontend/src/lib/alertsContract.test.ts
@@ -88,6 +88,8 @@ describe('alerts response contracts', () => {
expect(alertTargetStatus(targetFixture)).toBe(false);
expect(alertTargetStatus({ target: targetFixture, enabled: 'true' })).toBe(false);
expect(alertTarget({ ...targetFixture, headers: { token: 123 } })).toBe(false);
+ expect(alertTarget({ ...targetFixture, payloadFormat: 'json' })).toBe(true);
+ expect(alertTarget({ ...targetFixture, payloadFormat: 'xml' })).toBe(false);
expect(alertTarget({ ...targetFixture, skipTlsCheck: 'true' })).toBe(false);
});
});
diff --git a/frontend/src/lib/alertsContract.ts b/frontend/src/lib/alertsContract.ts
index 5eda2bfb6..9461affa9 100644
--- a/frontend/src/lib/alertsContract.ts
+++ b/frontend/src/lib/alertsContract.ts
@@ -120,6 +120,7 @@ export function alertTarget(value: unknown): value is AlertTarget {
object(value) &&
['id', 'name', 'endpoint'].every((key) => typeof value[key] === 'string') &&
oneOf(value.type, ['slack', 'webhook', 'alertManager']) &&
+ (value.payloadFormat === undefined || oneOf(value.payloadFormat, ['text', 'json'])) &&
(value.headers === undefined || labels(value.headers)) &&
(value.skipTlsCheck === undefined || typeof value.skipTlsCheck === 'boolean') &&
(value.username === undefined || nullableString(value.username)) &&
diff --git a/frontend/src/lib/demoAlerts.ts b/frontend/src/lib/demoAlerts.ts
index ff72e3769..8079152b5 100644
--- a/frontend/src/lib/demoAlerts.ts
+++ b/frontend/src/lib/demoAlerts.ts
@@ -179,7 +179,7 @@ export function createDemoAlerts(now = Date.now()): Pick 1) fail('Subquery not allowed');
}
}
- function mask(body: AlertTargetRequest, id: string): AlertTarget {
+ function mask(body: AlertTargetRequest, id: string, previous?: AlertTarget): AlertTarget {
const endpoint = `${new URL(body.endpoint).protocol}//********`;
if (body.type === 'slack') return { id, name: body.name, type: 'slack', endpoint };
if (body.type === 'alertManager')
@@ -198,6 +198,7 @@ export function createDemoAlerts(now = Date.now()): Pick [key, '********'])),
skipTlsCheck: body.skipTlsCheck,
};
@@ -359,7 +360,7 @@ export function createDemoAlerts(now = Date.now()): Pick;
skipTlsCheck: boolean;
}
@@ -352,6 +353,7 @@ export type AlertTarget = {
name: string;
type: AlertTargetType;
endpoint: string;
+ payloadFormat?: 'text' | 'json';
headers?: Record;
skipTlsCheck?: boolean;
username?: string | null;
diff --git a/scripts/test-promql-alerts.py b/scripts/test-promql-alerts.py
index e5851ddb1..c7084c5da 100755
--- a/scripts/test-promql-alerts.py
+++ b/scripts/test-promql-alerts.py
@@ -36,9 +36,11 @@ def fail(message):
def request(path, *, method="GET", params=None, body=None, auth=True, timeout=15,
- username=None, password=None):
+ username=None, password=None, stream=None):
url = f"{BASE_URL}{path}"
headers = {"Accept": "application/json"}
+ if stream is not None:
+ headers["X-P-Stream"] = stream
if auth:
credentials = (
f"{username if username is not None else USERNAME}:"
@@ -112,6 +114,18 @@ def ingest(stream, metric, suffix, values):
except urllib.error.HTTPError as exc:
fail(f"OTLP ingestion failed, HTTP {exc.code}: {exc.read().decode(errors='replace')}")
+ # The scan can end at the minute boundary preceding this successful write.
+ # Evaluate transitions only after the instant query sees this batch.
+ deadline = time.monotonic() + max(75, WAIT_SECONDS)
+ while time.monotonic() < deadline:
+ status, raw = request("/prometheus/api/v1/query", params={"query": metric}, stream=stream)
+ vector = data_success(status, raw, "read fixture samples")["result"]
+ observed = {row["metric"]["host"]: float(row["value"][1]) for row in vector}
+ if observed == values:
+ return
+ time.sleep(1)
+ fail(f"fixture samples for {stream} did not become queryable")
+
class LocalWebhook:
"""Tiny loopback receiver that records request bodies for opt-in checks."""
@@ -122,6 +136,7 @@ def __init__(self):
self.sock.bind(("127.0.0.1", 0))
self.sock.listen()
self.port = self.sock.getsockname()[1]
+ self.headers = []
self.messages = []
self.statuses = []
self.fail_next = 0
@@ -151,6 +166,9 @@ def _serve(self):
length = int(line.split(b":", 1)[1].strip())
while len(body) < length:
body += client.recv(4096)
+ headers = {name.lower(): value.strip() for name, value in
+ (line.split(b":", 1) for line in head.split(b"\r\n")[1:])}
+ self.headers.append((headers.get(b"content-type"), headers.get(b"authorization")))
self.messages.append(body[:length].decode(errors="replace"))
status = 503 if self.fail_next else 204
if self.fail_next:
@@ -257,6 +275,8 @@ def main():
target = {
"name": f"PromQL alert smoke {suffix}",
"type": "webhook",
+ "payloadFormat": "json",
+ "headers": {"Authorization": "Bearer local-fixture"},
"endpoint": f"http://127.0.0.1:{receiver.port}/notify",
}
status, raw = request(f"{API_PREFIX}/targets", method="POST", body=target)
@@ -277,7 +297,8 @@ def main():
"alertType": "threshold",
"thresholdConfig": {"operator": ">", "value": 5},
"promqlConfig": {"holdDuration": "2s"},
- "evalConfig": {"rollingWindow": {"evalStart": "1m", "evalEnd": "now", "evalFrequency": 1}},
+ # This fixture drives each evaluation explicitly, including retry.
+ "evalConfig": {"rollingWindow": {"evalStart": "1m", "evalEnd": "now", "evalFrequency": 10}},
"notificationConfig": {"interval": 1},
"targets": targets,
}
@@ -334,7 +355,8 @@ def main():
# Host A fires only after a continuous breach; B starts its own clock later.
ingest(stream, metric, suffix, {"host-a": 9.0, "host-b": 3.0})
evaluate(alert_id)
- wait_runtime(alert_id, lambda r: instance(r, "host-a") is not None, "host-a pending")
+ wait_runtime(alert_id, lambda r: instance(r, "host-a") is not None
+ and instance(r, "host-a").get("state") == "pending", "host-a pending")
time.sleep(2.1)
evaluate(alert_id)
runtime = wait_runtime(
@@ -380,8 +402,14 @@ def main():
deadline = time.monotonic() + WAIT_SECONDS
while time.monotonic() < deadline and len(receiver.messages) < 3:
time.sleep(0.1)
- if not any("resolved" in message.lower() for message in receiver.messages):
- fail(f"local webhook did not receive a recovery notification: {receiver.messages}")
+ events = [json.loads(message) for message in receiver.messages]
+ for transition in ("firing", "resolved"):
+ if not any(event["status"] == transition and event["alertId"] == alert_id
+ and event["message"] and event["series"][0]["host"] == "host-a"
+ for event in events):
+ fail(f"missing {transition} JSON event for host-a")
+ if any(pair != (b"application/json", b"Bearer local-fixture") for pair in receiver.headers):
+ fail("incorrect JSON content type or fixture bearer header")
# Create a second rule through a scoped writer so its scheduled identity
# is that user, not the administrator running this smoke test.
diff --git a/src/alerts/alert_structs.rs b/src/alerts/alert_structs.rs
index 4ef3b740c..1a304ce2d 100644
--- a/src/alerts/alert_structs.rs
+++ b/src/alerts/alert_structs.rs
@@ -69,6 +69,8 @@ const RESERVED_FIELDS: &[&str] = &[
"notification_config",
"created",
"tags",
+ "lastBreachedSeries",
+ "last_breached_series",
"lastTriggeredAt",
"last_triggered_at",
];
@@ -88,10 +90,20 @@ pub struct Alerts {
pub sender: mpsc::Sender,
}
+pub type SeriesLabels = HashMap;
+
+#[derive(Debug, Clone, Default)]
+pub struct AlertNotification {
+ pub message: String,
+ pub series: Vec,
+}
+
#[derive(Debug, Clone)]
pub struct Context {
pub alert_info: AlertInfo,
pub deployment_info: DeploymentInfo,
+ pub service: Option,
+ pub series: Vec,
pub message: String,
pub notification_config: NotificationConfig,
}
@@ -106,6 +118,8 @@ impl Context {
Self {
alert_info,
deployment_info,
+ service: None,
+ series: Vec::new(),
message,
notification_config,
}
@@ -403,6 +417,7 @@ impl AlertRequest {
notification_config: self.notification_config,
created: created_timestamp,
tags: self.tags,
+ last_breached_series: Vec::new(),
last_triggered_at: None,
other_fields,
tenant_id,
@@ -435,6 +450,8 @@ pub struct AlertConfig {
pub notification_config: NotificationConfig,
pub created: DateTime,
pub tags: Option>,
+ #[serde(default, skip_serializing_if = "Vec::is_empty")]
+ pub last_breached_series: Vec,
pub last_triggered_at: Option>,
#[serde(flatten)]
pub other_fields: Option>,
diff --git a/src/alerts/alert_traits.rs b/src/alerts/alert_traits.rs
index 55ce05812..b62b05681 100644
--- a/src/alerts/alert_traits.rs
+++ b/src/alerts/alert_traits.rs
@@ -18,7 +18,8 @@
use crate::{
alerts::{
- AlertConfig, AlertError, AlertQueryType, AlertState, AlertType, EvalConfig, Severity,
+ AlertConfig, AlertError, AlertNotification, AlertQueryType, AlertState, AlertType,
+ EvalConfig, Severity,
alert_enums::NotificationState,
alert_structs::{Context, ThresholdConfig},
},
@@ -49,7 +50,7 @@ pub trait MessageCreation {
#[async_trait]
pub trait AlertTrait: Debug + Send + Sync + MetastoreObject {
- async fn eval_alert(&self) -> Result, AlertError>;
+ async fn eval_alert(&self) -> Result , AlertError>;
async fn validate(&self, session_key: &SessionKey) -> Result<(), AlertError>;
async fn update_notification_state(
&mut self,
@@ -58,7 +59,7 @@ pub trait AlertTrait: Debug + Send + Sync + MetastoreObject {
async fn update_state(
&mut self,
alert_state: AlertState,
- trigger_notif: Option,
+ trigger_notif: Option,
) -> Result<(), AlertError>;
fn get_id(&self) -> &Ulid;
fn get_severity(&self) -> &Severity;
@@ -98,7 +99,7 @@ pub trait AlertManagerTrait: Send + Sync {
&self,
alert_id: Ulid,
new_state: AlertState,
- trigger_notif: Option,
+ trigger_notif: Option,
tenant_id: &Option,
) -> Result<(), AlertError>;
async fn update_notification_state(
diff --git a/src/alerts/alert_types.rs b/src/alerts/alert_types.rs
index a989e71f1..fc4092f04 100644
--- a/src/alerts/alert_types.rs
+++ b/src/alerts/alert_types.rs
@@ -27,10 +27,10 @@ use ulid::Ulid;
use crate::{
alerts::{
- AlertConfig, AlertError, AlertQueryType, AlertState, AlertType, AlertVersion, EvalConfig,
- Severity, ThresholdConfig,
+ AlertConfig, AlertError, AlertNotification, AlertQueryType, AlertState, AlertType,
+ AlertVersion, EvalConfig, Severity, ThresholdConfig,
alert_enums::NotificationState,
- alert_structs::{AlertStateEntry, GroupResult},
+ alert_structs::{AlertQueryResult, AlertStateEntry, GroupResult, SeriesLabels},
alert_traits::{AlertTrait, MessageCreation},
alerts_utils::{evaluate_condition, execute_alert_query, extract_time_range},
get_number_of_agg_exprs,
@@ -72,6 +72,8 @@ pub struct ThresholdAlert {
pub created: DateTime,
pub tags: Option>,
pub datasets: Vec,
+ #[serde(default, skip_serializing_if = "Vec::is_empty")]
+ pub last_breached_series: Vec,
pub last_triggered_at: Option>,
#[serde(flatten)]
pub other_fields: Option>,
@@ -90,7 +92,7 @@ impl MetastoreObject for ThresholdAlert {
#[async_trait]
impl AlertTrait for ThresholdAlert {
- async fn eval_alert(&self) -> Result, AlertError> {
+ async fn eval_alert(&self) -> Result , AlertError> {
self.validate_oss_query_type()?;
if self.query_type == AlertQueryType::Promql {
super::promql_alerts::authorize_execution(&self.to_alert_config())
@@ -111,7 +113,12 @@ impl AlertTrait for ThresholdAlert {
self.threshold_config.value,
)
})
- .map(|(_, value)| self.create_threshold_message(value))
+ .map(|(labels, value)| {
+ Ok(AlertNotification {
+ message: self.create_threshold_message(value)?,
+ series: vec![labels.into_iter().collect()],
+ })
+ })
.transpose();
}
@@ -142,44 +149,7 @@ impl AlertTrait for ThresholdAlert {
let query_result =
execute_alert_query(auth, self.get_query(), &time_range, &self.tenant_id).await?;
- if query_result.is_simple_query {
- // Handle simple queries
- let final_value = query_result.get_single_value();
- let result = evaluate_condition(
- &self.threshold_config.operator,
- final_value,
- self.threshold_config.value,
- );
-
- let message = if result {
- Some(self.create_threshold_message(final_value)?)
- } else {
- None
- };
- Ok(message)
- } else {
- // Handle GROUP BY queries - evaluate each group
- let mut breached_groups = Vec::new();
-
- for group in &query_result.groups {
- let result = evaluate_condition(
- &self.threshold_config.operator,
- group.aggregate_value,
- self.threshold_config.value,
- );
-
- if result {
- breached_groups.push(group.clone());
- }
- }
-
- let message = if !breached_groups.is_empty() {
- Some(self.create_group_message(&breached_groups)?)
- } else {
- None
- };
- Ok(message)
- }
+ self.threshold_notification(query_result)
}
async fn validate(&self, session_key: &SessionKey) -> Result<(), AlertError> {
@@ -280,11 +250,12 @@ impl AlertTrait for ThresholdAlert {
async fn update_state(
&mut self,
new_state: AlertState,
- trigger_notif: Option,
+ mut trigger_notif: Option,
) -> Result<(), AlertError> {
if self.query_type == AlertQueryType::Promql && new_state == AlertState::Disabled {
super::promql_alerts::reset_runtime_for_disable(&mut self.other_fields);
}
+ self.update_breached_series(new_state, trigger_notif.as_mut());
if self.state.eq(&AlertState::Disabled) {
warn!(
"Alert- {} is currently Disabled. Updating state to {new_state}.",
@@ -505,6 +476,7 @@ impl From for ThresholdAlert {
created: value.created,
tags: value.tags,
datasets: value.datasets,
+ last_breached_series: value.last_breached_series,
last_triggered_at: value.last_triggered_at,
other_fields: value.other_fields,
tenant_id: value.tenant_id,
@@ -531,6 +503,7 @@ impl From for AlertConfig {
created: val.created,
tags: val.tags,
datasets: val.datasets,
+ last_breached_series: val.last_breached_series,
last_triggered_at: val.last_triggered_at,
other_fields: val.other_fields,
tenant_id: val.tenant_id,
@@ -554,6 +527,65 @@ impl ThresholdAlert {
Ok(())
}
+ fn update_breached_series(
+ &mut self,
+ state: AlertState,
+ notification: Option<&mut AlertNotification>,
+ ) {
+ match (state, notification) {
+ (AlertState::Triggered, Some(event)) => {
+ self.last_breached_series.clone_from(&event.series)
+ }
+ (AlertState::NotTriggered, Some(event)) => {
+ event.series = std::mem::take(&mut self.last_breached_series)
+ }
+ (AlertState::Disabled | AlertState::NotTriggered, _) => {
+ self.last_breached_series.clear()
+ }
+ _ => {}
+ }
+ }
+
+ fn threshold_notification(
+ &self,
+ query_result: AlertQueryResult,
+ ) -> Result, AlertError> {
+ let breaches = |value| {
+ evaluate_condition(
+ &self.threshold_config.operator,
+ value,
+ self.threshold_config.value,
+ )
+ };
+ if query_result.is_simple_query {
+ let value = query_result.get_single_value();
+ if breaches(value) {
+ return Ok(Some(AlertNotification {
+ message: self.create_threshold_message(value)?,
+ series: Vec::new(),
+ }));
+ }
+ return Ok(None);
+ }
+
+ let breached_groups: Vec<_> = query_result
+ .groups
+ .into_iter()
+ .filter(|group| breaches(group.aggregate_value))
+ .collect();
+ if breached_groups.is_empty() {
+ return Ok(None);
+ }
+
+ Ok(Some(AlertNotification {
+ message: self.create_group_message(&breached_groups)?,
+ series: breached_groups
+ .into_iter()
+ .map(|group| group.group_values)
+ .collect(),
+ }))
+ }
+
fn create_group_message(&self, breached_groups: &[GroupResult]) -> Result {
let header = self.get_message_header()?;
let mut message = format!("{header}\n");
@@ -586,3 +618,48 @@ impl ThresholdAlert {
Ok(message)
}
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use serde_json::json;
+
+ #[test]
+ fn grouped_recovery_carries_the_last_breached_labels_across_reload() {
+ let legacy: AlertConfig = serde_json::from_value(json!({
+ "version": "v2", "severity": "high", "title": "Errors",
+ "query": "SELECT service, COUNT(*) AS errors FROM logs GROUP BY service",
+ "alertType": "threshold", "thresholdConfig": {"operator": ">", "value": 5},
+ "evalConfig": {"rollingWindow": {"evalStart": "5m", "evalEnd": "now", "evalFrequency": 1}},
+ "targets": [], "notificationConfig": {"interval": 1}, "notificationState": "notify",
+ "created": "2026-01-01T00:00:00Z", "datasets": ["logs"]
+ })).unwrap();
+ let mut alert = ThresholdAlert::from(legacy);
+ let labels = SeriesLabels::from([("service".into(), "checkout".into())]);
+ let result = AlertQueryResult {
+ is_simple_query: false,
+ groups: vec![
+ GroupResult {
+ group_values: labels.clone(),
+ aggregate_value: 7.0,
+ },
+ GroupResult {
+ group_values: SeriesLabels::from([("service".into(), "search".into())]),
+ aggregate_value: 1.0,
+ },
+ ],
+ };
+ let mut fired = alert.threshold_notification(result).unwrap().unwrap();
+ assert_eq!(fired.series, vec![labels.clone()]);
+ assert!(fired.message.contains("service: checkout"));
+ alert.update_breached_series(AlertState::Triggered, Some(&mut fired));
+
+ let stored = serde_json::to_vec(&alert.to_alert_config()).unwrap();
+ let mut loaded =
+ ThresholdAlert::from(serde_json::from_slice::(&stored).unwrap());
+ let mut resolved = AlertNotification::default();
+ loaded.update_breached_series(AlertState::NotTriggered, Some(&mut resolved));
+ assert_eq!(resolved.series, vec![labels]);
+ assert!(loaded.last_breached_series.is_empty());
+ }
+}
diff --git a/src/alerts/alerts_utils.rs b/src/alerts/alerts_utils.rs
index 4727bfe44..208ec06f3 100644
--- a/src/alerts/alerts_utils.rs
+++ b/src/alerts/alerts_utils.rs
@@ -44,7 +44,7 @@ use crate::{
utils::time::TimeRange,
};
-use super::{ALERTS, AlertError, AlertOperator, AlertState};
+use super::{ALERTS, AlertError, AlertNotification, AlertOperator, AlertState};
/// accept the alert
///
@@ -71,9 +71,9 @@ pub async fn evaluate_alert(alert: &dyn AlertTrait) -> Result<(), AlertError> {
if alert.get_query_type() == super::AlertQueryType::Promql {
return super::promql_alerts::evaluate(*alert.get_id(), alert.get_tenant_id()).await;
}
- let message = alert.eval_alert().await?;
+ let notification = alert.eval_alert().await?;
- update_alert_state(alert, message).await
+ update_alert_state(alert, notification).await
}
/// Extract time range from alert evaluation configuration
@@ -260,7 +260,7 @@ pub fn evaluate_condition(operator: &AlertOperator, actual: f64, expected: f64)
async fn update_alert_state(
alert: &dyn AlertTrait,
- message: Option,
+ notification: Option,
) -> Result<(), AlertError> {
// Get the alert manager reference while holding the lock briefly
let alerts = {
@@ -273,12 +273,12 @@ async fn update_alert_state(
};
// Now perform the state update
- if let Some(msg) = message {
+ if let Some(event) = notification {
alerts
.update_state(
*alert.get_id(),
AlertState::Triggered,
- Some(msg),
+ Some(event),
alert.get_tenant_id(),
)
.await
@@ -291,7 +291,7 @@ async fn update_alert_state(
.update_state(
*alert.get_id(),
AlertState::NotTriggered,
- Some("".into()),
+ Some(Default::default()),
alert.get_tenant_id(),
)
.await
diff --git a/src/alerts/mod.rs b/src/alerts/mod.rs
index 23e9969fd..f70e11453 100644
--- a/src/alerts/mod.rs
+++ b/src/alerts/mod.rs
@@ -45,15 +45,17 @@ pub mod alerts_utils;
pub mod outbound_http_policy;
pub mod promql_alerts;
pub mod target;
+#[cfg(test)]
+mod webhook_tests;
pub use crate::alerts::alert_enums::{
AggregateFunction, AlertOperator, AlertQueryType, AlertState, AlertTask, AlertType,
AlertVersion, EvalConfig, LogicalOperator, NotificationState, Severity, WhereConfigOperator,
};
pub use crate::alerts::alert_structs::{
- AlertConfig, AlertInfo, AlertRequest, AlertStateEntry, Alerts, AlertsInfo, AlertsInfoByState,
- AlertsSummary, BasicAlertFields, Context, DeploymentInfo, RollingWindow, StateTransition,
- ThresholdConfig,
+ AlertConfig, AlertInfo, AlertNotification, AlertRequest, AlertStateEntry, Alerts, AlertsInfo,
+ AlertsInfoByState, AlertsSummary, BasicAlertFields, Context, DeploymentInfo, RollingWindow,
+ StateTransition, ThresholdConfig,
};
use crate::alerts::alert_traits::{AlertManagerTrait, AlertTrait};
use crate::alerts::alert_types::ThresholdAlert;
@@ -243,6 +245,7 @@ impl AlertConfig {
notification_config: NotificationConfig::default(),
created: Utc::now(),
tags: None,
+ last_breached_series: Vec::new(),
last_triggered_at: None,
other_fields: None,
tenant_id: tenant_id.clone(),
@@ -698,7 +701,7 @@ impl AlertConfig {
}
}
- fn get_context(&self) -> Context {
+ fn get_context(&self, notification: AlertNotification) -> Context {
let deployment_instance = format!(
"{}://{}",
PARSEABLE.options.get_scheme(),
@@ -707,24 +710,36 @@ impl AlertConfig {
let deployment_id = storage::StorageMetadata::global().deployment_id;
let deployment_mode = storage::StorageMetadata::global().mode.to_string();
- Context::new(
- AlertInfo::new(
+ Context {
+ alert_info: AlertInfo::new(
self.id,
self.title.clone(),
self.state,
alert_enums::NotificationState::Notify,
self.severity.clone().to_string(),
),
- DeploymentInfo::new(deployment_instance, deployment_id, deployment_mode),
- self.notification_config.clone(),
- String::default(),
- )
+ deployment_info: DeploymentInfo::new(
+ deployment_instance,
+ deployment_id,
+ deployment_mode,
+ ),
+ notification_config: self.notification_config.clone(),
+ message: notification.message,
+ series: notification.series,
+ service: self
+ .other_fields
+ .as_ref()
+ .and_then(|fields| fields.get("service"))
+ .and_then(JsonValue::as_str)
+ .map(str::to_owned),
+ }
}
- pub async fn trigger_notifications(&self, message: String) -> Result<(), AlertError> {
- let mut context = self.get_context();
- context.message.clone_from(&message);
-
+ pub async fn trigger_notifications(
+ &self,
+ notification: AlertNotification,
+ ) -> Result<(), AlertError> {
+ let context = self.get_context(notification);
for target_id in &self.targets {
let target = TARGETS.get_target_by_id(target_id, &self.tenant_id).await?;
if let Err(e) = target.validate_outbound_policy().await {
@@ -1513,7 +1528,7 @@ impl AlertManagerTrait for Alerts {
&self,
alert_id: Ulid,
new_state: AlertState,
- trigger_notif: Option,
+ trigger_notif: Option,
tenant_id: &Option,
) -> Result<(), AlertError> {
let (mut alert, should_delete_task, should_create_task) = {
diff --git a/src/alerts/promql_alerts.rs b/src/alerts/promql_alerts.rs
index f3326499b..171a6a21a 100644
--- a/src/alerts/promql_alerts.rs
+++ b/src/alerts/promql_alerts.rs
@@ -564,7 +564,7 @@ pub async fn evaluate(id: Ulid, tenant_id: &Option) -> Result<(), AlertE
if notify && may_deliver {
// Each evaluation makes at most one delivery attempt per queued transition.
let deadline = tokio::time::Instant::now() + std::time::Duration::from_secs(30);
- let deployment = updated.get_context().deployment_info;
+ let mut context = updated.get_context(Default::default());
let valid_until = firing_valid_until(&updated, now);
for delivery in runtime
.deliveries
@@ -575,13 +575,19 @@ pub async fn evaluate(id: Ulid, tenant_id: &Option) -> Result<(), AlertE
if tokio::time::Instant::now() >= deadline {
break;
}
- let message =
+ context.message =
instance_message(&updated, &delivery.labels, delivery.value, delivery.firing);
+ context.alert_info.alert_state = if delivery.firing {
+ AlertState::Triggered
+ } else {
+ AlertState::NotTriggered
+ };
+ context.series = vec![delivery.labels.clone().into_iter().collect()];
let alert = alertmanager_alert(
&updated.title,
- &deployment,
+ &context.deployment_info,
&delivery.labels,
- message.clone(),
+ context.message.clone(),
if delivery.firing { valid_until } else { now },
);
delivery.attempts += 1;
@@ -592,7 +598,7 @@ pub async fn evaluate(id: Ulid, tenant_id: &Option) -> Result<(), AlertE
let result = match target_result {
Ok(target) => match tokio::time::timeout_at(
deadline.min(tokio::time::Instant::now() + std::time::Duration::from_secs(5)),
- target.deliver_promql(&updated.tenant_id, &message, &[alert]),
+ target.deliver_promql(&updated.tenant_id, &context, &[alert]),
)
.await
{
@@ -620,7 +626,7 @@ pub async fn evaluate(id: Ulid, tenant_id: &Option) -> Result<(), AlertE
.map(|instance| {
alertmanager_alert(
&updated.title,
- &deployment,
+ &context.deployment_info,
&instance.labels,
instance_message(&updated, &instance.labels, instance.value, true),
valid_until,
diff --git a/src/alerts/target.rs b/src/alerts/target.rs
index 17b688744..b171d13ce 100644
--- a/src/alerts/target.rs
+++ b/src/alerts/target.rs
@@ -213,6 +213,48 @@ pub struct Target {
}
impl Target {
+ /// Normalize Prism's custom-header input only on create/update. Stored headers
+ /// retain their original meaning when targets are loaded or delivered.
+ pub(crate) fn apply_webhook_format(
+ &mut self,
+ previous: Option<&Target>,
+ ) -> Result<(), AlertError> {
+ let TargetType::Other(webhook) = &mut self.target else {
+ return Ok(());
+ };
+ const FORMAT_HEADER: &str = "X-Parseable-Payload-Format";
+ for (_, value) in webhook
+ .headers
+ .extract_if(|name, _| name.eq_ignore_ascii_case(FORMAT_HEADER))
+ {
+ let format = match value.as_str() {
+ "json" => PayloadFormat::Json,
+ "text" => PayloadFormat::Text,
+ _ => {
+ return Err(AlertError::ValidationFailure(format!(
+ "{FORMAT_HEADER} must be json or text"
+ )));
+ }
+ };
+ if webhook
+ .payload_format
+ .replace(format)
+ .is_some_and(|field| field != format)
+ {
+ return Err(AlertError::ValidationFailure(
+ "Conflicting webhook payload formats".into(),
+ ));
+ }
+ }
+ // An older UI cannot echo payloadFormat when editing a JSON target.
+ if webhook.payload_format.is_none()
+ && let Some(TargetType::Other(old)) = previous.map(|target| &target.target)
+ {
+ webhook.payload_format = old.payload_format;
+ }
+ Ok(())
+ }
+
pub async fn validate_outbound_policy(&self) -> Result<(), AlertError> {
let tenant_id = &self.tenant;
match &self.target {
@@ -277,6 +319,7 @@ impl Target {
"type":"webhook",
"endpoint": format!("{}://********", other_web_hook.endpoint.scheme()),
"headers":safe_headers,
+ "payloadFormat":other_web_hook.payload_format.unwrap_or_default(),
"skipTlsCheck":other_web_hook.skip_tls_check,
"id":self.id
})
@@ -317,11 +360,11 @@ impl Target {
/// Delivery with an observable result for the persisted PromQL notification outbox.
/// Alertmanager receives `alerts`, which keep the series labels; Slack and
- /// webhook targets receive `message`.
+ /// webhook targets use the queued transition in `context`.
pub async fn deliver_promql(
&self,
tenant: &Option,
- message: &str,
+ context: &Context,
alerts: &[Value],
) -> Result<(), String> {
let request = match &self.target {
@@ -338,7 +381,7 @@ impl Target {
prepared
.client
.post(target.endpoint.clone())
- .json(&serde_json::json!({"text": message}))
+ .json(&serde_json::json!({"text": context.message}))
}
TargetType::Other(target) => {
let prepared = outbound_http_policy::prepare_alert_target(
@@ -350,11 +393,7 @@ impl Target {
)
.await
.map_err(|e| e.sanitized_message().to_string())?;
- prepared
- .client
- .post(target.endpoint.clone())
- .headers(prepared.headers)
- .body(message.to_owned())
+ target.webhook_request(prepared, context, &context.message)
}
TargetType::AlertManager(target) => return target.post_promql(tenant, alerts).await,
};
@@ -371,7 +410,14 @@ impl Target {
trace!("target.call context- {context:?}");
let timeout = context.notification_config.clone();
let resolves = context.alert_info.alert_state;
- let mut state = timeout.state.lock().unwrap();
+ let target_state = timeout
+ .target_states
+ .lock()
+ .unwrap()
+ .entry(self.id)
+ .or_default()
+ .clone();
+ let mut state = target_state.lock().unwrap();
trace!("target.call state- {state:?}");
state.alert_state = resolves;
@@ -385,7 +431,7 @@ impl Target {
state.timed_out = true;
state.awaiting_resolve = true;
drop(state);
- self.spawn_timeout_task(&timeout, context.clone());
+ self.spawn_timeout_task(&timeout, target_state, context);
}
}
alert_state @ AlertState::NotTriggered => {
@@ -408,9 +454,13 @@ impl Target {
}
}
- fn spawn_timeout_task(&self, target_timeout: &NotificationConfig, alert_context: Context) {
+ fn spawn_timeout_task(
+ &self,
+ target_timeout: &NotificationConfig,
+ state: SharedTimeoutState,
+ alert_context: Context,
+ ) {
trace!("repeat-\n{target_timeout:?}");
- let state = Arc::clone(&target_timeout.state);
let retry = target_timeout.times;
let timeout = target_timeout.interval;
let target = self.target.clone();
@@ -418,7 +468,7 @@ impl Target {
let tenant_id = self.tenant.clone();
let sleep_and_check_if_call =
- move |timeout_state: Arc>, current_state: AlertState| async move {
+ move |timeout_state: SharedTimeoutState, current_state: AlertState| async move {
tokio::time::sleep(Duration::from_secs(timeout * 60)).await;
let mut state = timeout_state.lock().unwrap();
@@ -649,20 +699,64 @@ impl CallableTarget for SlackWebHook {
}
}
}
+
+#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
+#[serde(rename_all = "camelCase")]
+enum PayloadFormat {
+ #[default]
+ Text,
+ Json,
+}
+
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct OtherWebHook {
endpoint: Url,
#[serde(default)]
headers: HashMap,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ payload_format: Option,
#[serde(default)]
skip_tls_check: bool,
}
+impl OtherWebHook {
+ fn webhook_request(
+ &self,
+ prepared: outbound_http_policy::PreparedAlertTarget,
+ payload: &Context,
+ message: &str,
+ ) -> reqwest::RequestBuilder {
+ let mut headers = prepared.headers;
+ let request = prepared.client.post(self.endpoint.clone());
+ match self.payload_format.unwrap_or_default() {
+ PayloadFormat::Text => request.headers(headers).body(message.to_owned()),
+ PayloadFormat::Json => {
+ // reqwest's json() only sets Content-Type if it is absent.
+ headers.remove(http::header::CONTENT_TYPE);
+ let status = match payload.alert_info.alert_state {
+ AlertState::Triggered => "firing",
+ AlertState::NotTriggered => "resolved",
+ AlertState::Disabled => "disabled",
+ };
+ request.headers(headers).json(&json!({
+ "status": status,
+ "alertId": payload.alert_info.alert_id,
+ "alertName": payload.alert_info.alert_name,
+ "severity": payload.alert_info.severity,
+ "service": payload.service,
+ "series": payload.series,
+ "message": message,
+ }))
+ }
+ }
+ }
+}
+
#[async_trait]
impl CallableTarget for OtherWebHook {
async fn call(&self, tenant_id: &Option, payload: &Context) {
- let alert = match payload.alert_info.alert_state {
+ let message = match payload.alert_info.alert_state {
AlertState::Triggered => payload.message.clone(),
AlertState::NotTriggered => payload.default_resolved_string(),
AlertState::Disabled => payload.default_disabled_string(),
@@ -685,11 +779,8 @@ impl CallableTarget for OtherWebHook {
return;
}
};
- let request = prepared
- .client
- .post(self.endpoint.clone())
- .headers(prepared.headers);
- if let Err(e) = request.body(alert).send().await {
+ let request = self.webhook_request(prepared, payload, &message);
+ if let Err(e) = request.send().await {
error!(
"Couldn't make call to webhook, error:{}",
safe_delivery_error(e)
@@ -821,7 +912,7 @@ pub struct NotificationConfig {
#[serde(skip)]
pub times: Retry,
#[serde(skip)]
- pub state: Arc>,
+ target_states: Arc>>,
}
impl Default for NotificationConfig {
@@ -829,11 +920,13 @@ impl Default for NotificationConfig {
Self {
interval: 1,
times: Retry::default(),
- state: Arc::>::default(),
+ target_states: Default::default(),
}
}
}
+type SharedTimeoutState = Arc>;
+
#[derive(Debug, Default, Clone, Copy)]
pub struct TimeoutState {
pub alert_state: AlertState,
@@ -891,6 +984,7 @@ mod tests {
fn webhook(endpoint: Url) -> TargetType {
TargetType::Other(OtherWebHook {
endpoint,
+ payload_format: None,
headers: HashMap::from([("X-Api-Key".into(), "SECRET-HEADER-VALUE".into())]),
skip_tls_check: false,
})
@@ -1121,7 +1215,7 @@ mod tests {
other.mask(),
json!({
"name":"redaction-target","type":"webhook","endpoint":"http://********",
- "headers":{"X-Api-Key":"********"},"skipTlsCheck":false,"id":id
+ "headers":{"X-Api-Key":"********"},"payloadFormat":"text","skipTlsCheck":false,"id":id
})
);
@@ -1250,7 +1344,7 @@ mod tests {
let (port, server) = serve_once("500 Internal Server Error");
let target = named(webhook(secret_url(&format!("127.0.0.1:{port}"))), &tenant);
let status = target
- .deliver_promql(&target.tenant, "message", &[])
+ .deliver_promql(&target.tenant, &context(), &[])
.await
.unwrap_err();
let request = server.join().unwrap().to_ascii_lowercase();
@@ -1261,7 +1355,7 @@ mod tests {
let port = refused_port();
let target = named(webhook(secret_url(&format!("127.0.0.1:{port}"))), &tenant);
let transport = target
- .deliver_promql(&target.tenant, "message", &[])
+ .deliver_promql(&target.tenant, &context(), &[])
.await
.unwrap_err();
assert!(transport.contains("error sending request"), "{transport}");
@@ -1282,7 +1376,7 @@ mod tests {
&tenant,
);
let status = target
- .deliver_promql(&target.tenant, "message", &alerts)
+ .deliver_promql(&target.tenant, &context(), &alerts)
.await
.unwrap_err();
let request = server.join().unwrap().to_ascii_lowercase();
@@ -1323,7 +1417,7 @@ mod tests {
);
let denied = named(webhook(secret_url("secret-denied.example")), &tenant);
let error = denied
- .deliver_promql(&denied.tenant, "message", &[])
+ .deliver_promql(&denied.tenant, &context(), &[])
.await
.unwrap_err();
assert_eq!(error, "Target domain is denied by outbound policy");
@@ -1338,7 +1432,7 @@ mod tests {
&tenant,
);
let error = slack
- .deliver_promql(&slack.tenant, "message", &[])
+ .deliver_promql(&slack.tenant, &context(), &[])
.await
.unwrap_err();
assert_eq!(error, "Slack target host is invalid");
@@ -1346,7 +1440,7 @@ mod tests {
// A public, non-allowlisted address may receive alerts but not credentials.
let blocked = named(alertmanager(secret_url("203.0.113.10"), true), &tenant);
let error = blocked
- .deliver_promql(&blocked.tenant, "message", &[])
+ .deliver_promql(&blocked.tenant, &context(), &[])
.await
.unwrap_err();
assert_eq!(error, "Target credentials blocked by outbound policy");
diff --git a/src/alerts/webhook_tests.rs b/src/alerts/webhook_tests.rs
new file mode 100644
index 000000000..88cda717b
--- /dev/null
+++ b/src/alerts/webhook_tests.rs
@@ -0,0 +1,234 @@
+use std::collections::HashMap;
+
+use serde_json::{Value, json};
+use ulid::Ulid;
+
+use super::{
+ AlertState, Context,
+ target::{NotificationConfig, Target},
+};
+
+#[test]
+fn webhook_format_round_trips_and_mask_hides_credentials() {
+ let mut spec = json!({
+ "type": "webhook", "name": "automation", "endpoint": "https://example.test/private",
+ "headers": {"Authorization": "Bearer fixture"}
+ });
+ for format in [None, Some("text"), Some("json")] {
+ if let Some(format) = format {
+ spec["payloadFormat"] = json!(format);
+ }
+ let target: Target = serde_json::from_value(spec.clone()).unwrap();
+ let stored = serde_json::to_value(&target).unwrap();
+ assert_eq!(stored.get("payloadFormat").and_then(Value::as_str), format);
+ let loaded: Target = serde_json::from_value(stored).unwrap();
+ assert_eq!(loaded.target, target.target);
+ let masked = loaded.mask();
+ assert_eq!(masked["payloadFormat"], format.unwrap_or("text"));
+ assert_eq!(masked["headers"]["Authorization"], "********");
+ assert_eq!(masked["endpoint"], "https://********");
+ }
+ spec["payloadFormat"] = json!("yaml");
+ assert!(serde_json::from_value::(spec).is_err());
+}
+
+#[test]
+fn prism_form_sets_and_updates_the_canonical_format() {
+ let form = json!({
+ "type": "webhook", "name": "automation", "endpoint": "https://example.test/hook",
+ "headers": { "x-parseable-payload-format": "json", "Authorization": "Bearer fixture" }
+ });
+ let mut target: Target = serde_json::from_value(form.clone()).unwrap();
+ // Deserialization alone (e.g. metastore load) never reinterprets legacy headers.
+ assert_eq!(target.clone().mask()["payloadFormat"], "text");
+ target.apply_webhook_format(None).unwrap();
+ let stored = serde_json::to_value(&target).unwrap();
+ assert_eq!(stored["payloadFormat"], "json");
+ assert_eq!(
+ stored["headers"],
+ json!({"Authorization": "Bearer fixture"})
+ );
+
+ let mut edit = form;
+ edit["headers"]
+ .as_object_mut()
+ .unwrap()
+ .remove("x-parseable-payload-format");
+ let mut edited: Target = serde_json::from_value(edit.clone()).unwrap();
+ edited.apply_webhook_format(Some(&target)).unwrap();
+ assert_eq!(edited.mask()["payloadFormat"], "json");
+
+ edit["headers"]["X-Parseable-Payload-Format"] = json!("text");
+ let mut edited: Target = serde_json::from_value(edit).unwrap();
+ edited.apply_webhook_format(Some(&target)).unwrap();
+ assert_eq!(edited.mask()["payloadFormat"], "text");
+}
+
+#[actix_web::test]
+async fn webhook_delivers_selected_format_and_revalidates_policy() {
+ use crate::alerts::{
+ AlertInfo, DeploymentInfo, NotificationState,
+ outbound_http_policy::{ALERT_TARGET_POLICY, AlertTargetPolicyConfig},
+ };
+ use actix_web::{App, HttpRequest, HttpResponse, HttpServer, web};
+
+ let listener = std::net::TcpListener::bind(("127.0.0.1", 0)).unwrap();
+ let address = listener.local_addr().unwrap();
+ let (tx, mut received) = tokio::sync::mpsc::unbounded_channel();
+ let server = HttpServer::new(move || {
+ let tx = tx.clone();
+ App::new().route(
+ "/hook",
+ web::post().to(move |req: HttpRequest, body: web::Bytes| {
+ let tx = tx.clone();
+ async move {
+ tx.send((req.headers().clone(), body)).unwrap();
+ HttpResponse::NoContent().finish()
+ }
+ }),
+ )
+ })
+ .workers(1)
+ .listen(listener)
+ .unwrap()
+ .run();
+ let handle = server.handle();
+ actix_web::rt::spawn(server);
+
+ let tenant = Ulid::new().to_string();
+ ALERT_TARGET_POLICY.write().await.insert(
+ tenant.clone(),
+ AlertTargetPolicyConfig {
+ allow_private: true,
+ allowed_cidrs: vec!["127.0.0.1/32".into()],
+ ..Default::default()
+ },
+ );
+ let spec = json!({
+ "type": "webhook", "name": "fixture", "endpoint": format!("http://{address}/hook"),
+ "headers": { "Authorization": "Bearer local-fixture" }
+ });
+ let alert_id = Ulid::new();
+ let mut context = Context::new(
+ AlertInfo::new(
+ alert_id,
+ "Checkout".into(),
+ AlertState::Triggered,
+ NotificationState::Notify,
+ "High".into(),
+ ),
+ DeploymentInfo::new("local".into(), Ulid::new(), "all".into()),
+ NotificationConfig::default(),
+ "Checkout: \"errors\"\nabove threshold".into(),
+ );
+ context.service = Some("shop".into());
+ context.series = vec![HashMap::from([("service.name".into(), "checkout".into())])];
+ let tenant_id = Some(tenant.clone());
+ for (format, form_control, custom_type, expected_type) in [
+ (None, None, None, None),
+ (
+ None,
+ None,
+ Some("application/json"),
+ Some("application/json"),
+ ),
+ (Some("text"), None, Some("text/plain"), Some("text/plain")),
+ (Some("json"), None, None, Some("application/json")),
+ (
+ None,
+ Some("json"),
+ Some("text/plain"),
+ Some("application/json"),
+ ),
+ ] {
+ let mut input = spec.clone();
+ if let Some(format) = format {
+ input["payloadFormat"] = json!(format);
+ }
+ if let Some(control) = form_control {
+ input["headers"]["X-Parseable-Payload-Format"] = json!(control);
+ }
+ if let Some(custom_type) = custom_type {
+ input["headers"]["cOnTeNt-TyPe"] = json!(custom_type);
+ }
+ let mut target: Target = serde_json::from_value(input).unwrap();
+ target.apply_webhook_format(None).unwrap();
+ for (state, status, expected_message) in [
+ (AlertState::Triggered, "firing", context.message.clone()),
+ (
+ AlertState::NotTriggered,
+ "resolved",
+ "Checkout is now `not-triggered` ".into(),
+ ),
+ ] {
+ context.alert_info.alert_state = state;
+ target.target.call(&tenant_id, &context).await;
+ let (headers, body) = received.try_recv().expect("receiver handled the POST");
+ assert_eq!(
+ headers.get("authorization").unwrap(),
+ "Bearer local-fixture"
+ );
+ assert!(!headers.contains_key("x-parseable-payload-format"));
+ let types: Vec<_> = headers
+ .get_all("content-type")
+ .map(|v| v.to_str().unwrap())
+ .collect();
+ assert_eq!(types, expected_type.into_iter().collect::>());
+ if format.or(form_control) == Some("json") {
+ assert_eq!(
+ serde_json::from_slice::(&body).unwrap(),
+ json!({
+ "status": status, "alertId": alert_id, "alertName": "Checkout",
+ "severity": "High", "service": "shop",
+ "series": [{"service.name":"checkout"}], "message": expected_message
+ })
+ );
+ } else {
+ assert_eq!(body.as_ref(), expected_message.as_bytes());
+ }
+ }
+ }
+
+ // A single alert can fan out to both a legacy target and a JSON automation.
+ let mut text: Target = serde_json::from_value(spec.clone()).unwrap();
+ text.tenant = tenant_id.clone();
+ let mut json_spec = spec.clone();
+ json_spec["payloadFormat"] = json!("json");
+ let mut structured: Target = serde_json::from_value(json_spec).unwrap();
+ structured.tenant = tenant_id.clone();
+ for (state, status) in [
+ (AlertState::Triggered, "firing"),
+ (AlertState::NotTriggered, "resolved"),
+ ] {
+ context.alert_info.alert_state = state;
+ text.call(context.clone());
+ structured.call(context.clone());
+ let mut formats = Vec::new();
+ for _ in 0..2 {
+ let (headers, body) =
+ tokio::time::timeout(std::time::Duration::from_secs(5), received.recv())
+ .await
+ .expect("both alert targets should receive a POST")
+ .unwrap();
+ let is_json = headers.contains_key("content-type");
+ if is_json {
+ assert_eq!(
+ serde_json::from_slice::(&body).unwrap()["status"],
+ status
+ );
+ }
+ formats.push(is_json);
+ }
+ formats.sort_unstable();
+ assert_eq!(formats, [false, true]);
+ }
+
+ // A stored JSON target loses access immediately when the allowlist is removed.
+ ALERT_TARGET_POLICY.write().await.remove(&tenant);
+ let mut stored = spec;
+ stored["payloadFormat"] = json!("json");
+ let target: Target = serde_json::from_value(stored).unwrap();
+ target.target.call(&tenant_id, &context).await;
+ assert!(received.try_recv().is_err());
+ handle.stop(true).await;
+}
diff --git a/src/handlers/http/alerts.rs b/src/handlers/http/alerts.rs
index 19e57d709..892107687 100644
--- a/src/handlers/http/alerts.rs
+++ b/src/handlers/http/alerts.rs
@@ -518,7 +518,12 @@ pub async fn disable_alert_internal(
user_auth_for_alert_config(session_key, &alert.to_alert_config()).await?;
alerts
- .update_state(alert_id, AlertState::Disabled, Some("".into()), tenant_id)
+ .update_state(
+ alert_id,
+ AlertState::Disabled,
+ Some(Default::default()),
+ tenant_id,
+ )
.await?;
let alert = alerts.get_alert_by_id(alert_id, tenant_id).await?;
@@ -571,7 +576,7 @@ pub async fn enable_alert_internal(
.update_state(
alert_id,
AlertState::NotTriggered,
- Some("".into()),
+ Some(Default::default()),
tenant_id,
)
.await?;
diff --git a/src/handlers/http/targets.rs b/src/handlers/http/targets.rs
index cfd003b02..b192002e9 100644
--- a/src/handlers/http/targets.rs
+++ b/src/handlers/http/targets.rs
@@ -48,6 +48,7 @@ pub async fn post_internal(
tenant_id: &Option,
) -> Result {
target.tenant.clone_from(tenant_id);
+ target.apply_webhook_format(None)?;
target.validate_outbound_policy().await?;
// should check for duplicacy and liveness (??)
// add to the map
@@ -153,6 +154,7 @@ pub async fn update(
// esnure that the supplied target id is assigned to the target config
target.id = target_id;
target.tenant = tenant_id;
+ target.apply_webhook_format(Some(&old_target))?;
target.validate_outbound_policy().await?;
// should check for duplicacy and liveness (??)
// add to the map
@@ -187,6 +189,8 @@ mod tests {
let denied_domain = "sensitive.internal.example";
let target: Target = serde_json::from_value(json!({
"name": "sensitive-target",
+ "payloadFormat": "json",
+ "headers": {"Authorization": "Bearer fixture"},
"type": "webhook",
"endpoint": format!("https://{denied_domain}/hook"),
"tenantId": tenant
@@ -222,6 +226,11 @@ mod tests {
response[0]["error"],
"Target domain is denied by outbound policy"
);
+ assert_eq!(response[0]["target"]["payloadFormat"], "json");
+ assert_eq!(
+ response[0]["target"]["headers"]["Authorization"],
+ "********"
+ );
assert!(!response.to_string().contains(denied_domain));
}
@@ -348,4 +357,20 @@ mod tests {
assert!(!text.contains(secret), "{secret} leaked in: {text}");
}
}
+
+ #[actix_web::test]
+ async fn create_rejects_invalid_or_conflicting_webhook_formats() {
+ let app = test::init_service(App::new().route("/targets", web::post().to(post))).await;
+ for (field, control) in [("xml", "json"), ("json", "text"), ("text", "invalid")] {
+ let request = test::TestRequest::post()
+ .uri("/targets")
+ .set_json(json!({
+ "type": "webhook", "name": "fixture", "endpoint": "http://127.0.0.1",
+ "payloadFormat": field, "headers": {"X-Parseable-Payload-Format": control}
+ }))
+ .to_request();
+ let response = test::call_service(&app, request).await;
+ assert_eq!(response.status(), actix_web::http::StatusCode::BAD_REQUEST);
+ }
+ }
}