refactor cli vpn config (#46)

* refactor cli vpn config

Co-authored-by: katexochen <49727155+katexochen@users.noreply.github.com>
This commit is contained in:
3u13r 2022-04-12 14:20:46 +02:00 committed by GitHub
parent 4c73c5076e
commit 1c0f52e04e
10 changed files with 265 additions and 349 deletions

View file

@ -21,6 +21,7 @@ import (
"github.com/edgelesssys/constellation/internal/config"
"github.com/edgelesssys/constellation/internal/state"
"github.com/kr/text"
wgquick "github.com/nmiculinic/wg-quick-go"
"github.com/spf13/afero"
"github.com/spf13/cobra"
"golang.zx2c4.com/wireguard/wgctrl/wgtypes"
@ -45,6 +46,7 @@ func newInitCmd() *cobra.Command {
// runInitialize runs the initialize command.
func runInitialize(cmd *cobra.Command, args []string) error {
fileHandler := file.NewHandler(afero.NewOsFs())
vpnHandler := vpn.NewConfigHandler()
devConfigName, err := cmd.Flags().GetString("dev-config")
if err != nil {
return err
@ -56,20 +58,19 @@ func runInitialize(cmd *cobra.Command, args []string) error {
protoClient := proto.NewClient(*config.Provider.GCP.PCRs)
defer protoClient.Close()
vpnClient, err := vpn.NewConfigurerWithDefaults()
if err != nil {
return err
}
// We have to parse the context separately, since cmd.Context()
// returns nil during the tests otherwise.
return initialize(cmd.Context(), cmd, protoClient, vpnClient, serviceAccountClient{}, fileHandler, config, status.NewWaiter(*config.Provider.GCP.PCRs))
return initialize(cmd.Context(), cmd, protoClient, serviceAccountClient{}, fileHandler, config, status.NewWaiter(*config.Provider.GCP.PCRs), vpnHandler)
}
// initialize initializes a Constellation. Coordinator instances are activated as Coordinators and will
// themself activate the other peers as nodes.
func initialize(ctx context.Context, cmd *cobra.Command, protCl protoClient, vpnCl vpnConfigurer, serviceAccountCr serviceAccountCreator,
fileHandler file.Handler, config *config.Config, waiter statusWaiter,
func initialize(ctx context.Context, cmd *cobra.Command, protCl protoClient, serviceAccountCr serviceAccountCreator,
fileHandler file.Handler, config *config.Config, waiter statusWaiter, vpnHandler vpnHandler,
) error {
flagArgs, err := evalFlagArgs(cmd, fileHandler, config)
if err != nil {
@ -138,12 +139,17 @@ func initialize(ctx context.Context, cmd *cobra.Command, protCl protoClient, vpn
return err
}
if err := result.writeWGQuickFile(fileHandler, config, string(flagArgs.userPrivKey)); err != nil {
vpnConfig, err := vpnHandler.Create(result.coordinatorPubKey, result.coordinatorPubIP, string(flagArgs.userPrivKey), result.clientVpnIP, wireguardAdminMTU)
if err != nil {
return err
}
if err := writeWGQuickFile(fileHandler, config, vpnHandler, vpnConfig); err != nil {
return fmt.Errorf("write wg-quick file: %w", err)
}
if flagArgs.autoconfigureWG {
if err := configureVpn(vpnCl, result.clientVpnIP, result.coordinatorPubKey, result.coordinatorPubIP, flagArgs.userPrivKey); err != nil {
if err := vpnHandler.Apply(vpnConfig); err != nil {
return err
}
}
@ -217,14 +223,10 @@ type activationResult struct {
}
// writeWGQuickFile writes the wg-quick file to the default path.
func (r activationResult) writeWGQuickFile(fileHandler file.Handler, config *config.Config, clientPrivKey string) error {
wgConf, err := vpn.NewConfig(r.coordinatorPubKey, r.coordinatorPubIP, clientPrivKey)
func writeWGQuickFile(fileHandler file.Handler, config *config.Config, vpnHandler vpnHandler, vpnConfig *wgquick.Config) error {
data, err := vpnHandler.Marshal(vpnConfig)
if err != nil {
return fmt.Errorf("create wg config: %w", err)
}
data, err := vpn.NewWGQuickConfig(wgConf, r.clientVpnIP, wireguardAdminMTU)
if err != nil {
return fmt.Errorf("create wg-quick config: %w", err)
return err
}
return fileHandler.Write(*config.WGQuickConfigPath, data, false)
}
@ -327,14 +329,6 @@ func readOrGenerateVPNKey(fileHandler file.Handler, privKeyPath string) (privKey
return privKey, pubKey, nil
}
func configureVpn(vpnCl vpnConfigurer, clientVpnIp, coordinatorPubKey, coordinatorPublicIp string, privKey []byte) error {
err := vpnCl.Configure(clientVpnIp, coordinatorPubKey, coordinatorPublicIp, string(privKey))
if err != nil {
return fmt.Errorf("could not configure WireGuard automatically: %w", err)
}
return nil
}
func ipsToEndpoints(ips []string, port string) []string {
var endpoints []string
for _, ip := range ips {

View file

@ -5,7 +5,6 @@ import (
"context"
"encoding/base64"
"errors"
"fmt"
"strconv"
"strings"
"testing"
@ -17,11 +16,11 @@ import (
"github.com/edgelesssys/constellation/cli/gcp"
"github.com/edgelesssys/constellation/internal/config"
"github.com/edgelesssys/constellation/internal/state"
wgquick "github.com/nmiculinic/wg-quick-go"
"github.com/spf13/afero"
"github.com/spf13/cobra"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"golang.zx2c4.com/wireguard/wgctrl/wgtypes"
)
func TestInitArgumentValidation(t *testing.T) {
@ -112,6 +111,8 @@ func TestInitialize(t *testing.T) {
serviceAccountCreator stubServiceAccountCreator
waiter statusWaiter
privKey string
vpnHandler vpnHandler
initVPN bool
errExpected bool
}{
"initialize some ec2 instances": {
@ -119,30 +120,77 @@ func TestInitialize(t *testing.T) {
client: &fakeProtoClient{
respClient: &fakeActivationRespClient{responses: testActivationResps},
},
waiter: stubStatusWaiter{},
privKey: testKey,
waiter: stubStatusWaiter{},
vpnHandler: &stubVPNHandler{},
privKey: testKey,
},
"initialize some gcp instances": {
existingState: testGcpState,
client: &fakeProtoClient{
respClient: &fakeActivationRespClient{responses: testActivationResps},
},
waiter: stubStatusWaiter{},
privKey: testKey,
waiter: stubStatusWaiter{},
vpnHandler: &stubVPNHandler{},
privKey: testKey,
},
"initialize some azure instances": {
existingState: testAzureState,
client: &fakeProtoClient{
respClient: &fakeActivationRespClient{responses: testActivationResps},
},
waiter: stubStatusWaiter{},
privKey: testKey,
waiter: stubStatusWaiter{},
vpnHandler: &stubVPNHandler{},
privKey: testKey,
},
"initialize vpn": {
existingState: testAzureState,
client: &fakeProtoClient{
respClient: &fakeActivationRespClient{responses: testActivationResps},
},
waiter: stubStatusWaiter{},
vpnHandler: &stubVPNHandler{},
initVPN: true,
privKey: testKey,
},
"invalid initialize vpn": {
existingState: testAzureState,
client: &fakeProtoClient{
respClient: &fakeActivationRespClient{responses: testActivationResps},
},
waiter: stubStatusWaiter{},
vpnHandler: &stubVPNHandler{applyErr: someErr},
initVPN: true,
privKey: testKey,
errExpected: true,
},
"invalid create vpn config": {
existingState: testAzureState,
client: &fakeProtoClient{
respClient: &fakeActivationRespClient{responses: testActivationResps},
},
waiter: stubStatusWaiter{},
vpnHandler: &stubVPNHandler{createErr: someErr},
initVPN: true,
privKey: testKey,
errExpected: true,
},
"invalid write vpn config": {
existingState: testAzureState,
client: &fakeProtoClient{
respClient: &fakeActivationRespClient{responses: testActivationResps},
},
waiter: stubStatusWaiter{},
vpnHandler: &stubVPNHandler{marshalErr: someErr},
initVPN: true,
privKey: testKey,
errExpected: true,
},
"no state exists": {
existingState: state.ConstellationState{},
client: &stubProtoClient{},
waiter: stubStatusWaiter{},
privKey: testKey,
vpnHandler: &stubVPNHandler{},
errExpected: true,
},
"no instances to pick one": {
@ -153,6 +201,7 @@ func TestInitialize(t *testing.T) {
client: &stubProtoClient{},
waiter: stubStatusWaiter{},
privKey: testKey,
vpnHandler: &stubVPNHandler{},
errExpected: true,
},
"only one instance": {
@ -163,6 +212,7 @@ func TestInitialize(t *testing.T) {
client: &stubProtoClient{},
waiter: stubStatusWaiter{},
privKey: testKey,
vpnHandler: &stubVPNHandler{},
errExpected: true,
},
"public key to short": {
@ -170,6 +220,7 @@ func TestInitialize(t *testing.T) {
client: &stubProtoClient{},
waiter: stubStatusWaiter{},
privKey: base64.StdEncoding.EncodeToString([]byte("tooShortKey")),
vpnHandler: &stubVPNHandler{},
errExpected: true,
},
"public key to long": {
@ -177,6 +228,7 @@ func TestInitialize(t *testing.T) {
client: &stubProtoClient{},
waiter: stubStatusWaiter{},
privKey: base64.StdEncoding.EncodeToString([]byte("thisWireguardKeyIsToLongAndHasTooManyBytes")),
vpnHandler: &stubVPNHandler{},
errExpected: true,
},
"public key not base64": {
@ -184,6 +236,7 @@ func TestInitialize(t *testing.T) {
client: &stubProtoClient{},
waiter: stubStatusWaiter{},
privKey: "this is not base64 encoded",
vpnHandler: &stubVPNHandler{},
errExpected: true,
},
"fail Connect": {
@ -191,6 +244,7 @@ func TestInitialize(t *testing.T) {
client: &stubProtoClient{connectErr: someErr},
waiter: stubStatusWaiter{},
privKey: testKey,
vpnHandler: &stubVPNHandler{},
errExpected: true,
},
"fail Activate": {
@ -198,6 +252,7 @@ func TestInitialize(t *testing.T) {
client: &stubProtoClient{activateErr: someErr},
waiter: stubStatusWaiter{},
privKey: testKey,
vpnHandler: &stubVPNHandler{},
errExpected: true,
},
"fail respClient WriteLogStream": {
@ -205,6 +260,7 @@ func TestInitialize(t *testing.T) {
client: &stubProtoClient{respClient: &stubActivationRespClient{writeLogStreamErr: someErr}},
waiter: stubStatusWaiter{},
privKey: testKey,
vpnHandler: &stubVPNHandler{},
errExpected: true,
},
"fail respClient getKubeconfig": {
@ -212,6 +268,7 @@ func TestInitialize(t *testing.T) {
client: &stubProtoClient{respClient: &stubActivationRespClient{getKubeconfigErr: someErr}},
waiter: stubStatusWaiter{},
privKey: testKey,
vpnHandler: &stubVPNHandler{},
errExpected: true,
},
"fail respClient getCoordinatorVpnKey": {
@ -219,6 +276,7 @@ func TestInitialize(t *testing.T) {
client: &stubProtoClient{respClient: &stubActivationRespClient{getCoordinatorVpnKeyErr: someErr}},
waiter: stubStatusWaiter{},
privKey: testKey,
vpnHandler: &stubVPNHandler{},
errExpected: true,
},
"fail respClient getClientVpnIp": {
@ -226,6 +284,7 @@ func TestInitialize(t *testing.T) {
client: &stubProtoClient{respClient: &stubActivationRespClient{getClientVpnIpErr: someErr}},
waiter: stubStatusWaiter{},
privKey: testKey,
vpnHandler: &stubVPNHandler{},
errExpected: true,
},
"fail respClient getOwnerID": {
@ -233,6 +292,7 @@ func TestInitialize(t *testing.T) {
client: &stubProtoClient{respClient: &stubActivationRespClient{getOwnerIDErr: someErr}},
waiter: stubStatusWaiter{},
privKey: testKey,
vpnHandler: &stubVPNHandler{},
errExpected: true,
},
"fail respClient getClusterID": {
@ -240,6 +300,7 @@ func TestInitialize(t *testing.T) {
client: &stubProtoClient{respClient: &stubActivationRespClient{getClusterIDErr: someErr}},
waiter: stubStatusWaiter{},
privKey: testKey,
vpnHandler: &stubVPNHandler{},
errExpected: true,
},
"fail to wait for required status": {
@ -247,6 +308,7 @@ func TestInitialize(t *testing.T) {
client: &stubProtoClient{},
waiter: stubStatusWaiter{waitForAllErr: someErr},
privKey: testKey,
vpnHandler: &stubVPNHandler{},
errExpected: true,
},
"fail to create service account": {
@ -257,6 +319,7 @@ func TestInitialize(t *testing.T) {
},
waiter: stubStatusWaiter{},
privKey: testKey,
vpnHandler: &stubVPNHandler{},
errExpected: true,
},
}
@ -278,16 +341,21 @@ func TestInitialize(t *testing.T) {
// Write key file to filesystem and set path in flag.
require.NoError(afero.Afero{Fs: fs}.WriteFile("privK", []byte(tc.privKey), 0o600))
require.NoError(cmd.Flags().Set("privatekey", "privK"))
if tc.initVPN {
require.NoError(cmd.Flags().Set("wg-autoconfig", "true"))
}
ctx := context.Background()
ctx, cancel := context.WithTimeout(ctx, 4*time.Second)
defer cancel()
err := initialize(ctx, cmd, tc.client, &dummyVPNConfigurer{}, &tc.serviceAccountCreator, fileHandler, config, tc.waiter)
err := initialize(ctx, cmd, tc.client, &tc.serviceAccountCreator, fileHandler, config, tc.waiter, tc.vpnHandler)
if tc.errExpected {
assert.Error(err)
} else {
require.NoError(err)
assert.Equal(tc.initVPN, tc.vpnHandler.(*stubVPNHandler).configured)
assert.Contains(out.String(), "192.0.2.2")
assert.Contains(out.String(), "ownerID")
assert.Contains(out.String(), "clusterID")
@ -296,21 +364,6 @@ func TestInitialize(t *testing.T) {
}
}
func TestConfigureVPN(t *testing.T) {
assert := assert.New(t)
key := []byte(base64.StdEncoding.EncodeToString([]byte("32bytesWireGuardKeyForTheTesting")))
ip := "192.0.2.1"
someErr := errors.New("failed")
configurer := stubVPNConfigurer{}
assert.NoError(configureVpn(&configurer, ip, string(key), ip, key))
assert.True(configurer.configured)
configurer = stubVPNConfigurer{configureErr: someErr}
assert.Error(configureVpn(&configurer, ip, string(key), ip, key))
}
func TestWriteOutput(t *testing.T) {
assert := assert.New(t)
@ -643,6 +696,7 @@ func TestAutoscaleFlag(t *testing.T) {
cmd.SetErr(&errOut)
fs := afero.NewMemMapFs()
fileHandler := file.NewHandler(fs)
vpnHandler := stubVPNHandler{}
require.NoError(fileHandler.WriteJSON(*config.StatePath, tc.existingState, false))
// Write key file to filesystem and set path in flag.
@ -652,7 +706,7 @@ func TestAutoscaleFlag(t *testing.T) {
require.NoError(cmd.Flags().Set("autoscale", strconv.FormatBool(tc.autoscaleFlag)))
ctx := context.Background()
require.NoError(initialize(ctx, cmd, tc.client, &dummyVPNConfigurer{}, &tc.serviceAccountCreator, fileHandler, config, tc.waiter))
require.NoError(initialize(ctx, cmd, tc.client, &tc.serviceAccountCreator, fileHandler, config, tc.waiter, &vpnHandler))
if tc.autoscaleFlag {
assert.Len(tc.client.activateAutoscalingNodeGroups, 1)
} else {
@ -663,52 +717,29 @@ func TestAutoscaleFlag(t *testing.T) {
}
func TestWriteWGQuickFile(t *testing.T) {
require := require.New(t)
testKey, err := wgtypes.GeneratePrivateKey()
require.NoError(err)
testCases := map[string]struct {
coordinatorPubKey string
coordinatorPubIP string
clientVpnIp string
fileHandler file.Handler
config *config.Config
clientPrivKey string
wantErr bool
fileHandler file.Handler
config *config.Config
vpnHandler *stubVPNHandler
vpnConfig *wgquick.Config
wantErr bool
}{
"write wg quick file": {
coordinatorPubKey: testKey.PublicKey().String(),
coordinatorPubIP: "192.0.2.1",
clientVpnIp: "192.0.2.2",
fileHandler: file.NewHandler(afero.NewMemMapFs()),
config: &config.Config{WGQuickConfigPath: func(s string) *string { return &s }("a.conf")},
clientPrivKey: testKey.String(),
fileHandler: file.NewHandler(afero.NewMemMapFs()),
config: &config.Config{WGQuickConfigPath: func(s string) *string { return &s }("a.conf")},
vpnHandler: &stubVPNHandler{marshalRes: "config"},
},
"invalid coordinator public key": {
coordinatorPubIP: "192.0.2.1",
clientVpnIp: "192.0.2.2",
fileHandler: file.NewHandler(afero.NewMemMapFs()),
config: &config.Config{WGQuickConfigPath: func(s string) *string { return &s }("a.conf")},
clientPrivKey: testKey.String(),
wantErr: true,
},
"invalid client vpn ip": {
coordinatorPubKey: testKey.PublicKey().String(),
coordinatorPubIP: "192.0.2.1",
fileHandler: file.NewHandler(afero.NewMemMapFs()),
config: &config.Config{WGQuickConfigPath: func(s string) *string { return &s }("a.conf")},
clientPrivKey: testKey.String(),
wantErr: true,
"marshal failed": {
fileHandler: file.NewHandler(afero.NewMemMapFs()),
config: &config.Config{WGQuickConfigPath: func(s string) *string { return &s }("a.conf")},
vpnHandler: &stubVPNHandler{marshalErr: errors.New("some err")},
wantErr: true,
},
"write fails": {
coordinatorPubKey: testKey.PublicKey().String(),
coordinatorPubIP: "192.0.2.1",
clientVpnIp: "192.0.2.2",
fileHandler: file.NewHandler(afero.NewReadOnlyFs(afero.NewMemMapFs())),
config: &config.Config{WGQuickConfigPath: func(s string) *string { return &s }("a.conf")},
clientPrivKey: testKey.String(),
wantErr: true,
fileHandler: file.NewHandler(afero.NewReadOnlyFs(afero.NewMemMapFs())),
config: &config.Config{WGQuickConfigPath: func(s string) *string { return &s }("a.conf")},
vpnHandler: &stubVPNHandler{marshalRes: "config"},
wantErr: true,
},
}
@ -716,12 +747,7 @@ func TestWriteWGQuickFile(t *testing.T) {
t.Run(name, func(t *testing.T) {
assert := assert.New(t)
result := activationResult{
coordinatorPubKey: tc.coordinatorPubKey,
coordinatorPubIP: tc.coordinatorPubIP,
clientVpnIP: tc.clientVpnIp,
}
err := result.writeWGQuickFile(tc.fileHandler, tc.config, tc.clientPrivKey)
err := writeWGQuickFile(tc.fileHandler, tc.config, tc.vpnHandler, tc.vpnConfig)
if tc.wantErr {
assert.Error(err)
@ -729,7 +755,7 @@ func TestWriteWGQuickFile(t *testing.T) {
assert.NoError(err)
file, err := tc.fileHandler.Read(*tc.config.WGQuickConfigPath)
assert.NoError(err)
assert.Contains(string(file), fmt.Sprint("MTU = ", wireguardAdminMTU))
assert.Contains(string(file), tc.vpnHandler.marshalRes)
}
})
}

9
cli/cmd/vpnconfig.go Normal file
View file

@ -0,0 +1,9 @@
package cmd
import wgquick "github.com/nmiculinic/wg-quick-go"
type vpnHandler interface {
Create(coordinatorPubKey string, coordinatorPubIP string, clientPrivKey string, clientVPNIP string, mtu int) (*wgquick.Config, error)
Apply(*wgquick.Config) error
Marshal(*wgquick.Config) ([]byte, error)
}

25
cli/cmd/vpnconfig_test.go Normal file
View file

@ -0,0 +1,25 @@
package cmd
import wgquick "github.com/nmiculinic/wg-quick-go"
type stubVPNHandler struct {
configured bool
marshalRes string
createErr error
applyErr error
marshalErr error
}
func (c *stubVPNHandler) Create(coordinatorPubKey string, coordinatorPubIP string, clientPrivKey string, clientVPNIP string, mtu int) (*wgquick.Config, error) {
return &wgquick.Config{}, c.createErr
}
func (c *stubVPNHandler) Apply(*wgquick.Config) error {
c.configured = true
return c.applyErr
}
func (c *stubVPNHandler) Marshal(*wgquick.Config) ([]byte, error) {
return []byte(c.marshalRes), c.marshalErr
}

View file

@ -1,5 +0,0 @@
package cmd
type vpnConfigurer interface {
Configure(clientVpnIp string, coordinatorPubKey string, coordinatorPubIP string, clientPrivKey string) error
}

View file

@ -1,17 +0,0 @@
package cmd
type stubVPNConfigurer struct {
configured bool
configureErr error
}
func (c *stubVPNConfigurer) Configure(clientVpnIp, coordinatorPubKey, coordinatorPubIP, clientPrivKey string) error {
c.configured = true
return c.configureErr
}
type dummyVPNConfigurer struct{}
func (c *dummyVPNConfigurer) Configure(clientVpnIp, coordinatorPubKey, coordinatorPubIP, clientPrivKey string) error {
panic("dummy doesn't implement this function")
}