Documentation ¶
Index ¶
- Constants
- Variables
- func ExtracTokenFromRequest(r *http.Request) string
- func ExtractClientIP(r *http.Request) string
- func HttpHeaderToMap(header http.Header) map[string]string
- func InCIDR(ip string, cidrs []string) bool
- func MatchMIME(accept string, supported []string) bool
- func MediaTypeCheckFunc(accepts, produces []string, handler http.Handler) http.HandlerFunc
- func MethodNotAllowed(w http.ResponseWriter, r *http.Request)
- func NewDefauBodyltValidation() func(r *http.Request, data any) error
- func NewRedocUI(specPath string) []byte
- func NewSwaggerUI(specPath string) []byte
- func NotAcceptable(w http.ResponseWriter, r *http.Request)
- func PathVars(r *http.Request) request.PathVarList
- func ReadBodySafely(req *http.Request, allowsContentType []string, maxReadSize int) []byte
- func RequestSourceIPInCIDR(cidrs []string, r *http.Request) bool
- func ResponseHeaderFromContext(ctx context.Context) http.Header
- func SetAuditExtra(req *http.Request, k, v string)
- func UnsupportedMediaType(w http.ResponseWriter, r *http.Request)
- func WithAttributes(ctx context.Context, attributes *Attributes) context.Context
- func WithAuditLog(ctx context.Context, log *AuditLog) context.Context
- func WithAuthenticate(ctx context.Context, info AuthenticateInfo) context.Context
- func WithAuthorizationContext(ctx context.Context, decision Decision) context.Context
- type API
- func (m *API) Build() http.Handler
- func (m *API) Group(groups ...Group) *API
- func (m *API) NotFound(handler http.Handler) *API
- func (m *API) Plugin(plugin ...Plugin) *API
- func (m *API) PrefixGroup(prefix string, groups ...Group) *API
- func (m *API) Route(route Route) *API
- func (m *API) Serve(ctx context.Context, listenaddr string) error
- func (m *API) TLS(cert, key string) *API
- type APIDocPlugin
- type AnonymousAuthenticator
- type AttrbuteResource
- type AttributeExtractor
- type Attributes
- type AuditExtraMetadata
- type AuditLog
- type AuditRequest
- type AuditResponse
- type AuditSSH
- type AuditSink
- type Auditor
- type AuthenticateErrorHandleFunc
- type AuthenticateFunc
- type AuthenticateInfo
- type AuthenticatorChain
- type Authorizer
- type AuthorizerChain
- type AuthorizerFunc
- type CachedAuditSink
- type CachedBody
- type CompresseWriter
- type ContextKey
- type Decision
- type Filter
- func CORSFilter() Filter
- func LoggingFilter(log logr.Logger) Filter
- func NewAttributeFilter(attributer AttributeExtractor) Filter
- func NewAuditEndFilter(auditor Auditor, sink AuditSink) Filter
- func NewAuditFilter(auditor Auditor, sink AuditSink) Filter
- func NewAuditStartFilter(auditor Auditor) Filter
- func NewAuthenticateFilter(onauth AuthenticateFunc, onerr AuthenticateErrorHandleFunc) Filter
- func NewAuthorizationFilter(authorizer Authorizer) Filter
- func NewCompressionFilter() Filter
- func NewConditionFilter(cond func(r *http.Request) bool, filter Filter) Filter
- func NewRequestAuthorizationFilter(on RequestAuthorizerFunc) Filter
- func NewTokenAuthenticationFilter(authenticator TokenAuthenticator) Filter
- func NewTokenAuthenticationFilterWithErrHandle(authenticator TokenAuthenticator, errhandle AuthenticateErrorHandleFunc) Filter
- func NoopFilter() Filter
- type FilterFunc
- type Filters
- type Group
- func (g Group) Accept(mime ...string) Group
- func (t Group) Build() map[string]map[string]Route
- func (g Group) ContentType(mime ...string) Group
- func (g Group) Filter(filters ...Filter) Group
- func (g Group) Param(params ...Param) Group
- func (g Group) Route(rs ...Route) Group
- func (g Group) SubGroup(groups ...Group) Group
- func (g Group) Tag(name string) Group
- type HTTPAuthenticateFunc
- type HTTPAuthenticator
- type HealthCheckPlugin
- type LRUCache
- type LRUCacheAuthenticator
- type LRUCacheAuthorizer
- type LRUCacheSSHAuthenticator
- type LoggerAuditSink
- type MethodsHandler
- type Mux
- type NoopPlugin
- type OIDCAuthenticator
- type OIDCOptions
- type OpenTelemetryPlugin
- type Param
- type ParamKind
- type Plugin
- type PredicatedFilter
- type RequestAuthorizer
- type RequestAuthorizerFunc
- type ResponseInfo
- type Route
- func (n Route) Accept(mime ...string) Route
- func (n Route) ContentType(mime ...string) Route
- func (n Route) Doc(summary string) Route
- func (n Route) Param(params ...Param) Route
- func (n Route) Property(k string, v interface{}) Route
- func (n Route) Response(body interface{}, desc ...string) Route
- func (n Route) ResponseStatus(status int, body interface{}, desc ...string) Route
- func (route Route) ServeHTTP(w http.ResponseWriter, r *http.Request)
- func (n Route) Tag(tags ...string) Route
- func (n Route) To(fun http.HandlerFunc) Route
- type Router
- type SSHAuthenticator
- type SimpleAuditor
- type StatusResponseWriter
- type TokenAuthenticator
- type UserInfo
- type UsernamePasswordAuthenticator
- type VersionPlugin
Constants ¶
const ( RedocTemplate = `` /* 622-byte string literal not displayed */ SwaggerTemplate = `` /* 1427-byte string literal not displayed */ )
const AnonymousUser = "anonymous" // anonymous username
const DefaultAuditLogCacheSize = 256
const MB = 1 << 20
Variables ¶
var ( NameRegexp = regexp.MustCompile(`^[a-zA-Z0-9]+(?:[._-][a-zA-Z0-9]+)*$`) NameWithSlashRegexp = regexp.MustCompile(`^[a-zA-Z0-9]+(?:[._/-][a-zA-Z0-9]+)*$`) )
var DecisionDenyStatusNotFoundMessage = "not found"
var MethodActionMapPlural = map[string]string{
"GET": "list",
"POST": "create",
"DELETE": "removeBatch",
"PUT": "updateBatch",
}
plural
var MethodActionMapSingular = map[string]string{
"GET": "get",
"PUT": "update",
"DELETE": "remove",
"PATCH": "patch",
}
singular plural
Functions ¶
func ExtracTokenFromRequest ¶
func ExtractClientIP ¶
func MediaTypeCheckFunc ¶
func MediaTypeCheckFunc(accepts, produces []string, handler http.Handler) http.HandlerFunc
func MethodNotAllowed ¶
func MethodNotAllowed(w http.ResponseWriter, r *http.Request)
func NewRedocUI ¶
func NewSwaggerUI ¶
func NotAcceptable ¶
func NotAcceptable(w http.ResponseWriter, r *http.Request)
The HyperText Transfer Protocol (HTTP) 406 Not Acceptable client error response code indicates that the server cannot produce a response matching the list of acceptable values defined in the request's proactive content negotiation headers, and that the server is unwilling to supply a default representation.
func ReadBodySafely ¶
func SetAuditExtra ¶
func UnsupportedMediaType ¶
func UnsupportedMediaType(w http.ResponseWriter, r *http.Request)
func WithAttributes ¶
func WithAttributes(ctx context.Context, attributes *Attributes) context.Context
func WithAuthenticate ¶
func WithAuthenticate(ctx context.Context, info AuthenticateInfo) context.Context
Types ¶
type APIDocPlugin ¶
func NewAPIDocPlugin ¶
func NewAPIDocPlugin(basepath string, fn func(swagger *spec.Swagger)) *APIDocPlugin
func (*APIDocPlugin) Install ¶
func (s *APIDocPlugin) Install(m *API) error
Install implements Plugin.
func (*APIDocPlugin) OnRoute ¶
func (s *APIDocPlugin) OnRoute(route *Route) error
OnRoute implements Plugin.
type AnonymousAuthenticator ¶
type AnonymousAuthenticator struct{}
func NewAnonymousAuthenticator ¶
func NewAnonymousAuthenticator() *AnonymousAuthenticator
func (*AnonymousAuthenticator) Authenticate ¶
func (a *AnonymousAuthenticator) Authenticate(ctx context.Context, token string) (*AuthenticateInfo, error)
type AttrbuteResource ¶
type AttrbuteResource struct { Resource string `json:"resource,omitempty"` Name string `json:"name,omitempty"` }
func DefaultRestAttributeExtractor ¶
func DefaultRestAttributeExtractor(method string, path string) (string, []AttrbuteResource)
type AttributeExtractor ¶
type AttributeExtractor func(r *http.Request) (*Attributes, error)
func PrefixedAttributesExtractor ¶
func PrefixedAttributesExtractor(prefix string) AttributeExtractor
type Attributes ¶
type Attributes struct { Action string `json:"action,omitempty"` Resources []AttrbuteResource `json:"resources,omitempty"` Path string `json:"path,omitempty"` }
func AttributesFromContext ¶
func AttributesFromContext(ctx context.Context) *Attributes
func (Attributes) ToWildcards ¶
func (a Attributes) ToWildcards() (string, string)
return wildcards for action and expression e.g. action: get, resources: [AttrbuteResource{Resource: "namespaces", Name: "default"}] -> "get", "namespaces:default"
type AuditExtraMetadata ¶
type AuditLog ¶
type AuditLog struct { SSH *AuditSSH `json:"ssh,omitempty"` // for ssh only // request Request AuditRequest `json:"request,omitempty"` Response AuditResponse `json:"response,omitempty"` // authz Subject string `json:"subject,omitempty"` // username // Resource is the resource type, e.g. "pods", "namespaces/default/pods/nginx-xxx" // we can detect the resource type and name from the request path. // GET /zoos/{zoo_id}/animals/{animal_id} -> get zoos,zoo_id,animals,animal_id // GET /zoos/{zoo_id}/animals -> list zoos,zoo_id,animals,animal_id // POST /zoos/{zoo_id}/animals:set-free -> set-free zoos,zoo_id,animals Action string `json:"action,omitempty"` // create, update, delete, get, list, set-free, etc. Domain string `json:"domain,omitempty"` // for multi-tenant Parents []AttrbuteResource `json:"parents,omitempty"` // parent resources, e.g. "zoos/{zoo_id}", Resource string `json:"resource,omitempty"` // resource type, e.g. "animals" ResourceName string `json:"resourceName,omitempty"` // "{animal_id}", or "" if list // metadata StartTime time.Time `json:"startTime,omitempty"` // request start time EndTime time.Time `json:"endTime,omitempty"` // request end time Metadata AuditExtraMetadata `json:"metadata,omitempty"` // extra metadata }
func AuditLogFromContext ¶
type AuditRequest ¶
type AuditRequest struct { HttpVersion string `json:"httpVersion,omitempty"` // http version Method string `json:"method,omitempty"` // method URL string `json:"url,omitempty"` // full url Header map[string]string `json:"header,omitempty"` // header Body []byte `json:"body,omitempty"` // ignore body if size > 1MB or stream. ClientIP string `json:"clientIP,omitempty"` // client ip RemoteAddr string `json:"remoteAddr,omitempty"` LocalAddr string `json:"localAddr,omitempty"` }
type AuditResponse ¶
type AuditSSH ¶
type AuditSSH struct { User string `json:"user,omitempty"` RemoteAddr string `json:"remoteAddr,omitempty"` LocalAddr string `json:"localAddr,omitempty"` SessionID string `json:"sessionID,omitempty"` ClientVersion string `json:"clientVersion,omitempty"` ServerVersion string `json:"serverVersion,omitempty"` PublicKey string `json:"publicKey,omitempty"` Command string `json:"command,omitempty"` Env []string `json:"env,omitempty"` }
type Auditor ¶
type Auditor interface { OnRequest(w http.ResponseWriter, r *http.Request) (http.ResponseWriter, *AuditLog) OnResponse(w http.ResponseWriter, r *http.Request, auditlog *AuditLog) }
type AuthenticateErrorHandleFunc ¶
type AuthenticateErrorHandleFunc func(w http.ResponseWriter, r *http.Request, err error)
type AuthenticateFunc ¶
type AuthenticateFunc func(w http.ResponseWriter, r *http.Request) (*AuthenticateInfo, error)
type AuthenticateInfo ¶
type AuthenticateInfo struct { // Audiences is the set of audiences the authenticator was able to validate // the token against. If the authenticator is not audience aware, this field // will be empty. Audiences []string // User is the UserInfo associated with the authentication context. User UserInfo }
func AuthenticateFromContext ¶
func AuthenticateFromContext(ctx context.Context) AuthenticateInfo
type AuthenticatorChain ¶
type AuthenticatorChain []TokenAuthenticator
func (AuthenticatorChain) Authenticate ¶
func (c AuthenticatorChain) Authenticate(ctx context.Context, token string) (*AuthenticateInfo, error)
type Authorizer ¶
type Authorizer interface {
Authorize(ctx context.Context, user UserInfo, a Attributes) (authorized Decision, reason string, err error)
}
func NewAlwaysAllowAuthorizer ¶
func NewAlwaysAllowAuthorizer() Authorizer
func NewAlwaysDenyAuthorizer ¶
func NewAlwaysDenyAuthorizer() Authorizer
func NewCacheAuthorizer ¶
func NewCacheAuthorizer(authorizer Authorizer, size int, ttl time.Duration) Authorizer
type AuthorizerChain ¶
type AuthorizerChain []Authorizer
func (AuthorizerChain) Authorize ¶
func (c AuthorizerChain) Authorize(ctx context.Context, user UserInfo, a Attributes) (Decision, string, error)
type AuthorizerFunc ¶
type AuthorizerFunc func(ctx context.Context, user UserInfo, a Attributes) (authorized Decision, reason string, err error)
func (AuthorizerFunc) Authorize ¶
func (f AuthorizerFunc) Authorize(ctx context.Context, user UserInfo, a Attributes) (authorized Decision, reason string, err error)
type CachedAuditSink ¶
type CachedAuditSink struct {
// contains filtered or unexported fields
}
func (*CachedAuditSink) Save ¶
func (c *CachedAuditSink) Save(log *AuditLog) error
type CachedBody ¶
type CachedBody struct {
// contains filtered or unexported fields
}
func NewCachedBody ¶
func NewCachedBody(body io.ReadCloser, cached []byte, earlyerr error) *CachedBody
NewCachedBody returns a new CachedBody. a CachedBody is a io.ReadCloser that read from cached first, then read from body.
func (*CachedBody) Close ¶
func (w *CachedBody) Close() error
type CompresseWriter ¶
type CompresseWriter struct { http.ResponseWriter // contains filtered or unexported fields }
func (*CompresseWriter) Flush ¶
func (cw *CompresseWriter) Flush()
type ContextKey ¶
type ContextKey string
type Filter ¶
func CORSFilter ¶
func CORSFilter() Filter
func LoggingFilter ¶
func NewAttributeFilter ¶
func NewAttributeFilter(attributer AttributeExtractor) Filter
func NewAuditEndFilter ¶
func NewAuditFilter ¶
func NewAuditStartFilter ¶
func NewAuthenticateFilter ¶
func NewAuthenticateFilter(onauth AuthenticateFunc, onerr AuthenticateErrorHandleFunc) Filter
func NewAuthorizationFilter ¶
func NewAuthorizationFilter(authorizer Authorizer) Filter
func NewCompressionFilter ¶
func NewCompressionFilter() Filter
NewCompressionFilter returns a filter that compresses the response body
func NewConditionFilter ¶
func NewRequestAuthorizationFilter ¶
func NewRequestAuthorizationFilter(on RequestAuthorizerFunc) Filter
func NewTokenAuthenticationFilter ¶
func NewTokenAuthenticationFilter(authenticator TokenAuthenticator) Filter
func NewTokenAuthenticationFilterWithErrHandle ¶
func NewTokenAuthenticationFilterWithErrHandle(authenticator TokenAuthenticator, errhandle AuthenticateErrorHandleFunc) Filter
func NoopFilter ¶
func NoopFilter() Filter
type FilterFunc ¶
func NewOpenTelemetryFilter ¶
func NewOpenTelemetryFilter(tracer trace.Tracer) FilterFunc
func (FilterFunc) Process ¶
func (f FilterFunc) Process(w http.ResponseWriter, r *http.Request, next http.Handler)
type Group ¶
type Group struct { Path string Filters Filters Tags []string Params []Param // common params apply to all routes in the group Routes []Route SubGroups []Group // sub groups Consumes []string Produces []string }
func (Group) ContentType ¶
ContentType match request Content-Type header
type HTTPAuthenticateFunc ¶
func (HTTPAuthenticateFunc) Authenticate ¶
func (f HTTPAuthenticateFunc) Authenticate(ctx context.Context, r *http.Request) (*AuthenticateInfo, error)
type HTTPAuthenticator ¶
type HealthCheckPlugin ¶
type HealthCheckPlugin struct { NoopPlugin CheckFun func() error }
func (HealthCheckPlugin) Install ¶
func (h HealthCheckPlugin) Install(m *API) error
type LRUCacheAuthenticator ¶
type LRUCacheAuthenticator struct { Authenticator TokenAuthenticator Cache LRUCache[*AuthenticateInfo] }
func NewCacheAuthenticator ¶
func NewCacheAuthenticator(authenticator TokenAuthenticator, size int, ttl time.Duration) *LRUCacheAuthenticator
func (*LRUCacheAuthenticator) Authenticate ¶
func (a *LRUCacheAuthenticator) Authenticate(ctx context.Context, token string) (*AuthenticateInfo, error)
Authenticate implements TokenAuthenticator.
type LRUCacheAuthorizer ¶
type LRUCacheAuthorizer struct { Authorizer Authorizer // contains filtered or unexported fields }
func (*LRUCacheAuthorizer) Authorize ¶
func (c *LRUCacheAuthorizer) Authorize(ctx context.Context, user UserInfo, a Attributes) (authorized Decision, reason string, err error)
Authorize implements Authorizer.
type LRUCacheSSHAuthenticator ¶
type LRUCacheSSHAuthenticator struct { Authenticator SSHAuthenticator Cache LRUCache[*AuthenticateInfo] }
func NewCachedSSHAuthenticator ¶
func NewCachedSSHAuthenticator(authenticator SSHAuthenticator, size int, ttl time.Duration) *LRUCacheSSHAuthenticator
func (*LRUCacheSSHAuthenticator) Authenticate ¶
func (a *LRUCacheSSHAuthenticator) Authenticate(ctx context.Context, username, password string) (*AuthenticateInfo, error)
AuthenticatePassword implements SSHAuthenticator.
func (*LRUCacheSSHAuthenticator) AuthenticatePublibcKey ¶
func (a *LRUCacheSSHAuthenticator) AuthenticatePublibcKey(ctx context.Context, pubkey ssh.PublicKey) (*AuthenticateInfo, error)
AuthenticatePublibcKey implements SSHAuthenticator.
type LoggerAuditSink ¶
func (*LoggerAuditSink) Save ¶
func (l *LoggerAuditSink) Save(log *AuditLog) error
type MethodsHandler ¶
func (MethodsHandler) ServeHTTP ¶
func (h MethodsHandler) ServeHTTP(w http.ResponseWriter, r *http.Request)
type Mux ¶
type Mux struct { NotFound http.Handler Tree matcher.Node[MethodsHandler] }
func (*Mux) HandleRoute ¶
func (*Mux) SetNotFound ¶
type NoopPlugin ¶
type NoopPlugin struct{}
func (NoopPlugin) Install ¶
func (n NoopPlugin) Install(m *API) error
func (NoopPlugin) OnRoute ¶
func (n NoopPlugin) OnRoute(route *Route) error
type OIDCAuthenticator ¶
type OIDCAuthenticator struct { Verifier *oidc.IDTokenVerifier UsernameClaimCandidate []string EmailClaimCandidate []string GroupsClaimCandidate []string EmailToUsername func(email string) string }
func NewOIDCAuthenticator ¶
func NewOIDCAuthenticator(ctx context.Context, opts *OIDCOptions) (*OIDCAuthenticator, error)
func (*OIDCAuthenticator) Authenticate ¶
func (o *OIDCAuthenticator) Authenticate(ctx context.Context, token string) (*AuthenticateInfo, error)
type OIDCOptions ¶
type OIDCOptions struct { Issuer string `json:"issuer" description:"oidc issuer url"` Insecure bool `json:"insecure" description:"skip issuer and audience verification"` // ClientID is the OAuth2 client ID for this server. ClientID string `json:"clientID" description:"oidc client id"` // ClientSecret is the secret for the client ID. If no secret is provided, // the client is assumed to be a public client and authentication will // proceed without a client secret. ClientSecret string `json:"clientSecret" description:"oidc client secret"` // Scopes is the set of scopes to request. Scope []string `json:"scope" description:"oidc scope"` }
func NewDefaultOIDCOptions ¶
func NewDefaultOIDCOptions() *OIDCOptions
type OpenTelemetryPlugin ¶
type OpenTelemetryPlugin struct {
TraceProvider trace.TracerProvider
}
func (OpenTelemetryPlugin) Install ¶
func (o OpenTelemetryPlugin) Install(m *API) error
func (OpenTelemetryPlugin) OnRoute ¶
func (o OpenTelemetryPlugin) OnRoute(route *Route) error
type Param ¶
type Param struct { Name string Kind ParamKind Type string Enum []any Default any IsOptional bool Description string Example any Pattern string }
func QueryParam ¶
type PredicatedFilter ¶
func (PredicatedFilter) Process ¶
func (f PredicatedFilter) Process(w http.ResponseWriter, r *http.Request, next http.Handler)
type RequestAuthorizer ¶
func NewAllowCIDRAuthorizer ¶
func NewAllowCIDRAuthorizer(cidrs []string, defaultDec Decision) RequestAuthorizer
type RequestAuthorizerFunc ¶
func (RequestAuthorizerFunc) AuthorizeRequest ¶
type ResponseInfo ¶
type Route ¶
type Route struct { Summary string Path string Method string Deprecated bool Handler http.Handler Filters Filters Tags []string Consumes []string Produces []string Params []Param Responses []ResponseInfo Properties map[string]interface{} }
func (Route) ContentType ¶
ContentType match request Content-Type header
func (Route) ResponseStatus ¶
type SSHAuthenticator ¶
type SSHAuthenticator interface { UsernamePasswordAuthenticator AuthenticatePublibcKey(ctx context.Context, pubkey ssh.PublicKey) (*AuthenticateInfo, error) }
type SimpleAuditor ¶
type SimpleAuditor struct { RecordReadBody bool // Record read actions RecordRequestBodyContentTypes []string // Record only for these content types MaxBodySize int // Max body size to record,0 means disable WhiteList []string // White list }
func NewSimpleAuditor ¶
func NewSimpleAuditor() *SimpleAuditor
func (*SimpleAuditor) OnRequest ¶
func (a *SimpleAuditor) OnRequest(w http.ResponseWriter, r *http.Request) (http.ResponseWriter, *AuditLog)
func (*SimpleAuditor) OnResponse ¶
func (a *SimpleAuditor) OnResponse(w http.ResponseWriter, r *http.Request, auditlog *AuditLog)
type StatusResponseWriter ¶
type StatusResponseWriter struct { Inner http.ResponseWriter Code int Cache []byte MaxCacheSize int }
func (*StatusResponseWriter) Header ¶
func (w *StatusResponseWriter) Header() http.Header
func (*StatusResponseWriter) Write ¶
func (w *StatusResponseWriter) Write(p []byte) (n int, err error)
func (*StatusResponseWriter) WriteHeader ¶
func (w *StatusResponseWriter) WriteHeader(statusCode int)
type TokenAuthenticator ¶
type TokenAuthenticator interface { // Authenticate authenticates the token and returns the authentication info. // if can't authenticate, return nil, "reason message", nil // if unexpected error, return nil, "", err Authenticate(ctx context.Context, token string) (*AuthenticateInfo, error) }
type UsernamePasswordAuthenticator ¶
type UsernamePasswordAuthenticator interface {
Authenticate(ctx context.Context, username, password string) (*AuthenticateInfo, error)
}
type VersionPlugin ¶
type VersionPlugin struct { NoopPlugin Version any }
func (VersionPlugin) Install ¶
func (v VersionPlugin) Install(m *API) error