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()
}
}
Output:
Index ¶
- Constants
- Variables
- func StreamClientInterceptor() grpc.StreamClientInterceptor
- func StreamServerInterceptor(opts ...ServerOption) grpc.StreamServerInterceptor
- func TrustNone(context.Context, string) bool
- func UnaryClientInterceptor() grpc.UnaryClientInterceptor
- func UnaryServerInterceptor(opts ...ServerOption) grpc.UnaryServerInterceptor
- func WithActor(ctx context.Context, a Actor) context.Context
- type Actor
- type Codes
- type Event
- type Observer
- type Outcome
- type ServerOption
- type TrustFunc
Examples ¶
Constants ¶
const MaxFieldLen = 256
MaxFieldLen is the longest value, in bytes, any Actor field may hold.
const MaxWireLen = 4096
MaxWireLen is the largest encoded actor a server will decode.
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
FromContext returns the actor in ctx, if any.
func Require ¶
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 ¶
Impersonated reports whether an admin is acting as Subject.
type Codes ¶
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 ¶
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 ¶
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 )
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 ¶
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 ForMethods ¶
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 ¶
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 ¶
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.