edgecontext

package
v1.6.3 Latest Latest
Warning

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

Go to latest
Published: Feb 3, 2023 License: BSD-3-Clause Imports: 20 Imported by: 0

Documentation

Overview

Package edgecontext implements Baseplate edge request context.

Index

Constants

View Source
const JWTHeaderKeyID = "kid"

JWTHeaderKeyID is the JWT header for the key id, as defined in RFC 7517 section 4.5.

View Source
const LoIDPrefix = "t2_"

LoIDPrefix is the prefix for all LoIDs.

Variables

View Source
var (
	// ErrLoIDWrongPrefix is an error could be returned by New() when passed in LoID
	// does not have the correct prefix.
	ErrLoIDWrongPrefix = errors.New("edgecontext: loid should have " + LoIDPrefix + " prefix")

	// ErrInvalidLocaleCode is returned by New() when an invalid locale code is passed in.
	ErrInvalidLocaleCode = errors.New("edgecontext: locale code should match format: en, en_US")
)
View Source
var ErrEmptyToken = errors.New("edgecontext.ValidateToken: empty JWT token")

ErrEmptyToken is an error returned by ValidateToken indicates that the JWT token is empty string.

View Source
var ErrNoPublicKeysLoaded = errors.New("edgecontext.ValidateToken: no public keys loaded")

ErrNoPublicKeysLoaded is an error returned by ValidateToken indicates that the function is called before any public keys are loaded from secrets.

View Source
var LocaleRegex = regexp.MustCompile(`^[a-z]{2,}([_|\-][\da-zA-Z]{2,})*$`)

LocaleRegex validates that locale codes are correctly formatted. They can contain either a language, or a language and region specifier separated by an underscore. e.g. en, en_US

Functions

func Factory

func Factory(cfg Config) ecinterface.Factory

Factory returns an ecinterface.Factory implementation by wrapping Init.

The Store in cfg will be replaced by the Factory arg.

func RSAPublicKeyFingerprint added in v1.6.1

func RSAPublicKeyFingerprint(pubKey *rsa.PublicKey) (string, error)

RSAPublicKeyFingerprint calculates the fingerprint of an RSA public key, using ssh.FingerprintSHA256: https://pkg.go.dev/golang.org/x/crypto/ssh#FingerprintSHA256

func SetEdgeContext

func SetEdgeContext(ctx context.Context, ec *EdgeRequestContext) context.Context

SetEdgeContext sets the given EdgeRequestContext on the context object.

Types

type AuthenticationToken

type AuthenticationToken struct {
	jwt.StandardClaims

	Roles []string `json:"roles,omitempty"`

	OAuthClientID   string   `json:"client_id,omitempty"`
	OAuthClientType string   `json:"client_type,omitempty"`
	Scopes          []string `json:"scopes,omitempty"`

	LoID struct {
		ID        string                      `json:"id,omitempty"`
		CreatedAt timebp.TimestampMillisecond `json:"created_ms,omitempty"`
	} `json:"loid,omitempty"`
}

AuthenticationToken defines the json format of the authentication token.

func (AuthenticationToken) Subject

func (t AuthenticationToken) Subject() string

Subject returns the subject field of the token.

type Config

type Config struct {
	// The secret store to get the keys for jwt validation
	Store *secrets.Store
	// The logger to log key decoding errors
	Logger log.Wrapper
}

Config for Init function.

type EdgeRequestContext

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

An EdgeRequestContext contains context info about an edge request.

func FromHeader

func FromHeader(ctx context.Context, header string, impl *Impl) (*EdgeRequestContext, error)

FromHeader returns a new EdgeRequestContext from the given header string using the given Impl.

func GetEdgeContext

func GetEdgeContext(ctx context.Context) (ec *EdgeRequestContext, ok bool)

GetEdgeContext gets the current EdgeRequestContext from the context object, if set.

func New

func New(ctx context.Context, impl *Impl, args NewArgs) (*EdgeRequestContext, error)

New creates a new EdgeRequestContext from scratch.

This function should be used by services on the edge talking to clients directly, after talked to authentication service to get the auth token.

func (*EdgeRequestContext) AuthToken

func (e *EdgeRequestContext) AuthToken() *AuthenticationToken

AuthToken either validates the raw auth token and cache it, or return the cached token.

If the validation failed, the error will be logged.

func (*EdgeRequestContext) CountryCode

func (e *EdgeRequestContext) CountryCode() string

CountryCode returns the two-character ISO 3166-1 country code where the request orginated from.

func (*EdgeRequestContext) DeviceID

func (e *EdgeRequestContext) DeviceID() string

DeviceID returns the device id of this request.

func (*EdgeRequestContext) Header

func (e *EdgeRequestContext) Header() string

Header returns the raw, underlying edge request context header that was parsed to create the EdgeRequestContext object.

This is not really intended to be used directly but to allow us to propogate the header between services.

func (*EdgeRequestContext) LocaleCode added in v1.6.0

func (e *EdgeRequestContext) LocaleCode() string

LocaleCode returns the IETF language code for the client

func (*EdgeRequestContext) OAuthClient

func (e *EdgeRequestContext) OAuthClient() (client OAuthClient, ok bool)

OAuthClient returns the info about the oauth client of this request.

ok will be false if this request does not have a valid auth token.

func (*EdgeRequestContext) OriginService

func (e *EdgeRequestContext) OriginService() OriginService

OriginService returns the info about the origin of this request.

func (*EdgeRequestContext) RequestID added in v1.0.2

func (e *EdgeRequestContext) RequestID() string

RequestID is the id of this request.

func (*EdgeRequestContext) Service

func (e *EdgeRequestContext) Service() (service Service, ok bool)

Service returns the info about the client service of this request.

ok will be false if this request does not have a valid auth token.

func (*EdgeRequestContext) SessionID

func (e *EdgeRequestContext) SessionID() string

SessionID returns the session id of this request.

func (*EdgeRequestContext) UpdateExperimentEvent

func (e *EdgeRequestContext) UpdateExperimentEvent(ee *experiments.ExperimentEvent)

UpdateExperimentEvent updates the passed in experiment event with info from this edge request context.

It always updates UserID, LoggedIn, CookieCreatedAt, OAuthClientID, SessionID, and DeviceID fields, and never touches other fields in experiment event.

The caller should create an experiments.ExperimentEvent object, with other non-edge-request related fields already filled, call this function to update edge-request related fields updated, then pass it to an event logger.

func (*EdgeRequestContext) User

func (e *EdgeRequestContext) User() User

User returns the info about the user of this request.

type Impl

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

An Impl is an initialized edge context implementation.

It implements ecinterface.Interface.

Please call Init function to initialize it.

func Init

func Init(cfg Config) *Impl

Init intializes an Impl.

It also calls ecinterface.Set to store the implementation created globally.

func (*Impl) ContextToHeader

func (impl *Impl) ContextToHeader(ctx context.Context) (header string, ok bool)

ContextToHeader implements ecinterface.Interface.

func (*Impl) HeaderToContext

func (impl *Impl) HeaderToContext(ctx context.Context, header string) (context.Context, error)

HeaderToContext implements ecinterface.Interface.

func (*Impl) ValidateToken

func (impl *Impl) ValidateToken(token string) (*AuthenticationToken, error)

ValidateToken parses and validates a jwt token, and return the decoded AuthenticationToken.

type NewArgs

type NewArgs struct {
	// If LoID is non-empty, it must have prefix of LoIDPrefix ("t2_").
	LoID          string
	LoIDCreatedAt time.Time

	SessionID string

	DeviceID string

	AuthToken string

	OriginServiceName string

	CountryCode string

	RequestID string

	LocaleCode string
}

NewArgs are the args for New function.

All fields are optional.

type OAuthClient

type OAuthClient AuthenticationToken

An OAuthClient wrapps AuthenticationToken and provides info about a client using OAuth2.

func (OAuthClient) ID

func (o OAuthClient) ID() string

ID returns the OAuth client id.

func (OAuthClient) IsType

func (o OAuthClient) IsType(types ...string) bool

IsType checks if the given OAuth client matches any of the given types.

When checking the type of the current OAuthClient, you should check that the type "is" one of the allowed types, rather than checking that it "is not" a disallowed type.

For example, use:

if client.IsType("third_party")

Instead of:

if !client.IsType("first_party")

func (OAuthClient) UpdateExperimentEvent

func (o OAuthClient) UpdateExperimentEvent(ee *experiments.ExperimentEvent)

UpdateExperimentEvent updates the passed in experiment event with oauth client info.

It always updates OAuthClientID field and never touches other fields.

type OriginService

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

OriginService holds metadata about the origin of the request.

func (OriginService) Name

func (os OriginService) Name() string

Name returns the name of the service that serves as the origin of the request.

type Service

type Service AuthenticationToken

A Service wraps AuthenticationToken and provides info about an authenticated service talking to us.

func (Service) Name

func (s Service) Name() (name string, ok bool)

Name returns the name of the service.

If it's not coming from an authenticated service, ("", false) will be returned.

type User

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

An User wraps *EdgeRequestContext and provides info about a logged in or logged our user.

func (User) CookieCreatedAt

func (u User) CookieCreatedAt() (ts time.Time, ok bool)

CookieCreatedAt returns the time the cookie was created.

func (User) HasRole

func (u User) HasRole(role string) bool

HasRole returns true if the user has the specific role.

func (User) ID

func (u User) ID() (id string, ok bool)

ID returns the authenticated account id of the user.

ok will be false if the user is not logged in.

func (User) IsLoggedIn

func (u User) IsLoggedIn() bool

IsLoggedIn returns true if the user is logged in.

func (User) LoID

func (u User) LoID() (loid string, ok bool)

LoID returns the LoID of this user.

func (User) Roles

func (u User) Roles() []string

Roles returns the roles the user has.

func (User) UpdateExperimentEvent

func (u User) UpdateExperimentEvent(ee *experiments.ExperimentEvent)

UpdateExperimentEvent updates the passed in experiment event with user info.

It always updates UserID, LoggedIn, and CookieCreatedAt fields and never touches other fields.

func (User) VariantInputs

func (u User) VariantInputs() map[string]interface{}

VariantInputs returns the map containing the user related fields that should be used in experiments.Variant call.

Jump to

Keyboard shortcuts

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