Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
52 changes: 51 additions & 1 deletion crypto/spiffe/spiffe.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,10 @@ package spiffe

import (
"context"
"crypto"
"crypto/ed25519"
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"errors"
"fmt"
Expand All @@ -38,6 +40,24 @@ const (
// renewalDivisor represents the divisor for calculating renewal time.
// A value of 2 means renewal at 50% of the validity period.
renewalDivisor = 2

// rsaKeyBits is the size, in bits, of generated RSA workload keys.
rsaKeyBits = 2048
)

// KeyAlgorithm selects the algorithm used to generate the workload's
// private key when requesting an SVID.
type KeyAlgorithm int

const (
// KeyAlgorithmEd25519 generates an Ed25519 private key. This is the
// default when no algorithm is specified.
KeyAlgorithmEd25519 KeyAlgorithm = iota

// KeyAlgorithmRSA generates an RSA private key. Used by workloads whose
// certificates are consumed by systems that do not accept Ed25519, such
// as the Kubernetes API server when calling admission webhooks.
KeyAlgorithmRSA
)

// SVIDResponse represents the response from the SVID request function,
Expand Down Expand Up @@ -73,6 +93,10 @@ type Options struct {
WriteIdentityToFile *string

TrustAnchors trustanchors.Interface

// KeyAlgorithm selects the algorithm used for the workload's private
// key. When nil, defaults to Ed25519.
KeyAlgorithm *KeyAlgorithm
}
Comment thread
JoshVanL marked this conversation as resolved.
Resolved

// SPIFFE is a readable/writeable store of SPIFFE SVID credentials.
Expand All @@ -88,6 +112,8 @@ type SPIFFE struct {
dir *dir.Dir
trustAnchors trustanchors.Interface

keyAlgorithm KeyAlgorithm

log logger.Logger
lock sync.RWMutex
clock clock.Clock
Expand All @@ -104,10 +130,16 @@ func New(opts Options) *SPIFFE {
})
}

keyAlg := KeyAlgorithmEd25519
if opts.KeyAlgorithm != nil {
keyAlg = *opts.KeyAlgorithm
}

return &SPIFFE{
requestSVIDFn: opts.RequestSVIDFn,
dir: sdir,
trustAnchors: opts.TrustAnchors,
keyAlgorithm: keyAlg,
log: opts.Log,
clock: clock.RealClock{},
readyCh: make(chan struct{}),
Expand Down Expand Up @@ -233,7 +265,7 @@ func (s *SPIFFE) runRotation(ctx context.Context) {

// Returns both X.509 SVID and JWT SVID (if available).
func (s *SPIFFE) fetchIdentity(ctx context.Context) (*Identity, error) {
_, key, err := ed25519.GenerateKey(rand.Reader)
key, err := generatePrivateKey(s.keyAlgorithm)
if err != nil {
return nil, fmt.Errorf("failed to generate private key: %w", err)
}
Expand Down Expand Up @@ -335,6 +367,24 @@ func (s *SPIFFE) fetchIdentity(ctx context.Context) (*Identity, error) {
return identity, nil
}

// generatePrivateKey returns a freshly generated private key for the
// configured algorithm.
func generatePrivateKey(alg KeyAlgorithm) (crypto.Signer, error) {
switch alg {
case KeyAlgorithmRSA:
return rsa.GenerateKey(rand.Reader, rsaKeyBits)
case KeyAlgorithmEd25519:
_, key, err := ed25519.GenerateKey(rand.Reader)
if err != nil {
return nil, err
}

return key, nil
default:
return nil, fmt.Errorf("unsupported key algorithm: %d", alg)
}
Comment thread
JoshVanL marked this conversation as resolved.
Resolved
}

// renewalTime is 50% through the certificate validity period.
func renewalTime(notBefore, notAfter time.Time) time.Time {
return notBefore.Add(notAfter.Sub(notBefore) / renewalDivisor)
Expand Down
57 changes: 57 additions & 0 deletions crypto/spiffe/spiffe_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@ package spiffe

import (
"context"
"crypto/ed25519"
"crypto/rsa"
"crypto/x509"
"errors"
"fmt"
Expand Down Expand Up @@ -129,6 +131,61 @@ func Test_fetchIdentity_perAudienceParseError_includesAudience(t *testing.T) {
require.Contains(t, err.Error(), fmt.Sprintf("audience %q", "bad-aud"))
}

func Test_fetchIdentity_keyAlgorithm(t *testing.T) {
pki := test.GenPKI(t, test.PKIOptions{
LeafID: spiffeid.RequireFromString("spiffe://example.com/foo/bar"),
})

rsaAlg := KeyAlgorithmRSA
edAlg := KeyAlgorithmEd25519

tests := map[string]struct {
alg *KeyAlgorithm
assert func(t *testing.T, key any)
}{
"nil defaults to Ed25519": {
alg: nil,
assert: func(t *testing.T, key any) {
assert.IsType(t, ed25519.PrivateKey{}, key)
},
},
"explicit Ed25519": {
alg: &edAlg,
assert: func(t *testing.T, key any) {
assert.IsType(t, ed25519.PrivateKey{}, key)
},
},
"RSA generates an RSA private key": {
alg: &rsaAlg,
assert: func(t *testing.T, key any) {
rsaKey, ok := key.(*rsa.PrivateKey)
require.True(t, ok, "expected *rsa.PrivateKey, got %T", key)
assert.Equal(t, rsaKeyBits, rsaKey.N.BitLen())
},
},
}

for name, tc := range tests {
t.Run(name, func(t *testing.T) {
s := New(Options{
Log: logger.NewLogger("test"),
KeyAlgorithm: tc.alg,
RequestSVIDFn: func(context.Context, []byte) (*SVIDResponse, error) {
return &SVIDResponse{
X509Certificates: []*x509.Certificate{pki.LeafCert},
}, nil
},
})

identity, err := s.fetchIdentity(t.Context())
require.NoError(t, err)
require.NotNil(t, identity)
require.NotNil(t, identity.X509SVID)
tc.assert(t, identity.X509SVID.PrivateKey)
})
}
}

func Test_Run(t *testing.T) {
t.Run("should return error multiple Runs are called", func(t *testing.T) {
pki := test.GenPKI(t, test.PKIOptions{
Expand Down
Loading