Violet Hynes 17be1024e4
VAULT-12564 Add new token_file auto-auth method (#18740)
* VAULT-12564 Work so far on token file auto-auth

* VAULT-12564 remove lifetime watcher struct modifications

* VAULT-12564 add other config items, and clean up

* VAULT-12564 clean-up and more tests

* VAULT-12564 clean-up

* VAULT-12564 lookup-self and some clean-up

* VAULT-12564 safer client usage

* VAULT-12564 some clean-up

* VAULT-12564 changelog

* VAULT-12564 some clean-ups

* VAULT-12564 batch token warning

* VAULT-12564 remove follow_symlink reference

* VAULT-12564 Remove redundant stat, change temp file creation

* VAULT-12564 Remove ability to delete token after auth
2023-01-24 16:09:32 -05:00

84 lines
1.9 KiB
Go

package token_file
import (
"context"
"errors"
"fmt"
"net/http"
"os"
"strings"
"github.com/hashicorp/go-hclog"
"github.com/hashicorp/vault/api"
"github.com/hashicorp/vault/command/agent/auth"
)
type tokenFileMethod struct {
logger hclog.Logger
mountPath string
cachedToken string
tokenFilePath string
}
func NewTokenFileAuthMethod(conf *auth.AuthConfig) (auth.AuthMethod, error) {
if conf == nil {
return nil, errors.New("empty config")
}
if conf.Config == nil {
return nil, errors.New("empty config data")
}
a := &tokenFileMethod{
logger: conf.Logger,
mountPath: "auth/token",
}
tokenFilePathRaw, ok := conf.Config["token_file_path"]
if !ok {
return nil, errors.New("missing 'token_file_path' value")
}
a.tokenFilePath, ok = tokenFilePathRaw.(string)
if !ok {
return nil, errors.New("could not convert 'token_file_path' config value to string")
}
if a.tokenFilePath == "" {
return nil, errors.New("'token_file_path' value is empty")
}
return a, nil
}
func (a *tokenFileMethod) Authenticate(ctx context.Context, client *api.Client) (string, http.Header, map[string]interface{}, error) {
token, err := os.ReadFile(a.tokenFilePath)
if err != nil {
if a.cachedToken == "" {
return "", nil, nil, fmt.Errorf("error reading token file and no cached token known: %w", err)
}
a.logger.Warn("error reading token file", "error", err)
}
if len(token) == 0 {
if a.cachedToken == "" {
return "", nil, nil, errors.New("token file empty and no cached token known")
}
a.logger.Warn("token file exists but read empty value, re-using cached value")
} else {
a.cachedToken = strings.TrimSpace(string(token))
}
// i.e. auth/token/lookup-self
return fmt.Sprintf("%s/lookup-self", a.mountPath), nil, map[string]interface{}{
"token": a.cachedToken,
}, nil
}
func (a *tokenFileMethod) NewCreds() chan struct{} {
return nil
}
func (a *tokenFileMethod) CredSuccess() {
}
func (a *tokenFileMethod) Shutdown() {
}