mongo

package
v0.2.6 Latest Latest
Warning

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

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

Documentation

Index

Constants

View Source
const (
	// IdxClientID provides a mongo index based on clientId
	IdxClientID = "idxClientId"

	// IdxExpires provides a mongo index based on expires
	IdxExpires = "idxExpires"

	// IdxExpiry provides a mongo index for generating ttl based record
	// expiration indices.
	IdxExpiry = "idxExpiry"

	// IdxUserID provides a mongo index based on userID
	IdxUserID = "idxUserId"

	// IdxUsername provides a mongo index based on username
	IdxUsername = "idxUsername"

	// IdxSessionID provides a mongo index based on Session
	IdxSessionID = "idxSessionId"

	// IdxSignatureID provides a mongo index based on Signature
	IdxSignatureID = "idxSignatureId"

	// IdxCompoundRequester provides a mongo compound index based on Client ID
	// and User ID for when filtering request records.
	IdxCompoundRequester = "idxCompoundRequester"
)

Variables

This section is empty.

Functions

func Connect

func Connect(cfg *Config) (*mongo.Database, error)

Connect returns a connection to a mongo database.

func ConnectionInfo

func ConnectionInfo(cfg *Config) *options.ClientOptions

ConnectionInfo configures options for establishing a session with a MongoDB cluster.

func ContextToSession

func ContextToSession(ctx context.Context) (sess mongo.Session, ok bool)

ContextToSession provides a way to obtain a mongo session, if contained within the presented context.

func NewExpiryIndex

func NewExpiryIndex(name string, key string, expireAfter int) (model mongo.IndexModel)

NewExpiryIndex generates a new index with a time to live value before the record expires in mongodb.

func NewIndex

func NewIndex(name string, keys ...string) (model mongo.IndexModel)

NewIndex generates a new index model, ready to be saved in mongo.

Note:

  • This function assumes you are entering valid index keys and relies on mongo rejecting index operations if a bad index is created.

func NewUniqueIndex

func NewUniqueIndex(name string, keys ...string) mongo.IndexModel

NewUniqueIndex generates a new unique index model, ready to be saved in mongo.

func SessionToContext

func SessionToContext(ctx context.Context, session mongo.Session) context.Context

SessionToContext provides a way to push a mongo datastore session into the current context, which can then be passed on to other routes or functions.

Types

type ClientManager

type ClientManager struct {
	DB     *DB
	Hasher fosite.Hasher

	DeniedJTIs storage.DeniedJTIStore
}

ClientManager provides a fosite storage implementation for Clients.

Implements: - fosite.Storage - fosite.ClientManager - storage.AuthClientMigrator - storage.ClientManager - storage.ClientStore

func (*ClientManager) Authenticate

func (c *ClientManager) Authenticate(ctx context.Context, clientID string, secret string) (result storage.Client, err error)

Authenticate verifies the identity of a client resource.

func (*ClientManager) AuthenticateMigration

func (c *ClientManager) AuthenticateMigration(ctx context.Context, currentAuth storage.AuthClientFunc, clientID string, secret string) (result storage.Client, err error)

AuthenticateMigration is provided to authenticate clients that have been migrated from a system that may use a different underlying hashing mechanism. It authenticates a Client first by using the provided AuthClientFunc which, if fails, will otherwise try to authenticate using the configured fosite.hasher.

func (*ClientManager) ClientAssertionJWTValid

func (c *ClientManager) ClientAssertionJWTValid(ctx context.Context, jti string) error

ClientAssertionJWTValid returns an error if the JTI is known or the DB check failed and nil if the JTI is not known.

func (*ClientManager) Configure

func (c *ClientManager) Configure(ctx context.Context) (err error)

Configure sets up the Mongo collection for OAuth 2.0 client resources.

func (*ClientManager) Create

func (c *ClientManager) Create(ctx context.Context, client storage.Client) (result storage.Client, err error)

Create stores a new OAuth2.0 Client resource.

func (*ClientManager) Delete

func (c *ClientManager) Delete(ctx context.Context, clientID string) (err error)

Delete removes an OAuth 2.0 Client resource.

func (*ClientManager) Get

func (c *ClientManager) Get(ctx context.Context, clientID string) (result storage.Client, err error)

Get finds and returns an OAuth 2.0 client resource.

func (*ClientManager) GetClient

func (c *ClientManager) GetClient(ctx context.Context, clientID string) (fosite.Client, error)

GetClient finds and returns an OAuth 2.0 client resource.

GetClient implements: - fosite.Storage - fosite.ClientManager

func (*ClientManager) GrantScopes

func (c *ClientManager) GrantScopes(ctx context.Context, clientID string, scopes []string) (result storage.Client, err error)

GrantScopes grants the provided scopes to the specified Client resource.

func (*ClientManager) IsJWTUsed added in v0.0.4

func (c *ClientManager) IsJWTUsed(ctx context.Context, jti string) (bool, error)

func (*ClientManager) List

func (c *ClientManager) List(ctx context.Context, filter storage.ListClientsRequest) (results []storage.Client, err error)

List filters resources to return a list of OAuth 2.0 client resources.

func (*ClientManager) MarkJWTUsedForTime added in v0.0.4

func (c *ClientManager) MarkJWTUsedForTime(ctx context.Context, jti string, exp time.Time) error

func (*ClientManager) Migrate

func (c *ClientManager) Migrate(ctx context.Context, migratedClient storage.Client) (result storage.Client, err error)

Migrate is provided solely for the case where you want to migrate clients and upgrade their password using the AuthClientMigrator interface. This performs an upsert, either creating or overwriting the record with the newly provided full record. Use with caution, be secure, don't be dumb.

func (*ClientManager) RemoveScopes

func (c *ClientManager) RemoveScopes(ctx context.Context, clientID string, scopes []string) (result storage.Client, err error)

RemoveScopes revokes the provided scopes from the specified Client resource.

func (*ClientManager) SetClientAssertionJWT

func (c *ClientManager) SetClientAssertionJWT(ctx context.Context, jti string, exp time.Time) (err error)

SetClientAssertionJWT marks a JTI as known for the given expiry time. Before inserting the new JTI, it will clean up any existing JTIs that have expired as those tokens can not be replayed due to the expiry.

func (*ClientManager) Update

func (c *ClientManager) Update(ctx context.Context, clientID string, updatedClient storage.Client) (result storage.Client, err error)

Update updates an OAuth 2.0 client resource.

type Config

type Config struct {
	Hostnames        []string    `default:"localhost" envconfig:"CONNECTIONS_MONGO_HOSTNAMES"`
	Port             uint16      `default:"27017"     envconfig:"CONNECTIONS_MONGO_PORT"`
	SSL              bool        `default:"false"     envconfig:"CONNECTIONS_MONGO_SSL"`
	AuthDB           string      `default:"admin"     envconfig:"CONNECTIONS_MONGO_AUTHDB"`
	Username         string      `default:""          envconfig:"CONNECTIONS_MONGO_USERNAME"`
	Password         string      `default:""          envconfig:"CONNECTIONS_MONGO_PASSWORD"`
	DatabaseName     string      `default:""          envconfig:"CONNECTIONS_MONGO_NAME"`
	Replset          string      `default:""          envconfig:"CONNECTIONS_MONGO_REPLSET"`
	Timeout          uint        `default:"10"        envconfig:"CONNECTIONS_MONGO_TIMEOUT"`
	PoolMinSize      uint64      `default:"0"         envconfig:"CONNECTIONS_MONGO_POOL_MIN_SIZE"`
	PoolMaxSize      uint64      `default:"100"       envconfig:"CONNECTIONS_MONGO_POOL_MAX_SIZE"`
	Compressors      []string    `default:""          envconfig:"CONNECTIONS_MONGO_COMPRESSORS"`
	TokenTTL         uint32      `default:"0"         envconfig:"CONNECTIONS_MONGO_TOKEN_TTL"`
	CollectionPrefix string      `default:""          envconfig:"CONNECTIONS_MONGO_COLLECTION_PREFIX"`
	TLSConfig        *tls.Config `ignored:"true"`
}

Config defines the configuration parameters which are used by GetMongoSession.

func DefaultConfig

func DefaultConfig() *Config

DefaultConfig returns a configuration for a locally hosted, unauthenticated mongo

type DB

type DB struct {
	*mongo.Database
}

DB wraps the mongo database connection and the features that are enabled.

type DeniedJtiManager

type DeniedJtiManager struct {
	DB *DB

	BlacklistedJTIs        map[string]time.Time
	AccessTokenRequestIDs  map[string]string
	RefreshTokenRequestIDs map[string]string
	// contains filtered or unexported fields
}

DeniedJtiManager provides a mongo backed implementation for denying JSON Web Tokens (JWTs) by ID.

func (*DeniedJtiManager) ClientAssertionJWTValid added in v0.0.4

func (d *DeniedJtiManager) ClientAssertionJWTValid(_ context.Context, jti string) error

func (*DeniedJtiManager) Configure

func (d *DeniedJtiManager) Configure(ctx context.Context) (err error)

Configure implements storage.Configure.

func (*DeniedJtiManager) Create

func (d *DeniedJtiManager) Create(ctx context.Context, deniedJTI storage.DeniedJTI) (result storage.DeniedJTI, err error)

Create creates a new User resource and returns the newly created User resource.

func (*DeniedJtiManager) Delete

func (d *DeniedJtiManager) Delete(ctx context.Context, jti string) (err error)

func (*DeniedJtiManager) DeleteBefore

func (d *DeniedJtiManager) DeleteBefore(ctx context.Context, expBefore int64) (err error)

DeleteBefore DeleteExpired removes all JTIs before the given time. Returns not found if no tokens were found before the given time.

func (*DeniedJtiManager) Get

func (d *DeniedJtiManager) Get(ctx context.Context, signature string) (result storage.DeniedJTI, err error)

Get returns the specified User resource.

func (*DeniedJtiManager) SetClientAssertionJWT added in v0.0.4

func (d *DeniedJtiManager) SetClientAssertionJWT(_ context.Context, jti string, exp time.Time) error

type IssuerPublicKeys added in v0.0.4

type IssuerPublicKeys struct {
	Issuer    string
	KeysBySub map[string]SubjectPublicKeys
}

type PublicKeyScopes added in v0.0.4

type PublicKeyScopes struct {
	Key    *jose.JSONWebKey
	Scopes []string
}

type RequestManager

type RequestManager struct {
	// DB contains the Mongo connection that holds the base session that can be
	// copied and closed.
	DB *DB

	// Clients provides access to Client entities in order to create, read,
	// update and delete resources from the clients collection.
	// A client is required when cross referencing scope access rights.
	Clients storage.ClientStore

	// Users provides access to User entities in order to create, read, update
	// and delete resources from the user collection.
	// Users are required when the Password Credentials Grant, is implemented
	// in order to find and authenticate users.
	Users storage.UserStorer

	// Public keys to check signature in auth grant jwt assertion.
	IssuerPublicKeys map[string]IssuerPublicKeys
	// contains filtered or unexported fields
}

RequestManager manages the main Mongo Session for a Request.

func (*RequestManager) Authenticate

func (r *RequestManager) Authenticate(ctx context.Context, username string, secret string) (err error)

Authenticate confirms whether the specified password matches the stored hashed password within a User resource, found by username.

func (*RequestManager) Configure

func (r *RequestManager) Configure(ctx context.Context) (err error)

Configure implements storage.Configure.

func (*RequestManager) ConfigureExpiryWithTTL

func (r *RequestManager) ConfigureExpiryWithTTL(ctx context.Context, ttl int) error

ConfigureExpiryWithTTL implements storage.Expire.

func (*RequestManager) Create

func (r *RequestManager) Create(ctx context.Context, entityName string, request storage.Request) (result storage.Request, err error)

Create creates the new Request resource and returns the newly created Request resource.

func (*RequestManager) CreateAccessTokenSession

func (r *RequestManager) CreateAccessTokenSession(ctx context.Context, signature string, request fosite.Requester) (err error)

CreateAccessTokenSession creates a new session for an Access Token

func (*RequestManager) CreateAuthorizeCodeSession

func (r *RequestManager) CreateAuthorizeCodeSession(ctx context.Context, code string, request fosite.Requester) (err error)

CreateAuthorizeCodeSession stores the authorization request for a given authorization code.

func (*RequestManager) CreateOpenIDConnectSession

func (r *RequestManager) CreateOpenIDConnectSession(ctx context.Context, authorizeCode string, request fosite.Requester) (err error)

CreateOpenIDConnectSession creates an open id connect session resource for a given authorize code. This is relevant for explicit open id connect flow.

func (*RequestManager) CreatePKCERequestSession

func (r *RequestManager) CreatePKCERequestSession(ctx context.Context, signature string, request fosite.Requester) (err error)

CreatePKCERequestSession implements fosite.PKCERequestStorage.

func (*RequestManager) CreateRefreshTokenSession

func (r *RequestManager) CreateRefreshTokenSession(ctx context.Context, signature string, request fosite.Requester) (err error)

CreateRefreshTokenSession implements fosite.RefreshTokenStorage.

func (*RequestManager) Delete

func (r *RequestManager) Delete(ctx context.Context, entityName string, requestID string) (err error)

Delete deletes the specified Request resource.

func (*RequestManager) DeleteAccessTokenSession

func (r *RequestManager) DeleteAccessTokenSession(ctx context.Context, signature string) (err error)

DeleteAccessTokenSession removes an Access Token's session

func (*RequestManager) DeleteBySignature

func (r *RequestManager) DeleteBySignature(ctx context.Context, entityName string, signature string) (err error)

DeleteBySignature deletes the specified request resource, if the presented signature returns a match.

func (*RequestManager) DeleteOpenIDConnectSession

func (r *RequestManager) DeleteOpenIDConnectSession(ctx context.Context, authorizeCode string) (err error)

DeleteOpenIDConnectSession removes an open id connect session from mongo.

func (*RequestManager) DeletePKCERequestSession

func (r *RequestManager) DeletePKCERequestSession(ctx context.Context, signature string) (err error)

DeletePKCERequestSession implements fosite.PKCERequestStorage.

func (*RequestManager) DeleteRefreshTokenSession

func (r *RequestManager) DeleteRefreshTokenSession(ctx context.Context, signature string) (err error)

DeleteRefreshTokenSession implements fosite.RefreshTokenStorage.

func (*RequestManager) Get

func (r *RequestManager) Get(ctx context.Context, entityName string, requestID string) (result storage.Request, err error)

Get returns the specified Request resource.

func (*RequestManager) GetAccessTokenSession

func (r *RequestManager) GetAccessTokenSession(ctx context.Context, signature string, session fosite.Session) (request fosite.Requester, err error)

GetAccessTokenSession returns a session if it can be found by signature

func (*RequestManager) GetAuthorizeCodeSession

func (r *RequestManager) GetAuthorizeCodeSession(ctx context.Context, code string, session fosite.Session) (request fosite.Requester, err error)

GetAuthorizeCodeSession hydrates the session based on the given code and returns the authorization request.

func (*RequestManager) GetBySignature

func (r *RequestManager) GetBySignature(ctx context.Context, entityName string, signature string) (result storage.Request, err error)

GetBySignature returns a Request resource, if the presented signature returns a match.

func (*RequestManager) GetOpenIDConnectSession

func (r *RequestManager) GetOpenIDConnectSession(ctx context.Context, authorizeCode string, requester fosite.Requester) (request fosite.Requester, err error)

GetOpenIDConnectSession gets a session resource based off the Authorize Code and returns a fosite.Requester, or an error.

func (*RequestManager) GetPKCERequestSession

func (r *RequestManager) GetPKCERequestSession(ctx context.Context, signature string, session fosite.Session) (request fosite.Requester, err error)

GetPKCERequestSession implements fosite.PKCERequestStorage.

func (*RequestManager) GetPublicKey added in v0.0.4

func (r *RequestManager) GetPublicKey(ctx context.Context, issuer string, subject string, keyId string) (*jose.JSONWebKey, error)

func (*RequestManager) GetPublicKeyScopes added in v0.0.4

func (r *RequestManager) GetPublicKeyScopes(ctx context.Context, issuer string, subject string, keyId string) ([]string, error)

func (*RequestManager) GetPublicKeys added in v0.0.4

func (r *RequestManager) GetPublicKeys(ctx context.Context, issuer string, subject string) (*jose.JSONWebKeySet, error)

func (*RequestManager) GetRefreshTokenSession

func (r *RequestManager) GetRefreshTokenSession(ctx context.Context, signature string, session fosite.Session) (request fosite.Requester, err error)

GetRefreshTokenSession implements fosite.RefreshTokenStorage.

func (*RequestManager) InvalidateAuthorizeCodeSession

func (r *RequestManager) InvalidateAuthorizeCodeSession(ctx context.Context, code string) (err error)

InvalidateAuthorizeCodeSession is called when an authorize code is being used. The state of the authorization code should be set to invalid and consecutive requests to GetAuthorizeCodeSession should return the ErrInvalidatedAuthorizeCode error.

func (*RequestManager) List

func (r *RequestManager) List(ctx context.Context, entityName string, filter storage.ListRequestsRequest) (results []storage.Request, err error)

List returns a list of Request resources that match the provided inputs.

func (*RequestManager) RevokeAccessToken

func (r *RequestManager) RevokeAccessToken(ctx context.Context, requestID string) (err error)

RevokeAccessToken deletes the access token session.

func (*RequestManager) RevokeRefreshToken

func (r *RequestManager) RevokeRefreshToken(ctx context.Context, requestID string) (err error)

RevokeRefreshToken deletes the refresh token session.

func (*RequestManager) RevokeRefreshTokenMaybeGracePeriod added in v0.0.4

func (r *RequestManager) RevokeRefreshTokenMaybeGracePeriod(ctx context.Context, requestID string, signature string) error

func (*RequestManager) Update

func (r *RequestManager) Update(ctx context.Context, entityName string, requestID string, updatedRequest storage.Request) (result storage.Request, err error)

Update updates the Request resource and attributes and returns the updated Request resource.

type Store

type Store struct {
	// Internals
	DB *DB

	// Public API
	Hasher fosite.Hasher
	storage.Store
	// contains filtered or unexported fields
}

Store provides a MongoDB storage driver compatible with fosite's required storage interfaces.

func New

func New(cfg *Config, hashee fosite.Hasher) (*Store, error)

New allows for custom mongo configuration and custom hashers.

func NewDefaultStore

func NewDefaultStore() (*Store, error)

NewDefaultStore returns a Store configured with the default mongo configuration and default Hasher.

func (*Store) Close

func (s *Store) Close()

Close terminates the mongo connection.

func (*Store) NewSession

func (s *Store) NewSession(ctx context.Context) (context.Context, func(), error)

NewSession creates and returns a new mongo session. A deferrable session closer is returned in an attempt to enforce proper session handling/closing of sessions to avoid session and memory leaks.

NewSession boilerplate becomes: ``` ctx := context.Background()

if store.DB.HasSessions {
    var closeSession func()
    ctx, closeSession, err = store.NewSession(nil)
    if err != nil {
        panic(err)
    }
    defer closeSession()
}

```

type SubjectPublicKeys added in v0.0.4

type SubjectPublicKeys struct {
	Subject string
	Keys    map[string]PublicKeyScopes
}

type UserManager

type UserManager struct {
	DB     *DB
	Hasher fosite.Hasher
}

UserManager provides a mongo backed implementation for user resources.

Implements: - storage.Configure - storage.AuthUserMigrator - storage.UserStorer - storage.UserManager

func (*UserManager) Authenticate

func (u *UserManager) Authenticate(ctx context.Context, username string, password string) (result storage.User, err error)

Authenticate confirms whether the specified password matches the stored hashed password within the User resource. The User resource returned is matched by username.

func (*UserManager) AuthenticateByID

func (u *UserManager) AuthenticateByID(ctx context.Context, userID string, password string) (result storage.User, err error)

AuthenticateByID confirms whether the specified password matches the stored hashed password within the User resource. The User resource returned is matched by User ID.

func (*UserManager) AuthenticateByUsername

func (u *UserManager) AuthenticateByUsername(ctx context.Context, username string, password string) (result storage.User, err error)

AuthenticateByUsername confirms whether the specified password matches the stored hashed password within the User resource. The User resource returned is matched by username.

func (*UserManager) AuthenticateMigration

func (u *UserManager) AuthenticateMigration(ctx context.Context, currentAuth storage.AuthUserFunc, userID string, password string) (result storage.User, err error)

AuthenticateMigration enables developers to supply your own authentication function, which in turn, if true, will migrate the secret to the Hasher implemented within fosite.

func (*UserManager) Configure

func (u *UserManager) Configure(ctx context.Context) (err error)

Configure implements storage.Configure.

func (*UserManager) Create

func (u *UserManager) Create(ctx context.Context, user storage.User) (result storage.User, err error)

Create creates a new User resource and returns the newly created User resource.

func (*UserManager) Delete

func (u *UserManager) Delete(ctx context.Context, userID string) (err error)

Delete deletes the specified User resource.

func (*UserManager) Get

func (u *UserManager) Get(ctx context.Context, userID string) (result storage.User, err error)

Get returns the specified User resource.

func (*UserManager) GetByUsername

func (u *UserManager) GetByUsername(ctx context.Context, username string) (result storage.User, err error)

GetByUsername returns a user resource if found by username.

func (*UserManager) GrantScopes

func (u *UserManager) GrantScopes(ctx context.Context, userID string, scopes []string) (result storage.User, err error)

GrantScopes grants the provided scopes to the specified User resource.

func (*UserManager) List

func (u *UserManager) List(ctx context.Context, filter storage.ListUsersRequest) (results []storage.User, err error)

List returns a list of User resources that match the provided inputs.

func (*UserManager) Migrate

func (u *UserManager) Migrate(ctx context.Context, migratedUser storage.User) (result storage.User, err error)

Migrate is provided solely for the case where you want to migrate users and upgrade their password using the AuthUserMigrator interface. This performs an upsert, either creating or overwriting the record with the newly provided full record. Use with caution, be secure, don't be dumb.

func (*UserManager) RemoveScopes

func (u *UserManager) RemoveScopes(ctx context.Context, userID string, scopes []string) (result storage.User, err error)

RemoveScopes revokes the provided scopes from the specified User Resource.

func (*UserManager) Update

func (u *UserManager) Update(ctx context.Context, userID string, updatedUser storage.User) (result storage.User, err error)

Update updates the User resource and attributes and returns the updated User resource.

Jump to

Keyboard shortcuts

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