rotate: Resend API-key driver (create→verify→revoke)
First of the vibe-coder API-rotation batch. Resend mints a new API key authenticated by the old one (POST /api-keys), verifies it by listing keys with the new Bearer token and asserting its id is present, then deletes the old key by id (DELETE /api-keys/<id>). Self-contained blob resend://host/?id=&secret= keeps the token off Identity/Meta/logs/argv. httptest emulator enforces Bearer validity (key authenticates only while it exists) so the test proves a real cutover: old dead, new alive, plus a leak check. Recorded MOCK-ONLY in proofs.go + ROTATION-PROOFS.md (no self-host). Note: GitHub PAT is intentionally NOT an API Rotator — GitHub has no create-token API (classic Authorizations API removed 2020; fine-grained PATs are UI-only), so a PAT belongs in the guided/worklist path, not here. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
@@ -68,6 +68,7 @@ stops a mock-only driver from ever being mistaken for a live one.
|
||||
| `gcp` | `httptest` IAM emulator (verifies the driver's RS256 JWT against the key's public key) | no self-host |
|
||||
| `twilio` | `httptest` emulator (Basic-auth Keys resource) | no self-host |
|
||||
| `flyio` | `httptest` GraphQL emulator | no self-host |
|
||||
| `resend` | `httptest` emulator (Bearer `/api-keys` resource) | no self-host |
|
||||
|
||||
## What the MOCK-ONLY emulators actually prove
|
||||
|
||||
@@ -82,10 +83,11 @@ protocol so the test exercises the driver's true cutover logic:
|
||||
on `PUT` **decrypts the sealed value** and stores the plaintext; the test asserts the
|
||||
decrypted value equals the new value the driver put in the rebuilt blob — proving the
|
||||
sealed-box encryption is correct, not simulated.
|
||||
- **npm / twilio** — each emulator enforces credential validity (a token/key
|
||||
- **npm / twilio / resend** — each emulator enforces credential validity (a token/key
|
||||
authenticates only while it exists) and the test asserts `Verify(old)` fails after
|
||||
`RevokeOld` — proving the create→verify→revoke cutover really happened, old credential
|
||||
dead, new one alive.
|
||||
dead, new one alive. (Resend additionally proves `Verify(new)` by listing keys with the
|
||||
new Bearer token and asserting the new id is present — auth success *and* the key exists.)
|
||||
- **gcp** — the emulator **verifies the RS256 JWT signature** the driver mints against the
|
||||
public key recorded for the key's `kid`; it only issues an access token for a JWT that
|
||||
actually verifies, and `DELETE` removes the key — so the test proves real service-account
|
||||
|
||||
@@ -69,6 +69,7 @@ var proofLevels = map[string]ProofLevel{
|
||||
"gcp": ProofMockOnly, // httptest emulator (real RS256 JWT signing); no self-host
|
||||
"twilio": ProofMockOnly, // httptest emulator; no self-host
|
||||
"flyio": ProofMockOnly, // httptest GraphQL emulator; no self-host
|
||||
"resend": ProofMockOnly, // httptest emulator; no self-host (real key needs a paid-ish account)
|
||||
}
|
||||
|
||||
// ProofLevelOf returns the recorded proof level for a driver name. Unknown or
|
||||
|
||||
@@ -0,0 +1,224 @@
|
||||
package rotate
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"incredigo/internal/discover"
|
||||
"incredigo/internal/vault"
|
||||
)
|
||||
|
||||
// Resend rotates a Resend API key (re_...) via the REST API by CREATING a new key,
|
||||
// verifying it, then DELETING the old one — the provider-API rotation pattern
|
||||
// (create-new → verify → revoke-old):
|
||||
//
|
||||
// POST /api-keys (Bearer old-key) -> {id, token}
|
||||
// GET /api-keys (Bearer new-key) -> {data:[{id,...}]} (auth + membership proof)
|
||||
// DELETE /api-keys/<old-id> (Bearer old-key)
|
||||
//
|
||||
// A Resend key authenticates as `Authorization: Bearer re_...`; the token is returned
|
||||
// by Resend only once, at create time, alongside its id. Revoking the OLD key needs
|
||||
// that key's id, so the credential carries it. The credential's secret is a single
|
||||
// self-contained line:
|
||||
//
|
||||
// resend://<host>/?id=<key-id>&secret=<re_token>
|
||||
//
|
||||
// - scheme "resend" maps to https; "http"/"https" are accepted so a test can point
|
||||
// at a loopback emulator.
|
||||
// - <host> API host; "resend" (or empty) defaults to api.resend.com.
|
||||
// - id= the API key id (non-secret) — names the DELETE path for revoke-old.
|
||||
// - secret= the API key token (Bearer credential, rotated).
|
||||
//
|
||||
// SECURITY: the token lives only in the vault blob and the Bearer header; it never
|
||||
// reaches Identity/Meta/logs/argv. The new token is decoded straight from the create
|
||||
// response into the rebuilt blob.
|
||||
type Resend struct {
|
||||
// HTTPClient is injectable for tests / custom TLS. Defaults to a 15s-timeout client.
|
||||
HTTPClient *http.Client
|
||||
}
|
||||
|
||||
// init self-registers the driver. Availability alone changes nothing; the
|
||||
// `rotate --execute` + INCREDIGO_ALLOW_EXECUTE=1 gate still applies.
|
||||
func init() { Register(&Resend{}) }
|
||||
|
||||
// Name identifies the driver in plans and audit records.
|
||||
func (re *Resend) Name() string { return "resend" }
|
||||
|
||||
// Detect claims credentials tagged Source == "resend".
|
||||
func (re *Resend) Detect(c discover.Credential) bool { return c.Source == "resend" }
|
||||
|
||||
func (re *Resend) client() *http.Client {
|
||||
if re.HTTPClient != nil {
|
||||
return re.HTTPClient
|
||||
}
|
||||
return &http.Client{Timeout: 15 * time.Second}
|
||||
}
|
||||
|
||||
// resendSecret is the parsed credential blob. None of its fields are ever logged.
|
||||
type resendSecret struct {
|
||||
base string // scheme://host
|
||||
id string // key id (non-secret)
|
||||
secret string // re_... Bearer token
|
||||
}
|
||||
|
||||
func parseResendSecret(v *vault.Vault, h *vault.Handle) (resendSecret, error) {
|
||||
buf, err := v.Open(h)
|
||||
if err != nil {
|
||||
return resendSecret{}, err
|
||||
}
|
||||
u, err := url.Parse(strings.TrimSpace(string(buf.Bytes())))
|
||||
if err != nil {
|
||||
return resendSecret{}, fmt.Errorf("resend: parse secret url: %w", err)
|
||||
}
|
||||
if u.Scheme != "resend" && u.Scheme != "http" && u.Scheme != "https" {
|
||||
return resendSecret{}, fmt.Errorf("resend: unexpected scheme %q", u.Scheme)
|
||||
}
|
||||
scheme := u.Scheme
|
||||
host := u.Host
|
||||
if scheme == "resend" {
|
||||
scheme = "https"
|
||||
}
|
||||
if host == "" || host == "resend" {
|
||||
host = "api.resend.com"
|
||||
}
|
||||
q := u.Query()
|
||||
s := resendSecret{base: scheme + "://" + host, id: q.Get("id"), secret: q.Get("secret")}
|
||||
if s.secret == "" {
|
||||
return resendSecret{}, fmt.Errorf("resend: secret missing token")
|
||||
}
|
||||
return s, nil
|
||||
}
|
||||
|
||||
// build re-encodes a resendSecret into the single-line blob form (scheme normalised
|
||||
// back to "resend").
|
||||
func (s resendSecret) build() string {
|
||||
host := hostOf(s.base)
|
||||
if host == "api.resend.com" {
|
||||
host = "resend"
|
||||
}
|
||||
u := &url.URL{Scheme: "resend", Host: host, Path: "/"}
|
||||
q := url.Values{}
|
||||
q.Set("id", s.id)
|
||||
q.Set("secret", s.secret)
|
||||
u.RawQuery = q.Encode()
|
||||
return u.String()
|
||||
}
|
||||
|
||||
func (s resendSecret) keysURL(id string) string {
|
||||
base := s.base + "/api-keys"
|
||||
if id != "" {
|
||||
return base + "/" + url.PathEscape(id)
|
||||
}
|
||||
return base
|
||||
}
|
||||
|
||||
// Rotate creates a NEW API key (authenticated by the OLD key) and returns a vault
|
||||
// handle to a rebuilt blob carrying the new id + token. It does not delete the old key.
|
||||
func (re *Resend) Rotate(ctx context.Context, c discover.Credential, v *vault.Vault) (*vault.Handle, error) {
|
||||
s, err := parseResendSecret(v, c.Secret)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
body, err := json.Marshal(map[string]string{"name": "incredigo-rotated", "permission": "full_access"})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPost, s.keysURL(""), bytes.NewReader(body))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
req.Header.Set("Authorization", "Bearer "+s.secret)
|
||||
resp, err := re.client().Do(req)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("resend: create key: %w", err)
|
||||
}
|
||||
defer func() { io.Copy(io.Discard, resp.Body); resp.Body.Close() }()
|
||||
if resp.StatusCode != http.StatusCreated && resp.StatusCode != http.StatusOK {
|
||||
return nil, fmt.Errorf("resend: create key: unexpected status %s", resp.Status)
|
||||
}
|
||||
var created struct {
|
||||
ID string `json:"id"`
|
||||
Token string `json:"token"`
|
||||
}
|
||||
if err := json.NewDecoder(resp.Body).Decode(&created); err != nil {
|
||||
return nil, fmt.Errorf("resend: decode created key: %w", err)
|
||||
}
|
||||
if created.ID == "" || created.Token == "" {
|
||||
return nil, fmt.Errorf("resend: create key: empty id or token in response")
|
||||
}
|
||||
ns := s
|
||||
ns.id = created.ID
|
||||
ns.secret = created.Token
|
||||
return v.Store([]byte(ns.build())), nil
|
||||
}
|
||||
|
||||
// Verify proves the newly minted key authenticates by listing keys with it and
|
||||
// confirming the new id is present (auth success + the key really exists).
|
||||
func (re *Resend) Verify(ctx context.Context, newSecret *vault.Handle, v *vault.Vault) error {
|
||||
s, err := parseResendSecret(v, newSecret)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, s.keysURL(""), nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
req.Header.Set("Authorization", "Bearer "+s.secret)
|
||||
resp, err := re.client().Do(req)
|
||||
if err != nil {
|
||||
return fmt.Errorf("resend verify: %w", err)
|
||||
}
|
||||
defer func() { io.Copy(io.Discard, resp.Body); resp.Body.Close() }()
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return fmt.Errorf("resend verify: list keys status %s", resp.Status)
|
||||
}
|
||||
var got struct {
|
||||
Data []struct {
|
||||
ID string `json:"id"`
|
||||
} `json:"data"`
|
||||
}
|
||||
if err := json.NewDecoder(resp.Body).Decode(&got); err != nil {
|
||||
return fmt.Errorf("resend verify: decode keys: %w", err)
|
||||
}
|
||||
for _, k := range got.Data {
|
||||
if k.ID == s.id {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
return fmt.Errorf("resend verify: new key id not present in account")
|
||||
}
|
||||
|
||||
// RevokeOld deletes the OLD API key by its id. The old key is still valid at this
|
||||
// point (revoke runs only after the new key is stored+verified), so it authenticates
|
||||
// its own deletion.
|
||||
func (re *Resend) RevokeOld(ctx context.Context, c discover.Credential, v *vault.Vault) error {
|
||||
s, err := parseResendSecret(v, c.Secret)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if s.id == "" {
|
||||
return fmt.Errorf("resend revoke: credential has no key id")
|
||||
}
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodDelete, s.keysURL(s.id), nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
req.Header.Set("Authorization", "Bearer "+s.secret)
|
||||
resp, err := re.client().Do(req)
|
||||
if err != nil {
|
||||
return fmt.Errorf("resend revoke: %w", err)
|
||||
}
|
||||
defer func() { io.Copy(io.Discard, resp.Body); resp.Body.Close() }()
|
||||
if resp.StatusCode != http.StatusOK && resp.StatusCode != http.StatusNoContent {
|
||||
return fmt.Errorf("resend revoke: delete key status %s", resp.Status)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,204 @@
|
||||
package rotate
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
|
||||
"incredigo/internal/discover"
|
||||
"incredigo/internal/vault"
|
||||
)
|
||||
|
||||
// resendEmu emulates the Resend /api-keys resource and ENFORCES key validity via the
|
||||
// Bearer token: a key authenticates only while it exists, POST mints a new key, and
|
||||
// DELETE makes a key stop working — so a test can prove a real cutover.
|
||||
type resendEmu struct {
|
||||
mu sync.Mutex
|
||||
secrets map[string]string // id -> token
|
||||
srv *httptest.Server
|
||||
}
|
||||
|
||||
func newResendEmu(t *testing.T, seedID, seedToken string) *resendEmu {
|
||||
e := &resendEmu{secrets: map[string]string{seedID: seedToken}}
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("/api-keys", e.handleCollection)
|
||||
mux.HandleFunc("/api-keys/", e.handleItem)
|
||||
e.srv = httptest.NewTLSServer(mux)
|
||||
t.Cleanup(e.srv.Close)
|
||||
return e
|
||||
}
|
||||
|
||||
// bearer returns the id whose token matches the request's Bearer header, or "".
|
||||
func (e *resendEmu) bearer(r *http.Request) string {
|
||||
tok := strings.TrimPrefix(r.Header.Get("Authorization"), "Bearer ")
|
||||
e.mu.Lock()
|
||||
defer e.mu.Unlock()
|
||||
for id, t := range e.secrets {
|
||||
if t == tok && tok != "" {
|
||||
return id
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func (e *resendEmu) handleCollection(w http.ResponseWriter, r *http.Request) {
|
||||
if e.bearer(r) == "" {
|
||||
w.WriteHeader(http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
switch r.Method {
|
||||
case http.MethodPost:
|
||||
raw := make([]byte, 8)
|
||||
rand.Read(raw)
|
||||
id := "key_" + hex.EncodeToString(raw)
|
||||
tokRaw := make([]byte, 16)
|
||||
rand.Read(tokRaw)
|
||||
token := "re_" + hex.EncodeToString(tokRaw)
|
||||
e.mu.Lock()
|
||||
e.secrets[id] = token
|
||||
e.mu.Unlock()
|
||||
w.WriteHeader(http.StatusCreated)
|
||||
json.NewEncoder(w).Encode(map[string]any{"id": id, "token": token})
|
||||
case http.MethodGet:
|
||||
e.mu.Lock()
|
||||
var data []map[string]any
|
||||
for id := range e.secrets {
|
||||
data = append(data, map[string]any{"id": id, "name": "k"})
|
||||
}
|
||||
e.mu.Unlock()
|
||||
json.NewEncoder(w).Encode(map[string]any{"data": data})
|
||||
default:
|
||||
w.WriteHeader(http.StatusMethodNotAllowed)
|
||||
}
|
||||
}
|
||||
|
||||
func (e *resendEmu) handleItem(w http.ResponseWriter, r *http.Request) {
|
||||
if e.bearer(r) == "" {
|
||||
w.WriteHeader(http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
id := strings.TrimPrefix(r.URL.Path, "/api-keys/")
|
||||
switch r.Method {
|
||||
case http.MethodDelete:
|
||||
e.mu.Lock()
|
||||
delete(e.secrets, id)
|
||||
e.mu.Unlock()
|
||||
w.WriteHeader(http.StatusOK)
|
||||
default:
|
||||
w.WriteHeader(http.StatusMethodNotAllowed)
|
||||
}
|
||||
}
|
||||
|
||||
func (e *resendEmu) valid(token string) bool {
|
||||
e.mu.Lock()
|
||||
defer e.mu.Unlock()
|
||||
for _, t := range e.secrets {
|
||||
if t == token {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func TestResendDetect(t *testing.T) {
|
||||
re := &Resend{}
|
||||
if !re.Detect(discover.Credential{Source: "resend"}) {
|
||||
t.Error("should detect Source=resend")
|
||||
}
|
||||
if re.Detect(discover.Credential{Source: "twilio"}) {
|
||||
t.Error("should not detect Source=twilio")
|
||||
}
|
||||
}
|
||||
|
||||
func TestResendRotateRealCutover(t *testing.T) {
|
||||
v := vault.New()
|
||||
defer v.Purge()
|
||||
ctx := context.Background()
|
||||
|
||||
const seedID, oldToken = "key_seed01234567", "re_old0123456789abcdef"
|
||||
emu := newResendEmu(t, seedID, oldToken)
|
||||
|
||||
host := strings.TrimPrefix(emu.srv.URL, "https://")
|
||||
oldBlob := "resend://" + host + "/?id=" + seedID + "&secret=" + oldToken
|
||||
cred := discover.Credential{
|
||||
Source: "resend",
|
||||
Kind: discover.KindToken,
|
||||
Identity: "resend api key",
|
||||
Location: "imported/resend/labkey",
|
||||
Secret: v.Store([]byte(oldBlob)),
|
||||
}
|
||||
re := &Resend{HTTPClient: emu.srv.Client()}
|
||||
|
||||
if !emu.valid(oldToken) {
|
||||
t.Fatal("seed key should be valid at start")
|
||||
}
|
||||
|
||||
// 1. Rotate.
|
||||
newH, err := re.Rotate(ctx, cred, v)
|
||||
if err != nil {
|
||||
t.Fatalf("Rotate: %v", err)
|
||||
}
|
||||
ns, err := parseResendSecret(v, newH)
|
||||
if err != nil {
|
||||
t.Fatalf("parse new secret: %v", err)
|
||||
}
|
||||
if ns.id == seedID || ns.secret == oldToken {
|
||||
t.Fatal("new key equals old — rotation minted nothing")
|
||||
}
|
||||
if !emu.valid(oldToken) {
|
||||
t.Fatal("old key must remain valid before revoke")
|
||||
}
|
||||
if !emu.valid(ns.secret) {
|
||||
t.Fatal("new key must be valid after create")
|
||||
}
|
||||
|
||||
// 2. Verify(new).
|
||||
if err := re.Verify(ctx, newH, v); err != nil {
|
||||
t.Fatalf("Verify(new): %v", err)
|
||||
}
|
||||
|
||||
// 3. RevokeOld.
|
||||
if err := re.RevokeOld(ctx, cred, v); err != nil {
|
||||
t.Fatalf("RevokeOld: %v", err)
|
||||
}
|
||||
if emu.valid(oldToken) {
|
||||
t.Fatal("old key must be invalid after revoke")
|
||||
}
|
||||
if err := re.Verify(ctx, newH, v); err != nil {
|
||||
t.Fatalf("new key must still authenticate after revoke: %v", err)
|
||||
}
|
||||
|
||||
// Leak check.
|
||||
for _, f := range []string{cred.Identity, cred.Source, cred.Location, string(cred.Kind)} {
|
||||
if strings.Contains(f, oldToken) || strings.Contains(f, ns.secret) {
|
||||
t.Errorf("secret leaked into non-secret field %q", f)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestResendRejectsBadSecret(t *testing.T) {
|
||||
v := vault.New()
|
||||
defer v.Purge()
|
||||
re := &Resend{}
|
||||
// missing token
|
||||
cred := discover.Credential{Source: "resend", Secret: v.Store([]byte("resend://api.resend.com/?id=key_x"))}
|
||||
if _, err := re.Rotate(context.Background(), cred, v); err == nil {
|
||||
t.Error("Rotate should reject a secret with no token")
|
||||
}
|
||||
}
|
||||
|
||||
func TestResendRevokeNeedsID(t *testing.T) {
|
||||
v := vault.New()
|
||||
defer v.Purge()
|
||||
re := &Resend{}
|
||||
cred := discover.Credential{Source: "resend", Secret: v.Store([]byte("resend://api.resend.com/?secret=re_x"))}
|
||||
if err := re.RevokeOld(context.Background(), cred, v); err == nil {
|
||||
t.Error("RevokeOld should fail when the credential carries no key id")
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user