rotate: 6 service-API drivers (mongo, npm, gcp, twilio, flyio, k8s)

Each driver is real-service code only (no test awareness; tests inject just an
HTTPClient/Bin), following the established patterns:

- mongo: in-place changeUserPassword over the old connection; no secret on argv
  (host/db on the URI, both passwords on stdin, output scrubbed).
- npm:   create token -> /-/whoami -> delete-by-key; blob records the key.
- gcp:   service-account KEY rotation; mints an RS256 JWT signed with the SA's
  own private key (crypto/rsa, stdlib) to self-auth the IAM create/verify/delete.
- twilio: API Key create -> get -> delete, Basic auth (KeySid/secret).
- flyio: GraphQL — a managing token mints/deletes the rotated deploy token.
- k8s:   create a service-account-token Secret, await the populated token,
  verify against the SA, delete the old Secret (invalidates the old token).

All 6 register their honest proof level (MOCK-ONLY) in proofs.go +
ROTATION-PROOFS.md; mongo/npm/k8s are LIVE-VM candidates pending real-target VM
POCs. Emulators enforce credential validity (gcp verifies the JWT signature),
tests assert Verify(old) fails after revoke + a secret-leak canary.

Full suite: 103 green, -race clean on rotate/sink/vault.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
leetcrypt
2026-06-18 15:57:59 -07:00
parent b415c43bff
commit 35f19c007a
15 changed files with 2776 additions and 2 deletions
+35
View File
@@ -264,6 +264,41 @@ service + re-run — zero driver code changes (the drivers contain no test aware
Full suite after the batch: **82 green**, `-race` clean on rotate/sink/vault.
## Service-API batch 2 — 6 drivers (mongo, npm, gcp, twilio, flyio, k8s), 2026-06-18
Six more rotation drivers, each **real-service code only** (no test awareness; tests inject
just an `HTTPClient`/`Bin`), validated against protocol-enforcing emulators:
- **mongo** (in-place DB) — `changeUserPassword` over the OLD authenticated connection is
itself the cutover; `RevokeOld` is a no-op. NO secret on argv: the URI handed to `mongosh`
carries host/db only, both passwords go in on stdin, captured output is scrubbed. Fake
`mongosh` stub authenticates against a state-file password → proves old password dies.
- **npm** (provider-API create→verify→revoke) — `POST /-/npm/v1/tokens` (Bearer old) →
`/-/whoami` (Bearer new) → `DELETE …/tokens/token/<key>`. Blob records the token `key=`
for deletion; degrades to guided when absent.
- **gcp** (provider-API, service-account KEY) — mints an **RS256 JWT signed with the SA's own
private key** (`crypto/rsa`, stdlib, no new dep), exchanges it for an access token, then
`CreateServiceAccountKey` → GET serviceAccount (verify) → `DeleteServiceAccountKey`. The
emulator **verifies the JWT signature** against the key's public key, so the test proves
genuine signing, not a stub. SA JSON round-trips base64-wrapped in the one-line blob.
- **twilio** (provider-API) — `POST …/Keys.json` (Basic old) → GET key (Basic new) →
`DELETE …/Keys/<sid>.json`. Basic-auth username=KeySid, password=secret.
- **flyio** (provider-API, GraphQL) — a **managing token** mints/deletes the **deploy token**
(the rotated value) via `createLimitedAccessToken` / `deleteLimitedAccessToken`; verify
runs the app query as the new deploy token. Same "auth rotates a value" shape as ghactions.
- **k8s** (provider-API) — creates a new `kubernetes.io/service-account-token` Secret, waits
for the controller to populate `.data.token`, GETs the SA to verify, then DELETEs the old
Secret (which invalidates the old token).
**All 6 are MOCK-ONLY** — honestly, because they were proven only against emulators. mongo,
npm and k8s are LIVE-VM *candidates* (real MongoDB / a throwaway npm registry / a k3s cluster
would promote them with zero driver-code change), but per the standing rule a driver is only
LIVE-VM after the *real target* validates the cutover, so they stay MOCK-ONLY until those VM
POCs run. Each emulator enforces credential validity and the tests assert `Verify(old)` fails
after revoke, plus a leak canary (no token/secret/`PRIVATE KEY` in Identity/Source/Location).
Full suite after batch 2: **103 green**, `-race` clean on rotate/sink/vault.
## Summary
- Harness result: **31/31 PASS**, including the global secret-leak canary (no CANARY
+23 -2
View File
@@ -53,6 +53,12 @@ stops a mock-only driver from ever being mistaken for a live one.
| `cloudflare` | `httptest` emulator | no self-host |
| `ghactions` | `httptest` emulator (holds the libsodium box keypair, decrypts the sealed PUT) | no self-host |
| `gitlab` | `httptest` emulator | GitLab CE too heavy for the VM |
| `mongo` | fake-`mongosh` shell stub (auths against a state file) | real-MongoDB VM POC not yet run |
| `npm` | `httptest` registry emulator | real registry never hit |
| `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 |
| `k8s` | `httptest` apiserver emulator (token-Secret create/delete) | real k3s POC not yet run |
## What the MOCK-ONLY emulators actually prove
@@ -67,7 +73,22 @@ 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 / k8s** — 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.
- **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
self-auth (genuine `crypto/rsa` signing) *and* the cutover (revoked key can no longer mint
a token).
- **flyio** — a managing token mints/deletes the deploy token over GraphQL; the deploy token
authenticates the app query only while it exists, so the test proves the managing-token →
deploy-token rotation and that the revoked deploy token stops working.
- **mongo** — the fake `mongosh` authenticates `db.auth` against a password held in a state
file and only `changeUserPassword` updates it; the test proves the in-place cutover (old
password rejected after rotation). No password ever reaches `mongosh`'s argv.
Promoting any of these to LIVE-VM only requires standing up the real service (a self-hosted
GitLab CE / a real Cloudflare token / a throwaway GitHub repo) and re-running the same
driver against it — no driver code changes.
GitLab CE / a real Cloudflare token / a throwaway GitHub repo / a real MongoDB / a real npm
registry / a k3s cluster) and re-running the same driver against it — no driver code changes.
+242
View File
@@ -0,0 +1,242 @@
package rotate
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"strings"
"time"
"incredigo/internal/discover"
"incredigo/internal/vault"
)
// Flyio rotates a Fly.io app-scoped DEPLOY TOKEN via the GraphQL API by CREATING a new
// limited-access token, verifying it, then DELETING the old one — the provider-API
// rotation pattern (create-new → verify → revoke-old).
//
// A deploy token is itself too limited to mint or delete tokens, so rotation is driven
// by a separate MANAGING token (a personal/org access token). The credential blob
// therefore carries both — the managing token (auth=, NOT rotated) and the deploy token
// being rotated (token=, with its id= for deletion) — the same "auth rotates a value"
// shape as the GitHub-Actions secret driver:
//
// flyio://<host>/?org=<orgId>&app=<appId>&auth=<managing-token>&id=<tok-id>&token=<deploy-token>
//
// - scheme "flyio" maps to https; "http"/"https" are accepted for a loopback emulator.
// - <host> API host; "flyio" (or empty) defaults to api.fly.io.
// - org=/app= the organization and app the deploy token is scoped to (createLimited...).
// - auth= the managing token (Bearer for create/delete) — non-secret to the rotation
// of the deploy token in that it is preserved, but still kept vault-only.
// - id= the deploy token's limited-access-token id — required to DELETE the old one.
// - token= the deploy token value being rotated.
//
// SECURITY: both tokens live only in the vault blob and Bearer headers; neither reaches
// Identity/Meta/logs/argv. The new deploy token is decoded straight from the create
// response into the rebuilt blob.
type Flyio 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(&Flyio{}) }
// Name identifies the driver in plans and audit records.
func (f *Flyio) Name() string { return "flyio" }
// Detect claims credentials tagged Source == "flyio".
func (f *Flyio) Detect(c discover.Credential) bool { return c.Source == "flyio" }
func (f *Flyio) client() *http.Client {
if f.HTTPClient != nil {
return f.HTTPClient
}
return &http.Client{Timeout: 15 * time.Second}
}
// flyioSecret is the parsed credential blob. None of its fields are ever logged.
type flyioSecret struct {
base string // scheme://host
org string
app string
auth string // managing token
id string // deploy token id (for delete)
token string // deploy token value (rotated)
}
func parseFlyioSecret(v *vault.Vault, h *vault.Handle) (flyioSecret, error) {
buf, err := v.Open(h)
if err != nil {
return flyioSecret{}, err
}
u, err := url.Parse(strings.TrimSpace(string(buf.Bytes())))
if err != nil {
return flyioSecret{}, fmt.Errorf("flyio: parse secret url: %w", err)
}
if u.Scheme != "flyio" && u.Scheme != "http" && u.Scheme != "https" {
return flyioSecret{}, fmt.Errorf("flyio: unexpected scheme %q", u.Scheme)
}
scheme := u.Scheme
host := u.Host
if scheme == "flyio" {
scheme = "https"
}
if host == "" || host == "flyio" {
host = "api.fly.io"
}
q := u.Query()
s := flyioSecret{
base: scheme + "://" + host,
org: q.Get("org"),
app: q.Get("app"),
auth: q.Get("auth"),
id: q.Get("id"),
token: q.Get("token"),
}
if s.auth == "" {
return flyioSecret{}, fmt.Errorf("flyio: secret has no managing token (auth=)")
}
if s.token == "" {
return flyioSecret{}, fmt.Errorf("flyio: secret has no deploy token")
}
return s, nil
}
// build re-encodes a flyioSecret into the single-line blob form (scheme normalised
// back to "flyio").
func (s flyioSecret) build() string {
host := hostOf(s.base)
if host == "api.fly.io" {
host = "flyio"
}
u := &url.URL{Scheme: "flyio", Host: host, Path: "/"}
q := url.Values{}
if s.org != "" {
q.Set("org", s.org)
}
if s.app != "" {
q.Set("app", s.app)
}
q.Set("auth", s.auth)
if s.id != "" {
q.Set("id", s.id)
}
q.Set("token", s.token)
u.RawQuery = q.Encode()
return u.String()
}
// gql POSTs a GraphQL request authenticated by the given Bearer token and decodes the
// data envelope into out. A non-2xx status or a non-empty errors array is an error.
func (f *Flyio) gql(ctx context.Context, base, bearer, query string, vars map[string]any, out any) error {
body, _ := json.Marshal(map[string]any{"query": query, "variables": vars})
req, err := http.NewRequestWithContext(ctx, http.MethodPost, base+"/graphql", bytes.NewReader(body))
if err != nil {
return err
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", "Bearer "+bearer)
resp, err := f.client().Do(req)
if err != nil {
return err
}
defer func() { io.Copy(io.Discard, resp.Body); resp.Body.Close() }()
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("graphql status %s", resp.Status)
}
var env struct {
Data json.RawMessage `json:"data"`
Errors []struct {
Message string `json:"message"`
} `json:"errors"`
}
if err := json.NewDecoder(resp.Body).Decode(&env); err != nil {
return fmt.Errorf("decode graphql: %w", err)
}
if len(env.Errors) > 0 {
return fmt.Errorf("graphql error: %s", env.Errors[0].Message)
}
if out != nil {
if err := json.Unmarshal(env.Data, out); err != nil {
return fmt.Errorf("decode graphql data: %w", err)
}
}
return nil
}
const flyCreateMutation = `mutation($org:ID!,$app:ID!,$name:String!){createLimitedAccessToken(input:{name:$name,organizationId:$org,profile:"deploy",profileParams:{app_id:$app}}){limitedAccessToken{id,token}}}`
const flyDeleteMutation = `mutation($id:ID!){deleteLimitedAccessToken(input:{id:$id}){token}}`
const flyAppQuery = `query($n:String!){app(name:$n){id,name}}`
// Rotate creates a NEW deploy token (authenticated by the managing token) and returns
// a vault handle to a rebuilt blob carrying the new token + id. It does not delete the
// old deploy token.
func (f *Flyio) Rotate(ctx context.Context, c discover.Credential, v *vault.Vault) (*vault.Handle, error) {
s, err := parseFlyioSecret(v, c.Secret)
if err != nil {
return nil, err
}
var out struct {
Create struct {
Tok struct {
ID string `json:"id"`
Token string `json:"token"`
} `json:"limitedAccessToken"`
} `json:"createLimitedAccessToken"`
}
vars := map[string]any{"org": s.org, "app": s.app, "name": "incredigo-rotated"}
if err := f.gql(ctx, s.base, s.auth, flyCreateMutation, vars, &out); err != nil {
return nil, fmt.Errorf("flyio: create token: %w", err)
}
if out.Create.Tok.Token == "" {
return nil, fmt.Errorf("flyio: create token: empty token in response")
}
ns := s
ns.id = out.Create.Tok.ID
ns.token = out.Create.Tok.Token
return v.Store([]byte(ns.build())), nil
}
// Verify proves the newly minted deploy token authenticates by running the app query
// with it as the Bearer token.
func (f *Flyio) Verify(ctx context.Context, newSecret *vault.Handle, v *vault.Vault) error {
s, err := parseFlyioSecret(v, newSecret)
if err != nil {
return err
}
var out struct {
App struct {
ID string `json:"id"`
} `json:"app"`
}
if err := f.gql(ctx, s.base, s.token, flyAppQuery, map[string]any{"n": s.app}, &out); err != nil {
return fmt.Errorf("flyio verify: %w", err)
}
if out.App.ID == "" {
return fmt.Errorf("flyio verify: deploy token did not resolve the app")
}
return nil
}
// RevokeOld deletes the OLD deploy token by id, authenticated by the managing token.
func (f *Flyio) RevokeOld(ctx context.Context, c discover.Credential, v *vault.Vault) error {
s, err := parseFlyioSecret(v, c.Secret)
if err != nil {
return err
}
if s.id == "" {
return fmt.Errorf("flyio revoke: old token has no recorded id — delete it manually (guided)")
}
if err := f.gql(ctx, s.base, s.auth, flyDeleteMutation, map[string]any{"id": s.id}, nil); err != nil {
return fmt.Errorf("flyio revoke: %w", err)
}
return nil
}
+220
View File
@@ -0,0 +1,220 @@
package rotate
import (
"context"
"crypto/rand"
"encoding/hex"
"encoding/json"
"net/http"
"net/http/httptest"
"strings"
"sync"
"testing"
"incredigo/internal/discover"
"incredigo/internal/vault"
)
// flyioEmu emulates the Fly.io GraphQL token API and ENFORCES token validity: the
// managing token is always valid and may create/delete; a deploy token authenticates
// the app query only while it exists, and deleteLimitedAccessToken makes it stop
// working — so a test can prove a real cutover.
type flyioEmu struct {
mu sync.Mutex
managing string
app string
tokens map[string]string // deploy token id -> token value
valid map[string]bool // deploy token value -> alive
srv *httptest.Server
}
func newFlyioEmu(t *testing.T, managing, app, seedID, seedToken string) *flyioEmu {
e := &flyioEmu{
managing: managing,
app: app,
tokens: map[string]string{seedID: seedToken},
valid: map[string]bool{seedToken: true},
}
mux := http.NewServeMux()
mux.HandleFunc("/graphql", e.handle)
e.srv = httptest.NewTLSServer(mux)
t.Cleanup(e.srv.Close)
return e
}
func (e *flyioEmu) handle(w http.ResponseWriter, r *http.Request) {
bear := bearer(r)
var body struct {
Query string `json:"query"`
Variables map[string]any `json:"variables"`
}
json.NewDecoder(r.Body).Decode(&body)
switch {
case strings.Contains(body.Query, "createLimitedAccessToken"):
if bear != e.managing {
gqlErr(w, "unauthorized: create requires managing token")
return
}
idRaw := make([]byte, 8)
rand.Read(idRaw)
id := "lat_" + hex.EncodeToString(idRaw)
tRaw := make([]byte, 16)
rand.Read(tRaw)
tok := "FlyV1_" + hex.EncodeToString(tRaw)
e.mu.Lock()
e.tokens[id] = tok
e.valid[tok] = true
e.mu.Unlock()
gqlData(w, map[string]any{
"createLimitedAccessToken": map[string]any{
"limitedAccessToken": map[string]any{"id": id, "token": tok},
},
})
case strings.Contains(body.Query, "deleteLimitedAccessToken"):
if bear != e.managing {
gqlErr(w, "unauthorized: delete requires managing token")
return
}
id, _ := body.Variables["id"].(string)
e.mu.Lock()
if v, ok := e.tokens[id]; ok {
delete(e.valid, v)
delete(e.tokens, id)
}
e.mu.Unlock()
gqlData(w, map[string]any{"deleteLimitedAccessToken": map[string]any{"token": "deleted"}})
case strings.Contains(body.Query, "app(name"):
e.mu.Lock()
ok := e.valid[bear]
e.mu.Unlock()
if !ok {
gqlErr(w, "unauthorized: unknown or revoked token")
return
}
gqlData(w, map[string]any{"app": map[string]any{"id": "app_123", "name": e.app}})
default:
gqlErr(w, "unknown query")
}
}
func gqlData(w http.ResponseWriter, data map[string]any) {
json.NewEncoder(w).Encode(map[string]any{"data": data})
}
func gqlErr(w http.ResponseWriter, msg string) {
json.NewEncoder(w).Encode(map[string]any{"errors": []map[string]any{{"message": msg}}})
}
func (e *flyioEmu) tokenValid(tok string) bool {
e.mu.Lock()
defer e.mu.Unlock()
return e.valid[tok]
}
func TestFlyioDetect(t *testing.T) {
f := &Flyio{}
if !f.Detect(discover.Credential{Source: "flyio"}) {
t.Error("should detect Source=flyio")
}
if f.Detect(discover.Credential{Source: "gcp"}) {
t.Error("should not detect Source=gcp")
}
}
func TestFlyioRotateRealCutover(t *testing.T) {
v := vault.New()
defer v.Purge()
ctx := context.Background()
const managing, app, seedID, oldTok = "FlyV1_managing0123", "labapp", "lat_seed01", "FlyV1_old0123456789"
emu := newFlyioEmu(t, managing, app, seedID, oldTok)
host := strings.TrimPrefix(emu.srv.URL, "https://")
oldBlob := "flyio://" + host + "/?org=orglab&app=" + app + "&auth=" + managing + "&id=" + seedID + "&token=" + oldTok
cred := discover.Credential{
Source: "flyio",
Kind: discover.KindToken,
Identity: app + " @ flyio",
Location: "imported/flyio/labapp",
Secret: v.Store([]byte(oldBlob)),
}
f := &Flyio{HTTPClient: emu.srv.Client()}
if !emu.tokenValid(oldTok) {
t.Fatal("seed deploy token should be valid at start")
}
// 1. Rotate.
newH, err := f.Rotate(ctx, cred, v)
if err != nil {
t.Fatalf("Rotate: %v", err)
}
ns, err := parseFlyioSecret(v, newH)
if err != nil {
t.Fatalf("parse new secret: %v", err)
}
if ns.token == oldTok {
t.Fatal("new deploy token equals old — rotation minted nothing")
}
if ns.id == "" || ns.id == seedID {
t.Fatalf("new secret must carry a fresh token id, got %q", ns.id)
}
if ns.auth != managing {
t.Fatal("managing token must be preserved across rotation")
}
if !emu.tokenValid(oldTok) {
t.Fatal("old deploy token must remain valid before revoke")
}
if !emu.tokenValid(ns.token) {
t.Fatal("new deploy token must be valid after create")
}
// 2. Verify(new).
if err := f.Verify(ctx, newH, v); err != nil {
t.Fatalf("Verify(new): %v", err)
}
// 3. RevokeOld.
if err := f.RevokeOld(ctx, cred, v); err != nil {
t.Fatalf("RevokeOld: %v", err)
}
if emu.tokenValid(oldTok) {
t.Fatal("old deploy token must be invalid after revoke")
}
if err := f.Verify(ctx, newH, v); err != nil {
t.Fatalf("new deploy token must still authenticate after revoke: %v", err)
}
// Leak check.
for _, fld := range []string{cred.Identity, cred.Source, cred.Location, string(cred.Kind)} {
if strings.Contains(fld, oldTok) || strings.Contains(fld, ns.token) || strings.Contains(fld, managing) {
t.Errorf("token leaked into non-secret field %q", fld)
}
}
}
func TestFlyioRevokeRequiresID(t *testing.T) {
v := vault.New()
defer v.Purge()
f := &Flyio{}
cred := discover.Credential{
Source: "flyio",
Secret: v.Store([]byte("flyio://api.fly.io/?app=a&auth=mgmt&token=deploytok")),
}
err := f.RevokeOld(context.Background(), cred, v)
if err == nil || !strings.Contains(err.Error(), "no recorded id") {
t.Fatalf("expected revoke-without-id error, got %v", err)
}
}
func TestFlyioRejectsBadSecret(t *testing.T) {
v := vault.New()
defer v.Purge()
f := &Flyio{}
// no managing token
cred := discover.Credential{Source: "flyio", Secret: v.Store([]byte("flyio://api.fly.io/?app=a&token=deploytok"))}
if _, err := f.Rotate(context.Background(), cred, v); err == nil {
t.Error("Rotate should reject a secret with no managing token")
}
}
+340
View File
@@ -0,0 +1,340 @@
package rotate
import (
"context"
"crypto"
"crypto/rand"
"crypto/rsa"
"crypto/sha256"
"crypto/x509"
"encoding/base64"
"encoding/json"
"encoding/pem"
"fmt"
"io"
"net/http"
"net/url"
"strings"
"time"
"incredigo/internal/discover"
"incredigo/internal/vault"
)
// GCP rotates a Google Cloud service-account KEY via the IAM API by CREATING a new
// key, verifying it authenticates, then DELETING the old one — the provider-API
// rotation pattern (create-new → verify → revoke-old).
//
// The credential's secret is the service-account JSON key file. To round-trip through
// the single-line gopass sink, the compact JSON is base64-wrapped in a one-line blob:
//
// gcp://<host>/?sa=<base64url(compact-sa-json)>[&endpoint=<iam-base-url>]
//
// - sa= the FULL service-account JSON (project_id, client_email,
// private_key_id, private_key PEM, token_uri) base64url-encoded.
// - endpoint= OPTIONAL override of the IAM API base (for a self-hosted emulator in
// testing). Absent → real GCP (https://iam.googleapis.com).
//
// AUTH: every IAM call is made with an OAuth2 access token that the driver mints by
// signing an RS256 JWT with the service account's OWN private key and exchanging it at
// the token endpoint (the standard service-account self-auth — the SA needs
// iam.serviceAccountKeys.create/delete on itself). The new key's privateKeyData is
// returned by GCP only once in the CreateServiceAccountKey response; it is decoded
// straight into the vault and never logged. The private key never reaches argv.
type GCP struct {
// HTTPClient is injectable for tests / custom TLS. Defaults to a 15s-timeout client.
HTTPClient *http.Client
// now is injectable so tests can pin the JWT iat/exp; defaults to time.Now.
now func() time.Time
}
// init self-registers the driver. Availability alone changes nothing; the
// `rotate --execute` + INCREDIGO_ALLOW_EXECUTE=1 gate still applies.
func init() { Register(&GCP{}) }
// Name identifies the driver in plans and audit records.
func (g *GCP) Name() string { return "gcp" }
// Detect claims credentials tagged Source == "gcp".
func (g *GCP) Detect(c discover.Credential) bool { return c.Source == "gcp" }
func (g *GCP) client() *http.Client {
if g.HTTPClient != nil {
return g.HTTPClient
}
return &http.Client{Timeout: 15 * time.Second}
}
func (g *GCP) clock() time.Time {
if g.now != nil {
return g.now()
}
return time.Now()
}
// gcpSA mirrors the fields of a service-account JSON key the driver needs. None of
// these are ever logged.
type gcpSA struct {
ProjectID string `json:"project_id"`
ClientEmail string `json:"client_email"`
PrivateKeyID string `json:"private_key_id"`
PrivateKey string `json:"private_key"`
TokenURI string `json:"token_uri"`
}
// gcpSecret is the parsed credential blob.
type gcpSecret struct {
raw []byte // the compact SA JSON exactly as stored (round-trips via build)
sa gcpSA
endpoint string // "" = real GCP IAM
}
func parseGCPSecret(v *vault.Vault, h *vault.Handle) (gcpSecret, error) {
buf, err := v.Open(h)
if err != nil {
return gcpSecret{}, err
}
u, err := url.Parse(strings.TrimSpace(string(buf.Bytes())))
if err != nil {
return gcpSecret{}, fmt.Errorf("gcp: parse secret url: %w", err)
}
if u.Scheme != "gcp" {
return gcpSecret{}, fmt.Errorf("gcp: unexpected scheme %q", u.Scheme)
}
q := u.Query()
raw, err := base64.URLEncoding.DecodeString(q.Get("sa"))
if err != nil {
return gcpSecret{}, fmt.Errorf("gcp: decode sa json: %w", err)
}
var sa gcpSA
if err := json.Unmarshal(raw, &sa); err != nil {
return gcpSecret{}, fmt.Errorf("gcp: parse sa json: %w", err)
}
if sa.ClientEmail == "" || sa.PrivateKey == "" {
return gcpSecret{}, fmt.Errorf("gcp: sa json missing client_email or private_key")
}
return gcpSecret{raw: raw, sa: sa, endpoint: q.Get("endpoint")}, nil
}
// build re-encodes a gcpSecret into the single-line blob form.
func (s gcpSecret) build() string {
u := &url.URL{Scheme: "gcp", Host: "gcp", Path: "/"}
q := url.Values{}
q.Set("sa", base64.URLEncoding.EncodeToString(s.raw))
if s.endpoint != "" {
q.Set("endpoint", s.endpoint)
}
u.RawQuery = q.Encode()
return u.String()
}
func (s gcpSecret) iamBase() string {
if s.endpoint != "" {
return strings.TrimRight(s.endpoint, "/")
}
return "https://iam.googleapis.com"
}
func (s gcpSecret) tokenURI() string {
if s.sa.TokenURI != "" {
return s.sa.TokenURI
}
return "https://oauth2.googleapis.com/token"
}
// keysURL builds the .../serviceAccounts/{email}/keys collection or member URL.
func (s gcpSecret) keysURL(keyID string) string {
base := s.iamBase() + "/v1/projects/" + url.PathEscape(s.sa.ProjectID) +
"/serviceAccounts/" + url.PathEscape(s.sa.ClientEmail) + "/keys"
if keyID != "" {
base += "/" + url.PathEscape(keyID)
}
return base
}
// b64url is RFC 7515 base64url without padding (JWT segment encoding).
func b64url(b []byte) string { return base64.RawURLEncoding.EncodeToString(b) }
// accessToken mints an OAuth2 access token by signing an RS256 JWT with the SA's
// private key and exchanging it at the token endpoint. The private key is parsed
// transiently and never logged.
func (g *GCP) accessToken(ctx context.Context, s gcpSecret) (string, error) {
key, err := parseRSAPrivateKey(s.sa.PrivateKey)
if err != nil {
return "", fmt.Errorf("gcp: parse private key: %w", err)
}
now := g.clock().UTC()
header := map[string]any{"alg": "RS256", "typ": "JWT", "kid": s.sa.PrivateKeyID}
claims := map[string]any{
"iss": s.sa.ClientEmail,
"sub": s.sa.ClientEmail,
"aud": s.tokenURI(),
"scope": "https://www.googleapis.com/auth/cloud-platform",
"iat": now.Unix(),
"exp": now.Add(10 * time.Minute).Unix(),
}
hj, _ := json.Marshal(header)
cj, _ := json.Marshal(claims)
signingInput := b64url(hj) + "." + b64url(cj)
digest := sha256.Sum256([]byte(signingInput))
sig, err := rsa.SignPKCS1v15(rand.Reader, key, crypto.SHA256, digest[:])
if err != nil {
return "", fmt.Errorf("gcp: sign jwt: %w", err)
}
assertion := signingInput + "." + b64url(sig)
form := url.Values{}
form.Set("grant_type", "urn:ietf:params:oauth:grant-type:jwt-bearer")
form.Set("assertion", assertion)
req, err := http.NewRequestWithContext(ctx, http.MethodPost, s.tokenURI(), strings.NewReader(form.Encode()))
if err != nil {
return "", err
}
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
resp, err := g.client().Do(req)
if err != nil {
return "", fmt.Errorf("gcp: token exchange: %w", err)
}
defer func() { io.Copy(io.Discard, resp.Body); resp.Body.Close() }()
if resp.StatusCode != http.StatusOK {
return "", fmt.Errorf("gcp: token exchange: status %s", resp.Status)
}
var tok struct {
AccessToken string `json:"access_token"`
}
if err := json.NewDecoder(resp.Body).Decode(&tok); err != nil {
return "", fmt.Errorf("gcp: decode token: %w", err)
}
if tok.AccessToken == "" {
return "", fmt.Errorf("gcp: token exchange: empty access_token")
}
return tok.AccessToken, nil
}
// parseRSAPrivateKey parses a PEM private key (PKCS#8, as GCP emits, or PKCS#1).
func parseRSAPrivateKey(pemStr string) (*rsa.PrivateKey, error) {
block, _ := pem.Decode([]byte(pemStr))
if block == nil {
return nil, fmt.Errorf("no PEM block")
}
if k, err := x509.ParsePKCS8PrivateKey(block.Bytes); err == nil {
rk, ok := k.(*rsa.PrivateKey)
if !ok {
return nil, fmt.Errorf("not an RSA key")
}
return rk, nil
}
return x509.ParsePKCS1PrivateKey(block.Bytes)
}
// Rotate creates a NEW service-account key (authenticated by the OLD key) and returns
// a vault handle to the rebuilt blob carrying the new key JSON. It does not delete the
// old key.
func (g *GCP) Rotate(ctx context.Context, c discover.Credential, v *vault.Vault) (*vault.Handle, error) {
s, err := parseGCPSecret(v, c.Secret)
if err != nil {
return nil, err
}
token, err := g.accessToken(ctx, s)
if err != nil {
return nil, err
}
body, _ := json.Marshal(map[string]string{
"privateKeyType": "TYPE_GOOGLE_CREDENTIALS_FILE",
"keyAlgorithm": "KEY_ALG_RSA_2048",
})
req, err := http.NewRequestWithContext(ctx, http.MethodPost, s.keysURL(""), strings.NewReader(string(body)))
if err != nil {
return nil, err
}
req.Header.Set("Authorization", "Bearer "+token)
req.Header.Set("Content-Type", "application/json")
resp, err := g.client().Do(req)
if err != nil {
return nil, fmt.Errorf("gcp: create key: %w", err)
}
defer func() { io.Copy(io.Discard, resp.Body); resp.Body.Close() }()
if resp.StatusCode != http.StatusOK && resp.StatusCode != http.StatusCreated {
return nil, fmt.Errorf("gcp: create key: status %s", resp.Status)
}
var created struct {
Name string `json:"name"`
PrivateKeyData string `json:"privateKeyData"` // base64 of the new SA JSON
}
if err := json.NewDecoder(resp.Body).Decode(&created); err != nil {
return nil, fmt.Errorf("gcp: decode created key: %w", err)
}
newRaw, err := base64.StdEncoding.DecodeString(created.PrivateKeyData)
if err != nil {
return nil, fmt.Errorf("gcp: decode new key data: %w", err)
}
var newSA gcpSA
if err := json.Unmarshal(newRaw, &newSA); err != nil {
return nil, fmt.Errorf("gcp: parse new key json: %w", err)
}
if newSA.PrivateKey == "" {
return nil, fmt.Errorf("gcp: create key: new key carries no private_key")
}
ns := gcpSecret{raw: newRaw, sa: newSA, endpoint: s.endpoint}
return v.Store([]byte(ns.build())), nil
}
// Verify proves the freshly minted key authenticates by minting an access token with
// it and GETting the service-account resource from the IAM API.
func (g *GCP) Verify(ctx context.Context, newSecret *vault.Handle, v *vault.Vault) error {
s, err := parseGCPSecret(v, newSecret)
if err != nil {
return err
}
token, err := g.accessToken(ctx, s)
if err != nil {
return fmt.Errorf("gcp verify: %w", err)
}
saURL := s.iamBase() + "/v1/projects/" + url.PathEscape(s.sa.ProjectID) +
"/serviceAccounts/" + url.PathEscape(s.sa.ClientEmail)
req, err := http.NewRequestWithContext(ctx, http.MethodGet, saURL, nil)
if err != nil {
return err
}
req.Header.Set("Authorization", "Bearer "+token)
resp, err := g.client().Do(req)
if err != nil {
return fmt.Errorf("gcp verify: %w", err)
}
defer func() { io.Copy(io.Discard, resp.Body); resp.Body.Close() }()
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("gcp verify: get serviceAccount status %s", resp.Status)
}
return nil
}
// RevokeOld deletes the OLD key by its private_key_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 (g *GCP) RevokeOld(ctx context.Context, c discover.Credential, v *vault.Vault) error {
s, err := parseGCPSecret(v, c.Secret)
if err != nil {
return err
}
if s.sa.PrivateKeyID == "" {
return fmt.Errorf("gcp revoke: old key has no recorded private_key_id — delete it manually (guided)")
}
token, err := g.accessToken(ctx, s)
if err != nil {
return err
}
req, err := http.NewRequestWithContext(ctx, http.MethodDelete, s.keysURL(s.sa.PrivateKeyID), nil)
if err != nil {
return err
}
req.Header.Set("Authorization", "Bearer "+token)
resp, err := g.client().Do(req)
if err != nil {
return fmt.Errorf("gcp 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("gcp revoke: delete key status %s", resp.Status)
}
return nil
}
+263
View File
@@ -0,0 +1,263 @@
package rotate
import (
"context"
"crypto"
"crypto/rand"
"crypto/rsa"
"crypto/sha256"
"crypto/x509"
"encoding/base64"
"encoding/hex"
"encoding/json"
"encoding/pem"
"net/http"
"net/http/httptest"
"strings"
"sync"
"testing"
"incredigo/internal/discover"
"incredigo/internal/vault"
)
// gcpEmu emulates the GCP token endpoint + IAM service-account keys API and ENFORCES
// key validity: it verifies the RS256 JWT signature against the public key recorded
// for the JWT's kid, so a token only mints while its key exists — and DELETE makes the
// key (and therefore its self-auth) stop working. This proves a real cutover and that
// the driver's JWT signing is genuine, not stubbed.
type gcpEmu struct {
mu sync.Mutex
pubByKid map[string]*rsa.PublicKey
tokens map[string]bool // issued access tokens
email string
project string
srv *httptest.Server
}
func newGCPEmu(t *testing.T, project, email, seedKid string, seedPub *rsa.PublicKey) *gcpEmu {
e := &gcpEmu{
pubByKid: map[string]*rsa.PublicKey{seedKid: seedPub},
tokens: map[string]bool{},
email: email,
project: project,
}
mux := http.NewServeMux()
mux.HandleFunc("/token", e.handleToken)
mux.HandleFunc("/v1/", e.handleIAM)
e.srv = httptest.NewTLSServer(mux)
t.Cleanup(e.srv.Close)
return e
}
func (e *gcpEmu) handleToken(w http.ResponseWriter, r *http.Request) {
r.ParseForm()
assertion := r.Form.Get("assertion")
parts := strings.Split(assertion, ".")
if len(parts) != 3 {
w.WriteHeader(http.StatusBadRequest)
return
}
hdrBytes, _ := base64.RawURLEncoding.DecodeString(parts[0])
var hdr struct {
Kid string `json:"kid"`
}
json.Unmarshal(hdrBytes, &hdr)
e.mu.Lock()
pub, ok := e.pubByKid[hdr.Kid]
e.mu.Unlock()
if !ok {
w.WriteHeader(http.StatusUnauthorized)
return
}
sig, err := base64.RawURLEncoding.DecodeString(parts[2])
if err != nil {
w.WriteHeader(http.StatusBadRequest)
return
}
digest := sha256.Sum256([]byte(parts[0] + "." + parts[1]))
if rsa.VerifyPKCS1v15(pub, crypto.SHA256, digest[:], sig) != nil {
w.WriteHeader(http.StatusUnauthorized)
return
}
raw := make([]byte, 16)
rand.Read(raw)
tok := "ya29." + hex.EncodeToString(raw)
e.mu.Lock()
e.tokens[tok] = true
e.mu.Unlock()
json.NewEncoder(w).Encode(map[string]any{"access_token": tok, "token_type": "Bearer", "expires_in": 3600})
}
func (e *gcpEmu) bearerOK(r *http.Request) bool {
tok := bearer(r) // reuses helper from npm_test.go
e.mu.Lock()
defer e.mu.Unlock()
return e.tokens[tok]
}
func (e *gcpEmu) handleIAM(w http.ResponseWriter, r *http.Request) {
if !e.bearerOK(r) {
w.WriteHeader(http.StatusUnauthorized)
return
}
parts := strings.Split(strings.Trim(r.URL.Path, "/"), "/")
// Find the "keys" segment, if any.
keysIdx := -1
for i, p := range parts {
if p == "keys" {
keysIdx = i
}
}
switch {
case r.Method == http.MethodPost && keysIdx == len(parts)-1:
e.createKey(w)
case r.Method == http.MethodDelete && keysIdx == len(parts)-2:
kid := parts[len(parts)-1]
e.mu.Lock()
delete(e.pubByKid, kid)
e.mu.Unlock()
w.WriteHeader(http.StatusOK)
w.Write([]byte("{}"))
case r.Method == http.MethodGet && keysIdx == -1:
// GET the serviceAccount resource.
json.NewEncoder(w).Encode(map[string]any{"email": e.email, "projectId": e.project})
default:
w.WriteHeader(http.StatusNotFound)
}
}
func (e *gcpEmu) createKey(w http.ResponseWriter) {
priv, _ := rsa.GenerateKey(rand.Reader, 2048)
kidRaw := make([]byte, 12)
rand.Read(kidRaw)
kid := hex.EncodeToString(kidRaw)
e.mu.Lock()
e.pubByKid[kid] = &priv.PublicKey
e.mu.Unlock()
saJSON, _ := json.Marshal(map[string]string{
"type": "service_account",
"project_id": e.project,
"private_key_id": kid,
"private_key": pkcs8PEM(priv),
"client_email": e.email,
"token_uri": e.srv.URL + "/token",
})
json.NewEncoder(w).Encode(map[string]any{
"name": "projects/" + e.project + "/serviceAccounts/" + e.email + "/keys/" + kid,
"privateKeyData": base64.StdEncoding.EncodeToString(saJSON),
})
}
func pkcs8PEM(k *rsa.PrivateKey) string {
der, _ := x509.MarshalPKCS8PrivateKey(k)
return string(pem.EncodeToMemory(&pem.Block{Type: "PRIVATE KEY", Bytes: der}))
}
// seedBlob builds the initial gcp:// blob carrying the seed SA JSON.
func gcpSeedBlob(t *testing.T, emu *gcpEmu, kid string, priv *rsa.PrivateKey) string {
t.Helper()
saJSON, _ := json.Marshal(map[string]string{
"type": "service_account",
"project_id": emu.project,
"private_key_id": kid,
"private_key": pkcs8PEM(priv),
"client_email": emu.email,
"token_uri": emu.srv.URL + "/token",
})
return (gcpSecret{raw: saJSON, endpoint: emu.srv.URL}).build()
}
func TestGCPDetect(t *testing.T) {
g := &GCP{}
if !g.Detect(discover.Credential{Source: "gcp"}) {
t.Error("should detect Source=gcp")
}
if g.Detect(discover.Credential{Source: "aws"}) {
t.Error("should not detect Source=aws")
}
}
func TestGCPRotateRealCutover(t *testing.T) {
v := vault.New()
defer v.Purge()
ctx := context.Background()
const project, email = "lab-proj", "labsa@lab-proj.iam.gserviceaccount.com"
seedPriv, err := rsa.GenerateKey(rand.Reader, 2048)
if err != nil {
t.Fatal(err)
}
seedKid := "seedkid000111222"
emu := newGCPEmu(t, project, email, seedKid, &seedPriv.PublicKey)
oldBlob := gcpSeedBlob(t, emu, seedKid, seedPriv)
cred := discover.Credential{
Source: "gcp",
Kind: discover.KindToken,
Identity: email + " @ gcp",
Location: "imported/gcp/labsa",
Secret: v.Store([]byte(oldBlob)),
}
g := &GCP{HTTPClient: emu.srv.Client()}
// 1. Rotate — create a new key (old still valid).
newH, err := g.Rotate(ctx, cred, v)
if err != nil {
t.Fatalf("Rotate: %v", err)
}
ns, err := parseGCPSecret(v, newH)
if err != nil {
t.Fatalf("parse new secret: %v", err)
}
if ns.sa.PrivateKeyID == seedKid {
t.Fatal("new key id equals old — rotation minted nothing")
}
if ns.sa.PrivateKey == "" || strings.Contains(ns.sa.PrivateKey, pkcs8PEM(seedPriv)) {
t.Fatal("new secret must carry a fresh private key")
}
// 2. Verify(new) authenticates against the IAM API.
if err := g.Verify(ctx, newH, v); err != nil {
t.Fatalf("Verify(new): %v", err)
}
// old key still authenticates before revoke.
if err := g.Verify(ctx, cred.Secret, v); err != nil {
t.Fatalf("old key must authenticate before revoke: %v", err)
}
// 3. RevokeOld — delete the old key.
if err := g.RevokeOld(ctx, cred, v); err != nil {
t.Fatalf("RevokeOld: %v", err)
}
// Cutover: old key can no longer mint a token, new key still works.
if err := g.Verify(ctx, cred.Secret, v); err == nil {
t.Fatal("old key must fail to authenticate after revoke")
}
if err := g.Verify(ctx, newH, v); err != nil {
t.Fatalf("new key must still authenticate after revoke: %v", err)
}
// Leak check: the private key PEM must not appear in non-secret fields.
for _, f := range []string{cred.Identity, cred.Source, cred.Location, string(cred.Kind)} {
if strings.Contains(f, "PRIVATE KEY") || strings.Contains(f, ns.sa.PrivateKey) {
t.Errorf("key material leaked into non-secret field %q", f)
}
}
}
func TestGCPRejectsBadSecret(t *testing.T) {
v := vault.New()
defer v.Purge()
g := &GCP{}
// sa json missing private_key
bad, _ := json.Marshal(map[string]string{"client_email": "x@y.iam"})
blob := (gcpSecret{raw: bad}).build()
cred := discover.Credential{Source: "gcp", Secret: v.Store([]byte(blob))}
if _, err := g.Rotate(context.Background(), cred, v); err == nil {
t.Error("Rotate should reject a sa json with no private_key")
}
}
+268
View File
@@ -0,0 +1,268 @@
package rotate
import (
"bytes"
"context"
"encoding/base64"
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"strings"
"time"
"incredigo/internal/discover"
"incredigo/internal/vault"
)
// K8s rotates a Kubernetes ServiceAccount token (the legacy, individually-revocable
// kind backed by a Secret of type kubernetes.io/service-account-token) by CREATING a
// new token Secret, verifying the minted token authenticates, then DELETING the old
// Secret — the provider-API rotation pattern (create-new → verify → revoke-old).
//
// Bound TokenRequest tokens cannot be revoked individually, so rotation targets the
// Secret-backed token whose deletion immediately invalidates it. The credential blob:
//
// k8s://<host:port>/?ns=<namespace>&sa=<serviceaccount>&secret=<secret-name>&token=<token>
//
// - scheme "k8s" maps to https; "http"/"https" are accepted for a loopback emulator.
// - <host> the apiserver host:port.
// - ns= the namespace holding the SA + token Secret.
// - sa= the ServiceAccount name (the new Secret is annotated to it).
// - secret= the token Secret's name — required to DELETE the old token.
// - token= the bearer token value (rotated).
//
// AUTH: every call authenticates with a token Bearer header against the apiserver. The
// rotating SA needs RBAC to create/delete Secrets in its namespace. The new token is
// read (base64) from the controller-populated Secret straight into the vault; it never
// reaches Identity/Meta/logs/argv.
type K8s struct {
// HTTPClient is injectable for tests / custom CA. A real apiserver needs a client
// configured with the cluster CA; defaults to a 15s-timeout client otherwise.
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(&K8s{}) }
// Name identifies the driver in plans and audit records.
func (k *K8s) Name() string { return "k8s" }
// Detect claims credentials tagged Source == "k8s".
func (k *K8s) Detect(c discover.Credential) bool { return c.Source == "k8s" }
func (k *K8s) client() *http.Client {
if k.HTTPClient != nil {
return k.HTTPClient
}
return &http.Client{Timeout: 15 * time.Second}
}
// k8sCred is the parsed credential blob. None of its fields are ever logged.
type k8sCred struct {
base string // scheme://host:port
ns string
sa string
secret string // token Secret name
token string
}
func parseK8sCred(v *vault.Vault, h *vault.Handle) (k8sCred, error) {
buf, err := v.Open(h)
if err != nil {
return k8sCred{}, err
}
u, err := url.Parse(strings.TrimSpace(string(buf.Bytes())))
if err != nil {
return k8sCred{}, fmt.Errorf("k8s: parse secret url: %w", err)
}
if u.Scheme != "k8s" && u.Scheme != "http" && u.Scheme != "https" {
return k8sCred{}, fmt.Errorf("k8s: unexpected scheme %q", u.Scheme)
}
scheme := u.Scheme
if scheme == "k8s" {
scheme = "https"
}
if u.Host == "" {
return k8sCred{}, fmt.Errorf("k8s: secret has no apiserver host")
}
q := u.Query()
c := k8sCred{base: scheme + "://" + u.Host, ns: q.Get("ns"), sa: q.Get("sa"), secret: q.Get("secret"), token: q.Get("token")}
if c.ns == "" || c.sa == "" {
return k8sCred{}, fmt.Errorf("k8s: secret missing namespace or serviceaccount")
}
if c.token == "" {
return k8sCred{}, fmt.Errorf("k8s: secret has no token")
}
return c, nil
}
// build re-encodes a k8sCred into the single-line blob form (scheme normalised back
// to "k8s").
func (c k8sCred) build() string {
u := &url.URL{Scheme: "k8s", Host: hostPortOf(c.base), Path: "/"}
q := url.Values{}
q.Set("ns", c.ns)
q.Set("sa", c.sa)
if c.secret != "" {
q.Set("secret", c.secret)
}
q.Set("token", c.token)
u.RawQuery = q.Encode()
return u.String()
}
// hostPortOf strips the scheme from a scheme://host:port base.
func hostPortOf(base string) string {
if i := strings.Index(base, "://"); i >= 0 {
return base[i+3:]
}
return base
}
// k8sSecretObj is the subset of a core/v1 Secret the driver reads or writes.
type k8sSecretObj struct {
Metadata struct {
Name string `json:"name"`
Annotations map[string]string `json:"annotations,omitempty"`
} `json:"metadata"`
Type string `json:"type,omitempty"`
Data map[string]string `json:"data,omitempty"`
}
// do issues an authenticated apiserver request and returns the body for 2xx responses.
func (k *K8s) do(ctx context.Context, method, urlStr, token string, body []byte) ([]byte, int, error) {
var r io.Reader
if body != nil {
r = bytes.NewReader(body)
}
req, err := http.NewRequestWithContext(ctx, method, urlStr, r)
if err != nil {
return nil, 0, err
}
req.Header.Set("Authorization", "Bearer "+token)
if body != nil {
req.Header.Set("Content-Type", "application/json")
}
resp, err := k.client().Do(req)
if err != nil {
return nil, 0, err
}
defer resp.Body.Close()
rb, _ := io.ReadAll(io.LimitReader(resp.Body, 1<<20))
return rb, resp.StatusCode, nil
}
func (c k8sCred) secretsURL(name string) string {
base := c.base + "/api/v1/namespaces/" + url.PathEscape(c.ns) + "/secrets"
if name != "" {
return base + "/" + url.PathEscape(name)
}
return base
}
// Rotate creates a NEW token Secret for the SA (authenticated by the OLD token), waits
// for the controller to populate its token, and returns a vault handle to the rebuilt
// blob carrying the new Secret name + token. It does not delete the old Secret.
func (k *K8s) Rotate(ctx context.Context, c discover.Credential, v *vault.Vault) (*vault.Handle, error) {
cr, err := parseK8sCred(v, c.Secret)
if err != nil {
return nil, err
}
suffix, err := genHex(4)
if err != nil {
return nil, err
}
newName := cr.sa + "-token-" + suffix
obj := k8sSecretObj{Type: "kubernetes.io/service-account-token"}
obj.Metadata.Name = newName
obj.Metadata.Annotations = map[string]string{"kubernetes.io/service-account.name": cr.sa}
body, _ := json.Marshal(obj)
_, code, err := k.do(ctx, http.MethodPost, cr.secretsURL(""), cr.token, body)
if err != nil {
return nil, fmt.Errorf("k8s: create token secret: %w", err)
}
if code != http.StatusCreated && code != http.StatusOK {
return nil, fmt.Errorf("k8s: create token secret: status %d", code)
}
// Wait for the token-controller to populate .data.token.
token, err := k.awaitToken(ctx, cr, newName)
if err != nil {
return nil, err
}
nc := cr
nc.secret = newName
nc.token = token
return v.Store([]byte(nc.build())), nil
}
// awaitToken polls the new Secret until its .data.token is present, decoding it.
func (k *K8s) awaitToken(ctx context.Context, cr k8sCred, name string) (string, error) {
for attempt := 0; attempt < 10; attempt++ {
rb, code, err := k.do(ctx, http.MethodGet, cr.secretsURL(name), cr.token, nil)
if err != nil {
return "", fmt.Errorf("k8s: read token secret: %w", err)
}
if code == http.StatusOK {
var got k8sSecretObj
if err := json.Unmarshal(rb, &got); err != nil {
return "", fmt.Errorf("k8s: decode token secret: %w", err)
}
if enc := got.Data["token"]; enc != "" {
tok, err := base64.StdEncoding.DecodeString(enc)
if err != nil {
return "", fmt.Errorf("k8s: decode token data: %w", err)
}
return string(tok), nil
}
}
select {
case <-ctx.Done():
return "", ctx.Err()
case <-time.After(200 * time.Millisecond):
}
}
return "", fmt.Errorf("k8s: token secret never populated a token")
}
// Verify proves the new token authenticates by GETting the ServiceAccount with it.
func (k *K8s) Verify(ctx context.Context, newSecret *vault.Handle, v *vault.Vault) error {
cr, err := parseK8sCred(v, newSecret)
if err != nil {
return err
}
saURL := cr.base + "/api/v1/namespaces/" + url.PathEscape(cr.ns) + "/serviceaccounts/" + url.PathEscape(cr.sa)
_, code, err := k.do(ctx, http.MethodGet, saURL, cr.token, nil)
if err != nil {
return fmt.Errorf("k8s verify: %w", err)
}
if code != http.StatusOK {
return fmt.Errorf("k8s verify: get serviceaccount status %d", code)
}
return nil
}
// RevokeOld deletes the OLD token Secret, which invalidates the old token. The old
// token is still valid at this point (revoke runs only after the new token is
// stored+verified), so it authenticates its own Secret's deletion.
func (k *K8s) RevokeOld(ctx context.Context, c discover.Credential, v *vault.Vault) error {
cr, err := parseK8sCred(v, c.Secret)
if err != nil {
return err
}
if cr.secret == "" {
return fmt.Errorf("k8s revoke: old token has no recorded secret name — delete it manually (guided)")
}
_, code, err := k.do(ctx, http.MethodDelete, cr.secretsURL(cr.secret), cr.token, nil)
if err != nil {
return fmt.Errorf("k8s revoke: %w", err)
}
if code != http.StatusOK && code != http.StatusNoContent {
return fmt.Errorf("k8s revoke: delete token secret status %d", code)
}
return nil
}
+230
View File
@@ -0,0 +1,230 @@
package rotate
import (
"context"
"crypto/rand"
"encoding/base64"
"encoding/hex"
"encoding/json"
"net/http"
"net/http/httptest"
"strings"
"sync"
"testing"
"incredigo/internal/discover"
"incredigo/internal/vault"
)
// k8sEmu emulates the relevant slice of the kube-apiserver and ENFORCES token
// validity: a token authenticates only while its backing Secret exists. Creating a
// token Secret immediately populates a fresh token (acting as the token-controller);
// deleting a token Secret invalidates its token — so a test can prove a real cutover.
type k8sEmu struct {
mu sync.Mutex
ns string
sa string
secrets map[string]string // secret name -> token value
valid map[string]bool // token value -> alive
srv *httptest.Server
}
func newK8sEmu(t *testing.T, ns, sa, seedSecret, seedToken string) *k8sEmu {
e := &k8sEmu{
ns: ns,
sa: sa,
secrets: map[string]string{seedSecret: seedToken},
valid: map[string]bool{seedToken: true},
}
mux := http.NewServeMux()
mux.HandleFunc("/api/v1/namespaces/"+ns+"/secrets", e.handleSecrets)
mux.HandleFunc("/api/v1/namespaces/"+ns+"/secrets/", e.handleSecret)
mux.HandleFunc("/api/v1/namespaces/"+ns+"/serviceaccounts/", e.handleSA)
e.srv = httptest.NewTLSServer(mux)
t.Cleanup(e.srv.Close)
return e
}
func (e *k8sEmu) tokenOK(r *http.Request) bool {
tok := bearer(r)
e.mu.Lock()
defer e.mu.Unlock()
return e.valid[tok]
}
// handleSecrets serves POST .../secrets (create token Secret + populate token).
func (e *k8sEmu) handleSecrets(w http.ResponseWriter, r *http.Request) {
if !e.tokenOK(r) {
w.WriteHeader(http.StatusUnauthorized)
return
}
if r.Method != http.MethodPost {
w.WriteHeader(http.StatusMethodNotAllowed)
return
}
var obj map[string]any
json.NewDecoder(r.Body).Decode(&obj)
meta, _ := obj["metadata"].(map[string]any)
name, _ := meta["name"].(string)
raw := make([]byte, 24)
rand.Read(raw)
tok := "eyJ" + hex.EncodeToString(raw) // pseudo-JWT-looking token
e.mu.Lock()
e.secrets[name] = tok
e.valid[tok] = true
e.mu.Unlock()
w.WriteHeader(http.StatusCreated)
json.NewEncoder(w).Encode(map[string]any{"metadata": map[string]any{"name": name}})
}
// handleSecret serves GET/DELETE .../secrets/<name>.
func (e *k8sEmu) handleSecret(w http.ResponseWriter, r *http.Request) {
if !e.tokenOK(r) {
w.WriteHeader(http.StatusUnauthorized)
return
}
name := r.URL.Path[strings.LastIndex(r.URL.Path, "/")+1:]
switch r.Method {
case http.MethodGet:
e.mu.Lock()
tok, ok := e.secrets[name]
e.mu.Unlock()
if !ok {
w.WriteHeader(http.StatusNotFound)
return
}
json.NewEncoder(w).Encode(map[string]any{
"metadata": map[string]any{"name": name},
"data": map[string]string{"token": base64.StdEncoding.EncodeToString([]byte(tok))},
})
case http.MethodDelete:
e.mu.Lock()
if tok, ok := e.secrets[name]; ok {
delete(e.valid, tok)
delete(e.secrets, name)
}
e.mu.Unlock()
w.WriteHeader(http.StatusOK)
w.Write([]byte("{}"))
default:
w.WriteHeader(http.StatusMethodNotAllowed)
}
}
func (e *k8sEmu) handleSA(w http.ResponseWriter, r *http.Request) {
if !e.tokenOK(r) {
w.WriteHeader(http.StatusUnauthorized)
return
}
json.NewEncoder(w).Encode(map[string]any{"metadata": map[string]any{"name": e.sa, "namespace": e.ns}})
}
func (e *k8sEmu) tokenValid(tok string) bool {
e.mu.Lock()
defer e.mu.Unlock()
return e.valid[tok]
}
func TestK8sDetect(t *testing.T) {
k := &K8s{}
if !k.Detect(discover.Credential{Source: "k8s"}) {
t.Error("should detect Source=k8s")
}
if k.Detect(discover.Credential{Source: "gcp"}) {
t.Error("should not detect Source=gcp")
}
}
func TestK8sRotateRealCutover(t *testing.T) {
v := vault.New()
defer v.Purge()
ctx := context.Background()
const ns, sa, seedSecret, oldTok = "labns", "labsa", "labsa-token-seed", "eyJold0123456789"
emu := newK8sEmu(t, ns, sa, seedSecret, oldTok)
host := strings.TrimPrefix(emu.srv.URL, "https://")
oldBlob := "k8s://" + host + "/?ns=" + ns + "&sa=" + sa + "&secret=" + seedSecret + "&token=" + oldTok
cred := discover.Credential{
Source: "k8s",
Kind: discover.KindToken,
Identity: sa + " @ k8s",
Location: "imported/k8s/labsa",
Secret: v.Store([]byte(oldBlob)),
}
k := &K8s{HTTPClient: emu.srv.Client()}
if !emu.tokenValid(oldTok) {
t.Fatal("seed token should be valid at start")
}
// 1. Rotate.
newH, err := k.Rotate(ctx, cred, v)
if err != nil {
t.Fatalf("Rotate: %v", err)
}
nc, err := parseK8sCred(v, newH)
if err != nil {
t.Fatalf("parse new secret: %v", err)
}
if nc.token == oldTok {
t.Fatal("new token equals old — rotation minted nothing")
}
if nc.secret == "" || nc.secret == seedSecret {
t.Fatalf("new secret must carry a fresh token-secret name, got %q", nc.secret)
}
if !emu.tokenValid(oldTok) {
t.Fatal("old token must remain valid before revoke")
}
if !emu.tokenValid(nc.token) {
t.Fatal("new token must be valid after create")
}
// 2. Verify(new).
if err := k.Verify(ctx, newH, v); err != nil {
t.Fatalf("Verify(new): %v", err)
}
// 3. RevokeOld.
if err := k.RevokeOld(ctx, cred, v); err != nil {
t.Fatalf("RevokeOld: %v", err)
}
if emu.tokenValid(oldTok) {
t.Fatal("old token must be invalid after revoke")
}
if err := k.Verify(ctx, newH, v); err != nil {
t.Fatalf("new token 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, oldTok) || strings.Contains(f, nc.token) {
t.Errorf("token leaked into non-secret field %q", f)
}
}
}
func TestK8sRevokeRequiresSecretName(t *testing.T) {
v := vault.New()
defer v.Purge()
k := &K8s{}
cred := discover.Credential{
Source: "k8s",
Secret: v.Store([]byte("k8s://10.0.0.1:6443/?ns=n&sa=s&token=t")),
}
err := k.RevokeOld(context.Background(), cred, v)
if err == nil || !strings.Contains(err.Error(), "no recorded secret name") {
t.Fatalf("expected revoke-without-secret error, got %v", err)
}
}
func TestK8sRejectsBadSecret(t *testing.T) {
v := vault.New()
defer v.Purge()
k := &K8s{}
// missing namespace/sa
cred := discover.Credential{Source: "k8s", Secret: v.Store([]byte("k8s://10.0.0.1:6443/?token=t"))}
if _, err := k.Rotate(context.Background(), cred, v); err == nil {
t.Error("Rotate should reject a secret with no namespace/sa")
}
}
+176
View File
@@ -0,0 +1,176 @@
package rotate
import (
"bytes"
"context"
"fmt"
"net/url"
"os"
"os/exec"
"strings"
"incredigo/internal/discover"
"incredigo/internal/vault"
)
// Mongo rotates a MongoDB user's password in place, the same in-place pattern as
// Postgres/MySQL/Redis. The credential's secret is a mongodb URI
// ("mongodb://user:pw@host:port/db?authSource=admin"); rotation mints a new password
// and runs, over the OLD (authenticated) connection:
//
// db.getSiblingDB(<authSource>).changeUserPassword(<user>, <newpw>)
//
// changeUserPassword is itself the cutover — the old password stops authenticating new
// connections immediately — so RevokeOld is a no-op and the §3 sealed backup is the
// recovery path (see docs/ROTATION.md §17).
//
// SECURITY (Hard Rule #3): NO secret ever reaches argv. The connection URI passed to
// mongosh on the command line carries the host/db ONLY — never credentials. The script
// fed on stdin authenticates with the OLD password (db.auth) and sets the NEW one; both
// passwords live only in that stdin script (and the vault). The new password is hex
// ([0-9a-f]) so it cannot break out of the JS string literal. Captured output is
// scrubbed of both passwords before any error surfaces.
type Mongo struct {
Bin string // mongosh binary; defaults to "mongosh"
}
// init registers the driver. Registration only makes it available; changing a
// credential still requires `rotate --execute` AND INCREDIGO_ALLOW_EXECUTE=1.
func init() { Register(&Mongo{}) }
// Name identifies the driver in plans and audit records.
func (m *Mongo) Name() string { return "mongo" }
// Detect claims credentials a mongo scanner/seed emitted (Source == "mongo").
func (m *Mongo) Detect(c discover.Credential) bool { return c.Source == "mongo" }
func (m *Mongo) bin() string {
if m.Bin != "" {
return m.Bin
}
return "mongosh"
}
// authSource returns the DB to authenticate against / change the password in. Mongo
// stores users in authSource (default "admin" unless the URI overrides it).
func authSourceOf(u *url.URL) string {
if a := u.Query().Get("authSource"); a != "" {
return a
}
return "admin"
}
// Rotate mints a new password, applies it via changeUserPassword over the existing
// (old) connection, and returns a vault handle to the rebuilt URI.
func (m *Mongo) Rotate(ctx context.Context, c discover.Credential, v *vault.Vault) (*vault.Handle, error) {
u, err := openMongoURI(v, c.Secret)
if err != nil {
return nil, err
}
user := u.User.Username()
if user == "" {
return nil, fmt.Errorf("mongo: uri has no user")
}
oldPw, _ := u.User.Password()
newPw, err := genHex(24)
if err != nil {
return nil, err
}
as := authSourceOf(u)
// auth with the OLD password, then change to the NEW one — all on stdin.
script := fmt.Sprintf(
"db.getSiblingDB(%q).auth(%q,%q); db.getSiblingDB(%q).changeUserPassword(%q,%q); print('ROTATED');",
as, user, oldPw, as, user, newPw)
out, err := m.mongosh(ctx, u, script, oldPw, newPw)
if err != nil {
return nil, fmt.Errorf("mongo: changeUserPassword: %w", err)
}
if !strings.Contains(out, "ROTATED") {
return nil, fmt.Errorf("mongo: changeUserPassword: unexpected result")
}
nu := *u
nu.User = url.UserPassword(user, newPw)
return v.Store([]byte(nu.String())), nil
}
// Verify proves the freshly minted URI authenticates by db.auth + ping with the new
// password.
func (m *Mongo) Verify(ctx context.Context, newSecret *vault.Handle, v *vault.Vault) error {
u, err := openMongoURI(v, newSecret)
if err != nil {
return err
}
user := u.User.Username()
pw, _ := u.User.Password()
as := authSourceOf(u)
script := fmt.Sprintf(
"var ok = db.getSiblingDB(%q).auth(%q,%q); if (ok) { print('AUTH-OK'); } else { print('AUTH-FAIL'); }",
as, user, pw)
out, err := m.mongosh(ctx, u, script, pw, "")
if err != nil {
return fmt.Errorf("mongo verify: %w", err)
}
if !strings.Contains(out, "AUTH-OK") {
return fmt.Errorf("mongo verify: new password did not authenticate")
}
return nil
}
// RevokeOld is a no-op for an in-place engine: changeUserPassword in Rotate already
// invalidated the previous password. Defined to satisfy the safety-spine ordering.
func (m *Mongo) RevokeOld(ctx context.Context, c discover.Credential, v *vault.Vault) error {
return nil
}
// mongosh runs one JS script against the URI's host/port (credentials stripped from
// the URI before it reaches argv). redactA/redactB, if non-empty, are scrubbed from
// captured output before it can reach an error string.
func (m *Mongo) mongosh(ctx context.Context, u *url.URL, script, redactA, redactB string) (string, error) {
host := u.Hostname()
port := u.Port()
if port == "" {
port = "27017"
}
// Credential-free connection target: host:port/db only.
target := &url.URL{Scheme: "mongodb", Host: host + ":" + port, Path: u.Path}
cmd := exec.CommandContext(ctx, m.bin(), "--quiet", "--norc", target.String())
cmd.Env = os.Environ()
cmd.Stdin = strings.NewReader(script + "\n")
var out, errb bytes.Buffer
cmd.Stdout = &out
cmd.Stderr = &errb
err := cmd.Run()
so, se := out.String(), errb.String()
for _, r := range []string{redactA, redactB} {
if r != "" {
so = strings.ReplaceAll(so, r, "***")
se = strings.ReplaceAll(se, r, "***")
}
}
if err != nil {
return so, fmt.Errorf("%v: %s", err, strings.TrimSpace(se+" "+so))
}
return so, nil
}
// openMongoURI reads a mongodb URI secret from the vault and parses it, accepting the
// mongodb:// and mongodb+srv:// schemes. The URI string is transient and never persisted.
func openMongoURI(v *vault.Vault, h *vault.Handle) (*url.URL, error) {
buf, err := v.Open(h)
if err != nil {
return nil, err
}
u, err := url.Parse(strings.TrimSpace(string(buf.Bytes())))
if err != nil {
return nil, fmt.Errorf("mongo: parse uri: %w", err)
}
if u.Scheme != "mongodb" && u.Scheme != "mongodb+srv" {
return nil, fmt.Errorf("mongo: unexpected uri scheme %q", u.Scheme)
}
if u.User == nil {
return nil, fmt.Errorf("mongo: uri has no user:password")
}
return u, nil
}
+126
View File
@@ -0,0 +1,126 @@
package rotate
import (
"context"
"os"
"path/filepath"
"strings"
"testing"
"incredigo/internal/discover"
"incredigo/internal/vault"
)
// writeFakeMongosh writes a stub `mongosh` that emulates a single mongo user against a
// state file holding the user's CURRENT password. The stdin script uses db.auth(user,pw)
// and changeUserPassword(user,newpw); the stub parses those literal calls: auth prints
// AUTH-OK only when the password matches the state, and changeUserPassword updates the
// state only when a preceding auth matched. This lets a test prove a real cutover — after
// Rotate the OLD password must stop authenticating.
func writeFakeMongosh(t *testing.T, statePath string) string {
t.Helper()
dir := t.TempDir()
p := filepath.Join(dir, "mongosh")
// The script extracts the auth password and the (optional) new password from the
// JS on stdin using sed, compares to state, and acts accordingly.
script := `#!/usr/bin/env bash
set -uo pipefail
js="$(cat)"
cur="$(cat "` + statePath + `" 2>/dev/null || true)"
# auth("user","PW") -> capture PW from the FIRST .auth( call
authpw="$(printf '%s' "$js" | sed -n 's/.*\.auth([^,]*,"\([^"]*\)").*/\1/p' | head -n1)"
newpw="$(printf '%s' "$js" | sed -n 's/.*changeUserPassword([^,]*,"\([^"]*\)").*/\1/p' | head -n1)"
if [ "$authpw" != "$cur" ]; then
# auth failed
case "$js" in
*AUTH-OK*) echo "AUTH-FAIL";; # Verify path: report failure
*) echo "auth failed"; exit 1;; # Rotate path: error out
esac
exit 0
fi
# auth succeeded
if [ -n "$newpw" ]; then
printf '%s' "$newpw" > "` + statePath + `"
echo "ROTATED"
else
echo "AUTH-OK"
fi
exit 0
`
if err := os.WriteFile(p, []byte(script), 0o755); err != nil {
t.Fatal(err)
}
return p
}
func TestMongoDetect(t *testing.T) {
m := &Mongo{}
if !m.Detect(discover.Credential{Source: "mongo"}) {
t.Error("should detect Source=mongo")
}
if m.Detect(discover.Credential{Source: "redis"}) {
t.Error("should not detect Source=redis")
}
}
func TestMongoRotateRealCutover(t *testing.T) {
state := filepath.Join(t.TempDir(), "pw")
if err := os.WriteFile(state, []byte("oldpw"), 0o600); err != nil {
t.Fatal(err)
}
m := &Mongo{Bin: writeFakeMongosh(t, state)}
v := vault.New()
defer v.Purge()
oldURI := "mongodb://labapp:oldpw@127.0.0.1:27017/labdb?authSource=admin"
cred := discover.Credential{Source: "mongo", Identity: "mongo labapp@labdb", Secret: v.Store([]byte(oldURI))}
ctx := context.Background()
newH, err := m.Rotate(ctx, cred, v)
if err != nil {
t.Fatalf("Rotate: %v", err)
}
if cur, _ := os.ReadFile(state); string(cur) == "oldpw" {
t.Fatal("password not changed by changeUserPassword")
}
// The rebuilt URI must carry a fresh password (and same user/host/db).
nb, _ := v.Open(newH)
nu := strings.TrimSpace(string(nb.Bytes()))
if strings.Contains(nu, ":oldpw@") {
t.Fatal("rebuilt uri still carries old password")
}
if !strings.Contains(nu, "labapp:") || !strings.Contains(nu, "/labdb") {
t.Errorf("rebuilt uri lost user/db: %q", nu)
}
if err := m.Verify(ctx, newH, v); err != nil {
t.Errorf("Verify(new) should pass: %v", err)
}
// CUTOVER: the old password must be dead after the change.
if err := m.Verify(ctx, cred.Secret, v); err == nil {
t.Error("Verify(old) must fail after rotation — old password should be revoked")
} else if strings.Contains(err.Error(), "oldpw") {
t.Error("error leaked the old password")
}
if err := m.RevokeOld(ctx, cred, v); err != nil {
t.Errorf("RevokeOld (no-op) returned: %v", err)
}
}
func TestMongoRejectsBadURI(t *testing.T) {
m := &Mongo{Bin: "/bin/false"}
v := vault.New()
defer v.Purge()
// wrong scheme
cred := discover.Credential{Source: "mongo", Secret: v.Store([]byte("redis://u:p@h:6379"))}
if _, err := m.Rotate(context.Background(), cred, v); err == nil {
t.Error("Rotate should reject a non-mongodb scheme")
}
// no user
cred2 := discover.Credential{Source: "mongo", Secret: v.Store([]byte("mongodb://127.0.0.1:27017/db"))}
if _, err := m.Rotate(context.Background(), cred2, v); err == nil {
t.Error("Rotate should reject a uri with no user")
}
}
+226
View File
@@ -0,0 +1,226 @@
package rotate
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"strings"
"time"
"incredigo/internal/discover"
"incredigo/internal/vault"
)
// NPM rotates an npm registry access token via the registry token API by CREATING a
// new token, verifying it, then DELETING the old one — the canonical provider-API
// rotation pattern (create-new → verify → revoke-old):
//
// POST /-/npm/v1/tokens (Bearer old) -> {token, key}
// GET /-/whoami (Bearer new) -> {username}
// DELETE /-/npm/v1/tokens/token/<key>(Bearer old)
//
// The registry deletes tokens by their KEY (a sha512 id); the token VALUE cannot be
// mapped back to a key, so the key is recorded in the blob (incredigo writes the new
// key on every rotation, keeping the chain self-sustaining). A bare discovered token
// with no key degrades to the guided worklist for the old-token deletion.
//
// The credential's secret is a single self-contained line:
//
// npm://<host>/?user=<user>&token=<token>&key=<key>
//
// - scheme "npm" maps to https; "http"/"https" are accepted so a test can point
// at a loopback emulator.
// - <host> the registry host; "registry" (or empty) defaults to registry.npmjs.org.
// - token= the access token being rotated (Bearer auth).
// - key= the token's registry key/id — required to DELETE the old token.
// - user= optional username (Verify checks /-/whoami matches it when present).
//
// SECURITY: the token lives only in the vault blob and the Bearer header; it never
// reaches Identity/Meta/logs/argv. Response bodies carrying the new token are decoded
// straight into the rebuilt blob.
type NPM struct {
// HTTPClient is injectable for tests / custom TLS. Defaults to a 15s-timeout
// client using http.DefaultTransport.
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(&NPM{}) }
// Name identifies the driver in plans and audit records.
func (n *NPM) Name() string { return "npm" }
// Detect claims credentials tagged Source == "npm".
func (n *NPM) Detect(c discover.Credential) bool { return c.Source == "npm" }
func (n *NPM) client() *http.Client {
if n.HTTPClient != nil {
return n.HTTPClient
}
return &http.Client{Timeout: 15 * time.Second}
}
// npmSecret is the parsed credential blob. None of its fields are ever logged.
type npmSecret struct {
base string // scheme://host
user string
token string
key string
}
func parseNPMSecret(v *vault.Vault, h *vault.Handle) (npmSecret, error) {
buf, err := v.Open(h)
if err != nil {
return npmSecret{}, err
}
u, err := url.Parse(strings.TrimSpace(string(buf.Bytes())))
if err != nil {
return npmSecret{}, fmt.Errorf("npm: parse secret url: %w", err)
}
if u.Scheme != "npm" && u.Scheme != "http" && u.Scheme != "https" {
return npmSecret{}, fmt.Errorf("npm: unexpected scheme %q", u.Scheme)
}
scheme := u.Scheme
host := u.Host
if scheme == "npm" {
scheme = "https"
}
if host == "" || host == "registry" {
host = "registry.npmjs.org"
}
q := u.Query()
s := npmSecret{base: scheme + "://" + host, user: q.Get("user"), token: q.Get("token"), key: q.Get("key")}
if s.token == "" {
return npmSecret{}, fmt.Errorf("npm: secret has no token")
}
return s, nil
}
// build re-encodes an npmSecret into the single-line blob form (scheme normalised back
// to "npm" so the in-vault form stays stable).
func (s npmSecret) build() string {
host := hostOf(s.base)
if host == "registry.npmjs.org" {
host = "registry"
}
u := &url.URL{Scheme: "npm", Host: host, Path: "/"}
q := url.Values{}
if s.user != "" {
q.Set("user", s.user)
}
q.Set("token", s.token)
if s.key != "" {
q.Set("key", s.key)
}
u.RawQuery = q.Encode()
return u.String()
}
// Rotate creates a NEW registry token (authenticating with the old token) and returns
// a vault handle to a rebuilt blob carrying the new token + new key. It does not revoke
// the old token.
func (n *NPM) Rotate(ctx context.Context, c discover.Credential, v *vault.Vault) (*vault.Handle, error) {
s, err := parseNPMSecret(v, c.Secret)
if err != nil {
return nil, err
}
// readonly:false, no cidr restriction — a like-for-like automation token.
body, _ := json.Marshal(map[string]any{"readonly": false, "cidr_whitelist": []string{}})
req, err := http.NewRequestWithContext(ctx, http.MethodPost, s.base+"/-/npm/v1/tokens", bytes.NewReader(body))
if err != nil {
return nil, err
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", "Bearer "+s.token)
resp, err := n.client().Do(req)
if err != nil {
return nil, fmt.Errorf("npm: 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("npm: create token: unexpected status %s", resp.Status)
}
var created struct {
Token string `json:"token"`
Key string `json:"key"`
}
if err := json.NewDecoder(resp.Body).Decode(&created); err != nil {
return nil, fmt.Errorf("npm: decode created token: %w", err)
}
if created.Token == "" {
return nil, fmt.Errorf("npm: create token: empty token in response")
}
ns := s
ns.token = created.Token
ns.key = created.Key
return v.Store([]byte(ns.build())), nil
}
// Verify proves the newly minted token authenticates by calling GET /-/whoami with it.
func (n *NPM) Verify(ctx context.Context, newSecret *vault.Handle, v *vault.Vault) error {
s, err := parseNPMSecret(v, newSecret)
if err != nil {
return err
}
req, err := http.NewRequestWithContext(ctx, http.MethodGet, s.base+"/-/whoami", nil)
if err != nil {
return err
}
req.Header.Set("Authorization", "Bearer "+s.token)
resp, err := n.client().Do(req)
if err != nil {
return fmt.Errorf("npm verify: %w", err)
}
defer func() { io.Copy(io.Discard, resp.Body); resp.Body.Close() }()
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("npm verify: /-/whoami status %s", resp.Status)
}
var who struct {
Username string `json:"username"`
}
if err := json.NewDecoder(resp.Body).Decode(&who); err != nil {
return fmt.Errorf("npm verify: decode whoami: %w", err)
}
if who.Username == "" {
return fmt.Errorf("npm verify: token did not resolve to a user")
}
if s.user != "" && !strings.EqualFold(who.Username, s.user) {
return fmt.Errorf("npm verify: token authenticates as %q, expected %q", who.Username, s.user)
}
return nil
}
// RevokeOld deletes the OLD token by key. 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 (n *NPM) RevokeOld(ctx context.Context, c discover.Credential, v *vault.Vault) error {
s, err := parseNPMSecret(v, c.Secret)
if err != nil {
return err
}
if s.key == "" {
return fmt.Errorf("npm revoke: old token has no recorded key — delete it manually (guided)")
}
req, err := http.NewRequestWithContext(ctx, http.MethodDelete,
s.base+"/-/npm/v1/tokens/token/"+url.PathEscape(s.key), nil)
if err != nil {
return err
}
req.Header.Set("Authorization", "Bearer "+s.token)
resp, err := n.client().Do(req)
if err != nil {
return fmt.Errorf("npm 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("npm revoke: delete token status %s", resp.Status)
}
return nil
}
+219
View File
@@ -0,0 +1,219 @@
package rotate
import (
"context"
"crypto/rand"
"encoding/hex"
"encoding/json"
"net/http"
"net/http/httptest"
"strings"
"sync"
"testing"
"incredigo/internal/discover"
"incredigo/internal/vault"
)
// npmEmu is a minimal npm registry token API emulator that ENFORCES token validity:
// a token authenticates (whoami) only while it exists, POST mints a new token+key,
// and DELETE-by-key makes a token stop working — so a test can prove a real cutover
// (old token dead, new token alive).
type npmEmu struct {
mu sync.Mutex
byKey map[string]string // key -> token value
byValue map[string]string // token value -> key
user string
srv *httptest.Server
}
func newNPMEmu(t *testing.T, user, seedKey, seedValue string) *npmEmu {
e := &npmEmu{
byKey: map[string]string{seedKey: seedValue},
byValue: map[string]string{seedValue: seedKey},
user: user,
}
mux := http.NewServeMux()
mux.HandleFunc("/-/whoami", e.handleWhoami)
mux.HandleFunc("/-/npm/v1/tokens", e.handleCreate)
mux.HandleFunc("/-/npm/v1/tokens/token/", e.handleDelete)
e.srv = httptest.NewTLSServer(mux)
t.Cleanup(e.srv.Close)
return e
}
func (e *npmEmu) valid(token string) bool {
e.mu.Lock()
defer e.mu.Unlock()
_, ok := e.byValue[token]
return ok
}
// bearer returns the token from an "Authorization: Bearer <v>" header.
func bearer(r *http.Request) string {
h := r.Header.Get("Authorization")
if strings.HasPrefix(h, "Bearer ") {
return strings.TrimPrefix(h, "Bearer ")
}
return ""
}
func (e *npmEmu) handleWhoami(w http.ResponseWriter, r *http.Request) {
if !e.valid(bearer(r)) {
w.WriteHeader(http.StatusUnauthorized)
return
}
json.NewEncoder(w).Encode(map[string]any{"username": e.user})
}
func (e *npmEmu) handleCreate(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
w.WriteHeader(http.StatusMethodNotAllowed)
return
}
if !e.valid(bearer(r)) {
w.WriteHeader(http.StatusUnauthorized)
return
}
raw := make([]byte, 20)
rand.Read(raw)
val := "npm_" + hex.EncodeToString(raw)
keyRaw := make([]byte, 16)
rand.Read(keyRaw)
key := hex.EncodeToString(keyRaw)
e.mu.Lock()
e.byKey[key] = val
e.byValue[val] = key
e.mu.Unlock()
w.WriteHeader(http.StatusCreated)
json.NewEncoder(w).Encode(map[string]any{"token": val, "key": key})
}
func (e *npmEmu) handleDelete(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodDelete {
w.WriteHeader(http.StatusMethodNotAllowed)
return
}
if !e.valid(bearer(r)) {
w.WriteHeader(http.StatusUnauthorized)
return
}
parts := strings.Split(strings.Trim(r.URL.Path, "/"), "/")
key := parts[len(parts)-1]
e.mu.Lock()
if v, ok := e.byKey[key]; ok {
delete(e.byValue, v)
delete(e.byKey, key)
}
e.mu.Unlock()
w.WriteHeader(http.StatusOK)
}
func TestNPMDetect(t *testing.T) {
n := &NPM{}
if !n.Detect(discover.Credential{Source: "npm"}) {
t.Error("should detect Source=npm")
}
if n.Detect(discover.Credential{Source: "gitea"}) {
t.Error("should not detect Source=gitea")
}
}
func TestNPMRotateRealCutover(t *testing.T) {
v := vault.New()
defer v.Purge()
ctx := context.Background()
const user, seedKey, oldTok = "labpub", "seedkey0123456789", "npm_0123456789abcdef0123456789abcdef01234567"
emu := newNPMEmu(t, user, seedKey, oldTok)
host := strings.TrimPrefix(emu.srv.URL, "https://")
// npm:// scheme normalises to https, matching the TLS emulator; the rebuilt blob
// (which Verify re-parses) uses the same npm→https mapping.
oldBlob := "npm://" + host + "/?user=" + user + "&token=" + oldTok + "&key=" + seedKey
cred := discover.Credential{
Source: "npm",
Kind: discover.KindToken,
Identity: user + " @ npm",
Location: "imported/npm/labpub",
Secret: v.Store([]byte(oldBlob)),
}
n := &NPM{HTTPClient: emu.srv.Client()}
if !emu.valid(oldTok) {
t.Fatal("seed token should be valid at start")
}
// 1. Rotate — create a new token (old still valid).
newH, err := n.Rotate(ctx, cred, v)
if err != nil {
t.Fatalf("Rotate: %v", err)
}
ns, err := parseNPMSecret(v, newH)
if err != nil {
t.Fatalf("parse new secret: %v", err)
}
if ns.token == oldTok {
t.Fatal("new token equals old — rotation minted nothing")
}
if ns.key == "" || ns.key == seedKey {
t.Fatalf("new secret must carry a fresh key, got %q", ns.key)
}
if !emu.valid(oldTok) {
t.Fatal("old token must remain valid before revoke")
}
if !emu.valid(ns.token) {
t.Fatal("new token must be valid after create")
}
// 2. Verify(new) via the driver.
if err := n.Verify(ctx, newH, v); err != nil {
t.Fatalf("Verify(new): %v", err)
}
// 3. RevokeOld — delete the old token by key.
if err := n.RevokeOld(ctx, cred, v); err != nil {
t.Fatalf("RevokeOld: %v", err)
}
// Cutover assertions: old dead, new alive.
if emu.valid(oldTok) {
t.Fatal("old token must be invalid after revoke")
}
if err := n.Verify(ctx, newH, v); err != nil {
t.Fatalf("new token must still authenticate after revoke: %v", err)
}
// Leak check: token values must not appear in non-secret credential fields.
for _, f := range []string{cred.Identity, cred.Source, cred.Location, string(cred.Kind)} {
if strings.Contains(f, oldTok) || strings.Contains(f, ns.token) {
t.Errorf("token leaked into non-secret field %q", f)
}
}
}
func TestNPMRevokeRequiresKey(t *testing.T) {
v := vault.New()
defer v.Purge()
n := &NPM{}
// Blob with token but no key= → RevokeOld must refuse (guided), not silently pass.
cred := discover.Credential{
Source: "npm",
Secret: v.Store([]byte("npm://registry.npmjs.org/?user=bob&token=npm_abc123")),
}
err := n.RevokeOld(context.Background(), cred, v)
if err == nil || !strings.Contains(err.Error(), "no recorded key") {
t.Fatalf("expected revoke-without-key error, got %v", err)
}
}
func TestNPMRejectsBadSecret(t *testing.T) {
v := vault.New()
defer v.Purge()
n := &NPM{}
// no token
cred := discover.Credential{Source: "npm", Secret: v.Store([]byte("npm://registry.npmjs.org/?user=bob"))}
if _, err := n.Rotate(context.Background(), cred, v); err == nil {
t.Error("Rotate should reject a secret with no token")
}
}
+6
View File
@@ -63,6 +63,12 @@ var proofLevels = map[string]ProofLevel{
"cloudflare": ProofMockOnly, // httptest emulator; no self-host
"ghactions": ProofMockOnly, // httptest emulator; no self-host
"gitlab": ProofMockOnly, // httptest emulator; GitLab CE too heavy for the VM
"mongo": ProofMockOnly, // fake-mongosh stub; real-MongoDB VM POC not yet run
"npm": ProofMockOnly, // httptest emulator; real registry never hit
"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
"k8s": ProofMockOnly, // httptest apiserver emulator; real k3s POC not yet run
}
// ProofLevelOf returns the recorded proof level for a driver name. Unknown or
+218
View File
@@ -0,0 +1,218 @@
package rotate
import (
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"strings"
"time"
"incredigo/internal/discover"
"incredigo/internal/vault"
)
// Twilio rotates a Twilio API Key (SK...) 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 /2010-04-01/Accounts/<AC>/Keys.json (Basic old-key) -> {sid, secret}
// GET /2010-04-01/Accounts/<AC>/Keys/<new>.json (Basic new-key) -> {sid}
// DELETE /2010-04-01/Accounts/<AC>/Keys/<old>.json (Basic old-key)
//
// A Twilio API key authenticates as Basic auth username=<KeySid> password=<KeySecret>;
// the secret is returned by Twilio only once at create time. The credential's secret is
// a single self-contained line:
//
// twilio://<host>/?account=<AC...>&sid=<SK...>&secret=<secret>[&endpoint=<url>]
//
// - scheme "twilio" maps to https; "http"/"https" are accepted so a test can point
// at a loopback emulator.
// - <host> API host; "twilio" (or empty) defaults to api.twilio.com.
// - account= the Account SID (AC...) — non-secret, names the URL path.
// - sid= the API Key SID (SK...) — non-secret Basic-auth username.
// - secret= the API Key secret — Basic-auth password (rotated).
//
// SECURITY: the secret lives only in the vault blob and the Basic-auth header; it never
// reaches Identity/Meta/logs/argv. The new secret is decoded straight from the create
// response into the rebuilt blob.
type Twilio 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(&Twilio{}) }
// Name identifies the driver in plans and audit records.
func (tw *Twilio) Name() string { return "twilio" }
// Detect claims credentials tagged Source == "twilio".
func (tw *Twilio) Detect(c discover.Credential) bool { return c.Source == "twilio" }
func (tw *Twilio) client() *http.Client {
if tw.HTTPClient != nil {
return tw.HTTPClient
}
return &http.Client{Timeout: 15 * time.Second}
}
// twilioSecret is the parsed credential blob. None of its fields are ever logged.
type twilioSecret struct {
base string // scheme://host
account string // AC...
sid string // SK...
secret string
}
func parseTwilioSecret(v *vault.Vault, h *vault.Handle) (twilioSecret, error) {
buf, err := v.Open(h)
if err != nil {
return twilioSecret{}, err
}
u, err := url.Parse(strings.TrimSpace(string(buf.Bytes())))
if err != nil {
return twilioSecret{}, fmt.Errorf("twilio: parse secret url: %w", err)
}
if u.Scheme != "twilio" && u.Scheme != "http" && u.Scheme != "https" {
return twilioSecret{}, fmt.Errorf("twilio: unexpected scheme %q", u.Scheme)
}
scheme := u.Scheme
host := u.Host
if scheme == "twilio" {
scheme = "https"
}
if host == "" || host == "twilio" {
host = "api.twilio.com"
}
q := u.Query()
s := twilioSecret{base: scheme + "://" + host, account: q.Get("account"), sid: q.Get("sid"), secret: q.Get("secret")}
if s.account == "" {
return twilioSecret{}, fmt.Errorf("twilio: secret has no account sid")
}
if s.sid == "" || s.secret == "" {
return twilioSecret{}, fmt.Errorf("twilio: secret missing key sid or secret")
}
return s, nil
}
// build re-encodes a twilioSecret into the single-line blob form (scheme normalised
// back to "twilio").
func (s twilioSecret) build() string {
host := hostOf(s.base)
if host == "api.twilio.com" {
host = "twilio"
}
u := &url.URL{Scheme: "twilio", Host: host, Path: "/"}
q := url.Values{}
q.Set("account", s.account)
q.Set("sid", s.sid)
q.Set("secret", s.secret)
u.RawQuery = q.Encode()
return u.String()
}
func (s twilioSecret) keysURL(sid string) string {
base := s.base + "/2010-04-01/Accounts/" + url.PathEscape(s.account) + "/Keys"
if sid != "" {
return base + "/" + url.PathEscape(sid) + ".json"
}
return base + ".json"
}
// Rotate creates a NEW API key (authenticated by the OLD key) and returns a vault
// handle to a rebuilt blob carrying the new sid + secret. It does not delete the old key.
func (tw *Twilio) Rotate(ctx context.Context, c discover.Credential, v *vault.Vault) (*vault.Handle, error) {
s, err := parseTwilioSecret(v, c.Secret)
if err != nil {
return nil, err
}
form := url.Values{}
form.Set("FriendlyName", "incredigo-rotated")
req, err := http.NewRequestWithContext(ctx, http.MethodPost, s.keysURL(""), strings.NewReader(form.Encode()))
if err != nil {
return nil, err
}
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
req.SetBasicAuth(s.sid, s.secret)
resp, err := tw.client().Do(req)
if err != nil {
return nil, fmt.Errorf("twilio: 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("twilio: create key: unexpected status %s", resp.Status)
}
var created struct {
Sid string `json:"sid"`
Secret string `json:"secret"`
}
if err := json.NewDecoder(resp.Body).Decode(&created); err != nil {
return nil, fmt.Errorf("twilio: decode created key: %w", err)
}
if created.Sid == "" || created.Secret == "" {
return nil, fmt.Errorf("twilio: create key: empty sid or secret in response")
}
ns := s
ns.sid = created.Sid
ns.secret = created.Secret
return v.Store([]byte(ns.build())), nil
}
// Verify proves the newly minted key authenticates by GETting its own Key resource.
func (tw *Twilio) Verify(ctx context.Context, newSecret *vault.Handle, v *vault.Vault) error {
s, err := parseTwilioSecret(v, newSecret)
if err != nil {
return err
}
req, err := http.NewRequestWithContext(ctx, http.MethodGet, s.keysURL(s.sid), nil)
if err != nil {
return err
}
req.SetBasicAuth(s.sid, s.secret)
resp, err := tw.client().Do(req)
if err != nil {
return fmt.Errorf("twilio verify: %w", err)
}
defer func() { io.Copy(io.Discard, resp.Body); resp.Body.Close() }()
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("twilio verify: get key status %s", resp.Status)
}
var got struct {
Sid string `json:"sid"`
}
if err := json.NewDecoder(resp.Body).Decode(&got); err != nil {
return fmt.Errorf("twilio verify: decode key: %w", err)
}
if got.Sid != s.sid {
return fmt.Errorf("twilio verify: key sid mismatch")
}
return nil
}
// RevokeOld deletes the OLD API key by its sid. 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 (tw *Twilio) RevokeOld(ctx context.Context, c discover.Credential, v *vault.Vault) error {
s, err := parseTwilioSecret(v, c.Secret)
if err != nil {
return err
}
req, err := http.NewRequestWithContext(ctx, http.MethodDelete, s.keysURL(s.sid), nil)
if err != nil {
return err
}
req.SetBasicAuth(s.sid, s.secret)
resp, err := tw.client().Do(req)
if err != nil {
return fmt.Errorf("twilio 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("twilio revoke: delete key status %s", resp.Status)
}
return nil
}
+184
View File
@@ -0,0 +1,184 @@
package rotate
import (
"context"
"crypto/rand"
"encoding/hex"
"encoding/json"
"net/http"
"net/http/httptest"
"strings"
"sync"
"testing"
"incredigo/internal/discover"
"incredigo/internal/vault"
)
// twilioEmu emulates the Twilio API Keys resource and ENFORCES key validity via Basic
// auth: a key (sid+secret) 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 twilioEmu struct {
mu sync.Mutex
secrets map[string]string // sid -> secret
account string
srv *httptest.Server
}
func newTwilioEmu(t *testing.T, account, seedSid, seedSecret string) *twilioEmu {
e := &twilioEmu{
secrets: map[string]string{seedSid: seedSecret},
account: account,
}
mux := http.NewServeMux()
mux.HandleFunc("/2010-04-01/Accounts/", e.handle)
e.srv = httptest.NewTLSServer(mux)
t.Cleanup(e.srv.Close)
return e
}
func (e *twilioEmu) authed(r *http.Request) bool {
u, p, ok := r.BasicAuth()
if !ok {
return false
}
e.mu.Lock()
defer e.mu.Unlock()
s, exists := e.secrets[u]
return exists && s == p
}
func (e *twilioEmu) handle(w http.ResponseWriter, r *http.Request) {
if !e.authed(r) {
w.WriteHeader(http.StatusUnauthorized)
return
}
// Path: /2010-04-01/Accounts/<AC>/Keys[.json | /<sid>.json]
tail := strings.TrimSuffix(r.URL.Path[strings.Index(r.URL.Path, "/Keys"):], ".json")
switch {
case r.Method == http.MethodPost && tail == "/Keys":
raw := make([]byte, 16)
rand.Read(raw)
sid := "SK" + hex.EncodeToString(raw)
secRaw := make([]byte, 16)
rand.Read(secRaw)
secret := hex.EncodeToString(secRaw)
e.mu.Lock()
e.secrets[sid] = secret
e.mu.Unlock()
w.WriteHeader(http.StatusCreated)
json.NewEncoder(w).Encode(map[string]any{"sid": sid, "secret": secret, "friendly_name": "incredigo-rotated"})
case r.Method == http.MethodGet && strings.HasPrefix(tail, "/Keys/"):
sid := strings.TrimPrefix(tail, "/Keys/")
e.mu.Lock()
_, ok := e.secrets[sid]
e.mu.Unlock()
if !ok {
w.WriteHeader(http.StatusNotFound)
return
}
json.NewEncoder(w).Encode(map[string]any{"sid": sid, "friendly_name": "incredigo-rotated"})
case r.Method == http.MethodDelete && strings.HasPrefix(tail, "/Keys/"):
sid := strings.TrimPrefix(tail, "/Keys/")
e.mu.Lock()
delete(e.secrets, sid)
e.mu.Unlock()
w.WriteHeader(http.StatusNoContent)
default:
w.WriteHeader(http.StatusNotFound)
}
}
func (e *twilioEmu) valid(sid, secret string) bool {
e.mu.Lock()
defer e.mu.Unlock()
s, ok := e.secrets[sid]
return ok && s == secret
}
func TestTwilioDetect(t *testing.T) {
tw := &Twilio{}
if !tw.Detect(discover.Credential{Source: "twilio"}) {
t.Error("should detect Source=twilio")
}
if tw.Detect(discover.Credential{Source: "aws"}) {
t.Error("should not detect Source=aws")
}
}
func TestTwilioRotateRealCutover(t *testing.T) {
v := vault.New()
defer v.Purge()
ctx := context.Background()
const account, seedSid, oldSecret = "AClab0123456789", "SKseed0123456789", "oldsecret0123456789abcdef"
emu := newTwilioEmu(t, account, seedSid, oldSecret)
host := strings.TrimPrefix(emu.srv.URL, "https://")
oldBlob := "twilio://" + host + "/?account=" + account + "&sid=" + seedSid + "&secret=" + oldSecret
cred := discover.Credential{
Source: "twilio",
Kind: discover.KindToken,
Identity: account + " @ twilio",
Location: "imported/twilio/labkey",
Secret: v.Store([]byte(oldBlob)),
}
tw := &Twilio{HTTPClient: emu.srv.Client()}
if !emu.valid(seedSid, oldSecret) {
t.Fatal("seed key should be valid at start")
}
// 1. Rotate.
newH, err := tw.Rotate(ctx, cred, v)
if err != nil {
t.Fatalf("Rotate: %v", err)
}
ns, err := parseTwilioSecret(v, newH)
if err != nil {
t.Fatalf("parse new secret: %v", err)
}
if ns.sid == seedSid || ns.secret == oldSecret {
t.Fatal("new key equals old — rotation minted nothing")
}
if !emu.valid(seedSid, oldSecret) {
t.Fatal("old key must remain valid before revoke")
}
if !emu.valid(ns.sid, ns.secret) {
t.Fatal("new key must be valid after create")
}
// 2. Verify(new).
if err := tw.Verify(ctx, newH, v); err != nil {
t.Fatalf("Verify(new): %v", err)
}
// 3. RevokeOld.
if err := tw.RevokeOld(ctx, cred, v); err != nil {
t.Fatalf("RevokeOld: %v", err)
}
if emu.valid(seedSid, oldSecret) {
t.Fatal("old key must be invalid after revoke")
}
if err := tw.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, oldSecret) || strings.Contains(f, ns.secret) {
t.Errorf("secret leaked into non-secret field %q", f)
}
}
}
func TestTwilioRejectsBadSecret(t *testing.T) {
v := vault.New()
defer v.Purge()
tw := &Twilio{}
// missing account
cred := discover.Credential{Source: "twilio", Secret: v.Store([]byte("twilio://api.twilio.com/?sid=SKx&secret=y"))}
if _, err := tw.Rotate(context.Background(), cred, v); err == nil {
t.Error("Rotate should reject a secret with no account")
}
}