agent

package
v0.8.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Feb 2, 2021 License: MPL-2.0 Imports: 14 Imported by: 0

Documentation

Index

Constants

View Source
const (
	DefaultVaultImage                    = "vault:1.6.2"
	DefaultVaultAuthPath                 = "auth/kubernetes"
	DefaultAgentRunAsUser                = 100
	DefaultAgentRunAsGroup               = 1000
	DefaultAgentRunAsSameUser            = false
	DefaultAgentAllowPrivilegeEscalation = false
	DefaultAgentDropCapabilities         = "ALL"
	DefaultAgentSetSecurityContext       = true
	DefaultAgentReadOnlyRoot             = true
	DefaultAgentCacheEnable              = "false"
	DefaultAgentCacheUseAutoAuthToken    = "true"
	DefaultAgentCacheListenerPort        = "8200"
	DefaultAgentUseLeaderElector         = false
)
View Source
const (
	// AnnotationAgentStatus is the key of the annotation that is added to
	// a pod after an injection is done.
	// There's only one valid status we care about: "injected".
	AnnotationAgentStatus = "vault.hashicorp.com/agent-inject-status"

	// AnnotationAgentInject is the key of the annotation that controls whether
	// injection is explicitly enabled or disabled for a pod. This should
	// be set to a true or false value, as parseable by strconv.ParseBool
	AnnotationAgentInject = "vault.hashicorp.com/agent-inject"

	// AnnotationAgentInjectSecret is the key annotation that configures Vault
	// Agent to retrieve the secrets from Vault required by the app.  The name
	// of the secret is any unique string after "vault.hashicorp.com/agent-inject-secret-",
	// such as "vault.hashicorp.com/agent-inject-secret-foobar".  The value is the
	// path in Vault where the secret is located.
	AnnotationAgentInjectSecret = "vault.hashicorp.com/agent-inject-secret"

	// AnnotationAgentInjectFile is the key of the annotation that contains the
	// name (and optional path) of the file to create on disk. The name of the
	// secret is the string after "vault.hashicorp.com/agent-inject-file-", and
	// should map to the same unique value provided in
	// "vault.hashicorp.com/agent-inject-secret-". The value is the filename and
	// path in the secrets volume where the vault secret will be written. The
	// container mount path of the secrets volume may be modified with the
	// secret-volume-path annotation.
	AnnotationAgentInjectFile = "vault.hashicorp.com/agent-inject-file"

	// AnnotationAgentInjectTemplate is the key annotation that configures Vault
	// Agent what template to use for rendering the secrets.  The name
	// of the template is any unique string after "vault.hashicorp.com/agent-inject-template-",
	// such as "vault.hashicorp.com/agent-inject-template-foobar".  This should map
	// to the same unique value provided in "vault.hashicorp.com/agent-inject-secret-".
	// If not provided, a default generic template is used.
	AnnotationAgentInjectTemplate = "vault.hashicorp.com/agent-inject-template"

	// AnnotationAgentInjectToken is the annotation key for injecting the token
	// from auth/token/lookup-self
	AnnotationAgentInjectToken = "vault.hashicorp.com/agent-inject-token"

	// AnnotationAgentInjectCommand is the key annotation that configures Vault Agent
	// to run a command after the secret is rendered. The name of the template is any
	// unique string after "vault.hashicorp.com/agent-inject-command-". This should map
	// to the same unique value provided in "vault.hashicorp.com/agent-inject-secret-".
	// If not provided (the default), no command is executed.
	AnnotationAgentInjectCommand = "vault.hashicorp.com/agent-inject-command"

	// AnnotationAgentImage is the name of the Vault docker image to use.
	AnnotationAgentImage = "vault.hashicorp.com/agent-image"

	// AnnotationAgentRequestNamespace is the Kubernetes namespace where the request
	// originated from.
	AnnotationAgentRequestNamespace = "vault.hashicorp.com/agent-request-namespace"

	// AnnotationAgentInitFirst makes the initialization container the first container
	// to run when a pod starts. Default is last.
	AnnotationAgentInitFirst = "vault.hashicorp.com/agent-init-first"

	// AnnotationAgentPrePopulate controls whether an init container is included
	// to pre-populate the shared memory volume with secrets prior to the application
	// starting.
	AnnotationAgentPrePopulate = "vault.hashicorp.com/agent-pre-populate"

	// AnnotationAgentPrePopulateOnly controls whether an init container is the only
	// injected container.  If true, no sidecar container will be injected at runtime
	// of the application.
	AnnotationAgentPrePopulateOnly = "vault.hashicorp.com/agent-pre-populate-only"

	// AnnotationAgentConfigMap is the name of the configuration map where Vault Agent
	// configuration file and templates can be found.
	AnnotationAgentConfigMap = "vault.hashicorp.com/agent-configmap"

	// AnnotationAgentExtraSecret is the name of a Kubernetes secret that will be mounted
	// into the Vault agent container so that the agent config can reference secrets.
	AnnotationAgentExtraSecret = "vault.hashicorp.com/agent-extra-secret"

	// AnnotationAgentLimitsCPU sets the CPU limit on the Vault Agent containers.
	AnnotationAgentLimitsCPU = "vault.hashicorp.com/agent-limits-cpu"

	// AnnotationAgentLimitsMem sets the memory limit on the Vault Agent containers.
	AnnotationAgentLimitsMem = "vault.hashicorp.com/agent-limits-mem"

	// AnnotationAgentRequestsCPU sets the requested CPU amount on the Vault Agent containers.
	AnnotationAgentRequestsCPU = "vault.hashicorp.com/agent-requests-cpu"

	// AnnotationAgentRequestsMem sets the requested memory amount on the Vault Agent containers.
	AnnotationAgentRequestsMem = "vault.hashicorp.com/agent-requests-mem"

	// AnnotationAgentRevokeOnShutdown controls whether a sidecar container will revoke its
	// own Vault token before shutting down. If you are using a custom agent template, you must
	// make sure it's written to `/home/vault/.vault-token`. Only supported for sidecar containers.
	AnnotationAgentRevokeOnShutdown = "vault.hashicorp.com/agent-revoke-on-shutdown"

	// AnnotationAgentRevokeGrace sets the number of seconds after receiving the signal for pod
	// termination that the container will attempt to revoke its own Vault token. Defaults to 5s.
	AnnotationAgentRevokeGrace = "vault.hashicorp.com/agent-revoke-grace"

	// AnnotationVaultNamespace is the Vault namespace where secrets can be found.
	AnnotationVaultNamespace = "vault.hashicorp.com/namespace"

	// AnnotationAgentRunAsUser sets the User ID to run the Vault Agent containers as.
	AnnotationAgentRunAsUser = "vault.hashicorp.com/agent-run-as-user"

	// AnnotationAgentRunAsGroup sets the Group ID to run the Vault Agent containers as.
	AnnotationAgentRunAsGroup = "vault.hashicorp.com/agent-run-as-group"

	// AnnotationAgentRunAsSameUser sets the User ID of the injected Vault Agent
	// containers to the User ID of the first application container in the Pod.
	// Requires Spec.Containers[0].SecurityContext.RunAsUser to be set in the
	// Pod Spec.
	AnnotationAgentRunAsSameUser = "vault.hashicorp.com/agent-run-as-same-user"

	// AnnotationAgentSetSecurityContext controls whether a SecurityContext (uid
	// and gid) is set on the injected Vault Agent containers
	AnnotationAgentSetSecurityContext = "vault.hashicorp.com/agent-set-security-context"

	// AnnotationVaultService is the name of the Vault server.  This can be overridden by the
	// user but will be set by a flag on the deployment.
	AnnotationVaultService = "vault.hashicorp.com/service"

	// AnnotationVaultTLSSkipVerify allows users to configure verifying TLS
	// when communicating with Vault.
	AnnotationVaultTLSSkipVerify = "vault.hashicorp.com/tls-skip-verify"

	// AnnotationVaultTLSSecret is the name of the Kubernetes secret containing
	// client TLS certificates and keys.
	AnnotationVaultTLSSecret = "vault.hashicorp.com/tls-secret"

	// AnnotationVaultTLSServerName is the name of the Vault server to verify the
	// authenticity of the server when communicating with Vault over TLS.
	AnnotationVaultTLSServerName = "vault.hashicorp.com/tls-server-name"

	// AnnotationVaultCACert is the path of the CA certificate used to verify Vault's
	// CA certificate.
	AnnotationVaultCACert = "vault.hashicorp.com/ca-cert"

	// AnnotationVaultCAKey is the path of the CA key used to verify Vault's CA.
	AnnotationVaultCAKey = "vault.hashicorp.com/ca-key"

	// AnnotationVaultClientCert is the path of the client certificate used to communicate
	// with Vault over TLS.
	AnnotationVaultClientCert = "vault.hashicorp.com/client-cert"

	// AnnotationVaultClientKey is the path of the client key used to communicate
	// with Vault over TLS.
	AnnotationVaultClientKey = "vault.hashicorp.com/client-key"

	// AnnotationVaultClientMaxRetries is the number of retry attempts when 5xx errors are encountered.
	AnnotationVaultClientMaxRetries = "vault.hashicorp.com/client-max-retries"

	// AnnotationVaultClientTimeout sets the request timeout when communicating with Vault.
	AnnotationVaultClientTimeout = "vault.hashicorp.com/client-timeout"

	// AnnotationVaultLogLevel sets the Vault Agent log level.
	AnnotationVaultLogLevel = "vault.hashicorp.com/log-level"

	// AnnotationVaultLogFormat sets the Vault Agent log format.
	AnnotationVaultLogFormat = "vault.hashicorp.com/log-format"

	// AnnotationVaultRole specifies the role to be used for the Kubernetes auto-auth
	// method.
	AnnotationVaultRole = "vault.hashicorp.com/role"

	// AnnotationVaultAuthPath specifies the mount path to be used for the Kubernetes auto-auth
	// method.
	AnnotationVaultAuthPath = "vault.hashicorp.com/auth-path"

	// AnnotationVaultSecretVolumePath specifies where the secrets are to be
	// Mounted after fetching.
	AnnotationVaultSecretVolumePath = "vault.hashicorp.com/secret-volume-path"

	// AnnotationPreserveSecretCase if enabled will preserve the case of secret name
	// by default the name is converted to lower case.
	AnnotationPreserveSecretCase = "vault.hashicorp.com/preserve-secret-case"

	// AnnotationAgentCacheEnable if enabled will configure the sidecar container
	// to enable agent caching
	AnnotationAgentCacheEnable = "vault.hashicorp.com/agent-cache-enable"

	// AnnotationAgentCacheUseAutoAuthToken configures the agent cache to use the
	// auto auth token or not. Can be set to "force" to force usage of the auto-auth token
	AnnotationAgentCacheUseAutoAuthToken = "vault.hashicorp.com/agent-cache-use-auto-auth-token"

	// AnnotationAgentCacheListenerPort configures the port the agent cache should listen on
	AnnotationAgentCacheListenerPort = "vault.hashicorp.com/agent-cache-listener-port"

	// AnnotationAgentCopyVolumeMounts is the name of the container or init container
	// in the Pod whose volume mounts should be copied onto the Vault Agent init and
	// sidecar containers. Ignores any Kubernetes service account token mounts.
	AnnotationAgentCopyVolumeMounts = "vault.hashicorp.com/agent-copy-volume-mounts"
)
View Source
const (
	DefaultTemplate = "{{ with secret \"%s\" }}{{ range $k, $v := .Data }}{{ $k }}: {{ $v }}\n{{ end }}{{ end }}"
	TokenTemplate   = "{{ with secret \"auth/token/lookup-self\" }}{{ .Data.id }}\n{{ end }}"
	TokenSecret     = "auth/token/lookup-self"
	PidFile         = "/home/vault/.pid"
	TokenFile       = "/home/vault/.vault-token"
)
View Source
const (
	// https://kubernetes.io/docs/concepts/configuration/manage-compute-resources-container/#meaning-of-cpu
	DefaultResourceLimitCPU   = "500m"
	DefaultResourceLimitMem   = "128Mi"
	DefaultResourceRequestCPU = "250m"
	DefaultResourceRequestMem = "64Mi"
	DefaultContainerArg       = "echo ${VAULT_CONFIG?} | base64 -d > /home/vault/config.json && vault agent -config=/home/vault/config.json"
	DefaultRevokeGrace        = 5
	DefaultAgentLogLevel      = "info"
	DefaultAgentLogFormat     = "standard"
)

Variables

This section is empty.

Functions

func EscapeJSONPointer

func EscapeJSONPointer(s string) string

EscapeJSONPointer escapes a JSON string to be compliant with the JavaScript Object Notation (JSON) Pointer syntax RFC: https://tools.ietf.org/html/rfc6901.

func Init

func Init(pod *corev1.Pod, cfg AgentConfig) error

Init configures the expected annotations required to create a new instance of Agent. This should be run before running new to ensure all annotations are present.

func ShouldInject

func ShouldInject(pod *corev1.Pod) (bool, error)

ShouldInject checks whether the pod in question should be injected with Vault Agent containers.

Types

type Agent

type Agent struct {
	// Annotations are the current pod annotations used to
	// configure the Vault Agent container.
	Annotations map[string]string

	// ImageName is the name of the Vault image to use for the
	// sidecar container.
	ImageName string

	// Inject is the flag used to determine if a container should be requested
	// in a pod request.
	Inject bool

	// InitFirst controls whether an init container is first to run.
	InitFirst bool

	// LimitsCPU is the upper CPU limit the sidecar container is allowed to consume.
	LimitsCPU string

	// LimitsMem is the upper memory limit the sidecar container is allowed to consume.
	LimitsMem string

	// Namespace is the Kubernetes namespace the request originated from.
	Namespace string

	// Patches are all the mutations we will make to the pod request.
	Patches []*jsonpatch.JsonPatchOperation

	// Pod is the original Kubernetes pod spec.
	Pod *corev1.Pod

	// PrePopulate controls whether an init container is added to the request.
	PrePopulate bool

	// PrePopulateOnly controls whether an init container is the _only_ container
	// added to the request.
	PrePopulateOnly bool

	// RevokeOnShutdown controls whether a sidecar container will attempt to revoke its Vault
	// token on shutting down.
	RevokeOnShutdown bool

	// RevokeGrace controls after receiving the signal for pod
	// termination that the container will attempt to revoke its own Vault token.
	RevokeGrace uint64

	// RequestsCPU is the requested minimum CPU amount required  when being scheduled to deploy.
	RequestsCPU string

	// RequestsMem is the requested minimum memory amount required when being scheduled to deploy.
	RequestsMem string

	// Secrets are all the templates, the path in Vault where the secret can be
	//found, and the unique name of the secret which will be used for the filename.
	Secrets []*Secret

	// ServiceAccountName is the Kubernetes service account name for the pod.
	// This is used when we mount the service account to the  Vault Agent container(s).
	ServiceAccountName string

	// ServiceAccountPath is the path on disk where the service account JWT
	// can be located.  This is used when we mount the service account to the
	// Vault Agent container(s).
	ServiceAccountPath string

	// Status is the current injection status.  The only status considered is "injected",
	// which prevents further mutations.  A user can patch this annotation to force a new
	// mutation.
	Status string

	// ConfigMapName is the name of the configmap a user wants to mount to Vault Agent
	// container(s).
	ConfigMapName string

	// Vault is the structure holding all the Vault specific configurations.
	Vault Vault

	// VaultAgentCache is the structure holding the Vault agent cache specific configurations
	VaultAgentCache VaultAgentCache

	// RunAsUser is the user ID to run the Vault agent container(s) as.
	RunAsUser int64

	// RunAsGroup is the group ID to run the Vault agent container(s) as.
	RunAsGroup int64

	// RunAsSameID sets the user ID of the Vault agent container(s) to be the
	// same as the first application container
	RunAsSameID bool

	// SetSecurityContext controls whether the injected containers have a
	// SecurityContext set.
	SetSecurityContext bool

	// ExtraSecret is the Kubernetes secret to mount as a volume in the Vault agent container
	// which can be referenced by the Agent config for secrets. Mounted at /vault/custom/
	ExtraSecret string

	// CopyVolumeMounts is the name of the container in the Pod whose volume mounts
	// should be copied into the Vault Agent init and/or sidecar containers.
	CopyVolumeMounts string
}

Agent is the top level structure holding all the configurations for the Vault Agent container.

func New

func New(pod *corev1.Pod, patches []*jsonpatch.JsonPatchOperation) (*Agent, error)

New creates a new instance of Agent by parsing all the Kubernetes annotations.

func (*Agent) ContainerConfigMapVolume

func (a *Agent) ContainerConfigMapVolume() corev1.Volume

ContainerConfigMapVolume returns a volume to mount a config map if the user supplied any.

func (*Agent) ContainerEnvVars

func (a *Agent) ContainerEnvVars(init bool) ([]corev1.EnvVar, error)

ContainerEnvVars adds the applicable environment vars for the Vault Agent sidecar.

func (*Agent) ContainerExtraSecretVolume added in v0.6.0

func (a *Agent) ContainerExtraSecretVolume() corev1.Volume

ContainerExtraSecretVolume returns a volume to mount a Kube secret if the user supplied one.

func (*Agent) ContainerInitSidecar

func (a *Agent) ContainerInitSidecar() (corev1.Container, error)

ContainerInitSidecar creates a new init container to be added to the pod being mutated. After Vault 1.4 is released, this can be removed because an exit_after_auth environment variable is available for the agent. This means we won't need to generate two config files.

func (*Agent) ContainerSidecar

func (a *Agent) ContainerSidecar() (corev1.Container, error)

ContainerSidecar creates a new container to be added to the pod being mutated.

func (*Agent) ContainerTLSSecretVolume

func (a *Agent) ContainerTLSSecretVolume() corev1.Volume

ContainerTLSSecretVolume returns a volume to mount TLS secrets if the user supplied any.

func (*Agent) ContainerTokenVolume added in v0.4.0

func (a *Agent) ContainerTokenVolume() []corev1.Volume

ContainerTokenVolume returns a volume to mount the home directory where the token sink will write to.

func (*Agent) ContainerVolumeMounts added in v0.3.0

func (a *Agent) ContainerVolumeMounts() []corev1.VolumeMount

ContainerVolumeMounts mounts the shared memory volume where secrets will be rendered.

func (*Agent) ContainerVolumes added in v0.3.0

func (a *Agent) ContainerVolumes() []corev1.Volume

ContainerVolume returns the volume data to add to the pod. This volumes are used for shared data between containers.

func (*Agent) Patch

func (a *Agent) Patch() ([]byte, error)

Patch creates the necessary pod patches to inject the Vault Agent containers.

func (*Agent) Validate

func (a *Agent) Validate() error

Validate the instance of Agent to ensure we have everything needed for basic functionality.

type AgentConfig added in v0.4.0

type AgentConfig struct {
	Image              string
	Address            string
	AuthPath           string
	Namespace          string
	RevokeOnShutdown   bool
	UserID             string
	GroupID            string
	SameID             bool
	SetSecurityContext bool
}

type AutoAuth

type AutoAuth struct {
	Method *Method `json:"method,omitempty"`
	Sinks  []*Sink `json:"sink,omitempty"`
}

AutoAuth is the configured authentication method and sinks

type Cache added in v0.5.0

type Cache struct {
	UseAuthAuthToken string `json:"use_auto_auth_token"`
}

Cache defines the configuration for the Vault Agent Cache

type Config

type Config struct {
	AutoAuth      *AutoAuth    `json:"auto_auth"`
	ExitAfterAuth bool         `json:"exit_after_auth"`
	PidFile       string       `json:"pid_file"`
	Vault         *VaultConfig `json:"vault"`
	Templates     []*Template  `json:"template,omitempty"`
	Listener      []*Listener  `json:"listener,omitempty"`
	Cache         *Cache       `json:"cache,omitempty"`
}

Config is the top level struct that composes a Vault Agent configuration file.

type Listener added in v0.5.0

type Listener struct {
	Type       string `json:"type"`
	Address    string `json:"address"`
	TLSDisable bool   `json:"tls_disable"`
}

Listener defines the configuration for Vault Agent Cache Listener

type Method

type Method struct {
	Type       string                 `json:"type"`
	MountPath  string                 `json:"mount_path,omitempty"`
	WrapTTLRaw interface{}            `json:"wrap_ttl,omitempty"`
	WrapTTL    time.Duration          `json:"-"`
	Namespace  string                 `json:"namespace,omitempty"`
	Config     map[string]interface{} `json:"config,omitempty"`
}

Method represents the configuration for the authentication backend

type Secret

type Secret struct {
	// Name of the secret used to identify other annotation directives, and used
	// as the filename for the rendered secret file (unless FilePathAndName is
	// specified).
	Name string

	// Path in Vault where the secret desired can be found.
	Path string

	// Template is the optional custom template to use when rendering the secret.
	Template string

	// Mount Path for the volume holding the rendered secret file
	MountPath string

	// Command is the optional command to run after rendering the secret.
	Command string

	// FilePathAndName is the optional file path and name for the rendered secret file.
	FilePathAndName string
}

type Sink

type Sink struct {
	Type       string                 `json:"type"`
	WrapTTLRaw interface{}            `json:"wrap_ttl,omitempty"`
	WrapTTL    time.Duration          `json:"-"`
	DHType     string                 `json:"dh_type,omitempty"`
	DHPath     string                 `json:"dh_path,omitempty"`
	AAD        string                 `json:"aad,omitempty"`
	AADEnvVar  string                 `json:"aad_env_var,omitempty"`
	Config     map[string]interface{} `json:"config,omitempty"`
}

Sink defines a location to write the authenticated token

type Template

type Template struct {
	CreateDestDirs bool   `json:"create_dest_dirs,omitempty"`
	Destination    string `json:"destination"`
	Contents       string `json:"contents"`
	LeftDelim      string `json:"left_delimiter,omitempty"`
	RightDelim     string `json:"right_delimiter,omitempty"`
	Command        string `json:"command,omitempty"`
}

Template defines the Consul Template parameters

type Vault

type Vault struct {
	// Address is the Vault service address.
	Address string

	// AuthPath is the Mount Path of Vault Kubernetes Auth Method.
	AuthPath string

	// CACert is the name of the Certificate Authority certificate
	// to use when validating Vault's server certificates.
	CACert string

	// CAKey is the name of the Certificate Authority key
	// to use when validating Vault's server certificates.
	CAKey string

	// ClientCert is the name of the client certificate to use when communicating
	// with Vault over TLS.
	ClientCert string

	// ClientKey is the name of the client key to use when communicating
	// with Vault over TLS.
	ClientKey string

	// ClientMaxRetries configures the number of retries the client should make
	// when 5-- errors are received from the Vault server.  Default is 2.
	ClientMaxRetries string

	// ClientTimeout is the max number in seconds the client should attempt to
	// make a request to the Vault server.
	ClientTimeout string

	// LogLevel sets the Vault Agent log level.  Defaults to info.
	LogLevel string

	// LogFormat sets the Vault Agent log format.  Defaults to standard.
	LogFormat string

	// Namespace is the Vault namespace to prepend to secret paths.
	Namespace string

	// Role is the name of the Vault role to use for authentication.
	Role string

	// TLSSecret is the name of the secret to be mounted to the Vault Agent container
	// containing the TLS certificates required to communicate with Vault.
	TLSSecret string

	// TLSSkipVerify toggles verification of Vault's certificates.
	TLSSkipVerify bool

	// TLSServerName is the name of the Vault server to use when validating Vault's
	// TLS certificates.
	TLSServerName string
}

type VaultAgentCache added in v0.5.0

type VaultAgentCache struct {
	// Enable configures whether the cache is enabled or not
	Enable bool

	// ListenerPort is the port the cache should listen to
	ListenerPort string

	// UseAutoAuthToken configures whether the auto auth token is used in cache requests
	UseAutoAuthToken string
}

type VaultConfig

type VaultConfig struct {
	Address       string `json:"address"`
	CACert        string `json:"ca_cert,omitempty"`
	CAPath        string `json:"ca_path,omitempty"`
	TLSSkipVerify bool   `json:"tls_skip_verify,omitempty"`
	ClientCert    string `json:"client_cert,omitempty"`
	ClientKey     string `json:"client_key,omitempty"`
	TLSServerName string `json:"tls_server_name,omitempty"`
}

Vault contains configuration for connecting to Vault servers

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL