Skip to content
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

xds: add support for mTLS Credentials in xDS bootstrap #6757

Merged
merged 21 commits into from Jan 4, 2024
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
14 changes: 14 additions & 0 deletions xds/internal/xdsclient/bootstrap/bootstrap.go
Expand Up @@ -39,6 +39,7 @@ import (
"google.golang.org/grpc/internal/envconfig"
"google.golang.org/grpc/internal/pretty"
"google.golang.org/grpc/xds/bootstrap"
"google.golang.org/grpc/xds/internal/xdsclient/creds"
)

const (
Expand All @@ -60,6 +61,7 @@ const (
func init() {
bootstrap.RegisterCredentials(&insecureCredsBuilder{})
bootstrap.RegisterCredentials(&googleDefaultCredsBuilder{})
bootstrap.RegisterCredentials(&tlsCredsBuilder{})
}

// For overriding in unit tests.
Expand All @@ -77,6 +79,18 @@ func (i *insecureCredsBuilder) Name() string {
return "insecure"
}

// tlsCredsBuilder implements the `Credentials` interface defined in
// package `xds/bootstrap` and encapsulates a TLS credential.
type tlsCredsBuilder struct{}

func (t *tlsCredsBuilder) Build(config json.RawMessage) (credentials.Bundle, error) {
return creds.NewTLS(config)
}

func (t *tlsCredsBuilder) Name() string {
return "tls"
}

// googleDefaultCredsBuilder implements the `Credentials` interface defined in
// package `xds/boostrap` and encapsulates a Google Default credential.
type googleDefaultCredsBuilder struct{}
Expand Down
23 changes: 23 additions & 0 deletions xds/internal/xdsclient/bootstrap/bootstrap_test.go
Expand Up @@ -1015,6 +1015,10 @@ func TestDefaultBundles(t *testing.T) {
if c := bootstrap.GetCredentials("insecure"); c == nil {
t.Errorf(`bootstrap.GetCredentials("insecure") credential is nil, want non-nil`)
}

if c := bootstrap.GetCredentials("tls"); c == nil {
t.Errorf(`bootstrap.GetCredentials("tls") credential is nil, want non-nil`)
}
}

func TestCredsBuilders(t *testing.T) {
Expand All @@ -1034,4 +1038,23 @@ func TestCredsBuilders(t *testing.T) {
if got, want := i.Name(), "insecure"; got != want {
t.Errorf("insecureCredsBuilder.Name = %v, want %v", got, want)
}

tcb := &tlsCredsBuilder{}
if _, err := tcb.Build(nil); err == nil {
t.Errorf("tlsCredsBuilder.Build succeeded, want failure")
}
easwars marked this conversation as resolved.
Show resolved Hide resolved
if got, want := tcb.Name(), "tls"; got != want {
t.Errorf("tlsCredsBuilder.Name = %v, want %v", got, want)
}
}

func TestTlsCredsBuilder(t *testing.T) {
tls := &tlsCredsBuilder{}
if _, err := tls.Build(json.RawMessage(`{}`)); err != nil {
t.Errorf("unexpected error with empty config: %s", err)
easwars marked this conversation as resolved.
Show resolved Hide resolved
}
if _, err := tls.Build(json.RawMessage(`{"ca_certificate_file":"/ca_certificates.pem","refresh_interval": "asdf"}`)); err == nil {
t.Errorf("expected an error with invalid refresh interval")
easwars marked this conversation as resolved.
Show resolved Hide resolved
}
// more tests for config validity are defined in creds subpackage.
easwars marked this conversation as resolved.
Show resolved Hide resolved
}
179 changes: 179 additions & 0 deletions xds/internal/xdsclient/creds/tls.go
arvindbr8 marked this conversation as resolved.
Show resolved Hide resolved
@@ -0,0 +1,179 @@
/*
*
* Copyright 2023 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 creds implements mTLS Credentials in xDS Bootstrap File.
// See [gRFC A65](github.com/grpc/proposal/blob/master/A65-xds-mtls-creds-in-bootstrap.md).
package creds
easwars marked this conversation as resolved.
Show resolved Hide resolved

import (
"context"
"crypto/tls"
"encoding/json"
"fmt"
"net"
"sync"

"google.golang.org/grpc/credentials"
"google.golang.org/grpc/credentials/tls/certprovider"
_ "google.golang.org/grpc/credentials/tls/certprovider/pemfile" // for file_watcher provider
)

// tlsBundle is an implementation of credentials.Bundle which implements mTLS
// Credentials in xDS Bootstrap File.
// See [gRFC A65](github.com/grpc/proposal/blob/master/A65-xds-mtls-creds-in-bootstrap.md).
type tlsBundle struct {
arvindbr8 marked this conversation as resolved.
Show resolved Hide resolved
jd json.RawMessage
transportCredentials credentials.TransportCredentials
}

// NewTLS returns a credentials.Bundle which implements mTLS Credentials in xDS
// Bootstrap File. It delegates certificate loading to a file_watcher provider
// if either client certificates or server root CA is specified.
// See [gRFC A65](github.com/grpc/proposal/blob/master/A65-xds-mtls-creds-in-bootstrap.md).
func NewTLS(jd json.RawMessage) (credentials.Bundle, error) {
cfg := &struct {
CertificateFile string `json:"certificate_file"`
CACertificateFile string `json:"ca_certificate_file"`
PrivateKeyFile string `json:"private_key_file"`
}{}

tlsConfig := tls.Config{}
if err := json.Unmarshal(jd, cfg); err != nil {
return nil, err
}

// We cannot simply always use a file_watcher provider because it behaves
// slightly differently from the xDS TLS config. Quoting A65:
//
// > The only difference between the file-watcher certificate provider
// > config and this one is that in the file-watcher certificate provider,
// > at least one of the "certificate_file" or "ca_certificate_file" fields
// > must be specified, whereas in this configuration, it is acceptable to
// > specify neither one.
//
// We only use a file_watcher provider if either one of them or both are
// specified.
if cfg.CACertificateFile != "" || cfg.CertificateFile != "" || cfg.PrivateKeyFile != "" {
easwars marked this conversation as resolved.
Show resolved Hide resolved
// file_watcher currently ignores BuildOptions.
provider, err := certprovider.GetProvider("file_watcher", jd, certprovider.BuildOptions{})
easwars marked this conversation as resolved.
Show resolved Hide resolved
if err != nil {
// GetProvider fails if jd is invalid, e.g. if only one of private
// key and certificate is specified.
return nil, fmt.Errorf("failed to get TLS provider: %w", err)
easwars marked this conversation as resolved.
Show resolved Hide resolved
}
if cfg.CertificateFile != "" {
tlsConfig.GetClientCertificate = func(*tls.CertificateRequestInfo) (*tls.Certificate, error) {
// Client cert reloading for mTLS.
km, err := provider.KeyMaterial(context.Background())
if err != nil {
return nil, err
}

Check warning on line 85 in xds/internal/xdsclient/creds/tls.go

View check run for this annotation

Codecov / codecov/patch

xds/internal/xdsclient/creds/tls.go#L84-L85

Added lines #L84 - L85 were not covered by tests
if len(km.Certs) != 1 {
// xDS bootstrap has a single private key file, so there
// must be exactly one certificate or certificate chain
// matching this private key.
easwars marked this conversation as resolved.
Show resolved Hide resolved
return nil, fmt.Errorf("certificate_file must contains exactly one certificate or certificate chain")
}

Check warning on line 91 in xds/internal/xdsclient/creds/tls.go

View check run for this annotation

Codecov / codecov/patch

xds/internal/xdsclient/creds/tls.go#L87-L91

Added lines #L87 - L91 were not covered by tests
return &km.Certs[0], nil
}
if cfg.CACertificateFile == "" {
// No need for a callback to load the CA. Use the normal mTLS
// transport credentials.
return &tlsBundle{
jd: jd,
transportCredentials: credentials.NewTLS(&tlsConfig),
}, nil
}
}
return &tlsBundle{
jd: jd,
transportCredentials: &caReloadingClientTLSCreds{
baseConfig: &tlsConfig,
provider: provider,
},
}, nil
}

// None of certificate_file and ca_certificate_file are set.
// Use the system-wide root certs.
return &tlsBundle{
jd: jd,
transportCredentials: credentials.NewTLS(&tlsConfig),
}, nil
}

func (t *tlsBundle) TransportCredentials() credentials.TransportCredentials {
return t.transportCredentials
}

func (t *tlsBundle) PerRPCCredentials() credentials.PerRPCCredentials {
// mTLS provides transport credentials only. There are no per-RPC
// credentials.
return nil
}

func (t *tlsBundle) NewWithMode(_ string) (credentials.Bundle, error) {
easwars marked this conversation as resolved.
Show resolved Hide resolved
return NewTLS(t.jd)

Check warning on line 131 in xds/internal/xdsclient/creds/tls.go

View check run for this annotation

Codecov / codecov/patch

xds/internal/xdsclient/creds/tls.go#L130-L131

Added lines #L130 - L131 were not covered by tests
easwars marked this conversation as resolved.
Show resolved Hide resolved
}

// caReloadingClientTLSCreds is credentials.TransportCredentials for client
// side mTLS that attempts to reload the server root certificate from its
// provider on every client handshake. This is needed because Go's tls.Config
// does not support reloading the root CAs.
type caReloadingClientTLSCreds struct {
mu sync.Mutex
provider certprovider.Provider
baseConfig *tls.Config
easwars marked this conversation as resolved.
Show resolved Hide resolved
}

func (c *caReloadingClientTLSCreds) ClientHandshake(ctx context.Context, authority string, rawConn net.Conn) (net.Conn, credentials.AuthInfo, error) {
km, err := c.provider.KeyMaterial(ctx)
if err != nil {
return nil, nil, err
}

Check warning on line 148 in xds/internal/xdsclient/creds/tls.go

View check run for this annotation

Codecov / codecov/patch

xds/internal/xdsclient/creds/tls.go#L147-L148

Added lines #L147 - L148 were not covered by tests
c.mu.Lock()
defer c.mu.Unlock()
if !km.Roots.Equal(c.baseConfig.RootCAs) {
// Provider returned a different root CA. Update it.
c.baseConfig.RootCAs = km.Roots
}
return credentials.NewTLS(c.baseConfig).ClientHandshake(ctx, authority, rawConn)
easwars marked this conversation as resolved.
Show resolved Hide resolved
}

func (c *caReloadingClientTLSCreds) Info() credentials.ProtocolInfo {
c.mu.Lock()
defer c.mu.Unlock()
return credentials.NewTLS(c.baseConfig).Info()
}

func (c *caReloadingClientTLSCreds) Clone() credentials.TransportCredentials {
c.mu.Lock()
defer c.mu.Unlock()
return &caReloadingClientTLSCreds{
provider: c.provider,
baseConfig: c.baseConfig.Clone(),
}

Check warning on line 170 in xds/internal/xdsclient/creds/tls.go

View check run for this annotation

Codecov / codecov/patch

xds/internal/xdsclient/creds/tls.go#L164-L170

Added lines #L164 - L170 were not covered by tests
}

func (c *caReloadingClientTLSCreds) OverrideServerName(_ string) error {
panic("cannot override server name for private xds tls credentials")

Check warning on line 174 in xds/internal/xdsclient/creds/tls.go

View check run for this annotation

Codecov / codecov/patch

xds/internal/xdsclient/creds/tls.go#L173-L174

Added lines #L173 - L174 were not covered by tests
}

func (c *caReloadingClientTLSCreds) ServerHandshake(_ net.Conn) (net.Conn, credentials.AuthInfo, error) {
panic("cannot perform handshake for server. xDS TLS credentials are client only.")

Check warning on line 178 in xds/internal/xdsclient/creds/tls.go

View check run for this annotation

Codecov / codecov/patch

xds/internal/xdsclient/creds/tls.go#L177-L178

Added lines #L177 - L178 were not covered by tests
}