Skip to content
Merged
74 changes: 74 additions & 0 deletions internal/xds/bootstrap/accesstokencreds/call_creds.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
/*
*
* 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 accesstokencreds implements static access token CallCredentials for
// xDS-configured side channels, as specified in gRFC A102.
package accesstokencreds

import (
"context"
"encoding/json"
"fmt"

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

// NewCallCredentials returns call credentials that attach a static bearer
// token to outgoing RPCs. The config must be a JSON object of the form
// {"token": <non-empty string>}.
//
// The caller is expected to invoke the cancel function when they are done
// using the returned call creds. This cancel function is idempotent.
func NewCallCredentials(configJSON json.RawMessage) (credentials.PerRPCCredentials, func(), error) {
var cfg struct {
Token string `json:"token"`
}
emptyFn := func() {}

if err := json.Unmarshal(configJSON, &cfg); err != nil {
return nil, emptyFn, fmt.Errorf("failed to unmarshal access token call credentials config: %v", err)
}
if cfg.Token == "" {
return nil, emptyFn, fmt.Errorf("token is required in access token call credentials config")
}
return &callCreds{token: cfg.Token}, emptyFn, nil
}

// callCreds implements credentials.PerRPCCredentials by attaching a static
// bearer token to each RPC.
type callCreds struct {
token string
}

// GetRequestMetadata returns the token as an authorization header, but only
// when the connection provides privacy and integrity. On weaker connections
// the token is withheld without failing the RPC, as per gRFC A102.
Comment thread
easwars marked this conversation as resolved.
Outdated
func (c *callCreds) GetRequestMetadata(ctx context.Context, _ ...string) (map[string]string, error) {
ri, ok := credentials.RequestInfoFromContext(ctx)
if !ok || credentials.CheckSecurityLevel(ri.AuthInfo, credentials.PrivacyAndIntegrity) != nil {
return nil, nil
}
return map[string]string{"authorization": "Bearer " + c.token}, nil
}

// RequireTransportSecurity returns false. The credentials may be used on any
Comment thread
easwars marked this conversation as resolved.
Outdated
// connection, but GetRequestMetadata withholds the token on connections that
// do not provide privacy and integrity.
Comment thread
easwars marked this conversation as resolved.
Outdated
func (c *callCreds) RequireTransportSecurity() bool {
return false
}
128 changes: 128 additions & 0 deletions internal/xds/bootstrap/accesstokencreds/call_creds_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,128 @@
/*
*
* 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 accesstokencreds

import (
"context"
"encoding/json"
"testing"
"time"

"google.golang.org/grpc/credentials"
"google.golang.org/grpc/internal/grpctest"
)

type s struct {
grpctest.Tester
}

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

func (s) TestNewCallCredentialsWithInvalidConfig(t *testing.T) {
tests := []struct {
name string
config string
}{
{
name: "not_an_object",
config: `""`,
},
{
name: "empty_config",
config: `{}`,
},
{
name: "empty_token",
config: `{"token": ""}`,
},
}

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
callCreds, cleanup, err := NewCallCredentials(json.RawMessage(tt.config))
if err == nil {
t.Fatalf("NewCallCredentials(%s): got nil, want error", tt.config)
}
if callCreds != nil {
t.Errorf("NewCallCredentials(%s): returned non-nil call credentials", tt.config)
}
if cleanup == nil {
t.Errorf("NewCallCredentials(%s): returned nil cleanup function", tt.config)
}
})
}
}

// Tests that the token is attached as a bearer authorization header on
// connections providing privacy and integrity, and is withheld without error
// on weaker connections.
func (s) TestGetRequestMetadata(t *testing.T) {
const config = `{"token": "test-token"}`
callCreds, cleanup, err := NewCallCredentials(json.RawMessage(config))
if err != nil {
t.Fatalf("NewCallCredentials(%s) failed: %v", config, err)
}
defer cleanup()

if callCreds.RequireTransportSecurity() {
t.Error("RequireTransportSecurity() = true, want false")
}

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

// The token must be attached on a connection with privacy and integrity.
secureCtx := credentials.NewContextWithRequestInfo(ctx, credentials.RequestInfo{
AuthInfo: &testAuthInfo{secLevel: credentials.PrivacyAndIntegrity},
})
md, err := callCreds.GetRequestMetadata(secureCtx)
if err != nil {
t.Fatalf("GetRequestMetadata() on a secure connection failed: %v", err)
}
if got, want := md["authorization"], "Bearer test-token"; got != want {
t.Fatalf("GetRequestMetadata() on a secure connection returned authorization header %q, want %q", got, want)
}

// The token must be withheld, without error, on an insecure connection.
insecureCtx := credentials.NewContextWithRequestInfo(ctx, credentials.RequestInfo{
AuthInfo: &testAuthInfo{secLevel: credentials.NoSecurity},
})
md, err = callCreds.GetRequestMetadata(insecureCtx)
if err != nil {
t.Fatalf("GetRequestMetadata() on an insecure connection failed: %v", err)
}
if len(md) != 0 {
t.Fatalf("GetRequestMetadata() on an insecure connection returned metadata %v, want none", md)
}
}

// testAuthInfo implements credentials.AuthInfo for testing.
type testAuthInfo struct {
secLevel credentials.SecurityLevel
}

func (t *testAuthInfo) AuthType() string {
return "test"
}

func (t *testAuthInfo) GetCommonAuthInfo() credentials.CommonAuthInfo {
return credentials.CommonAuthInfo{SecurityLevel: t.secLevel}
}
7 changes: 7 additions & 0 deletions internal/xds/bootstrap/bootstrap.go
Original file line number Diff line number Diff line change
Expand Up @@ -643,6 +643,13 @@ func (c *Config) AllowedGRPCServices() AllowedGRPCServices {
return c.allowedGRPCServices
}

// AllowedGRPCService returns the allowed gRPC service configured for the
// given target URI, if any.
func (c *Config) AllowedGRPCService(targetURI string) (*AllowedGRPCService, bool) {
Comment thread
easwars marked this conversation as resolved.
Outdated
svc, ok := c.allowedGRPCServices[targetURI]
return svc, ok
}

// XDSServers returns the top-level list of management servers to connect to,
// ordered by priority.
func (c *Config) XDSServers() ServerConfigs {
Expand Down
Loading
Loading