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

feat(api-client): add cert auth method #29546

Open
wants to merge 6 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 3 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
165 changes: 165 additions & 0 deletions api/auth/cert/cert.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,165 @@
package cert
witochandra marked this conversation as resolved.
Show resolved Hide resolved

import (
"bytes"
"context"
"crypto/tls"
"encoding/json"
"fmt"
"io"
"net/http"

"github.com/hashicorp/go-rootcerts"
"github.com/hashicorp/vault/api"
)

type CertAuth struct {
role string
caCert string
caCertBytes []byte
clientCert string
clientKey string
insecureSkipVerify bool
}

var _ api.AuthMethod = (*CertAuth)(nil)

type LoginOption func(a *CertAuth) error

// NewCertAuth initializes a new Cert auth method interface to be
// passed as a parameter to the client.Auth().Login method.
//
// Supported options: WithCACert, WithCACertBytes, WithInsecure
func NewCertAuth(roleName, clientCert, clientKey string, opts ...LoginOption) (*CertAuth, error) {
if roleName == "" {
return nil, fmt.Errorf("no role name provided for login")
}

if clientCert == "" || clientKey == "" {
return nil, fmt.Errorf("client certificate and key must be provided")
}

a := &CertAuth{
role: roleName,
clientCert: clientCert,
clientKey: clientKey,
}

// Loop through each option
for _, opt := range opts {
// Call the option giving the instantiated
// *CertAuth as the argument
err := opt(a)
if err != nil {
return nil, fmt.Errorf("error with login option: %w", err)
}
}

// return the modified auth struct instance
return a, nil
}

// Login sets up the required request body for the Cert auth method's /login
// endpoint, and performs a write to it.
// It adds the client cert and key to the request.
func (a *CertAuth) Login(ctx context.Context, client *api.Client) (*api.Secret, error) {
if ctx == nil {
ctx = context.Background()
}

c, err := a.httpClient()
if err != nil {
return nil, err
}

reqBody, err := json.Marshal(map[string]interface{}{
"name": a.role,
aslamovamir marked this conversation as resolved.
Show resolved Hide resolved
})
if err != nil {
return nil, fmt.Errorf("unable to marshal login data: %w", err)
}

url := fmt.Sprintf("%s/v1/auth/cert/login", client.Address())
req, err := http.NewRequestWithContext(ctx, http.MethodPost, url, bytes.NewBuffer(reqBody))
if err != nil {
return nil, fmt.Errorf("unable to create request: %w", err)
}

resp, err := c.Do(req)
if err != nil {
return nil, fmt.Errorf("unable to log in with cert auth: %w", err)
}

defer resp.Body.Close()

body, err := io.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("unable to read response body: %w", err)
}

if resp.StatusCode >= 400 {
return nil, fmt.Errorf("unable to log in with cert auth, response code: %d. response body: %s", resp.StatusCode, string(body))
}

var secret api.Secret
if err := json.Unmarshal(body, &secret); err != nil {
return nil, fmt.Errorf("unable to unmarshal response body: %w", err)
}

return &secret, nil
}

func (a *CertAuth) httpClient() (*http.Client, error) {
cert, err := tls.LoadX509KeyPair(a.clientCert, a.clientKey)
if err != nil {
return nil, fmt.Errorf("unable to load cert: %w", err)
}
aslamovamir marked this conversation as resolved.
Show resolved Hide resolved

tlsConfig := &tls.Config{
InsecureSkipVerify: a.insecureSkipVerify,
Certificates: []tls.Certificate{cert},
}

if a.caCert != "" || len(a.caCertBytes) > 0 {
err = rootcerts.ConfigureTLS(tlsConfig, &rootcerts.Config{
CAPath: a.caCert,
CACertificate: a.caCertBytes,
})
if err != nil {
return nil, fmt.Errorf("unable to configure TLS: %w", err)
}
}

return &http.Client{
Transport: &http.Transport{
TLSClientConfig: tlsConfig,
},
}, nil
}

// WithCACert sets the CA cert to be used for the login request.
// caCert is the path to the CA cert file.
func WithCACert(caCert string) LoginOption {
return func(a *CertAuth) error {
a.caCert = caCert
return nil
}
}

// WithCACertBytes sets the CA cert to be used for the login request.
// caCertBytes is the bytes of the CA cert.
// caCertBytes takes precedence over caCert.
func WithCACertBytes(caCertBytes []byte) LoginOption {
return func(a *CertAuth) error {
a.caCertBytes = caCertBytes
return nil
}
}

// WithInsecure skips the verification of the server's certificate chain and host name.
func WithInsecure() LoginOption {
return func(a *CertAuth) error {
a.insecureSkipVerify = true
return nil
}
}
225 changes: 225 additions & 0 deletions api/auth/cert/cert_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,225 @@
package cert
witochandra marked this conversation as resolved.
Show resolved Hide resolved

import (
"context"
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"crypto/tls"
"crypto/x509"
"crypto/x509/pkix"
"encoding/pem"
"fmt"
"math/big"
mathrand "math/rand"
"net"
"net/http"
"os"
"path/filepath"
"sync"
"testing"
"time"

"github.com/hashicorp/go-rootcerts"
"github.com/hashicorp/vault/api"
)

func TestLogin(t *testing.T) {
certDir := createCertificatePairs(t)

wg := &sync.WaitGroup{}
wg.Add(1)
ln := runTestServer(t, certDir, func(w http.ResponseWriter, r *http.Request) {
wg.Done()

if r.TLS == nil || len(r.TLS.PeerCertificates) == 0 {
t.Fatalf("no client cert provided")
}

w.WriteHeader(http.StatusOK)
w.Write([]byte(`{"auth": {"client_token": "test-token"}}`))
})

// Create a new CertAuth struct.
auth, err := NewCertAuth(
"role-name",
filepath.Join(certDir, "client_cert.pem"),
filepath.Join(certDir, "client_key.pem"),
WithCACert(filepath.Join(certDir, "ca_cert.pem")),
)
if err != nil {
t.Fatalf("failed to create CertAuth: %v", err)
}

witochandra marked this conversation as resolved.
Show resolved Hide resolved
cfg := api.DefaultConfig()
cfg.Address = fmt.Sprintf("https://%s", ln.Addr())

client, err := api.NewClient(cfg)
if err != nil {
t.Fatalf("failed to create client: %v", err)
}

secret, err := auth.Login(context.Background(), client)
if err != nil {
t.Fatalf("failed to login: %v", err)
}

if secret == nil || secret.Auth == nil || secret.Auth.ClientToken != "test-token" {
t.Fatalf("unexpected response: %v", secret)
}

done := make(chan struct{})
go func() {
wg.Wait()
close(done)
}()

select {
case <-done:
t.Log("done")
case <-time.After(time.Second):
t.Error("timeout")
}
}

func runTestServer(t *testing.T, certDir string, fn http.HandlerFunc) net.Listener {
certPool, err := rootcerts.LoadCACerts(&rootcerts.Config{
CAPath: filepath.Join(certDir, "ca_cert.pem"),
})
if err != nil {
t.Fatalf("failed to load CA certs: %v", err)
}

tlsConfig := &tls.Config{
ClientAuth: tls.RequireAndVerifyClientCert,
ClientCAs: certPool,
RootCAs: certPool,
}

ln, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatalf("failed to create listener: %v", err)
}

sv := &http.Server{
TLSConfig: tlsConfig,
Handler: http.HandlerFunc(fn),
}

witochandra marked this conversation as resolved.
Show resolved Hide resolved
t.Cleanup(func() {
sv.Close()
ln.Close()
})

go func() {
sv.ServeTLS(ln, filepath.Join(certDir, "server_cert.pem"), filepath.Join(certDir, "server_key.pem"))
}()

return ln
}

func createCertificatePairs(t *testing.T) string {
tempDir, err := os.MkdirTemp("", "api_certauth_test")
if err != nil {
t.Fatal(err)
}

t.Logf("test %s, temp dir %s", t.Name(), tempDir)
caCertTemplate := &x509.Certificate{
Subject: pkix.Name{
CommonName: "localhost",
},
DNSNames: []string{"localhost"},
IPAddresses: []net.IP{net.ParseIP("127.0.0.1")},
KeyUsage: x509.KeyUsage(x509.KeyUsageCertSign | x509.KeyUsageCRLSign),
SerialNumber: big.NewInt(mathrand.Int63()),
NotBefore: time.Now().Add(-30 * time.Second),
NotAfter: time.Now().Add(262980 * time.Hour),
BasicConstraintsValid: true,
IsCA: true,
}
caKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
if err != nil {
t.Fatal(err)
}
caBytes, err := x509.CreateCertificate(rand.Reader, caCertTemplate, caCertTemplate, caKey.Public(), caKey)
if err != nil {
t.Fatal(err)
}
caCert, err := x509.ParseCertificate(caBytes)
if err != nil {
t.Fatal(err)
}
caCertPEMBlock := &pem.Block{
Type: "CERTIFICATE",
Bytes: caBytes,
}
err = os.WriteFile(filepath.Join(tempDir, "ca_cert.pem"), pem.EncodeToMemory(caCertPEMBlock), 0o755)
if err != nil {
t.Fatal(err)
}
marshaledCAKey, err := x509.MarshalECPrivateKey(caKey)
if err != nil {
t.Fatal(err)
}
caKeyPEMBlock := &pem.Block{
Type: "EC PRIVATE KEY",
Bytes: marshaledCAKey,
}
err = os.WriteFile(filepath.Join(tempDir, "ca_key.pem"), pem.EncodeToMemory(caKeyPEMBlock), 0o755)
if err != nil {
t.Fatal(err)
}

createCertificate := func(prefix string) {
key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
if err != nil {
t.Fatal(err)
}

template := &x509.Certificate{
Subject: pkix.Name{
CommonName: "example.com",
},
EmailAddresses: []string{"[email protected]"},
IPAddresses: []net.IP{net.ParseIP("127.0.0.1")},
ExtKeyUsage: []x509.ExtKeyUsage{
x509.ExtKeyUsageServerAuth,
x509.ExtKeyUsageClientAuth,
},
KeyUsage: x509.KeyUsageDigitalSignature | x509.KeyUsageKeyEncipherment | x509.KeyUsageKeyAgreement,
SerialNumber: big.NewInt(mathrand.Int63()),
NotBefore: time.Now().Add(-30 * time.Second),
NotAfter: time.Now().Add(262980 * time.Hour),
}
certBytes, err := x509.CreateCertificate(rand.Reader, template, caCert, key.Public(), caKey)
if err != nil {
t.Fatal(err)
}
certPEMBlock := &pem.Block{
Type: "CERTIFICATE",
Bytes: certBytes,
}
err = os.WriteFile(filepath.Join(tempDir, prefix+"_cert.pem"), pem.EncodeToMemory(certPEMBlock), 0o755)
if err != nil {
t.Fatal(err)
}
marshaledKey, err := x509.MarshalECPrivateKey(key)
if err != nil {
t.Fatal(err)
}
keyPEMBlock := &pem.Block{
Type: "EC PRIVATE KEY",
Bytes: marshaledKey,
}
err = os.WriteFile(filepath.Join(tempDir, prefix+"_key.pem"), pem.EncodeToMemory(keyPEMBlock), 0o755)
if err != nil {
t.Fatal(err)
}
}

createCertificate("client")
createCertificate("server")

return tempDir
}
Loading
Loading