gatewayx

package
v0.2.2 Latest Latest
Warning

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

Go to latest
Published: Jul 3, 2026 License: MIT Imports: 26 Imported by: 0

Documentation

Overview

Package gatewayx provides Gateway/BFF building blocks on top of Kernel's existing transportx/http package.

The route registry is a small go-zero-inspired target for generated code: a future kernel api generator can emit []Route and []Service values instead of making business services register routes manually in main.go.

Index

Constants

View Source
const DefaultSessionCookie = "AISP_SESSION"

Variables

This section is empty.

Functions

func ClearSessionCookie

func ClearSessionCookie(w http.ResponseWriter, name string, secure bool)

ClearSessionCookie clears the browser session cookie.

func GRPCClientContextFromDispatch added in v0.1.16

func GRPCClientContextFromDispatch(parent context.Context, req DispatchRequest, match RouteMatch) context.Context

GRPCClientContextFromDispatch copies Gateway request headers into outgoing gRPC metadata before calling a generated upstream client. Real backend gRPC servers then reconstruct Kernel transport context from incoming metadata.

func GRPCServerContextFromDispatch added in v0.1.16

func GRPCServerContextFromDispatch(parent context.Context, req DispatchRequest, match RouteMatch) context.Context

GRPCServerContextFromDispatch builds the downstream server context used by generated in-process invokers. It preserves authorization, request id and tracing headers so the backend Kernel server chain performs authoritative authn/authz/audit exactly as a real gRPC call would.

func GRPCServerContextFromIncomingMetadata added in v0.1.16

func GRPCServerContextFromIncomingMetadata(parent context.Context, operation string) context.Context

GRPCServerContextFromIncomingMetadata reconstructs Kernel's transport context from incoming gRPC metadata. Lightweight/generated validation servers can use this when they do not run through Kernel's managed transportx/grpc.Server.

func InternalJWTHTTPMiddleware

func InternalJWTHTTPMiddleware(jwt *InternalJWT, audience string) httpx.FilterFunc

InternalJWTHTTPMiddleware verifies Gateway-signed internal JWTs on internal HTTP endpoints and injects the actor into authn context. It is intended for backend services that accept Gateway -> service HTTP calls during migration.

func InternalJWTStreamClientInterceptor

func InternalJWTStreamClientInterceptor(jwt *InternalJWT, audience string) grpc.StreamClientInterceptor

InternalJWTStreamClientInterceptor is the streaming counterpart of InternalJWTUnaryClientInterceptor.

func InternalJWTStreamServerInterceptor

func InternalJWTStreamServerInterceptor(jwt *InternalJWT, audience string) grpc.StreamServerInterceptor

InternalJWTStreamServerInterceptor verifies Gateway-signed internal JWTs for backend streaming gRPC services.

func InternalJWTUnaryClientInterceptor

func InternalJWTUnaryClientInterceptor(jwt *InternalJWT, audience string) grpc.UnaryClientInterceptor

InternalJWTUnaryClientInterceptor injects a Gateway-signed internal JWT into outgoing gRPC calls. Use it for Gateway/BFF -> internal service calls when the backend service should trust the gateway rather than browser cookies.

func InternalJWTUnaryServerInterceptor

func InternalJWTUnaryServerInterceptor(jwt *InternalJWT, audience string) grpc.UnaryServerInterceptor

InternalJWTUnaryServerInterceptor verifies Gateway-signed internal JWTs for backend gRPC services.

func NewReverseProxy

func NewReverseProxy(conf ProxyConfig) (http.Handler, error)

NewReverseProxy creates an HTTP reverse proxy with optional internal JWT injection. BFF endpoints should usually call RPC clients directly; this is for pass-through routes such as file downloads or legacy migration windows.

func NewSessionID

func NewSessionID() (string, error)

NewSessionID returns a URL-safe opaque session id.

func RegisterRoutes

func RegisterRoutes(router *httpx.Router, routes ...Route) error

RegisterRoutes registers routes on router.

func RegisterServices

func RegisterServices(parent *httpx.Router, services ...Service) error

RegisterServices registers route groups under parent. It keeps transportx/http untouched while giving services a generated-code-friendly entry point.

func SessionMiddleware

func SessionMiddleware(conf SessionConfig) httpx.FilterFunc

SessionMiddleware loads a server-side session and injects authn.Principal into request context. Set Required=false for routes that can be anonymous.

func SetSessionCookie

func SetSessionCookie(w http.ResponseWriter, name string, id string, expires time.Time, secure bool)

SetSessionCookie writes the browser session cookie.

Types

type AuthnMode added in v0.1.16

type AuthnMode string

AuthnMode describes how the gateway treats authentication at the edge. Resource-level authorization remains the downstream service's responsibility.

const (
	AuthnModeNone       AuthnMode = "none"
	AuthnModePassive    AuthnMode = "passive"
	AuthnModeVerifyJWT  AuthnMode = "verify_jwt"
	AuthnModeIntrospect AuthnMode = "introspect"
)

type BindFunc added in v0.1.16

type BindFunc[Req any] func(DispatchRequest, RouteMatch) (Req, error)

BindFunc converts a matched Gateway request into a strongly typed upstream request. Generated code should own this binding so business handlers do not parse HTTP paths, query strings or bodies by hand.

type DispatchRequest added in v0.1.16

type DispatchRequest struct {
	Method  string
	Path    string
	Headers map[string]string
	Body    any
}

DispatchRequest is a transport-neutral request used by validation tests and future Gateway proxy implementations. Real HTTP handlers should adapt to this shape after route matching.

type DispatchResponse added in v0.1.16

type DispatchResponse struct {
	Status  int
	Headers map[string]string
	Body    any
}

DispatchResponse is a transport-neutral response from an upstream service.

type Dispatcher added in v0.1.16

type Dispatcher struct {
	Registry RouteRegistry
	Hosts    StaticHosts
	Invoker  UpstreamInvoker
}

Dispatcher combines route registry, matcher snapshot, boundary authn policy and upstream invocation.

func NewDispatcher added in v0.1.16

func NewDispatcher(registry RouteRegistry, hosts StaticHosts, invoker UpstreamInvoker) Dispatcher

func (Dispatcher) Dispatch added in v0.1.16

type EtcdRegistry added in v0.1.16

type EtcdRegistry struct {
	Store  KVStore
	Prefix string
}

EtcdRegistry stores manifests in an etcd-shaped KV store. The type does not import clientv3 directly so offline builds and unit tests stay lightweight.

func NewEtcdRegistry added in v0.1.16

func NewEtcdRegistry(store KVStore, prefix string) *EtcdRegistry

func (*EtcdRegistry) ListRoutes added in v0.1.16

func (r *EtcdRegistry) ListRoutes() []GatewayRoute

func (*EtcdRegistry) RegisterManifest added in v0.1.16

func (r *EtcdRegistry) RegisterManifest(manifest Manifest) error

type GatewayPolicy added in v0.1.16

type GatewayPolicy struct {
	Exposure             accessv1.Exposure
	AuthnMode            AuthnMode
	ForwardAuthorization bool
	Timeout              time.Duration

	// Profiles is an optional publication profile list such as public, internal,
	// or ops. Empty means deployment-time filters derive behavior from Exposure.
	Profiles []string

	// Tags are optional governance labels such as skill, admin, debug, dtm.
	Tags []string
}

GatewayPolicy is the boundary-governance slice of a route policy. It must not contain business resource authorization details; those stay in the service access resolver and authz provider.

func (GatewayPolicy) EffectiveAuthnMode added in v0.1.16

func (p GatewayPolicy) EffectiveAuthnMode() AuthnMode

EffectiveAuthnMode returns the explicit mode or derives a safe default from exposure. MVP gateway deployments should use passive token relay by default.

type GatewayRoute added in v0.1.16

type GatewayRoute struct {
	ID       string
	Method   string
	Path     string
	Upstream UpstreamRef
	Gateway  GatewayPolicy
}

GatewayRoute is generated from google.api.http + aisphere.access.v1.policy.

type HandlerFunc

type HandlerFunc = httpx.HandlerFunc

HandlerFunc is the Kernel HTTP business handler.

type InternalClaims

type InternalClaims struct {
	Issuer          string          `json:"iss"`
	Audience        string          `json:"aud"`
	Subject         string          `json:"sub"`
	Actor           authn.Principal `json:"actor"`
	RequestID       string          `json:"request_id,omitempty"`
	AuthzDecisionID string          `json:"authz_decision_id,omitempty"`
	IssuedAt        int64           `json:"iat"`
	ExpiresAt       int64           `json:"exp"`
	JWTID           string          `json:"jti"`
}

InternalClaims is the signed Gateway-to-service identity envelope.

type InternalJWT

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

InternalJWT signs and verifies compact HS256 JWTs without adding a new public dependency. It is meant for Gateway -> internal service calls; external OIDC tokens should still be verified by the IdP/OIDC adapter.

func NewInternalJWT

func NewInternalJWT(issuer string, secret []byte, ttl time.Duration) *InternalJWT

NewInternalJWT creates a signer/verifier.

func (*InternalJWT) Sign

func (j *InternalJWT) Sign(audience string, actor authn.Principal, requestID, decisionID string, now time.Time) (string, error)

Sign signs claims for audience. Subject defaults to issuer when empty.

func (*InternalJWT) Verify

func (j *InternalJWT) Verify(token, audience string, now time.Time) (InternalClaims, error)

Verify verifies a token and expected audience.

type InvokerRegistry added in v0.1.16

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

InvokerRegistry routes matched Gateway operations to generated operation invokers. It implements UpstreamInvoker so Dispatcher can use it directly.

func NewInvokerRegistry added in v0.1.16

func NewInvokerRegistry() *InvokerRegistry

func (*InvokerRegistry) Invoke added in v0.1.16

func (r *InvokerRegistry) Invoke(ctx context.Context, match RouteMatch, req DispatchRequest, target string) (DispatchResponse, error)

func (*InvokerRegistry) Register added in v0.1.16

func (r *InvokerRegistry) Register(operation string, invoker OperationInvoker) error

type KVStore added in v0.1.16

type KVStore interface {
	Put(ctx context.Context, key string, value []byte) error
	DeletePrefix(ctx context.Context, prefix string) error
	ListPrefix(ctx context.Context, prefix string) (map[string][]byte, error)
}

KVStore is the small etcd-like contract Gateway needs. Production should adapt this to clientv3 under gatewayx/etcd or an etcdx.Store; tests can use MemoryKVStore. Kernel business packages must not use raw etcd clients.

type Manifest added in v0.1.16

type Manifest struct {
	Service   string
	Namespace string
	Routes    []GatewayRoute
}

Manifest is the route artifact a service publishes into the route registry.

func FilterManifest added in v0.2.2

func FilterManifest(manifest Manifest, filter RouteFilter) Manifest

type Matcher added in v0.1.16

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

Matcher resolves HTTP method/path to a GatewayRoute. It intentionally keeps a small surface so an etcd route controller can swap snapshots atomically.

func NewMatcher added in v0.1.16

func NewMatcher(routes []GatewayRoute) Matcher

func (Matcher) Match added in v0.1.16

func (m Matcher) Match(method, path string) (RouteMatch, bool)

type MemoryKVStore added in v0.1.16

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

MemoryKVStore is an in-memory KVStore for tests. It mirrors etcd prefix semantics closely enough for Gateway route registry validation.

func NewMemoryKVStore added in v0.1.16

func NewMemoryKVStore() *MemoryKVStore

func (*MemoryKVStore) DeletePrefix added in v0.1.16

func (s *MemoryKVStore) DeletePrefix(ctx context.Context, prefix string) error

func (*MemoryKVStore) ListPrefix added in v0.1.16

func (s *MemoryKVStore) ListPrefix(ctx context.Context, prefix string) (map[string][]byte, error)

func (*MemoryKVStore) Put added in v0.1.16

func (s *MemoryKVStore) Put(ctx context.Context, key string, value []byte) error

type MemoryRegistry added in v0.1.16

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

MemoryRegistry is a local/demo route registry. It mirrors the etcd registry shape without introducing an external dependency into unit tests.

func NewMemoryRegistry added in v0.1.16

func NewMemoryRegistry() *MemoryRegistry

func (*MemoryRegistry) ListRoutes added in v0.1.16

func (r *MemoryRegistry) ListRoutes() []GatewayRoute

func (*MemoryRegistry) RegisterManifest added in v0.1.16

func (r *MemoryRegistry) RegisterManifest(manifest Manifest) error

type MemorySessionStore

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

MemorySessionStore is a development and test session store. Production gateways should implement SessionStore with Redis.

func NewMemorySessionStore

func NewMemorySessionStore() *MemorySessionStore

NewMemorySessionStore creates an in-memory store.

func (*MemorySessionStore) Delete

func (s *MemorySessionStore) Delete(_ context.Context, id string) error

func (*MemorySessionStore) Get

func (*MemorySessionStore) Set

func (s *MemorySessionStore) Set(_ context.Context, session Session) error

type OperationInvoker added in v0.1.16

type OperationInvoker interface {
	InvokeOperation(ctx context.Context, match RouteMatch, req DispatchRequest) (DispatchResponse, error)
}

OperationInvoker invokes one generated upstream operation.

func GRPCUnaryInvoker added in v0.1.16

func GRPCUnaryInvoker[Req any, Reply any](bind BindFunc[Req], call UnaryRPC[Req, Reply], opts ...grpc.CallOption) OperationInvoker

GRPCUnaryInvoker adapts a generated bind function and a generated gRPC client method into a Gateway upstream operation invoker.

func UnaryInvoker added in v0.1.16

func UnaryInvoker[Req any, Reply any](bind BindFunc[Req], call UnaryHandler[Req, Reply]) OperationInvoker

UnaryInvoker adapts a generated bind function and an in-process service call into a Gateway upstream operation invoker.

type ProxyConfig

type ProxyConfig struct {
	Target      string
	StripPrefix string
	AddPrefix   string
	Audience    string
	JWT         *InternalJWT
	Timeout     time.Duration
}

ProxyConfig configures a lightweight reverse proxy for Gateway routes that should remain HTTP-to-HTTP instead of BFF logic -> RPC calls.

type Route

type Route struct {
	Method  string
	Path    string
	Handler HandlerFunc
	Filters []httpx.FilterFunc
	Name    string
}

Route describes a single external Gateway/BFF route.

type RouteFilter added in v0.2.2

type RouteFilter struct {
	IncludeExposures []accessv1.Exposure
	ExcludeExposures []accessv1.Exposure

	IncludeProfiles []string
	ExcludeProfiles []string
	IncludeTags     []string
	ExcludeTags     []string

	IncludeServices  []string
	ExcludeServices  []string
	IncludePathGlobs []string
	ExcludePathGlobs []string
	IncludeIDs       []string
	ExcludeIDs       []string
}

RouteFilter decides which generated routes are published to a concrete gateway profile. It is intentionally applied at registration time, not only at runtime, so public route registries do not leak internal/debug routes.

func InternalRouteFilter added in v0.2.2

func InternalRouteFilter() RouteFilter

InternalRouteFilter publishes internal service-to-service APIs. It still excludes debug/ops-only endpoints by path because those should normally be served through an ops plane or direct probe, not service API dispatch.

func OpsRouteFilter added in v0.2.2

func OpsRouteFilter() RouteFilter

OpsRouteFilter is for operator-only endpoints. Keep it opt-in; services should still avoid putting dangerous repair/migration/debug APIs in ordinary product manifests.

func PublicRouteFilter added in v0.2.2

func PublicRouteFilter() RouteFilter

PublicRouteFilter publishes normal product APIs to a public gateway. INTERNAL and SYSTEM routes are deliberately excluded even if a service generated them.

func (RouteFilter) Allow added in v0.2.2

func (f RouteFilter) Allow(route GatewayRoute) bool

type RouteMatch added in v0.1.16

type RouteMatch struct {
	Route  GatewayRoute
	Params map[string]string
}

RouteMatch is the result of matching an external request to a generated route.

type RouteRegistry added in v0.1.16

type RouteRegistry interface {
	RegisterManifest(manifest Manifest) error
	ListRoutes() []GatewayRoute
}

RouteRegistry is the provider-neutral gateway route registry contract. Production implementation should be etcd-backed; tests and local demos use MemoryRegistry.

type Service

type Service struct {
	Name    string
	Prefix  string
	Filters []httpx.FilterFunc
	Routes  []Route
}

Service groups routes under a common prefix and filter chain. It is the runtime shape that a go-zero-like .api generator should target.

type Session

type Session struct {
	ID           string
	Principal    authn.Principal
	AccessToken  string
	RefreshToken string
	IDToken      string
	CSRFToken    string
	CreatedAt    time.Time
	LastSeenAt   time.Time
	ExpiresAt    time.Time
	Attributes   map[string]any
}

Session is a browser/BFF login session. Access and refresh tokens are stored server-side so the browser only receives an opaque HttpOnly cookie.

func (Session) Expired

func (s Session) Expired(now time.Time) bool

Expired reports whether the session is expired at now.

type SessionConfig

type SessionConfig struct {
	Store      SessionStore
	CookieName string
	Required   bool
	Touch      bool
}

SessionConfig configures SessionMiddleware.

type SessionStore

type SessionStore interface {
	Get(ctx context.Context, id string) (Session, error)
	Set(ctx context.Context, session Session) error
	Delete(ctx context.Context, id string) error
}

SessionStore persists sessions.

type StaticHosts added in v0.1.16

type StaticHosts map[string]string

StaticHosts is a validation/local substitute for Kubernetes Service DNS. In production, Gateway should resolve UpstreamRef through Kubernetes Service DNS or EndpointSlice, not through a custom registry.

func (StaticHosts) Resolve added in v0.1.16

func (h StaticHosts) Resolve(upstream UpstreamRef) (string, error)

type UnaryHandler added in v0.1.16

type UnaryHandler[Req any, Reply any] func(context.Context, Req) (Reply, error)

UnaryHandler is the in-process shape used by validation tests and local demos. It mirrors generated gRPC unary clients without requiring a network listener.

type UnaryRPC added in v0.1.16

type UnaryRPC[Req any, Reply any] func(context.Context, Req, ...grpc.CallOption) (Reply, error)

UnaryRPC is the generated gRPC client method shape, for example SkillServiceClient.GetSkill(ctx, req, opts...).

type UpstreamInvoker added in v0.1.16

type UpstreamInvoker interface {
	Invoke(ctx context.Context, match RouteMatch, req DispatchRequest, target string) (DispatchResponse, error)
}

UpstreamInvoker invokes the selected upstream. HTTP reverse proxy, gRPC transcoding and in-memory validation dispatchers can all implement it.

type UpstreamRef added in v0.1.16

type UpstreamRef struct {
	Service   string
	Namespace string
	Port      int
	Protocol  string
	Operation string
}

UpstreamRef points to a Kubernetes Service in production. Validation tests can resolve it through StaticHosts, mirroring /etc/hosts or local docker-compose.

func (UpstreamRef) Key added in v0.1.16

func (u UpstreamRef) Key() string

Jump to

Keyboard shortcuts

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