auth.go 3.48 KB
Newer Older
Patrick Devine's avatar
Patrick Devine committed
1
2
3
4
package server

import (
	"bytes"
5
	"context"
Patrick Devine's avatar
Patrick Devine committed
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
	"crypto/rand"
	"crypto/sha256"
	"encoding/base64"
	"encoding/hex"
	"encoding/json"
	"fmt"
	"io"
	"log"
	"net/http"
	"os"
	"path"
	"strings"
	"time"

	"golang.org/x/crypto/ssh"

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

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
}

func (r AuthRedirect) URL() (string, error) {
	nonce, err := generateNonce(16)
	if err != nil {
		return "", err
	}
	return fmt.Sprintf("%s?service=%s&scope=%s&ts=%d&nonce=%s", r.Realm, r.Service, r.Scope, time.Now().Unix(), nonce), nil
}

54
func getAuthToken(ctx context.Context, redirData AuthRedirect, regOpts *RegistryOptions) (string, error) {
Patrick Devine's avatar
Patrick Devine committed
55
56
57
58
59
60
61
62
63
64
	url, err := redirData.URL()
	if err != nil {
		return "", err
	}

	home, err := os.UserHomeDir()
	if err != nil {
		return "", err
	}

65
	keyPath := path.Join(home, ".ollama", "id_ed25519")
Patrick Devine's avatar
Patrick Devine committed
66

67
	rawKey, err := os.ReadFile(keyPath)
Patrick Devine's avatar
Patrick Devine committed
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
	if err != nil {
		log.Printf("Failed to load private key: %v", err)
		return "", err
	}

	s := SignatureData{
		Method: "GET",
		Path:   url,
		Data:   nil,
	}

	if !strings.HasPrefix(s.Path, "http") {
		if regOpts.Insecure {
			s.Path = "http://" + url
		} else {
			s.Path = "https://" + url
		}
	}

	sig, err := s.Sign(rawKey)
	if err != nil {
		return "", err
	}

	headers := map[string]string{
		"Authorization": sig,
	}

96
	resp, err := makeRequest(ctx, "GET", url, headers, nil, regOpts)
Patrick Devine's avatar
Patrick Devine committed
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
	if err != nil {
		log.Printf("couldn't get token: %q", err)
	}
	defer resp.Body.Close()

	if resp.StatusCode != http.StatusOK {
		body, _ := io.ReadAll(resp.Body)
		return "", fmt.Errorf("on pull registry responded with code %d: %s", resp.StatusCode, body)
	}

	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) {
	privateKey, err := ssh.ParseRawPrivateKey(rawKey)
	if err != nil {
		return "", err
	}

	signer, err := ssh.NewSignerFromKey(privateKey)
	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
}