when using cert-based auth, present the client certificate on every path that reuses a cached login

This commit is contained in:
dovholuknf
2026-09-24 16:57:16 -04:00
parent e6cd1afce8
commit 2e4964c392
4 changed files with 327 additions and 44 deletions
+241
View File
@@ -0,0 +1,241 @@
//go:build cli_tests
/*
Copyright NetFoundry Inc.
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
https://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 cli_tests
import (
"crypto"
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"crypto/x509"
"crypto/x509/pkix"
"math/big"
"testing"
"time"
"github.com/golang-jwt/jwt/v5"
"github.com/google/uuid"
"github.com/openziti/edge-api/rest_management_api_client/auth_policy"
"github.com/openziti/edge-api/rest_management_api_client/external_jwt_signer"
"github.com/openziti/edge-api/rest_management_api_client/identity"
"github.com/openziti/edge-api/rest_model"
nfpem "github.com/openziti/foundation/v2/pem"
edge_apis "github.com/openziti/sdk-golang/v2/edge-apis"
"github.com/openziti/ziti/v2/ziti/cmd/edge"
"github.com/openziti/ziti/v2/ziti/util"
"github.com/stretchr/testify/require"
)
// ziti ops export, ops import and ops verify traffic do not reach the controller through the cached
// RestClientEdgeIdentity. They call LoginOptions.NewManagementClient(true), which rebuilds a client from
// the cached login and refreshes the session before using it. Whatever a login mode needs in order to be
// replayed has to survive into that client, so every mode that persists is exercised here.
//
// Each case logs in, then throws away everything but the cache and asks for a management client the way
// those commands do. Running under the overlay phases covers the zitified transport as well.
func (s *cliTestState) cachedMgmtClientTests(t *testing.T) {
cases := []struct {
name string
opts func(t *testing.T) *edge.LoginOptions
}{
{
name: "updb",
opts: func(*testing.T) *edge.LoginOptions {
return &edge.LoginOptions{
Options: s.commonOpts,
Username: s.controllerUnderTest.Username,
Password: s.controllerUnderTest.Password,
ControllerUrl: s.controllerUnderTest.ControllerHostPort(),
Yes: true,
NetworkId: s.controllerUnderTest.NetworkDialingIdFile,
}
},
},
{
name: "identity file",
opts: func(*testing.T) *edge.LoginOptions {
return &edge.LoginOptions{
Options: s.commonOpts,
ControllerUrl: s.controllerUnderTest.ControllerHostPort(),
Yes: true,
File: s.controllerUnderTest.AdminIdFile,
NetworkId: s.controllerUnderTest.NetworkDialingIdFile,
}
},
},
{
name: "client cert",
opts: func(*testing.T) *edge.LoginOptions {
return &edge.LoginOptions{
Options: s.commonOpts,
ControllerUrl: s.controllerUnderTest.ControllerHostPort(),
Yes: true,
ClientCert: s.controllerUnderTest.AdminCertFile,
ClientKey: s.controllerUnderTest.AdminKeyFile,
NetworkId: s.controllerUnderTest.NetworkDialingIdFile,
}
},
},
{
name: "external jwt",
opts: func(t *testing.T) *edge.LoginOptions {
return &edge.LoginOptions{
Options: s.commonOpts,
ControllerUrl: s.controllerUnderTest.ControllerHostPort(),
Yes: true,
ExtJwtToken: s.newExternalJwtToken(t),
NetworkId: s.controllerUnderTest.NetworkDialingIdFile,
}
},
},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
s.removeZitiDir(t)
opts := tc.opts(t)
require.NoError(t, opts.Run(), "%s login should succeed", tc.name)
util.ReloadConfig()
// nothing but the cache from here on, exactly as an ops command starts
cachedOpts := &edge.LoginOptions{Options: s.commonOpts}
client, err := cachedOpts.NewManagementClient(true)
require.NoError(t, err, "'ziti ops export' and friends build their client this way")
require.NotNil(t, client)
params := identity.NewListIdentitiesParams()
params.SetTimeout(30 * time.Second)
list, err := client.API.Identity.ListIdentities(params, nil)
require.NoError(t, err, "a management call over the cached %s login must be authorized", tc.name)
require.NotEmpty(t, list.GetPayload().Data)
})
}
}
// newExternalJwtToken registers a signer with the controller, allows it on the default auth policy, and
// returns a JWT for the admin identity that the signer vouches for.
func (s *cliTestState) newExternalJwtToken(t *testing.T) string {
t.Helper()
admin := &edge.LoginOptions{
Options: s.commonOpts,
Username: s.controllerUnderTest.Username,
Password: s.controllerUnderTest.Password,
ControllerUrl: s.controllerUnderTest.ControllerHostPort(),
Yes: true,
NetworkId: s.controllerUnderTest.NetworkDialingIdFile,
}
require.NoError(t, admin.Run(), "admin login should succeed")
util.ReloadConfig()
// NewManagementClient(false) hands back a client that has not authenticated, so go through the cache
client, err := (&edge.LoginOptions{Options: s.commonOpts}).NewManagementClient(true)
require.NoError(t, err)
signerCert, signerKey := newExtJwtSigningCert(t, "cli-test-ext-jwt-signer")
issuer := uuid.NewString()
audience := uuid.NewString()
kid := uuid.NewString()
createSigner := external_jwt_signer.NewCreateExternalJWTSignerParams()
createSigner.ExternalJWTSigner = &rest_model.ExternalJWTSignerCreate{
CertPem: toPtr(nfpem.EncodeToString(signerCert)),
Enabled: toPtr(true),
Name: toPtr("cli-test-ext-jwt-signer-" + uuid.NewString()),
Kid: toPtr(kid),
Issuer: toPtr(issuer),
Audience: toPtr(audience),
}
created, err := client.API.ExternalJWTSigner.CreateExternalJWTSigner(createSigner, nil)
require.NoError(t, err, "creating the signer should succeed")
signerId := created.Payload.Data.ID
patchPolicy := auth_policy.NewPatchAuthPolicyParams()
patchPolicy.ID = "default"
patchPolicy.AuthPolicy = &rest_model.AuthPolicyPatch{
Primary: &rest_model.AuthPolicyPrimaryPatch{
ExtJWT: &rest_model.AuthPolicyPrimaryExtJWTPatch{
Allowed: toPtr(true),
AllowedSigners: []string{signerId},
},
},
}
_, err = client.API.AuthPolicy.PatchAuthPolicy(patchPolicy, nil)
require.NoError(t, err, "allowing the signer on the default policy should succeed")
token := jwt.New(jwt.SigningMethodES256)
token.Claims = jwt.RegisteredClaims{
Audience: []string{audience},
Issuer: issuer,
Subject: s.adminIdentityId(t, client),
ID: uuid.NewString(),
IssuedAt: &jwt.NumericDate{Time: time.Now()},
NotBefore: &jwt.NumericDate{Time: time.Now()},
ExpiresAt: &jwt.NumericDate{Time: time.Now().Add(2 * time.Hour)},
}
token.Header["kid"] = kid
signed, err := token.SignedString(signerKey)
require.NoError(t, err)
return signed
}
// adminIdentityId looks up the identity the admin username belongs to, which the JWT names as its subject.
func (s *cliTestState) adminIdentityId(t *testing.T, client *edge_apis.ManagementApiClient) string {
t.Helper()
params := identity.NewListIdentitiesParams()
params.Filter = toPtr(`name="` + s.controllerUnderTest.Username + `"`)
params.SetTimeout(30 * time.Second)
list, err := client.API.Identity.ListIdentities(params, nil)
require.NoError(t, err)
require.NotEmpty(t, list.GetPayload().Data, "the admin identity should exist")
return *list.GetPayload().Data[0].ID
}
func newExtJwtSigningCert(t *testing.T, commonName string) (*x509.Certificate, crypto.PrivateKey) {
t.Helper()
key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
require.NoError(t, err)
template := &x509.Certificate{
SerialNumber: big.NewInt(1),
Subject: pkix.Name{CommonName: commonName},
NotBefore: time.Now().Add(-time.Hour),
NotAfter: time.Now().Add(24 * time.Hour),
KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature,
BasicConstraintsValid: true,
}
der, err := x509.CreateCertificate(rand.Reader, template, template, &key.PublicKey, key)
require.NoError(t, err)
cert, err := x509.ParseCertificate(der)
require.NoError(t, err)
return cert, key
}
func toPtr[T any](v T) *T {
return &v
}
+1
View File
@@ -51,6 +51,7 @@ func (s *cliTestState) loginTests(t *testing.T) {
t.Run("client cert auth then cached request", s.testClientCertLoginThenCachedRequest)
t.Run("identity file given as a relative path", s.testIdentityFileRelativePath)
t.Run("identity file auth then token refresh", s.testIdentityFileLoginThenTokenRefresh)
t.Run("cached management client", s.cachedMgmtClientTests)
t.Run("external JWT authentication", s.testExternalJWTAuthentication)
t.Run("network identity zitified connection", s.testNetworkIdentityZitifiedConnection)
+59 -27
View File
@@ -17,10 +17,8 @@
package edge
import (
"crypto"
"crypto/tls"
"crypto/x509"
"encoding/pem"
"fmt"
"io"
"net/http"
@@ -386,8 +384,7 @@ func (o *LoginOptions) Run() error {
}
}
if !o.IgnoreConfig {
// a certificate based login binds the session to the certificate, so record how to find it again.
// Later commands build a new client and have to present it or the controller rejects the session.
// record how to find the credential again, so a later command run from anywhere can present it
clientIdFile := absPathOrSelf(o.File)
clientCert := absPathOrSelf(o.ClientCert)
clientKey := absPathOrSelf(o.ClientKey)
@@ -402,7 +399,7 @@ func (o *LoginOptions) Run() error {
ClientCert: clientCert,
ClientKey: clientKey,
ReadOnly: o.ReadOnly,
NetworkIdFile: o.NetworkId,
NetworkIdFile: absPathOrSelf(o.NetworkId),
ApiSession: sess,
}
o.Printf("Saving identity '%v' to %v\n", id, configFile)
@@ -632,11 +629,21 @@ func (o *LoginOptions) terminatorId() string {
}
func (o *LoginOptions) createHttpTransport() (*http.Transport, error) {
// a certificate based login has to present its certificate whichever transport carries the request
cert, certErr := util.ClientCertificate(o.File, o.ClientCert, o.ClientKey)
if certErr != nil {
return nil, certErr
}
// if cli param supplied - use it first
if o.NetworkId != "" {
t, e := util.NewZitifiedTransportFromFile(o.NetworkId, o.terminatorId())
if e != nil {
return nil, e
}
attachClientCert(t, cert)
o.transport = t
return t, e
return t, nil
}
// if env var set - use it
@@ -647,6 +654,7 @@ func (o *LoginOptions) createHttpTransport() (*http.Transport, error) {
if zt != nil {
o.Printf("NetworkId found by env var [%s], zitified transport enabled\n", constants.ZitiCliNetworkIdVarName)
o.NetworkId = ""
attachClientCert(zt, cert)
o.transport = zt
return zt, nil
}
@@ -656,11 +664,27 @@ func (o *LoginOptions) createHttpTransport() (*http.Transport, error) {
if caErr != nil {
return nil, caErr
}
return &http.Transport{
transport := &http.Transport{
TLSClientConfig: &tls.Config{
RootCAs: caPool,
},
}, nil
}
attachClientCert(transport, cert)
return transport, nil
}
// attachClientCert adds the login's certificate to a transport, leaving the rest of its TLS settings as
// they were.
func attachClientCert(transport *http.Transport, cert *tls.Certificate) {
if cert == nil {
return
}
if transport.TLSClientConfig == nil {
transport.TLSClientConfig = &tls.Config{}
}
transport.TLSClientConfig.Certificates = []tls.Certificate{*cert}
}
func (o *LoginOptions) PopulateFromCache() {
@@ -687,6 +711,16 @@ func (o *LoginOptions) PopulateFromCache() {
if o.NetworkId == "" {
o.NetworkId = cachedCliConfig.NetworkIdFile
}
// commands that reuse a cached login still have to present the certificate it authenticated with
if o.File == "" {
o.File = cachedCliConfig.ClientIdFile
}
if o.ClientCert == "" {
o.ClientCert = cachedCliConfig.ClientCert
}
if o.ClientKey == "" {
o.ClientKey = cachedCliConfig.ClientKey
}
if o.CaCert == "" {
cachedUrl := addHttpsIfNeeded(cachedCliConfig.Url)
currentUrl := addHttpsIfNeeded(o.ControllerUrl)
@@ -890,31 +924,29 @@ func (o *LoginOptions) Login() (edge_apis.ApiSession, error) {
} else if o.Username != "" && o.Password != "" {
authCreds = edge_apis.NewUpdbCredentials(o.Username, o.Password)
} else if o.ClientCert != "" || o.ClientKey != "" {
var key crypto.PrivateKey
if keyPEM, err := os.ReadFile(o.ClientKey); err != nil {
keyPEM, err := os.ReadFile(o.ClientKey)
if err != nil {
return nil, fmt.Errorf("failed to read key: %w", err)
} else {
keyBlock, _ := pem.Decode(keyPEM)
k, _ := x509.ParsePKCS1PrivateKey(keyBlock.Bytes)
key = k
}
var cert *x509.Certificate
if certPEM, err := os.ReadFile(o.ClientCert); err != nil {
certPEM, err := os.ReadFile(o.ClientCert)
if err != nil {
return nil, fmt.Errorf("failed to read cert: %w", err)
} else {
block, _ := pem.Decode(certPEM)
if block == nil {
return nil, fmt.Errorf("invalid cert pem")
}
c, err := x509.ParseCertificate(block.Bytes)
if err != nil {
return nil, fmt.Errorf("failed to parse cert: %w", err)
}
cert = c
}
authCreds = edge_apis.NewCertCredentials([]*x509.Certificate{cert}, key)
// X509KeyPair accepts RSA, EC and PKCS#8 keys alike, and is what later commands use to load this
// same pair back out of the cache
pair, err := tls.X509KeyPair(certPEM, keyPEM)
if err != nil {
return nil, fmt.Errorf("failed to load client certificate and key: %w", err)
}
cert, err := x509.ParseCertificate(pair.Certificate[0])
if err != nil {
return nil, fmt.Errorf("failed to parse cert: %w", err)
}
authCreds = edge_apis.NewCertCredentials([]*x509.Certificate{cert}, pair.PrivateKey)
} else if o.File != "" {
cfg, err := ziti.NewConfigFromFile(o.File)
if err != nil {
+26 -17
View File
@@ -31,6 +31,8 @@ import (
var zitiCliContextCollection *ziti.CtxCollection
var networkIdWarning sync.Once
func init() {
zitiCliContextCollection = ziti.NewSdkCollection()
}
@@ -102,34 +104,33 @@ func (self *RestClientEdgeIdentity) IsReadOnly() bool {
return self.ReadOnly
}
// clientCertificate returns the certificate this login authenticated with, or nil when the login used a
// credential that isn't certificate based. Certificate authentication binds the session to the
// certificate, and the controller verifies proof of possession on every request, so each new client has
// to present it again.
func (self *RestClientEdgeIdentity) clientCertificate() (*tls.Certificate, error) {
if self.ClientIdFile != "" {
cfg, err := ziti.NewConfigFromFile(self.ClientIdFile)
// ClientCertificate loads the certificate a certificate based login authenticates with. idFile is an
// enrolled identity file; certFile and keyFile are a PEM certificate and its key. Returns nil when none
// of them are set.
func ClientCertificate(idFile, certFile, keyFile string) (*tls.Certificate, error) {
if idFile != "" {
cfg, err := ziti.NewConfigFromFile(idFile)
if err != nil {
return nil, errors.Errorf("client identity file [%s] is no longer readable: %v. Run 'ziti edge login' to log in again", self.ClientIdFile, err)
return nil, errors.Errorf("client identity file [%s] is no longer readable: %v. Run 'ziti edge login' to log in again", idFile, err)
}
id, err := identity.LoadIdentity(cfg.ID)
if err != nil {
return nil, errors.Errorf("could not load the identity in [%s]: %v. Run 'ziti edge login' to log in again", self.ClientIdFile, err)
return nil, errors.Errorf("could not load the identity in [%s]: %v. Run 'ziti edge login' to log in again", idFile, err)
}
cert := id.Cert()
if cert == nil || len(cert.Certificate) == 0 {
return nil, errors.Errorf("the identity in [%s] has no certificate to authenticate with. Run 'ziti edge login' to log in again", self.ClientIdFile)
return nil, errors.Errorf("the identity in [%s] has no certificate to authenticate with. Run 'ziti edge login' to log in again", idFile)
}
return cert, nil
}
if self.ClientCert != "" && self.ClientKey != "" {
cert, err := tls.LoadX509KeyPair(self.ClientCert, self.ClientKey)
if certFile != "" && keyFile != "" {
cert, err := tls.LoadX509KeyPair(certFile, keyFile)
if err != nil {
return nil, errors.Errorf("client certificate [%s] and key [%s] are no longer usable: %v. Run 'ziti edge login' to log in again", self.ClientCert, self.ClientKey, err)
return nil, errors.Errorf("client certificate [%s] and key [%s] are no longer usable: %v. Run 'ziti edge login' to log in again", certFile, keyFile, err)
}
return &cert, nil
@@ -138,6 +139,12 @@ func (self *RestClientEdgeIdentity) clientCertificate() (*tls.Certificate, error
return nil, nil
}
// clientCertificate returns the certificate this login authenticated with, or nil for a login that was
// not certificate based.
func (self *RestClientEdgeIdentity) clientCertificate() (*tls.Certificate, error) {
return ClientCertificate(self.ClientIdFile, self.ClientCert, self.ClientKey)
}
func (self *RestClientEdgeIdentity) NewTlsClientConfig() (*tls.Config, error) {
rootCaPool := x509.NewCertPool()
@@ -187,8 +194,11 @@ func (self *RestClientEdgeIdentity) getHttpTransport(log *log.Logger, verbose bo
} else {
if self.NetworkIdFile != "" {
if ztFromFile, ztFromFileErr := NewZitifiedTransportFromFile(self.NetworkIdFile, terminator); ztFromFileErr != nil {
// the default transport still works, so warn and carry on rather than failing
_, _ = fmt.Fprintf(os.Stderr, "WARNING: network identity [%s] is no longer usable, falling back to a direct connection: %v\n", self.NetworkIdFile, ztFromFileErr)
// the default transport still works, so warn and carry on rather than failing. A single
// command builds more than one client, so only the first of them warns.
networkIdWarning.Do(func() {
_, _ = fmt.Fprintf(os.Stderr, "WARNING: network identity [%s] is no longer usable, falling back to a direct connection: %v\n", self.NetworkIdFile, ztFromFileErr)
})
} else {
if verbose {
log.Printf("Using Ziti transport from cached file: %s", self.NetworkIdFile)
@@ -288,8 +298,7 @@ func OidcRefreshTokenValid(sess edge_apis.ApiSession) bool {
}
// newComponentsWithTls builds the http components an edge-apis client needs, carrying the whole TLS
// config rather than only the root CAs. The controller verifies the certificate binding on a token
// refresh too, so a cert based session has to present its certificate there as well.
// config rather than only the root CAs.
func newComponentsWithTls(tlsClientConfig *tls.Config) *edge_apis.Components {
components := edge_apis.NewComponentsWithConfig(&edge_apis.ComponentsConfig{
Proxy: http.ProxyFromEnvironment,