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:
shankar0123
2026-03-23 17:58:14 -04:00
parent b227502cef
commit 9b0ff37973
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)
}
@@ -0,0 +1,100 @@
package pagerduty
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"time"
)
const eventsAPIURL = "https://events.pagerduty.com/v2/enqueue"
// Config holds configuration for the PagerDuty notifier.
type Config struct {
// RoutingKey is the PagerDuty Events API v2 integration/routing key.
RoutingKey string `json:"routing_key"`
// Severity is the default event severity (critical, error, warning, info).
// Defaults to "warning" if not set.
Severity string `json:"severity,omitempty"`
}
// Notifier sends notifications to PagerDuty via the Events API v2.
type Notifier struct {
config Config
httpClient *http.Client
}
// New creates a new PagerDuty notifier.
func New(config Config) *Notifier {
if config.Severity == "" {
config.Severity = "warning"
}
return &Notifier{
config: config,
httpClient: &http.Client{
Timeout: 10 * time.Second,
},
}
}
// Channel returns the channel identifier.
func (n *Notifier) Channel() string {
return "PagerDuty"
}
// Send delivers a notification to PagerDuty as a trigger event.
func (n *Notifier) Send(ctx context.Context, recipient string, subject string, body string) error {
event := pdEvent{
RoutingKey: n.config.RoutingKey,
EventAction: "trigger",
Payload: pdPayload{
Summary: subject,
Severity: n.config.Severity,
Source: "certctl",
CustomDetails: map[string]string{
"body": body,
"recipient": recipient,
},
},
}
jsonBytes, err := json.Marshal(event)
if err != nil {
return fmt.Errorf("pagerduty: failed to marshal payload: %w", err)
}
req, err := http.NewRequestWithContext(ctx, http.MethodPost, eventsAPIURL, bytes.NewReader(jsonBytes))
if err != nil {
return fmt.Errorf("pagerduty: failed to create request: %w", err)
}
req.Header.Set("Content-Type", "application/json")
resp, err := n.httpClient.Do(req)
if err != nil {
return fmt.Errorf("pagerduty: 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("pagerduty: API returned HTTP %d: %s", resp.StatusCode, string(respBody))
}
return nil
}
type pdEvent struct {
RoutingKey string `json:"routing_key"`
EventAction string `json:"event_action"`
Payload pdPayload `json:"payload"`
}
type pdPayload struct {
Summary string `json:"summary"`
Severity string `json:"severity"`
Source string `json:"source"`
CustomDetails map[string]string `json:"custom_details,omitempty"`
}
@@ -0,0 +1,144 @@
package pagerduty
import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"strings"
"testing"
)
func TestPagerDuty_Channel(t *testing.T) {
n := New(Config{RoutingKey: "test-key"})
if n.Channel() != "PagerDuty" {
t.Errorf("expected channel PagerDuty, got %s", n.Channel())
}
}
func TestPagerDuty_DefaultSeverity(t *testing.T) {
n := New(Config{RoutingKey: "test-key"})
if n.config.Severity != "warning" {
t.Errorf("expected default severity 'warning', got %s", n.config.Severity)
}
}
func TestPagerDuty_CustomSeverity(t *testing.T) {
n := New(Config{RoutingKey: "test-key", Severity: "critical"})
if n.config.Severity != "critical" {
t.Errorf("expected severity 'critical', got %s", n.config.Severity)
}
}
func TestPagerDuty_SendSuccess(t *testing.T) {
var receivedEvent pdEvent
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)
}
if err := json.NewDecoder(r.Body).Decode(&receivedEvent); err != nil {
t.Fatalf("failed to decode payload: %v", err)
}
w.WriteHeader(http.StatusAccepted)
}))
defer server.Close()
// Override the events URL for testing — use a custom HTTP client that redirects
n := New(Config{RoutingKey: "test-routing-key", Severity: "error"})
// We can't easily override the const URL, so test with a direct HTTP call approach.
// Instead, test the payload structure by calling Send with a mock server.
// We need to make the notifier use our test server URL.
// The simplest way: create the notifier, then manually set the URL by using the test server.
// Since eventsAPIURL is a const, we'll test by replacing the http client's transport.
// Alternative approach: just test that the method constructs the right payload
// by using a custom transport that intercepts the request.
n.httpClient = server.Client()
// For this test, we need to override the target URL. Since it's a package-level const,
// we'll create a custom RoundTripper that redirects to our test server.
originalURL := eventsAPIURL
_ = originalURL // just to avoid unused var in case we reference it
transport := &urlRewriteTransport{
target: server.URL,
transport: http.DefaultTransport,
}
n.httpClient = &http.Client{Transport: transport}
err := n.Send(context.Background(), "oncall@example.com", "Cert Expired", "mc-api-prod has expired")
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if receivedEvent.RoutingKey != "test-routing-key" {
t.Errorf("expected routing key test-routing-key, got %s", receivedEvent.RoutingKey)
}
if receivedEvent.EventAction != "trigger" {
t.Errorf("expected event action trigger, got %s", receivedEvent.EventAction)
}
if receivedEvent.Payload.Summary != "Cert Expired" {
t.Errorf("expected summary 'Cert Expired', got %s", receivedEvent.Payload.Summary)
}
if receivedEvent.Payload.Severity != "error" {
t.Errorf("expected severity error, got %s", receivedEvent.Payload.Severity)
}
if receivedEvent.Payload.Source != "certctl" {
t.Errorf("expected source certctl, got %s", receivedEvent.Payload.Source)
}
if receivedEvent.Payload.CustomDetails["body"] != "mc-api-prod has expired" {
t.Errorf("expected body in custom_details, got %v", receivedEvent.Payload.CustomDetails)
}
if receivedEvent.Payload.CustomDetails["recipient"] != "oncall@example.com" {
t.Errorf("expected recipient in custom_details, got %v", receivedEvent.Payload.CustomDetails)
}
}
func TestPagerDuty_SendHTTPError(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusBadRequest)
w.Write([]byte(`{"status":"invalid","message":"bad routing key"}`))
}))
defer server.Close()
n := New(Config{RoutingKey: "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 400") {
t.Errorf("expected HTTP 400 in error, got %v", err)
}
}
func TestPagerDuty_SendConnectionError(t *testing.T) {
n := New(Config{RoutingKey: "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)
}
@@ -0,0 +1,92 @@
package slack
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"time"
)
// Config holds configuration for the Slack notifier.
type Config struct {
// WebhookURL is the Slack incoming webhook URL.
WebhookURL string `json:"webhook_url"`
// ChannelOverride optionally overrides the webhook's default channel.
ChannelOverride string `json:"channel,omitempty"`
// Username optionally sets the bot display name.
Username string `json:"username,omitempty"`
// IconEmoji optionally sets the bot icon (e.g., ":lock:").
IconEmoji string `json:"icon_emoji,omitempty"`
}
// Notifier sends notifications to Slack via incoming webhooks.
type Notifier struct {
config Config
httpClient *http.Client
}
// New creates a new Slack notifier.
func New(config Config) *Notifier {
return &Notifier{
config: config,
httpClient: &http.Client{
Timeout: 10 * time.Second,
},
}
}
// Channel returns the channel identifier.
func (n *Notifier) Channel() string {
return "Slack"
}
// Send delivers a notification to Slack via webhook.
func (n *Notifier) Send(ctx context.Context, recipient string, subject string, body string) error {
payload := slackMessage{
Text: fmt.Sprintf("*%s*\n%s", subject, body),
}
if n.config.ChannelOverride != "" {
payload.Channel = n.config.ChannelOverride
}
if n.config.Username != "" {
payload.Username = n.config.Username
}
if n.config.IconEmoji != "" {
payload.IconEmoji = n.config.IconEmoji
}
jsonBytes, err := json.Marshal(payload)
if err != nil {
return fmt.Errorf("slack: failed to marshal payload: %w", err)
}
req, err := http.NewRequestWithContext(ctx, http.MethodPost, n.config.WebhookURL, bytes.NewReader(jsonBytes))
if err != nil {
return fmt.Errorf("slack: failed to create request: %w", err)
}
req.Header.Set("Content-Type", "application/json")
resp, err := n.httpClient.Do(req)
if err != nil {
return fmt.Errorf("slack: request failed: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
respBody, _ := io.ReadAll(resp.Body)
return fmt.Errorf("slack: webhook returned HTTP %d: %s", resp.StatusCode, string(respBody))
}
return nil
}
type slackMessage struct {
Text string `json:"text"`
Channel string `json:"channel,omitempty"`
Username string `json:"username,omitempty"`
IconEmoji string `json:"icon_emoji,omitempty"`
}
@@ -0,0 +1,107 @@
package slack
import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"strings"
"testing"
)
func TestSlack_Channel(t *testing.T) {
n := New(Config{WebhookURL: "https://hooks.slack.com/test"})
if n.Channel() != "Slack" {
t.Errorf("expected channel Slack, got %s", n.Channel())
}
}
func TestSlack_SendSuccess(t *testing.T) {
var receivedPayload slackMessage
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)
}
if err := json.NewDecoder(r.Body).Decode(&receivedPayload); err != nil {
t.Fatalf("failed to decode payload: %v", err)
}
w.WriteHeader(http.StatusOK)
}))
defer server.Close()
n := New(Config{WebhookURL: server.URL})
err := n.Send(context.Background(), "ops@example.com", "Cert Expiring", "mc-api-prod expires in 7 days")
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if !strings.Contains(receivedPayload.Text, "*Cert Expiring*") {
t.Errorf("expected bold subject in text, got %q", receivedPayload.Text)
}
if !strings.Contains(receivedPayload.Text, "mc-api-prod expires in 7 days") {
t.Errorf("expected body in text, got %q", receivedPayload.Text)
}
}
func TestSlack_SendWithOverrides(t *testing.T) {
var receivedPayload slackMessage
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
json.NewDecoder(r.Body).Decode(&receivedPayload)
w.WriteHeader(http.StatusOK)
}))
defer server.Close()
n := New(Config{
WebhookURL: server.URL,
ChannelOverride: "#alerts",
Username: "certctl-bot",
IconEmoji: ":lock:",
})
err := n.Send(context.Background(), "", "Test", "body")
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if receivedPayload.Channel != "#alerts" {
t.Errorf("expected channel #alerts, got %s", receivedPayload.Channel)
}
if receivedPayload.Username != "certctl-bot" {
t.Errorf("expected username certctl-bot, got %s", receivedPayload.Username)
}
if receivedPayload.IconEmoji != ":lock:" {
t.Errorf("expected icon_emoji :lock:, got %s", receivedPayload.IconEmoji)
}
}
func TestSlack_SendHTTPError(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusForbidden)
w.Write([]byte("invalid_token"))
}))
defer server.Close()
n := New(Config{WebhookURL: server.URL})
err := n.Send(context.Background(), "", "Test", "body")
if err == nil {
t.Fatal("expected error, got nil")
}
if !strings.Contains(err.Error(), "HTTP 403") {
t.Errorf("expected HTTP 403 in error, got %v", err)
}
}
func TestSlack_SendConnectionError(t *testing.T) {
n := New(Config{WebhookURL: "http://127.0.0.1:1"})
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)
}
}
@@ -0,0 +1,93 @@
package teams
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"time"
)
// Config holds configuration for the Microsoft Teams notifier.
type Config struct {
// WebhookURL is the Teams incoming webhook URL.
WebhookURL string `json:"webhook_url"`
}
// Notifier sends notifications to Microsoft Teams via incoming webhooks.
type Notifier struct {
config Config
httpClient *http.Client
}
// New creates a new Teams notifier.
func New(config Config) *Notifier {
return &Notifier{
config: config,
httpClient: &http.Client{
Timeout: 10 * time.Second,
},
}
}
// Channel returns the channel identifier.
func (n *Notifier) Channel() string {
return "Teams"
}
// Send delivers a notification to Teams via webhook using MessageCard format.
func (n *Notifier) Send(ctx context.Context, recipient string, subject string, body string) error {
card := teamsMessageCard{
Type: "MessageCard",
Context: "https://schema.org/extensions",
ThemeColor: "0076D7",
Summary: subject,
Sections: []teamsSection{
{
ActivityTitle: subject,
Text: body,
Markdown: true,
},
},
}
jsonBytes, err := json.Marshal(card)
if err != nil {
return fmt.Errorf("teams: failed to marshal payload: %w", err)
}
req, err := http.NewRequestWithContext(ctx, http.MethodPost, n.config.WebhookURL, bytes.NewReader(jsonBytes))
if err != nil {
return fmt.Errorf("teams: failed to create request: %w", err)
}
req.Header.Set("Content-Type", "application/json")
resp, err := n.httpClient.Do(req)
if err != nil {
return fmt.Errorf("teams: request failed: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
respBody, _ := io.ReadAll(resp.Body)
return fmt.Errorf("teams: webhook returned HTTP %d: %s", resp.StatusCode, string(respBody))
}
return nil
}
type teamsMessageCard struct {
Type string `json:"@type"`
Context string `json:"@context"`
ThemeColor string `json:"themeColor"`
Summary string `json:"summary"`
Sections []teamsSection `json:"sections"`
}
type teamsSection struct {
ActivityTitle string `json:"activityTitle"`
Text string `json:"text"`
Markdown bool `json:"markdown"`
}
@@ -0,0 +1,91 @@
package teams
import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"strings"
"testing"
)
func TestTeams_Channel(t *testing.T) {
n := New(Config{WebhookURL: "https://outlook.office.com/webhook/test"})
if n.Channel() != "Teams" {
t.Errorf("expected channel Teams, got %s", n.Channel())
}
}
func TestTeams_SendSuccess(t *testing.T) {
var receivedCard teamsMessageCard
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)
}
if err := json.NewDecoder(r.Body).Decode(&receivedCard); err != nil {
t.Fatalf("failed to decode payload: %v", err)
}
w.WriteHeader(http.StatusOK)
}))
defer server.Close()
n := New(Config{WebhookURL: server.URL})
err := n.Send(context.Background(), "team@example.com", "Renewal Failed", "Certificate mc-api-prod renewal failed after 3 attempts")
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if receivedCard.Type != "MessageCard" {
t.Errorf("expected @type MessageCard, got %s", receivedCard.Type)
}
if receivedCard.Summary != "Renewal Failed" {
t.Errorf("expected summary 'Renewal Failed', got %s", receivedCard.Summary)
}
if receivedCard.ThemeColor != "0076D7" {
t.Errorf("expected theme color 0076D7, got %s", receivedCard.ThemeColor)
}
if len(receivedCard.Sections) != 1 {
t.Fatalf("expected 1 section, got %d", len(receivedCard.Sections))
}
if receivedCard.Sections[0].ActivityTitle != "Renewal Failed" {
t.Errorf("expected section title 'Renewal Failed', got %s", receivedCard.Sections[0].ActivityTitle)
}
if !strings.Contains(receivedCard.Sections[0].Text, "mc-api-prod") {
t.Errorf("expected body to contain cert ID, got %s", receivedCard.Sections[0].Text)
}
if !receivedCard.Sections[0].Markdown {
t.Error("expected markdown=true in section")
}
}
func TestTeams_SendHTTPError(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusBadRequest)
w.Write([]byte("bad request"))
}))
defer server.Close()
n := New(Config{WebhookURL: server.URL})
err := n.Send(context.Background(), "", "Test", "body")
if err == nil {
t.Fatal("expected error, got nil")
}
if !strings.Contains(err.Error(), "HTTP 400") {
t.Errorf("expected HTTP 400 in error, got %v", err)
}
}
func TestTeams_SendConnectionError(t *testing.T) {
n := New(Config{WebhookURL: "http://127.0.0.1:1"})
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)
}
}