Skip to content
Draft
Show file tree
Hide file tree
Changes from all 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
71 changes: 71 additions & 0 deletions internal/sshbootstrap/key_owners.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
package sshbootstrap

import (
"crypto/sha256"
"fmt"
"strings"

v1 "github.com/brevdev/cloud/v1"
)

// InstallForKeyOwners discovers the provider's login account from the unique CA
// public key supplied to its create API, then replaces raw keys with scoped trust.
func InstallForKeyOwners(authority v1.SSHCertificateAuthority) (string, error) {
if authority.PrincipalPrefix == "" || strings.ContainsAny(authority.PrincipalPrefix, "\"\\,\r\n") {
return "", fmt.Errorf("invalid SSH CA principal prefix")
}
publicKey, err := CanonicalPublicKey(authority.PublicKey)
if err != nil {
return "", fmt.Errorf("invalid SSH CA public key: %w", err)
}
return fmt.Sprintf(installForKeyOwnersScript, shellQuote(publicKey), shellQuote(authority.PrincipalPrefix),
sha256.Sum256([]byte(authority.PrincipalPrefix+publicKey))), nil
}

func shellQuote(value string) string {
return "'" + strings.ReplaceAll(value, "'", "'\"'\"'") + "'"
}

// A CA-specific marker prevents a replayed launch script from undoing rotation.
// Use the health probe's authorized_keys lock and publish each file atomically.
const installForKeyOwnersScript = `#!/bin/bash
(
set -eu
umask 077
CA_PUBLIC_KEY=%s
PRINCIPAL_PREFIX=%s
CA_TYPE=${CA_PUBLIC_KEY%%%% *}
CA_DATA=${CA_PUBLIC_KEY#* }
INSTALLED=0
while IFS=: read -r SSH_USER _ _ _ _ HOME_DIR _; do
AUTH_KEYS="$HOME_DIR/.ssh/authorized_keys"
MARKER="$HOME_DIR/.ssh/.brev-ca-bootstrap-%x"
if [ -f "$MARKER" ]; then
INSTALLED=1
continue
fi
[ -f "$AUTH_KEYS" ] || continue
if ! awk -v type="$CA_TYPE" -v key="$CA_DATA" '$1 == type && $2 == key { found=1 } END { exit !found }' "$AUTH_KEYS"; then
continue
fi
(
exec 9>"$AUTH_KEYS.lock"
flock 9
chown "$SSH_USER" "$AUTH_KEYS.lock"
chmod 600 "$AUTH_KEYS.lock"
[ ! -f "$MARKER" ] || exit 0
TMP_KEYS=$(mktemp "$AUTH_KEYS.tmp.XXXXXX")
trap 'rm -f "$TMP_KEYS"' EXIT
printf 'cert-authority,principals="%%s%%s" %%s\n' "$PRINCIPAL_PREFIX" "$SSH_USER" "$CA_PUBLIC_KEY" > "$TMP_KEYS"
chmod 600 "$TMP_KEYS"
chown "$SSH_USER" "$TMP_KEYS"
mv "$TMP_KEYS" "$AUTH_KEYS"
touch "$MARKER"
)
INSTALLED=1
done < <(getent passwd)
[ "$INSTALLED" -eq 1 ] || { echo "No account contains the SSH CA bootstrap key" >&2; exit 1; }
)
BREV_CA_STATUS=$?
[ "$BREV_CA_STATUS" -eq 0 ] || exit "$BREV_CA_STATUS"
`
92 changes: 92 additions & 0 deletions internal/sshbootstrap/key_owners_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
package sshbootstrap

import (
"crypto/ed25519"
"crypto/rand"
"os"
"os/exec"
"path/filepath"
"strings"
"testing"

v1 "github.com/brevdev/cloud/v1"
"github.com/stretchr/testify/require"
"golang.org/x/crypto/ssh"
)

func TestInstallForKeyOwnersUsesProviderAccountAndPreservesRotation(t *testing.T) {
public, _, err := ed25519.GenerateKey(rand.Reader)
require.NoError(t, err)
key, err := ssh.NewPublicKey(public)
require.NoError(t, err)
ca := v1.SSHCertificateAuthority{
PublicKey: string(ssh.MarshalAuthorizedKey(key)),
PrincipalPrefix: "brev:v1:vm:env-shadeform:login:",
}
script, err := InstallForKeyOwners(ca)
require.NoError(t, err)
for _, owner := range []string{"ubuntu", "shadeform", "no-matching-key"} {
t.Run(owner, func(t *testing.T) {
home := t.TempDir()
original := map[string]string{}
for _, user := range []string{"ubuntu", "shadeform", "root"} {
original[user] = "unrelated-key\n"
if user == owner {
original[user] += strings.TrimSpace(ca.PublicKey) + " provider-comment\n"
}
if user == "root" {
original[user] += `command="use the login user" ` + ca.PublicKey
}
require.NoError(t, os.MkdirAll(filepath.Join(home, user, ".ssh"), 0o700))
require.NoError(t, os.WriteFile(filepath.Join(home, user, ".ssh", "authorized_keys"), []byte(original[user]), 0o600))
}
const utilities = `getent() {
for user in ubuntu shadeform root; do
printf '%s:x:1000:1000::%s/%s:/bin/bash\n' "$user" "$BOOTSTRAP_HOME" "$user"
done
}
chown() { printf '%s:%s\n' "$1" "$2" >> "$BOOTSTRAP_HOME/ownership"; }
flock() { :; }
`
run := func() ([]byte, error) {
t.Helper()
command := exec.CommandContext(t.Context(), "bash")
command.Env = append(os.Environ(), "BOOTSTRAP_HOME="+home)
command.Stdin = strings.NewReader(utilities + script + "printf continued")
return command.CombinedOutput()
}
output, err := run()
if owner == "no-matching-key" {
require.Error(t, err, "missing provider bootstrap key must fail closed")
return
}
require.NoError(t, err, string(output))
require.Equal(t, "continued", string(output))
for user, before := range original {
contents, err := os.ReadFile(filepath.Join(home, user, ".ssh", "authorized_keys")) //nolint:gosec // test ok
require.NoError(t, err)
want := before
if user == owner {
want, err = AuthorizedKey(ca, owner)
require.NoError(t, err)
want += "\n"
}
require.Equal(t, want, string(contents), user)
}
path := filepath.Join(home, owner, ".ssh", "authorized_keys")
ownership, err := os.ReadFile(filepath.Join(home, "ownership")) //nolint:gosec // test ok
require.NoError(t, err)
require.Contains(t, string(ownership), owner+":"+path+".lock\n", "later healing runs as the login user")
lock, err := os.Stat(path + ".lock")
require.NoError(t, err)
require.Equal(t, os.FileMode(0o600), lock.Mode().Perm())
require.NoError(t, os.WriteFile(path, []byte("rotated-ca\n"), 0o600))
output, err = run()
require.NoError(t, err, string(output))
require.Equal(t, "continued", string(output))
contents, err := os.ReadFile(path) //nolint:gosec // test ok
require.NoError(t, err)
require.Equal(t, "rotated-ca\n", string(contents))
})
}
}
26 changes: 24 additions & 2 deletions v1/providers/launchpad/instance_create.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (

"github.com/brevdev/cloud/internal/collections"
"github.com/brevdev/cloud/internal/errors"
"github.com/brevdev/cloud/internal/sshbootstrap"

v1 "github.com/brevdev/cloud/v1"
openapi "github.com/brevdev/cloud/v1/providers/launchpad/gen/launchpad"
Expand All @@ -21,7 +22,11 @@ const (

func (c *LaunchpadClient) CreateInstance(ctx context.Context, attrs v1.CreateInstanceAttrs) (*v1.Instance, error) {
createAttrs := launchpadCreateAttrs(attrs)
err := createAttrs.validate()
startupScript, err := createAttrs.prepareSSHBootstrap()
if err != nil {
return nil, errors.WrapAndTrace(err)
}
err = createAttrs.validate()
if err != nil {
return nil, errors.WrapAndTrace(err)
}
Expand All @@ -38,7 +43,7 @@ func (c *LaunchpadClient) CreateInstance(ctx context.Context, attrs v1.CreateIns
region = *openapi.NewNullableString(nil)
}

publicKey := openapi.NewNullableString(collections.Ptr(attrs.PublicKey))
publicKey := openapi.NewNullableString(collections.Ptr(createAttrs.PublicKey))
createAttrs.Tags = createAttrs.generateTags(c.GetReferenceID())

deployment := openapi.Deployment{
Expand All @@ -56,6 +61,10 @@ func (c *LaunchpadClient) CreateInstance(ctx context.Context, attrs v1.CreateIns
Tags: createAttrs.Tags,
Region: region,
}
if startupScript != "" {
// Launchpad 2.72.1 supports this field; our pinned schema predates it.
deployment.AdditionalProperties = map[string]interface{}{"startup_script": startupScript}
}

// The workshop ID should only be set if it was determined to be not empty
if instanceTypeInfo.workshopID != "" {
Expand Down Expand Up @@ -94,6 +103,7 @@ func (c *LaunchpadClient) CreateInstance(ctx context.Context, attrs v1.CreateIns
if err != nil {
return nil, errors.WrapAndTrace(err)
}
inst.SSHCertificateBootstrap = attrs.SSHCertificateAuthority != nil
return inst, nil
}

Expand All @@ -115,6 +125,18 @@ func matchesGH200Experience(info instanceTypeInfo) bool {

type launchpadCreateAttrs v1.CreateInstanceAttrs

func (l *launchpadCreateAttrs) prepareSSHBootstrap() (string, error) {
if l.SSHCertificateAuthority == nil {
return "", nil
}
publicKey, err := sshbootstrap.CanonicalPublicKey(l.SSHCertificateAuthority.PublicKey)
if err != nil {
return "", err
}
l.PublicKey = publicKey
return sshbootstrap.InstallForKeyOwners(*l.SSHCertificateAuthority)
}

func (l launchpadCreateAttrs) validate() error {
err := validation.ValidateStruct(
&l,
Expand Down
116 changes: 116 additions & 0 deletions v1/providers/launchpad/ssh_ca_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,116 @@
package v1

import (
"crypto/ed25519"
"crypto/rand"
"encoding/json"
"io"
"net/http"
"strings"
"testing"

"github.com/brevdev/cloud/internal/collections"
"github.com/brevdev/cloud/internal/sshbootstrap"
v1 "github.com/brevdev/cloud/v1"
openapi "github.com/brevdev/cloud/v1/providers/launchpad/gen/launchpad"
"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) {
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
publicKey string
certificate bool
invalidCA bool
}{
{name: "legacy", publicKey: "legacy-user-key"},
{name: "certificate replaces user key", publicKey: "legacy-user-key", certificate: true},
{name: "certificate needs no user key", certificate: true},
{name: "invalid CA never reaches provider", publicKey: "legacy-user-key", certificate: true, invalidCA: true},
} {
t.Run(test.name, func(t *testing.T) {
args := v1.CreateInstanceAttrs{
Name: "workspace", RefID: "env-launchpad", PublicKey: test.publicKey,
InstanceType: "dmz.h100x1.pcie", Location: "pdx",
FirewallRules: v1.FirewallRules{IngressRules: []v1.FirewallRule{{IPRanges: []string{"192.0.2.1/32"}}}},
}
if test.certificate {
args.SSHCertificateAuthority = &v1.SSHCertificateAuthority{
PublicKey: caKey + " provider-comment\n", PrincipalPrefix: "brev:v1:vm:env-launchpad:login:",
}
if test.invalidCA {
args.SSHCertificateAuthority.PublicKey = "invalid-key"
}
}
var posted map[string]json.RawMessage
config := openapi.NewConfiguration()
config.HTTPClient = &http.Client{Transport: bootstrapTransport(func(request *http.Request) (*http.Response, error) {
if test.invalidCA {
t.Fatal("invalid CA must be rejected before any provider request")
}
status := http.StatusOK
switch request.Method + " " + request.URL.Path {
case "POST /v1/catalog/deployments/":
require.NoError(t, json.NewDecoder(request.Body).Decode(&posted))
status = http.StatusCreated
case "GET /v1/catalog/deployments/vm-id/":
default:
t.Fatalf("unexpected request: %s %s", request.Method, request.URL.Path)
}
response := openapi.Deployment{
Id: "vm-id", SshUser: "launchpad-login", SshPort: 22, State: openapi.DeploymentStateWaiting,
Cluster: &openapi.ClusterPipelineCluster{Cluster: &openapi.Cluster{
Deployment: openapi.ClusterDeployment{String: collections.Ptr("vm-id")},
}},
Tags: map[string]string{"RefID": args.RefID},
}
encoded, err := json.Marshal(response)
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, err := NewLaunchpadClient(*NewLaunchpadCredential("credential", "test-key", "https://launchpad.invalid"))
require.NoError(t, err)
client.client = openapi.NewAPIClient(config)
instance, err := client.CreateInstance(t.Context(), args)
if test.invalidCA {
require.Error(t, err)
return
}
require.NoError(t, err)
require.Equal(t, test.certificate, instance.SSHCertificateBootstrap)
require.JSONEq(t, `"env-launchpad"`, string(posted["request_id"]))
require.JSONEq(t, `["192.0.2.1"]`, string(posted["ip_allowlist"]))
var installedKey string
require.NoError(t, json.Unmarshal(posted["public_key"], &installedKey))
if test.certificate {
require.Equal(t, caKey, installedKey)
var script string
require.NoError(t, json.Unmarshal(posted["startup_script"], &script))
want, err := sshbootstrap.InstallForKeyOwners(*args.SSHCertificateAuthority)
require.NoError(t, err)
require.Equal(t, want, script, "send the installer as plain text without changing its quoting")
} else {
require.Equal(t, args.PublicKey, installedKey)
require.NotContains(t, posted, "startup_script")
}
fetched, err := client.GetInstance(t.Context(), instance.CloudID)
require.NoError(t, err)
require.False(t, fetched.SSHCertificateBootstrap, "only CreateInstance reports bootstrap selection")
})
}
}
Loading