Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
81 commits
Select commit Hold shift + click to select a range
6e63daa
xds: read JWT credentials from file as per A97
dimpavloff Jun 14, 2025
3268ea5
remove example
dimpavloff Jul 6, 2025
b18a1f5
refactor test creation
dimpavloff Jul 6, 2025
eb391af
refactor token string padding
dimpavloff Jul 26, 2025
d43893a
remove example; mark as experimental
dimpavloff Jul 29, 2025
167b86e
reorganise struct attributes
dimpavloff Jul 29, 2025
439d28c
rename methods with Locked suffix
dimpavloff Jul 29, 2025
b36d4b6
remove context param from refreshTokenSync
dimpavloff Jul 29, 2025
26e0451
reformat comments; remove redundant cachedErrorTime field
dimpavloff Jul 29, 2025
da2de8c
add defaultTestTimeout const
dimpavloff Jul 29, 2025
51ce34c
refactor test to use wantErr string only
dimpavloff Jul 29, 2025
f87f1f2
fix punctuation
dimpavloff Jul 29, 2025
15dd057
less prosaic subtest names
dimpavloff Jul 29, 2025
54cbbcb
remove unit test
dimpavloff Jul 30, 2025
9c5035d
rename preemptiveRefresh to forceRefresh
dimpavloff Jul 31, 2025
ec915dc
remove unused context param
dimpavloff Jul 31, 2025
1d95fa2
rename files
dimpavloff Aug 21, 2025
a797ed9
use cond variable
dimpavloff Aug 21, 2025
fd388d1
refactor to no longer need cond
dimpavloff Aug 21, 2025
790a2d9
fix docstring comment
dimpavloff Aug 21, 2025
6713190
cache authorization header instead of token
dimpavloff Aug 21, 2025
3f563eb
remove internal/ and xds/ changes
dimpavloff Aug 21, 2025
a38573b
remove xds/bootstrap
dimpavloff Aug 21, 2025
12fedd5
fix comment docstrings
dimpavloff Aug 21, 2025
417652f
add grpctester (#8423)
eshitachandwani Jul 1, 2025
866fc1d
xds: Avoid error logs when setting fallback bootstrap config (#8419)
arjan-bal Jul 1, 2025
4dc1686
dns: add environment variable to disable TXT lookups in DNS resolver …
dfawley Jul 1, 2025
4d0c694
xdsclient: relay marshalled bytes of complete resource proto to decod…
purnesh42H Jul 2, 2025
6b2ad57
xds: cleanup internal testing functions for env vars that have long b…
easwars Jul 2, 2025
4350e2a
grpctest: minor improvements to the test logger implementation (#8370)
asheshvidyut Jul 7, 2025
20f3d41
xds/cdsbalancer: correctly remove the unwanted cds watchers (#8428)
eshitachandwani Jul 8, 2025
b6fd0a9
deps: update dependencies for all modules (#8434)
arjan-bal Jul 9, 2025
4c6db95
server: allow 0s grpc-timeout header values, as java is known to be a…
dfawley Jul 9, 2025
b486205
alts: improve alts handshaker error logs (#8444)
rockspore Jul 10, 2025
fc3b4d9
xds: give up pool lock before closing xdsclient channel (#8445)
dfawley Jul 11, 2025
446caca
Remove inactive maintainers (#8416)
gnossen Jul 11, 2025
325e063
Move erm-g to Emeritus Maintainer (#8418)
gnossen Jul 11, 2025
632e7eb
credentials: allow audience to be configured (#8421) (#8442)
chrisstaite-menlo Jul 14, 2025
94cd548
endpointsharding: shuffle endpoint order before updating children (#8…
dfawley Jul 14, 2025
35b336e
xds: add a test for deadlocks in nested xDS channels (#8448)
arjan-bal Jul 15, 2025
1af6654
transport: release mutex before returning on expired deadlines in ser…
arjan-bal Jul 16, 2025
3185233
Revert "credentials: allow audience to be configured (#8421) (#8442)"…
eshitachandwani Jul 16, 2025
b3fc6f7
Retract v1.74.0 and v1.74.1 (#8456)
dfawley Jul 17, 2025
4ba816f
xdsclient: typed config better nil checks (#8412)
wooffie Jul 18, 2025
ae5aa6e
transport: add test case for zero second timeout (#8452)
dfawley Jul 18, 2025
f90d323
testutils/roundrobin: Improve validation of WRR distribution (#8459)
arjan-bal Jul 21, 2025
99fb5d1
github: run arm64 tests without emulation (#8463)
arjan-bal Jul 21, 2025
e86093a
stats: add DelayedPickComplete and follow correct semantics (#8465)
dfawley Jul 21, 2025
0a097fe
advancedtls: avoid txt lookups in test and use test logger instead of…
arjan-bal Jul 22, 2025
c806552
xdsclient: delay resource cache deletion to handle immediate re-subsc…
purnesh42H Jul 24, 2025
d48493e
protoc-gen-go-grpc: bump golang.org/x/net (#8458)
dependabot[bot] Jul 24, 2025
53c7457
cleanup: use slices.Equal to simplify code (#8472)
jishudashu Jul 24, 2025
735d1e4
Allow empty nodeID (#8476)
davinci26 Jul 29, 2025
159a3bc
xdsclient: do not process updates from closed server channels (#8389)
easwars Jul 29, 2025
80aaa37
examples/opentelemetry: use experimental metrics in example (#8441)
vinothkumarr227 Jul 30, 2025
c8ad648
update deps (#8478)
eshitachandwani Jul 30, 2025
2973e9a
stats: change non-standard units to annotations (#8481)
arjan-bal Aug 1, 2025
bc67bc5
grpc: Fix cardinality violations in non-client streaming RPCs. (#8385)
Pranjali-2501 Aug 5, 2025
a2d06df
xds: remove xds client fallback environment variable (#8482)
cjqzhao Aug 5, 2025
ec22c08
credentials: fix behavior of grpc.WithAuthority and credential handsh…
dfawley Aug 5, 2025
53cb266
Change version to 1.76.0-dev
Pranjali-2501 Aug 6, 2025
ed7dfef
deps: update dependencies for all modules (#8497)
Pranjali-2501 Aug 6, 2025
01163c5
xdsclient: modify how the resource watch state is retrieved for testi…
easwars Aug 6, 2025
90d4314
grpclb: simplify stringifying of IPv6 with net.JoinHostPort (#8503)
alexandear Aug 12, 2025
7ae194d
deps: update github.com/prometheus/client_golang (#8502)
Pranjali-2501 Aug 12, 2025
f340a51
grpcsync: use context.AfterFunc to close buffer after context cancele…
turfaa Aug 12, 2025
21aa74b
xdsclient: schedule serializer callback from the authority instead of…
easwars Aug 13, 2025
db143e5
xdsclient: add an e2e style test for fallback involving more than 2 s…
vinothkumarr227 Aug 14, 2025
61821c4
deps: bump go version to 1.24 (#8509)
kevinGC Aug 14, 2025
8dbee87
grpctest: add test coverages of `ExitIdle` (#8375)
hugehoo Aug 15, 2025
4919174
xds/cdsbalancer: increase buffer size of requested resource channel i…
eshitachandwani Aug 18, 2025
8f85592
xds: move all functionality from `xds/internal` to `internal/xds` (#8…
CynicDog Aug 19, 2025
b06baac
deps: bump Go version in Dockerfiles (#8522)
stanley-cheung Aug 19, 2025
3506cea
transport: ensure header mutex is held while copying trailers in hand…
arjan-bal Aug 21, 2025
b473f1f
github: add PR template (#8524)
dfawley Aug 21, 2025
317ecac
xds: read JWT credentials from file as per A97
dimpavloff Jun 14, 2025
b07fe25
comment punctuation
dimpavloff Aug 7, 2025
79a254d
remove leftover
dimpavloff Aug 7, 2025
f76a9cb
refactor test to use wantErr string only
dimpavloff Aug 7, 2025
a3335b9
tidy comments
dimpavloff Aug 7, 2025
f454768
Merge remote-tracking branch 'origin/master' into a97-xds-stacked-2
dimpavloff Aug 22, 2025
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
50 changes: 50 additions & 0 deletions credentials/jwt/doc.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
/*
*
* Copyright 2025 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 implements JWT token file-based call credentials.
//
// This package provides support for A97 JWT Call Credentials, allowing gRPC
// clients to authenticate using JWT tokens read from files. While originally
// designed for xDS environments, these credentials are general-purpose.
//
// The credentials can be used directly in gRPC clients or configured via xDS.
//
// # Token Requirements
//
// JWT tokens must:
// - Be valid, well-formed JWT tokens with header, payload, and signature
// - Include an "exp" (expiration) claim
// - Be readable from the specified file path
//
// # Considerations
//
// - Tokens are cached until expiration to avoid excessive file I/O
// - Transport security is required (RequireTransportSecurity returns true)
// - Errors in reading tokens or parsing JWTs will result in RPC UNAVAILALBE or
// UNAUTHENTICATED errors. The errors are cached and retried with exponential
// backoff.
//
// This implementation is originally intended for use in service mesh
// environments like Istio where JWT tokens are provisioned and rotated by the
// infrastructure.
//
// # Experimental
//
// Notice: All APIs in this package are experimental and may be removed in a
// later release.
package jwt
58 changes: 58 additions & 0 deletions credentials/jwt/example_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
/*
*
* Copyright 2025 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"
"log"
"time"

"google.golang.org/grpc"
"google.golang.org/grpc/credentials/jwt"
)

// ExampleNewTokenFileCallCredentials demonstrates how to create and use JWT
// token file call credentials for authentication.
func ExampleNewTokenFileCallCredentials() {
// Create JWT call credentials that read tokens from a file
creds, err := jwt.NewTokenFileCallCredentials(
"/path/to/jwt.token", // Path to JWT token file
)
if err != nil {
log.Fatalf("Failed to create JWT credentials: %v", err)
}

// Use the credentials when creating a gRPC connection
conn, err := grpc.NewClient(
"service.example.com:443",
grpc.WithPerRPCCredentials(creds),
// ... other dial options
)
if err != nil {
log.Fatalf("Failed to connect: %v", err)
}
defer conn.Close()

// Use the connection for RPC calls
// The JWT token will be automatically included in the authorization header
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
// ... make RPC calls using ctx and conn
_ = ctx
}
103 changes: 103 additions & 0 deletions credentials/jwt/jwt_file_reader.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
/*
*
* Copyright 2025 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

import (
"encoding/base64"
"encoding/json"
"fmt"
"os"
"strings"
"time"
)

// jwtClaims represents the JWT claims structure for extracting expiration time.
type jwtClaims struct {

Check failure on line 31 in credentials/jwt/jwt_file_reader.go

View workflow job for this annotation

GitHub Actions / upload

other declaration of jwtClaims

Check failure on line 31 in credentials/jwt/jwt_file_reader.go

View workflow job for this annotation

GitHub Actions / tests (extras, 1.25)

other declaration of jwtClaims

Check failure on line 31 in credentials/jwt/jwt_file_reader.go

View workflow job for this annotation

GitHub Actions / tests (tests, 1.24)

other declaration of jwtClaims

Check failure on line 31 in credentials/jwt/jwt_file_reader.go

View workflow job for this annotation

GitHub Actions / tests (tests, 1.25)

other declaration of jwtClaims

Check failure on line 31 in credentials/jwt/jwt_file_reader.go

View workflow job for this annotation

GitHub Actions / tests (tests, 1.25, arm64, ubuntu-24.04-arm)

other declaration of jwtClaims

Check failure on line 31 in credentials/jwt/jwt_file_reader.go

View workflow job for this annotation

GitHub Actions / tests (tests, 1.25, 386)

other declaration of jwtClaims

Check failure on line 31 in credentials/jwt/jwt_file_reader.go

View workflow job for this annotation

GitHub Actions / tests (tests, 1.25, -race)

other declaration of jwtClaims

Check failure on line 31 in credentials/jwt/jwt_file_reader.go

View workflow job for this annotation

GitHub Actions / tests (tests, 1.25, -race, GRPC_EXPERIMENTAL_ENABLE_NEW_PICK_FIRST=false)

other declaration of jwtClaims
Exp int64 `json:"exp"`
}

// jWTFileReader handles reading and parsing JWT tokens from files.
type jWTFileReader struct {
tokenFilePath string
}

// newJWTFileReader creates a new JWTFileReader for the specified file path.
func newJWTFileReader(tokenFilePath string) *jWTFileReader {
return &jWTFileReader{
tokenFilePath: tokenFilePath,
}
}

// ReadToken reads and parses a JWT token from the configured file.
// Returns the token string, expiration time, and any error encountered.
func (r *jWTFileReader) ReadToken() (string, time.Time, error) {
tokenBytes, err := os.ReadFile(r.tokenFilePath)
if err != nil {
return "", time.Time{}, fmt.Errorf("failed to read token file %q: %v", r.tokenFilePath, err)
}

token := strings.TrimSpace(string(tokenBytes))
if token == "" {
return "", time.Time{}, fmt.Errorf("token file %q is empty", r.tokenFilePath)
}

exp, err := r.extractExpiration(token)
if err != nil {
return "", time.Time{}, fmt.Errorf("failed to parse JWT from token file %q: %v", r.tokenFilePath, err)
}

return token, exp, nil
}

// extractExpiration parses the JWT token to extract the expiration time.
func (r *jWTFileReader) extractExpiration(token string) (time.Time, error) {
parts := strings.Split(token, ".")
if len(parts) != 3 {
return time.Time{}, fmt.Errorf("invalid JWT format: expected 3 parts, got %d", len(parts))
}

payload := parts[1]
// Add padding if necessary for base64 decoding.
if m := len(payload) % 4; m != 0 {
payload += strings.Repeat("=", 4-m)
}

payloadBytes, err := base64.URLEncoding.DecodeString(payload)
if err != nil {
return time.Time{}, fmt.Errorf("failed to decode JWT payload: %v", err)
}

var claims jwtClaims
if err := json.Unmarshal(payloadBytes, &claims); err != nil {
return time.Time{}, fmt.Errorf("failed to unmarshal JWT claims: %v", err)
}

if claims.Exp == 0 {
return time.Time{}, fmt.Errorf("JWT token has no expiration claim")
}

expTime := time.Unix(claims.Exp, 0)

// Check if token is already expired.
if expTime.Before(time.Now()) {
return time.Time{}, fmt.Errorf("JWT token is expired")
}

return expTime, nil
}
180 changes: 180 additions & 0 deletions credentials/jwt/jwt_file_reader_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,180 @@
/*
*
* Copyright 2025 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

import (
"encoding/base64"
"encoding/json"
"fmt"
"os"
"path/filepath"
"strings"
"testing"
"time"
)

func TestJWTFileReader_ReadToken_FileErrors(t *testing.T) {
tests := []struct {
name string
setupFile func(string) error
wantErrContains string
}{
{
name: "nonexistent file",
setupFile: func(_ string) error {
return nil // Don't create the file
},
wantErrContains: "failed to read token file",
},
{
name: "empty file",
setupFile: func(path string) error {
return os.WriteFile(path, []byte(""), 0600)
},
wantErrContains: "token file",
},
{
name: "file with whitespace only",
setupFile: func(path string) error {
return os.WriteFile(path, []byte(" \n\t "), 0600)
},
wantErrContains: "token file",
},
}

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
tempDir := t.TempDir()
tokenFile := filepath.Join(tempDir, "token")
if err := tt.setupFile(tokenFile); err != nil {
t.Fatalf("Failed to setup test file: %v", err)
}

reader := newJWTFileReader(tokenFile)
_, _, err := reader.ReadToken()
if err == nil {
t.Fatal("ReadToken() expected error, got nil")
}

if !strings.Contains(err.Error(), tt.wantErrContains) {
t.Fatalf("ReadToken() error = %v, want error containing %q", err, tt.wantErrContains)
}
})
}
}

func TestJWTFileReader_ReadToken_InvalidJWT(t *testing.T) {
now := time.Now().Truncate(time.Second)
tests := []struct {
name string
tokenContent string
wantErrContains string
}{
{
name: "valid token without expiration",
tokenContent: createTestJWT(t, "", time.Time{}),
wantErrContains: "JWT token has no expiration claim",
},
{
name: "expired token",
tokenContent: createTestJWT(t, "", now.Add(-time.Hour)),
wantErrContains: "JWT token is expired",
},
{
name: "malformed JWT - not enough parts",
tokenContent: "invalid.jwt",
wantErrContains: "invalid JWT format: expected 3 parts, got 2",
},
{
name: "malformed JWT - invalid base64",
tokenContent: "header.invalid_base64!@#.signature",
wantErrContains: "failed to decode JWT payload",
},
{
name: "malformed JWT - invalid JSON",
tokenContent: createInvalidJSONJWT(t),
wantErrContains: "failed to unmarshal JWT claims",
},
}

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
tokenFile := writeTempFile(t, "token", tt.tokenContent)

reader := newJWTFileReader(tokenFile)
_, _, err := reader.ReadToken()
if err == nil {
t.Fatal("ReadToken() expected error, got nil")
}

if !strings.Contains(err.Error(), tt.wantErrContains) {
t.Fatalf("ReadToken() error = %v, want error containing %q", err, tt.wantErrContains)
}
})
}
}

func TestJWTFileReader_ReadToken_ValidToken(t *testing.T) {
now := time.Now().Truncate(time.Second)
tokenExp := now.Add(time.Hour)
token := createTestJWT(t, "https://example.com", tokenExp)
tokenFile := writeTempFile(t, "token", token)

reader := newJWTFileReader(tokenFile)
readToken, expiry, err := reader.ReadToken()
if err != nil {
t.Fatalf("ReadToken() unexpected error: %v", err)
}

if readToken != token {
t.Errorf("ReadToken() token = %q, want %q", readToken, token)
}

if !expiry.Equal(tokenExp) {
t.Errorf("ReadToken() expiry = %v, want %v", expiry, tokenExp)
}
}

// createInvalidJSONJWT creates a JWT with invalid JSON in the payload.
func createInvalidJSONJWT(t *testing.T) string {
t.Helper()

header := map[string]any{
"typ": "JWT",
"alg": "HS256",
}

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

headerB64 := base64.URLEncoding.EncodeToString(headerBytes)
headerB64 = strings.TrimRight(headerB64, "=")

// Create invalid JSON payload
invalidJSON := "invalid json content"
payloadB64 := base64.URLEncoding.EncodeToString([]byte(invalidJSON))
payloadB64 = strings.TrimRight(payloadB64, "=")

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

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