Skip to content
Open
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
258 changes: 258 additions & 0 deletions credentials/jwt/jwt_e2e_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,258 @@
/*
*
* Copyright 2026 gRPC authors.
*
* 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 jwt_test

import (
"context"
"crypto/tls"
"encoding/base64"
"encoding/json"
"fmt"
"os"
"path/filepath"
"strings"
"testing"
"time"

"google.golang.org/grpc"
"google.golang.org/grpc/credentials"
"google.golang.org/grpc/credentials/insecure"
"google.golang.org/grpc/credentials/jwt"
"google.golang.org/grpc/internal/grpctest"
"google.golang.org/grpc/internal/stubserver"
"google.golang.org/grpc/metadata"
"google.golang.org/grpc/testdata"

testgrpc "google.golang.org/grpc/interop/grpc_testing"
testpb "google.golang.org/grpc/interop/grpc_testing"
)

const defaultTestTimeout = 5 * time.Second

type s struct {
grpctest.Tester
}

func Test(t *testing.T) {
grpctest.RunSubTests(t, s{})
}

// createTestJWT creates a test JWT token with the specified expiration.
func createTestJWT(t *testing.T, expiration time.Time) string {
t.Helper()

claims := map[string]any{}
if !expiration.IsZero() {
claims["exp"] = expiration.Unix()
}

header := map[string]any{
"typ": "JWT",
"alg": "HS256",
}
headerBytes, err := json.Marshal(header)
if err != nil {
t.Fatalf("Failed to marshal header: %v", err)
}

claimsBytes, err := json.Marshal(claims)
if err != nil {
t.Fatalf("Failed to marshal claims: %v", err)
}

headerB64 := base64.URLEncoding.EncodeToString(headerBytes)
claimsB64 := base64.URLEncoding.EncodeToString(claimsBytes)

headerB64 = strings.TrimRight(headerB64, "=")
claimsB64 = strings.TrimRight(claimsB64, "=")

signature := base64.URLEncoding.EncodeToString([]byte("fake_signature"))
signature = strings.TrimRight(signature, "=")

return fmt.Sprintf("%s.%s.%s", headerB64, claimsB64, signature)
}

// writeTempTokenFile creates a temporary file with the given JWT token content.
func writeTempTokenFile(t *testing.T, token string) string {
t.Helper()
tempDir := t.TempDir()
filePath := filepath.Join(tempDir, "jwt_token")
if err := os.WriteFile(filePath, []byte(token), 0600); err != nil {
t.Fatalf("Failed to write temp token file: %v", err)
}
return filePath
}

// TestJWTCallCredentials_InsecureTransport_AsCallOption verifies that when JWT
// call credentials (which require transport security) are used with an insecure
// transport as a per-RPC call option, the RPC fails with a meaningful error.
//
// This is an e2e test for gRFC A97 JWT call credentials behavior.
func (s) TestJWTCallCredentials_InsecureTransport_AsCallOption(t *testing.T) {
token := createTestJWT(t, time.Now().Add(time.Hour))
tokenFile := writeTempTokenFile(t, token)

jwtCreds, err := jwt.NewTokenFileCallCredentials(tokenFile)
if err != nil {
t.Fatalf("jwt.NewTokenFileCallCredentials(%q) failed: %v", tokenFile, err)
}

ss := &stubserver.StubServer{
EmptyCallF: func(context.Context, *testpb.Empty) (*testpb.Empty, error) {
return &testpb.Empty{}, nil
},
}
if err := ss.StartServer(grpc.Creds(insecure.NewCredentials())); err != nil {
t.Fatalf("Failed to start server: %v", err)
}
defer ss.Stop()

cc, err := grpc.NewClient(ss.Address, grpc.WithTransportCredentials(insecure.NewCredentials()))
if err != nil {
t.Fatalf("grpc.NewClient(%q) failed: %v", ss.Address, err)
}
defer cc.Close()

ctx, cancel := context.WithTimeout(context.Background(), defaultTestTimeout)
defer cancel()

client := testgrpc.NewTestServiceClient(cc)
_, err = client.EmptyCall(ctx, &testpb.Empty{}, grpc.PerRPCCredentials(jwtCreds))

if err == nil {
t.Fatal("EmptyCall() succeeded; want error about secure credentials on insecure connection")
}

const wantErrSubstring = "cannot send secure credentials on an insecure connection"
if !strings.Contains(err.Error(), wantErrSubstring) {
t.Fatalf("EmptyCall() error = %v; want error containing %q", err, wantErrSubstring)
}
}

// TestJWTCallCredentials_InsecureTransport_AsDialOption verifies that when JWT
// call credentials (which require transport security) are configured as a dial
// option with an insecure transport, the client creation fails with a
// meaningful error.
//
// This is an e2e test for gRFC A97 JWT call credentials behavior.
func (s) TestJWTCallCredentials_InsecureTransport_AsDialOption(t *testing.T) {
token := createTestJWT(t, time.Now().Add(time.Hour))
tokenFile := writeTempTokenFile(t, token)

jwtCreds, err := jwt.NewTokenFileCallCredentials(tokenFile)
if err != nil {
t.Fatalf("jwt.NewTokenFileCallCredentials(%q) failed: %v", tokenFile, err)
}

ss := &stubserver.StubServer{
EmptyCallF: func(context.Context, *testpb.Empty) (*testpb.Empty, error) {
return &testpb.Empty{}, nil
},
}
if err := ss.StartServer(grpc.Creds(insecure.NewCredentials())); err != nil {
t.Fatalf("Failed to start server: %v", err)
}
defer ss.Stop()

dopts := []grpc.DialOption{
grpc.WithTransportCredentials(insecure.NewCredentials()),
grpc.WithPerRPCCredentials(jwtCreds),
}

const wantErrSubstring = "the credentials require transport level security"
_, err = grpc.NewClient(ss.Address, dopts...)
if err == nil || !strings.Contains(err.Error(), wantErrSubstring) {
t.Fatalf("grpc.NewClient() error = %v; want error containing %q", err, wantErrSubstring)
}
}

// TestJWTCallCredentials_SecureTransport verifies that JWT call credentials
// work correctly when used with a secure transport (TLS).
//
// This is a positive e2e test for gRFC A97 JWT call credentials behavior.
func (s) TestJWTCallCredentials_SecureTransport(t *testing.T) {
token := createTestJWT(t, time.Now().Add(time.Hour))
tokenFile := writeTempTokenFile(t, token)

jwtCreds, err := jwt.NewTokenFileCallCredentials(tokenFile)
if err != nil {
t.Fatalf("jwt.NewTokenFileCallCredentials(%q) failed: %v", tokenFile, err)
}

expectedAuth := "Bearer " + token
ss := &stubserver.StubServer{
EmptyCallF: func(ctx context.Context, _ *testpb.Empty) (*testpb.Empty, error) {
md, ok := metadata.FromIncomingContext(ctx)
if !ok {
t.Error("No metadata received")
return nil, fmt.Errorf("no metadata received")
}
authHeaders := md.Get("authorization")
if len(authHeaders) != 1 {
t.Errorf("Expected 1 authorization header, got %d", len(authHeaders))
return nil, fmt.Errorf("expected 1 authorization header, got %d", len(authHeaders))
}
if authHeaders[0] != expectedAuth {
t.Errorf("Authorization header = %q, want %q", authHeaders[0], expectedAuth)
return nil, fmt.Errorf("authorization header mismatch")
}
return &testpb.Empty{}, nil
},
}

serverCert, err := tls.LoadX509KeyPair(
testdata.Path("x509/server1_cert.pem"),
testdata.Path("x509/server1_key.pem"),
)
if err != nil {
t.Fatalf("Failed to load server cert: %v", err)
}
serverCreds := credentials.NewServerTLSFromCert(&serverCert)

if err := ss.StartServer(grpc.Creds(serverCreds)); err != nil {
t.Fatalf("Failed to start server: %v", err)
}
defer ss.Stop()

clientCreds, err := credentials.NewClientTLSFromFile(
testdata.Path("x509/server_ca_cert.pem"),
"x.test.example.com",
)
if err != nil {
t.Fatalf("Failed to create client TLS credentials: %v", err)
}

cc, err := grpc.NewClient(
ss.Address,
grpc.WithTransportCredentials(clientCreds),
grpc.WithPerRPCCredentials(jwtCreds),
)
if err != nil {
t.Fatalf("grpc.NewClient(%q) failed: %v", ss.Address, err)
}
defer cc.Close()

ctx, cancel := context.WithTimeout(context.Background(), defaultTestTimeout)
defer cancel()

client := testgrpc.NewTestServiceClient(cc)
if _, err = client.EmptyCall(ctx, &testpb.Empty{}); err != nil {
t.Fatalf("EmptyCall() failed: %v", err)
}
}
Loading