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

Allow for mTLS connections configured from environment #237

Merged
merged 2 commits into from
Jul 22, 2024
Merged
Changes from 1 commit
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
65 changes: 65 additions & 0 deletions internal/cmd/authenticated/client.go
Original file line number Diff line number Diff line change
@@ -1,12 +1,36 @@
package authenticated

import (
"crypto/tls"
"crypto/x509"
"fmt"
"net/http"
"os"

"github.com/urfave/cli/v2"

"github.com/spacelift-io/spacectl/client"
"github.com/spacelift-io/spacectl/client/session"
)

const (
// EnvSpaceliftAPIClientTLSCert represents the path to a client certificate for
// communicating with the Spacelift API endpoint.
EnvSpaceliftAPIClientTLSCert = "SPACELIFT_API_TLS_CERT"

// EnvSpaceliftAPIClientTLSKey represents the path to a client key for
// communicating with the Spacelift API endpoint.
EnvSpaceliftAPIClientTLSKey = "SPACELIFT_API_TLS_KEY"

// EnvSpaceliftAPIClientCA represents the path to a CA bundle for
// verifying Spacelift API endpoint.
EnvSpaceliftAPIClientCA = "SPACELIFT_API_TLS_CA"
)

var (
errEnvSpaceliftAPIClientCAParse = fmt.Errorf("failed to parse %s", EnvSpaceliftAPIClientCA)
)

// Client is the authenticated client that can be used by all CLI commands.
var Client client.Client

Expand All @@ -15,6 +39,10 @@
func Ensure(*cli.Context) error {
ctx, httpClient := session.Defaults()

if err := configureTLS(httpClient); err != nil {
return err
}

session, err := session.New(ctx, httpClient)
if err != nil {
return err
Expand All @@ -24,3 +52,40 @@

return nil
}

// configureTLS configures client TLS from the environment.
func configureTLS(httpClient *http.Client) error {
clientTLS := &tls.Config{}

Check failure

Code scanning / Golang security checks by gosec

TLS MinVersion too low. Error

TLS MinVersion too low.

if caFile, ok := os.LookupEnv(EnvSpaceliftAPIClientCA); ok && caFile != "" {
caCert, err := os.ReadFile("cacert")
if err != nil {
return err
}

caCertPool := x509.NewCertPool()
if !caCertPool.AppendCertsFromPEM(caCert) {
return errEnvSpaceliftAPIClientCAParse
}

clientTLS.RootCAs = caCertPool
}

keyFile, keyOk := os.LookupEnv(EnvSpaceliftAPIClientTLSKey)
certFile, certOk := os.LookupEnv(EnvSpaceliftAPIClientTLSCert)

if keyOk && keyFile != "" && certOk && certFile != "" {
cert, err := tls.LoadX509KeyPair(certFile, keyFile)
if err != nil {
return err
}

clientTLS.Certificates = []tls.Certificate{cert}
}

httpClient.Transport = &http.Transport{
TLSClientConfig: clientTLS,
}

return nil
}