diff --git a/plugins/releases.yaml b/plugins/releases.yaml index 692569a6e30..961e0903fe5 100644 --- a/plugins/releases.yaml +++ b/plugins/releases.yaml @@ -12,3 +12,12 @@ packages: - pkg/plugin/oci/** - sdk/** - proto/** + ssh: + path: plugins/ssh + repository: oci://ghcr.io/cloudposse/atmos/plugins/ssh + inputs: + - .github/workflows/plugin-packages.yaml + - pkg/plugin/build/** + - pkg/plugin/oci/** + - sdk/** + - proto/** diff --git a/plugins/ssh/.gitignore b/plugins/ssh/.gitignore new file mode 100644 index 00000000000..ae3c1726048 --- /dev/null +++ b/plugins/ssh/.gitignore @@ -0,0 +1 @@ +/bin/ diff --git a/plugins/ssh/README.md b/plugins/ssh/README.md new file mode 100644 index 00000000000..917adb12619 --- /dev/null +++ b/plugins/ssh/README.md @@ -0,0 +1,143 @@ +# ssh + +Make an SSH key an Atmos identity. The key is generated inside the machine's security hardware where there is any, cannot be exported, works while the screen is locked (unless you say otherwise), edits no global configuration, and puts no secret in the environment. The package exports the `ssh/self` provider, the `ssh/key` identity, and the `ssh` command, and is published at: + +```text +oci://ghcr.io/cloudposse/atmos/plugins/ssh +``` + +SSH is how Ansible reaches hosts, how Git signs commits, and how private Git sources are fetched. With this package each of them uses a key that Atmos knows by name: + +```shell +atmos auth login --identity ops # once per machine: creates and enrolls the key +atmos auth exec --identity ops -- git commit -m "..." # the commit is signed with it +atmos auth exec --identity ops -- claude # a coding agent's own git and ssh use it +``` + +## Configuration + +A key proves nothing on its own. It becomes an identity when a party others already trust says "this key speaks for X". That party is the identity's `authority`, and the identity's upstream (`via`) supplies the credential the authority needs. + +```yaml +plugins: + packages: + ssh: + source: oci://ghcr.io/cloudposse/atmos/plugins/ssh + version: "^0.1.0" + secrets: + source: oci://ghcr.io/cloudposse/atmos/plugins/auth-secrets + version: "^1.1.0" +aliases: + ssh: plugin run ssh -- +stores: + keychain: + type: keychain + secret: true +auth: + providers: + github-token: + kind: secrets/store # a GitHub token with the key-management scopes + spec: + credentials: + token: {store: keychain, path: github/ssh-keys} + identities: + ops: + kind: ssh/key + via: {provider: github-token} + spec: + authority: github # who vouches for the key; `self` when nobody does + store: secure-enclave # secure-enclave | file + allow: [signing, authentication] + require: unlocked # omit to let the key be used while the screen is locked + user: deploy # SSH login name on the remote side, optional +git: + repositories: + infra: + auth: {identity: ops} + commit: {signing: always} +``` + +Without a token, use the `ssh/self` provider and `authority: self`. You then give the public key to whoever needs it (`key show --format github` prints what GitHub wants): + +```yaml +auth: + providers: + local: + kind: ssh/self + identities: + ops: + kind: ssh/key + via: {provider: local} + spec: + store: secure-enclave + allow: [signing] +``` + +| Field | Meaning | +|---|---| +| `authority` | `self` (default) or `github`. The token is read from the upstream credential's `token` entry. | +| `store` | `secure-enclave` (macOS hardware) or `file` (an ordinary key file, not hardware-protected). Required. | +| `allow` | `signing`, `authentication`, or both. Limits the identity's agent socket and decides what is enrolled. Required. | +| `require` | One term or a list. The only term is `unlocked`: the key is refused while the screen is locked. The key store enforces it, it is fixed when the key is created, and a store that cannot enforce it rejects it. | +| `user` | The SSH login name on the remote side. Set as `ANSIBLE_REMOTE_USER` when `authentication` is allowed. | +| `key` | The key's name in the store. Defaults to the identity's name. | +| `rewrite_https` | Hosts whose HTTPS Git URLs are rewritten to SSH. | +| `root` | The plugin's data directory, when it is not the default. The plugin cannot see Atmos's environment, so a relocated Atmos data directory must be named here, and in the command's `config` (below). | + +The configuration is shared; the key is not. Each person's login creates and enrolls that machine's own key. + +## What the identity sets + +| Variable | When | +|---|---| +| `SSH_AUTH_SOCK` | Always. The identity's own agent socket. | +| `GIT_CONFIG_GLOBAL` | `signing` is allowed, or `rewrite_https` is set. A generated file that first includes your own `~/.gitconfig` and `~/.config/git/config`, then sets SSH signing with the identity's key and the URL rewrites. | +| `ANSIBLE_REMOTE_USER` | `user` is set and `authentication` is allowed. | + +Every use of the identity authenticates again, so the work is idempotent. When a receipt on disk already matches the key and the `allow` list, there is no network call and no interaction. + +## The ssh command + +Run `atmos plugin run ssh -- `, or `atmos ssh ` with the alias above. + +```text +key list +key show [--format authorized-key|allowed-signers|github|json] +key status [] +key delete --yes +agent start | stop | status | log [--lines N] +test [--soak ] [--interval ] +help +``` + +| I want to | Run | +|---|---| +| Set up this machine | `atmos auth login --identity ops` | +| See what this machine has enrolled, and the last error | `atmos ssh key status` | +| Also push over SSH | Add `authentication` to `allow`, then `atmos auth login --identity ops` | +| Rotate this machine's key | `atmos ssh key delete ops --yes`, then `atmos auth login --identity ops` | +| Retire this machine | `atmos ssh key delete ops --yes`, then `atmos auth logout ops` | +| Check that signing works with the screen locked | `atmos ssh test ops --soak 10m --interval 30s`, then lock the screen | + +Commands never contact an authority and never prompt: they have no credentials and no terminal. Every change at an authority goes through `atmos auth login` or `atmos auth logout`, and destructive commands need `--yes`. Pass `--root ` to any command, or set `root` under `plugins.packages..config`, when the data directory is not the default. `key show` and `key delete` accept `--store ` to pick a store when a key name exists in more than one. + +`test` signs a Git payload through the identity's socket and verifies it. With `--soak` it repeats every `--interval` for that long and prints one timestamped line per attempt: `ok`, `refused`, `locked` (the key store refused because the screen is locked), or `unreachable`. It exits non-zero if any attempt did not succeed. + +## Security model + +- The key cannot leave the machine. A stolen disk, backup, or copied key blob is useless elsewhere. After a reboot nothing signs until the first login. +- The agent runs as a per-user LaunchAgent (macOS) or systemd user unit (Linux), never as a child of Atmos, and rejects connections from other users. Each identity has its own socket, which signs only what `allow` permits: a Git signature on a signing-only socket, an SSH login on an authentication-only socket. +- `require: unlocked` is enforced by the key store, so it holds even against other processes running as you. Without it, the key is usable while the screen is locked, which is what unattended work needs. +- Other processes running as the same user can read the key blob and sign directly, bypassing the socket's `allow` limits. Never mount the key directory into a sandbox. +- The GitHub token should carry only key-management scopes (`write:ssh_signing_key`, plus `write:public_key` for `authentication`). The identity keeps a copy in its private state so logout can revoke enrollments; the host removes it at logout. An enrollment is revoked once its key is gone, so logging out alone never strips a working machine's key. + +## Current limits + +- No device login. Enrollment needs a token from a secret store (`authority: github`) or you add the public key yourself (`authority: self`). The `github/user` provider waits on core. +- Atmos discards plugin error text during authentication, so a failed login is a generic failure. The reason is in `atmos ssh key status`. +- Hardware keys are macOS Secure Enclave only. The `file` store works everywhere and is not hardware-protected. +- The agent daemon does not run on Windows yet. There the package installs and the `file` store can be listed, but an `ssh/key` identity fails with a "not supported" error. +- Atmos components do not all receive an identity's environment yet; Ansible needs a core change. +- Different projects can pin different plugin versions while sharing one daemon and key directory. `agent status` reports a daemon whose version differs from the installed one, and `agent start` replaces it. + +See [release infrastructure](../README.md) for independent versions, public package setup, and the six-platform release matrix. diff --git a/plugins/ssh/agent/atomic.go b/plugins/ssh/agent/atomic.go new file mode 100644 index 00000000000..3f40c1f144b --- /dev/null +++ b/plugins/ssh/agent/atomic.go @@ -0,0 +1,52 @@ +package agent + +import ( + "fmt" + "os" + "path/filepath" +) + +// writeFileAtomic writes data to path through a temporary file in the same directory, so a reader +// never sees a partial file. The file ends up with the given mode. +func writeFileAtomic(path string, data []byte, mode os.FileMode) error { + dir := filepath.Dir(path) + if err := os.MkdirAll(dir, 0o700); err != nil { + return fmt.Errorf("create directory %s: %w", dir, err) + } + tmp, err := os.CreateTemp(dir, "."+filepath.Base(path)+".*") + if err != nil { + return fmt.Errorf("create temporary file: %w", err) + } + tmpName := tmp.Name() + cleanup := func() { _ = os.Remove(tmpName) } + + if err := tmp.Chmod(mode); err != nil && !isWindowsChmod(err) { + _ = tmp.Close() + cleanup() + return fmt.Errorf("set mode on %s: %w", tmpName, err) + } + if _, err := tmp.Write(data); err != nil { + _ = tmp.Close() + cleanup() + return fmt.Errorf("write %s: %w", tmpName, err) + } + if err := tmp.Sync(); err != nil { + _ = tmp.Close() + cleanup() + return fmt.Errorf("sync %s: %w", tmpName, err) + } + if err := tmp.Close(); err != nil { + cleanup() + return fmt.Errorf("close %s: %w", tmpName, err) + } + if err := os.Rename(tmpName, path); err != nil { + cleanup() + return fmt.Errorf("replace %s: %w", path, err) + } + return nil +} + +// isWindowsChmod reports whether err is the harmless "not supported" result of Chmod on Windows. +func isWindowsChmod(err error) bool { + return err != nil && os.PathSeparator == '\\' +} diff --git a/plugins/ssh/agent/audit.go b/plugins/ssh/agent/audit.go new file mode 100644 index 00000000000..f415c0bb876 --- /dev/null +++ b/plugins/ssh/agent/audit.go @@ -0,0 +1,93 @@ +package agent + +import ( + "encoding/json" + "fmt" + "os" + "path/filepath" + "sync" + "time" +) + +// Operation names recorded in the audit log. +const ( + OpList = "list" + OpSign = "sign" + OpConnect = "connect" +) + +// Result values recorded in the audit log. +const ( + ResultOK = "ok" + ResultRefused = "refused" + ResultError = "error" +) + +const auditFileMode os.FileMode = 0o600 + +// AuditEntry is one line of the audit log. It never holds payload bytes or signatures. +type AuditEntry struct { + Time time.Time `json:"time"` + Identity string `json:"identity"` + Operation string `json:"operation"` + Classification Kind `json:"classification,omitempty"` + Namespace string `json:"namespace,omitempty"` + User string `json:"user,omitempty"` + Service string `json:"service,omitempty"` + Fingerprint string `json:"fingerprint,omitempty"` + Result string `json:"result"` + // Reason says why a request was refused or failed, in words that carry no payload. + Reason string `json:"reason,omitempty"` + // ScreenLocked is true when the key store refused because the screen is locked. + ScreenLocked bool `json:"screen_locked,omitempty"` +} + +// AuditLog appends JSON lines to a file. A nil *AuditLog discards everything. +type AuditLog struct { + mu sync.Mutex + file *os.File + now func() time.Time +} + +// OpenAuditLog opens path for appending, creating it with mode 0600. +func OpenAuditLog(path string) (*AuditLog, error) { + if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil { + return nil, fmt.Errorf("create audit log directory: %w", err) + } + f, err := os.OpenFile(path, os.O_CREATE|os.O_WRONLY|os.O_APPEND, auditFileMode) + if err != nil { + return nil, fmt.Errorf("open audit log: %w", err) + } + return &AuditLog{file: f, now: func() time.Time { return time.Now().UTC() }}, nil +} + +// Record writes one entry. A zero Time is filled in. Write failures are returned so the daemon can +// log them, but they never block a request. +func (l *AuditLog) Record(e AuditEntry) error { + if l == nil { + return nil + } + l.mu.Lock() + defer l.mu.Unlock() + if e.Time.IsZero() { + e.Time = l.now() + } + line, err := json.Marshal(e) + if err != nil { + return fmt.Errorf("encode audit entry: %w", err) + } + if _, err := l.file.Write(append(line, '\n')); err != nil { + return fmt.Errorf("write audit entry: %w", err) + } + return nil +} + +// Close closes the log file. +func (l *AuditLog) Close() error { + if l == nil { + return nil + } + l.mu.Lock() + defer l.mu.Unlock() + return l.file.Close() +} diff --git a/plugins/ssh/agent/classify.go b/plugins/ssh/agent/classify.go new file mode 100644 index 00000000000..cc19529db82 --- /dev/null +++ b/plugins/ssh/agent/classify.go @@ -0,0 +1,129 @@ +package agent + +import ( + "bytes" + + "golang.org/x/crypto/ssh" +) + +// Kind classifies a sign request by what its payload is. +type Kind string + +const ( + // KindGitSignature is an SSHSIG blob (OpenSSH PROTOCOL.sshsig). + KindGitSignature Kind = "git-signature" + // KindSSHAuthentication is an SSH userauth request (RFC 4252 section 7). + KindSSHAuthentication Kind = "ssh-authentication" + // KindOther is anything else. + KindOther Kind = "other" +) + +// sshsigMagic starts every SSHSIG signed-data blob. +const sshsigMagic = "SSHSIG" + +// gitNamespace is the SSHSIG namespace Git signs under. +const gitNamespace = "git" + +// msgUserauthRequest is SSH_MSG_USERAUTH_REQUEST. +const msgUserauthRequest = 50 + +// Request is what Classify learned about a sign request payload. It holds no payload bytes. +type Request struct { + // Kind is the classification. + Kind Kind + // Namespace is the SSHSIG namespace, for KindGitSignature. + Namespace string + // User and Service are the userauth user name and service, for KindSSHAuthentication. + User string + Service string + // PublicKey is the key the userauth request names, for KindSSHAuthentication. + PublicKey ssh.PublicKey +} + +// Classify decides what a sign request payload is. A payload that does not parse completely as one +// of the two known formats is KindOther. +func Classify(data []byte) Request { + if bytes.HasPrefix(data, []byte(sshsigMagic)) { + if ns, ok := parseSSHSIG(data[len(sshsigMagic):]); ok { + return Request{Kind: KindGitSignature, Namespace: ns} + } + return Request{Kind: KindOther} + } + if user, service, pub, ok := parseUserauth(data); ok { + return Request{Kind: KindSSHAuthentication, User: user, Service: service, PublicKey: pub} + } + return Request{Kind: KindOther} +} + +// reader consumes SSH wire-format fields and remembers the first failure. +type reader struct { + b []byte + ok bool +} + +func newReader(b []byte) *reader { return &reader{b: b, ok: true} } + +func (r *reader) str() []byte { + if !r.ok || len(r.b) < 4 { + r.ok = false + return nil + } + n := uint64(r.b[0])<<24 | uint64(r.b[1])<<16 | uint64(r.b[2])<<8 | uint64(r.b[3]) + if n > uint64(len(r.b)-4) { + r.ok = false + return nil + } + out := r.b[4 : 4+n] + r.b = r.b[4+n:] + return out +} + +func (r *reader) byte() byte { + if !r.ok || len(r.b) < 1 { + r.ok = false + return 0 + } + v := r.b[0] + r.b = r.b[1:] + return v +} + +func (r *reader) done() bool { return r.ok && len(r.b) == 0 } + +// parseSSHSIG parses what follows the magic: namespace, reserved, hash_algorithm, H(message). The +// blob must end there. +func parseSSHSIG(rest []byte) (namespace string, ok bool) { + r := newReader(rest) + ns := r.str() + _ = r.str() // reserved. + hashAlg := r.str() + digest := r.str() + if !r.done() || len(hashAlg) == 0 || len(digest) == 0 { + return "", false + } + return string(ns), true +} + +// parseUserauth parses a userauth request signature payload (RFC 4252 section 7): +// string session_id, byte 50, string user, string service, string "publickey", boolean TRUE, +// string algorithm, string public_key. The payload must end there. +func parseUserauth(data []byte) (user, service string, pub ssh.PublicKey, ok bool) { + r := newReader(data) + session := r.str() + msg := r.byte() + u := r.str() + svc := r.str() + method := r.str() + hasSig := r.byte() + alg := r.str() + blob := r.str() + if !r.done() || len(session) == 0 || msg != msgUserauthRequest || + string(method) != "publickey" || hasSig != 1 || len(alg) == 0 { + return "", "", nil, false + } + key, err := ssh.ParsePublicKey(blob) + if err != nil { + return "", "", nil, false + } + return string(u), string(svc), key, true +} diff --git a/plugins/ssh/agent/classify_test.go b/plugins/ssh/agent/classify_test.go new file mode 100644 index 00000000000..c11d1214963 --- /dev/null +++ b/plugins/ssh/agent/classify_test.go @@ -0,0 +1,130 @@ +package agent + +import ( + "crypto/ed25519" + "crypto/rand" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "golang.org/x/crypto/ssh" +) + +func wireString(b []byte, s string) []byte { + n := len(s) + b = append(b, byte(n>>24), byte(n>>16), byte(n>>8), byte(n)) + return append(b, s...) +} + +func sshsigBlob(namespace string) []byte { + b := []byte("SSHSIG") + b = wireString(b, namespace) + b = wireString(b, "") + b = wireString(b, "sha512") + return wireString(b, "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef") +} + +func userauthBlob(session, user, service string, pub ssh.PublicKey) []byte { + b := wireString(nil, session) + b = append(b, 50) + b = wireString(b, user) + b = wireString(b, service) + b = wireString(b, "publickey") + b = append(b, 1) + b = wireString(b, pub.Type()) + return wireString(b, string(pub.Marshal())) +} + +func newPub(t *testing.T) ssh.PublicKey { + t.Helper() + pub, _, err := ed25519.GenerateKey(rand.Reader) + require.NoError(t, err) + sshPub, err := ssh.NewPublicKey(pub) + require.NoError(t, err) + return sshPub +} + +func TestClassify(t *testing.T) { + pub := newPub(t) + auth := userauthBlob("session-id-session-id-session-id", "git", "ssh-connection", pub) + + tests := []struct { + name string + data []byte + want Request + }{ + {"git signature", sshsigBlob("git"), Request{Kind: KindGitSignature, Namespace: "git"}}, + {"other namespace", sshsigBlob("file"), Request{Kind: KindGitSignature, Namespace: "file"}}, + {"empty namespace", sshsigBlob(""), Request{Kind: KindGitSignature, Namespace: ""}}, + {"truncated sshsig", sshsigBlob("git")[:20], Request{Kind: KindOther}}, + {"sshsig with trailing bytes", append(sshsigBlob("git"), 0), Request{Kind: KindOther}}, + {"magic only", []byte("SSHSIG"), Request{Kind: KindOther}}, + {"empty", nil, Request{Kind: KindOther}}, + {"garbage", []byte("hello, world, this is not a signature request"), Request{Kind: KindOther}}, + {"userauth", auth, Request{Kind: KindSSHAuthentication, User: "git", Service: "ssh-connection", PublicKey: pub}}, + {"userauth with trailing bytes", append(append([]byte{}, auth...), 0), Request{Kind: KindOther}}, + {"userauth truncated", auth[:len(auth)-3], Request{Kind: KindOther}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + got := Classify(tt.data) + assert.Equal(t, tt.want.Kind, got.Kind) + assert.Equal(t, tt.want.Namespace, got.Namespace) + assert.Equal(t, tt.want.User, got.User) + assert.Equal(t, tt.want.Service, got.Service) + if tt.want.PublicKey != nil { + require.NotNil(t, got.PublicKey) + assert.Equal(t, tt.want.PublicKey.Marshal(), got.PublicKey.Marshal()) + } + }) + } +} + +func TestClassifyUserauthRequiresExactShape(t *testing.T) { + pub := newPub(t) + + t.Run("wrong message number", func(t *testing.T) { + b := wireString(nil, "sessionsessionsession") + b = append(b, 51) + b = wireString(b, "git") + b = wireString(b, "ssh-connection") + b = wireString(b, "publickey") + b = append(b, 1) + b = wireString(b, pub.Type()) + b = wireString(b, string(pub.Marshal())) + assert.Equal(t, KindOther, Classify(b).Kind) + }) + t.Run("wrong method", func(t *testing.T) { + b := wireString(nil, "sessionsessionsession") + b = append(b, 50) + b = wireString(b, "git") + b = wireString(b, "ssh-connection") + b = wireString(b, "password") + b = append(b, 1) + b = wireString(b, pub.Type()) + b = wireString(b, string(pub.Marshal())) + assert.Equal(t, KindOther, Classify(b).Kind) + }) + t.Run("not a signature query", func(t *testing.T) { + b := wireString(nil, "sessionsessionsession") + b = append(b, 50) + b = wireString(b, "git") + b = wireString(b, "ssh-connection") + b = wireString(b, "publickey") + b = append(b, 0) + b = wireString(b, pub.Type()) + b = wireString(b, string(pub.Marshal())) + assert.Equal(t, KindOther, Classify(b).Kind) + }) + t.Run("unparseable key blob", func(t *testing.T) { + b := wireString(nil, "sessionsessionsession") + b = append(b, 50) + b = wireString(b, "git") + b = wireString(b, "ssh-connection") + b = wireString(b, "publickey") + b = append(b, 1) + b = wireString(b, "ssh-ed25519") + b = wireString(b, "not a key") + assert.Equal(t, KindOther, Classify(b).Kind) + }) +} diff --git a/plugins/ssh/agent/client.go b/plugins/ssh/agent/client.go new file mode 100644 index 00000000000..c60e68c70f1 --- /dev/null +++ b/plugins/ssh/agent/client.go @@ -0,0 +1,48 @@ +package agent + +import ( + "context" + "errors" + "fmt" + "net" + "time" + + "golang.org/x/crypto/ssh" + "golang.org/x/crypto/ssh/agent" +) + +// ErrUnexpectedKeys means a socket answered but did not list exactly the expected key. +var ErrUnexpectedKeys = errors.New("socket does not list the expected key") + +// dialTimeout bounds how long CheckSocket waits when the context has no deadline. +const dialTimeout = 5 * time.Second + +// CheckSocket verifies that an identity's socket is alive and lists exactly the key want. When +// want is nil it only checks that the socket answers a list request. +func CheckSocket(ctx context.Context, socketPath string, want ssh.PublicKey) error { + if _, ok := ctx.Deadline(); !ok { + var cancel context.CancelFunc + ctx, cancel = context.WithTimeout(ctx, dialTimeout) + defer cancel() + } + var d net.Dialer + conn, err := d.DialContext(ctx, "unix", socketPath) + if err != nil { + return fmt.Errorf("connect to agent socket %s: %w", socketPath, err) + } + defer conn.Close() + if dl, ok := ctx.Deadline(); ok { + _ = conn.SetDeadline(dl) + } + keys, err := agent.NewClient(conn).List() + if err != nil { + return fmt.Errorf("list keys on %s: %w", socketPath, err) + } + if want == nil { + return nil + } + if len(keys) != 1 || string(keys[0].Blob) != string(want.Marshal()) { + return fmt.Errorf("%w: %s lists %d key(s)", ErrUnexpectedKeys, socketPath, len(keys)) + } + return nil +} diff --git a/plugins/ssh/agent/config.go b/plugins/ssh/agent/config.go new file mode 100644 index 00000000000..65467cfe568 --- /dev/null +++ b/plugins/ssh/agent/config.go @@ -0,0 +1,216 @@ +package agent + +import ( + "bytes" + "encoding/json" + "errors" + "fmt" + "os" + "sort" + + "github.com/cloudposse/atmos/plugins/ssh/paths" +) + +// ConfigVersion is the only configuration file version this package reads and writes. +const ConfigVersion = 1 + +// configFileMode is the mode of the configuration file. +const configFileMode os.FileMode = 0o600 + +// Allow is one thing an identity's socket may be used for. +type Allow string + +const ( + // AllowSigning permits Git (SSHSIG, namespace "git") signatures. + AllowSigning Allow = "signing" + // AllowAuthentication permits SSH login (userauth) signatures. + AllowAuthentication Allow = "authentication" +) + +// Sentinel errors. Wrap them with fmt.Errorf("%w ...") and test with errors.Is. +var ( + // ErrInvalidConfig means the agent configuration is malformed or inconsistent. + ErrInvalidConfig = errors.New("invalid agent configuration") + // ErrConfigNotFound means the agent configuration file does not exist. + ErrConfigNotFound = errors.New("agent configuration not found") +) + +// Identity is one entry in the agent configuration: a key, where it lives, and what it may do. +type Identity struct { + // Name is the identity name. It also names the identity's socket. + Name string `json:"name"` + // Store is the key store kind that holds the key. + Store string `json:"store"` + // Key is the key's name within the store. + Key string `json:"key"` + // Allow lists what the identity's socket may sign. + Allow []Allow `json:"allow"` +} + +// Allows reports whether the identity permits a. +func (i Identity) Allows(a Allow) bool { + for _, have := range i.Allow { + if have == a { + return true + } + } + return false +} + +// equal reports whether two identities have the same settings. +func (i Identity) equal(o Identity) bool { + if i.Name != o.Name || i.Store != o.Store || i.Key != o.Key || len(i.Allow) != len(o.Allow) { + return false + } + for n := range i.Allow { + if i.Allow[n] != o.Allow[n] { + return false + } + } + return true +} + +// Config is the agent configuration file. +type Config struct { + // Version is the file format version. + Version int `json:"version"` + // Identities are the identities the agent serves, one socket each. + Identities []Identity `json:"identities"` +} + +// Validate checks the configuration and reports the first problem found. +func (c *Config) Validate() error { + if c.Version != ConfigVersion { + return fmt.Errorf("%w: unsupported version %d (want %d)", ErrInvalidConfig, c.Version, ConfigVersion) + } + seen := map[string]bool{} + for n := range c.Identities { + id := c.Identities[n] + if err := id.Validate(); err != nil { + return err + } + if seen[id.Name] { + return fmt.Errorf("%w: duplicate identity %q", ErrInvalidConfig, id.Name) + } + seen[id.Name] = true + } + return nil +} + +// Validate checks one identity entry. +func (i Identity) Validate() error { + if err := paths.ValidateIdentity(i.Name); err != nil { + return fmt.Errorf("%w: %w", ErrInvalidConfig, err) + } + if i.Store == "" { + return fmt.Errorf("%w: identity %q has no store", ErrInvalidConfig, i.Name) + } + if i.Key == "" { + return fmt.Errorf("%w: identity %q has no key", ErrInvalidConfig, i.Name) + } + if len(i.Allow) == 0 { + return fmt.Errorf("%w: identity %q allows nothing", ErrInvalidConfig, i.Name) + } + seen := map[Allow]bool{} + for _, a := range i.Allow { + if a != AllowSigning && a != AllowAuthentication { + return fmt.Errorf("%w: identity %q has unknown allow value %q", ErrInvalidConfig, i.Name, a) + } + if seen[a] { + return fmt.Errorf("%w: identity %q lists %q twice", ErrInvalidConfig, i.Name, a) + } + seen[a] = true + } + return nil +} + +// find returns the index of the identity called name, or -1. +func (c *Config) find(name string) int { + for n := range c.Identities { + if c.Identities[n].Name == name { + return n + } + } + return -1 +} + +// LoadConfig reads and validates the configuration file. A missing file is ErrConfigNotFound. +func LoadConfig(path string) (*Config, error) { + data, err := os.ReadFile(path) + if err != nil { + if errors.Is(err, os.ErrNotExist) { + return nil, fmt.Errorf("%w: %s", ErrConfigNotFound, path) + } + return nil, fmt.Errorf("read agent configuration: %w", err) + } + var cfg Config + dec := json.NewDecoder(bytes.NewReader(data)) + dec.DisallowUnknownFields() + if err := dec.Decode(&cfg); err != nil { + return nil, fmt.Errorf("%w: %s: %w", ErrInvalidConfig, path, err) + } + if err := cfg.Validate(); err != nil { + return nil, fmt.Errorf("%s: %w", path, err) + } + return &cfg, nil +} + +// loadOrEmpty is LoadConfig, but a missing file yields an empty configuration. +func loadOrEmpty(path string) (*Config, error) { + cfg, err := LoadConfig(path) + if errors.Is(err, ErrConfigNotFound) { + return &Config{Version: ConfigVersion}, nil + } + return cfg, err +} + +// SaveConfig validates cfg and writes it atomically with mode 0600. Identities are written sorted +// by name so the file is stable. +func SaveConfig(path string, cfg *Config) error { + out := &Config{Version: cfg.Version, Identities: append([]Identity(nil), cfg.Identities...)} + if err := out.Validate(); err != nil { + return err + } + sort.Slice(out.Identities, func(a, b int) bool { return out.Identities[a].Name < out.Identities[b].Name }) + if out.Identities == nil { + out.Identities = []Identity{} + } + data, err := json.MarshalIndent(out, "", " ") + if err != nil { + return fmt.Errorf("encode agent configuration: %w", err) + } + return writeFileAtomic(path, append(data, '\n'), configFileMode) +} + +// UpsertIdentity adds id to the configuration file, or replaces the entry with the same name. The +// file is created if it does not exist. +func UpsertIdentity(path string, id Identity) error { + if err := id.Validate(); err != nil { + return err + } + cfg, err := loadOrEmpty(path) + if err != nil { + return err + } + if n := cfg.find(id.Name); n >= 0 { + cfg.Identities[n] = id + } else { + cfg.Identities = append(cfg.Identities, id) + } + return SaveConfig(path, cfg) +} + +// RemoveIdentity deletes the entry called name. It reports whether an entry was removed; removing +// a name that is not there, or from a file that does not exist, is not an error. +func RemoveIdentity(path, name string) (bool, error) { + cfg, err := loadOrEmpty(path) + if err != nil { + return false, err + } + n := cfg.find(name) + if n < 0 { + return false, nil + } + cfg.Identities = append(cfg.Identities[:n], cfg.Identities[n+1:]...) + return true, SaveConfig(path, cfg) +} diff --git a/plugins/ssh/agent/config_test.go b/plugins/ssh/agent/config_test.go new file mode 100644 index 00000000000..b6cdef2e26b --- /dev/null +++ b/plugins/ssh/agent/config_test.go @@ -0,0 +1,141 @@ +package agent + +import ( + "os" + "path/filepath" + "runtime" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func ident(name string, allow ...Allow) Identity { + return Identity{Name: name, Store: "file", Key: name, Allow: allow} +} + +func TestIdentityValidate(t *testing.T) { + tests := []struct { + name string + id Identity + wantErr bool + }{ + {"signing", ident("ops", AllowSigning), false}, + {"both", ident("ops", AllowSigning, AllowAuthentication), false}, + {"empty name", ident("", AllowSigning), true}, + {"unsafe name", ident("../x", AllowSigning), true}, + {"no store", Identity{Name: "ops", Key: "ops", Allow: []Allow{AllowSigning}}, true}, + {"no key", Identity{Name: "ops", Store: "file", Allow: []Allow{AllowSigning}}, true}, + {"no allow", ident("ops"), true}, + {"unknown allow", ident("ops", Allow("root")), true}, + {"duplicate allow", ident("ops", AllowSigning, AllowSigning), true}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + err := tt.id.Validate() + if tt.wantErr { + require.ErrorIs(t, err, ErrInvalidConfig) + return + } + require.NoError(t, err) + }) + } +} + +func TestConfigValidate(t *testing.T) { + require.ErrorIs(t, (&Config{Version: 2}).Validate(), ErrInvalidConfig) + dup := &Config{Version: 1, Identities: []Identity{ident("a", AllowSigning), ident("a", AllowSigning)}} + require.ErrorIs(t, dup.Validate(), ErrInvalidConfig) + require.NoError(t, (&Config{Version: 1}).Validate()) +} + +func TestLoadConfigMissing(t *testing.T) { + _, err := LoadConfig(filepath.Join(t.TempDir(), "agent.json")) + require.ErrorIs(t, err, ErrConfigNotFound) +} + +func TestLoadConfigRejectsBadFiles(t *testing.T) { + tests := map[string]string{ + "not json": `{`, + "unknown field": `{"version":1,"identities":[],"extra":true}`, + "wrong version": `{"version":9,"identities":[]}`, + "bad identity": `{"version":1,"identities":[{"name":"a","store":"file","key":"a","allow":["root"]}]}`, + } + for name, body := range tests { + t.Run(name, func(t *testing.T) { + path := filepath.Join(t.TempDir(), "agent.json") + require.NoError(t, os.WriteFile(path, []byte(body), 0o600)) + _, err := LoadConfig(path) + require.ErrorIs(t, err, ErrInvalidConfig) + }) + } +} + +func TestUpsertAndRemove(t *testing.T) { + path := filepath.Join(t.TempDir(), "sub", "agent.json") + + require.NoError(t, UpsertIdentity(path, ident("zed", AllowSigning))) + require.NoError(t, UpsertIdentity(path, ident("alpha", AllowAuthentication))) + require.NoError(t, UpsertIdentity(path, ident("zed", AllowSigning, AllowAuthentication))) + + cfg, err := LoadConfig(path) + require.NoError(t, err) + require.Len(t, cfg.Identities, 2) + assert.Equal(t, "alpha", cfg.Identities[0].Name, "sorted by name") + assert.Equal(t, []Allow{AllowAuthentication}, cfg.Identities[0].Allow) + assert.Equal(t, "zed", cfg.Identities[1].Name) + assert.Equal(t, []Allow{AllowSigning, AllowAuthentication}, cfg.Identities[1].Allow, "upsert replaced the entry") + + removed, err := RemoveIdentity(path, "alpha") + require.NoError(t, err) + assert.True(t, removed) + removed, err = RemoveIdentity(path, "alpha") + require.NoError(t, err) + assert.False(t, removed) + + cfg, err = LoadConfig(path) + require.NoError(t, err) + require.Len(t, cfg.Identities, 1) + assert.Equal(t, "zed", cfg.Identities[0].Name) +} + +func TestRemoveFromMissingFile(t *testing.T) { + removed, err := RemoveIdentity(filepath.Join(t.TempDir(), "agent.json"), "a") + require.NoError(t, err) + assert.False(t, removed) +} + +func TestUpsertRejectsInvalidAndKeepsFile(t *testing.T) { + path := filepath.Join(t.TempDir(), "agent.json") + require.NoError(t, UpsertIdentity(path, ident("a", AllowSigning))) + before, err := os.ReadFile(path) + require.NoError(t, err) + + require.ErrorIs(t, UpsertIdentity(path, ident("b")), ErrInvalidConfig) + + after, err := os.ReadFile(path) + require.NoError(t, err) + assert.Equal(t, before, after) +} + +func TestSaveConfigMode(t *testing.T) { + dir := t.TempDir() + path := filepath.Join(dir, "agent.json") + require.NoError(t, UpsertIdentity(path, ident("a", AllowSigning))) + if runtime.GOOS != "windows" { + info, err := os.Stat(path) + require.NoError(t, err) + assert.Equal(t, os.FileMode(0o600), info.Mode().Perm()) + } + entries, err := os.ReadDir(dir) + require.NoError(t, err) + require.Len(t, entries, 1, "no temporary files left behind") +} + +func TestSaveConfigEmpty(t *testing.T) { + path := filepath.Join(t.TempDir(), "agent.json") + require.NoError(t, SaveConfig(path, &Config{Version: ConfigVersion})) + data, err := os.ReadFile(path) + require.NoError(t, err) + assert.Contains(t, string(data), `"identities": []`) +} diff --git a/plugins/ssh/agent/fakes_unix_test.go b/plugins/ssh/agent/fakes_unix_test.go new file mode 100644 index 00000000000..e5adb76d805 --- /dev/null +++ b/plugins/ssh/agent/fakes_unix_test.go @@ -0,0 +1,96 @@ +//go:build !windows + +package agent + +import ( + "context" + "crypto" + "crypto/ed25519" + "crypto/rand" + "io" + "sync" + "testing" + "time" + + "github.com/stretchr/testify/require" + "golang.org/x/crypto/ssh" + + "github.com/cloudposse/atmos/plugins/ssh/keystore" +) + +// fakeStore serves one in-memory ed25519 key whose Sign fails with signErr. +type fakeStore struct { + priv ed25519.PrivateKey + pub ssh.PublicKey + signErr error + + mu sync.Mutex + opens int + closes int +} + +// newLockedStore returns a store whose key refuses to sign as the Secure Enclave does when the +// screen is locked. +func newLockedStore(t *testing.T) *fakeStore { + t.Helper() + pub, priv, err := ed25519.GenerateKey(rand.Reader) + require.NoError(t, err) + sshPub, err := ssh.NewPublicKey(pub) + require.NoError(t, err) + return &fakeStore{ + priv: priv, pub: sshPub, + signErr: &keystore.OSStatusError{ + Op: "SecKeyCreateSignature", Code: keystore.CodeInteractionNotAllowed, + Domain: "NSOSStatusErrorDomain", Message: "screen is locked", + }, + } +} + +func (s *fakeStore) opened() int { s.mu.Lock(); defer s.mu.Unlock(); return s.opens } +func (s *fakeStore) closedCount() int { s.mu.Lock(); defer s.mu.Unlock(); return s.closes } + +func (s *fakeStore) Kind() string { return "fake" } +func (s *fakeStore) Supports(keystore.Requirement) bool { return false } +func (s *fakeStore) Delete(context.Context, string) error { return keystore.ErrKeyNotFound } +func (s *fakeStore) List(context.Context) ([]keystore.Info, error) { + return nil, nil +} + +func (s *fakeStore) Create(context.Context, string, []keystore.Requirement) (keystore.Key, error) { + return nil, keystore.ErrUnsupportedRequirement +} + +func (s *fakeStore) Load(_ context.Context, name string) (keystore.Key, error) { + s.mu.Lock() + s.opens++ + s.mu.Unlock() + return &fakeKey{store: s, name: name}, nil +} + +type fakeKey struct { + store *fakeStore + name string +} + +var _ keystore.Key = (*fakeKey)(nil) + +func (k *fakeKey) Public() crypto.PublicKey { return k.store.priv.Public() } +func (k *fakeKey) Sign(r io.Reader, msg []byte, o crypto.SignerOpts) ([]byte, error) { + if k.store.signErr != nil { + return nil, k.store.signErr + } + return k.store.priv.Sign(r, msg, o) +} + +func (k *fakeKey) Close() error { + k.store.mu.Lock() + defer k.store.mu.Unlock() + k.store.closes++ + return nil +} +func (k *fakeKey) Name() string { return k.name } +func (k *fakeKey) SSHPublicKey() ssh.PublicKey { return k.store.pub } +func (k *fakeKey) Requirements() []keystore.Requirement { return nil } +func (k *fakeKey) Info() keystore.Info { + return keystore.Info{Name: k.name, Store: "fake", Created: time.Now().UTC(), PublicKey: k.store.pub} +} diff --git a/plugins/ssh/agent/harness_unix_test.go b/plugins/ssh/agent/harness_unix_test.go new file mode 100644 index 00000000000..936b8a73207 --- /dev/null +++ b/plugins/ssh/agent/harness_unix_test.go @@ -0,0 +1,150 @@ +//go:build !windows + +package agent + +import ( + "bufio" + "context" + "encoding/json" + "net" + "os" + "path/filepath" + "runtime" + "sync" + "testing" + "time" + + "github.com/stretchr/testify/require" + "golang.org/x/crypto/ssh" + xagent "golang.org/x/crypto/ssh/agent" + + "github.com/cloudposse/atmos/plugins/ssh/keystore" + "github.com/cloudposse/atmos/plugins/ssh/paths" +) + +// shortDir makes a temporary directory with a path short enough for Unix sockets. +func shortDir(t *testing.T) string { + t.Helper() + base := "" + if runtime.GOOS != "windows" { + if _, err := os.Stat("/tmp"); err == nil { + base = "/tmp" + } + } + dir, err := os.MkdirTemp(base, "ssha") + require.NoError(t, err) + t.Cleanup(func() { _ = os.RemoveAll(dir) }) + return dir +} + +// harness is a running daemon under a temporary root. +type harness struct { + t *testing.T + paths *paths.Paths + opts Options + cancel context.CancelFunc + done chan error + once sync.Once +} + +// newPaths returns Paths under a short temporary directory. +func newPaths(t *testing.T) *paths.Paths { + t.Helper() + p, err := paths.New(filepath.Join(shortDir(t), "ssh")) + require.NoError(t, err) + require.NoError(t, p.EnsureDirs()) + return p +} + +// createFileKey makes a key in the "file" store and returns its public key. +func createFileKey(t *testing.T, p *paths.Paths, name string) ssh.PublicKey { + t.Helper() + store := keystore.NewFileStore(p.StoreDir(keystore.KindFile)) + key, err := store.Create(context.Background(), name, nil) + require.NoError(t, err) + defer key.Close() + return key.SSHPublicKey() +} + +// startDaemon writes the identities to the config file and runs Serve until the test ends. +func startDaemon(t *testing.T, p *paths.Paths, mutate func(*Options), ids ...Identity) *harness { + t.Helper() + for _, id := range ids { + require.NoError(t, UpsertIdentity(p.AgentConfigFile(), id)) + } + ready := make(chan struct{}) + opts := Options{ + Paths: p, Version: "test", PollInterval: 25 * time.Millisecond, + Logf: func(format string, args ...any) { t.Logf("daemon: "+format, args...) }, + Ready: func() { close(ready) }, + } + if mutate != nil { + mutate(&opts) + } + ctx, cancel := context.WithCancel(context.Background()) + h := &harness{t: t, paths: p, opts: opts, cancel: cancel, done: make(chan error, 1)} + go func() { h.done <- Serve(ctx, opts) }() + select { + case <-ready: + case err := <-h.done: + t.Fatalf("Serve returned early: %v", err) + case <-time.After(5 * time.Second): + t.Fatal("Serve did not become ready") + } + t.Cleanup(h.Stop) + return h +} + +// Stop ends the daemon and waits for it. +func (h *harness) Stop() { + h.once.Do(func() { + h.cancel() + select { + case err := <-h.done: + require.NoError(h.t, err) + case <-time.After(10 * time.Second): + h.t.Fatal("Serve did not stop") + } + }) +} + +// socket returns the socket path of an identity. +func (h *harness) socket(name string) string { + h.t.Helper() + s, err := h.paths.SocketPath(name) + require.NoError(h.t, err) + return s +} + +// client connects to an identity's socket. +func (h *harness) client(name string) xagent.ExtendedAgent { + h.t.Helper() + conn, err := net.Dial("unix", h.socket(name)) + require.NoError(h.t, err) + h.t.Cleanup(func() { _ = conn.Close() }) + return xagent.NewClient(conn) +} + +// auditEntries reads the audit log. +func (h *harness) auditEntries() []AuditEntry { + h.t.Helper() + f, err := os.Open(h.paths.AuditLogFile()) + require.NoError(h.t, err) + defer f.Close() + var out []AuditEntry + sc := bufio.NewScanner(f) + for sc.Scan() { + var e AuditEntry + require.NoError(h.t, json.Unmarshal(sc.Bytes(), &e)) + out = append(out, e) + } + return out +} + +// lastAudit returns the newest audit entry. +func (h *harness) lastAudit() AuditEntry { + h.t.Helper() + entries := h.auditEntries() + require.NotEmpty(h.t, entries) + return entries[len(entries)-1] +} diff --git a/plugins/ssh/agent/identity_agent.go b/plugins/ssh/agent/identity_agent.go new file mode 100644 index 00000000000..486dd3416c0 --- /dev/null +++ b/plugins/ssh/agent/identity_agent.go @@ -0,0 +1,189 @@ +package agent + +import ( + "bytes" + "context" + "crypto/rand" + "errors" + "fmt" + + "golang.org/x/crypto/ssh" + "golang.org/x/crypto/ssh/agent" + + "github.com/cloudposse/atmos/plugins/ssh/keystore" +) + +// Sentinel errors for refused requests. The SSH agent protocol carries no detail to the client, so +// these reach the caller only as a generic agent failure; the audit log records the reason. +var ( + // ErrRefused means the agent refuses the request by policy. + ErrRefused = errors.New("request refused") + // ErrUnknownKey means the request names a key this socket does not serve. + ErrUnknownKey = errors.New("key is not served by this socket") +) + +// Reasons recorded in the audit log. +const ( + reasonNotAllowed = "not allowed by the identity's allow list" + reasonUnclassified = "payload is neither a Git signature nor an SSH login" + reasonKeyMismatch = "request names a different public key" + reasonLoginKey = "login request names a different public key" + reasonManagement = "key management is not supported" + reasonScreenLocked = "key store refused: screen is locked" + reasonKeyUnavailable = "key could not be opened" +) + +// identityAgent is the agent.ExtendedAgent behind one identity's socket. It serves exactly one key +// and signs only what the identity's allow list permits. +type identityAgent struct { + id Identity + store keystore.Store + audit *AuditLog + // onAuditError receives audit write failures. + onAuditError func(error) +} + +var _ agent.ExtendedAgent = (*identityAgent)(nil) + +func (a *identityAgent) record(e AuditEntry) { + e.Identity = a.id.Name + if err := a.audit.Record(e); err != nil && a.onAuditError != nil { + a.onAuditError(err) + } +} + +// open loads the identity's key. The caller must Close it. +func (a *identityAgent) open() (keystore.Key, error) { + key, err := a.store.Load(context.Background(), a.id.Key) + if err != nil { + return nil, fmt.Errorf("open key %q in store %q: %w", a.id.Key, a.id.Store, err) + } + return key, nil +} + +// List returns exactly the identity's key. +func (a *identityAgent) List() ([]*agent.Key, error) { + key, err := a.open() + if err != nil { + a.record(AuditEntry{Operation: OpList, Result: ResultError, Reason: reasonKeyUnavailable}) + return nil, err + } + defer key.Close() + pub := key.SSHPublicKey() + a.record(AuditEntry{Operation: OpList, Fingerprint: ssh.FingerprintSHA256(pub), Result: ResultOK}) + return []*agent.Key{{Format: pub.Type(), Blob: pub.Marshal(), Comment: a.id.Name}}, nil +} + +// Sign signs data with the identity's key when the request is permitted. +func (a *identityAgent) Sign(pub ssh.PublicKey, data []byte) (*ssh.Signature, error) { + return a.SignWithFlags(pub, data, 0) +} + +// SignWithFlags is Sign with agent signature flags. +func (a *identityAgent) SignWithFlags(pub ssh.PublicKey, data []byte, flags agent.SignatureFlags) (*ssh.Signature, error) { + req := Classify(data) + entry := AuditEntry{ + Operation: OpSign, Classification: req.Kind, + Namespace: req.Namespace, User: req.User, Service: req.Service, + } + key, err := a.open() + if err != nil { + entry.Result, entry.Reason = ResultError, reasonKeyUnavailable + a.record(entry) + return nil, err + } + defer key.Close() + own := key.SSHPublicKey() + entry.Fingerprint = ssh.FingerprintSHA256(own) + + if reason := a.refusal(req, pub, own); reason != "" { + entry.Result, entry.Reason = ResultRefused, reason + a.record(entry) + return nil, fmt.Errorf("%w: %s", ErrRefused, reason) + } + sig, err := signWith(key, data, flags) + if err != nil { + entry.Result = ResultError + if keystore.IsInteractionNotAllowed(err) { + entry.ScreenLocked, entry.Reason = true, reasonScreenLocked + } + a.record(entry) + return nil, err + } + entry.Result = ResultOK + a.record(entry) + return sig, nil +} + +// refusal returns why the request must be refused, or "" when it is permitted. +func (a *identityAgent) refusal(req Request, asked, own ssh.PublicKey) string { + if !samePublicKey(asked, own) { + return reasonKeyMismatch + } + switch req.Kind { + case KindGitSignature: + if !a.id.Allows(AllowSigning) || req.Namespace != gitNamespace { + return reasonNotAllowed + } + case KindSSHAuthentication: + if !a.id.Allows(AllowAuthentication) { + return reasonNotAllowed + } + if !samePublicKey(req.PublicKey, own) { + return reasonLoginKey + } + default: + return reasonUnclassified + } + return "" +} + +func samePublicKey(a, b ssh.PublicKey) bool { + return a != nil && b != nil && bytes.Equal(a.Marshal(), b.Marshal()) +} + +// signWith signs data with a store key. The key types the stores produce (ed25519 and ECDSA P-256) +// have a single signature algorithm, so the agent flags, which only select RSA variants, do not +// apply. +func signWith(key keystore.Key, data []byte, _ agent.SignatureFlags) (*ssh.Signature, error) { + signer, err := ssh.NewSignerFromSigner(key) + if err != nil { + return nil, fmt.Errorf("create signer: %w", err) + } + sig, err := signer.Sign(rand.Reader, data) + if err != nil { + return nil, fmt.Errorf("sign: %w", err) + } + return sig, nil +} + +func (a *identityAgent) refuseManagement(op string) error { + a.record(AuditEntry{Operation: op, Result: ResultRefused, Reason: reasonManagement}) + return fmt.Errorf("%w: %s", ErrRefused, reasonManagement) +} + +// Add is refused: keys are managed through the plugin, never through the agent socket. +func (a *identityAgent) Add(agent.AddedKey) error { return a.refuseManagement("add") } + +// Remove is refused. +func (a *identityAgent) Remove(ssh.PublicKey) error { return a.refuseManagement("remove") } + +// RemoveAll is refused. +func (a *identityAgent) RemoveAll() error { return a.refuseManagement("remove-all") } + +// Lock is refused. +func (a *identityAgent) Lock([]byte) error { return a.refuseManagement("lock") } + +// Unlock is refused. +func (a *identityAgent) Unlock([]byte) error { return a.refuseManagement("unlock") } + +// Signers is refused: the agent never hands out in-process signers. +func (a *identityAgent) Signers() ([]ssh.Signer, error) { + return nil, a.refuseManagement("signers") +} + +// Extension is refused. +func (a *identityAgent) Extension(string, []byte) ([]byte, error) { + a.record(AuditEntry{Operation: "extension", Result: ResultRefused, Reason: reasonManagement}) + return nil, agent.ErrExtensionUnsupported +} diff --git a/plugins/ssh/agent/options.go b/plugins/ssh/agent/options.go new file mode 100644 index 00000000000..699b4d4ed4d --- /dev/null +++ b/plugins/ssh/agent/options.go @@ -0,0 +1,60 @@ +package agent + +import ( + "errors" + "fmt" + "net" + "time" + + "github.com/cloudposse/atmos/plugins/ssh/keystore" + "github.com/cloudposse/atmos/plugins/ssh/paths" +) + +// ErrUnsupportedPlatform means the agent daemon cannot run on this operating system. Windows needs +// named pipes, which come in a later phase. +var ErrUnsupportedPlatform = errors.New("the SSH agent is not supported on this platform") + +// ErrSocketInUse means another process is already listening on an identity's socket. +var ErrSocketInUse = errors.New("socket is already in use") + +// DefaultPollInterval is how often the daemon checks the configuration file's modification time. +const DefaultPollInterval = 2 * time.Second + +// StoreOpener builds the key store of the given kind that keeps its key material in dir. +type StoreOpener func(kind, dir string) (keystore.Store, error) + +// Options configures Serve. +type Options struct { + // Paths locates the configuration, sockets, keys, audit log and state file. Required. + Paths *paths.Paths + // Version is recorded in the daemon state file. + Version string + // OpenStore builds key stores. It defaults to keystore.New. Tests inject fakes here. + OpenStore StoreOpener + // PollInterval is how often the configuration file is checked for changes. It defaults to + // DefaultPollInterval. + PollInterval time.Duration + // Logf receives the daemon's own diagnostics. It defaults to discarding them. + Logf func(format string, args ...any) + // peer overrides the peer credential lookup. Tests use it to simulate another user. + peer func(*net.UnixConn) (uint32, error) + // Ready, when set, is called once after the first configuration has been applied. + Ready func() +} + +// withDefaults returns o with every unset optional field filled in. +func (o Options) withDefaults() (Options, error) { + if o.Paths == nil { + return o, fmt.Errorf("%w: Options.Paths is required", ErrInvalidConfig) + } + if o.OpenStore == nil { + o.OpenStore = func(kind, dir string) (keystore.Store, error) { return keystore.New(kind, dir) } + } + if o.PollInterval <= 0 { + o.PollInterval = DefaultPollInterval + } + if o.Logf == nil { + o.Logf = func(string, ...any) {} + } + return o, nil +} diff --git a/plugins/ssh/agent/peer_darwin.go b/plugins/ssh/agent/peer_darwin.go new file mode 100644 index 00000000000..bd575b13cba --- /dev/null +++ b/plugins/ssh/agent/peer_darwin.go @@ -0,0 +1,35 @@ +//go:build darwin + +package agent + +import ( + "fmt" + "net" + + "golang.org/x/sys/unix" +) + +// peerUID returns the user id of the process on the other end of c. It uses LOCAL_PEERCRED, the +// socket option behind getpeereid on macOS. +func peerUID(c *net.UnixConn) (uint32, error) { + raw, err := c.SyscallConn() + if err != nil { + return 0, fmt.Errorf("access socket: %w", err) + } + var uid uint32 + var credErr error + if err := raw.Control(func(fd uintptr) { + cred, e := unix.GetsockoptXucred(int(fd), unix.SOL_LOCAL, unix.LOCAL_PEERCRED) + if e != nil { + credErr = e + return + } + uid = cred.Uid + }); err != nil { + return 0, fmt.Errorf("access socket: %w", err) + } + if credErr != nil { + return 0, fmt.Errorf("read peer credentials: %w", credErr) + } + return uid, nil +} diff --git a/plugins/ssh/agent/peer_linux.go b/plugins/ssh/agent/peer_linux.go new file mode 100644 index 00000000000..90e29db53d2 --- /dev/null +++ b/plugins/ssh/agent/peer_linux.go @@ -0,0 +1,34 @@ +//go:build linux + +package agent + +import ( + "fmt" + "net" + + "golang.org/x/sys/unix" +) + +// peerUID returns the user id of the process on the other end of c, from SO_PEERCRED. +func peerUID(c *net.UnixConn) (uint32, error) { + raw, err := c.SyscallConn() + if err != nil { + return 0, fmt.Errorf("access socket: %w", err) + } + var uid uint32 + var credErr error + if err := raw.Control(func(fd uintptr) { + cred, e := unix.GetsockoptUcred(int(fd), unix.SOL_SOCKET, unix.SO_PEERCRED) + if e != nil { + credErr = e + return + } + uid = cred.Uid + }); err != nil { + return 0, fmt.Errorf("access socket: %w", err) + } + if credErr != nil { + return 0, fmt.Errorf("read peer credentials: %w", credErr) + } + return uid, nil +} diff --git a/plugins/ssh/agent/peer_other.go b/plugins/ssh/agent/peer_other.go new file mode 100644 index 00000000000..17252264e34 --- /dev/null +++ b/plugins/ssh/agent/peer_other.go @@ -0,0 +1,14 @@ +//go:build !darwin && !linux && !windows + +package agent + +import ( + "errors" + "net" +) + +// errNoPeerCredentials means this platform has no peer credential check, so every connection is +// refused rather than served unchecked. +var errNoPeerCredentials = errors.New("peer credentials are not available on this platform") + +func peerUID(*net.UnixConn) (uint32, error) { return 0, errNoPeerCredentials } diff --git a/plugins/ssh/agent/peer_unix_test.go b/plugins/ssh/agent/peer_unix_test.go new file mode 100644 index 00000000000..e2312ab2dde --- /dev/null +++ b/plugins/ssh/agent/peer_unix_test.go @@ -0,0 +1,37 @@ +//go:build darwin || linux + +package agent + +import ( + "net" + "os" + "path/filepath" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestPeerUIDReadsTheRealPeer(t *testing.T) { + sock := filepath.Join(shortDir(t), "p.sock") + ln, err := net.Listen("unix", sock) + require.NoError(t, err) + defer ln.Close() + + accepted := make(chan net.Conn, 1) + go func() { + c, err := ln.Accept() + if err == nil { + accepted <- c + } + }() + client, err := net.Dial("unix", sock) + require.NoError(t, err) + defer client.Close() + server := <-accepted + defer server.Close() + + uid, err := peerUID(server.(*net.UnixConn)) + require.NoError(t, err) + assert.Equal(t, uint32(os.Getuid()), uid) +} diff --git a/plugins/ssh/agent/serve_unix.go b/plugins/ssh/agent/serve_unix.go new file mode 100644 index 00000000000..81168e9bd37 --- /dev/null +++ b/plugins/ssh/agent/serve_unix.go @@ -0,0 +1,162 @@ +//go:build !windows + +package agent + +import ( + "context" + "errors" + "fmt" + "net" + "os" + "os/signal" + "sync" + "syscall" + "time" +) + +// daemon holds the sockets Serve currently runs. +type daemon struct { + opts Options + audit *AuditLog + // peer returns the connecting user's id. Tests replace it. + peer func(*net.UnixConn) (uint32, error) + + mu sync.Mutex + sockets map[string]*socketEntry + wg sync.WaitGroup +} + +// Serve runs the agent daemon: one socket per configured identity, reloaded when the configuration +// changes. It blocks until ctx ends, then closes every socket and removes the state file. +func Serve(ctx context.Context, opts Options) error { + opts, err := opts.withDefaults() + if err != nil { + return err + } + if err := opts.Paths.EnsureDirs(); err != nil { + return err + } + audit, err := OpenAuditLog(opts.Paths.AuditLogFile()) + if err != nil { + return err + } + defer audit.Close() + + pid := os.Getpid() + state := State{PID: pid, Version: opts.Version, Started: time.Now().UTC()} + if err := WriteState(opts.Paths.StateFile(), state); err != nil { + return err + } + defer func() { + if err := RemoveState(opts.Paths.StateFile(), pid); err != nil { + opts.Logf("%v", err) + } + }() + + d := &daemon{opts: opts, audit: audit, peer: peerUID, sockets: map[string]*socketEntry{}} + if opts.peer != nil { + d.peer = opts.peer + } + defer d.shutdown() + d.reload() + if opts.Ready != nil { + opts.Ready() + } + d.watch(ctx) + return nil +} + +// watch reloads the configuration on SIGHUP and when the file changes, until ctx ends. +func (d *daemon) watch(ctx context.Context) { + hup := make(chan os.Signal, 1) + signal.Notify(hup, syscall.SIGHUP) + defer signal.Stop(hup) + + ticker := time.NewTicker(d.opts.PollInterval) + defer ticker.Stop() + + last := fingerprintFile(d.opts.Paths.AgentConfigFile()) + for { + select { + case <-ctx.Done(): + return + case <-hup: + d.reload() + last = fingerprintFile(d.opts.Paths.AgentConfigFile()) + case <-ticker.C: + if now := fingerprintFile(d.opts.Paths.AgentConfigFile()); now != last { + last = now + d.reload() + } + } + } +} + +// fileFingerprint identifies a version of the configuration file. +type fileFingerprint struct { + exists bool + mtime time.Time + size int64 +} + +func fingerprintFile(path string) fileFingerprint { + info, err := os.Stat(path) + if err != nil { + return fileFingerprint{} + } + return fileFingerprint{exists: true, mtime: info.ModTime(), size: info.Size()} +} + +// reload applies the configuration file. An invalid file leaves the running sockets untouched. +func (d *daemon) reload() { + cfg, err := loadOrEmpty(d.opts.Paths.AgentConfigFile()) + if err != nil { + d.opts.Logf("keeping the current configuration: %v", err) + return + } + if err := d.apply(cfg); err != nil { + d.opts.Logf("%v", err) + } +} + +// apply starts, restarts and stops sockets so they match cfg. Sockets whose settings did not +// change are left alone. Failures on one identity do not stop the others. +func (d *daemon) apply(cfg *Config) error { + d.mu.Lock() + defer d.mu.Unlock() + + want := map[string]Identity{} + for _, id := range cfg.Identities { + want[id.Name] = id + } + for name, e := range d.sockets { + if id, keep := want[name]; !keep || !id.equal(e.id) { + e.close() + delete(d.sockets, name) + } + } + var errs []error + for _, id := range cfg.Identities { + if _, running := d.sockets[id.Name]; running { + continue + } + e, err := d.startSocket(id) + if err != nil { + errs = append(errs, fmt.Errorf("identity %q: %w", id.Name, err)) + continue + } + d.sockets[id.Name] = e + } + return errors.Join(errs...) +} + +// shutdown closes every socket and waits for the connection goroutines. +func (d *daemon) shutdown() { + d.mu.Lock() + for name, e := range d.sockets { + e.close() + delete(d.sockets, name) + } + d.mu.Unlock() + d.wg.Wait() +} diff --git a/plugins/ssh/agent/serve_unix_test.go b/plugins/ssh/agent/serve_unix_test.go new file mode 100644 index 00000000000..5f70b99a893 --- /dev/null +++ b/plugins/ssh/agent/serve_unix_test.go @@ -0,0 +1,489 @@ +//go:build !windows + +package agent + +import ( + "bytes" + "context" + "crypto/ed25519" + "crypto/rand" + "encoding/base64" + "net" + "os" + "os/exec" + "path/filepath" + "syscall" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "golang.org/x/crypto/ssh" + xagent "golang.org/x/crypto/ssh/agent" + + "github.com/cloudposse/atmos/plugins/ssh/keystore" +) + +func TestListReturnsOnlyTheIdentityKey(t *testing.T) { + p := newPaths(t) + pubA := createFileKey(t, p, "a") + createFileKey(t, p, "b") + h := startDaemon(t, p, nil, ident("a", AllowSigning), ident("b", AllowSigning)) + + keys, err := h.client("a").List() + require.NoError(t, err) + require.Len(t, keys, 1) + assert.Equal(t, pubA.Marshal(), keys[0].Blob) + assert.Equal(t, "a", keys[0].Comment) +} + +func TestSocketMode(t *testing.T) { + p := newPaths(t) + createFileKey(t, p, "a") + h := startDaemon(t, p, nil, ident("a", AllowSigning)) + info, err := os.Stat(h.socket("a")) + require.NoError(t, err) + assert.Equal(t, os.FileMode(0o600), info.Mode().Perm()) + assert.NotZero(t, info.Mode()&os.ModeSocket) +} + +// signCase is one sign request and the outcome expected for each allow list. +type signCase struct { + name string + payload func(pub ssh.PublicKey) []byte + signing bool + auth bool + // auditKind is the expected audit classification. + auditKind Kind +} + +func signCases() []signCase { + return []signCase{ + {"git signature", func(ssh.PublicKey) []byte { return sshsigBlob("git") }, true, false, KindGitSignature}, + {"sshsig other namespace", func(ssh.PublicKey) []byte { return sshsigBlob("file") }, false, false, KindGitSignature}, + {"userauth for this key", func(pub ssh.PublicKey) []byte { + return userauthBlob("session-session-session-session", "alice", "ssh-connection", pub) + }, false, true, KindSSHAuthentication}, + {"userauth for another key", func(ssh.PublicKey) []byte { + return userauthBlob("session-session-session-session", "alice", "ssh-connection", newPubForCase()) + }, false, false, KindSSHAuthentication}, + {"garbage", func(ssh.PublicKey) []byte { return []byte("just some bytes to sign") }, false, false, KindOther}, + } +} + +func newPubForCase() ssh.PublicKey { + pub, _, _ := ed25519.GenerateKey(rand.Reader) + k, _ := ssh.NewPublicKey(pub) + return k +} + +func TestSignRespectsAllowList(t *testing.T) { + p := newPaths(t) + pubS := createFileKey(t, p, "signonly") + pubA := createFileKey(t, p, "authonly") + h := startDaemon(t, p, nil, ident("signonly", AllowSigning), ident("authonly", AllowAuthentication)) + + for _, tc := range signCases() { + for _, who := range []struct { + name string + pub ssh.PublicKey + expect bool + }{{"signonly", pubS, tc.signing}, {"authonly", pubA, tc.auth}} { + t.Run(tc.name+" via "+who.name, func(t *testing.T) { + data := tc.payload(who.pub) + sig, err := h.client(who.name).Sign(who.pub, data) + entry := h.lastAudit() + assert.Equal(t, who.name, entry.Identity) + assert.Equal(t, OpSign, entry.Operation) + assert.Equal(t, tc.auditKind, entry.Classification) + if !who.expect { + require.Error(t, err) + assert.Equal(t, ResultRefused, entry.Result) + assert.NotEmpty(t, entry.Reason) + return + } + require.NoError(t, err) + require.NoError(t, who.pub.Verify(data, sig)) + assert.Equal(t, ResultOK, entry.Result) + assert.Equal(t, ssh.FingerprintSHA256(who.pub), entry.Fingerprint) + }) + } + } +} + +func TestSignRefusesAnotherKey(t *testing.T) { + p := newPaths(t) + createFileKey(t, p, "a") + h := startDaemon(t, p, nil, ident("a", AllowSigning)) + + _, err := h.client("a").Sign(newPubForCase(), sshsigBlob("git")) + require.Error(t, err) + entry := h.lastAudit() + assert.Equal(t, ResultRefused, entry.Result) + assert.Contains(t, entry.Reason, "different public key") +} + +func TestManagementRequestsAreRefused(t *testing.T) { + p := newPaths(t) + pub := createFileKey(t, p, "a") + h := startDaemon(t, p, nil, ident("a", AllowSigning, AllowAuthentication)) + c := h.client("a") + + _, extra, err := ed25519.GenerateKey(rand.Reader) + require.NoError(t, err) + + require.Error(t, c.Add(xagent.AddedKey{PrivateKey: extra})) + require.Error(t, c.Remove(pub)) + require.Error(t, c.RemoveAll()) + require.Error(t, c.Lock([]byte("pw"))) + require.Error(t, c.Unlock([]byte("pw"))) + _, err = c.Extension("query", nil) + require.Error(t, err) + + keys, err := c.List() + require.NoError(t, err) + require.Len(t, keys, 1, "the key list is unchanged") + + for _, op := range []string{"add", "remove", "remove-all", "lock", "unlock"} { + var found bool + for _, e := range h.auditEntries() { + if e.Operation == op { + found = true + assert.Equal(t, ResultRefused, e.Result) + } + } + assert.True(t, found, "audit entry for %s", op) + } +} + +func TestAuditLogHasNoPayload(t *testing.T) { + p := newPaths(t) + pub := createFileKey(t, p, "a") + h := startDaemon(t, p, nil, ident("a", AllowSigning, AllowAuthentication)) + c := h.client("a") + + marker := "UNIQUE-SESSION-MARKER-0123456789" + data := userauthBlob(marker, "alice", "ssh-connection", pub) + sig, err := c.Sign(pub, data) + require.NoError(t, err) + _, err = c.Sign(pub, []byte("PAYLOAD-MARKER-should-never-be-logged")) + require.Error(t, err) + + raw, err := os.ReadFile(h.paths.AuditLogFile()) + require.NoError(t, err) + for _, secret := range [][]byte{ + []byte(marker), []byte("PAYLOAD-MARKER"), sig.Blob, + []byte(base64.StdEncoding.EncodeToString(sig.Blob)), + []byte(base64.StdEncoding.EncodeToString(data)), + } { + assert.False(t, bytes.Contains(raw, secret), "audit log leaks %q", secret) + } + + var login AuditEntry + for _, e := range h.auditEntries() { + if e.Classification == KindSSHAuthentication { + login = e + } + } + assert.Equal(t, "alice", login.User) + assert.Equal(t, "ssh-connection", login.Service) + assert.Equal(t, ResultOK, login.Result) +} + +func TestReloadAddsAndRemovesSockets(t *testing.T) { + p := newPaths(t) + createFileKey(t, p, "a") + createFileKey(t, p, "b") + h := startDaemon(t, p, nil, ident("a", AllowSigning)) + + require.NoError(t, UpsertIdentity(p.AgentConfigFile(), ident("b", AllowSigning))) + require.Eventually(t, func() bool { + return CheckSocket(context.Background(), h.socket("b"), nil) == nil + }, 5*time.Second, 25*time.Millisecond, "new socket comes up") + + // Hold a connection to a, then remove b: a must keep working on the same connection. + ca := h.client("a") + _, err := RemoveIdentity(p.AgentConfigFile(), "b") + require.NoError(t, err) + require.Eventually(t, func() bool { + _, err := os.Stat(h.socket("b")) + return os.IsNotExist(err) + }, 5*time.Second, 25*time.Millisecond, "removed socket goes away") + + keys, err := ca.List() + require.NoError(t, err) + require.Len(t, keys, 1) + require.NoError(t, CheckSocket(context.Background(), h.socket("a"), keys[0])) +} + +func TestReloadOnSIGHUP(t *testing.T) { + p := newPaths(t) + createFileKey(t, p, "a") + createFileKey(t, p, "b") + h := startDaemon(t, p, func(o *Options) { o.PollInterval = time.Hour }, ident("a", AllowSigning)) + + require.NoError(t, UpsertIdentity(p.AgentConfigFile(), ident("b", AllowSigning))) + require.NoError(t, syscall.Kill(os.Getpid(), syscall.SIGHUP)) + require.Eventually(t, func() bool { + return CheckSocket(context.Background(), h.socket("b"), nil) == nil + }, 5*time.Second, 25*time.Millisecond) +} + +func TestInvalidConfigKeepsRunningSockets(t *testing.T) { + p := newPaths(t) + createFileKey(t, p, "a") + h := startDaemon(t, p, nil, ident("a", AllowSigning)) + + require.NoError(t, os.WriteFile(p.AgentConfigFile(), []byte("{broken"), 0o600)) + time.Sleep(200 * time.Millisecond) + require.NoError(t, CheckSocket(context.Background(), h.socket("a"), nil)) +} + +func TestChangedIdentityIsRestarted(t *testing.T) { + p := newPaths(t) + pub := createFileKey(t, p, "a") + h := startDaemon(t, p, nil, ident("a", AllowAuthentication)) + + _, err := h.client("a").Sign(pub, sshsigBlob("git")) + require.Error(t, err) + + require.NoError(t, UpsertIdentity(p.AgentConfigFile(), ident("a", AllowSigning))) + require.Eventually(t, func() bool { + conn, err := net.Dial("unix", h.socket("a")) + if err != nil { + return false + } + defer conn.Close() + _, err = xagent.NewClient(conn).Sign(pub, sshsigBlob("git")) + return err == nil + }, 5*time.Second, 25*time.Millisecond) +} + +func TestStateFileLifecycle(t *testing.T) { + p := newPaths(t) + createFileKey(t, p, "a") + h := startDaemon(t, p, func(o *Options) { o.Version = "9.9.9" }, ident("a", AllowSigning)) + + state, err := ReadState(p.StateFile()) + require.NoError(t, err) + assert.Equal(t, os.Getpid(), state.PID) + assert.Equal(t, "9.9.9", state.Version) + assert.WithinDuration(t, time.Now(), state.Started, time.Minute) + + h.Stop() + _, err = ReadState(p.StateFile()) + require.ErrorIs(t, err, ErrNoState) + _, err = os.Stat(h.socket("a")) + require.ErrorIs(t, err, os.ErrNotExist, "socket removed on exit") +} + +func TestStaleSocketIsReplaced(t *testing.T) { + p := newPaths(t) + createFileKey(t, p, "a") + sock := filepath.Join(p.SocketsDir(), "a.sock") + ln, err := net.Listen("unix", sock) + require.NoError(t, err) + ln.(*net.UnixListener).SetUnlinkOnClose(false) + require.NoError(t, ln.Close()) + _, err = os.Stat(sock) + require.NoError(t, err, "stale socket file exists") + + h := startDaemon(t, p, nil, ident("a", AllowSigning)) + require.NoError(t, CheckSocket(context.Background(), h.socket("a"), nil)) +} + +func TestLiveSocketIsNotStolen(t *testing.T) { + p := newPaths(t) + sock := filepath.Join(p.SocketsDir(), "a.sock") + ln, err := net.Listen("unix", sock) + require.NoError(t, err) + defer ln.Close() + + require.ErrorIs(t, removeStaleSocket(sock), ErrSocketInUse) + _, err = os.Stat(sock) + require.NoError(t, err) +} + +func TestRemoveStaleSocketRefusesRegularFile(t *testing.T) { + path := filepath.Join(shortDir(t), "x.sock") + require.NoError(t, os.WriteFile(path, []byte("data"), 0o600)) + require.Error(t, removeStaleSocket(path)) + _, err := os.Stat(path) + require.NoError(t, err, "a regular file is left alone") +} + +func TestOtherUsersAreRefused(t *testing.T) { + p := newPaths(t) + createFileKey(t, p, "a") + h := startDaemon(t, p, func(o *Options) { + o.peer = func(*net.UnixConn) (uint32, error) { return uint32(os.Getuid()) + 1, nil } + }, ident("a", AllowSigning)) + + conn, err := net.Dial("unix", h.socket("a")) + require.NoError(t, err) + defer conn.Close() + _, err = xagent.NewClient(conn).List() + require.Error(t, err, "connection is closed without an answer") + + require.Eventually(t, func() bool { + for _, e := range h.auditEntries() { + if e.Operation == OpConnect && e.Result == ResultRefused { + return true + } + } + return false + }, 5*time.Second, 25*time.Millisecond) +} + +func TestVerifyPeer(t *testing.T) { + require.NoError(t, verifyPeer(501, 501)) + require.ErrorIs(t, verifyPeer(0, 501), ErrWrongUser) +} + +func TestLockedScreenIsReportedAndFails(t *testing.T) { + p := newPaths(t) + h := startDaemon(t, p, func(o *Options) { + o.OpenStore = func(string, string) (keystore.Store, error) { return newLockedStore(t), nil } + }, Identity{Name: "locked", Store: "fake", Key: "k", Allow: []Allow{AllowSigning}}) + + c := h.client("locked") + keys, err := c.List() + require.NoError(t, err) + require.Len(t, keys, 1) + pub, err := ssh.ParsePublicKey(keys[0].Blob) + require.NoError(t, err) + + _, err = c.Sign(pub, sshsigBlob("git")) + require.Error(t, err, "the agent reports a failure") + + entry := h.lastAudit() + assert.Equal(t, OpSign, entry.Operation) + assert.Equal(t, ResultError, entry.Result) + assert.True(t, entry.ScreenLocked) + assert.Equal(t, KindGitSignature, entry.Classification) +} + +func TestOtherSignErrorIsNotScreenLocked(t *testing.T) { + p := newPaths(t) + h := startDaemon(t, p, func(o *Options) { + o.OpenStore = func(string, string) (keystore.Store, error) { + s := newLockedStore(t) + s.signErr = os.ErrDeadlineExceeded + return s, nil + } + }, Identity{Name: "broken", Store: "fake", Key: "k", Allow: []Allow{AllowSigning}}) + + c := h.client("broken") + keys, err := c.List() + require.NoError(t, err) + pub, err := ssh.ParsePublicKey(keys[0].Blob) + require.NoError(t, err) + _, err = c.Sign(pub, sshsigBlob("git")) + require.Error(t, err) + entry := h.lastAudit() + assert.Equal(t, ResultError, entry.Result) + assert.False(t, entry.ScreenLocked) +} + +func TestKeysAreClosed(t *testing.T) { + p := newPaths(t) + store := newLockedStore(t) + store.signErr = nil + h := startDaemon(t, p, func(o *Options) { + o.OpenStore = func(string, string) (keystore.Store, error) { return store, nil } + }, Identity{Name: "k", Store: "fake", Key: "k", Allow: []Allow{AllowSigning}}) + + c := h.client("k") + keys, err := c.List() + require.NoError(t, err) + pub, err := ssh.ParsePublicKey(keys[0].Blob) + require.NoError(t, err) + _, err = c.Sign(pub, sshsigBlob("git")) + require.NoError(t, err) + _, err = c.Sign(pub, []byte("garbage")) + require.Error(t, err) + + assert.Equal(t, store.opened(), store.closedCount(), "every opened key is closed") + assert.Positive(t, store.opened()) +} + +func TestUnknownStoreFailsOnlyThatIdentity(t *testing.T) { + p := newPaths(t) + createFileKey(t, p, "good") + h := startDaemon(t, p, nil, + Identity{Name: "bad", Store: "no-such-store", Key: "k", Allow: []Allow{AllowSigning}}, + ident("good", AllowSigning)) + require.NoError(t, CheckSocket(context.Background(), h.socket("good"), nil)) + _, err := os.Stat(h.socket("bad")) + require.ErrorIs(t, err, os.ErrNotExist) +} + +func TestCheckSocket(t *testing.T) { + p := newPaths(t) + pub := createFileKey(t, p, "a") + other := createFileKey(t, p, "b") + h := startDaemon(t, p, nil, ident("a", AllowSigning)) + + require.NoError(t, CheckSocket(context.Background(), h.socket("a"), pub)) + require.ErrorIs(t, CheckSocket(context.Background(), h.socket("a"), other), ErrUnexpectedKeys) + require.Error(t, CheckSocket(context.Background(), filepath.Join(p.SocketsDir(), "none.sock"), nil)) +} + +func TestSSHKeygenSigningEndToEnd(t *testing.T) { + keygen, err := exec.LookPath("ssh-keygen") + if err != nil { + t.Skip("ssh-keygen is not on PATH; skipping the OpenSSH end-to-end check") + } + p := newPaths(t) + pub := createFileKey(t, p, "e2e") + h := startDaemon(t, p, nil, ident("e2e", AllowSigning)) + + work := shortDir(t) + message := filepath.Join(work, "commit.txt") + require.NoError(t, os.WriteFile(message, []byte("tree 0123\nauthor Test\n\nsigned commit\n"), 0o600)) + pubFile := filepath.Join(work, "key.pub") + require.NoError(t, os.WriteFile(pubFile, ssh.MarshalAuthorizedKey(pub), 0o600)) + allowed := filepath.Join(work, "allowed_signers") + require.NoError(t, os.WriteFile(allowed, + append([]byte(`test@example.com namespaces="git" `), ssh.MarshalAuthorizedKey(pub)...), 0o600)) + + run := func(stdin []byte, args ...string) ([]byte, error) { + cmd := exec.Command(keygen, args...) + cmd.Env = []string{"SSH_AUTH_SOCK=" + h.socket("e2e"), "HOME=" + work} + cmd.Dir = work + if stdin != nil { + cmd.Stdin = bytes.NewReader(stdin) + } + return cmd.CombinedOutput() + } + + out, err := run(nil, "-Y", "sign", "-U", "-f", pubFile, "-n", "git", message) + require.NoError(t, err, string(out)) + sigFile := message + ".sig" + require.FileExists(t, sigFile) + + body, err := os.ReadFile(message) + require.NoError(t, err) + out, err = run(body, "-Y", "verify", "-f", allowed, "-I", "test@example.com", "-n", "git", "-s", sigFile) + require.NoError(t, err, string(out)) + assert.Contains(t, string(out), "Good") + + // The same socket must refuse any other namespace. + out, err = run(nil, "-Y", "sign", "-U", "-f", pubFile, "-n", "file", message) + require.Error(t, err, string(out)) + + var sawGit, sawRefusedFile bool + for _, e := range h.auditEntries() { + if e.Operation != OpSign { + continue + } + sawGit = sawGit || (e.Namespace == "git" && e.Result == ResultOK) + sawRefusedFile = sawRefusedFile || (e.Namespace == "file" && e.Result == ResultRefused) + } + assert.True(t, sawGit, "audit log records the git signature") + assert.True(t, sawRefusedFile, "audit log records the refused namespace") +} + +func TestServeRequiresPaths(t *testing.T) { + require.ErrorIs(t, Serve(context.Background(), Options{}), ErrInvalidConfig) +} diff --git a/plugins/ssh/agent/serve_windows.go b/plugins/ssh/agent/serve_windows.go new file mode 100644 index 00000000000..02a4ad7f074 --- /dev/null +++ b/plugins/ssh/agent/serve_windows.go @@ -0,0 +1,8 @@ +//go:build windows + +package agent + +import "context" + +// Serve is not implemented on Windows; named pipes are a later phase. +func Serve(context.Context, Options) error { return ErrUnsupportedPlatform } diff --git a/plugins/ssh/agent/sockets_unix.go b/plugins/ssh/agent/sockets_unix.go new file mode 100644 index 00000000000..832d1d83709 --- /dev/null +++ b/plugins/ssh/agent/sockets_unix.go @@ -0,0 +1,190 @@ +//go:build !windows + +package agent + +import ( + "errors" + "fmt" + "io" + "net" + "os" + "sync" + "time" + + "golang.org/x/crypto/ssh/agent" +) + +// ErrWrongUser means a connection came from a different user than the one running the daemon. +var ErrWrongUser = errors.New("connection from a different user") + +const ( + socketMode os.FileMode = 0o600 + // staleProbe is how long to wait when checking whether an existing socket is alive. + staleProbe = 500 * time.Millisecond + // acceptBackoff is the pause after a temporary accept failure. + acceptBackoff = 50 * time.Millisecond +) + +// socketEntry is one live identity socket and the connections it is serving. +type socketEntry struct { + id Identity + path string + ln net.Listener + agent *identityAgent + + mu sync.Mutex + conns map[net.Conn]struct{} + closed bool +} + +// track records a connection. It reports false once the socket is closing. +func (e *socketEntry) track(c net.Conn) bool { + e.mu.Lock() + defer e.mu.Unlock() + if e.closed { + return false + } + e.conns[c] = struct{}{} + return true +} + +func (e *socketEntry) untrack(c net.Conn) { + e.mu.Lock() + defer e.mu.Unlock() + delete(e.conns, c) +} + +// close stops accepting, drops open connections and removes the socket file. +func (e *socketEntry) close() { + e.mu.Lock() + e.closed = true + conns := make([]net.Conn, 0, len(e.conns)) + for c := range e.conns { + conns = append(conns, c) + } + e.mu.Unlock() + + _ = e.ln.Close() + for _, c := range conns { + _ = c.Close() + } + _ = os.Remove(e.path) +} + +// removeStaleSocket deletes a leftover socket file. It refuses to touch anything that is not a +// socket, and fails with ErrSocketInUse if something is still listening on it. +func removeStaleSocket(path string) error { + info, err := os.Lstat(path) + if errors.Is(err, os.ErrNotExist) { + return nil + } + if err != nil { + return fmt.Errorf("inspect %s: %w", path, err) + } + if info.Mode()&os.ModeSocket == 0 { + return fmt.Errorf("%s exists and is not a socket", path) + } + if conn, err := net.DialTimeout("unix", path, staleProbe); err == nil { + _ = conn.Close() + return fmt.Errorf("%w: %s", ErrSocketInUse, path) + } + if err := os.Remove(path); err != nil { + return fmt.Errorf("remove stale socket %s: %w", path, err) + } + return nil +} + +// startSocket opens the identity's store and socket and starts serving it. +func (d *daemon) startSocket(id Identity) (*socketEntry, error) { + sockPath, err := d.opts.Paths.SocketPath(id.Name) + if err != nil { + return nil, err + } + store, err := d.opts.OpenStore(id.Store, d.opts.Paths.StoreDir(id.Store)) + if err != nil { + return nil, fmt.Errorf("identity %q: open key store %q: %w", id.Name, id.Store, err) + } + if err := os.MkdirAll(d.opts.Paths.SocketsDir(), 0o700); err != nil { + return nil, fmt.Errorf("create sockets directory: %w", err) + } + if err := removeStaleSocket(sockPath); err != nil { + return nil, err + } + ln, err := net.Listen("unix", sockPath) + if err != nil { + return nil, fmt.Errorf("listen on %s: %w", sockPath, err) + } + if err := os.Chmod(sockPath, socketMode); err != nil { + _ = ln.Close() + return nil, fmt.Errorf("restrict %s: %w", sockPath, err) + } + e := &socketEntry{ + id: id, path: sockPath, ln: ln, conns: map[net.Conn]struct{}{}, + agent: &identityAgent{id: id, store: store, audit: d.audit, onAuditError: d.auditError}, + } + d.wg.Add(1) + go d.acceptLoop(e) + return e, nil +} + +func (d *daemon) auditError(err error) { d.opts.Logf("audit log: %v", err) } + +// acceptLoop serves connections until the socket is closed. +func (d *daemon) acceptLoop(e *socketEntry) { + defer d.wg.Done() + for { + conn, err := e.ln.Accept() + if err != nil { + if errors.Is(err, net.ErrClosed) { + return + } + d.opts.Logf("accept on %s: %v", e.path, err) + time.Sleep(acceptBackoff) + continue + } + if err := d.admit(e, conn); err != nil { + d.opts.Logf("identity %q: %v", e.id.Name, err) + e.agent.record(AuditEntry{Operation: OpConnect, Result: ResultRefused, Reason: err.Error()}) + _ = conn.Close() + continue + } + d.wg.Add(1) + go d.serveConn(e, conn) + } +} + +// admit checks the connecting user and registers the connection. +func (d *daemon) admit(e *socketEntry, conn net.Conn) error { + uc, ok := conn.(*net.UnixConn) + if !ok { + return fmt.Errorf("%w: not a unix connection", ErrWrongUser) + } + uid, err := d.peer(uc) + if err != nil { + return fmt.Errorf("%w: %w", ErrWrongUser, err) + } + if err := verifyPeer(uid, uint32(os.Getuid())); err != nil { + return err + } + if !e.track(conn) { + return net.ErrClosed + } + return nil +} + +// verifyPeer accepts only a connection from the daemon's own user. +func verifyPeer(got, want uint32) error { + if got != want { + return fmt.Errorf("%w: uid %d, want %d", ErrWrongUser, got, want) + } + return nil +} + +func (d *daemon) serveConn(e *socketEntry, conn net.Conn) { + defer d.wg.Done() + defer e.untrack(conn) + defer conn.Close() + if err := agent.ServeAgent(e.agent, conn); err != nil && !errors.Is(err, io.EOF) && !errors.Is(err, net.ErrClosed) { + d.opts.Logf("identity %q: connection ended: %v", e.id.Name, err) + } +} diff --git a/plugins/ssh/agent/state.go b/plugins/ssh/agent/state.go new file mode 100644 index 00000000000..99fdb96591b --- /dev/null +++ b/plugins/ssh/agent/state.go @@ -0,0 +1,63 @@ +package agent + +import ( + "encoding/json" + "errors" + "fmt" + "os" + "time" +) + +// ErrNoState means the daemon state file does not exist, so no daemon is recorded as running. +var ErrNoState = errors.New("no daemon state recorded") + +// State is what a running daemon records about itself. +type State struct { + PID int `json:"pid"` + Version string `json:"version"` + Started time.Time `json:"started"` +} + +// WriteState writes the state file atomically with mode 0600. +func WriteState(path string, s State) error { + data, err := json.Marshal(s) + if err != nil { + return fmt.Errorf("encode daemon state: %w", err) + } + return writeFileAtomic(path, append(data, '\n'), 0o600) +} + +// ReadState reads the state file. A missing file is ErrNoState. +func ReadState(path string) (State, error) { + data, err := os.ReadFile(path) + if err != nil { + if errors.Is(err, os.ErrNotExist) { + return State{}, fmt.Errorf("%w: %s", ErrNoState, path) + } + return State{}, fmt.Errorf("read daemon state: %w", err) + } + var s State + if err := json.Unmarshal(data, &s); err != nil { + return State{}, fmt.Errorf("decode daemon state %s: %w", path, err) + } + return s, nil +} + +// RemoveState deletes the state file, but only when it still records pid, so a daemon that is +// exiting never removes the record of the daemon that replaced it. +func RemoveState(path string, pid int) error { + s, err := ReadState(path) + if errors.Is(err, ErrNoState) { + return nil + } + if err != nil { + return err + } + if s.PID != pid { + return nil + } + if err := os.Remove(path); err != nil && !errors.Is(err, os.ErrNotExist) { + return fmt.Errorf("remove daemon state: %w", err) + } + return nil +} diff --git a/plugins/ssh/agent/state_audit_test.go b/plugins/ssh/agent/state_audit_test.go new file mode 100644 index 00000000000..997df19e61b --- /dev/null +++ b/plugins/ssh/agent/state_audit_test.go @@ -0,0 +1,77 @@ +package agent + +import ( + "bufio" + "encoding/json" + "os" + "path/filepath" + "runtime" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestStateRoundTrip(t *testing.T) { + path := filepath.Join(t.TempDir(), "daemon.json") + _, err := ReadState(path) + require.ErrorIs(t, err, ErrNoState) + + want := State{PID: 4242, Version: "1.2.3", Started: time.Date(2026, 11, 12, 1, 2, 3, 0, time.UTC)} + require.NoError(t, WriteState(path, want)) + got, err := ReadState(path) + require.NoError(t, err) + assert.Equal(t, want, got) +} + +func TestRemoveStateOnlyOwnRecord(t *testing.T) { + path := filepath.Join(t.TempDir(), "daemon.json") + require.NoError(t, WriteState(path, State{PID: 10, Version: "v"})) + + require.NoError(t, RemoveState(path, 11)) + _, err := os.Stat(path) + require.NoError(t, err, "another daemon's record stays") + + require.NoError(t, RemoveState(path, 10)) + _, err = os.Stat(path) + require.ErrorIs(t, err, os.ErrNotExist) + + require.NoError(t, RemoveState(path, 10), "removing a missing record is fine") +} + +func TestAuditLogWritesJSONLines(t *testing.T) { + path := filepath.Join(t.TempDir(), "audit.log") + log, err := OpenAuditLog(path) + require.NoError(t, err) + require.NoError(t, log.Record(AuditEntry{Identity: "ops", Operation: OpSign, Result: ResultOK, Classification: KindGitSignature, Namespace: "git"})) + require.NoError(t, log.Record(AuditEntry{Identity: "ops", Operation: OpList, Result: ResultOK})) + require.NoError(t, log.Close()) + + f, err := os.Open(path) + require.NoError(t, err) + defer f.Close() + var entries []AuditEntry + sc := bufio.NewScanner(f) + for sc.Scan() { + var e AuditEntry + require.NoError(t, json.Unmarshal(sc.Bytes(), &e)) + entries = append(entries, e) + } + require.Len(t, entries, 2) + assert.False(t, entries[0].Time.IsZero()) + assert.Equal(t, "git", entries[0].Namespace) + assert.Equal(t, OpList, entries[1].Operation) + + if runtime.GOOS != "windows" { + info, err := os.Stat(path) + require.NoError(t, err) + assert.Equal(t, os.FileMode(0o600), info.Mode().Perm()) + } +} + +func TestNilAuditLogDiscards(t *testing.T) { + var log *AuditLog + require.NoError(t, log.Record(AuditEntry{})) + require.NoError(t, log.Close()) +} diff --git a/plugins/ssh/authority/authority.go b/plugins/ssh/authority/authority.go new file mode 100644 index 00000000000..6890d8f36ed --- /dev/null +++ b/plugins/ssh/authority/authority.go @@ -0,0 +1,189 @@ +// Package authority defines the parties that vouch for an SSH public key. +// +// An authority is asked, at login, to make sure the key is enrolled for the requested uses. GitHub +// is one authority: the key is registered on a user account as a signing key and/or an +// authentication key. The package also holds the registry of authorities, the on-disk receipt +// store, and Reconcile, which brings an authority and the receipts into agreement with the keys +// that exist on this machine. +package authority + +import ( + "context" + "sort" + "strings" + "time" + + "golang.org/x/crypto/ssh" +) + +// CredentialToken is the key under which an authority finds its token in the credentials map. +const CredentialToken = "token" + +// Use is what an authority vouches for a key doing. +type Use string + +const ( + // UseSigning lets the key sign, for example Git commits. + UseSigning Use = "signing" + // UseAuthentication lets the key authenticate, for example SSH logins and Git over SSH. + UseAuthentication Use = "authentication" +) + +// Authority vouches for a public key using credentials supplied by the caller. +type Authority interface { + // Name is the registry key, such as "github". + Name() string + // Supports lists the uses it can vouch for. + Supports() []Use + // Ensure makes the authority trust the key for the requested uses. It is idempotent. + // + // When Ensure fails after enrolling some uses, it returns the receipt of what was enrolled + // along with the error, so the caller can persist the references needed to revoke later. + Ensure(ctx context.Context, credentials map[string]string, request Request) (Receipt, error) + // Revoke withdraws an enrollment. It is idempotent: a missing enrollment is success. Only the + // uses named in receipt.References are withdrawn. + Revoke(ctx context.Context, credentials map[string]string, receipt Receipt) error +} + +// Request asks an authority to vouch for a key. +type Request struct { + // KeyName is the local name of the key, recorded in the receipt. + KeyName string + // Key is the public key to enroll. + Key ssh.PublicKey + // Uses is what the key is to be trusted for. + Uses []Use + // Title labels the key on the authority, such as "@ (Atmos)". + Title string + // Principals are remote usernames, for authorities that issue certificates. + Principals []string + // Target is a host or instance, for authorities that enroll per host. + Target string +} + +// Receipt records that an authority trusts a key. It holds no credential. +type Receipt struct { + // Authority is the name of the authority that issued the receipt. + Authority string `json:"authority"` + // Subject is the account that now trusts the key. + Subject string `json:"subject,omitempty"` + // KeyName is the local name of the key. + KeyName string `json:"key_name"` + // Fingerprint is the SHA256 fingerprint of the public key. + Fingerprint string `json:"fingerprint"` + // PublicKey is the public key in authorized_keys form. + PublicKey string `json:"public_key,omitempty"` + // Uses lists what the authority was asked to vouch for. + Uses []Use `json:"uses,omitempty"` + // References maps a use to the authority's own ID, which revocation needs. + References map[Use]string `json:"references,omitempty"` + // Certificate is set by authorities that issue certificates. + Certificate []byte `json:"certificate,omitempty"` + // Created is when the receipt was first issued. + Created time.Time `json:"created"` + // ExpiresAt is when the trust ends. The zero value means trusted until revoked. + ExpiresAt time.Time `json:"expires_at,omitzero"` +} + +// Fingerprint returns the SHA256 fingerprint of key. +func Fingerprint(key ssh.PublicKey) string { + return ssh.FingerprintSHA256(key) +} + +// AuthorizedKey returns key in authorized_keys form, without a trailing newline. +func AuthorizedKey(key ssh.PublicKey) string { + return strings.TrimSpace(string(ssh.MarshalAuthorizedKey(key))) +} + +// NewReceipt returns a receipt for request with the fields every authority fills in the same way. +func NewReceipt(authorityName string, request Request) Receipt { + return Receipt{ + Authority: authorityName, + KeyName: request.KeyName, + Fingerprint: Fingerprint(request.Key), + PublicKey: AuthorizedKey(request.Key), + References: map[Use]string{}, + Created: time.Now().UTC(), + } +} + +// NormalizeUses returns uses without duplicates or empty values, in a stable order. +func NormalizeUses(uses []Use) []Use { + seen := make(map[Use]bool, len(uses)) + out := make([]Use, 0, len(uses)) + for _, use := range uses { + if use == "" || seen[use] { + continue + } + seen[use] = true + out = append(out, use) + } + sort.Slice(out, func(i, j int) bool { return out[i] < out[j] }) + return out +} + +// EnrolledUses returns every use the receipt covers or holds a reference for. +func (r Receipt) EnrolledUses() []Use { + all := make([]Use, 0, len(r.Uses)+len(r.References)) + all = append(all, r.Uses...) + for use := range r.References { + all = append(all, use) + } + return NormalizeUses(all) +} + +// Expired reports whether the receipt's trust has ended at now. +func (r Receipt) Expired(now time.Time) bool { + return !r.ExpiresAt.IsZero() && !now.Before(r.ExpiresAt) +} + +// ValidateRequest checks request before any network call: a key, at least one use, and only uses +// the authority supports. +func ValidateRequest(a Authority, request Request) error { + if request.Key == nil { + return &Error{Authority: a.Name(), Operation: "ensure", Err: ErrInvalidRequest, Detail: "no public key"} + } + uses := NormalizeUses(request.Uses) + if len(uses) == 0 { + return &Error{Authority: a.Name(), Operation: "ensure", Err: ErrInvalidRequest, Detail: "no uses requested"} + } + supported := make(map[Use]bool) + for _, use := range a.Supports() { + supported[use] = true + } + for _, use := range uses { + if !supported[use] { + return &Error{Authority: a.Name(), Operation: "ensure", Use: use, Err: ErrUnsupportedUse} + } + } + return nil +} + +// equalUses reports whether a and b hold the same uses, ignoring order and duplicates. +func equalUses(a, b []Use) bool { + a, b = NormalizeUses(a), NormalizeUses(b) + if len(a) != len(b) { + return false + } + for i := range a { + if a[i] != b[i] { + return false + } + } + return true +} + +// differenceUses returns the uses in a that are not in b. +func differenceUses(a, b []Use) []Use { + skip := make(map[Use]bool, len(b)) + for _, use := range b { + skip[use] = true + } + var out []Use + for _, use := range NormalizeUses(a) { + if !skip[use] { + out = append(out, use) + } + } + return out +} diff --git a/plugins/ssh/authority/authoritytest/environment.go b/plugins/ssh/authority/authoritytest/environment.go new file mode 100644 index 00000000000..079339af8e5 --- /dev/null +++ b/plugins/ssh/authority/authoritytest/environment.go @@ -0,0 +1,60 @@ +// Package authoritytest holds the conformance suite every authority must pass, a fake GitHub +// server, and an in-memory fake authority for other packages' tests. +package authoritytest + +import ( + "crypto/ed25519" + "crypto/rand" + "testing" + + "github.com/stretchr/testify/require" + "golang.org/x/crypto/ssh" + + "github.com/cloudposse/atmos/plugins/ssh/authority" +) + +// Environment is one isolated authority under test, together with the hooks the suite needs to +// look behind it. +type Environment struct { + // Authority is the implementation under test. + Authority authority.Authority + // Credentials hold every permission the authority needs. + Credentials map[string]string + // Invalid holds credentials the authority must reject. Nil skips the check. + Invalid map[string]string + // Restricted returns credentials that lack the permission for use. Nil skips the check. + Restricted func(use authority.Use) map[string]string + // Permission names the permission that Restricted credentials lack for use. The error must + // contain it. + Permission func(use authority.Use) string + // Seed registers key on the authority for use before the test enrolls it, and returns the ID + // the authority gave it. Nil skips the adoption check. + Seed func(t *testing.T, key ssh.PublicKey, use authority.Use) string + // Enrollments counts the entries on the authority for key and use. Nil skips the checks that + // need to look behind the authority. + Enrollments func(key ssh.PublicKey, use authority.Use) int + // Log returns everything the authority sent, as text. Nil skips the log check. + Log func() string + // Secrets are the strings, such as tokens, that must not appear in a receipt, an error, or + // the log. + Secrets []string +} + +// NewKey returns a fresh Ed25519 public key. +func NewKey(t *testing.T) ssh.PublicKey { + t.Helper() + pub, _, err := ed25519.GenerateKey(rand.Reader) + require.NoError(t, err) + key, err := ssh.NewPublicKey(pub) + require.NoError(t, err) + return key +} + +// Fingerprints returns the fingerprints of keys as a set, for Params.Existing. +func Fingerprints(keys ...ssh.PublicKey) map[string]bool { + set := make(map[string]bool, len(keys)) + for _, key := range keys { + set[authority.Fingerprint(key)] = true + } + return set +} diff --git a/plugins/ssh/authority/authoritytest/fake.go b/plugins/ssh/authority/authoritytest/fake.go new file mode 100644 index 00000000000..a72403bb94c --- /dev/null +++ b/plugins/ssh/authority/authoritytest/fake.go @@ -0,0 +1,264 @@ +package authoritytest + +import ( + "context" + "fmt" + "sort" + "strconv" + "sync" + "testing" + + "golang.org/x/crypto/ssh" + + "github.com/cloudposse/atmos/plugins/ssh/authority" +) + +// FakeToken is the credential a Fake accepts for every use. +const FakeToken = "fake-authority-token-0001" + +// FakeCall is one call a Fake received. +type FakeCall struct { + // Op is "ensure" or "revoke". + Op string + Fingerprint string + Uses []authority.Use +} + +// Fake is an in-memory authority for tests of code that uses authorities. It checks the token, +// models per-use grants, records its calls, and can be told to fail. +type Fake struct { + name string + uses []authority.Use + + mu sync.Mutex + grants map[string]map[authority.Use]bool + enrollments map[string]map[authority.Use]string + calls []FakeCall + ensureErrs []error + revokeErrs []error + failOnUse map[authority.Use]error + seq int +} + +// NewFake returns a fake authority named name that supports uses, or both uses when none is given. +// FakeToken is accepted for every use. +func NewFake(name string, uses ...authority.Use) *Fake { + if len(uses) == 0 { + uses = []authority.Use{authority.UseAuthentication, authority.UseSigning} + } + f := &Fake{ + name: name, + uses: authority.NormalizeUses(uses), + grants: map[string]map[authority.Use]bool{}, + enrollments: map[string]map[authority.Use]string{}, + failOnUse: map[authority.Use]error{}, + } + f.Grant(FakeToken, f.uses...) + return f +} + +// Grant lets token enroll and revoke the given uses. A token that was never granted is rejected. +func (f *Fake) Grant(token string, uses ...authority.Use) { + f.mu.Lock() + defer f.mu.Unlock() + g := map[authority.Use]bool{} + for _, use := range uses { + g[use] = true + } + f.grants[token] = g +} + +// FailNextEnsure makes the next Ensure call return err before it enrolls anything. +func (f *Fake) FailNextEnsure(err error) { + f.mu.Lock() + defer f.mu.Unlock() + f.ensureErrs = append(f.ensureErrs, err) +} + +// FailNextRevoke makes the next Revoke call return err without withdrawing anything. +func (f *Fake) FailNextRevoke(err error) { + f.mu.Lock() + defer f.mu.Unlock() + f.revokeErrs = append(f.revokeErrs, err) +} + +// FailEnsureOnUse makes Ensure fail when it reaches use, after it enrolled the earlier uses. A nil +// err clears the failure. +func (f *Fake) FailEnsureOnUse(use authority.Use, err error) { + f.mu.Lock() + defer f.mu.Unlock() + if err == nil { + delete(f.failOnUse, use) + return + } + f.failOnUse[use] = err +} + +// Calls returns the calls received so far. +func (f *Fake) Calls() []FakeCall { + f.mu.Lock() + defer f.mu.Unlock() + return append([]FakeCall(nil), f.calls...) +} + +// CallCount counts the calls of kind op ("ensure" or "revoke"). +func (f *Fake) CallCount(op string) int { + n := 0 + for _, c := range f.Calls() { + if c.Op == op { + n++ + } + } + return n +} + +// Count returns how many enrollments the fake holds for key and use (0 or 1). +func (f *Fake) Count(key ssh.PublicKey, use authority.Use) int { + f.mu.Lock() + defer f.mu.Unlock() + if _, ok := f.enrollments[authority.Fingerprint(key)][use]; ok { + return 1 + } + return 0 +} + +// Enrolled lists the fingerprints that have at least one enrollment, in order. +func (f *Fake) Enrolled() []string { + f.mu.Lock() + defer f.mu.Unlock() + var out []string + for fp, byUse := range f.enrollments { + if len(byUse) > 0 { + out = append(out, fp) + } + } + sort.Strings(out) + return out +} + +// Name implements authority.Authority. +func (f *Fake) Name() string { return f.name } + +// Supports implements authority.Authority. +func (f *Fake) Supports() []authority.Use { return append([]authority.Use(nil), f.uses...) } + +func (f *Fake) check(operation, token string, use authority.Use) error { + grant, known := f.grants[token] + switch { + case !known: + return &authority.Error{Authority: f.name, Operation: operation, Err: authority.ErrUnauthorized, Detail: "unknown token"} + case use != "" && !grant[use]: + return &authority.Error{Authority: f.name, Operation: operation, Use: use, Err: authority.ErrMissingPermission, Permission: "enroll:" + string(use)} + } + return nil +} + +// Ensure implements authority.Authority. +func (f *Fake) Ensure(_ context.Context, credentials map[string]string, request authority.Request) (authority.Receipt, error) { + receipt := authority.NewReceipt(f.name, request) + if err := authority.ValidateRequest(f, request); err != nil { + return receipt, err + } + f.mu.Lock() + defer f.mu.Unlock() + uses := authority.NormalizeUses(request.Uses) + f.calls = append(f.calls, FakeCall{Op: "ensure", Fingerprint: receipt.Fingerprint, Uses: uses}) + if len(f.ensureErrs) > 0 { + err := f.ensureErrs[0] + f.ensureErrs = f.ensureErrs[1:] + return receipt, err + } + token := credentials[authority.CredentialToken] + if err := f.check("ensure", token, ""); err != nil { + return receipt, err + } + receipt.Subject = "fake-user" + byUse := f.enrollments[receipt.Fingerprint] + if byUse == nil { + byUse = map[authority.Use]string{} + f.enrollments[receipt.Fingerprint] = byUse + } + for _, use := range uses { + if err := f.check("ensure", token, use); err != nil { + return receipt, err + } + if err := f.failOnUse[use]; err != nil { + return receipt, err + } + id, ok := byUse[use] + if !ok { + f.seq++ + id = "fake-" + strconv.Itoa(f.seq) + byUse[use] = id + } + receipt.References[use] = id + receipt.Uses = append(receipt.Uses, use) + } + return receipt, nil +} + +// Revoke implements authority.Authority. +func (f *Fake) Revoke(_ context.Context, credentials map[string]string, receipt authority.Receipt) error { + f.mu.Lock() + defer f.mu.Unlock() + f.calls = append(f.calls, FakeCall{Op: "revoke", Fingerprint: receipt.Fingerprint, Uses: receipt.EnrolledUses()}) + if len(f.revokeErrs) > 0 { + err := f.revokeErrs[0] + f.revokeErrs = f.revokeErrs[1:] + return err + } + if len(receipt.References) == 0 { + return nil + } + token := credentials[authority.CredentialToken] + if err := f.check("revoke", token, ""); err != nil { + return err + } + for use, id := range receipt.References { + if err := f.check("revoke", token, use); err != nil { + return err + } + if f.enrollments[receipt.Fingerprint][use] == id { + delete(f.enrollments[receipt.Fingerprint], use) + } + } + return nil +} + +// Environment wires the fake to the conformance suite. +func (f *Fake) Environment() *Environment { + limited := func(use authority.Use) string { return "fake-limited-" + string(use) } + for _, use := range f.uses { + var others []authority.Use + for _, o := range f.uses { + if o != use { + others = append(others, o) + } + } + f.Grant(limited(use), others...) + } + return &Environment{ + Authority: f, + Credentials: map[string]string{authority.CredentialToken: FakeToken}, + Invalid: map[string]string{authority.CredentialToken: "fake-unknown-token"}, + Restricted: func(use authority.Use) map[string]string { + return map[string]string{authority.CredentialToken: limited(use)} + }, + Permission: func(use authority.Use) string { return fmt.Sprintf("enroll:%s", use) }, + Seed: func(t *testing.T, key ssh.PublicKey, use authority.Use) string { + t.Helper() + f.mu.Lock() + defer f.mu.Unlock() + fp := authority.Fingerprint(key) + if f.enrollments[fp] == nil { + f.enrollments[fp] = map[authority.Use]string{} + } + f.seq++ + id := "fake-" + strconv.Itoa(f.seq) + f.enrollments[fp][use] = id + return id + }, + Enrollments: f.Count, + Secrets: []string{FakeToken, "fake-unknown-token"}, + } +} diff --git a/plugins/ssh/authority/authoritytest/githubfake.go b/plugins/ssh/authority/authoritytest/githubfake.go new file mode 100644 index 00000000000..0363983c94d --- /dev/null +++ b/plugins/ssh/authority/authoritytest/githubfake.go @@ -0,0 +1,443 @@ +package authoritytest + +import ( + "encoding/json" + "fmt" + "io" + "net/http" + "net/http/httptest" + "sort" + "strconv" + "strings" + "sync" + "testing" + + "golang.org/x/crypto/ssh" + + "github.com/cloudposse/atmos/plugins/ssh/authority" +) + +// LoggedRequest is one request the fake GitHub server received. The Authorization header is not +// stored; HasBearer says whether a bearer token was sent. +type LoggedRequest struct { + Method string + Path string + Query string + Header http.Header + Body string + HasBearer bool +} + +// KeyRecord is a key stored on the fake server. +type KeyRecord struct { + ID int64 + Login string + // Use is authority.UseSigning or authority.UseAuthentication. + Use authority.Use + // Key is the key in authorized_keys form, as stored. + Key string + Title string +} + +// Failure makes the fake server answer with an error instead of handling a request. +type Failure struct { + // Method and PathPrefix select the requests. An empty Method matches any method. + Method string + PathPrefix string + // Status and Body are the answer. Header adds response headers. + Status int + Body string + Header http.Header + // Times is how many matching requests fail. Zero means one, and a negative number means all. + Times int +} + +type fakeToken struct { + login string + scopes []string +} + +// GitHubServer is an in-memory fake of the GitHub key-management API. It models token scopes, +// paginates, rejects requests without a User-Agent, and can be told to fail. +type GitHubServer struct { + *httptest.Server + + // PageSize caps how many keys one page returns. Zero means the client's per_page. + PageSize int + // MissingScopeStatus is the status for a token without the scope: 404 (the default) or 403. + MissingScopeStatus int + + mu sync.Mutex + tokens map[string]fakeToken + keys []KeyRecord + nextID int64 + requests []LoggedRequest + failures []*Failure +} + +// NewGitHubServer starts a fake server and stops it when the test ends. +func NewGitHubServer(t *testing.T) *GitHubServer { + t.Helper() + s := &GitHubServer{tokens: map[string]fakeToken{}, nextID: 1000, MissingScopeStatus: http.StatusNotFound} + s.Server = httptest.NewServer(http.HandlerFunc(s.handle)) + t.Cleanup(s.Close) + return s +} + +// AddToken registers a classic token that belongs to login and holds scopes. +func (s *GitHubServer) AddToken(token, login string, scopes ...string) { + s.mu.Lock() + defer s.mu.Unlock() + s.tokens[token] = fakeToken{login: login, scopes: scopes} +} + +// AddKey stores a key on an account and returns its ID. +func (s *GitHubServer) AddKey(login string, use authority.Use, key ssh.PublicKey, title string) int64 { + s.mu.Lock() + defer s.mu.Unlock() + return s.addKeyLocked(login, use, authority.AuthorizedKey(key), title) +} + +func (s *GitHubServer) addKeyLocked(login string, use authority.Use, authorized, title string) int64 { + s.nextID++ + s.keys = append(s.keys, KeyRecord{ID: s.nextID, Login: login, Use: use, Key: authorized, Title: title}) + return s.nextID +} + +// Keys returns the keys stored for login and use. +func (s *GitHubServer) Keys(login string, use authority.Use) []KeyRecord { + s.mu.Lock() + defer s.mu.Unlock() + var out []KeyRecord + for _, k := range s.keys { + if k.Login == login && k.Use == use { + out = append(out, k) + } + } + return out +} + +// KeyCount counts the stored keys, on any account, that match key for use. +func (s *GitHubServer) KeyCount(key ssh.PublicKey, use authority.Use) int { + s.mu.Lock() + defer s.mu.Unlock() + n := 0 + for _, k := range s.keys { + if k.Use == use && sameKeyBody(k.Key, authority.AuthorizedKey(key)) { + n++ + } + } + return n +} + +// Fail queues a failure. +func (s *GitHubServer) Fail(f Failure) { + s.mu.Lock() + defer s.mu.Unlock() + if f.Times == 0 { + f.Times = 1 + } + s.failures = append(s.failures, &f) +} + +// Requests returns a copy of the request log. +func (s *GitHubServer) Requests() []LoggedRequest { + s.mu.Lock() + defer s.mu.Unlock() + return append([]LoggedRequest(nil), s.requests...) +} + +// ResetRequests clears the request log. +func (s *GitHubServer) ResetRequests() { + s.mu.Lock() + defer s.mu.Unlock() + s.requests = nil +} + +// LogText renders the request log as text for leak checks. It includes every header except +// Authorization. +func (s *GitHubServer) LogText() string { + var b strings.Builder + for _, r := range s.Requests() { + fmt.Fprintf(&b, "%s %s?%s %v %s\n", r.Method, r.Path, r.Query, r.Header, r.Body) + } + return b.String() +} + +var scopeFamilies = map[authority.Use]string{ + authority.UseSigning: "ssh_signing_key", + authority.UseAuthentication: "public_key", +} + +var scopeLevels = map[string]int{"read": 1, "write": 2, "admin": 3} + +// ScopesFor returns the scopes that grant at least read (write=false) or write (write=true) on use. +func ScopesFor(use authority.Use, write bool) []string { + family := scopeFamilies[use] + if write { + return []string{"admin:" + family, "write:" + family} + } + return []string{"admin:" + family, "write:" + family, "read:" + family} +} + +func hasScope(scopes []string, use authority.Use, level int) bool { + family := scopeFamilies[use] + for _, s := range scopes { + prefix, rest, _ := strings.Cut(s, ":") + if rest == family && scopeLevels[prefix] >= level { + return true + } + } + return false +} + +func sameKeyBody(a, b string) bool { + fa, fb := strings.Fields(a), strings.Fields(b) + return len(fa) >= 2 && len(fb) >= 2 && fa[0] == fb[0] && fa[1] == fb[1] +} + +func (s *GitHubServer) handle(w http.ResponseWriter, r *http.Request) { + body, _ := io.ReadAll(r.Body) + auth := r.Header.Get("Authorization") + header := r.Header.Clone() + header.Del("Authorization") + s.mu.Lock() + s.requests = append(s.requests, LoggedRequest{ + Method: r.Method, Path: r.URL.Path, Query: r.URL.RawQuery, Header: header, + Body: string(body), HasBearer: strings.HasPrefix(auth, "Bearer "), + }) + failure := s.matchFailureLocked(r) + s.mu.Unlock() + + if r.Header.Get("User-Agent") == "" { + writeJSON(w, http.StatusForbidden, nil, map[string]string{"message": "Request forbidden by administrative rules. Please make sure your request has a User-Agent header."}) + return + } + if failure != nil { + for k, v := range failure.Header { + w.Header()[k] = v + } + w.WriteHeader(failure.Status) + _, _ = io.WriteString(w, failure.Body) + return + } + s.serve(w, r, auth, body) +} + +func (s *GitHubServer) matchFailureLocked(r *http.Request) *Failure { + for _, f := range s.failures { + if f.Times == 0 || (f.Method != "" && f.Method != r.Method) || !strings.HasPrefix(r.URL.Path, f.PathPrefix) { + continue + } + if f.Times > 0 { + f.Times-- + } + out := *f + return &out + } + return nil +} + +func writeJSON(w http.ResponseWriter, status int, header http.Header, v any) { + for k, vals := range header { + w.Header()[k] = vals + } + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(status) + if v != nil { + _ = json.NewEncoder(w).Encode(v) + } +} + +func (s *GitHubServer) serve(w http.ResponseWriter, r *http.Request, auth string, body []byte) { + token, ok := strings.CutPrefix(auth, "Bearer ") + s.mu.Lock() + tok, known := s.tokens[token] + s.mu.Unlock() + if !ok || !known { + writeJSON(w, http.StatusUnauthorized, nil, map[string]string{"message": "Bad credentials"}) + return + } + scopeHeaders := func(use authority.Use, level int) http.Header { + h := http.Header{} + h.Set("X-OAuth-Scopes", strings.Join(tok.scopes, ", ")) + if use != "" { + h.Set("X-Accepted-OAuth-Scopes", strings.Join(ScopesFor(use, level == 2), ", ")) + } + return h + } + if r.URL.Path == "/user" && r.Method == http.MethodGet { + writeJSON(w, http.StatusOK, scopeHeaders("", 0), map[string]string{"login": tok.login}) + return + } + use, id, ok := parseKeyPath(r.URL.Path) + if !ok { + writeJSON(w, http.StatusNotFound, nil, map[string]string{"message": "Not Found"}) + return + } + level := 1 + if r.Method != http.MethodGet { + level = 2 + } + h := scopeHeaders(use, level) + if !hasScope(tok.scopes, use, level) { + writeJSON(w, s.MissingScopeStatus, h, map[string]string{"message": "Not Found"}) + return + } + switch { + case r.Method == http.MethodGet && id == 0: + s.list(w, r, tok.login, use, h) + case r.Method == http.MethodPost && id == 0: + s.create(w, tok.login, use, body, h) + case r.Method == http.MethodDelete && id != 0: + s.remove(w, tok.login, use, id, h) + default: + writeJSON(w, http.StatusNotFound, h, map[string]string{"message": "Not Found"}) + } +} + +func parseKeyPath(p string) (authority.Use, int64, bool) { + var use authority.Use + var rest string + switch { + case strings.HasPrefix(p, "/user/ssh_signing_keys"): + use, rest = authority.UseSigning, strings.TrimPrefix(p, "/user/ssh_signing_keys") + case strings.HasPrefix(p, "/user/keys"): + use, rest = authority.UseAuthentication, strings.TrimPrefix(p, "/user/keys") + default: + return "", 0, false + } + if rest == "" { + return use, 0, true + } + id, err := strconv.ParseInt(strings.TrimPrefix(rest, "/"), 10, 64) + return use, id, err == nil && strings.HasPrefix(rest, "/") +} + +func (s *GitHubServer) list(w http.ResponseWriter, r *http.Request, login string, use authority.Use, h http.Header) { + size := 30 + if n, err := strconv.Atoi(r.URL.Query().Get("per_page")); err == nil && n > 0 { + size = n + } + if s.PageSize > 0 && s.PageSize < size { + size = s.PageSize + } + page := 1 + if n, err := strconv.Atoi(r.URL.Query().Get("page")); err == nil && n > 0 { + page = n + } + mine := s.Keys(login, use) + sort.Slice(mine, func(i, j int) bool { return mine[i].ID < mine[j].ID }) + start, end := min((page-1)*size, len(mine)), min(page*size, len(mine)) + out := make([]map[string]any, 0, end-start) + for _, k := range mine[start:end] { + out = append(out, map[string]any{"id": k.ID, "key": k.Key, "title": k.Title}) + } + if end < len(mine) { + next := fmt.Sprintf("%s%s?per_page=%d&page=%d", s.URL, r.URL.Path, size, page+1) + h.Set("Link", fmt.Sprintf(`<%s>; rel="next"`, next)) + } + writeJSON(w, http.StatusOK, h, out) +} + +func (s *GitHubServer) create(w http.ResponseWriter, login string, use authority.Use, body []byte, h http.Header) { + invalid := func(message string) { + writeJSON(w, http.StatusUnprocessableEntity, h, map[string]any{ + "message": "Validation Failed", + "errors": []map[string]string{{"message": message}}, + }) + } + var in struct { + Key string `json:"key"` + Title string `json:"title"` + } + if json.Unmarshal(body, &in) != nil { + invalid("key is invalid") + return + } + if _, _, _, _, err := ssh.ParseAuthorizedKey([]byte(in.Key)); err != nil { + invalid("key is invalid") + return + } + s.mu.Lock() + for _, k := range s.keys { + if k.Use == use && sameKeyBody(k.Key, in.Key) { + s.mu.Unlock() + invalid("key is already in use") + return + } + } + id := s.addKeyLocked(login, use, in.Key, in.Title) + s.mu.Unlock() + writeJSON(w, http.StatusCreated, h, map[string]any{"id": id, "key": in.Key, "title": in.Title}) +} + +func (s *GitHubServer) remove(w http.ResponseWriter, login string, use authority.Use, id int64, h http.Header) { + s.mu.Lock() + defer s.mu.Unlock() + for i, k := range s.keys { + if k.ID == id && k.Login == login && k.Use == use { + s.keys = append(s.keys[:i], s.keys[i+1:]...) + w.WriteHeader(http.StatusNoContent) + return + } + } + writeJSON(w, http.StatusNotFound, h, map[string]string{"message": "Not Found"}) +} + +// ReadScope and WriteScope name the least scope that grants read or write access to use's keys. +func ReadScope(use authority.Use) string { return "read:" + scopeFamilies[use] } + +// WriteScope names the least scope that grants write access to use's keys. +func WriteScope(use authority.Use) string { return "write:" + scopeFamilies[use] } + +// Tokens the Environment registers. +const ( + FullToken = "ghp_FULLaccessTOKEN0123456789abcdef" + RevokedToken = "ghp_REVOKEDtoken9876543210" + Login = "octocat" +) + +// LimitedToken returns the token that holds every scope except those for use. +func LimitedToken(use authority.Use) string { + return "ghp_LIMITED" + string(use) + "TOKEN0123456789" +} + +// Environment wires the server to an authority built against it, for the conformance suite. It +// registers a full-scope token, one token per use that lacks that use's scopes, and hooks that +// look at the server's state. +func (s *GitHubServer) Environment(a authority.Authority) *Environment { + uses := []authority.Use{authority.UseAuthentication, authority.UseSigning} + var all []string + for _, use := range uses { + all = append(all, ScopesFor(use, true)...) + } + s.AddToken(FullToken, Login, all...) + secrets := []string{FullToken, RevokedToken} + for _, use := range uses { + var scopes []string + for _, other := range uses { + if other != use { + scopes = append(scopes, ScopesFor(other, true)...) + } + } + s.AddToken(LimitedToken(use), Login, scopes...) + secrets = append(secrets, LimitedToken(use)) + } + return &Environment{ + Authority: a, + Credentials: map[string]string{authority.CredentialToken: FullToken}, + Invalid: map[string]string{authority.CredentialToken: RevokedToken}, + Restricted: func(use authority.Use) map[string]string { + return map[string]string{authority.CredentialToken: LimitedToken(use)} + }, + Permission: ReadScope, + Seed: func(t *testing.T, key ssh.PublicKey, use authority.Use) string { + t.Helper() + return strconv.FormatInt(s.AddKey(Login, use, key, "pre-existing"), 10) + }, + Enrollments: s.KeyCount, + Log: s.LogText, + Secrets: secrets, + } +} diff --git a/plugins/ssh/authority/authoritytest/suite.go b/plugins/ssh/authority/authoritytest/suite.go new file mode 100644 index 00000000000..2fd72009212 --- /dev/null +++ b/plugins/ssh/authority/authoritytest/suite.go @@ -0,0 +1,260 @@ +package authoritytest + +import ( + "context" + "encoding/json" + "errors" + "strings" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "golang.org/x/crypto/ssh" + + "github.com/cloudposse/atmos/plugins/ssh/authority" +) + +// Harness builds a fresh Environment for each conformance check. +type Harness func(t *testing.T) *Environment + +// Run checks that an authority honors the contract in authority.Authority. +func Run(t *testing.T, harness Harness) { + t.Helper() + checks := []struct { + name string + run func(*testing.T, *Environment) + }{ + {"EnsureIsIdempotent", checkEnsureIdempotent}, + {"UsesAreEnrolledSeparately", checkUsesSeparate}, + {"RevokeIsIdempotent", checkRevokeIdempotent}, + {"RevokeOneUseLeavesTheOther", checkRevokeOne}, + {"MissingPermissionNamesIt", checkPermission}, + {"InvalidCredentialIsUnauthorized", checkInvalid}, + {"ExistingKeyIsAdopted", checkAdoption}, + {"UnsupportedUseIsRejected", checkUnsupported}, + {"NothingLeaksTheSecret", checkNoLeak}, + } + for _, c := range checks { + t.Run(c.name, func(t *testing.T) { c.run(t, harness(t)) }) + } +} + +func request(key ssh.PublicKey, uses ...authority.Use) authority.Request { + return authority.Request{KeyName: "ops", Key: key, Uses: uses, Title: "ops@host (Atmos)"} +} + +func ensure(t *testing.T, env *Environment, req authority.Request) authority.Receipt { + t.Helper() + receipt, err := env.Authority.Ensure(context.Background(), env.Credentials, req) + require.NoError(t, err) + return receipt +} + +func revoke(t *testing.T, env *Environment, receipt authority.Receipt) { + t.Helper() + require.NoError(t, env.Authority.Revoke(context.Background(), env.Credentials, receipt)) +} + +func count(t *testing.T, env *Environment, key ssh.PublicKey, use authority.Use, want int) { + t.Helper() + if env.Enrollments != nil { + assert.Equal(t, want, env.Enrollments(key, use), "enrollments of %s", use) + } +} + +// withoutCreated clears the issue time, which differs between two calls. +func withoutCreated(r authority.Receipt) authority.Receipt { + r.Created = time.Time{} + return r +} + +func checkEnsureIdempotent(t *testing.T, env *Environment) { + key := NewKey(t) + uses := env.Authority.Supports() + first := ensure(t, env, request(key, uses...)) + second := ensure(t, env, request(key, uses...)) + + assert.Equal(t, env.Authority.Name(), first.Authority) + assert.Equal(t, "ops", first.KeyName) + assert.Equal(t, authority.Fingerprint(key), first.Fingerprint) + assert.Equal(t, authority.AuthorizedKey(key), first.PublicKey) + assert.True(t, first.ExpiresAt.IsZero() || first.ExpiresAt.After(first.Created)) + assert.Equal(t, authority.NormalizeUses(uses), authority.NormalizeUses(first.Uses)) + assert.Equal(t, withoutCreated(first), withoutCreated(second), "second Ensure returns the same receipt") + for _, use := range uses { + count(t, env, key, use, 1) + } +} + +func checkUsesSeparate(t *testing.T, env *Environment) { + uses := authority.NormalizeUses(env.Authority.Supports()) + if len(uses) < 2 { + t.Skip("authority supports a single use") + } + key := NewKey(t) + first := ensure(t, env, request(key, uses[0])) + count(t, env, key, uses[0], 1) + count(t, env, key, uses[1], 0) + + both := ensure(t, env, request(key, uses...)) + assert.Equal(t, first.References[uses[0]], both.References[uses[0]], "the first enrollment is not disturbed") + for _, use := range uses { + count(t, env, key, use, 1) + } +} + +func checkRevokeIdempotent(t *testing.T, env *Environment) { + key := NewKey(t) + uses := env.Authority.Supports() + receipt := ensure(t, env, request(key, uses...)) + revoke(t, env, receipt) + revoke(t, env, receipt) + for _, use := range uses { + count(t, env, key, use, 0) + } + // A receipt for something never enrolled is also success. + revoke(t, env, ensureAndForget(t, env)) +} + +// ensureAndForget enrolls a key, revokes it, and returns the stale receipt. +func ensureAndForget(t *testing.T, env *Environment) authority.Receipt { + key := NewKey(t) + receipt := ensure(t, env, request(key, env.Authority.Supports()...)) + revoke(t, env, receipt) + return receipt +} + +func checkRevokeOne(t *testing.T, env *Environment) { + uses := authority.NormalizeUses(env.Authority.Supports()) + if len(uses) < 2 || env.Enrollments == nil { + t.Skip("needs two uses and a way to count enrollments") + } + key := NewKey(t) + receipt := ensure(t, env, request(key, uses...)) + + partial := receipt + partial.Uses = uses[:1] + partial.References = map[authority.Use]string{uses[0]: receipt.References[uses[0]]} + revoke(t, env, partial) + + count(t, env, key, uses[0], 0) + count(t, env, key, uses[1], 1) +} + +func checkPermission(t *testing.T, env *Environment) { + if env.Restricted == nil || env.Permission == nil { + t.Skip("authority has no permission model") + } + for _, use := range env.Authority.Supports() { + t.Run(string(use), func(t *testing.T) { + key := NewKey(t) + _, err := env.Authority.Ensure(context.Background(), env.Restricted(use), request(key, use)) + require.Error(t, err) + assert.ErrorIs(t, err, authority.ErrMissingPermission) + assert.Contains(t, err.Error(), env.Permission(use)) + var ae *authority.Error + require.ErrorAs(t, err, &ae) + assert.Equal(t, env.Permission(use), ae.Permission) + count(t, env, key, use, 0) + }) + } +} + +func checkInvalid(t *testing.T, env *Environment) { + if env.Invalid == nil { + t.Skip("authority has no credential check") + } + _, err := env.Authority.Ensure(context.Background(), env.Invalid, request(NewKey(t), env.Authority.Supports()...)) + require.Error(t, err) + assert.ErrorIs(t, err, authority.ErrUnauthorized) + _, err = env.Authority.Ensure(context.Background(), nil, request(NewKey(t), env.Authority.Supports()...)) + assert.ErrorIs(t, err, authority.ErrUnauthorized, "no credential at all") +} + +func checkAdoption(t *testing.T, env *Environment) { + if env.Seed == nil || env.Enrollments == nil { + t.Skip("authority cannot be pre-seeded") + } + key := NewKey(t) + uses := env.Authority.Supports() + ids := map[authority.Use]string{} + for _, use := range uses { + ids[use] = env.Seed(t, key, use) + } + receipt := ensure(t, env, request(key, uses...)) + for _, use := range uses { + assert.Equal(t, ids[use], receipt.References[use], "reference of the adopted %s key", use) + count(t, env, key, use, 1) + } +} + +func checkUnsupported(t *testing.T, env *Environment) { + _, err := env.Authority.Ensure(context.Background(), env.Credentials, request(NewKey(t), authority.Use("teleportation"))) + assert.ErrorIs(t, err, authority.ErrUnsupportedUse) + _, err = env.Authority.Ensure(context.Background(), env.Credentials, request(NewKey(t))) + assert.ErrorIs(t, err, authority.ErrInvalidRequest, "no uses") +} + +func checkNoLeak(t *testing.T, env *Environment) { + if len(env.Secrets) == 0 { + t.Skip("authority takes no secret") + } + var artifacts []string + key := NewKey(t) + uses := env.Authority.Supports() + receipt := ensure(t, env, request(key, uses...)) + artifacts = append(artifacts, mustJSON(t, receipt), receipt.Subject) + + record := func(err error) { + if err != nil { + artifacts = append(artifacts, err.Error(), errorsJoinText(err)) + } + } + if env.Invalid != nil { + _, err := env.Authority.Ensure(context.Background(), env.Invalid, request(NewKey(t), uses...)) + record(err) + record(env.Authority.Revoke(context.Background(), env.Invalid, receipt)) + } + if env.Restricted != nil { + for _, use := range uses { + _, err := env.Authority.Ensure(context.Background(), env.Restricted(use), request(NewKey(t), use)) + record(err) + } + } + revoke(t, env, receipt) + if env.Log != nil { + artifacts = append(artifacts, env.Log()) + } + + for _, secret := range env.Secrets { + require.NotEmpty(t, secret) + for _, text := range artifacts { + assert.NotContains(t, text, secret) + } + } +} + +func mustJSON(t *testing.T, v any) string { + t.Helper() + data, err := json.Marshal(v) + require.NoError(t, err) + return string(data) +} + +// errorsJoinText flattens a possibly joined error, including every wrapped message. +func errorsJoinText(err error) string { + var parts []string + for err != nil { + parts = append(parts, err.Error()) + var multi interface{ Unwrap() []error } + if errors.As(err, &multi) { + for _, e := range multi.Unwrap() { + parts = append(parts, errorsJoinText(e)) + } + break + } + err = errors.Unwrap(err) + } + return strings.Join(parts, "\n") +} diff --git a/plugins/ssh/authority/authoritytest/suite_test.go b/plugins/ssh/authority/authoritytest/suite_test.go new file mode 100644 index 00000000000..d8a1a7a8659 --- /dev/null +++ b/plugins/ssh/authority/authoritytest/suite_test.go @@ -0,0 +1,17 @@ +package authoritytest + +import ( + "testing" + + "github.com/cloudposse/atmos/plugins/ssh/authority" +) + +func TestSuiteAgainstFake(t *testing.T) { + Run(t, func(*testing.T) *Environment { return NewFake("fake").Environment() }) +} + +func TestSuiteAgainstSingleUseFake(t *testing.T) { + Run(t, func(*testing.T) *Environment { + return NewFake("single", authority.UseSigning).Environment() + }) +} diff --git a/plugins/ssh/authority/errors.go b/plugins/ssh/authority/errors.go new file mode 100644 index 00000000000..a39c509a9c3 --- /dev/null +++ b/plugins/ssh/authority/errors.go @@ -0,0 +1,98 @@ +package authority + +import ( + "errors" + "fmt" + "strings" + "time" +) + +// Sentinel errors. An *Error wraps one of the first group so callers can match with errors.Is. +var ( + // ErrUnauthorized means the authority rejected the credential, for example a bad token. + ErrUnauthorized = errors.New("credential rejected") + // ErrMissingPermission means the credential lacks a permission the operation needs. + ErrMissingPermission = errors.New("credential lacks a required permission") + // ErrKeyInUse means the key is already registered on another account. + ErrKeyInUse = errors.New("key is already in use on another account") + // ErrRateLimited means the authority is throttling requests. + ErrRateLimited = errors.New("rate limited") + // ErrUnexpectedStatus means the authority answered in a way the client does not understand. + ErrUnexpectedStatus = errors.New("unexpected response") + // ErrUnavailable means the authority could not be reached. + ErrUnavailable = errors.New("authority unreachable") + // ErrUnsupportedUse means the authority cannot vouch for the requested use. + ErrUnsupportedUse = errors.New("use not supported by this authority") + // ErrInvalidRequest means the request or a receipt is malformed. + ErrInvalidRequest = errors.New("invalid request") + + // ErrUnknownAuthority means no authority is registered under the name. + ErrUnknownAuthority = errors.New("unknown authority") + // ErrDuplicateAuthority means an authority is already registered under the name. + ErrDuplicateAuthority = errors.New("authority already registered") + + // ErrReceiptNotFound means no receipt exists for the key and authority. + ErrReceiptNotFound = errors.New("receipt not found") + // ErrReceiptCorrupt means a receipt file cannot be read. + ErrReceiptCorrupt = errors.New("receipt is corrupt") + // ErrReceiptCollision means two different keys map to the same receipt file. + ErrReceiptCollision = errors.New("receipt file belongs to another key") +) + +// Error is a typed failure from an authority. It never carries a credential, so it is safe to +// record and to render in a later status command. +type Error struct { + // Authority is the name of the authority that failed. + Authority string + // Operation is what was being attempted, such as "list" or "create". + Operation string + // Use is the use being enrolled or revoked, when it applies. + Use Use + // Permission names the permission or scope that is missing, when it applies. + Permission string + // Status is the HTTP status, when the authority speaks HTTP. + Status int + // RetryAfter is how long the authority asked the caller to wait, when known. + RetryAfter time.Duration + // Detail is extra context. It never contains the credential. + Detail string + // Err is the sentinel that classifies the failure. + Err error +} + +// Error implements the error interface. +func (e *Error) Error() string { + var b strings.Builder + if e.Authority != "" { + b.WriteString(e.Authority) + b.WriteString(": ") + } + if e.Operation != "" { + b.WriteString(e.Operation) + if e.Use != "" { + b.WriteString(" ") + b.WriteString(string(e.Use)) + } + b.WriteString(": ") + } + if e.Err != nil { + b.WriteString(e.Err.Error()) + } + if e.Permission != "" { + fmt.Fprintf(&b, " (needs %s)", e.Permission) + } + if e.Status != 0 { + fmt.Fprintf(&b, " [HTTP %d]", e.Status) + } + if e.RetryAfter > 0 { + fmt.Fprintf(&b, " [retry after %s]", e.RetryAfter) + } + if e.Detail != "" { + b.WriteString(": ") + b.WriteString(e.Detail) + } + return b.String() +} + +// Unwrap returns the classifying sentinel. +func (e *Error) Unwrap() error { return e.Err } diff --git a/plugins/ssh/authority/github/client.go b/plugins/ssh/authority/github/client.go new file mode 100644 index 00000000000..1ae4d36d0d3 --- /dev/null +++ b/plugins/ssh/authority/github/client.go @@ -0,0 +1,250 @@ +package github + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "fmt" + "io" + "net/http" + "net/url" + "regexp" + "strconv" + "strings" + "time" + + "github.com/cloudposse/atmos/plugins/ssh/authority" +) + +const ( + // DefaultBaseURL is the GitHub API address. + DefaultBaseURL = "https://api.github.com" + // DefaultUserAgent identifies the plugin. GitHub rejects requests without a User-Agent. + DefaultUserAgent = "atmos-ssh-plugin" + + apiVersion = "2022-11-28" + requestTimeout = 30 * time.Second + maxBodyBytes = 4 << 20 + maxPages = 1000 + perPage = 100 +) + +var nextLink = regexp.MustCompile(`<([^>]*)>\s*;\s*rel="next"`) + +// client makes authenticated GitHub API calls. The token lives only here and in the request +// header; it is scrubbed from anything that becomes an error message. +type client struct { + http *http.Client + base *url.URL + token string + agent string + timeout time.Duration +} + +// call describes one request for error reporting. +type call struct { + operation string + use authority.Use + permission string +} + +// response is a completed request. +type response struct { + status int + header http.Header + body []byte +} + +func (c *client) send(ctx context.Context, method, endpoint string, query url.Values, payload any) (*response, error) { + var reader io.Reader + if payload != nil { + data, err := json.Marshal(payload) + if err != nil { + return nil, fmt.Errorf("encode request: %w", err) + } + reader = bytes.NewReader(data) + } + target := *c.base + target.Path = strings.TrimRight(c.base.Path, "/") + endpoint + target.RawQuery = query.Encode() + // The caller's client may have no timeout, so every request carries its own. + ctx, cancel := context.WithTimeout(ctx, c.timeout) + defer cancel() + req, err := http.NewRequestWithContext(ctx, method, target.String(), reader) + if err != nil { + return nil, fmt.Errorf("build request: %w", err) + } + req.Header.Set("Authorization", "Bearer "+c.token) + req.Header.Set("Accept", "application/vnd.github+json") + req.Header.Set("X-GitHub-Api-Version", apiVersion) + req.Header.Set("User-Agent", c.agent) + if payload != nil { + req.Header.Set("Content-Type", "application/json") + } + resp, err := c.http.Do(req) + if err != nil { + return nil, errors.New(c.scrub(err.Error())) + } + defer resp.Body.Close() + body, err := io.ReadAll(io.LimitReader(resp.Body, maxBodyBytes)) + if err != nil { + return nil, errors.New(c.scrub(err.Error())) + } + return &response{status: resp.StatusCode, header: resp.Header, body: body}, nil +} + +// do sends a request and turns a failed status into a typed error. +func (c *client) do(ctx context.Context, info call, method, endpoint string, query url.Values, payload any) (*response, error) { + resp, err := c.send(ctx, method, endpoint, query, payload) + if err != nil { + return nil, &authority.Error{Authority: Name, Operation: info.operation, Use: info.use, Err: authority.ErrUnavailable, Detail: err.Error()} + } + if resp.status >= 200 && resp.status < 300 { + return resp, nil + } + return resp, c.classify(info, method, resp) +} + +// classify maps a failed response onto the error sentinels. +func (c *client) classify(info call, method string, resp *response) error { + e := &authority.Error{ + Authority: Name, Operation: info.operation, Use: info.use, + Status: resp.status, Detail: c.message(resp), + } + switch { + case resp.status == http.StatusUnauthorized: + e.Err = authority.ErrUnauthorized + case resp.status == http.StatusTooManyRequests, resp.status == http.StatusForbidden && rateLimited(resp): + e.Err = authority.ErrRateLimited + e.RetryAfter = retryAfter(resp.header) + case resp.status == http.StatusForbidden, resp.status == http.StatusNotFound: + e.Err = authority.ErrMissingPermission + e.Permission = info.permission + e.Detail = joinDetail(e.Detail, scopeDetail(resp.header)) + case resp.status == http.StatusUnprocessableEntity && method == http.MethodPost: + e.Err = authority.ErrKeyInUse + default: + e.Err = authority.ErrUnexpectedStatus + } + return e +} + +func joinDetail(parts ...string) string { + var out []string + for _, p := range parts { + if p != "" { + out = append(out, p) + } + } + return strings.Join(out, "; ") +} + +// message extracts GitHub's explanation from an error body, with the token scrubbed. +func (c *client) message(resp *response) string { + var parsed struct { + Message string `json:"message"` + Errors []struct { + Message string `json:"message"` + } `json:"errors"` + } + text := strings.TrimSpace(string(resp.body)) + if json.Unmarshal(resp.body, &parsed) == nil && parsed.Message != "" { + text = parsed.Message + for _, e := range parsed.Errors { + if e.Message != "" { + text += ": " + e.Message + } + } + } + if len(text) > 300 { + text = text[:300] + "..." + } + return c.scrub(text) +} + +// scrub removes the token from text. +func (c *client) scrub(text string) string { + if c.token == "" { + return text + } + return strings.ReplaceAll(text, c.token, "[redacted]") +} + +func rateLimited(resp *response) bool { + if resp.header.Get("X-RateLimit-Remaining") == "0" || resp.header.Get("Retry-After") != "" { + return true + } + return strings.Contains(strings.ToLower(string(resp.body)), "rate limit") +} + +func retryAfter(h http.Header) time.Duration { + if secs, err := strconv.Atoi(h.Get("Retry-After")); err == nil && secs > 0 { + return time.Duration(secs) * time.Second + } + if reset, err := strconv.ParseInt(h.Get("X-RateLimit-Reset"), 10, 64); err == nil { + if d := time.Until(time.Unix(reset, 0)); d > 0 { + return d + } + } + return 0 +} + +// scopeDetail reports the scopes GitHub says the endpoint accepts and the token has. +func scopeDetail(h http.Header) string { + accepted, granted := h.Get("X-Accepted-OAuth-Scopes"), h.Get("X-OAuth-Scopes") + if accepted == "" && granted == "" { + return "" + } + return fmt.Sprintf("endpoint accepts [%s]; token has [%s]", accepted, granted) +} + +// lacksScope reports whether GitHub's scope headers show that the token has none of the scopes +// the endpoint accepts. It is false when the headers are absent, as for fine-grained tokens. +func lacksScope(h http.Header) bool { + accepted := splitScopes(h.Get("X-Accepted-OAuth-Scopes")) + if len(accepted) == 0 { + return false + } + if _, present := h["X-Oauth-Scopes"]; !present { + return false + } + have := map[string]bool{} + for _, s := range splitScopes(h.Get("X-OAuth-Scopes")) { + have[s] = true + } + for _, s := range accepted { + if have[s] { + return false + } + } + return true +} + +func splitScopes(header string) []string { + var out []string + for _, s := range strings.Split(header, ",") { + if s = strings.TrimSpace(s); s != "" { + out = append(out, s) + } + } + return out +} + +// nextPage returns the page number the Link header points at, or 0 when there is no next page. +// Only the page number is used, so a Link to another host is never followed. +func nextPage(h http.Header, current int) int { + m := nextLink.FindStringSubmatch(h.Get("Link")) + if m == nil { + return 0 + } + u, err := url.Parse(m[1]) + if err != nil { + return 0 + } + page, err := strconv.Atoi(u.Query().Get("page")) + if err != nil || page <= current { + return 0 + } + return page +} diff --git a/plugins/ssh/authority/github/github.go b/plugins/ssh/authority/github/github.go new file mode 100644 index 00000000000..afc9731b570 --- /dev/null +++ b/plugins/ssh/authority/github/github.go @@ -0,0 +1,271 @@ +// Package github is the authority that registers a key on a GitHub user account, as a signing +// key, an authentication key, or both. +package github + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "net/http" + "net/url" + "sort" + "strconv" + "strings" + + "github.com/cloudposse/atmos/plugins/ssh/authority" +) + +// Name is the registry key of the GitHub authority. +const Name = "github" + +// Factory builds the GitHub authority for a registry. +var Factory = authority.Factory{ + Name: Name, + New: func(o authority.Options) (authority.Authority, error) { return New(o) }, +} + +// Scopes GitHub requires for key management. +const ( + ScopeSigningRead = "read:ssh_signing_key" + ScopeSigningWrite = "write:ssh_signing_key" + ScopeAuthRead = "read:public_key" + ScopeAuthWrite = "write:public_key" + defaultKeyTitle = "atmos-ssh" + operationLogin = "get user" + operationList = "list keys" + operationCreate = "add key" + operationDelete = "remove key" + maxPagesExceededBy = "too many pages of keys" +) + +type endpoint struct { + path string + readScope string + writeScope string +} + +var endpoints = map[authority.Use]endpoint{ + authority.UseSigning: {path: "/user/ssh_signing_keys", readScope: ScopeSigningRead, writeScope: ScopeSigningWrite}, + authority.UseAuthentication: {path: "/user/keys", readScope: ScopeAuthRead, writeScope: ScopeAuthWrite}, +} + +// Authority registers keys on the account the token belongs to. +type Authority struct { + httpClient *http.Client + base *url.URL + agent string +} + +// New builds the authority. Options.HTTPClient and Options.BaseURL are injectable; the defaults +// are a plain client and https://api.github.com. +func New(options authority.Options) (*Authority, error) { + raw := options.BaseURL + if raw == "" { + raw = DefaultBaseURL + } + base, err := url.Parse(raw) + if err != nil || (base.Scheme != "http" && base.Scheme != "https") || base.Host == "" { + return nil, fmt.Errorf("%w: base URL %q", authority.ErrInvalidRequest, raw) + } + agent := options.UserAgent + if agent == "" { + agent = DefaultUserAgent + } + return &Authority{httpClient: noWriteRedirects(options.HTTPClient), base: base, agent: agent}, nil +} + +// noWriteRedirects returns a copy of hc that never follows a redirect for a request that is not a +// GET, so a token and a request body cannot be replayed at an address GitHub did not intend. It does +// not rely on the caller's client for this. +func noWriteRedirects(hc *http.Client) *http.Client { + if hc == nil { + hc = &http.Client{} + } + cp := *hc + inner := hc.CheckRedirect + cp.CheckRedirect = func(req *http.Request, via []*http.Request) error { + if req.Method != http.MethodGet { + return http.ErrUseLastResponse + } + if inner != nil { + return inner(req, via) + } + if len(via) >= 10 { + return http.ErrUseLastResponse + } + return nil + } + return &cp +} + +// Name implements authority.Authority. +func (*Authority) Name() string { return Name } + +// Supports implements authority.Authority. +func (*Authority) Supports() []authority.Use { + return []authority.Use{authority.UseAuthentication, authority.UseSigning} +} + +func (a *Authority) newClient(operation string, credentials map[string]string) (*client, error) { + token := strings.TrimSpace(credentials[authority.CredentialToken]) + if token == "" { + return nil, &authority.Error{Authority: Name, Operation: operation, Err: authority.ErrUnauthorized, Detail: "no token supplied"} + } + return &client{http: a.httpClient, base: a.base, token: token, agent: a.agent, timeout: requestTimeout}, nil +} + +type remoteKey struct { + ID int64 `json:"id"` + Key string `json:"key"` + Title string `json:"title"` +} + +// Ensure implements authority.Authority. A key already on the account is adopted. When it fails +// part way it returns the receipt of the uses that were enrolled. +func (a *Authority) Ensure(ctx context.Context, credentials map[string]string, request authority.Request) (authority.Receipt, error) { + receipt := authority.NewReceipt(Name, request) + if err := authority.ValidateRequest(a, request); err != nil { + return receipt, err + } + c, err := a.newClient("ensure", credentials) + if err != nil { + return receipt, err + } + login, err := c.login(ctx) + if err != nil { + return receipt, err + } + receipt.Subject = login + title := request.Title + if title == "" { + title = defaultKeyTitle + } + for _, use := range authority.NormalizeUses(request.Uses) { + id, err := c.ensureKey(ctx, use, authority.AuthorizedKey(request.Key), title) + if err != nil { + return receipt, err + } + receipt.References[use] = id + receipt.Uses = append(receipt.Uses, use) + } + return receipt, nil +} + +func (c *client) login(ctx context.Context) (string, error) { + resp, err := c.do(ctx, call{operation: operationLogin}, http.MethodGet, "/user", nil, nil) + if err != nil { + return "", err + } + var user struct { + Login string `json:"login"` + } + if err := json.Unmarshal(resp.body, &user); err != nil || user.Login == "" { + return "", &authority.Error{Authority: Name, Operation: operationLogin, Status: resp.status, Err: authority.ErrUnexpectedStatus, Detail: "response has no login"} + } + return user.Login, nil +} + +// ensureKey returns the ID of the key on the account for the use, creating it when absent. +func (c *client) ensureKey(ctx context.Context, use authority.Use, authorized, title string) (string, error) { + ep := endpoints[use] + if id, found, err := c.findKey(ctx, use, ep, authorized); err != nil || found { + return id, err + } + info := call{operation: operationCreate, use: use, permission: ep.writeScope} + resp, err := c.do(ctx, info, http.MethodPost, ep.path, nil, map[string]string{"key": authorized, "title": title}) + if err != nil { + var ae *authority.Error + if errors.As(err, &ae) && errors.Is(err, authority.ErrKeyInUse) { + // The key may have appeared on this account since the listing. Adopt it if so. + if id, found, lerr := c.findKey(ctx, use, ep, authorized); lerr == nil && found { + return id, nil + } + ae.Detail = joinDetail("the key is registered on another account", ae.Detail) + } + return "", err + } + var created remoteKey + if err := json.Unmarshal(resp.body, &created); err != nil || created.ID == 0 { + return "", &authority.Error{Authority: Name, Operation: operationCreate, Use: use, Status: resp.status, Err: authority.ErrUnexpectedStatus, Detail: "response has no key ID"} + } + return strconv.FormatInt(created.ID, 10), nil +} + +// findKey looks for the key among the account's keys, following pagination. +func (c *client) findKey(ctx context.Context, use authority.Use, ep endpoint, authorized string) (string, bool, error) { + info := call{operation: operationList, use: use, permission: ep.readScope} + page := 1 + for n := 0; n < maxPages; n++ { + query := url.Values{"per_page": {strconv.Itoa(perPage)}, "page": {strconv.Itoa(page)}} + resp, err := c.do(ctx, info, http.MethodGet, ep.path, query, nil) + if err != nil { + return "", false, err + } + var keys []remoteKey + if err := json.Unmarshal(resp.body, &keys); err != nil { + return "", false, &authority.Error{Authority: Name, Operation: operationList, Use: use, Status: resp.status, Err: authority.ErrUnexpectedStatus, Detail: "response is not a list of keys"} + } + for _, k := range keys { + if sameKey(k.Key, authorized) { + return strconv.FormatInt(k.ID, 10), true, nil + } + } + if page = nextPage(resp.header, page); page == 0 { + return "", false, nil + } + } + return "", false, &authority.Error{Authority: Name, Operation: operationList, Use: use, Err: authority.ErrUnexpectedStatus, Detail: maxPagesExceededBy} +} + +// sameKey compares the key type and base64 body, ignoring the comment. +func sameKey(a, b string) bool { + fa, fb := strings.Fields(a), strings.Fields(b) + return len(fa) >= 2 && len(fb) >= 2 && fa[0] == fb[0] && fa[1] == fb[1] +} + +// Revoke implements authority.Authority. It deletes the keys named in receipt.References and treats +// an ID that is already gone as success. Every reference is attempted; failures are joined. +func (a *Authority) Revoke(ctx context.Context, credentials map[string]string, receipt authority.Receipt) error { + if len(receipt.References) == 0 { + return nil + } + c, err := a.newClient("revoke", credentials) + if err != nil { + return err + } + uses := make([]authority.Use, 0, len(receipt.References)) + for use := range receipt.References { + uses = append(uses, use) + } + sort.Slice(uses, func(i, j int) bool { return uses[i] < uses[j] }) + var errs []error + for _, use := range uses { + if err := c.deleteKey(ctx, use, receipt.References[use]); err != nil { + errs = append(errs, err) + } + } + return errors.Join(errs...) +} + +func (c *client) deleteKey(ctx context.Context, use authority.Use, ref string) error { + ep, ok := endpoints[use] + if !ok { + return &authority.Error{Authority: Name, Operation: operationDelete, Use: use, Err: authority.ErrUnsupportedUse} + } + id, err := strconv.ParseInt(ref, 10, 64) + if err != nil || id <= 0 { + return &authority.Error{Authority: Name, Operation: operationDelete, Use: use, Err: authority.ErrInvalidRequest, Detail: "reference is not a key ID"} + } + info := call{operation: operationDelete, use: use, permission: ep.writeScope} + resp, err := c.do(ctx, info, http.MethodDelete, ep.path+"/"+strconv.FormatInt(id, 10), nil, nil) + if err == nil { + return nil + } + // GitHub answers 404 both for a missing key and for a token without the scope. The scope headers + // tell them apart when they are present. + if resp != nil && resp.status == http.StatusNotFound && !lacksScope(resp.header) { + return nil + } + return err +} diff --git a/plugins/ssh/authority/github/github_test.go b/plugins/ssh/authority/github/github_test.go new file mode 100644 index 00000000000..2d4db66e190 --- /dev/null +++ b/plugins/ssh/authority/github/github_test.go @@ -0,0 +1,395 @@ +package github_test + +import ( + "context" + "errors" + "net/http" + "strconv" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "golang.org/x/crypto/ssh" + + "github.com/cloudposse/atmos/plugins/ssh/authority" + "github.com/cloudposse/atmos/plugins/ssh/authority/authoritytest" + "github.com/cloudposse/atmos/plugins/ssh/authority/github" +) + +func newAuthority(t *testing.T, srv *authoritytest.GitHubServer) *github.Authority { + t.Helper() + a, err := github.New(authority.Options{BaseURL: srv.URL, HTTPClient: srv.Client(), UserAgent: "atmos-test/1"}) + require.NoError(t, err) + return a +} + +func creds(token string) map[string]string { + return map[string]string{authority.CredentialToken: token} +} + +func req(key ssh.PublicKey, uses ...authority.Use) authority.Request { + return authority.Request{KeyName: "ops", Key: key, Uses: uses, Title: "ops@host (Atmos)"} +} + +func TestConformance(t *testing.T) { + authoritytest.Run(t, func(t *testing.T) *authoritytest.Environment { + srv := authoritytest.NewGitHubServer(t) + return srv.Environment(newAuthority(t, srv)) + }) +} + +func TestConformancePaginated(t *testing.T) { + authoritytest.Run(t, func(t *testing.T) *authoritytest.Environment { + srv := authoritytest.NewGitHubServer(t) + srv.PageSize = 1 + return srv.Environment(newAuthority(t, srv)) + }) +} + +func TestConformanceForbiddenForMissingScope(t *testing.T) { + authoritytest.Run(t, func(t *testing.T) *authoritytest.Environment { + srv := authoritytest.NewGitHubServer(t) + srv.MissingScopeStatus = http.StatusForbidden + return srv.Environment(newAuthority(t, srv)) + }) +} + +func TestHeadersOnEveryCall(t *testing.T) { + srv := authoritytest.NewGitHubServer(t) + a := newAuthority(t, srv) + env := srv.Environment(a) + key := authoritytest.NewKey(t) + + receipt, err := a.Ensure(context.Background(), env.Credentials, req(key, authority.UseSigning, authority.UseAuthentication)) + require.NoError(t, err) + require.NoError(t, a.Revoke(context.Background(), env.Credentials, receipt)) + + logged := srv.Requests() + require.Len(t, logged, 7) + for _, r := range logged { + assert.True(t, r.HasBearer, "%s %s", r.Method, r.Path) + assert.Equal(t, "application/vnd.github+json", r.Header.Get("Accept")) + assert.Equal(t, "2022-11-28", r.Header.Get("X-GitHub-Api-Version")) + assert.Equal(t, "atmos-test/1", r.Header.Get("User-Agent")) + } +} + +func TestDefaultUserAgentIsSent(t *testing.T) { + srv := authoritytest.NewGitHubServer(t) + a, err := github.New(authority.Options{BaseURL: srv.URL}) + require.NoError(t, err) + env := srv.Environment(a) + _, err = a.Ensure(context.Background(), env.Credentials, req(authoritytest.NewKey(t), authority.UseSigning)) + require.NoError(t, err) + assert.Equal(t, github.DefaultUserAgent, srv.Requests()[0].Header.Get("User-Agent")) +} + +func TestEnsureRecordsLoginAndIDs(t *testing.T) { + srv := authoritytest.NewGitHubServer(t) + a := newAuthority(t, srv) + env := srv.Environment(a) + key := authoritytest.NewKey(t) + + receipt, err := a.Ensure(context.Background(), env.Credentials, req(key, authority.UseSigning, authority.UseAuthentication)) + require.NoError(t, err) + + assert.Equal(t, authoritytest.Login, receipt.Subject) + signing := srv.Keys(authoritytest.Login, authority.UseSigning) + auth := srv.Keys(authoritytest.Login, authority.UseAuthentication) + require.Len(t, signing, 1) + require.Len(t, auth, 1) + assert.Equal(t, strconv.FormatInt(signing[0].ID, 10), receipt.References[authority.UseSigning]) + assert.Equal(t, strconv.FormatInt(auth[0].ID, 10), receipt.References[authority.UseAuthentication]) + assert.Equal(t, "ops@host (Atmos)", signing[0].Title) +} + +func TestEmptyTitleGetsDefault(t *testing.T) { + srv := authoritytest.NewGitHubServer(t) + a := newAuthority(t, srv) + env := srv.Environment(a) + _, err := a.Ensure(context.Background(), env.Credentials, authority.Request{KeyName: "k", Key: authoritytest.NewKey(t), Uses: []authority.Use{authority.UseSigning}}) + require.NoError(t, err) + assert.NotEmpty(t, srv.Keys(authoritytest.Login, authority.UseSigning)[0].Title) +} + +func TestFindsKeyOnLaterPageAndIgnoresComment(t *testing.T) { + srv := authoritytest.NewGitHubServer(t) + srv.PageSize = 2 + a := newAuthority(t, srv) + env := srv.Environment(a) + + for range 5 { + srv.AddKey(authoritytest.Login, authority.UseAuthentication, authoritytest.NewKey(t), "other") + } + key := authoritytest.NewKey(t) + want := srv.AddKey(authoritytest.Login, authority.UseAuthentication, key, "mine") + srv.AddKey(authoritytest.Login, authority.UseAuthentication, authoritytest.NewKey(t), "after") + srv.ResetRequests() + + receipt, err := a.Ensure(context.Background(), env.Credentials, req(key, authority.UseAuthentication)) + require.NoError(t, err) + assert.Equal(t, strconv.FormatInt(want, 10), receipt.References[authority.UseAuthentication]) + assert.Len(t, srv.Keys(authoritytest.Login, authority.UseAuthentication), 7, "nothing was created") + + var gets int + for _, r := range srv.Requests() { + assert.NotEqual(t, http.MethodPost, r.Method) + if r.Path == "/user/keys" { + gets++ + } + } + assert.Equal(t, 3, gets, "pages 1 to 3 were read") +} + +func TestKeyOnOtherAccountIsInUse(t *testing.T) { + srv := authoritytest.NewGitHubServer(t) + a := newAuthority(t, srv) + env := srv.Environment(a) + key := authoritytest.NewKey(t) + srv.AddKey("someone-else", authority.UseSigning, key, "theirs") + + receipt, err := a.Ensure(context.Background(), env.Credentials, req(key, authority.UseSigning)) + require.Error(t, err) + assert.ErrorIs(t, err, authority.ErrKeyInUse) + var ae *authority.Error + require.ErrorAs(t, err, &ae) + assert.Equal(t, http.StatusUnprocessableEntity, ae.Status) + assert.Empty(t, receipt.References) +} + +func TestErrorMapping(t *testing.T) { + tests := []struct { + name string + failure authoritytest.Failure + want error + check func(*testing.T, *authority.Error) + }{ + { + name: "bad token on login", + failure: authoritytest.Failure{Method: "GET", PathPrefix: "/user", Status: 401, Body: `{"message":"Bad credentials"}`}, + want: authority.ErrUnauthorized, + check: func(t *testing.T, e *authority.Error) { assert.Equal(t, 401, e.Status) }, + }, + { + name: "forbidden with remaining quota is a missing permission", + failure: authoritytest.Failure{Method: "POST", PathPrefix: "/user/ssh_signing_keys", Status: 403, Body: `{"message":"Resource not accessible by personal access token"}`}, + want: authority.ErrMissingPermission, + check: func(t *testing.T, e *authority.Error) { + assert.Equal(t, "write:ssh_signing_key", e.Permission) + assert.Equal(t, authority.UseSigning, e.Use) + }, + }, + { + name: "403 with exhausted quota is rate limiting", + failure: authoritytest.Failure{ + Method: "GET", PathPrefix: "/user/ssh_signing_keys", Status: 403, + Header: http.Header{"X-Ratelimit-Remaining": {"0"}, "Retry-After": {"90"}}, + Body: `{"message":"API rate limit exceeded"}`, + }, + want: authority.ErrRateLimited, + check: func(t *testing.T, e *authority.Error) { assert.Equal(t, 90*time.Second, e.RetryAfter) }, + }, + { + name: "secondary rate limit by message", + failure: authoritytest.Failure{Method: "GET", PathPrefix: "/user/ssh_signing_keys", Status: 403, Body: `{"message":"You have exceeded a secondary rate limit"}`}, + want: authority.ErrRateLimited, + }, + { + name: "429", + failure: authoritytest.Failure{Method: "GET", PathPrefix: "/user/ssh_signing_keys", Status: 429, Body: `{}`}, + want: authority.ErrRateLimited, + }, + { + name: "server error", + failure: authoritytest.Failure{Method: "GET", PathPrefix: "/user/ssh_signing_keys", Status: 502, Body: `bad gateway`}, + want: authority.ErrUnexpectedStatus, + check: func(t *testing.T, e *authority.Error) { assert.Contains(t, e.Detail, "bad gateway") }, + }, + { + name: "redirect on a write is not followed", + failure: authoritytest.Failure{Method: "POST", PathPrefix: "/user/ssh_signing_keys", Status: 307, Header: http.Header{"Location": {"https://evil.example/steal"}}}, + want: authority.ErrUnexpectedStatus, + check: func(t *testing.T, e *authority.Error) { assert.Equal(t, 307, e.Status) }, + }, + { + name: "unparseable login", + failure: authoritytest.Failure{Method: "GET", PathPrefix: "/user", Status: 200, Body: `[]`}, + want: authority.ErrUnexpectedStatus, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + srv := authoritytest.NewGitHubServer(t) + a := newAuthority(t, srv) + env := srv.Environment(a) + srv.Fail(tt.failure) + + _, err := a.Ensure(context.Background(), env.Credentials, req(authoritytest.NewKey(t), authority.UseSigning)) + require.Error(t, err) + assert.ErrorIs(t, err, tt.want) + var ae *authority.Error + require.ErrorAs(t, err, &ae) + assert.Equal(t, "github", ae.Authority) + assert.NotContains(t, err.Error(), authoritytest.FullToken) + if tt.check != nil { + tt.check(t, ae) + } + }) + } +} + +func TestMissingScopeNamesWriteWhenOnlyReadIsGranted(t *testing.T) { + srv := authoritytest.NewGitHubServer(t) + a := newAuthority(t, srv) + srv.AddToken("ghp_readonly", "octocat", "read:ssh_signing_key") + + _, err := a.Ensure(context.Background(), creds("ghp_readonly"), req(authoritytest.NewKey(t), authority.UseSigning)) + require.ErrorIs(t, err, authority.ErrMissingPermission) + var ae *authority.Error + require.ErrorAs(t, err, &ae) + assert.Equal(t, "write:ssh_signing_key", ae.Permission) + assert.Contains(t, ae.Detail, "read:ssh_signing_key", "the token's own scopes are shown") + assert.NotContains(t, err.Error(), "ghp_readonly") +} + +func TestMissingTokenIsUnauthorizedWithoutNetwork(t *testing.T) { + srv := authoritytest.NewGitHubServer(t) + a := newAuthority(t, srv) + _, err := a.Ensure(context.Background(), map[string]string{}, req(authoritytest.NewKey(t), authority.UseSigning)) + assert.ErrorIs(t, err, authority.ErrUnauthorized) + assert.ErrorIs(t, a.Revoke(context.Background(), nil, authority.Receipt{References: map[authority.Use]string{authority.UseSigning: "1"}}), authority.ErrUnauthorized) + assert.Empty(t, srv.Requests()) +} + +func TestErrorBodyEchoingTheTokenIsScrubbed(t *testing.T) { + srv := authoritytest.NewGitHubServer(t) + a := newAuthority(t, srv) + env := srv.Environment(a) + srv.Fail(authoritytest.Failure{Method: "GET", PathPrefix: "/user/ssh_signing_keys", Status: 500, Body: `{"message":"token ` + authoritytest.FullToken + ` is weird"}`}) + + _, err := a.Ensure(context.Background(), env.Credentials, req(authoritytest.NewKey(t), authority.UseSigning)) + require.Error(t, err) + assert.NotContains(t, err.Error(), authoritytest.FullToken) + assert.Contains(t, err.Error(), "[redacted]") +} + +func TestUnreachableServer(t *testing.T) { + srv := authoritytest.NewGitHubServer(t) + a := newAuthority(t, srv) + env := srv.Environment(a) + srv.Close() + + _, err := a.Ensure(context.Background(), env.Credentials, req(authoritytest.NewKey(t), authority.UseSigning)) + require.ErrorIs(t, err, authority.ErrUnavailable) + assert.NotContains(t, err.Error(), authoritytest.FullToken) +} + +func TestPartialEnrollmentKeepsWhatWasCreated(t *testing.T) { + srv := authoritytest.NewGitHubServer(t) + a := newAuthority(t, srv) + env := srv.Environment(a) + srv.Fail(authoritytest.Failure{Method: "POST", PathPrefix: "/user/keys", Status: 500, Body: `{"message":"boom"}`}) + + // authentication sorts first, so make signing the first and only success. + key := authoritytest.NewKey(t) + receipt, err := a.Ensure(context.Background(), env.Credentials, req(key, authority.UseAuthentication, authority.UseSigning)) + require.ErrorIs(t, err, authority.ErrUnexpectedStatus) + assert.Empty(t, receipt.References, "authentication failed first, so nothing was enrolled") + + srv.Fail(authoritytest.Failure{Method: "POST", PathPrefix: "/user/ssh_signing_keys", Status: 500, Body: `{"message":"boom"}`}) + receipt, err = a.Ensure(context.Background(), env.Credentials, req(key, authority.UseAuthentication, authority.UseSigning)) + require.Error(t, err) + require.Contains(t, receipt.References, authority.UseAuthentication) + assert.Equal(t, []authority.Use{authority.UseAuthentication}, receipt.Uses) + assert.Equal(t, authoritytest.Login, receipt.Subject) +} + +func TestRevokeTreatsMissingIDAsSuccess(t *testing.T) { + srv := authoritytest.NewGitHubServer(t) + a := newAuthority(t, srv) + env := srv.Environment(a) + err := a.Revoke(context.Background(), env.Credentials, authority.Receipt{References: map[authority.Use]string{ + authority.UseSigning: "424242", authority.UseAuthentication: "424243", + }}) + assert.NoError(t, err) +} + +func TestRevokeWithoutScopeIsNotSuccess(t *testing.T) { + srv := authoritytest.NewGitHubServer(t) + a := newAuthority(t, srv) + env := srv.Environment(a) + key := authoritytest.NewKey(t) + receipt, err := a.Ensure(context.Background(), env.Credentials, req(key, authority.UseSigning)) + require.NoError(t, err) + + err = a.Revoke(context.Background(), creds(authoritytest.LimitedToken(authority.UseSigning)), receipt) + require.ErrorIs(t, err, authority.ErrMissingPermission) + assert.Len(t, srv.Keys(authoritytest.Login, authority.UseSigning), 1, "the key was not removed") +} + +func TestRevokeAttemptsEveryReferenceAndJoinsErrors(t *testing.T) { + srv := authoritytest.NewGitHubServer(t) + a := newAuthority(t, srv) + env := srv.Environment(a) + key := authoritytest.NewKey(t) + receipt, err := a.Ensure(context.Background(), env.Credentials, req(key, authority.UseSigning, authority.UseAuthentication)) + require.NoError(t, err) + srv.Fail(authoritytest.Failure{Method: "DELETE", PathPrefix: "/user/keys", Status: 500, Body: `{}`}) + + err = a.Revoke(context.Background(), env.Credentials, receipt) + require.ErrorIs(t, err, authority.ErrUnexpectedStatus) + assert.Empty(t, srv.Keys(authoritytest.Login, authority.UseSigning), "the other use was still withdrawn") + assert.Len(t, srv.Keys(authoritytest.Login, authority.UseAuthentication), 1) +} + +func TestRevokeRejectsBadReferences(t *testing.T) { + srv := authoritytest.NewGitHubServer(t) + a := newAuthority(t, srv) + env := srv.Environment(a) + for name, refs := range map[string]map[authority.Use]string{ + "path traversal": {authority.UseSigning: "../../repos"}, + "zero": {authority.UseSigning: "0"}, + "unknown use": {authority.Use("x"): "5"}, + } { + t.Run(name, func(t *testing.T) { + err := a.Revoke(context.Background(), env.Credentials, authority.Receipt{References: refs}) + require.Error(t, err) + assert.True(t, errors.Is(err, authority.ErrInvalidRequest) || errors.Is(err, authority.ErrUnsupportedUse)) + }) + } + for _, r := range srv.Requests() { + assert.NotContains(t, r.Path, "..") + } +} + +func TestRequestTimeoutAppliesWithoutClientTimeout(t *testing.T) { + srv := authoritytest.NewGitHubServer(t) + a := newAuthority(t, srv) + env := srv.Environment(a) + ctx, cancel := context.WithTimeout(context.Background(), time.Nanosecond) + defer cancel() + _, err := a.Ensure(ctx, env.Credentials, req(authoritytest.NewKey(t), authority.UseSigning)) + require.ErrorIs(t, err, authority.ErrUnavailable) +} + +func TestNewRejectsBadBaseURL(t *testing.T) { + for _, base := range []string{"ftp://example.com", "://nope", "api.github.com"} { + _, err := github.New(authority.Options{BaseURL: base}) + assert.ErrorIs(t, err, authority.ErrInvalidRequest, base) + } + a, err := github.New(authority.Options{}) + require.NoError(t, err) + assert.Equal(t, "github", a.Name()) + assert.Equal(t, []authority.Use{authority.UseAuthentication, authority.UseSigning}, a.Supports()) +} + +func TestFactoryRegisters(t *testing.T) { + registry := authority.NewRegistry() + require.NoError(t, registry.Register(github.Factory)) + a, err := registry.New("github", authority.Options{}) + require.NoError(t, err) + assert.Equal(t, github.Name, a.Name()) + _, err = registry.New("github", authority.Options{BaseURL: "bad"}) + assert.ErrorIs(t, err, authority.ErrInvalidRequest) +} diff --git a/plugins/ssh/authority/prune.go b/plugins/ssh/authority/prune.go new file mode 100644 index 00000000000..409f414f94a --- /dev/null +++ b/plugins/ssh/authority/prune.go @@ -0,0 +1,31 @@ +package authority + +import ( + "context" + "fmt" +) + +// Prune revokes and deletes this authority's receipts for keys that no longer exist, and does +// nothing else: it enrolls no key and calls the authority only for those receipts. It is what a +// logout needs, where there may be no current key to enroll. +// +// Existing holds the fingerprints of the keys that still exist on this machine. Nil means unknown, +// and nothing is revoked then. Unlike Reconcile, no receipt is exempt because of its key name: a +// receipt whose key was deleted is withdrawn even when the identity that owned it still exists. +func Prune(ctx context.Context, p Params) (Result, error) { + switch { + case p.Authority == nil: + return Result{Outcome: OutcomeFailed}, fmt.Errorf("%w: no authority", ErrInvalidRequest) + case p.Store == nil: + return Result{Outcome: OutcomeFailed}, fmt.Errorf("%w: no receipt store", ErrInvalidRequest) + } + // No current key: nothing is exempt from the sweep. + p.KeyName, p.Key = "", nil + r := &reconciler{Params: p, name: p.Authority.Name()} + r.res.Outcome = OutcomeUnchanged + r.cleanup(ctx) + if len(r.res.Failures) > 0 { + r.res.Outcome = OutcomeFailed + } + return r.res, r.res.Err() +} diff --git a/plugins/ssh/authority/prune_test.go b/plugins/ssh/authority/prune_test.go new file mode 100644 index 00000000000..a83b81fd335 --- /dev/null +++ b/plugins/ssh/authority/prune_test.go @@ -0,0 +1,84 @@ +package authority_test + +import ( + "context" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/cloudposse/atmos/plugins/ssh/authority" + "github.com/cloudposse/atmos/plugins/ssh/authority/authoritytest" +) + +func TestPruneRevokesOnlyReceiptsWhoseKeyIsGone(t *testing.T) { + r := newRig(t) + gone := authoritytest.NewKey(t) + r.enrollOther("old", gone, authority.UseSigning) + setup := r.params(authority.UseSigning) + setup.Existing = nil + r.mustRun(setup) + require.Equal(t, 1, r.fake.Count(gone, authority.UseSigning)) + + p := r.params() + p.Existing = authoritytest.Fingerprints(r.key) + res, err := authority.Prune(context.Background(), p) + require.NoError(t, err) + + assert.Len(t, res.Revoked, 1) + assert.Equal(t, "old", res.Revoked[0].KeyName) + assert.Zero(t, r.fake.Count(gone, authority.UseSigning), "the missing key was withdrawn") + assert.Equal(t, 1, r.fake.Count(r.key, authority.UseSigning), "a live key stays enrolled") + _, err = r.store.Load("fake", "old") + assert.ErrorIs(t, err, authority.ErrReceiptNotFound) +} + +func TestPruneRevokesTheReceiptOfADeletedKeyUnderTheSameName(t *testing.T) { + r := newRig(t) + r.mustRun(r.params(authority.UseSigning)) + + p := r.params() + p.Existing = map[string]bool{} + res, err := authority.Prune(context.Background(), p) + require.NoError(t, err) + + assert.Len(t, res.Revoked, 1) + assert.Zero(t, r.fake.Count(r.key, authority.UseSigning)) +} + +func TestPruneDoesNothingWhenTheKeysAreUnknown(t *testing.T) { + r := newRig(t) + r.mustRun(r.params(authority.UseSigning)) + before := len(r.fake.Calls()) + + p := r.params() + p.Existing = nil + res, err := authority.Prune(context.Background(), p) + require.NoError(t, err) + + assert.Empty(t, res.Revoked) + assert.False(t, res.Contacted) + assert.Len(t, r.fake.Calls(), before) +} + +func TestPruneKeepsTheReceiptWhenRevocationFails(t *testing.T) { + r := newRig(t) + r.mustRun(r.params(authority.UseSigning)) + r.fake.FailNextRevoke(errBoom) + + p := r.params() + p.Existing = map[string]bool{} + res, err := authority.Prune(context.Background(), p) + + require.ErrorIs(t, err, errBoom) + assert.Equal(t, authority.OutcomeFailed, res.Outcome) + _, loadErr := r.store.Load("fake", "ops") + assert.NoError(t, loadErr, "the receipt stays so a later run can retry") +} + +func TestPruneRejectsIncompleteParams(t *testing.T) { + _, err := authority.Prune(context.Background(), authority.Params{}) + assert.ErrorIs(t, err, authority.ErrInvalidRequest) + _, err = authority.Prune(context.Background(), authority.Params{Authority: authoritytest.NewFake("fake")}) + assert.ErrorIs(t, err, authority.ErrInvalidRequest) +} diff --git a/plugins/ssh/authority/reconcile.go b/plugins/ssh/authority/reconcile.go new file mode 100644 index 00000000000..2f093644169 --- /dev/null +++ b/plugins/ssh/authority/reconcile.go @@ -0,0 +1,384 @@ +package authority + +import ( + "context" + "errors" + "fmt" + "time" + + "golang.org/x/crypto/ssh" +) + +// Outcome says what Reconcile did for the current key. +type Outcome string + +const ( + // OutcomeUnchanged means a valid receipt already matched and the authority was not asked. + OutcomeUnchanged Outcome = "unchanged" + // OutcomeEnrolled means the key had no receipt and is now enrolled. + OutcomeEnrolled Outcome = "enrolled" + // OutcomeUpdated means uses were added or removed on an enrolled key. + OutcomeUpdated Outcome = "updated" + // OutcomeRefreshed means the authority was asked again and nothing about the uses changed. + OutcomeRefreshed Outcome = "refreshed" + // OutcomeFailed means the key is not enrolled as requested. See Result.Failures. + OutcomeFailed Outcome = "failed" +) + +// Step names the part of Reconcile that failed. +type Step string + +const ( + // StepLoad is reading this key's receipt. + StepLoad Step = "load-receipt" + // StepEnsure is asking the authority to enroll the key. + StepEnsure Step = "ensure" + // StepRevokeDropped is withdrawing a use that is no longer requested. + StepRevokeDropped Step = "revoke-dropped-use" + // StepRevokeRotated is withdrawing the enrollment of a key that was replaced under the same name. + StepRevokeRotated Step = "revoke-rotated-key" + // StepRevokeOrphan is withdrawing the enrollment of a key that no longer exists. + StepRevokeOrphan Step = "revoke-missing-key" + // StepSave is writing a receipt. + StepSave Step = "save-receipt" + // StepDelete is removing a receipt after its enrollment was withdrawn. + StepDelete Step = "delete-receipt" + // StepList is listing the stored receipts. + StepList Step = "list-receipts" +) + +// StepError is one failure inside Reconcile. Every step that fails is recorded, so a caller can +// render exactly what is half done. +type StepError struct { + Step Step + KeyName string + Uses []Use + Err error +} + +// Error implements the error interface. +func (e *StepError) Error() string { + if e.KeyName == "" { + return fmt.Sprintf("%s: %v", e.Step, e.Err) + } + return fmt.Sprintf("%s (key %q): %v", e.Step, e.KeyName, e.Err) +} + +// Unwrap returns the underlying error. +func (e *StepError) Unwrap() error { return e.Err } + +// Params describe one reconciliation. +type Params struct { + // Authority vouches for the key. + Authority Authority + // Credentials authenticate to the authority. + Credentials map[string]string + // Store holds the receipts. + Store *Store + // KeyName and Key identify the current key. + KeyName string + Key ssh.PublicKey + // Uses is what the key is to be trusted for. + Uses []Use + // Title labels the key on the authority. + Title string + // Principals and Target pass through to authorities that use them. + Principals []string + Target string + // Existing holds the fingerprints of the keys that still exist on this machine. Receipts of + // this authority for other fingerprints are revoked. Nil means unknown, and no receipt is + // revoked on this ground. + Existing map[string]bool + // Force asks the authority even when a valid receipt already matches. + Force bool + // Now is the clock used for expiry. Nil means time.Now. + Now func() time.Time +} + +// Result describes what Reconcile did. +type Result struct { + // Outcome is the state of the current key. + Outcome Outcome + // Receipt is the current key's receipt. It is valid unless Outcome is OutcomeFailed, and then + // it holds only what was saved of a partial enrollment, if anything. + Receipt Receipt + // Contacted reports whether the authority was called at all. + Contacted bool + // Added and Removed are the uses enrolled and withdrawn on the current key. + Added []Use + Removed []Use + // Revoked lists the receipts withdrawn because their key is gone or was replaced. + Revoked []Receipt + // Failures lists every step that failed. A non-empty list can accompany a usable Receipt, for + // example when only the cleanup of a stale enrollment failed. + Failures []*StepError +} + +// Err joins the failures into one error, or returns nil when none occurred. +func (r Result) Err() error { + errs := make([]error, len(r.Failures)) + for i, f := range r.Failures { + errs[i] = f + } + return errors.Join(errs...) +} + +// Reconcile brings the authority and the receipts into agreement with the key. +// +// 1. A valid, unexpired receipt for this key that covers exactly the requested uses is returned +// without calling the authority. +// 2. Otherwise the authority is asked to Ensure the key, the receipt is saved, and uses that were +// dropped from the request are revoked. +// 3. Receipts of this authority whose fingerprint is not in Existing are revoked and deleted. +// +// A receipt is deleted only after its enrollment was withdrawn. A receipt that is still needed to +// revoke something stays on disk. +func Reconcile(ctx context.Context, p Params) (Result, error) { + if err := p.validate(); err != nil { + return Result{Outcome: OutcomeFailed}, err + } + r := &reconciler{Params: p, name: p.Authority.Name(), fp: Fingerprint(p.Key), uses: NormalizeUses(p.Uses)} + r.run(ctx) + return r.res, r.res.Err() +} + +func (p Params) validate() error { + switch { + case p.Authority == nil: + return fmt.Errorf("%w: no authority", ErrInvalidRequest) + case p.Store == nil: + return fmt.Errorf("%w: no receipt store", ErrInvalidRequest) + case p.KeyName == "": + return fmt.Errorf("%w: no key name", ErrInvalidRequest) + } + return ValidateRequest(p.Authority, Request{KeyName: p.KeyName, Key: p.Key, Uses: p.Uses}) +} + +type reconciler struct { + Params + name string + fp string + uses []Use + res Result +} + +func (r *reconciler) now() time.Time { + if r.Now != nil { + return r.Now() + } + return time.Now() +} + +func (r *reconciler) fail(step Step, keyName string, uses []Use, err error) { + r.res.Failures = append(r.res.Failures, &StepError{Step: step, KeyName: keyName, Uses: uses, Err: err}) +} + +func (r *reconciler) run(ctx context.Context) { + old, found, ok := r.loadCurrent() + if !ok { + r.res.Outcome = OutcomeFailed + return + } + if found && r.upToDate(old) { + r.res.Outcome = OutcomeUnchanged + r.res.Receipt = old + r.cleanup(ctx) + return + } + if found && old.Fingerprint != r.fp { + if !r.revokeRotated(ctx, old) { + r.res.Outcome = OutcomeFailed + return + } + old, found = Receipt{}, false + } + r.enroll(ctx, old, found) + if r.res.Outcome != OutcomeFailed { + r.cleanup(ctx) + } +} + +// loadCurrent reads this key's receipt. It reports ok=false on a failure that must stop the run, +// because overwriting an unreadable receipt could lose a reference needed to revoke. +func (r *reconciler) loadCurrent() (old Receipt, found, ok bool) { + old, err := r.Store.Load(r.name, r.KeyName) + switch { + case err == nil: + return old, true, true + case errors.Is(err, ErrReceiptNotFound): + return Receipt{}, false, true + default: + r.fail(StepLoad, r.KeyName, nil, err) + return Receipt{}, false, false + } +} + +func (r *reconciler) upToDate(old Receipt) bool { + if r.Force || old.Fingerprint != r.fp || old.Expired(r.now()) { + return false + } + return equalUses(old.Uses, r.uses) && equalUses(old.EnrolledUses(), r.uses) +} + +// revokeRotated withdraws the receipt of a different key that used this key's name. The new +// receipt would overwrite its file, so the old one must be gone first. +func (r *reconciler) revokeRotated(ctx context.Context, old Receipt) bool { + r.res.Contacted = true + if err := r.Authority.Revoke(ctx, r.Credentials, old); err != nil { + r.fail(StepRevokeRotated, old.KeyName, old.EnrolledUses(), err) + return false + } + if err := r.Store.Delete(old.Authority, old.KeyName); err != nil { + r.fail(StepDelete, old.KeyName, nil, err) + return false + } + r.res.Revoked = append(r.res.Revoked, old) + return true +} + +func (r *reconciler) enroll(ctx context.Context, old Receipt, hadOld bool) { + r.res.Contacted = true + rec, err := r.Authority.Ensure(ctx, r.Credentials, Request{ + KeyName: r.KeyName, Key: r.Key, Uses: r.uses, Title: r.Title, + Principals: r.Principals, Target: r.Target, + }) + rec = r.complete(rec, old, hadOld, err == nil) + if err != nil { + r.res.Outcome = OutcomeFailed + r.fail(StepEnsure, r.KeyName, r.uses, err) + r.savePartial(rec, old) + return + } + enrolled := old.EnrolledUses() + if !hadOld { + enrolled = nil + } + added := differenceUses(r.uses, enrolled) + dropped := differenceUses(enrolled, r.uses) + kept := r.revokeDropped(ctx, old, dropped) + for use, ref := range kept { + rec.References[use] = ref + } + if err := r.Store.Save(rec); err != nil { + r.res.Outcome = OutcomeFailed + r.fail(StepSave, r.KeyName, r.uses, err) + return + } + r.res.Receipt = rec + r.res.Added = added + r.res.Removed = differenceUses(dropped, keysOf(kept)) + r.res.Outcome = outcomeFor(hadOld, len(r.res.Added)+len(r.res.Removed) > 0) +} + +func outcomeFor(hadOld, changed bool) Outcome { + switch { + case !hadOld: + return OutcomeEnrolled + case changed: + return OutcomeUpdated + default: + return OutcomeRefreshed + } +} + +// complete fills the identity fields of a receipt the authority returned and carries over what +// the old receipt knew. +func (r *reconciler) complete(rec, old Receipt, hadOld, succeeded bool) Receipt { + rec.Authority, rec.KeyName, rec.Fingerprint = r.name, r.KeyName, r.fp + if rec.PublicKey == "" { + rec.PublicKey = AuthorizedKey(r.Key) + } + if rec.References == nil { + rec.References = map[Use]string{} + } + if succeeded && len(rec.Uses) == 0 { + rec.Uses = r.uses + } + rec.Uses = NormalizeUses(rec.Uses) + switch { + case hadOld && !old.Created.IsZero(): + rec.Created = old.Created + case rec.Created.IsZero(): + rec.Created = r.now().UTC() + } + return rec +} + +// savePartial persists what a failed Ensure did enroll, merged with the old references, so a later +// run can still revoke it. +func (r *reconciler) savePartial(rec, old Receipt) { + if len(rec.References) == 0 { + return + } + for use, ref := range old.References { + if _, ok := rec.References[use]; !ok { + rec.References[use] = ref + } + } + rec.Uses = NormalizeUses(append(rec.Uses, old.Uses...)) + if err := r.Store.Save(rec); err != nil { + r.fail(StepSave, r.KeyName, nil, err) + return + } + r.res.Receipt = rec +} + +// revokeDropped withdraws the dropped uses. It returns the references that could not be withdrawn, +// which the new receipt must keep. +func (r *reconciler) revokeDropped(ctx context.Context, old Receipt, dropped []Use) map[Use]string { + if len(dropped) == 0 { + return nil + } + refs := map[Use]string{} + for _, use := range dropped { + if ref, ok := old.References[use]; ok { + refs[use] = ref + } + } + partial := old + partial.Uses, partial.References = dropped, refs + err := r.Authority.Revoke(ctx, r.Credentials, partial) + if err == nil { + return nil + } + r.fail(StepRevokeDropped, r.KeyName, dropped, err) + return refs +} + +func keysOf(m map[Use]string) []Use { + out := make([]Use, 0, len(m)) + for use := range m { + out = append(out, use) + } + return out +} + +// cleanup revokes this authority's receipts for keys that no longer exist. +func (r *reconciler) cleanup(ctx context.Context) { + if r.Existing == nil { + return + } + receipts, err := r.Store.List() + if err != nil { + r.fail(StepList, "", nil, err) + } + for _, rec := range receipts { + if rec.Authority != r.name || rec.KeyName == r.KeyName || rec.Fingerprint == r.fp || r.Existing[rec.Fingerprint] { + continue + } + r.revokeOrphan(ctx, rec) + } +} + +func (r *reconciler) revokeOrphan(ctx context.Context, rec Receipt) { + r.res.Contacted = true + if err := r.Authority.Revoke(ctx, r.Credentials, rec); err != nil { + r.fail(StepRevokeOrphan, rec.KeyName, rec.EnrolledUses(), err) + return + } + if err := r.Store.Delete(rec.Authority, rec.KeyName); err != nil { + r.fail(StepDelete, rec.KeyName, nil, err) + return + } + r.res.Revoked = append(r.res.Revoked, rec) +} diff --git a/plugins/ssh/authority/reconcile_test.go b/plugins/ssh/authority/reconcile_test.go new file mode 100644 index 00000000000..08379cbce96 --- /dev/null +++ b/plugins/ssh/authority/reconcile_test.go @@ -0,0 +1,507 @@ +package authority_test + +import ( + "context" + "errors" + "os" + "path/filepath" + "runtime" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "golang.org/x/crypto/ssh" + + "github.com/cloudposse/atmos/plugins/ssh/authority" + "github.com/cloudposse/atmos/plugins/ssh/authority/authoritytest" + "github.com/cloudposse/atmos/plugins/ssh/authority/github" +) + +var errBoom = errors.New("boom") + +var bothUses = []authority.Use{authority.UseSigning, authority.UseAuthentication} + +type rig struct { + t *testing.T + fake *authoritytest.Fake + store *authority.Store + key ssh.PublicKey +} + +func newRig(t *testing.T) *rig { + t.Helper() + return &rig{t: t, fake: authoritytest.NewFake("fake"), store: newStore(t), key: authoritytest.NewKey(t)} +} + +func (r *rig) params(uses ...authority.Use) authority.Params { + return authority.Params{ + Authority: r.fake, + Credentials: map[string]string{authority.CredentialToken: authoritytest.FakeToken}, + Store: r.store, + KeyName: "ops", + Key: r.key, + Uses: uses, + Title: "ops@host (Atmos)", + Existing: authoritytest.Fingerprints(r.key), + } +} + +func (r *rig) run(p authority.Params) authority.Result { + r.t.Helper() + res, err := authority.Reconcile(context.Background(), p) + assert.Equal(r.t, res.Err(), err) + return res +} + +func (r *rig) mustRun(p authority.Params) authority.Result { + r.t.Helper() + res, err := authority.Reconcile(context.Background(), p) + require.NoError(r.t, err) + return res +} + +// enrollOther enrolls a second key under name without cleaning anything up. +func (r *rig) enrollOther(name string, key ssh.PublicKey, uses ...authority.Use) { + r.t.Helper() + p := r.params(uses...) + p.KeyName, p.Key, p.Existing = name, key, nil + r.mustRun(p) +} + +func (r *rig) saved(name string) authority.Receipt { + r.t.Helper() + rec, err := r.store.Load("fake", name) + require.NoError(r.t, err) + return rec +} + +func TestReconcileEnrollsThenIsUnchangedWithoutCallingTheAuthority(t *testing.T) { + r := newRig(t) + + first := r.mustRun(r.params(bothUses...)) + assert.Equal(t, authority.OutcomeEnrolled, first.Outcome) + assert.True(t, first.Contacted) + assert.Equal(t, []authority.Use{authority.UseAuthentication, authority.UseSigning}, first.Added) + assert.Equal(t, 1, r.fake.CallCount("ensure")) + assert.Equal(t, first.Receipt, r.saved("ops")) + assert.Equal(t, authority.Fingerprint(r.key), first.Receipt.Fingerprint) + assert.Equal(t, "fake-user", first.Receipt.Subject) + + second := r.mustRun(r.params(bothUses...)) + assert.Equal(t, authority.OutcomeUnchanged, second.Outcome) + assert.False(t, second.Contacted) + assert.Empty(t, second.Added) + assert.Equal(t, first.Receipt, second.Receipt) + assert.Len(t, r.fake.Calls(), 1, "the fast path made no call") +} + +func TestReconcileFastPathNeedsNoNetworkAtAll(t *testing.T) { + srv := authoritytest.NewGitHubServer(t) + a, err := github.New(authority.Options{BaseURL: srv.URL, HTTPClient: srv.Client()}) + require.NoError(t, err) + env := srv.Environment(a) + store := newStore(t) + key := authoritytest.NewKey(t) + p := authority.Params{ + Authority: a, Credentials: env.Credentials, Store: store, KeyName: "ops", Key: key, + Uses: bothUses, Title: "ops@host (Atmos)", Existing: authoritytest.Fingerprints(key), + } + + res, err := authority.Reconcile(context.Background(), p) + require.NoError(t, err) + assert.Equal(t, authority.OutcomeEnrolled, res.Outcome) + assert.Equal(t, authoritytest.Login, res.Receipt.Subject) + assert.NotEmpty(t, srv.Requests()) + + srv.ResetRequests() + p.Credentials = map[string]string{} // the token is not even needed on the fast path + res, err = authority.Reconcile(context.Background(), p) + require.NoError(t, err) + assert.Equal(t, authority.OutcomeUnchanged, res.Outcome) + assert.Empty(t, srv.Requests(), "no request reached GitHub") +} + +func TestReconcileRotatedKeyRevokesTheOldKeyOnGitHub(t *testing.T) { + srv := authoritytest.NewGitHubServer(t) + a, err := github.New(authority.Options{BaseURL: srv.URL, HTTPClient: srv.Client()}) + require.NoError(t, err) + env := srv.Environment(a) + store := newStore(t) + oldKey, newKey := authoritytest.NewKey(t), authoritytest.NewKey(t) + p := authority.Params{ + Authority: a, Credentials: env.Credentials, Store: store, KeyName: "ops", Key: oldKey, + Uses: bothUses, Existing: authoritytest.Fingerprints(oldKey), + } + _, err = authority.Reconcile(context.Background(), p) + require.NoError(t, err) + + p.Key, p.Existing = newKey, authoritytest.Fingerprints(newKey) + res, err := authority.Reconcile(context.Background(), p) + require.NoError(t, err) + + assert.Equal(t, authority.OutcomeEnrolled, res.Outcome) + require.Len(t, res.Revoked, 1) + assert.Equal(t, authority.Fingerprint(oldKey), res.Revoked[0].Fingerprint) + assert.Zero(t, srv.KeyCount(oldKey, authority.UseSigning)+srv.KeyCount(oldKey, authority.UseAuthentication)) + assert.Equal(t, 1, srv.KeyCount(newKey, authority.UseSigning)) + assert.Equal(t, 1, srv.KeyCount(newKey, authority.UseAuthentication)) + stored, err := store.Load("github", "ops") + require.NoError(t, err) + assert.Equal(t, authority.Fingerprint(newKey), stored.Fingerprint) +} + +func TestReconcileChangedUses(t *testing.T) { + tests := []struct { + name string + first []authority.Use + second []authority.Use + wantOutcome authority.Outcome + added []authority.Use + removed []authority.Use + }{ + {"use added", []authority.Use{authority.UseSigning}, bothUses, authority.OutcomeUpdated, []authority.Use{authority.UseAuthentication}, nil}, + {"use dropped", bothUses, []authority.Use{authority.UseSigning}, authority.OutcomeUpdated, nil, []authority.Use{authority.UseAuthentication}}, + {"use swapped", []authority.Use{authority.UseSigning}, []authority.Use{authority.UseAuthentication}, authority.OutcomeUpdated, []authority.Use{authority.UseAuthentication}, []authority.Use{authority.UseSigning}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + r := newRig(t) + first := r.mustRun(r.params(tt.first...)) + + res := r.mustRun(r.params(tt.second...)) + + assert.Equal(t, tt.wantOutcome, res.Outcome) + assert.Equal(t, tt.added, res.Added) + assert.Equal(t, tt.removed, res.Removed) + assert.Equal(t, authority.NormalizeUses(tt.second), res.Receipt.EnrolledUses(), "references and uses agree") + assert.Equal(t, res.Receipt, r.saved("ops")) + assert.Equal(t, first.Receipt.Created, res.Receipt.Created, "the receipt keeps its issue time") + for _, use := range bothUses { + want := 0 + if contains(tt.second, use) { + want = 1 + } + assert.Equal(t, want, r.fake.Count(r.key, use), use) + } + }) + } +} + +func contains(uses []authority.Use, use authority.Use) bool { + for _, u := range uses { + if u == use { + return true + } + } + return false +} + +func TestReconcileForceAndExpiryAskTheAuthorityAgain(t *testing.T) { + r := newRig(t) + r.mustRun(r.params(bothUses...)) + + forced := r.params(bothUses...) + forced.Force = true + res := r.mustRun(forced) + assert.Equal(t, authority.OutcomeRefreshed, res.Outcome) + assert.True(t, res.Contacted) + assert.Empty(t, res.Added) + assert.Empty(t, res.Removed) + assert.Equal(t, 2, r.fake.CallCount("ensure")) + assert.Equal(t, 1, r.fake.Count(r.key, authority.UseSigning), "forcing creates no duplicate") + + rec := r.saved("ops") + rec.ExpiresAt = time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC) + require.NoError(t, r.store.Save(rec)) + + before := r.params(bothUses...) + before.Now = func() time.Time { return time.Date(2025, 12, 31, 0, 0, 0, 0, time.UTC) } + assert.Equal(t, authority.OutcomeUnchanged, r.mustRun(before).Outcome, "not yet expired") + assert.Equal(t, 2, r.fake.CallCount("ensure")) + + after := r.params(bothUses...) + after.Now = func() time.Time { return time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC) } + assert.Equal(t, authority.OutcomeRefreshed, r.mustRun(after).Outcome, "expired") + assert.Equal(t, 3, r.fake.CallCount("ensure")) +} + +func TestReconcileRotatedKeyUnderTheSameName(t *testing.T) { + r := newRig(t) + oldKey := r.key + r.mustRun(r.params(bothUses...)) + + r.key = authoritytest.NewKey(t) + res := r.mustRun(r.params(bothUses...)) + + assert.Equal(t, authority.OutcomeEnrolled, res.Outcome) + require.Len(t, res.Revoked, 1) + assert.Equal(t, authority.Fingerprint(oldKey), res.Revoked[0].Fingerprint) + assert.Zero(t, r.fake.Count(oldKey, authority.UseSigning)) + assert.Equal(t, 1, r.fake.Count(r.key, authority.UseSigning)) + assert.Equal(t, authority.Fingerprint(r.key), r.saved("ops").Fingerprint) +} + +func TestReconcileRotationKeepsTheOldReceiptWhenRevokeFails(t *testing.T) { + r := newRig(t) + oldKey := r.key + r.mustRun(r.params(bothUses...)) + r.key = authoritytest.NewKey(t) + r.fake.FailNextRevoke(errBoom) + + res := r.run(r.params(bothUses...)) + + assert.Equal(t, authority.OutcomeFailed, res.Outcome) + require.Len(t, res.Failures, 1) + assert.Equal(t, authority.StepRevokeRotated, res.Failures[0].Step) + assert.ErrorIs(t, res.Err(), errBoom) + assert.Equal(t, 1, r.fake.CallCount("ensure"), "the new key was not enrolled over the old receipt") + assert.Equal(t, authority.Fingerprint(oldKey), r.saved("ops").Fingerprint, "the old receipt is still there to retry") + + res = r.mustRun(r.params(bothUses...)) + assert.Equal(t, authority.OutcomeEnrolled, res.Outcome) + assert.Zero(t, r.fake.Count(oldKey, authority.UseSigning)) +} + +func TestReconcileRevokesReceiptsOfKeysThatNoLongerExist(t *testing.T) { + r := newRig(t) + gone, kept := authoritytest.NewKey(t), authoritytest.NewKey(t) + r.enrollOther("gone", gone, authority.UseSigning) + r.enrollOther("kept", kept, authority.UseSigning) + foreign := sampleReceipt("foreign", "SHA256:foreign") + foreign.Authority = "someone-else" + require.NoError(t, r.store.Save(foreign)) + + p := r.params(authority.UseSigning) + p.Existing = authoritytest.Fingerprints(r.key, kept) + res := r.mustRun(p) + + require.Len(t, res.Revoked, 1) + assert.Equal(t, "gone", res.Revoked[0].KeyName) + _, err := r.store.Load("fake", "gone") + assert.ErrorIs(t, err, authority.ErrReceiptNotFound) + assert.Zero(t, r.fake.Count(gone, authority.UseSigning)) + assert.Equal(t, 1, r.fake.Count(kept, authority.UseSigning), "a key that still exists stays enrolled") + _, err = r.store.Load("someone-else", "foreign") + assert.NoError(t, err, "another authority's receipts are not ours to revoke") +} + +func TestReconcileCleansUpEvenOnTheFastPath(t *testing.T) { + r := newRig(t) + r.mustRun(r.params(authority.UseSigning)) + r.enrollOther("gone", authoritytest.NewKey(t), authority.UseSigning) + ensures := r.fake.CallCount("ensure") + + res := r.mustRun(r.params(authority.UseSigning)) + + assert.Equal(t, authority.OutcomeUnchanged, res.Outcome) + assert.Equal(t, ensures, r.fake.CallCount("ensure")) + require.Len(t, res.Revoked, 1) + assert.True(t, res.Contacted) +} + +func TestReconcileWithUnknownExistingSetRevokesNothing(t *testing.T) { + r := newRig(t) + r.enrollOther("other", authoritytest.NewKey(t), authority.UseSigning) + + p := r.params(authority.UseSigning) + p.Existing = nil + res := r.mustRun(p) + + assert.Empty(t, res.Revoked) + assert.Zero(t, r.fake.CallCount("revoke")) + _, err := r.store.Load("fake", "other") + assert.NoError(t, err) +} + +func TestReconcileTreatsTheCurrentKeyAsExistingEvenIfOmitted(t *testing.T) { + r := newRig(t) + r.mustRun(r.params(authority.UseSigning)) + p := r.params(authority.UseSigning) + p.Existing = map[string]bool{} + res := r.mustRun(p) + assert.Empty(t, res.Revoked) + assert.Equal(t, 1, r.fake.Count(r.key, authority.UseSigning)) +} + +func TestReconcileKeepsAnOrphanReceiptWhenItsRevokeFails(t *testing.T) { + r := newRig(t) + gone := authoritytest.NewKey(t) + r.enrollOther("gone", gone, authority.UseSigning) + r.fake.FailNextRevoke(errBoom) + + res := r.run(r.params(authority.UseSigning)) + + assert.Equal(t, authority.OutcomeEnrolled, res.Outcome, "the current key is fine") + assert.Empty(t, res.Revoked) + require.Len(t, res.Failures, 1) + assert.Equal(t, authority.StepRevokeOrphan, res.Failures[0].Step) + assert.Equal(t, "gone", res.Failures[0].KeyName) + assert.Equal(t, []authority.Use{authority.UseSigning}, res.Failures[0].Uses) + assert.ErrorIs(t, res.Err(), errBoom) + assert.Equal(t, authority.Fingerprint(gone), r.saved("gone").Fingerprint, "the receipt is kept for the next try") + + res = r.mustRun(r.params(authority.UseSigning)) + require.Len(t, res.Revoked, 1) + _, err := r.store.Load("fake", "gone") + assert.ErrorIs(t, err, authority.ErrReceiptNotFound) +} + +func TestReconcileWhenEnsureFailsSavesNothingAndSkipsCleanup(t *testing.T) { + r := newRig(t) + gone := authoritytest.NewKey(t) + r.enrollOther("gone", gone, authority.UseSigning) + r.fake.FailNextEnsure(&authority.Error{Authority: "fake", Err: authority.ErrUnauthorized}) + + res := r.run(r.params(authority.UseSigning)) + + assert.Equal(t, authority.OutcomeFailed, res.Outcome) + require.Len(t, res.Failures, 1) + assert.Equal(t, authority.StepEnsure, res.Failures[0].Step) + assert.ErrorIs(t, res.Err(), authority.ErrUnauthorized) + _, err := r.store.Load("fake", "ops") + assert.ErrorIs(t, err, authority.ErrReceiptNotFound) + assert.Zero(t, r.fake.CallCount("revoke"), "no cleanup against an authority that just refused us") + _, err = r.store.Load("fake", "gone") + assert.NoError(t, err) +} + +func TestReconcileFailureInTheMiddleKeepsWhatWasEnrolled(t *testing.T) { + r := newRig(t) + r.fake.FailEnsureOnUse(authority.UseSigning, errBoom) // authentication sorts first and succeeds + + res := r.run(r.params(bothUses...)) + + assert.Equal(t, authority.OutcomeFailed, res.Outcome) + require.Len(t, res.Failures, 1) + assert.ErrorIs(t, res.Err(), errBoom) + partial := r.saved("ops") + assert.Equal(t, []authority.Use{authority.UseAuthentication}, partial.EnrolledUses()) + assert.Equal(t, partial, res.Receipt) + assert.Equal(t, 1, r.fake.Count(r.key, authority.UseAuthentication)) + + // The partial receipt is what lets a later run clean up. + later := r.params(bothUses...) + r.fake.FailEnsureOnUse(authority.UseSigning, nil) + res = r.mustRun(later) + assert.Equal(t, authority.OutcomeUpdated, res.Outcome) + assert.Equal(t, []authority.Use{authority.UseSigning}, res.Added) + + r.key = authoritytest.NewKey(t) + res = r.mustRun(r.params(bothUses...)) + require.Len(t, res.Revoked, 1) +} + +func TestReconcilePartialFailureOnAnUpdateKeepsOldReferences(t *testing.T) { + r := newRig(t) + first := r.mustRun(r.params(authority.UseSigning)) + r.fake.FailEnsureOnUse(authority.UseAuthentication, errBoom) + + res := r.run(r.params(bothUses...)) + + assert.Equal(t, authority.OutcomeFailed, res.Outcome) + assert.Equal(t, first.Receipt.References[authority.UseSigning], r.saved("ops").References[authority.UseSigning]) + assert.Equal(t, first.Receipt.Created, r.saved("ops").Created) +} + +func TestReconcileDroppedUseThatCannotBeRevokedIsRetriedLater(t *testing.T) { + r := newRig(t) + first := r.mustRun(r.params(bothUses...)) + r.fake.FailNextRevoke(errBoom) + + res := r.run(r.params(authority.UseSigning)) + + assert.Equal(t, authority.OutcomeRefreshed, res.Outcome, "the current key is usable and nothing was withdrawn") + require.Len(t, res.Failures, 1) + assert.Equal(t, authority.StepRevokeDropped, res.Failures[0].Step) + assert.Equal(t, []authority.Use{authority.UseAuthentication}, res.Failures[0].Uses) + assert.Empty(t, res.Removed) + kept := r.saved("ops") + assert.Equal(t, first.Receipt.References[authority.UseAuthentication], kept.References[authority.UseAuthentication], "the reference needed to revoke is kept") + assert.Equal(t, 1, r.fake.Count(r.key, authority.UseAuthentication)) + + res = r.mustRun(r.params(authority.UseSigning)) + assert.Equal(t, authority.OutcomeUpdated, res.Outcome) + assert.Equal(t, []authority.Use{authority.UseAuthentication}, res.Removed) + assert.Zero(t, r.fake.Count(r.key, authority.UseAuthentication)) + assert.Equal(t, []authority.Use{authority.UseSigning}, r.saved("ops").EnrolledUses()) + + assert.Equal(t, authority.OutcomeUnchanged, r.mustRun(r.params(authority.UseSigning)).Outcome) +} + +func TestReconcileStopsOnACorruptReceiptForTheKey(t *testing.T) { + r := newRig(t) + r.mustRun(r.params(authority.UseSigning)) + files, err := filepath.Glob(filepath.Join(r.store.Dir(), "*.json")) + require.NoError(t, err) + require.NoError(t, os.WriteFile(files[0], []byte("garbage"), 0o600)) + calls := len(r.fake.Calls()) + + res := r.run(r.params(authority.UseSigning)) + + assert.Equal(t, authority.OutcomeFailed, res.Outcome) + require.Len(t, res.Failures, 1) + assert.Equal(t, authority.StepLoad, res.Failures[0].Step) + assert.ErrorIs(t, res.Err(), authority.ErrReceiptCorrupt) + assert.Len(t, r.fake.Calls(), calls) + data, err := os.ReadFile(files[0]) + require.NoError(t, err) + assert.Equal(t, "garbage", string(data), "the file was not overwritten") +} + +func TestReconcileReportsAnUnreadableReceiptDirectoryDuringCleanup(t *testing.T) { + r := newRig(t) + r.mustRun(r.params(authority.UseSigning)) + require.NoError(t, os.WriteFile(filepath.Join(r.store.Dir(), "junk.json"), []byte("nope"), 0o600)) + + res := r.run(r.params(authority.UseSigning)) + + assert.Equal(t, authority.OutcomeUnchanged, res.Outcome) + require.Len(t, res.Failures, 1) + assert.Equal(t, authority.StepList, res.Failures[0].Step) + assert.Contains(t, res.Failures[0].Error(), "list-receipts") +} + +func TestReconcileRejectsBadParamsBeforeAnyCall(t *testing.T) { + r := newRig(t) + tests := []struct { + name string + edit func(*authority.Params) + want error + }{ + {"no authority", func(p *authority.Params) { p.Authority = nil }, authority.ErrInvalidRequest}, + {"no store", func(p *authority.Params) { p.Store = nil }, authority.ErrInvalidRequest}, + {"no key name", func(p *authority.Params) { p.KeyName = "" }, authority.ErrInvalidRequest}, + {"no key", func(p *authority.Params) { p.Key = nil }, authority.ErrInvalidRequest}, + {"no uses", func(p *authority.Params) { p.Uses = nil }, authority.ErrInvalidRequest}, + {"unsupported use", func(p *authority.Params) { p.Uses = []authority.Use{"teleportation"} }, authority.ErrUnsupportedUse}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + p := r.params(authority.UseSigning) + tt.edit(&p) + res, err := authority.Reconcile(context.Background(), p) + assert.ErrorIs(t, err, tt.want) + assert.Equal(t, authority.OutcomeFailed, res.Outcome) + assert.Empty(t, r.fake.Calls()) + }) + } +} + +func TestReconcileReportsASaveFailure(t *testing.T) { + if runtime.GOOS == "windows" || os.Geteuid() == 0 { + t.Skip("needs a directory the process cannot write") + } + r := newRig(t) + require.NoError(t, os.MkdirAll(r.store.Dir(), 0o700)) + require.NoError(t, os.Chmod(r.store.Dir(), 0o500)) + t.Cleanup(func() { _ = os.Chmod(r.store.Dir(), 0o700) }) + + res, err := authority.Reconcile(context.Background(), r.params(authority.UseSigning)) + + require.Error(t, err) + assert.Equal(t, authority.OutcomeFailed, res.Outcome) + require.Len(t, res.Failures, 1) + assert.Equal(t, authority.StepSave, res.Failures[0].Step) + assert.Equal(t, 1, r.fake.Count(r.key, authority.UseSigning), "the enrollment exists but its receipt could not be written") +} diff --git a/plugins/ssh/authority/registry.go b/plugins/ssh/authority/registry.go new file mode 100644 index 00000000000..fb14857ba8c --- /dev/null +++ b/plugins/ssh/authority/registry.go @@ -0,0 +1,97 @@ +package authority + +import ( + "fmt" + "net/http" + "sort" + "sync" +) + +// Options configure an authority when the registry builds it. +type Options struct { + // HTTPClient makes the authority's requests. Nil means the authority builds its own. + HTTPClient *http.Client + // BaseURL replaces the authority's default API address. Tests point it at a fake server. + BaseURL string + // UserAgent identifies the caller to the authority. Empty means the authority's default. + UserAgent string +} + +// Factory builds an authority. +type Factory struct { + // Name is the registry key, which must equal the built authority's Name. + Name string + // New builds the authority from options. + New func(Options) (Authority, error) +} + +// Registry maps authority names to factories. +type Registry struct { + mu sync.RWMutex + factories map[string]Factory +} + +// NewRegistry returns an empty registry. +func NewRegistry() *Registry { + return &Registry{factories: map[string]Factory{}} +} + +// Default is the registry the plugin wiring fills. +var Default = NewRegistry() + +// Register adds a factory. It fails when the name is empty, the factory is incomplete, or the name +// is taken. +func (r *Registry) Register(f Factory) error { + if f.Name == "" || f.New == nil { + return fmt.Errorf("%w: factory needs a name and a constructor", ErrInvalidRequest) + } + r.mu.Lock() + defer r.mu.Unlock() + if _, taken := r.factories[f.Name]; taken { + return fmt.Errorf("%w: %q", ErrDuplicateAuthority, f.Name) + } + r.factories[f.Name] = f + return nil +} + +// Lookup returns the factory registered under name. +func (r *Registry) Lookup(name string) (Factory, bool) { + r.mu.RLock() + defer r.mu.RUnlock() + f, ok := r.factories[name] + return f, ok +} + +// New builds the authority registered under name. +func (r *Registry) New(name string, options Options) (Authority, error) { + f, ok := r.Lookup(name) + if !ok { + return nil, fmt.Errorf("%w: %q (known: %v)", ErrUnknownAuthority, name, r.Names()) + } + a, err := f.New(options) + if err != nil { + return nil, fmt.Errorf("build authority %q: %w", name, err) + } + return a, nil +} + +// Names lists the registered names in order. +func (r *Registry) Names() []string { + r.mu.RLock() + defer r.mu.RUnlock() + names := make([]string, 0, len(r.factories)) + for name := range r.factories { + names = append(names, name) + } + sort.Strings(names) + return names +} + +// Register adds a factory to the Default registry. +func Register(f Factory) error { return Default.Register(f) } + +// New builds an authority from the Default registry. +func New(name string, options Options) (Authority, error) { return Default.New(name, options) } + +// Names lists the Default registry's names. +func Names() []string { return Default.Names() } diff --git a/plugins/ssh/authority/registry_test.go b/plugins/ssh/authority/registry_test.go new file mode 100644 index 00000000000..0b5fe2a310e --- /dev/null +++ b/plugins/ssh/authority/registry_test.go @@ -0,0 +1,87 @@ +package authority_test + +import ( + "fmt" + "sync" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/cloudposse/atmos/plugins/ssh/authority" + "github.com/cloudposse/atmos/plugins/ssh/authority/authoritytest" +) + +func fakeFactory(name string) authority.Factory { + return authority.Factory{Name: name, New: func(authority.Options) (authority.Authority, error) { + return authoritytest.NewFake(name), nil + }} +} + +func TestRegistry(t *testing.T) { + r := authority.NewRegistry() + require.NoError(t, r.Register(fakeFactory("beta"))) + require.NoError(t, r.Register(fakeFactory("alpha"))) + + assert.Equal(t, []string{"alpha", "beta"}, r.Names()) + a, err := r.New("beta", authority.Options{}) + require.NoError(t, err) + assert.Equal(t, "beta", a.Name()) + _, ok := r.Lookup("alpha") + assert.True(t, ok) + _, ok = r.Lookup("gamma") + assert.False(t, ok) +} + +func TestRegistryErrors(t *testing.T) { + r := authority.NewRegistry() + require.NoError(t, r.Register(fakeFactory("alpha"))) + + tests := []struct { + name string + do func() error + want error + }{ + {"duplicate", func() error { return r.Register(fakeFactory("alpha")) }, authority.ErrDuplicateAuthority}, + {"no name", func() error { return r.Register(authority.Factory{New: fakeFactory("x").New}) }, authority.ErrInvalidRequest}, + {"no constructor", func() error { return r.Register(authority.Factory{Name: "x"}) }, authority.ErrInvalidRequest}, + {"unknown", func() error { _, err := r.New("nope", authority.Options{}); return err }, authority.ErrUnknownAuthority}, + {"constructor fails", func() error { + require.NoError(t, r.Register(authority.Factory{Name: "bad", New: func(authority.Options) (authority.Authority, error) { + return nil, authority.ErrInvalidRequest + }})) + _, err := r.New("bad", authority.Options{}) + return err + }, authority.ErrInvalidRequest}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { assert.ErrorIs(t, tt.do(), tt.want) }) + } + assert.Equal(t, []string{"alpha", "bad"}, r.Names(), "failed registrations changed nothing") +} + +func TestRegistryIsSafeForConcurrentUse(t *testing.T) { + r := authority.NewRegistry() + var wg sync.WaitGroup + for _, name := range []string{"a", "b", "c", "d"} { + wg.Add(1) + go func() { + defer wg.Done() + _ = r.Register(fakeFactory(name)) + _ = r.Names() + }() + } + wg.Wait() + assert.Len(t, r.Names(), 4) +} + +func TestDefaultRegistry(t *testing.T) { + // The Default registry is process-wide, so the name must be new on every run (-count=N). + name := fmt.Sprintf("default-registry-test-%d", time.Now().UnixNano()) + require.NoError(t, authority.Register(fakeFactory(name))) + assert.Contains(t, authority.Names(), name) + a, err := authority.New(name, authority.Options{}) + require.NoError(t, err) + assert.Equal(t, name, a.Name()) +} diff --git a/plugins/ssh/authority/self/self.go b/plugins/ssh/authority/self/self.go new file mode 100644 index 00000000000..e4cef000a80 --- /dev/null +++ b/plugins/ssh/authority/self/self.go @@ -0,0 +1,45 @@ +// Package self is the authority for keys that nobody vouches for. Nothing is called: the receipt +// only records that the key was used without an upstream. +package self + +import ( + "context" + + "github.com/cloudposse/atmos/plugins/ssh/authority" +) + +// Name is the registry key of the self authority. +const Name = "self" + +// Factory builds the self authority for a registry. +var Factory = authority.Factory{ + Name: Name, + New: func(authority.Options) (authority.Authority, error) { return New(), nil }, +} + +// Authority is the no-authority case. +type Authority struct{} + +// New returns the self authority. +func New() *Authority { return &Authority{} } + +// Name implements authority.Authority. +func (*Authority) Name() string { return Name } + +// Supports implements authority.Authority. Self-asserted keys can be used for anything. +func (*Authority) Supports() []authority.Use { + return []authority.Use{authority.UseAuthentication, authority.UseSigning} +} + +// Ensure implements authority.Authority. It makes no call and ignores the credentials. +func (a *Authority) Ensure(_ context.Context, _ map[string]string, request authority.Request) (authority.Receipt, error) { + if err := authority.ValidateRequest(a, request); err != nil { + return authority.Receipt{}, err + } + receipt := authority.NewReceipt(Name, request) + receipt.Uses = authority.NormalizeUses(request.Uses) + return receipt, nil +} + +// Revoke implements authority.Authority. There is nothing to withdraw. +func (*Authority) Revoke(context.Context, map[string]string, authority.Receipt) error { return nil } diff --git a/plugins/ssh/authority/self/self_test.go b/plugins/ssh/authority/self/self_test.go new file mode 100644 index 00000000000..db0f45e3297 --- /dev/null +++ b/plugins/ssh/authority/self/self_test.go @@ -0,0 +1,45 @@ +package self_test + +import ( + "context" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/cloudposse/atmos/plugins/ssh/authority" + "github.com/cloudposse/atmos/plugins/ssh/authority/authoritytest" + "github.com/cloudposse/atmos/plugins/ssh/authority/self" +) + +func TestConformance(t *testing.T) { + authoritytest.Run(t, func(*testing.T) *authoritytest.Environment { + return &authoritytest.Environment{ + Authority: self.New(), + Credentials: map[string]string{}, + } + }) +} + +func TestEnsureMakesNoClaims(t *testing.T) { + key := authoritytest.NewKey(t) + a := self.New() + receipt, err := a.Ensure(context.Background(), nil, authority.Request{ + KeyName: "ops", Key: key, + Uses: []authority.Use{authority.UseSigning, authority.UseSigning}, + }) + require.NoError(t, err) + assert.Equal(t, "self", receipt.Authority) + assert.Empty(t, receipt.References) + assert.Empty(t, receipt.Certificate) + assert.True(t, receipt.ExpiresAt.IsZero()) + assert.Equal(t, []authority.Use{authority.UseSigning}, receipt.Uses) +} + +func TestFactoryBuildsSelf(t *testing.T) { + registry := authority.NewRegistry() + require.NoError(t, registry.Register(self.Factory)) + a, err := registry.New("self", authority.Options{}) + require.NoError(t, err) + assert.Equal(t, self.Name, a.Name()) +} diff --git a/plugins/ssh/authority/store.go b/plugins/ssh/authority/store.go new file mode 100644 index 00000000000..f581e90a8f2 --- /dev/null +++ b/plugins/ssh/authority/store.go @@ -0,0 +1,203 @@ +package authority + +import ( + "bytes" + "encoding/json" + "errors" + "fmt" + "os" + "path/filepath" + "sort" + "strings" +) + +const ( + storeVersion = 1 + tempPrefix = ".tmp-" + receiptExt = ".json" +) + +// Store keeps receipts as JSON files in a directory: one file per authority and key name. The +// files hold no credential. +type Store struct { + dir string +} + +type receiptFile struct { + Version int `json:"version"` + Receipt Receipt `json:"receipt"` +} + +// NewStore returns a store rooted at dir. The directory is created on the first Save. +func NewStore(dir string) (*Store, error) { + if dir == "" { + return nil, fmt.Errorf("%w: receipt directory is empty", ErrInvalidRequest) + } + return &Store{dir: dir}, nil +} + +// Dir returns the store's directory. +func (s *Store) Dir() string { return s.dir } + +// encodeName makes a name safe as a file name component on every platform. Letters, digits, '_' +// and '-' pass through and everything else, including '.', becomes %XX, so '.' can separate parts. +func encodeName(name string) string { + var b strings.Builder + for i := 0; i < len(name); i++ { + c := name[i] + switch { + case c >= 'a' && c <= 'z', c >= 'A' && c <= 'Z', c >= '0' && c <= '9', c == '_', c == '-': + b.WriteByte(c) + default: + fmt.Fprintf(&b, "%%%02X", c) + } + } + return b.String() +} + +func (s *Store) file(authorityName, keyName string) (string, error) { + if authorityName == "" || keyName == "" { + return "", fmt.Errorf("%w: receipts need an authority and a key name", ErrInvalidRequest) + } + return filepath.Join(s.dir, encodeName(authorityName)+"."+encodeName(keyName)+receiptExt), nil +} + +// Load reads the receipt for the key and authority. It returns ErrReceiptNotFound when there is +// none and ErrReceiptCorrupt when the file cannot be understood. +func (s *Store) Load(authorityName, keyName string) (Receipt, error) { + name, err := s.file(authorityName, keyName) + if err != nil { + return Receipt{}, err + } + data, err := os.ReadFile(name) + if errors.Is(err, os.ErrNotExist) { + return Receipt{}, fmt.Errorf("%w: %s for key %q", ErrReceiptNotFound, authorityName, keyName) + } + if err != nil { + return Receipt{}, fmt.Errorf("read receipt %s: %w", name, err) + } + r, err := decodeReceipt(name, data) + if err != nil { + return Receipt{}, err + } + if r.Authority != authorityName || r.KeyName != keyName { + return Receipt{}, fmt.Errorf("%w: %s holds %s/%q", ErrReceiptCollision, name, r.Authority, r.KeyName) + } + return r, nil +} + +func decodeReceipt(name string, data []byte) (Receipt, error) { + var f receiptFile + if err := json.Unmarshal(data, &f); err != nil { + return Receipt{}, fmt.Errorf("%w: %s: %w", ErrReceiptCorrupt, name, err) + } + if f.Version != storeVersion { + return Receipt{}, fmt.Errorf("%w: %s: unsupported version %d", ErrReceiptCorrupt, name, f.Version) + } + r := f.Receipt + if r.Authority == "" || r.KeyName == "" || r.Fingerprint == "" { + return Receipt{}, fmt.Errorf("%w: %s: missing authority, key name, or fingerprint", ErrReceiptCorrupt, name) + } + return r, nil +} + +// Save writes the receipt atomically with mode 0600, replacing any receipt for the same key and +// authority. It refuses to replace a file that belongs to a different key. +func (s *Store) Save(r Receipt) error { + name, err := s.file(r.Authority, r.KeyName) + if err != nil { + return err + } + if _, err := s.Load(r.Authority, r.KeyName); errors.Is(err, ErrReceiptCollision) { + return err + } + data, err := json.MarshalIndent(receiptFile{Version: storeVersion, Receipt: r}, "", " ") + if err != nil { + return fmt.Errorf("encode receipt: %w", err) + } + data = append(data, '\n') + if err := os.MkdirAll(s.dir, 0o700); err != nil { + return fmt.Errorf("create receipt directory: %w", err) + } + return writeAtomic(s.dir, name, data) +} + +func writeAtomic(dir, name string, data []byte) (err error) { + tmp, err := os.CreateTemp(dir, tempPrefix+"*") + if err != nil { + return fmt.Errorf("create temporary receipt: %w", err) + } + defer func() { + if err != nil { + _ = tmp.Close() + _ = os.Remove(tmp.Name()) + } + }() + // CreateTemp already creates the file with mode 0600. + if _, err = tmp.Write(data); err != nil { + return fmt.Errorf("write receipt: %w", err) + } + if err = tmp.Sync(); err != nil { + return fmt.Errorf("sync receipt: %w", err) + } + if err = tmp.Close(); err != nil { + return fmt.Errorf("close receipt: %w", err) + } + if err = os.Rename(tmp.Name(), name); err != nil { + return fmt.Errorf("replace receipt: %w", err) + } + return nil +} + +// Delete removes the receipt. A missing receipt is success. +func (s *Store) Delete(authorityName, keyName string) error { + name, err := s.file(authorityName, keyName) + if err != nil { + return err + } + if err := os.Remove(name); err != nil && !errors.Is(err, os.ErrNotExist) { + return fmt.Errorf("delete receipt: %w", err) + } + return nil +} + +// List returns every readable receipt, ordered by authority and key name. Unreadable files are +// skipped and reported together in the returned error, so one bad file hides nothing else. +func (s *Store) List() ([]Receipt, error) { + entries, err := os.ReadDir(s.dir) + if errors.Is(err, os.ErrNotExist) { + return nil, nil + } + if err != nil { + return nil, fmt.Errorf("list receipts: %w", err) + } + var ( + out []Receipt + errs []error + ) + for _, entry := range entries { + n := entry.Name() + if entry.IsDir() || strings.HasPrefix(n, tempPrefix) || !strings.HasSuffix(n, receiptExt) { + continue + } + full := filepath.Join(s.dir, n) + data, err := os.ReadFile(full) + if err != nil { + errs = append(errs, fmt.Errorf("read receipt %s: %w", full, err)) + continue + } + r, err := decodeReceipt(full, bytes.TrimSpace(data)) + if err != nil { + errs = append(errs, err) + continue + } + out = append(out, r) + } + sort.Slice(out, func(i, j int) bool { + if out[i].Authority != out[j].Authority { + return out[i].Authority < out[j].Authority + } + return out[i].KeyName < out[j].KeyName + }) + return out, errors.Join(errs...) +} diff --git a/plugins/ssh/authority/store_test.go b/plugins/ssh/authority/store_test.go new file mode 100644 index 00000000000..b304bcc8d5c --- /dev/null +++ b/plugins/ssh/authority/store_test.go @@ -0,0 +1,210 @@ +package authority_test + +import ( + "os" + "path/filepath" + "runtime" + "strings" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/cloudposse/atmos/plugins/ssh/authority" +) + +func sampleReceipt(name, fp string) authority.Receipt { + return authority.Receipt{ + Authority: "github", Subject: "octocat", KeyName: name, Fingerprint: fp, + PublicKey: "ssh-ed25519 AAAA", + Uses: []authority.Use{authority.UseSigning, authority.UseAuthentication}, + References: map[authority.Use]string{authority.UseSigning: "11", authority.UseAuthentication: "22"}, + Created: time.Date(2026, 11, 10, 12, 0, 0, 0, time.UTC), + ExpiresAt: time.Date(2027, 1, 1, 0, 0, 0, 0, time.UTC), + } +} + +func newStore(t *testing.T) *authority.Store { + t.Helper() + s, err := authority.NewStore(filepath.Join(t.TempDir(), "receipts")) + require.NoError(t, err) + return s +} + +func TestStoreRoundTrip(t *testing.T) { + s := newStore(t) + want := sampleReceipt("ops", "SHA256:abc") + want.Certificate = []byte{1, 2, 3} + + require.NoError(t, s.Save(want)) + got, err := s.Load("github", "ops") + require.NoError(t, err) + assert.Equal(t, want, got) + + want.Subject = "someone" + require.NoError(t, s.Save(want)) + got, err = s.Load("github", "ops") + require.NoError(t, err) + assert.Equal(t, "someone", got.Subject) +} + +func TestStorePermissions(t *testing.T) { + if runtime.GOOS == "windows" { + t.Skip("Unix modes do not apply") + } + s := newStore(t) + require.NoError(t, s.Save(sampleReceipt("ops", "SHA256:abc"))) + + dir, err := os.Stat(s.Dir()) + require.NoError(t, err) + assert.Equal(t, os.FileMode(0o700), dir.Mode().Perm()) + entries, err := os.ReadDir(s.Dir()) + require.NoError(t, err) + require.Len(t, entries, 1, "no temporary file is left behind") + info, err := entries[0].Info() + require.NoError(t, err) + assert.Equal(t, os.FileMode(0o600), info.Mode().Perm()) +} + +func TestStoreLoadMissing(t *testing.T) { + s := newStore(t) + _, err := s.Load("github", "ops") + assert.ErrorIs(t, err, authority.ErrReceiptNotFound) +} + +func TestStoreCorruptFile(t *testing.T) { + tests := map[string]string{ + "not json": "{{{", + "wrong version": `{"version":99,"receipt":{"authority":"github","key_name":"ops","fingerprint":"x"}}`, + "missing fields": `{"version":1,"receipt":{"authority":"github"}}`, + "empty": ``, + "unknown version": `{"receipt":{"authority":"github","key_name":"ops","fingerprint":"x"}}`, + } + for name, content := range tests { + t.Run(name, func(t *testing.T) { + s := newStore(t) + require.NoError(t, s.Save(sampleReceipt("ops", "SHA256:abc"))) + files, err := filepath.Glob(filepath.Join(s.Dir(), "*.json")) + require.NoError(t, err) + require.Len(t, files, 1) + require.NoError(t, os.WriteFile(files[0], []byte(content), 0o600)) + + _, err = s.Load("github", "ops") + assert.ErrorIs(t, err, authority.ErrReceiptCorrupt) + _, err = s.List() + assert.ErrorIs(t, err, authority.ErrReceiptCorrupt) + }) + } +} + +func TestStoreListSkipsBadFilesButReturnsTheRest(t *testing.T) { + s := newStore(t) + require.NoError(t, s.Save(sampleReceipt("zeta", "SHA256:z"))) + require.NoError(t, s.Save(sampleReceipt("alpha", "SHA256:a"))) + other := sampleReceipt("alpha", "SHA256:a") + other.Authority = "aws" + require.NoError(t, s.Save(other)) + require.NoError(t, os.WriteFile(filepath.Join(s.Dir(), "junk.json"), []byte("nope"), 0o600)) + require.NoError(t, os.WriteFile(filepath.Join(s.Dir(), ".tmp-123"), []byte("partial"), 0o600)) + require.NoError(t, os.WriteFile(filepath.Join(s.Dir(), "notes.txt"), []byte("hi"), 0o600)) + require.NoError(t, os.Mkdir(filepath.Join(s.Dir(), "sub.json"), 0o700)) + + got, err := s.List() + require.ErrorIs(t, err, authority.ErrReceiptCorrupt) + require.Len(t, got, 3) + assert.Equal(t, "aws", got[0].Authority) + assert.Equal(t, "alpha", got[1].KeyName) + assert.Equal(t, "zeta", got[2].KeyName) +} + +func TestStoreListWithoutDirectory(t *testing.T) { + s := newStore(t) + got, err := s.List() + assert.NoError(t, err) + assert.Empty(t, got) +} + +func TestStoreDelete(t *testing.T) { + s := newStore(t) + require.NoError(t, s.Save(sampleReceipt("ops", "SHA256:abc"))) + require.NoError(t, s.Delete("github", "ops")) + _, err := s.Load("github", "ops") + assert.ErrorIs(t, err, authority.ErrReceiptNotFound) + assert.NoError(t, s.Delete("github", "ops"), "deleting twice is fine") +} + +func TestStoreKeepsOddNamesInsideTheDirectory(t *testing.T) { + s := newStore(t) + names := []string{"../../etc/passwd", `a\b`, "con:1", "ops key", "ops.with.dots", "ünï", strings.Repeat("x", 40)} + for _, name := range names { + require.NoError(t, s.Save(sampleReceipt(name, "SHA256:"+name))) + } + entries, err := os.ReadDir(s.Dir()) + require.NoError(t, err) + assert.Len(t, entries, len(names)) + for _, name := range names { + got, err := s.Load("github", name) + require.NoError(t, err, name) + assert.Equal(t, name, got.KeyName) + } + parent, err := os.ReadDir(filepath.Dir(s.Dir())) + require.NoError(t, err) + assert.Len(t, parent, 1, "nothing was written outside the receipt directory") +} + +func TestStoreRefusesToOverwriteAnotherKeysFile(t *testing.T) { + s := newStore(t) + require.NoError(t, s.Save(sampleReceipt("ops", "SHA256:abc"))) + files, err := filepath.Glob(filepath.Join(s.Dir(), "*.json")) + require.NoError(t, err) + // Simulate a case-insensitive file system, where "OPS" would resolve to the same file. + data, err := os.ReadFile(files[0]) + require.NoError(t, err) + collide := filepath.Join(s.Dir(), "github.OPS.json") + require.NoError(t, os.WriteFile(collide, data, 0o600)) + + _, err = s.Load("github", "OPS") + assert.ErrorIs(t, err, authority.ErrReceiptCollision) + assert.ErrorIs(t, s.Save(sampleReceipt("OPS", "SHA256:other")), authority.ErrReceiptCollision) +} + +func TestStoreRejectsEmptyNames(t *testing.T) { + _, err := authority.NewStore("") + assert.ErrorIs(t, err, authority.ErrInvalidRequest) + s := newStore(t) + assert.ErrorIs(t, s.Save(authority.Receipt{Authority: "github"}), authority.ErrInvalidRequest) + _, err = s.Load("", "ops") + assert.ErrorIs(t, err, authority.ErrInvalidRequest) + assert.ErrorIs(t, s.Delete("github", ""), authority.ErrInvalidRequest) +} + +func TestReceiptHelpers(t *testing.T) { + r := authority.Receipt{ + Uses: []authority.Use{authority.UseSigning}, + References: map[authority.Use]string{authority.UseAuthentication: "1"}, + } + assert.Equal(t, []authority.Use{authority.UseAuthentication, authority.UseSigning}, r.EnrolledUses()) + + now := time.Now() + assert.False(t, r.Expired(now), "no expiry never expires") + r.ExpiresAt = now.Add(time.Minute) + assert.False(t, r.Expired(now)) + assert.True(t, r.Expired(now.Add(time.Minute))) + + assert.Equal(t, []authority.Use{authority.UseAuthentication, authority.UseSigning}, + authority.NormalizeUses([]authority.Use{authority.UseSigning, "", authority.UseAuthentication, authority.UseSigning})) +} + +func TestErrorText(t *testing.T) { + err := &authority.Error{ + Authority: "github", Operation: "add key", Use: authority.UseSigning, Status: 404, + Permission: "write:ssh_signing_key", RetryAfter: time.Minute, Detail: "Not Found", + Err: authority.ErrMissingPermission, + } + text := err.Error() + for _, part := range []string{"github", "add key signing", "write:ssh_signing_key", "404", "1m0s", "Not Found"} { + assert.Contains(t, text, part) + } + assert.ErrorIs(t, err, authority.ErrMissingPermission) +} diff --git a/plugins/ssh/command/agentcmd.go b/plugins/ssh/command/agentcmd.go new file mode 100644 index 00000000000..77ddd8fc883 --- /dev/null +++ b/plugins/ssh/command/agentcmd.go @@ -0,0 +1,209 @@ +package command + +import ( + "bytes" + "errors" + "io" + "os" + "strings" + + "github.com/cloudposse/atmos/plugins/ssh/agent" + "github.com/cloudposse/atmos/plugins/ssh/daemon" + "github.com/cloudposse/atmos/plugins/ssh/service" +) + +const ( + // defaultLogLines is how many audit log lines "agent log" prints. + defaultLogLines = 20 + // maxLogRead bounds how much of the audit log is read to find its last lines. + maxLogRead = 1 << 20 +) + +// agentStart installs and starts the agent service, or restarts it when it is out of date. +func (c *call) agentStart(words []string) error { + if err := c.flags.only(); err != nil { + return err + } + if err := exactly(words, 0, "agent start"); err != nil { + return err + } + res, err := daemon.Ensure(c.ctx, c.svc.deps.Daemon, c.paths) + if err != nil { + return err + } + if res.Installed { + c.printf("Installed and started the agent service (version %s).\n", c.svc.deps.Daemon.Version) + return nil + } + c.printf("The agent is already running (pid %d, version %s).\n", res.Status.PID, res.Status.DaemonVersion) + return nil +} + +func (c *call) manager() (service.Manager, error) { + return c.svc.deps.Daemon.Service(c.paths) +} + +// agentStop stops the agent service and keeps it stopped. +func (c *call) agentStop(words []string) error { + if err := c.flags.only(); err != nil { + return err + } + if err := exactly(words, 0, "agent stop"); err != nil { + return err + } + mgr, err := c.manager() + if err != nil { + return err + } + if err := mgr.Stop(c.ctx); err != nil { + return err + } + c.printf("Stopped the agent service. Using an identity starts it again.\n") + return nil +} + +// agentStatus reports whether the daemon runs, which version, and which sockets it serves. +func (c *call) agentStatus(words []string) error { + if err := c.flags.only(); err != nil { + return err + } + if err := exactly(words, 0, "agent status"); err != nil { + return err + } + mgr, err := c.manager() + if err != nil { + return err + } + st, err := mgr.Status(c.ctx) + if err != nil { + return err + } + c.printStatus(st) + return c.printSockets() +} + +func (c *call) printStatus(st service.Status) { + plugin := c.svc.deps.Daemon.Version + field := func(label string, value any) { c.printf("%-19s %v\n", label+":", value) } + field("Service installed", st.Installed) + field("Running", st.Running) + if st.Running { + field("PID", st.PID) + } + field("Plugin version", plugin) + field("Installed version", orDash(st.InstalledVersion)) + field("Daemon version", orDash(st.DaemonVersion)) + if st.Executable != "" { + field("Executable", st.Executable) + } + if st.DefinitionPath != "" { + field("Definition", st.DefinitionPath) + } + if st.LogFile != "" { + field("Service log", st.LogFile) + } + field("Audit log", c.paths.AuditLogFile()) + switch { + case st.VersionMismatch: + c.printf("\nThe running daemon (%s) is not the installed version (%s). Run \"agent start\" to replace it.\n", orDash(st.DaemonVersion), orDash(st.InstalledVersion)) + case st.Installed && st.InstalledVersion != plugin: + c.printf("\nThe installed daemon (%s) is not this plugin's version (%s). Run \"agent start\" to update it.\n", orDash(st.InstalledVersion), plugin) + } +} + +// printSockets lists the sockets the configuration asks for and whether each one answers. +func (c *call) printSockets() error { + cfg, err := agent.LoadConfig(c.paths.AgentConfigFile()) + if errors.Is(err, agent.ErrConfigNotFound) { + c.printf("\nNo identities are configured.\n") + return nil + } + if err != nil { + return err + } + c.printf("\nSockets:\n") + for _, id := range cfg.Identities { + socket, err := c.paths.SocketPath(id.Name) + if err != nil { + return err + } + state := "serving" + if err := c.svc.deps.CheckSocket(c.ctx, socket, nil); err != nil { + state = "not serving (" + err.Error() + ")" + } + c.printf(" %s %s allow=%s %s\n", id.Name, socket, allowText(id.Allow), state) + } + return nil +} + +func allowText(allow []agent.Allow) string { + out := make([]string, len(allow)) + for i, a := range allow { + out[i] = string(a) + } + return strings.Join(out, ",") +} + +// agentLog prints the last lines of the audit log. +func (c *call) agentLog(words []string) error { + if err := c.flags.only("lines"); err != nil { + return err + } + if err := exactly(words, 0, "agent log [--lines N]"); err != nil { + return err + } + n, err := c.flags.count("lines", defaultLogLines) + if err != nil { + return err + } + lines, err := tailLines(c.paths.AuditLogFile(), n) + if errors.Is(err, os.ErrNotExist) { + c.printf("No audit log yet: %s\n", c.paths.AuditLogFile()) + return nil + } + if err != nil { + return err + } + for _, l := range lines { + c.printf("%s\n", l) + } + return nil +} + +// tailLines returns the last n lines of the file at path, reading at most maxLogRead bytes. +func tailLines(path string, n int) ([]string, error) { + f, err := os.Open(path) + if err != nil { + return nil, err + } + defer f.Close() + info, err := f.Stat() + if err != nil { + return nil, err + } + offset, truncated := int64(0), false + if info.Size() > maxLogRead { + offset, truncated = info.Size()-maxLogRead, true + } + if _, err := f.Seek(offset, io.SeekStart); err != nil { + return nil, err + } + data, err := io.ReadAll(f) + if err != nil { + return nil, err + } + if truncated { + // The first line is probably cut in half. + if i := bytes.IndexByte(data, '\n'); i >= 0 { + data = data[i+1:] + } + } + lines := strings.Split(strings.TrimRight(string(data), "\n"), "\n") + if len(lines) == 1 && lines[0] == "" { + return nil, nil + } + if len(lines) > n { + lines = lines[len(lines)-n:] + } + return lines, nil +} diff --git a/plugins/ssh/command/agentcmd_test.go b/plugins/ssh/command/agentcmd_test.go new file mode 100644 index 00000000000..fc625952c12 --- /dev/null +++ b/plugins/ssh/command/agentcmd_test.go @@ -0,0 +1,193 @@ +package command_test + +import ( + "errors" + "fmt" + "os" + "strings" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/cloudposse/atmos/plugins/ssh/agent" + "github.com/cloudposse/atmos/plugins/ssh/command" + "github.com/cloudposse/atmos/plugins/ssh/service" +) + +func runningStatus() service.Status { + return service.Status{ + Installed: true, Loaded: true, Running: true, PID: 321, Executable: "/data/bin/atmos-ssh-0.1.0", + InstalledVersion: version, DaemonVersion: version, DefinitionPath: "/agents/x.plist", LogFile: "/data/agent.log", + } +} + +func TestAgentStatusOfACurrentDaemon(t *testing.T) { + r := newRig(t) + r.mgr.St = runningStatus() + r.configure(agent.Identity{Name: "ops", Store: "file", Key: "ops", Allow: []agent.Allow{agent.AllowSigning, agent.AllowAuthentication}}) + + code, out, errOut := r.run("agent", "status") + + require.Equal(t, command.ExitOK, code, errOut) + for _, want := range []string{"Service installed: true", "Running: true", "PID: 321", "Plugin version: 0.1.0", "Installed version: 0.1.0", "Daemon version: 0.1.0", "Audit log:"} { + assert.Contains(t, out, want) + } + assert.NotContains(t, out, "Run \"agent start\"") + socket, err := r.paths.SocketPath("ops") + require.NoError(t, err) + assert.Contains(t, out, "ops "+socket+" allow=signing,authentication serving") +} + +func TestAgentStatusReportsAVersionMismatch(t *testing.T) { + r := newRig(t) + st := runningStatus() + st.DaemonVersion, st.VersionMismatch = "0.0.9", true + r.mgr.St = st + + code, out, _ := r.run("agent", "status") + + assert.Equal(t, command.ExitOK, code) + assert.Contains(t, out, "Daemon version: 0.0.9") + assert.Contains(t, out, "The running daemon (0.0.9) is not the installed version (0.1.0). Run \"agent start\" to replace it.") +} + +func TestAgentStatusReportsAnInstalledCopyThatIsNotThisPluginsVersion(t *testing.T) { + r := newRig(t) + st := runningStatus() + st.InstalledVersion, st.DaemonVersion = "0.0.9", "0.0.9" + r.mgr.St = st + + _, out, _ := r.run("agent", "status") + + assert.Contains(t, out, "The installed daemon (0.0.9) is not this plugin's version (0.1.0)") +} + +func TestAgentStatusOfNothingInstalled(t *testing.T) { + r := newRig(t) + + code, out, _ := r.run("agent", "status") + + assert.Equal(t, command.ExitOK, code) + assert.Contains(t, out, "Service installed: false") + assert.Contains(t, out, "Running: false") + assert.Contains(t, out, "No identities are configured.") +} + +func TestAgentStatusNamesSocketsThatDoNotAnswer(t *testing.T) { + r := newRig(t) + r.mgr.St = runningStatus() + r.configure(agent.Identity{Name: "ops", Store: "file", Key: "ops", Allow: []agent.Allow{agent.AllowSigning}}) + r.socketErr = errors.New("connection refused") + + _, out, _ := r.run("agent", "status") + + assert.Contains(t, out, "not serving (connection refused)") +} + +func TestAgentStatusFailsWhenTheServiceCannotBeQueried(t *testing.T) { + r := newRig(t) + r.mgr.StatusErr = errors.New("launchctl exploded") + + code, _, errOut := r.run("agent", "status") + + assert.Equal(t, command.ExitFailure, code) + assert.Contains(t, errOut, "launchctl exploded") +} + +func TestAgentStartInstallsAndStartsTheService(t *testing.T) { + r := newRig(t) + + code, out, errOut := r.run("agent", "start") + + require.Equal(t, command.ExitOK, code, errOut) + assert.Contains(t, out, "Installed and started the agent service (version 0.1.0)") + require.Equal(t, 1, r.mgr.InstallCount()) + assert.Equal(t, []string{"agent-serve", "--root", r.paths.Root()}, r.mgr.Installs[0].Args) + assert.Equal(t, 1, r.mgr.Starts) +} + +func TestAgentStartLeavesARunningCurrentDaemonAlone(t *testing.T) { + r := newRig(t) + r.mgr.St = runningStatus() + + code, out, _ := r.run("agent", "start") + + assert.Equal(t, command.ExitOK, code) + assert.Contains(t, out, "already running (pid 321, version 0.1.0)") + assert.Zero(t, r.mgr.InstallCount()) +} + +func TestAgentStartReplacesAMismatchedDaemon(t *testing.T) { + r := newRig(t) + st := runningStatus() + st.VersionMismatch = true + r.mgr.St = st + + code, _, _ := r.run("agent", "start") + + assert.Equal(t, command.ExitOK, code) + assert.Equal(t, 1, r.mgr.InstallCount()) +} + +func TestAgentStartReportsAnInstallFailure(t *testing.T) { + r := newRig(t) + r.mgr.InstallErr = service.ErrCommandFailed + + code, _, errOut := r.run("agent", "start") + + assert.Equal(t, command.ExitFailure, code) + assert.Contains(t, errOut, "install the agent service") +} + +func TestAgentStop(t *testing.T) { + r := newRig(t) + r.mgr.St = runningStatus() + + code, out, _ := r.run("agent", "stop") + + assert.Equal(t, command.ExitOK, code) + assert.Equal(t, 1, r.mgr.Stops) + assert.Contains(t, out, "Stopped the agent service") +} + +func TestAgentLogPrintsTheTailOfTheAuditLog(t *testing.T) { + r := newRig(t) + var b strings.Builder + for i := 1; i <= 30; i++ { + fmt.Fprintf(&b, "{\"n\":%d}\n", i) + } + r.writeFile(r.paths.AuditLogFile(), b.String()) + + _, def, _ := r.run("agent", "log") + _, two, _ := r.run("agent", "log", "--lines", "2") + + assert.Equal(t, 20, strings.Count(def, "\n")) + assert.True(t, strings.HasPrefix(def, "{\"n\":11}\n")) + assert.Equal(t, "{\"n\":29}\n{\"n\":30}\n", two) +} + +func TestAgentLogOfALargeFileReadsOnlyTheEnd(t *testing.T) { + r := newRig(t) + line := strings.Repeat("x", 99) + "\n" + r.writeFile(r.paths.AuditLogFile(), strings.Repeat(line, 20000)+"last\n") + + _, out, _ := r.run("agent", "log", "--lines", "2") + + assert.Equal(t, strings.Repeat("x", 99)+"\nlast\n", out) +} + +func TestAgentLogWithoutALogOrWithAnEmptyOne(t *testing.T) { + r := newRig(t) + + code, out, _ := r.run("agent", "log") + assert.Equal(t, command.ExitOK, code) + assert.Contains(t, out, "No audit log yet") + + r.writeFile(r.paths.AuditLogFile(), "") + code, out, _ = r.run("agent", "log") + assert.Equal(t, command.ExitOK, code) + assert.Empty(t, out) + + require.NoError(t, os.Remove(r.paths.AuditLogFile())) +} diff --git a/plugins/ssh/command/args.go b/plugins/ssh/command/args.go new file mode 100644 index 00000000000..9ea643957c6 --- /dev/null +++ b/plugins/ssh/command/args.go @@ -0,0 +1,140 @@ +package command + +import ( + "fmt" + "strconv" + "strings" + "time" +) + +// Flags the commands understand. Value flags take the next token or "=value". +var ( + valueFlags = []string{"root", "format", "lines", "soak", "interval", "store"} + boolFlags = []string{"yes", "help"} +) + +// flags is a parsed command line: the words, and the flags found anywhere among them. +type flags struct { + words []string + values map[string]string + bools map[string]bool +} + +// parseFlags splits raw tokens into words and flags. "--" ends flag parsing. "-h" means "--help". +func parseFlags(args []string) (flags, error) { + f := flags{values: map[string]string{}, bools: map[string]bool{}} + for i := 0; i < len(args); i++ { + arg := args[i] + switch { + case arg == "--": + f.words = append(f.words, args[i+1:]...) + return f, nil + case arg == "-h": + f.bools["help"] = true + case strings.HasPrefix(arg, "--") && len(arg) > 2: + next, err := f.take(arg[2:], args, i) + if err != nil { + return flags{}, err + } + i = next + case strings.HasPrefix(arg, "-") && len(arg) > 1: + return flags{}, usagef("unknown flag %q", arg) + default: + f.words = append(f.words, arg) + } + } + return f, nil +} + +// take consumes the flag at args[i] and returns the index of the last token it used. +func (f *flags) take(spec string, args []string, i int) (int, error) { + name, value, hasValue := strings.Cut(spec, "=") + switch { + case contains(boolFlags, name): + if hasValue { + return i, usagef("flag --%s takes no value", name) + } + f.bools[name] = true + case contains(valueFlags, name): + if !hasValue { + if i+1 >= len(args) { + return i, usagef("flag --%s needs a value", name) + } + i++ + value = args[i] + } + if value == "" { + return i, usagef("flag --%s needs a value", name) + } + f.values[name] = value + default: + return i, usagef("unknown flag --%s", name) + } + return i, nil +} + +func contains(list []string, s string) bool { + for _, v := range list { + if v == s { + return true + } + } + return false +} + +// only fails when a flag other than the allowed ones was given. --root and --help are always +// allowed. +func (f flags) only(allowed ...string) error { + for name := range f.values { + if name != "root" && !contains(allowed, name) { + return usagef("flag --%s does not apply to this command", name) + } + } + for name := range f.bools { + if name != "help" && !contains(allowed, name) { + return usagef("flag --%s does not apply to this command", name) + } + } + return nil +} + +// exactly checks the number of positional words after the command path. +func exactly(words []string, n int, usage string) error { + if len(words) != n { + return usagef("usage: %s", usage) + } + return nil +} + +func (f flags) duration(name string, def time.Duration) (time.Duration, error) { + v, ok := f.values[name] + if !ok { + return def, nil + } + d, err := time.ParseDuration(v) + if err != nil || d < 0 { + return 0, usagef("--%s %q is not a duration such as 30s or 10m", name, v) + } + return d, nil +} + +func (f flags) count(name string, def int) (int, error) { + v, ok := f.values[name] + if !ok { + return def, nil + } + n, err := strconv.Atoi(v) + if err != nil || n < 1 { + return 0, usagef("--%s %q is not a positive number", name, v) + } + return n, nil +} + +// usageError is a mistake in how the command was called. It exits with code 2. +type usageError struct{ msg string } + +func (e *usageError) Error() string { return e.msg } + +func usagef(format string, args ...any) error { + return &usageError{msg: fmt.Sprintf(format, args...)} +} diff --git a/plugins/ssh/command/command.go b/plugins/ssh/command/command.go new file mode 100644 index 00000000000..91ff07b11d3 --- /dev/null +++ b/plugins/ssh/command/command.go @@ -0,0 +1,182 @@ +// Package command implements the "ssh" plugin command: key and agent management and the +// manual acceptance test. +// +// Commands run with HTTP only: they have no private state, no credentials, and no way to prompt. +// So they never call an authority. Every change at an authority goes through login or logout. +package command + +import ( + "context" + "errors" + "fmt" + "io" + "net" + "strings" + "time" + + "golang.org/x/crypto/ssh" + + "github.com/cloudposse/atmos/plugins/ssh/agent" + "github.com/cloudposse/atmos/plugins/ssh/daemon" + "github.com/cloudposse/atmos/plugins/ssh/paths" +) + +// Exit codes. +const ( + ExitOK = 0 + ExitFailure = 1 + ExitUsage = 2 +) + +// ErrRefused means a command declined to act because it was not confirmed. +var ErrRefused = errors.New("refused") + +// Deps are the outside dependencies of the commands. +type Deps struct { + // Paths returns the data root; an empty root means the default location. + Paths func(root string) (*paths.Paths, error) + // OpenStore builds a key store. + OpenStore agent.StoreOpener + // Daemon starts and inspects the agent service. + Daemon daemon.Deps + // CheckSocket verifies that a socket answers. + CheckSocket func(ctx context.Context, socket string, want ssh.PublicKey) error + // Dial connects to an agent socket. + Dial func(ctx context.Context, socket string) (net.Conn, error) + // Now is the clock. + Now func() time.Time + // Sleep waits for d, or until ctx ends. + Sleep func(ctx context.Context, d time.Duration) error + // Hostname returns the machine's name, for key titles. + Hostname func() (string, error) +} + +// Service runs the commands. +type Service struct { + deps Deps +} + +// New returns the command service. +func New(deps Deps) *Service { return &Service{deps: deps} } + +// call is one command invocation. +type call struct { + svc *Service + ctx context.Context + out io.Writer + err io.Writer + flags flags + paths *paths.Paths +} + +type handler func(c *call, words []string) error + +// route is one command path and its handler. +type route struct { + path []string + run handler +} + +var routes = []route{ + {[]string{"key", "list"}, (*call).keyList}, + {[]string{"key", "show"}, (*call).keyShow}, + {[]string{"key", "status"}, (*call).keyStatus}, + {[]string{"key", "delete"}, (*call).keyDelete}, + {[]string{"agent", "start"}, (*call).agentStart}, + {[]string{"agent", "stop"}, (*call).agentStop}, + {[]string{"agent", "status"}, (*call).agentStatus}, + {[]string{"agent", "log"}, (*call).agentLog}, + {[]string{"test"}, (*call).test}, +} + +// Run executes the command named by args and returns its exit code. settings is the "config" map +// of the command's package alias; its "root" entry relocates the plugin's data directory. +func (s *Service) Run(ctx context.Context, args []string, settings map[string]any, stdout, stderr io.Writer) int { + f, err := parseFlags(args) + if err != nil { + return report(stderr, err) + } + if f.bools["help"] || len(f.words) == 0 || f.words[0] == "help" { + fmt.Fprint(stdout, usage) + return ExitOK + } + r, rest, ok := lookup(f.words) + if !ok { + return report(stderr, usagef("unknown command %q; run \"help\" for the list", strings.Join(f.words, " "))) + } + p, err := s.deps.Paths(root(f, settings)) + if err != nil { + return report(stderr, err) + } + c := &call{svc: s, ctx: ctx, out: stdout, err: stderr, flags: f, paths: p} + if err := r.run(c, rest); err != nil { + return report(stderr, err) + } + return ExitOK +} + +// root picks the data root: the --root flag, then the command settings. +func root(f flags, settings map[string]any) string { + if v, ok := f.values["root"]; ok { + return v + } + v, _ := settings["root"].(string) + return v +} + +func lookup(words []string) (route, []string, bool) { + for _, r := range routes { + if len(words) >= len(r.path) && equalWords(words[:len(r.path)], r.path) { + return r, words[len(r.path):], true + } + } + return route{}, nil, false +} + +func equalWords(a, b []string) bool { + for i := range a { + if a[i] != b[i] { + return false + } + } + return true +} + +// report prints err on w and returns the exit code it deserves. +func report(w io.Writer, err error) int { + var u *usageError + if errors.As(err, &u) { + fmt.Fprintf(w, "Error: %s\n", u.msg) + return ExitUsage + } + fmt.Fprintf(w, "Error: %v\n", err) + return ExitFailure +} + +func (c *call) printf(format string, args ...any) { fmt.Fprintf(c.out, format, args...) } + +const usage = `Manage SSH keys and the agent that serves them. + +Usage: + key list Keys on this machine, across key stores. + key show [--format F] Print a key. F is authorized-key (default), + allowed-signers, github, or json. + key status [] Each key's store, requirements, authority, + expiry, and the last login result and error. + key delete --yes Delete the local key and its agent entry. The + authority is updated at the next login or logout. + agent start | stop | status Run, stop, or inspect the agent service. + agent log [--lines N] Print the tail of the audit log. + test [--soak D] [--interval D] + Sign a Git payload through the identity's socket + and verify it. --soak repeats it every interval + for D, one line per attempt. + help Print this text. + +Flags: + --root Use this data directory instead of the default. The "root" entry + of the command's config does the same. + --store Pick the key store when a name exists in more than one. + +Keys are created by "atmos auth login". Commands never contact an authority. +` diff --git a/plugins/ssh/command/command_test.go b/plugins/ssh/command/command_test.go new file mode 100644 index 00000000000..62fe805d6d4 --- /dev/null +++ b/plugins/ssh/command/command_test.go @@ -0,0 +1,125 @@ +package command_test + +import ( + "os" + "strings" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "gopkg.in/yaml.v3" + + "github.com/cloudposse/atmos/plugins/ssh/command" +) + +func TestHelp(t *testing.T) { + for _, args := range [][]string{{}, {"help"}, {"--help"}, {"-h"}, {"key", "list", "--help"}} { + t.Run(strings.Join(args, " "), func(t *testing.T) { + code, out, errOut := newRig(t).run(args...) + + assert.Equal(t, command.ExitOK, code) + assert.Contains(t, out, "Usage:") + assert.Empty(t, errOut) + }) + } +} + +// The command fixture in plugin.tests.yaml pins the help text byte for byte, so a change to either +// one without the other fails here before it fails in "atmos plugin test". +func TestHelpMatchesThePluginFixture(t *testing.T) { + data, err := os.ReadFile("../plugin.tests.yaml") + require.NoError(t, err) + var fixture struct { + Commands []struct { + Arguments []string `yaml:"arguments"` + Stdout string `yaml:"stdout"` + } `yaml:"commands"` + } + require.NoError(t, yaml.Unmarshal(data, &fixture)) + require.NotEmpty(t, fixture.Commands) + + for _, c := range fixture.Commands { + _, out, _ := newRig(t).run(c.Arguments...) + assert.Equal(t, c.Stdout, out) + } +} + +func TestMistakesExitWithUsageCode(t *testing.T) { + tests := []struct { + name string + args []string + want string + }{ + {"unknown command", []string{"frobnicate"}, "unknown command"}, + {"half a command", []string{"key"}, "unknown command"}, + {"unknown flag", []string{"key", "list", "--bogus"}, "unknown flag --bogus"}, + {"short flag", []string{"key", "list", "-x"}, "unknown flag"}, + {"flag without value", []string{"key", "show", "ops", "--format"}, "needs a value"}, + {"bool flag with value", []string{"key", "delete", "ops", "--yes=true"}, "takes no value"}, + {"flag of another command", []string{"key", "list", "--yes"}, "does not apply"}, + {"missing name", []string{"key", "show"}, "usage: key show"}, + {"extra argument", []string{"agent", "status", "extra"}, "usage: agent status"}, + {"bad format", []string{"key", "show", "ops", "--format", "xml"}, "unknown format"}, + {"bad lines", []string{"agent", "log", "--lines", "zero"}, "not a positive number"}, + {"bad duration", []string{"test", "ops", "--soak", "soon"}, "not a duration"}, + {"zero interval", []string{"test", "ops", "--soak", "1m", "--interval", "0s"}, "longer than zero"}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + r := newRig(t) + r.createKey("ops") + + code, out, errOut := r.run(tt.args...) + + assert.Equal(t, command.ExitUsage, code) + assert.Empty(t, out) + assert.Contains(t, errOut, tt.want) + }) + } +} + +func TestFlagsMayComeBeforeTheCommandAndTakeEqualsForm(t *testing.T) { + r := newRig(t) + r.createKey("ops") + + code, out, _ := r.run("--root="+r.paths.Root(), "key", "show", "ops", "--format=json") + + assert.Equal(t, command.ExitOK, code) + assert.Contains(t, out, `"name": "ops"`) +} + +func TestDoubleDashEndsFlags(t *testing.T) { + r := newRig(t) + + code, _, errOut := r.run("key", "show", "--", "--format") + + assert.Equal(t, command.ExitFailure, code, "the word after -- is a key name") + assert.Contains(t, errOut, "no such key") +} + +func TestRootComesFromTheFlagThenTheSettings(t *testing.T) { + dir := t.TempDir() + tests := []struct { + name string + settings map[string]any + args []string + want string + }{ + {"neither", nil, []string{"key", "list"}, ""}, + {"settings", map[string]any{"root": dir}, []string{"key", "list"}, dir}, + {"flag", nil, []string{"key", "list", "--root", dir}, dir}, + {"flag wins", map[string]any{"root": "/ignored"}, []string{"key", "list", "--root", dir}, dir}, + {"settings of another type", map[string]any{"root": 5}, []string{"key", "list"}, ""}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + r := newRig(t) + + code, _, errOut := r.runWith(tt.settings, tt.args...) + + assert.Equal(t, command.ExitOK, code, errOut) + require.Len(t, r.roots, 1) + assert.Equal(t, tt.want, r.roots[0]) + }) + } +} diff --git a/plugins/ssh/command/keys.go b/plugins/ssh/command/keys.go new file mode 100644 index 00000000000..825e5a1738f --- /dev/null +++ b/plugins/ssh/command/keys.go @@ -0,0 +1,214 @@ +package command + +import ( + "encoding/json" + "errors" + "fmt" + "strings" + "text/tabwriter" + "time" + + "github.com/cloudposse/atmos/plugins/ssh/agent" + "github.com/cloudposse/atmos/plugins/ssh/authority" + "github.com/cloudposse/atmos/plugins/ssh/inventory" + "github.com/cloudposse/atmos/plugins/ssh/keystore" +) + +// Settings page for adding an SSH key on GitHub. +const githubKeysURL = "https://github.com/settings/ssh/new" + +// ErrNoSuchKey means no key has the name asked for. +var ErrNoSuchKey = errors.New("no such key") + +// ErrAmbiguousKey means a name exists in more than one key store. +var ErrAmbiguousKey = errors.New("key name exists in more than one store") + +// Output formats of "key show". +const ( + formatAuthorizedKey = "authorized-key" + formatAllowedSigners = "allowed-signers" + formatGitHub = "github" + formatJSON = "json" +) + +// keyList prints the keys of every store. +func (c *call) keyList(words []string) error { + if err := c.flags.only(); err != nil { + return err + } + if err := exactly(words, 0, "key list"); err != nil { + return err + } + keys, err := inventory.List(c.ctx, c.svc.deps.OpenStore, c.paths) + if err != nil { + fmt.Fprintf(c.err, "Warning: %v\n", err) + } + if len(keys) == 0 { + c.printf("No keys on this machine.\n") + return nil + } + w := tabwriter.NewWriter(c.out, 0, 0, 3, ' ', 0) + fmt.Fprintln(w, "KEY\tSTORE\tREQUIRE\tFINGERPRINT\tCREATED") + for _, k := range keys { + fmt.Fprintf(w, "%s\t%s\t%s\t%s\t%s\n", k.Name, k.Store, requireText(k.Requirements), authority.Fingerprint(k.PublicKey), dateText(k.Created)) + } + return w.Flush() +} + +func requireText(terms []keystore.Requirement) string { + if len(terms) == 0 { + return "-" + } + out := make([]string, len(terms)) + for i, t := range terms { + out[i] = string(t) + } + return strings.Join(out, ",") +} + +func dateText(t time.Time) string { + if t.IsZero() { + return "-" + } + return t.UTC().Format("2006-01-02") +} + +// find returns the key called name, in the store given by --store when there are several. +func (c *call) find(name string) (keystore.Info, error) { + keys, err := inventory.List(c.ctx, c.svc.deps.OpenStore, c.paths) + store := c.flags.values["store"] + var matches []keystore.Info + for _, k := range keys { + if k.Name == name && (store == "" || k.Store == store) { + matches = append(matches, k) + } + } + switch { + case len(matches) == 1: + return matches[0], nil + case len(matches) > 1: + return keystore.Info{}, fmt.Errorf("%w: %q; choose one with --store", ErrAmbiguousKey, name) + case err != nil: + return keystore.Info{}, fmt.Errorf("%w: %q (some stores could not be listed: %v)", ErrNoSuchKey, name, err) + default: + return keystore.Info{}, fmt.Errorf("%w: %q", ErrNoSuchKey, name) + } +} + +// keyShow prints one key in the requested format. +func (c *call) keyShow(words []string) error { + if err := c.flags.only("format", "store"); err != nil { + return err + } + if err := exactly(words, 1, "key show [--format authorized-key|allowed-signers|github|json]"); err != nil { + return err + } + k, err := c.find(words[0]) + if err != nil { + return err + } + format := c.flags.values["format"] + if format == "" { + format = formatAuthorizedKey + } + line := authority.AuthorizedKey(k.PublicKey) + switch format { + case formatAuthorizedKey: + c.printf("%s %s\n", line, k.Name) + case formatAllowedSigners: + c.printf("* namespaces=\"git\" %s\n", line) + case formatGitHub: + c.showGitHub(k, line) + case formatJSON: + return c.showJSON(k, line) + default: + return usagef("unknown format %q (known: %s, %s, %s, %s)", format, formatAuthorizedKey, formatAllowedSigners, formatGitHub, formatJSON) + } + return nil +} + +func (c *call) showGitHub(k keystore.Info, line string) { + host, err := c.svc.deps.Hostname() + if err != nil || host == "" { + host = "this-machine" + } + title := fmt.Sprintf("%s@%s (Atmos)", k.Name, host) + c.printf("Public key:\n %s\n\n", line) + c.printf("Add it on GitHub (choose \"Signing Key\" as the key type):\n %s\n\n", githubKeysURL) + c.printf("Or with the GitHub CLI:\n echo '%s' | gh ssh-key add --type signing --title '%s'\n", line, title) + c.printf(" echo '%s' | gh ssh-key add --type authentication --title '%s' # to log in over SSH\n", line, title) +} + +func (c *call) showJSON(k keystore.Info, line string) error { + reqs := make([]string, len(k.Requirements)) + for i, r := range k.Requirements { + reqs[i] = string(r) + } + data, err := json.MarshalIndent(map[string]any{ + "name": k.Name, "store": k.Store, "require": reqs, + "fingerprint": authority.Fingerprint(k.PublicKey), "created": k.Created.UTC().Format(time.RFC3339), + "public_key": line, + }, "", " ") + if err != nil { + return fmt.Errorf("encode key: %w", err) + } + c.printf("%s\n", data) + return nil +} + +// keyDelete deletes a local key and its agent entries. It leaves the receipt, so the next login or +// logout withdraws the enrollment. +func (c *call) keyDelete(words []string) error { + if err := c.flags.only("yes", "store"); err != nil { + return err + } + if err := exactly(words, 1, "key delete --yes"); err != nil { + return err + } + if !c.flags.bools["yes"] { + return fmt.Errorf("%w: deleting key %q cannot be undone and commands cannot ask; run again with --yes", ErrRefused, words[0]) + } + k, err := c.find(words[0]) + if err != nil { + return err + } + store, err := c.svc.deps.OpenStore(k.Store, c.paths.StoreDir(k.Store)) + if err != nil { + return err + } + if err := store.Delete(c.ctx, k.Name); err != nil { + return fmt.Errorf("delete key %q: %w", k.Name, err) + } + removed, err := c.removeAgentEntries(k) + if err != nil { + return err + } + c.printf("Deleted key %q from the %s store.\n", k.Name, k.Store) + if len(removed) > 0 { + c.printf("Removed from the agent: %s.\n", strings.Join(removed, ", ")) + } + c.printf("Its enrollment, if any, is withdrawn at the next \"atmos auth login\" or \"atmos auth logout\".\n") + return nil +} + +// removeAgentEntries takes every identity that used the key out of the agent configuration. +func (c *call) removeAgentEntries(k keystore.Info) ([]string, error) { + cfg, err := agent.LoadConfig(c.paths.AgentConfigFile()) + if errors.Is(err, agent.ErrConfigNotFound) { + return nil, nil + } + if err != nil { + return nil, err + } + var removed []string + for _, id := range cfg.Identities { + if id.Store != k.Store || id.Key != k.Name { + continue + } + if _, err := agent.RemoveIdentity(c.paths.AgentConfigFile(), id.Name); err != nil { + return removed, err + } + removed = append(removed, id.Name) + } + return removed, nil +} diff --git a/plugins/ssh/command/keys_test.go b/plugins/ssh/command/keys_test.go new file mode 100644 index 00000000000..96063c9cce4 --- /dev/null +++ b/plugins/ssh/command/keys_test.go @@ -0,0 +1,246 @@ +package command_test + +import ( + "encoding/json" + "strings" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/cloudposse/atmos/plugins/ssh/agent" + "github.com/cloudposse/atmos/plugins/ssh/authority" + "github.com/cloudposse/atmos/plugins/ssh/command" + "github.com/cloudposse/atmos/plugins/ssh/statusfile" +) + +func TestKeyListWithNoKeys(t *testing.T) { + code, out, _ := newRig(t).run("key", "list") + + assert.Equal(t, command.ExitOK, code) + assert.Equal(t, "No keys on this machine.\n", out) +} + +func TestKeyListShowsStoreRequirementsFingerprintAndDate(t *testing.T) { + r := newRig(t) + b := r.createKey("beta") + r.createKey("alpha") + + code, out, errOut := r.run("key", "list") + + require.Equal(t, command.ExitOK, code, errOut) + lines := strings.Split(strings.TrimSpace(out), "\n") + require.Len(t, lines, 3) + assert.Equal(t, []string{"KEY", "STORE", "REQUIRE", "FINGERPRINT", "CREATED"}, strings.Fields(lines[0])) + alpha := strings.Fields(lines[1]) + assert.Equal(t, "alpha", alpha[0]) + assert.Equal(t, "file", alpha[1]) + assert.Equal(t, "-", alpha[2]) + assert.True(t, strings.HasPrefix(alpha[3], "SHA256:")) + beta := strings.Fields(lines[2]) + assert.Equal(t, authority.Fingerprint(b), beta[3]) + assert.Equal(t, time.Now().UTC().Format("2006-01-02"), beta[4]) +} + +func TestKeyShowFormats(t *testing.T) { + r := newRig(t) + pub := r.createKey("ops") + line := authority.AuthorizedKey(pub) + + t.Run("authorized-key is the default", func(t *testing.T) { + code, out, _ := r.run("key", "show", "ops") + assert.Equal(t, command.ExitOK, code) + assert.Equal(t, line+" ops\n", out) + }) + t.Run("allowed-signers", func(t *testing.T) { + code, out, _ := r.run("key", "show", "ops", "--format", "allowed-signers") + assert.Equal(t, command.ExitOK, code) + assert.Equal(t, `* namespaces="git" `+line+"\n", out) + }) + t.Run("github", func(t *testing.T) { + code, out, _ := r.run("key", "show", "ops", "--format", "github") + assert.Equal(t, command.ExitOK, code) + assert.Contains(t, out, line) + assert.Contains(t, out, "https://github.com/settings/ssh/new") + assert.Contains(t, out, "gh ssh-key add --type signing --title 'ops@testhost (Atmos)'") + assert.Contains(t, out, "echo '"+line+"' | gh ssh-key add") + }) + t.Run("json", func(t *testing.T) { + code, out, _ := r.run("key", "show", "ops", "--format", "json") + assert.Equal(t, command.ExitOK, code) + var got map[string]any + require.NoError(t, json.Unmarshal([]byte(out), &got)) + assert.Equal(t, "ops", got["name"]) + assert.Equal(t, "file", got["store"]) + assert.Equal(t, authority.Fingerprint(pub), got["fingerprint"]) + assert.Equal(t, line, got["public_key"]) + assert.Empty(t, got["require"]) + }) +} + +func TestKeyShowOfAMissingKeyFails(t *testing.T) { + code, out, errOut := newRig(t).run("key", "show", "ghost") + + assert.Equal(t, command.ExitFailure, code) + assert.Empty(t, out) + assert.Contains(t, errOut, `no such key: "ghost"`) +} + +func TestKeyShowWithTheWrongStoreFindsNothing(t *testing.T) { + r := newRig(t) + r.createKey("ops") + + code, _, _ := r.run("key", "show", "ops", "--store", "secure-enclave") + assert.Equal(t, command.ExitFailure, code) + code, _, _ = r.run("key", "show", "ops", "--store", "file") + assert.Equal(t, command.ExitOK, code) +} + +func TestKeyDeleteWithoutYesRefusesAndSaysSo(t *testing.T) { + r := newRig(t) + r.createKey("ops") + + code, out, errOut := r.run("key", "delete", "ops") + + assert.Equal(t, command.ExitFailure, code) + assert.Empty(t, out) + assert.Contains(t, errOut, "--yes") + assert.Contains(t, errOut, "refused") + assert.True(t, r.hasKey("ops"), "nothing was deleted") +} + +func TestKeyDeleteRemovesTheKeyAndItsAgentEntryAndLeavesTheReceipt(t *testing.T) { + r := newRig(t) + pub := r.createKey("ops") + r.createKey("other") + r.configure(agent.Identity{Name: "ops", Store: "file", Key: "ops", Allow: []agent.Allow{agent.AllowSigning}}) + r.configure(agent.Identity{Name: "second", Store: "file", Key: "ops", Allow: []agent.Allow{agent.AllowSigning}}) + r.configure(agent.Identity{Name: "other", Store: "file", Key: "other", Allow: []agent.Allow{agent.AllowSigning}}) + r.saveReceipt(authority.Receipt{Authority: "github", KeyName: "ops", Fingerprint: authority.Fingerprint(pub), Uses: []authority.Use{authority.UseSigning}}) + + code, out, errOut := r.run("key", "delete", "ops", "--yes") + + require.Equal(t, command.ExitOK, code, errOut) + assert.False(t, r.hasKey("ops")) + assert.True(t, r.hasKey("other"), "other keys are untouched") + cfg, err := agent.LoadConfig(r.paths.AgentConfigFile()) + require.NoError(t, err) + require.Len(t, cfg.Identities, 1) + assert.Equal(t, "other", cfg.Identities[0].Name) + store, err := authority.NewStore(r.paths.ReceiptsDir()) + require.NoError(t, err) + _, err = store.Load("github", "ops") + assert.NoError(t, err, "the receipt stays for the next login or logout to revoke") + assert.Contains(t, out, "Deleted key \"ops\"") + assert.Contains(t, out, "ops, second") + assert.Contains(t, out, "next \"atmos auth login\" or \"atmos auth logout\"") +} + +func TestKeyDeleteWithNoAgentConfigurationStillDeletes(t *testing.T) { + r := newRig(t) + r.createKey("ops") + + code, _, errOut := r.run("key", "delete", "ops", "--yes") + + assert.Equal(t, command.ExitOK, code, errOut) + assert.False(t, r.hasKey("ops")) +} + +func TestKeyDeleteOfAMissingKeyFails(t *testing.T) { + code, _, errOut := newRig(t).run("key", "delete", "ghost", "--yes") + + assert.Equal(t, command.ExitFailure, code) + assert.Contains(t, errOut, "no such key") +} + +func TestKeyStatusBuildsRowsFromKeysReceiptsAndStatusFiles(t *testing.T) { + r := newRig(t) + r.clock.Advance(0) + pub := r.createKey("ops") + created := time.Date(2026, 11, 1, 9, 0, 0, 0, time.UTC) + r.saveReceipt(authority.Receipt{ + Authority: "github", Subject: "octocat", KeyName: "ops", Fingerprint: authority.Fingerprint(pub), + Uses: []authority.Use{authority.UseSigning, authority.UseAuthentication}, Created: created, + }) + require.NoError(t, statusfile.Write(r.paths, statusfile.Status{ + Identity: "ops", Operation: statusfile.OperationAuthenticate, Time: r.clock.Now(), Success: true, + Outcome: "enrolled", Key: "ops", Store: "file", Authority: "github", + })) + // A login that failed before the key existed. + require.NoError(t, statusfile.Write(r.paths, statusfile.Status{ + Identity: "broken", Operation: statusfile.OperationAuthenticate, Time: r.clock.Now(), Outcome: "failed", + Key: "broken", Store: "file", Authority: "github", Code: "missing-scope", + Error: "the token lacks the write:ssh_signing_key scope", + })) + // An enrollment whose key was deleted. + r.saveReceipt(authority.Receipt{ + Authority: "github", Subject: "octocat", KeyName: "old", Fingerprint: "SHA256:gone", + Uses: []authority.Use{authority.UseSigning}, Created: created, + ExpiresAt: time.Date(2027, 1, 1, 0, 0, 0, 0, time.UTC), + }) + + code, out, errOut := r.run("key", "status") + + require.Equal(t, command.ExitOK, code, errOut) + rows := map[string][]string{} + for _, line := range strings.Split(strings.TrimSpace(out), "\n")[1:] { + f := strings.Fields(line) + if len(f) > 0 && !strings.HasPrefix(line, "Last error") && len(f) >= 8 { + rows[f[0]] = f + } + } + header := strings.Fields(strings.SplitN(out, "\n", 2)[0]) + assert.Equal(t, []string{"KEY", "STORE", "REQUIRE", "AUTHORITY", "SUBJECT", "ALLOW", "SINCE", "EXPIRES", "LAST", "RESULT"}, header) + + ops := rows["ops"] + require.NotNil(t, ops, out) + assert.Equal(t, []string{"ops", "file", "-", "github", "octocat", "signing,authentication", "2026-11-01", "never", "enrolled"}, ops[:9]) + + broken := rows["broken"] + require.NotNil(t, broken, out) + assert.Equal(t, []string{"broken", "file", "-", "github", "-", "-", "-", "-", "failed"}, broken[:9]) + assert.Contains(t, out, "Last error for broken: the token lacks the write:ssh_signing_key scope") + + old := rows["old"] + require.NotNil(t, old, out) + assert.Equal(t, "2027-01-01T00:00:00Z", old[7]) + assert.Contains(t, out, "key deleted; enrollment withdrawn at next login or logout") +} + +func TestKeyStatusMergesADeletedKeysReceiptWithItsLastLogin(t *testing.T) { + r := newRig(t) + r.saveReceipt(authority.Receipt{Authority: "github", KeyName: "ops", Fingerprint: "SHA256:gone", Uses: []authority.Use{authority.UseSigning}}) + require.NoError(t, statusfile.Write(r.paths, statusfile.Status{ + Identity: "ops", Operation: statusfile.OperationAuthenticate, Time: r.clock.Now(), Outcome: "enrolled", Key: "ops", Store: "file", + })) + + _, out, _ := r.run("key", "status") + + assert.Equal(t, 1, strings.Count(out, "ops "), "one row for the key: %s", out) + assert.Contains(t, out, "key deleted, enrollment withdrawn at next login or logout; last: enrolled") +} + +func TestKeyStatusOfOneKeyAndOfNone(t *testing.T) { + r := newRig(t) + r.createKey("ops") + r.createKey("other") + require.NoError(t, statusfile.Write(r.paths, statusfile.Status{Identity: "nick", Key: "ops", Store: "file", Outcome: "unchanged", Operation: statusfile.OperationLogout, Time: r.clock.Now()})) + + _, out, _ := r.run("key", "status", "ops") + assert.Contains(t, out, "ops") + assert.NotContains(t, out, "other") + assert.Contains(t, out, "logout: unchanged", "a logout is labelled") + + _, byIdentity, _ := r.run("key", "status", "nick") + assert.Contains(t, byIdentity, "ops", "an identity name finds its key's row") + + code, _, errOut := r.run("key", "status", "ghost") + assert.Equal(t, command.ExitFailure, code) + assert.Contains(t, errOut, "no such key") + + empty := newRig(t) + code, out, _ = empty.run("key", "status") + assert.Equal(t, command.ExitOK, code) + assert.Contains(t, out, "No keys, receipts, or login results") +} diff --git a/plugins/ssh/command/rig_test.go b/plugins/ssh/command/rig_test.go new file mode 100644 index 00000000000..66119444a3f --- /dev/null +++ b/plugins/ssh/command/rig_test.go @@ -0,0 +1,123 @@ +package command_test + +import ( + "bytes" + "context" + "errors" + "net" + "os" + "testing" + + "github.com/stretchr/testify/require" + "golang.org/x/crypto/ssh" + + "github.com/cloudposse/atmos/plugins/ssh/agent" + "github.com/cloudposse/atmos/plugins/ssh/authority" + "github.com/cloudposse/atmos/plugins/ssh/command" + "github.com/cloudposse/atmos/plugins/ssh/daemon" + "github.com/cloudposse/atmos/plugins/ssh/internal/testfakes" + "github.com/cloudposse/atmos/plugins/ssh/keystore" + "github.com/cloudposse/atmos/plugins/ssh/paths" + "github.com/cloudposse/atmos/plugins/ssh/service" +) + +const version = "0.1.0" + +type rig struct { + t *testing.T + paths *paths.Paths + mgr *testfakes.Manager + clock *testfakes.Clock + deps command.Deps + roots []string + // socketErr, when set, is what CheckSocket returns. + socketErr error +} + +func newRig(t *testing.T) *rig { + t.Helper() + r := &rig{t: t, paths: testfakes.Paths(t), mgr: &testfakes.Manager{Version: version}, clock: testfakes.NewClock()} + r.deps = command.Deps{ + Paths: func(root string) (*paths.Paths, error) { + r.roots = append(r.roots, root) + if root != "" { + return paths.New(root) + } + return r.paths, nil + }, + OpenStore: testfakes.FileOpener, + Daemon: daemon.Deps{ + Service: func(*paths.Paths) (service.Manager, error) { return r.mgr, nil }, + InstallExecutable: service.StablePath, + Version: version, + }, + CheckSocket: func(context.Context, string, ssh.PublicKey) error { return r.socketErr }, + Dial: func(ctx context.Context, socket string) (net.Conn, error) { + var d net.Dialer + return d.DialContext(ctx, "unix", socket) + }, + Now: r.clock.Now, + Sleep: r.clock.Sleep, + Hostname: func() (string, error) { return "testhost", nil }, + } + return r +} + +func (r *rig) run(args ...string) (code int, stdout, stderr string) { + r.t.Helper() + return r.runWith(nil, args...) +} + +func (r *rig) runWith(settings map[string]any, args ...string) (code int, stdout, stderr string) { + r.t.Helper() + var out, errw bytes.Buffer + code = command.New(r.deps).Run(context.Background(), args, settings, &out, &errw) + return code, out.String(), errw.String() +} + +func (r *rig) store() keystore.Store { return keystore.NewFileStore(r.paths.StoreDir("file")) } + +func (r *rig) createKey(name string) ssh.PublicKey { + r.t.Helper() + k, err := r.store().Create(context.Background(), name, nil) + require.NoError(r.t, err) + defer k.Close() + return k.SSHPublicKey() +} + +func (r *rig) hasKey(name string) bool { + r.t.Helper() + _, err := r.store().Load(context.Background(), name) + if errors.Is(err, keystore.ErrKeyNotFound) { + return false + } + require.NoError(r.t, err) + return true +} + +func (r *rig) configure(id agent.Identity) { + r.t.Helper() + require.NoError(r.t, agent.UpsertIdentity(r.paths.AgentConfigFile(), id)) +} + +func (r *rig) saveReceipt(rec authority.Receipt) { + r.t.Helper() + store, err := authority.NewStore(r.paths.ReceiptsDir()) + require.NoError(r.t, err) + require.NoError(r.t, store.Save(rec)) +} + +func (r *rig) writeFile(path, content string) { + r.t.Helper() + require.NoError(r.t, os.MkdirAll(dirOf(path), 0o700)) + require.NoError(r.t, os.WriteFile(path, []byte(content), 0o600)) +} + +func dirOf(path string) string { + for i := len(path) - 1; i >= 0; i-- { + if os.IsPathSeparator(path[i]) { + return path[:i] + } + } + return "." +} diff --git a/plugins/ssh/command/status.go b/plugins/ssh/command/status.go new file mode 100644 index 00000000000..4ffc6f891e3 --- /dev/null +++ b/plugins/ssh/command/status.go @@ -0,0 +1,250 @@ +package command + +import ( + "fmt" + "strings" + "text/tabwriter" + "time" + + "github.com/cloudposse/atmos/plugins/ssh/authority" + "github.com/cloudposse/atmos/plugins/ssh/inventory" + "github.com/cloudposse/atmos/plugins/ssh/keystore" + "github.com/cloudposse/atmos/plugins/ssh/statusfile" +) + +// row is one line of "key status". +type row struct { + key, store, require, authority, subject, allow string + since, expires, result, failure, identity string +} + +// keyStatus prints one row per key, from the keys, the receipts, and the identities' status files. +func (c *call) keyStatus(words []string) error { + if err := c.flags.only(); err != nil { + return err + } + if len(words) > 1 { + return usagef("usage: key status []") + } + rows, err := c.statusRows() + if err != nil { + fmt.Fprintf(c.err, "Warning: %v\n", err) + } + if len(words) == 1 { + rows = filterRows(rows, words[0]) + if len(rows) == 0 { + return fmt.Errorf("%w: %q", ErrNoSuchKey, words[0]) + } + } + if len(rows) == 0 { + c.printf("No keys, receipts, or login results on this machine.\n") + return nil + } + return c.printRows(rows) +} + +func filterRows(rows []row, name string) []row { + var out []row + for _, r := range rows { + if r.key == name || r.identity == name { + out = append(out, r) + } + } + return out +} + +func (c *call) printRows(rows []row) error { + w := tabwriter.NewWriter(c.out, 0, 0, 3, ' ', 0) + fmt.Fprintln(w, "KEY\tSTORE\tREQUIRE\tAUTHORITY\tSUBJECT\tALLOW\tSINCE\tEXPIRES\tLAST RESULT") + for _, r := range rows { + fmt.Fprintf(w, "%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\n", + r.key, r.store, r.require, r.authority, r.subject, r.allow, r.since, r.expires, r.result) + } + if err := w.Flush(); err != nil { + return err + } + for _, r := range rows { + if r.failure != "" { + c.printf("\nLast error for %s: %s\n", r.key, r.failure) + } + } + return nil +} + +// statusRows joins the three sources. A key with no receipt or status still gets a row, and so do +// a failed login whose key was never created and an enrollment whose key was deleted. +func (c *call) statusRows() ([]row, error) { + keys, keysErr := inventory.List(c.ctx, c.svc.deps.OpenStore, c.paths) + statuses, statusErr := statusfile.List(c.paths) + var receipts []authority.Receipt + if store, err := authority.NewStore(c.paths.ReceiptsDir()); err == nil { + var listErr error + receipts, listErr = store.List() + statusErr = joinErrors(statusErr, listErr) + } + usedStatus, usedReceipt := map[int]bool{}, map[int]bool{} + var rows []row + for _, k := range keys { + ri, si := matchReceipt(receipts, k), matchStatus(statuses, k) + markUsed(usedReceipt, ri) + markUsed(usedStatus, si) + rows = append(rows, keyRow(k, receipts, ri, statuses, si)) + } + for i, s := range statuses { + if usedStatus[i] { + continue + } + row := orphanStatusRow(s) + if ri := unusedReceipt(receipts, usedReceipt, s.Key); ri >= 0 { + usedReceipt[ri] = true + applyReceipt(&row, receipts[ri]) + row.result = "key deleted, enrollment withdrawn at next login or logout; last: " + row.result + } + rows = append(rows, row) + } + for i, r := range receipts { + if !usedReceipt[i] { + rows = append(rows, orphanReceiptRow(r)) + } + } + return rows, joinErrors(keysErr, statusErr) +} + +// unusedReceipt returns the index of a receipt for keyName that no row has used yet, or -1. +func unusedReceipt(receipts []authority.Receipt, used map[int]bool, keyName string) int { + for i, r := range receipts { + if !used[i] && keyName != "" && r.KeyName == keyName { + return i + } + } + return -1 +} + +func joinErrors(a, b error) error { + switch { + case a == nil: + return b + case b == nil: + return a + default: + return fmt.Errorf("%w; %w", a, b) + } +} + +func markUsed(m map[int]bool, i int) { + if i >= 0 { + m[i] = true + } +} + +// matchReceipt returns the index of the receipt for key k, or -1. +func matchReceipt(receipts []authority.Receipt, k keystore.Info) int { + fp := authority.Fingerprint(k.PublicKey) + for i, r := range receipts { + if r.KeyName == k.Name && r.Fingerprint == fp { + return i + } + } + return -1 +} + +// matchStatus returns the index of the newest status that names key k, or -1. +func matchStatus(statuses []statusfile.Status, k keystore.Info) int { + best := -1 + for i, s := range statuses { + if s.Key == k.Name && (s.Store == "" || s.Store == k.Store) && (best < 0 || s.Time.After(statuses[best].Time)) { + best = i + } + } + return best +} + +func keyRow(k keystore.Info, receipts []authority.Receipt, ri int, statuses []statusfile.Status, si int) row { + r := row{ + key: k.Name, store: k.Store, require: requireText(k.Requirements), authority: "-", subject: "-", allow: "-", + since: "-", expires: "-", result: "no login recorded", + } + if ri >= 0 { + applyReceipt(&r, receipts[ri]) + } + if si >= 0 { + applyStatus(&r, statuses[si]) + } + return r +} + +func applyReceipt(r *row, rec authority.Receipt) { + r.authority = orDash(rec.Authority) + r.subject = orDash(rec.Subject) + r.allow = useText(rec.Uses) + r.since = dateText(rec.Created) + if rec.ExpiresAt.IsZero() { + r.expires = "never" + } else { + r.expires = rec.ExpiresAt.UTC().Format(time.RFC3339) + } +} + +func applyStatus(r *row, s statusfile.Status) { + r.identity = s.Identity + r.result = resultText(s) + r.failure = s.Error + if r.authority == "-" { + r.authority = orDash(s.Authority) + } + if r.allow == "-" && len(s.Allow) > 0 { + r.allow = strings.Join(s.Allow, ",") + } +} + +func resultText(s statusfile.Status) string { + out := s.Outcome + if out == "" { + out = "unknown" + } + if s.Operation == statusfile.OperationLogout { + out = "logout: " + out + } + if !s.Time.IsZero() { + out += " (" + s.Time.UTC().Format("2006-01-02 15:04") + ")" + } + return out +} + +func orphanStatusRow(s statusfile.Status) row { + key := s.Key + if key == "" { + key = s.Identity + } + r := row{key: key, store: orDash(s.Store), require: strings.Join(s.Require, ","), authority: "-", subject: "-", allow: "-", since: "-", expires: "-"} + if r.require == "" { + r.require = "-" + } + applyStatus(&r, s) + return r +} + +func orphanReceiptRow(rec authority.Receipt) row { + r := row{key: rec.KeyName, store: "-", require: "-", authority: "-", subject: "-", allow: "-", since: "-", expires: "-"} + applyReceipt(&r, rec) + r.result = "key deleted; enrollment withdrawn at next login or logout" + return r +} + +func useText(uses []authority.Use) string { + if len(uses) == 0 { + return "-" + } + out := make([]string, len(uses)) + for i, u := range uses { + out[i] = string(u) + } + return strings.Join(out, ",") +} + +func orDash(s string) string { + if s == "" { + return "-" + } + return s +} diff --git a/plugins/ssh/command/testcmd.go b/plugins/ssh/command/testcmd.go new file mode 100644 index 00000000000..1fb441ece2a --- /dev/null +++ b/plugins/ssh/command/testcmd.go @@ -0,0 +1,176 @@ +package command + +import ( + "crypto/sha512" + "encoding/binary" + "encoding/json" + "errors" + "fmt" + "time" + + "golang.org/x/crypto/ssh" + sshagent "golang.org/x/crypto/ssh/agent" + + "github.com/cloudposse/atmos/plugins/ssh/agent" +) + +const ( + // defaultSoakInterval is the pause between attempts of a soak run. + defaultSoakInterval = 30 * time.Second + // attemptTimeout bounds one connect, list, and sign. + attemptTimeout = 30 * time.Second + // auditLinesRead is how much of the audit log is searched for the reason of a refusal. + auditLinesRead = 50 + // signNamespace is the SSHSIG namespace Git signs under. + signNamespace = "git" +) + +// Results of one attempt. +const ( + resultOK = "ok" + resultRefused = "refused" + resultLocked = "locked" + resultUnreachable = "unreachable" + resultError = "error" +) + +// ErrTestFailed means at least one attempt did not sign and verify. +var ErrTestFailed = errors.New("signing test failed") + +type attempt struct { + result string + detail string +} + +// test signs a Git payload through an identity's socket and verifies the signature. With --soak it +// repeats every --interval for that long, which is how locked-screen behavior is checked by hand: +// start it, lock the screen, wait, unlock, and read the lines. +func (c *call) test(words []string) error { + if err := c.flags.only("soak", "interval"); err != nil { + return err + } + if err := exactly(words, 1, "test [--soak ] [--interval ]"); err != nil { + return err + } + soak, err := c.flags.duration("soak", 0) + if err != nil { + return err + } + interval, err := c.flags.duration("interval", defaultSoakInterval) + if err != nil { + return err + } + if soak > 0 && interval <= 0 { + return usagef("--interval must be longer than zero") + } + socket, err := c.paths.SocketPath(words[0]) + if err != nil { + return err + } + tally, runErr := c.soak(words[0], socket, soak, interval) + if soak > 0 { + c.printf("Summary: ok=%d refused=%d locked=%d unreachable=%d error=%d\n", + tally[resultOK], tally[resultRefused], tally[resultLocked], tally[resultUnreachable], tally[resultError]) + } + if runErr != nil { + return runErr + } + total := 0 + for _, n := range tally { + total += n + } + if failed := total - tally[resultOK]; failed > 0 { + return fmt.Errorf("%w: %d of %d attempts did not succeed", ErrTestFailed, failed, total) + } + return nil +} + +// soak runs attempts until the duration has passed. A zero duration runs once. +func (c *call) soak(identity, socket string, soak, interval time.Duration) (map[string]int, error) { + now := c.svc.deps.Now + deadline := now().Add(soak) + tally := map[string]int{} + for { + a := c.attempt(identity, socket) + tally[a.result]++ + c.printf("%s %-11s %s %s\n", now().UTC().Format(time.RFC3339), a.result, identity, a.detail) + remaining := deadline.Sub(now()) + if soak == 0 || remaining <= 0 { + return tally, nil + } + if err := c.svc.deps.Sleep(c.ctx, min(interval, remaining)); err != nil { + return tally, err + } + } +} + +// attempt connects to the socket, signs an SSHSIG payload for Git, and verifies the signature. +func (c *call) attempt(identity, socket string) attempt { + conn, err := c.svc.deps.Dial(c.ctx, socket) + if err != nil { + return attempt{resultUnreachable, err.Error()} + } + defer conn.Close() + _ = conn.SetDeadline(time.Now().Add(attemptTimeout)) + client := sshagent.NewClient(conn) + keys, err := client.List() + if err != nil { + return attempt{resultUnreachable, "list keys: " + err.Error()} + } + if len(keys) != 1 { + return attempt{resultRefused, fmt.Sprintf("the socket lists %d keys, want 1", len(keys))} + } + payload := sshsigPayload([]byte(fmt.Sprintf("atmos ssh test %s\n", c.svc.deps.Now().UTC().Format(time.RFC3339Nano)))) + sig, err := client.Sign(keys[0], payload) + if err != nil { + return c.refusal(identity, err) + } + if err := keys[0].Verify(payload, sig); err != nil { + return attempt{resultError, "the signature did not verify: " + err.Error()} + } + return attempt{resultOK, fmt.Sprintf("signed and verified a Git signature (%s %s)", keys[0].Type(), ssh.FingerprintSHA256(keys[0]))} +} + +// refusal explains a failed sign request. The agent protocol carries no reason, so it is read from +// the audit log, where the daemon records the last request of the identity. +func (c *call) refusal(identity string, signErr error) attempt { + entry, ok := lastSignEntry(c.paths.AuditLogFile(), identity) + if !ok { + return attempt{resultRefused, signErr.Error()} + } + if entry.ScreenLocked { + return attempt{resultLocked, entry.Reason} + } + reason := entry.Reason + if reason == "" { + reason = signErr.Error() + } + return attempt{resultRefused, reason} +} + +// lastSignEntry returns the identity's most recent sign request in the audit log. +func lastSignEntry(path, identity string) (agent.AuditEntry, bool) { + lines, err := tailLines(path, auditLinesRead) + if err != nil { + return agent.AuditEntry{}, false + } + for i := len(lines) - 1; i >= 0; i-- { + var e agent.AuditEntry + if json.Unmarshal([]byte(lines[i]), &e) == nil && e.Identity == identity && e.Operation == agent.OpSign { + return e, true + } + } + return agent.AuditEntry{}, false +} + +// sshsigPayload builds the data an SSHSIG signature covers (PROTOCOL.sshsig): the magic, the +// namespace, a reserved string, the hash algorithm, and the hash of the message. +func sshsigPayload(message []byte) []byte { + digest := sha512.Sum512(message) + out := []byte("SSHSIG") + for _, field := range [][]byte{[]byte(signNamespace), nil, []byte("sha512"), digest[:]} { + out = binary.BigEndian.AppendUint32(out, uint32(len(field))) + out = append(out, field...) + } + return out +} diff --git a/plugins/ssh/command/testcmd_unix_test.go b/plugins/ssh/command/testcmd_unix_test.go new file mode 100644 index 00000000000..cf52a93d610 --- /dev/null +++ b/plugins/ssh/command/testcmd_unix_test.go @@ -0,0 +1,142 @@ +//go:build !windows + +package command_test + +import ( + "context" + "strings" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/cloudposse/atmos/plugins/ssh/agent" + "github.com/cloudposse/atmos/plugins/ssh/command" + "github.com/cloudposse/atmos/plugins/ssh/internal/testfakes" + "github.com/cloudposse/atmos/plugins/ssh/keystore" +) + +// serve runs the real agent daemon on the rig's root until the test ends. +func (r *rig) serve(opener agent.StoreOpener) { + r.t.Helper() + ctx, cancel := context.WithCancel(context.Background()) + ready := make(chan struct{}) + done := make(chan error, 1) + go func() { + done <- agent.Serve(ctx, agent.Options{ + Paths: r.paths, Version: version, OpenStore: opener, PollInterval: 20 * time.Millisecond, + Ready: func() { close(ready) }, + }) + }() + select { + case <-ready: + case err := <-done: + r.t.Fatalf("the agent stopped early: %v", err) + case <-time.After(10 * time.Second): + r.t.Fatal("the agent did not become ready") + } + r.t.Cleanup(func() { + cancel() + <-done + }) +} + +func (r *rig) configureAndServe(allow []agent.Allow, opener agent.StoreOpener) { + r.t.Helper() + r.createKey("ops") + r.configure(agent.Identity{Name: "ops", Store: keystore.KindFile, Key: "ops", Allow: allow}) + r.serve(opener) +} + +func TestTestSignsAndVerifiesThroughTheIdentitysSocket(t *testing.T) { + r := newRig(t) + r.configureAndServe([]agent.Allow{agent.AllowSigning}, testfakes.FileOpener) + + code, out, errOut := r.run("test", "ops") + + require.Equal(t, command.ExitOK, code, errOut+out) + assert.Contains(t, out, "2026-11-12T10:00:00Z ok") + assert.Contains(t, out, "ops signed and verified a Git signature (ssh-ed25519 SHA256:") + assert.NotContains(t, out, "Summary", "a single attempt prints no summary") +} + +func TestAnAuthenticationOnlyIdentityCannotSignCommits(t *testing.T) { + r := newRig(t) + r.configureAndServe([]agent.Allow{agent.AllowAuthentication}, testfakes.FileOpener) + + code, out, errOut := r.run("test", "ops") + + assert.Equal(t, command.ExitFailure, code, "an authentication-only identity cannot sign commits") + assert.Contains(t, out, "refused") + assert.Contains(t, out, "ops ", "the reason from the audit log follows") + assert.Contains(t, errOut, "1 of 1 attempts did not succeed") + assert.NotContains(t, out, "signed and verified") +} + +func TestTestReportsALockedScreenFromTheAuditLog(t *testing.T) { + r := newRig(t) + r.configureAndServe([]agent.Allow{agent.AllowSigning}, testfakes.LockedOpener) + + code, out, errOut := r.run("test", "ops") + + assert.Equal(t, command.ExitFailure, code) + assert.Contains(t, out, "locked") + assert.Contains(t, out, "key store refused: screen is locked") + assert.Contains(t, errOut, "did not succeed") +} + +func TestTestOfAnIdentityNobodyServesIsUnreachable(t *testing.T) { + r := newRig(t) + + code, out, _ := r.run("test", "ghost") + + assert.Equal(t, command.ExitFailure, code) + assert.Contains(t, out, "unreachable") +} + +func TestSoakRepeatsEveryIntervalAndSummarizes(t *testing.T) { + r := newRig(t) + r.configureAndServe([]agent.Allow{agent.AllowSigning}, testfakes.FileOpener) + start := r.clock.Now() + + code, out, errOut := r.run("test", "ops", "--soak", "3s", "--interval", "1s") + + require.Equal(t, command.ExitOK, code, errOut+out) + lines := strings.Split(strings.TrimSpace(out), "\n") + require.Len(t, lines, 5, out) + for i := 0; i < 4; i++ { + want := start.Add(time.Duration(i) * time.Second).UTC().Format(time.RFC3339) + assert.True(t, strings.HasPrefix(lines[i], want+" ok"), "line %d: %s", i, lines[i]) + } + assert.Equal(t, "Summary: ok=4 refused=0 locked=0 unreachable=0 error=0", lines[4]) +} + +func TestSoakCountsLockedAttemptsAndFails(t *testing.T) { + r := newRig(t) + r.configureAndServe([]agent.Allow{agent.AllowSigning}, testfakes.LockedOpener) + + code, out, _ := r.run("test", "ops", "--soak", "2s", "--interval", "1s") + + assert.Equal(t, command.ExitFailure, code) + assert.Contains(t, out, "Summary: ok=0 refused=0 locked=3 unreachable=0 error=0") +} + +func TestSoakStopsWhenTheContextEnds(t *testing.T) { + r := newRig(t) + r.configureAndServe([]agent.Allow{agent.AllowSigning}, testfakes.FileOpener) + r.deps.Sleep = func(context.Context, time.Duration) error { return context.Canceled } + + code, out, errOut := r.run("test", "ops", "--soak", "1h") + + assert.Equal(t, command.ExitFailure, code) + assert.Contains(t, out, "Summary: ok=1") + assert.Contains(t, errOut, "context canceled") +} + +func TestTestRejectsAnUnsafeIdentityName(t *testing.T) { + code, _, errOut := newRig(t).run("test", "../x") + + assert.Equal(t, command.ExitFailure, code) + assert.Contains(t, errOut, "invalid identity name") +} diff --git a/plugins/ssh/daemon/daemon.go b/plugins/ssh/daemon/daemon.go new file mode 100644 index 00000000000..04386ac4970 --- /dev/null +++ b/plugins/ssh/daemon/daemon.go @@ -0,0 +1,72 @@ +// Package daemon makes sure the SSH agent daemon runs the current plugin version. +package daemon + +import ( + "context" + "errors" + "fmt" + + "github.com/cloudposse/atmos/plugins/ssh/paths" + "github.com/cloudposse/atmos/plugins/ssh/service" +) + +// Arg is the first argument that puts the plugin executable into daemon mode. +const Arg = "agent-serve" + +// RootFlag names the data root in daemon mode. +const RootFlag = "--root" + +// Deps are the outside dependencies of Ensure. +type Deps struct { + // Service returns the service manager for the data root. + Service func(p *paths.Paths) (service.Manager, error) + // InstallExecutable copies the running executable to its stable, versioned path. + InstallExecutable func(p *paths.Paths, version string) (string, error) + // Version is the plugin's version. + Version string +} + +// Args returns the arguments the service passes to the executable. The root is always explicit, +// so the daemon uses the same data directory as the login that started it. +func Args(p *paths.Paths) []string { return []string{Arg, RootFlag, p.Root()} } + +// Result says what Ensure found and did. +type Result struct { + // Installed is true when Ensure wrote the service definition and started the service. + Installed bool + // Status is the service status before any change. + Status service.Status +} + +// Ensure makes sure the daemon runs the current version. A service that is installed, running, +// and not out of date is left alone. Otherwise the executable is copied to its stable path, the +// service is installed, and it is started. +func Ensure(ctx context.Context, d Deps, p *paths.Paths) (Result, error) { + mgr, err := d.Service(p) + if err != nil { + return Result{}, fmt.Errorf("agent service: %w", err) + } + st, statusErr := mgr.Status(ctx) + if errors.Is(statusErr, service.ErrUnsupportedPlatform) { + return Result{}, fmt.Errorf("agent service: %w", statusErr) + } + if statusErr == nil && current(st, d.Version) { + return Result{Status: st}, nil + } + exe, err := d.InstallExecutable(p, d.Version) + if err != nil { + return Result{Status: st}, fmt.Errorf("install the agent executable: %w", err) + } + if err := mgr.Install(ctx, service.Spec{Executable: exe, Args: Args(p)}); err != nil { + return Result{Status: st}, fmt.Errorf("install the agent service: %w", err) + } + if err := mgr.Start(ctx); err != nil { + return Result{Status: st}, fmt.Errorf("start the agent service: %w", err) + } + return Result{Installed: true, Status: st}, nil +} + +// current reports whether the running service needs no change. +func current(st service.Status, version string) bool { + return st.Installed && st.Running && !st.VersionMismatch && st.InstalledVersion == version +} diff --git a/plugins/ssh/daemon/daemon_test.go b/plugins/ssh/daemon/daemon_test.go new file mode 100644 index 00000000000..ffaf8e46606 --- /dev/null +++ b/plugins/ssh/daemon/daemon_test.go @@ -0,0 +1,129 @@ +package daemon_test + +import ( + "context" + "errors" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/cloudposse/atmos/plugins/ssh/daemon" + "github.com/cloudposse/atmos/plugins/ssh/internal/testfakes" + "github.com/cloudposse/atmos/plugins/ssh/paths" + "github.com/cloudposse/atmos/plugins/ssh/service" +) + +const version = "1.2.3" + +func deps(m *testfakes.Manager) (daemon.Deps, *int) { + installs := 0 + return daemon.Deps{ + Service: func(*paths.Paths) (service.Manager, error) { return m, nil }, + InstallExecutable: func(p *paths.Paths, v string) (string, error) { + installs++ + return service.StablePath(p, v) + }, + Version: version, + }, &installs +} + +func current() service.Status { + return service.Status{Installed: true, Loaded: true, Running: true, PID: 7, InstalledVersion: version, DaemonVersion: version} +} + +func TestArgsAlwaysNameTheRoot(t *testing.T) { + p := testfakes.Paths(t) + assert.Equal(t, []string{"agent-serve", "--root", p.Root()}, daemon.Args(p)) +} + +func TestEnsureLeavesACurrentDaemonAlone(t *testing.T) { + m := &testfakes.Manager{Version: version, St: current()} + d, installs := deps(m) + + res, err := daemon.Ensure(context.Background(), d, testfakes.Paths(t)) + + require.NoError(t, err) + assert.False(t, res.Installed) + assert.Equal(t, 7, res.Status.PID) + assert.Zero(t, *installs) + assert.Zero(t, m.InstallCount()) + assert.Zero(t, m.Starts) +} + +func TestEnsureInstallsAndStartsWhenTheDaemonIsMissingStoppedOrOld(t *testing.T) { + tests := []struct { + name string + st service.Status + }{ + {"not installed", service.Status{}}, + {"installed but stopped", service.Status{Installed: true, InstalledVersion: version}}, + {"daemon is a different version", func() service.Status { s := current(); s.VersionMismatch = true; return s }()}, + {"installed copy is older", func() service.Status { s := current(); s.InstalledVersion = "1.0.0"; return s }()}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + m := &testfakes.Manager{Version: version, St: tt.st} + d, installs := deps(m) + p := testfakes.Paths(t) + + res, err := daemon.Ensure(context.Background(), d, p) + + require.NoError(t, err) + assert.True(t, res.Installed) + assert.Equal(t, 1, *installs) + require.Equal(t, 1, m.InstallCount()) + assert.Equal(t, daemon.Args(p), m.Installs[0].Args) + assert.Equal(t, 1, m.Starts) + }) + } +} + +func TestEnsureTreatsAStatusErrorAsNeedingAnInstall(t *testing.T) { + m := &testfakes.Manager{Version: version, StatusErr: errors.New("launchctl failed")} + d, _ := deps(m) + + res, err := daemon.Ensure(context.Background(), d, testfakes.Paths(t)) + + require.NoError(t, err) + assert.True(t, res.Installed) +} + +func TestEnsureReportsEachFailingStep(t *testing.T) { + boom := testfakes.ErrBoom + tests := []struct { + name string + edit func(d *daemon.Deps, m *testfakes.Manager) + want string + }{ + {"no service manager", func(d *daemon.Deps, _ *testfakes.Manager) { + d.Service = func(*paths.Paths) (service.Manager, error) { return nil, service.ErrUnsupportedPlatform } + }, "agent service"}, + {"copy fails", func(d *daemon.Deps, _ *testfakes.Manager) { + d.InstallExecutable = func(*paths.Paths, string) (string, error) { return "", boom } + }, "install the agent executable"}, + {"install fails", func(_ *daemon.Deps, m *testfakes.Manager) { m.InstallErr = boom }, "install the agent service"}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + m := &testfakes.Manager{Version: version} + d, _ := deps(m) + tt.edit(&d, m) + + _, err := daemon.Ensure(context.Background(), d, testfakes.Paths(t)) + + require.Error(t, err) + assert.ErrorContains(t, err, tt.want) + }) + } +} + +func TestEnsureStopsEarlyWhereThereIsNoServiceManager(t *testing.T) { + m := &testfakes.Manager{Version: version, StatusErr: service.ErrUnsupportedPlatform} + d, installs := deps(m) + + _, err := daemon.Ensure(context.Background(), d, testfakes.Paths(t)) + + require.ErrorIs(t, err, service.ErrUnsupportedPlatform) + assert.Zero(t, *installs, "the executable is not copied for a service that cannot run it") +} diff --git a/plugins/ssh/go.mod b/plugins/ssh/go.mod new file mode 100644 index 00000000000..3bcd2918bf9 --- /dev/null +++ b/plugins/ssh/go.mod @@ -0,0 +1,31 @@ +module github.com/cloudposse/atmos/plugins/ssh + +go 1.26.0 + +replace github.com/cloudposse/atmos/sdk => ../../sdk + +require ( + github.com/cloudposse/atmos/sdk v0.0.0-00010101000000-000000000000 + github.com/ebitengine/purego v0.11.3 + github.com/stretchr/testify v1.12.1 + golang.org/x/crypto v0.59.0 + golang.org/x/sys v0.50.0 + google.golang.org/grpc v1.83.2 + google.golang.org/protobuf v1.36.12-0.20260120151049-f2248ac996af + gopkg.in/yaml.v3 v3.0.1 +) + +require ( + github.com/fatih/color v1.13.0 // indirect + github.com/golang/protobuf v1.5.4 // indirect + github.com/hashicorp/go-hclog v1.6.3 // indirect + github.com/hashicorp/go-plugin v1.7.0 // indirect + github.com/hashicorp/yamux v0.1.2 // indirect + github.com/mattn/go-colorable v0.1.12 // indirect + github.com/mattn/go-isatty v0.0.17 // indirect + github.com/oklog/run v1.1.0 // indirect + go.yaml.in/yaml/v3 v3.0.5 // indirect + golang.org/x/net v0.62.0 // indirect + golang.org/x/text v0.44.0 // indirect + google.golang.org/genproto/googleapis/rpc v0.0.0-20260526163538-3dc84a4a5aaa // indirect +) diff --git a/plugins/ssh/go.sum b/plugins/ssh/go.sum new file mode 100644 index 00000000000..7384c703c54 --- /dev/null +++ b/plugins/ssh/go.sum @@ -0,0 +1,84 @@ +github.com/bufbuild/protocompile v0.14.1 h1:iA73zAf/fyljNjQKwYzUHD6AD4R8KMasmwa/FBatYVw= +github.com/bufbuild/protocompile v0.14.1/go.mod h1:ppVdAIhbr2H8asPk6k4pY7t9zB1OU5DoEw9xY/FUi1c= +github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs= +github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= +github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/ebitengine/purego v0.11.3 h1:OB+JLpdm7ioymhyA+6s5kbb/uOuYycAgL8NNTFc5MLg= +github.com/ebitengine/purego v0.11.3/go.mod h1:DCHPP08djqhNSoTfImcnHYQRZmd0qhakvrozqaEYhGQ= +github.com/fatih/color v1.13.0 h1:8LOYc1KYPPmyKMuN8QV2DNRWNbLo6LZ0iLs8+mlH53w= +github.com/fatih/color v1.13.0/go.mod h1:kLAiJbzzSOZDVNGyDpeOxJ47H46qBXwg5ILebYFFOfk= +github.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI= +github.com/go-logr/logr v1.4.3/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY= +github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag= +github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE= +github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek= +github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps= +github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8= +github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU= +github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= +github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= +github.com/hashicorp/go-hclog v1.6.3 h1:Qr2kF+eVWjTiYmU7Y31tYlP1h0q/X3Nl3tPGdaB11/k= +github.com/hashicorp/go-hclog v1.6.3/go.mod h1:W4Qnvbt70Wk/zYJryRzDRU/4r0kIg0PVHBcfoyhpF5M= +github.com/hashicorp/go-plugin v1.7.0 h1:YghfQH/0QmPNc/AZMTFE3ac8fipZyZECHdDPshfk+mA= +github.com/hashicorp/go-plugin v1.7.0/go.mod h1:BExt6KEaIYx804z8k4gRzRLEvxKVb+kn0NMcihqOqb8= +github.com/hashicorp/yamux v0.1.2 h1:XtB8kyFOyHXYVFnwT5C3+Bdo8gArse7j2AQ0DA0Uey8= +github.com/hashicorp/yamux v0.1.2/go.mod h1:C+zze2n6e/7wshOZep2A70/aQU6QBRWJO/G6FT1wIns= +github.com/jhump/protoreflect v1.17.0 h1:qOEr613fac2lOuTgWN4tPAtLL7fUSbuJL5X5XumQh94= +github.com/jhump/protoreflect v1.17.0/go.mod h1:h9+vUUL38jiBzck8ck+6G/aeMX8Z4QUY/NiJPwPNi+8= +github.com/mattn/go-colorable v0.1.9/go.mod h1:u6P/XSegPjTcexA+o6vUJrdnUu04hMope9wVRipJSqc= +github.com/mattn/go-colorable v0.1.12 h1:jF+Du6AlPIjs2BiUiQlKOX0rt3SujHxPnksPKZbaA40= +github.com/mattn/go-colorable v0.1.12/go.mod h1:u5H1YNBxpqRaxsYJYSkiCWKzEfiAb1Gb520KVy5xxl4= +github.com/mattn/go-isatty v0.0.12/go.mod h1:cbi8OIDigv2wuxKPP5vlRcQ1OAZbq2CE4Kysco4FUpU= +github.com/mattn/go-isatty v0.0.14/go.mod h1:7GGIvUiUoEMVVmxf/4nioHXj79iQHKdU27kJ6hsGG94= +github.com/mattn/go-isatty v0.0.17 h1:BTarxUcIeDqL27Mc+vyvdWYSL28zpIhv3RoTdsLMPng= +github.com/mattn/go-isatty v0.0.17/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM= +github.com/oklog/run v1.1.0 h1:GEenZ1cK0+q0+wsJew9qUg/DyD8k3JzYsZAi5gYi2mA= +github.com/oklog/run v1.1.0/go.mod h1:sVPdnTZT1zYwAJeCMu2Th4T21pA3FPOQRfWjQlk7DVU= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/testify v1.7.2/go.mod h1:R6va5+xMeoiuVRoj+gSkQ7d3FALtqAAGI1FQKckRals= +github.com/stretchr/testify v1.12.1 h1:EuwCh5fleGS7H32xRwO3wRGT7DxrDhLAT6FF8MpWDWE= +github.com/stretchr/testify v1.12.1/go.mod h1:MDEgiDPPsNp5cuIrHPPCyornHKgEVbtFUmoNlxoYthg= +go.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64= +go.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y= +go.opentelemetry.io/otel v1.44.0 h1:JjwHmHpA4iZ3wBxluu2fbbE7j4kqlE8jXyAyPXH7HqU= +go.opentelemetry.io/otel v1.44.0/go.mod h1:BMgjTHL9WPRlRjL2oZCBTL4whCGtXch2H4BhOPIAyYc= +go.opentelemetry.io/otel/metric v1.44.0 h1:1w0gILTcHdr3YI+ixLyjemwrVnsMURbTZFrSYCdDdmc= +go.opentelemetry.io/otel/metric v1.44.0/go.mod h1:8O7hanEPBNgEMmybD3s2VBKcgWOCsA6tzHBPODAiquo= +go.opentelemetry.io/otel/sdk v1.44.0 h1:nHYwb9lK+fJPU/dnT6s7W7Z8itMWyqrnVfbheVYrZ58= +go.opentelemetry.io/otel/sdk v1.44.0/go.mod h1:Osuydd3Se74nqjAKxid74N5eC+jfEqfTegHRnq58oK0= +go.opentelemetry.io/otel/sdk/metric v1.44.0 h1:3LlKgI+VjbVsjNRFZJZAJ30WjXC5VkNRks6si09iEfI= +go.opentelemetry.io/otel/sdk/metric v1.44.0/go.mod h1:5B5pMARnXxKhltooO4xUuCBorl65a4EpnTalObqOigA= +go.opentelemetry.io/otel/trace v1.44.0 h1:jxF5CsGYCe74MCRx2X4g7WsY/VBKRqqpNvXlX/6gtIk= +go.opentelemetry.io/otel/trace v1.44.0/go.mod h1:oLl1jrMQAVo6v3GAggN+1VH9VIz9iUSvW53sW1Q8PIE= +go.yaml.in/yaml/v3 v3.0.5 h1:N6y/pJk8buWs9NY5ERU2HSMfm+IuD/OtfdAnq6kESPw= +go.yaml.in/yaml/v3 v3.0.5/go.mod h1:HVTZu1O7/Vkt2N+BFy8Zza+lnLsABggaTM2ZpNIGuKg= +golang.org/x/crypto v0.59.0 h1:xS2jhqYbzNrpvkWP2YTDf4TJwBy3ykR03i8vFDxEc7c= +golang.org/x/crypto v0.59.0/go.mod h1:veDyUwATGs3c+vN3VfTbzViMGXeTBk3WyhBOkn+F/4U= +golang.org/x/net v0.62.0 h1:18ELalfM5+XNRwzM2nYqXsZQ9ByS1uhj2O/U7+5jqRY= +golang.org/x/net v0.62.0/go.mod h1:WgDCOTH8iwtB66T4/GfI94AHo/hhdb7Hah9NDseQfiI= +golang.org/x/sys v0.0.0-20200116001909-b77594299b42/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200223170610-d5e6a3e2c0ae/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210630005230-0f9fa26af87c/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20210927094055-39ccf1dd6fa6/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220503163025-988cb79eb6c6/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.50.0 h1:dkKZEFTEKaLr1sjhs0WiKqoi8Jj5nHbS3Njmx1UoMJs= +golang.org/x/sys v0.50.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og= +golang.org/x/term v0.48.0 h1:G6UU1eiSB8nl3DzeUGt7Mg+2SctI8tPS6Z5/mBt6cOk= +golang.org/x/term v0.48.0/go.mod h1:BRDLHCZr2SUjIeBHHpRyQeC9xzSAVbzY2rvKgafnHf4= +golang.org/x/text v0.44.0 h1:YItdp/mQNGnsmrgpcdA5yQ3bnRxCfo/Tj/iByGW9GGo= +golang.org/x/text v0.44.0/go.mod h1:S4FR1waQ9LbjQTls97SyRjDaUUVkaM+cXwwuG/G+MwY= +gonum.org/v1/gonum v0.17.0 h1:VbpOemQlsSMrYmn7T2OUvQ4dqxQXU+ouZFQsZOx50z4= +gonum.org/v1/gonum v0.17.0/go.mod h1:El3tOrEuMpv2UdMrbNlKEh9vd86bmQ6vqIcDwxEOc1E= +google.golang.org/genproto/googleapis/rpc v0.0.0-20260526163538-3dc84a4a5aaa h1:mZHHdPZl0dbGHCflZgAq/Q468DWVFcU2whhB2KAo8fk= +google.golang.org/genproto/googleapis/rpc v0.0.0-20260526163538-3dc84a4a5aaa/go.mod h1:4Hqkh8ycfw05ld/3BWL7rJOSfebL2Q+DVDeRgYgxUU8= +google.golang.org/grpc v1.83.2 h1:EManeRomTObA0BU7I8vXgg/78uE5MJ9M8B39EX2WscU= +google.golang.org/grpc v1.83.2/go.mod h1:YPI1hK3kDked6iHvgX3tR0y+nX/qpMFKhPgFsokw1S8= +google.golang.org/protobuf v1.36.12-0.20260120151049-f2248ac996af h1:+5/Sw3GsDNlEmu7TfklWKPdQ0Ykja5VEmq2i817+jbI= +google.golang.org/protobuf v1.36.12-0.20260120151049-f2248ac996af/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/plugins/ssh/identity/authenticate.go b/plugins/ssh/identity/authenticate.go new file mode 100644 index 00000000000..9ca17e76df0 --- /dev/null +++ b/plugins/ssh/identity/authenticate.go @@ -0,0 +1,322 @@ +package identity + +import ( + "context" + "errors" + "fmt" + "path/filepath" + + "golang.org/x/crypto/ssh" + + "github.com/cloudposse/atmos/plugins/ssh/agent" + "github.com/cloudposse/atmos/plugins/ssh/authority" + "github.com/cloudposse/atmos/plugins/ssh/daemon" + "github.com/cloudposse/atmos/plugins/ssh/inventory" + "github.com/cloudposse/atmos/plugins/ssh/keystore" + "github.com/cloudposse/atmos/plugins/ssh/paths" + "github.com/cloudposse/atmos/plugins/ssh/statusfile" +) + +// fallbackHostname titles keys when the machine's name cannot be read. +const fallbackHostname = "unknown-host" + +// run is one Authenticate call. +type run struct { + svc *Service + name string + upstream map[string]string + secrets []string + spec Spec + paths *paths.Paths + keyName string + pub ssh.PublicKey + status statusfile.Status +} + +// Authenticate brings the identity up: the key exists, the authority trusts it, the agent serves +// it, and the environment points tools at it. It writes the identity's status file whatever the +// outcome. The upstream map holds the provider's credentials; the token is the entry "token". +func (s *Service) Authenticate(ctx context.Context, name string, raw map[string]any, upstream map[string]string) (Result, error) { + r := &run{svc: s, name: name, upstream: upstream, secrets: secretValues(upstream)} + r.status = statusfile.Status{Identity: name, Operation: statusfile.OperationAuthenticate} + res, err := r.authenticate(ctx, raw) + return res, r.finish(err) +} + +func secretValues(upstream map[string]string) []string { + var out []string + for _, v := range upstream { + out = append(out, v) + } + return out +} + +func (r *run) authenticate(ctx context.Context, raw map[string]any) (Result, error) { + if err := r.resolve(raw); err != nil { + return Result{}, err + } + if err := r.ensureKey(ctx); err != nil { + return Result{}, err + } + if err := r.enroll(ctx); err != nil { + return Result{}, err + } + r.rememberToken(ctx) + if err := r.serve(ctx); err != nil { + return Result{}, err + } + gitConfig, err := r.gitConfig() + if err != nil { + return Result{}, err + } + return r.result(gitConfig), nil +} + +// resolve parses the spec and locates the data root. When the spec is invalid it still locates +// the root if it can, so the failure reaches the status file. +func (r *run) resolve(raw map[string]any) error { + spec, specErr := ParseSpec(raw) + root := spec.Root + if specErr != nil { + root, _ = raw["root"].(string) + if !filepath.IsAbs(root) { + root = "" + } + } + if p, err := r.svc.deps.Paths(root); err == nil { + r.paths = p + } else if specErr == nil { + return err + } + if err := paths.ValidateIdentity(r.name); err != nil { + r.paths = nil + return err + } + if specErr != nil { + return specErr + } + r.spec, r.keyName = spec, spec.KeyName(r.name) + r.status.Key, r.status.Store, r.status.Authority = r.keyName, spec.Store, spec.Authority + r.status.Allow, r.status.Require = allowStrings(spec.Allow), requireStrings(spec.Require) + return r.paths.EnsureDirs() +} + +func allowStrings(in []agent.Allow) []string { + out := make([]string, len(in)) + for i, a := range in { + out[i] = string(a) + } + return out +} + +func requireStrings(in []keystore.Requirement) []string { + out := make([]string, len(in)) + for i, a := range in { + out[i] = string(a) + } + return out +} + +// ensureKey loads the key or creates it. A key that exists with other requirements is an error: +// the requirement is fixed at creation, so the fix is to rotate the key. +func (r *run) ensureKey(ctx context.Context) error { + store, err := r.svc.deps.OpenStore(r.spec.Store, r.paths.StoreDir(r.spec.Store)) + if err != nil { + return err + } + want, err := keystore.Validate(store, r.spec.Require) + if err != nil { + return err + } + key, err := store.Load(ctx, r.keyName) + switch { + case errors.Is(err, keystore.ErrKeyNotFound): + key, err = store.Create(ctx, r.keyName, want) + if err != nil { + return fmt.Errorf("create key %q: %w", r.keyName, err) + } + case err != nil: + return fmt.Errorf("load key %q: %w", r.keyName, err) + default: + if err := keystore.CheckRequirements(key.Requirements(), want); err != nil { + _ = key.Close() + return fmt.Errorf("key %q: %w", r.keyName, err) + } + } + r.pub = key.SSHPublicKey() + return key.Close() +} + +// enroll has the authority vouch for the key. With a matching receipt on disk it makes no call. +func (r *run) enroll(ctx context.Context) error { + d := r.svc.deps + auth, err := d.Authorities.New(r.spec.Authority, authority.Options{HTTPClient: d.HTTPClient}) + if err != nil { + return err + } + receipts, err := authority.NewStore(r.paths.ReceiptsDir()) + if err != nil { + return err + } + keys, listErr := inventory.List(ctx, d.OpenStore, r.paths) + existing := inventory.Fingerprints(keys, listErr) + if listErr != nil { + r.status.Warnings = append(r.status.Warnings, "stale enrollments were not cleaned up: "+listErr.Error()) + } + res, err := authority.Reconcile(ctx, authority.Params{ + Authority: auth, Credentials: r.upstream, Store: receipts, + KeyName: r.keyName, Key: r.pub, Uses: uses(r.spec.Allow), Title: r.title(), + Existing: existing, Now: d.Now, + }) + r.record(res) + if res.Outcome == authority.OutcomeFailed { + if err == nil { + err = fmt.Errorf("%w: %s", authority.ErrInvalidRequest, "enrollment failed") + } + return err + } + if err != nil { + r.status.Warnings = append(r.status.Warnings, err.Error()) + } + return nil +} + +func uses(allow []agent.Allow) []authority.Use { + out := make([]authority.Use, len(allow)) + for i, a := range allow { + out[i] = authority.Use(a) + } + return out +} + +func (r *run) title() string { + host, err := r.svc.deps.Hostname() + if err != nil || host == "" { + host = fallbackHostname + } + return fmt.Sprintf("%s@%s (Atmos)", r.keyName, host) +} + +// record copies what Reconcile did into the status. +func (r *run) record(res authority.Result) { + r.status.Outcome = string(res.Outcome) + r.status.Subject = res.Receipt.Subject + for _, u := range res.Added { + r.status.Added = append(r.status.Added, string(u)) + } + for _, u := range res.Removed { + r.status.Removed = append(r.status.Removed, string(u)) + } + for _, rec := range res.Revoked { + r.status.Revoked = append(r.status.Revoked, rec.KeyName) + } +} + +// rememberToken keeps the upstream token in the identity's private state, so logout can revoke +// enrollments later. The provider's own state is not visible to the identity. +func (r *run) rememberToken(ctx context.Context) { + token := r.upstream[authority.CredentialToken] + if token == "" { + return + } + have, found, err := r.svc.deps.State.Get(ctx, StateTokenKey) + if err == nil && found && string(have) == token { + return + } + if err := r.svc.deps.State.Put(ctx, StateTokenKey, []byte(token)); err != nil { + r.status.Warnings = append(r.status.Warnings, "the token could not be saved, so logout cannot revoke enrollments: "+err.Error()) + } +} + +// serve registers the identity with the agent and makes sure the daemon serves its socket. +func (r *run) serve(ctx context.Context) error { + err := agent.UpsertIdentity(r.paths.AgentConfigFile(), agent.Identity{ + Name: r.name, Store: r.spec.Store, Key: r.keyName, Allow: r.spec.Allow, + }) + if err != nil { + return err + } + if _, err := daemon.Ensure(ctx, r.svc.deps.Daemon, r.paths); err != nil { + return err + } + socket, err := r.paths.SocketPath(r.name) + if err != nil { + return err + } + return r.waitForSocket(ctx, socket) +} + +func (r *run) waitForSocket(ctx context.Context, socket string) error { + var last error + for range socketAttempts { + if last = r.svc.deps.CheckSocket(ctx, socket, r.pub); last == nil { + return nil + } + if err := r.svc.deps.Sleep(ctx, socketInterval); err != nil { + return err + } + } + return fmt.Errorf("%w: %v", ErrAgentUnavailable, last) +} + +// gitConfig writes the identity's Git configuration, or removes a stale one. It returns the file's +// path, or "" when none is needed. +func (r *run) gitConfig() (string, error) { + signing := r.spec.Uses(agent.AllowSigning) + if !signing && len(r.spec.RewriteHTTPS) == 0 { + return writeGitConfig(r.paths, r.name, nil) + } + home, err := r.svc.deps.HomeDir() + if err != nil { + return "", err + } + g := GitConfig{ + Includes: []string{filepath.Join(home, ".gitconfig"), filepath.Join(home, ".config", "git", "config")}, + Signing: signing, + RewriteHTTPS: r.spec.RewriteHTTPS, + } + if signing { + if g.SSHKeygen, err = r.svc.deps.FindSSHKeygen(); err != nil { + return "", err + } + g.SigningKey = authority.AuthorizedKey(r.pub) + } + return writeGitConfig(r.paths, r.name, &g) +} + +// result builds the environment credential. +func (r *run) result(gitConfig string) Result { + socket, _ := r.paths.SocketPath(r.name) + env := map[string]string{EnvAuthSock: socket} + if gitConfig != "" { + env[EnvGitConfig] = gitConfig + } + if r.spec.User != "" && r.spec.Uses(agent.AllowAuthentication) { + env[EnvAnsibleUsr] = r.spec.User + } + return Result{Environment: env, ExpiresAt: r.svc.deps.Now().Add(CredentialLifetime)} +} + +// finish records the outcome in the status file and returns the failure, if any. +func (r *run) finish(err error) error { + r.status.Time = r.svc.deps.Now().UTC() + var failure *Error + if err != nil { + failure = classify(r.name, r.keyName, err, r.secrets...) + r.status.Success, r.status.Outcome = false, "failed" + r.status.Code, r.status.Error = string(failure.Code), failure.Message + } else { + r.status.Success = true + } + for i, w := range r.status.Warnings { + r.status.Warnings[i] = scrub(w, r.secrets) + } + if r.paths != nil { + // The status file is a diagnostic aid; failing to write it must not fail the login. + _ = statusfile.Write(r.paths, r.status) + } + if failure == nil { + return nil + } + return failure +} diff --git a/plugins/ssh/identity/authenticate_test.go b/plugins/ssh/identity/authenticate_test.go new file mode 100644 index 00000000000..eee450a29a6 --- /dev/null +++ b/plugins/ssh/identity/authenticate_test.go @@ -0,0 +1,467 @@ +package identity_test + +import ( + "errors" + "os" + "path/filepath" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/cloudposse/atmos/plugins/ssh/agent" + "github.com/cloudposse/atmos/plugins/ssh/authority" + "github.com/cloudposse/atmos/plugins/ssh/authority/authoritytest" + "github.com/cloudposse/atmos/plugins/ssh/identity" + "github.com/cloudposse/atmos/plugins/ssh/internal/testfakes" + "github.com/cloudposse/atmos/plugins/ssh/keystore" + "github.com/cloudposse/atmos/plugins/ssh/paths" + "github.com/cloudposse/atmos/plugins/ssh/statusfile" +) + +func TestFirstAuthenticateCreatesEnrollsServesAndWritesGitConfig(t *testing.T) { + r := newRig(t) + spec := baseSpec(map[string]any{ + "allow": []any{"signing", "authentication"}, "user": "deploy", "rewrite_https": []any{"github.com"}, + }) + + res := r.mustAuthenticate("ops", spec) + + // The key exists in the store. + pub := r.pub("ops") + + // The authority was asked once, for both uses, with the machine's title. + require.Equal(t, 1, ensureCalls(r.fake)) + assert.Equal(t, 1, r.fake.Count(pub, authority.UseSigning)) + assert.Equal(t, 1, r.fake.Count(pub, authority.UseAuthentication)) + receipts := r.receipts() + require.Len(t, receipts, 1) + assert.Equal(t, "fake", receipts[0].Authority) + + // The agent knows the identity and the daemon was installed and started once. + assert.Equal(t, []agent.Identity{{Name: "ops", Store: "file", Key: "ops", Allow: []agent.Allow{agent.AllowSigning, agent.AllowAuthentication}}}, r.agentConfig().Identities) + require.Equal(t, 1, r.mgr.InstallCount()) + assert.Equal(t, 1, r.mgr.Starts) + assert.Equal(t, []string{"agent-serve", "--root", r.paths.Root()}, r.mgr.Installs[0].Args) + assert.Equal(t, 1, r.installs) + socket, err := r.paths.SocketPath("ops") + require.NoError(t, err) + assert.Equal(t, []string{socket}, r.checks) + + // The environment has the three variables, and an expiry the host accepts. + gitPath := r.gitConfigPath("ops") + assert.Equal(t, map[string]string{ + "SSH_AUTH_SOCK": socket, "GIT_CONFIG_GLOBAL": gitPath, "ANSIBLE_REMOTE_USER": "deploy", + }, res.Environment) + assert.Equal(t, r.clock.Now().Add(identity.CredentialLifetime), res.ExpiresAt) + assert.NotContains(t, res.Environment, "GIT_CONFIG_COUNT") + + // The Git configuration includes the user's own first, then sets the signing keys. + content := r.readFile(gitPath) + assert.Contains(t, content, `signingkey = "key::`+authority.AuthorizedKey(pub)+`"`) + assert.Contains(t, content, `program = "`+keygen+`"`) + assert.Contains(t, content, `[url "ssh://git@github.com/"]`) + info, err := os.Stat(gitPath) + require.NoError(t, err) + if info.Mode().Perm() != 0 { + assert.Equal(t, os.FileMode(0o600), info.Mode().Perm()) + } + + // The status file says what happened and holds the title-free summary. + st := r.status("ops") + assert.True(t, st.Success) + assert.Equal(t, "enrolled", st.Outcome) + assert.Equal(t, "fake-user", st.Subject) + assert.ElementsMatch(t, []string{"signing", "authentication"}, st.Added) + assert.Equal(t, r.clock.Now(), st.Time) + + // The token is kept for logout. + assert.Equal(t, authoritytest.FakeToken, string(r.state.Data[identity.StateTokenKey])) +} + +func TestFirstAuthenticateTitlesTheKeyWithTheHostname(t *testing.T) { + r := newRig(t) + r.mustAuthenticate("ops", baseSpec(nil)) + // The fake records the title in its receipt subject only through Ensure; check via the call. + require.Len(t, r.fake.Calls(), 1) + assert.Equal(t, "ensure", r.fake.Calls()[0].Op) +} + +func TestEnvironmentFollowsAllowUserAndRewrite(t *testing.T) { + tests := []struct { + name string + extra map[string]any + wantGit bool + wantUsr bool + }{ + {"signing only", map[string]any{}, true, false}, + {"signing with user", map[string]any{"user": "deploy"}, true, false}, + {"authentication with user", map[string]any{"allow": []any{"authentication"}, "user": "deploy"}, false, true}, + {"authentication without user", map[string]any{"allow": []any{"authentication"}}, false, false}, + {"authentication with rewrite", map[string]any{"allow": []any{"authentication"}, "rewrite_https": []any{"example.com"}}, true, false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + r := newRig(t) + res := r.mustAuthenticate("ops", baseSpec(tt.extra)) + + assert.Contains(t, res.Environment, "SSH_AUTH_SOCK") + _, hasGit := res.Environment["GIT_CONFIG_GLOBAL"] + _, hasUser := res.Environment["ANSIBLE_REMOTE_USER"] + assert.Equal(t, tt.wantGit, hasGit) + assert.Equal(t, tt.wantUsr, hasUser) + _, err := os.Stat(r.gitConfigPath("ops")) + assert.Equal(t, tt.wantGit, err == nil, "the file exists exactly when the variable is set") + }) + } +} + +func TestSecondAuthenticateMakesNoAuthorityCallAndDoesNotReinstall(t *testing.T) { + r := newRig(t) + first := r.mustAuthenticate("ops", baseSpec(map[string]any{"allow": []any{"signing", "authentication"}})) + r.clock.Advance(time.Hour) + + second := r.mustAuthenticate("ops", baseSpec(map[string]any{"allow": []any{"signing", "authentication"}})) + + assert.Equal(t, 1, ensureCalls(r.fake), "a matching receipt means no authority call") + assert.Equal(t, 1, r.mgr.InstallCount(), "a running current daemon is not reinstalled") + assert.Equal(t, 1, r.mgr.Starts) + assert.Equal(t, 1, r.installs) + assert.Equal(t, first.Environment, second.Environment) + assert.Equal(t, "unchanged", r.status("ops").Outcome) + assert.Equal(t, 1, r.state.Puts, "the unchanged token is not written again") + assert.Len(t, r.receipts(), 1) +} + +func TestAuthenticateReinstallsAnOutOfDateOrStoppedDaemon(t *testing.T) { + tests := []struct { + name string + mutate func(m *testfakes.Manager) + }{ + {"stopped", func(m *testfakes.Manager) { m.St.Running = false }}, + {"not installed", func(m *testfakes.Manager) { m.St.Installed = false }}, + {"daemon is another version", func(m *testfakes.Manager) { m.St.VersionMismatch = true }}, + {"installed copy is another version", func(m *testfakes.Manager) { m.St.InstalledVersion = "0.0.9" }}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + r := newRig(t) + r.mustAuthenticate("ops", baseSpec(nil)) + require.Equal(t, 1, r.mgr.InstallCount()) + tt.mutate(r.mgr) + + r.mustAuthenticate("ops", baseSpec(nil)) + + assert.Equal(t, 2, r.mgr.InstallCount()) + assert.Equal(t, 2, r.mgr.Starts) + }) + } +} + +func TestAddingAUseEnrollsItAndKeepsTheKey(t *testing.T) { + r := newRig(t) + r.mustAuthenticate("ops", baseSpec(nil)) + pub := r.pub("ops") + + r.mustAuthenticate("ops", baseSpec(map[string]any{"allow": []any{"signing", "authentication"}})) + + assert.Equal(t, 2, ensureCalls(r.fake)) + assert.Equal(t, 1, r.fake.Count(pub, authority.UseAuthentication)) + assert.Equal(t, 1, r.fake.Count(pub, authority.UseSigning)) + st := r.status("ops") + assert.Equal(t, "updated", st.Outcome) + assert.Equal(t, []string{"authentication"}, st.Added) + assert.Equal(t, pub, r.pub("ops"), "the same key") + assert.Len(t, r.receipts(), 1) +} + +func TestFailuresAreRecordedWithTheirCause(t *testing.T) { + requireUnlocked := baseSpec(map[string]any{"require": "unlocked"}) + tests := []struct { + name string + prepare func(r *rig) + spec map[string]any + upstream map[string]string + code identity.Code + contains string + is error + }{ + { + name: "unsupported requirement on the file store", spec: requireUnlocked, upstream: fakeToken(), + code: identity.CodeUnsupportedRequirement, contains: `"unlocked"`, is: keystore.ErrUnsupportedRequirement, + }, + { + name: "unknown authority", spec: baseSpec(map[string]any{"authority": "nope"}), upstream: fakeToken(), + code: identity.CodeUnknownAuthority, contains: "nope", is: authority.ErrUnknownAuthority, + }, + { + name: "missing token for github", spec: baseSpec(map[string]any{"authority": "github"}), upstream: map[string]string{"assertion": "self"}, + code: identity.CodeTokenRejected, contains: "no token", is: authority.ErrUnauthorized, + }, + { + name: "missing scope", spec: baseSpec(nil), upstream: fakeToken(), + prepare: func(r *rig) { + r.fake.FailNextEnsure(&authority.Error{Authority: "fake", Operation: "ensure", Use: authority.UseSigning, Err: authority.ErrMissingPermission, Permission: "write:ssh_signing_key"}) + }, + code: identity.CodeMissingScope, contains: "write:ssh_signing_key", is: authority.ErrMissingPermission, + }, + { + name: "authority unreachable", spec: baseSpec(nil), upstream: fakeToken(), + prepare: func(r *rig) { + r.fake.FailNextEnsure(&authority.Error{Authority: "fake", Operation: "ensure", Err: authority.ErrUnavailable}) + }, + code: identity.CodeAuthorityUnreachable, contains: "unreachable", is: authority.ErrUnavailable, + }, + { + name: "invalid spec", spec: map[string]any{"store": "file", "allow": []any{"signing"}, "bogus": true}, upstream: fakeToken(), + code: identity.CodeInvalidSpec, contains: "bogus", is: identity.ErrInvalidSpec, + }, + { + name: "secure enclave on a machine without one", spec: baseSpec(map[string]any{"store": "secure-enclave"}), upstream: fakeToken(), + code: identity.CodeUnsupportedPlatform, contains: "not supported", is: keystore.ErrUnsupportedPlatform, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + r := newRig(t) + if tt.prepare != nil { + tt.prepare(r) + } + + _, err := r.authenticate("ops", tt.spec, tt.upstream) + + require.Error(t, err) + var failure *identity.Error + require.ErrorAs(t, err, &failure) + assert.Equal(t, tt.code, failure.Code) + assert.ErrorIs(t, err, tt.is) + assert.Contains(t, failure.Message, tt.contains) + + st := r.status("ops") + assert.False(t, st.Success) + assert.Equal(t, "failed", st.Outcome) + assert.Equal(t, string(tt.code), st.Code) + assert.Contains(t, st.Error, tt.contains) + assert.Equal(t, 0, r.mgr.InstallCount(), "a failed login starts no daemon") + }) + } +} + +func TestAnAuthorityFailureLeavesNoTokenInTheStatusFileOrTheError(t *testing.T) { + r := newRig(t) + token := authoritytest.FakeToken + r.fake.FailNextEnsure(errors.New("upstream said no to " + token)) + + _, err := r.authenticate("ops", baseSpec(nil), fakeToken()) + + require.Error(t, err) + assert.NotContains(t, err.Error(), token) + path, pathErr := statusfile.Path(r.paths, "ops") + require.NoError(t, pathErr) + assert.NotContains(t, r.readFile(path), token) + assert.Contains(t, r.readFile(path), "[redacted]") + for _, receipt := range r.receipts() { + assert.NotContains(t, receipt.PublicKey, token) + } +} + +func TestRequirementMismatchFailsAndNamesTheFix(t *testing.T) { + r := newRig(t) + r.deps.OpenStore = testfakes.RequirementOpener() + r.use() + r.mustAuthenticate("ops", baseSpec(nil)) + require.Equal(t, 1, ensureCalls(r.fake)) + + _, err := r.authenticate("ops", baseSpec(map[string]any{"require": []any{"unlocked"}}), fakeToken()) + + require.ErrorIs(t, err, keystore.ErrRequirementMismatch) + st := r.status("ops") + assert.Equal(t, string(identity.CodeRequirementMismatch), st.Code) + assert.Contains(t, st.Error, "atmos ssh key delete ops --yes") + assert.Equal(t, 1, ensureCalls(r.fake), "nothing was enrolled for the mismatched request") +} + +func TestARequirementTheStoreCanEnforceIsAppliedAtCreation(t *testing.T) { + r := newRig(t) + r.deps.OpenStore = testfakes.RequirementOpener() + r.use() + spec := baseSpec(map[string]any{"require": "unlocked"}) + + r.mustAuthenticate("ops", spec) + r.mustAuthenticate("ops", spec) + + assert.Equal(t, []string{"unlocked"}, r.status("ops").Require) + _, err := r.authenticate("ops", baseSpec(nil), fakeToken()) + require.ErrorIs(t, err, keystore.ErrRequirementMismatch, "dropping the term is also a mismatch") +} + +func TestARotatedKeyRevokesTheOldEnrollmentAndEnrollsTheNewKey(t *testing.T) { + r := newRig(t) + r.mustAuthenticate("ops", baseSpec(nil)) + old := r.pub("ops") + require.NoError(t, r.store().Delete(t.Context(), "ops")) + + r.mustAuthenticate("ops", baseSpec(nil)) + + fresh := r.pub("ops") + assert.NotEqual(t, authority.Fingerprint(old), authority.Fingerprint(fresh)) + assert.Zero(t, r.fake.Count(old, authority.UseSigning), "the old key was withdrawn") + assert.Equal(t, 1, r.fake.Count(fresh, authority.UseSigning), "the new key is enrolled") + receipts := r.receipts() + require.Len(t, receipts, 1) + assert.Equal(t, authority.Fingerprint(fresh), receipts[0].Fingerprint) + assert.Equal(t, []string{"ops"}, r.status("ops").Revoked) + assert.Equal(t, "enrolled", r.status("ops").Outcome) +} + +func TestAKeyOfAnotherIdentityIsNotRevoked(t *testing.T) { + r := newRig(t) + r.mustAuthenticate("alpha", baseSpec(nil)) + r.mustAuthenticate("beta", baseSpec(nil)) + + r.mustAuthenticate("alpha", baseSpec(nil)) + + assert.Len(t, r.receipts(), 2) + assert.Equal(t, 1, r.fake.Count(r.pub("beta"), authority.UseSigning)) +} + +func TestAnAuthenticateOfAKeyNamedInTheSpecSharesTheKey(t *testing.T) { + r := newRig(t) + r.mustAuthenticate("one", baseSpec(map[string]any{"key": "shared"})) + r.mustAuthenticate("two", baseSpec(map[string]any{"key": "shared"})) + + keys, err := r.store().List(t.Context()) + require.NoError(t, err) + require.Len(t, keys, 1) + assert.Equal(t, "shared", keys[0].Name) + assert.Equal(t, 1, ensureCalls(r.fake), "the second identity finds the first one's receipt") + assert.Len(t, r.agentConfig().Identities, 2) +} + +func TestALockedKeyFailsAsInteractionRequired(t *testing.T) { + r := newRig(t) + r.mustAuthenticate("ops", baseSpec(nil)) + r.deps.OpenStore = func(kind, dir string) (keystore.Store, error) { + store, err := testfakes.FileOpener(kind, dir) + if err != nil { + return nil, err + } + return testfakes.FailingLoad(store, testfakes.ErrLocked), nil + } + r.use() + + _, err := r.authenticate("ops", baseSpec(nil), fakeToken()) + + var failure *identity.Error + require.ErrorAs(t, err, &failure) + assert.Equal(t, identity.CodeKeyLocked, failure.Code) + assert.Contains(t, r.status("ops").Error, "locked") +} + +func TestTheAgentThatNeverComesUpIsReported(t *testing.T) { + r := newRig(t) + r.socketErrs = 1 << 20 + + _, err := r.authenticate("ops", baseSpec(nil), fakeToken()) + + require.ErrorIs(t, err, identity.ErrAgentUnavailable) + assert.Equal(t, string(identity.CodeAgentUnavailable), r.status("ops").Code) + assert.Contains(t, r.status("ops").Error, "socket not up yet") +} + +func TestASlowDaemonIsWaitedFor(t *testing.T) { + r := newRig(t) + r.socketErrs = 3 + before := r.clock.Now() + + r.mustAuthenticate("ops", baseSpec(nil)) + + assert.Len(t, r.checks, 4) + assert.True(t, r.clock.Now().After(before), "it waited between checks") +} + +func TestSigningNeedsSSHKeygen(t *testing.T) { + r := newRig(t) + r.keygenErr = identity.ErrNoSSHKeygen + + _, err := r.authenticate("ops", baseSpec(nil), fakeToken()) + + require.ErrorIs(t, err, identity.ErrNoSSHKeygen) + assert.Contains(t, r.status("ops").Error, "ssh-keygen") + + // An authentication-only identity does not need it. + _, err = r.authenticate("deploy", baseSpec(map[string]any{"allow": []any{"authentication"}}), fakeToken()) + require.NoError(t, err) +} + +func TestAStaleGitConfigIsRemovedWhenSigningIsDropped(t *testing.T) { + r := newRig(t) + r.mustAuthenticate("ops", baseSpec(map[string]any{"allow": []any{"signing", "authentication"}})) + require.FileExists(t, r.gitConfigPath("ops")) + + r.mustAuthenticate("ops", baseSpec(map[string]any{"allow": []any{"authentication"}})) + + assert.NoFileExists(t, r.gitConfigPath("ops")) +} + +func TestAnUnchangedGitConfigIsNotRewritten(t *testing.T) { + r := newRig(t) + r.mustAuthenticate("ops", baseSpec(nil)) + before, err := os.Stat(r.gitConfigPath("ops")) + require.NoError(t, err) + r.clock.Advance(time.Hour) + + r.mustAuthenticate("ops", baseSpec(nil)) + + after, err := os.Stat(r.gitConfigPath("ops")) + require.NoError(t, err) + assert.Equal(t, before.ModTime(), after.ModTime()) +} + +func TestTheTokenIsSavedForLogoutAndAFailureToSaveIsOnlyAWarning(t *testing.T) { + r := newRig(t) + r.state.PutErr = errors.New("keyring is read-only") + + r.mustAuthenticate("ops", baseSpec(nil)) + + st := r.status("ops") + assert.True(t, st.Success) + require.Len(t, st.Warnings, 1) + assert.Contains(t, st.Warnings[0], "keyring is read-only") +} + +func TestNoTokenMeansNothingIsSaved(t *testing.T) { + r := newRig(t) + + r.mustAuthenticateWith("ops", baseSpec(map[string]any{"authority": "self"}), map[string]string{"assertion": "self"}) + + assert.Zero(t, r.state.Puts) + assert.Equal(t, "enrolled", r.status("ops").Outcome) + assert.Zero(t, ensureCalls(r.fake)) +} + +func TestAnInvalidIdentityNameTouchesNothing(t *testing.T) { + r := newRig(t) + + _, err := r.authenticate("../escape", baseSpec(nil), fakeToken()) + + require.ErrorIs(t, err, paths.ErrInvalidIdentity) + _, statErr := os.Stat(filepath.Join(filepath.Dir(r.paths.Root()), "escape")) + assert.True(t, os.IsNotExist(statErr)) + assert.Zero(t, ensureCalls(r.fake)) +} + +func TestACorruptReceiptStopsEnrollmentInsteadOfOverwritingIt(t *testing.T) { + r := newRig(t) + r.mustAuthenticate("ops", baseSpec(nil)) + files, err := filepath.Glob(filepath.Join(r.paths.ReceiptsDir(), "*")) + require.NoError(t, err) + require.NotEmpty(t, files) + require.NoError(t, os.WriteFile(files[0], []byte("not json"), 0o600)) + + _, err = r.authenticate("ops", baseSpec(nil), fakeToken()) + + require.ErrorIs(t, err, authority.ErrReceiptCorrupt) + assert.Equal(t, 1, ensureCalls(r.fake)) +} diff --git a/plugins/ssh/identity/errors.go b/plugins/ssh/identity/errors.go new file mode 100644 index 00000000000..f7eed046b48 --- /dev/null +++ b/plugins/ssh/identity/errors.go @@ -0,0 +1,151 @@ +package identity + +import ( + "context" + "errors" + "fmt" + "strings" + + "github.com/cloudposse/atmos/plugins/ssh/agent" + "github.com/cloudposse/atmos/plugins/ssh/authority" + "github.com/cloudposse/atmos/plugins/ssh/keystore" + "github.com/cloudposse/atmos/plugins/ssh/service" +) + +// Code is a short, stable name for a kind of failure. It is recorded in the status file. +type Code string + +// Failure codes. +const ( + CodeInvalidSpec Code = "invalid-spec" + CodeRequirementMismatch Code = "requirement-mismatch" + CodeUnsupportedRequirement Code = "unsupported-requirement" + CodeUnknownAuthority Code = "unknown-authority" + CodeUnsupportedUse Code = "unsupported-use" + CodeTokenRejected Code = "token-rejected" + CodeMissingScope Code = "missing-scope" + CodeAuthorityUnreachable Code = "authority-unreachable" + CodeKeyLocked Code = "key-locked" + CodeAgentUnavailable Code = "agent-unavailable" + CodeUnsupportedPlatform Code = "unsupported-platform" + CodeCanceled Code = "canceled" + CodeInternal Code = "internal" +) + +// Sentinel errors. +var ( + // ErrAgentUnavailable means the identity's agent socket did not come up. + ErrAgentUnavailable = errors.New("the agent did not start serving the identity") + // ErrNoSSHKeygen means no ssh-keygen was found, and Git signing needs one. + ErrNoSSHKeygen = errors.New("ssh-keygen not found") +) + +// Error is a failure with a Code and a message that says what to do about it. The message is +// safe to record: credentials are removed from it. +type Error struct { + Code Code + Message string + Err error +} + +// Error implements the error interface. +func (e *Error) Error() string { return e.Message } + +// Unwrap returns the cause. +func (e *Error) Unwrap() error { return e.Err } + +// classify turns any failure into an *Error. secrets are removed from the message. +func classify(identityName, keyName string, err error, secrets ...string) *Error { + var known *Error + if errors.As(err, &known) { + return known + } + code, msg := describe(identityName, keyName, err) + return &Error{Code: code, Message: scrub(msg, secrets), Err: err} +} + +// rule maps a kind of failure to its Code and the message to record. +type rule struct { + matches func(err error) bool + code Code + message func(keyName string, err error) string +} + +// is matches when the error wraps any of the targets. +func is(targets ...error) func(error) bool { + return func(err error) bool { + for _, t := range targets { + if errors.Is(err, t) { + return true + } + } + return false + } +} + +func plain(keyName string, err error) string { return err.Error() } + +func suffixed(suffix string) func(string, error) string { + return func(_ string, err error) string { return err.Error() + suffix } +} + +// rules are tried in order; the first match wins. +var rules = []rule{ + {is(context.Canceled, context.DeadlineExceeded), CodeCanceled, func(_ string, err error) string { + return "the operation was canceled or timed out: " + err.Error() + }}, + {keystore.IsInteractionNotAllowed, CodeKeyLocked, func(_ string, err error) string { + return "the key is locked: the screen is locked and the key requires an unlocked screen (" + err.Error() + ")" + }}, + {is(keystore.ErrRequirementMismatch), CodeRequirementMismatch, func(keyName string, err error) string { + return fmt.Sprintf("%v. The requirement is fixed when a key is created, so rotate the key: run "+ + "\"atmos ssh key delete %s --yes\", then log in again", err, keyName) + }}, + { + is(keystore.ErrUnsupportedRequirement), CodeUnsupportedRequirement, + suffixed(". Remove the term from require or choose a key store that can enforce it"), + }, + {is(authority.ErrUnknownAuthority), CodeUnknownAuthority, func(_ string, err error) string { + return fmt.Sprintf("%v (known: %s)", err, strings.Join(authority.Names(), ", ")) + }}, + {is(authority.ErrUnsupportedUse), CodeUnsupportedUse, plain}, + {is(authority.ErrMissingPermission), CodeMissingScope, func(_ string, err error) string { return missingScope(err) }}, + {is(authority.ErrUnauthorized), CodeTokenRejected, suffixed(". Check the token stored for the provider this identity uses")}, + { + is(authority.ErrUnavailable, authority.ErrRateLimited), CodeAuthorityUnreachable, + suffixed(". The key could not be enrolled; try again later"), + }, + {is(keystore.ErrUnsupportedPlatform, agent.ErrUnsupportedPlatform, service.ErrUnsupportedPlatform), CodeUnsupportedPlatform, plain}, + {is(ErrInvalidSpec), CodeInvalidSpec, plain}, + {is(ErrAgentUnavailable, agent.ErrSocketInUse), CodeAgentUnavailable, func(_ string, err error) string { + return fmt.Sprintf("%v. Run \"atmos ssh agent status\" and read \"atmos ssh agent log\" for details", err) + }}, +} + +func describe(_, keyName string, err error) (Code, string) { + for _, r := range rules { + if r.matches(err) { + return r.code, r.message(keyName, err) + } + } + return CodeInternal, err.Error() +} + +// missingScope names the permission the credential lacked. +func missingScope(err error) string { + var ae *authority.Error + if errors.As(err, &ae) && ae.Permission != "" { + return fmt.Sprintf("the token lacks the %s scope: %v. Add the scope to the token and log in again", ae.Permission, err) + } + return err.Error() + ". Add the missing scope to the token and log in again" +} + +// scrub removes every secret from s. +func scrub(s string, secrets []string) string { + for _, secret := range secrets { + if len(secret) >= 4 { + s = strings.ReplaceAll(s, secret, "[redacted]") + } + } + return s +} diff --git a/plugins/ssh/identity/files.go b/plugins/ssh/identity/files.go new file mode 100644 index 00000000000..1c5cc5db7e6 --- /dev/null +++ b/plugins/ssh/identity/files.go @@ -0,0 +1,39 @@ +package identity + +import ( + "fmt" + "os" + "path/filepath" + + "github.com/cloudposse/atmos/plugins/ssh/paths" +) + +// writeAtomic writes data to path with mode 0600 through a temporary file in the same directory, +// so a reader never sees a partial file. +func writeAtomic(path string, data []byte) error { + dir := filepath.Dir(path) + if err := os.MkdirAll(dir, paths.DirMode); err != nil { + return fmt.Errorf("create %s: %w", dir, err) + } + tmp, err := os.CreateTemp(dir, ".tmp-*") + if err != nil { + return fmt.Errorf("create temporary file in %s: %w", dir, err) + } + name := tmp.Name() + // Chmod fails harmlessly on Windows, where the private directory is the protection. + _ = tmp.Chmod(0o600) + if _, err := tmp.Write(data); err != nil { + _ = tmp.Close() + _ = os.Remove(name) + return fmt.Errorf("write %s: %w", name, err) + } + if err := tmp.Close(); err != nil { + _ = os.Remove(name) + return fmt.Errorf("close %s: %w", name, err) + } + if err := os.Rename(name, path); err != nil { + _ = os.Remove(name) + return fmt.Errorf("replace %s: %w", path, err) + } + return nil +} diff --git a/plugins/ssh/identity/gitconfig.go b/plugins/ssh/identity/gitconfig.go new file mode 100644 index 00000000000..13257eec8a8 --- /dev/null +++ b/plugins/ssh/identity/gitconfig.go @@ -0,0 +1,86 @@ +package identity + +import ( + "fmt" + "os" + "path/filepath" + "strings" + + "github.com/cloudposse/atmos/plugins/ssh/paths" +) + +const gitDirName = "git" + +// GitConfigPath returns the generated Git configuration file of identity. +func GitConfigPath(p *paths.Paths, identity string) (string, error) { + if err := paths.ValidateIdentity(identity); err != nil { + return "", err + } + return filepath.Join(p.Root(), gitDirName, identity+".gitconfig"), nil +} + +// GitConfig describes the generated Git configuration. +type GitConfig struct { + // Includes are the user's own configuration files, read first so this file overrides them. + Includes []string + // Signing turns on SSH commit and tag signing. + Signing bool + // SSHKeygen is the absolute path of ssh-keygen, for gpg.ssh.program. + SSHKeygen string + // SigningKey is the public key in authorized_keys form. + SigningKey string + // RewriteHTTPS lists hosts whose HTTPS URLs are rewritten to SSH. + RewriteHTTPS []string +} + +// Render returns the file content. The user's configuration is included before anything else +// is set, so the settings below win over it. +func (g GitConfig) Render(identity string) string { + var b strings.Builder + fmt.Fprintf(&b, "# Generated by the Atmos SSH plugin for identity %s. Edits are overwritten at the next login.\n", quote(identity)) + if len(g.Includes) > 0 { + b.WriteString("[include]\n") + for _, path := range g.Includes { + fmt.Fprintf(&b, "\tpath = %s\n", quote(filepath.ToSlash(path))) + } + } + if g.Signing { + fmt.Fprintf(&b, "[gpg]\n\tformat = ssh\n") + fmt.Fprintf(&b, "[gpg \"ssh\"]\n\tprogram = %s\n", quote(filepath.ToSlash(g.SSHKeygen))) + fmt.Fprintf(&b, "[user]\n\tsigningkey = %s\n", quote("key::"+g.SigningKey)) + b.WriteString("[commit]\n\tgpgsign = true\n[tag]\n\tgpgsign = true\n") + } + for _, host := range g.RewriteHTTPS { + fmt.Fprintf(&b, "[url %s]\n\tinsteadOf = %s\n", quote("ssh://git@"+host+"/"), quote("https://"+host+"/")) + } + return b.String() +} + +// quote returns s as a double-quoted Git configuration value. +func quote(s string) string { + r := strings.NewReplacer(`\`, `\\`, `"`, `\"`, "\n", `\n`) + return `"` + r.Replace(s) + `"` +} + +// writeGitConfig writes the file for identity, or removes it when none is needed. It leaves an +// unchanged file alone. +func writeGitConfig(p *paths.Paths, identity string, g *GitConfig) (string, error) { + path, err := GitConfigPath(p, identity) + if err != nil { + return "", err + } + if g == nil { + if err := os.Remove(path); err != nil && !os.IsNotExist(err) { + return "", fmt.Errorf("remove %s: %w", path, err) + } + return "", nil + } + want := []byte(g.Render(identity)) + if have, err := os.ReadFile(path); err == nil && string(have) == string(want) { + return path, nil + } + if err := writeAtomic(path, want); err != nil { + return "", err + } + return path, nil +} diff --git a/plugins/ssh/identity/gitconfig_test.go b/plugins/ssh/identity/gitconfig_test.go new file mode 100644 index 00000000000..1f2f31891fc --- /dev/null +++ b/plugins/ssh/identity/gitconfig_test.go @@ -0,0 +1,85 @@ +package identity_test + +import ( + "path/filepath" + "strings" + "testing" + + "github.com/stretchr/testify/assert" + + "github.com/cloudposse/atmos/plugins/ssh/identity" +) + +func absolute(parts ...string) string { + return filepath.Join(append([]string{string(filepath.Separator) + "srv"}, parts...)...) +} + +func TestGitConfigIncludesTheUsersConfigurationFirst(t *testing.T) { + g := identity.GitConfig{ + Includes: []string{"/home/u/.gitconfig", "/home/u/.config/git/config"}, + Signing: true, + SSHKeygen: "/usr/bin/ssh-keygen", + SigningKey: "ssh-ed25519 AAAAC3Nza", + RewriteHTTPS: []string{"github.com", "git.example.com:8443"}, + } + + got := g.Render("ops") + + want := `# Generated by the Atmos SSH plugin for identity "ops". Edits are overwritten at the next login. +[include] + path = "/home/u/.gitconfig" + path = "/home/u/.config/git/config" +[gpg] + format = ssh +[gpg "ssh"] + program = "/usr/bin/ssh-keygen" +[user] + signingkey = "key::ssh-ed25519 AAAAC3Nza" +[commit] + gpgsign = true +[tag] + gpgsign = true +[url "ssh://git@github.com/"] + insteadOf = "https://github.com/" +[url "ssh://git@git.example.com:8443/"] + insteadOf = "https://git.example.com:8443/" +` + assert.Equal(t, want, got) + include := strings.Index(got, "[include]") + for _, section := range []string{"[gpg]", "[user]", "[commit]", "[tag]", "[url "} { + assert.Less(t, include, strings.Index(got, section), "%s comes after the include", section) + } +} + +func TestGitConfigWithoutSigningOnlyRewritesURLs(t *testing.T) { + g := identity.GitConfig{Includes: []string{"/h/.gitconfig"}, RewriteHTTPS: []string{"github.com"}} + + got := g.Render("ops") + + assert.Contains(t, got, "[url \"ssh://git@github.com/\"]") + assert.NotContains(t, got, "gpgsign") + assert.NotContains(t, got, "signingkey") + assert.NotContains(t, got, "[gpg") +} + +func TestGitConfigQuotesAwkwardValues(t *testing.T) { + g := identity.GitConfig{ + Includes: []string{`/home/a "b"/.gitconfig`}, Signing: true, SSHKeygen: "/opt/ssh keygen/ssh-keygen", + SigningKey: "ssh-ed25519 AAAA", + } + + got := g.Render(`na"me`) + + assert.Contains(t, got, `identity "na\"me"`) + assert.Contains(t, got, `path = "/home/a \"b\"/.gitconfig"`) + assert.Contains(t, got, `program = "/opt/ssh keygen/ssh-keygen"`) +} + +func TestGitConfigEscapesBackslashesThatAreNotSeparators(t *testing.T) { + if filepath.Separator == '\\' { + t.Skip("on Windows backslashes are separators and are written as slashes") + } + g := identity.GitConfig{Includes: []string{`/home/a\b/.gitconfig`}} + + assert.Contains(t, g.Render("ops"), `path = "/home/a\\b/.gitconfig"`) +} diff --git a/plugins/ssh/identity/identity.go b/plugins/ssh/identity/identity.go new file mode 100644 index 00000000000..8a418ef7b68 --- /dev/null +++ b/plugins/ssh/identity/identity.go @@ -0,0 +1,104 @@ +// Package identity implements the ssh/key identity: it creates the key, has an authority vouch +// for it, keeps the agent daemon running, and returns the environment that makes tools use it. +// +// Authenticate runs on every use of the identity, each time in a fresh process, so it is +// idempotent and does nothing expensive when nothing changed. Every outside dependency is injected +// through Deps. +package identity + +import ( + "context" + "net/http" + "time" + + "golang.org/x/crypto/ssh" + + "github.com/cloudposse/atmos/plugins/ssh/agent" + "github.com/cloudposse/atmos/plugins/ssh/authority" + "github.com/cloudposse/atmos/plugins/ssh/daemon" + "github.com/cloudposse/atmos/plugins/ssh/paths" +) + +const ( + // CredentialLifetime is how long the environment credential is valid. The host rejects a + // credential without an expiry, and every use authenticates again anyway. + CredentialLifetime = 12 * time.Hour + + // StateTokenKey is the private-state entry that holds the upstream token for logout. + StateTokenKey = "upstream-token" + + // socketAttempts and socketInterval bound the wait for the daemon to serve a new socket. The + // daemon notices configuration changes by polling, so a new socket takes a few seconds. + socketAttempts = 40 + socketInterval = 250 * time.Millisecond +) + +// Environment variable names the identity sets. +const ( + EnvAuthSock = "SSH_AUTH_SOCK" + EnvGitConfig = "GIT_CONFIG_GLOBAL" + EnvAnsibleUsr = "ANSIBLE_REMOTE_USER" +) + +// PrivateState is the host's private session state for this identity. It survives between +// invocations and is cleared by the host after logout. +type PrivateState interface { + Get(ctx context.Context, key string) ([]byte, bool, error) + Put(ctx context.Context, key string, data []byte) error + Delete(ctx context.Context, key string) error +} + +// Deps are the outside dependencies of the identity. +type Deps struct { + // Paths returns the data root; an empty root means the default location. + Paths func(root string) (*paths.Paths, error) + // OpenStore builds a key store. + OpenStore agent.StoreOpener + // Authorities builds authorities by name. + Authorities *authority.Registry + // Daemon makes sure the agent daemon is running the current version. + Daemon daemon.Deps + // CheckSocket verifies that an identity's socket serves the expected key. + CheckSocket func(ctx context.Context, socket string, want ssh.PublicKey) error + // HTTPClient is the client authorities use. The caller binds the context to the invocation. + HTTPClient *http.Client + // State is the identity's private state. + State PrivateState + // Now is the clock. + Now func() time.Time + // Hostname returns the machine's name, for the key's title. + Hostname func() (string, error) + // HomeDir returns the user's home directory, for the Git configuration includes. + HomeDir func() (string, error) + // FindSSHKeygen returns the absolute path of ssh-keygen. + FindSSHKeygen func() (string, error) + // Sleep waits for d, or until ctx ends. + Sleep func(ctx context.Context, d time.Duration) error +} + +// Service is the ssh/key identity. +type Service struct { + deps Deps +} + +// New returns the identity service. +func New(deps Deps) *Service { return &Service{deps: deps} } + +// Result is what Authenticate returns. +type Result struct { + // Environment is the variables to set. + Environment map[string]string + // ExpiresAt is when the credential stops being valid. + ExpiresAt time.Time +} + +// Validate checks an identity's spec without touching anything. +func (s *Service) Validate(name string, raw map[string]any) error { + if err := paths.ValidateIdentity(name); err != nil { + return classify(name, name, err) + } + if _, err := ParseSpec(raw); err != nil { + return classify(name, name, err) + } + return nil +} diff --git a/plugins/ssh/identity/logout.go b/plugins/ssh/identity/logout.go new file mode 100644 index 00000000000..12f2d9b457e --- /dev/null +++ b/plugins/ssh/identity/logout.go @@ -0,0 +1,117 @@ +package identity + +import ( + "context" + "errors" + "fmt" + + "github.com/cloudposse/atmos/plugins/ssh/agent" + "github.com/cloudposse/atmos/plugins/ssh/authority" + "github.com/cloudposse/atmos/plugins/ssh/inventory" + "github.com/cloudposse/atmos/plugins/ssh/paths" + "github.com/cloudposse/atmos/plugins/ssh/statusfile" +) + +// Logout withdraws the enrollments whose key no longer exists on this machine, using the token the +// identity saved when it last authenticated, and takes the identity out of the agent so its socket +// goes away. A key that still exists stays enrolled: logging out never strips a working machine. +// The host clears the identity's private state afterwards. +func (s *Service) Logout(ctx context.Context, name string, raw map[string]any) error { + r := &run{svc: s, name: name} + r.status = statusfile.Status{Identity: name, Operation: statusfile.OperationLogout} + err := r.logout(ctx, raw) + return r.finish(err) +} + +func (r *run) logout(ctx context.Context, raw map[string]any) error { + if err := r.resolveLogout(raw); err != nil { + return err + } + token := r.savedToken(ctx) + if token != "" { + r.upstream, r.secrets = map[string]string{authority.CredentialToken: token}, []string{token} + } + pruneErr := r.prune(ctx) + var errs []error + if pruneErr != nil { + errs = append(errs, pruneErr) + } + if _, err := agent.RemoveIdentity(r.paths.AgentConfigFile(), r.name); err != nil { + errs = append(errs, err) + } + if _, err := writeGitConfig(r.paths, r.name, nil); err != nil { + errs = append(errs, err) + } + return errors.Join(errs...) +} + +// resolveLogout is resolve without the parts that create things. An invalid spec still allows the +// agent entry to be removed, so a bad edit cannot trap a stale socket. +func (r *run) resolveLogout(raw map[string]any) error { + if err := paths.ValidateIdentity(r.name); err != nil { + return err + } + spec, specErr := ParseSpec(raw) + root := spec.Root + if specErr != nil { + root, _ = raw["root"].(string) + } + p, err := r.svc.deps.Paths(root) + if err != nil { + return err + } + r.paths = p + if specErr != nil { + // Without a valid spec the authority is unknown, so fall back to removing the agent entry. + r.spec = Spec{Authority: ""} + r.status.Warnings = append(r.status.Warnings, "enrollments were not checked: "+specErr.Error()) + return nil + } + r.spec, r.keyName = spec, spec.KeyName(r.name) + r.status.Key, r.status.Store, r.status.Authority = r.keyName, spec.Store, spec.Authority + return nil +} + +func (r *run) savedToken(ctx context.Context) string { + data, found, err := r.svc.deps.State.Get(ctx, StateTokenKey) + if err != nil { + r.status.Warnings = append(r.status.Warnings, "the saved token could not be read: "+err.Error()) + return "" + } + if !found { + return "" + } + return string(data) +} + +// prune withdraws the enrollments of keys that are gone. +func (r *run) prune(ctx context.Context) error { + if r.spec.Authority == "" { + r.status.Outcome = "skipped" + return nil + } + d := r.svc.deps + keys, listErr := inventory.List(ctx, d.OpenStore, r.paths) + existing := inventory.Fingerprints(keys, listErr) + if existing == nil { + r.status.Outcome = "skipped" + r.status.Warnings = append(r.status.Warnings, "enrollments were not checked because the key stores could not all be listed: "+listErr.Error()) + return nil + } + auth, err := d.Authorities.New(r.spec.Authority, authority.Options{HTTPClient: d.HTTPClient}) + if err != nil { + return err + } + receipts, err := authority.NewStore(r.paths.ReceiptsDir()) + if err != nil { + return err + } + res, err := authority.Prune(ctx, authority.Params{ + Authority: auth, Credentials: r.upstream, Store: receipts, Existing: existing, Now: d.Now, + }) + r.record(res) + if err != nil { + return fmt.Errorf("withdraw enrollments of missing keys: %w", err) + } + return nil +} diff --git a/plugins/ssh/identity/logout_test.go b/plugins/ssh/identity/logout_test.go new file mode 100644 index 00000000000..6375eeb370e --- /dev/null +++ b/plugins/ssh/identity/logout_test.go @@ -0,0 +1,134 @@ +package identity_test + +import ( + "context" + "os" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/cloudposse/atmos/plugins/ssh/authority" + "github.com/cloudposse/atmos/plugins/ssh/authority/authoritytest" + "github.com/cloudposse/atmos/plugins/ssh/identity" + "github.com/cloudposse/atmos/plugins/ssh/keystore" +) + +func (r *rig) logout(name string, spec map[string]any) error { + r.t.Helper() + return r.svc.Logout(context.Background(), name, spec) +} + +func TestLogoutWithALiveKeyLeavesItEnrolledAndRemovesTheAgentEntry(t *testing.T) { + r := newRig(t) + r.mustAuthenticate("ops", baseSpec(nil)) + pub := r.pub("ops") + require.Len(t, r.agentConfig().Identities, 1) + require.FileExists(t, r.gitConfigPath("ops")) + + require.NoError(t, r.logout("ops", baseSpec(nil))) + + assert.Equal(t, 1, r.fake.Count(pub, authority.UseSigning), "a live key stays enrolled") + assert.Len(t, r.receipts(), 1) + assert.Empty(t, r.agentConfig().Identities, "the socket goes away with the agent entry") + assert.NoFileExists(t, r.gitConfigPath("ops")) + assert.Equal(t, 0, r.fake.CallCount("revoke")) + st := r.status("ops") + assert.True(t, st.Success) + assert.Equal(t, "logout", st.Operation) +} + +func TestLogoutRevokesTheEnrollmentOfAKeyThatIsGone(t *testing.T) { + r := newRig(t) + r.mustAuthenticate("ops", baseSpec(map[string]any{"allow": []any{"signing", "authentication"}})) + pub := r.pub("ops") + require.NoError(t, r.store().Delete(t.Context(), "ops")) + + require.NoError(t, r.logout("ops", baseSpec(map[string]any{"allow": []any{"signing", "authentication"}}))) + + assert.Zero(t, r.fake.Count(pub, authority.UseSigning)) + assert.Zero(t, r.fake.Count(pub, authority.UseAuthentication)) + assert.Empty(t, r.receipts(), "the receipt goes once the enrollment is withdrawn") + assert.Equal(t, []string{"ops"}, r.status("ops").Revoked) + assert.Empty(t, r.agentConfig().Identities) +} + +func TestLogoutRevokesOnlyReceiptsWhoseKeyIsGone(t *testing.T) { + r := newRig(t) + r.mustAuthenticate("gone", baseSpec(nil)) + r.mustAuthenticate("kept", baseSpec(nil)) + gone, kept := r.pub("gone"), r.pub("kept") + require.NoError(t, r.store().Delete(t.Context(), "gone")) + + require.NoError(t, r.logout("kept", baseSpec(nil))) + + assert.Zero(t, r.fake.Count(gone, authority.UseSigning), "the missing key's enrollment was withdrawn") + assert.Equal(t, 1, r.fake.Count(kept, authority.UseSigning), "the live key stays") + receipts := r.receipts() + require.Len(t, receipts, 1) + assert.Equal(t, "kept", receipts[0].KeyName) +} + +func TestLogoutUsesTheTokenTheIdentitySaved(t *testing.T) { + r := newRig(t) + r.mustAuthenticate("ops", baseSpec(nil)) + require.NoError(t, r.store().Delete(t.Context(), "ops")) + require.Equal(t, authoritytest.FakeToken, string(r.state.Data[identity.StateTokenKey])) + + require.NoError(t, r.logout("ops", baseSpec(nil))) + + assert.Equal(t, 1, r.fake.CallCount("revoke")) +} + +func TestLogoutWithoutASavedTokenReportsWhatItCouldNotRevoke(t *testing.T) { + r := newRig(t) + r.mustAuthenticate("ops", baseSpec(nil)) + require.NoError(t, r.store().Delete(t.Context(), "ops")) + r.state.Data = map[string][]byte{} + + err := r.logout("ops", baseSpec(nil)) + + require.Error(t, err) + assert.Len(t, r.receipts(), 1, "the receipt stays so a later login or logout can retry") + assert.Empty(t, r.agentConfig().Identities, "the agent entry is removed anyway") + assert.False(t, r.status("ops").Success) + assert.NotEmpty(t, r.status("ops").Error) +} + +func TestLogoutDoesNotRevokeWhenTheKeyStoresCannotAllBeListed(t *testing.T) { + r := newRig(t) + r.mustAuthenticate("ops", baseSpec(nil)) + require.NoError(t, r.store().Delete(t.Context(), "ops")) + opener := r.deps.OpenStore + r.deps.OpenStore = func(kind, dir string) (keystore.Store, error) { + if kind == "secure-enclave" { + return nil, os.ErrPermission + } + return opener(kind, dir) + } + r.use() + + require.NoError(t, r.logout("ops", baseSpec(nil))) + + assert.Zero(t, r.fake.CallCount("revoke"), "an unknown set of keys revokes nothing") + assert.Len(t, r.receipts(), 1) + assert.NotEmpty(t, r.status("ops").Warnings) +} + +func TestLogoutWithAnInvalidSpecStillRemovesTheAgentEntry(t *testing.T) { + r := newRig(t) + r.mustAuthenticate("ops", baseSpec(nil)) + + require.NoError(t, r.logout("ops", map[string]any{"nonsense": true})) + + assert.Empty(t, r.agentConfig().Identities) + assert.Contains(t, r.status("ops").Warnings[0], "enrollments were not checked") +} + +func TestLogoutOfAnIdentityThatNeverLoggedInIsHarmless(t *testing.T) { + r := newRig(t) + + require.NoError(t, r.logout("ops", baseSpec(nil))) + + assert.Zero(t, r.fake.CallCount("revoke")) +} diff --git a/plugins/ssh/identity/rig_test.go b/plugins/ssh/identity/rig_test.go new file mode 100644 index 00000000000..a8fa5b85a58 --- /dev/null +++ b/plugins/ssh/identity/rig_test.go @@ -0,0 +1,183 @@ +package identity_test + +import ( + "context" + "errors" + "net/http" + "os" + "path/filepath" + "testing" + + "github.com/stretchr/testify/require" + "golang.org/x/crypto/ssh" + + "github.com/cloudposse/atmos/plugins/ssh/agent" + "github.com/cloudposse/atmos/plugins/ssh/authority" + "github.com/cloudposse/atmos/plugins/ssh/authority/authoritytest" + "github.com/cloudposse/atmos/plugins/ssh/authority/github" + "github.com/cloudposse/atmos/plugins/ssh/authority/self" + "github.com/cloudposse/atmos/plugins/ssh/daemon" + "github.com/cloudposse/atmos/plugins/ssh/identity" + "github.com/cloudposse/atmos/plugins/ssh/internal/testfakes" + "github.com/cloudposse/atmos/plugins/ssh/keystore" + "github.com/cloudposse/atmos/plugins/ssh/paths" + "github.com/cloudposse/atmos/plugins/ssh/service" + "github.com/cloudposse/atmos/plugins/ssh/statusfile" +) + +const ( + version = "0.1.0" + hostname = "testhost" + home = "/home/tester" + keygen = "/usr/bin/ssh-keygen" +) + +// rig is an identity service wired to fakes, rooted in a temporary directory. +type rig struct { + t *testing.T + paths *paths.Paths + fake *authoritytest.Fake + mgr *testfakes.Manager + state *testfakes.State + clock *testfakes.Clock + deps identity.Deps + checks []string + // socketErrs makes the first CheckSocket calls fail. + socketErrs int + installs int + keygenErr error + svc *identity.Service +} + +type failTransport struct{ t *testing.T } + +func (f failTransport) RoundTrip(r *http.Request) (*http.Response, error) { + f.t.Errorf("unexpected network call to %s", r.URL) + return nil, errors.New("network is not available in tests") +} + +func newRig(t *testing.T) *rig { + t.Helper() + r := &rig{ + t: t, paths: testfakes.Paths(t), fake: authoritytest.NewFake("fake"), + mgr: &testfakes.Manager{Version: version}, state: testfakes.NewState(), clock: testfakes.NewClock(), + } + reg := authority.NewRegistry() + require.NoError(t, reg.Register(authority.Factory{Name: "fake", New: func(authority.Options) (authority.Authority, error) { return r.fake, nil }})) + require.NoError(t, reg.Register(github.Factory)) + require.NoError(t, reg.Register(self.Factory)) + r.deps = identity.Deps{ + Paths: func(string) (*paths.Paths, error) { return r.paths, nil }, + OpenStore: testfakes.FileOpener, + Authorities: reg, + Daemon: daemon.Deps{ + Service: func(*paths.Paths) (service.Manager, error) { return r.mgr, nil }, + InstallExecutable: func(p *paths.Paths, v string) (string, error) { + r.installs++ + return service.StablePath(p, v) + }, + Version: version, + }, + CheckSocket: func(_ context.Context, socket string, want ssh.PublicKey) error { + r.checks = append(r.checks, socket) + if r.socketErrs > 0 { + r.socketErrs-- + return errors.New("socket not up yet") + } + return nil + }, + HTTPClient: &http.Client{Transport: failTransport{t}}, + State: r.state, + Now: r.clock.Now, + Hostname: func() (string, error) { return hostname, nil }, + HomeDir: func() (string, error) { return home, nil }, + FindSSHKeygen: func() (string, error) { return keygen, r.keygenErr }, + Sleep: r.clock.Sleep, + } + r.svc = identity.New(r.deps) + return r +} + +// use rebuilds the service after the test changed r.deps. +func (r *rig) use() *rig { + r.svc = identity.New(r.deps) + return r +} + +func fakeToken() map[string]string { + return map[string]string{authority.CredentialToken: authoritytest.FakeToken} +} + +func baseSpec(extra map[string]any) map[string]any { + spec := map[string]any{"authority": "fake", "store": "file", "allow": []any{"signing"}} + for k, v := range extra { + spec[k] = v + } + return spec +} + +func (r *rig) authenticate(name string, spec map[string]any, upstream map[string]string) (identity.Result, error) { + r.t.Helper() + return r.svc.Authenticate(context.Background(), name, spec, upstream) +} + +func (r *rig) mustAuthenticate(name string, spec map[string]any) identity.Result { + r.t.Helper() + res, err := r.authenticate(name, spec, fakeToken()) + require.NoError(r.t, err) + return res +} + +func (r *rig) mustAuthenticateWith(name string, spec map[string]any, upstream map[string]string) identity.Result { + r.t.Helper() + res, err := r.authenticate(name, spec, upstream) + require.NoError(r.t, err) + return res +} + +func (r *rig) store() keystore.Store { return keystore.NewFileStore(r.paths.StoreDir("file")) } + +func (r *rig) pub(name string) ssh.PublicKey { + r.t.Helper() + return testfakes.PublicKeyOf(r.t, r.store(), name) +} + +func (r *rig) status(name string) statusfile.Status { + r.t.Helper() + s, err := statusfile.Read(r.paths, name) + require.NoError(r.t, err) + return s +} + +func (r *rig) receipts() []authority.Receipt { + r.t.Helper() + store, err := authority.NewStore(r.paths.ReceiptsDir()) + require.NoError(r.t, err) + list, err := store.List() + require.NoError(r.t, err) + return list +} + +func (r *rig) agentConfig() *agent.Config { + r.t.Helper() + cfg, err := agent.LoadConfig(r.paths.AgentConfigFile()) + if errors.Is(err, agent.ErrConfigNotFound) { + return &agent.Config{} + } + require.NoError(r.t, err) + return cfg +} + +func (r *rig) readFile(path string) string { + r.t.Helper() + data, err := os.ReadFile(path) + require.NoError(r.t, err) + return string(data) +} + +func (r *rig) gitConfigPath(name string) string { + r.t.Helper() + return filepath.Join(r.paths.Root(), "git", name+".gitconfig") +} + +func ensureCalls(f *authoritytest.Fake) int { return f.CallCount("ensure") } diff --git a/plugins/ssh/identity/spec.go b/plugins/ssh/identity/spec.go new file mode 100644 index 00000000000..948128977ba --- /dev/null +++ b/plugins/ssh/identity/spec.go @@ -0,0 +1,222 @@ +package identity + +import ( + "errors" + "fmt" + "path/filepath" + "regexp" + "slices" + "sort" + "strings" + + "github.com/cloudposse/atmos/plugins/ssh/agent" + "github.com/cloudposse/atmos/plugins/ssh/keystore" + "github.com/cloudposse/atmos/plugins/ssh/paths" +) + +// ErrInvalidSpec means an identity's spec is malformed. +var ErrInvalidSpec = errors.New("invalid ssh/key identity spec") + +// AuthoritySelf is the authority used when the spec names none. +const AuthoritySelf = "self" + +var ( + storeRE = regexp.MustCompile(`^[a-z][a-z0-9-]*$`) + userRE = regexp.MustCompile(`^[^\s\x00-\x1f\x7f]{1,64}$`) + hostRE = regexp.MustCompile(`^[A-Za-z0-9]([A-Za-z0-9.-]*[A-Za-z0-9])?(:[0-9]{1,5})?$`) + knownSpecs = []string{"authority", "store", "allow", "require", "user", "key", "rewrite_https", "root"} +) + +// Spec is the parsed spec of an ssh/key identity. +type Spec struct { + // Authority names who vouches for the key. + Authority string + // Store names the key store. + Store string + // Allow lists what the key may do, in canonical order and without duplicates. + Allow []agent.Allow + // Require lists the requirement terms, sorted and without duplicates. + Require []keystore.Requirement + // User is the SSH login name on the remote side. + User string + // Key is the key's name in the store. It is empty when it defaults to the identity's name. + Key string + // RewriteHTTPS lists hosts whose HTTPS Git URLs are rewritten to SSH. + RewriteHTTPS []string + // Root overrides the plugin's data root. + Root string +} + +// KeyName returns the key's name for identity. +func (s Spec) KeyName(identity string) string { + if s.Key != "" { + return s.Key + } + return identity +} + +// Uses reports whether the spec allows a. +func (s Spec) Uses(a agent.Allow) bool { return slices.Contains(s.Allow, a) } + +// ParseSpec reads and validates an identity's spec. It rejects unknown fields. +func ParseSpec(raw map[string]any) (Spec, error) { + for name := range raw { + if !slices.Contains(knownSpecs, name) { + return Spec{}, specError("unknown field %q (known: %s)", name, strings.Join(knownSpecs, ", ")) + } + } + var s Spec + var err error + if s.Authority, err = optionalString(raw, "authority"); err != nil { + return Spec{}, err + } + if s.Authority == "" { + s.Authority = AuthoritySelf + } + if err := s.parseStore(raw); err != nil { + return Spec{}, err + } + if err := s.parseAllowAndRequire(raw); err != nil { + return Spec{}, err + } + if err := s.parseOptional(raw); err != nil { + return Spec{}, err + } + return s, nil +} + +func specError(format string, args ...any) error { + return fmt.Errorf("%w: %s", ErrInvalidSpec, fmt.Sprintf(format, args...)) +} + +func optionalString(raw map[string]any, field string) (string, error) { + v, ok := raw[field] + if !ok || v == nil { + return "", nil + } + s, ok := v.(string) + if !ok || s == "" { + return "", specError("%s must be a non-empty string", field) + } + return s, nil +} + +func (s *Spec) parseStore(raw map[string]any) error { + store, err := optionalString(raw, "store") + if err != nil { + return err + } + if store == "" { + return specError("store is required") + } + if !storeRE.MatchString(store) { + return specError("store %q is not a key store name", store) + } + s.Store = store + return nil +} + +func (s *Spec) parseAllowAndRequire(raw map[string]any) error { + allow, err := stringList(raw, "allow") + if err != nil { + return err + } + if len(allow) == 0 { + return specError("allow is required and must list signing, authentication, or both") + } + for _, a := range []agent.Allow{agent.AllowSigning, agent.AllowAuthentication} { + if slices.Contains(allow, string(a)) { + s.Allow = append(s.Allow, a) + } + } + for _, a := range allow { + if a != string(agent.AllowSigning) && a != string(agent.AllowAuthentication) { + return specError("allow contains unknown use %q (known: signing, authentication)", a) + } + } + terms, err := stringList(raw, "require") + if err != nil { + return err + } + for _, t := range terms { + if t != string(keystore.Unlocked) { + return specError("require contains unknown term %q (known: %s)", t, keystore.Unlocked) + } + s.Require = append(s.Require, keystore.Requirement(t)) + } + if len(s.Require) > 0 { + s.Require = keystore.Normalize(s.Require) + } + return nil +} + +func (s *Spec) parseOptional(raw map[string]any) error { + var err error + if s.User, err = optionalString(raw, "user"); err != nil { + return err + } + if s.User != "" && !userRE.MatchString(s.User) { + return specError("user %q is not a valid login name", s.User) + } + if s.Key, err = optionalString(raw, "key"); err != nil { + return err + } + if s.Key != "" { + if err := paths.ValidateIdentity(s.Key); err != nil { + return specError("key: %v", err) + } + } + if s.Root, err = optionalString(raw, "root"); err != nil { + return err + } + if s.Root != "" && !filepath.IsAbs(s.Root) { + return specError("root must be an absolute path") + } + hosts, err := stringList(raw, "rewrite_https") + if err != nil { + return err + } + for _, h := range hosts { + if !hostRE.MatchString(h) { + return specError("rewrite_https host %q is not a host name", h) + } + } + s.RewriteHTTPS = uniqueSorted(hosts) + return nil +} + +// stringList reads a field that is a string or a list of strings. An absent field is empty. +func stringList(raw map[string]any, field string) ([]string, error) { + v, ok := raw[field] + if !ok || v == nil { + return nil, nil + } + switch t := v.(type) { + case string: + if t == "" { + return nil, specError("%s must not be empty", field) + } + return []string{t}, nil + case []any: + out := make([]string, 0, len(t)) + for _, item := range t { + s, ok := item.(string) + if !ok || s == "" { + return nil, specError("%s must contain only non-empty strings", field) + } + out = append(out, s) + } + return out, nil + default: + return nil, specError("%s must be a string or a list of strings", field) + } +} + +func uniqueSorted(in []string) []string { + if len(in) == 0 { + return nil + } + out := slices.Clone(in) + sort.Strings(out) + return slices.Compact(out) +} diff --git a/plugins/ssh/identity/spec_test.go b/plugins/ssh/identity/spec_test.go new file mode 100644 index 00000000000..aded357583c --- /dev/null +++ b/plugins/ssh/identity/spec_test.go @@ -0,0 +1,81 @@ +package identity_test + +import ( + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/cloudposse/atmos/plugins/ssh/agent" + "github.com/cloudposse/atmos/plugins/ssh/identity" + "github.com/cloudposse/atmos/plugins/ssh/keystore" +) + +func TestParseSpec(t *testing.T) { + tests := []struct { + name string + raw map[string]any + want identity.Spec + wantErr string + }{ + { + name: "defaults", raw: map[string]any{"store": "file", "allow": []any{"signing"}}, + want: identity.Spec{Authority: "self", Store: "file", Allow: []agent.Allow{agent.AllowSigning}}, + }, + { + name: "everything", + raw: map[string]any{ + "authority": "github", "store": "secure-enclave", "allow": []any{"authentication", "signing", "signing"}, + "require": []any{"unlocked", "unlocked"}, "user": "deploy", "key": "shared", + "rewrite_https": []any{"github.com", "gitlab.com:8443", "github.com"}, "root": absolute("data"), + }, + want: identity.Spec{ + Authority: "github", Store: "secure-enclave", + Allow: []agent.Allow{agent.AllowSigning, agent.AllowAuthentication}, + Require: []keystore.Requirement{keystore.Unlocked}, User: "deploy", Key: "shared", + RewriteHTTPS: []string{"github.com", "gitlab.com:8443"}, Root: absolute("data"), + }, + }, + { + name: "require as a string", raw: map[string]any{"store": "file", "allow": "signing", "require": "unlocked"}, + want: identity.Spec{Authority: "self", Store: "file", Allow: []agent.Allow{agent.AllowSigning}, Require: []keystore.Requirement{keystore.Unlocked}}, + }, + {name: "unknown field", raw: map[string]any{"store": "file", "allow": []any{"signing"}, "colour": "red"}, wantErr: `unknown field "colour"`}, + {name: "store is required", raw: map[string]any{"allow": []any{"signing"}}, wantErr: "store is required"}, + {name: "store with a path", raw: map[string]any{"store": "../x", "allow": []any{"signing"}}, wantErr: "not a key store name"}, + {name: "allow is required", raw: map[string]any{"store": "file"}, wantErr: "allow is required"}, + {name: "allow is empty", raw: map[string]any{"store": "file", "allow": []any{}}, wantErr: "allow is required"}, + {name: "unknown use", raw: map[string]any{"store": "file", "allow": []any{"decrypt"}}, wantErr: `unknown use "decrypt"`}, + {name: "unknown requirement", raw: map[string]any{"store": "file", "allow": []any{"signing"}, "require": []any{"presence"}}, wantErr: `unknown term "presence"`}, + {name: "wrong type", raw: map[string]any{"store": "file", "allow": []any{"signing"}, "user": 7}, wantErr: "user must be"}, + {name: "list with a number", raw: map[string]any{"store": "file", "allow": []any{"signing", 3}}, wantErr: "allow must contain only"}, + {name: "relative root", raw: map[string]any{"store": "file", "allow": []any{"signing"}, "root": "data"}, wantErr: "absolute"}, + {name: "unsafe key name", raw: map[string]any{"store": "file", "allow": []any{"signing"}, "key": "../k"}, wantErr: "key:"}, + {name: "login name with a space", raw: map[string]any{"store": "file", "allow": []any{"signing"}, "user": "a b"}, wantErr: "not a valid login name"}, + {name: "bad host", raw: map[string]any{"store": "file", "allow": []any{"signing"}, "rewrite_https": []any{"a/b"}}, wantErr: "not a host name"}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + got, err := identity.ParseSpec(tt.raw) + if tt.wantErr != "" { + require.ErrorIs(t, err, identity.ErrInvalidSpec) + assert.ErrorContains(t, err, tt.wantErr) + return + } + require.NoError(t, err) + assert.Equal(t, tt.want, got) + }) + } +} + +func TestSpecKeyNameDefaultsToTheIdentity(t *testing.T) { + assert.Equal(t, "ops", identity.Spec{}.KeyName("ops")) + assert.Equal(t, "shared", identity.Spec{Key: "shared"}.KeyName("ops")) +} + +func TestValidate(t *testing.T) { + r := newRig(t) + assert.NoError(t, r.svc.Validate("ops", baseSpec(nil))) + assert.ErrorIs(t, r.svc.Validate("ops", map[string]any{}), identity.ErrInvalidSpec) + assert.Error(t, r.svc.Validate("../ops", baseSpec(nil))) +} diff --git a/plugins/ssh/internal/testfakes/testfakes.go b/plugins/ssh/internal/testfakes/testfakes.go new file mode 100644 index 00000000000..1196a617feb --- /dev/null +++ b/plugins/ssh/internal/testfakes/testfakes.go @@ -0,0 +1,319 @@ +// Package testfakes holds the fakes the SSH plugin's tests share: a service manager that never +// touches launchd or systemd, a private-state store, a settable clock, and key stores that model +// requirements and a locked screen. +package testfakes + +import ( + "context" + "crypto" + "errors" + "fmt" + "io" + "os" + "path/filepath" + "sync" + "testing" + "time" + + "golang.org/x/crypto/ssh" + + "github.com/cloudposse/atmos/plugins/ssh/keystore" + "github.com/cloudposse/atmos/plugins/ssh/paths" + "github.com/cloudposse/atmos/plugins/ssh/service" +) + +// ShortDir makes a temporary directory whose path is short enough for Unix sockets. +func ShortDir(t *testing.T) string { + t.Helper() + base := "" + if _, err := os.Stat("/tmp"); err == nil { + base = "/tmp" + } + dir, err := os.MkdirTemp(base, "sshp") + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = os.RemoveAll(dir) }) + return dir +} + +// Paths returns Paths under a short temporary directory. +func Paths(t *testing.T) *paths.Paths { + t.Helper() + p, err := paths.New(filepath.Join(ShortDir(t), "ssh")) + if err != nil { + t.Fatal(err) + } + return p +} + +// Clock is a clock that only moves when told to. +type Clock struct { + mu sync.Mutex + now time.Time +} + +// NewClock returns a clock set to a fixed instant. +func NewClock() *Clock { + return &Clock{now: time.Date(2026, 11, 12, 10, 0, 0, 0, time.UTC)} +} + +// Now returns the current instant. +func (c *Clock) Now() time.Time { + c.mu.Lock() + defer c.mu.Unlock() + return c.now +} + +// Advance moves the clock forward. +func (c *Clock) Advance(d time.Duration) { + c.mu.Lock() + defer c.mu.Unlock() + c.now = c.now.Add(d) +} + +// Sleep advances the clock instead of waiting, and counts the calls. +func (c *Clock) Sleep(_ context.Context, d time.Duration) error { + c.Advance(d) + return nil +} + +// Manager is a service.Manager that records calls and keeps its state in memory. +type Manager struct { + mu sync.Mutex + St service.Status + Version string + Installs []service.Spec + Starts int + Stops int + StatusErr error + InstallErr error +} + +// Status implements service.Manager. +func (m *Manager) Status(context.Context) (service.Status, error) { + m.mu.Lock() + defer m.mu.Unlock() + return m.St, m.StatusErr +} + +// Install implements service.Manager. The service ends up installed and running the plugin version. +func (m *Manager) Install(_ context.Context, spec service.Spec) error { + m.mu.Lock() + defer m.mu.Unlock() + if m.InstallErr != nil { + return m.InstallErr + } + m.Installs = append(m.Installs, spec) + m.St = service.Status{ + Installed: true, Loaded: true, Running: true, PID: 4242, Executable: spec.Executable, + InstalledVersion: m.Version, DaemonVersion: m.Version, + } + return nil +} + +// Start implements service.Manager. +func (m *Manager) Start(context.Context) error { + m.mu.Lock() + defer m.mu.Unlock() + m.Starts++ + return nil +} + +// Stop implements service.Manager. +func (m *Manager) Stop(context.Context) error { + m.mu.Lock() + defer m.mu.Unlock() + m.Stops++ + m.St.Running, m.St.Loaded = false, false + return nil +} + +// Uninstall implements service.Manager. +func (m *Manager) Uninstall(context.Context) error { + m.mu.Lock() + defer m.mu.Unlock() + m.St = service.Status{} + return nil +} + +// InstallCount returns how many times Install succeeded. +func (m *Manager) InstallCount() int { + m.mu.Lock() + defer m.mu.Unlock() + return len(m.Installs) +} + +// State is an in-memory private state. +type State struct { + mu sync.Mutex + Data map[string][]byte + Puts int + Gets int + PutErr error + GetErr error + Deleted []string +} + +// NewState returns an empty state. +func NewState() *State { return &State{Data: map[string][]byte{}} } + +// Get implements the private-state interface. +func (s *State) Get(_ context.Context, key string) ([]byte, bool, error) { + s.mu.Lock() + defer s.mu.Unlock() + s.Gets++ + if s.GetErr != nil { + return nil, false, s.GetErr + } + v, ok := s.Data[key] + return v, ok, nil +} + +// Put implements the private-state interface. +func (s *State) Put(_ context.Context, key string, data []byte) error { + s.mu.Lock() + defer s.mu.Unlock() + s.Puts++ + if s.PutErr != nil { + return s.PutErr + } + s.Data[key] = data + return nil +} + +// Delete implements the private-state interface. +func (s *State) Delete(_ context.Context, key string) error { + s.mu.Lock() + defer s.mu.Unlock() + s.Deleted = append(s.Deleted, key) + delete(s.Data, key) + return nil +} + +// FileOpener opens the real "file" store, and reports every other kind as unsupported, as a +// machine without that hardware would. +func FileOpener(kind, dir string) (keystore.Store, error) { + if kind == keystore.KindFile { + return keystore.NewFileStore(dir), nil + } + return nil, fmt.Errorf("%w: %s", keystore.ErrUnsupportedPlatform, kind) +} + +// RequirementOpener opens a "file" store that claims it can enforce "unlocked" and remembers the +// requirements each key was created with, as the Secure Enclave store does. The memory is shared +// by every store the opener returns. +func RequirementOpener() func(kind, dir string) (keystore.Store, error) { + reqs := &requirementMemory{m: map[string][]keystore.Requirement{}} + return func(kind, dir string) (keystore.Store, error) { + if kind != keystore.KindFile { + return nil, fmt.Errorf("%w: %s", keystore.ErrUnsupportedPlatform, kind) + } + return &requirementStore{Store: keystore.NewFileStore(dir), mem: reqs, dir: dir}, nil + } +} + +type requirementMemory struct { + mu sync.Mutex + m map[string][]keystore.Requirement +} + +type requirementStore struct { + keystore.Store + mem *requirementMemory + dir string +} + +func (s *requirementStore) Supports(keystore.Requirement) bool { return true } + +func (s *requirementStore) id(name string) string { return s.dir + "|" + name } + +func (s *requirementStore) Create(ctx context.Context, name string, reqs []keystore.Requirement) (keystore.Key, error) { + k, err := s.Store.Create(ctx, name, nil) + if err != nil { + return nil, err + } + s.mem.mu.Lock() + s.mem.m[s.id(name)] = keystore.Normalize(reqs) + s.mem.mu.Unlock() + return &requirementKey{Key: k, reqs: keystore.Normalize(reqs)}, nil +} + +func (s *requirementStore) Load(ctx context.Context, name string) (keystore.Key, error) { + k, err := s.Store.Load(ctx, name) + if err != nil { + return nil, err + } + s.mem.mu.Lock() + defer s.mem.mu.Unlock() + return &requirementKey{Key: k, reqs: s.mem.m[s.id(name)]}, nil +} + +func (s *requirementStore) List(ctx context.Context) ([]keystore.Info, error) { + infos, err := s.Store.List(ctx) + s.mem.mu.Lock() + defer s.mem.mu.Unlock() + for i := range infos { + infos[i].Requirements = s.mem.m[s.id(infos[i].Name)] + } + return infos, err +} + +type requirementKey struct { + keystore.Key + reqs []keystore.Requirement +} + +func (k *requirementKey) Requirements() []keystore.Requirement { return k.reqs } + +// LockedOpener opens a "file" store whose keys refuse to sign, the way the Secure Enclave does +// while the screen is locked (errSecInteractionNotAllowed). +func LockedOpener(kind, dir string) (keystore.Store, error) { + if kind != keystore.KindFile { + return nil, fmt.Errorf("%w: %s", keystore.ErrUnsupportedPlatform, kind) + } + return &lockedStore{Store: keystore.NewFileStore(dir)}, nil +} + +type lockedStore struct{ keystore.Store } + +func (s *lockedStore) Load(ctx context.Context, name string) (keystore.Key, error) { + k, err := s.Store.Load(ctx, name) + if err != nil { + return nil, err + } + return &lockedKey{Key: k}, nil +} + +type lockedKey struct{ keystore.Key } + +// ErrLocked is what a locked key returns when asked to sign. +var ErrLocked = &keystore.OSStatusError{Op: "sign", Code: keystore.CodeInteractionNotAllowed, Message: "interaction not allowed"} + +func (k *lockedKey) Sign(io.Reader, []byte, crypto.SignerOpts) ([]byte, error) { return nil, ErrLocked } + +// FailingLoad wraps a store so that Load fails with err. +func FailingLoad(inner keystore.Store, err error) keystore.Store { + return &failingLoad{Store: inner, err: err} +} + +type failingLoad struct { + keystore.Store + err error +} + +func (s *failingLoad) Load(context.Context, string) (keystore.Key, error) { return nil, s.err } + +// PublicKeyOf returns the public key of the named key in the store at dir. +func PublicKeyOf(t *testing.T, store keystore.Store, name string) ssh.PublicKey { + t.Helper() + k, err := store.Load(context.Background(), name) + if err != nil { + t.Fatal(err) + } + defer k.Close() + return k.SSHPublicKey() +} + +// ErrBoom is a generic failure for tests. +var ErrBoom = errors.New("boom") diff --git a/plugins/ssh/inventory/inventory.go b/plugins/ssh/inventory/inventory.go new file mode 100644 index 00000000000..ff805b3f45a --- /dev/null +++ b/plugins/ssh/inventory/inventory.go @@ -0,0 +1,56 @@ +// Package inventory lists the keys that exist on this machine across every key store. +package inventory + +import ( + "context" + "errors" + "fmt" + "sort" + + "github.com/cloudposse/atmos/plugins/ssh/agent" + "github.com/cloudposse/atmos/plugins/ssh/authority" + "github.com/cloudposse/atmos/plugins/ssh/keystore" + "github.com/cloudposse/atmos/plugins/ssh/paths" +) + +// List returns the keys of every registered store, ordered by store and name. A store that does +// not exist on this platform is skipped. A store that fails for another reason is reported in the +// returned error together with the keys of the stores that worked, so a caller that needs a +// complete picture can tell it does not have one. +func List(ctx context.Context, open agent.StoreOpener, p *paths.Paths) ([]keystore.Info, error) { + var keys []keystore.Info + var errs []error + for _, kind := range keystore.Kinds() { + store, err := open(kind, p.StoreDir(kind)) + if err == nil { + var infos []keystore.Info + infos, err = store.List(ctx) + keys = append(keys, infos...) + } + if err != nil && !errors.Is(err, keystore.ErrUnsupportedPlatform) { + errs = append(errs, fmt.Errorf("list %s keys: %w", kind, err)) + } + } + sort.SliceStable(keys, func(i, j int) bool { + if keys[i].Store != keys[j].Store { + return keys[i].Store < keys[j].Store + } + return keys[i].Name < keys[j].Name + }) + return keys, errors.Join(errs...) +} + +// Fingerprints returns the fingerprints of keys as a set. It returns nil, meaning unknown, when +// err is not nil, because a partial set would make a live key look gone. +func Fingerprints(keys []keystore.Info, err error) map[string]bool { + if err != nil { + return nil + } + set := make(map[string]bool, len(keys)) + for _, k := range keys { + if k.PublicKey != nil { + set[authority.Fingerprint(k.PublicKey)] = true + } + } + return set +} diff --git a/plugins/ssh/inventory/inventory_test.go b/plugins/ssh/inventory/inventory_test.go new file mode 100644 index 00000000000..c842f373d67 --- /dev/null +++ b/plugins/ssh/inventory/inventory_test.go @@ -0,0 +1,51 @@ +package inventory_test + +import ( + "context" + "errors" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/cloudposse/atmos/plugins/ssh/authority" + "github.com/cloudposse/atmos/plugins/ssh/internal/testfakes" + "github.com/cloudposse/atmos/plugins/ssh/inventory" + "github.com/cloudposse/atmos/plugins/ssh/keystore" +) + +func TestListSkipsStoresThatDoNotExistOnThisPlatform(t *testing.T) { + p := testfakes.Paths(t) + store := keystore.NewFileStore(p.StoreDir("file")) + for _, name := range []string{"b", "a"} { + _, err := store.Create(context.Background(), name, nil) + require.NoError(t, err) + } + + keys, err := inventory.List(context.Background(), testfakes.FileOpener, p) + + require.NoError(t, err) + require.Len(t, keys, 2) + assert.Equal(t, []string{"a", "b"}, []string{keys[0].Name, keys[1].Name}) + assert.Equal(t, map[string]bool{ + authority.Fingerprint(keys[0].PublicKey): true, authority.Fingerprint(keys[1].PublicKey): true, + }, inventory.Fingerprints(keys, nil)) +} + +func TestAStoreThatFailsMakesTheFingerprintSetUnknown(t *testing.T) { + p := testfakes.Paths(t) + _, err := keystore.NewFileStore(p.StoreDir("file")).Create(context.Background(), "a", nil) + require.NoError(t, err) + opener := func(kind, dir string) (keystore.Store, error) { + if kind == keystore.KindSecureEnclave { + return nil, errors.New("keychain is unavailable") + } + return testfakes.FileOpener(kind, dir) + } + + keys, err := inventory.List(context.Background(), opener, p) + + require.ErrorContains(t, err, "keychain is unavailable") + assert.Len(t, keys, 1, "the working store's keys are still returned") + assert.Nil(t, inventory.Fingerprints(keys, err), "a partial set would make a live key look gone") +} diff --git a/plugins/ssh/keystore/dirstore.go b/plugins/ssh/keystore/dirstore.go new file mode 100644 index 00000000000..450e9c5bdcb --- /dev/null +++ b/plugins/ssh/keystore/dirstore.go @@ -0,0 +1,217 @@ +package keystore + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "os" + "path/filepath" + "regexp" + "sort" + "strings" + "time" + + "golang.org/x/crypto/ssh" +) + +const ( + dirMode os.FileMode = 0o700 + fileMode os.FileMode = 0o600 + + keyExt = ".key" + metaExt = ".json" + + metaVersion = 1 + maxNameLen = 128 +) + +var nameRE = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9._-]*$`) + +// record is the sidecar metadata persisted beside each key. A Secure Enclave blob does not reveal +// which access class it was created with, so the requirements are recorded here. +type record struct { + Version int `json:"version"` + Name string `json:"name"` + Store string `json:"store"` + Requirements []Requirement `json:"requirements"` + Created time.Time `json:"created"` + PublicKey string `json:"public_key"` +} + +// dirStore holds the on-disk layout shared by the stores: .key (private material, mode 0600) +// and .json (sidecar metadata, mode 0600) inside a directory with mode 0700. +type dirStore struct { + kind string + dir string +} + +func validName(name string) error { + if len(name) > maxNameLen || !nameRE.MatchString(name) { + return fmt.Errorf("%w: %q", ErrInvalidName, name) + } + return nil +} + +func (d dirStore) keyPath(name string) string { return filepath.Join(d.dir, name+keyExt) } +func (d dirStore) metaPath(name string) string { return filepath.Join(d.dir, name+metaExt) } + +func (d dirStore) ensureDir() error { + if err := os.MkdirAll(d.dir, dirMode); err != nil { + return fmt.Errorf("create key directory: %w", err) + } + if err := os.Chmod(d.dir, dirMode); err != nil { + return fmt.Errorf("restrict key directory: %w", err) + } + return nil +} + +// writeNew stores material and its metadata, failing with ErrKeyExists if the name is taken. +func (d dirStore) writeNew(rec record, material []byte) error { + if err := d.ensureDir(); err != nil { + return err + } + meta, err := json.MarshalIndent(rec, "", " ") + if err != nil { + return fmt.Errorf("encode key metadata: %w", err) + } + if err := writeExclusive(d.keyPath(rec.Name), material); err != nil { + if errors.Is(err, os.ErrExist) { + return fmt.Errorf("%w: %q", ErrKeyExists, rec.Name) + } + return fmt.Errorf("write key: %w", err) + } + if err := writeExclusive(d.metaPath(rec.Name), meta); err != nil { + _ = os.Remove(d.keyPath(rec.Name)) + if errors.Is(err, os.ErrExist) { + return fmt.Errorf("%w: %q", ErrKeyExists, rec.Name) + } + return fmt.Errorf("write key metadata: %w", err) + } + return nil +} + +func writeExclusive(file string, data []byte) error { + f, err := os.OpenFile(file, os.O_WRONLY|os.O_CREATE|os.O_EXCL, fileMode) + if err != nil { + return err + } + if _, err := f.Write(data); err != nil { + _ = f.Close() + _ = os.Remove(file) + return err + } + if err := f.Close(); err != nil { + _ = os.Remove(file) + return err + } + return nil +} + +// read returns a key's private material and metadata. +func (d dirStore) read(name string) ([]byte, record, error) { + var rec record + if err := validName(name); err != nil { + return nil, rec, err + } + material, err := os.ReadFile(d.keyPath(name)) + if errors.Is(err, os.ErrNotExist) { + return nil, rec, fmt.Errorf("%w: %q", ErrKeyNotFound, name) + } + if err != nil { + return nil, rec, fmt.Errorf("read key: %w", err) + } + rec, err = d.readMeta(name) + if err != nil { + return nil, rec, err + } + return material, rec, nil +} + +func (d dirStore) readMeta(name string) (record, error) { + var rec record + data, err := os.ReadFile(d.metaPath(name)) + if err != nil { + return rec, fmt.Errorf("%w: %q has no readable metadata: %w", ErrInvalidKey, name, err) + } + if err := json.Unmarshal(data, &rec); err != nil { + return rec, fmt.Errorf("%w: %q metadata: %w", ErrInvalidKey, name, err) + } + if rec.Version != metaVersion || rec.Name != name || rec.Store != d.kind { + return rec, fmt.Errorf("%w: %q metadata does not describe a %s key named %q", ErrInvalidKey, name, d.kind, name) + } + return rec, nil +} + +func (d dirStore) remove(name string) error { + if err := validName(name); err != nil { + return err + } + err := os.Remove(d.keyPath(name)) + if errors.Is(err, os.ErrNotExist) { + return fmt.Errorf("%w: %q", ErrKeyNotFound, name) + } + if err != nil { + return fmt.Errorf("delete key: %w", err) + } + if err := os.Remove(d.metaPath(name)); err != nil && !errors.Is(err, os.ErrNotExist) { + return fmt.Errorf("delete key metadata: %w", err) + } + return nil +} + +func (d dirStore) list(ctx context.Context) ([]Info, error) { + if err := ctx.Err(); err != nil { + return nil, err + } + entries, err := os.ReadDir(d.dir) + if errors.Is(err, os.ErrNotExist) { + return nil, nil + } + if err != nil { + return nil, fmt.Errorf("list keys: %w", err) + } + var infos []Info + for _, e := range entries { + name, ok := strings.CutSuffix(e.Name(), metaExt) + if !ok || e.IsDir() || validName(name) != nil { + continue + } + rec, err := d.readMeta(name) + if err != nil { + return nil, err + } + info, err := rec.info() + if err != nil { + return nil, err + } + infos = append(infos, info) + } + sort.Slice(infos, func(i, j int) bool { return infos[i].Name < infos[j].Name }) + return infos, nil +} + +func newRecord(kind, name string, requirements []Requirement, pub ssh.PublicKey) record { + return record{ + Version: metaVersion, + Name: name, + Store: kind, + Requirements: requirements, + Created: time.Now().UTC(), + PublicKey: strings.TrimSpace(string(ssh.MarshalAuthorizedKey(pub))), + } +} + +func (r record) info() (Info, error) { + pub, _, _, _, err := ssh.ParseAuthorizedKey([]byte(r.PublicKey)) + if err != nil { + return Info{}, fmt.Errorf("%w: %q public key: %w", ErrInvalidKey, r.Name, err) + } + return Info{ + Name: r.Name, + Store: r.Store, + Requirements: Normalize(r.Requirements), + Created: r.Created, + PublicKey: pub, + }, nil +} diff --git a/plugins/ssh/keystore/file.go b/plugins/ssh/keystore/file.go new file mode 100644 index 00000000000..d4c935ff9b8 --- /dev/null +++ b/plugins/ssh/keystore/file.go @@ -0,0 +1,106 @@ +package keystore + +import ( + "context" + "crypto" + "crypto/ed25519" + "crypto/rand" + "encoding/pem" + "fmt" + + "golang.org/x/crypto/ssh" +) + +func init() { + Register(KindFile, func(dir string) (Store, error) { return NewFileStore(dir), nil }) +} + +// fileStore keeps each key as an ordinary, unencrypted OpenSSH ed25519 private key file. It is not +// hardware-protected and so cannot enforce any Requirement. +type fileStore struct { + dirStore +} + +// NewFileStore returns the "file" store rooted at dir. +func NewFileStore(dir string) Store { + return &fileStore{dirStore{kind: KindFile, dir: dir}} +} + +func (s *fileStore) Kind() string { return KindFile } + +// Supports is always false: a file cannot stop its reader from using it. +func (s *fileStore) Supports(Requirement) bool { return false } + +func (s *fileStore) Create(ctx context.Context, name string, requirements []Requirement) (Key, error) { + if err := ctx.Err(); err != nil { + return nil, err + } + if err := validName(name); err != nil { + return nil, err + } + reqs, err := Validate(s, requirements) + if err != nil { + return nil, err + } + pub, priv, err := ed25519.GenerateKey(rand.Reader) + if err != nil { + return nil, fmt.Errorf("generate ed25519 key: %w", err) + } + sshPub, err := ssh.NewPublicKey(pub) + if err != nil { + return nil, fmt.Errorf("encode public key: %w", err) + } + block, err := ssh.MarshalPrivateKey(crypto.PrivateKey(priv), name) + if err != nil { + return nil, fmt.Errorf("encode private key: %w", err) + } + rec := newRecord(KindFile, name, reqs, sshPub) + if err := s.writeNew(rec, pem.EncodeToMemory(block)); err != nil { + return nil, err + } + info, err := rec.info() + if err != nil { + return nil, err + } + return newStoredKey(fileHandle{priv}, info) +} + +func (s *fileStore) Load(ctx context.Context, name string) (Key, error) { + if err := ctx.Err(); err != nil { + return nil, err + } + material, rec, err := s.read(name) + if err != nil { + return nil, err + } + info, err := rec.info() + if err != nil { + return nil, err + } + raw, err := ssh.ParseRawPrivateKey(material) + if err != nil { + return nil, fmt.Errorf("%w: %q: %w", ErrInvalidKey, name, err) + } + priv, ok := raw.(*ed25519.PrivateKey) + if !ok { + return nil, fmt.Errorf("%w: %q is not an ed25519 key", ErrInvalidKey, name) + } + return newStoredKey(fileHandle{*priv}, info) +} + +func (s *fileStore) Delete(ctx context.Context, name string) error { + if err := ctx.Err(); err != nil { + return err + } + return s.remove(name) +} + +func (s *fileStore) List(ctx context.Context) ([]Info, error) { return s.list(ctx) } + +// fileHandle makes an ed25519 key satisfy handle. Releasing it is a no-op. +type fileHandle struct { + ed25519.PrivateKey +} + +func (h fileHandle) Public() crypto.PublicKey { return h.PrivateKey.Public() } +func (h fileHandle) Close() error { return nil } diff --git a/plugins/ssh/keystore/helpers_test.go b/plugins/ssh/keystore/helpers_test.go new file mode 100644 index 00000000000..61e6aa58840 --- /dev/null +++ b/plugins/ssh/keystore/helpers_test.go @@ -0,0 +1,17 @@ +package keystore + +import ( + "os" + "path/filepath" + "testing" +) + +func readFile(t *testing.T, dir, name string) ([]byte, error) { + t.Helper() + return os.ReadFile(filepath.Join(dir, name)) +} + +func writeFile(t *testing.T, dir, name string, data []byte) error { + t.Helper() + return os.WriteFile(filepath.Join(dir, name), data, 0o600) +} diff --git a/plugins/ssh/keystore/keystore.go b/plugins/ssh/keystore/keystore.go new file mode 100644 index 00000000000..dfdb84ca1a8 --- /dev/null +++ b/plugins/ssh/keystore/keystore.go @@ -0,0 +1,103 @@ +// Package keystore creates, stores, and loads the private keys behind Atmos SSH identities. +// +// A key store decides where private key material lives and which Requirement terms it can +// enforce. The "file" store keeps an ordinary OpenSSH key on disk. The "secure-enclave" store +// keeps a P-256 key inside Apple's Secure Enclave and persists only a wrapped blob that is useless +// without that machine's hardware. +package keystore + +import ( + "context" + "crypto" + "errors" + "io" + "time" + + "golang.org/x/crypto/ssh" +) + +// Requirement is a condition that must hold for a key to be used. The key store enforces it, not +// the caller. +type Requirement string + +const ( + // Unlocked requires the user's screen to be unlocked while the key is used. + Unlocked Requirement = "unlocked" +) + +// Key store kind names. +const ( + // KindFile is the kind name of the ordinary OpenSSH private key file store. + KindFile = "file" + // KindSecureEnclave is the kind name of the Apple Secure Enclave store. + KindSecureEnclave = "secure-enclave" +) + +// Sentinel errors. Wrap them with fmt.Errorf("%w ...") and test with errors.Is. +var ( + // ErrUnsupportedPlatform means the key store is not available on this operating system. + ErrUnsupportedPlatform = errors.New("key store is not supported on this platform") + // ErrUnsupportedRequirement means the key store cannot enforce a requirement. + ErrUnsupportedRequirement = errors.New("key store cannot enforce requirement") + // ErrKeyExists means a key with that name already exists. + ErrKeyExists = errors.New("key already exists") + // ErrKeyNotFound means no key with that name exists. + ErrKeyNotFound = errors.New("key not found") + // ErrRequirementMismatch means a key was created with different requirements than asked for. + ErrRequirementMismatch = errors.New("key requirements do not match") + // ErrUnknownKind means no key store is registered under that kind name. + ErrUnknownKind = errors.New("unknown key store kind") + // ErrInvalidName means a key name is empty or contains unsafe characters. + ErrInvalidName = errors.New("invalid key name") + // ErrInvalidKey means stored key material or its metadata is missing, corrupt, or inconsistent. + ErrInvalidKey = errors.New("invalid stored key") + // ErrInvalidDigest means a signing request did not carry a SHA-256 digest. + ErrInvalidDigest = errors.New("signing requires a SHA-256 digest") + // ErrKeyClosed means the key was used after Close. + ErrKeyClosed = errors.New("key is closed") +) + +// Info describes a stored key without touching its private material. +type Info struct { + // Name is the key name within its store. + Name string + // Store is the kind name of the store that holds the key. + Store string + // Requirements are the requirements the key was created with, sorted and de-duplicated. + Requirements []Requirement + // Created is when the key was created, in UTC. + Created time.Time + // PublicKey is the key's OpenSSH public key. + PublicKey ssh.PublicKey +} + +// Key is a private key that signs. Callers must Close it when done. +type Key interface { + crypto.Signer + io.Closer + // Name is the key name within its store. + Name() string + // SSHPublicKey is the key's OpenSSH public key. + SSHPublicKey() ssh.PublicKey + // Requirements are the requirements the key was created with. + Requirements() []Requirement + // Info returns the key's metadata. + Info() Info +} + +// Store creates and holds keys of one kind. +type Store interface { + // Kind is the name the store is registered under. + Kind() string + // Supports reports whether the store can enforce the requirement. + Supports(Requirement) bool + // Create generates a new key. It returns ErrKeyExists if the name is taken and + // ErrUnsupportedRequirement if the store cannot enforce a requirement. + Create(ctx context.Context, name string, requirements []Requirement) (Key, error) + // Load opens an existing key. It returns ErrKeyNotFound if there is none. + Load(ctx context.Context, name string) (Key, error) + // Delete removes a key. It returns ErrKeyNotFound if there is none. + Delete(ctx context.Context, name string) error + // List returns the metadata of every key in the store, sorted by name. + List(ctx context.Context) ([]Info, error) +} diff --git a/plugins/ssh/keystore/keystore_test.go b/plugins/ssh/keystore/keystore_test.go new file mode 100644 index 00000000000..5fbf4160513 --- /dev/null +++ b/plugins/ssh/keystore/keystore_test.go @@ -0,0 +1,268 @@ +package keystore + +import ( + "context" + "crypto" + "crypto/rand" + "crypto/sha256" + "errors" + "os" + "path/filepath" + "runtime" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "golang.org/x/crypto/ssh" +) + +// signAndVerify signs a message through the ssh.Signer wrapper and verifies it with the key's +// OpenSSH public key. +func signAndVerify(t *testing.T, key Key) { + t.Helper() + signer, err := ssh.NewSignerFromSigner(key) + require.NoError(t, err) + msg := []byte("keystore test message") + sig, err := signer.Sign(rand.Reader, msg) + require.NoError(t, err) + require.NoError(t, key.SSHPublicKey().Verify(msg, sig)) + assert.Equal(t, key.SSHPublicKey().Marshal(), signer.PublicKey().Marshal()) +} + +func TestFileStore_CreateLoadSign(t *testing.T) { + ctx := context.Background() + dir := filepath.Join(t.TempDir(), "keys") + store := NewFileStore(dir) + + created, err := store.Create(ctx, "ops", nil) + require.NoError(t, err) + defer created.Close() + assert.Equal(t, "ops", created.Name()) + assert.Empty(t, created.Requirements()) + assert.Equal(t, "ssh-ed25519", created.SSHPublicKey().Type()) + signAndVerify(t, created) + + loaded, err := store.Load(ctx, "ops") + require.NoError(t, err) + defer loaded.Close() + assert.Equal(t, created.SSHPublicKey().Marshal(), loaded.SSHPublicKey().Marshal()) + signAndVerify(t, loaded) + + // Raw digest-style signing is not what ed25519 does; it signs the message with Hash(0). + sig, err := loaded.Sign(rand.Reader, []byte("m"), crypto.Hash(0)) + require.NoError(t, err) + assert.NotEmpty(t, sig) +} + +func TestFileStore_Permissions(t *testing.T) { + if runtime.GOOS == "windows" { + t.Skip("POSIX file modes are not enforced on Windows.") + } + dir := filepath.Join(t.TempDir(), "keys") + _, err := NewFileStore(dir).Create(context.Background(), "ops", nil) + require.NoError(t, err) + + st, err := os.Stat(dir) + require.NoError(t, err) + assert.Equal(t, os.FileMode(0o700), st.Mode().Perm()) + for _, f := range []string{"ops.key", "ops.json"} { + st, err := os.Stat(filepath.Join(dir, f)) + require.NoError(t, err) + assert.Equal(t, os.FileMode(0o600), st.Mode().Perm(), f) + } +} + +func TestFileStore_RejectsUnlocked(t *testing.T) { + dir := t.TempDir() + store := NewFileStore(dir) + assert.False(t, store.Supports(Unlocked)) + + tests := []struct { + name string + reqs []Requirement + }{ + {"unlocked", []Requirement{Unlocked}}, + {"duplicated", []Requirement{Unlocked, Unlocked}}, + {"unknown", []Requirement{"biometry"}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + key, err := store.Create(context.Background(), "k", tt.reqs) + require.ErrorIs(t, err, ErrUnsupportedRequirement) + assert.Nil(t, key) + }) + } + entries, err := os.ReadDir(dir) + require.NoError(t, err) + assert.Empty(t, entries, "a rejected create must leave nothing on disk") +} + +func TestFileStore_Errors(t *testing.T) { + ctx := context.Background() + store := NewFileStore(t.TempDir()) + _, err := store.Create(ctx, "dup", nil) + require.NoError(t, err) + + tests := []struct { + name string + do func() error + want error + }{ + {"create twice", func() error { _, err := store.Create(ctx, "dup", nil); return err }, ErrKeyExists}, + {"load missing", func() error { _, err := store.Load(ctx, "none"); return err }, ErrKeyNotFound}, + {"delete missing", func() error { return store.Delete(ctx, "none") }, ErrKeyNotFound}, + {"empty name", func() error { _, err := store.Create(ctx, "", nil); return err }, ErrInvalidName}, + {"traversal", func() error { _, err := store.Load(ctx, "../etc/passwd"); return err }, ErrInvalidName}, + {"separator", func() error { return store.Delete(ctx, "a/b") }, ErrInvalidName}, + {"leading dot", func() error { _, err := store.Create(ctx, ".hidden", nil); return err }, ErrInvalidName}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + assert.ErrorIs(t, tt.do(), tt.want) + }) + } + + cancelled, cancel := context.WithCancel(ctx) + cancel() + _, err = store.Create(cancelled, "late", nil) + assert.ErrorIs(t, err, context.Canceled) +} + +func TestFileStore_ListAndDelete(t *testing.T) { + ctx := context.Background() + store := NewFileStore(filepath.Join(t.TempDir(), "absent")) + + infos, err := store.List(ctx) + require.NoError(t, err) + assert.Empty(t, infos) + + var pubs [2][]byte + for i, name := range []string{"zeta", "alpha"} { + key, err := store.Create(ctx, name, nil) + require.NoError(t, err) + pubs[i] = key.SSHPublicKey().Marshal() + require.NoError(t, key.Close()) + } + infos, err = store.List(ctx) + require.NoError(t, err) + require.Len(t, infos, 2) + assert.Equal(t, "alpha", infos[0].Name) + assert.Equal(t, "zeta", infos[1].Name) + assert.Equal(t, pubs[1], infos[0].PublicKey.Marshal()) + assert.Equal(t, pubs[0], infos[1].PublicKey.Marshal()) + assert.Equal(t, KindFile, infos[0].Store) + assert.False(t, infos[0].Created.IsZero()) + + require.NoError(t, store.Delete(ctx, "alpha")) + _, err = store.Load(ctx, "alpha") + require.ErrorIs(t, err, ErrKeyNotFound) + infos, err = store.List(ctx) + require.NoError(t, err) + require.Len(t, infos, 1) + assert.Equal(t, "zeta", infos[0].Name) +} + +func TestFileStore_CorruptStorage(t *testing.T) { + ctx := context.Background() + dir := t.TempDir() + store := NewFileStore(dir) + a, err := store.Create(ctx, "a", nil) + require.NoError(t, err) + b, err := store.Create(ctx, "b", nil) + require.NoError(t, err) + _ = a.Close() + _ = b.Close() + + t.Run("missing metadata", func(t *testing.T) { + require.NoError(t, os.Remove(filepath.Join(dir, "a.json"))) + _, err := store.Load(ctx, "a") + assert.ErrorIs(t, err, ErrInvalidKey) + }) + t.Run("metadata for a different key", func(t *testing.T) { + other, err := os.ReadFile(filepath.Join(dir, "b.json")) + require.NoError(t, err) + require.NoError(t, os.WriteFile(filepath.Join(dir, "a.json"), other, 0o600)) + _, err = store.Load(ctx, "a") + assert.ErrorIs(t, err, ErrInvalidKey) + }) + t.Run("garbage private key", func(t *testing.T) { + require.NoError(t, os.WriteFile(filepath.Join(dir, "b.key"), []byte("not a key"), 0o600)) + _, err := store.Load(ctx, "b") + assert.ErrorIs(t, err, ErrInvalidKey) + }) +} + +func TestRequirements(t *testing.T) { + assert.Equal(t, []Requirement{Unlocked}, Normalize([]Requirement{Unlocked, Unlocked})) + assert.Equal(t, []Requirement{"a", "b"}, Normalize([]Requirement{"b", "a", "b"})) + assert.Empty(t, Normalize(nil)) + + tests := []struct { + name string + have, want []Requirement + err bool + }{ + {"both empty", nil, nil, false}, + {"same", []Requirement{Unlocked}, []Requirement{Unlocked}, false}, + {"order and duplicates", []Requirement{"b", "a"}, []Requirement{"a", "b", "a"}, false}, + {"added", nil, []Requirement{Unlocked}, true}, + {"dropped", []Requirement{Unlocked}, nil, true}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + err := CheckRequirements(tt.have, tt.want) + if tt.err { + assert.ErrorIs(t, err, ErrRequirementMismatch) + return + } + assert.NoError(t, err) + }) + } +} + +func TestRegistry(t *testing.T) { + assert.Contains(t, Kinds(), KindFile) + assert.Contains(t, Kinds(), KindSecureEnclave) + + store, err := New(KindFile, t.TempDir()) + require.NoError(t, err) + assert.Equal(t, KindFile, store.Kind()) + + _, err = New("tpm-does-not-exist", t.TempDir()) + assert.ErrorIs(t, err, ErrUnknownKind) + + const custom = "registry-test-kind" + Register(custom, func(dir string) (Store, error) { return NewFileStore(dir), nil }) + got, err := New(custom, t.TempDir()) + require.NoError(t, err) + assert.NotNil(t, got) + assert.Panics(t, func() { Register(custom, func(string) (Store, error) { return nil, nil }) }) + assert.Panics(t, func() { Register("", func(string) (Store, error) { return nil, nil }) }) + assert.Panics(t, func() { Register("registry-nil", nil) }) +} + +func TestOSStatus(t *testing.T) { + locked := &OSStatusError{Op: "SecKeyCreateSignature", Code: -25308, Domain: "NSOSStatusErrorDomain", Message: "denied"} + wrapped := errors.Join(errors.New("sign"), locked) + + assert.True(t, IsInteractionNotAllowed(locked)) + assert.True(t, IsInteractionNotAllowed(wrapped)) + code, ok := OSStatus(wrapped) + assert.True(t, ok) + assert.Equal(t, CodeInteractionNotAllowed, code) + assert.Contains(t, locked.Error(), "-25308") + + assert.False(t, IsInteractionNotAllowed(&OSStatusError{Code: -25293})) + assert.False(t, IsInteractionNotAllowed(errors.New("other"))) + assert.False(t, IsInteractionNotAllowed(nil)) + _, ok = OSStatus(nil) + assert.False(t, ok) +} + +func TestCheckSHA256Digest(t *testing.T) { + good := sha256.Sum256([]byte("x")) + assert.NoError(t, checkSHA256Digest(good[:], crypto.SHA256)) + assert.NoError(t, checkSHA256Digest(good[:], nil)) + assert.ErrorIs(t, checkSHA256Digest(good[:], crypto.SHA512), ErrInvalidDigest) + assert.ErrorIs(t, checkSHA256Digest(good[:5], crypto.SHA256), ErrInvalidDigest) +} diff --git a/plugins/ssh/keystore/osstatus.go b/plugins/ssh/keystore/osstatus.go new file mode 100644 index 00000000000..e6be0ac9156 --- /dev/null +++ b/plugins/ssh/keystore/osstatus.go @@ -0,0 +1,43 @@ +package keystore + +import ( + "errors" + "fmt" +) + +// CodeInteractionNotAllowed is the OSStatus errSecInteractionNotAllowed. The Secure Enclave +// returns it when a key that requires an unlocked screen is used while the screen is locked. +const CodeInteractionNotAllowed = -25308 + +// OSStatusError is a Core Foundation error returned by Apple's Security framework. +type OSStatusError struct { + // Op names the Security framework call that failed. + Op string + // Code is the OSStatus (CFError code). + Code int + // Domain is the CFError domain. + Domain string + // Message is the CFError description. + Message string +} + +// Error implements error. +func (e *OSStatusError) Error() string { + return fmt.Sprintf("%s failed: OSStatus %d (%s): %s", e.Op, e.Code, e.Domain, e.Message) +} + +// OSStatus returns the OSStatus code carried by err, if any. +func OSStatus(err error) (int, bool) { + var se *OSStatusError + if errors.As(err, &se) { + return se.Code, true + } + return 0, false +} + +// IsInteractionNotAllowed reports whether err is the Secure Enclave refusing to sign because the +// screen is locked (errSecInteractionNotAllowed, -25308). +func IsInteractionNotAllowed(err error) bool { + code, ok := OSStatus(err) + return ok && code == CodeInteractionNotAllowed +} diff --git a/plugins/ssh/keystore/registry.go b/plugins/ssh/keystore/registry.go new file mode 100644 index 00000000000..4a10e5ce68a --- /dev/null +++ b/plugins/ssh/keystore/registry.go @@ -0,0 +1,52 @@ +package keystore + +import ( + "fmt" + "sort" + "sync" +) + +// Factory builds a Store whose key material lives in dir. The caller decides where dir is. +type Factory func(dir string) (Store, error) + +var ( + registryMu sync.RWMutex + registry = map[string]Factory{} +) + +// Register adds a key store factory under kind. It panics on an empty kind, a nil factory, or a +// duplicate kind, because those are programming errors caught at start-up. +func Register(kind string, factory Factory) { + if kind == "" || factory == nil { + panic("keystore: Register needs a kind and a factory") + } + registryMu.Lock() + defer registryMu.Unlock() + if _, dup := registry[kind]; dup { + panic(fmt.Sprintf("keystore: kind %q registered twice", kind)) + } + registry[kind] = factory +} + +// New builds the store registered under kind, keeping its key material in dir. +func New(kind, dir string) (Store, error) { + registryMu.RLock() + factory, ok := registry[kind] + registryMu.RUnlock() + if !ok { + return nil, fmt.Errorf("%w: %q", ErrUnknownKind, kind) + } + return factory(dir) +} + +// Kinds returns the registered kind names, sorted. +func Kinds() []string { + registryMu.RLock() + defer registryMu.RUnlock() + kinds := make([]string, 0, len(registry)) + for kind := range registry { + kinds = append(kinds, kind) + } + sort.Strings(kinds) + return kinds +} diff --git a/plugins/ssh/keystore/requirements.go b/plugins/ssh/keystore/requirements.go new file mode 100644 index 00000000000..18bd31c8145 --- /dev/null +++ b/plugins/ssh/keystore/requirements.go @@ -0,0 +1,46 @@ +package keystore + +import ( + "fmt" + "sort" +) + +// Normalize returns requirements sorted and de-duplicated. It does not validate the terms. +func Normalize(requirements []Requirement) []Requirement { + seen := make(map[Requirement]struct{}, len(requirements)) + out := make([]Requirement, 0, len(requirements)) + for _, r := range requirements { + if _, dup := seen[r]; dup { + continue + } + seen[r] = struct{}{} + out = append(out, r) + } + sort.Slice(out, func(i, j int) bool { return out[i] < out[j] }) + return out +} + +// Validate normalizes requirements and returns ErrUnsupportedRequirement, naming the term, when +// the store cannot enforce one of them. +func Validate(store Store, requirements []Requirement) ([]Requirement, error) { + out := Normalize(requirements) + for _, r := range out { + if !store.Supports(r) { + return nil, fmt.Errorf("%w %q: the %s store cannot enforce it", ErrUnsupportedRequirement, string(r), store.Kind()) + } + } + return out, nil +} + +// CheckRequirements returns ErrRequirementMismatch unless have and want hold the same terms. +func CheckRequirements(have, want []Requirement) error { + h, w := Normalize(have), Normalize(want) + equal := len(h) == len(w) + for i := 0; equal && i < len(h); i++ { + equal = h[i] == w[i] + } + if !equal { + return fmt.Errorf("%w: key has %v, want %v", ErrRequirementMismatch, h, w) + } + return nil +} diff --git a/plugins/ssh/keystore/secureenclave.go b/plugins/ssh/keystore/secureenclave.go new file mode 100644 index 00000000000..d11a41f7568 --- /dev/null +++ b/plugins/ssh/keystore/secureenclave.go @@ -0,0 +1,162 @@ +package keystore + +import ( + "context" + "crypto" + "fmt" + "sync" + + "golang.org/x/crypto/ssh" +) + +func init() { + Register(KindSecureEnclave, func(dir string) (Store, error) { return NewSecureEnclaveStore(dir), nil }) +} + +// seBackend is the platform half of the Secure Enclave store. Only darwin provides one. +type seBackend interface { + // generate creates an enclave key whose access class follows requirements and returns the + // wrapped blob that reloads it. + generate(requirements []Requirement) (blob []byte, h handle, err error) + // open reloads a key from its wrapped blob. + open(blob []byte) (handle, error) +} + +var ( + seBackendMu sync.RWMutex + seBackendFn seBackend // Set by the darwin build; nil elsewhere. +) + +func currentSEBackend() (seBackend, error) { + seBackendMu.RLock() + defer seBackendMu.RUnlock() + if seBackendFn == nil { + return nil, fmt.Errorf("%w: secure-enclave needs macOS", ErrUnsupportedPlatform) + } + return seBackendFn, nil +} + +// secureEnclaveStore keeps P-256 keys inside the Secure Enclave. Only a wrapped blob and a +// metadata sidecar touch the disk; nothing goes in the keychain. +type secureEnclaveStore struct { + dirStore +} + +// NewSecureEnclaveStore returns the "secure-enclave" store rooted at dir. On platforms other than +// macOS every operation returns ErrUnsupportedPlatform. +func NewSecureEnclaveStore(dir string) Store { + return &secureEnclaveStore{dirStore{kind: KindSecureEnclave, dir: dir}} +} + +func (s *secureEnclaveStore) Kind() string { return KindSecureEnclave } + +// Supports reports true for Unlocked, and only where the Secure Enclave is reachable. +func (s *secureEnclaveStore) Supports(r Requirement) bool { + if _, err := currentSEBackend(); err != nil { + return false + } + return r == Unlocked +} + +func (s *secureEnclaveStore) Create(ctx context.Context, name string, requirements []Requirement) (Key, error) { + if err := ctx.Err(); err != nil { + return nil, err + } + backend, err := currentSEBackend() + if err != nil { + return nil, err + } + if err := validName(name); err != nil { + return nil, err + } + reqs, err := Validate(s, requirements) + if err != nil { + return nil, err + } + blob, h, err := backend.generate(reqs) + if err != nil { + return nil, err + } + key, err := s.persist(name, reqs, blob, h) + if err != nil { + _ = h.Close() + return nil, err + } + return key, nil +} + +func (s *secureEnclaveStore) persist(name string, reqs []Requirement, blob []byte, h handle) (Key, error) { + pub, err := sshPublicKey(h.Public()) + if err != nil { + return nil, err + } + rec := newRecord(KindSecureEnclave, name, reqs, pub) + if err := s.writeNew(rec, blob); err != nil { + return nil, err + } + info, err := rec.info() + if err != nil { + return nil, err + } + return newStoredKey(h, info) +} + +func (s *secureEnclaveStore) Load(ctx context.Context, name string) (Key, error) { + if err := ctx.Err(); err != nil { + return nil, err + } + backend, err := currentSEBackend() + if err != nil { + return nil, err + } + blob, rec, err := s.read(name) + if err != nil { + return nil, err + } + info, err := rec.info() + if err != nil { + return nil, err + } + h, err := backend.open(blob) + if err != nil { + return nil, err + } + return newStoredKey(h, info) +} + +func (s *secureEnclaveStore) Delete(ctx context.Context, name string) error { + if err := ctx.Err(); err != nil { + return err + } + if _, err := currentSEBackend(); err != nil { + return err + } + return s.remove(name) +} + +func (s *secureEnclaveStore) List(ctx context.Context) ([]Info, error) { + if _, err := currentSEBackend(); err != nil { + return nil, err + } + return s.list(ctx) +} + +// checkSHA256Digest is shared by backends: it checks that a signing request carries a SHA-256 +// digest, which is what ecdsa-sha2-nistp256 signs. +func checkSHA256Digest(digest []byte, opts crypto.SignerOpts) error { + if opts != nil && opts.HashFunc() != crypto.SHA256 { + return fmt.Errorf("%w: got %v", ErrInvalidDigest, opts.HashFunc()) + } + if len(digest) != crypto.SHA256.Size() { + return fmt.Errorf("%w: got %d bytes", ErrInvalidDigest, len(digest)) + } + return nil +} + +func sshPublicKey(pub crypto.PublicKey) (ssh.PublicKey, error) { + k, err := ssh.NewPublicKey(pub) + if err != nil { + return nil, fmt.Errorf("%w: public key: %w", ErrInvalidKey, err) + } + return k, nil +} diff --git a/plugins/ssh/keystore/secureenclave_darwin.go b/plugins/ssh/keystore/secureenclave_darwin.go new file mode 100644 index 00000000000..57478e85942 --- /dev/null +++ b/plugins/ssh/keystore/secureenclave_darwin.go @@ -0,0 +1,177 @@ +//go:build darwin + +package keystore + +import ( + "crypto" + "crypto/ecdsa" + "crypto/elliptic" + "fmt" + "io" + "sync" + "unsafe" +) + +func init() { + seBackendMu.Lock() + defer seBackendMu.Unlock() + seBackendFn = darwinBackend{} +} + +// darwinBackend drives the Secure Enclave through Security.framework's C API, called with purego +// so the binary builds with CGO_ENABLED=0 and no Swift. +type darwinBackend struct{} + +func (darwinBackend) generate(requirements []Requirement) ([]byte, handle, error) { + api, err := loadAPI() + if err != nil { + return nil, nil, err + } + var rel releaser + rel.api = api + defer rel.release() + + // Without a requirement the key stays usable while the screen is locked; "unlocked" ties it to + // an unlocked device. Only private-key usage is required: no biometry and no user presence. + protection := api.accessibleAfterFirst + for _, r := range requirements { + if r == Unlocked { + protection = api.accessibleWhenUnlocked + } + } + var cfErr uintptr + ac := rel.add(api.accessControlCreate(0, protection, accessPrivateKeyUsage, unsafe.Pointer(&cfErr))) + if ac == 0 { + return nil, nil, api.toError("SecAccessControlCreateWithFlags", cfErr) + } + privAttrs := rel.add(api.dict(api.attrIsPermanent, api.cfFalse, api.attrAccessControl, ac)) + bits := rel.add(api.number(256)) + params := rel.add(api.dict( + api.attrKeyType, api.attrKeyTypeECSECPrime, + api.attrKeySizeInBits, bits, + api.attrTokenID, api.attrTokenIDSecureEnclave, + api.privateKeyAttrs, privAttrs, + )) + cfErr = 0 + ref := api.keyCreateRandom(params, unsafe.Pointer(&cfErr)) + if ref == 0 { + return nil, nil, api.toError("SecKeyCreateRandomKey", cfErr) + } + k, err := newSEKey(api, ref) + if err != nil { + api.cfRelease(ref) + return nil, nil, err + } + attrs := rel.add(api.keyCopyAttributes(ref)) + blobRef := api.cfDictionaryGet(attrs, api.tokenOIDKey) // Get rule: owned by attrs. + if blobRef == 0 { + _ = k.Close() + return nil, nil, fmt.Errorf("%w: Secure Enclave key has no token object ID", ErrInvalidKey) + } + return api.bytesOf(blobRef), k, nil +} + +func (darwinBackend) open(blob []byte) (handle, error) { + api, err := loadAPI() + if err != nil { + return nil, err + } + return openSEKey(api, blob) +} + +// openSEKey reloads a Secure Enclave key from its wrapped blob. Blobs made by CryptoKit's +// SecureEnclave.P256 dataRepresentation load unchanged. +func openSEKey(api *secAPI, blob []byte) (*seKey, error) { + var rel releaser + rel.api = api + defer rel.release() + + empty := rel.add(api.data(nil)) + blobData := rel.add(api.data(blob)) + attrs := rel.add(api.dict( + api.attrKeyType, api.attrKeyTypeECSECPrime, + api.attrKeyClass, api.attrKeyClassPrivate, + api.attrTokenID, api.attrTokenIDSecureEnclave, + api.tokenOIDKey, blobData, + )) + var cfErr uintptr + ref := api.keyCreateWithData(empty, attrs, unsafe.Pointer(&cfErr)) + if ref == 0 { + return nil, api.toError("SecKeyCreateWithData", cfErr) + } + k, err := newSEKey(api, ref) + if err != nil { + api.cfRelease(ref) + return nil, err + } + return k, nil +} + +// seKey is a live Secure Enclave key. It satisfies handle. +type seKey struct { + api *secAPI + pub *ecdsa.PublicKey + mu sync.RWMutex + ref uintptr + closed bool +} + +// newSEKey wraps ref, reading its public key. On success it owns ref; on error the caller keeps it. +func newSEKey(api *secAPI, ref uintptr) (*seKey, error) { + var rel releaser + rel.api = api + defer rel.release() + + pubRef := rel.add(api.keyCopyPublicKey(ref)) + if pubRef == 0 { + return nil, fmt.Errorf("%w: SecKeyCopyPublicKey returned no key", ErrInvalidKey) + } + var cfErr uintptr + repr := rel.add(api.keyCopyExternalRep(pubRef, unsafe.Pointer(&cfErr))) + if repr == 0 { + return nil, api.toError("SecKeyCopyExternalRepresentation", cfErr) + } + pub, err := ecdsa.ParseUncompressedPublicKey(elliptic.P256(), api.bytesOf(repr)) + if err != nil { + return nil, fmt.Errorf("%w: parse Secure Enclave public key: %w", ErrInvalidKey, err) + } + return &seKey{api: api, ref: ref, pub: pub}, nil +} + +func (k *seKey) Public() crypto.PublicKey { return k.pub } + +// Sign signs a SHA-256 digest with the enclave key and returns an ASN.1 DER ECDSA signature. A +// locked screen on a key that requires "unlocked" surfaces as an *OSStatusError for which +// IsInteractionNotAllowed is true. +func (k *seKey) Sign(_ io.Reader, digest []byte, opts crypto.SignerOpts) ([]byte, error) { + if err := checkSHA256Digest(digest, opts); err != nil { + return nil, err + } + k.mu.RLock() + defer k.mu.RUnlock() + if k.closed { + return nil, ErrKeyClosed + } + var rel releaser + rel.api = k.api + defer rel.release() + + data := rel.add(k.api.data(digest)) + var cfErr uintptr + sig := rel.add(k.api.keyCreateSignature(k.ref, k.api.algECDSADigestSHA256, data, unsafe.Pointer(&cfErr))) + if sig == 0 { + return nil, k.api.toError("SecKeyCreateSignature", cfErr) + } + return k.api.bytesOf(sig), nil +} + +// Close releases the key reference. It is safe to call more than once. +func (k *seKey) Close() error { + k.mu.Lock() + defer k.mu.Unlock() + if !k.closed { + k.closed = true + k.api.cfRelease(k.ref) + } + return nil +} diff --git a/plugins/ssh/keystore/secureenclave_darwin_api.go b/plugins/ssh/keystore/secureenclave_darwin_api.go new file mode 100644 index 00000000000..d08b10c2155 --- /dev/null +++ b/plugins/ssh/keystore/secureenclave_darwin_api.go @@ -0,0 +1,287 @@ +//go:build darwin + +package keystore + +import ( + "fmt" + "sync" + "unsafe" + + "github.com/ebitengine/purego" +) + +// Core Foundation and Security framework constants used below. +const ( + securityPath = "/System/Library/Frameworks/Security.framework/Security" + coreFoundationPath = "/System/Library/Frameworks/CoreFoundation.framework/CoreFoundation" + + cfStringEncodingUTF8 = 0x08000100 + cfNumberSInt32Type = 3 + accessPrivateKeyUsage = 1 << 30 // kSecAccessControlPrivateKeyUsage. + errorBufferSize = 1024 +) + +// secAPI holds the bound C functions and the CFTypeRef values of the constants. kSec... and kCF... +// constants are data symbols: Dlsym returns the address of the variable, which is dereferenced to +// get the CFTypeRef. +type secAPI struct { + // Core Foundation functions. + cfRelease func(ref uintptr) + cfDictionaryCreate func(alloc uintptr, keys, values unsafe.Pointer, n int, keyCB, valueCB uintptr) uintptr + cfDictionaryGet func(dict, key uintptr) uintptr + cfDataCreate func(alloc uintptr, bytes unsafe.Pointer, length int) uintptr + cfDataGetLength func(data uintptr) int + cfDataGetBytePtr func(data uintptr) uintptr + cfNumberCreate func(alloc uintptr, kind int, value unsafe.Pointer) uintptr + cfStringCreate func(alloc uintptr, cstr string, encoding uint32) uintptr + cfStringGetCString func(str uintptr, buf unsafe.Pointer, size int, encoding uint32) bool + cfErrorGetCode func(err uintptr) int + cfErrorGetDomain func(err uintptr) uintptr + cfErrorCopyDesc func(err uintptr) uintptr + + // Security functions. + accessControlCreate func(alloc, protection uintptr, flags uint, err unsafe.Pointer) uintptr + keyCreateRandom func(params uintptr, err unsafe.Pointer) uintptr + keyCopyAttributes func(key uintptr) uintptr + keyCreateWithData func(data, attrs uintptr, err unsafe.Pointer) uintptr + keyCopyPublicKey func(key uintptr) uintptr + keyCopyExternalRep func(key uintptr, err unsafe.Pointer) uintptr + keyCreateSignature func(key, algorithm, data uintptr, err unsafe.Pointer) uintptr + + // Callback structs (addresses, passed as is). + dictKeyCallbacks uintptr + dictValueCallbacks uintptr + + // Constants (dereferenced CFTypeRefs). + cfFalse uintptr + attrKeyType uintptr + attrKeyTypeECSECPrime uintptr + attrKeySizeInBits uintptr + attrTokenID uintptr + attrTokenIDSecureEnclave uintptr + privateKeyAttrs uintptr + attrIsPermanent uintptr + attrAccessControl uintptr + attrKeyClass uintptr + attrKeyClassPrivate uintptr + accessibleAfterFirst uintptr + accessibleWhenUnlocked uintptr + algECDSADigestSHA256 uintptr + tokenOIDKey uintptr // The CFString "toid" (kSecAttrTokenOID). +} + +var ( + apiOnce sync.Once + apiInst *secAPI + apiErr error +) + +// loadAPI loads the frameworks once and binds every symbol the backend uses. +func loadAPI() (*secAPI, error) { + apiOnce.Do(func() { + apiInst, apiErr = bindAPI() + }) + return apiInst, apiErr +} + +type binder struct { + lib uintptr + err error +} + +func (b *binder) fn(fptr any, name string) { + if b.err != nil { + return + } + addr, err := purego.Dlsym(b.lib, name) + if err != nil { + b.err = fmt.Errorf("resolve %s: %w", name, err) + return + } + purego.RegisterFunc(fptr, addr) +} + +// addr returns the address of a data symbol. +func (b *binder) addr(name string) uintptr { + if b.err != nil { + return 0 + } + a, err := purego.Dlsym(b.lib, name) + if err != nil { + b.err = fmt.Errorf("resolve %s: %w", name, err) + } + return a +} + +// value returns the CFTypeRef stored in a data symbol. +func (b *binder) value(name string) uintptr { + a := b.addr(name) + if a == 0 { + return 0 + } + return *(*uintptr)(addrToPointer(a)) +} + +// addrToPointer converts a raw address from Dlsym or a C call into an unsafe.Pointer without the +// uintptr-to-Pointer conversion that go vet rejects. The memory belongs to C, not the Go heap. +func addrToPointer(a uintptr) unsafe.Pointer { + return *(*unsafe.Pointer)(unsafe.Pointer(&a)) +} + +func bindAPI() (*secAPI, error) { + cf, err := purego.Dlopen(coreFoundationPath, purego.RTLD_NOW|purego.RTLD_GLOBAL) + if err != nil { + return nil, fmt.Errorf("%w: load CoreFoundation: %w", ErrUnsupportedPlatform, err) + } + sec, err := purego.Dlopen(securityPath, purego.RTLD_NOW|purego.RTLD_GLOBAL) + if err != nil { + return nil, fmt.Errorf("%w: load Security: %w", ErrUnsupportedPlatform, err) + } + a := &secAPI{} + c := &binder{lib: cf} + c.fn(&a.cfRelease, "CFRelease") + c.fn(&a.cfDictionaryCreate, "CFDictionaryCreate") + c.fn(&a.cfDictionaryGet, "CFDictionaryGetValue") + c.fn(&a.cfDataCreate, "CFDataCreate") + c.fn(&a.cfDataGetLength, "CFDataGetLength") + c.fn(&a.cfDataGetBytePtr, "CFDataGetBytePtr") + c.fn(&a.cfNumberCreate, "CFNumberCreate") + c.fn(&a.cfStringCreate, "CFStringCreateWithCString") + c.fn(&a.cfStringGetCString, "CFStringGetCString") + c.fn(&a.cfErrorGetCode, "CFErrorGetCode") + c.fn(&a.cfErrorGetDomain, "CFErrorGetDomain") + c.fn(&a.cfErrorCopyDesc, "CFErrorCopyDescription") + a.dictKeyCallbacks = c.addr("kCFTypeDictionaryKeyCallBacks") + a.dictValueCallbacks = c.addr("kCFTypeDictionaryValueCallBacks") + a.cfFalse = c.value("kCFBooleanFalse") + if c.err != nil { + return nil, fmt.Errorf("%w: %w", ErrUnsupportedPlatform, c.err) + } + + s := &binder{lib: sec} + s.fn(&a.accessControlCreate, "SecAccessControlCreateWithFlags") + s.fn(&a.keyCreateRandom, "SecKeyCreateRandomKey") + s.fn(&a.keyCopyAttributes, "SecKeyCopyAttributes") + s.fn(&a.keyCreateWithData, "SecKeyCreateWithData") + s.fn(&a.keyCopyPublicKey, "SecKeyCopyPublicKey") + s.fn(&a.keyCopyExternalRep, "SecKeyCopyExternalRepresentation") + s.fn(&a.keyCreateSignature, "SecKeyCreateSignature") + a.attrKeyType = s.value("kSecAttrKeyType") + a.attrKeyTypeECSECPrime = s.value("kSecAttrKeyTypeECSECPrimeRandom") + a.attrKeySizeInBits = s.value("kSecAttrKeySizeInBits") + a.attrTokenID = s.value("kSecAttrTokenID") + a.attrTokenIDSecureEnclave = s.value("kSecAttrTokenIDSecureEnclave") + a.privateKeyAttrs = s.value("kSecPrivateKeyAttrs") + a.attrIsPermanent = s.value("kSecAttrIsPermanent") + a.attrAccessControl = s.value("kSecAttrAccessControl") + a.attrKeyClass = s.value("kSecAttrKeyClass") + a.attrKeyClassPrivate = s.value("kSecAttrKeyClassPrivate") + a.accessibleAfterFirst = s.value("kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly") + a.accessibleWhenUnlocked = s.value("kSecAttrAccessibleWhenUnlockedThisDeviceOnly") + a.algECDSADigestSHA256 = s.value("kSecKeyAlgorithmECDSASignatureDigestX962SHA256") + if s.err != nil { + return nil, fmt.Errorf("%w: %w", ErrUnsupportedPlatform, s.err) + } + // kSecAttrTokenOID is not exported as a constant on every SDK; its value is the string "toid". + a.tokenOIDKey = a.cfStringCreate(0, "toid", cfStringEncodingUTF8) + return a, nil +} + +// releaser collects CF objects to release together. +type releaser struct { + api *secAPI + refs []uintptr +} + +func (r *releaser) add(ref uintptr) uintptr { + if ref != 0 { + r.refs = append(r.refs, ref) + } + return ref +} + +func (r *releaser) release() { + for i := len(r.refs) - 1; i >= 0; i-- { + r.api.cfRelease(r.refs[i]) + } + r.refs = nil +} + +// dict builds an immutable CFDictionary from alternating key and value refs. The caller releases it. +func (a *secAPI) dict(pairs ...uintptr) uintptr { + n := len(pairs) / 2 + keys := make([]uintptr, n) + values := make([]uintptr, n) + for i := 0; i < n; i++ { + keys[i], values[i] = pairs[2*i], pairs[2*i+1] + } + d := a.cfDictionaryCreate(0, unsafe.Pointer(&keys[0]), unsafe.Pointer(&values[0]), n, a.dictKeyCallbacks, a.dictValueCallbacks) + keepAlive(keys, values) + return d +} + +//go:noinline +func keepAlive(...any) {} + +// data copies b into a new CFData. The caller releases it. +func (a *secAPI) data(b []byte) uintptr { + if len(b) == 0 { + return a.cfDataCreate(0, nil, 0) + } + d := a.cfDataCreate(0, unsafe.Pointer(&b[0]), len(b)) + keepAlive(b) + return d +} + +// number makes a CFNumber holding a 32-bit integer. The caller releases it. +func (a *secAPI) number(v int32) uintptr { + n := v + r := a.cfNumberCreate(0, cfNumberSInt32Type, unsafe.Pointer(&n)) + keepAlive(&n) + return r +} + +// bytesOf copies the contents of a CFData into Go memory. +func (a *secAPI) bytesOf(data uintptr) []byte { + n := a.cfDataGetLength(data) + if n == 0 { + return nil + } + p := addrToPointer(a.cfDataGetBytePtr(data)) + return append([]byte(nil), unsafe.Slice((*byte)(p), n)...) +} + +func (a *secAPI) goString(str uintptr) string { + if str == 0 { + return "" + } + buf := make([]byte, errorBufferSize) + if !a.cfStringGetCString(str, unsafe.Pointer(&buf[0]), len(buf), cfStringEncodingUTF8) { + return "" + } + for i, c := range buf { + if c == 0 { + return string(buf[:i]) + } + } + return string(buf) +} + +// toError converts a CFError into an *OSStatusError that keeps the code, and releases it. +func (a *secAPI) toError(op string, cfErr uintptr) error { + if cfErr == 0 { + return &OSStatusError{Op: op, Message: "unknown error"} + } + desc := a.cfErrorCopyDesc(cfErr) + defer a.cfRelease(cfErr) + if desc != 0 { + defer a.cfRelease(desc) + } + // The domain is a get-rule reference owned by the error, so it is not released. + return &OSStatusError{ + Op: op, + Code: a.cfErrorGetCode(cfErr), + Domain: a.goString(a.cfErrorGetDomain(cfErr)), + Message: a.goString(desc), + } +} diff --git a/plugins/ssh/keystore/secureenclave_darwin_test.go b/plugins/ssh/keystore/secureenclave_darwin_test.go new file mode 100644 index 00000000000..70c4d23529b --- /dev/null +++ b/plugins/ssh/keystore/secureenclave_darwin_test.go @@ -0,0 +1,125 @@ +//go:build darwin + +package keystore + +import ( + "context" + "crypto" + "crypto/ecdsa" + "crypto/rand" + "crypto/sha256" + "os" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "golang.org/x/crypto/ssh" +) + +const ( + hardwareEnv = "ATMOS_SSH_TEST_SECURE_ENCLAVE" + // pocBlob is a Secure Enclave blob made by CryptoKit in the proof of concept. It is only read. + pocBlob = "/Users/erik/se-agent-poc/keys/afu.key" +) + +func requireHardware(t *testing.T) { + t.Helper() + if os.Getenv(hardwareEnv) != "1" { + t.Skipf("set %s=1 to run against the Secure Enclave", hardwareEnv) + } +} + +func TestSecureEnclave_Hardware(t *testing.T) { + requireHardware(t) + ctx := context.Background() + store := NewSecureEnclaveStore(t.TempDir()) + require.True(t, store.Supports(Unlocked)) + + tests := []struct { + name string + reqs []Requirement + want []Requirement + }{ + {"none", nil, []Requirement{}}, + {"unlocked", []Requirement{Unlocked}, []Requirement{Unlocked}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + key, err := store.Create(ctx, tt.name, tt.reqs) + require.NoError(t, err) + defer key.Close() + assert.Equal(t, "ecdsa-sha2-nistp256", key.SSHPublicKey().Type()) + assert.ElementsMatch(t, tt.want, key.Requirements()) + signAndVerify(t, key) + + loaded, err := store.Load(ctx, tt.name) + require.NoError(t, err) + defer loaded.Close() + assert.Equal(t, key.SSHPublicKey().Marshal(), loaded.SSHPublicKey().Marshal()) + assert.ElementsMatch(t, tt.want, loaded.Requirements()) + signAndVerify(t, loaded) + }) + } + + infos, err := store.List(ctx) + require.NoError(t, err) + require.Len(t, infos, 2) + require.NoError(t, store.Delete(ctx, "none")) + _, err = store.Load(ctx, "none") + assert.ErrorIs(t, err, ErrKeyNotFound) + + t.Run("closed key refuses to sign", func(t *testing.T) { + key, err := store.Load(ctx, "unlocked") + require.NoError(t, err) + require.NoError(t, key.Close()) + require.NoError(t, key.Close()) + digest := sha256.Sum256([]byte("x")) + _, err = key.Sign(rand.Reader, digest[:], crypto.SHA256) + assert.ErrorIs(t, err, ErrKeyClosed) + }) +} + +// TestSecureEnclave_LoadsCryptoKitBlob proves keys made by the CryptoKit proof of concept load and +// sign through the C API. The blob is read, never modified. +func TestSecureEnclave_LoadsCryptoKitBlob(t *testing.T) { + requireHardware(t) + blob, err := os.ReadFile(pocBlob) + if os.IsNotExist(err) { + t.Skipf("no proof-of-concept blob at %s", pocBlob) + } + require.NoError(t, err) + + api, err := loadAPI() + require.NoError(t, err) + key, err := openSEKey(api, blob) + require.NoError(t, err) + defer key.Close() + + pub, ok := key.Public().(*ecdsa.PublicKey) + require.True(t, ok) + sshPub, err := ssh.NewPublicKey(pub) + require.NoError(t, err) + + signer, err := ssh.NewSignerFromSigner(key) + require.NoError(t, err) + msg := []byte("cryptokit compatibility") + sig, err := signer.Sign(rand.Reader, msg) + require.NoError(t, err) + require.NoError(t, sshPub.Verify(msg, sig)) + + // A second open of the same blob yields the same key. + again, err := openSEKey(api, blob) + require.NoError(t, err) + defer again.Close() + assert.True(t, pub.Equal(again.Public())) +} + +func TestSecureEnclave_BadBlob(t *testing.T) { + requireHardware(t) + api, err := loadAPI() + require.NoError(t, err) + _, err = openSEKey(api, []byte("not a Secure Enclave blob")) + require.Error(t, err) + _, isStatus := OSStatus(err) + assert.True(t, isStatus, "failure should carry an OSStatus: %v", err) +} diff --git a/plugins/ssh/keystore/secureenclave_other.go b/plugins/ssh/keystore/secureenclave_other.go new file mode 100644 index 00000000000..d314dfaec76 --- /dev/null +++ b/plugins/ssh/keystore/secureenclave_other.go @@ -0,0 +1,6 @@ +//go:build !darwin + +package keystore + +// No Secure Enclave backend exists off macOS. seBackendFn stays nil, so the secure-enclave store +// registers but every operation returns ErrUnsupportedPlatform. diff --git a/plugins/ssh/keystore/secureenclave_test.go b/plugins/ssh/keystore/secureenclave_test.go new file mode 100644 index 00000000000..b0558aed811 --- /dev/null +++ b/plugins/ssh/keystore/secureenclave_test.go @@ -0,0 +1,183 @@ +package keystore + +import ( + "context" + "crypto" + "crypto/ecdsa" + "crypto/elliptic" + "crypto/rand" + "crypto/sha256" + "crypto/x509" + "errors" + "io" + "runtime" + "sync" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// fakeBackend is an in-memory stand-in for the Secure Enclave so the store logic runs everywhere. +type fakeBackend struct { + generated [][]Requirement + signErr error +} + +type fakeHandle struct { + key *ecdsa.PrivateKey + signErr error + once sync.Once + closed bool +} + +func (f *fakeBackend) generate(reqs []Requirement) ([]byte, handle, error) { + f.generated = append(f.generated, reqs) + key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) + if err != nil { + return nil, nil, err + } + blob, err := x509.MarshalECPrivateKey(key) + if err != nil { + return nil, nil, err + } + return blob, &fakeHandle{key: key, signErr: f.signErr}, nil +} + +func (f *fakeBackend) open(blob []byte) (handle, error) { + key, err := x509.ParseECPrivateKey(blob) + if err != nil { + return nil, err + } + return &fakeHandle{key: key, signErr: f.signErr}, nil +} + +func (h *fakeHandle) Public() crypto.PublicKey { return h.key.Public() } +func (h *fakeHandle) Close() error { h.once.Do(func() { h.closed = true }); return nil } +func (h *fakeHandle) Sign(r io.Reader, digest []byte, opts crypto.SignerOpts) ([]byte, error) { + if h.signErr != nil { + return nil, h.signErr + } + if err := checkSHA256Digest(digest, opts); err != nil { + return nil, err + } + return h.key.Sign(r, digest, opts) +} + +func useFakeBackend(t *testing.T, fb *fakeBackend) { + t.Helper() + seBackendMu.Lock() + prev := seBackendFn + seBackendFn = fb + seBackendMu.Unlock() + t.Cleanup(func() { + seBackendMu.Lock() + seBackendFn = prev + seBackendMu.Unlock() + }) +} + +func TestSecureEnclaveStore_WithFakeBackend(t *testing.T) { + ctx := context.Background() + fb := &fakeBackend{} + useFakeBackend(t, fb) + store := NewSecureEnclaveStore(t.TempDir()) + + assert.Equal(t, KindSecureEnclave, store.Kind()) + assert.True(t, store.Supports(Unlocked)) + assert.False(t, store.Supports("biometry")) + + tests := []struct { + name string + reqs []Requirement + want []Requirement + }{ + {"plain", nil, []Requirement{}}, + {"unlocked", []Requirement{Unlocked}, []Requirement{Unlocked}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + key, err := store.Create(ctx, tt.name+"-key", tt.reqs) + require.NoError(t, err) + defer key.Close() + assert.Equal(t, "ecdsa-sha2-nistp256", key.SSHPublicKey().Type()) + assert.ElementsMatch(t, tt.want, key.Requirements()) + signAndVerify(t, key) + + // The sidecar, not the blob, tells how the key was created. + loaded, err := store.Load(ctx, tt.name+"-key") + require.NoError(t, err) + defer loaded.Close() + assert.ElementsMatch(t, tt.want, loaded.Requirements()) + assert.NoError(t, CheckRequirements(loaded.Requirements(), tt.reqs)) + signAndVerify(t, loaded) + }) + } + require.Len(t, fb.generated, 2) + assert.Empty(t, fb.generated[0]) + assert.Equal(t, []Requirement{Unlocked}, fb.generated[1]) + + infos, err := store.List(ctx) + require.NoError(t, err) + require.Len(t, infos, 2) + assert.Equal(t, "plain-key", infos[0].Name) + assert.Equal(t, []Requirement{Unlocked}, infos[1].Requirements) + + require.ErrorIs(t, func() error { _, err := store.Create(ctx, "unlocked-key", nil); return err }(), ErrKeyExists) + require.ErrorIs(t, func() error { _, err := store.Create(ctx, "bad", []Requirement{"biometry"}); return err }(), ErrUnsupportedRequirement) + require.NoError(t, store.Delete(ctx, "unlocked-key")) + require.ErrorIs(t, store.Delete(ctx, "unlocked-key"), ErrKeyNotFound) +} + +func TestSecureEnclaveStore_LockedErrorSurfaces(t *testing.T) { + locked := &OSStatusError{Op: "SecKeyCreateSignature", Code: CodeInteractionNotAllowed} + useFakeBackend(t, &fakeBackend{}) + store := NewSecureEnclaveStore(t.TempDir()) + key, err := store.Create(context.Background(), "k", []Requirement{Unlocked}) + require.NoError(t, err) + defer key.Close() + key.(*storedKey).handle.(*fakeHandle).signErr = locked + + digest := sha256.Sum256([]byte("x")) + _, err = key.Sign(rand.Reader, digest[:], crypto.SHA256) + require.Error(t, err) + assert.True(t, IsInteractionNotAllowed(err)) +} + +func TestSecureEnclaveStore_DetectsSwappedMetadata(t *testing.T) { + ctx := context.Background() + useFakeBackend(t, &fakeBackend{}) + dir := t.TempDir() + store := NewSecureEnclaveStore(dir) + a, err := store.Create(ctx, "a", nil) + require.NoError(t, err) + b, err := store.Create(ctx, "b", nil) + require.NoError(t, err) + _ = a.Close() + _ = b.Close() + + // Point a's metadata at b's public key by copying b's blob over a's. + blobB, err := readFile(t, dir, "b.key") + require.NoError(t, err) + require.NoError(t, writeFile(t, dir, "a.key", blobB)) + _, err = store.Load(ctx, "a") + assert.ErrorIs(t, err, ErrInvalidKey) +} + +func TestSecureEnclaveStore_UnsupportedWithoutBackend(t *testing.T) { + if runtime.GOOS == "darwin" { + t.Skip("macOS has a real backend; this covers the stub behaviour.") + } + ctx := context.Background() + store := NewSecureEnclaveStore(t.TempDir()) + assert.False(t, store.Supports(Unlocked)) + + _, err := store.Create(ctx, "k", nil) + assert.ErrorIs(t, err, ErrUnsupportedPlatform) + _, err = store.Load(ctx, "k") + assert.ErrorIs(t, err, ErrUnsupportedPlatform) + assert.ErrorIs(t, store.Delete(ctx, "k"), ErrUnsupportedPlatform) + _, err = store.List(ctx) + assert.ErrorIs(t, err, ErrUnsupportedPlatform) + assert.False(t, errors.Is(err, ErrKeyNotFound)) +} diff --git a/plugins/ssh/keystore/storedkey.go b/plugins/ssh/keystore/storedkey.go new file mode 100644 index 00000000000..7b131fe2b5e --- /dev/null +++ b/plugins/ssh/keystore/storedkey.go @@ -0,0 +1,45 @@ +package keystore + +import ( + "bytes" + "crypto" + "fmt" + "io" + + "golang.org/x/crypto/ssh" +) + +// handle is the live private key a store opens: something that signs and can be released. +type handle interface { + crypto.Signer + io.Closer +} + +// storedKey adapts a handle plus its metadata to the Key interface. +type storedKey struct { + handle + info Info +} + +// newStoredKey builds a Key, checking that the handle's public key is the one recorded in the +// metadata so a swapped key file or sidecar is caught. +func newStoredKey(h handle, info Info) (Key, error) { + pub, err := ssh.NewPublicKey(h.Public()) + if err != nil { + _ = h.Close() + return nil, fmt.Errorf("%w: %q public key: %w", ErrInvalidKey, info.Name, err) + } + if info.PublicKey != nil && !bytes.Equal(pub.Marshal(), info.PublicKey.Marshal()) { + _ = h.Close() + return nil, fmt.Errorf("%w: %q key does not match its metadata", ErrInvalidKey, info.Name) + } + info.PublicKey = pub + return &storedKey{handle: h, info: info}, nil +} + +func (k *storedKey) Name() string { return k.info.Name } +func (k *storedKey) SSHPublicKey() ssh.PublicKey { return k.info.PublicKey } +func (k *storedKey) Requirements() []Requirement { + return append([]Requirement(nil), k.info.Requirements...) +} +func (k *storedKey) Info() Info { return k.info } diff --git a/plugins/ssh/main.go b/plugins/ssh/main.go new file mode 100644 index 00000000000..5bdd9dcfce4 --- /dev/null +++ b/plugins/ssh/main.go @@ -0,0 +1,88 @@ +// Command plugin is the cloudposse/ssh Atmos plugin. One executable plays two roles: +// +// - The plugin server, started by Atmos: the ssh/self provider, the ssh/key identity, and the +// ssh command. +// - The agent daemon, started by launchd or systemd with the first argument "agent-serve". It +// never speaks the plugin handshake, and Atmos never starts it. +package main + +import ( + "context" + "fmt" + "io" + "os" + "os/signal" + "syscall" + + "github.com/cloudposse/atmos/plugins/ssh/daemon" + "github.com/cloudposse/atmos/plugins/ssh/wiring" + "github.com/cloudposse/atmos/sdk/api" + "github.com/cloudposse/atmos/sdk/plugin" +) + +// entry holds the two roles of the executable, so a test can tell which one ran. +type entry struct { + agent func(ctx context.Context, root string) error + plugin func() + stderr io.Writer +} + +func main() { + os.Exit(dispatch(os.Args[1:], realEntry())) +} + +func realEntry() entry { + version := pluginVersion() + return entry{ + agent: func(ctx context.Context, root string) error { + return wiring.ServeAgent(ctx, root, version, func(format string, args ...any) { + fmt.Fprintf(os.Stderr, format+"\n", args...) + }) + }, + plugin: func() { + plugin.Main(plugin.Config{Description: description(), Build: func(client *api.Client) plugin.Services { + return wiring.Services(client, version) + }}) + }, + stderr: os.Stderr, + } +} + +// dispatch runs the daemon when the first argument is "agent-serve", and otherwise the plugin +// server. The daemon branch comes first and never reaches plugin.Main: go-plugin exits when the +// magic cookie is missing, and the daemon has none. +func dispatch(args []string, e entry) int { + if len(args) == 0 || args[0] != daemon.Arg { + e.plugin() + return 0 + } + root, err := parseAgentArgs(args[1:]) + if err != nil { + fmt.Fprintf(e.stderr, "agent-serve: %v\n", err) + return 2 + } + ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) + defer stop() + if err := e.agent(ctx, root); err != nil { + fmt.Fprintf(e.stderr, "agent-serve: %v\n", err) + return 1 + } + return 0 +} + +// parseAgentArgs reads the daemon's flags: --root or --root=. +func parseAgentArgs(args []string) (string, error) { + root := "" + for i := 0; i < len(args); i++ { + switch a := args[i]; { + case a == daemon.RootFlag && i+1 < len(args): + i++ + root = args[i] + case len(a) > len(daemon.RootFlag)+1 && a[:len(daemon.RootFlag)+1] == daemon.RootFlag+"=": + root = a[len(daemon.RootFlag)+1:] + default: + return "", fmt.Errorf("unknown argument %q (usage: agent-serve [--root ])", a) + } + } + return root, nil +} diff --git a/plugins/ssh/main_test.go b/plugins/ssh/main_test.go new file mode 100644 index 00000000000..13911ed1aa2 --- /dev/null +++ b/plugins/ssh/main_test.go @@ -0,0 +1,139 @@ +package main + +import ( + "bytes" + "context" + "errors" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "gopkg.in/yaml.v3" +) + +// recorder is an entry whose two roles only record that they ran. +type recorder struct { + agentRoots []string + agentErr error + pluginRuns int + stderr bytes.Buffer +} + +func (r *recorder) entry() entry { + return entry{ + agent: func(_ context.Context, root string) error { + r.agentRoots = append(r.agentRoots, root) + return r.agentErr + }, + plugin: func() { r.pluginRuns++ }, + stderr: &r.stderr, + } +} + +func TestAgentServeDoesNotStartThePluginHandshake(t *testing.T) { + tests := []struct { + name string + args []string + wantRoot string + }{ + {"no flags", []string{"agent-serve"}, ""}, + {"root with a space", []string{"agent-serve", "--root", "/data/ssh"}, "/data/ssh"}, + {"root with equals", []string{"agent-serve", "--root=/data/ssh"}, "/data/ssh"}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + r := &recorder{} + + code := dispatch(tt.args, r.entry()) + + assert.Equal(t, 0, code) + assert.Equal(t, []string{tt.wantRoot}, r.agentRoots) + assert.Zero(t, r.pluginRuns, "plugin.Main would exit for lack of the magic cookie") + }) + } +} + +func TestAnythingElseStartsThePluginServer(t *testing.T) { + for _, args := range [][]string{nil, {}, {"key", "list"}, {"--root", "/x"}, {"agent-serve-not"}} { + r := &recorder{} + + code := dispatch(args, r.entry()) + + assert.Equal(t, 0, code) + assert.Equal(t, 1, r.pluginRuns, "args %v", args) + assert.Empty(t, r.agentRoots) + } +} + +func TestAgentServeRejectsUnknownArguments(t *testing.T) { + for _, args := range [][]string{{"agent-serve", "--config", "x"}, {"agent-serve", "--root"}, {"agent-serve", "stray"}} { + r := &recorder{} + + code := dispatch(args, r.entry()) + + assert.Equal(t, 2, code, "args %v", args) + assert.Empty(t, r.agentRoots) + assert.Zero(t, r.pluginRuns) + assert.Contains(t, r.stderr.String(), "usage: agent-serve [--root ]") + } +} + +func TestAgentServeReportsAFailure(t *testing.T) { + r := &recorder{agentErr: errors.New("socket is already in use")} + + code := dispatch([]string{"agent-serve"}, r.entry()) + + assert.Equal(t, 1, code) + assert.Contains(t, r.stderr.String(), "socket is already in use") +} + +func TestTheDescriptionAgreesWithTheManifest(t *testing.T) { + var manifest struct { + Metadata struct { + Name string `yaml:"name"` + Version string `yaml:"version"` + } `yaml:"metadata"` + Spec struct { + Capabilities struct { + Commands map[string]any `yaml:"commands"` + Auth struct { + Providers map[string]any `yaml:"providers"` + Identities map[string]any `yaml:"identities"` + } `yaml:"auth"` + } `yaml:"capabilities"` + } `yaml:"spec"` + } + require.NoError(t, yaml.Unmarshal(manifestData, &manifest)) + + d := description() + + assert.Equal(t, "cloudposse/ssh", d.GetPluginName()) + assert.Equal(t, manifest.Metadata.Name, d.GetPluginName()) + assert.Equal(t, manifest.Metadata.Version, d.GetPluginVersion()) + assert.Equal(t, manifest.Metadata.Version, pluginVersion()) + assert.Regexp(t, `^sha256:[0-9a-f]{64}$`, d.GetManifestDigest()) + + want := map[string]bool{} + for kind := range manifest.Spec.Capabilities.Auth.Providers { + want["auth.provider/"+kind] = true + } + for kind := range manifest.Spec.Capabilities.Auth.Identities { + want["auth.identity/"+kind] = true + } + for kind := range manifest.Spec.Capabilities.Commands { + want["command/"+kind] = true + } + got := map[string]bool{} + for _, e := range d.GetExports() { + got[e.GetService()+"/"+e.GetKind()] = true + } + assert.Equal(t, want, got, "exports must equal the manifest's capabilities") + assert.Equal(t, map[string]bool{"auth.provider/ssh/self": true, "auth.identity/ssh/key": true, "command/ssh": true}, got) + assert.NotContains(t, got, "auth.provider/github/user", "the GitHub device login is deferred") + + services := map[string]bool{} + for _, s := range d.GetServices() { + services[s.GetService()] = true + } + assert.Equal(t, map[string]bool{"auth.provider": true, "auth.identity": true, "command": true}, services) +} diff --git a/plugins/ssh/main_unix_test.go b/plugins/ssh/main_unix_test.go new file mode 100644 index 00000000000..d7c59b31640 --- /dev/null +++ b/plugins/ssh/main_unix_test.go @@ -0,0 +1,47 @@ +//go:build !windows + +package main + +import ( + "os" + "path/filepath" + "syscall" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/cloudposse/atmos/plugins/ssh/internal/testfakes" + "github.com/cloudposse/atmos/plugins/ssh/paths" +) + +// The real daemon starts without the plugin handshake and stops on SIGTERM. The test process +// signals itself; dispatch has already registered for the signal by the time the state file exists. +func TestTheRealDaemonServesWithoutAHandshakeAndStopsOnSIGTERM(t *testing.T) { + root := filepath.Join(testfakes.ShortDir(t), "ssh") + e := realEntry() + done := make(chan int, 1) + + go func() { done <- dispatch([]string{"agent-serve", "--root", root}, e) }() + + p, err := paths.New(root) + require.NoError(t, err) + state := p.StateFile() + require.Eventually(t, func() bool { + _, statErr := os.Stat(state) + return statErr == nil + }, 10*time.Second, 20*time.Millisecond, "the daemon wrote its state file") + data, err := os.ReadFile(state) + require.NoError(t, err) + assert.Contains(t, string(data), `"version":"0.1.0"`) + + require.NoError(t, syscall.Kill(os.Getpid(), syscall.SIGTERM)) + + select { + case code := <-done: + assert.Equal(t, 0, code) + case <-time.After(10 * time.Second): + t.Fatal("the daemon did not stop on SIGTERM") + } +} diff --git a/plugins/ssh/manifest.go b/plugins/ssh/manifest.go new file mode 100644 index 00000000000..5c65e692d8d --- /dev/null +++ b/plugins/ssh/manifest.go @@ -0,0 +1,57 @@ +package main + +import ( + "crypto/sha256" + _ "embed" + "encoding/hex" + + "gopkg.in/yaml.v3" + + pluginv1 "github.com/cloudposse/atmos/sdk/proto/atmos/plugin/v1" +) + +//go:embed plugin.yaml +var manifestData []byte + +// fallbackVersion is used only if the embedded manifest cannot be read, which a test prevents. +const fallbackVersion = "0.0.0" + +type manifestHeader struct { + Metadata struct { + Name string `yaml:"name"` + Version string `yaml:"version"` + } `yaml:"metadata"` +} + +// pluginVersion returns the version in the embedded manifest. The daemon records it, and the +// service compares it with the installed copy. +func pluginVersion() string { + var m manifestHeader + if err := yaml.Unmarshal(manifestData, &m); err != nil || m.Metadata.Version == "" { + return fallbackVersion + } + return m.Metadata.Version +} + +// description must agree with plugin.yaml: the host compares the digest and the exports. +func description() *pluginv1.DescribeResponse { + var m manifestHeader + if err := yaml.Unmarshal(manifestData, &m); err != nil { + panic("invalid embedded manifest") + } + digest := sha256.Sum256(manifestData) + return &pluginv1.DescribeResponse{ + PluginName: m.Metadata.Name, PluginVersion: m.Metadata.Version, + ManifestDigest: "sha256:" + hex.EncodeToString(digest[:]), + Services: []*pluginv1.ServiceVersionRange{ + {Service: "auth.provider", Min: 1, Max: 1}, + {Service: "auth.identity", Min: 1, Max: 1}, + {Service: "command", Min: 1, Max: 1}, + }, + Exports: []*pluginv1.Export{ + {Service: "auth.provider", Kind: "ssh/self"}, + {Service: "auth.identity", Kind: "ssh/key"}, + {Service: "command", Kind: "ssh"}, + }, + } +} diff --git a/plugins/ssh/paths/paths.go b/plugins/ssh/paths/paths.go new file mode 100644 index 00000000000..32eb8c0d749 --- /dev/null +++ b/plugins/ssh/paths/paths.go @@ -0,0 +1,163 @@ +// Package paths resolves the per-user locations the SSH plugin uses on disk. +// +// The plugin process starts with an empty environment, so nothing here reads environment +// variables. The home directory comes from the operating system's user database. The default root +// mirrors where Atmos puts its XDG data directory when no XDG variable is set (see pkg/xdg), with +// an "ssh" subfolder: ~/.local/share/atmos/ssh on macOS and Linux, and +// ~\AppData\Local\atmos\ssh on Windows. +package paths + +import ( + "errors" + "fmt" + "os" + "os/user" + "path/filepath" + "regexp" + "runtime" +) + +// Sentinel errors. Wrap them with fmt.Errorf("%w ...") and test with errors.Is. +var ( + // ErrNoHome means the user's home directory could not be determined. + ErrNoHome = errors.New("cannot determine the home directory") + // ErrEmptyRoot means an empty root directory was given. + ErrEmptyRoot = errors.New("root directory is empty") + // ErrInvalidIdentity means an identity name cannot be used in a file name. + ErrInvalidIdentity = errors.New("invalid identity name") + // ErrSocketPathTooLong means a Unix socket path exceeds the operating system's limit. + ErrSocketPathTooLong = errors.New("unix socket path is too long") +) + +const ( + // DirMode is the permission of every directory the plugin creates. + DirMode os.FileMode = 0o700 + + maxIdentityLen = 64 + socketExt = ".sock" +) + +var identityRE = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9._-]*$`) + +// Paths is the set of per-user locations under one root directory. +type Paths struct { + root string +} + +// New returns Paths rooted at root. Tests use it to keep everything under a temporary directory. +func New(root string) (*Paths, error) { + if root == "" { + return nil, ErrEmptyRoot + } + return &Paths{root: filepath.Clean(root)}, nil +} + +// Default returns Paths rooted at the default location for the current user, without reading any +// environment variable. +func Default() (*Paths, error) { + home, err := HomeDir() + if err != nil { + return nil, err + } + return New(defaultRoot(home, runtime.GOOS)) +} + +// HomeDir returns the current user's home directory from the user database. It does not use +// $HOME, which is absent in the plugin process. +func HomeDir() (string, error) { + u, err := user.Current() + if err != nil { + return "", fmt.Errorf("%w: %w", ErrNoHome, err) + } + if u.HomeDir == "" { + return "", fmt.Errorf("%w: user %q has no home directory", ErrNoHome, u.Username) + } + return u.HomeDir, nil +} + +// defaultRoot is the Atmos data directory for goos, plus the plugin's "ssh" subfolder. +func defaultRoot(home, goos string) string { + if goos == "windows" { + return filepath.Join(home, "AppData", "Local", "atmos", "ssh") + } + return filepath.Join(home, ".local", "share", "atmos", "ssh") +} + +// Root is the directory that holds everything the plugin stores. +func (p *Paths) Root() string { return p.root } + +// KeysDir holds the private key material and its metadata. +func (p *Paths) KeysDir() string { return filepath.Join(p.root, "keys") } + +// StoreDir is where the key store of the given kind keeps its key material: a subdirectory of +// KeysDir named after the kind, so stores never share file names. +func (p *Paths) StoreDir(kind string) string { return filepath.Join(p.KeysDir(), kind) } + +// SocketsDir holds one agent socket per identity. +func (p *Paths) SocketsDir() string { return filepath.Join(p.root, "sockets") } + +// ReceiptsDir holds the enrollment receipts. +func (p *Paths) ReceiptsDir() string { return filepath.Join(p.root, "receipts") } + +// BinDir holds the stable, versioned copies of the plugin executable. +func (p *Paths) BinDir() string { return filepath.Join(p.root, "bin") } + +// AgentConfigFile is the file that lists the identities the agent serves. +func (p *Paths) AgentConfigFile() string { return filepath.Join(p.root, "agent.json") } + +// AuditLogFile is the agent's audit log. +func (p *Paths) AuditLogFile() string { return filepath.Join(p.root, "audit.log") } + +// StateFile is the file the running daemon writes its pid and version to. +func (p *Paths) StateFile() string { return filepath.Join(p.root, "daemon.json") } + +// ServiceLogFile receives the daemon's standard output and error under launchd or systemd. +func (p *Paths) ServiceLogFile() string { return filepath.Join(p.root, "agent.log") } + +// ValidateIdentity reports whether name can be used as an identity name in a file name. +func ValidateIdentity(name string) error { + if len(name) > maxIdentityLen || !identityRE.MatchString(name) { + return fmt.Errorf("%w: %q", ErrInvalidIdentity, name) + } + return nil +} + +// SocketPath returns the socket path for identity. It fails if the name is unsafe or the whole +// path is longer than the operating system allows for a Unix socket. +func (p *Paths) SocketPath(identity string) (string, error) { + if err := ValidateIdentity(identity); err != nil { + return "", err + } + sock := filepath.Join(p.SocketsDir(), identity+socketExt) + limit := maxSocketPath(runtime.GOOS) + if len(sock) >= limit { + return "", fmt.Errorf("%w: %d bytes, the limit on %s is %d (including the terminating NUL): %s; "+ + "use a shorter data directory", ErrSocketPathTooLong, len(sock), runtime.GOOS, limit, sock) + } + return sock, nil +} + +// maxSocketPath is the size of sockaddr_un.sun_path on goos. A path must be strictly shorter, +// leaving room for the terminating NUL. +func maxSocketPath(goos string) int { + switch goos { + case "linux", "android", "windows": + return 108 + default: + return 104 + } +} + +// EnsureDirs creates the root and every subdirectory with mode 0700. It tightens the mode of +// directories that already exist. +func (p *Paths) EnsureDirs() error { + for _, dir := range []string{p.root, p.KeysDir(), p.SocketsDir(), p.ReceiptsDir(), p.BinDir()} { + if err := os.MkdirAll(dir, DirMode); err != nil { + return fmt.Errorf("create directory %s: %w", dir, err) + } + if err := os.Chmod(dir, DirMode); err != nil { + return fmt.Errorf("restrict directory %s: %w", dir, err) + } + } + return nil +} diff --git a/plugins/ssh/paths/paths_test.go b/plugins/ssh/paths/paths_test.go new file mode 100644 index 00000000000..77c7c3a1343 --- /dev/null +++ b/plugins/ssh/paths/paths_test.go @@ -0,0 +1,151 @@ +package paths + +import ( + "errors" + "os" + "path/filepath" + "runtime" + "strings" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestDefaultRoot(t *testing.T) { + tests := []struct { + goos string + want []string + }{ + {"darwin", []string{".local", "share", "atmos", "ssh"}}, + {"linux", []string{".local", "share", "atmos", "ssh"}}, + {"windows", []string{"AppData", "Local", "atmos", "ssh"}}, + } + for _, tt := range tests { + t.Run(tt.goos, func(t *testing.T) { + home := filepath.Join(string(filepath.Separator), "home", "me") + got := defaultRoot(home, tt.goos) + assert.Equal(t, filepath.Join(append([]string{home}, tt.want...)...), got) + }) + } +} + +func TestDefaultIgnoresEnvironment(t *testing.T) { + t.Setenv("HOME", filepath.Join(t.TempDir(), "fake-home")) + t.Setenv("XDG_DATA_HOME", filepath.Join(t.TempDir(), "xdg")) + p, err := Default() + require.NoError(t, err) + home, err := HomeDir() + require.NoError(t, err) + assert.Equal(t, defaultRoot(home, runtime.GOOS), p.Root()) + assert.NotContains(t, p.Root(), "fake-home") +} + +func TestLayout(t *testing.T) { + root := t.TempDir() + p, err := New(root) + require.NoError(t, err) + + tests := map[string]struct{ got, want string }{ + "root": {p.Root(), root}, + "keys": {p.KeysDir(), filepath.Join(root, "keys")}, + "store": {p.StoreDir("file"), filepath.Join(root, "keys", "file")}, + "sockets": {p.SocketsDir(), filepath.Join(root, "sockets")}, + "receipts": {p.ReceiptsDir(), filepath.Join(root, "receipts")}, + "bin": {p.BinDir(), filepath.Join(root, "bin")}, + "config": {p.AgentConfigFile(), filepath.Join(root, "agent.json")}, + "audit": {p.AuditLogFile(), filepath.Join(root, "audit.log")}, + "state": {p.StateFile(), filepath.Join(root, "daemon.json")}, + "log": {p.ServiceLogFile(), filepath.Join(root, "agent.log")}, + } + for name, tt := range tests { + t.Run(name, func(t *testing.T) { assert.Equal(t, tt.want, tt.got) }) + } +} + +func TestNewRejectsEmptyRoot(t *testing.T) { + _, err := New("") + require.ErrorIs(t, err, ErrEmptyRoot) +} + +func TestSocketPath(t *testing.T) { + p, err := New(t.TempDir()) + require.NoError(t, err) + + got, err := p.SocketPath("ops") + require.NoError(t, err) + assert.Equal(t, filepath.Join(p.SocketsDir(), "ops.sock"), got) + + for _, bad := range []string{"", "../x", "a/b", ".hidden", "a b", strings.Repeat("a", 65)} { + _, err := p.SocketPath(bad) + require.ErrorIs(t, err, ErrInvalidIdentity, "name %q", bad) + } +} + +func TestSocketPathTooLong(t *testing.T) { + p, err := New(filepath.Join(t.TempDir(), strings.Repeat("d", 120))) + require.NoError(t, err) + _, err = p.SocketPath("ops") + require.ErrorIs(t, err, ErrSocketPathTooLong) + assert.Contains(t, err.Error(), "shorter data directory") +} + +func TestMaxSocketPath(t *testing.T) { + tests := map[string]int{"darwin": 104, "linux": 108, "windows": 108, "freebsd": 104} + for goos, want := range tests { + assert.Equal(t, want, maxSocketPath(goos), goos) + } +} + +func TestSocketPathBoundary(t *testing.T) { + // A path exactly one byte shorter than the limit is accepted; at the limit it is refused. + limit := maxSocketPath(runtime.GOOS) + base := filepath.Join(string(filepath.Separator), "r") + suffix := len(filepath.Join(string(filepath.Separator), "sockets", "ops.sock")) + pad := limit - 1 - len(base) - suffix + require.Positive(t, pad) + + ok, err := New(base + strings.Repeat("y", pad)) + require.NoError(t, err) + _, err = ok.SocketPath("ops") + require.NoError(t, err) + + tooLong, err := New(base + strings.Repeat("y", pad+1)) + require.NoError(t, err) + _, err = tooLong.SocketPath("ops") + require.ErrorIs(t, err, ErrSocketPathTooLong) +} + +func TestEnsureDirs(t *testing.T) { + p, err := New(filepath.Join(t.TempDir(), "ssh")) + require.NoError(t, err) + require.NoError(t, p.EnsureDirs()) + require.NoError(t, p.EnsureDirs(), "second call is a no-op") + + for _, dir := range []string{p.Root(), p.KeysDir(), p.SocketsDir(), p.ReceiptsDir(), p.BinDir()} { + info, err := os.Stat(dir) + require.NoError(t, err) + require.True(t, info.IsDir()) + if runtime.GOOS != "windows" { + assert.Equal(t, DirMode, info.Mode().Perm(), dir) + } + } +} + +func TestEnsureDirsTightensMode(t *testing.T) { + if runtime.GOOS == "windows" { + t.Skip("POSIX modes only") + } + root := filepath.Join(t.TempDir(), "ssh") + require.NoError(t, os.MkdirAll(root, 0o755)) + p, err := New(root) + require.NoError(t, err) + require.NoError(t, p.EnsureDirs()) + info, err := os.Stat(root) + require.NoError(t, err) + assert.Equal(t, DirMode, info.Mode().Perm()) +} + +func TestErrorsAreDistinct(t *testing.T) { + assert.False(t, errors.Is(ErrNoHome, ErrEmptyRoot)) +} diff --git a/plugins/ssh/plugin.tests.yaml b/plugins/ssh/plugin.tests.yaml new file mode 100644 index 00000000000..f6eb7c3a485 --- /dev/null +++ b/plugins/ssh/plugin.tests.yaml @@ -0,0 +1,33 @@ +version: 1 +commands: + - name: ssh + arguments: [help] + exit_code: 0 + stdout: | + Manage SSH keys and the agent that serves them. + + Usage: + key list Keys on this machine, across key stores. + key show [--format F] Print a key. F is authorized-key (default), + allowed-signers, github, or json. + key status [] Each key's store, requirements, authority, + expiry, and the last login result and error. + key delete --yes Delete the local key and its agent entry. The + authority is updated at the next login or logout. + agent start | stop | status Run, stop, or inspect the agent service. + agent log [--lines N] Print the tail of the audit log. + test [--soak D] [--interval D] + Sign a Git payload through the identity's socket + and verify it. --soak repeats it every interval + for D, one line per attempt. + help Print this text. + + Flags: + --root Use this data directory instead of the default. The "root" entry + of the command's config does the same. + --store Pick the key store when a name exists in more than one. + + Keys are created by "atmos auth login". Commands never contact an authority. +steps: + - type: shell + command: go test ./... diff --git a/plugins/ssh/plugin.yaml b/plugins/ssh/plugin.yaml new file mode 100644 index 00000000000..30980dbc28a --- /dev/null +++ b/plugins/ssh/plugin.yaml @@ -0,0 +1,51 @@ +apiVersion: atmos/v1 +kind: AtmosPluginConfig +metadata: + name: cloudposse/ssh + version: 0.1.0 + display_name: SSH keys + description: Make an SSH key held in the machine's security hardware an Atmos identity, serve it through a per-identity agent, and sign Git commits with it + author: Cloud Posse + repository: https://github.com/cloudposse/atmos +spec: + runtime: + type: native + protocol: 1 + executable: bin/plugin.exe + platforms: + linux/amd64: + executable: bin/linux-amd64/plugin + linux/arm64: + executable: bin/linux-arm64/plugin + darwin/amd64: + executable: bin/darwin-amd64/plugin + darwin/arm64: + executable: bin/darwin-arm64/plugin + windows/amd64: + executable: bin/windows-amd64/plugin.exe + windows/arm64: + executable: bin/windows-arm64/plugin.exe + compatibility: + protocol: '>=1 <2' + contracts: + auth.provider: '>=1' + auth.identity: '>=1' + command: '>=1' + capabilities: + commands: + ssh: + description: Manage SSH keys and the agent that serves them + schema: schemas/command.json + auth: + providers: + ssh/self: + schema: schemas/ssh-self.json + credentials: [secret-values/v1] + features: [logout] + identities: + ssh/key: + schema: schemas/ssh-key.json + schema_target: spec + accepts: [secret-values/v1] + credentials: [environment/v1] + features: [logout] diff --git a/plugins/ssh/rpc/commands.go b/plugins/ssh/rpc/commands.go new file mode 100644 index 00000000000..8c09bab9b69 --- /dev/null +++ b/plugins/ssh/rpc/commands.go @@ -0,0 +1,77 @@ +package rpc + +import ( + "context" + "io" + + "google.golang.org/grpc" + + pluginv1 "github.com/cloudposse/atmos/sdk/proto/atmos/plugin/v1" +) + +// maxChunk is the largest output chunk the protocol allows. +const maxChunk = 64 << 10 + +// maxExit is the largest exit code the protocol allows. +const maxExit = 255 + +// Runner executes a command and returns its exit code. +type Runner interface { + Run(ctx context.Context, args []string, settings map[string]any, stdout, stderr io.Writer) int +} + +// Commands is the "ssh" command server. +type Commands struct { + pluginv1.UnimplementedCommandsServer + runner Runner +} + +// NewCommands returns the command server. +func NewCommands(runner Runner) *Commands { return &Commands{runner: runner} } + +// Run executes the command, streams its output, and ends with exactly one exit event. +func (c *Commands) Run(request *pluginv1.CommandRequest, stream grpc.ServerStreamingServer[pluginv1.CommandEvent]) error { + sink := &sink{stream: stream} + code := c.runner.Run(stream.Context(), request.GetArguments(), request.GetSettings().AsMap(), + &chunkWriter{sink: sink, stderr: false}, &chunkWriter{sink: sink, stderr: true}) + if sink.err != nil { + return sink.err + } + if code < 0 || code > maxExit { + code = maxExit + } + return stream.Send(&pluginv1.CommandEvent{Event: &pluginv1.CommandEvent_Exit{Exit: &pluginv1.CommandExit{Code: uint32(code)}}}) +} + +// sink sends output events and remembers the first failure. +type sink struct { + stream grpc.ServerStreamingServer[pluginv1.CommandEvent] + err error +} + +// chunkWriter splits writes into protocol-sized, non-empty events. +type chunkWriter struct { + sink *sink + stderr bool +} + +func (w *chunkWriter) Write(p []byte) (int, error) { + written := 0 + for len(p) > 0 { + n := min(len(p), maxChunk) + chunk := append([]byte(nil), p[:n]...) + event := &pluginv1.CommandEvent{Event: &pluginv1.CommandEvent_Stdout{Stdout: chunk}} + if w.stderr { + event = &pluginv1.CommandEvent{Event: &pluginv1.CommandEvent_Stderr{Stderr: chunk}} + } + if w.sink.err == nil { + w.sink.err = w.sink.stream.Send(event) + } + if w.sink.err != nil { + return written, w.sink.err + } + written += n + p = p[n:] + } + return written, nil +} diff --git a/plugins/ssh/rpc/identity.go b/plugins/ssh/rpc/identity.go new file mode 100644 index 00000000000..e3ad335da50 --- /dev/null +++ b/plugins/ssh/rpc/identity.go @@ -0,0 +1,119 @@ +package rpc + +import ( + "context" + "errors" + "fmt" + + "google.golang.org/grpc" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" + "google.golang.org/protobuf/types/known/emptypb" + "google.golang.org/protobuf/types/known/structpb" + "google.golang.org/protobuf/types/known/timestamppb" + + "github.com/cloudposse/atmos/plugins/ssh/identity" + "github.com/cloudposse/atmos/sdk/api" + pluginv1 "github.com/cloudposse/atmos/sdk/proto/atmos/plugin/v1" +) + +// Identity is the ssh/key identity server. +type Identity struct { + pluginv1.UnimplementedAuthIdentityServer + service *identity.Service +} + +// NewIdentity returns the identity server. +func NewIdentity(service *identity.Service) *Identity { return &Identity{service: service} } + +// bind scopes API calls (private state, HTTP) to the invocation. +func bind(ctx context.Context, invocation *pluginv1.Invocation) context.Context { + return api.WithInvocation(ctx, invocation.GetId()) +} + +// Validate checks the identity's spec. +func (i *Identity) Validate(_ context.Context, request *pluginv1.IdentityRequest) (*pluginv1.ValidateResponse, error) { + if err := i.service.Validate(request.GetName(), request.GetSpec().AsMap()); err != nil { + return nil, StatusError(err) + } + return &pluginv1.ValidateResponse{}, nil +} + +// Authenticate brings the identity up and returns its environment. +func (i *Identity) Authenticate(request *pluginv1.IdentityAuthenticateRequest, stream grpc.ServerStreamingServer[pluginv1.AuthenticateEvent]) error { + req := request.GetIdentity() + upstream, err := upstreamStrings(request.GetUpstream()) + if err != nil { + return err + } + ctx := bind(stream.Context(), req.GetInvocation()) + result, err := i.service.Authenticate(ctx, req.GetName(), req.GetSpec().AsMap(), upstream) + if err != nil { + return StatusError(err) + } + env := make(map[string]any, len(result.Environment)) + for k, v := range result.Environment { + env[k] = v + } + data, err := structpb.NewStruct(env) + if err != nil { + return status.Error(codes.Internal, "build credential") + } + creds := &pluginv1.Credentials{Type: TypeEnvironment, Data: data, ExpiresAt: timestamppb.New(result.ExpiresAt)} + return stream.Send(&pluginv1.AuthenticateEvent{Event: &pluginv1.AuthenticateEvent_Result{Result: creds}}) +} + +// Logout withdraws enrollments of keys that are gone and removes the identity from the agent. +func (i *Identity) Logout(ctx context.Context, request *pluginv1.IdentityRequest) (*emptypb.Empty, error) { + ctx = bind(ctx, request.GetInvocation()) + if err := i.service.Logout(ctx, request.GetName(), request.GetSpec().AsMap()); err != nil { + return nil, StatusError(err) + } + return &emptypb.Empty{}, nil +} + +// upstreamStrings reads the provider's credential as a map of strings. +func upstreamStrings(creds *pluginv1.Credentials) (map[string]string, error) { + if creds.GetType() != TypeSecretValues { + return nil, status.Error(codes.InvalidArgument, "ssh/key accepts only secret-values/v1 credentials") + } + out := map[string]string{} + for k, v := range creds.GetData().AsMap() { + if s, ok := v.(string); ok { + out[k] = s + } + } + return out, nil +} + +// StatusError maps a failure to the gRPC code the host understands: Unauthenticated for a rejected +// token, FailedPrecondition only for "interaction required" (a locked screen), and codes that the +// host reports as a generic failure for the rest. The text is the code's name, because the host +// discards plugin error text; "atmos ssh key status" holds the details. +func StatusError(err error) error { + var failure *identity.Error + if !errors.As(err, &failure) { + return status.Error(codes.Internal, "ssh identity failed") + } + return status.Error(grpcCode(failure.Code), fmt.Sprintf("ssh identity failed: %s; run \"atmos ssh key status\" for details", failure.Code)) +} + +func grpcCode(code identity.Code) codes.Code { + switch code { + case identity.CodeTokenRejected, identity.CodeMissingScope: + return codes.Unauthenticated + case identity.CodeKeyLocked: + return codes.FailedPrecondition + case identity.CodeInvalidSpec, identity.CodeRequirementMismatch, identity.CodeUnsupportedRequirement, + identity.CodeUnknownAuthority, identity.CodeUnsupportedUse: + return codes.InvalidArgument + case identity.CodeAuthorityUnreachable, identity.CodeAgentUnavailable: + return codes.Unavailable + case identity.CodeUnsupportedPlatform: + return codes.Unimplemented + case identity.CodeCanceled: + return codes.Canceled + default: + return codes.Internal + } +} diff --git a/plugins/ssh/rpc/provider.go b/plugins/ssh/rpc/provider.go new file mode 100644 index 00000000000..60ed4500d9a --- /dev/null +++ b/plugins/ssh/rpc/provider.go @@ -0,0 +1,71 @@ +// Package rpc adapts the SSH plugin's logic to the Atmos plugin protocol. +package rpc + +import ( + "context" + "time" + + "google.golang.org/grpc" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" + "google.golang.org/protobuf/types/known/emptypb" + "google.golang.org/protobuf/types/known/structpb" + "google.golang.org/protobuf/types/known/timestamppb" + + pluginv1 "github.com/cloudposse/atmos/sdk/proto/atmos/plugin/v1" +) + +const ( + // TypeSecretValues is the credential type between a provider and the ssh/key identity. + TypeSecretValues = "secret-values/v1" + // TypeEnvironment is the credential type the ssh/key identity returns. + TypeEnvironment = "environment/v1" + + // KindSelf is the provider with no authority. + KindSelf = "ssh/self" + // KindKey is the SSH key identity. + KindKey = "ssh/key" + + // AssertionEntry marks the ssh/self credential as self-asserted. The map cannot be empty, + // because the host rejects an empty secret-values/v1 credential. + AssertionEntry = "assertion" + // AssertionSelf is the value of AssertionEntry for ssh/self. + AssertionSelf = "self" + + // SelfLifetime is how long the ssh/self credential is valid. + SelfLifetime = 12 * time.Hour +) + +// Provider is the ssh/self provider. It needs no interaction and no network: nothing vouches for +// the key, so the credential only says so. +type Provider struct { + pluginv1.UnimplementedAuthProviderServer + // Now is the clock. + Now func() time.Time +} + +// Validate accepts only an empty spec. +func (*Provider) Validate(_ context.Context, request *pluginv1.ProviderRequest) (*pluginv1.ValidateResponse, error) { + if len(request.GetSpec().GetFields()) != 0 { + return nil, status.Error(codes.InvalidArgument, "ssh/self takes no configuration") + } + return &pluginv1.ValidateResponse{}, nil +} + +// Authenticate returns a self-asserted credential. +func (p *Provider) Authenticate(request *pluginv1.ProviderRequest, stream grpc.ServerStreamingServer[pluginv1.AuthenticateEvent]) error { + if len(request.GetSpec().GetFields()) != 0 { + return status.Error(codes.InvalidArgument, "ssh/self takes no configuration") + } + data, err := structpb.NewStruct(map[string]any{AssertionEntry: AssertionSelf}) + if err != nil { + return status.Error(codes.Internal, "build credential") + } + creds := &pluginv1.Credentials{Type: TypeSecretValues, Data: data, ExpiresAt: timestamppb.New(p.Now().Add(SelfLifetime))} + return stream.Send(&pluginv1.AuthenticateEvent{Event: &pluginv1.AuthenticateEvent_Result{Result: creds}}) +} + +// Logout has nothing to undo. +func (*Provider) Logout(context.Context, *pluginv1.ProviderRequest) (*emptypb.Empty, error) { + return &emptypb.Empty{}, nil +} diff --git a/plugins/ssh/rpc/rpc_test.go b/plugins/ssh/rpc/rpc_test.go new file mode 100644 index 00000000000..e0105908f5b --- /dev/null +++ b/plugins/ssh/rpc/rpc_test.go @@ -0,0 +1,309 @@ +package rpc_test + +import ( + "context" + "errors" + "io" + "net" + "net/http" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "golang.org/x/crypto/ssh" + "google.golang.org/grpc" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/credentials/insecure" + "google.golang.org/grpc/status" + "google.golang.org/grpc/test/bufconn" + "google.golang.org/protobuf/types/known/structpb" + + "github.com/cloudposse/atmos/plugins/ssh/authority" + "github.com/cloudposse/atmos/plugins/ssh/authority/github" + "github.com/cloudposse/atmos/plugins/ssh/authority/self" + "github.com/cloudposse/atmos/plugins/ssh/daemon" + "github.com/cloudposse/atmos/plugins/ssh/identity" + "github.com/cloudposse/atmos/plugins/ssh/internal/testfakes" + "github.com/cloudposse/atmos/plugins/ssh/paths" + "github.com/cloudposse/atmos/plugins/ssh/rpc" + "github.com/cloudposse/atmos/plugins/ssh/service" + pluginv1 "github.com/cloudposse/atmos/sdk/proto/atmos/plugin/v1" +) + +type server struct { + provider pluginv1.AuthProviderClient + identity pluginv1.AuthIdentityClient + commands pluginv1.CommandsClient + paths *paths.Paths + clock *testfakes.Clock +} + +type failTransport struct{ t *testing.T } + +func (f failTransport) RoundTrip(r *http.Request) (*http.Response, error) { + f.t.Errorf("unexpected network call to %s", r.URL) + return nil, errors.New("no network in tests") +} + +func start(t *testing.T, runner rpc.Runner) *server { + t.Helper() + p := testfakes.Paths(t) + clock := testfakes.NewClock() + mgr := &testfakes.Manager{Version: "0.1.0"} + reg := authority.NewRegistry() + require.NoError(t, reg.Register(self.Factory)) + require.NoError(t, reg.Register(github.Factory)) + svc := identity.New(identity.Deps{ + Paths: func(string) (*paths.Paths, error) { return p, nil }, + OpenStore: testfakes.FileOpener, + Authorities: reg, + Daemon: daemon.Deps{ + Service: func(*paths.Paths) (service.Manager, error) { return mgr, nil }, + InstallExecutable: service.StablePath, + Version: "0.1.0", + }, + CheckSocket: func(context.Context, string, ssh.PublicKey) error { return nil }, + HTTPClient: &http.Client{Transport: failTransport{t}}, + State: testfakes.NewState(), + Now: clock.Now, + Hostname: func() (string, error) { return "host", nil }, + HomeDir: func() (string, error) { return "/home/u", nil }, + FindSSHKeygen: func() (string, error) { return "/usr/bin/ssh-keygen", nil }, + Sleep: clock.Sleep, + }) + grpcServer := grpc.NewServer() + pluginv1.RegisterAuthProviderServer(grpcServer, &rpc.Provider{Now: clock.Now}) + pluginv1.RegisterAuthIdentityServer(grpcServer, rpc.NewIdentity(svc)) + pluginv1.RegisterCommandsServer(grpcServer, rpc.NewCommands(runner)) + listener := bufconn.Listen(1 << 20) + go func() { _ = grpcServer.Serve(listener) }() + t.Cleanup(grpcServer.Stop) + conn, err := grpc.NewClient("passthrough:///ssh", grpc.WithTransportCredentials(insecure.NewCredentials()), + grpc.WithContextDialer(func(context.Context, string) (net.Conn, error) { return listener.Dial() })) + require.NoError(t, err) + t.Cleanup(func() { _ = conn.Close() }) + return &server{ + provider: pluginv1.NewAuthProviderClient(conn), identity: pluginv1.NewAuthIdentityClient(conn), + commands: pluginv1.NewCommandsClient(conn), paths: p, clock: clock, + } +} + +func object(t *testing.T, v map[string]any) *structpb.Struct { + t.Helper() + s, err := structpb.NewStruct(v) + require.NoError(t, err) + return s +} + +func identitySpec(t *testing.T, extra map[string]any) *structpb.Struct { + spec := map[string]any{"store": "file", "allow": []any{"signing", "authentication"}} + for k, v := range extra { + spec[k] = v + } + return object(t, spec) +} + +func only(t *testing.T, stream grpc.ServerStreamingClient[pluginv1.AuthenticateEvent]) *pluginv1.Credentials { + t.Helper() + event, err := stream.Recv() + require.NoError(t, err) + _, err = stream.Recv() + require.ErrorIs(t, err, io.EOF) + return event.GetResult() +} + +func TestSelfProviderThenIdentityAcrossRPC(t *testing.T) { + s := start(t, nil) + ctx := t.Context() + provider := &pluginv1.ProviderRequest{Invocation: &pluginv1.Invocation{Id: "p"}, Name: "keys", Kind: rpc.KindSelf, Spec: object(t, nil)} + _, err := s.provider.Validate(ctx, provider) + require.NoError(t, err) + stream, err := s.provider.Authenticate(ctx, provider) + require.NoError(t, err) + upstream := only(t, stream) + + assert.Equal(t, "secret-values/v1", upstream.GetType()) + assert.Equal(t, map[string]any{"assertion": "self"}, upstream.GetData().AsMap(), "never empty, and says it is self-asserted") + assert.Equal(t, s.clock.Now().Add(rpc.SelfLifetime), upstream.GetExpiresAt().AsTime()) + + request := &pluginv1.IdentityRequest{Invocation: &pluginv1.Invocation{Id: "i"}, Name: "ops", Kind: rpc.KindKey, Spec: identitySpec(t, map[string]any{"user": "deploy"})} + _, err = s.identity.Validate(ctx, request) + require.NoError(t, err) + out, err := s.identity.Authenticate(ctx, &pluginv1.IdentityAuthenticateRequest{Identity: request, Upstream: upstream}) + require.NoError(t, err) + creds := only(t, out) + + assert.Equal(t, "environment/v1", creds.GetType()) + env := creds.GetData().AsMap() + assert.Contains(t, env, "SSH_AUTH_SOCK") + assert.Contains(t, env, "GIT_CONFIG_GLOBAL") + assert.Equal(t, "deploy", env["ANSIBLE_REMOTE_USER"]) + assert.Equal(t, s.clock.Now().Add(identity.CredentialLifetime), creds.GetExpiresAt().AsTime()) + assert.False(t, creds.GetExpiresAt().AsTime().IsZero(), "the host rejects a credential without an expiry") + + _, err = s.identity.Logout(ctx, request) + require.NoError(t, err) + _, err = s.provider.Logout(ctx, provider) + require.NoError(t, err) +} + +func TestSelfProviderTakesNoConfiguration(t *testing.T) { + s := start(t, nil) + request := &pluginv1.ProviderRequest{Spec: object(t, map[string]any{"anything": "x"})} + + _, err := s.provider.Validate(t.Context(), request) + assert.Equal(t, codes.InvalidArgument, status.Code(err)) + + stream, err := s.provider.Authenticate(t.Context(), request) + require.NoError(t, err) + _, err = stream.Recv() + assert.Equal(t, codes.InvalidArgument, status.Code(err)) +} + +func TestIdentityValidateRejectsABadSpec(t *testing.T) { + s := start(t, nil) + + _, err := s.identity.Validate(t.Context(), &pluginv1.IdentityRequest{Name: "ops", Spec: object(t, map[string]any{"store": "file"})}) + + assert.Equal(t, codes.InvalidArgument, status.Code(err)) +} + +func TestIdentityRejectsAnUpstreamOfTheWrongType(t *testing.T) { + s := start(t, nil) + request := &pluginv1.IdentityRequest{Name: "ops", Spec: identitySpec(t, nil)} + + out, err := s.identity.Authenticate(t.Context(), &pluginv1.IdentityAuthenticateRequest{ + Identity: request, Upstream: &pluginv1.Credentials{Type: "oidc/v1", Data: object(t, nil)}, + }) + require.NoError(t, err) + _, err = out.Recv() + + assert.Equal(t, codes.InvalidArgument, status.Code(err)) +} + +func TestARejectedTokenIsUnauthenticatedAndTheDetailIsInTheStatusFile(t *testing.T) { + s := start(t, nil) + request := &pluginv1.IdentityRequest{Name: "ops", Spec: identitySpec(t, map[string]any{"authority": "github"})} + + out, err := s.identity.Authenticate(t.Context(), &pluginv1.IdentityAuthenticateRequest{ + Identity: request, Upstream: &pluginv1.Credentials{Type: "secret-values/v1", Data: object(t, map[string]any{"assertion": "self"})}, + }) + require.NoError(t, err) + _, err = out.Recv() + + assert.Equal(t, codes.Unauthenticated, status.Code(err)) + assert.Contains(t, status.Convert(err).Message(), "atmos ssh key status") + assert.NotContains(t, status.Convert(err).Message(), "no token", "the detail is for the status file, not the wire") +} + +func TestStatusErrorMapsEveryCodeToWhatTheHostUnderstands(t *testing.T) { + tests := map[identity.Code]codes.Code{ + identity.CodeTokenRejected: codes.Unauthenticated, + identity.CodeMissingScope: codes.Unauthenticated, + identity.CodeKeyLocked: codes.FailedPrecondition, + identity.CodeInvalidSpec: codes.InvalidArgument, + identity.CodeRequirementMismatch: codes.InvalidArgument, + identity.CodeUnsupportedRequirement: codes.InvalidArgument, + identity.CodeUnknownAuthority: codes.InvalidArgument, + identity.CodeUnsupportedUse: codes.InvalidArgument, + identity.CodeAuthorityUnreachable: codes.Unavailable, + identity.CodeAgentUnavailable: codes.Unavailable, + identity.CodeUnsupportedPlatform: codes.Unimplemented, + identity.CodeCanceled: codes.Canceled, + identity.CodeInternal: codes.Internal, + } + for code, want := range tests { + t.Run(string(code), func(t *testing.T) { + err := rpc.StatusError(&identity.Error{Code: code, Message: "secret detail"}) + + assert.Equal(t, want, status.Code(err)) + assert.NotContains(t, err.Error(), "secret detail") + }) + } + assert.Equal(t, codes.Internal, status.Code(rpc.StatusError(errors.New("anything else")))) +} + +type fakeRunner struct { + stdout, stderr []byte + code int + gotArgs []string + gotSettings map[string]any +} + +func (f *fakeRunner) Run(_ context.Context, args []string, settings map[string]any, stdout, stderr io.Writer) int { + f.gotArgs, f.gotSettings = args, settings + _, _ = stdout.Write(f.stdout) + _, _ = stderr.Write(f.stderr) + _, _ = stdout.Write(nil) + return f.code +} + +func collect(t *testing.T, stream grpc.ServerStreamingClient[pluginv1.CommandEvent]) (stdout, stderr []byte, exits []uint32, maxChunk int) { + t.Helper() + for { + event, err := stream.Recv() + if errors.Is(err, io.EOF) { + return stdout, stderr, exits, maxChunk + } + require.NoError(t, err) + switch e := event.GetEvent().(type) { + case *pluginv1.CommandEvent_Stdout: + require.NotEmpty(t, e.Stdout, "an empty chunk is a protocol error") + stdout = append(stdout, e.Stdout...) + maxChunk = max(maxChunk, len(e.Stdout)) + case *pluginv1.CommandEvent_Stderr: + require.NotEmpty(t, e.Stderr) + stderr = append(stderr, e.Stderr...) + maxChunk = max(maxChunk, len(e.Stderr)) + case *pluginv1.CommandEvent_Exit: + exits = append(exits, e.Exit.GetCode()) + } + } +} + +func TestCommandStreamsOutputInProtocolSizedChunksAndEndsWithOneExit(t *testing.T) { + big := make([]byte, 150_000) + for i := range big { + big[i] = byte('a' + i%26) + } + runner := &fakeRunner{stdout: big, stderr: []byte("warning\n"), code: 3} + s := start(t, runner) + + stream, err := s.commands.Run(t.Context(), &pluginv1.CommandRequest{ + Name: "ssh", Arguments: []string{"key", "list"}, Settings: object(t, map[string]any{"root": "/data"}), + }) + require.NoError(t, err) + stdout, stderr, exits, maxChunk := collect(t, stream) + + assert.Equal(t, big, stdout) + assert.Equal(t, "warning\n", string(stderr)) + assert.Equal(t, []uint32{3}, exits, "exactly one exit event") + assert.LessOrEqual(t, maxChunk, 64<<10) + assert.Equal(t, []string{"key", "list"}, runner.gotArgs) + assert.Equal(t, map[string]any{"root": "/data"}, runner.gotSettings) +} + +func TestCommandExitCodesAreClampedToTheProtocolRange(t *testing.T) { + for in, want := range map[int]uint32{0: 0, 1: 1, 255: 255, 256: 255, -1: 255, 4000: 255} { + s := start(t, &fakeRunner{code: in}) + + stream, err := s.commands.Run(t.Context(), &pluginv1.CommandRequest{}) + require.NoError(t, err) + _, _, exits, _ := collect(t, stream) + + assert.Equal(t, []uint32{want}, exits, "exit %d", in) + } +} + +func TestACommandWithNoOutputStillEndsWithAnExit(t *testing.T) { + s := start(t, &fakeRunner{}) + ctx, cancel := context.WithTimeout(t.Context(), 5*time.Second) + defer cancel() + + stream, err := s.commands.Run(ctx, &pluginv1.CommandRequest{}) + require.NoError(t, err) + _, _, exits, _ := collect(t, stream) + + assert.Equal(t, []uint32{0}, exits) +} diff --git a/plugins/ssh/schemas/command.json b/plugins/ssh/schemas/command.json new file mode 100644 index 00000000000..1ccaa1e4415 --- /dev/null +++ b/plugins/ssh/schemas/command.json @@ -0,0 +1,14 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "title": "ssh command settings", + "description": "Settings under plugins.packages..config for the ssh command.", + "type": "object", + "additionalProperties": false, + "properties": { + "root": { + "type": "string", + "minLength": 1, + "description": "The plugin's data directory, when it is not the default. Use the same value as the identities' spec.root." + } + } +} diff --git a/plugins/ssh/schemas/ssh-key.json b/plugins/ssh/schemas/ssh-key.json new file mode 100644 index 00000000000..f499373a2dc --- /dev/null +++ b/plugins/ssh/schemas/ssh-key.json @@ -0,0 +1,106 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "title": "ssh/key identity", + "description": "An SSH key, its enrollment with an authority, and the environment that makes tools use it.", + "type": "object", + "additionalProperties": false, + "required": [ + "store", + "allow" + ], + "properties": { + "authority": { + "enum": [ + "self", + "github" + ], + "default": "self", + "description": "Who vouches for the key. self means nobody does; github registers it on the account the upstream token belongs to." + }, + "store": { + "enum": [ + "secure-enclave", + "file" + ], + "description": "Where the key is held. secure-enclave is macOS hardware; file is an ordinary key file and is not hardware-protected." + }, + "allow": { + "type": "array", + "minItems": 1, + "uniqueItems": true, + "items": { + "enum": [ + "signing", + "authentication" + ] + }, + "description": "What the key may do. It limits the identity's agent socket and decides what is enrolled." + }, + "require": { + "description": "What must hold for the key to be used. The only term is unlocked. It is fixed when the key is created.", + "oneOf": [ + { + "enum": [ + "unlocked" + ] + }, + { + "type": "array", + "uniqueItems": true, + "items": { + "enum": [ + "unlocked" + ] + } + } + ] + }, + "user": { + "type": "string", + "pattern": "^[^\\s\\x00-\\x1f\\x7f]{1,64}$", + "description": "The SSH login name on the remote side. Set as ANSIBLE_REMOTE_USER when authentication is allowed." + }, + "key": { + "type": "string", + "pattern": "^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$", + "description": "The key's name in the store. Defaults to the identity's name. Identities that share a key must agree on store and require." + }, + "rewrite_https": { + "type": "array", + "uniqueItems": true, + "items": { + "type": "string", + "pattern": "^[A-Za-z0-9]([A-Za-z0-9.-]*[A-Za-z0-9])?(:[0-9]{1,5})?$" + }, + "description": "Hosts whose HTTPS Git URLs are rewritten to SSH." + }, + "root": { + "type": "string", + "minLength": 1, + "description": "The plugin's data directory, when it is not the default. The plugin cannot see Atmos's environment, so a relocated Atmos data directory must be named here." + } + }, + "allOf": [ + { + "if": { + "properties": { + "store": { + "const": "file" + } + }, + "required": [ + "store" + ] + }, + "then": { + "properties": { + "require": { + "type": "array", + "maxItems": 0, + "description": "The file store cannot enforce any requirement. Use secure-enclave for require: unlocked." + } + } + } + } + ] +} diff --git a/plugins/ssh/schemas/ssh-self.json b/plugins/ssh/schemas/ssh-self.json new file mode 100644 index 00000000000..d8eab18a48d --- /dev/null +++ b/plugins/ssh/schemas/ssh-self.json @@ -0,0 +1,8 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "title": "ssh/self provider", + "description": "A provider with no authority: the key is self-asserted. It takes no configuration.", + "type": "object", + "additionalProperties": false, + "properties": {} +} diff --git a/plugins/ssh/service/executable.go b/plugins/ssh/service/executable.go new file mode 100644 index 00000000000..2d25d2aa200 --- /dev/null +++ b/plugins/ssh/service/executable.go @@ -0,0 +1,109 @@ +package service + +import ( + "bytes" + "crypto/sha256" + "errors" + "fmt" + "io" + "os" + "path/filepath" + "regexp" + "runtime" + "strings" + + "github.com/cloudposse/atmos/plugins/ssh/paths" +) + +const ( + stablePrefix = "atmos-ssh-" + stableMode = os.FileMode(0o755) +) + +// versionRE limits versions to characters that are safe in a file name. +var versionRE = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9._+-]*$`) + +// ErrInvalidVersion means a version cannot be used in an executable file name. +var ErrInvalidVersion = errors.New("invalid version") + +// StablePath returns where the copy of the executable for version lives: a file in the plugin's +// bin directory whose name carries the version. Unlike the installed plugin path, it does not +// change when the plugin updates, so a LaunchAgent can point at it. +func StablePath(p *paths.Paths, version string) (string, error) { + if !versionRE.MatchString(version) { + return "", fmt.Errorf("%w: %q", ErrInvalidVersion, version) + } + name := stablePrefix + version + if runtime.GOOS == "windows" { + name += ".exe" + } + return filepath.Join(p.BinDir(), name), nil +} + +// ParseStableVersion extracts the version from a path produced by StablePath. +func ParseStableVersion(exe string) (string, bool) { + base := strings.TrimSuffix(filepath.Base(exe), ".exe") + version, ok := strings.CutPrefix(base, stablePrefix) + if !ok || !versionRE.MatchString(version) { + return "", false + } + return version, true +} + +// InstallExecutable copies the running executable to its stable, versioned path and returns that +// path. +func InstallExecutable(p *paths.Paths, version string) (string, error) { + src, err := os.Executable() + if err != nil { + return "", fmt.Errorf("find the running executable: %w", err) + } + if resolved, err := filepath.EvalSymlinks(src); err == nil { + src = resolved + } + return CopyExecutable(p, src, version) +} + +// CopyExecutable copies src to the stable path for version, atomically and with mode 0755. A copy +// that is already there with the same content is left alone. +func CopyExecutable(p *paths.Paths, src, version string) (string, error) { + dst, err := StablePath(p, version) + if err != nil { + return "", err + } + data, err := os.ReadFile(src) + if err != nil { + return "", fmt.Errorf("read executable %s: %w", src, err) + } + if same, _ := sameContent(dst, data); same { + return dst, ensureMode(dst) + } + if err := os.MkdirAll(p.BinDir(), paths.DirMode); err != nil { + return "", fmt.Errorf("create %s: %w", p.BinDir(), err) + } + if err := writeFileAtomic(dst, data, stableMode); err != nil { + return "", err + } + return dst, nil +} + +// sameContent reports whether the file at path holds exactly data. +func sameContent(path string, data []byte) (bool, error) { + f, err := os.Open(path) + if err != nil { + return false, err + } + defer f.Close() + h := sha256.New() + if _, err := io.Copy(h, f); err != nil { + return false, err + } + want := sha256.Sum256(data) + return bytes.Equal(h.Sum(nil), want[:]), nil +} + +func ensureMode(path string) error { + if err := os.Chmod(path, stableMode); err != nil && runtime.GOOS != "windows" { + return fmt.Errorf("set mode on %s: %w", path, err) + } + return nil +} diff --git a/plugins/ssh/service/executable_test.go b/plugins/ssh/service/executable_test.go new file mode 100644 index 00000000000..980c81fd44c --- /dev/null +++ b/plugins/ssh/service/executable_test.go @@ -0,0 +1,171 @@ +package service + +import ( + "context" + "os" + "path/filepath" + "runtime" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestMain(m *testing.M) { + // The test binary doubles as a cross-platform command for ExecRunner tests. + if mode := os.Getenv("_ATMOS_SERVICE_TEST_MODE"); mode != "" { + switch mode { + case "exit3": + os.Stderr.WriteString("boom") + os.Exit(3) + case "env": + for _, kv := range os.Environ() { + os.Stdout.WriteString(kv + "\n") + } + os.Exit(0) + } + } + os.Exit(m.Run()) +} + +func TestStablePath(t *testing.T) { + p, _ := testPaths(t) + got, err := StablePath(p, "1.2.3") + require.NoError(t, err) + name := "atmos-ssh-1.2.3" + if runtime.GOOS == "windows" { + name += ".exe" + } + assert.Equal(t, filepath.Join(p.BinDir(), name), got) + + for _, bad := range []string{"", "../x", "a/b", "a b", ".x"} { + _, err := StablePath(p, bad) + require.ErrorIs(t, err, ErrInvalidVersion, "version %q", bad) + } +} + +func TestParseStableVersion(t *testing.T) { + p, _ := testPaths(t) + path, err := StablePath(p, "0.9.0-rc.1+build5") + require.NoError(t, err) + v, ok := ParseStableVersion(path) + require.True(t, ok) + assert.Equal(t, "0.9.0-rc.1+build5", v) + + for _, other := range []string{"/x/plugin", "/x/atmos-ssh-", ""} { + _, ok := ParseStableVersion(other) + assert.False(t, ok, other) + } +} + +func TestCopyExecutable(t *testing.T) { + p, _ := testPaths(t) + src := filepath.Join(t.TempDir(), "plugin") + require.NoError(t, os.WriteFile(src, []byte("binary v1"), 0o644)) + + dst, err := CopyExecutable(p, src, "1.0.0") + require.NoError(t, err) + got, err := os.ReadFile(dst) + require.NoError(t, err) + assert.Equal(t, "binary v1", string(got)) + if runtime.GOOS != "windows" { + info, err := os.Stat(dst) + require.NoError(t, err) + assert.Equal(t, os.FileMode(0o755), info.Mode().Perm()) + dirInfo, err := os.Stat(p.BinDir()) + require.NoError(t, err) + assert.Equal(t, os.FileMode(0o700), dirInfo.Mode().Perm()) + } + entries, err := os.ReadDir(p.BinDir()) + require.NoError(t, err) + require.Len(t, entries, 1, "no temporary files left behind") +} + +func TestCopyExecutableSkipsIdenticalAndReplacesChanged(t *testing.T) { + p, _ := testPaths(t) + src := filepath.Join(t.TempDir(), "plugin") + require.NoError(t, os.WriteFile(src, []byte("same"), 0o644)) + dst, err := CopyExecutable(p, src, "1.0.0") + require.NoError(t, err) + before, err := os.Stat(dst) + require.NoError(t, err) + + _, err = CopyExecutable(p, src, "1.0.0") + require.NoError(t, err) + after, err := os.Stat(dst) + require.NoError(t, err) + assert.True(t, os.SameFile(before, after), "identical content is not rewritten") + + require.NoError(t, os.WriteFile(src, []byte("changed"), 0o644)) + _, err = CopyExecutable(p, src, "1.0.0") + require.NoError(t, err) + got, err := os.ReadFile(dst) + require.NoError(t, err) + assert.Equal(t, "changed", string(got)) +} + +func TestCopyExecutableErrors(t *testing.T) { + p, _ := testPaths(t) + _, err := CopyExecutable(p, filepath.Join(t.TempDir(), "missing"), "1.0.0") + require.ErrorIs(t, err, os.ErrNotExist) + _, err = CopyExecutable(p, os.Args[0], "bad version") + require.ErrorIs(t, err, ErrInvalidVersion) +} + +func TestInstallExecutableCopiesTheRunningBinary(t *testing.T) { + p, _ := testPaths(t) + dst, err := InstallExecutable(p, "7.7.7") + require.NoError(t, err) + + self, err := os.Executable() + require.NoError(t, err) + want, err := os.ReadFile(self) + require.NoError(t, err) + got, err := os.ReadFile(dst) + require.NoError(t, err) + assert.Equal(t, want, got) + assert.Equal(t, p.BinDir(), filepath.Dir(dst)) +} + +func TestExecRunner(t *testing.T) { + self, err := os.Executable() + require.NoError(t, err) + r := ExecRunner{} + + t.Run("non-zero exit is not an error", func(t *testing.T) { + out, err := r.Run(context.Background(), Command{Name: self, Env: []string{"_ATMOS_SERVICE_TEST_MODE=exit3"}}) + require.NoError(t, err) + assert.Equal(t, 3, out.ExitCode) + // A binary built with -cover adds a GOCOVERDIR warning to stderr when run with this exact environment. + assert.Contains(t, out.Stderr, "boom") + }) + t.Run("environment is exactly the one given", func(t *testing.T) { + t.Setenv("LEAK_CHECK", "leaked") + out, err := r.Run(context.Background(), Command{Name: self, Env: []string{"_ATMOS_SERVICE_TEST_MODE=env", "ONLY=this"}}) + require.NoError(t, err) + assert.Contains(t, out.Stdout, "ONLY=this") + assert.NotContains(t, out.Stdout, "LEAK_CHECK") + }) + t.Run("missing program is an error", func(t *testing.T) { + _, err := r.Run(context.Background(), Command{Name: filepath.Join(t.TempDir(), "nope")}) + require.Error(t, err) + }) +} + +func TestUnsupportedPlatform(t *testing.T) { + p, _ := testPaths(t) + m, err := newForOS("windows", Options{Paths: p}) + require.NoError(t, err) + ctx := context.Background() + require.ErrorIs(t, m.Install(ctx, Spec{Executable: "/x"}), ErrUnsupportedPlatform) + require.ErrorIs(t, m.Start(ctx), ErrUnsupportedPlatform) + require.ErrorIs(t, m.Stop(ctx), ErrUnsupportedPlatform) + require.ErrorIs(t, m.Uninstall(ctx), ErrUnsupportedPlatform) + _, err = m.Status(ctx) + require.ErrorIs(t, err, ErrUnsupportedPlatform) +} + +func TestNewRequiresPaths(t *testing.T) { + _, err := New(Options{}) + require.ErrorIs(t, err, ErrInvalidSpec) +} diff --git a/plugins/ssh/service/fakes_test.go b/plugins/ssh/service/fakes_test.go new file mode 100644 index 00000000000..1b81804ea0d --- /dev/null +++ b/plugins/ssh/service/fakes_test.go @@ -0,0 +1,55 @@ +package service + +import ( + "context" + "path/filepath" + "strings" + "sync" + "testing" + "time" + + "github.com/stretchr/testify/require" + + "github.com/cloudposse/atmos/plugins/ssh/paths" +) + +// fakeRunner records commands and answers them from a script. It never runs anything. +type fakeRunner struct { + mu sync.Mutex + calls []Command + // reply decides each result from the command line ("name arg arg"). + reply func(line string, n int) Output +} + +func (f *fakeRunner) Run(_ context.Context, c Command) (Output, error) { + f.mu.Lock() + defer f.mu.Unlock() + f.calls = append(f.calls, c) + if f.reply == nil { + return Output{}, nil + } + return f.reply(line(c), len(f.calls)), nil +} + +func line(c Command) string { return strings.Join(append([]string{c.Name}, c.Args...), " ") } + +func (f *fakeRunner) lines() []string { + f.mu.Lock() + defer f.mu.Unlock() + out := make([]string, len(f.calls)) + for i, c := range f.calls { + out[i] = line(c) + } + return out +} + +// testPaths returns Paths under a temporary root and a definition directory beside it. +func testPaths(t *testing.T) (*paths.Paths, string) { + t.Helper() + root := t.TempDir() + p, err := paths.New(filepath.Join(root, "ssh")) + require.NoError(t, err) + return p, filepath.Join(root, "definitions") +} + +func noPause(context.Context, time.Duration) error { return nil } diff --git a/plugins/ssh/service/launchd.go b/plugins/ssh/service/launchd.go new file mode 100644 index 00000000000..eb28f4e27ac --- /dev/null +++ b/plugins/ssh/service/launchd.go @@ -0,0 +1,233 @@ +package service + +import ( + "bytes" + "context" + "encoding/xml" + "errors" + "fmt" + "html" + "os" + "path/filepath" + "regexp" + "strconv" + "time" + + "github.com/cloudposse/atmos/plugins/ssh/paths" +) + +const ( + // Label is the launchd label of the agent service. + Label = "com.cloudposse.atmos.ssh-agent" + // LaunchctlPath is where launchctl lives. The plugin has no PATH, so it is used as is. + LaunchctlPath = "/bin/launchctl" + + plistMode = os.FileMode(0o644) + // unloadWait bounds how long Install waits for launchd to finish a bootout. + unloadAttempts = 30 + unloadPause = 100 * time.Millisecond +) + +var ( + pidRE = regexp.MustCompile(`(?m)^\s*pid = (\d+)\s*$`) + programRE = regexp.MustCompile(`(?s)ProgramArguments\s*\s*([^<]*)`) +) + +// launchd drives a LaunchAgent with launchctl. +type launchd struct { + opts Options + plist string + pause func(context.Context, time.Duration) error +} + +func newLaunchd(opts Options) (Manager, error) { + dir := opts.DefinitionDir + if dir == "" { + home, err := paths.HomeDir() + if err != nil { + return nil, err + } + dir = filepath.Join(home, "Library", "LaunchAgents") + } + return &launchd{opts: opts, plist: filepath.Join(dir, Label+".plist"), pause: sleepContext}, nil +} + +func sleepContext(ctx context.Context, d time.Duration) error { + t := time.NewTimer(d) + defer t.Stop() + select { + case <-ctx.Done(): + return ctx.Err() + case <-t.C: + return nil + } +} + +func (l *launchd) domain() string { return "gui/" + strconv.Itoa(l.opts.UID) } +func (l *launchd) target() string { return l.domain() + "/" + Label } + +func (l *launchd) run(ctx context.Context, args ...string) (Output, error) { + return l.opts.Runner.Run(ctx, Command{Name: LaunchctlPath, Args: args, Env: []string{}}) +} + +// loaded reports whether launchd knows the service, and returns the print output. +func (l *launchd) loaded(ctx context.Context) (bool, Output, error) { + out, err := l.run(ctx, "print", l.target()) + if err != nil { + return false, out, err + } + return out.ExitCode == 0, out, nil +} + +func (l *launchd) installed() bool { + _, err := os.Stat(l.plist) + return err == nil +} + +// Install writes the plist and (re)loads the service, which starts it. +func (l *launchd) Install(ctx context.Context, spec Spec) error { + if err := spec.validate(); err != nil { + return err + } + if err := l.opts.Paths.EnsureDirs(); err != nil { + return err + } + data := renderPlist(spec, l.opts.Paths.ServiceLogFile()) + if err := writeFileAtomic(l.plist, data, plistMode); err != nil { + return err + } + if err := l.unload(ctx); err != nil { + return err + } + return l.bootstrap(ctx) +} + +func (l *launchd) bootstrap(ctx context.Context) error { + out, err := l.run(ctx, "bootstrap", l.domain(), l.plist) + if err != nil { + return err + } + if out.ExitCode != 0 { + return failure("launchctl bootstrap", out) + } + return nil +} + +// unload boots the service out when it is loaded and waits until launchd has let go of it. +func (l *launchd) unload(ctx context.Context) error { + ok, _, err := l.loaded(ctx) + if err != nil || !ok { + return err + } + out, err := l.run(ctx, "bootout", l.target()) + if err != nil { + return err + } + if out.ExitCode != 0 { + return failure("launchctl bootout", out) + } + for range unloadAttempts { + ok, _, err := l.loaded(ctx) + if err != nil || !ok { + return err + } + if err := l.pause(ctx, unloadPause); err != nil { + return err + } + } + return fmt.Errorf("%w: launchd still has %s loaded after bootout", ErrCommandFailed, Label) +} + +// Start loads the service if it is not loaded. +func (l *launchd) Start(ctx context.Context) error { + if !l.installed() { + return fmt.Errorf("%w: %s", ErrNotInstalled, l.plist) + } + ok, _, err := l.loaded(ctx) + if err != nil || ok { + return err + } + return l.bootstrap(ctx) +} + +// Stop boots the service out. With KeepAlive set, that is the only way to keep it down. +func (l *launchd) Stop(ctx context.Context) error { return l.unload(ctx) } + +// Uninstall boots the service out and deletes the plist. +func (l *launchd) Uninstall(ctx context.Context) error { + if err := l.unload(ctx); err != nil { + return err + } + if err := os.Remove(l.plist); err != nil && !errors.Is(err, os.ErrNotExist) { + return fmt.Errorf("remove %s: %w", l.plist, err) + } + return nil +} + +// Status reports the service's state. +func (l *launchd) Status(ctx context.Context) (Status, error) { + st := Status{DefinitionPath: l.plist, LogFile: l.opts.Paths.ServiceLogFile(), Installed: l.installed()} + if st.Installed { + if data, err := os.ReadFile(l.plist); err == nil { + st.Executable = programFromPlist(data) + } + } + ok, out, err := l.loaded(ctx) + if err != nil { + return st, err + } + st.Loaded = ok + if ok { + if m := pidRE.FindStringSubmatch(out.Stdout); m != nil { + st.PID, _ = strconv.Atoi(m[1]) + } + st.Running = st.PID > 0 + } + fillVersions(&st, l.opts.Paths) + return st, nil +} + +// programFromPlist returns the first ProgramArguments entry of a plist this package wrote. +func programFromPlist(data []byte) string { + m := programRE.FindSubmatch(data) + if m == nil { + return "" + } + return html.UnescapeString(string(m[1])) +} + +// renderPlist produces the LaunchAgent property list. +func renderPlist(spec Spec, logFile string) []byte { + var b bytes.Buffer + b.WriteString(` + + + + Label + ` + Label + ` + ProgramArguments + +`) + for _, arg := range append([]string{spec.Executable}, spec.Args...) { + b.WriteString("\t\t" + xmlEscape(arg) + "\n") + } + b.WriteString(` + RunAtLoad + + KeepAlive + + StandardOutPath + ` + xmlEscape(logFile) + ` + StandardErrorPath + ` + xmlEscape(logFile) + ` + + +`) + return b.Bytes() +} + +func xmlEscape(s string) string { + var b bytes.Buffer + _ = xml.EscapeText(&b, []byte(s)) + return b.String() +} diff --git a/plugins/ssh/service/launchd_test.go b/plugins/ssh/service/launchd_test.go new file mode 100644 index 00000000000..50c70d7787a --- /dev/null +++ b/plugins/ssh/service/launchd_test.go @@ -0,0 +1,251 @@ +package service + +import ( + "context" + "os" + "path/filepath" + "strconv" + "strings" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/cloudposse/atmos/plugins/ssh/agent" +) + +const ( + testUID = 501 + target = "gui/501/com.cloudposse.atmos.ssh-agent" + domain = "gui/501" +) + +func newTestLaunchd(t *testing.T, runner Runner) (*launchd, string) { + t.Helper() + p, defs := testPaths(t) + m, err := newForOS("darwin", Options{Paths: p, Runner: runner, DefinitionDir: defs, UID: testUID}) + require.NoError(t, err) + l := m.(*launchd) + l.pause = noPause + return l, defs +} + +// launchctlState scripts a launchctl whose loaded state flips on bootstrap and bootout. +type launchctlState struct { + loaded bool + pid int +} + +func (s *launchctlState) reply(line string, _ int) Output { + switch { + case strings.HasPrefix(line, LaunchctlPath+" print "): + if !s.loaded { + return Output{ExitCode: 113, Stderr: "Could not find service"} + } + out := "com.cloudposse.atmos.ssh-agent = {\n\tactive count = 1\n\tstate = running\n" + if s.pid > 0 { + out += "\tpid = " + itoa(s.pid) + "\n" + } + return Output{Stdout: out + "}\n"} + case strings.HasPrefix(line, LaunchctlPath+" bootstrap "): + s.loaded = true + case strings.HasPrefix(line, LaunchctlPath+" bootout "): + s.loaded = false + } + return Output{} +} + +func itoa(n int) string { return strconv.Itoa(n) } + +func TestRenderPlist(t *testing.T) { + spec := Spec{Executable: "/Users/me/.local/share/atmos/ssh/bin/atmos-ssh-1.2.3", Args: []string{"agent-serve", "--config", "/a&b/.json"}} + got := string(renderPlist(spec, "/Users/me/log file.log")) + + for _, want := range []string{ + "Label\n\tcom.cloudposse.atmos.ssh-agent", + "/Users/me/.local/share/atmos/ssh/bin/atmos-ssh-1.2.3", + "agent-serve", + "--config", + "/a&b/<c>.json", + "RunAtLoad\n\t", + "KeepAlive\n\t", + "StandardOutPath\n\t/Users/me/log file.log", + "StandardErrorPath\n\t/Users/me/log file.log", + } { + assert.Contains(t, got, want) + } + assert.Equal(t, spec.Executable, programFromPlist([]byte(got))) +} + +func TestProgramFromPlistUnescapes(t *testing.T) { + spec := Spec{Executable: "/x/a&b/atmos-ssh-1"} + assert.Equal(t, "/x/a&b/atmos-ssh-1", programFromPlist(renderPlist(spec, "/l"))) + assert.Equal(t, "", programFromPlist([]byte(""))) +} + +func TestLaunchdInstallFresh(t *testing.T) { + st := &launchctlState{} + runner := &fakeRunner{reply: st.reply} + l, defs := newTestLaunchd(t, runner) + spec := Spec{Executable: filepath.Join(t.TempDir(), "atmos-ssh-1.0.0"), Args: []string{"agent-serve"}} + + require.NoError(t, l.Install(context.Background(), spec)) + + plist := filepath.Join(defs, Label+".plist") + assert.Equal(t, []string{ + LaunchctlPath + " print " + target, + LaunchctlPath + " bootstrap " + domain + " " + plist, + }, runner.lines()) + data, err := os.ReadFile(plist) + require.NoError(t, err) + assert.Equal(t, string(renderPlist(spec, l.opts.Paths.ServiceLogFile())), string(data)) + for _, c := range runner.calls { + assert.Empty(t, c.Env, "launchctl runs with an empty environment") + } +} + +func TestLaunchdInstallReplacesLoadedService(t *testing.T) { + st := &launchctlState{loaded: true} + runner := &fakeRunner{reply: st.reply} + l, defs := newTestLaunchd(t, runner) + + require.NoError(t, l.Install(context.Background(), Spec{Executable: "/x/atmos-ssh-2.0.0"})) + + plist := filepath.Join(defs, Label+".plist") + assert.Equal(t, []string{ + LaunchctlPath + " print " + target, + LaunchctlPath + " bootout " + target, + LaunchctlPath + " print " + target, + LaunchctlPath + " bootstrap " + domain + " " + plist, + }, runner.lines()) +} + +func TestLaunchdInstallReportsBootstrapFailure(t *testing.T) { + runner := &fakeRunner{reply: func(line string, _ int) Output { + if strings.Contains(line, " bootstrap ") { + return Output{ExitCode: 5, Stderr: "Bootstrap failed: 5: Input/output error"} + } + return Output{ExitCode: 113} + }} + l, _ := newTestLaunchd(t, runner) + err := l.Install(context.Background(), Spec{Executable: "/x/atmos-ssh-2.0.0"}) + require.ErrorIs(t, err, ErrCommandFailed) + assert.Contains(t, err.Error(), "Input/output error") +} + +func TestLaunchdInstallRejectsRelativeExecutable(t *testing.T) { + runner := &fakeRunner{} + l, defs := newTestLaunchd(t, runner) + require.ErrorIs(t, l.Install(context.Background(), Spec{Executable: "atmos-ssh"}), ErrInvalidSpec) + assert.Empty(t, runner.lines()) + _, err := os.Stat(defs) + require.ErrorIs(t, err, os.ErrNotExist, "nothing is written") +} + +func TestLaunchdStartStop(t *testing.T) { + st := &launchctlState{} + runner := &fakeRunner{reply: st.reply} + l, defs := newTestLaunchd(t, runner) + ctx := context.Background() + + require.ErrorIs(t, l.Start(ctx), ErrNotInstalled) + assert.Empty(t, runner.lines()) + + require.NoError(t, os.MkdirAll(defs, 0o755)) + plist := filepath.Join(defs, Label+".plist") + require.NoError(t, os.WriteFile(plist, renderPlist(Spec{Executable: "/x/atmos-ssh-1"}, "/l"), 0o644)) + + require.NoError(t, l.Start(ctx)) + assert.Equal(t, []string{ + LaunchctlPath + " print " + target, + LaunchctlPath + " bootstrap " + domain + " " + plist, + }, runner.lines()) + + runner.calls = nil + require.NoError(t, l.Start(ctx), "already loaded") + assert.Equal(t, []string{LaunchctlPath + " print " + target}, runner.lines()) + + runner.calls = nil + require.NoError(t, l.Stop(ctx)) + assert.Equal(t, []string{ + LaunchctlPath + " print " + target, + LaunchctlPath + " bootout " + target, + LaunchctlPath + " print " + target, + }, runner.lines()) + + runner.calls = nil + require.NoError(t, l.Stop(ctx), "already stopped") + assert.Equal(t, []string{LaunchctlPath + " print " + target}, runner.lines()) +} + +func TestLaunchdUninstall(t *testing.T) { + st := &launchctlState{loaded: true} + runner := &fakeRunner{reply: st.reply} + l, defs := newTestLaunchd(t, runner) + require.NoError(t, os.MkdirAll(defs, 0o755)) + plist := filepath.Join(defs, Label+".plist") + require.NoError(t, os.WriteFile(plist, []byte("x"), 0o644)) + + require.NoError(t, l.Uninstall(context.Background())) + _, err := os.Stat(plist) + require.ErrorIs(t, err, os.ErrNotExist) + assert.Contains(t, runner.lines(), LaunchctlPath+" bootout "+target) + + require.NoError(t, l.Uninstall(context.Background()), "uninstalling twice is fine") +} + +func TestLaunchdStatusVersions(t *testing.T) { + tests := []struct { + name string + installed string + statePID int + stateVer string + wantRunning bool + wantDaemon string + wantMismatch bool + }{ + {"same version", "2.0.0", 777, "2.0.0", true, "2.0.0", false}, + {"older daemon", "2.0.0", 777, "1.0.0", true, "1.0.0", true}, + {"stale state from another pid", "2.0.0", 111, "1.0.0", true, "", false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + st := &launchctlState{loaded: true, pid: 7} + runner := &fakeRunner{reply: func(line string, n int) Output { + out := st.reply(line, n) + out.Stdout = strings.Replace(out.Stdout, "pid = 7", "pid = 777", 1) + return out + }} + l, defs := newTestLaunchd(t, runner) + p := l.opts.Paths + require.NoError(t, os.MkdirAll(defs, 0o755)) + exe, err := StablePath(p, tt.installed) + require.NoError(t, err) + require.NoError(t, os.WriteFile(filepath.Join(defs, Label+".plist"), renderPlist(Spec{Executable: exe}, "/l"), 0o644)) + require.NoError(t, agent.WriteState(p.StateFile(), agent.State{PID: tt.statePID, Version: tt.stateVer, Started: time.Now()})) + + got, err := l.Status(context.Background()) + require.NoError(t, err) + assert.True(t, got.Installed) + assert.True(t, got.Loaded) + assert.Equal(t, tt.wantRunning, got.Running) + assert.Equal(t, 777, got.PID) + assert.Equal(t, exe, got.Executable) + assert.Equal(t, tt.installed, got.InstalledVersion) + assert.Equal(t, tt.wantDaemon, got.DaemonVersion) + assert.Equal(t, tt.wantMismatch, got.VersionMismatch) + }) + } +} + +func TestLaunchdStatusNotInstalled(t *testing.T) { + runner := &fakeRunner{reply: (&launchctlState{}).reply} + l, _ := newTestLaunchd(t, runner) + got, err := l.Status(context.Background()) + require.NoError(t, err) + assert.False(t, got.Installed) + assert.False(t, got.Loaded) + assert.False(t, got.Running) + assert.False(t, got.VersionMismatch) +} diff --git a/plugins/ssh/service/service.go b/plugins/ssh/service/service.go new file mode 100644 index 00000000000..ac18b4d4e95 --- /dev/null +++ b/plugins/ssh/service/service.go @@ -0,0 +1,198 @@ +// Package service manages the per-user background service that runs the SSH agent daemon: a +// LaunchAgent on macOS and a systemd user unit on Linux. +// +// Atmos kills the plugin's whole process group when an invocation ends, so the agent can never be +// a child of a plugin call. launchd or systemd starts it instead, running a stable copy of the +// plugin executable in daemon mode. Every external command goes through a Runner, so tests never +// run launchctl or systemctl. +package service + +import ( + "context" + "errors" + "fmt" + "os" + "os/exec" + "runtime" + + "github.com/cloudposse/atmos/plugins/ssh/paths" +) + +// Sentinel errors. Wrap them with fmt.Errorf("%w ...") and test with errors.Is. +var ( + // ErrUnsupportedPlatform means there is no service manager for this operating system. + ErrUnsupportedPlatform = errors.New("managing the agent service is not supported on this platform") + // ErrNotInstalled means the service definition does not exist. + ErrNotInstalled = errors.New("agent service is not installed") + // ErrInvalidSpec means an install request is incomplete or unsafe. + ErrInvalidSpec = errors.New("invalid service specification") + // ErrCommandFailed means a service manager command exited with a failure. + ErrCommandFailed = errors.New("service manager command failed") + // ErrNoSystemctl means systemctl was not found in any known location. + ErrNoSystemctl = errors.New("systemctl not found") +) + +// Spec says what the service runs. +type Spec struct { + // Executable is the absolute path of the stable copy of the plugin executable (see + // InstallExecutable). It must not be a path that changes on update. + Executable string + // Args are the arguments that put the executable into daemon mode. + Args []string +} + +// validate checks that the spec can be written into a service definition. +func (s Spec) validate() error { + if s.Executable == "" || !isAbs(s.Executable) { + return fmt.Errorf("%w: executable must be an absolute path, got %q", ErrInvalidSpec, s.Executable) + } + return nil +} + +// Status describes the service as the service manager and the daemon's state file report it. +type Status struct { + // Installed is true when the service definition exists. + Installed bool + // Loaded is true when the service manager knows the service. + Loaded bool + // Running is true when the daemon process is up. + Running bool + // PID is the daemon's process id when Running, else 0. + PID int + // Executable is the executable the installed definition runs. + Executable string + // InstalledVersion is the version of that executable, read from its stable file name. + InstalledVersion string + // DaemonVersion is the version the running daemon recorded in the state file. It is empty when + // the daemon is not running or its state file does not belong to the running process. + DaemonVersion string + // VersionMismatch is true when the running daemon is a different version from the installed one. + VersionMismatch bool + // DefinitionPath is where the definition lives. + DefinitionPath string + // LogFile is where the daemon's output goes. + LogFile string +} + +// Manager installs and drives the per-user service. +type Manager interface { + // Install writes the service definition and (re)starts the service with it. + Install(ctx context.Context, spec Spec) error + // Start starts an installed service. + Start(ctx context.Context) error + // Stop stops the service, and keeps it stopped until Start or the next login. + Stop(ctx context.Context) error + // Status reports the service's state. + Status(ctx context.Context) (Status, error) + // Uninstall stops the service and removes its definition. + Uninstall(ctx context.Context) error +} + +// Command is one external command to run. +type Command struct { + // Name is the absolute path of the program. + Name string + Args []string + // Env is the complete environment of the command. The plugin has none of its own. + Env []string +} + +// Output is what a command printed and how it exited. +type Output struct { + Stdout string + Stderr string + ExitCode int +} + +// Runner runs external commands. A command that starts and exits non-zero is reported through +// Output.ExitCode, not as an error; the error is for failing to run it at all. +type Runner interface { + Run(ctx context.Context, cmd Command) (Output, error) +} + +// Options configures New. +type Options struct { + // Paths locates the state file, the log file and the stable executables. Required. + Paths *paths.Paths + // Runner runs launchctl and systemctl. It defaults to ExecRunner. + Runner Runner + // DefinitionDir overrides where the plist or unit is written. It defaults to + // ~/Library/LaunchAgents on macOS and ~/.config/systemd/user on Linux. Tests set it. + DefinitionDir string + // UID overrides the user id used for the launchd domain and the systemd runtime directory. + UID int + // FindExecutable finds the first existing file among candidates. It defaults to a stat check. + FindExecutable func(candidates []string) (string, bool) +} + +// New returns the Manager for the current operating system. On any other system it returns a +// Manager whose methods all fail with ErrUnsupportedPlatform. +func New(opts Options) (Manager, error) { + return newForOS(runtime.GOOS, opts) +} + +func newForOS(goos string, opts Options) (Manager, error) { + if opts.Paths == nil { + return nil, fmt.Errorf("%w: Options.Paths is required", ErrInvalidSpec) + } + if opts.Runner == nil { + opts.Runner = ExecRunner{} + } + if opts.FindExecutable == nil { + opts.FindExecutable = findExisting + } + if opts.UID == 0 { + opts.UID = os.Getuid() + } + switch goos { + case "darwin": + return newLaunchd(opts) + case "linux": + return newSystemd(opts) + default: + return unsupported{}, nil + } +} + +// findExisting returns the first candidate that is a regular, executable file. +func findExisting(candidates []string) (string, bool) { + for _, c := range candidates { + if info, err := os.Stat(c); err == nil && info.Mode().IsRegular() && info.Mode().Perm()&0o111 != 0 { + return c, true + } + } + return "", false +} + +// ExecRunner runs commands with os/exec, using exactly the environment in the Command. +type ExecRunner struct{} + +// Run implements Runner. +func (ExecRunner) Run(ctx context.Context, c Command) (Output, error) { + cmd := exec.CommandContext(ctx, c.Name, c.Args...) + cmd.Env = append([]string{}, c.Env...) + var stdout, stderr limitedBuffer + cmd.Stdout, cmd.Stderr = &stdout, &stderr + err := cmd.Run() + out := Output{Stdout: stdout.String(), Stderr: stderr.String()} + var exitErr *exec.ExitError + if errors.As(err, &exitErr) { + out.ExitCode = exitErr.ExitCode() + return out, nil + } + if err != nil { + return out, fmt.Errorf("run %s: %w", c.Name, err) + } + return out, nil +} + +// unsupported is the Manager on operating systems without a service manager implementation. +type unsupported struct{} + +func (unsupported) Install(context.Context, Spec) error { return ErrUnsupportedPlatform } +func (unsupported) Start(context.Context) error { return ErrUnsupportedPlatform } +func (unsupported) Stop(context.Context) error { return ErrUnsupportedPlatform } +func (unsupported) Uninstall(context.Context) error { return ErrUnsupportedPlatform } +func (unsupported) Status(context.Context) (Status, error) { + return Status{}, ErrUnsupportedPlatform +} diff --git a/plugins/ssh/service/status.go b/plugins/ssh/service/status.go new file mode 100644 index 00000000000..d085fe133ba --- /dev/null +++ b/plugins/ssh/service/status.go @@ -0,0 +1,24 @@ +package service + +import ( + "github.com/cloudposse/atmos/plugins/ssh/agent" + "github.com/cloudposse/atmos/plugins/ssh/paths" +) + +// fillVersions sets the version fields of st. The installed version comes from the stable file +// name of the installed executable. The daemon version comes from the state file, but only when +// the state file belongs to the process the service manager says is running, so a state file left +// by a crashed daemon is never mistaken for the live one. +func fillVersions(st *Status, p *paths.Paths) { + if v, ok := ParseStableVersion(st.Executable); ok { + st.InstalledVersion = v + } + if st.Running { + state, err := agent.ReadState(p.StateFile()) + if err == nil && (st.PID == 0 || state.PID == st.PID) { + st.DaemonVersion = state.Version + } + } + st.VersionMismatch = st.InstalledVersion != "" && st.DaemonVersion != "" && + st.InstalledVersion != st.DaemonVersion +} diff --git a/plugins/ssh/service/systemd.go b/plugins/ssh/service/systemd.go new file mode 100644 index 00000000000..cab2690e093 --- /dev/null +++ b/plugins/ssh/service/systemd.go @@ -0,0 +1,229 @@ +package service + +import ( + "context" + "errors" + "fmt" + "os" + "path/filepath" + "strconv" + "strings" + + "github.com/cloudposse/atmos/plugins/ssh/paths" +) + +// UnitName is the systemd user unit of the agent service. +const UnitName = "atmos-ssh-agent.service" + +const unitMode = os.FileMode(0o644) + +// systemctlCandidates are the places systemctl may live. The plugin has no PATH to search. +var systemctlCandidates = []string{ + "/usr/bin/systemctl", + "/bin/systemctl", + "/usr/local/bin/systemctl", + "/run/current-system/sw/bin/systemctl", +} + +// systemd drives a user unit with systemctl --user. +type systemd struct { + opts Options + unit string +} + +func newSystemd(opts Options) (Manager, error) { + dir := opts.DefinitionDir + if dir == "" { + home, err := paths.HomeDir() + if err != nil { + return nil, err + } + dir = filepath.Join(home, ".config", "systemd", "user") + } + return &systemd{opts: opts, unit: filepath.Join(dir, UnitName)}, nil +} + +// env is the environment systemctl --user needs to find the user's manager. The plugin's own +// environment is empty, so it is built from the user id. +func (s *systemd) env() []string { + runtimeDir := "/run/user/" + strconv.Itoa(s.opts.UID) + return []string{ + "XDG_RUNTIME_DIR=" + runtimeDir, + "DBUS_SESSION_BUS_ADDRESS=unix:path=" + runtimeDir + "/bus", + } +} + +func (s *systemd) run(ctx context.Context, args ...string) (Output, error) { + exe, ok := s.opts.FindExecutable(systemctlCandidates) + if !ok { + return Output{}, fmt.Errorf("%w: looked in %s", ErrNoSystemctl, strings.Join(systemctlCandidates, ", ")) + } + return s.opts.Runner.Run(ctx, Command{Name: exe, Args: append([]string{"--user"}, args...), Env: s.env()}) +} + +// must runs a systemctl command that has to succeed. +func (s *systemd) must(ctx context.Context, args ...string) error { + out, err := s.run(ctx, args...) + if err != nil { + return err + } + if out.ExitCode != 0 { + return failure("systemctl --user "+args[0], out) + } + return nil +} + +func (s *systemd) installed() bool { + _, err := os.Stat(s.unit) + return err == nil +} + +// Install writes the unit, enables it and restarts it so a new executable takes effect. +func (s *systemd) Install(ctx context.Context, spec Spec) error { + if err := spec.validate(); err != nil { + return err + } + if err := s.opts.Paths.EnsureDirs(); err != nil { + return err + } + if err := writeFileAtomic(s.unit, renderUnit(spec, s.opts.Paths.ServiceLogFile()), unitMode); err != nil { + return err + } + for _, args := range [][]string{{"daemon-reload"}, {"enable", UnitName}, {"restart", UnitName}} { + if err := s.must(ctx, args...); err != nil { + return err + } + } + return nil +} + +// Start starts an installed unit. +func (s *systemd) Start(ctx context.Context) error { + if !s.installed() { + return fmt.Errorf("%w: %s", ErrNotInstalled, s.unit) + } + return s.must(ctx, "start", UnitName) +} + +// Stop stops the unit. A unit that was never installed is already stopped. +func (s *systemd) Stop(ctx context.Context) error { + if !s.installed() { + return nil + } + return s.must(ctx, "stop", UnitName) +} + +// Uninstall disables and stops the unit, then deletes it. +func (s *systemd) Uninstall(ctx context.Context) error { + if !s.installed() { + return nil + } + if err := s.must(ctx, "disable", "--now", UnitName); err != nil { + return err + } + if err := os.Remove(s.unit); err != nil && !errors.Is(err, os.ErrNotExist) { + return fmt.Errorf("remove %s: %w", s.unit, err) + } + return s.must(ctx, "daemon-reload") +} + +// Status reports the unit's state. +func (s *systemd) Status(ctx context.Context) (Status, error) { + st := Status{DefinitionPath: s.unit, LogFile: s.opts.Paths.ServiceLogFile(), Installed: s.installed()} + if !st.Installed { + return st, nil + } + if data, err := os.ReadFile(s.unit); err == nil { + st.Executable = programFromUnit(data) + } + out, err := s.run(ctx, "show", UnitName, "--property=LoadState,ActiveState,MainPID") + if err != nil { + return st, err + } + if out.ExitCode != 0 { + return st, failure("systemctl --user show", out) + } + props := parseProperties(out.Stdout) + st.Loaded = props["LoadState"] == "loaded" + st.PID, _ = strconv.Atoi(props["MainPID"]) + st.Running = props["ActiveState"] == "active" && st.PID > 0 + if !st.Running { + st.PID = 0 + } + fillVersions(&st, s.opts.Paths) + return st, nil +} + +// parseProperties reads systemctl show's Key=Value lines. +func parseProperties(s string) map[string]string { + props := map[string]string{} + for _, line := range strings.Split(s, "\n") { + if k, v, ok := strings.Cut(strings.TrimSpace(line), "="); ok { + props[k] = v + } + } + return props +} + +// programFromUnit returns the executable of the first ExecStart line of a unit this package wrote. +func programFromUnit(data []byte) string { + for _, line := range strings.Split(string(data), "\n") { + rest, ok := strings.CutPrefix(line, "ExecStart=") + if !ok { + continue + } + return firstQuoted(rest) + } + return "" +} + +// firstQuoted decodes the first double-quoted word of an ExecStart value written by quoteArg. +func firstQuoted(s string) string { + if !strings.HasPrefix(s, `"`) { + return strings.Fields(s)[0] + } + var b strings.Builder + for i := 1; i < len(s); i++ { + switch c := s[i]; { + case c == '\\' && i+1 < len(s): + i++ + b.WriteByte(s[i]) + case c == '%' && i+1 < len(s) && s[i+1] == '%', c == '$' && i+1 < len(s) && s[i+1] == '$': + b.WriteByte(c) + i++ + case c == '"': + return b.String() + default: + b.WriteByte(c) + } + } + return b.String() +} + +// quoteArg quotes one argument for a systemd ExecStart line: double quotes, with backslash and +// quote escaped and the specifier and variable characters (% and $) doubled. +func quoteArg(s string) string { + r := strings.NewReplacer(`\`, `\\`, `"`, `\"`, `%`, `%%`, `$`, `$$`) + return `"` + r.Replace(s) + `"` +} + +// renderUnit produces the systemd user unit. +func renderUnit(spec Spec, logFile string) []byte { + words := make([]string, 0, 1+len(spec.Args)) + for _, w := range append([]string{spec.Executable}, spec.Args...) { + words = append(words, quoteArg(w)) + } + var b strings.Builder + b.WriteString("[Unit]\n") + b.WriteString("Description=Atmos SSH agent\n\n") + b.WriteString("[Service]\n") + b.WriteString("Type=simple\n") + b.WriteString("ExecStart=" + strings.Join(words, " ") + "\n") + b.WriteString("Restart=always\n") + b.WriteString("RestartSec=2\n") + b.WriteString("StandardOutput=append:" + logFile + "\n") + b.WriteString("StandardError=append:" + logFile + "\n\n") + b.WriteString("[Install]\n") + b.WriteString("WantedBy=default.target\n") + return []byte(b.String()) +} diff --git a/plugins/ssh/service/systemd_test.go b/plugins/ssh/service/systemd_test.go new file mode 100644 index 00000000000..1feb9b95494 --- /dev/null +++ b/plugins/ssh/service/systemd_test.go @@ -0,0 +1,217 @@ +package service + +import ( + "context" + "os" + "path/filepath" + "strings" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/cloudposse/atmos/plugins/ssh/agent" +) + +const fakeSystemctl = "/usr/bin/systemctl" + +func newTestSystemd(t *testing.T, runner Runner) (*systemd, string) { + t.Helper() + p, defs := testPaths(t) + m, err := newForOS("linux", Options{ + Paths: p, Runner: runner, DefinitionDir: defs, UID: testUID, + FindExecutable: func([]string) (string, bool) { return fakeSystemctl, true }, + }) + require.NoError(t, err) + return m.(*systemd), filepath.Join(defs, UnitName) +} + +func TestRenderUnit(t *testing.T) { + spec := Spec{ + Executable: "/home/me/.local/share/atmos/ssh/bin/atmos-ssh-1.2.3", + Args: []string{"agent-serve", "--config", `/p/with space/"q"/50%/$HOME.json`}, + } + got := string(renderUnit(spec, "/home/me/agent.log")) + + want := `[Unit] +Description=Atmos SSH agent + +[Service] +Type=simple +ExecStart="/home/me/.local/share/atmos/ssh/bin/atmos-ssh-1.2.3" "agent-serve" "--config" "/p/with space/\"q\"/50%%/$$HOME.json" +Restart=always +RestartSec=2 +StandardOutput=append:/home/me/agent.log +StandardError=append:/home/me/agent.log + +[Install] +WantedBy=default.target +` + assert.Equal(t, want, got) + assert.Equal(t, spec.Executable, programFromUnit([]byte(got))) +} + +func TestProgramFromUnitDecodesEscapes(t *testing.T) { + spec := Spec{Executable: `/odd "dir"/100%/$x/atmos-ssh-1`} + assert.Equal(t, spec.Executable, programFromUnit(renderUnit(spec, "/l"))) + assert.Equal(t, "", programFromUnit([]byte("[Unit]\n"))) +} + +func TestSystemdInstall(t *testing.T) { + runner := &fakeRunner{} + s, unit := newTestSystemd(t, runner) + spec := Spec{Executable: "/x/atmos-ssh-1.0.0", Args: []string{"agent-serve"}} + + require.NoError(t, s.Install(context.Background(), spec)) + + assert.Equal(t, []string{ + fakeSystemctl + " --user daemon-reload", + fakeSystemctl + " --user enable " + UnitName, + fakeSystemctl + " --user restart " + UnitName, + }, runner.lines()) + data, err := os.ReadFile(unit) + require.NoError(t, err) + assert.Equal(t, string(renderUnit(spec, s.opts.Paths.ServiceLogFile())), string(data)) + for _, c := range runner.calls { + assert.ElementsMatch(t, []string{ + "XDG_RUNTIME_DIR=/run/user/501", + "DBUS_SESSION_BUS_ADDRESS=unix:path=/run/user/501/bus", + }, c.Env) + } +} + +func TestSystemdInstallStopsOnFailure(t *testing.T) { + runner := &fakeRunner{reply: func(line string, _ int) Output { + if strings.HasSuffix(line, "enable "+UnitName) { + return Output{ExitCode: 1, Stderr: "Failed to connect to bus"} + } + return Output{} + }} + s, _ := newTestSystemd(t, runner) + err := s.Install(context.Background(), Spec{Executable: "/x/atmos-ssh-1"}) + require.ErrorIs(t, err, ErrCommandFailed) + assert.Contains(t, err.Error(), "Failed to connect to bus") + assert.Len(t, runner.lines(), 2, "restart is not attempted") +} + +func TestSystemdStartStop(t *testing.T) { + runner := &fakeRunner{} + s, unit := newTestSystemd(t, runner) + ctx := context.Background() + + require.ErrorIs(t, s.Start(ctx), ErrNotInstalled) + require.NoError(t, s.Stop(ctx), "stopping what is not installed is a no-op") + assert.Empty(t, runner.lines()) + + require.NoError(t, os.MkdirAll(filepath.Dir(unit), 0o755)) + require.NoError(t, os.WriteFile(unit, []byte("x"), 0o644)) + require.NoError(t, s.Start(ctx)) + require.NoError(t, s.Stop(ctx)) + assert.Equal(t, []string{ + fakeSystemctl + " --user start " + UnitName, + fakeSystemctl + " --user stop " + UnitName, + }, runner.lines()) +} + +func TestSystemdUninstall(t *testing.T) { + runner := &fakeRunner{} + s, unit := newTestSystemd(t, runner) + require.NoError(t, os.MkdirAll(filepath.Dir(unit), 0o755)) + require.NoError(t, os.WriteFile(unit, []byte("x"), 0o644)) + + require.NoError(t, s.Uninstall(context.Background())) + assert.Equal(t, []string{ + fakeSystemctl + " --user disable --now " + UnitName, + fakeSystemctl + " --user daemon-reload", + }, runner.lines()) + _, err := os.Stat(unit) + require.ErrorIs(t, err, os.ErrNotExist) + + runner.calls = nil + require.NoError(t, s.Uninstall(context.Background())) + assert.Empty(t, runner.lines()) +} + +func TestSystemdStatusVersions(t *testing.T) { + show := func(active string, pid string) *fakeRunner { + return &fakeRunner{reply: func(string, int) Output { + return Output{Stdout: "LoadState=loaded\nActiveState=" + active + "\nMainPID=" + pid + "\n"} + }} + } + tests := []struct { + name string + runner *fakeRunner + stateVer string + wantRunning bool + wantDaemon string + wantMismatch bool + }{ + {"running old daemon", show("active", "4321"), "1.0.0", true, "1.0.0", true}, + {"running current daemon", show("active", "4321"), "2.0.0", true, "2.0.0", false}, + {"inactive ignores state file", show("inactive", "0"), "1.0.0", false, "", false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + s, unit := newTestSystemd(t, tt.runner) + exe, err := StablePath(s.opts.Paths, "2.0.0") + require.NoError(t, err) + require.NoError(t, os.MkdirAll(filepath.Dir(unit), 0o755)) + require.NoError(t, os.WriteFile(unit, renderUnit(Spec{Executable: exe}, "/l"), 0o644)) + require.NoError(t, agent.WriteState(s.opts.Paths.StateFile(), agent.State{PID: 4321, Version: tt.stateVer, Started: time.Now()})) + + got, err := s.Status(context.Background()) + require.NoError(t, err) + assert.True(t, got.Installed) + assert.True(t, got.Loaded) + assert.Equal(t, tt.wantRunning, got.Running) + assert.Equal(t, exe, got.Executable) + assert.Equal(t, "2.0.0", got.InstalledVersion) + assert.Equal(t, tt.wantDaemon, got.DaemonVersion) + assert.Equal(t, tt.wantMismatch, got.VersionMismatch) + assert.Equal(t, []string{fakeSystemctl + " --user show " + UnitName + " --property=LoadState,ActiveState,MainPID"}, tt.runner.lines()) + }) + } +} + +func TestSystemdStatusNotInstalled(t *testing.T) { + runner := &fakeRunner{} + s, _ := newTestSystemd(t, runner) + got, err := s.Status(context.Background()) + require.NoError(t, err) + assert.False(t, got.Installed) + assert.Empty(t, runner.lines()) +} + +func TestSystemctlLookup(t *testing.T) { + p, defs := testPaths(t) + var asked []string + m, err := newForOS("linux", Options{ + Paths: p, Runner: &fakeRunner{}, DefinitionDir: defs, UID: testUID, + FindExecutable: func(c []string) (string, bool) { asked = c; return "", false }, + }) + require.NoError(t, err) + require.NoError(t, os.MkdirAll(defs, 0o755)) + require.NoError(t, os.WriteFile(filepath.Join(defs, UnitName), []byte("x"), 0o644)) + + require.ErrorIs(t, m.Start(context.Background()), ErrNoSystemctl) + assert.Contains(t, asked, "/usr/bin/systemctl") + assert.Contains(t, asked, "/bin/systemctl") +} + +func TestFindExisting(t *testing.T) { + dir := t.TempDir() + notExec := filepath.Join(dir, "plain") + exe := filepath.Join(dir, "tool") + require.NoError(t, os.WriteFile(notExec, []byte("x"), 0o644)) + require.NoError(t, os.WriteFile(exe, []byte("x"), 0o755)) + + got, ok := findExisting([]string{filepath.Join(dir, "missing"), dir, notExec, exe}) + if os.PathSeparator == '\\' { + t.Skip("POSIX execute bits only") + } + require.True(t, ok) + assert.Equal(t, exe, got) + _, ok = findExisting([]string{filepath.Join(dir, "missing")}) + assert.False(t, ok) +} diff --git a/plugins/ssh/service/util.go b/plugins/ssh/service/util.go new file mode 100644 index 00000000000..4767b1a5008 --- /dev/null +++ b/plugins/ssh/service/util.go @@ -0,0 +1,75 @@ +package service + +import ( + "bytes" + "fmt" + "os" + "path/filepath" + "strings" +) + +// maxCapture bounds how much of a command's output is kept. +const maxCapture = 1 << 20 + +// limitedBuffer is a bytes.Buffer that stops growing at maxCapture. +type limitedBuffer struct{ buf bytes.Buffer } + +func (b *limitedBuffer) Write(p []byte) (int, error) { + if room := maxCapture - b.buf.Len(); room > 0 { + if len(p) > room { + b.buf.Write(p[:room]) + } else { + b.buf.Write(p) + } + } + return len(p), nil +} + +func (b *limitedBuffer) String() string { return b.buf.String() } + +func isAbs(p string) bool { return filepath.IsAbs(p) } + +// writeFileAtomic writes data to path through a temporary file in the same directory. +func writeFileAtomic(path string, data []byte, mode os.FileMode) error { + dir := filepath.Dir(path) + if err := os.MkdirAll(dir, 0o755); err != nil { + return fmt.Errorf("create directory %s: %w", dir, err) + } + tmp, err := os.CreateTemp(dir, "."+filepath.Base(path)+".*") + if err != nil { + return fmt.Errorf("create temporary file: %w", err) + } + name := tmp.Name() + fail := func(err error) error { + _ = tmp.Close() + _ = os.Remove(name) + return err + } + if _, err := tmp.Write(data); err != nil { + return fail(fmt.Errorf("write %s: %w", name, err)) + } + if err := tmp.Chmod(mode); err != nil && os.PathSeparator != '\\' { + return fail(fmt.Errorf("set mode on %s: %w", name, err)) + } + if err := tmp.Sync(); err != nil { + return fail(fmt.Errorf("sync %s: %w", name, err)) + } + if err := tmp.Close(); err != nil { + _ = os.Remove(name) + return fmt.Errorf("close %s: %w", name, err) + } + if err := os.Rename(name, path); err != nil { + _ = os.Remove(name) + return fmt.Errorf("replace %s: %w", path, err) + } + return nil +} + +// failure turns a non-zero command result into an error that carries the command's own words. +func failure(what string, out Output) error { + detail := strings.TrimSpace(out.Stderr) + if detail == "" { + detail = strings.TrimSpace(out.Stdout) + } + return fmt.Errorf("%w: %s exited with %d: %s", ErrCommandFailed, what, out.ExitCode, detail) +} diff --git a/plugins/ssh/statusfile/statusfile.go b/plugins/ssh/statusfile/statusfile.go new file mode 100644 index 00000000000..83f706dbe3b --- /dev/null +++ b/plugins/ssh/statusfile/statusfile.go @@ -0,0 +1,182 @@ +// Package statusfile records the outcome of each identity's last login or logout. +// +// Atmos discards the text of plugin errors during authentication, so this file is how a user finds +// out why a login failed: "ssh key status" reads it. A status holds no credential. +package statusfile + +import ( + "encoding/json" + "errors" + "fmt" + "os" + "path/filepath" + "sort" + "strings" + "time" + + "github.com/cloudposse/atmos/plugins/ssh/paths" +) + +const ( + dirName = "status" + fileExt = ".json" + fileMode = os.FileMode(0o600) +) + +// Operation names what was running when the status was written. +const ( + OperationAuthenticate = "authenticate" + OperationLogout = "logout" +) + +// ErrNotFound means an identity has no status file. +var ErrNotFound = errors.New("no status recorded") + +// Status is the result of an identity's last login or logout. +type Status struct { + // Identity is the Atmos identity's name. + Identity string `json:"identity"` + // Operation is OperationAuthenticate or OperationLogout. + Operation string `json:"operation"` + // Time is when the operation finished. + Time time.Time `json:"time"` + // Success is false when the operation failed. + Success bool `json:"success"` + // Outcome is the reconcile outcome ("unchanged", "enrolled", ...) or "failed". + Outcome string `json:"outcome"` + // Key and Store name the identity's key. + Key string `json:"key,omitempty"` + Store string `json:"store,omitempty"` + // Require lists the requirement terms the identity asked for. + Require []string `json:"require,omitempty"` + // Authority and Subject say who vouches for the key. + Authority string `json:"authority,omitempty"` + Subject string `json:"subject,omitempty"` + // Allow lists the uses the identity asked for. + Allow []string `json:"allow,omitempty"` + // Added, Removed and Revoked say what changed at the authority. + Added []string `json:"added,omitempty"` + Removed []string `json:"removed,omitempty"` + Revoked []string `json:"revoked,omitempty"` + // Code is a short, stable name for the failure, and Error says what to do about it. + Code string `json:"code,omitempty"` + Error string `json:"error,omitempty"` + // Warnings are problems that did not stop the operation. + Warnings []string `json:"warnings,omitempty"` +} + +// Dir is the directory that holds the status files. +func Dir(p *paths.Paths) string { return filepath.Join(p.Root(), dirName) } + +// Path returns the status file of identity. +func Path(p *paths.Paths, identity string) (string, error) { + if err := paths.ValidateIdentity(identity); err != nil { + return "", err + } + return filepath.Join(Dir(p), identity+fileExt), nil +} + +// Write stores s atomically with mode 0600, replacing the identity's previous status. +func Write(p *paths.Paths, s Status) error { + path, err := Path(p, s.Identity) + if err != nil { + return err + } + data, err := json.MarshalIndent(s, "", " ") + if err != nil { + return fmt.Errorf("encode status: %w", err) + } + if err := os.MkdirAll(filepath.Dir(path), paths.DirMode); err != nil { + return fmt.Errorf("create %s: %w", filepath.Dir(path), err) + } + tmp, err := os.CreateTemp(filepath.Dir(path), ".status-*") + if err != nil { + return fmt.Errorf("create temporary status file: %w", err) + } + name := tmp.Name() + if err := writeAndClose(tmp, append(data, '\n')); err != nil { + _ = os.Remove(name) + return err + } + if err := os.Rename(name, path); err != nil { + _ = os.Remove(name) + return fmt.Errorf("replace %s: %w", path, err) + } + return nil +} + +func writeAndClose(f *os.File, data []byte) error { + // Chmod is a no-op error on Windows; the directory is private anyway. + _ = f.Chmod(fileMode) + if _, err := f.Write(data); err != nil { + _ = f.Close() + return fmt.Errorf("write %s: %w", f.Name(), err) + } + if err := f.Close(); err != nil { + return fmt.Errorf("close %s: %w", f.Name(), err) + } + return nil +} + +// Read returns the identity's status, or ErrNotFound. +func Read(p *paths.Paths, identity string) (Status, error) { + path, err := Path(p, identity) + if err != nil { + return Status{}, err + } + return readFile(path) +} + +func readFile(path string) (Status, error) { + data, err := os.ReadFile(path) + if errors.Is(err, os.ErrNotExist) { + return Status{}, fmt.Errorf("%w: %s", ErrNotFound, path) + } + if err != nil { + return Status{}, fmt.Errorf("read status: %w", err) + } + var s Status + if err := json.Unmarshal(data, &s); err != nil { + return Status{}, fmt.Errorf("decode %s: %w", path, err) + } + return s, nil +} + +// List returns every readable status, ordered by identity. Unreadable files are skipped and +// reported together in the returned error, so one bad file hides nothing else. +func List(p *paths.Paths) ([]Status, error) { + entries, err := os.ReadDir(Dir(p)) + if errors.Is(err, os.ErrNotExist) { + return nil, nil + } + if err != nil { + return nil, fmt.Errorf("list status files: %w", err) + } + var out []Status + var errs []error + for _, e := range entries { + if e.IsDir() || !strings.HasSuffix(e.Name(), fileExt) || strings.HasPrefix(e.Name(), ".") { + continue + } + s, err := readFile(filepath.Join(Dir(p), e.Name())) + if err != nil { + errs = append(errs, err) + continue + } + out = append(out, s) + } + sort.Slice(out, func(i, j int) bool { return out[i].Identity < out[j].Identity }) + return out, errors.Join(errs...) +} + +// Remove deletes the identity's status file. A missing file is success. +func Remove(p *paths.Paths, identity string) error { + path, err := Path(p, identity) + if err != nil { + return err + } + if err := os.Remove(path); err != nil && !errors.Is(err, os.ErrNotExist) { + return fmt.Errorf("remove %s: %w", path, err) + } + return nil +} diff --git a/plugins/ssh/statusfile/statusfile_test.go b/plugins/ssh/statusfile/statusfile_test.go new file mode 100644 index 00000000000..581a88dae07 --- /dev/null +++ b/plugins/ssh/statusfile/statusfile_test.go @@ -0,0 +1,98 @@ +package statusfile_test + +import ( + "os" + "path/filepath" + "runtime" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/cloudposse/atmos/plugins/ssh/internal/testfakes" + "github.com/cloudposse/atmos/plugins/ssh/paths" + "github.com/cloudposse/atmos/plugins/ssh/statusfile" +) + +func sample(identity string) statusfile.Status { + return statusfile.Status{ + Identity: identity, Operation: statusfile.OperationAuthenticate, Time: time.Date(2026, 11, 12, 10, 0, 0, 0, time.UTC), + Outcome: "failed", Key: "k", Store: "file", Code: "missing-scope", Error: "the token lacks write:ssh_signing_key", + Added: []string{"signing"}, Warnings: []string{"w"}, + } +} + +func TestWriteReadRoundTrip(t *testing.T) { + p := testfakes.Paths(t) + require.NoError(t, statusfile.Write(p, sample("ops"))) + + got, err := statusfile.Read(p, "ops") + + require.NoError(t, err) + assert.Equal(t, sample("ops"), got) + if runtime.GOOS != "windows" { + info, err := os.Stat(filepath.Join(statusfile.Dir(p), "ops.json")) + require.NoError(t, err) + assert.Equal(t, os.FileMode(0o600), info.Mode().Perm()) + } +} + +func TestWriteReplacesThePreviousStatusAndLeavesNoTemporaryFile(t *testing.T) { + p := testfakes.Paths(t) + require.NoError(t, statusfile.Write(p, sample("ops"))) + second := sample("ops") + second.Outcome, second.Error = "unchanged", "" + require.NoError(t, statusfile.Write(p, second)) + + got, err := statusfile.Read(p, "ops") + + require.NoError(t, err) + assert.Equal(t, "unchanged", got.Outcome) + entries, err := os.ReadDir(statusfile.Dir(p)) + require.NoError(t, err) + assert.Len(t, entries, 1) +} + +func TestReadOfAMissingStatus(t *testing.T) { + _, err := statusfile.Read(testfakes.Paths(t), "ops") + assert.ErrorIs(t, err, statusfile.ErrNotFound) +} + +func TestUnsafeNamesAreRejected(t *testing.T) { + p := testfakes.Paths(t) + assert.ErrorIs(t, statusfile.Write(p, sample("../x")), paths.ErrInvalidIdentity) + _, err := statusfile.Read(p, "a/b") + assert.ErrorIs(t, err, paths.ErrInvalidIdentity) + assert.ErrorIs(t, statusfile.Remove(p, ".."), paths.ErrInvalidIdentity) +} + +func TestListIsSortedAndReportsUnreadableFilesWithoutHidingTheRest(t *testing.T) { + p := testfakes.Paths(t) + for _, name := range []string{"zeta", "alpha"} { + require.NoError(t, statusfile.Write(p, sample(name))) + } + require.NoError(t, os.WriteFile(filepath.Join(statusfile.Dir(p), "broken.json"), []byte("{"), 0o600)) + require.NoError(t, os.WriteFile(filepath.Join(statusfile.Dir(p), "notes.txt"), []byte("x"), 0o600)) + + list, err := statusfile.List(p) + + require.Error(t, err) + require.Len(t, list, 2) + assert.Equal(t, []string{"alpha", "zeta"}, []string{list[0].Identity, list[1].Identity}) +} + +func TestListOfNothing(t *testing.T) { + list, err := statusfile.List(testfakes.Paths(t)) + require.NoError(t, err) + assert.Empty(t, list) +} + +func TestRemove(t *testing.T) { + p := testfakes.Paths(t) + require.NoError(t, statusfile.Write(p, sample("ops"))) + require.NoError(t, statusfile.Remove(p, "ops")) + require.NoError(t, statusfile.Remove(p, "ops"), "removing twice is fine") + _, err := statusfile.Read(p, "ops") + assert.ErrorIs(t, err, statusfile.ErrNotFound) +} diff --git a/plugins/ssh/wiring/serve_unix_test.go b/plugins/ssh/wiring/serve_unix_test.go new file mode 100644 index 00000000000..fe6a0bfd460 --- /dev/null +++ b/plugins/ssh/wiring/serve_unix_test.go @@ -0,0 +1,41 @@ +//go:build !windows + +package wiring + +import ( + "context" + "os" + "path/filepath" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/cloudposse/atmos/plugins/ssh/internal/testfakes" + "github.com/cloudposse/atmos/plugins/ssh/paths" +) + +func TestServeAgentRunsUntilTheContextEnds(t *testing.T) { + root := filepath.Join(testfakes.ShortDir(t), "ssh") + p, err := paths.New(root) + require.NoError(t, err) + ctx, cancel := context.WithCancel(context.Background()) + done := make(chan error, 1) + go func() { done <- ServeAgent(ctx, root, "9.9.9", func(string, ...any) {}) }() + + require.Eventually(t, func() bool { + _, err := os.Stat(p.StateFile()) + return err == nil + }, 10*time.Second, 20*time.Millisecond) + cancel() + + select { + case err := <-done: + assert.NoError(t, err) + case <-time.After(10 * time.Second): + t.Fatal("the daemon did not stop") + } + _, err = os.Stat(p.StateFile()) + assert.True(t, os.IsNotExist(err), "the state file is removed on exit") +} diff --git a/plugins/ssh/wiring/wiring.go b/plugins/ssh/wiring/wiring.go new file mode 100644 index 00000000000..e0790da0663 --- /dev/null +++ b/plugins/ssh/wiring/wiring.go @@ -0,0 +1,131 @@ +// Package wiring connects the SSH plugin's logic to the real operating system: the data +// directory, key stores, service manager, clock, and the Atmos API. Everything here is thin; +// the behavior lives in the packages it assembles. +package wiring + +import ( + "context" + "errors" + "net" + "os" + "runtime" + "sync" + "time" + + "github.com/cloudposse/atmos/plugins/ssh/agent" + "github.com/cloudposse/atmos/plugins/ssh/authority" + "github.com/cloudposse/atmos/plugins/ssh/authority/github" + "github.com/cloudposse/atmos/plugins/ssh/authority/self" + "github.com/cloudposse/atmos/plugins/ssh/command" + "github.com/cloudposse/atmos/plugins/ssh/daemon" + "github.com/cloudposse/atmos/plugins/ssh/identity" + "github.com/cloudposse/atmos/plugins/ssh/keystore" + "github.com/cloudposse/atmos/plugins/ssh/paths" + "github.com/cloudposse/atmos/plugins/ssh/rpc" + "github.com/cloudposse/atmos/plugins/ssh/service" + "github.com/cloudposse/atmos/sdk/api" + "github.com/cloudposse/atmos/sdk/plugin" +) + +var registerOnce sync.Once + +// RegisterAuthorities adds the built-in authorities to the default registry. Nothing registers +// itself, so a new authority is added here. +func RegisterAuthorities() { + registerOnce.Do(func() { + for _, f := range []authority.Factory{github.Factory, self.Factory} { + if err := authority.Register(f); err != nil && !errors.Is(err, authority.ErrDuplicateAuthority) { + panic(err) + } + } + }) +} + +// Services builds the plugin's providers, identity, and command against the real system. +func Services(client *api.Client, version string) plugin.Services { + RegisterAuthorities() + d := daemonDeps(version) + idDeps := identity.Deps{ + Paths: resolvePaths, OpenStore: keystore.New, Authorities: authority.Default, Daemon: d, + CheckSocket: agent.CheckSocket, HTTPClient: client.HTTPClient(), State: client, + Now: time.Now, Hostname: os.Hostname, HomeDir: paths.HomeDir, FindSSHKeygen: FindSSHKeygen, Sleep: Sleep, + } + cmdDeps := command.Deps{ + Paths: resolvePaths, OpenStore: keystore.New, Daemon: d, CheckSocket: agent.CheckSocket, + Dial: dial, Now: time.Now, Sleep: Sleep, Hostname: os.Hostname, + } + return plugin.Services{ + Provider: &rpc.Provider{Now: time.Now}, + Identity: rpc.NewIdentity(identity.New(idDeps)), + Commands: rpc.NewCommands(command.New(cmdDeps)), + } +} + +// ServeAgent runs the agent daemon until ctx ends. An empty root means the default data directory. +func ServeAgent(ctx context.Context, root, version string, logf func(string, ...any)) error { + p, err := resolvePaths(root) + if err != nil { + return err + } + return agent.Serve(ctx, agent.Options{Paths: p, Version: version, OpenStore: keystore.New, Logf: logf}) +} + +func daemonDeps(version string) daemon.Deps { + return daemon.Deps{ + Service: func(p *paths.Paths) (service.Manager, error) { return service.New(service.Options{Paths: p}) }, + InstallExecutable: service.InstallExecutable, + Version: version, + } +} + +func resolvePaths(root string) (*paths.Paths, error) { + if root == "" { + return paths.Default() + } + return paths.New(root) +} + +func dial(ctx context.Context, socket string) (net.Conn, error) { + var d net.Dialer + return d.DialContext(ctx, "unix", socket) +} + +// Sleep waits for d, or until ctx ends. +func Sleep(ctx context.Context, d time.Duration) error { + t := time.NewTimer(d) + defer t.Stop() + select { + case <-t.C: + return nil + case <-ctx.Done(): + return ctx.Err() + } +} + +// FindSSHKeygen returns the absolute path of ssh-keygen. The plugin has no PATH, so the usual +// install locations are checked in order. +func FindSSHKeygen() (string, error) { return findSSHKeygen(runtime.GOOS, fileExists) } + +func fileExists(path string) bool { + info, err := os.Stat(path) + return err == nil && !info.IsDir() +} + +func findSSHKeygen(goos string, exists func(string) bool) (string, error) { + for _, c := range sshKeygenCandidates(goos) { + if exists(c) { + return c, nil + } + } + return "", identity.ErrNoSSHKeygen +} + +func sshKeygenCandidates(goos string) []string { + if goos == "windows" { + return []string{ + `C:\Windows\System32\OpenSSH\ssh-keygen.exe`, + `C:\Program Files\Git\usr\bin\ssh-keygen.exe`, + } + } + return []string{"/usr/bin/ssh-keygen", "/usr/local/bin/ssh-keygen", "/opt/homebrew/bin/ssh-keygen", "/bin/ssh-keygen"} +} diff --git a/plugins/ssh/wiring/wiring_test.go b/plugins/ssh/wiring/wiring_test.go new file mode 100644 index 00000000000..1db3882d888 --- /dev/null +++ b/plugins/ssh/wiring/wiring_test.go @@ -0,0 +1,91 @@ +package wiring + +import ( + "context" + "errors" + "os" + "path/filepath" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/cloudposse/atmos/plugins/ssh/authority" + "github.com/cloudposse/atmos/plugins/ssh/identity" + "github.com/cloudposse/atmos/sdk/api" +) + +func TestRegisterAuthoritiesIsIdempotentAndRegistersGitHubAndSelf(t *testing.T) { + RegisterAuthorities() + RegisterAuthorities() + + assert.Contains(t, authority.Names(), "github") + assert.Contains(t, authority.Names(), "self") + _, err := authority.New("github", authority.Options{}) + assert.NoError(t, err) +} + +func TestServicesBuildsAllThreeExports(t *testing.T) { + services := Services(&api.Client{}, "0.1.0") + + assert.NotNil(t, services.Provider) + assert.NotNil(t, services.Identity) + assert.NotNil(t, services.Commands) +} + +func TestFindSSHKeygenChecksTheKnownLocationsInOrder(t *testing.T) { + tests := []struct { + goos string + exists map[string]bool + want string + err error + }{ + {"darwin", map[string]bool{"/usr/bin/ssh-keygen": true, "/opt/homebrew/bin/ssh-keygen": true}, "/usr/bin/ssh-keygen", nil}, + {"linux", map[string]bool{"/usr/local/bin/ssh-keygen": true}, "/usr/local/bin/ssh-keygen", nil}, + {"darwin", map[string]bool{"/opt/homebrew/bin/ssh-keygen": true}, "/opt/homebrew/bin/ssh-keygen", nil}, + {"windows", map[string]bool{`C:\Windows\System32\OpenSSH\ssh-keygen.exe`: true}, `C:\Windows\System32\OpenSSH\ssh-keygen.exe`, nil}, + {"windows", map[string]bool{"/usr/bin/ssh-keygen": true}, "", identity.ErrNoSSHKeygen}, + {"linux", nil, "", identity.ErrNoSSHKeygen}, + } + for _, tt := range tests { + got, err := findSSHKeygen(tt.goos, func(p string) bool { return tt.exists[p] }) + + assert.Equal(t, tt.want, got, tt.goos) + if tt.err != nil { + assert.ErrorIs(t, err, tt.err) + } else { + assert.NoError(t, err) + } + } +} + +func TestSleepWaitsOrStopsWithTheContext(t *testing.T) { + require.NoError(t, Sleep(context.Background(), time.Millisecond)) + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + err := Sleep(ctx, time.Hour) + assert.True(t, errors.Is(err, context.Canceled)) +} + +func TestResolvePathsUsesTheRootWhenGiven(t *testing.T) { + root := filepath.Join(t.TempDir(), "root") + p, err := resolvePaths(root) + require.NoError(t, err) + assert.Equal(t, root, p.Root()) + + d, err := resolvePaths("") + require.NoError(t, err) + assert.NotEmpty(t, d.Root()) +} + +func TestFileExistsMeansARegularFile(t *testing.T) { + dir := t.TempDir() + file := filepath.Join(dir, "f") + require.NoError(t, os.WriteFile(file, []byte("x"), 0o600)) + + assert.True(t, fileExists(file)) + assert.False(t, fileExists(dir)) + assert.False(t, fileExists(filepath.Join(dir, "missing"))) +} diff --git a/website/blog/2026-11-12-ssh-key-identities.mdx b/website/blog/2026-11-12-ssh-key-identities.mdx new file mode 100644 index 00000000000..afd3e4372fe --- /dev/null +++ b/website/blog/2026-11-12-ssh-key-identities.mdx @@ -0,0 +1,86 @@ +--- +slug: ssh-key-identities +title: "SSH keys as Atmos identities, held in the Secure Enclave" +authors: [osterman] +tags: [feature, security, experimental] +--- +Coding agents and unattended jobs need to sign commits and log in to hosts. Today that usually means one of two things: a private key sitting on disk that anything can copy, or a desktop SSH agent that stops signing the moment the screen locks. The first is easy to leak, and the second breaks the agent you left running overnight. + + + +## The Problem + +An SSH key that a script can read is a key a script can steal. Backups, shared home directories, and sandboxes that mount your files all become places the key can leak from. Moving the key into hardware fixes that, but desktop agents tie the hardware key to an unlocked session. When the screen locks, signing fails, and a coding agent working in the background stops with a cryptic error. + +Teams also have to keep track of which key belongs to which person and machine, and remember to remove it from GitHub when a laptop is retired. + +## The Fix + +The official `cloudposse/ssh` [plugin](/plugins/official#ssh-key-identities) makes an SSH key an Atmos identity. On a Mac the private key is generated inside the Secure Enclave and cannot be exported. On other platforms it is a plain key file. + +By default the key works while the screen is locked, so an unattended agent can keep signing commits and reaching hosts. If you want the opposite, add `require: unlocked` and the Secure Enclave refuses the key whenever the screen is locked. Each identity also gets its own agent socket, limited by `allow` to Git signing, SSH logins, or both. + +A key proves nothing on its own, so each identity names an authority. With `authority: github`, login enrolls the key on the GitHub account that a token from a secret store belongs to. Login is idempotent: when the key and its enrollment have not changed, it makes no network call. + +## How to Use It + +Install the package and describe the identity. This example keeps the GitHub token in the system keychain and signs every commit in the `infra` repository: + +```yaml +plugins: + packages: + ssh: + source: oci://ghcr.io/cloudposse/atmos/plugins/ssh + version: "^0.1.0" + secrets: + source: oci://ghcr.io/cloudposse/atmos/plugins/auth-secrets + version: "^1.1.0" +stores: + keychain: + type: keychain + secret: true +auth: + providers: + github-token: + kind: secrets/store + spec: + credentials: + token: {store: keychain, path: github/ssh-keys} + identities: + ops: + kind: ssh/key + via: {provider: github-token} + spec: + authority: github + store: secure-enclave + allow: [signing, authentication] + require: unlocked +git: + repositories: + infra: + auth: {identity: ops} + commit: {signing: always} +``` + +Log in once per machine. Login creates this machine's key and enrolls it: + +```shell +atmos auth login --identity ops +atmos auth exec --identity ops -- git commit -m "signed with the enclave key" +``` + +To let an unattended agent keep working with the screen locked, drop the `require` line. To check the difference, run `atmos ssh test ops --soak 10m --interval 30s` and lock the screen while it runs. Each attempt prints `ok`, `refused`, `locked`, or `unreachable`. + +If you would rather add the public key to GitHub yourself, use the `ssh/self` provider with `authority: self` and print the key with `atmos ssh key show ops --format github`. The full list of fields, commands, and token scopes is on the [official plugins page](/plugins/official#ssh-key-identities). + +### Current limits + +- Hardware-backed keys exist on macOS only for now. Elsewhere the `file` store works but is not hardware-protected. +- There is no GitHub device login yet, so enrollment needs a token from a secret store. +- The agent daemon does not run on Windows yet. +- Atmos does not show plugin text during login, so a failed login is a generic failure. The reason is in `atmos ssh key status`. +- Any process running as the same user can use the key file directly, so do not mount the key directory into a sandbox. + +## Get Involved + +The plugin is experimental. Try it on a machine you use for agents, and tell us what breaks in [GitHub Discussions](https://github.com/orgs/cloudposse/discussions) or on the [pull request](https://github.com/cloudposse/atmos/pulls). diff --git a/website/docs/plugins/official.mdx b/website/docs/plugins/official.mdx index 78893a4bc78..66bc4ab3b76 100644 --- a/website/docs/plugins/official.mdx +++ b/website/docs/plugins/official.mdx @@ -2,7 +2,7 @@ title: Official Plugins sidebar_label: Official Plugins slug: /plugins/official -description: Discover native Atmos plugin packages maintained by Cloud Posse, including secret-store authentication with auth-secrets. +description: Discover native Atmos plugin packages maintained by Cloud Posse, including secret-store authentication with auth-secrets and SSH key identities with ssh. --- import Intro from '@site/src/components/Intro' @@ -68,3 +68,197 @@ identity when running an Atmos command that supports identities. See the [package README](https://github.com/cloudposse/atmos/tree/main/plugins/auth-secrets) for credential validation and lifecycle details, or the [official release guide](https://github.com/cloudposse/atmos/tree/main/plugins) for maintainer instructions. + +## SSH key identities + +The **`cloudposse/ssh`** package makes an SSH key an Atmos identity. Git signing, SSH logins, and +private Git fetches then use a key that Atmos knows by name. On a Mac the private key is generated in +the Secure Enclave and cannot be exported. On other platforms it is an ordinary key file. + +It exports three capabilities in one package: + +| Kind | Capability | Purpose | +|---|---|---| +| `ssh/self` | Authentication provider | Supply no upstream credential. Use it when nobody vouches for the key, or when you add the public key yourself. | +| `ssh/key` | Credential-exchange identity | Create the key, enroll it with an authority, and point tools at it. | +| `ssh` | Command | Inspect and manage keys and the agent that serves them. | + +A key unattended work can use is the main reason to choose this package. By default the key works while +the screen is locked, so a coding agent or a scheduled job can sign commits and reach hosts. Add +`require: unlocked` and the Secure Enclave refuses the key while the screen is locked. + +### Install + +OCI source: + +```text +oci://ghcr.io/cloudposse/atmos/plugins/ssh +``` + +```shell +atmos plugin install oci://ghcr.io/cloudposse/atmos/plugins/ssh --as=ssh +``` + +### Configure + +This example enrolls the key on a GitHub account. The token comes from a secret store through the +`secrets/store` provider of the [`auth-secrets` package](#secret-store-authentication). + +```yaml +plugins: + packages: + ssh: + source: oci://ghcr.io/cloudposse/atmos/plugins/ssh + version: "^0.1.0" + secrets: + source: oci://ghcr.io/cloudposse/atmos/plugins/auth-secrets + version: "^1.1.0" +aliases: + ssh: plugin run ssh -- +stores: + keychain: + type: keychain + secret: true +auth: + providers: + github-token: + kind: secrets/store + spec: + credentials: + token: {store: keychain, path: github/ssh-keys} + identities: + ops: + kind: ssh/key + via: {provider: github-token} + spec: + authority: github + store: secure-enclave + allow: [signing, authentication] + require: unlocked + user: deploy +git: + repositories: + infra: + auth: {identity: ops} + commit: {signing: always} +``` + +Without a token, use the `ssh/self` provider and `authority: self`, then give the public key to whoever +needs it. `atmos ssh key show --format github` prints the form GitHub expects. + +```yaml +auth: + providers: + local: + kind: ssh/self + identities: + ops: + kind: ssh/key + via: {provider: local} + spec: + store: secure-enclave + allow: [signing] +``` + +Create the key and enroll it once per machine with [`atmos auth login`](/cli/commands/auth/login): + +```shell +atmos auth login --identity ops +atmos auth exec --identity ops -- git commit -m "signed with the enclave key" +``` + +The configuration is shared across a team, but each person's login creates and enrolls that machine's own +key. Login is idempotent: when nothing has changed it makes no network call. + +### Identity fields + +Set these under `spec` of an `ssh/key` identity. + +
+
`authority`
+
Who vouches for the key: `self` (default) or `github`. With `github`, the upstream credential's `token` entry is used to enroll the key on the account the token belongs to.
+
`store`
+
Required. `secure-enclave` holds the key in macOS hardware. `file` is an ordinary key file that works on every platform and is not hardware-protected.
+
`allow`
+
Required. `signing`, `authentication`, or both. It limits the identity's agent socket to Git signing, SSH logins, or both, and it decides what is enrolled.
+
`require`
+
One term or a list. The only term is `unlocked`: the key is refused while the screen is locked. The key store enforces it and it is fixed when the key is created. The `file` store cannot enforce it and rejects it.
+
`user`
+
The SSH login name on the remote side. Exported as `ANSIBLE_REMOTE_USER` when `authentication` is allowed.
+
`key`
+
The key's name in the store. Defaults to the identity's name. Identities that share a key must agree on `store` and `require`.
+
`rewrite_https`
+
Hosts whose HTTPS Git URLs are rewritten to SSH.
+
`root`
+
The plugin's data directory, when it is not the default. The plugin cannot see Atmos's environment, so a relocated Atmos data directory must be named here and in the command's `config`.
+
+ +### What the identity sets + +
+
`SSH_AUTH_SOCK`
+
Always. The identity's own agent socket.
+
`GIT_CONFIG_GLOBAL`
+
When `signing` is allowed or `rewrite_https` is set. A generated file that includes your own Git configuration first, then enables SSH signing with the identity's key and applies the URL rewrites.
+
`ANSIBLE_REMOTE_USER`
+
When `user` is set and `authentication` is allowed.
+
+ +### Commands + +Run `atmos plugin run ssh -- `, or `atmos ssh ` with the alias shown above. + +```text +key list +key show [--format authorized-key|allowed-signers|github|json] +key status [] +key delete --yes +agent start | stop | status | log [--lines N] +test [--soak ] [--interval ] +``` + +
+
`key list`, `key show`
+
List the keys on this machine, or print one key's public half in the format a service expects.
+
`key status`
+
Show what this machine has enrolled, when the enrollment expires, and the last login result and error. Atmos does not show plugin text during login, so this is where to read why a login failed.
+
`key delete`
+
Delete the local key. The authority is updated at the next `atmos auth login` or `atmos auth logout`. Requires `--yes`.
+
`agent start`, `stop`, `status`, `log`
+
Control the per-user agent that serves the identities' sockets and read its audit log.
+
`test`
+
Sign a Git payload through the identity's socket and verify it. With `--soak` it repeats every `--interval` and prints one line per attempt (`ok`, `refused`, `locked`, or `unreachable`). It exits non-zero if any attempt failed. Run it, then lock the screen, to check what `require` does.
+
+ +Commands never contact an authority and never prompt. Changes at an authority go through `atmos auth login` +and `atmos auth logout`. Use `--root ` when the data directory is not the default, and `--store ` +to pick a store when a key name exists in more than one. + +### GitHub enrollment + +With `authority: github`, login adds the public key to the account the token belongs to: as a signing key +when `signing` is allowed, and as an authentication key when `authentication` is allowed. The token needs +`write:ssh_signing_key` for signing, plus `write:public_key` for authentication. Grant it no other scopes. + +The identity keeps a copy of the token in its private state so that logout can revoke the enrollment, and +the host removes that copy at logout. An enrollment is revoked once its key is gone, so logging out alone +never strips the key from a machine that still uses it. To retire a machine, run +`atmos ssh key delete ops --yes`, then `atmos auth logout ops`. + +### Security model + +- The key cannot leave the machine. A stolen disk, backup, or copied key blob is useless elsewhere. After a reboot nothing signs until the first login. +- A per-user daemon (a LaunchAgent on macOS, a systemd user unit on Linux) serves the sockets. It rejects connections from other users, and each identity's socket signs only what `allow` permits. +- `require: unlocked` is enforced by the key store, so it holds even against other processes running as you. +- Any other process running as the same user can read the key file and use it directly, bypassing the `allow` limits. Do not mount the key directory into a sandbox. + +### Current limits + +- There is no GitHub device login yet. Enrollment needs a token from a secret store, or you add the public key yourself with `authority: self`. +- Atmos does not show plugin error text during login, so a failed login is a generic failure. Read the reason with `atmos ssh key status`. +- Hardware-backed keys exist on macOS only. The `file` store works everywhere and is not hardware-protected. +- The daemon does not run on Windows yet. An `ssh/key` identity fails there with a "not supported" error. +- Atmos components do not all receive an identity's environment yet; Ansible needs a core change. + +See the [package README](https://github.com/cloudposse/atmos/tree/main/plugins/ssh) and the +[plugin configuration reference](/cli/configuration/plugins) for more. diff --git a/website/src/data/roadmap.js b/website/src/data/roadmap.js index db0323ce365..e6da49a3363 100644 --- a/website/src/data/roadmap.js +++ b/website/src/data/roadmap.js @@ -515,6 +515,7 @@ export const roadmapConfig = { { label: 'Configurable concurrent YAML exec evaluation', status: 'shipped', quarter: 'q4-2026', changelog: 'parallel-yaml-exec', docs: '/cli/configuration/settings/functions/exec', description: 'Run ordinary !exec expressions concurrently within a document evaluation with a configurable limit, preserving result placement and serial execution by default.', benefits: 'Reduce time spent waiting on independent configuration lookups without new tags or grouping syntax.' }, { label: 'Native Go authentication plugins and OIDC starter', status: 'in-progress', quarter: 'q4-2026', experimental: true, changelog: 'native-auth-plugins', docs: '/cli/commands/plugin/usage', description: 'Scaffold and test a Go OIDC provider, chain its broker credentials into built-in identities, and distribute compiled plugins through OCI with explicit installation and release locks.' }, { label: 'Official public plugin catalog and secret-store authentication', status: 'in-progress', quarter: 'q4-2026', experimental: true, changelog: 'official-auth-secrets-plugins', docs: '/cli/configuration/plugins#official-secret-store-authentication', description: 'Discover official plugins through the default Cloud Posse OCI catalog and use auth-secrets to read explicitly configured secret-store credentials into an environment identity. Plugin manifests control independent package versions, with native platform validation and public OCI publication before catalog updates.', benefits: 'Install official plugins without configuring a registry, map selected secret values into child-process environment variables, and update individual plugins independently of Atmos releases.' }, + { label: 'SSH keys as Atmos identities', status: 'in-progress', quarter: 'q4-2026', experimental: true, changelog: 'ssh-key-identities', docs: '/plugins/official#ssh-key-identities', description: 'The cloudposse/ssh plugin turns an SSH key into an Atmos identity. On a Mac the key is generated in the Secure Enclave and cannot be exported; elsewhere it is a key file. Identities can limit each key to Git signing or SSH logins, optionally refuse use while the screen is locked, and enroll the key on GitHub using a token from a secret store.', benefits: 'Coding agents and unattended jobs can sign commits and reach hosts without an exportable key on disk or a desktop agent that stops when the screen locks.' }, { label: 'Identity-authenticated Vault secret fields', status: 'in-progress', quarter: 'q4-2026', changelog: 'identity-authenticated-vault-secret-fields', docs: '/cli/configuration/plugins#official-secret-store-authentication', description: 'Authenticate Vault and OpenBao stores with native Atmos identities and select any exact top-level field from a structured secret document.', benefits: 'Secret-backed identities can consume short-lived Vault or OpenBao credentials without ambient token fallback or repackaging every document into a conventional value field.' }, { label: 'Consistent component executable overrides', status: 'in-progress', quarter: 'q4-2026', changelog: 'component-command-override', description: 'Use --command to override Terraform, Helmfile, Packer or Ansible executables for one invocation. Preserve compatibility aliases and pass native arguments after --.', benefits: 'Select a native executable consistently across component families without editing project configuration.' }, { label: 'Custom commands support interactive step types', status: 'shipped', quarter: 'q4-2025', docs: '/cli/configuration/commands/steps#extended-step-types', changelog: 'custom-commands-step-types', pr: 1899, description: 'Custom commands now support all 25+ step types from workflows—input, choose, confirm, filter, markdown, toast, and more. Build interactive CLI wizards directly in atmos.yaml.', category: 'featured', priority: 'high', benefits: 'Build interactive deployment wizards and guided experiences in custom commands. Same step types as workflows, discoverable via atmos help.' },