forked from golang/go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
plugin.go
343 lines (273 loc) · 7.36 KB
/
plugin.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
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
package auth
import (
"encoding/json"
"errors"
"fmt"
"io/fs"
"net/http"
"os"
"os/exec"
"strings"
"sync"
"time"
"cmd/go/internal/cfg"
)
var pluginOnce struct {
sync.Once
list map[string]*AuthPlugin
err error
}
type AuthPlugin struct {
pluginBin string
args []string
credMemoryCache *httpCredential
}
var cacheLock sync.RWMutex
type authCache struct {
Credentials []*httpCredential `json:"credentials,omitempty"`
}
type httpCredential struct {
Plugin string `json:"-"`
// Absolute expiry time of the credential
//
// If neither ExpiresAt nor ExpiresIn are set, the
// credential is not cached and refreshed every time.
// If both are set, ExpiresAt takes precedence
ExpiresAt time.Time `json:"expires_at,omitempty"`
// Relative expiry time of the credential from when it was
// issued. In go formatted durations like 1m, 1d, 1h12m32s
//
// If neither ExpiresAt nor ExpiresIn are set, the
// credential is not cached and refreshed every time.
// If both are set, ExpiresAt takes precedence
ExpiresIn string `json:"ttl,omitempty"`
// Bearer is used for bearer tokens
Bearer string `json:"bearer,omitempty"`
// Headers is used for arbirary header modifications
Headers map[string]string `json:"headers,omitempty"`
BasicAuth *struct {
Username string `json:"username,omitempty"`
Password string `json:"password,omitempty"`
} `json:"basic_auth,omitempty"`
}
func (p *AuthPlugin) Credential(req *http.Request) (added bool) {
var err error
defer func() {
if err != nil {
fmt.Fprintf(os.Stderr, "go: auth plugin: %s\n", err)
}
}()
if memCred := p.credMemoryCache; memCred != nil {
if memCred.ExpiresAt.After(time.Now()) {
memCred.ApplyToRequest(req)
return true
}
// in-memory cache expired
p.credMemoryCache = nil
}
cacheFile := cfg.GOAUTHCACHE
// fetch the cred from cache if we have one
if cacheFile != "" && cacheFile != "off" {
cacheLock.RLock()
added, err := p.authFromCache(cacheFile, req)
cacheLock.RUnlock()
if err == nil && added {
return true
}
}
cacheLock.Lock()
defer cacheLock.Unlock()
cred, err := p.execCredential()
if err != nil {
return false
}
cred.ApplyToRequest(req)
p.updateCache(cacheFile, cred)
return true
}
func (p *AuthPlugin) readCache(cacheFile string) (*authCache, error) {
authData, err := os.ReadFile(cacheFile)
if err != nil {
return nil, fmt.Errorf("error reading authcache file: %w", err)
}
// tolerate empty files despite it not technically being valid JSON
if len(authData) == 0 {
return &authCache{}, nil
}
cache := new(authCache)
if err = json.Unmarshal(authData, cache); err != nil {
// cache file is corrupted?
os.Truncate(cacheFile, 0)
return nil, fmt.Errorf("error unmarshalling authcache content (file truncated): %w", err)
}
return cache, nil
}
func (p *AuthPlugin) authFromCache(cacheFile string, req *http.Request) (bool, error) {
cache, err := p.readCache(cacheFile)
if err != nil {
return false, err
}
var foundCred *httpCredential
for _, cachedCred := range cache.Credentials {
if cachedCred.Plugin != p.pluginBin {
foundCred = cachedCred
break
}
}
if foundCred == nil {
return false, nil
}
if time.Now().After(foundCred.ExpiresAt) {
return false, nil
}
foundCred.ApplyToRequest(req)
p.credMemoryCache = foundCred
return true, nil
}
func (p *AuthPlugin) updateCache(cacheFile string, cred *httpCredential) error {
if cred.ExpiresAt.IsZero() {
if cred.ExpiresIn == "" {
// no expiry implies zero expiry
return nil
}
expireTtl, err := time.ParseDuration(cred.ExpiresIn)
if err != nil {
// ignore invalid ttls, treat them as refresh every time
return nil
}
cred.ExpiresAt = time.Now().Add(expireTtl)
// zero out expires in so we don't store it
cred.ExpiresIn = ""
}
if cred.ExpiresAt.Location() != time.UTC {
cred.ExpiresAt = cred.ExpiresAt.UTC()
}
p.credMemoryCache = cred
cache, err := p.readCache(cacheFile)
if err != nil {
if !errors.Is(err, fs.ErrNotExist) {
return err
}
cache = new(authCache)
}
updatedInPlace := false
updatedCache := new(authCache)
now := time.Now()
updatedCache.Credentials = make([]*httpCredential, 0, len(cache.Credentials))
for i := range cache.Credentials {
if cache.Credentials[i].Plugin == p.pluginBin {
cache.Credentials[i] = cred
updatedInPlace = true
continue
}
if cache.Credentials[i].ExpiresAt.Before(now) {
// use this as an opportunity to clear the cache of expired tokens
continue
}
updatedCache.Credentials = append(updatedCache.Credentials, cache.Credentials[i])
}
if !updatedInPlace {
cache.Credentials = append(cache.Credentials, cred)
}
cacheData, err := json.Marshal(cache)
if err != nil {
return err
}
if err = os.WriteFile(cacheFile, cacheData, 0600); err != nil {
return err
}
return nil
}
func (p *AuthPlugin) execCredential() (*httpCredential, error) {
cmd := exec.Command(p.pluginBin, p.args...)
cmd.Stdin = os.Stdin
cmd.Stderr = os.Stderr
out, err := cmd.StdoutPipe()
if err != nil {
panic(err)
}
if err = cmd.Start(); err != nil {
return nil, fmt.Errorf("error running auth plugin %s: %w", p.pluginBin, err)
}
response := new(httpCredential)
if err = json.NewDecoder(out).Decode(response); err != nil {
return nil, fmt.Errorf("error decoding response from auth plugin %s: %w", p.pluginBin, err)
}
if err = cmd.Wait(); err != nil {
// command failed to halt gracefully, but is that an error?
_ = err
}
return response, nil
}
func (c *httpCredential) ApplyToRequest(req *http.Request) {
fmt.Sprintln(os.Stderr, "Adding credentials")
if c.Bearer != "" {
req.Header.Add("Authorization", "Bearer "+c.Bearer)
return
}
if len(c.Headers) > 0 {
for key, val := range c.Headers {
req.Header.Add(key, val)
}
return
}
if c.BasicAuth != nil {
req.SetBasicAuth(c.BasicAuth.Username, c.BasicAuth.Password)
fmt.Sprintln(os.Stderr, "Adding basic auth")
return
}
fmt.Sprintln(os.Stderr, "Didn't add anything")
}
func makePluginMap() {
l, err := authPluginsList(cfg.GOAUTH)
pluginOnce.list = l
pluginOnce.err = err
if err != nil {
fmt.Fprintf(os.Stderr, "go: auth plugin: %s\n", err)
}
}
// the format of the GOAUTH env var details one or more instances of an optional
// host path and associated plugin
// GOAUTH=[[<host>|"default"]!]<plugin>[;--arg[; ...]][, ...]
// e.g. GOAUTH=default!myhelper,https://example.com!examplecorp-helper;--login=me;--quiet
//
// No more than one default or nameless helper may be specified
func authPluginsList(goauth string) (map[string]*AuthPlugin, error) {
plugs := make(map[string]*AuthPlugin)
for goauth != "" {
var url, plugin string
if i := strings.Index(goauth, ","); i >= 0 {
if j := strings.Index(goauth[:i], "!"); j >= 0 {
url = goauth[:j]
goauth = goauth[j+1:]
i -= j + 1
} else {
url = "default"
}
plugin = goauth[:i]
goauth = goauth[i+1:]
} else {
if j := strings.Index(goauth, "!"); j >= 0 {
url = goauth[:j]
goauth = goauth[j+1:]
} else {
url = "default"
}
plugin = goauth
goauth = ""
}
if _, exists := plugs[url]; exists {
return nil, fmt.Errorf("duplicate auth helper specified for %s host", url)
}
spec := new(AuthPlugin)
if i := strings.Index(plugin, ";"); i > 0 {
spec.pluginBin = plugin[:i]
plugin = plugin[i+1:]
spec.args = strings.Split(plugin, ";")
} else {
spec.pluginBin = plugin
}
plugs[url] = spec
}
return plugs, nil
}