edgeauth

package
v0.3.1 Latest Latest
Warning

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

Go to latest
Published: Nov 18, 2026 License: MIT Imports: 16 Imported by: 1 module, 0 packages

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 edgeauth verifies the identity guard hands every authenticated request upstream, so an app knows who is calling without running OIDC itself.

Guard is the platform's only OIDC relying party. It owns browser sessions, validates Zitadel bearer tokens for native clients, and forwards each authenticated request with one short-lived signed identity JWT in the x-bastion-identity header (Header). Envoy strips a client's copy of that header and guard overwrites it, but an app still never trusts it as a plain header: it verifies the token, and keeps its own domain authorization on top of the identity it gets.

A token is accepted only when every one of these holds:

  • the JOSE header is alg ES256 and typ bastion-id+jwt, with a kid that is in guard's JWKS;
  • the ES256 signature verifies against that key;
  • iss is "bastion" and aud is one of the hosts the app serves (Config.Audiences);
  • exp has not passed and iat is not in the future, both with a 10 s leeway for clock skew, and sub is set.

The JWKS is fetched lazily, on the first token, never in New, so an app boots and serves anonymous traffic while guard is unreachable. It is cached for 5 minutes; a token whose kid is not in the cache refetches it at most once every 30 seconds, and concurrent requests share one fetch. Guard publishes a new signing key at least 10 minutes before it signs with it, so a rotation never meets a verifier with a stale cache.

Verify tells two failures apart. ErrInvalid means the token is wrong (forged, expired, for another host, signed by an unknown key): Middleware answers 401 and logs it, because behind guard it can only be an attack or a key mistake. ErrUnavailable means the token could not be checked because the JWKS could not be fetched: Middleware answers 503, and the request may succeed on a retry. A request without the header is anonymous: Middleware passes it on with no identity in the context, and RequireIdentity or RequireRole refuse it on the handlers that need one. Guard fails closed on routes with an auth rule, and the app fails closed again on its protected handlers, so a request that slipped past guard is never treated as signed in.

The edgeauthtest package mints identities for an app's own tests, and testdata/vectors.json holds conformance vectors that the Go verifier, the TypeScript verifier (@metsaapp/edgeauth, ts/edgeauth in this repository) and guard's signer all run.

Index

Constants

View Source
const (
	// SourceSession is a browser session guard holds.
	SourceSession = "session"
	// SourceBearer is a Zitadel access token guard validated.
	SourceBearer = "bearer"
)

Sources of an identity (Identity.Source).

View Source
const (
	// Header carries the identity JWT from guard to the app.
	Header = "x-bastion-identity"
	// Issuer is the iss of every identity JWT.
	Issuer = "bastion"
	// TokenType is the typ in the JOSE header of every identity JWT.
	TokenType = "bastion-id+jwt" //nolint:gosec // a media type, not a credential
	// DefaultJWKSURL is guard's in-cluster key endpoint.
	DefaultJWKSURL = "http://guard.guard-production.svc.cluster.local:8082/jwks.json"
)

The token's fixed values.

View Source
const Leeway = 10 * time.Second

Leeway is the clock skew tolerated on exp, iat and nbf, each way.

Variables

View Source
var (
	// ErrInvalid means the token is present but not acceptable: malformed,
	// forged, expired, for another host or signed by an unknown key.
	// Middleware answers 401.
	ErrInvalid = errors.New("edgeauth: invalid identity token")
	// ErrUnavailable means the token could not be checked because guard's
	// JWKS could not be fetched. Middleware answers 503.
	ErrUnavailable = errors.New("edgeauth: identity keys unavailable")
	// ErrConfig means New was given an unusable Config.
	ErrConfig = errors.New("edgeauth: invalid config")
)

Functions

func ContextWith

func ContextWith(ctx context.Context, id Identity) context.Context

ContextWith returns a copy of ctx carrying id. Middleware calls it for a verified token; a test calls it to run a handler as someone without minting a token.

func RequireIdentity

func RequireIdentity(next http.Handler) http.Handler

RequireIdentity refuses an anonymous request with 401. It goes inside Middleware, on the handlers that need a signed-in caller.

func RequireRole

func RequireRole(roles ...string) func(http.Handler) http.Handler

RequireRole refuses an anonymous request with 401 and a caller holding none of roles with 403. With no roles it is RequireIdentity.

Types

type Config

type Config struct {
	// JWKSURL is guard's JWKS. The default is the in-cluster endpoint; a
	// verifier outside the cluster uses
	// https://<host>/.well-known/bastion/jwks.json.
	JWKSURL string `env:"PLATFORM_KIT_EDGEAUTH_JWKS_URL" envDefault:"http://guard.guard-production.svc.cluster.local:8082/jwks.json"`
	// Audiences are the hosts this app serves (lower case, no port); a token
	// is accepted only for one of them. Required, comma-separated in the
	// environment.
	Audiences []string `env:"PLATFORM_KIT_EDGEAUTH_AUDIENCES"`
}

Config is what New needs. Apps read it from the environment with ConfigFromEnv, or embed it in their own env-parsed config.

func ConfigFromEnv

func ConfigFromEnv() (Config, error)

ConfigFromEnv reads Config from PLATFORM_KIT_EDGEAUTH_JWKS_URL and PLATFORM_KIT_EDGEAUTH_AUDIENCES.

type Identity

type Identity struct {
	// Subject is the Zitadel user id.
	Subject string
	// Email may be empty.
	Email         string
	EmailVerified bool
	// Name is the display name and may be empty.
	Name string
	// Roles are the role keys of the host's Zitadel project, sorted and
	// de-duplicated; empty, never nil, when the user has none.
	Roles []string
	// SessionID is an opaque session id, empty for a bearer.
	SessionID string
	// AuthTime is when the user logged in at Zitadel; zero when unknown.
	AuthTime time.Time
	// ClientID is the Zitadel client the session or bearer belongs to.
	ClientID string
	// Source is SourceSession or SourceBearer.
	Source string
}

Identity is the caller guard vouches for.

func FromContext

func FromContext(ctx context.Context) (Identity, bool)

FromContext returns the identity Middleware verified, and false for an anonymous request.

func (Identity) HasAnyRole

func (i Identity) HasAnyRole(roles ...string) bool

HasAnyRole reports whether the identity holds at least one of roles. It is false when roles is empty.

func (Identity) HasRole

func (i Identity) HasRole(role string) bool

HasRole reports whether the identity holds role.

type Option

type Option func(*options)

Option tunes New.

func WithClock

func WithClock(clock func() time.Time) Option

WithClock replaces time.Now for the token's time checks and the JWKS cache, for tests.

func WithHTTPClient

func WithHTTPClient(client *http.Client) Option

WithHTTPClient fetches the JWKS with client instead of a default client with a 5 s timeout.

func WithLogger

func WithLogger(logger *slog.Logger) Option

WithLogger is where Middleware logs refused tokens. Without it nothing is logged.

type Verifier

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

Verifier checks identity JWTs against guard's JWKS. It is safe for concurrent use; an app builds one at start and shares it.

func New

func New(cfg Config, opts ...Option) (*Verifier, error)

New builds a Verifier. It never contacts guard: the JWKS is fetched when the first token arrives.

func (*Verifier) Middleware

func (v *Verifier) Middleware(next http.Handler) http.Handler

Middleware verifies the identity header and puts the identity in the request's context (FromContext). A request without the header passes on anonymous. A token that is invalid is refused with 401 and logged; one that cannot be checked because guard's JWKS is unreachable is refused with 503. The responses are plain text and never echo the token.

With echo: e.Use(echo.WrapMiddleware(v.Middleware)).

func (*Verifier) Verify

func (v *Verifier) Verify(ctx context.Context, token string) (Identity, error)

Verify checks token and returns the identity it carries. The error wraps ErrInvalid or ErrUnavailable.

Directories

Path Synopsis
Package edgeauthtest mints identity JWTs for an app's tests, the way guard signs them, with a throwaway key served from an in-process JWKS:
Package edgeauthtest mints identity JWTs for an app's tests, the way guard signs them, with a throwaway key served from an in-process JWKS:
internal
vectorgen command
Command vectorgen writes the edgeauth conformance vectors:
Command vectorgen writes the edgeauth conformance vectors:
vectors
Package vectors builds the conformance vectors in edgeauth/testdata (vectors.json): a JWKS, a fixed "now", and tokens with the result every verifier must give for them.
Package vectors builds the conformance vectors in edgeauth/testdata (vectors.json): a JWKS, a fixed "now", and tokens with the result every verifier must give for them.

Jump to

Keyboard shortcuts

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