oauth2

package
v0.0.0-...-ce8de81 Latest Latest
Warning

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

Go to latest
Published: Sep 25, 2023 License: MIT Imports: 41 Imported by: 5

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrClientIDNotFound is raised when a client_id was not found
	ErrClientIDNotFound = errors.New(http.StatusBadRequest, "Invalid client ID provided")

	// ErrAccessTokenOfOtherOrigin is used when the access token is of other origin
	ErrAccessTokenOfOtherOrigin = errors.New(http.StatusUnauthorized, "access token of other origin")

	// ErrOauthServerNotFound is used when the oauth server was not found in the datastore
	ErrOauthServerNotFound = errors.New(http.StatusNotFound, "oauth server not found")

	// ErrDBContextNotSet is used when the database request context is not set
	ErrDBContextNotSet = errors.New(http.StatusInternalServerError, "DB context was not set for this request")

	// ErrJWTSecretMissing is used when the database request context is not set
	ErrJWTSecretMissing = errors.New(http.StatusBadRequest, "You need to set a JWT secret")

	// ErrUnknownManager is used when a manager type is not known
	ErrUnknownManager = errors.New(http.StatusBadRequest, "Unknown manager type provided")

	// ErrUnknownStrategy is used when a token strategy is not known
	ErrUnknownStrategy = errors.New(http.StatusBadRequest, "Unknown token strategy type provided")

	// ErrInvalidIntrospectionURL is used when an introspection URL is invalid
	ErrInvalidIntrospectionURL = errors.New(http.StatusBadRequest, "The provided introspection URL is invalid")

	// ErrOauthServerNameExists is used when the Oauth Server name is already registered on the datastore
	ErrOauthServerNameExists = errors.New(http.StatusConflict, "oauth server name is already registered")
)
View Source
var (
	AuthHeaderValue = ContextKey("auth_header")

	// ErrAuthorizationFieldNotFound is used when the http Authorization header is missing from the request
	ErrAuthorizationFieldNotFound = errors.New(http.StatusBadRequest, "authorization field missing")
	// ErrBearerMalformed is used when the Bearer string in the Authorization header is not found or is malformed
	ErrBearerMalformed = errors.New(http.StatusBadRequest, "bearer token malformed")
	// ErrAccessTokenNotAuthorized is used when the access token is not found on the storage
	ErrAccessTokenNotAuthorized = errors.New(http.StatusUnauthorized, "access token not authorized")
)

Enums for keys to be stored in a session context - this is how gorilla expects these to be implemented and is lifted pretty much from docs

Functions

func NewKeyExistsMiddleware

func NewKeyExistsMiddleware(manager Manager) func(http.Handler) http.Handler

NewKeyExistsMiddleware creates a new instance of KeyExistsMiddleware

func NewRevokeRulesMiddleware

func NewRevokeRulesMiddleware(parser *jwt.Parser, accessRules []*AccessRule) func(http.Handler) http.Handler

NewRevokeRulesMiddleware creates a new revoke rules middleware

Types

type AccessRequestType

type AccessRequestType string

AccessRequestType is the type for OAuth param `grant_type`

type AccessRule

type AccessRule struct {
	Predicate string `bson:"predicate" json:"predicate"`
	Action    string `bson:"action" json:"action"`
	// contains filtered or unexported fields
}

AccessRule represents a rule that will be applied to a JWT that could be revoked

func (*AccessRule) IsAllowed

func (r *AccessRule) IsAllowed(claims map[string]interface{}) (bool, error)

IsAllowed checks if the rule is allowed to

type AuthorizeRequestType

type AuthorizeRequestType string

AuthorizeRequestType is the type for OAuth param `response_type`

type CassandraRepository

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

CassandraRepository represents a cassandra repository

func NewCassandraRepository

func NewCassandraRepository(session wrapper.Holder) (*CassandraRepository, error)

func (*CassandraRepository) Add

func (r *CassandraRepository) Add(oauth *OAuth) error

Add add a new OAuth Server to the repository Add is the same as Save because Cassandra only upserts and I didn't want to write an existence checker

func (*CassandraRepository) FindAll

func (r *CassandraRepository) FindAll() ([]*OAuth, error)

FindAll fetches all the OAuth Servers available

func (*CassandraRepository) FindByName

func (r *CassandraRepository) FindByName(name string) (*OAuth, error)

FindByName find an OAuth Server by name

func (*CassandraRepository) Remove

func (r *CassandraRepository) Remove(name string) error

Remove removes an OAuth Server from the repository

func (*CassandraRepository) Save

func (r *CassandraRepository) Save(oauth *OAuth) error

Save saves OAuth Server to the repository

type ClientEndpoints

type ClientEndpoints struct {
	Create *proxy.Definition `bson:"create" json:"create"`
	Remove *proxy.Definition `bson:"remove" json:"remove"`
}

ClientEndpoints defines the oauth client endpoints that wil be proxied

type Config

type Config struct {
	ServerName string `json:"server_name"`
}

Config represents the oauth configuration

type ContextKey

type ContextKey string

ContextKey is used to create context keys that are concurrent safe

func (ContextKey) String

func (c ContextKey) String() string

type Controller

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

Controller is the api rest controller

func NewController

func NewController(repo Repository) *Controller

NewController creates a new instance of Controller

func (*Controller) DeleteBy

func (c *Controller) DeleteBy() http.HandlerFunc

DeleteBy is the delete handler

func (*Controller) Get

func (c *Controller) Get() http.HandlerFunc

Get is the find all handler

func (*Controller) GetBy

func (c *Controller) GetBy() http.HandlerFunc

GetBy is the find by handler

func (*Controller) Post

func (c *Controller) Post() http.HandlerFunc

Post is the create handler

func (*Controller) PutBy

func (c *Controller) PutBy() http.HandlerFunc

PutBy is the update handler

type Endpoints

type Endpoints struct {
	Authorize  *proxy.Definition `bson:"authorize" json:"authorize"`
	Token      *proxy.Definition `bson:"token" json:"token"`
	Introspect *proxy.Definition `bson:"introspect" json:"introspect"`
	Revoke     *proxy.Definition `bson:"revoke" json:"revoke"`
}

Endpoints defines the oauth endpoints that wil be proxied

type FileSystemRepository

type FileSystemRepository struct {
	*InMemoryRepository
	sync.Mutex
}

FileSystemRepository represents a mongodb repository

func NewFileSystemRepository

func NewFileSystemRepository(dir string) (*FileSystemRepository, error)

NewFileSystemRepository creates a mongo OAuth Server repo

type InMemoryRepository

type InMemoryRepository struct {
	sync.RWMutex
	// contains filtered or unexported fields
}

InMemoryRepository represents a in memory repository

func NewInMemoryRepository

func NewInMemoryRepository() *InMemoryRepository

NewInMemoryRepository creates a in memory repository

func (*InMemoryRepository) Add

func (r *InMemoryRepository) Add(server *OAuth) error

Add add a new OAuth Server to the repository

func (*InMemoryRepository) FindAll

func (r *InMemoryRepository) FindAll() ([]*OAuth, error)

FindAll fetches all the OAuth Servers available

func (*InMemoryRepository) FindByName

func (r *InMemoryRepository) FindByName(name string) (*OAuth, error)

FindByName find an OAuth Server by name

func (*InMemoryRepository) Remove

func (r *InMemoryRepository) Remove(name string) error

Remove removes an OAuth Server from the repository

func (*InMemoryRepository) Save

func (r *InMemoryRepository) Save(server *OAuth) error

Save saves a OAuth Server to the repository

type IntrospectionManager

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

IntrospectionManager is responsible for using OAuth2 Introspection definition to validate tokens from an authentication provider

func NewIntrospectionManager

func NewIntrospectionManager(def *proxy.Definition, settings *IntrospectionSettings) (*IntrospectionManager, error)

NewIntrospectionManager creates a new instance of Introspection

func (*IntrospectionManager) IsKeyAuthorized

func (o *IntrospectionManager) IsKeyAuthorized(ctx context.Context, accessToken string) bool

IsKeyAuthorized checks if the access token is valid

type IntrospectionSettings

type IntrospectionSettings struct {
	UseCustomHeader bool   `mapstructure:"use_custom_header" bson:"use_custom_header" json:"use_custom_header"`
	HeaderName      string `mapstructure:"header_name" bson:"header_name" json:"header_name"`
	UseAuthHeader   bool   `mapstructure:"use_auth_header" bson:"use_auth_header" json:"use_auth_header"`
	AuthHeaderType  string `mapstructure:"auth_header_type" bson:"auth_header_type" json:"auth_header_type"`
	UseBody         bool   `mapstructure:"use_body" bson:"use_body" json:"use_body"`
	ParamName       string `mapstructure:"param_name" bson:"param_name" json:"param_name"`
}

IntrospectionSettings represents the settings for introspection

type JWTManager

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

JWTManager is responsible for managing the JWT tokens

func NewJWTManager

func NewJWTManager(parser *jwt.Parser) *JWTManager

NewJWTManager creates a new instance of JWTManager

func (*JWTManager) IsKeyAuthorized

func (m *JWTManager) IsKeyAuthorized(ctx context.Context, accessToken string) bool

IsKeyAuthorized checks if the access token is valid

type Manager

type Manager interface {
	IsKeyAuthorized(ctx context.Context, accessToken string) bool
}

Manager holds the methods to handle tokens

type ManagerFactory

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

ManagerFactory is used for creating a new manager

func NewManagerFactory

func NewManagerFactory(oAuthServer *OAuth) *ManagerFactory

NewManagerFactory creates a new instance of ManagerFactory

func (*ManagerFactory) Build

func (f *ManagerFactory) Build(t ManagerType) (Manager, error)

Build creates a manager based on the type

type ManagerType

type ManagerType uint8

ManagerType type

const (
	// JWT provides a way to check the `exp` field on the JWT and make sure the token is still valid. This is
	// probably the most versatile way to check for tokens, since it doesn't require any storage or extra calls in
	// each request.
	JWT ManagerType = iota
	// Introspection strategy makes sure to validate the provided token on every request against the authentication provider.
	Introspection
)

func ParseType

func ParseType(lvl string) (ManagerType, error)

ParseType takes a string type and returns the Manager type constant.

type MongoRepository

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

MongoRepository represents a mongodb repository

func NewMongoRepository

func NewMongoRepository(db *mongo.Database) (*MongoRepository, error)

NewMongoRepository creates a mongodb OAuth Server repo

func (*MongoRepository) Add

func (r *MongoRepository) Add(oauth *OAuth) error

Add add a new OAuth Server to the repository

func (*MongoRepository) FindAll

func (r *MongoRepository) FindAll() ([]*OAuth, error)

FindAll fetches all the OAuth Servers available

func (*MongoRepository) FindByName

func (r *MongoRepository) FindByName(name string) (*OAuth, error)

FindByName find an OAuth Server by name

func (*MongoRepository) Remove

func (r *MongoRepository) Remove(name string) error

Remove removes an OAuth Server from the repository

func (*MongoRepository) Save

func (r *MongoRepository) Save(oauth *OAuth) error

Save saves OAuth Server to the repository

type OAuth

type OAuth struct {
	Name                   string                 `bson:"name" json:"name" valid:"required"`
	Endpoints              Endpoints              `bson:"oauth_endpoints" json:"oauth_endpoints" mapstructure:"oauth_endpoints"`
	ClientEndpoints        ClientEndpoints        `bson:"oauth_client_endpoints" json:"oauth_client_endpoints" mapstructure:"oauth_client_endpoints"`
	AllowedAccessTypes     []AccessRequestType    `bson:"allowed_access_types" json:"allowed_access_types" mapstructure:"allowed_access_types" `
	AllowedAuthorizeTypes  []AuthorizeRequestType `bson:"allowed_authorize_types" json:"allowed_authorize_types" mapstructure:"allowed_authorize_types"`
	AuthorizeLoginRedirect string                 `bson:"auth_login_redirect" json:"auth_login_redirect" mapstructure:"auth_login_redirect"`
	Secrets                map[string]string      `bson:"secrets" json:"secrets"`
	CorsMeta               corsMeta               `bson:"cors_meta" json:"cors_meta" mapstructure:"cors_meta"`
	RateLimit              rateLimitMeta          `bson:"rate_limit" json:"rate_limit"`
	TokenStrategy          TokenStrategy          `bson:"token_strategy" json:"token_strategy" mapstructure:"token_strategy"`
	AccessRules            []*AccessRule          `bson:"access_rules" json:"access_rules"`
}

OAuth holds the configuration for oauth proxies

func NewOAuth

func NewOAuth() *OAuth

NewOAuth creates a new instance of OAuth

type OAuthLoader

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

OAuthLoader handles the loading of the api specs

func NewOAuthLoader

func NewOAuthLoader(register *proxy.Register) *OAuthLoader

NewOAuthLoader creates a new instance of the Loader

func (*OAuthLoader) LoadDefinitions

func (m *OAuthLoader) LoadDefinitions(repo Repository)

LoadDefinitions loads all oauth servers from a data source

func (*OAuthLoader) RegisterOAuthServers

func (m *OAuthLoader) RegisterOAuthServers(oauthServers []*Spec, repo Repository)

RegisterOAuthServers register many oauth servers

type Repository

type Repository interface {
	FindAll() ([]*OAuth, error)
	FindByName(name string) (*OAuth, error)
	Add(oauth *OAuth) error
	Save(oauth *OAuth) error
	Remove(id string) error
}

Repository defines the behavior of a OAuth Server repo

type SecretMiddleware

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

SecretMiddleware is used as a helper for client applications that don't want to send the client secret on the request. The applications should only send the `client_id` and this middleware will try to find the secret on it's configuration. If the secret is found then the middleware will build a valid `Authorization` header to be sent to the authentication provider. If the secret is not found then and error is returned to the client application.

func NewSecretMiddleware

func NewSecretMiddleware(oauth *Spec) *SecretMiddleware

NewSecretMiddleware creates an instance of SecretMiddleware

func (*SecretMiddleware) Handler

func (m *SecretMiddleware) Handler(handler http.Handler) http.Handler

Handler is the middleware method.

type Spec

type Spec struct {
	*OAuth
	Manager Manager
}

Spec Holds an api definition and basic options

type TokenStrategy

type TokenStrategy struct {
	Name     string      `bson:"name" json:"name"`
	Settings interface{} `bson:"settings" json:"settings"`
	// TODO: this should become part of the settings, but for "jwt" strategy we expect array of signing methods
	// at the moment, so this will be BC-breaking change. In the next major version we need to turn settings
	// into object/dictionary and make leeway one of the settings.
	Leeway int64 `bson:"leeway" json:"leeway"`
}

TokenStrategy defines the token strategy fields

func (TokenStrategy) GetIntrospectionSettings

func (t TokenStrategy) GetIntrospectionSettings() (*IntrospectionSettings, error)

GetIntrospectionSettings returns the settings for introspection

func (TokenStrategy) GetJWTSigningMethods

func (t TokenStrategy) GetJWTSigningMethods() ([]jwt.SigningMethod, error)

GetJWTSigningMethods parses and returns chain of JWT signing methods for token signature validation. Supports fallback to legacy format with {"secret": "key"} as single signing method with HS256 alg.

Jump to

Keyboard shortcuts

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