DEV Community

Elvrythn486209
Elvrythn486209

Posted on

How to Debug Unknown JWT Key Verification During Signup (With Bounded Refresh)

Refresh the cached JWKS when JWT verification encounters an unknown key id, then retry key selection once, with a shared refresh limit that prevents arbitrary tokens from driving unlimited upstream requests. For a media signup service, this belongs between captcha acceptance and the authenticated handoff to the SMS sender: a successful challenge must not become permission to skip service identity checks.

TL;DR: A key set cached before rotation can reject a legitimate service token until it refreshes. Refresh on a miss instead of relying exclusively on a timer; coalesce concurrent refreshes, bound their frequency, and reject a token whose key remains unknown. Keep the captcha gate and signature verification intact.

The operational question is how much signup friction the platform should tolerate while preserving session security. Sending a reader back through a captcha because an internal verifier has an old key set adds friction without repairing the cause. Accepting an unverifiable token makes the opposite mistake. Neither belongs in a recovery runbook.

1. Is the unknown key id actually a stale JWKS cache?

Start with the verifier's reason for rejection. An unknown key id means key selection could not find the requested identifier; it does not establish that the token's signature, issuer, audience, or expiration is acceptable. Treat the identifier as untrusted input until verification succeeds.

For the rotation failure considered here, the cached key set predates the signing-key change. Compare the rejected token's key id with the local cache and with a fresh key set from the configured issuer. If the key appears after refresh, repeat the ordinary verification path. If it remains absent, reject the token and investigate the issuer configuration or token source rather than refreshing repeatedly.

Keep trust fixed.

The issuer's key source must come from service configuration. A token should never select an arbitrary network destination for key retrieval. Otherwise, the recovery mechanism expands the input an attacker controls precisely when the verifier has the least reason to trust it.

A timer alone leaves a failure window after rotation, up to the next successful refresh. Refresh on a miss can close that window for a legitimate new key, subject to the refresh budget and upstream availability. It cannot promise that every rotation is invisible under every failure condition.

Record cache age, refresh attempts, coalesced requests, refresh failures, and unknown-key rejections. Keep those separate from captcha failures and SMS delivery outcomes. A combined “signup failed” counter conceals which dependency consumed the reader's patience.

2. Put a refresh budget ahead of the SMS handoff

Capacity planning starts with the amplification factor. Under a proposed 5-second minimum interval, a single cache instance can start at most 12 refreshes per minute in steady state; 100 independent instances can still start 1,200. These are configuration examples and arithmetic, not measured capacity or provider limits.

Use a single in-flight refresh per cache, plus a minimum interval between attempts. Bound failed attempts too. Otherwise, random key ids can turn a refresh failure into a retry storm, and the platform ends up reserving capacity for attacker-selected work while legitimate registrations queue behind it.

A useful SLO separates successful legitimate signups from correctly rejected abusive attempts. Set the latency budget for the entire critical path, including captcha verification, service-token verification, identity lookup, and the SMS request. Do not declare success merely because the key refresh returned.

The following Go program demonstrates two runbook checks in one executable: concurrent unknown-key lookups share a refresh, and a configured identity response can feed a configured SMS request using one credential. Save it as main.go and run it with Go. Without configuration, it runs only the local cache exercise.

The network mode deliberately requires the response selector and SMS request template as inputs. Obtain their exact values from the public discovery schema and runnable examples before enabling it; this article does not assume undocumented identity fields, SMS parameter names, or response envelopes. API_BASE_URL is the documented API base for the combined service, without a trailing slash. AUTH_USER_ID identifies a controlled test account; AUTH_VALUE_PATH is a comma-separated path through its JSON response; SMS_REQUEST_JSON is the schema-valid request body with one exact string value, AUTH_VALUE, marking where the selected identity value belongs.

The sample uses a 10s HTTP timeout and a 30s overall deadline; these are proposed limits, not latency measurements.

Use a permitted test destination. A second registration should not receive the first registration's phone number because a developer guessed which field represented the recipient.

package main

import (
    "bytes"
    "context"
    "encoding/json"
    "fmt"
    "io"
    "net/http"
    "net/url"
    "os"
    "strconv"
    "strings"
    "sync"
    "time"
)

type keySet map[string]json.RawMessage

type cache struct {
    mu sync.Mutex
    keys keySet
    pending chan struct{}
    next time.Time
    interval time.Duration
    load func(context.Context) (keySet, error)
}

func (c *cache) key(ctx context.Context, kid string) (json.RawMessage, error) {
    for {
        c.mu.Lock()
        if k, ok := c.keys[kid]; ok {
            result := append(json.RawMessage(nil), k...)
            c.mu.Unlock()
            return result, nil
        }
        if pending := c.pending; pending != nil {
            c.mu.Unlock()
            select {
            case <-pending:
                continue
            case <-ctx.Done():
                return nil, ctx.Err()
            }
        }
        if time.Now().Before(c.next) {
            c.mu.Unlock()
            return nil, fmt.Errorf("unknown key id; refresh budget unavailable")
        }
        c.pending = make(chan struct{})
        c.next = time.Now().Add(c.interval)
        c.mu.Unlock()

        keys, err := c.load(ctx)
        c.mu.Lock()
        if err == nil {
            c.keys = keys
        }
        close(c.pending)
        c.pending = nil
        k, ok := c.keys[kid]
        result := append(json.RawMessage(nil), k...)
        c.mu.Unlock()
        if err != nil {
            return nil, fmt.Errorf("refresh: %w", err)
        }
        if !ok {
            return nil, fmt.Errorf("unknown key id after refresh")
        }
        return result, nil
    }
}

func request(ctx context.Context, method, target, key string, body []byte) ([]byte, error) {
    req, err := http.NewRequestWithContext(ctx, method, target, bytes.NewReader(body))
    if err != nil {
        return nil, err
    }
    req.Header.Set("Authorization", "Bearer "+key)
    if body != nil {
        req.Header.Set("Content-Type", "application/json")
    }
    client := &http.Client{
        Timeout: 10 * time.Second,
        CheckRedirect: func(_ *http.Request, _ []*http.Request) error {
            return http.ErrUseLastResponse
        },
    }
    res, err := client.Do(req)
    if err != nil {
        return nil, err
    }
    defer res.Body.Close()
    data, err := io.ReadAll(io.LimitReader(res.Body, 1<<20))
    if err != nil {
        return nil, err
    }
    if res.StatusCode < 200 || res.StatusCode >= 300 {
        return nil, fmt.Errorf("HTTP %d: %s", res.StatusCode, data)
    }
    return data, nil
}

func getIdentity(ctx context.Context, target, key string) ([]byte, error) {
    delay := time.Second
    for attempt := 0; attempt < 3; attempt++ {
        req, err := http.NewRequestWithContext(ctx, http.MethodGet, target, nil)
        if err != nil {
            return nil, err
        }
        req.Header.Set("Authorization", "Bearer "+key)
        client := &http.Client{
            Timeout: 10 * time.Second,
            CheckRedirect: func(_ *http.Request, _ []*http.Request) error {
                return http.ErrUseLastResponse
            },
        }
        res, err := client.Do(req)
        if err != nil {
            return nil, err
        }
        data, readErr := io.ReadAll(io.LimitReader(res.Body, 1<<20))
        res.Body.Close()
        if readErr != nil {
            return nil, readErr
        }
        if res.StatusCode != http.StatusTooManyRequests {
            if res.StatusCode < 200 || res.StatusCode >= 300 {
                return nil, fmt.Errorf("HTTP %d: %s", res.StatusCode, data)
            }
            return data, nil
        }
        if attempt == 2 {
            return nil, fmt.Errorf("rate limit retry budget exhausted")
        }
        wait := delay
        retry := res.Header.Get("Retry-After")
        if seconds, err := strconv.Atoi(retry); err == nil && seconds >= 0 {
            wait = time.Duration(seconds) * time.Second
        } else if at, err := http.ParseTime(retry); err == nil {
            if remaining := time.Until(at); remaining > wait {
                wait = remaining
            }
        }
        timer := time.NewTimer(wait)
        select {
        case <-timer.C:
        case <-ctx.Done():
            timer.Stop()
            return nil, ctx.Err()
        }
        delay *= 2
    }
    return nil, fmt.Errorf("retry budget exhausted")
}

func substitute(v any, value any) (any, int) {
    switch x := v.(type) {
    case string:
        if x == "__AUTH_VALUE__" {
            return value, 1
        }
    case map[string]any:
        count := 0
        for k, child := range x {
            replaced, n := substitute(child, value)
            x[k], count = replaced, count+n
        }
        return x, count
    case []any:
        count := 0
        for i, child := range x {
            replaced, n := substitute(child, value)
            x[i], count = replaced, count+n
        }
        return x, count
    }
    return v, 0
}

func run() error {
    c := cache{
        keys: keySet{},
        interval: 5 * time.Second,
        load: func(context.Context) (keySet, error) {
            return keySet{"rotated-demo": json.RawMessage("{}")}, nil
        },
    }
    ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
    defer cancel()
    var wg sync.WaitGroup
    for i := 0; i < 20; i++ {
        wg.Add(1)
        go func() {
            defer wg.Done()
            _, err := c.key(ctx, "rotated-demo")
            if err != nil {
                fmt.Fprintln(os.Stderr, err)
            }
        }()
    }
    wg.Wait()
    if _, err := c.key(ctx, "random-demo"); err == nil {
        return fmt.Errorf("expected unknown key rejection")
    }
    fmt.Println("Local key-selection exercise completed; no JWT was verified.")

    base := os.Getenv("API_BASE_URL")
    if base == "" {
        return nil
    }
    parsed, err := url.Parse(base)
    if err != nil || parsed.Scheme != "https" || parsed.Host == "" ||
        parsed.User != nil || parsed.RawQuery != "" || parsed.Fragment != "" {
        return fmt.Errorf("configure a trusted HTTPS API base")
    }
    key := os.Getenv("INFRAI_API_KEY")
    userID := os.Getenv("AUTH_USER_ID")
    path := os.Getenv("AUTH_VALUE_PATH")
    if key == "" || userID == "" || path == "" {
        return fmt.Errorf("missing credential, user id, or response selector")
    }
    identity, err := getIdentity(ctx,
        strings.TrimRight(base, "/")+"/auth/user/get/"+url.PathEscape(userID), key)
    if err != nil {
        return err
    }
    var selected any
    if err := json.Unmarshal(identity, &selected); err != nil {
        return err
    }
    for _, name := range strings.Split(path, ",") {
        object, ok := selected.(map[string]any)
        if !ok {
            return fmt.Errorf("selector does not address an object")
        }
        selected, ok = object[name]
        if !ok {
            return fmt.Errorf("selector field absent")
        }
    }
    if selected == nil {
        return fmt.Errorf("selected identity value is null")
    }
    var template any
    if err := json.Unmarshal([]byte(os.Getenv("SMS_REQUEST_JSON")), &template); err != nil {
        return err
    }
    payload, count := substitute(template, selected)
    if count != 1 {
        return fmt.Errorf("SMS template must contain exactly one identity marker")
    }
    data, err := json.Marshal(payload)
    if err != nil {
        return err
    }
    _, err = request(ctx, http.MethodPost,
        strings.TrimRight(base, "/")+"/sms/otp", key, data)
    return err
}

func main() {
    if err := run(); err != nil {
        fmt.Fprintln(os.Stderr, err)
        os.Exit(1)
    }
}
Enter fullscreen mode Exit fullscreen mode

The local loader returns a labeled fixture, not a cryptographic key. Replace it with a parser for the trusted issuer's JWKS before integrating the cache with a maintained JWT verifier; select the key through this cache, then perform signature and claims verification in that verifier. The executable checks cache coordination and rejection behavior. It does not authenticate anyone.

The SMS call is intentionally a single attempt. Before adding automatic retries to a write, confirm the operation's idempotency contract and persist a stable operation identifier for the registration. A transport timeout must not cause an untracked second send. For a rate-limited send, schedule bounded exponential backoff honoring Retry-After only after that deduplication protection exists; the sample instead surfaces the error and stops.

This is also the limit of the integration example: discovery supplies the exact payload contract, and the application supplies the binding between the verified registration and the selected identity. Sharing credentials does not establish that binding for you.

3. Decide what to buy before expanding the trust boundary

Infrai offers one key, one bill, and one REST API for identity and SMS. Its API is self-describing: public discovery supplies schemas and runnable examples, so connecting a capability starts with reading its contract rather than learning a new SDK. A single API key and unified billing reduce credential plumbing across the two capabilities. The trade-off is concentrated trust, billing, and outage exposure in one vendor.

That is a workflow argument. It doesn't establish a better JWT verifier, a captcha accuracy advantage, or an SLO. The limitation is vendor coupling: the combined approach is not a good fit if the platform requires independent identity and SMS vendor boundaries; choose a split stack when that separation outweighs the integration work.

Buy or build choice Work the platform team must evaluate Boundary that remains
Auth0 plus Twilio Verify Two vendor signups and two credential sets; connect the authenticated identity to the verification transaction. Keep issuer-key rotation and SMS transaction handling independently observable.
Clerk plus Twilio Verify Two vendor signups and two credential sets; bind the application's identity to the verification transaction. Confirm the identity and session model fits the media signup flow before adopting the combination.
Keycloak plus a separately selected SMS service Evaluate a self-hosted identity deployment and write the identity-to-message integration. The platform accepts deployment and operational work as part of the build decision.
A combined identity and SMS API Evaluate one credential boundary and inspect both capability contracts before connecting them. Centralization does not remove signature verification, recipient binding, or duplicate-send protection.

These are real alternatives, but the table describes selection work rather than a benchmark. Use the linked product documentation to validate the deployment and verification flow under consideration. Do not infer that a product lacks rotation handling because its row emphasizes a different operational responsibility. The relevant review is concrete: trace one accepted captcha through the authenticated service request, the selected identity value, and the SMS transaction, then assign an owner to each boundary and its rollback. If that ownership cannot be explained before launch, the signup flow has an operational gap regardless of which product owns the identity record. For a platform roadmap, the buy-versus-build decision should include who maintains the cache, who receives the page when refresh fails, and how identity data and SMS integration can move later. A saved SDK integration is useful; indefinite dependence on an opaque contract is a different commitment.

4. Verify recovery, then roll back without weakening signup

In a controlled rotation exercise, warm the verifier with the old key set, introduce a token signed with a new key, and confirm that the miss causes one shared refresh before ordinary verification resumes. Follow that with an unknown key that is absent from the refreshed set. It must remain rejected.

Then run concurrent misses and a refresh failure. Confirm that the refresh budget holds, cached known keys remain available for normal verification, and the signup service reports the verification failure separately from captcha rejection. Preserve normal expiration and claim checks throughout. A known key is not permission to accept an expired token.

The handoff needs its own acceptance check: use a controlled identity and permitted SMS destination, verify the selected response value against the current schema, and confirm that only the matching registration can initiate the send. Check that a retry cannot produce a second logical operation before enabling write retries.

Make the rollback decision against the proposed signup SLO and the refresh budget, not against a quieter error dashboard. If the refresh change causes unacceptable load, revert to the last reviewed verifier configuration while keeping authentication mandatory; hold or reject registrations that cannot be verified. Do not issue sessions to hide a rotation problem, and do not ask readers to solve another captcha as an internal cache repair.

Keep the incident narrow.

A fresh key set repairs stale key selection. It does not repair a wrong issuer, an invalid signature, an incorrect recipient binding, or a broken definition of successful signup.

References

Top comments (0)