auth.go 3.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168
  1. package server
  2. import (
  3. "bytes"
  4. "crypto/rand"
  5. "crypto/sha256"
  6. "encoding/base64"
  7. "encoding/hex"
  8. "encoding/json"
  9. "fmt"
  10. "io"
  11. "log"
  12. "net/http"
  13. "os"
  14. "path"
  15. "strings"
  16. "time"
  17. "golang.org/x/crypto/ssh"
  18. "github.com/jmorganca/ollama/api"
  19. )
  20. type AuthRedirect struct {
  21. Realm string
  22. Service string
  23. Scope string
  24. }
  25. type SignatureData struct {
  26. Method string
  27. Path string
  28. Data []byte
  29. }
  30. func generateNonce(length int) (string, error) {
  31. nonce := make([]byte, length)
  32. _, err := rand.Read(nonce)
  33. if err != nil {
  34. return "", err
  35. }
  36. return base64.RawURLEncoding.EncodeToString(nonce), nil
  37. }
  38. func (r AuthRedirect) URL() (string, error) {
  39. nonce, err := generateNonce(16)
  40. if err != nil {
  41. return "", err
  42. }
  43. return fmt.Sprintf("%s?service=%s&scope=%s&ts=%d&nonce=%s", r.Realm, r.Service, r.Scope, time.Now().Unix(), nonce), nil
  44. }
  45. func getAuthToken(redirData AuthRedirect, regOpts *RegistryOptions) (string, error) {
  46. url, err := redirData.URL()
  47. if err != nil {
  48. return "", err
  49. }
  50. home, err := os.UserHomeDir()
  51. if err != nil {
  52. return "", err
  53. }
  54. keyPath := path.Join(home, ".ollama", "id_ed25519")
  55. err = os.MkdirAll(path.Dir(keyPath), 0700)
  56. if err != nil {
  57. return "", fmt.Errorf("could not create .ollama directory %w", err)
  58. }
  59. rawKey, err := os.ReadFile(keyPath)
  60. if err != nil {
  61. log.Printf("Failed to load private key: %v", err)
  62. return "", err
  63. }
  64. s := SignatureData{
  65. Method: "GET",
  66. Path: url,
  67. Data: nil,
  68. }
  69. if !strings.HasPrefix(s.Path, "http") {
  70. if regOpts.Insecure {
  71. s.Path = "http://" + url
  72. } else {
  73. s.Path = "https://" + url
  74. }
  75. }
  76. sig, err := s.Sign(rawKey)
  77. if err != nil {
  78. return "", err
  79. }
  80. headers := map[string]string{
  81. "Authorization": sig,
  82. }
  83. resp, err := makeRequest("GET", url, headers, nil, regOpts)
  84. if err != nil {
  85. log.Printf("couldn't get token: %q", err)
  86. }
  87. defer resp.Body.Close()
  88. if resp.StatusCode != http.StatusOK {
  89. body, _ := io.ReadAll(resp.Body)
  90. return "", fmt.Errorf("on pull registry responded with code %d: %s", resp.StatusCode, body)
  91. }
  92. respBody, err := io.ReadAll(resp.Body)
  93. if err != nil {
  94. return "", err
  95. }
  96. var tok api.TokenResponse
  97. if err := json.Unmarshal(respBody, &tok); err != nil {
  98. return "", err
  99. }
  100. return tok.Token, nil
  101. }
  102. // Bytes returns a byte slice of the data to sign for the request
  103. func (s SignatureData) Bytes() []byte {
  104. // We first derive the content hash of the request body using:
  105. // base64(hex(sha256(request body)))
  106. hash := sha256.Sum256(s.Data)
  107. hashHex := make([]byte, hex.EncodedLen(len(hash)))
  108. hex.Encode(hashHex, hash[:])
  109. contentHash := base64.StdEncoding.EncodeToString(hashHex)
  110. // We then put the entire request together in a serialize string using:
  111. // "<method>,<uri>,<content hash>"
  112. // e.g. "GET,http://localhost,OTdkZjM1O..."
  113. return []byte(strings.Join([]string{s.Method, s.Path, contentHash}, ","))
  114. }
  115. // SignData takes a SignatureData object and signs it with a raw private key
  116. func (s SignatureData) Sign(rawKey []byte) (string, error) {
  117. privateKey, err := ssh.ParseRawPrivateKey(rawKey)
  118. if err != nil {
  119. return "", err
  120. }
  121. signer, err := ssh.NewSignerFromKey(privateKey)
  122. if err != nil {
  123. return "", err
  124. }
  125. // get the pubkey, but remove the type
  126. pubKey := ssh.MarshalAuthorizedKey(signer.PublicKey())
  127. parts := bytes.Split(pubKey, []byte(" "))
  128. if len(parts) < 2 {
  129. return "", fmt.Errorf("malformed public key")
  130. }
  131. signedData, err := signer.Sign(nil, s.Bytes())
  132. if err != nil {
  133. return "", err
  134. }
  135. // signature is <pubkey>:<signature>
  136. sig := fmt.Sprintf("%s:%s", bytes.TrimSpace(parts[1]), base64.StdEncoding.EncodeToString(signedData.Blob))
  137. return sig, nil
  138. }