framework

package
v0.12.0 Latest Latest
Warning

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

Go to latest
Published: May 13, 2026 License: MPL-2.0 Imports: 31 Imported by: 0

Documentation

Index

Constants

View Source
const (
	DefaultMaxBodySize = int64(10485760) // 10MB
	DefaultTimeout     = 30 * time.Second
)

Default values for common provider fields

View Source
const (
	// MaxBodySizeLimit is the maximum allowed value for max_body_size (100MB).
	MaxBodySizeLimit = 104857600
)
View Source
const OASVersion = "3.0.2"

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

Variables

View Source
var DefaultAuthRolePattern = regexp.MustCompile(`^role/([^/]+)/gateway`)

DefaultAuthRolePattern is the default pattern for extracting the auth role from transparent paths. Matches: role/{role}/gateway... and extracts the auth role name.

View Source
var OASStdRespNoContent = &OASResponse{
	Description: "empty body",
}
View Source
var OASStdRespOK = &OASResponse{
	Description: "OK",
}

Functions

func DefaultPathRewriter

func DefaultPathRewriter(path string) string

DefaultPathRewriter rewrites transparent paths to standard paths. Converts: role/X/gateway/... -> gateway/...

func DefaultTokenExtractor

func DefaultTokenExtractor(r *http.Request) string

DefaultTokenExtractor is the default token extraction function. It checks X-Warden-Token header first, then falls back to Authorization: Bearer.

func DocumentMount added in v0.12.0

func DocumentMount(b any, mountPrefix string, doc *OASDocument) error

DocumentMount documents a mounted backend's regular Paths into `doc`, prepending `mountPrefix` to every path key. Accepts any logical.Backend value: provider wrappers, *StreamingBackend, *Backend itself; the framework-level extraction is handled internally.

StreamingPaths (e.g. gateway/.* proxies) are intentionally NOT documented: they accept arbitrary HTTP methods, sub-paths, and bodies, so any OAS fragment we'd emit would be fictional and would mislead agents and codegen tooling about what methods are actually supported.

func DocumentPaths added in v0.12.0

func DocumentPaths(backend *Backend, requestResponsePrefix string, doc *OASDocument) error

DocumentPaths parses all paths in a framework.Backend into OpenAPI paths. Path keys in the result are relative to the backend (not mount-prefixed). For a server-wide assembly, prefer DocumentPathsWithMountPrefix.

func DocumentPathsWithMountPrefix added in v0.12.0

func DocumentPathsWithMountPrefix(backend *Backend, mountPrefix string, doc *OASDocument) error

DocumentPathsWithMountPrefix is the warden-facing entry point for assembling a server-wide OAS doc. It documents `backend` into `doc`, prepending `mountPrefix` to every path key so multiple mounts don't collide. The upstream `requestResponsePrefix` argument controls operation-ID and component-schema naming and is set to a slug derived from the mount.

`mountPrefix` must be non-empty; passing "" returns an error rather than silently producing malformed `//<path>` keys that would conflict across mounts.

Use DocumentPaths (no prefix) when you want a single backend's spec without mount-relative path prefixing, e.g. for the per-backend `?warden-help=1` response.

func GenericNameRegex

func GenericNameRegex(name string) string

GenericNameRegex 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 GetConfigString added in v0.11.0

func GetConfigString(conf map[string]any, key, defaultValue string) string

GetConfigString extracts a string value from config with a default.

func MatchAllRegex

func MatchAllRegex(name string) string

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

func OptionalGenericNameRegex

func OptionalGenericNameRegex(name string) string

OptionalGenericNameRegex returns a regex string for optionally matching a name

func OptionalParamRegex

func OptionalParamRegex(name string) string

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

func ParseMaxBodySize added in v0.11.0

func ParseMaxBodySize(conf map[string]any) int64

ParseMaxBodySize extracts max_body_size from config. Handles int, int64, float64, json.Number, and string. Returns DefaultMaxBodySize if missing or invalid.

func ParseTLSConfig added in v0.11.0

func ParseTLSConfig(conf map[string]any) (tlsSkipVerify bool, caData string)

ParseTLSConfig extracts tls_skip_verify and ca_data from config.

func ParseTimeout added in v0.11.0

func ParseTimeout(conf map[string]any, defaultTimeout time.Duration) time.Duration

ParseTimeout extracts timeout from config. Handles string (duration format) and int/float64 (seconds). Returns defaultTimeout if missing or invalid.

func ValidateAllowedKeys added in v0.11.0

func ValidateAllowedKeys(conf map[string]any, allowed ...string) error

ValidateAllowedKeys checks that all keys in conf are in the allowed set.

func ValidateCommonConfig added in v0.11.0

func ValidateCommonConfig(conf map[string]any) error

ValidateCommonConfig validates the fields common to all providers: max_body_size, timeout, auto_auth_path, and default_role.

func ValidateMaxBodySize added in v0.11.0

func ValidateMaxBodySize(conf map[string]any) error

ValidateMaxBodySize validates that max_body_size is a valid integer within bounds.

func ValidateStringField added in v0.11.0

func ValidateStringField(conf map[string]any, key string) error

ValidateStringField validates that a config field, if present, is a string.

func ValidateTLSConfig added in v0.11.0

func ValidateTLSConfig(conf map[string]any) error

ValidateTLSConfig validates tls_skip_verify and ca_data fields.

func ValidateTimeout added in v0.11.0

func ValidateTimeout(conf map[string]any) error

ValidateTimeout validates that timeout is a valid duration string or integer.

func ValidateURL added in v0.11.0

func ValidateURL(addr string, urlKey string, tlsSkipVerify bool) error

ValidateURL validates that a URL is well-formed with an https:// scheme. When tlsSkipVerify is true, http:// is also accepted for dev/test environments. urlKey is used in error messages (e.g., "scaleway_url", "openai_url").

Types

type AccessBackend added in v0.6.0

type AccessBackend struct {
	*Backend

	// Logger is the provider's scoped logger.
	Logger *logger.GatedLogger

	// StorageView is the provider's storage backend for persisting configuration.
	StorageView sdklogical.Storage

	// AccessPathPrefix is the path prefix that triggers transparent auth.
	// Defaults to "access/" if empty.
	AccessPathPrefix string
	// contains filtered or unexported fields
}

AccessBackend implements logical.Backend for access backends that vend access grants (connection strings, presigned URLs, etc.) without proxying traffic. It provides implicit auth support and storage access, paralleling StreamingBackend for proxy providers.

func (*AccessBackend) GetAccessConfig added in v0.6.0

func (b *AccessBackend) GetAccessConfig() *AccessConfig

GetAccessConfig returns the current access configuration.

func (*AccessBackend) GetAuthRole added in v0.6.0

func (b *AccessBackend) GetAuthRole(_ string, req *logical.Request) string

GetAuthRole extracts the auth role from the ?role= query parameter. Falls back to empty string (auth method's default_role provides the fallback).

func (*AccessBackend) GetAutoAuthPath added in v0.6.0

func (b *AccessBackend) GetAutoAuthPath() string

GetAutoAuthPath returns the auth mount path for implicit authentication.

func (*AccessBackend) IsTransparentMode added in v0.6.0

func (b *AccessBackend) IsTransparentMode() bool

IsTransparentMode returns whether the backend has an auth path configured.

func (*AccessBackend) IsTransparentPath added in v0.6.0

func (b *AccessBackend) IsTransparentPath(path string) bool

IsTransparentPath checks if the given path should trigger transparent authentication. Matches paths starting with the configured access path prefix (default "access/").

func (*AccessBackend) IsUnauthenticatedPath added in v0.6.0

func (b *AccessBackend) IsUnauthenticatedPath(path string) bool

IsUnauthenticatedPath returns false — all access paths require authentication.

func (*AccessBackend) PathAccessConfig added in v0.6.0

func (b *AccessBackend) PathAccessConfig() *Path

PathAccessConfig returns a standard config path for access backends. Providers can include this in their paths() to get config CRUD for free.

func (*AccessBackend) SetAccessConfig added in v0.6.0

func (b *AccessBackend) SetAccessConfig(ctx context.Context, cfg *AccessConfig) error

SetAccessConfig updates and persists the access configuration.

func (*AccessBackend) Setup added in v0.6.0

func (b *AccessBackend) Setup(ctx context.Context, conf *logical.BackendConfig) error

Setup initializes the access backend with the provided configuration. It loads persisted config from storage.

type AccessConfig added in v0.6.0

type AccessConfig struct {
	AutoAuthPath string `json:"auto_auth_path"`
}

AccessConfig holds the implicit auth configuration for access backends.

type Backend

type Backend struct {
	// Help is the help text shown when a help request is made on the root.
	Help string

	// Paths are the various routes that the backend responds to.
	Paths []*Path

	// PathsSpecial is the list of path patterns that require special privileges.
	PathsSpecial *logical.Paths

	// InitializeFunc is the callback invoked after a plugin has been mounted.
	InitializeFunc InitializeFunc

	// Clean is called on unload to clean up connections or file handles.
	Clean CleanupFunc

	// BackendClass is the warden-specific backend class (Provider, Auth, System)
	BackendClass logical.BackendClass

	// BackendType is a string identifier for the backend type (e.g., "jwt", "aws")
	BackendType string

	// TokenExtractor is the warden-specific token extraction function
	TokenExtractor func(r *http.Request) string
	// contains filtered or unexported fields
}

Backend is an implementation of logical.Backend that allows the implementer to code a backend using a programmer-friendly framework.

func ExtractBackend added in v0.12.0

func ExtractBackend(b any) *Backend

ExtractBackend returns the *framework.Backend embedded in `b`, walking through arbitrary anonymous-field chains to find it. Provider wrappers (e.g. *awsBackend) embed *StreamingBackend, which itself embeds *Backend; auth methods embed *Backend directly; the system backend embeds *Backend. All of these are reachable.

Returns nil for values that don't ultimately wrap a *framework.Backend (audit devices, custom logical.Backend implementations).

Used by the sys/schema endpoint to document every framework-based mount without forcing every wrapper to implement an extraction method.

func (*Backend) Class

func (b *Backend) Class() logical.BackendClass

Class returns the warden backend class

func (*Backend) Cleanup

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

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

func (*Backend) Config

func (b *Backend) Config() map[string]any

Config returns the backend configuration

func (*Backend) ExtractToken

func (b *Backend) ExtractToken(r *http.Request) string

ExtractToken extracts token from HTTP request using the configured extractor. If no custom extractor is set, uses the default extraction logic: 1. X-Warden-Token header 2. Authorization: Bearer <token>

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

func (b *Backend) Initialize(ctx context.Context) error

Initialize is the logical.Backend implementation.

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) 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) Type

func (b *Backend) Type() string

Type returns the backend type string

type CleanupFunc

type CleanupFunc func(context.Context)

CleanupFunc is the callback for backend unload.

type DisplayAttributes

type DisplayAttributes struct {
	Name            string      `json:"name,omitempty"`
	Description     string      `json:"description,omitempty"`
	Value           interface{} `json:"value,omitempty"`
	Sensitive       bool        `json:"sensitive,omitempty"`
	Navigation      bool        `json:"navigation,omitempty"`
	ItemType        string      `json:"itemType,omitempty"`
	Group           string      `json:"group,omitempty"`
	Action          string      `json:"action,omitempty"`
	OperationPrefix string      `json:"operationPrefix,omitempty"`
	OperationVerb   string      `json:"operationVerb,omitempty"`
	OperationSuffix string      `json:"operationSuffix,omitempty"`
	EditType        string      `json:"editType,omitempty"`
}

DisplayAttributes provides hints for UI and documentation generators.

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 (*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.

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.

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.

func (*FieldData) GetTimeWithExplicitDefault

func (d *FieldData) GetTimeWithExplicitDefault(field string, defaultValue time.Duration) time.Duration

func (*FieldData) GetWithExplicitDefault

func (d *FieldData) GetWithExplicitDefault(field string, defaultValue interface{}) interface{}

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

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.

type FieldSchema

type FieldSchema struct {
	Type        FieldType
	Default     interface{}
	Description string
	Required    bool
	Deprecated  bool
	Query       bool

	// AllowedValues is an optional list of permitted values for this field.
	AllowedValues []interface{}

	// DisplayAttrs provides hints for UI and documentation generators.
	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 backends.
	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

type InitializeFunc func(context.Context) error

InitializeFunc is the callback invoked after a backend has been mounted.

type OASComponents added in v0.12.0

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

type OASContent added in v0.12.0

type OASContent map[string]*OASMediaTypeObject

type OASDocument added in v0.12.0

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 added in v0.12.0

func NewOASDocument(version string) *OASDocument

NewOASDocument returns an empty OpenAPI document.

func NewOASDocumentFromMap added in v0.12.0

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

NewOASDocumentFromMap builds an OASDocument from an existing map version of a document. After a JSON round-trip the document is a map[string]interface{} and needs special handling beyond the default mapstructure decoding.

func (*OASDocument) CreateOperationIDs deprecated added in v0.12.0

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 OpenAPI consumers.

type OASInfo added in v0.12.0

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

type OASLicense added in v0.12.0

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

type OASMediaTypeObject added in v0.12.0

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

type OASOperation added in v0.12.0

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 added in v0.12.0

func NewOASOperation() *OASOperation

NewOASOperation creates an empty OpenAPI Operations object.

type OASParameter added in v0.12.0

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 added in v0.12.0

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"`
	DisplayNavigation bool               `json:"x-vault-displayNavigation,omitempty" mapstructure:"x-vault-displayNavigation"`
	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 added in v0.12.0

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

type OASResponse added in v0.12.0

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

type OASSchema added in v0.12.0

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"`

	// 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"`
	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.

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.
	Description string

	// Examples provides samples of the expected request data.
	Examples []RequestExample

	// Responses provides a list of response description for a given response code.
	Responses map[int][]Response

	// Unpublished indicates that this operation should not appear in public documentation.
	Unpublished bool

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

	// DisplayAttrs provides hints for UI and documentation generators.
	DisplayAttrs *DisplayAttributes
}

OperationProperties describes an operation for documentation, help text, and other clients.

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.
	// The pattern will automatically have a ^ prepended and a $ appended.
	Pattern string

	// Fields is the mapping of data fields to a schema describing that field.
	Fields map[string]*FieldSchema

	// Operations is the set of operations supported and the associated OperationsHandler.
	Operations map[logical.Operation]OperationHandler

	// Callbacks are the set of callbacks that are called for a given operation.
	// 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.
	ExistenceCheck ExistenceFunc

	// Deprecated denotes that this path is considered deprecated.
	Deprecated bool

	// HelpSynopsis is a one-sentence description of the path.
	HelpSynopsis string

	// HelpDescription is a long-form description of the path.
	HelpDescription string

	// DisplayAttrs provides hints for UI and documentation generators.
	DisplayAttrs *DisplayAttributes

	// TakesArbitraryInput is used for endpoints that take arbitrary input.
	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 PathOperation

type PathOperation struct {
	Callback     OperationFunc
	Summary      string
	Description  string
	Examples     []RequestExample
	Responses    map[int][]Response
	Unpublished  bool
	Deprecated   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 RequestExample

type RequestExample struct {
	Description string
	Data        map[string]interface{}
	Response    *Response
}

RequestExample is example of request data.

type Response

type Response struct {
	Description string
	MediaType   string
	Fields      map[string]*FieldSchema
	Example     *logical.Response
	SchemaName  string
}

Response describes an operation response.

type StreamingBackend

type StreamingBackend struct {
	// StreamingPaths are paths that handle streaming operations (e.g., gateway/*)
	StreamingPaths []*StreamingPath

	// TransparentConfig holds the implicit auth configuration
	// When set, StreamingBackend implements logical.TransparentModeProvider
	TransparentConfig *TransparentConfig

	// UnauthenticatedPaths are paths that can be accessed without authentication.
	// These are hardcoded by the provider for read-only endpoints that some clients
	// access without sending tokens (e.g., PKI certificate PEM files).
	// Supports: exact match, prefix match (*), segment wildcard (+)
	UnauthenticatedPaths []string

	// ParseStreamBody enables request body parsing for streaming requests.
	// When true, the core parses application/json and application/x-www-form-urlencoded
	// bodies into req.Data before policy evaluation, then restores the body so
	// the streaming handler can still read it.
	// Default: false (body is passed raw to the streaming handler).
	ParseStreamBody bool

	// Backend is the embedded standard framework backend for non-streaming paths
	*Backend

	// MaxBodySize is the maximum request body size in bytes.
	MaxBodySize int64

	// Timeout is the request timeout duration.
	Timeout time.Duration

	// Proxy is the shared reverse proxy for streaming requests.
	// Initialized via InitProxy with a provider-specific transport.
	Proxy *httputil.ReverseProxy

	// Logger is the provider's scoped logger (set via conf.Logger.WithSubsystem).
	Logger *logger.GatedLogger

	// StorageView is the provider's storage backend for persisting configuration.
	StorageView sdklogical.Storage
	// contains filtered or unexported fields
}

StreamingBackend implements logical.Backend for streaming/proxy operations. It combines streaming paths (for proxy operations) with regular framework paths (for configuration and management).

func (*StreamingBackend) Class

Class delegates to the embedded Backend

func (*StreamingBackend) Cleanup

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

Cleanup delegates to the embedded Backend

func (*StreamingBackend) Config

func (b *StreamingBackend) Config() map[string]any

Config delegates to the embedded Backend

func (*StreamingBackend) ExtractToken

func (b *StreamingBackend) ExtractToken(r *http.Request) string

ExtractToken delegates to the embedded Backend

func (*StreamingBackend) GetAuthRole added in v0.6.0

func (b *StreamingBackend) GetAuthRole(path string, _ *logical.Request) string

GetAuthRole extracts the auth role name from the request path for implicit login.

func (*StreamingBackend) GetAutoAuthPath

func (b *StreamingBackend) GetAutoAuthPath() string

GetAutoAuthPath returns the auth mount path for implicit authentication

func (*StreamingBackend) HandleExistenceCheck

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

HandleExistenceCheck delegates to the embedded Backend

func (*StreamingBackend) HandleRequest

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

HandleRequest routes to either streaming or standard handling based on req.Streamed. If req.Streamed is true (set by core routing), it handles streaming directly. Otherwise, it falls back to the embedded Backend's HandleRequest.

func (*StreamingBackend) InitProxy

func (b *StreamingBackend) InitProxy(transport http.RoundTripper)

InitProxy creates a standard reverse proxy with the given transport. The proxy uses an empty Director (providers prepare requests before ServeHTTP) and a standard error handler that logs and returns 502. Logger must be set on the StreamingBackend before calling this method.

func (*StreamingBackend) Initialize

func (b *StreamingBackend) Initialize(ctx context.Context) error

Initialize delegates to the embedded Backend

func (*StreamingBackend) IsTransparentMode

func (b *StreamingBackend) IsTransparentMode() bool

IsTransparentMode returns whether the backend has an auth config set

func (*StreamingBackend) IsTransparentPath added in v0.6.0

func (b *StreamingBackend) IsTransparentPath(path string) bool

IsTransparentPath checks if the given path should trigger transparent authentication. For streaming backends, this matches gateway paths: "gateway", "gateway/...", "role/X/gateway", "role/X/gateway/...".

func (*StreamingBackend) IsUnauthenticatedPath

func (b *StreamingBackend) IsUnauthenticatedPath(path string) bool

IsUnauthenticatedPath checks if the path matches an unauthenticated pattern. Uses radix tree for O(log n) lookup with wildcard fallback.

func (*StreamingBackend) RewriteTransparentPath

func (b *StreamingBackend) RewriteTransparentPath(path string) string

RewriteTransparentPath rewrites a transparent path to standard path

func (*StreamingBackend) SetTransparentConfig

func (b *StreamingBackend) SetTransparentConfig(config *TransparentConfig)

SetTransparentConfig updates the implicit auth configuration at runtime

func (*StreamingBackend) Setup

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

Setup delegates to the embedded Backend

func (*StreamingBackend) ShouldParseStreamBody added in v0.2.0

func (b *StreamingBackend) ShouldParseStreamBody() bool

ShouldParseStreamBody implements logical.StreamBodyParser.

func (*StreamingBackend) SpecialPaths

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

SpecialPaths returns special paths including streaming paths

func (*StreamingBackend) Type

func (b *StreamingBackend) Type() string

Type delegates to the embedded Backend

type StreamingOperationFunc

type StreamingOperationFunc func(ctx context.Context, req *logical.Request, fd *FieldData) error

StreamingOperationFunc handles streaming operations with raw HTTP access. It receives the context, the full logical.Request (which includes ResponseWriter, HTTPRequest, and Credential), and parsed field data. The function is responsible for writing the response directly to req.ResponseWriter.

type StreamingPath

type StreamingPath struct {
	// Pattern is the regex pattern for matching this path
	Pattern string

	// Fields defines the expected fields for this path
	Fields map[string]*FieldSchema

	// Handler is the streaming operation handler
	Handler StreamingOperationFunc

	// HelpSynopsis is a brief description of this path
	HelpSynopsis string

	// HelpDescription is a longer description of this path
	HelpDescription string
}

StreamingPath represents a path that handles streaming requests. Unlike regular paths, streaming paths write directly to the HTTP response.

type TransparentConfig

type TransparentConfig struct {
	// AutoAuthPath is the auth mount path for implicit authentication (e.g., "auth/jwt/")
	AutoAuthPath string

	// DefaultAuthRole is the auth role to use when not specified in URL path
	DefaultAuthRole string

	// AuthRolePattern is the regex pattern to extract the auth role from path (optional)
	// If nil, uses DefaultAuthRolePattern: `^role/([^/]+)/gateway`
	// First capture group is used as the auth role name
	AuthRolePattern *regexp.Regexp

	// PathRewriter converts transparent paths to standard paths (optional)
	// If nil, uses DefaultPathRewriter: role/X/gateway/... -> gateway/...
	PathRewriter func(path string) string
}

TransparentConfig holds the authentication configuration for implicit auth. When set on a StreamingBackend, the provider performs implicit JWT or cert authentication on every request — no explicit login step is needed.

Jump to

Keyboard shortcuts

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