feat(connectors): T4 add PagerDuty connector

Incident lifecycle + audit-record ingestion via PagerDuty REST API
(Token token=<key> scheme). Two streams with distinct pagination:
GET /incidents uses classic offset/limit/more, GET /audit/records uses
opaque next_cursor. Wave-1 severity collapse: priority P1/critical →
high, P2/error → medium, P3/warning → low, P4/P5/info → low/info;
falls back to urgency (high/low) when no priority is set; resolved
incidents collapse to info regardless. Audit ops: user.role_changed,
user.create/delete, api_key.create/delete, extension.create/delete,
webhook_subscription.create/delete, service.delete,
escalation_policy.delete → high; other *.delete → medium; rest → info.
test_connection() handles both user-level and general-access keys by
probing /users/me first, falling back to /incidents?limit=1 on 401.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
Prince Sinha
2026-05-13 20:21:55 +05:30
co-authored by Cursor
parent 1ba2991725
commit 431ad3434a
5 changed files with 650 additions and 0 deletions
+85
View File
@@ -0,0 +1,85 @@
---
sidebar_position: 73
title: PagerDuty
description: Pull PagerDuty incident lifecycle and audit-record events into AiSOC via the REST API.
---
# PagerDuty
The PagerDuty connector pulls two streams from a single PagerDuty tenant:
1. **Incidents** — `GET /incidents` returns the full incident lifecycle (`triggered → acknowledged → resolved`) with `urgency` (`high / low`) and an optional `priority` (`P1..P5`).
2. **Audit records** — `GET /audit/records` returns the tenant audit trail: user role changes, service config edits, API key issuance, webhook subscription create/delete.
Events are normalised with `source: pagerduty`, `category: saas`.
## Prerequisites
- A **PagerDuty account** on any plan that includes API access (Professional, Business, Enterprise, or Digital Operations).
- A **REST API key**. Two variants:
- **General-access key** — tenant-scoped, can read incidents but not the audit log.
- **User-level key** — paired to a specific user; *the user must be an Account Owner or Account Admin* to read `/audit/records`.
- Both variants are generated under **Integrations → API Access Keys**.
## Setup walkthrough
### 1. Create the API key
1. **Integrations → API Access Keys → Create API User Token** (or "Create General Access Key").
2. **Read-only** is sufficient — the connector never writes to PagerDuty.
3. Copy the token (PagerDuty does not show it again).
### 2. Add the connector in AiSOC
1. **Connectors → Add connector → PagerDuty**.
2. `api_key` = the REST API key (encrypted in the credential vault).
3. `subdomain` *(optional)* = the `acme` part of `acme.pagerduty.com`. Used to build clickable links in normalised events.
4. **Test connection** — probes `GET /users/me` first (user-level key); falls back to `GET /incidents?limit=1` for general-access keys.
5. **Save**.
## Polling details
- Default interval: **300 seconds**.
- Per poll, the connector calls:
- `GET /incidents?limit=100&since=<since>&sort_by=incident_number:desc&statuses[]=triggered,acknowledged,resolved` — paginates with classic `offset` + `more`.
- `GET /audit/records?limit=100&since=<since>` — paginates with the opaque `next_cursor` field.
- Pagination terminates when `more=false` (incidents) or `next_cursor` is empty (audit).
## Severity mapping
Vendor signals collapse to the AiSOC 4-tier ladder per the wave-1 PagerDuty rule:
| Source | Vendor value | AiSOC severity |
|---|---|---|
| incident | priority name `P1` or `critical` | `high` |
| incident | priority name `P2` or `error` | `medium` |
| incident | priority name `P3` or `warning` / `warn` | `low` |
| incident | priority name `P4` / `P5` / `info` | `low` / `info` |
| incident | no priority, urgency `high` | `high` |
| incident | no priority, urgency `low` | `low` |
| incident | `status = resolved` | collapses to `info` |
| audit | `user.role_changed` / `user.create` / `user.delete` | `high` |
| audit | `api_key.create` / `api_key.delete` | `high` |
| audit | `extension.create` / `extension.delete` | `high` |
| audit | `webhook_subscription.create` / `webhook_subscription.delete` | `high` |
| audit | `service.delete` / `escalation_policy.delete` | `high` |
| audit | other `*.delete` / `*.destroyed` | `medium` |
| audit | other operations | `info` |
## Troubleshooting
**`HTTP 401`** — the key is invalid or revoked. If you used a general-access key against the audit endpoint, you'll see `401` on `/audit/records` even though `/incidents` works. Switch to a user-level key from an Account Owner.
**`HTTP 403` on audit** — auth is fine but the user lacks the **Account Owner** or **Account Admin** role required to read the audit log. Adjust the user's role or use a different account.
**Resolved incidents flooding the timeline** — by design the connector pulls resolved incidents but collapses them to severity `info`. If you want to drop them entirely, add a downstream filter in the alert-fusion pipeline.
## What this connector does **not** cover
- **Triggering pages from AiSOC** — that's the [PagerDuty Paging action plugin](/docs/connectors/pagerduty-paging), a separate write-mode integration.
- **Per-incident log entry stream** — only the top-level incident envelope is pulled. The fine-grained "log_entries" stream is a separate endpoint and deliberately omitted from wave-1 to avoid quota pressure.
## Related
- [Opsgenie](/docs/connectors/opsgenie) — sibling on-call platform with the same audit surface.
- [PagerDuty Paging](/docs/connectors/pagerduty-paging) — outbound paging action plugin (write-mode counterpart).
+26
View File
@@ -0,0 +1,26 @@
id: pagerduty
name: PagerDuty (Incidents + Audit)
version: "1.0.0"
plugin_type: connector
tier: stable
description: >
PagerDuty on-call platform connector. Pulls incident lifecycle events
(triggered / acknowledged / resolved) and tenant audit records (role
changes, integration edits, API key issuance) via the REST API. Requires
a read-only REST API key.
author: AiSOC Core Team
tags: [saas, oncall, paging, incidents, audit, pagerduty]
homepage: https://github.com/beenuar/AiSOC/tree/main/services/connectors/app/connectors/pagerduty.py
license: MIT
min_aisoc_version: "4.0.0"
config_schema:
type: object
required: [api_key]
properties:
api_key:
type: string
description: "PagerDuty REST API key (read-only is sufficient)"
secret: true
subdomain:
type: string
description: "Optional acme subdomain (used to build clickable incident URLs)"
@@ -0,0 +1,337 @@
"""
PagerDuty connector.
Pulls two streams from the PagerDuty REST API:
1. **Incidents** — ``GET /incidents`` returns the full incident
timeline. We page through incidents updated in the poll window and
normalise their ``urgency`` / ``status`` into AiSOC severity.
2. **Audit records** — ``GET /audit/records`` returns the tenant audit
trail (user role changes, service config edits, API key issuance,
webhook subscriptions). This is the on-call security surface we
care about most: an attacker who pwns a PagerDuty admin can silence
pages globally.
Auth: a REST API key (``Authorization: Token token=<key>``). The
operator generates a *user-level* or *general access* key under
**Integrations → API Access Keys**. Read-only is sufficient.
"""
from __future__ import annotations
from datetime import UTC, datetime, timedelta
from typing import Any
import httpx
import structlog
from app.connectors.base import BaseConnector, Capability, ConnectorSchema, Field, OAuthHints
logger = structlog.get_logger()
_BASE = "https://api.pagerduty.com"
_MAX_PAGES = 20
_PAGE_SIZE = 100
class PagerDutyConnector(BaseConnector):
"""PagerDuty incidents + audit records."""
connector_id = "pagerduty"
connector_name = "PagerDuty"
connector_category = "saas"
@classmethod
def schema(cls) -> ConnectorSchema:
return ConnectorSchema(
connector_id=cls.connector_id,
connector_name=cls.connector_name,
category=cls.connector_category,
description=(
"PagerDuty on-call platform. Pulls incident lifecycle events and "
"tenant audit records (role changes, integration edits, API key "
"issuance) via the REST API. Requires a read-only REST API key."
),
docs_url="/docs/connectors/pagerduty",
fields=[
Field(
"api_key",
"secret",
"REST API Key",
help_text=("Generate under Integrations → API Access Keys. Read-only access is sufficient."),
),
Field(
"subdomain",
"string",
"Subdomain (optional)",
required=False,
placeholder="acme",
help_text=("Your acme.pagerduty.com subdomain. Used to build clickable links in normalised events; not required for ingestion."),
),
],
oauth=OAuthHints(
supported_in_hosted=True,
authorize_url="https://app.pagerduty.com/oauth/authorize",
token_url="https://identity.pagerduty.com/oauth/token",
scopes=["read"],
),
)
@classmethod
def capabilities(cls) -> tuple[Capability, ...]:
return (
Capability.PULL_ALERTS,
Capability.PULL_AUDIT,
Capability.READ_AUDIT_TRAIL,
)
def __init__(self, api_key: str, subdomain: str | None = None):
self._api_key = api_key
self._subdomain = (subdomain or "").strip() or None
# --------------------------- auth ---------------------------
def _headers(self) -> dict[str, str]:
return {
# PagerDuty's classic API uses the ``Token token=...`` scheme;
# ``Bearer`` only works for OAuth-issued tokens.
"Authorization": f"Token token={self._api_key}",
"Accept": "application/vnd.pagerduty+json;version=2",
"Content-Type": "application/json",
"User-Agent": "AiSOC-Connector/1.0",
}
# ------------------------- contract -------------------------
async def test_connection(self) -> dict[str, Any]:
try:
async with httpx.AsyncClient(timeout=15.0) as client:
resp = await client.get(
f"{_BASE}/users/me",
headers=self._headers(),
)
# ``/users/me`` is only valid for *user-level* keys.
# General-access keys return 401 here but still work for
# ``/incidents`` so we fall back to probing that.
if resp.status_code == 200:
me = resp.json().get("user", {})
return {
"success": True,
"connector": self.connector_id,
"user_email": me.get("email"),
"auth_type": "user_key",
}
if resp.status_code == 401:
probe = await client.get(
f"{_BASE}/incidents",
headers=self._headers(),
params={"limit": 1},
)
if probe.status_code == 200:
return {
"success": True,
"connector": self.connector_id,
"auth_type": "general_access_key",
}
return {
"success": False,
"connector": self.connector_id,
"error": f"HTTP {resp.status_code}: {resp.text[:200]}",
}
except Exception as exc:
return {"success": False, "connector": self.connector_id, "error": str(exc)}
async def fetch_alerts(self, since_seconds: int = 300) -> list[dict[str, Any]]:
since = datetime.now(UTC) - timedelta(seconds=since_seconds)
since_iso = since.strftime("%Y-%m-%dT%H:%M:%SZ")
events: list[dict[str, Any]] = []
async with httpx.AsyncClient(timeout=30.0) as client:
incidents = await self._paginate_offset(
client=client,
path="/incidents",
params={
"limit": _PAGE_SIZE,
"since": since_iso,
"sort_by": "incident_number:desc",
"statuses[]": ["triggered", "acknowledged", "resolved"],
},
stream="incident",
items_key="incidents",
)
events.extend(incidents)
audit = await self._paginate_cursor(
client=client,
path="/audit/records",
params={"limit": _PAGE_SIZE, "since": since_iso},
stream="audit_record",
items_key="records",
)
events.extend(audit)
return [self.normalize(e) for e in events]
async def _paginate_offset(
self,
client: httpx.AsyncClient,
path: str,
params: dict[str, Any],
stream: str,
items_key: str,
) -> list[dict[str, Any]]:
"""Classic PagerDuty pagination: ``offset`` / ``limit`` / ``more``."""
out: list[dict[str, Any]] = []
offset = 0
for _ in range(_MAX_PAGES):
call_params = dict(params, offset=offset)
resp = await client.get(f"{_BASE}{path}", headers=self._headers(), params=call_params)
if resp.status_code != 200:
logger.warning("pagerduty.fetch_failed", path=path, status=resp.status_code, body=resp.text[:200])
break
body = resp.json() or {}
items = body.get(items_key) or []
if not items:
break
for item in items:
item["_aisoc_stream"] = stream
out.append(item)
if not body.get("more"):
break
offset += len(items)
return out
async def _paginate_cursor(
self,
client: httpx.AsyncClient,
path: str,
params: dict[str, Any],
stream: str,
items_key: str,
) -> list[dict[str, Any]]:
"""Newer audit endpoint uses opaque ``cursor`` pagination."""
out: list[dict[str, Any]] = []
cursor: str | None = None
for _ in range(_MAX_PAGES):
call_params = dict(params)
if cursor:
call_params["cursor"] = cursor
resp = await client.get(f"{_BASE}{path}", headers=self._headers(), params=call_params)
if resp.status_code != 200:
logger.warning("pagerduty.audit_fetch_failed", path=path, status=resp.status_code, body=resp.text[:200])
break
body = resp.json() or {}
items = body.get(items_key) or []
if not items:
break
for item in items:
item["_aisoc_stream"] = stream
out.append(item)
cursor = body.get("next_cursor")
if not cursor:
break
return out
# ----------------------- normalize --------------------------
# PagerDuty incident urgency × status → AiSOC severity. Severity
# follows the urgency primarily; resolved incidents collapse to
# ``info`` so closed pages aren't re-surfaced as live alerts.
_URGENCY_SEVERITY = {"high": "high", "low": "low"}
# Vendor priority labels map per the wave-1 PagerDuty rule
# (``info → info, warning → low, error → medium, critical → high``).
_PRIORITY_SEVERITY = {
"info": "info",
"warning": "low",
"warn": "low",
"error": "medium",
"critical": "high",
"p1": "high",
"p2": "medium",
"p3": "low",
"p4": "low",
"p5": "info",
}
_HIGH_RISK_AUDIT_ACTIONS = (
"user.role_changed",
"user.delete",
"user.create",
"api_key.create",
"api_key.delete",
"extension.create",
"extension.delete",
"webhook_subscription.create",
"webhook_subscription.delete",
"service.delete",
"escalation_policy.delete",
)
def _normalize_incident(self, raw: dict[str, Any]) -> dict[str, Any]:
status = (raw.get("status") or "").lower()
urgency = (raw.get("urgency") or "low").lower()
priority_obj = raw.get("priority") or {}
priority_name = (priority_obj.get("name") or "").lower() if isinstance(priority_obj, dict) else ""
if priority_name and priority_name in self._PRIORITY_SEVERITY:
severity = self._PRIORITY_SEVERITY[priority_name]
else:
severity = self._URGENCY_SEVERITY.get(urgency, "low")
if status == "resolved":
severity = "info"
service = (raw.get("service") or {}).get("summary") if isinstance(raw.get("service"), dict) else None
assignees = raw.get("assignments") or []
assignee_email = None
if assignees and isinstance(assignees[0], dict):
assignee_email = ((assignees[0].get("assignee") or {}).get("summary")) if isinstance(assignees[0].get("assignee"), dict) else None
link = raw.get("html_url") or (f"https://{self._subdomain}.pagerduty.com/incidents/{raw.get('id')}" if self._subdomain and raw.get("id") else None)
return {
"source": self.connector_id,
"external_id": f"pagerduty-incident-{raw.get('id', raw.get('incident_number', ''))}",
"title": raw.get("title") or raw.get("description") or "PagerDuty incident",
"description": (f"service={service or 'unknown'}; status={status}; urgency={urgency}; priority={priority_name or 'none'}; url={link or 'n/a'}"),
"severity": severity,
"actor": assignee_email,
"actor_email": assignee_email,
"src_ip": None,
"event_type": f"pagerduty.incident.{status or 'updated'}",
"raw_event": raw,
"created_at": raw.get("created_at") or raw.get("last_status_change_at"),
}
def _normalize_audit(self, raw: dict[str, Any]) -> dict[str, Any]:
action = raw.get("action") or raw.get("event_type") or "pagerduty.audit"
actor = raw.get("actor") or {}
actor_email = actor.get("email") if isinstance(actor, dict) else None
if any(action == h for h in self._HIGH_RISK_AUDIT_ACTIONS):
severity = "high"
elif action.endswith(".delete") or action.endswith(".destroyed"):
severity = "medium"
else:
severity = "info"
return {
"source": self.connector_id,
"external_id": f"pagerduty-audit-{raw.get('id', '')}",
"title": f"PagerDuty audit: {action}",
"description": (f"actor={actor_email or 'unknown'}; action={action}; method={raw.get('method', {}).get('type', '') if isinstance(raw.get('method'), dict) else ''}"),
"severity": severity,
"actor": actor_email,
"actor_email": actor_email,
"src_ip": (raw.get("method") or {}).get("source_ip") if isinstance(raw.get("method"), dict) else None,
"event_type": f"pagerduty.{action}",
"raw_event": raw,
"created_at": raw.get("execution_time") or raw.get("created_at"),
}
def normalize(self, raw: dict[str, Any]) -> dict[str, Any]:
stream = raw.get("_aisoc_stream", "incident")
if stream == "audit_record":
return self._normalize_audit(raw)
return self._normalize_incident(raw)
@@ -0,0 +1,139 @@
"""Tests for the PagerDuty connector (T4.2)."""
from __future__ import annotations
import json
from pathlib import Path
import httpx
import pytest
import respx
from app.connectors import CONNECTOR_REGISTRY
from app.connectors.base import Capability
from app.connectors.pagerduty import PagerDutyConnector
_FIXTURE = Path(__file__).resolve().parent.parent / "fixtures" / "pagerduty" / "sample_event.json"
_BASE = "https://api.pagerduty.com"
_KEY = "pd_api_key_fakefakefakefakefakefakefa" # noqa: S105 — fake
@pytest.fixture(scope="module")
def fixture() -> dict:
return json.loads(_FIXTURE.read_text())
def test_schema_valid():
schema = PagerDutyConnector.schema()
assert schema.connector_id == "pagerduty"
assert schema.category == "saas"
names = {f.name for f in schema.fields}
assert "api_key" in names
secret = next(f for f in schema.fields if f.name == "api_key")
assert secret.type == "secret"
assert Capability.PULL_ALERTS in PagerDutyConnector.capabilities()
assert Capability.PULL_AUDIT in PagerDutyConnector.capabilities()
def test_registry_contains_pagerduty():
assert "pagerduty" in CONNECTOR_REGISTRY
assert CONNECTOR_REGISTRY["pagerduty"] is PagerDutyConnector
def test_normalize_incident_p1_triggered_high(fixture):
ev = dict(fixture["incidents"][0], _aisoc_stream="incident")
out = PagerDutyConnector(_KEY, subdomain="acme").normalize(ev)
# P1 priority maps to high via the wave-1 priority table.
assert out["severity"] == "high"
assert out["source"] == "pagerduty"
assert out["external_id"] == "pagerduty-incident-PT4KHLK"
assert out["event_type"] == "pagerduty.incident.triggered"
def test_normalize_incident_low_urgency_low(fixture):
ev = dict(fixture["incidents"][1], _aisoc_stream="incident")
out = PagerDutyConnector(_KEY).normalize(ev)
# P4 priority → low.
assert out["severity"] == "low"
def test_normalize_incident_resolved_collapses_info(fixture):
ev = dict(fixture["incidents"][2], _aisoc_stream="incident")
out = PagerDutyConnector(_KEY).normalize(ev)
# Resolved incidents collapse to info regardless of urgency/priority.
assert out["severity"] == "info"
assert out["event_type"] == "pagerduty.incident.resolved"
def test_normalize_audit_api_key_create_high(fixture):
ev = dict(fixture["records"][0], _aisoc_stream="audit_record")
out = PagerDutyConnector(_KEY).normalize(ev)
assert out["severity"] == "high"
assert out["src_ip"] == "10.0.0.10"
assert out["event_type"] == "pagerduty.api_key.create"
def test_normalize_audit_role_changed_high(fixture):
ev = dict(fixture["records"][1], _aisoc_stream="audit_record")
out = PagerDutyConnector(_KEY).normalize(ev)
assert out["severity"] == "high"
def test_normalize_audit_routine_info(fixture):
ev = dict(fixture["records"][2], _aisoc_stream="audit_record")
out = PagerDutyConnector(_KEY).normalize(ev)
assert out["severity"] == "info"
@pytest.mark.asyncio
@respx.mock
async def test_fetch_alerts_uses_pagination(fixture):
inc_calls = 0
def inc_handler(request: httpx.Request) -> httpx.Response:
nonlocal inc_calls
inc_calls += 1
if inc_calls == 1:
return httpx.Response(200, json={"incidents": fixture["incidents"], "more": True})
return httpx.Response(200, json={"incidents": [], "more": False})
respx.get(f"{_BASE}/incidents").mock(side_effect=inc_handler)
audit_calls = 0
def audit_handler(request: httpx.Request) -> httpx.Response:
nonlocal audit_calls
audit_calls += 1
if audit_calls == 1:
return httpx.Response(200, json={"records": fixture["records"], "next_cursor": "cur2"})
return httpx.Response(200, json={"records": [], "next_cursor": None})
respx.get(f"{_BASE}/audit/records").mock(side_effect=audit_handler)
connector = PagerDutyConnector(_KEY)
events = await connector.fetch_alerts(since_seconds=10**9)
# Both pagination styles ran.
assert inc_calls == 2 # offset+more terminated after empty page
assert audit_calls == 2 # cursor terminated after empty page
assert len(events) == len(fixture["incidents"]) + len(fixture["records"])
@pytest.mark.asyncio
@respx.mock
async def test_test_connection_user_key():
respx.get(f"{_BASE}/users/me").mock(
return_value=httpx.Response(200, json={"user": {"email": "owner@example.com"}}),
)
out = await PagerDutyConnector(_KEY).test_connection()
assert out["success"] is True
assert out["auth_type"] == "user_key"
@pytest.mark.asyncio
@respx.mock
async def test_test_connection_general_access_key_fallback():
respx.get(f"{_BASE}/users/me").mock(return_value=httpx.Response(401, text="not a user key"))
respx.get(f"{_BASE}/incidents").mock(return_value=httpx.Response(200, json={"incidents": []}))
out = await PagerDutyConnector(_KEY).test_connection()
assert out["success"] is True
assert out["auth_type"] == "general_access_key"
@@ -0,0 +1,63 @@
{
"incidents": [
{
"id": "PT4KHLK",
"incident_number": 1234,
"title": "Database CPU > 95%",
"status": "triggered",
"urgency": "high",
"priority": {"name": "P1"},
"created_at": "2099-01-01T12:00:00Z",
"service": {"summary": "Production Postgres"},
"html_url": "https://acme.pagerduty.com/incidents/PT4KHLK",
"assignments": [
{"assignee": {"summary": "alice@example.com"}}
]
},
{
"id": "PT4KHLM",
"incident_number": 1235,
"title": "Low-urgency disk space warning",
"status": "acknowledged",
"urgency": "low",
"priority": {"name": "P4"},
"created_at": "2099-01-01T12:01:00Z",
"service": {"summary": "Backups service"},
"assignments": []
},
{
"id": "PT4KHLN",
"incident_number": 1236,
"title": "Resolved page",
"status": "resolved",
"urgency": "high",
"priority": {"name": "P1"},
"created_at": "2099-01-01T11:58:00Z",
"service": {"summary": "Production Postgres"}
}
],
"records": [
{
"id": "01H1234567ABCDEF",
"action": "api_key.create",
"execution_time": "2099-01-01T12:02:00Z",
"actor": {"email": "owner@example.com"},
"method": {"type": "browser", "source_ip": "10.0.0.10"}
},
{
"id": "01H1234567ABCDEG",
"action": "user.role_changed",
"execution_time": "2099-01-01T12:03:00Z",
"actor": {"email": "owner@example.com"},
"method": {"type": "api"}
},
{
"id": "01H1234567ABCDEH",
"action": "service.update",
"execution_time": "2099-01-01T12:04:00Z",
"actor": {"email": "ops@example.com"},
"method": {"type": "api"}
}
],
"more": false
}