DocsHTTP ServerReferenceMiddleware and auth

Middleware and auth

AuthMiddleware, SlogMiddleware, the claims and identity helpers, and the Authorizer contract.

Two middlewares ship with the package. AuthMiddleware turns a Bearer token into request-context identity, and SlogMiddleware logs each request. Both take the local Logger interface, satisfied structurally by github.com/toaweme/log.

AuthMiddleware

func AuthMiddleware(extract ClaimsExtractor, logger Logger) func(http.Handler) http.Handler

Extracts the Bearer token, runs extract to parse it into Claims, injects the org, user, and scopes into the request context, and aborts with HTTP 401 on a missing or invalid header or an extractor failure.

type ClaimsExtractor func(token string) (*Claims, error)

Parses a raw Bearer token into claims. Return a non-nil error to reject the request with a 401.

type Claims struct {
	OrgID	string
	UserID	string
	Scopes	[]string
}

Identity context

The middleware stores identity on the request context. Read it back with the FromContext readers, or set it directly with the ContextWith helpers.

func OrgIDFromContext(ctx context.Context) (string, bool)
func UserIDFromContext(ctx context.Context) (string, bool)
func ScopesFromContext(ctx context.Context) []string
func ContextWithOrgID(ctx context.Context, orgID string) context.Context
func ContextWithUserID(ctx context.Context, userID string) context.Context
func ContextWithScopes(ctx context.Context, scopes []string) context.Context

Authorizing

Authorizer is the interface called before a privileged operation. Its single Authorize(ctx, action, resourceID) method returns nil to allow, ErrUnauthorized to deny, or any other error for an infrastructure failure. It reads identity from the context the middleware populated.

type Action string

The action is one of ActionRead, ActionWrite, ActionDelete, or ActionAdmin.

SlogMiddleware

func SlogMiddleware(cfg SlogConfig, logger Logger) func(http.Handler) http.Handler

Logs method, url, duration, and status for every request. Opt in to capturing headers and bodies for local debugging through the config.

type SlogConfig struct {
	// LogRequestBody captures and logs the request body.
	LogRequestBody	bool
	// LogResponseBody captures and logs the response body.
	LogResponseBody	bool
	// LogRequestHeaders logs incoming request headers.
	LogRequestHeaders	bool
	// LogResponseHeaders logs outgoing response headers (captured at end of request).
	LogResponseHeaders	bool
	// MaxBodyBytes caps how much of each body is captured. 0 means no cap.
	MaxBodyBytes	int
}

Body and header capture are off by default. MaxBodyBytes caps how much of each body is captured, where 0 means no cap.