1package sshutils
 2
 3import (
 4	"bytes"
 5	"context"
 6
 7	"github.com/charmbracelet/ssh"
 8	gossh "golang.org/x/crypto/ssh"
 9)
10
11// ParseAuthorizedKey parses an authorized key string into a public key.
12func ParseAuthorizedKey(ak string) (gossh.PublicKey, string, error) {
13	pk, c, _, _, err := gossh.ParseAuthorizedKey([]byte(ak))
14	return pk, c, err
15}
16
17// MarshalAuthorizedKey marshals a public key into an authorized key string.
18//
19// This is the inverse of ParseAuthorizedKey.
20// This function is a copy of ssh.MarshalAuthorizedKey, but without the trailing newline.
21// It returns an empty string if pk is nil.
22func MarshalAuthorizedKey(pk gossh.PublicKey) string {
23	if pk == nil {
24		return ""
25	}
26	return string(bytes.TrimSuffix(gossh.MarshalAuthorizedKey(pk), []byte("\n")))
27}
28
29// KeysEqual returns whether the two public keys are equal.
30func KeysEqual(a, b gossh.PublicKey) bool {
31	return ssh.KeysEqual(a, b)
32}
33
34// PublicKeyFromContext returns the public key from the context.
35func PublicKeyFromContext(ctx context.Context) gossh.PublicKey {
36	if pk, ok := ctx.Value(ssh.ContextKeyPublicKey).(gossh.PublicKey); ok {
37		return pk
38	}
39	return nil
40}
41
42// ContextKeySession is the context key for the SSH session.
43var ContextKeySession = &struct{ string }{"session"}
44
45// SessionFromContext returns the SSH session from the context.
46func SessionFromContext(ctx context.Context) ssh.Session {
47	if s, ok := ctx.Value(ContextKeySession).(ssh.Session); ok {
48		return s
49	}
50	return nil
51}