auth.go 3.7 KB

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