identity

package
v0.40.416 Latest Latest
Warning

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

Go to latest
Published: Sep 21, 2026 License: MIT Imports: 21 Imported by: 2 modules, 1 package

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package identity extracts the caller's identity (role, subject, tenant, claims, auth method) and connection details (client IP, user agent, target) from HTTP requests or gRPC contexts and exposes them through the request context.

Servers install NewContextHandler (HTTP) or NewAuthUnaryInterceptor / NewStreamServerInterceptor (gRPC) with an identity mapper; handlers then read the result:

h := identity.NewContextHandler(next, myMapper) // ProviderFromRequest

func handler(w http.ResponseWriter, r *http.Request) {
	rc := identity.FromRequest(r)
	role := rc.Identity().Role()
	ip := rc.ClientIP()
}

When no identity is present a guest identity (role "guest") is returned, never nil. GuestIdentityMapper / GuestIdentityForContext are the default mappers. ClientIPFromRequest trusts X-Forwarded-For and X-Real-Ip headers, so it should only be relied on behind a proxy that sets them.

Index

Constants

View Source
const GuestRoleName = "guest"

GuestRoleName is default role name for guest

Variables

This section is empty.

Functions

func AddToContext

func AddToContext(ctx context.Context, rq *RequestContext) context.Context

AddToContext returns a child context carrying rq as the request context, as later returned by FromContext.

func BasicAuthFromRequest

func BasicAuthFromRequest(r *http.Request) (id string, secret string, err error)

BasicAuthFromRequest parses the "Authorization: Basic base64(id:secret)" header. It returns empty values and a nil error when the header is absent or uses another scheme (callers must check id), an httperror.InvalidRequest when the base64 is malformed, and an empty secret when no ":" is present. The scheme prefix is matched case-sensitively.

func ClientIPFromGRPC added in v0.36.373

func ClientIPFromGRPC(ctx context.Context) string

ClientIPFromGRPC returns the client address for a gRPC call: the raw value of the x-forwarded-for or x-real-ip incoming metadata when present, otherwise the peer address including port, or "" when unknown.

func ClientIPFromRequest

func ClientIPFromRequest(r *http.Request) string

ClientIPFromRequest returns the client's IP address as a string. When the X-Real-Ip and X-Forwarded-For headers are both absent it is the host part of r.RemoteAddr (or the local IP if that is empty). Otherwise it is the first globally routable address in X-Forwarded-For, falling back to X-Real-Ip (which may be ""). The headers are trusted as sent, so the result is only reliable behind a proxy that overwrites them.

func NewAuthUnaryInterceptor

func NewAuthUnaryInterceptor(identityMapper ProviderFromContext) grpc.UnaryServerInterceptor

NewAuthUnaryInterceptor returns a grpc.UnaryServerInterceptor that calls identityMapper with the full method name and stores the RequestContext (identity, client IP from x-forwarded-for/x-real-ip metadata or the peer address, user agent) in the context. A mapper error fails the call with codes.PermissionDenied. Panics in the handler are recovered, logged and returned as an "unhandled exception" error.

func NewContextHandler

func NewContextHandler(delegate http.Handler, identityMapper ProviderFromRequest) http.Handler

NewContextHandler returns middleware that calls identityMapper for each request and stores the resulting RequestContext (identity, client IP, path, user agent) in the request context for later handlers. A mapper error is answered with a JSON 401 unauthorized response and the request is not forwarded. For non-guest identities tenant/user/email/role are also added to the xlog context fields. A RequestContext already present in the context (for example from WithTestIdentity) is left untouched.

func NewStreamServerInterceptor added in v0.33.319

func NewStreamServerInterceptor(identityMapper ProviderFromContext) grpc.StreamServerInterceptor

NewStreamServerInterceptor returns the streaming counterpart of NewAuthUnaryInterceptor; the stream is wrapped with streamctx.WithContext so the handler sees the enriched context. It does not recover panics.

func WithTestIdentity

func WithTestIdentity(r *http.Request, identity Identity) *http.Request

WithTestIdentity returns a copy of r whose context carries the given identity (with the local IP as client IP), for use in unit tests.

Types

type AuthMethod added in v0.37.390

type AuthMethod int

AuthMethod identifies how the caller was authenticated.

const (
	// MethodNone means the caller was not authenticated (guest).
	MethodNone AuthMethod = iota
	// MethodCertificate means a TLS client certificate was used.
	MethodCertificate
	// MethodAWS means AWS request signing was used.
	MethodAWS
	// MethodDPoP means a DPoP-bound access token was used.
	MethodDPoP
	// MethodJWT means a bearer JWT was used.
	MethodJWT
	// MethodJWTCookie means a JWT carried in a cookie was used.
	MethodJWTCookie
)

Authentication methods reported by Identity.AuthMethod.

func (AuthMethod) String added in v0.37.390

func (m AuthMethod) String() string

String returns the method name ("Certificate", "AWS", "DPoP", "JWT", "JWTCookie"), or "None" for MethodNone and unknown values.

type Context

type Context interface {
	// Identity returns the caller's identity; never nil (guest when unknown).
	Identity() Identity
	// ClientIP returns the client IP as determined by ClientIPFromRequest or
	// ClientIPFromGRPC, or "".
	ClientIP() string
	// Target of the request, e.g. HTTP path or gRPC method
	Target() string
	// UserAgent returns the User-Agent header (or user-agent / x-user-agent
	// gRPC metadata), or "".
	UserAgent() string
}

Context is the read-only view of RequestContext.

type Identity

type Identity interface {
	// String returns the identity as a single string value
	// in the format of {tenant/}subject{:role}
	String() string
	// Role returns the role used for authorization (see restserver/authz).
	Role() string
	// Subject returns the caller's subject: a certificate CommonName, a JWT
	// "email" claim, or similar.
	Subject() string
	// Tenant returns the tenant the identity belongs to, or "".
	Tenant() string
	// Claims returns a copy of the application-specific claims.
	Claims() jwt.MapClaims
	// AccessToken returns the raw access token presented, or "".
	AccessToken() string
	// TokenType returns the token type (e.g. "Bearer", "DPoP"), or "".
	TokenType() string
	// AuthMethod returns how the caller was authenticated.
	AuthMethod() AuthMethod
}

Identity contains information about the identity of an API caller. Implementations are immutable values; create them with NewIdentity.

func GuestIdentityForContext

func GuestIdentityForContext(_ context.Context, _ string) (Identity, error)

GuestIdentityForContext is a ProviderFromContext that always returns the guest role with an empty subject.

func GuestIdentityMapper

func GuestIdentityMapper(r *http.Request) (Identity, error)

GuestIdentityMapper is a ProviderFromRequest that always returns the guest role, with the subject set to the TLS client certificate CommonName when one was presented, or "unknown". It is restserver's default mapper.

func NewIdentity

func NewIdentity(role, subject, tenant string, claims map[string]any, accessToken, tokenType string, authMethod AuthMethod) Identity

NewIdentity returns an immutable Identity with the given attributes. claims may be nil; when provided they are copied.

type ProviderFromContext

type ProviderFromContext func(ctx context.Context, uri string) (Identity, error)

ProviderFromContext maps a gRPC request context and full method name to the caller's Identity. It is used by the gRPC interceptors; returning an error rejects the call with codes.PermissionDenied, returning a nil Identity yields the guest identity.

type ProviderFromRequest

type ProviderFromRequest func(*http.Request) (Identity, error)

ProviderFromRequest maps an HTTP request to the caller's Identity. It is used by NewContextHandler; returning an error rejects the request with 401, returning a nil Identity yields the guest identity.

type RequestContext

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

RequestContext is the per-request value stored in the context by NewContextHandler and the gRPC interceptors: the caller's Identity, client IP, target (HTTP path or gRPC method) and user agent. It implements Context. Correlation IDs live in xhttp/correlation, not here.

func FromContext

func FromContext(ctx context.Context) *RequestContext

FromContext returns the RequestContext stored in ctx. When none exists it returns a new RequestContext with the guest identity, never nil.

func FromRequest

func FromRequest(r *http.Request) *RequestContext

FromRequest returns the RequestContext for r (guest when none was stored), filling in target, client IP and user agent from the request when they are empty. Note that it updates the stored RequestContext in place.

func NewRequestContext

func NewRequestContext(id Identity, target string) *RequestContext

NewRequestContext creates a request context with a specific identity and target; client IP and user agent are left empty. Store it with AddToContext.

func (*RequestContext) ClientIP

func (c *RequestContext) ClientIP() string

ClientIP returns the request's client IP, or "" when unknown.

func (*RequestContext) Identity

func (c *RequestContext) Identity() Identity

Identity returns the request's identity; never nil.

func (*RequestContext) Target added in v0.36.373

func (c *RequestContext) Target() string

Target returns the request's target: the HTTP path or gRPC full method.

func (*RequestContext) UserAgent added in v0.36.373

func (c *RequestContext) UserAgent() string

UserAgent returns the request's user agent, or "".

Jump to

Keyboard shortcuts

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