diff --git a/v1/providers/shadeform/instance.go b/v1/providers/shadeform/instance.go index d87d22f..ac87012 100644 --- a/v1/providers/shadeform/instance.go +++ b/v1/providers/shadeform/instance.go @@ -12,7 +12,6 @@ import ( "github.com/brevdev/cloud/internal/errors" v1 "github.com/brevdev/cloud/v1" openapi "github.com/brevdev/cloud/v1/providers/shadeform/gen/shadeform" - "github.com/google/uuid" ) const ( @@ -29,7 +28,7 @@ type DefaultErrorResponse struct { Error string `json:"error"` } -func (c *ShadeformClient) CreateInstance(ctx context.Context, attrs v1.CreateInstanceAttrs) (*v1.Instance, error) { //nolint:gocyclo,funlen // ok +func (c *ShadeformClient) CreateInstance(ctx context.Context, attrs v1.CreateInstanceAttrs) (*v1.Instance, error) { //nolint:funlen // ok authCtx := c.makeAuthContext(ctx) c.logger.Debug(ctx, "Creating instance", v1.LogField("instanceAttrs", attrs)) @@ -39,24 +38,13 @@ func (c *ShadeformClient) CreateInstance(ctx context.Context, attrs v1.CreateIns return nil, errors.WrapAndTrace(fmt.Errorf("instance type: %v is not deployable", attrs.InstanceType)) } - sshKeyID := "" - - keyPairName := attrs.RefID - if attrs.KeyPairName != nil { - keyPairName = *attrs.KeyPairName - } - - if keyPairName == "" { - keyPairName = uuid.New().String() - c.logger.Debug(ctx, "No key pair name provided, generating new one", v1.LogField("keyPairName", keyPairName)) + base64Script, err := c.instanceLaunchScript(attrs) + if err != nil { + return nil, errors.WrapAndTrace(err) } - - if attrs.PublicKey != "" { - var err error - sshKeyID, err = c.addSSHKey(ctx, keyPairName, attrs.PublicKey) - if err != nil && !strings.Contains(err.Error(), "name must be unique") { - return nil, errors.WrapAndTrace(fmt.Errorf("failed to add SSH key: %w", err)) - } + sshKeyID, err := c.getSSHBootstrapKey(ctx, attrs) + if err != nil { + return nil, errors.WrapAndTrace(err) } region := attrs.Location @@ -87,11 +75,6 @@ func (c *ShadeformClient) CreateInstance(ctx context.Context, attrs v1.CreateIns tags = append(tags, createdTag) } - base64Script, err := c.GenerateFirewallScript(attrs.FirewallRules) - if err != nil { - return nil, errors.WrapAndTrace(err) - } - req := openapi.CreateRequest{ Cloud: cloud, Region: region, @@ -126,6 +109,7 @@ func (c *ShadeformClient) CreateInstance(ctx context.Context, attrs v1.CreateIns return nil, errors.WrapAndTrace(err) } + createdInstance.SSHCertificateBootstrap = attrs.SSHCertificateAuthority != nil return createdInstance, nil } @@ -185,6 +169,9 @@ func (c *ShadeformClient) addSSHKey(ctx context.Context, keyPairName string, pub defer func() { _ = httpResp.Body.Close() }() } if err != nil { + if httpResp == nil { + return "", errors.WrapAndTrace(err) + } httpMessage, _ := io.ReadAll(httpResp.Body) return "", errors.WrapAndTrace(fmt.Errorf("failed to add SSH Key: %w, %s", err, string(httpMessage))) } diff --git a/v1/providers/shadeform/ssh_ca.go b/v1/providers/shadeform/ssh_ca.go new file mode 100644 index 0000000..bab3ad6 --- /dev/null +++ b/v1/providers/shadeform/ssh_ca.go @@ -0,0 +1,89 @@ +package v1 + +import ( + "context" + "encoding/base64" + "fmt" + "strings" + + "github.com/brevdev/cloud/internal/errors" + "github.com/brevdev/cloud/internal/sshbootstrap" + v1 "github.com/brevdev/cloud/v1" + "github.com/google/uuid" +) + +func (c *ShadeformClient) instanceLaunchScript(attrs v1.CreateInstanceAttrs) (string, error) { + firewall, err := c.GenerateFirewallScript(attrs.FirewallRules) + if err != nil || attrs.SSHCertificateAuthority == nil { + return firewall, err + } + setup, err := sshbootstrap.InstallForKeyOwners(*attrs.SSHCertificateAuthority) + if err != nil { + return "", errors.WrapAndTrace(err) + } + decoded, err := base64.StdEncoding.DecodeString(firewall) + if err != nil { + return "", errors.WrapAndTrace(err) + } + return base64.StdEncoding.EncodeToString([]byte(setup + "\n" + string(decoded))), nil +} + +func (c *ShadeformClient) getSSHBootstrapKey(ctx context.Context, attrs v1.CreateInstanceAttrs) (string, error) { + if attrs.SSHCertificateAuthority != nil { + return c.getOrCreateSSHCAKey(ctx, attrs) + } + keyPairName := attrs.RefID + if attrs.KeyPairName != nil { + keyPairName = *attrs.KeyPairName + } + if keyPairName == "" { + keyPairName = uuid.New().String() + c.logger.Debug(ctx, "No key pair name provided, generating new one", v1.LogField("keyPairName", keyPairName)) + } + if attrs.PublicKey == "" { + return "", nil + } + id, err := c.addSSHKey(ctx, keyPairName, attrs.PublicKey) + if err != nil && !strings.Contains(err.Error(), "name must be unique") { + return "", errors.WrapAndTrace(fmt.Errorf("failed to add SSH key: %w", err)) + } + return id, nil +} + +func (c *ShadeformClient) getOrCreateSSHCAKey(ctx context.Context, attrs v1.CreateInstanceAttrs) (string, error) { + publicKey, err := sshbootstrap.CanonicalPublicKey(attrs.SSHCertificateAuthority.PublicKey) + if err != nil { + return "", errors.WrapAndTrace(err) + } + name := "brev-sshca-" + attrs.RefID + id, err := c.addSSHKey(ctx, name, publicKey) + if err == nil { + if id == "" { + return "", errors.New("Shadeform returned an empty SSH CA key ID") + } + return id, nil + } + if !strings.Contains(err.Error(), "name must be unique") { + return "", errors.WrapAndTrace(err) + } + keys, response, err := c.client.DefaultAPI.SshKeys(c.makeAuthContext(ctx)).Execute() + if response != nil && response.Body != nil { + defer func() { _ = response.Body.Close() }() + } + if err != nil { + return "", errors.WrapAndTrace(err) + } + if keys != nil { + for _, key := range keys.SshKeys { + if key.Name != name { + continue + } + existing, err := sshbootstrap.CanonicalPublicKey(key.PublicKey) + if err != nil || existing != publicKey || key.Id == "" { + return "", errors.Errorf("existing Shadeform SSH CA key %q does not match", name) + } + return key.Id, nil + } + } + return "", errors.Errorf("Shadeform SSH CA key %q not found after name conflict", name) +} diff --git a/v1/providers/shadeform/ssh_ca_test.go b/v1/providers/shadeform/ssh_ca_test.go new file mode 100644 index 0000000..9760f43 --- /dev/null +++ b/v1/providers/shadeform/ssh_ca_test.go @@ -0,0 +1,151 @@ +package v1 + +import ( + "crypto/ed25519" + "crypto/rand" + "encoding/base64" + "encoding/json" + "io" + "net/http" + "strings" + "testing" + + v1 "github.com/brevdev/cloud/v1" + openapi "github.com/brevdev/cloud/v1/providers/shadeform/gen/shadeform" + "github.com/stretchr/testify/require" + "golang.org/x/crypto/ssh" +) + +type bootstrapTransport func(*http.Request) (*http.Response, error) + +func (f bootstrapTransport) RoundTrip(request *http.Request) (*http.Response, error) { + return f(request) +} + +func TestCreateInstanceSSHCertificateBootstrap(t *testing.T) { //nolint:funlen // test ok + public, _, err := ed25519.GenerateKey(rand.Reader) + require.NoError(t, err) + key, err := ssh.NewPublicKey(public) + require.NoError(t, err) + caKey := strings.TrimSpace(string(ssh.MarshalAuthorizedKey(key))) + for _, test := range []struct { + name string + certificate bool + existingKey string + wantError bool + }{ + {name: "legacy"}, + { + name: "certificate", + certificate: true, + }, + { + name: "retry with matching CA", + certificate: true, + existingKey: caKey + " provider-comment", + }, + { + name: "name collision cannot select a user key", + certificate: true, + existingKey: "legacy-user-key", + wantError: true, + }, + } { + t.Run(test.name, func(t *testing.T) { + args := v1.CreateInstanceAttrs{ + RefID: "instance-ref", + Name: "workspace", + InstanceType: "cloud_H100", + PublicKey: "legacy-user-key", + } + if test.certificate { + args.SSHCertificateAuthority = &v1.SSHCertificateAuthority{ + PublicKey: caKey, + PrincipalPrefix: "brev:v1:vm:env-shadeform:login:", + } + } + var registered openapi.AddSshKeyRequest + var posted *openapi.CreateRequest + config := openapi.NewConfiguration() + config.HTTPClient = &http.Client{ + Transport: bootstrapTransport(func(request *http.Request) (*http.Response, error) { + status := http.StatusOK + var body any + switch request.Method + " " + request.URL.Path { + case "POST /v1/sshkeys/add": + require.NoError(t, json.NewDecoder(request.Body).Decode(®istered)) + body = openapi.AddSshKeyResponse{Id: "registered-key"} + if test.existingKey != "" { + status = http.StatusConflict + body = map[string]string{"error": "name must be unique"} + } + case "GET /v1/sshkeys": + body = openapi.SshKeysResponse{SshKeys: []openapi.SshKey{ + { + Id: "default-user-key", + Name: "other-key", + PublicKey: "legacy-user-key", + }, + { + Id: "existing-ca-key", + Name: registered.Name, + PublicKey: test.existingKey, + }, + }} + case "POST /v1/instances/create": + require.NoError(t, json.NewDecoder(request.Body).Decode(&posted)) + body = openapi.CreateResponse{Id: "vm-id"} + case "GET /v1/instances/vm-id/info": + body = openapi.InstanceInfoResponse{ + Id: "vm-id", + Name: posted.Name, + Tags: posted.Tags, + Cloud: "cloud", + ShadeInstanceType: "H100", + SshUser: "shadeform", + Status: openapi.ACTIVE, + } + default: + t.Fatalf("unexpected request: %s %s", request.Method, request.URL.Path) + } + encoded, err := json.Marshal(body) + require.NoError(t, err) + return &http.Response{ + StatusCode: status, + Header: http.Header{"Content-Type": {"application/json"}}, + Body: io.NopCloser(strings.NewReader(string(encoded))), + Request: request, + }, nil + }), + } + client := NewShadeformClient("credential", "test-key") + client.client = openapi.NewAPIClient(config) + instance, err := client.CreateInstance(t.Context(), args) + if test.wantError { + require.Error(t, err) + require.Nil(t, posted, "a conflicting key must never select the account default") + return + } + require.NoError(t, err) + require.Equal(t, test.certificate, instance.SSHCertificateBootstrap) + script, err := base64.StdEncoding.DecodeString(posted.LaunchConfiguration.ScriptConfiguration.Base64Script) + require.NoError(t, err) + require.Contains(t, string(script), "ufw allow 22/tcp") + if !test.certificate { + require.Equal(t, "legacy-user-key", registered.PublicKey) + require.Equal(t, args.RefID, registered.Name) + require.NotContains(t, string(script), "cert-authority") + return + } + require.Equal(t, caKey, registered.PublicKey) + require.Equal(t, "brev-sshca-"+args.RefID, registered.Name) + id := "registered-key" + if test.existingKey != "" { + id = "existing-ca-key" + } + require.Equal(t, id, *posted.SshKeyId) + require.Contains(t, string(script), "brev:v1:vm:env-shadeform:login:") + require.NotContains(t, string(script), "legacy-user-key") + }) + } +}