auth.go 3.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169
  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 := map[string]string{
  83. "Authorization": sig,
  84. }
  85. resp, err := makeRequest(ctx, "GET", url, headers, nil, regOpts)
  86. if err != nil {
  87. log.Printf("couldn't get token: %q", err)
  88. }
  89. defer resp.Body.Close()
  90. if resp.StatusCode != http.StatusOK {
  91. body, _ := io.ReadAll(resp.Body)
  92. return "", fmt.Errorf("on pull registry responded with code %d: %s", resp.StatusCode, body)
  93. }
  94. respBody, err := io.ReadAll(resp.Body)
  95. if err != nil {
  96. return "", err
  97. }
  98. var tok api.TokenResponse
  99. if err := json.Unmarshal(respBody, &tok); err != nil {
  100. return "", err
  101. }
  102. return tok.Token, nil
  103. }
  104. // Bytes returns a byte slice of the data to sign for the request
  105. func (s SignatureData) Bytes() []byte {
  106. // We first derive the content hash of the request body using:
  107. // base64(hex(sha256(request body)))
  108. hash := sha256.Sum256(s.Data)
  109. hashHex := make([]byte, hex.EncodedLen(len(hash)))
  110. hex.Encode(hashHex, hash[:])
  111. contentHash := base64.StdEncoding.EncodeToString(hashHex)
  112. // We then put the entire request together in a serialize string using:
  113. // "<method>,<uri>,<content hash>"
  114. // e.g. "GET,http://localhost,OTdkZjM1O..."
  115. return []byte(strings.Join([]string{s.Method, s.Path, contentHash}, ","))
  116. }
  117. // SignData takes a SignatureData object and signs it with a raw private key
  118. func (s SignatureData) Sign(rawKey []byte) (string, error) {
  119. privateKey, err := ssh.ParseRawPrivateKey(rawKey)
  120. if err != nil {
  121. return "", err
  122. }
  123. signer, err := ssh.NewSignerFromKey(privateKey)
  124. if err != nil {
  125. return "", err
  126. }
  127. // get the pubkey, but remove the type
  128. pubKey := ssh.MarshalAuthorizedKey(signer.PublicKey())
  129. parts := bytes.Split(pubKey, []byte(" "))
  130. if len(parts) < 2 {
  131. return "", fmt.Errorf("malformed public key")
  132. }
  133. signedData, err := signer.Sign(nil, s.Bytes())
  134. if err != nil {
  135. return "", err
  136. }
  137. // signature is <pubkey>:<signature>
  138. sig := fmt.Sprintf("%s:%s", bytes.TrimSpace(parts[1]), base64.StdEncoding.EncodeToString(signedData.Blob))
  139. return sig, nil
  140. }