-
Notifications
You must be signed in to change notification settings - Fork 4.6k
credentials: add end-to-end tests for JWT call credentials behavior #8818
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
iamrajiv
wants to merge
6
commits into
grpc:master
Choose a base branch
from
iamrajiv:8635
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+271
−0
Open
Changes from 3 commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
832614c
Add end-to-end tests for JWT call credentials behavior
iamrajiv 8df024e
fix typos
iamrajiv 7e94774
year
iamrajiv 508402d
tdt
iamrajiv 9b366bf
Address review feedback
iamrajiv e40e0b3
Address review feedback
iamrajiv File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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) { | ||
iamrajiv marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| 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) | ||
| } | ||
| } | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.