auth.go 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. package auth
  2. import (
  3. "bytes"
  4. "context"
  5. "crypto/rand"
  6. "encoding/base64"
  7. "errors"
  8. "fmt"
  9. "io"
  10. "log/slog"
  11. "os"
  12. "path/filepath"
  13. "strings"
  14. "golang.org/x/crypto/ssh"
  15. )
  16. const defaultPrivateKey = "id_ed25519"
  17. func keyPath() (string, error) {
  18. home, err := os.UserHomeDir()
  19. if err != nil {
  20. return "", err
  21. }
  22. return filepath.Join(home, ".ollama", defaultPrivateKey), nil
  23. }
  24. func GetPublicKey() (string, error) {
  25. keyPath, err := keyPath()
  26. if err != nil {
  27. return "", err
  28. }
  29. privateKeyFile, err := os.ReadFile(keyPath)
  30. if err != nil {
  31. slog.Info(fmt.Sprintf("Failed to load private key: %v", err))
  32. return "", err
  33. }
  34. privateKey, err := ssh.ParsePrivateKey(privateKeyFile)
  35. if err != nil {
  36. return "", err
  37. }
  38. publicKey := ssh.MarshalAuthorizedKey(privateKey.PublicKey())
  39. return strings.TrimSpace(string(publicKey)), nil
  40. }
  41. func NewNonce(r io.Reader, length int) (string, error) {
  42. nonce := make([]byte, length)
  43. if _, err := io.ReadFull(r, nonce); err != nil {
  44. return "", err
  45. }
  46. return base64.RawURLEncoding.EncodeToString(nonce), nil
  47. }
  48. func Sign(ctx context.Context, bts []byte) (string, error) {
  49. keyPath, err := keyPath()
  50. if err != nil {
  51. return "", err
  52. }
  53. privateKeyFile, err := os.ReadFile(keyPath)
  54. if err != nil {
  55. slog.Info(fmt.Sprintf("Failed to load private key: %v", err))
  56. return "", err
  57. }
  58. privateKey, err := ssh.ParsePrivateKey(privateKeyFile)
  59. if err != nil {
  60. return "", err
  61. }
  62. // get the pubkey, but remove the type
  63. publicKey := ssh.MarshalAuthorizedKey(privateKey.PublicKey())
  64. parts := bytes.Split(publicKey, []byte(" "))
  65. if len(parts) < 2 {
  66. return "", errors.New("malformed public key")
  67. }
  68. signedData, err := privateKey.Sign(rand.Reader, bts)
  69. if err != nil {
  70. return "", err
  71. }
  72. // signature is <pubkey>:<signature>
  73. return fmt.Sprintf("%s:%s", bytes.TrimSpace(parts[1]), base64.StdEncoding.EncodeToString(signedData.Blob)), nil
  74. }