auth

package
v1.23.9 Latest Latest
Warning

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

Go to latest
Published: May 4, 2023 License: Apache-2.0 Imports: 15 Imported by: 0

Documentation

Index

Constants

View Source
const AnonymousUser = "" // anonymous username
View Source
const DefaultAuditLogCacheSize = 256
View Source
const MB = 1 << 20

Variables

View Source
var MethodActionMapPlural = map[string]PermissionAction{
	"GET":    ActionList,
	"POST":   ActionCreate,
	"DELETE": ActionRemoveBatch,
}

plural

View Source
var MethodActionMapSingular = map[string]PermissionAction{
	"GET":    ActionGet,
	"PUT":    ActionUpdate,
	"DELETE": ActionRemove,
	"PATCH":  ActionPatch,
}

singular plural

Functions

func ExtractClientIP

func ExtractClientIP(r *http.Request) string

func HttpHeaderToMap

func HttpHeaderToMap(header http.Header) map[string]string

func NewHTTPAuditorHandler

func NewHTTPAuditorHandler(auditor HTTPAuditor, sink AuditSink, next http.Handler) http.Handler

func NewPermissionCheckerHandler

func NewPermissionCheckerHandler(matcher PathRewriteMatcher, extractor SubjectExtractor, authz PermissionChecker, next http.Handler) http.Handler

func NewTokenClaimsContext

func NewTokenClaimsContext(ctx context.Context, username TokenClaims) context.Context

func NewTokenVerifyHandler

func NewTokenVerifyHandler(authc TokenVerify, next http.Handler) http.Handler

NewTokenVerifyHandler returns a http.Handler that verifies access tokens in the Authorization header. in next handler, the username is stored in the context and can be retrieved by UsernameFromContext(r.Context()). We acting as a resource server, so we need to verify the access token from the client.

func Permission

func Permission(action PermissionAction, target ...string) string

func PermissionFromMethodPath

func PermissionFromMethodPath(method string, path string) string

func ReadBodySafely

func ReadBodySafely(req *http.Request, allowsContentType []string, maxReadSize int) []byte

func SetAuditExtraMeatadata

func SetAuditExtraMeatadata(req *http.Request, k, v string)

func UsernameFromContext

func UsernameFromContext(ctx context.Context) string

func WildcardMatch

func WildcardMatch(key1 string, key2 string) bool

func WildcardMatchFunc

func WildcardMatchFunc(args ...interface{}) (interface{}, error)

func WildcardMatchSections

func WildcardMatchSections(expr string, perm string) bool

acting like: https://shiro.apache.org/permissions.html#WildcardPermissions but extended to support ** to match all following sections

Types

type AuditExtraMetadata

type AuditExtraMetadata map[string]string

func GetAuditExtraMeatadata

func GetAuditExtraMeatadata(req *http.Request) AuditExtraMetadata

type AuditLog

type AuditLog struct {
	// request
	Request  AuditRequest  `json:"request"`
	Response AuditResponse `json:"response"`
	// authz
	Subject string `json:"subject"` // 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"`   // create, update, delete, get, list, set-free, etc.
	Domain   string           `json:"domain"`   // for multi-tenant
	Parents  []ParentResource `json:"parents"`  // parent resources, e.g. "zoos/{zoo_id}",
	Resource string           `json:"resource"` // resource type, e.g. "animals"
	Name     string           `json:"name"`     //  "{animal_id}", or "" if list
	// metadata
	StartTime time.Time          `json:"startTime"` // request start time
	EndTime   time.Time          `json:"endTime"`   // request end time
	Metadata  AuditExtraMetadata `json:"metadata"`  // extra metadata
}

type AuditOptions

type AuditOptions struct {
	RecordRead             bool     // Record read actions
	RecordBodyContentTypes []string // Record only for these content types
	MaxBodySize            int      // Max body size to record,0 means disable
}

func NewDefaultAuditOptions

func NewDefaultAuditOptions() *AuditOptions

type AuditRequest

type AuditRequest struct {
	HttpVersion string            `json:"httpVersion"` // http version
	Method      string            `json:"method"`      // method
	URL         string            `json:"url"`         // full url
	Header      map[string]string `json:"header"`      // header
	Body        []byte            `json:"body"`        // ignore body if size > 1MB or stream.
	ClientIP    string            `json:"clientIP"`    // client ip
}

type AuditResponse

type AuditResponse struct {
	StatusCode   int               `json:"statusCode"`   // status code
	Header       map[string]string `json:"header"`       // header
	ResponseBody []byte            `json:"responseBody"` // ignore body if size > 1MB or stream.
}

type AuditSink

type AuditSink interface {
	Save(log *AuditLog) error
}

func NewCachedAuditSink

func NewCachedAuditSink(ctx context.Context, sink AuditSink, maxCacheSize int) AuditSink

type AuthorizationManager

type AuthorizationManager interface {
	Roles() SimpleOperation
	RoleAuthorities() SimpleOperation
	UserRoles() SimpleOperation
}

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

func (*CachedBody) Read

func (w *CachedBody) Read(p []byte) (n int, err error)

type CasbinPermissionChecker

type CasbinPermissionChecker struct {
	// contains filtered or unexported fields
}

func NewCasbinPermissionChecker

func NewCasbinPermissionChecker(ctx context.Context, db *gorm.DB) (*CasbinPermissionChecker, error)

func (*CasbinPermissionChecker) HasPermission

func (c *CasbinPermissionChecker) HasPermission(subject string, perm string) (bool, error)

type HTTPAuditor

type HTTPAuditor interface {
	// Request is called on request stage, it returns the audit log and a wrapped response writer (if needed)
	OnRequest(w http.ResponseWriter, r *http.Request) (http.ResponseWriter, *AuditLog)
	// OnResponse is called on response stage, it passes the audit log and response writer produced by OnRequest
	OnResponse(w http.ResponseWriter, r *http.Request, auditlog *AuditLog)
}

Auditor is the interface to audit http request and response. Auditor must completes the audit log on request and response stage.

type MiddlewareFunc

type MiddlewareFunc func(http.Handler) http.Handler

func NewHTTPAuditorMiddleware

func NewHTTPAuditorMiddleware(auditor HTTPAuditor, sink AuditSink) MiddlewareFunc

func NewPermissionCheckerMiddleware

func NewPermissionCheckerMiddleware(matcher PathRewriteMatcher, extractor SubjectExtractor, authz PermissionChecker) MiddlewareFunc

func NewTokenVerifyMiddleware

func NewTokenVerifyMiddleware(authc TokenVerify) MiddlewareFunc

func NewWhitelistMiddleware

func NewWhitelistMiddleware(whitelist []string, onWhite http.Handler) MiddlewareFunc

type OIDCOptions

type OIDCOptions struct {
	Issuer   string `json:"issuer" description:"oidc issuer url"`
	Insecure bool   `json:"insecure" description:"skip issuer and audience verification (optional)"`
	Audience string `json:"audience" description:"oidc resource server audience (optional)"`
}

type ParentResource

type ParentResource struct {
	Resource string `json:"resource,omitempty"`
	Name     string `json:"name,omitempty"`
}

type PathRewriteMatcher

type PathRewriteMatcher func(string) (string, bool)

func PrefixedPathRewriteMatcher

func PrefixedPathRewriteMatcher(prefix string) PathRewriteMatcher

type PermissionAction

type PermissionAction string
const (
	// It is recommended to use the ActionRead and ActionWrite constants when granting permissions.
	ActionRead  PermissionAction = "get,list,watch"                      // read is a combination of get, list and watch
	ActionWrite PermissionAction = "get,list,watch,create,update,remove" // if you have write, you have read as well
	// The following constants are provided for convenience.
	ActionCreate      PermissionAction = "create"
	ActionUpdate      PermissionAction = "update"
	ActionPatch       PermissionAction = "patch"
	ActionRemove      PermissionAction = "remove"
	ActionRemoveBatch PermissionAction = "removeBatch"
	ActionList        PermissionAction = "list"
	ActionGet         PermissionAction = "get"
	ActionWatch       PermissionAction = "watch"
	ActionUnknown     PermissionAction = ""
)

type PermissionChecker

type PermissionChecker interface {

	// HasPermission("alice", PermissionFromMethodPath("GET","/regions"))
	// HasPermission("alice", "regions:read")
	HasPermission(subject string, perm string) (bool, error)
}

type SimpleAuditor

type SimpleAuditor struct {
	Prefix  string // api prefix, e.g. /api/v1
	Options *AuditOptions
}

func NewSimpleAuditor

func NewSimpleAuditor(apiprefix string, options *AuditOptions, whitelist ...string) *SimpleAuditor

func (*SimpleAuditor) CompleteAuditResource

func (a *SimpleAuditor) CompleteAuditResource(method string, path string, auditlog *AuditLog)

func (*SimpleAuditor) OnRequest

func (*SimpleAuditor) OnResponse

func (a *SimpleAuditor) OnResponse(w http.ResponseWriter, r *http.Request, auditlog *AuditLog)

type SimpleOperation

type SimpleOperation interface {
	Add(name string, values ...string) error
	Remove(name string, values ...string) error
	Set(name string, values ...string) error
	Get(name string) []string
	List() map[string][]string
}

type StatusResponseWriter

type StatusResponseWriter struct {
	Inner http.ResponseWriter
	Code  int
	Cache []byte
	// contains filtered or unexported fields
}

func NewStatusResponseWriter

func NewStatusResponseWriter(inner http.ResponseWriter, maxCacheBodySize int) *StatusResponseWriter

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 SubjectExtractor

type SubjectExtractor func(r *http.Request) string

func DefaultSubjectExtractor

func DefaultSubjectExtractor() SubjectExtractor

type TokenClaims

type TokenClaims map[string]any

func TokenClaimsFromContext

func TokenClaimsFromContext(ctx context.Context) TokenClaims

func (TokenClaims) Get

func (t TokenClaims) Get(key string) any

func (TokenClaims) Subject

func (t TokenClaims) Subject() string

type TokenVerify

type TokenVerify interface {
	Verify(ctx context.Context, token string) (TokenClaims, error)
}

TokenVerify is an interface for verifying access tokens. The returned token claims.

func NewOIDCTokenVerify

func NewOIDCTokenVerify(ctx context.Context, options *OIDCOptions) (TokenVerify, error)

type TokenVerifyFunc

type TokenVerifyFunc func(ctx context.Context, token string) (TokenClaims, error)

func (TokenVerifyFunc) Verify

func (f TokenVerifyFunc) Verify(ctx context.Context, token string) (TokenClaims, error)

Jump to

Keyboard shortcuts

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