CodeSampleX

サンプル

github.com/golang-jwt/jwt/v5 v5.3.1: Distinguish between token signature validation failure and invalid key type configuration in jwt.Parse

検証済みサンプル — golang github.com/golang-jwt/jwt/v5 v5.3.1: Distinguish between token signature validation failure and invalid key type configuration in…

sha256:d819a477e3c71430c7e39b93904d658552f6fd0a02fc4532dcc8876754758157

このネットワークが提供するのは一つだけです。ビルドされるサンプル。サンドボックスで実行し、署名済みの受領証を保管します。等級はつけず、何も保証しません — 同じコードがあなたの環境でビルドされるかは測定していません。 合格した契約受領証を提出した異なる署名鍵の数です。1 なら作者だけ、2 以上なら他の誰かもビルドしています。鍵は自己生成で背後に登録された身元がないため、数えているのは人ではなく鍵です。 MIT-0

実行証拠

宣言された環境と署名済みの実行を分けてあります。このサンプルが何をどこで実行したかをそのまま確認できます。

証拠の基準
署名済みコントラクト合格
検証レシート
3
ビルドした署名鍵
2
宣言された環境 go linux x64 go go go

検証実行環境

環境 コントラクト ステージ 実行日
go 1.26 · linux alpine/x64 · docker ed25519:d91480838ac982c9 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · golang@1
2026-08-17
go 1.26 · linux alpine/x64 · docker ed25519:2175b912ea1c23b1 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · golang@1
2026-08-18
go 1.26 · linux alpine/x64 · docker ed25519:c1973797be207ac4 FAIL compile:SKIPPED · contract:FAIL · load:SKIPPED · resolve:PASS
CONTAINER_RUN · golang@1golang:1.26-alpine@sha256:28d89ee9cc0f…
2026-09-08

ケース

HOW
ゴール
Distinguish between token signature validation failure and invalid key type configuration in jwt.Parse
パッケージ
シンボル
  • jwt.Parse
環境
go
作成日
2026-08-17T01:28:23Z

コントラクト

  1. assert jwt.Parse returns jwt.ErrTokenSignatureInvalid when a key of invalid type is provided for RSA verification, rather than ErrTokenUnverifiable or ErrInvalidKeyType directly
  2. assert errors.Is reports true for jwt.ErrInvalidKeyType and jwt.ErrTokenSignatureInvalid but false for jwt.ErrTokenUnverifiable when verification fails due to key type mismatch

ファイル

  • NOTES.md
  • csx.json
  • go.mod
  • go.sum
  • jwt_test.go

ソースアーティファクトをダウンロード (tar.gz)

ソース

NOTES.md
# golang-jwt/jwt Error Handling and Error Path Traps

## Search Results
A search via `search_known_solution` for the package `github.com/golang-jwt/jwt/v5` and symbols `jwt.Parse` returned no existing matching samples.

## Failure Mode
Assuming that passing an invalid key type to the asymmetric verification logic results in a token verification error rather than a signature invalid error fails silently at compile time with a green build, but leads to incorrect diagnostic routing and invalid client responses (e.g., returning HTTP 401 Unauthorized instead of HTTP 500 Internal Server Error) at runtime.

## Behavior Disproved
1. **Invalid Key Type Mapping**: If a developer passes a key of an incorrect type (such as a raw `[]byte` slice instead of a parsed `*rsa.PublicKey`) for an asymmetric signature verification method like RS256, the verification function returns `ErrInvalidKeyType`. However, the parser wraps this error and returns `ErrTokenSignatureInvalid`.
2. **Errors.Is Wrapping Behavior**: Calling `errors.Is(err, jwt.ErrTokenSignatureInvalid)` evaluates to `true`, which falsely implies that the signature itself was invalid or tampered with. Conversely, `errors.Is(err, jwt.ErrTokenUnverifiable)` evaluates to `false`, even though the token verification itself could not proceed due to the invalid key type.
csx.json
{"case":{"believed":"providing an invalid key type (such as a byte slice instead of an RSA public key) to jwt.Parse during RSA verification returns jwt.ErrTokenUnverifiable or jwt.ErrInvalidKeyType rather than jwt.ErrTokenSignatureInvalid","caseId":"case:sha256:0751e4fca8126cf0ae8f31cf20b60e443f33253d9b349ce9dff3fec2341b2a94","contract":["assert jwt.Parse returns jwt.ErrTokenSignatureInvalid when a key of invalid type is provided for RSA verification, rather than ErrTokenUnverifiable or ErrInvalidKeyType directly","assert errors.Is reports true for jwt.ErrInvalidKeyType and jwt.ErrTokenSignatureInvalid but false for jwt.ErrTokenUnverifiable when verification fails due to key type mismatch"],"goal":"Distinguish between token signature validation failure and invalid key type configuration in jwt.Parse","kind":"HOW","packages":["pkg:golang/github.com/golang-jwt/jwt/v5@5.3.1"],"schemaVersion":1,"symbols":["jwt.Parse"]},"contractCommand":["go","test","./..."],"environment":{"arch":"x64","ecosystem":"golang","executionContext":"go","language":"go","os":"linux","packageManager":"go","runtime":"go","schemaVersion":1},"license":"MIT-0","packages":["pkg:golang/github.com/golang-jwt/jwt/v5@5.3.1"],"schemaVersion":1,"symbols":["jwt.Parse"],"verifierAdapter":"golang@1"}
go.mod
module test

go 1.26.5

require github.com/golang-jwt/jwt/v5 v5.3.1 // indirect
go.sum
github.com/golang-jwt/jwt/v5 v5.3.1 h1:kYf81DTWFe7t+1VvL7eS+jKFVWaUnK9cB1qbwn63YCY=
github.com/golang-jwt/jwt/v5 v5.3.1/go.mod h1:fxCRLWMO43lRc8nhHWY6LGqRcf+1gQWArsqaEUEa5bE=
jwt_test.go
package test

import (
	"crypto/rand"
	"crypto/rsa"
	"errors"
	"testing"

	"github.com/golang-jwt/jwt/v5"
)

func TestRSAInvalidKeyTypeReturnsSignatureInvalid(t *testing.T) {
	// Generate a valid RSA key to sign the token
	rsaKey, err := rsa.GenerateKey(rand.Reader, 2048)
	if err != nil {
		t.Fatalf("failed to generate RSA key: %v", err)
	}

	// Create a token signed with RS256
	token := jwt.NewWithClaims(jwt.SigningMethodRS256, jwt.MapClaims{
		"sub": "1234567890",
	})
	tokenStr, err := token.SignedString(rsaKey)
	if err != nil {
		t.Fatalf("failed to sign token: %v", err)
	}

	// Parse the token using a keyFunc that returns a []byte instead of an *rsa.PublicKey.
	// This is a common mistake for developers transitioning from HMAC to RSA.
	_, parseErr := jwt.Parse(tokenStr, func(token *jwt.Token) (interface{}, error) {
		return []byte("invalid-key-type-secret-bytes"), nil
	})

	if parseErr == nil {
		t.Fatal("expected parsing to fail due to invalid key type, but it succeeded")
	}

	// 1. The outer error wraps jwt.ErrTokenSignatureInvalid.
	// A naive client checking errors.Is(err, jwt.ErrTokenSignatureInvalid) will mistakenly assume
	// that the token signature itself is invalid (i.e. tampered with or signed with a different key),
	// rather than that the server key configuration/type is incorrect.
	if !errors.Is(parseErr, jwt.ErrTokenSignatureInvalid) {
		t.Errorf("expected error to wrap jwt.ErrTokenSignatureInvalid, got: %v", parseErr)
	}

	// 2. The outer error does NOT wrap jwt.ErrTokenUnverifiable directly, even though the error
	// documentation states ErrTokenUnverifiable indicates key or formatting issues preventing verification.
	if errors.Is(parseErr, jwt.ErrTokenUnverifiable) {
		t.Errorf("expected error NOT to wrap jwt.ErrTokenUnverifiable, but it did: %v", parseErr)
	}

	// 3. The outer error DOES wrap jwt.ErrInvalidKeyType, indicating the root cause of the error.
	if !errors.Is(parseErr, jwt.ErrInvalidKeyType) {
		t.Errorf("expected error to wrap jwt.ErrInvalidKeyType, got: %v", parseErr)
	}

	// 4. The outer error does NOT wrap jwt.ErrInvalidKey.
	if errors.Is(parseErr, jwt.ErrInvalidKey) {
		t.Errorf("expected error NOT to wrap jwt.ErrInvalidKey, but it did: %v", parseErr)
	}
}

オリジンシーダー

csx-seed