File: cache.go

package info (click to toggle)
golang-oras-oras-go 2.5.0-1
  • links: PTS, VCS
  • area: main
  • in suites: experimental, forky, sid, trixie
  • size: 2,232 kB
  • sloc: makefile: 29
file content (232 lines) | stat: -rw-r--r-- 7,977 bytes parent folder | download
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
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
/*
Copyright The ORAS Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package auth

import (
	"context"
	"strings"
	"sync"

	"oras.land/oras-go/v2/errdef"
	"oras.land/oras-go/v2/internal/syncutil"
)

// DefaultCache is the sharable cache used by DefaultClient.
var DefaultCache Cache = NewCache()

// Cache caches the auth-scheme and auth-token for the "Authorization" header in
// accessing the remote registry.
// Precisely, the header is `Authorization: auth-scheme auth-token`.
// The `auth-token` is a generic term as `token68` in RFC 7235 section 2.1.
type Cache interface {
	// GetScheme returns the auth-scheme part cached for the given registry.
	// A single registry is assumed to have a consistent scheme.
	// If a registry has different schemes per path, the auth client is still
	// workable. However, the cache may not be effective as the cache cannot
	// correctly guess the scheme.
	GetScheme(ctx context.Context, registry string) (Scheme, error)

	// GetToken returns the auth-token part cached for the given registry of a
	// given scheme.
	// The underlying implementation MAY cache the token for all schemes for the
	// given registry.
	GetToken(ctx context.Context, registry string, scheme Scheme, key string) (string, error)

	// Set fetches the token using the given fetch function and caches the token
	// for the given scheme with the given key for the given registry.
	// The return values of the fetch function is returned by this function.
	// The underlying implementation MAY combine the fetch operation if the Set
	// function is invoked multiple times at the same time.
	Set(ctx context.Context, registry string, scheme Scheme, key string, fetch func(context.Context) (string, error)) (string, error)
}

// cacheEntry is a cache entry for a single registry.
type cacheEntry struct {
	scheme Scheme
	tokens sync.Map // map[string]string
}

// concurrentCache is a cache suitable for concurrent invocation.
type concurrentCache struct {
	status sync.Map // map[string]*syncutil.Once
	cache  sync.Map // map[string]*cacheEntry
}

// NewCache creates a new go-routine safe cache instance.
func NewCache() Cache {
	return &concurrentCache{}
}

// GetScheme returns the auth-scheme part cached for the given registry.
func (cc *concurrentCache) GetScheme(ctx context.Context, registry string) (Scheme, error) {
	entry, ok := cc.cache.Load(registry)
	if !ok {
		return SchemeUnknown, errdef.ErrNotFound
	}
	return entry.(*cacheEntry).scheme, nil
}

// GetToken returns the auth-token part cached for the given registry of a given
// scheme.
func (cc *concurrentCache) GetToken(ctx context.Context, registry string, scheme Scheme, key string) (string, error) {
	entryValue, ok := cc.cache.Load(registry)
	if !ok {
		return "", errdef.ErrNotFound
	}
	entry := entryValue.(*cacheEntry)
	if entry.scheme != scheme {
		return "", errdef.ErrNotFound
	}
	if token, ok := entry.tokens.Load(key); ok {
		return token.(string), nil
	}
	return "", errdef.ErrNotFound
}

// Set fetches the token using the given fetch function and caches the token
// for the given scheme with the given key for the given registry.
// Set combines the fetch operation if the Set is invoked multiple times at the
// same time.
func (cc *concurrentCache) Set(ctx context.Context, registry string, scheme Scheme, key string, fetch func(context.Context) (string, error)) (string, error) {
	// fetch token
	statusKey := strings.Join([]string{
		registry,
		scheme.String(),
		key,
	}, " ")
	statusValue, _ := cc.status.LoadOrStore(statusKey, syncutil.NewOnce())
	fetchOnce := statusValue.(*syncutil.Once)
	fetchedFirst, result, err := fetchOnce.Do(ctx, func() (interface{}, error) {
		return fetch(ctx)
	})
	if fetchedFirst {
		cc.status.Delete(statusKey)
	}
	if err != nil {
		return "", err
	}
	token := result.(string)
	if !fetchedFirst {
		return token, nil
	}

	// cache token
	newEntry := &cacheEntry{
		scheme: scheme,
	}
	entryValue, exists := cc.cache.LoadOrStore(registry, newEntry)
	entry := entryValue.(*cacheEntry)
	if exists && entry.scheme != scheme {
		// there is a scheme change, which is not expected in most scenarios.
		// force invalidating all previous cache.
		entry = newEntry
		cc.cache.Store(registry, entry)
	}
	entry.tokens.Store(key, token)

	return token, nil
}

// noCache is a cache implementation that does not do cache at all.
type noCache struct{}

// GetScheme always returns not found error as it has no cache.
func (noCache) GetScheme(ctx context.Context, registry string) (Scheme, error) {
	return SchemeUnknown, errdef.ErrNotFound
}

// GetToken always returns not found error as it has no cache.
func (noCache) GetToken(ctx context.Context, registry string, scheme Scheme, key string) (string, error) {
	return "", errdef.ErrNotFound
}

// Set calls fetch directly without caching.
func (noCache) Set(ctx context.Context, registry string, scheme Scheme, key string, fetch func(context.Context) (string, error)) (string, error) {
	return fetch(ctx)
}

// hostCache is an auth cache that ignores scopes.  Uses only the registry's hostname to find a token.
type hostCache struct {
	Cache
}

// GetToken implements Cache.
func (c *hostCache) GetToken(ctx context.Context, registry string, scheme Scheme, key string) (string, error) {
	return c.Cache.GetToken(ctx, registry, scheme, "")
}

// Set implements Cache.
func (c *hostCache) Set(ctx context.Context, registry string, scheme Scheme, key string, fetch func(context.Context) (string, error)) (string, error) {
	return c.Cache.Set(ctx, registry, scheme, "", fetch)
}

// fallbackCache tries the primary cache then falls back to the secondary cache.
type fallbackCache struct {
	primary   Cache
	secondary Cache
}

// GetScheme implements Cache.
func (fc *fallbackCache) GetScheme(ctx context.Context, registry string) (Scheme, error) {
	scheme, err := fc.primary.GetScheme(ctx, registry)
	if err == nil {
		return scheme, nil
	}

	// fallback
	return fc.secondary.GetScheme(ctx, registry)
}

// GetToken implements Cache.
func (fc *fallbackCache) GetToken(ctx context.Context, registry string, scheme Scheme, key string) (string, error) {
	token, err := fc.primary.GetToken(ctx, registry, scheme, key)
	if err == nil {
		return token, nil
	}

	// fallback
	return fc.secondary.GetToken(ctx, registry, scheme, key)
}

// Set implements Cache.
func (fc *fallbackCache) Set(ctx context.Context, registry string, scheme Scheme, key string, fetch func(context.Context) (string, error)) (string, error) {
	token, err := fc.primary.Set(ctx, registry, scheme, key, fetch)
	if err != nil {
		return "", err
	}

	return fc.secondary.Set(ctx, registry, scheme, key, func(ctx context.Context) (string, error) {
		return token, nil
	})
}

// NewSingleContextCache creates a host-based cache for optimizing the auth flow for non-compliant registries.
// It is intended to be used in a single context, such as pulling from a single repository.
// This cache should not be shared.
//
// Note: [NewCache] should be used for compliant registries as it can be shared
// across context and will generally make less re-authentication requests.
func NewSingleContextCache() Cache {
	cache := NewCache()
	return &fallbackCache{
		primary: cache,
		// We can re-use the came concurrentCache here because the key space is different
		// (keys are always empty for the hostCache) so there is no collision.
		// Even if there is a collision it is not an issue.
		// Re-using saves a little memory.
		secondary: &hostCache{cache},
	}
}