"docs/source/en/api/pipelines/overview.mdx" did not exist on "830a9d1f0189d541328691c7cb20ceed829b7645"
auth.go 3.94 KB
Newer Older
1
package auth
Patrick Devine's avatar
Patrick Devine committed
2
3
4

import (
	"bytes"
5
	"context"
Patrick Devine's avatar
Patrick Devine committed
6
7
8
9
10
11
12
	"crypto/rand"
	"crypto/sha256"
	"encoding/base64"
	"encoding/hex"
	"encoding/json"
	"fmt"
	"io"
13
	"log/slog"
Patrick Devine's avatar
Patrick Devine committed
14
	"net/http"
Michael Yang's avatar
Michael Yang committed
15
	"net/url"
Patrick Devine's avatar
Patrick Devine committed
16
	"os"
Michael Yang's avatar
Michael Yang committed
17
	"path/filepath"
Michael Yang's avatar
Michael Yang committed
18
	"strconv"
Patrick Devine's avatar
Patrick Devine committed
19
20
21
22
23
24
25
26
	"strings"
	"time"

	"golang.org/x/crypto/ssh"

	"github.com/jmorganca/ollama/api"
)

27
28
29
30
const (
	KeyType = "id_ed25519"
)

Patrick Devine's avatar
Patrick Devine committed
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
type AuthRedirect struct {
	Realm   string
	Service string
	Scope   string
}

type SignatureData struct {
	Method string
	Path   string
	Data   []byte
}

func generateNonce(length int) (string, error) {
	nonce := make([]byte, length)
	_, err := rand.Read(nonce)
	if err != nil {
		return "", err
	}
	return base64.RawURLEncoding.EncodeToString(nonce), nil
}

Michael Yang's avatar
Michael Yang committed
52
53
func (r AuthRedirect) URL() (*url.URL, error) {
	redirectURL, err := url.Parse(r.Realm)
Patrick Devine's avatar
Patrick Devine committed
54
	if err != nil {
Michael Yang's avatar
Michael Yang committed
55
		return nil, err
Patrick Devine's avatar
Patrick Devine committed
56
	}
Michael Yang's avatar
Michael Yang committed
57
58
59
60
61

	values := redirectURL.Query()

	values.Add("service", r.Service)

62
	for _, s := range strings.Split(r.Scope, " ") {
Michael Yang's avatar
Michael Yang committed
63
		values.Add("scope", s)
64
	}
Michael Yang's avatar
Michael Yang committed
65
66
67
68
69
70
71
72
73
74
75

	values.Add("ts", strconv.FormatInt(time.Now().Unix(), 10))

	nonce, err := generateNonce(16)
	if err != nil {
		return nil, err
	}
	values.Add("nonce", nonce)

	redirectURL.RawQuery = values.Encode()
	return redirectURL, nil
Patrick Devine's avatar
Patrick Devine committed
76
77
}

78
func SignRequest(method, url string, data []byte, headers http.Header) error {
Patrick Devine's avatar
Patrick Devine committed
79
80
	home, err := os.UserHomeDir()
	if err != nil {
81
		return err
Patrick Devine's avatar
Patrick Devine committed
82
83
	}

84
	keyPath := filepath.Join(home, ".ollama", KeyType)
Patrick Devine's avatar
Patrick Devine committed
85

86
	rawKey, err := os.ReadFile(keyPath)
Patrick Devine's avatar
Patrick Devine committed
87
	if err != nil {
88
		slog.Info(fmt.Sprintf("Failed to load private key: %v", err))
89
		return err
Patrick Devine's avatar
Patrick Devine committed
90
91
92
	}

	s := SignatureData{
93
94
95
		Method: method,
		Path:   url,
		Data:   data,
Patrick Devine's avatar
Patrick Devine committed
96
97
98
	}

	sig, err := s.Sign(rawKey)
99
100
101
102
103
104
105
106
107
108
	if err != nil {
		return err
	}

	headers.Set("Authorization", sig)
	return nil
}

func GetAuthToken(ctx context.Context, redirData AuthRedirect) (string, error) {
	redirectURL, err := redirData.URL()
Patrick Devine's avatar
Patrick Devine committed
109
110
111
112
	if err != nil {
		return "", err
	}

Michael Yang's avatar
Michael Yang committed
113
	headers := make(http.Header)
114
115
116
117
118
	err = SignRequest(http.MethodGet, redirectURL.String(), nil, headers)
	if err != nil {
		return "", err
	}
	resp, err := MakeRequest(ctx, http.MethodGet, redirectURL, headers, nil, nil)
Patrick Devine's avatar
Patrick Devine committed
119
	if err != nil {
120
		slog.Info(fmt.Sprintf("couldn't get token: %q", err))
Michael Yang's avatar
Michael Yang committed
121
		return "", err
Patrick Devine's avatar
Patrick Devine committed
122
123
124
	}
	defer resp.Body.Close()

Michael Yang's avatar
Michael Yang committed
125
	if resp.StatusCode >= http.StatusBadRequest {
Michael Yang's avatar
Michael Yang committed
126
127
128
129
130
131
132
133
		responseBody, err := io.ReadAll(resp.Body)
		if err != nil {
			return "", fmt.Errorf("%d: %v", resp.StatusCode, err)
		} else if len(responseBody) > 0 {
			return "", fmt.Errorf("%d: %s", resp.StatusCode, responseBody)
		}

		return "", fmt.Errorf("%s", resp.Status)
Patrick Devine's avatar
Patrick Devine committed
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
	}

	respBody, err := io.ReadAll(resp.Body)
	if err != nil {
		return "", err
	}

	var tok api.TokenResponse
	if err := json.Unmarshal(respBody, &tok); err != nil {
		return "", err
	}

	return tok.Token, nil
}

// Bytes returns a byte slice of the data to sign for the request
func (s SignatureData) Bytes() []byte {
	// We first derive the content hash of the request body using:
	//     base64(hex(sha256(request body)))

	hash := sha256.Sum256(s.Data)
	hashHex := make([]byte, hex.EncodedLen(len(hash)))
	hex.Encode(hashHex, hash[:])
	contentHash := base64.StdEncoding.EncodeToString(hashHex)

	// We then put the entire request together in a serialize string using:
	//       "<method>,<uri>,<content hash>"
	// e.g.  "GET,http://localhost,OTdkZjM1O..."

	return []byte(strings.Join([]string{s.Method, s.Path, contentHash}, ","))
}

// SignData takes a SignatureData object and signs it with a raw private key
func (s SignatureData) Sign(rawKey []byte) (string, error) {
Michael Yang's avatar
Michael Yang committed
168
	signer, err := ssh.ParsePrivateKey(rawKey)
Patrick Devine's avatar
Patrick Devine committed
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
	if err != nil {
		return "", err
	}

	// get the pubkey, but remove the type
	pubKey := ssh.MarshalAuthorizedKey(signer.PublicKey())
	parts := bytes.Split(pubKey, []byte(" "))
	if len(parts) < 2 {
		return "", fmt.Errorf("malformed public key")
	}

	signedData, err := signer.Sign(nil, s.Bytes())
	if err != nil {
		return "", err
	}

	// signature is <pubkey>:<signature>
	sig := fmt.Sprintf("%s:%s", bytes.TrimSpace(parts[1]), base64.StdEncoding.EncodeToString(signedData.Blob))
	return sig, nil
}