framework

package
v0.14.0 Latest Latest
Warning

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

Go to latest
Published: Sep 10, 2024 License: MPL-2.0 Imports: 42 Imported by: 334

Documentation

Index

Constants

View Source
const OASVersion = "3.0.2"

OpenAPI specification (OAS): https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.2.md

View Source
const WALPrefix = "wal/"

WALPrefix is the prefix within Storage where WAL entries will be written.

Variables

View Source
var ErrNoEvents = errors.New("no event sender configured")

ErrNoEvents is returned when attempting to send an event, but when the event sender was not passed in during `backend.Setup()`.

View Source
var OASStdRespListOK = &OASResponse{
	Description: "OK",
	Content: OASContent{
		"application/json": &OASMediaTypeObject{
			Schema: &OASSchema{
				Ref: "#/components/schemas/StandardListResponse",
			},
		},
	},
}
View Source
var OASStdRespNoContent = &OASResponse{
	Description: "empty body",
}
View Source
var OASStdRespOK = &OASResponse{
	Description: "OK",
}
View Source
var OASStdSchemaStandardListResponse = &OASSchema{
	Type: "object",
	Properties: map[string]*OASSchema{
		"keys": {
			Type: "array",
			Items: &OASSchema{
				Type: "string",
			},
		},
	},
}

Functions

func CalculateTTL

func CalculateTTL(sysView logical.SystemView, increment, backendTTL, period, backendMaxTTL, explicitMaxTTL time.Duration, startTime time.Time) (ttl time.Duration, warnings []string, errors error)

CalculateTTL takes all the user-specified, backend, and system inputs and calculates a TTL for a lease

func DeleteWAL

func DeleteWAL(ctx context.Context, s logical.Storage, id string) error

DeleteWAL commits the WAL entry with the given ID. Once committed, it is assumed that the operation was a success and doesn't need to be rolled back.

func GenericNameRegex

func GenericNameRegex(name string) string

Helper which returns a generic regex string for creating endpoint patterns that are identified by the given name in the backends

func GenericNameWithAtRegex

func GenericNameWithAtRegex(name string) string

GenericNameWithAtRegex returns a generic regex that allows alphanumeric characters along with -, . and @.

func HandlePatchOperation added in v0.3.0

func HandlePatchOperation(input *FieldData, resource map[string]interface{}, preprocessor PatchPreprocessorFunc) ([]byte, error)

HandlePatchOperation acts as an abstraction for performing JSON merge patch operations (see https://datatracker.ietf.org/doc/html/rfc7396) for HTTP PATCH requests. It is responsible for properly processing and marshalling the input and existing resource prior to performing the JSON merge operation using the MergePatch function from the json-patch library. The preprocessor is an arbitrary func that can be provided to further process the input. The MergePatch function accepts and returns byte arrays. Null values will unset fields defined within the input's FieldData (as if they were never specified) and remove user-specified keys that exist within a map field.

func ListWAL

func ListWAL(ctx context.Context, s logical.Storage) ([]string, error)

ListWAL lists all the entries in the WAL.

func MatchAllRegex

func MatchAllRegex(name string) string

Helper which returns a regex string for capturing an entire endpoint path as the given name.

func OptionalParamRegex

func OptionalParamRegex(name string) string

Helper which returns a regex string for optionally accepting the a field from the API URL

func PopulateIdentityTemplate added in v0.2.0

func PopulateIdentityTemplate(tpl string, entityID string, sysView logical.SystemView) (string, error)

PopulateIdentityTemplate takes a template string, an entity ID, and an instance of system view. It will query system view for information about the entity and use the resulting identity information to populate the template string.

func PutWAL

func PutWAL(ctx context.Context, s logical.Storage, kind string, data interface{}) (string, error)

PutWAL writes some data to the WAL.

The kind parameter is used by the framework to allow users to store multiple kinds of WAL data and to easily disambiguate what data they're expecting.

Data within the WAL that is uncommitted (CommitWAL hasn't be called) will be given to the rollback callback when an rollback operation is received, allowing the backend to clean up some partial states.

The data must be JSON encodable.

This returns a unique ID that can be used to reference this WAL data. WAL data cannot be modified. You can only add to the WAL and commit existing WAL entries.

func TestBackendRoutes

func TestBackendRoutes(t *testing.T, b *Backend, rs []string)

TestBackendRoutes is a helper to test that all the given routes will route properly in the backend.

func ValidateIdentityTemplate added in v0.2.0

func ValidateIdentityTemplate(tpl string) (bool, error)

ValidateIdentityTemplate takes a template string and returns if the string is a valid identity template.

Types

type Backend

type Backend struct {
	// Help is the help text that is shown when a help request is made
	// on the root of this resource. The root help is special since we
	// show all the paths that can be requested.
	Help string

	// Paths are the various routes that the backend responds to.
	// This cannot be modified after construction (i.e. dynamically changing
	// paths, including adding or removing, is not allowed once the
	// backend is in use).
	//
	// PathsSpecial is the list of path patterns that denote the paths above
	// that require special privileges.
	Paths        []*Path
	PathsSpecial *logical.Paths

	// Secrets is the list of secret types that this backend can
	// return. It is used to automatically generate proper responses,
	// and ease specifying callbacks for revocation, renewal, etc.
	Secrets []*Secret

	// InitializeFunc is the callback, which if set, will be invoked via
	// Initialize() just after a plugin has been mounted.
	//
	// Note that storage writes should only occur on the active instance within a
	// primary cluster or local mount on a performance secondary. If your InitializeFunc
	// writes to storage, you can use the backend's WriteSafeReplicationState() method
	// to prevent it from attempting to write on a Vault instance with read-only storage.
	InitializeFunc InitializeFunc

	// PeriodicFunc is the callback, which if set, will be invoked when the
	// periodic timer of RollbackManager ticks. This can be used by
	// backends to do anything it wishes to do periodically.
	//
	// PeriodicFunc can be invoked to, say periodically delete stale
	// entries in backend's storage, while the backend is still being used.
	// (Note the difference between this action and `Clean`, which is
	// invoked just before the backend is unmounted).
	//
	// Note that storage writes should only occur on the active instance within a
	// primary cluster or local mount on a performance secondary. If your PeriodicFunc
	// writes to storage, you can use the backend's WriteSafeReplicationState() method
	// to prevent it from attempting to write on a Vault instance with read-only storage.
	PeriodicFunc periodicFunc

	// WALRollback is called when a WAL entry (see wal.go) has to be rolled
	// back. It is called with the data from the entry.
	//
	// WALRollbackMinAge is the minimum age of a WAL entry before it is attempted
	// to be rolled back. This should be longer than the maximum time it takes
	// to successfully create a secret.
	WALRollback       WALRollbackFunc
	WALRollbackMinAge time.Duration

	// Clean is called on unload to clean up e.g any existing connections
	// to the backend, if required.
	Clean CleanupFunc

	// Invalidate is called when a key is modified, if required.
	Invalidate InvalidateFunc

	// AuthRenew is the callback to call when a RenewRequest for an
	// authentication comes in. By default, renewal won't be allowed.
	// See the built-in AuthRenew helpers in lease.go for common callbacks.
	AuthRenew OperationFunc

	// BackendType is the logical.BackendType for the backend implementation
	BackendType logical.BackendType

	// RunningVersion is the optional version that will be self-reported
	RunningVersion string
	// contains filtered or unexported fields
}

Backend is an implementation of logical.Backend that allows the implementer to code a backend using a much more programmer-friendly framework that handles a lot of the routing and validation for you.

This is recommended over implementing logical.Backend directly.

func (*Backend) Cleanup

func (b *Backend) Cleanup(ctx context.Context)

Cleanup is used to release resources and prepare to stop the backend

func (*Backend) GetRandomReader added in v0.2.0

func (b *Backend) GetRandomReader() io.Reader

GetRandomReader returns an io.Reader to use for generating key material in backends. If the backend has access to an external entropy source it will return that, otherwise it returns crypto/rand.Reader.

func (*Backend) HandleExistenceCheck

func (b *Backend) HandleExistenceCheck(ctx context.Context, req *logical.Request) (checkFound bool, exists bool, err error)

HandleExistenceCheck is the logical.Backend implementation.

func (*Backend) HandleRequest

func (b *Backend) HandleRequest(ctx context.Context, req *logical.Request) (*logical.Response, error)

HandleRequest is the logical.Backend implementation.

func (*Backend) Initialize added in v0.1.12

func (b *Backend) Initialize(ctx context.Context, req *logical.InitializationRequest) error

Initialize is the logical.Backend implementation.

func (*Backend) InvalidateKey

func (b *Backend) InvalidateKey(ctx context.Context, key string)

InvalidateKey is used to clear caches and reset internal state on key changes

func (*Backend) Logger

func (b *Backend) Logger() log.Logger

Logger can be used to get the logger. If no logger has been set, the logs will be discarded.

func (*Backend) PluginVersion added in v0.6.0

func (b *Backend) PluginVersion() logical.PluginVersion

Version returns the plugin version information

func (*Backend) Route

func (b *Backend) Route(path string) *Path

Route looks up the path that would be used for a given path string.

func (*Backend) Secret

func (b *Backend) Secret(k string) *Secret

Secret is used to look up the secret with the given type.

func (*Backend) SendEvent added in v0.8.0

func (b *Backend) SendEvent(ctx context.Context, eventType logical.EventType, event *logical.EventData) error

SendEvent is used to send events through the underlying EventSender. It returns ErrNoEvents if the events system has not been configured or enabled.

func (*Backend) Setup

func (b *Backend) Setup(ctx context.Context, config *logical.BackendConfig) error

Setup is used to initialize the backend with the initial backend configuration

func (*Backend) SpecialPaths

func (b *Backend) SpecialPaths() *logical.Paths

SpecialPaths is the logical.Backend implementation.

func (*Backend) System

func (b *Backend) System() logical.SystemView

System returns the backend's system view.

func (*Backend) Type

func (b *Backend) Type() logical.BackendType

Type returns the backend type

func (*Backend) WriteSafeReplicationState added in v0.9.2

func (b *Backend) WriteSafeReplicationState() bool

WriteSafeReplicationState returns true if this backend instance is capable of writing to storage without receiving an ErrReadOnly error. The active instance in a primary cluster or a local mount on a performance secondary is capable of writing to storage.

type CleanupFunc

type CleanupFunc func(context.Context)

CleanupFunc is the callback for backend unload.

type DisplayAttributes added in v0.1.12

type DisplayAttributes struct {
	// Name is the name of the field suitable as a label or documentation heading.
	Name string `json:"name,omitempty"`

	// Description of the field that renders as tooltip help text beside the label (name) in the UI.
	// This may be used to replace descriptions that reference comma separation but correspond
	// to UI inputs where only arrays are valid. For example params with Type: framework.TypeCommaStringSlice
	Description string `json:"description,omitempty"`

	// Value is a sample value to display for this field. This may be used
	// to indicate a default value, but it is for display only and completely separate
	// from any Default member handling.
	Value interface{} `json:"value,omitempty"`

	// Sensitive indicates that the value should be masked by default in the UI.
	Sensitive bool `json:"sensitive,omitempty"`

	// Navigation indicates that the path should be available as a navigation tab
	Navigation bool `json:"navigation,omitempty"`

	// ItemType is the type of item this path operates on
	ItemType string `json:"itemType,omitempty"`

	// Group is the suggested UI group to place this field in.
	Group string `json:"group,omitempty"`

	// Action is the verb to use for the operation.
	Action string `json:"action,omitempty"`

	// OperationPrefix is a hyphenated lower-case string used to construct
	// OpenAPI OperationID (prefix + verb + suffix). OperationPrefix is
	// typically a human-readable name of the plugin or a prefix shared by
	// multiple related endpoints.
	OperationPrefix string `json:"operationPrefix,omitempty"`

	// OperationVerb is a hyphenated lower-case string used to construct
	// OpenAPI OperationID (prefix + verb + suffix). OperationVerb is typically
	// an action to be performed (e.g. "generate", "sign", "login", etc.). If
	// not specified, the verb defaults to `logical.Operation.String()`
	// (e.g. "read", "list", "delete", "write" for Create/Update)
	OperationVerb string `json:"operationVerb,omitempty"`

	// OperationSuffix is a hyphenated lower-case string used to construct
	// OpenAPI OperationID (prefix + verb + suffix). It is typically the name
	// of the resource on which the action is performed (e.g. "role",
	// "credentials", etc.). A pipe (|) separator can be used to list different
	// suffixes for various permutations of the `Path.Pattern` regular
	// expression. If not specified, the suffix defaults to the `Path.Pattern`
	// split by dashes.
	OperationSuffix string `json:"operationSuffix,omitempty"`

	// EditType is the optional type of form field needed for a property
	// This is only necessary for a "textarea" or "file"
	EditType string `json:"editType,omitempty"`
}

type ExistenceFunc

type ExistenceFunc func(context.Context, *logical.Request, *FieldData) (bool, error)

ExistenceFunc is the callback called for an existence check on a path.

type FieldData

type FieldData struct {
	Raw    map[string]interface{}
	Schema map[string]*FieldSchema
}

FieldData is the structure passed to the callback to handle a path containing the populated parameters for fields. This should be used instead of the raw (*vault.Request).Data to access data in a type-safe way.

func (*FieldData) Get

func (d *FieldData) Get(k string) interface{}

Get gets the value for the given field. If the key is an invalid field, FieldData will panic. If you want a safer version of this method, use GetOk. If the field k is not set, the default value (if set) will be returned, otherwise the zero value will be returned.

func (*FieldData) GetDefaultOrZero

func (d *FieldData) GetDefaultOrZero(k string) interface{}

GetDefaultOrZero gets the default value set on the schema for the given field. If there is no default value set, the zero value of the type will be returned.

func (*FieldData) GetFirst

func (d *FieldData) GetFirst(k ...string) (interface{}, bool)

GetFirst gets the value for the given field names, in order from first to last. This can be useful for fields with a current name, and one or more deprecated names. The second return value will be false if the keys are invalid or the keys are not set at all.

func (*FieldData) GetOk

func (d *FieldData) GetOk(k string) (interface{}, bool)

GetOk gets the value for the given field. The second return value will be false if the key is invalid or the key is not set at all. If the field k is set and the decoded value is nil, the default or zero value will be returned instead.

func (*FieldData) GetOkErr

func (d *FieldData) GetOkErr(k string) (interface{}, bool, error)

GetOkErr is the most conservative of all the Get methods. It returns whether key is set or not, but also an error value. The error value is non-nil if the field doesn't exist or there was an error parsing the field value.

func (*FieldData) Validate

func (d *FieldData) Validate() error

Validate cycles through raw data and validates conversions in the schema, so we don't get an error/panic later when trying to get data out. Data not in the schema is not an error at this point, so we don't worry about it.

func (*FieldData) ValidateStrict added in v0.7.0

func (d *FieldData) ValidateStrict() error

ValidateStrict cycles through raw data and validates conversions in the schema. In addition to the checks done by Validate, this function ensures that the raw data has all of the schema's required fields and does not have any fields outside of the schema. It will return a non-nil error if:

  1. a conversion (parsing of the field's value) fails
  2. a raw field does not exist in the schema (unless the schema is nil)
  3. a required schema field is missing from the raw data

This function is currently used for validating response schemas in tests.

type FieldSchema

type FieldSchema struct {
	Type        FieldType
	Default     interface{}
	Description string

	// The Required and Deprecated members are only used by openapi, and are not actually
	// used by the framework.
	Required   bool
	Deprecated bool

	// Query indicates this field will be expected as a query parameter as part
	// of ReadOperation, ListOperation or DeleteOperation requests:
	//
	//   /v1/foo/bar?some_param=some_value
	//
	// The field will still be expected as a request body parameter for
	// CreateOperation or UpdateOperation requests!
	//
	// To put that another way, you should set Query for any non-path parameter
	// you want to use in a read/list/delete operation.  While setting the Query
	// field to `true` is not required in such cases (Vault will expose the
	// query parameters to you via req.Data regardless), it is highly
	// recommended to do so in order to improve the quality of the generated
	// OpenAPI documentation (as well as any code generation based on it), which
	// will otherwise incorrectly omit the parameter.
	//
	// The reason for this design is historical: back at the start of 2018,
	// query parameters were not mapped to fields at all, and it was implicit
	// that all non-path fields were exclusively for the use of create/update
	// operations.  Since then, support for query parameters has gradually been
	// extended to read, delete and list operations - and now this declarative
	// metadata is needed, so that the OpenAPI generator can know which
	// parameters are actually referred to, from within the code of
	// read/delete/list operation handler functions.
	Query bool

	// AllowedValues is an optional list of permitted values for this field.
	// This constraint is not (yet) enforced by the framework, but the list is
	// output as part of OpenAPI generation and may affect documentation and
	// dynamic UI generation.
	AllowedValues []interface{}

	// DisplayAttrs provides hints for UI and documentation generators. They
	// will be included in OpenAPI output if set.
	DisplayAttrs *DisplayAttributes
}

FieldSchema is a basic schema to describe the format of a path field.

func (*FieldSchema) DefaultOrZero

func (s *FieldSchema) DefaultOrZero() interface{}

DefaultOrZero returns the default value if it is set, or otherwise the zero value of the type.

type FieldType

type FieldType uint

FieldType is the enum of types that a field can be.

const (
	TypeInvalid FieldType = 0
	TypeString  FieldType = iota
	TypeInt
	TypeInt64
	TypeBool
	TypeMap

	// TypeDurationSecond represent as seconds, this can be either an
	// integer or go duration format string (e.g. 24h)
	TypeDurationSecond

	// TypeSignedDurationSecond represents a positive or negative duration
	// as seconds, this can be either an integer or go duration format
	// string (e.g. 24h).
	TypeSignedDurationSecond

	// TypeSlice represents a slice of any type
	TypeSlice

	// TypeStringSlice is a helper for TypeSlice that returns a sanitized
	// slice of strings
	TypeStringSlice

	// TypeCommaStringSlice is a helper for TypeSlice that returns a sanitized
	// slice of strings and also supports parsing a comma-separated list in
	// a string field
	TypeCommaStringSlice

	// TypeLowerCaseString is a helper for TypeString that returns a lowercase
	// version of the provided string
	TypeLowerCaseString

	// TypeNameString represents a name that is URI safe and follows specific
	// rules.  These rules include start and end with an alphanumeric
	// character and characters in the middle can be alphanumeric or . or -.
	TypeNameString

	// TypeKVPairs allows you to represent the data as a map or a list of
	// equal sign delimited key pairs
	TypeKVPairs

	// TypeCommaIntSlice is a helper for TypeSlice that returns a sanitized
	// slice of Ints
	TypeCommaIntSlice

	// TypeHeader is a helper for sending request headers through to Vault.
	// For instance, the AWS and AliCloud credential plugins both act as a
	// benevolent MITM for a request, and the headers are sent through and
	// parsed.
	TypeHeader

	// TypeFloat parses both float32 and float64 values
	TypeFloat

	// TypeTime represents absolute time. It accepts an RFC3339-formatted
	// string (with or without fractional seconds), or an epoch timestamp
	// formatted as a string or a number. The resulting time.Time
	// is converted to UTC.
	TypeTime
)

func (FieldType) String

func (t FieldType) String() string

func (FieldType) Zero

func (t FieldType) Zero() interface{}

Zero returns the correct zero-value for a specific FieldType

type InitializeFunc added in v0.1.12

type InitializeFunc func(context.Context, *logical.InitializationRequest) error

InitializeFunc is the callback, which if set, will be invoked via Initialize() just after a plugin has been mounted.

type InvalidateFunc

type InvalidateFunc func(context.Context, string)

InvalidateFunc is the callback for backend key invalidation.

type OASComponents added in v0.5.0

type OASComponents struct {
	Schemas map[string]*OASSchema `json:"schemas"`
}

type OASContent

type OASContent map[string]*OASMediaTypeObject

type OASDocument

type OASDocument struct {
	Version    string                  `json:"openapi" mapstructure:"openapi"`
	Info       OASInfo                 `json:"info"`
	Paths      map[string]*OASPathItem `json:"paths"`
	Components OASComponents           `json:"components"`
}

func NewOASDocument

func NewOASDocument(version string) *OASDocument

NewOASDocument returns an empty OpenAPI document.

func NewOASDocumentFromMap

func NewOASDocumentFromMap(input map[string]interface{}) (*OASDocument, error)

NewOASDocumentFromMap builds an OASDocument from an existing map version of a document. If a document has been decoded from JSON or received from a plugin, it will be as a map[string]interface{} and needs special handling beyond the default mapstructure decoding.

func (*OASDocument) CreateOperationIDs deprecated

func (d *OASDocument) CreateOperationIDs(context string)

CreateOperationIDs generates unique operationIds for all paths/methods. The transform will convert path/method into camelcase. e.g.:

/sys/tools/random/{urlbytes} -> postSysToolsRandomUrlbytes

In the unlikely case of a duplicate ids, a numeric suffix is added:

postSysToolsRandomUrlbytes_2

An optional user-provided suffix ("context") may also be appended.

Deprecated: operationID's are now populated using `constructOperationID`. This function is here for backwards compatibility with older plugins.

type OASInfo

type OASInfo struct {
	Title       string     `json:"title"`
	Description string     `json:"description"`
	Version     string     `json:"version"`
	License     OASLicense `json:"license"`
}

type OASLicense

type OASLicense struct {
	Name string `json:"name"`
	URL  string `json:"url"`
}

type OASMediaTypeObject

type OASMediaTypeObject struct {
	Schema *OASSchema `json:"schema,omitempty"`
}

type OASOperation

type OASOperation struct {
	Summary     string               `json:"summary,omitempty"`
	Description string               `json:"description,omitempty"`
	OperationID string               `json:"operationId,omitempty"`
	Tags        []string             `json:"tags,omitempty"`
	Parameters  []OASParameter       `json:"parameters,omitempty"`
	RequestBody *OASRequestBody      `json:"requestBody,omitempty"`
	Responses   map[int]*OASResponse `json:"responses"`
	Deprecated  bool                 `json:"deprecated,omitempty"`
}

func NewOASOperation

func NewOASOperation() *OASOperation

NewOASOperation creates an empty OpenAPI Operations object.

type OASParameter

type OASParameter struct {
	Name        string     `json:"name"`
	Description string     `json:"description,omitempty"`
	In          string     `json:"in"`
	Schema      *OASSchema `json:"schema,omitempty"`
	Required    bool       `json:"required,omitempty"`
	Deprecated  bool       `json:"deprecated,omitempty"`
}

type OASPathItem

type OASPathItem struct {
	Description     string             `json:"description,omitempty"`
	Parameters      []OASParameter     `json:"parameters,omitempty"`
	Sudo            bool               `json:"x-vault-sudo,omitempty" mapstructure:"x-vault-sudo"`
	Unauthenticated bool               `json:"x-vault-unauthenticated,omitempty" mapstructure:"x-vault-unauthenticated"`
	CreateSupported bool               `json:"x-vault-createSupported,omitempty" mapstructure:"x-vault-createSupported"`
	DisplayAttrs    *DisplayAttributes `json:"x-vault-displayAttrs,omitempty" mapstructure:"x-vault-displayAttrs"`

	Get    *OASOperation `json:"get,omitempty"`
	Post   *OASOperation `json:"post,omitempty"`
	Delete *OASOperation `json:"delete,omitempty"`
}

type OASRequestBody

type OASRequestBody struct {
	Description string     `json:"description,omitempty"`
	Required    bool       `json:"required,omitempty"`
	Content     OASContent `json:"content,omitempty"`
}

type OASResponse

type OASResponse struct {
	Description string     `json:"description"`
	Content     OASContent `json:"content,omitempty"`
}

type OASSchema

type OASSchema struct {
	Ref         string                `json:"$ref,omitempty"`
	Type        string                `json:"type,omitempty"`
	Description string                `json:"description,omitempty"`
	Properties  map[string]*OASSchema `json:"properties,omitempty"`

	AdditionalProperties interface{} `json:"additionalProperties,omitempty"`

	// Required is a list of keys in Properties that are required to be present. This is a different
	// approach than OASParameter (unfortunately), but is how JSONSchema handles 'required'.
	Required []string `json:"required,omitempty"`

	Items      *OASSchema    `json:"items,omitempty"`
	Format     string        `json:"format,omitempty"`
	Pattern    string        `json:"pattern,omitempty"`
	Enum       []interface{} `json:"enum,omitempty"`
	Default    interface{}   `json:"default,omitempty"`
	Example    interface{}   `json:"example,omitempty"`
	Deprecated bool          `json:"deprecated,omitempty"`
	// DisplayName      string             `json:"x-vault-displayName,omitempty" mapstructure:"x-vault-displayName,omitempty"`
	DisplayValue     interface{}        `json:"x-vault-displayValue,omitempty" mapstructure:"x-vault-displayValue,omitempty"`
	DisplaySensitive bool               `json:"x-vault-displaySensitive,omitempty" mapstructure:"x-vault-displaySensitive,omitempty"`
	DisplayGroup     string             `json:"x-vault-displayGroup,omitempty" mapstructure:"x-vault-displayGroup,omitempty"`
	DisplayAttrs     *DisplayAttributes `json:"x-vault-displayAttrs,omitempty" mapstructure:"x-vault-displayAttrs,omitempty"`
}

type OperationFunc

type OperationFunc func(context.Context, *logical.Request, *FieldData) (*logical.Response, error)

OperationFunc is the callback called for an operation on a path.

func GlobListFilter added in v0.2.0

func GlobListFilter(fieldName string, callback OperationFunc) OperationFunc

GlobListFilter wraps an OperationFunc with an optional filter which excludes listed entries which don't match a glob style pattern

func LeaseExtend

func LeaseExtend(backendIncrement, backendMax time.Duration, systemView logical.SystemView) OperationFunc

LeaseExtend is left for backwards compatibility for plugins. This function now just passes back the data that was passed into it to be processed in core. DEPRECATED

type OperationHandler

type OperationHandler interface {
	Handler() OperationFunc
	Properties() OperationProperties
}

OperationHandler defines and describes a specific operation handler.

type OperationProperties

type OperationProperties struct {
	// Summary is a brief (usually one line) description of the operation.
	Summary string

	// Description is extended documentation of the operation and may contain
	// Markdown-formatted text markup.
	Description string

	// Examples provides samples of the expected request data. The most
	// relevant example should be first in the list, as it will be shown in
	// documentation that supports only a single example.
	Examples []RequestExample

	// Responses provides a list of response description for a given response
	// code. The most relevant response should be first in the list, as it will
	// be shown in documentation that only allows a single example.
	Responses map[int][]Response

	// Unpublished indicates that this operation should not appear in public
	// documentation or help text. The operation may still have documentation
	// attached that can be used internally.
	Unpublished bool

	// Deprecated indicates that this operation should be avoided.
	Deprecated bool

	// The ForwardPerformance* parameters tell the router to unconditionally forward requests
	// to this path if the processing node is a performance secondary/standby. This is generally
	// *not* needed as there is already handling in place to automatically forward requests
	// that try to write to storage. But there are a few cases where explicit forwarding is needed,
	// for example:
	//
	// * The handler makes requests to other systems (e.g. an external API, database, ...) that
	//   change external state somehow, and subsequently writes to storage. In this case the
	//   default forwarding logic could result in multiple mutative calls to the external system.
	//
	// * The operation spans multiple requests (e.g. an OIDC callback), in-memory caching used,
	//   and the same node (and therefore cache) should process both steps.
	//
	// If explicit forwarding is needed, it is usually true that forwarding from both performance
	// standbys and performance secondaries should be enabled.
	//
	// ForwardPerformanceStandby indicates that this path should not be processed
	// on a performance standby node, and should be forwarded to the active node instead.
	ForwardPerformanceStandby bool

	// ForwardPerformanceSecondary indicates that this path should not be processed
	// on a performance secondary node, and should be forwarded to the active node instead.
	ForwardPerformanceSecondary bool

	// DisplayAttrs provides hints for UI and documentation generators. They
	// will be included in OpenAPI output if set.
	DisplayAttrs *DisplayAttributes
}

OperationProperties describes an operation for documentation, help text, and other clients. A Summary should always be provided, whereas other fields can be populated as needed.

type PatchPreprocessorFunc added in v0.3.0

type PatchPreprocessorFunc func(map[string]interface{}) (map[string]interface{}, error)

PatchPreprocessorFunc is used by HandlePatchOperation in order to shape the input as defined by request handler prior to JSON marshaling

type Path

type Path struct {
	// Pattern is the pattern of the URL that matches this path.
	//
	// This should be a valid regular expression. Named captures will be
	// exposed as fields that should map to a schema in Fields. If a named
	// capture is not a field in the Fields map, then it will be ignored.
	//
	// The pattern will automatically have a ^ prepended and a $ appended before
	// use, if these are not already present, so these may be omitted for clarity.
	//
	// If a ListOperation is being defined, the pattern must end with /? to match
	// a trailing slash optionally, as ListOperations are always processed with a
	// trailing slash added to the path if not already present. The match must not
	// require the presence of a trailing slash, as HelpOperations, even for a
	// path which only implements ListOperation, are processed without a trailing
	// slash - so failure to make the trailing slash optional will break the
	// `vault path-help` command for the path.
	Pattern string

	// Fields is the mapping of data fields to a schema describing that
	// field.
	//
	// Field values are obtained from:
	//
	// - Named captures in the Pattern.
	//
	// - Parameters in the HTTP request body, for HTTP methods where a
	//   request body is expected, i.e. PUT/POST/PATCH. The request body is
	//   typically formatted as JSON, though
	//   "application/x-www-form-urlencoded" format can also be accepted.
	//
	// - Parameters in the HTTP URL query-string, for HTTP methods where
	//   there is no request body, i.e. GET/LIST/DELETE. The query-string
	//   is *not* parsed at all for PUT/POST/PATCH requests.
	//
	// Should the same field be specified both as a named capture and as
	// a parameter, the named capture takes precedence, and a warning is
	// returned.
	Fields map[string]*FieldSchema

	// Operations is the set of operations supported and the associated OperationsHandler.
	//
	// If both Create and Update operations are present, documentation and examples from
	// the Update definition will be used. Similarly if both Read and List are present,
	// Read will be used for documentation.
	Operations map[logical.Operation]OperationHandler

	// Callbacks are the set of callbacks that are called for a given
	// operation. If a callback for a specific operation is not present,
	// then logical.ErrUnsupportedOperation is automatically generated.
	//
	// The help operation is the only operation that the Path will
	// automatically handle if the Help field is set. If both the Help
	// field is set and there is a callback registered here, then the
	// callback will be called.
	//
	// Deprecated: Operations should be used instead and will take priority if present.
	Callbacks map[logical.Operation]OperationFunc

	// ExistenceCheck, if implemented, is used to query whether a given
	// resource exists or not. This is used for ACL purposes: if an Update
	// action is specified, and the existence check returns false, the action
	// is not allowed since the resource must first be created. The reverse is
	// also true. If not specified, the Update action is forced and the user
	// must have UpdateCapability on the path.
	ExistenceCheck ExistenceFunc

	// FeatureRequired, if implemented, will validate if the given feature is
	// enabled for the set of paths
	FeatureRequired license.Features

	// Deprecated denotes that this path is considered deprecated. This may
	// be reflected in help and documentation.
	Deprecated bool

	// Help is text describing how to use this path. This will be used
	// to auto-generate the help operation. The Path will automatically
	// generate a parameter listing and URL structure based on the
	// regular expression, so the help text should just contain a description
	// of what happens.
	//
	// HelpSynopsis is a one-sentence description of the path. This will
	// be automatically line-wrapped at 80 characters.
	//
	// HelpDescription is a long-form description of the path. This will
	// be automatically line-wrapped at 80 characters.
	HelpSynopsis    string
	HelpDescription string

	// DisplayAttrs provides hints for UI and documentation generators. They
	// will be included in OpenAPI output if set.
	DisplayAttrs *DisplayAttributes

	// TakesArbitraryInput is used for endpoints that take arbitrary input, instead
	// of or as well as their Fields. This is taken into account when printing
	// warnings about ignored fields. If this is set, we will not warn when data is
	// provided that is not part of the Fields declaration.
	TakesArbitraryInput bool
}

Path is a single path that the backend responds to.

func PathAppend

func PathAppend(paths ...[]*Path) []*Path

PathAppend is a helper for appending lists of paths into a single list.

type PathMap

type PathMap struct {
	Prefix        string
	Name          string
	Schema        map[string]*FieldSchema
	CaseSensitive bool
	Salt          *saltpkg.Salt
	SaltFunc      func(context.Context) (*saltpkg.Salt, error)
	// contains filtered or unexported fields
}

DEPRECATED: Don't use this. It's too inflexible, nearly impossible to use with some modern Vault features, and imposes specific API designs.

PathMap can be used to generate a path that stores mappings in the storage. It is a structure that also exports functions for querying the mappings.

The primary use case for this is for credential providers to do their mapping to policies.

func (*PathMap) Delete

func (p *PathMap) Delete(ctx context.Context, s logical.Storage, k string) error

Delete removes a value from the mapping

func (*PathMap) Get

func (p *PathMap) Get(ctx context.Context, s logical.Storage, k string) (map[string]interface{}, error)

Get reads a value out of the mapping

func (*PathMap) List

func (p *PathMap) List(ctx context.Context, s logical.Storage, prefix string) ([]string, error)

List reads the keys under a given path

func (*PathMap) Paths

func (p *PathMap) Paths() []*Path

Paths are the paths to append to the Backend paths.

func (*PathMap) Put

func (p *PathMap) Put(ctx context.Context, s logical.Storage, k string, v map[string]interface{}) error

Put writes a value into the mapping

type PathOperation

type PathOperation struct {
	Callback                    OperationFunc
	Summary                     string
	Description                 string
	Examples                    []RequestExample
	Responses                   map[int][]Response
	Unpublished                 bool
	Deprecated                  bool
	ForwardPerformanceSecondary bool
	ForwardPerformanceStandby   bool
	DisplayAttrs                *DisplayAttributes
}

PathOperation is a concrete implementation of OperationHandler.

func (*PathOperation) Handler

func (p *PathOperation) Handler() OperationFunc

func (*PathOperation) Properties

func (p *PathOperation) Properties() OperationProperties

type PathStruct

type PathStruct struct {
	Name            string
	Path            string
	Schema          map[string]*FieldSchema
	HelpSynopsis    string
	HelpDescription string

	Read bool
}

PathStruct can be used to generate a path that stores a struct in the storage. This structure is a map[string]interface{} but the types are set according to the schema in this structure.

func (*PathStruct) Delete

func (p *PathStruct) Delete(ctx context.Context, s logical.Storage) error

Delete removes the structure.

func (*PathStruct) Get

func (p *PathStruct) Get(ctx context.Context, s logical.Storage) (map[string]interface{}, error)

Get reads the structure.

func (*PathStruct) Paths

func (p *PathStruct) Paths() []*Path

Paths are the paths to append to the Backend paths.

func (*PathStruct) Put

func (p *PathStruct) Put(ctx context.Context, s logical.Storage, v map[string]interface{}) error

Put writes the structure.

type PolicyMap

type PolicyMap struct {
	PathMap

	DefaultKey string
	PolicyKey  string
}

DEPRECATED: Don't use this. It's too inflexible, nearly impossible to use with some modern Vault features, and imposes specific API designs.

PolicyMap is a specialization of PathMap that expects the values to be lists of policies. This assists in querying and loading policies from the PathMap.

func (*PolicyMap) Policies

func (p *PolicyMap) Policies(ctx context.Context, s logical.Storage, names ...string) ([]string, error)

type RequestExample

type RequestExample struct {
	Description string                 // optional description of the request
	Data        map[string]interface{} // map version of sample JSON request data

	// Optional example response to the sample request. This approach is considered
	// provisional for now, and this field may be changed or removed.
	Response *Response
}

RequestExample is example of request data.

type Response

type Response struct {
	Description string                  // summary of the response and should always be provided
	MediaType   string                  // media type of the response, defaulting to "application/json" if empty
	Fields      map[string]*FieldSchema // the fields present in this response, used to generate openapi response
	Example     *logical.Response       // example response data
}

Response describes and optional demonstrations an operation response.

type Secret

type Secret struct {
	// Type is the name of this secret type. This is used to setup the
	// vault ID and to look up the proper secret structure when revocation/
	// renewal happens. Once this is set this should not be changed.
	//
	// The format of this must match (case insensitive): ^a-Z0-9_$
	Type string

	// Fields is the mapping of data fields and schema that comprise
	// the structure of this secret.
	Fields map[string]*FieldSchema

	// DefaultDuration is the default value for the duration of the lease for
	// this secret. This can be manually overwritten with the result of
	// Response().
	//
	// If these aren't set, Vault core will set a default lease period which
	// may come from a mount tuning.
	DefaultDuration time.Duration

	// Renew is the callback called to renew this secret. If Renew is
	// not specified then renewable is set to false in the secret.
	// See lease.go for helpers for this value.
	Renew OperationFunc

	// Revoke is the callback called to revoke this secret. This is required.
	Revoke OperationFunc
}

Secret is a type of secret that can be returned from a backend.

func (*Secret) HandleRenew

func (s *Secret) HandleRenew(ctx context.Context, req *logical.Request) (*logical.Response, error)

HandleRenew is the request handler for renewing this secret.

func (*Secret) HandleRevoke

func (s *Secret) HandleRevoke(ctx context.Context, req *logical.Request) (*logical.Response, error)

HandleRevoke is the request handler for revoking this secret.

func (*Secret) Renewable

func (s *Secret) Renewable() bool

func (*Secret) Response

func (s *Secret) Response(
	data, internal map[string]interface{},
) *logical.Response

type WALEntry

type WALEntry struct {
	ID        string      `json:"-"`
	Kind      string      `json:"type"`
	Data      interface{} `json:"data"`
	CreatedAt int64       `json:"created_at"`
}

func GetWAL

func GetWAL(ctx context.Context, s logical.Storage, id string) (*WALEntry, error)

GetWAL reads a specific entry from the WAL. If the entry doesn't exist, then nil value is returned.

The kind, value, and error are returned.

type WALRollbackFunc

type WALRollbackFunc func(context.Context, *logical.Request, string, interface{}) error

WALRollbackFunc is the callback for rollbacks.

Jump to

Keyboard shortcuts

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