grpcactor

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Oct 4, 2026 License: MIT Imports: 16 Imported by: 0

README

go-grpc-actor 🐹

🧭 Carry the signed-in user and the act-as admin across gRPC service hops, trusted only from authenticated internal callers.

A request enters at the edge with a signed-in user. During act-as, an admin works as that user, and audit must still name the admin. A plain gRPC hop drops both. go-grpc-actor carries one Actor value through the context and gRPC metadata on every hop, and a receiving service accepts it only from a caller it has authenticated as an internal service.

✨ Highlights

  • 🔁 Survives every hop — the impersonator travels with the subject, so the third service sees the same admin the edge saw.
  • 🔒 Fail closed — a server trusts no caller until you say which ones; untrusted actor metadata is stripped or refused.
  • 🪪 mTLS trust built in — trust a peer by SPIFFE ID or DNS SAN, only with a verified client certificate.
  • 🧩 Pluggable trust — any TrustFunc, such as one backed by a verified workload token, with per-method allow-lists.
  • 🔢 go-apperr codes — refusals carry your own codes and the right gRPC status.
  • 🪶 Small — depends on gRPC and go-apperr only.

📦 Install

go get github.com/Bugs5382/go-grpc-actor

🚀 Usage

The edge authenticates the user, then puts the actor in the context. During act-as the real admin goes in Impersonator:

ctx = grpcactor.WithActor(ctx, grpcactor.Actor{
    Subject:      targetUserID, // authorization evaluates as this user
    Impersonator: adminUserID,  // empty when nobody is impersonating
})

Every service dials its internal peers with the client interceptors:

conn, err := grpc.NewClient(target,
    grpc.WithTransportCredentials(mtlsCreds),
    grpc.WithChainUnaryInterceptor(grpcactor.UnaryClientInterceptor()),
    grpc.WithChainStreamInterceptor(grpcactor.StreamClientInterceptor()),
)

Every internal service serves with the server interceptors and says whom it trusts:

opts := []grpcactor.ServerOption{
    grpcactor.WithTrust(grpcactor.TrustSPIFFEIDs(
        "spiffe://example.org/ns/apps/sa/gateway",
        "spiffe://example.org/ns/apps/sa/workflow",
    )),
    grpcactor.WithRejectUntrusted(),
}
srv := grpc.NewServer(
    grpc.Creds(mtlsServerCreds), // tls.RequireAndVerifyClientCert
    grpc.ChainUnaryInterceptor(grpcactor.UnaryServerInterceptor(opts...)),
    grpc.ChainStreamInterceptor(grpcactor.StreamServerInterceptor(opts...)),
)

Handlers read the actor, or require one:

a, err := grpcactor.Require(ctx, codeNoActor) // Unauthenticated, with your apperr code
audit.Record(a.RealUser(), a.Subject)

A handler that calls the next service with the context it was given forwards the actor with no code of its own.

🛡️ Trust model

  • 🚫 Nothing is trusted by default. TrustNone is the default, so a server that is not told whom to trust ignores every forwarded actor.
  • 🧹 Handlers never see the raw header. The actor key is removed from the incoming metadata on every call, trusted or not; FromContext is the only way to read it.
  • 🚪 Edge vs internal. From an untrusted caller the actor is dropped and the call is served without one. With WithRejectUntrusted the call is refused with PermissionDenied instead, and WithObserver reports it. Edge services that face clients strip; internal services reject.
  • 🪪 mTLS. TrustSPIFFEIDs trusts a client certificate with exactly one URI SAN equal to a listed SPIFFE ID; TrustDNSNames trusts a listed DNS SAN. Both refuse a certificate the TLS handshake did not verify, so the server must use tls.RequireAndVerifyClientCert.
  • 🎟️ Workload tokens. A service that authenticates callers with a projected service-account token writes a TrustFunc that reads the verified caller its auth interceptor put in the context, and installs this interceptor after that one. ForMethods and AnyOf turn it into a per-method allow-list.
  • ✍️ No signature, on purpose. Signing the actor with a shared key would add a shared secret between services and protect nothing the authenticated channel does not: the trusted caller is the one vouching for the actor, and an untrusted caller's actor is never read.
  • 🎭 No roles on the wire. The actor names people, not grants. Each service works out what the subject may do from its own data, so a forwarded actor can never widen a caller's authority.

📨 Wire format

One binary metadata key, x-grpc-actor-bin, holding one JSON object:

{"v":1,"sub":"user-1001","imp":"admin-7","ten":"tenant-1","sid":"sess-1"}

Empty fields are left out. One key keeps the actor atomic, so a subject and an impersonator can never come from two different senders. A server refuses, with InvalidArgument, an actor from a trusted caller that is not exactly one value, is over 4096 bytes, has an unknown version, has no subject, impersonates itself, or holds control characters or fields over 256 bytes.

❗ Errors

Sentinel gRPC status When
ErrNoActor Unauthenticated Require or WithRequireActor found no actor
ErrUntrustedCaller PermissionDenied an untrusted caller sent an actor, with WithRejectUntrusted
ErrInvalidActor InvalidArgument the actor is malformed

Require(ctx, code) and WithCodes(grpcactor.Codes{...}) attach your own go-apperr codes; apperr.Code(err) reads them back, and errors.Is still finds the sentinel.

🛠 Develop

task build    # go build ./...
task test     # go test ./...
task lint     # gofmt check + golangci-lint + yamllint
task license  # verify MIT headers (golic)

⚖️ License

MIT (c) 2026 Shane

Documentation

Overview

Package grpcactor carries the signed-in user, and during act-as the real admin behind them, across gRPC service hops, and trusts it only from authenticated internal callers.

The actor

An Actor names who a request is for. Subject is the effective user, the one authorization evaluates as. Impersonator is the admin acting as Subject, and is empty when nobody is impersonating; RealUser returns whichever person is actually at the keyboard, for audit. Tenant and Session ride along as they are. The edge sets the actor once, with WithActor, after it has authenticated the user; everything after that reads it with FromContext.

Hops

The client interceptors (UnaryClientInterceptor, StreamClientInterceptor) write the context actor to outgoing metadata under MetadataKey. The server interceptors (UnaryServerInterceptor, StreamServerInterceptor) read it back into the handler's context. A handler that calls the next service with the context it was given forwards the same actor, impersonator included, with no code of its own. Edge-set and forwarded actors are the same value in the same context key, so no hop can forget one half of it.

Only the context actor goes out. Actor metadata a caller wrote by hand is replaced, or removed when the context has no actor, so a system call that carries no user sends nothing.

Trust

A server accepts the actor only when its TrustFunc says the caller is an authenticated internal service allowed to forward one. The default is TrustNone: a server that is not told whom to trust trusts nobody. Actor metadata is always removed from the incoming metadata the handler sees, so a client-supplied header can never be read by mistake. From an untrusted caller it is dropped (the call is served without an actor) or, with WithRejectUntrusted, refused with PermissionDenied. Edge services that face clients strip; internal services reject, so an attempt is audited.

TrustSPIFFEIDs and TrustDNSNames trust an mTLS peer by its SPIFFE ID or a DNS SAN, and only when the handshake verified the client certificate. Services that authenticate callers with a workload token instead (a projected service-account token checked against the cluster's JWKS) write a TrustFunc that reads the verified caller from the context their auth interceptor fills, and install this package's interceptor after that one. ForMethods and AnyOf build per-method allow-lists, so only the callers that may pass an end-user actor to a method can do so.

The actor is not signed. A signature with a shared key would add a shared secret between services, and the actor's integrity already rests on the authenticated channel: the trusted caller is the one vouching for it, and an untrusted caller's actor is never read. An attacker who can impersonate a trusted workload could sign whatever it liked, too.

Errors

Refusals wrap ErrNoActor, ErrUntrustedCaller or ErrInvalidActor and convert to Unauthenticated, PermissionDenied and InvalidArgument gRPC statuses. Require and WithCodes attach the service's own go-apperr codes to them. WithObserver reports every decision for audit or logging.

Example

An internal service trusts actor metadata only from the services that call it with a verified mTLS client certificate, and forwards the actor on every call it makes.

package main

import (
	grpcactor "github.com/Bugs5382/go-grpc-actor"
	"google.golang.org/grpc"
)

func main() {
	trust := grpcactor.TrustSPIFFEIDs(
		"spiffe://example.org/ns/apps/sa/gateway",
		"spiffe://example.org/ns/apps/sa/workflow",
	)
	server := grpc.NewServer(
		grpc.ChainUnaryInterceptor(grpcactor.UnaryServerInterceptor(grpcactor.WithTrust(trust))),
		grpc.ChainStreamInterceptor(grpcactor.StreamServerInterceptor(grpcactor.WithTrust(trust))),
	)
	defer server.Stop()

	conn, err := grpc.NewClient("dns:///svc-b.example.org:443",
		// grpc.WithTransportCredentials(the workload's mTLS credentials),
		grpc.WithChainUnaryInterceptor(grpcactor.UnaryClientInterceptor()),
		grpc.WithChainStreamInterceptor(grpcactor.StreamClientInterceptor()),
	)
	if err == nil {
		_ = conn.Close()
	}
}

Index

Examples

Constants

View Source
const MaxFieldLen = 256

MaxFieldLen is the longest value, in bytes, any Actor field may hold.

View Source
const MaxWireLen = 4096

MaxWireLen is the largest encoded actor a server will decode.

View Source
const MetadataKey = "x-grpc-actor-bin"

MetadataKey is the gRPC metadata key the actor travels under. It is a binary key, so gRPC base64-encodes the value on the wire; the value is one JSON object: {"v":1,"sub":...,"imp":...,"ten":...,"sid":...}, with empty fields left out. One key keeps the actor atomic: a caller cannot mix a trusted subject with an impersonator from somewhere else.

Variables

View Source
var (
	// ErrNoActor means a method that needs an actor got none. It converts to
	// an Unauthenticated gRPC status.
	ErrNoActor = errors.New("grpcactor: no actor in the request")
	// ErrUntrustedCaller means a caller the trust check refused sent actor
	// metadata, and the server was set to refuse rather than strip it. It
	// converts to a PermissionDenied gRPC status.
	ErrUntrustedCaller = errors.New("grpcactor: actor sent by an untrusted caller")
	// ErrInvalidActor means the actor is malformed: bad wire data from a
	// trusted caller, or an Actor that fails Validate. It converts to an
	// InvalidArgument gRPC status.
	ErrInvalidActor = errors.New("grpcactor: invalid actor")
)

Functions

func StreamClientInterceptor

func StreamClientInterceptor() grpc.StreamClientInterceptor

StreamClientInterceptor is UnaryClientInterceptor for streaming calls.

func StreamServerInterceptor

func StreamServerInterceptor(opts ...ServerOption) grpc.StreamServerInterceptor

StreamServerInterceptor is UnaryServerInterceptor for streaming calls.

func TrustNone

func TrustNone(context.Context, string) bool

TrustNone trusts no caller. It is the server default, so a service that forgets to configure trust fails closed.

func UnaryClientInterceptor

func UnaryClientInterceptor() grpc.UnaryClientInterceptor

UnaryClientInterceptor puts the actor from the call's context on the wire. Install it on every connection a service dials to another internal service.

The context actor is the only one that leaves: any actor metadata already in the outgoing context is replaced, and removed when the context has no actor. An actor that fails Validate fails the call with InvalidArgument before it is sent.

func UnaryServerInterceptor

func UnaryServerInterceptor(opts ...ServerOption) grpc.UnaryServerInterceptor

UnaryServerInterceptor reads the actor a caller sent into the handler's context, but only when the trust check passes. Actor metadata is always removed from the incoming metadata the handler sees, trusted or not, so FromContext is the only way to read it.

Install it after the interceptor that authenticates the caller, when the trust check depends on what that interceptor puts in the context.

func WithActor

func WithActor(ctx context.Context, a Actor) context.Context

WithActor returns a copy of ctx carrying a. The edge calls it once it has authenticated the user; the server interceptors call it for a trusted hop.

Example

The edge sets the actor once, after it has authenticated the user; during act-as the real admin rides along as the impersonator.

package main

import (
	"context"
	"fmt"

	grpcactor "github.com/Bugs5382/go-grpc-actor"
)

func main() {
	ctx := grpcactor.WithActor(context.Background(), grpcactor.Actor{
		Subject:      "user-1001",
		Impersonator: "admin-7",
	})
	a, _ := grpcactor.FromContext(ctx)
	fmt.Println(a.Subject, a.RealUser(), a.Impersonated())
}
Output:
user-1001 admin-7 true

Types

type Actor

type Actor struct {
	Subject      string
	Impersonator string
	Tenant       string
	Session      string
}

Actor is who a request is for. Subject is the effective user: authorization evaluates as Subject. During act-as, Impersonator is the real admin doing the work, kept so every hop can attribute the action to them; it is empty otherwise. Tenant and Session are optional and carried as they are.

Roles and other grants are deliberately absent. A callee resolves what the subject may do from its own data, so a forwarded actor can never widen a caller's authority.

func FromContext

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

FromContext returns the actor in ctx, if any.

func Require

func Require(ctx context.Context, code int) (Actor, error)

Require returns the actor in ctx, or, when there is none, an error that wraps ErrNoActor, carries code as its go-apperr code and converts to an Unauthenticated gRPC status. code is the consumer's own: register it in the service's apperr registry. A zero code leaves the error uncoded.

Example

A handler that cannot run without a user asks for one; the error carries the service's own go-apperr code and an Unauthenticated gRPC status.

package main

import (
	"context"
	"fmt"

	grpcactor "github.com/Bugs5382/go-grpc-actor"
)

func main() {
	const codeNoActor = 4011
	_, err := grpcactor.Require(context.Background(), codeNoActor)
	fmt.Println(err)
}
Output:
code 4011: grpcactor: no actor in the request

func (Actor) Impersonated

func (a Actor) Impersonated() bool

Impersonated reports whether an admin is acting as Subject.

func (Actor) RealUser

func (a Actor) RealUser() string

RealUser returns the person actually at the keyboard: the impersonator during act-as, otherwise the subject. Audit records should name this user.

func (Actor) Validate

func (a Actor) Validate() error

Validate reports whether a is fit to put on the wire. Subject is required, an admin cannot impersonate themselves, and every field must be valid UTF-8 of at most MaxFieldLen bytes with no control characters. The error wraps ErrInvalidActor.

type Codes

type Codes struct {
	Missing   int
	Untrusted int
	Invalid   int
}

Codes are the go-apperr codes the server interceptors attach to the errors they return, one per sentinel. They are the consumer's own codes; a zero field leaves that error without one.

type Event

type Event struct {
	FullMethod string
	Outcome    Outcome
	Claimed    Actor
	Err        error
}

Event describes one decision, for audit and logging. Claimed is the actor the caller sent, decoded on a best-effort basis; for a stripped or rejected call it is unverified and must not be treated as who made the call. Err is set when the call was rejected.

type Observer

type Observer func(ctx context.Context, e Event)

Observer receives an Event for every call that carried actor metadata and for every call refused for a missing actor. It runs on the request path, so keep it fast.

type Outcome

type Outcome int

Outcome is what a server interceptor did with the actor metadata on a call.

const (
	// OutcomeAccepted: a trusted caller sent a valid actor, now in the context.
	OutcomeAccepted Outcome = iota + 1
	// OutcomeStripped: an untrusted caller sent an actor and it was dropped.
	OutcomeStripped
	// OutcomeRejected: the call was refused (untrusted with WithRejectUntrusted,
	// a malformed actor, or a required actor missing).
	OutcomeRejected
)

func (Outcome) String

func (o Outcome) String() string

String returns "accepted", "stripped" or "rejected".

type ServerOption

type ServerOption func(*serverConfig)

ServerOption configures the server interceptors.

func WithCodes

func WithCodes(codes Codes) ServerOption

WithCodes sets the go-apperr codes attached to the errors the interceptors return.

func WithObserver

func WithObserver(observe Observer) ServerOption

WithObserver sets a callback for each decision, for audit or logging.

func WithRejectUntrusted

func WithRejectUntrusted() ServerOption

WithRejectUntrusted refuses, with PermissionDenied, a call whose untrusted caller sent actor metadata, instead of stripping the metadata and serving the call as anonymous. Internal services should set it, so a caller that tries to pass an actor it may not pass is refused and audited rather than silently downgraded. Edge services that face clients leave it off.

func WithRequireActor

func WithRequireActor(match func(fullMethod string) bool) ServerOption

WithRequireActor refuses, with Unauthenticated, a call to a method match reports true for when no actor is in the context after the trust check.

func WithTrust

func WithTrust(trust TrustFunc) ServerOption

WithTrust sets the check that decides whether the caller may forward an actor. Without it the server trusts no caller (TrustNone).

type TrustFunc

type TrustFunc func(ctx context.Context, fullMethod string) bool

TrustFunc decides whether the caller of fullMethod is an authenticated internal service allowed to forward an actor. It must answer from what the transport or an earlier authentication interceptor proved (a verified mTLS peer, a verified workload token), never from anything else the caller sent.

func AnyOf

func AnyOf(fns ...TrustFunc) TrustFunc

AnyOf trusts a caller any of fns trusts. With no fns it trusts nobody.

func ForMethods

func ForMethods(trust TrustFunc, methods ...string) TrustFunc

ForMethods applies trust only to the listed full method names ("/pkg.Service/Method") and trusts nobody on any other method. It builds a per-method allow-list: combine one per caller group with AnyOf.

func TrustDNSNames

func TrustDNSNames(names ...string) TrustFunc

TrustDNSNames trusts a caller whose verified mTLS client certificate carries a DNS SAN equal, ignoring case, to one of names. Matching is exact: a wildcard SAN matches only the same wildcard in names.

func TrustSPIFFEIDs

func TrustSPIFFEIDs(ids ...string) TrustFunc

TrustSPIFFEIDs trusts a caller whose verified mTLS client certificate carries exactly one URI SAN, a spiffe:// ID equal to one of ids. The server must verify client certificates (tls.RequireAndVerifyClientCert); a certificate the handshake did not verify is never trusted.

Jump to

Keyboard shortcuts

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