fix(httpauth-jwt): WithJSONNumber in Verify, JSON errors in AuthMiddleware, bump httpauth v1.0.2 (#1)

Pass jwt.WithJSONNumber() to jwt.Parse in hmacSigner.Verify, rsaSigner.Verify, and
rsaPublicVerifier.Verify. JWT numbers (including permission bitmasks) are now decoded
as json.Number instead of float64 — exact parsing for all integers including
math.MaxInt64 (the ADMIN wildcard mask). Float64 would round MaxInt64 to 2^63 and
overflow back to math.MinInt64 on cast to int64.

AuthMiddleware now calls httpauth.WriteJSONError for all 401 responses instead of
http.Error. Standardizes the error format across the full httpauth-* middleware stack:
AuthMiddleware (httpauth-jwt), EnrichmentMiddleware, and AuthzMiddleware (httpauth)
all produce {"code":"UNAUTHENTICATED"|"PERMISSION_DENIED"|"INTERNAL","message":"..."}.

Update two existing tests (TestIssueTokenPair_CustomClaims,
TestRefreshTokenPair_CustomClaimsInNewToken) to assert json.Number instead of float64
— they were correct before WithJSONNumber, now reflect the actual decoded type.

Add TestVerify_JSONNumberPreservesMaxInt64: issues a token with math.MaxInt64 as a
bitmask, verifies it, and asserts the decoded value is exactly math.MaxInt64 via
json.Number.Int64() — proving no float64 round-trip occurs.

Add TestAuthMiddleware_UnauthorizedJSON: asserts the 401 response is
Content-Type: application/json with body {"code":"UNAUTHENTICATED","message":"..."}.

Bump httpauth dependency to v1.0.2.

Reviewed-on: #1
Co-authored-by: Rene Nochebuena Guerrero <rene@nochebuena.dev>
Co-committed-by: Rene Nochebuena Guerrero <rene@nochebuena.dev>
This commit was merged in pull request #1.
This commit is contained in:
2026-05-18 14:38:54 -06:00
committed by NOCHEBUENADEV
parent 9e29f60f67
commit 941b8972ed
6 changed files with 106 additions and 16 deletions

View File

@@ -4,7 +4,9 @@ import (
"context"
"crypto/rand"
"crypto/rsa"
"encoding/json"
"errors"
"math"
"net/http"
"net/http/httptest"
"testing"
@@ -152,7 +154,7 @@ func TestIssueTokenPair_StandardClaims(t *testing.T) {
func TestIssueTokenPair_CustomClaims(t *testing.T) {
custom := map[string]any{
"permisos": map[string]any{"usuarios": float64(515)},
"permisos": map[string]any{"usuarios": int64(515)},
}
pair, err := IssueTokenPair(testHMAC, "uid1", custom, testCfg)
if err != nil {
@@ -164,8 +166,13 @@ func TestIssueTokenPair_CustomClaims(t *testing.T) {
if !ok {
t.Fatalf("permisos claim missing or wrong type: %T", mc["permisos"])
}
if permisos["usuarios"] != float64(515) {
t.Errorf("want usuarios=515, got %v", permisos["usuarios"])
// Verify uses jwt.WithJSONNumber — numeric claims come back as json.Number.
n, ok := permisos["usuarios"].(json.Number)
if !ok {
t.Fatalf("want json.Number, got %T", permisos["usuarios"])
}
if v, _ := n.Int64(); v != 515 {
t.Errorf("want usuarios=515, got %d", v)
}
}
@@ -277,8 +284,48 @@ func TestRefreshTokenPair_CustomClaimsInNewToken(t *testing.T) {
if !ok {
t.Fatalf("permisos missing from new access token")
}
if permisos["usuarios"] != float64(7) {
t.Errorf("want 7, got %v", permisos["usuarios"])
// Verify uses jwt.WithJSONNumber — numeric claims come back as json.Number.
n, ok := permisos["usuarios"].(json.Number)
if !ok {
t.Fatalf("want json.Number, got %T", permisos["usuarios"])
}
if v, _ := n.Int64(); v != 7 {
t.Errorf("want 7, got %d", v)
}
}
// --- json.Number precision ---
func TestVerify_JSONNumberPreservesMaxInt64(t *testing.T) {
// math.MaxInt64 cannot be represented exactly as float64 — it would round to 2^63
// and overflow back to math.MinInt64 on cast. WithJSONNumber keeps it as a decimal
// string and json.Number.Int64() parses it exactly.
custom := map[string]any{
"masks": map[string]any{"*": int64(math.MaxInt64)},
}
pair, err := IssueTokenPair(testHMAC, "uid1", custom, testCfg)
if err != nil {
t.Fatalf("IssueTokenPair: %v", err)
}
tok, err := testHMAC.Verify(pair.AccessToken)
if err != nil {
t.Fatalf("Verify: %v", err)
}
mc, _ := tok.Claims.(jwt.MapClaims)
masks, ok := mc["masks"].(map[string]any)
if !ok {
t.Fatalf("masks claim missing or wrong type: %T", mc["masks"])
}
n, ok := masks["*"].(json.Number)
if !ok {
t.Fatalf("want json.Number, got %T — WithJSONNumber() may not be set", masks["*"])
}
got, err := n.Int64()
if err != nil {
t.Fatalf("Int64(): %v", err)
}
if got != math.MaxInt64 {
t.Errorf("want MaxInt64 (%d), got %d — precision lost in float64 round-trip", int64(math.MaxInt64), got)
}
}
@@ -364,6 +411,27 @@ func TestAuthMiddleware_PublicPathWildcard(t *testing.T) {
}
}
func TestAuthMiddleware_UnauthorizedJSON(t *testing.T) {
h := AuthMiddleware(testHMAC, nil)(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
}))
rec := httptest.NewRecorder()
h.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/api", nil))
if rec.Code != http.StatusUnauthorized {
t.Errorf("want 401, got %d", rec.Code)
}
if ct := rec.Header().Get("Content-Type"); ct != "application/json" {
t.Errorf("want Content-Type application/json, got %q", ct)
}
var body map[string]any
if err := json.NewDecoder(rec.Body).Decode(&body); err != nil {
t.Fatalf("response body is not valid JSON: %v", err)
}
if body["code"] != "UNAUTHENTICATED" {
t.Errorf("want code UNAUTHENTICATED, got %q", body["code"])
}
}
func TestAuthMiddleware_RSAPublicKeyVerifier(t *testing.T) {
verifier := NewRSAPublicKeyVerifier(&testRSAKey.PublicKey)
pair, _ := IssueTokenPair(testRSA, "uid1", nil, testCfg)