auth.go 3.6 KB

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