diff --git a/docs/SECURITY.md b/docs/SECURITY.md index 64393f2..b9d1390 100644 --- a/docs/SECURITY.md +++ b/docs/SECURITY.md @@ -21,6 +21,8 @@ This document outlines the security requirements and best practices for implemen - Public keys must be injectable during instance provisioning - SSH access must be available through the configured firewall rules +Providers supporting `CreateInstanceAttrs.SSHCertificateAuthority` install resource-scoped CA trust instead of the user's public key and report `Instance.SSHCertificateBootstrap` on creation. Providers that do not support CA bootstrap retain their existing key setup and leave that result false. CA private keys remain in the caller's secret store; the SDK receives only public trust material. + ## 🌐 Network Security Requirements ### Network Requirements diff --git a/internal/sshbootstrap/authorized_key.go b/internal/sshbootstrap/authorized_key.go new file mode 100644 index 0000000..bf40180 --- /dev/null +++ b/internal/sshbootstrap/authorized_key.go @@ -0,0 +1,31 @@ +// Package sshbootstrap renders resource-scoped SSH CA trust for provider bootstrapping. +package sshbootstrap + +import ( + "fmt" + "strings" + + v1 "github.com/brevdev/cloud/v1" + "golang.org/x/crypto/ssh" +) + +// AuthorizedKey binds CA trust to the resource and its actual SSH login account. +func AuthorizedKey(authority v1.SSHCertificateAuthority, user string) (string, error) { + if authority.PrincipalPrefix == "" || user == "" { + return "", fmt.Errorf("SSH CA bootstrap requires a principal prefix and SSH user") + } + publicKey, err := CanonicalPublicKey(authority.PublicKey) + if err != nil { + return "", fmt.Errorf("invalid SSH CA public key: %w", err) + } + return fmt.Sprintf("cert-authority,principals=%q %s", authority.PrincipalPrefix+user, publicKey), nil +} + +// CanonicalPublicKey discards authorized-key options, comments, and trailing content. +func CanonicalPublicKey(raw string) (string, error) { + key, _, _, _, err := ssh.ParseAuthorizedKey([]byte(raw)) + if err != nil { + return "", err + } + return strings.TrimSpace(string(ssh.MarshalAuthorizedKey(key))), nil +} diff --git a/v1/instance.go b/v1/instance.go index 70ee10c..45aa6f2 100644 --- a/v1/instance.go +++ b/v1/instance.go @@ -49,6 +49,9 @@ type UpdateHandler interface { } type Instance struct { + // CreateInstance only: the provider configured certificate-only SSH bootstrap. + SSHCertificateBootstrap bool + Name string RefID string CloudCredRefID string // cloudCred used to create the Instance @@ -129,7 +132,18 @@ type ListInstancesArgs struct { Locations LocationsFilter } +// SSHCertificateAuthority contains public trust material for one resource. +// Providers append their actual SSH login username to PrincipalPrefix. +type SSHCertificateAuthority struct { + PublicKey string + PrincipalPrefix string +} + type CreateInstanceAttrs struct { + // When set, supporting providers install CA trust instead of the user's PublicKey. + // Other providers retain their existing bootstrap and report SSHCertificateBootstrap=false. + SSHCertificateAuthority *SSHCertificateAuthority + Location string SubLocation string Name string diff --git a/v1/providers/nebius/instance.go b/v1/providers/nebius/instance.go index 9c8403a..7a3dc8d 100644 --- a/v1/providers/nebius/instance.go +++ b/v1/providers/nebius/instance.go @@ -5,12 +5,14 @@ import ( _ "embed" "encoding/base64" "fmt" + "strconv" "strings" "time" "github.com/alecthomas/units" "github.com/brevdev/cloud/internal/collections" "github.com/brevdev/cloud/internal/errors" + "github.com/brevdev/cloud/internal/sshbootstrap" v1 "github.com/brevdev/cloud/v1" "github.com/cenkalti/backoff/v4" common "github.com/nebius/gosdk/proto/nebius/common/v1" @@ -19,6 +21,7 @@ import ( ) const ( + defaultSSHUsername = "ubuntu" platformTypeCPU = "cpu" nebiusGPUImageFamily = "ubuntu24.04-cuda13.0" nebiusCPUImageFamily = "ubuntu24.04-driverless" @@ -46,6 +49,11 @@ var dockerFirewallDropIn string //nolint:funlen // Complex instance creation with resource management func (c *NebiusClient) CreateInstance(ctx context.Context, attrs v1.CreateInstanceAttrs) (*v1.Instance, error) { + cloudInitUserData, err := generateCloudInitUserData(attrs) + if err != nil { + return nil, errors.WrapAndTrace(err) + } + // Track created resources for automatic cleanup on failure var networkID, subnetID, bootDiskID, instanceID string var instanceCreateAttempted bool @@ -73,7 +81,6 @@ func (c *NebiusClient) CreateInstance(ctx context.Context, attrs v1.CreateInstan // Create isolated networking infrastructure for this instance // Use RefID (environmentId) for resource correlation - var err error networkID, subnetID, err = c.createIsolatedNetwork(ctx, attrs.RefID, ciRunLabels(attrs.Tags)) if err != nil { return nil, fmt.Errorf("failed to create isolated network: %w", err) @@ -91,10 +98,6 @@ func (c *NebiusClient) CreateInstance(ctx context.Context, attrs v1.CreateInstan return nil, fmt.Errorf("failed to parse instance type %s: %w", attrs.InstanceType, err) } - // Generate cloud-init user-data for SSH key injection and firewall configuration - // This is similar to Shadeform's LaunchConfiguration approach but uses cloud-init - cloudInitUserData := generateCloudInitUserData(attrs.PublicKey, attrs.FirewallRules) - // Create instance specification instanceSpec := &compute.InstanceSpec{ Resources: &compute.ResourcesSpec{ @@ -207,6 +210,7 @@ func (c *NebiusClient) CreateInstance(ctx context.Context, attrs v1.CreateInstan createdInstance.RefID = attrs.RefID createdInstance.CloudCredRefID = c.refID createdInstance.Tags = attrs.Tags + createdInstance.SSHCertificateBootstrap = attrs.SSHCertificateAuthority != nil // Success - instance reached RUNNING state // Disable cleanup and return @@ -365,7 +369,7 @@ func (c *NebiusClient) convertNebiusInstanceToV1(ctx context.Context, instance * } // Determine SSH user based on image - sshUser := "ubuntu" // Default SSH user for Nebius instances + sshUser := defaultSSHUsername // Default SSH user for Nebius instances imageFamily := extractImageFamily(instance.Spec.BootDisk) if strings.Contains(strings.ToLower(imageFamily), "centos") { sshUser = "centos" @@ -1709,7 +1713,15 @@ func (c *NebiusClient) cleanupOrphanedBootDisks(ctx context.Context, testID stri // generateCloudInitUserData generates a cloud-init user-data script for SSH key injection and firewall configuration // This is inspired by Shadeform's LaunchConfiguration approach but uses cloud-init directly. -func generateCloudInitUserData(publicKey string, firewallRules v1.FirewallRules) string { +func generateCloudInitUserData(attrs v1.CreateInstanceAttrs) (string, error) { + publicKey := attrs.PublicKey + if attrs.SSHCertificateAuthority != nil { + var err error + publicKey, err = sshbootstrap.AuthorizedKey(*attrs.SSHCertificateAuthority, defaultSSHUsername) + if err != nil { + return "", errors.WrapAndTrace(err) + } + } // Start with cloud-init header script := `#cloud-config packages: @@ -1720,7 +1732,7 @@ packages: if publicKey != "" { script += fmt.Sprintf(`ssh_authorized_keys: - %s -`, publicKey) +`, strconv.Quote(publicKey)) } script += generateDockerFirewallWriteFiles() @@ -1731,7 +1743,7 @@ packages: // Generate UFW firewall commands (similar to Shadeform's approach) // UFW (Uncomplicated Firewall) is available on Ubuntu/Debian instances - commands = append(commands, generateUFWCommands(firewallRules)...) + commands = append(commands, generateUFWCommands(attrs.FirewallRules)...) // Apply immediately for images where Docker is already running. The // docker.service ExecStartPost hook handles images where Docker starts later. @@ -1747,7 +1759,7 @@ packages: } } - return script + return script, nil } // generateUFWCommands generates UFW firewall commands similar to Shadeform diff --git a/v1/providers/nebius/instance_test.go b/v1/providers/nebius/instance_test.go index 3a5523e..aaff9a7 100644 --- a/v1/providers/nebius/instance_test.go +++ b/v1/providers/nebius/instance_test.go @@ -85,7 +85,8 @@ func TestNebiusClient_MergeInstanceForUpdate(t *testing.T) { } func TestGenerateCloudInitUserDataInstallsDockerFirewallHook(t *testing.T) { - script := generateCloudInitUserData("ssh-rsa test", v1.FirewallRules{}) + script, err := generateCloudInitUserData(v1.CreateInstanceAttrs{PublicKey: "ssh-rsa test"}) + assert.NoError(t, err) assert.NotContains(t, script, "iptables-persistent") assert.NotContains(t, script, "netfilter-persistent") diff --git a/v1/providers/nebius/ssh_ca_test.go b/v1/providers/nebius/ssh_ca_test.go new file mode 100644 index 0000000..612ff06 --- /dev/null +++ b/v1/providers/nebius/ssh_ca_test.go @@ -0,0 +1,60 @@ +package v1 + +import ( + "crypto/ed25519" + "crypto/rand" + "testing" + + v1 "github.com/brevdev/cloud/v1" + "github.com/stretchr/testify/require" + "golang.org/x/crypto/ssh" + "gopkg.in/yaml.v3" +) + +func TestCloudInitSSHCertificateTrustPreservesFirewall(t *testing.T) { + public, _, err := ed25519.GenerateKey(rand.Reader) + require.NoError(t, err) + key, err := ssh.NewPublicKey(public) + require.NoError(t, err) + publicKey := string(ssh.MarshalAuthorizedKey(key)) + args := v1.CreateInstanceAttrs{ + PublicKey: "legacy-user-key", + } + for _, certificate := range []bool{false, true} { + if certificate { + args.SSHCertificateAuthority = &v1.SSHCertificateAuthority{ + PublicKey: publicKey, + PrincipalPrefix: "brev:v1:vm:env-nebius:login:", + } + } + userData, err := generateCloudInitUserData(args) + require.NoError(t, err) + var config struct { + Keys []string `yaml:"ssh_authorized_keys"` + Commands []string `yaml:"runcmd"` + } + require.NoError(t, yaml.Unmarshal([]byte(userData), &config)) + require.Len(t, config.Keys, 1) + require.Contains(t, config.Commands, "ufw allow 22/tcp") + require.Contains(t, config.Commands, "sudo /usr/local/sbin/brev-apply-docker-firewall.sh || true") + if !certificate { + require.Equal(t, []string{"legacy-user-key"}, config.Keys) + continue + } + parsed, _, options, rest, err := ssh.ParseAuthorizedKey([]byte(config.Keys[0])) + require.NoError(t, err) + require.Equal(t, key.Marshal(), parsed.Marshal()) + require.ElementsMatch(t, []string{"cert-authority", `principals="brev:v1:vm:env-nebius:login:ubuntu"`}, options) + require.Empty(t, rest) + require.NotContains(t, userData, "legacy-user-key") + require.Contains(t, userData, dockerFirewallScriptPath) + require.Contains(t, userData, dockerFirewallDropInPath) + } + args.SSHCertificateAuthority.PublicKey = "invalid-key" + _, err = (&NebiusClient{}).CreateInstance(t.Context(), args) + require.ErrorContains(t, err, "invalid SSH CA public key") + args.SSHCertificateAuthority.PublicKey = publicKey + args.SSHCertificateAuthority.PrincipalPrefix = "" + _, err = generateCloudInitUserData(args) + require.Error(t, err) +}