feat: M19 API audit log + M16a notifier connectors (Slack, Teams, PagerDuty, OpsGenie)

M19: HTTP middleware records every API call to the immutable audit trail
with method, path, actor, SHA-256 body hash, status, and latency. Best-effort
async recording via goroutine. Health/ready probes excluded.

M16a: Four pluggable notifier connectors — Slack (incoming webhook), Teams
(MessageCard), PagerDuty (Events API v2), OpsGenie (Alert API v2). Each
enabled by config env var. 30 new tests across middleware and connectors.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
Shankar
2026-03-23 17:58:14 -04:00
parent 04fb4a4853
commit c0de973c53
14 changed files with 1399 additions and 5 deletions
@@ -0,0 +1,91 @@
package opsgenie
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"time"
)
const alertAPIURL = "https://api.opsgenie.com/v2/alerts"
// Config holds configuration for the OpsGenie notifier.
type Config struct {
// APIKey is the OpsGenie API integration key.
APIKey string `json:"api_key"`
// Priority is the default alert priority (P1-P5). Defaults to "P3".
Priority string `json:"priority,omitempty"`
// Tags are default tags applied to all alerts.
Tags []string `json:"tags,omitempty"`
}
// Notifier sends notifications to OpsGenie via the Alert API.
type Notifier struct {
config Config
httpClient *http.Client
}
// New creates a new OpsGenie notifier.
func New(config Config) *Notifier {
if config.Priority == "" {
config.Priority = "P3"
}
return &Notifier{
config: config,
httpClient: &http.Client{
Timeout: 10 * time.Second,
},
}
}
// Channel returns the channel identifier.
func (n *Notifier) Channel() string {
return "OpsGenie"
}
// Send delivers a notification to OpsGenie as an alert.
func (n *Notifier) Send(ctx context.Context, recipient string, subject string, body string) error {
alert := ogAlert{
Message: subject,
Description: body,
Priority: n.config.Priority,
Source: "certctl",
Tags: n.config.Tags,
}
jsonBytes, err := json.Marshal(alert)
if err != nil {
return fmt.Errorf("opsgenie: failed to marshal payload: %w", err)
}
req, err := http.NewRequestWithContext(ctx, http.MethodPost, alertAPIURL, bytes.NewReader(jsonBytes))
if err != nil {
return fmt.Errorf("opsgenie: failed to create request: %w", err)
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", "GenieKey "+n.config.APIKey)
resp, err := n.httpClient.Do(req)
if err != nil {
return fmt.Errorf("opsgenie: request failed: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusAccepted && resp.StatusCode != http.StatusOK {
respBody, _ := io.ReadAll(resp.Body)
return fmt.Errorf("opsgenie: API returned HTTP %d: %s", resp.StatusCode, string(respBody))
}
return nil
}
type ogAlert struct {
Message string `json:"message"`
Description string `json:"description,omitempty"`
Priority string `json:"priority,omitempty"`
Source string `json:"source,omitempty"`
Tags []string `json:"tags,omitempty"`
}
@@ -0,0 +1,128 @@
package opsgenie
import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"strings"
"testing"
)
func TestOpsGenie_Channel(t *testing.T) {
n := New(Config{APIKey: "test-key"})
if n.Channel() != "OpsGenie" {
t.Errorf("expected channel OpsGenie, got %s", n.Channel())
}
}
func TestOpsGenie_DefaultPriority(t *testing.T) {
n := New(Config{APIKey: "test-key"})
if n.config.Priority != "P3" {
t.Errorf("expected default priority P3, got %s", n.config.Priority)
}
}
func TestOpsGenie_CustomPriority(t *testing.T) {
n := New(Config{APIKey: "test-key", Priority: "P1"})
if n.config.Priority != "P1" {
t.Errorf("expected priority P1, got %s", n.config.Priority)
}
}
func TestOpsGenie_SendSuccess(t *testing.T) {
var receivedAlert ogAlert
var receivedAuthHeader string
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
t.Errorf("expected POST, got %s", r.Method)
}
if ct := r.Header.Get("Content-Type"); ct != "application/json" {
t.Errorf("expected application/json, got %s", ct)
}
receivedAuthHeader = r.Header.Get("Authorization")
if err := json.NewDecoder(r.Body).Decode(&receivedAlert); err != nil {
t.Fatalf("failed to decode payload: %v", err)
}
w.WriteHeader(http.StatusAccepted)
}))
defer server.Close()
n := New(Config{
APIKey: "test-api-key-123",
Priority: "P2",
Tags: []string{"certctl", "production"},
})
// Override HTTP client to hit test server
n.httpClient = &http.Client{Transport: &urlRewriteTransport{target: server.URL, transport: http.DefaultTransport}}
err := n.Send(context.Background(), "ops-team", "Key Compromise", "Certificate mc-api-prod may have compromised private key")
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if receivedAuthHeader != "GenieKey test-api-key-123" {
t.Errorf("expected GenieKey auth header, got %s", receivedAuthHeader)
}
if receivedAlert.Message != "Key Compromise" {
t.Errorf("expected message 'Key Compromise', got %s", receivedAlert.Message)
}
if receivedAlert.Description != "Certificate mc-api-prod may have compromised private key" {
t.Errorf("expected description with cert details, got %s", receivedAlert.Description)
}
if receivedAlert.Priority != "P2" {
t.Errorf("expected priority P2, got %s", receivedAlert.Priority)
}
if receivedAlert.Source != "certctl" {
t.Errorf("expected source certctl, got %s", receivedAlert.Source)
}
if len(receivedAlert.Tags) != 2 || receivedAlert.Tags[0] != "certctl" {
t.Errorf("expected tags [certctl, production], got %v", receivedAlert.Tags)
}
}
func TestOpsGenie_SendHTTPError(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusUnauthorized)
w.Write([]byte(`{"message":"API key is invalid"}`))
}))
defer server.Close()
n := New(Config{APIKey: "bad-key"})
n.httpClient = &http.Client{Transport: &urlRewriteTransport{target: server.URL, transport: http.DefaultTransport}}
err := n.Send(context.Background(), "", "Test", "body")
if err == nil {
t.Fatal("expected error, got nil")
}
if !strings.Contains(err.Error(), "HTTP 401") {
t.Errorf("expected HTTP 401 in error, got %v", err)
}
}
func TestOpsGenie_SendConnectionError(t *testing.T) {
n := New(Config{APIKey: "test-key"})
n.httpClient = &http.Client{Transport: &urlRewriteTransport{target: "http://127.0.0.1:1", transport: http.DefaultTransport}}
err := n.Send(context.Background(), "", "Test", "body")
if err == nil {
t.Fatal("expected connection error, got nil")
}
if !strings.Contains(err.Error(), "request failed") {
t.Errorf("expected 'request failed' in error, got %v", err)
}
}
// urlRewriteTransport redirects all requests to a test server URL.
type urlRewriteTransport struct {
target string
transport http.RoundTripper
}
func (t *urlRewriteTransport) RoundTrip(req *http.Request) (*http.Response, error) {
req = req.Clone(req.Context())
req.URL.Scheme = "http"
req.URL.Host = strings.TrimPrefix(t.target, "http://")
return t.transport.RoundTrip(req)
}