Skip to content
← All posts
· Delta1 Labs LicensingKeyright

Enforcing license entitlements in gRPC services

A gRPC service has no MVC filter pipeline and no [Authorize] attribute to hang a license check on — the one seam that sees every call is the server Interceptor. This post writes a LicensingInterceptor that validates a Keyright license once, maps each gRPC method to a required entitlement, and fails closed with the right status: FailedPrecondition when there is no valid license, PermissionDenied when the license lacks the entitlement, ResourceExhausted when a numeric limit is spent. Plus a cached hot path that never round-trips the issuing service, DI registration via AddGrpc, and the streaming variants.

An ASP.NET Core Web API gives you a tidy seam for license checks: an authorization policy, an [Authorize(Policy = "ent:export")] attribute, and the request is rejected before your action runs. A gRPC service has none of that. There is no controller, no action filter pipeline, no attribute that the framework evaluates per call. If you try to scatter if (license.HasEntitlement("export")) through your service methods you are back to the thing the HTTP authorization pipeline was built to replace — a check you have to remember to write in every method, where forgetting one ships a feature unlicensed.

gRPC does have one seam that sees every call, though, and it is the right place to put this: the server-side Interceptor. This post writes a LicensingInterceptor that validates a Keyright license once, maps each gRPC method to a required entitlement, and fails closed with the correct gRPC status.

Why gRPC needs its own enforcement seam

An interceptor is to gRPC what middleware and filters are to MVC, but the shape is different. You do not decorate methods and let a pipeline discover them; you subclass Grpc.Core.Interceptors.Interceptor and override the handler for each call kind — UnaryServerHandler, ServerStreamingServerHandler, ClientStreamingServerHandler, DuplexStreamingServerHandler. Each override receives the request, a ServerCallContext, and a continuation delegate that invokes the actual service method. Whatever you do before calling the continuation happens before the method body runs; if you throw instead of calling it, the method never executes.

That is precisely the admission-control seam a license gate wants. One class, registered once, guards every RPC — and because the method name is on the ServerCallContext, the same class can require a different entitlement per method.

The interceptor is the one seam that sees every call

Here is the flow for a unary call. The interceptor validates the cached license, looks up the entitlement this method requires, and either calls the continuation or throws an RpcException with a fail-closed status.

Unary RPC/Reports/ExportLicensingInterceptorvalidate cached licensemap method → entitlementService method runscontinuation(request, ctx)FailedPreconditionno valid licensePermissionDeniedentitlement missingKeyright SDK — cached, offline validation; no per-RPC round-trip to the issuing servicevalid + entitledno licenselacks entitlement

Keep the hot path cheap: validate once, cache the snapshot

An RPC server can field thousands of calls a second, so the gate must be close to free. The Keyright SDK already caches the activated lease — it does not re-contact the issuing service on each validation — but ValidateAsync still verifies the signature and parses the license each time it runs. Do that work once and hold the immutable LicenseInfo snapshot, refreshing it on a short interval so a renewed or revoked lease is picked up without hammering the CPU on every RPC.

using Grpc.Core;
using Keyright;

public sealed class LicenseGate
{
    private readonly IKeyrightClient _client;
    private readonly IReadOnlyDictionary<string, string> _methodEntitlements;
    private static readonly TimeSpan RefreshWindow = TimeSpan.FromSeconds(5);

    private volatile LicenseInfo? _snapshot;   // signature-verified once per window
    private long _nextRefreshTicks;

    public LicenseGate(IKeyrightClient client, MethodEntitlementMap map)
    {
        _client = client;
        _methodEntitlements = map.Entries;
    }

    private async ValueTask<LicenseInfo> CurrentAsync(CancellationToken ct)
    {
        LicenseInfo? snap = _snapshot;
        if (snap is not null && DateTime.UtcNow.Ticks < Interlocked.Read(ref _nextRefreshTicks))
            return snap;                         // hot path: field read, no verify

        snap = await _client.ValidateAsync(ct);  // offline: verify signature + parse, no network
        _snapshot = snap;
        Interlocked.Exchange(ref _nextRefreshTicks, (DateTime.UtcNow + RefreshWindow).Ticks);
        return snap;
    }

    public async ValueTask EnforceAsync(string method, CancellationToken ct)
    {
        LicenseInfo license = await CurrentAsync(ct);

        // 1. No valid license at all — the service cannot run this call.
        if (!license.IsValid)
            throw new RpcException(new Status(StatusCode.FailedPrecondition,
                $"No valid Keyright license for '{_client.Product}'. " +
                "Install or renew a license before calling this service."));

        // 2. This method requires a specific entitlement the license does not carry.
        if (_methodEntitlements.TryGetValue(method, out string? required)
            && !license.HasEntitlement(required))
            throw new RpcException(new Status(StatusCode.PermissionDenied,
                $"This license does not include the '{required}' entitlement required by {method}."));
    }
}

Two SDK properties make this safe. ValidateAsync never throws on an invalid license — a missing, expired, or revoked license resolves to the Community Edition tier carrying a status, so license.IsValid is simply false and the gate throws its own clean RpcException rather than letting an exception escape the pipeline. And HasEntitlement fails closed: an unknown or absent entitlement reads as false. Deny is the default, which is exactly what you want in an admission check.

Mapping methods to entitlements

ServerCallContext.Method is the fully-qualified method path — "/acme.Reports/Export". A dictionary keyed on that string is the simplest map, and it keeps the policy in one readable place. Methods that are not in the map require only a valid license, not a specific entitlement — so your base RPCs work on any edition and only the premium methods name an entitlement.

public sealed class MethodEntitlementMap
{
    public IReadOnlyDictionary<string, string> Entries { get; } =
        new Dictionary<string, string>(StringComparer.Ordinal)
        {
            ["/acme.Reports/Export"]      = "reports.export",
            ["/acme.Reports/StreamAudit"] = "audit.stream",
            ["/acme.Admin/RotateKeys"]    = "admin.security",
        };
}

If you would rather keep the requirement next to the method, mark the service implementation and build the map by reflection at startup:

[AttributeUsage(AttributeTargets.Method)]
public sealed class RequiresEntitlementAttribute(string entitlement) : Attribute
{
    public string Entitlement { get; } = entitlement;
}

// public override Task<ExportReply> Export(...)  ->  decorate with [RequiresEntitlement("reports.export")]

Walk the service type’s methods once, read the attribute, and translate each CLR method name into its gRPC path ("/" + ServiceName + "/" + MethodName) to populate the same dictionary. Either way the interceptor stays identical — it only consumes the finished map.

The LicensingInterceptor itself

The interceptor is thin: it delegates to the gate, then calls the continuation. All the policy lives in the gate; the interceptor only wires the gate into each call kind.

using Grpc.Core;
using Grpc.Core.Interceptors;

public sealed class LicensingInterceptor : Interceptor
{
    private readonly LicenseGate _gate;
    public LicensingInterceptor(LicenseGate gate) => _gate = gate;

    public override async Task<TResponse> UnaryServerHandler<TRequest, TResponse>(
        TRequest request,
        ServerCallContext context,
        UnaryServerMethod<TRequest, TResponse> continuation)
    {
        await _gate.EnforceAsync(context.Method, context.CancellationToken);
        return await continuation(request, context);   // only reached if the gate allowed it
    }
}

If EnforceAsync throws, continuation is never invoked and gRPC marshals the RpcException back to the client as the status and detail you chose — no half-run method, no leaked response.

Streaming calls need the same guard — once

Streaming RPCs have their own handlers, but the license decision is the same and is made once, at the top: the license and its entitlements do not change mid-call, so there is no value in re-checking per message. Enforce before the continuation, exactly as for unary.

public override async Task ServerStreamingServerHandler<TRequest, TResponse>(
    TRequest request,
    IServerStreamWriter<TResponse> responseStream,
    ServerCallContext context,
    ServerStreamingServerMethod<TRequest, TResponse> continuation)
{
    await _gate.EnforceAsync(context.Method, context.CancellationToken);
    await continuation(request, responseStream, context);
}

ClientStreamingServerHandler and DuplexStreamingServerHandler follow the same pattern — gate first, then await continuation(...). If you run a long-lived stream and want it to drop when a license lapses mid-session, re-read the cached snapshot on a timer inside your stream loop and complete the stream; but the admission check belongs at the top where it rejects before any data flows.

Choosing the right gRPC status

Status selection is not cosmetic — gRPC clients branch on StatusCode, so the code you return tells the caller whether and when to retry. A licensing failure maps onto three distinct codes:

  • FailedPrecondition — there is no valid license. The service is not in a state where the call can succeed, and the client must not retry blindly: a human has to install or renew a license first. This is the correct default for “no license, expired, revoked.”
  • PermissionDenied — the license is valid but does not carry the entitlement this method requires. The caller is known and the call is well-formed; it is simply not licensed for this capability, and retrying unchanged will not help.
  • ResourceExhausted — a numeric limit is spent: a seat cap, a per-day call quota. This one is retryable later, once usage frees up, which is how clients already treat ResourceExhausted from flow control. Read the number off the same license and throw it where a cap is reached:
long cap = license.GetLimit("rpc.daily", fallback: 0);   // fail-closed fallback
if (usage.Today(context.Method) >= cap)
    throw new RpcException(new Status(StatusCode.ResourceExhausted,
        $"Daily call limit of {cap} reached for {context.Method}."));

Resist Unauthenticated for any of these — that code is about who the caller is, not what they are licensed for, and conflating identity with entitlement makes both harder to reason about.

Registering the interceptor

Register the Keyright client as a singleton (it loads the public key once and is thread-safe), add the gate and map, and attach the interceptor to the gRPC pipeline:

builder.Services.AddSingleton<IKeyrightClient>(_ => KeyrightClient.Initialize(new KeyrightOptions
{
    Product         = "acme-grpc",
    PublicKeyBase64 = builder.Configuration["Keyright:PublicKey"],   // not a secret; verify-only
    ServiceUrl      = builder.Configuration["Keyright:ServiceUrl"],
}));

builder.Services.AddSingleton<MethodEntitlementMap>();
builder.Services.AddSingleton<LicenseGate>();

builder.Services.AddGrpc(o => o.Interceptors.Add<LicensingInterceptor>());

That single Interceptors.Add<LicensingInterceptor>() line is the whole registration: every unary and streaming method on every gRPC service in the app now passes through the gate before its body runs. Adding a newly gated method is one entry in the map (or one attribute) — not a line of enforcement code in the method itself.

Why this is the right seam

The point of pushing the check into the interceptor is the same as pushing it into ASP.NET Core authorization: it changes the default. With if checks sprinkled through service methods, forgetting one means a capability ships unlicensed — the default is allow. With the interceptor, the default is deny: an unmapped premium method still requires a valid license, and a gated one requires its entitlement, before the continuation ever runs. The decision stays offline and fail-closed exactly as everywhere else in Keyright, the hot path is a cached field read rather than a network call, and the client gets a precise gRPC status it can act on instead of a half-executed RPC.

See entitlements and feature flags for the capability model the map draws on, cached verification on the hot path for the snapshot pattern, and entitlements as ASP.NET Core authorization policies for the HTTP sibling of this seam.

Try Nebula.NET

Harden your .NET code in minutes — start with the free edition.