| 1 | package main |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "crypto/aes" |
| 6 | "crypto/cipher" |
| 7 | "crypto/hmac" |
| 8 | "crypto/sha256" |
| 9 | "encoding/base64" |
| 10 | "encoding/hex" |
| 11 | "encoding/json" |
| 12 | "errors" |
| 13 | "fmt" |
| 14 | "io" |
| 15 | "log" |
| 16 | "net/http" |
| 17 | "strconv" |
| 18 | "strings" |
| 19 | "time" |
| 20 | |
| 21 | "github.com/jackc/pgx/v5" |
| 22 | "github.com/jackc/pgx/v5/pgxpool" |
| 23 | ) |
| 24 | |
| 25 | // webhookPayload is what the API puts in delivery_job.payload for kind 'webhook'. |
| 26 | // Body is the JSON the receiver gets, frozen at fan-out so a retry sends the same bytes. |
| 27 | type webhookPayload struct { |
| 28 | Event string `json:"event" |
| 29 | Body string `json:"body" |
| 30 | } |
| 31 | |
| 32 | // Stored response bodies are cut to this; the delivery log only needs a glance. |
| 33 | const maxResponseBody = 4 |
| 34 | |
| 35 | type webhookSender struct { |
| 36 | db *pgxpool |
| 37 | client *http |
| 38 | key []byte // |
| 39 | hosts *hostLimiter |
| 40 | } |
| 41 | |
| 42 | // A job that finds its host busy waits this long; it is not the receiver's fault, so it records no attempt. |
| 43 | const hostBusyRetry = 5 |
| 44 | |
| 45 | func (w webhookSender |
| 46 | if j.EndpointID |
| 47 | return permanentError{errors |
| 48 | } |
| 49 | var p webhookPayload |
| 50 | if err := json |
| 51 | return permanentError{fmt |
| 52 | } |
| 53 | |
| 54 | // Read at send time: the endpoint may have been disabled or its URL changed since enqueue. |
| 55 | var ( |
| 56 | url, sealed string |
| 57 | active bool |
| 58 | ) |
| 59 | err := w. |
| 60 | `SELECT url, secret, active FROM webhook_endpoint WHERE id = $1`, *j |
| 61 | ).Scan(&url |
| 62 | if errors.Is( |
| 63 | return permanentError{errors |
| 64 | } |
| 65 | if err != nil |
| 66 | return err |
| 67 | } |
| 68 | if !active { |
| 69 | return permanentError{errors |
| 70 | } |
| 71 | secret, err := |
| 72 | if err != nil |
| 73 | return err |
| 74 | } |
| 75 | |
| 76 | req, err := |
| 77 | if err != nil |
| 78 | return permanentError{err |
| 79 | } |
| 80 | for k, v |
| 81 | req.Header.Set |
| 82 | } |
| 83 | |
| 84 | if !w.hosts |
| 85 | return retryAfterError{fmt |
| 86 | } |
| 87 | defer w.hosts. |
| 88 | |
| 89 | started := time. |
| 90 | res, sendErr := |
| 91 | var ( |
| 92 | status *int |
| 93 | resBody *string |
| 94 | ) |
| 95 | if sendErr == nil |
| 96 | b, _ := |
| 97 | res.Body.Close |
| 98 | status, resBody = |
| 99 | } |
| 100 | w.recordAttempt(ctx |
| 101 | |
| 102 | if sendErr != nil |
| 103 | return sendErr |
| 104 | } |
| 105 | return w.classify( |
| 106 | } |
| 107 | |
| 108 | // classify turns a response into the job's next step. |
| 109 | func (w webhookSender |
| 110 | switch code := res |
| 111 | case code >= 200 |
| 112 | return nil |
| 113 | case code == http |
| 114 | _, err := |
| 115 | UPDATE webhook_endpoint |
| 116 | SET active = false, disabled_reason = 'The endpoint responded 410 Gone.', updated_at = now() |
| 117 | WHERE id = $1`, endpointID) |
| 118 | if err != nil |
| 119 | return err |
| 120 | } |
| 121 | return permanentError{errors |
| 122 | case code == http |
| 123 | err := fmt. |
| 124 | if after, ok |
| 125 | return retryAfterError{err |
| 126 | } |
| 127 | return err |
| 128 | default: |
| 129 | // ponytail: every other status retries with backoff, 4xx included; a receiver fixing its config then catches up. Fail fast on 4xx if retries waste too much. |
| 130 | return fmt.Errorf( |
| 131 | } |
| 132 | } |
| 133 | |
| 134 | // recordAttempt writes one delivery_attempt row. A failure to write it is logged, not fatal: |
| 135 | // the job's own result matters more than its log line. |
| 136 | func (w webhookSender |
| 137 | flat := make( |
| 138 | for k := range |
| 139 | flat[k] = |
| 140 | } |
| 141 | var errText *string |
| 142 | if sendErr != nil |
| 143 | errText = ptr( |
| 144 | } |
| 145 | _, err := |
| 146 | INSERT INTO delivery_attempt (job_id, started_at, duration_ms, status_code, error, request_headers, response_body) |
| 147 | VALUES ($1, $2, $3, $4, $5, $6, $7)`, |
| 148 | jobID, started, |
| 149 | if err != nil |
| 150 | log.Printf("job |
| 151 | } |
| 152 | } |
| 153 | |
| 154 | // signedHeaders signs "<timestamp>.<body>" so a receiver can reject replays older |
| 155 | // than a few minutes. X-Hub-Signature-256 signs the body alone, for GitHub-style receivers. |
| 156 | func signedHeaders(secret [] |
| 157 | ts := strconv. |
| 158 | return map[string]string |
| 159 | "Content-Type": "application/json", |
| 160 | "User-Agent": "Ghost-Hookshot/1", |
| 161 | "X-Ghost-Event": event, |
| 162 | "X-Ghost-Delivery": deliveryID, |
| 163 | "X-Ghost-Timestamp": ts, |
| 164 | "X-Ghost-Signature-256": "sha256=" |
| 165 | "X-Hub-Signature-256": "sha256=" |
| 166 | } |
| 167 | } |
| 168 | |
| 169 | func hmacHex(secret [] |
| 170 | mac := hmac. |
| 171 | for _, p |
| 172 | mac.Write(p |
| 173 | } |
| 174 | return hex.EncodeToString( |
| 175 | } |
| 176 | |
| 177 | // openSecret decrypts webhook_endpoint.secret, stored as |
| 178 | // "v1:" + base64(12-byte nonce || AES-256-GCM ciphertext and tag). |
| 179 | func openSecret(key [] |
| 180 | if len(key) |
| 181 | return nil, errors. |
| 182 | } |
| 183 | raw, ok := |
| 184 | if !ok { |
| 185 | return nil, errors. |
| 186 | } |
| 187 | data, err := |
| 188 | if err != nil |
| 189 | return nil, fmt. |
| 190 | } |
| 191 | block, err := |
| 192 | if err != nil |
| 193 | return nil, err |
| 194 | } |
| 195 | gcm, err := |
| 196 | if err != nil |
| 197 | return nil, err |
| 198 | } |
| 199 | if len(data) |
| 200 | return nil, errors. |
| 201 | } |
| 202 | nonce, ciphertext := |
| 203 | plain, err := |
| 204 | if err != nil |
| 205 | return nil, fmt. |
| 206 | } |
| 207 | return plain, nil |
| 208 | } |
| 209 | |
| 210 | // parseRetryAfter reads Retry-After as seconds or an HTTP date. |
| 211 | func parseRetryAfter(v string |
| 212 | if v == "" |
| 213 | return 0, false |
| 214 | } |
| 215 | if s, err |
| 216 | return time.Duration( |
| 217 | } |
| 218 | if t, err |
| 219 | return max(t. |
| 220 | } |
| 221 | return 0, false |
| 222 | } |
| 223 | |
| 224 | func ptr[T any |