Skip to content

Agent Mesh

fix: rework re-enrollment per review, add bootstrap token revocation

Fernando Marinoa876e9cd86ed
diff --git a/internal/console/public/app.js b/internal/console/public/app.js
index 65295722..46ac4970 100644
--- a/internal/console/public/app.js
+++ b/internal/console/public/app.js
@@ -699,12 +699,19 @@ function renderRouterTopography(routers) {
function renderBootstrapTokensTable(tokens) {
const tbody = document.getElementById('table-bootstrap');
if (tokens.length === 0) {
- tbody.innerHTML = `<tr><td colspan="5" class="text-center">No active bootstrap tokens found</td></tr>`;
+ tbody.innerHTML = `<tr><td colspan="7" class="text-center">No active bootstrap tokens found</td></tr>`;
return;
}
tbody.innerHTML = tokens.map(token => {
const expiresAt = token.ExpiresAt && !token.ExpiresAt.startsWith('0001') ? new Date(token.ExpiresAt).toLocaleString() : 'Never';
+ const revoked = !!token.RevokedAt;
+ const status = revoked
+ ? `<span class="badge badge-rejected">Revoked</span>`
+ : `<span class="badge badge-approved">Active</span>`;
+ const action = revoked
+ ? '-'
+ : `<button class="btn btn-sm btn-danger" onclick="revokeBootstrapToken('${escapeHTML(token.ID)}')">Revoke</button>`;
return `
<tr>
<td><code>${escapeHTML(String(token.ID || '').substring(0, 8))}...</code></td>
@@ -712,11 +719,19 @@ function renderBootstrapTokensTable(tokens) {
<td><code>${escapeHTML(token.OwnerID || '-')}</code></td>
<td>${escapeHTML(String(token.UsagesCount))} / ${escapeHTML(String(token.MaxUsages))}</td>
<td>${escapeHTML(expiresAt)}</td>
+ <td>${status}</td>
+ <td>${action}</td>
</tr>
`;
}).join('');
}
+window.revokeBootstrapToken = function(id) {
+ if (confirm('Revoke this bootstrap token? It will no longer be usable to enroll or re-enroll any node.')) {
+ actionRequest(`api/admin/bootstrap-tokens/${id}`, 'DELETE').then(loadData).catch(() => {});
+ }
+};
+
window.generateBootstrapToken = async function() {
const role = document.getElementById('token-role').value;
const owner_id = document.getElementById('token-owner').value.trim();
diff --git a/internal/console/public/index.html b/internal/console/public/index.html
index ec55b739..708e50d5 100644
--- a/internal/console/public/index.html
+++ b/internal/console/public/index.html
@@ -335,10 +335,12 @@
<th>Owner</th>
<th>Usages</th>
<th>Expires</th>
+ <th>Status</th>
+ <th>Actions</th>
</tr>
</thead>
<tbody id="table-bootstrap">
- <tr><td colspan="5" class="text-center">Loading...</td></tr>
+ <tr><td colspan="7" class="text-center">Loading...</td></tr>
</tbody>
</table>
</div>
diff --git a/internal/controlplane/server.go b/internal/controlplane/server.go
index ea1155b5..957dc32e 100644
--- a/internal/controlplane/server.go
+++ b/internal/controlplane/server.go
@@ -214,6 +214,7 @@ func (s *Server) RegisterRoutes(mux *http.ServeMux) {
mux.HandleFunc("/refresh", s.HandleRefresh)
mux.HandleFunc("/nodes/catalog", s.HandleNodeCatalog)
mux.HandleFunc("/admin/bootstrap-tokens", s.HandleAdminBootstrapTokens)
+ mux.HandleFunc("/admin/bootstrap-tokens/", s.HandleAdminBootstrapTokenAction)
mux.HandleFunc("/admin/enrollments", s.HandleAdminEnrollments)
mux.HandleFunc("/admin/enrollments/", s.HandleAdminEnrollmentAction)
mux.HandleFunc("/admin/revoke", s.HandleAdminRevoke)
@@ -1237,6 +1238,12 @@ func (s *Server) HandleEnroll(w http.ResponseWriter, r *http.Request) {
return
}
+ if tokenRecord.IsRevoked() {
+ logger.Warnw("Revoked bootstrap token used", "peer_id", req.PeerId, "token_id", tokenRecord.ID)
+ s.writeEnrollError(w, api.EnrollmentStatus_ENROLLMENT_STATUS_REJECTED, "Bootstrap token revoked")
+ return
+ }
+
if tokenRecord.UsagesCount >= tokenRecord.MaxUsages {
logger.Warnw("Max usages exceeded for bootstrap token", "peer_id", req.PeerId, "token_id", tokenRecord.ID)
s.writeEnrollError(w, api.EnrollmentStatus_ENROLLMENT_STATUS_REJECTED, "Bootstrap token max usages exceeded")
@@ -1305,9 +1312,14 @@ func (s *Server) HandleEnroll(w http.ResponseWriter, r *http.Request) {
// Request already exists, return status
var resp *api.BootstrapEnrollResponse
if existingReq.Status == api.EnrollmentStatus_ENROLLMENT_STATUS_APPROVED {
- biscuitToken, resolvedAt, refreshErr := s.refreshExpiredBootstrapBiscuit(ctx, existingReq)
+ biscuitToken, resolvedAt, refreshErr := s.remintApprovedBootstrapBiscuit(ctx, existingReq, tokenRecord)
if refreshErr != nil {
- logger.Errorf("Failed to refresh expired enrollment biscuit: %v", refreshErr)
+ if errors.Is(refreshErr, storage.ErrNodeBanned) || errors.Is(refreshErr, storage.ErrNodeSessionExpired) || errors.Is(refreshErr, errBootstrapRoleMismatch) {
+ logger.Warnw("Refused bootstrap re-enrollment", "peer_id", req.PeerId, "error", refreshErr)
+ s.writeEnrollError(w, api.EnrollmentStatus_ENROLLMENT_STATUS_REJECTED, "Enrollment no longer valid: "+refreshErr.Error())
+ return
+ }
+ logger.Errorf("Failed to re-mint approved enrollment biscuit: %v", refreshErr)
http.Error(w, "Internal server error", http.StatusInternalServerError)
return
}
@@ -1522,13 +1534,15 @@ func (s *Server) HandleEnrollStatus(w http.ResponseWriter, r *http.Request) {
var resp *api.BootstrapEnrollResponse
if enrollReq.Status == api.EnrollmentStatus_ENROLLMENT_STATUS_APPROVED {
- biscuitToken, resolvedAt, refreshErr := s.refreshExpiredBootstrapBiscuit(ctx, enrollReq)
- if refreshErr != nil {
- logger.Errorf("Failed to refresh expired enrollment biscuit: %v", refreshErr)
- http.Error(w, "Internal server error", http.StatusInternalServerError)
- return
- }
- resp, err = s.buildApprovedBootstrapEnrollResponse(ctx, biscuitToken, resolvedAt)
+ // A GET status poll must not mint credentials: unlike /enroll, this
+ // endpoint checks neither a live bootstrap token nor the node
+ // record's ban/admission state (banNode only flips nodes.banned; the
+ // enrollment request stays APPROVED), so a banned peer or one that
+ // lost its bootstrap token could otherwise poll forever for a fresh,
+ // verifying biscuit using nothing but its own private key. Re-minting
+ // belongs only on /enroll, where a currently-valid bootstrap token is
+ // the operator's lever - see remintApprovedBootstrapBiscuit.
+ resp, err = s.buildApprovedBootstrapEnrollResponse(ctx, enrollReq.BiscuitToken, enrollReq.ResolvedAt)
if err != nil {
logger.Errorf("Failed to build approved response: %v", err)
http.Error(w, "Internal server error", http.StatusInternalServerError)
@@ -1700,6 +1714,43 @@ func (s *Server) HandleAdminBootstrapTokens(w http.ResponseWriter, r *http.Reque
})
}
+// HandleAdminBootstrapTokenAction HTTP DELETE `/admin/bootstrap-tokens/{id}`
+// soft-revokes a token (see storage.BootstrapToken.RevokedAt): idempotent,
+// and 404 only when the id names no token at all, per #368.
+func (s *Server) HandleAdminBootstrapTokenAction(w http.ResponseWriter, r *http.Request) {
+ if !s.checkAdminAuth(w, r) {
+ return
+ }
+
+ if r.Method != http.MethodDelete {
+ http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
+ return
+ }
+
+ id := strings.TrimPrefix(r.URL.Path, "/admin/bootstrap-tokens/")
+ if id == "" || strings.Contains(id, "/") {
+ http.Error(w, "Not found", http.StatusNotFound)
+ return
+ }
+
+ ctx := r.Context()
+ if _, err := s.store.GetBootstrapToken(ctx, id); err == storage.ErrNotFound {
+ http.Error(w, "Bootstrap token not found", http.StatusNotFound)
+ return
+ } else if err != nil {
+ logger.Errorf("Failed to look up bootstrap token %s: %v", id, err)
+ http.Error(w, "Internal server error", http.StatusInternalServerError)
+ return
+ }
+
+ if err := s.store.RevokeBootstrapToken(ctx, id); err != nil {
+ logger.Errorf("Failed to revoke bootstrap token %s: %v", id, err)
+ http.Error(w, "Internal server error", http.StatusInternalServerError)
+ return
+ }
+ w.WriteHeader(http.StatusNoContent)
+}
+
// HandleAdminEnrollments HTTP GET `/admin/enrollments`
func (s *Server) HandleAdminEnrollments(w http.ResponseWriter, r *http.Request) {
if !s.checkAdminAuth(w, r) {
@@ -1929,40 +1980,52 @@ func (s *Server) HandleAdminRevoke(w http.ResponseWriter, r *http.Request) {
_, _ = w.Write(respData)
}
-// refreshExpiredBootstrapBiscuit returns an already-approved enrollment
-// request's biscuit unchanged if it is still within its TTL, or mints and
-// persists a fresh one otherwise.
+// errBootstrapRoleMismatch guards remintApprovedBootstrapBiscuit's role
+// check: the bootstrap token presented at /enroll must match the role the
+// peer was actually admitted under, or a stale or reused token could re-mint
+// a biscuit for a role the node's enrollment record never granted it.
+var errBootstrapRoleMismatch = errors.New("bootstrap token role does not match enrolled node role")
+
+// remintApprovedBootstrapBiscuit re-mints and persists a fresh biscuit for an
+// already-approved bootstrap enrollment request, sourcing role and labels
+// from the enrolled node record - never from the request or the bootstrap
+// token - since that record is what both approval paths wrote before ever
+// returning this enrollment request as APPROVED.
//
-// Bootstrap peers (routers and other non-OIDC nodes) only ever call /refresh
-// proactively while already running; they have no equivalent of a stored
-// refresh token to fall back on across a restart. If a peer's data directory
-// is idle for longer than BiscuitTTL and then restarts, its old biscuit is
-// already expired by the time it re-enrolls, and re-enrolling just hits the
-// "existing enrollment request" branch below, which used to hand back that
-// same expired token every time -- an approve-fails-approve-fails loop with
-// no way out short of an operator manually deleting the enrollment record.
-func (s *Server) refreshExpiredBootstrapBiscuit(ctx context.Context, existingReq *storage.EnrollmentRequest) ([]byte, *time.Time, error) {
- if existingReq.ResolvedAt != nil && existingReq.ResolvedAt.Add(s.config.BiscuitTTL).After(time.Now()) {
- return existingReq.BiscuitToken, existingReq.ResolvedAt, nil
- }
-
+// This runs unconditionally on every hit of the existing-request branch, not
+// behind a "has the stored token aged past BiscuitTTL" check: that heuristic
+// missed a router that refreshed (B1->B2 in the node record) and then
+// restarted inside the TTL - it would get stale B1 back from this request and
+// still 401 on every future /refresh - and it missed a biscuit that is still
+// within its TTL but was signed by a key retired past its rotation grace
+// period. Always re-minting here sidesteps all three by construction. It is
+// safe to do unconditionally because the only caller, HandleEnroll's
+// existing-request branch, already sits behind a fresh proof-of-possession
+// signature and a currently-valid, non-exhausted bootstrap token - an
+// operator-controlled lever. HandleEnrollStatus (a GET status poll) must
+// never call this: it has no equivalent gate, only a signature check, so
+// minting there would hand any peer a forever-renewable credential.
+func (s *Server) remintApprovedBootstrapBiscuit(ctx context.Context, existingReq *storage.EnrollmentRequest, tokenRecord *storage.BootstrapToken) ([]byte, *time.Time, error) {
pID, err := peer.Decode(existingReq.PeerID)
if err != nil {
return nil, nil, fmt.Errorf("invalid stored peer id %q: %w", existingReq.PeerID, err)
}
- // The enrolled node record (not the bootstrap token, which may since have
- // been consumed or pruned) is the durable source of the role and labels
- // to re-mint -- both approval paths write it before ever returning this
- // enrollment request as APPROVED. Look it up by pID.String() (canonical),
- // not the raw existingReq.PeerID, matching every other GetNode call site
- // (e.g. HandleRefresh) - the two need not be byte-identical strings for
- // the same peer.
+ // Look up by pID.String() (canonical), not the raw existingReq.PeerID,
+ // matching every other GetNode call site (e.g. HandleRefresh) - the two
+ // need not be byte-identical strings for the same peer.
nodeRecord, err := s.store.GetNode(ctx, pID.String())
if err != nil {
return nil, nil, fmt.Errorf("failed to retrieve enrolled node %s: %w", pID, err)
}
+ if tokenRecord.Role != nodeRecord.Role {
+ return nil, nil, fmt.Errorf("%w: token role %q, node role %q", errBootstrapRoleMismatch, tokenRecord.Role, nodeRecord.Role)
+ }
+ if err := nodeRecord.CheckAdmission(time.Now()); err != nil {
+ return nil, nil, err
+ }
+
privKey, _, err := s.store.GetCurrentKey(ctx)
if err != nil {
return nil, nil, fmt.Errorf("failed to retrieve signing key: %w", err)
@@ -1991,6 +2054,15 @@ func (s *Server) refreshExpiredBootstrapBiscuit(ctx context.Context, existingReq
return nil, nil, fmt.Errorf("failed to persist refreshed node record: %w", err)
}
+ // Re-minting consumes a use of the bootstrap token, the same as the
+ // original enrollment did - it is the operator's lever on how many times
+ // this can happen, per #367/#368. A failure here only means the usage
+ // counter under-counts; it must not block the peer from getting its
+ // (already persisted) fresh biscuit.
+ if err := s.store.IncrementBootstrapTokenUsage(ctx, tokenRecord.ID); err != nil {
+ logger.Errorf("Failed to increment bootstrap token usage on re-mint for %s: %v", pID, err)
+ }
+
resolvedAt := time.Now()
return biscuitBytes, &resolvedAt, nil
}
diff --git a/internal/controlplane/server_test.go b/internal/controlplane/server_test.go
index 5d90248b..dd3465f0 100644
--- a/internal/controlplane/server_test.go
+++ b/internal/controlplane/server_test.go
@@ -17,10 +17,12 @@ package controlplane
import (
"bytes"
"context"
+ "crypto/ed25519"
"crypto/rand"
"crypto/rsa"
"encoding/base64"
"encoding/json"
+ "fmt"
"io"
"math/big"
"net/http"
@@ -1093,8 +1095,8 @@ func TestBootstrapEnrollmentRequiresProofOfPossession(t *testing.T) {
}
// POST /enroll is gated the same way: the existing-enrollment branch
- // re-serves the stored biscuit, so a bootstrap token holder who is not
- // the peer must never reach it.
+ // re-mints a fresh biscuit for the peer, so a bootstrap token holder who
+ // is not the peer must never reach it.
postEnroll := func(name string, payload []byte) *api.BootstrapEnrollResponse {
t.Helper()
resp, err := client.Post(baseURL+"/enroll", "application/x-protobuf", bytes.NewReader(payload))
@@ -1155,8 +1157,18 @@ func TestBootstrapEnrollmentRequiresProofOfPossession(t *testing.T) {
ChallengeSignature: retrySig,
})
r := postEnroll("enrollee retry", retryData)
- if r.Status != api.EnrollmentStatus_ENROLLMENT_STATUS_APPROVED || !bytes.Equal(r.BiscuitToken, enrollResp.BiscuitToken) {
- t.Fatalf("enrollee retry did not return its own biscuit: %v", r.Status)
+ if r.Status != api.EnrollmentStatus_ENROLLMENT_STATUS_APPROVED {
+ t.Fatalf("enrollee retry did not return APPROVED: %v", r.Status)
+ }
+ if len(r.BiscuitToken) == 0 {
+ t.Fatal("enrollee retry returned an empty biscuit")
+ }
+ // Re-minting is unconditional now (see remintApprovedBootstrapBiscuit), so
+ // the retry gets a freshly minted biscuit rather than the original
+ // byte-for-byte -- it must still verify for the same peer.
+ cpPubKey := ed25519.PublicKey(enrollResp.ControlPlanePublicKey)
+ if _, _, err := identity.VerifyBiscuitAndGetKey(r.BiscuitToken, pID, []ed25519.PublicKey{cpPubKey}, srv.config.BiscuitTimeout); err != nil {
+ t.Fatalf("enrollee retry's biscuit does not verify: %v", err)
}
// Domain separation: a signature captured from one endpoint must verify
@@ -2766,3 +2778,373 @@ func TestHandleInfoPublishesBanSet(t *testing.T) {
t.Errorf("after unban banned_peer_ids = %v, want empty", after.GetBannedPeerIds())
}
}
+
+// createAdminBootstrapToken creates a bootstrap token for role via the admin
+// API and returns the plaintext token string.
+func createAdminBootstrapToken(t *testing.T, baseURL, adminToken, role string, maxUsages int) string {
+ t.Helper()
+ body := fmt.Sprintf(`{"role":%q,"ttl_hours":2,"max_usages":%d,"description":"re-enroll test"}`, role, maxUsages)
+ req, err := http.NewRequest(http.MethodPost, baseURL+"/admin/bootstrap-tokens", bytes.NewBufferString(body))
+ if err != nil {
+ t.Fatal(err)
+ }
+ req.Header.Set("Content-Type", "application/json")
+ req.Header.Set("Authorization", "Bearer "+adminToken)
+ resp, err := (&http.Client{Timeout: 5 * time.Second}).Do(req)
+ if err != nil {
+ t.Fatalf("failed to create bootstrap token: %v", err)
+ }
+ defer func() { _ = resp.Body.Close() }()
+ var tokenDetails struct {
+ Token string `json:"token"`
+ }
+ _ = json.NewDecoder(resp.Body).Decode(&tokenDetails)
+ if tokenDetails.Token == "" {
+ t.Fatal("empty bootstrap token")
+ }
+ return tokenDetails.Token
+}
+
+// bootstrapEnroll drives POST /enroll for peer priv/pID with the given
+// bootstrap token, requested role and labels, and returns the decoded
+// response. A REJECTED status is still HTTP 200 (see writeEnrollError), so
+// callers check the response's own Status field, not just the transport
+// status.
+func bootstrapEnroll(t *testing.T, baseURL, token string, priv crypto.PrivKey, pID peer.ID, pubBytes []byte, role string, labels map[string]string) *api.BootstrapEnrollResponse {
+ t.Helper()
+ ts, sig := enrollPoP(t, priv, pID.String())
+ data, err := proto.Marshal(&api.BootstrapEnrollRequest{
+ BootstrapToken: token,
+ PeerId: pID.String(),
+ PublicKey: pubBytes,
+ RequestedRole: role,
+ Labels: labels,
+ Timestamp: ts,
+ ChallengeSignature: sig,
+ })
+ if err != nil {
+ t.Fatal(err)
+ }
+ resp, err := (&http.Client{Timeout: 5 * time.Second}).Post(baseURL+"/enroll", "application/x-protobuf", bytes.NewReader(data))
+ if err != nil {
+ t.Fatalf("/enroll failed: %v", err)
+ }
+ defer func() { _ = resp.Body.Close() }()
+ body, _ := io.ReadAll(resp.Body)
+ if resp.StatusCode != http.StatusOK {
+ t.Fatalf("/enroll status %s: %s", resp.Status, string(body))
+ }
+ var out api.BootstrapEnrollResponse
+ if err := proto.Unmarshal(body, &out); err != nil {
+ t.Fatalf("unmarshal BootstrapEnrollResponse: %v", err)
+ }
+ return &out
+}
+
+// TestReEnrollAfterExpiryMintsFreshBiscuit pins the fix for the bootstrap
+// enrollment stale-biscuit-replay bug, and the follow-up hardening requested
+// in review: re-minting must be unconditional rather than gated by how stale
+// the stored token looks, must never happen on the /enroll/status poll
+// (which has no ban check and no live-token requirement), must ignore
+// whatever role or labels a re-enroll request itself declares in favor of
+// the enrolled node record, and must refuse a peer that is no longer
+// admitted.
+//
+// Before the original fix, both /enroll's existing-request branch and
+// /enroll/status returned existingReq.BiscuitToken verbatim forever, so a
+// router hitting a 401 on lease renewal and re-enrolling would receive the
+// exact same expired token every time -- an unbreakable enroll -> reject ->
+// re-enroll loop, identical to the one HandleRouterLease logs as "failed
+// biscuit verification: ... $time <= $exp".
+func TestReEnrollAfterExpiryMintsFreshBiscuit(t *testing.T) {
+ issuer, _ := startCustomMockOIDC(t)
+ const adminToken = "super-secret-admin-token"
+
+ // start spins up a fresh server and a fresh bootstrap token, so no
+ // subtest's enrollment state can leak into another's.
+ start := func(t *testing.T, role string, maxUsages int) (*Server, storage.Store, string, string) {
+ t.Helper()
+ srv, store, baseURL := setupTestServer(t, issuer)
+ t.Cleanup(func() {
+ _ = srv.Close()
+ _ = store.Close()
+ })
+ srv.config.AdminToken = adminToken
+ srv.config.AutoApproveEnrollment = true
+ // Auto-approve still runs declared labels through LabelPatternsAllow;
+ // without a policy granting role, that always rejects a non-empty
+ // label set, so the label-mutation subtest would never get an
+ // enrolled node to check in the first place.
+ if err := store.SaveMeshPolicy(context.Background(), []*api.PolicyRole{
+ {Name: role, AllowedLabels: []string{"*"}},
+ }, nil); err != nil {
+ t.Fatal(err)
+ }
+ token := createAdminBootstrapToken(t, baseURL, adminToken, role, maxUsages)
+ return srv, store, baseURL, token
+ }
+
+ newPeer := func(t *testing.T) (crypto.PrivKey, peer.ID, []byte) {
+ t.Helper()
+ priv, pub, err := crypto.GenerateKeyPair(crypto.Ed25519, -1)
+ if err != nil {
+ t.Fatal(err)
+ }
+ pID, err := peer.IDFromPrivateKey(priv)
+ if err != nil {
+ t.Fatal(err)
+ }
+ pubBytes, err := crypto.MarshalPublicKey(pub)
+ if err != nil {
+ t.Fatal(err)
+ }
+ return priv, pID, pubBytes
+ }
+
+ t.Run("re-enroll mints a fresh, verifying biscuit unconditionally", func(t *testing.T) {
+ srv, _, baseURL, token := start(t, api.RoleRouter, 5)
+ priv, pID, pubBytes := newPeer(t)
+
+ first := bootstrapEnroll(t, baseURL, token, priv, pID, pubBytes, api.RoleRouter, nil)
+ if first.Status != api.EnrollmentStatus_ENROLLMENT_STATUS_APPROVED {
+ t.Fatalf("expected APPROVED on first enroll, got %v", first.Status)
+ }
+ cpPubKey := ed25519.PublicKey(first.ControlPlanePublicKey)
+ trustedKeys := []ed25519.PublicKey{cpPubKey}
+ if _, _, err := identity.VerifyBiscuitAndGetKey(first.BiscuitToken, pID, trustedKeys, srv.config.BiscuitTimeout); err != nil {
+ t.Fatalf("first biscuit failed to verify immediately after issuance: %v", err)
+ }
+
+ // No sleep needed: re-minting is unconditional now, so an immediate
+ // re-enroll must still get back a brand-new, verifying biscuit -- a
+ // stronger assertion than "eventually, once stale enough" was.
+ second := bootstrapEnroll(t, baseURL, token, priv, pID, pubBytes, api.RoleRouter, nil)
+ if second.Status != api.EnrollmentStatus_ENROLLMENT_STATUS_APPROVED {
+ t.Fatalf("expected APPROVED on re-enroll, got %v", second.Status)
+ }
+ if bytes.Equal(second.BiscuitToken, first.BiscuitToken) {
+ t.Fatal("re-enroll returned the exact same biscuit instead of minting a fresh one")
+ }
+ if _, _, err := identity.VerifyBiscuitAndGetKey(second.BiscuitToken, pID, trustedKeys, srv.config.BiscuitTimeout); err != nil {
+ t.Fatalf("refreshed biscuit from re-enroll does not verify: %v", err)
+ }
+ })
+
+ t.Run("enroll status never mints and never resurrects a stale token", func(t *testing.T) {
+ _, store, baseURL, token := start(t, api.RoleRouter, 5)
+ priv, pID, pubBytes := newPeer(t)
+
+ first := bootstrapEnroll(t, baseURL, token, priv, pID, pubBytes, api.RoleRouter, nil)
+
+ statusResp, err := (&http.Client{Timeout: 5 * time.Second}).Do(signedEnrollStatusRequest(t, baseURL, priv, pID.String(), time.Now().UnixMilli()))
+ if err != nil {
+ t.Fatal(err)
+ }
+ statusBody, _ := io.ReadAll(statusResp.Body)
+ _ = statusResp.Body.Close()
+ var polled api.BootstrapEnrollResponse
+ if err := proto.Unmarshal(statusBody, &polled); err != nil {
+ t.Fatalf("unmarshal polled BootstrapEnrollResponse: %v", err)
+ }
+ if !bytes.Equal(polled.BiscuitToken, first.BiscuitToken) {
+ t.Fatal("GET /enroll/status minted a new biscuit instead of returning the stored one unchanged")
+ }
+
+ record, err := store.GetNode(context.Background(), pID.String())
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !bytes.Equal(record.Biscuit, first.BiscuitToken) {
+ t.Fatal("GET /enroll/status mutated the enrolled node record's biscuit")
+ }
+ })
+
+ t.Run("re-enrolled biscuit refreshes cleanly via refresh", func(t *testing.T) {
+ _, _, baseURL, token := start(t, api.RoleRouter, 5)
+ priv, pID, pubBytes := newPeer(t)
+
+ bootstrapEnroll(t, baseURL, token, priv, pID, pubBytes, api.RoleRouter, nil)
+ second := bootstrapEnroll(t, baseURL, token, priv, pID, pubBytes, api.RoleRouter, nil)
+
+ // refreshNode's reuse-detection compares the presented biscuit
+ // against the node record's stored one -- exactly what the re-mint's
+ // nodeRecord.Biscuit sync protects; it fails outright if that drifted.
+ refreshed := refreshNode(t, baseURL, priv, second.BiscuitToken)
+ if len(refreshed.BiscuitToken) == 0 {
+ t.Fatal("refresh after re-enroll returned an empty biscuit")
+ }
+ })
+
+ t.Run("re-enroll ignores the request's own declared labels", func(t *testing.T) {
+ _, store, baseURL, token := start(t, api.RoleRouter, 5)
+ priv, pID, pubBytes := newPeer(t)
+
+ bootstrapEnroll(t, baseURL, token, priv, pID, pubBytes, api.RoleRouter, map[string]string{"component": "original"})
+
+ // Same token, so RequestedRole must still equal the token's own role
+ // to pass /enroll's earlier check, but a different declared label
+ // set -- the existing-request branch must not let this through.
+ bootstrapEnroll(t, baseURL, token, priv, pID, pubBytes, api.RoleRouter, map[string]string{"component": "attacker-supplied"})
+
+ record, err := store.GetNode(context.Background(), pID.String())
+ if err != nil {
+ t.Fatal(err)
+ }
+ if record.Labels["component"] != "original" {
+ t.Fatalf("re-enroll changed the enrolled node's stored labels to %v, want the original attested set unchanged", record.Labels)
+ }
+ })
+
+ t.Run("a banned peer is refused, not re-minted", func(t *testing.T) {
+ _, store, baseURL, token := start(t, api.RoleRouter, 5)
+ priv, pID, pubBytes := newPeer(t)
+
+ bootstrapEnroll(t, baseURL, token, priv, pID, pubBytes, api.RoleRouter, nil)
+ if err := store.SetNodeBanned(context.Background(), pID.String(), true); err != nil {
+ t.Fatal(err)
+ }
+
+ out := bootstrapEnroll(t, baseURL, token, priv, pID, pubBytes, api.RoleRouter, nil)
+ if out.Status != api.EnrollmentStatus_ENROLLMENT_STATUS_REJECTED {
+ t.Fatalf("expected REJECTED for a banned peer's re-enroll, got %v", out.Status)
+ }
+ })
+
+ t.Run("a node whose record role no longer matches the token's is refused", func(t *testing.T) {
+ _, store, baseURL, token := start(t, api.RoleRouter, 5)
+ priv, pID, pubBytes := newPeer(t)
+
+ bootstrapEnroll(t, baseURL, token, priv, pID, pubBytes, api.RoleRouter, nil)
+
+ // Simulate the node record's role having drifted since approval
+ // (e.g. a manual admin change) rather than via a real HTTP path,
+ // since there isn't one for it -- the defensive check exists
+ // precisely because this shouldn't be trusted to never happen.
+ record, err := store.GetNode(context.Background(), pID.String())
+ if err != nil {
+ t.Fatal(err)
+ }
+ record.Role = api.RoleNode
+ if err := store.EnrollNode(context.Background(), record); err != nil {
+ t.Fatal(err)
+ }
+
+ out := bootstrapEnroll(t, baseURL, token, priv, pID, pubBytes, api.RoleRouter, nil)
+ if out.Status != api.EnrollmentStatus_ENROLLMENT_STATUS_REJECTED {
+ t.Fatalf("expected REJECTED for a token/node role mismatch, got %v", out.Status)
+ }
+ })
+}
+
+// TestAdminRevokeBootstrapToken pins DELETE /admin/bootstrap-tokens/{id}
+// (#368's other half): a soft revoke, 404 only for an id that names no
+// token at all, idempotent otherwise, enforced at /enroll for both a brand
+// new enrollment and a re-enroll of an already-approved one.
+func TestAdminRevokeBootstrapToken(t *testing.T) {
+ issuer, _ := startCustomMockOIDC(t)
+ srv, store, baseURL := setupTestServer(t, issuer)
+ defer func() {
+ _ = srv.Close()
+ _ = store.Close()
+ }()
+ const adminToken = "super-secret-admin-token"
+ srv.config.AdminToken = adminToken
+ srv.config.AutoApproveEnrollment = true
+
+ client := &http.Client{Timeout: 5 * time.Second}
+ deleteToken := func(id string) *http.Response {
+ t.Helper()
+ req, err := http.NewRequest(http.MethodDelete, baseURL+"/admin/bootstrap-tokens/"+id, nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ req.Header.Set("Authorization", "Bearer "+adminToken)
+ resp, err := client.Do(req)
+ if err != nil {
+ t.Fatalf("DELETE /admin/bootstrap-tokens/%s: %v", id, err)
+ }
+ return resp
+ }
+
+ if resp := deleteToken("no-such-id"); resp.StatusCode != http.StatusNotFound {
+ t.Errorf("revoking an unknown token id: got %d, want 404", resp.StatusCode)
+ }
+
+ token := createAdminBootstrapToken(t, baseURL, adminToken, api.RoleRouter, 5)
+
+ // createAdminBootstrapToken returns the plaintext; the id path parameter
+ // is its sha256 hash (see HandleAdminBootstrapTokens), so fetch it back
+ // via the list rather than recomputing the hash here.
+ req, err := http.NewRequest(http.MethodGet, baseURL+"/admin/bootstrap-tokens", nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ req.Header.Set("Authorization", "Bearer "+adminToken)
+ listResp, err := client.Do(req)
+ if err != nil {
+ t.Fatal(err)
+ }
+ var listed []struct {
+ ID string
+ }
+ if err := json.NewDecoder(listResp.Body).Decode(&listed); err != nil {
+ t.Fatal(err)
+ }
+ _ = listResp.Body.Close()
+ if len(listed) != 1 {
+ t.Fatalf("GET /admin/bootstrap-tokens returned %d tokens, want 1", len(listed))
+ }
+ tokenID := listed[0].ID
+
+ priv, pub, err := crypto.GenerateKeyPair(crypto.Ed25519, -1)
+ if err != nil {
+ t.Fatal(err)
+ }
+ pID, err := peer.IDFromPrivateKey(priv)
+ if err != nil {
+ t.Fatal(err)
+ }
+ pubBytes, err := crypto.MarshalPublicKey(pub)
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ first := bootstrapEnroll(t, baseURL, token, priv, pID, pubBytes, api.RoleRouter, nil)
+ if first.Status != api.EnrollmentStatus_ENROLLMENT_STATUS_APPROVED {
+ t.Fatalf("expected APPROVED before revocation, got %v", first.Status)
+ }
+
+ if resp := deleteToken(tokenID); resp.StatusCode != http.StatusNoContent {
+ body, _ := io.ReadAll(resp.Body)
+ t.Fatalf("revoke: got %d: %s", resp.StatusCode, body)
+ }
+ // Idempotent: revoking the same token again must still succeed.
+ if resp := deleteToken(tokenID); resp.StatusCode != http.StatusNoContent {
+ body, _ := io.ReadAll(resp.Body)
+ t.Fatalf("second revoke: got %d: %s", resp.StatusCode, body)
+ }
+
+ // A revoked token can neither enroll a brand new peer...
+ otherPriv, otherPub, err := crypto.GenerateKeyPair(crypto.Ed25519, -1)
+ if err != nil {
+ t.Fatal(err)
+ }
+ otherPID, err := peer.IDFromPrivateKey(otherPriv)
+ if err != nil {
+ t.Fatal(err)
+ }
+ otherPubBytes, err := crypto.MarshalPublicKey(otherPub)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if out := bootstrapEnroll(t, baseURL, token, otherPriv, otherPID, otherPubBytes, api.RoleRouter, nil); out.Status != api.EnrollmentStatus_ENROLLMENT_STATUS_REJECTED {
+ t.Errorf("new enrollment with a revoked token: got %v, want REJECTED", out.Status)
+ }
+
+ // ...nor re-mint a fresh biscuit for the peer that enrolled before it was
+ // revoked - a revoked token must not become an exception to the
+ // unconditional re-mint enforced above.
+ if out := bootstrapEnroll(t, baseURL, token, priv, pID, pubBytes, api.RoleRouter, nil); out.Status != api.EnrollmentStatus_ENROLLMENT_STATUS_REJECTED {
+ t.Errorf("re-enroll with a revoked token: got %v, want REJECTED", out.Status)
+ }
+}
diff --git a/internal/controlplane/stale_biscuit_replay_test.go b/internal/controlplane/stale_biscuit_replay_test.go
deleted file mode 100644
index a27524ac..00000000
--- a/internal/controlplane/stale_biscuit_replay_test.go
+++ /dev/null
@@ -1,188 +0,0 @@
-// Copyright 2026 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-package controlplane
-
-import (
- "bytes"
- "crypto/ed25519"
- "encoding/json"
- "io"
- "net/http"
- "testing"
- "time"
-
- "github.com/google/sam/api"
- "github.com/google/sam/internal/identity"
- "github.com/libp2p/go-libp2p/core/crypto"
- "github.com/libp2p/go-libp2p/core/peer"
- "google.golang.org/protobuf/proto"
-)
-
-// TestReEnrollAfterExpiryMintsFreshBiscuit pins the fix for the bootstrap
-// enrollment stale-biscuit-replay bug: a peer whose approved enrollment
-// record outlives BiscuitTTL (e.g. a router restarting after several idle
-// days) and re-submits /enroll or polls /enroll/status must get back a
-// biscuit that actually verifies, not the original, now-expired one.
-//
-// Before the fix, both endpoints' "existing enrollment request" branch
-// returned existingReq.BiscuitToken verbatim forever, so a router hitting a
-// 401 on lease renewal and re-enrolling would receive the exact same expired
-// token every time -- an unbreakable enroll -> reject -> re-enroll loop,
-// identical to the one HandleRouterLease logs as "failed biscuit
-// verification: ... $time <= $exp".
-func TestReEnrollAfterExpiryMintsFreshBiscuit(t *testing.T) {
- issuer, _ := startCustomMockOIDC(t)
- srv, store, baseURL := setupTestServer(t, issuer, func(o *Options) {
- o.BiscuitTTL = 1 * time.Second
- })
- defer func() {
- _ = srv.Close()
- _ = store.Close()
- }()
- srv.config.AdminToken = "super-secret-admin-token"
- srv.config.AutoApproveEnrollment = true
-
- client := &http.Client{Timeout: 5 * time.Second}
-
- adminReqBody := []byte(`{"role": "sam:role:router", "ttl_hours": 2, "max_usages": 5, "description": "stale replay test"}`)
- req, err := http.NewRequest("POST", baseURL+"/admin/bootstrap-tokens", bytes.NewBuffer(adminReqBody))
- if err != nil {
- t.Fatal(err)
- }
- req.Header.Set("Content-Type", "application/json")
- req.Header.Set("Authorization", "Bearer super-secret-admin-token")
- resp, err := client.Do(req)
- if err != nil {
- t.Fatalf("failed to create bootstrap token: %v", err)
- }
- var tokenDetails struct {
- Token string `json:"token"`
- }
- _ = json.NewDecoder(resp.Body).Decode(&tokenDetails)
- _ = resp.Body.Close()
- if tokenDetails.Token == "" {
- t.Fatal("empty bootstrap token")
- }
-
- priv, pub, err := crypto.GenerateKeyPair(crypto.Ed25519, -1)
- if err != nil {
- t.Fatal(err)
- }
- pID, err := peer.IDFromPrivateKey(priv)
- if err != nil {
- t.Fatal(err)
- }
- pubBytes, err := crypto.MarshalPublicKey(pub)
- if err != nil {
- t.Fatal(err)
- }
-
- doEnroll := func() *api.BootstrapEnrollResponse {
- t.Helper()
- ts, sig := enrollPoP(t, priv, pID.String())
- data, err := proto.Marshal(&api.BootstrapEnrollRequest{
- BootstrapToken: tokenDetails.Token,
- PeerId: pID.String(),
- PublicKey: pubBytes,
- RequestedRole: api.RoleRouter,
- Timestamp: ts,
- ChallengeSignature: sig,
- })
- if err != nil {
- t.Fatal(err)
- }
- resp, err := client.Post(baseURL+"/enroll", "application/x-protobuf", bytes.NewReader(data))
- if err != nil {
- t.Fatalf("/enroll failed: %v", err)
- }
- defer func() { _ = resp.Body.Close() }()
- body, _ := io.ReadAll(resp.Body)
- if resp.StatusCode != http.StatusOK {
- t.Fatalf("/enroll status %s: %s", resp.Status, string(body))
- }
- var out api.BootstrapEnrollResponse
- if err := proto.Unmarshal(body, &out); err != nil {
- t.Fatalf("unmarshal BootstrapEnrollResponse: %v", err)
- }
- return &out
- }
-
- first := doEnroll()
- if first.Status != api.EnrollmentStatus_ENROLLMENT_STATUS_APPROVED {
- t.Fatalf("expected APPROVED on first enroll, got %v", first.Status)
- }
- if len(first.BiscuitToken) == 0 {
- t.Fatal("first biscuit token is empty")
- }
-
- cpPubKey := ed25519.PublicKey(first.ControlPlanePublicKey)
- trustedKeys := []ed25519.PublicKey{cpPubKey}
-
- // The first token must actually verify right away.
- if _, _, err := identity.VerifyBiscuitAndGetKey(first.BiscuitToken, pID, trustedKeys, srv.config.BiscuitTimeout); err != nil {
- t.Fatalf("first biscuit failed to verify immediately after issuance: %v", err)
- }
-
- // Let it age past BiscuitTTL, exactly as an idle router's stored token
- // would after being off for longer than the control plane's TTL. Biscuit
- // Date terms round to whole seconds, so the margin has to clear that,
- // not just the nominal 1s TTL.
- time.Sleep(3 * time.Second)
-
- if _, _, err := identity.VerifyBiscuitAndGetKey(first.BiscuitToken, pID, trustedKeys, srv.config.BiscuitTimeout); err == nil {
- t.Fatal("first biscuit still verifies after its TTL elapsed; test setup is not exercising an expired token")
- }
-
- // This is the re-enrollment call a router's reEnroll() makes after a 401
- // on lease renewal: same peer ID, same bootstrap token, fresh PoP
- // signature. It must hit the "existing enrollment request" branch (not
- // mint a brand-new one from scratch) to actually exercise the bug.
- second := doEnroll()
- if second.Status != api.EnrollmentStatus_ENROLLMENT_STATUS_APPROVED {
- t.Fatalf("expected APPROVED on re-enroll, got %v", second.Status)
- }
- if bytes.Equal(second.BiscuitToken, first.BiscuitToken) {
- t.Fatal("re-enroll after expiry returned the exact same (now-expired) biscuit token instead of minting a fresh one")
- }
- if _, _, err := identity.VerifyBiscuitAndGetKey(second.BiscuitToken, pID, trustedKeys, srv.config.BiscuitTimeout); err != nil {
- t.Fatalf("refreshed biscuit from re-enroll does not verify: %v", err)
- }
-
- // /enroll/status must agree: it must not resurrect the stale token either.
- statusResp, err := client.Do(signedEnrollStatusRequest(t, baseURL, priv, pID.String(), time.Now().UnixMilli()))
- if err != nil {
- t.Fatal(err)
- }
- statusBody, _ := io.ReadAll(statusResp.Body)
- _ = statusResp.Body.Close()
- var polled api.BootstrapEnrollResponse
- if err := proto.Unmarshal(statusBody, &polled); err != nil {
- t.Fatalf("unmarshal polled BootstrapEnrollResponse: %v", err)
- }
- if _, _, err := identity.VerifyBiscuitAndGetKey(polled.BiscuitToken, pID, trustedKeys, srv.config.BiscuitTimeout); err != nil {
- t.Fatalf("biscuit returned by /enroll/status does not verify: %v", err)
- }
-
- // The enrolled node record must stay in lockstep with the refreshed
- // token: /refresh's reuse-detection compares a presented biscuit against
- // exactly this field, so a drift here would silently break that path.
- nodeRecord, err := store.GetNode(t.Context(), pID.String())
- if err != nil {
- t.Fatal(err)
- }
- if !bytes.Equal(nodeRecord.Biscuit, second.BiscuitToken) {
- t.Fatalf("enrolled node record's biscuit is out of sync with the refreshed enrollment token")
- }
-}
diff --git a/internal/storage/round_trip_test.go b/internal/storage/round_trip_test.go
index 395eb608..e03c418d 100644
--- a/internal/storage/round_trip_test.go
+++ b/internal/storage/round_trip_test.go
@@ -202,7 +202,9 @@ func TestBootstrapTokenRoundTripsEveryField(t *testing.T) {
CreatedAt: time.Now().Add(-time.Hour),
ExpiresAt: time.Now().Add(time.Hour),
}
- requireAllFieldsSet(t, want)
+ // RevokedAt is never set at creation - only RevokeBootstrapToken sets it,
+ // covered separately below.
+ requireAllFieldsSet(t, want, "RevokedAt")
if err := store.SaveBootstrapToken(ctx, want); err != nil {
t.Fatalf("SaveBootstrapToken: %v", err)
@@ -213,6 +215,9 @@ func TestBootstrapTokenRoundTripsEveryField(t *testing.T) {
t.Fatalf("GetBootstrapToken: %v", err)
}
requireFieldsRoundTrip(t, want, got)
+ if got.IsRevoked() {
+ t.Error("a freshly saved token must not start out revoked")
+ }
listed, err := store.ListBootstrapTokens(ctx)
if err != nil {
@@ -222,6 +227,36 @@ func TestBootstrapTokenRoundTripsEveryField(t *testing.T) {
t.Fatalf("ListBootstrapTokens returned %d, want 1", len(listed))
}
requireFieldsRoundTrip(t, want, &listed[0])
+
+ if err := store.RevokeBootstrapToken(ctx, want.ID); err != nil {
+ t.Fatalf("RevokeBootstrapToken: %v", err)
+ }
+ revoked, err := store.GetBootstrapToken(ctx, want.ID)
+ if err != nil {
+ t.Fatalf("GetBootstrapToken after revoke: %v", err)
+ }
+ if !revoked.IsRevoked() {
+ t.Fatal("RevokedAt was not persisted by RevokeBootstrapToken")
+ }
+
+ // Idempotent: revoking an already-revoked token is not an error and does
+ // not un-set RevokedAt.
+ if err := store.RevokeBootstrapToken(ctx, want.ID); err != nil {
+ t.Fatalf("RevokeBootstrapToken (second call): %v", err)
+ }
+ revokedAgain, err := store.GetBootstrapToken(ctx, want.ID)
+ if err != nil {
+ t.Fatalf("GetBootstrapToken after second revoke: %v", err)
+ }
+ if !revokedAgain.IsRevoked() {
+ t.Error("a second RevokeBootstrapToken call must not un-revoke the token")
+ }
+
+ // Revoking an unknown id is also not an error - the HTTP layer is what
+ // distinguishes "unknown" via a preceding GetBootstrapToken.
+ if err := store.RevokeBootstrapToken(ctx, "no-such-token"); err != nil {
+ t.Errorf("RevokeBootstrapToken(unknown id) = %v, want nil", err)
+ }
}
func TestEnrollmentRequestRoundTripsEveryField(t *testing.T) {
diff --git a/internal/storage/sql_store.go b/internal/storage/sql_store.go
index 79291766..5713ace6 100644
--- a/internal/storage/sql_store.go
+++ b/internal/storage/sql_store.go
@@ -369,6 +369,18 @@ var migrations = []migration{
)`,
},
},
+ {
+ // Soft revoke, not delete: enrollment_requests.token_id has an FK to
+ // this table, and a revoked_at column keeps the audit trail distinct
+ // from the token's own natural expiry.
+ version: 9,
+ postgres: []string{
+ `ALTER TABLE bootstrap_tokens ADD COLUMN IF NOT EXISTS revoked_at BIGINT`,
+ },
+ sqlite: []string{
+ `ALTER TABLE bootstrap_tokens ADD COLUMN revoked_at BIGINT`,
+ },
+ },
}
func (s *SQLStore) initSchema() error {
@@ -1010,10 +1022,11 @@ func (s *SQLStore) SaveBootstrapToken(ctx context.Context, token *BootstrapToken
// GetBootstrapToken retrieves a bootstrap token by its ID (sha256 hash).
func (s *SQLStore) GetBootstrapToken(ctx context.Context, id string) (*BootstrapToken, error) {
- query := s.rebind(`SELECT id, token_hash, role, owner_id, max_usages, usages_count, description, created_at, expires_at FROM bootstrap_tokens WHERE id = ?`)
+ query := s.rebind(`SELECT id, token_hash, role, owner_id, max_usages, usages_count, description, created_at, expires_at, revoked_at FROM bootstrap_tokens WHERE id = ?`)
var t BootstrapToken
var created, expires int64
var ownerID sql.NullString
+ var revokedAt sql.NullInt64
err := s.db.QueryRowContext(ctx, query, id).Scan(
&t.ID,
&t.TokenHash,
@@ -1024,6 +1037,7 @@ func (s *SQLStore) GetBootstrapToken(ctx context.Context, id string) (*Bootstrap
&t.Description,
&created,
&expires,
+ &revokedAt,
)
if err == sql.ErrNoRows {
return nil, ErrNotFound
@@ -1036,6 +1050,10 @@ func (s *SQLStore) GetBootstrapToken(ctx context.Context, id string) (*Bootstrap
}
t.CreatedAt = time.Unix(created, 0)
t.ExpiresAt = time.Unix(expires, 0)
+ if revokedAt.Valid {
+ rt := time.Unix(revokedAt.Int64, 0)
+ t.RevokedAt = &rt
+ }
return &t, nil
}
@@ -1049,6 +1067,18 @@ func (s *SQLStore) IncrementBootstrapTokenUsage(ctx context.Context, id string)
return nil
}
+// RevokeBootstrapToken soft-revokes a token: see the Store interface comment
+// for why this doesn't delete the row. The WHERE clause makes a repeat call
+// a no-op rather than clobbering the original revocation time.
+func (s *SQLStore) RevokeBootstrapToken(ctx context.Context, id string) error {
+ query := `UPDATE bootstrap_tokens SET revoked_at = ? WHERE id = ? AND revoked_at IS NULL`
+ _, err := s.db.ExecContext(ctx, s.rebind(query), time.Now().Unix(), id)
+ if err != nil {
+ return fmt.Errorf("failed to revoke bootstrap token: %w", err)
+ }
+ return nil
+}
+
// CreateEnrollmentRequest saves a new pending request.
func (s *SQLStore) CreateEnrollmentRequest(ctx context.Context, req *EnrollmentRequest) error {
labelsJSON, err := json.Marshal(req.Labels)
@@ -1247,7 +1277,7 @@ func (s *SQLStore) ListNodes(ctx context.Context) ([]EnrolledNode, error) {
// ListBootstrapTokens retrieves all bootstrap tokens.
func (s *SQLStore) ListBootstrapTokens(ctx context.Context) ([]BootstrapToken, error) {
- query := s.rebind(`SELECT id, token_hash, role, owner_id, max_usages, usages_count, description, created_at, expires_at FROM bootstrap_tokens ORDER BY created_at DESC`)
+ query := s.rebind(`SELECT id, token_hash, role, owner_id, max_usages, usages_count, description, created_at, expires_at, revoked_at FROM bootstrap_tokens ORDER BY created_at DESC`)
rows, err := s.db.QueryContext(ctx, query)
if err != nil {
return nil, fmt.Errorf("failed to query bootstrap tokens: %w", err)
@@ -1260,6 +1290,7 @@ func (s *SQLStore) ListBootstrapTokens(ctx context.Context) ([]BootstrapToken, e
var desc sql.NullString
var ownerID sql.NullString
var created, expires int64
+ var revokedAt sql.NullInt64
err := rows.Scan(
&t.ID,
&t.TokenHash,
@@ -1270,6 +1301,7 @@ func (s *SQLStore) ListBootstrapTokens(ctx context.Context) ([]BootstrapToken, e
&desc,
&created,
&expires,
+ &revokedAt,
)
if err != nil {
return nil, fmt.Errorf("failed to scan bootstrap token: %w", err)
@@ -1282,6 +1314,10 @@ func (s *SQLStore) ListBootstrapTokens(ctx context.Context) ([]BootstrapToken, e
}
t.CreatedAt = time.Unix(created, 0)
t.ExpiresAt = time.Unix(expires, 0)
+ if revokedAt.Valid {
+ rt := time.Unix(revokedAt.Int64, 0)
+ t.RevokedAt = &rt
+ }
tokens = append(tokens, t)
}
if err := rows.Err(); err != nil {
diff --git a/internal/storage/storage.go b/internal/storage/storage.go
index 3158f4f6..623e6dc6 100644
--- a/internal/storage/storage.go
+++ b/internal/storage/storage.go
@@ -100,6 +100,17 @@ type BootstrapToken struct {
Description string
CreatedAt time.Time
ExpiresAt time.Time
+ // RevokedAt is set by RevokeBootstrapToken - a soft revoke, distinct from
+ // natural expiry, since enrollment_requests.token_id has a foreign key
+ // into this table and a hard delete would break that trail. Nil means
+ // never revoked.
+ RevokedAt *time.Time
+}
+
+// IsRevoked reports whether the token has been explicitly revoked, as
+// opposed to merely expired or usage-exhausted.
+func (t *BootstrapToken) IsRevoked() bool {
+ return t.RevokedAt != nil
}
// EnrollmentRequest represents a pending or resolved node registration request (CSR).
@@ -204,6 +215,13 @@ type Store interface {
// IncrementBootstrapTokenUsage increments the usage count of a token.
IncrementBootstrapTokenUsage(ctx context.Context, id string) error
+ // RevokeBootstrapToken soft-revokes a token by setting its RevokedAt, so
+ // HandleEnroll refuses it even though it may still be within its TTL and
+ // usage count. Idempotent: revoking an already-revoked or unknown token
+ // is not an error - callers that need to distinguish "unknown" first
+ // look the token up with GetBootstrapToken.
+ RevokeBootstrapToken(ctx context.Context, id string) error
+
// CreateEnrollmentRequest saves a new pending enrollment request.
CreateEnrollmentRequest(ctx context.Context, req *EnrollmentRequest) error