// NewCachedFileTokenSource returns a oauth2.TokenSource reads a token from a
// file at a specified path and periodically reloads it.
481816
func NewCachedFileTokenSource(path string) oauth2.TokenSource {
	return &cachingTokenSource{
		now:    time.Now,
		leeway: 10 * time.Second,
		base: &fileTokenSource{
			path: path,
			// This period was picked because it is half of the duration between when the kubelet
			// refreshes a projected service account token and when the original token expires.
			// Default token lifetime is 10 minutes, and the kubelet starts refreshing at 80% of lifetime.
			// This should induce re-reading at a frequency that works with the token volume source.
			period: time.Minute,
		},
	}
}
689165
func (a *cachedTokenAuthenticator) AuthenticateToken(ctx context.Context, token string) (*authenticator.Response, bool, error) {
	auds, _ := authenticator.AudiencesFrom(ctx)

	key := keyFunc(auds, token)
	if record, ok := a.cache.get(key); ok {
		return record.resp, record.ok, record.err
	}

	resp, ok, err := a.authenticator.AuthenticateToken(ctx, token)
	if !a.cacheErrs && err != nil {
		return resp, ok, err
	}

	switch {
	case ok && a.successTTL > 0:
		a.cache.set(key, &cacheRecord{resp: resp, ok: ok, err: err}, a.successTTL)
	case !ok && a.failureTTL > 0:
		a.cache.set(key, &cacheRecord{resp: resp, ok: ok, err: err}, a.failureTTL)
	}

	return resp, ok, err
}
990069
func RefreshToken(f TokenFunc, filename string) (int64, error) {
	log.Debug("Refreshing authentication token")
	token, expires, err := f()
	if err != nil {
		return 0, err
	}
	updateToken(token, time.Unix(expires, 0), filename)
	log.WithField("expiration", expires).Info("Received new authentication token")
	return expires, err
}
119948
func appEngineTokenSource(ctx context.Context, scope ...string) oauth2.TokenSource {
	scopes := append([]string{}, scope...)
	sort.Strings(scopes)
	return &gaeTokenSource{
		ctx:    ctx,
		scopes: scopes,
		key:    strings.Join(scopes, " "),
	}
}
1137593
func NewCachableSource(root string) *CachableSource {
	ts := &CachableSource{
		tree: iradix.New(),
		root: containerfs.NewLocalContainerFS(root),
	}
	return ts
}
1281192
func signFromSource(source TokenSource, req *http.Request) error {
	token, err := source.Token()
	if err != nil {
		return err
	}
	if !token.Valid() {
		return fmt.Errorf("token expired or invalid")
	}
	token.SetAuthHeader(req)
	return nil
}
745766
func (s tokenSource) Token() (*oauth2.Token, error) {
	return s.a.GetAccessToken(minAcceptedLifetime)
}
465017
func NewAuthorizerFromFileWithResource(resource string) (autorest.Authorizer, error) {
	s, err := GetSettingsFromFile()
	if err != nil {
		return nil, err
	}
	if a, err := s.ClientCredentialsAuthorizerWithResource(resource); err == nil {
		return a, err
	}
	if a, err := s.ClientCertificateAuthorizerWithResource(resource); err == nil {
		return a, err
	}
	return nil, errors.New("auth file missing client and certificate credentials")
}
781823
func newCachedDiscoveryClient(delegate discovery.DiscoveryInterface, cacheDirectory string, ttl time.Duration) *CachedDiscoveryClient {
	return &CachedDiscoveryClient{
		delegate:       delegate,
		cacheDirectory: cacheDirectory,
		ttl:            ttl,
		ourFiles:       map[string]struct{}{},
		fresh:          true,
	}
}
1111845
func NewCaches(p *helpers.PathSpec) (Caches, error) {
	dcfg, err := decodeConfig(p)
	if err != nil {
		return nil, err
	}

	fs := p.Fs.Source

	m := make(Caches)
	for k, v := range dcfg {
		var cfs afero.Fs

		if v.isResourceDir {
			cfs = p.BaseFs.Resources.Fs
		} else {
			cfs = fs
		}

		var baseDir string
		if !strings.HasPrefix(v.Dir, "_gen") {
			// We do cache eviction (file removes) and since the user can set
			// his/hers own cache directory, we really want to make sure
			// we do not delete any files that do not belong to this cache.
			// We do add the cache name as the root, but this is an extra safe
			// guard. We skip the files inside /resources/_gen/ because
			// that would be breaking.
			baseDir = filepath.Join(v.Dir, filecacheRootDirname, k)
		} else {
			baseDir = filepath.Join(v.Dir, k)
		}
		if err = cfs.MkdirAll(baseDir, 0777); err != nil && !os.IsExist(err) {
			return nil, err
		}

		bfs := afero.NewBasePathFs(cfs, baseDir)

		m[k] = NewCache(bfs, v.MaxAge)
	}

	return m, nil
}
1017615
func NewJSONSourceFromFile(f string) (InputSourceContext, error) {
	data, err := loadDataFrom(f)
	if err != nil {
		return nil, err
	}
	return NewJSONSource(data)
}
396211
func NewFileSource() FileSource {
	if fileConfigSource == nil {
		fileConfigSource = new(fileSource)
		fileConfigSource.priority = fileSourcePriority
		fileConfigSource.files = make([]file, 0)
		fileConfigSource.fileHandlers = make(map[string]FileHandler)
	}

	return fileConfigSource
}
961308
func (c *DiskTokenCache) GetToken(key *CacheKey) (*Token, error) {
	cache, err := c.readCacheFile()
	if err != nil {
		return nil, err
	}
	for _, entry := range cache.Cache {
		if EqualCacheKeys(&entry.Key, key) {
			return &Token{
				Token: entry.Token,
				Email: entry.Email,
			}, nil
		}
	}
	return nil, nil
}
823564
func ProjectTokenSource(proj string, scopes ...string) (oauth2.TokenSource, error) {
	// TODO(bradfitz): try different strategies too, like
	// three-legged flow if the service account doesn't exist, and
	// then cache the token file on disk somewhere. Or maybe that should be an
	// option, for environments without stdin/stdout available to the user.
	// We'll figure it out as needed.
	fileName := filepath.Join(homedir(), "keys", proj+".key.json")
	jsonConf, err := ioutil.ReadFile(fileName)
	if err != nil {
		if os.IsNotExist(err) {
			return nil, fmt.Errorf("Missing JSON key configuration. Download the Service Account JSON key from https://console.developers.google.com/project/%s/apiui/credential and place it at %s", proj, fileName)
		}
		return nil, err
	}
	conf, err := google.JWTConfigFromJSON(jsonConf, scopes...)
	if err != nil {
		return nil, fmt.Errorf("reading JSON config from %s: %v", fileName, err)
	}
	return conf.TokenSource(oauth2.NoContext), nil
}
1211573
func (t *Store) AgentTokenAndSource() (string, TokenSource) {
	t.l.RLock()
	defer t.l.RUnlock()

	return t.agentToken, t.agentTokenSource
}
547373
func NewCacheLoader(files []string) *CacheLoader {
	return &CacheLoader{
		files:  files,
		Logger: zap.NewNop(),
	}
}
210537
func (s *notifyRefreshTokenSource) Token() (*oauth2.Token, error) {
	s.mu.Lock()
	defer s.mu.Unlock()
	if s.t.Valid() {
		return s.t, nil
	}
	t, err := s.new.Token()
	if err != nil {
		return nil, err
	}
	s.t = t
	return t, s.f(t)
}