rotate: Vercel token + SendGrid API-key drivers (create→verify→revoke)
Two more provider-API rotation drivers for the vibe-coder credential surface, both following the create-new → verify → revoke-old pattern with the self-contained blob form <provider>://<host>/?id=&secret=. - vercel: POST /v3/user/tokens mints a new bearer; Verify lists tokens and asserts the new id is present; RevokeOld DELETEs the old token by id. - sendgrid: clones the old key's scopes (GET /v3/api_keys/<id>) onto the new key so rotation is a faithful replacement, not a privilege downgrade; Verify is a GET /v3/scopes auth proof; RevokeOld DELETEs the old key by id. Both ship Bearer-enforcing httptest emulators that prove a real cutover (old credential dead, new alive after RevokeOld) plus a leak check. Recorded as MOCK-ONLY in proofs.go + docs/ROTATION-PROOFS.md (no self-host). go build/vet clean; 77 rotate tests pass, -race clean. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
+14
-5
@@ -69,6 +69,8 @@ stops a mock-only driver from ever being mistaken for a live one.
|
||||
| `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 |
|
||||
| `vercel` | `httptest` emulator (Bearer `/v3/user/tokens` resource) | no self-host |
|
||||
| `sendgrid` | `httptest` emulator (Bearer `/v3/api_keys` resource, scope clone + `/v3/scopes` auth proof) | no self-host |
|
||||
|
||||
## What the MOCK-ONLY emulators actually prove
|
||||
|
||||
@@ -83,11 +85,18 @@ 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 / 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. (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.)
|
||||
- **npm / twilio / resend / vercel** — each emulator enforces credential validity (a
|
||||
token/key authenticates only while it exists) and the test asserts the old credential is
|
||||
dead after `RevokeOld` while the new one still authenticates — proving the
|
||||
create→verify→revoke cutover really happened. (Resend and Vercel additionally prove
|
||||
`Verify(new)` by listing keys/tokens with the new Bearer token and asserting the new id
|
||||
is present — auth success *and* the credential exists.)
|
||||
- **sendgrid** — the emulator enforces Bearer validity *and* records each key's scopes; the
|
||||
driver clones the old key's scopes onto the new one (`GET /v3/api_keys/<id>` → reuse on
|
||||
`POST /v3/api_keys`) so rotation is a faithful replacement, not a privilege downgrade. The
|
||||
test asserts the minted key carries the seeded scopes, that `Verify(new)` (a `GET /v3/scopes`
|
||||
auth proof) succeeds, and that the old key stops authenticating after `RevokeOld` while the
|
||||
new key still does — old key dead, new one alive with the same scopes.
|
||||
- **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
|
||||
|
||||
@@ -70,6 +70,8 @@ var proofLevels = map[string]ProofLevel{
|
||||
"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)
|
||||
"vercel": ProofMockOnly, // httptest emulator; no self-host
|
||||
"sendgrid": ProofMockOnly, // httptest emulator; no self-host
|
||||
}
|
||||
|
||||
// ProofLevelOf returns the recorded proof level for a driver name. Unknown or
|
||||
|
||||
@@ -0,0 +1,247 @@
|
||||
package rotate
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"incredigo/internal/discover"
|
||||
"incredigo/internal/vault"
|
||||
)
|
||||
|
||||
// SendGrid rotates a SendGrid API key via the REST API by CREATING a new key with the
|
||||
// SAME scopes as the old one, verifying it, then DELETING the old one — the provider-API
|
||||
// rotation pattern (create-new → verify → revoke-old):
|
||||
//
|
||||
// GET /v3/api_keys/<old-id> (Bearer old-key) -> {scopes:[…]} (clone scopes)
|
||||
// POST /v3/api_keys (Bearer old-key) -> {api_key, api_key_id}
|
||||
// GET /v3/scopes (Bearer new-key) -> {scopes:[…]} (auth proof)
|
||||
// DELETE /v3/api_keys/<old-id> (Bearer old-key)
|
||||
//
|
||||
// SendGrid returns the api_key secret only once, at create time, alongside its
|
||||
// api_key_id; revoking the OLD key needs that id, so the credential carries it. The
|
||||
// new key is created with the old key's scopes so the rotation is a faithful
|
||||
// replacement, not a privilege downgrade. The credential's secret is a single
|
||||
// self-contained line:
|
||||
//
|
||||
// sendgrid://<host>/?id=<api-key-id>&secret=<SG.token>
|
||||
//
|
||||
// - scheme "sendgrid" maps to https; "http"/"https" are accepted so a test can point
|
||||
// at a loopback emulator.
|
||||
// - <host> API host; "sendgrid" (or empty) defaults to api.sendgrid.com.
|
||||
// - id= the api_key_id (non-secret) — names the GET/DELETE paths.
|
||||
// - 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 SendGrid 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(&SendGrid{}) }
|
||||
|
||||
// Name identifies the driver in plans and audit records.
|
||||
func (sg *SendGrid) Name() string { return "sendgrid" }
|
||||
|
||||
// Detect claims credentials tagged Source == "sendgrid".
|
||||
func (sg *SendGrid) Detect(c discover.Credential) bool { return c.Source == "sendgrid" }
|
||||
|
||||
func (sg *SendGrid) client() *http.Client {
|
||||
if sg.HTTPClient != nil {
|
||||
return sg.HTTPClient
|
||||
}
|
||||
return &http.Client{Timeout: 15 * time.Second}
|
||||
}
|
||||
|
||||
// sendgridSecret is the parsed credential blob. None of its fields are ever logged.
|
||||
type sendgridSecret struct {
|
||||
base string // scheme://host
|
||||
id string // api_key_id (non-secret)
|
||||
secret string // SG.* Bearer token
|
||||
}
|
||||
|
||||
func parseSendGridSecret(v *vault.Vault, h *vault.Handle) (sendgridSecret, error) {
|
||||
buf, err := v.Open(h)
|
||||
if err != nil {
|
||||
return sendgridSecret{}, err
|
||||
}
|
||||
u, err := url.Parse(strings.TrimSpace(string(buf.Bytes())))
|
||||
if err != nil {
|
||||
return sendgridSecret{}, fmt.Errorf("sendgrid: parse secret url: %w", err)
|
||||
}
|
||||
if u.Scheme != "sendgrid" && u.Scheme != "http" && u.Scheme != "https" {
|
||||
return sendgridSecret{}, fmt.Errorf("sendgrid: unexpected scheme %q", u.Scheme)
|
||||
}
|
||||
scheme := u.Scheme
|
||||
host := u.Host
|
||||
if scheme == "sendgrid" {
|
||||
scheme = "https"
|
||||
}
|
||||
if host == "" || host == "sendgrid" {
|
||||
host = "api.sendgrid.com"
|
||||
}
|
||||
q := u.Query()
|
||||
s := sendgridSecret{base: scheme + "://" + host, id: q.Get("id"), secret: q.Get("secret")}
|
||||
if s.secret == "" {
|
||||
return sendgridSecret{}, fmt.Errorf("sendgrid: secret missing token")
|
||||
}
|
||||
return s, nil
|
||||
}
|
||||
|
||||
// build re-encodes a sendgridSecret into the single-line blob form (scheme normalised
|
||||
// back to "sendgrid").
|
||||
func (s sendgridSecret) build() string {
|
||||
host := hostOf(s.base)
|
||||
if host == "api.sendgrid.com" {
|
||||
host = "sendgrid"
|
||||
}
|
||||
u := &url.URL{Scheme: "sendgrid", 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 sendgridSecret) keysURL(id string) string {
|
||||
base := s.base + "/v3/api_keys"
|
||||
if id != "" {
|
||||
return base + "/" + url.PathEscape(id)
|
||||
}
|
||||
return base
|
||||
}
|
||||
|
||||
// oldScopes reads the scopes of the existing key so the new key can clone them. A
|
||||
// failure here is non-fatal: rotation proceeds with no explicit scopes rather than
|
||||
// blocking (SendGrid then mints a key with the account-default scope set).
|
||||
func (sg *SendGrid) oldScopes(ctx context.Context, s sendgridSecret) []string {
|
||||
if s.id == "" {
|
||||
return nil
|
||||
}
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, s.keysURL(s.id), nil)
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
req.Header.Set("Authorization", "Bearer "+s.secret)
|
||||
resp, err := sg.client().Do(req)
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
defer func() { io.Copy(io.Discard, resp.Body); resp.Body.Close() }()
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return nil
|
||||
}
|
||||
var got struct {
|
||||
Scopes []string `json:"scopes"`
|
||||
}
|
||||
if err := json.NewDecoder(resp.Body).Decode(&got); err != nil {
|
||||
return nil
|
||||
}
|
||||
return got.Scopes
|
||||
}
|
||||
|
||||
// Rotate creates a NEW API key (authenticated by the OLD key) carrying the old key's
|
||||
// scopes, and returns a vault handle to a rebuilt blob with the new id + token. It does
|
||||
// not delete the old key.
|
||||
func (sg *SendGrid) Rotate(ctx context.Context, c discover.Credential, v *vault.Vault) (*vault.Handle, error) {
|
||||
s, err := parseSendGridSecret(v, c.Secret)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
payload := map[string]any{"name": "incredigo-rotated"}
|
||||
if scopes := sg.oldScopes(ctx, s); len(scopes) > 0 {
|
||||
payload["scopes"] = scopes
|
||||
}
|
||||
body, err := json.Marshal(payload)
|
||||
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 := sg.client().Do(req)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("sendgrid: 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("sendgrid: create key: unexpected status %s", resp.Status)
|
||||
}
|
||||
var created struct {
|
||||
APIKey string `json:"api_key"`
|
||||
APIKeyID string `json:"api_key_id"`
|
||||
}
|
||||
if err := json.NewDecoder(resp.Body).Decode(&created); err != nil {
|
||||
return nil, fmt.Errorf("sendgrid: decode created key: %w", err)
|
||||
}
|
||||
if created.APIKey == "" || created.APIKeyID == "" {
|
||||
return nil, fmt.Errorf("sendgrid: create key: empty api_key or api_key_id in response")
|
||||
}
|
||||
ns := s
|
||||
ns.id = created.APIKeyID
|
||||
ns.secret = created.APIKey
|
||||
return v.Store([]byte(ns.build())), nil
|
||||
}
|
||||
|
||||
// Verify proves the newly minted key authenticates by GETting /v3/scopes with it (the
|
||||
// scopes endpoint succeeds for any valid key regardless of its permission set).
|
||||
func (sg *SendGrid) Verify(ctx context.Context, newSecret *vault.Handle, v *vault.Vault) error {
|
||||
s, err := parseSendGridSecret(v, newSecret)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, s.base+"/v3/scopes", nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
req.Header.Set("Authorization", "Bearer "+s.secret)
|
||||
resp, err := sg.client().Do(req)
|
||||
if err != nil {
|
||||
return fmt.Errorf("sendgrid verify: %w", err)
|
||||
}
|
||||
defer func() { io.Copy(io.Discard, resp.Body); resp.Body.Close() }()
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return fmt.Errorf("sendgrid verify: get scopes status %s", resp.Status)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// 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 (sg *SendGrid) RevokeOld(ctx context.Context, c discover.Credential, v *vault.Vault) error {
|
||||
s, err := parseSendGridSecret(v, c.Secret)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if s.id == "" {
|
||||
return fmt.Errorf("sendgrid revoke: credential has no api_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 := sg.client().Do(req)
|
||||
if err != nil {
|
||||
return fmt.Errorf("sendgrid 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("sendgrid revoke: delete key status %s", resp.Status)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,249 @@
|
||||
package rotate
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
|
||||
"incredigo/internal/discover"
|
||||
"incredigo/internal/vault"
|
||||
)
|
||||
|
||||
// sendgridEmu emulates the SendGrid /v3/api_keys resource and ENFORCES key validity
|
||||
// via the Bearer token: a key authenticates only while it exists, POST mints a new key
|
||||
// (cloning whatever scopes were requested), GET /v3/api_keys/<id> returns a key's
|
||||
// scopes, GET /v3/scopes proves auth, and DELETE makes a key stop working — so a test
|
||||
// can prove a real cutover.
|
||||
type sendgridEmu struct {
|
||||
mu sync.Mutex
|
||||
secrets map[string]string // id -> token
|
||||
scopes map[string][]string // id -> scopes
|
||||
srv *httptest.Server
|
||||
}
|
||||
|
||||
func newSendGridEmu(t *testing.T, seedID, seedToken string, seedScopes []string) *sendgridEmu {
|
||||
e := &sendgridEmu{
|
||||
secrets: map[string]string{seedID: seedToken},
|
||||
scopes: map[string][]string{seedID: seedScopes},
|
||||
}
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("/v3/api_keys", e.handleCollection)
|
||||
mux.HandleFunc("/v3/api_keys/", e.handleItem)
|
||||
mux.HandleFunc("/v3/scopes", e.handleScopes)
|
||||
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 *sendgridEmu) 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 *sendgridEmu) handleCollection(w http.ResponseWriter, r *http.Request) {
|
||||
if e.bearer(r) == "" {
|
||||
w.WriteHeader(http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
switch r.Method {
|
||||
case http.MethodPost:
|
||||
var in struct {
|
||||
Name string `json:"name"`
|
||||
Scopes []string `json:"scopes"`
|
||||
}
|
||||
json.NewDecoder(r.Body).Decode(&in)
|
||||
raw := make([]byte, 8)
|
||||
rand.Read(raw)
|
||||
id := "sgid_" + hex.EncodeToString(raw)
|
||||
tokRaw := make([]byte, 16)
|
||||
rand.Read(tokRaw)
|
||||
token := "SG." + hex.EncodeToString(tokRaw)
|
||||
e.mu.Lock()
|
||||
e.secrets[id] = token
|
||||
e.scopes[id] = in.Scopes
|
||||
e.mu.Unlock()
|
||||
w.WriteHeader(http.StatusCreated)
|
||||
json.NewEncoder(w).Encode(map[string]any{"api_key": token, "api_key_id": id, "name": in.Name, "scopes": in.Scopes})
|
||||
default:
|
||||
w.WriteHeader(http.StatusMethodNotAllowed)
|
||||
}
|
||||
}
|
||||
|
||||
func (e *sendgridEmu) handleItem(w http.ResponseWriter, r *http.Request) {
|
||||
if e.bearer(r) == "" {
|
||||
w.WriteHeader(http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
id := strings.TrimPrefix(r.URL.Path, "/v3/api_keys/")
|
||||
switch r.Method {
|
||||
case http.MethodGet:
|
||||
e.mu.Lock()
|
||||
sc, ok := e.scopes[id]
|
||||
e.mu.Unlock()
|
||||
if !ok {
|
||||
w.WriteHeader(http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
json.NewEncoder(w).Encode(map[string]any{"api_key_id": id, "scopes": sc})
|
||||
case http.MethodDelete:
|
||||
e.mu.Lock()
|
||||
delete(e.secrets, id)
|
||||
delete(e.scopes, id)
|
||||
e.mu.Unlock()
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
default:
|
||||
w.WriteHeader(http.StatusMethodNotAllowed)
|
||||
}
|
||||
}
|
||||
|
||||
// handleScopes is the auth proof endpoint: any valid key gets 200 + its scope list.
|
||||
func (e *sendgridEmu) handleScopes(w http.ResponseWriter, r *http.Request) {
|
||||
id := e.bearer(r)
|
||||
if id == "" {
|
||||
w.WriteHeader(http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
e.mu.Lock()
|
||||
sc := e.scopes[id]
|
||||
e.mu.Unlock()
|
||||
json.NewEncoder(w).Encode(map[string]any{"scopes": sc})
|
||||
}
|
||||
|
||||
func (e *sendgridEmu) valid(token string) bool {
|
||||
e.mu.Lock()
|
||||
defer e.mu.Unlock()
|
||||
for _, t := range e.secrets {
|
||||
if t == token {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func (e *sendgridEmu) scopesOf(token string) []string {
|
||||
e.mu.Lock()
|
||||
defer e.mu.Unlock()
|
||||
for id, t := range e.secrets {
|
||||
if t == token {
|
||||
return e.scopes[id]
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func TestSendGridDetect(t *testing.T) {
|
||||
sg := &SendGrid{}
|
||||
if !sg.Detect(discover.Credential{Source: "sendgrid"}) {
|
||||
t.Error("should detect Source=sendgrid")
|
||||
}
|
||||
if sg.Detect(discover.Credential{Source: "resend"}) {
|
||||
t.Error("should not detect Source=resend")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSendGridRotateRealCutover(t *testing.T) {
|
||||
v := vault.New()
|
||||
defer v.Purge()
|
||||
ctx := context.Background()
|
||||
|
||||
const seedID, oldToken = "sgid_seed01234567", "SG.old0123456789abcdef"
|
||||
wantScopes := []string{"mail.send", "templates.read"}
|
||||
emu := newSendGridEmu(t, seedID, oldToken, wantScopes)
|
||||
|
||||
host := strings.TrimPrefix(emu.srv.URL, "https://")
|
||||
oldBlob := "sendgrid://" + host + "/?id=" + seedID + "&secret=" + oldToken
|
||||
cred := discover.Credential{
|
||||
Source: "sendgrid",
|
||||
Kind: discover.KindToken,
|
||||
Identity: "sendgrid api key",
|
||||
Location: "imported/sendgrid/labkey",
|
||||
Secret: v.Store([]byte(oldBlob)),
|
||||
}
|
||||
sg := &SendGrid{HTTPClient: emu.srv.Client()}
|
||||
|
||||
if !emu.valid(oldToken) {
|
||||
t.Fatal("seed key should be valid at start")
|
||||
}
|
||||
|
||||
// 1. Rotate.
|
||||
newH, err := sg.Rotate(ctx, cred, v)
|
||||
if err != nil {
|
||||
t.Fatalf("Rotate: %v", err)
|
||||
}
|
||||
ns, err := parseSendGridSecret(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")
|
||||
}
|
||||
// The new key must clone the old key's scopes (faithful replacement, not a downgrade).
|
||||
gotScopes := emu.scopesOf(ns.secret)
|
||||
if strings.Join(gotScopes, ",") != strings.Join(wantScopes, ",") {
|
||||
t.Errorf("new key scopes = %v, want cloned %v", gotScopes, wantScopes)
|
||||
}
|
||||
|
||||
// 2. Verify(new).
|
||||
if err := sg.Verify(ctx, newH, v); err != nil {
|
||||
t.Fatalf("Verify(new): %v", err)
|
||||
}
|
||||
|
||||
// 3. RevokeOld.
|
||||
if err := sg.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 := sg.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 TestSendGridRejectsBadSecret(t *testing.T) {
|
||||
v := vault.New()
|
||||
defer v.Purge()
|
||||
sg := &SendGrid{}
|
||||
// missing token
|
||||
cred := discover.Credential{Source: "sendgrid", Secret: v.Store([]byte("sendgrid://api.sendgrid.com/?id=sgid_x"))}
|
||||
if _, err := sg.Rotate(context.Background(), cred, v); err == nil {
|
||||
t.Error("Rotate should reject a secret with no token")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSendGridRevokeNeedsID(t *testing.T) {
|
||||
v := vault.New()
|
||||
defer v.Purge()
|
||||
sg := &SendGrid{}
|
||||
cred := discover.Credential{Source: "sendgrid", Secret: v.Store([]byte("sendgrid://api.sendgrid.com/?secret=SG.x"))}
|
||||
if err := sg.RevokeOld(context.Background(), cred, v); err == nil {
|
||||
t.Error("RevokeOld should fail when the credential carries no api_key_id")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,225 @@
|
||||
package rotate
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"incredigo/internal/discover"
|
||||
"incredigo/internal/vault"
|
||||
)
|
||||
|
||||
// Vercel rotates a Vercel access token via the REST API by CREATING a new token,
|
||||
// verifying it, then DELETING the old one — the provider-API rotation pattern
|
||||
// (create-new → verify → revoke-old):
|
||||
//
|
||||
// POST /v3/user/tokens (Bearer old-token) -> {token:{id}, bearerToken}
|
||||
// GET /v3/user/tokens (Bearer new-token) -> {tokens:[{id,...}]} (auth + membership)
|
||||
// DELETE /v3/user/tokens/<old-id> (Bearer old-token)
|
||||
//
|
||||
// Vercel returns the bearer secret only once, at create time, alongside the token's id;
|
||||
// revoking the OLD token needs that id, so the credential carries it. The credential's
|
||||
// secret is a single self-contained line:
|
||||
//
|
||||
// vercel://<host>/?id=<token-id>&secret=<bearer>
|
||||
//
|
||||
// - scheme "vercel" maps to https; "http"/"https" are accepted so a test can point
|
||||
// at a loopback emulator.
|
||||
// - <host> API host; "vercel" (or empty) defaults to api.vercel.com.
|
||||
// - id= the token id (non-secret) — names the DELETE path for revoke-old.
|
||||
// - secret= the bearer token (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 Vercel 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(&Vercel{}) }
|
||||
|
||||
// Name identifies the driver in plans and audit records.
|
||||
func (ve *Vercel) Name() string { return "vercel" }
|
||||
|
||||
// Detect claims credentials tagged Source == "vercel".
|
||||
func (ve *Vercel) Detect(c discover.Credential) bool { return c.Source == "vercel" }
|
||||
|
||||
func (ve *Vercel) client() *http.Client {
|
||||
if ve.HTTPClient != nil {
|
||||
return ve.HTTPClient
|
||||
}
|
||||
return &http.Client{Timeout: 15 * time.Second}
|
||||
}
|
||||
|
||||
// vercelSecret is the parsed credential blob. None of its fields are ever logged.
|
||||
type vercelSecret struct {
|
||||
base string // scheme://host
|
||||
id string // token id (non-secret)
|
||||
secret string // bearer token
|
||||
}
|
||||
|
||||
func parseVercelSecret(v *vault.Vault, h *vault.Handle) (vercelSecret, error) {
|
||||
buf, err := v.Open(h)
|
||||
if err != nil {
|
||||
return vercelSecret{}, err
|
||||
}
|
||||
u, err := url.Parse(strings.TrimSpace(string(buf.Bytes())))
|
||||
if err != nil {
|
||||
return vercelSecret{}, fmt.Errorf("vercel: parse secret url: %w", err)
|
||||
}
|
||||
if u.Scheme != "vercel" && u.Scheme != "http" && u.Scheme != "https" {
|
||||
return vercelSecret{}, fmt.Errorf("vercel: unexpected scheme %q", u.Scheme)
|
||||
}
|
||||
scheme := u.Scheme
|
||||
host := u.Host
|
||||
if scheme == "vercel" {
|
||||
scheme = "https"
|
||||
}
|
||||
if host == "" || host == "vercel" {
|
||||
host = "api.vercel.com"
|
||||
}
|
||||
q := u.Query()
|
||||
s := vercelSecret{base: scheme + "://" + host, id: q.Get("id"), secret: q.Get("secret")}
|
||||
if s.secret == "" {
|
||||
return vercelSecret{}, fmt.Errorf("vercel: secret missing bearer token")
|
||||
}
|
||||
return s, nil
|
||||
}
|
||||
|
||||
// build re-encodes a vercelSecret into the single-line blob form (scheme normalised
|
||||
// back to "vercel").
|
||||
func (s vercelSecret) build() string {
|
||||
host := hostOf(s.base)
|
||||
if host == "api.vercel.com" {
|
||||
host = "vercel"
|
||||
}
|
||||
u := &url.URL{Scheme: "vercel", 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 vercelSecret) tokensURL(id string) string {
|
||||
base := s.base + "/v3/user/tokens"
|
||||
if id != "" {
|
||||
return base + "/" + url.PathEscape(id)
|
||||
}
|
||||
return base
|
||||
}
|
||||
|
||||
// Rotate creates a NEW access token (authenticated by the OLD token) and returns a
|
||||
// vault handle to a rebuilt blob carrying the new id + token. It does not delete the old.
|
||||
func (ve *Vercel) Rotate(ctx context.Context, c discover.Credential, v *vault.Vault) (*vault.Handle, error) {
|
||||
s, err := parseVercelSecret(v, c.Secret)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
body, err := json.Marshal(map[string]string{"name": "incredigo-rotated"})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPost, s.tokensURL(""), 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 := ve.client().Do(req)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("vercel: create token: %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("vercel: create token: unexpected status %s", resp.Status)
|
||||
}
|
||||
var created struct {
|
||||
Token struct {
|
||||
ID string `json:"id"`
|
||||
} `json:"token"`
|
||||
BearerToken string `json:"bearerToken"`
|
||||
}
|
||||
if err := json.NewDecoder(resp.Body).Decode(&created); err != nil {
|
||||
return nil, fmt.Errorf("vercel: decode created token: %w", err)
|
||||
}
|
||||
if created.Token.ID == "" || created.BearerToken == "" {
|
||||
return nil, fmt.Errorf("vercel: create token: empty id or bearerToken in response")
|
||||
}
|
||||
ns := s
|
||||
ns.id = created.Token.ID
|
||||
ns.secret = created.BearerToken
|
||||
return v.Store([]byte(ns.build())), nil
|
||||
}
|
||||
|
||||
// Verify proves the newly minted token authenticates by listing tokens with it and
|
||||
// confirming the new id is present (auth success + the token really exists).
|
||||
func (ve *Vercel) Verify(ctx context.Context, newSecret *vault.Handle, v *vault.Vault) error {
|
||||
s, err := parseVercelSecret(v, newSecret)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, s.tokensURL(""), nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
req.Header.Set("Authorization", "Bearer "+s.secret)
|
||||
resp, err := ve.client().Do(req)
|
||||
if err != nil {
|
||||
return fmt.Errorf("vercel verify: %w", err)
|
||||
}
|
||||
defer func() { io.Copy(io.Discard, resp.Body); resp.Body.Close() }()
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return fmt.Errorf("vercel verify: list tokens status %s", resp.Status)
|
||||
}
|
||||
var got struct {
|
||||
Tokens []struct {
|
||||
ID string `json:"id"`
|
||||
} `json:"tokens"`
|
||||
}
|
||||
if err := json.NewDecoder(resp.Body).Decode(&got); err != nil {
|
||||
return fmt.Errorf("vercel verify: decode tokens: %w", err)
|
||||
}
|
||||
for _, tkn := range got.Tokens {
|
||||
if tkn.ID == s.id {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
return fmt.Errorf("vercel verify: new token id not present in account")
|
||||
}
|
||||
|
||||
// RevokeOld deletes the OLD access token by its id. The old token is still valid at
|
||||
// this point (revoke runs only after the new token is stored+verified), so it
|
||||
// authenticates its own deletion.
|
||||
func (ve *Vercel) RevokeOld(ctx context.Context, c discover.Credential, v *vault.Vault) error {
|
||||
s, err := parseVercelSecret(v, c.Secret)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if s.id == "" {
|
||||
return fmt.Errorf("vercel revoke: credential has no token id")
|
||||
}
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodDelete, s.tokensURL(s.id), nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
req.Header.Set("Authorization", "Bearer "+s.secret)
|
||||
resp, err := ve.client().Do(req)
|
||||
if err != nil {
|
||||
return fmt.Errorf("vercel 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("vercel revoke: delete token status %s", resp.Status)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,199 @@
|
||||
package rotate
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
|
||||
"incredigo/internal/discover"
|
||||
"incredigo/internal/vault"
|
||||
)
|
||||
|
||||
// vercelEmu emulates the Vercel /v3/user/tokens resource and ENFORCES token validity
|
||||
// via the Bearer header: a token authenticates only while it exists, POST mints a new
|
||||
// one, DELETE makes a token stop working — so a test can prove a real cutover.
|
||||
type vercelEmu struct {
|
||||
mu sync.Mutex
|
||||
secrets map[string]string // id -> bearer
|
||||
srv *httptest.Server
|
||||
}
|
||||
|
||||
func newVercelEmu(t *testing.T, seedID, seedToken string) *vercelEmu {
|
||||
e := &vercelEmu{secrets: map[string]string{seedID: seedToken}}
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("/v3/user/tokens", e.handleCollection)
|
||||
mux.HandleFunc("/v3/user/tokens/", e.handleItem)
|
||||
e.srv = httptest.NewTLSServer(mux)
|
||||
t.Cleanup(e.srv.Close)
|
||||
return e
|
||||
}
|
||||
|
||||
func (e *vercelEmu) authed(r *http.Request) bool {
|
||||
tok := strings.TrimPrefix(r.Header.Get("Authorization"), "Bearer ")
|
||||
e.mu.Lock()
|
||||
defer e.mu.Unlock()
|
||||
for _, t := range e.secrets {
|
||||
if t == tok && tok != "" {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func (e *vercelEmu) handleCollection(w http.ResponseWriter, r *http.Request) {
|
||||
if !e.authed(r) {
|
||||
w.WriteHeader(http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
switch r.Method {
|
||||
case http.MethodPost:
|
||||
raw := make([]byte, 8)
|
||||
rand.Read(raw)
|
||||
id := "tok_" + hex.EncodeToString(raw)
|
||||
bRaw := make([]byte, 16)
|
||||
rand.Read(bRaw)
|
||||
bearer := hex.EncodeToString(bRaw)
|
||||
e.mu.Lock()
|
||||
e.secrets[id] = bearer
|
||||
e.mu.Unlock()
|
||||
w.WriteHeader(http.StatusOK)
|
||||
json.NewEncoder(w).Encode(map[string]any{"token": map[string]any{"id": id, "name": "incredigo-rotated"}, "bearerToken": bearer})
|
||||
case http.MethodGet:
|
||||
e.mu.Lock()
|
||||
var toks []map[string]any
|
||||
for id := range e.secrets {
|
||||
toks = append(toks, map[string]any{"id": id, "name": "t"})
|
||||
}
|
||||
e.mu.Unlock()
|
||||
json.NewEncoder(w).Encode(map[string]any{"tokens": toks})
|
||||
default:
|
||||
w.WriteHeader(http.StatusMethodNotAllowed)
|
||||
}
|
||||
}
|
||||
|
||||
func (e *vercelEmu) handleItem(w http.ResponseWriter, r *http.Request) {
|
||||
if !e.authed(r) {
|
||||
w.WriteHeader(http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
id := strings.TrimPrefix(r.URL.Path, "/v3/user/tokens/")
|
||||
switch r.Method {
|
||||
case http.MethodDelete:
|
||||
e.mu.Lock()
|
||||
delete(e.secrets, id)
|
||||
e.mu.Unlock()
|
||||
w.WriteHeader(http.StatusOK)
|
||||
json.NewEncoder(w).Encode(map[string]any{"tokenId": id})
|
||||
default:
|
||||
w.WriteHeader(http.StatusMethodNotAllowed)
|
||||
}
|
||||
}
|
||||
|
||||
func (e *vercelEmu) valid(token string) bool {
|
||||
e.mu.Lock()
|
||||
defer e.mu.Unlock()
|
||||
for _, t := range e.secrets {
|
||||
if t == token {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func TestVercelDetect(t *testing.T) {
|
||||
ve := &Vercel{}
|
||||
if !ve.Detect(discover.Credential{Source: "vercel"}) {
|
||||
t.Error("should detect Source=vercel")
|
||||
}
|
||||
if ve.Detect(discover.Credential{Source: "resend"}) {
|
||||
t.Error("should not detect Source=resend")
|
||||
}
|
||||
}
|
||||
|
||||
func TestVercelRotateRealCutover(t *testing.T) {
|
||||
v := vault.New()
|
||||
defer v.Purge()
|
||||
ctx := context.Background()
|
||||
|
||||
const seedID, oldToken = "tok_seed01234567", "oldbearer0123456789abcdef"
|
||||
emu := newVercelEmu(t, seedID, oldToken)
|
||||
|
||||
host := strings.TrimPrefix(emu.srv.URL, "https://")
|
||||
oldBlob := "vercel://" + host + "/?id=" + seedID + "&secret=" + oldToken
|
||||
cred := discover.Credential{
|
||||
Source: "vercel",
|
||||
Kind: discover.KindToken,
|
||||
Identity: "vercel access token",
|
||||
Location: "imported/vercel/labtoken",
|
||||
Secret: v.Store([]byte(oldBlob)),
|
||||
}
|
||||
ve := &Vercel{HTTPClient: emu.srv.Client()}
|
||||
|
||||
if !emu.valid(oldToken) {
|
||||
t.Fatal("seed token should be valid at start")
|
||||
}
|
||||
|
||||
newH, err := ve.Rotate(ctx, cred, v)
|
||||
if err != nil {
|
||||
t.Fatalf("Rotate: %v", err)
|
||||
}
|
||||
ns, err := parseVercelSecret(v, newH)
|
||||
if err != nil {
|
||||
t.Fatalf("parse new secret: %v", err)
|
||||
}
|
||||
if ns.id == seedID || ns.secret == oldToken {
|
||||
t.Fatal("new token equals old — rotation minted nothing")
|
||||
}
|
||||
if !emu.valid(oldToken) {
|
||||
t.Fatal("old token must remain valid before revoke")
|
||||
}
|
||||
if !emu.valid(ns.secret) {
|
||||
t.Fatal("new token must be valid after create")
|
||||
}
|
||||
|
||||
if err := ve.Verify(ctx, newH, v); err != nil {
|
||||
t.Fatalf("Verify(new): %v", err)
|
||||
}
|
||||
|
||||
if err := ve.RevokeOld(ctx, cred, v); err != nil {
|
||||
t.Fatalf("RevokeOld: %v", err)
|
||||
}
|
||||
if emu.valid(oldToken) {
|
||||
t.Fatal("old token must be invalid after revoke")
|
||||
}
|
||||
if err := ve.Verify(ctx, newH, v); err != nil {
|
||||
t.Fatalf("new token must still authenticate after revoke: %v", err)
|
||||
}
|
||||
|
||||
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 TestVercelRejectsBadSecret(t *testing.T) {
|
||||
v := vault.New()
|
||||
defer v.Purge()
|
||||
ve := &Vercel{}
|
||||
cred := discover.Credential{Source: "vercel", Secret: v.Store([]byte("vercel://api.vercel.com/?id=tok_x"))}
|
||||
if _, err := ve.Rotate(context.Background(), cred, v); err == nil {
|
||||
t.Error("Rotate should reject a secret with no bearer token")
|
||||
}
|
||||
}
|
||||
|
||||
func TestVercelRevokeNeedsID(t *testing.T) {
|
||||
v := vault.New()
|
||||
defer v.Purge()
|
||||
ve := &Vercel{}
|
||||
cred := discover.Credential{Source: "vercel", Secret: v.Store([]byte("vercel://api.vercel.com/?secret=abc"))}
|
||||
if err := ve.RevokeOld(context.Background(), cred, v); err == nil {
|
||||
t.Error("RevokeOld should fail when the credential carries no token id")
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user