-
Notifications
You must be signed in to change notification settings - Fork 4
/
ollama_registry_authenticate.go
214 lines (188 loc) · 5.59 KB
/
ollama_registry_authenticate.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
package gguf_parser
import (
"bytes"
"context"
"crypto/ed25519"
"crypto/rand"
"encoding/base64"
"encoding/json"
"encoding/pem"
"errors"
"fmt"
"net/http"
"net/url"
"os"
"path/filepath"
"runtime"
"strconv"
"strings"
"time"
"golang.org/x/crypto/ssh"
"github.com/gpustack/gguf-parser-go/util/funcx"
"github.com/gpustack/gguf-parser-go/util/httpx"
"github.com/gpustack/gguf-parser-go/util/osx"
"github.com/gpustack/gguf-parser-go/util/stringx"
)
const (
httpHeaderWWWAuthenticate = "WWW-Authenticate"
httpHeaderAuthorization = "Authorization"
)
// OllamaUserAgent returns the user agent string for Ollama,
// since llama3.1, the user agent is required to be set,
// otherwise the request will be rejected by 412.
func OllamaUserAgent() string {
return fmt.Sprintf("ollama/0.3.3 (%s %s) Go/%s", runtime.GOARCH, runtime.GOOS, runtime.Version())
}
// OllamaRegistryAuthorizeRetry returns true if the request should be retried with authorization.
//
// OllamaRegistryAuthorizeRetry leverages OllamaRegistryAuthorize to obtain an authorization token,
// and configures the request with the token.
func OllamaRegistryAuthorizeRetry(resp *http.Response, cli *http.Client) bool {
if resp == nil || cli == nil {
return false
}
if resp.StatusCode != http.StatusUnauthorized && resp.Request == nil {
// Not unauthorized, return.
return false
}
req := resp.Request
if req.Header.Get(httpHeaderAuthorization) != "" {
// Already authorized, return.
return false
}
const tokenPrefix = "Bearer "
authnToken := strings.TrimPrefix(resp.Header.Get(httpHeaderWWWAuthenticate), tokenPrefix)
if authnToken == "" {
// No authentication token, return.
return false
}
authzToken := funcx.MustNoError(OllamaRegistryAuthorize(req.Context(), cli, authnToken))
req.Header.Set(httpHeaderAuthorization, tokenPrefix+authzToken)
return true
}
// OllamaRegistryAuthorize authorizes the request with the given authentication token,
// and returns the authorization token.
func OllamaRegistryAuthorize(ctx context.Context, cli *http.Client, authnToken string) (string, error) {
priKey, err := OllamaSingKeyLoad()
if err != nil {
return "", fmt.Errorf("load sign key: %w", err)
}
var authzUrl string
{
ss := strings.Split(authnToken, ",")
if len(ss) < 3 {
return "", errors.New("invalid authn token")
}
var realm, service, scope string
for _, s := range ss {
sp := strings.SplitN(s, "=", 2)
if len(sp) < 2 {
continue
}
sp[1] = strings.TrimFunc(sp[1], func(r rune) bool {
return r == '"' || r == '\''
})
switch sp[0] {
case "realm":
realm = sp[1]
case "service":
service = sp[1]
case "scope":
scope = sp[1]
}
}
u, err := url.Parse(realm)
if err != nil {
return "", fmt.Errorf("parse realm: %w", err)
}
qs := u.Query()
qs.Add("service", service)
for _, s := range strings.Split(scope, " ") {
qs.Add("scope", s)
}
qs.Add("ts", strconv.FormatInt(time.Now().Unix(), 10))
qs.Add("nonce", stringx.RandomBase64(16))
u.RawQuery = qs.Encode()
authzUrl = u.String()
}
var authnData string
{
pubKey := ssh.MarshalAuthorizedKey(priKey.PublicKey())
pubKeyp := bytes.Split(pubKey, []byte(" "))
if len(pubKeyp) < 2 {
return "", errors.New("malformed public key")
}
nc := base64.StdEncoding.EncodeToString([]byte(stringx.SumBytesBySHA256(nil)))
py := []byte(fmt.Sprintf("%s,%s,%s", http.MethodGet, authzUrl, nc))
sd, err := priKey.Sign(rand.Reader, py)
if err != nil {
return "", fmt.Errorf("signing data: %w", err)
}
authnData = fmt.Sprintf("%s:%s", bytes.TrimSpace(pubKeyp[1]), base64.StdEncoding.EncodeToString(sd.Blob))
}
req, err := httpx.NewGetRequestWithContext(ctx, authzUrl)
if err != nil {
return "", fmt.Errorf("new request: %w", err)
}
req.Header.Add(httpHeaderAuthorization, authnData)
var authzToken string
err = httpx.Do(cli, req, func(resp *http.Response) error {
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("status code %d", resp.StatusCode)
}
var tok struct {
Token string `json:"token"`
}
if err = json.NewDecoder(resp.Body).Decode(&tok); err != nil {
return err
}
if tok.Token == "" {
return errors.New("empty token")
}
authzToken = tok.Token
return nil
})
if err != nil {
return "", fmt.Errorf("do request %s: %w", authzUrl, err)
}
return authzToken, nil
}
// OllamaSingKeyLoad loads the signing key for Ollama,
// and generates a new key if not exists.
func OllamaSingKeyLoad() (ssh.Signer, error) {
hd := filepath.Join(osx.UserHomeDir(), ".ollama")
priKeyPath := filepath.Join(hd, "id_ed25519")
if !osx.ExistsFile(priKeyPath) {
// Generate key if not exists.
pubKey, priKey, err := ed25519.GenerateKey(rand.Reader)
if err != nil {
return nil, fmt.Errorf("generate key: %w", err)
}
priKeyPem, err := ssh.MarshalPrivateKey(priKey, "")
if err != nil {
return nil, fmt.Errorf("marshal private key: %w", err)
}
priKeyBs := pem.EncodeToMemory(priKeyPem)
sshPubKey, err := ssh.NewPublicKey(pubKey)
if err != nil {
return nil, fmt.Errorf("new public key: %w", err)
}
pubKeyBs := ssh.MarshalAuthorizedKey(sshPubKey)
if err = osx.WriteFile(priKeyPath, priKeyBs, 0o600); err != nil {
return nil, fmt.Errorf("write private key: %w", err)
}
if err = osx.WriteFile(priKeyPath+".pub", pubKeyBs, 0o644); err != nil {
_ = os.Remove(priKeyPath)
return nil, fmt.Errorf("write public key: %w", err)
}
}
priKeyBs, err := os.ReadFile(priKeyPath)
if err != nil {
return nil, fmt.Errorf("read private key: %w", err)
}
priKey, err := ssh.ParsePrivateKey(priKeyBs)
if err != nil {
return nil, fmt.Errorf("parse private key: %w", err)
}
return priKey, nil
}