Scoping a Keyright license to an environment
The same license file tends to flow from production into staging, onto a developer laptop, and through CI, until nobody can tell which environment a validation came from and a leaked staging key quietly unlocks production. This is a migration guide: compare the three ways teams separate environments — a product per environment, a bare file per environment, and one product with a signed env entitlement — then move to the last one on Keyright without a flag day. It covers where the app learns its own environment (IHostEnvironment and the DOTNET_ENVIRONMENT / ASPNETCORE_ENVIRONMENT fallback), a twenty-line gate that fails closed on an unknown environment, a backward-compatible rollout where an unscoped legacy key still runs anywhere, and the honest limit: the environment is self-reported by your own config, so this is hygiene and clean telemetry, not a wall against an operator who sets the variable.
Watch a single license file long enough and it ends up everywhere. You issue one key for the product, drop it into the production deployment, and within a sprint it has been copied into the staging environment so the pre-prod smoke tests pass, pasted into a developer’s appsettings.Development.json, and baked into a CI secret so integration tests can run. Now four environments present the same signed key to your Keyright instance, and three facts you would like to have are gone: you cannot tell from a validation which environment it came from, a staging key that leaks is a production key, and the day you want to expire the staging key early you discover it is the production key.
This post is a migration guide. We will compare the three ways teams actually separate environments, pick the one that keeps a single product and a single code path, and move to it on Keyright without a flag day — including the part most rollouts skip, which is letting the old unscoped key keep working while the new scoped keys roll out.
Three ways to tell production from staging
There are only three shapes for this, and they differ in how much ceremony and how much duplication they cost.
A product per environment. Register acme-studio-prod and acme-studio-staging as separate products in your issuing service, each with its own signing key, and ship a different public key per build. It works, and the separation is absolute, but you now maintain two of everything — two key pairs, two entitlement catalogues, two rotation schedules — and a feature you add to one you must remember to add to the other. This is the right answer only when staging and production are genuinely different products with different capabilities, which they rarely are.
A bare file per environment, same product. Issue two licenses for the one product and rely on deployment discipline to keep them apart. Nothing in the key says which environment it is for, so nothing stops the staging file from running in production; the moment someone copies the wrong file you are back where you started, and the signed payload is no help because it carries no environment at all.
One product, an environment written into the signed payload. Keep a single product and a single public key, and add a scope:env entitlement that names the environment(s) the key is licensed for. The key for staging literally cannot validate as licensed in production, because the app checks its own environment against the claim and the claim is covered by the signature. No second product, no second rotation, one gate. This is the shape we migrate to.
What the key says
A scope:env entitlement is an ordinary signed entitlement — a string in the canonical payload the signature covers — holding a comma-separated set of environment names the key is valid in. A production key names one environment; a key you want to reuse across your own pre-prod tiers names several.
{
"product": "acme-studio",
"licensee": "Contoso Ltd",
"expiryUtc": "2027-11-16T00:00:00Z",
"tier": "pro",
"entitlements": {
"scope:env": "production",
"export": "true",
"max-seats": "400"
},
"signature": "…"
}
The scope: prefix is a convention, not a Keyright feature, and it earns its keep the same way site: does: it keeps where this key may run visibly separate from what this key unlocks, so nobody later gates the export feature on an environment or vice versa. Because the value is inside the signed payload, a customer — or a developer in a hurry — can no more change production to staging than they can push the expiry out a year: one changed byte and the app sees LicenseStatus.SignatureInvalid.
What the app knows about its own environment
The app has to answer “which environment am I?” from its own configuration, offline, at startup. In an ASP.NET Core or generic-host app the answer already exists: IHostEnvironment.EnvironmentName, which the host resolves from DOTNET_ENVIRONMENT (or ASPNETCORE_ENVIRONMENT for the web host), defaulting to Production when neither is set. Wrap it behind an interface so the gate stays testable and so non-host apps can supply the same answer from a raw environment variable.
public interface IAppEnvironment
{
string? Name { get; } // "Production", "Staging", … ; null when genuinely unknown
}
// Host apps: let the framework resolve DOTNET_ENVIRONMENT / ASPNETCORE_ENVIRONMENT.
public sealed class HostAppEnvironment(IHostEnvironment env) : IAppEnvironment
{
public string? Name =>
string.IsNullOrWhiteSpace(env.EnvironmentName) ? null : env.EnvironmentName;
}
// Console / worker without a host: same variables, explicit fallback order.
public sealed class VariableAppEnvironment : IAppEnvironment
{
public string? Name =>
Environment.GetEnvironmentVariable("DOTNET_ENVIRONMENT")
?? Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");
// intentionally NOT defaulting to "Production": see the gate — unknown fails closed
}
One deliberate choice: the host wrapper inherits the framework’s “default to Production” behaviour, but the variable wrapper does not. For a gate you want an unset environment to be unknown, not silently production — an unknown environment on a scoped key should be refused, not waved through as the most privileged tier. The host case is the exception because the framework has already made the decision for the whole app, consistently, before your gate runs.
The gate
The gate runs after Validate() and only does anything when the key actually carries a scope:env claim. Matching is a case-insensitive membership test against the comma-separated set, so scope:env = "staging,production" admits both.
public enum EnvStatus { Ok, NotEnvScoped, Unknown, WrongEnv }
public static class EnvGate
{
public static EnvStatus Check(LicenseInfo info, IAppEnvironment app)
{
var claim = info.Entitlements.GetRaw("scope:env");
if (string.IsNullOrWhiteSpace(claim))
return EnvStatus.NotEnvScoped; // legacy/unscoped key: nothing to check
var here = app.Name;
if (string.IsNullOrWhiteSpace(here))
return EnvStatus.Unknown; // fail closed: unknown ≠ allowed
var allowed = claim.Split(',', StringSplitOptions.TrimEntries | StringSplitOptions.RemoveEmptyEntries);
foreach (var e in allowed)
if (string.Equals(e, here, StringComparison.OrdinalIgnoreCase))
return EnvStatus.Ok;
return EnvStatus.WrongEnv; // e.g. staging key launched in Production
}
}
Wire it at startup, after the signature and expiry checks the SDK already performs:
static readonly KeyrightClient License = KeyrightClient.Initialize(new KeyrightOptions
{
Product = "acme-studio",
PublicKeyBase64 = AcmeKeys.LicensePublicKey, // public key only; safe to ship
});
LicenseInfo info = License.Validate(); // signature, product, expiry
if (!info.IsValid) { RunEvaluation(info); return; }
var env = EnvGate.Check(info, app); // app resolved from DI or the variable wrapper
if (env is not (EnvStatus.Ok or EnvStatus.NotEnvScoped))
{
RunEvaluation(info, reason: env); // "this key is licensed for staging, not Production"
return;
}
RunLicensed(info);
The ordering matters: the env check runs after IsValid. A key with a bad signature never reaches the gate, so the scope:env string an attacker could have typed in is never read — entitlements are only trustworthy once the signature over them has verified, and Keyright returns an empty entitlement set for anything that did not validate.
Migrating without a flag day
The trap in every enforcement rollout is the flag day: you ship the gate and the scoped keys in the same release, a customer’s production node comes up holding the old unscoped key, the gate finds no claim it recognises, and you have turned an upgrade into an outage. The gate above is written to avoid exactly that — NotEnvScoped is a pass — but it is worth being explicit about the three phases.
Phase 1 — backward-compatible issuance. Start issuing new keys with scope:env present, and leave every existing unscoped key alone. Because a missing claim returns NotEnvScoped and that is treated as “runs anywhere”, the legacy production key keeps working untouched while the new staging and production keys carry their scope. No node has to be re-keyed to upgrade.
Phase 2 — audit, don’t enforce. Ship the gate computing EnvStatus but logging it instead of acting on it. Read the logs for a release. This is where you discover the environment names you did not predict — the Staging2 someone stood up, the blue/green slot that reports Production under a different DOTNET_ENVIRONMENT, the load test rig that inherited a production key. The audit-mode rollout pattern applies here unchanged.
Phase 3 — enforce, and re-issue. Flip the gate to acting on WrongEnv/Unknown, and re-issue the remaining legacy unscoped keys as scoped ones on their next renewal. The unscoped key is not insecure — it simply says nothing about environment — so there is no urgency, only a direction: every renewal narrows the blast radius of a leak by one more environment.
Issuing a scoped key, and the diagnostic
On the issuing side the scope is just another entitlement to set. However you mint keys — admin API or CLI against your Keyright instance — the production and staging keys differ in one field:
# production key
keyright issue --product acme-studio --licensee "Contoso Ltd" \
--entitlement scope:env=production --entitlement max-seats=400 --expiry 2027-11-16
# a single key reusable across your own pre-prod tiers
keyright issue --product acme-studio --licensee "Contoso Ltd (pre-prod)" \
--entitlement scope:env=staging,qa --expiry 2027-11-16
Close the hand-off gap the same way the site-license flow does: ship a one-line diagnostic that prints the environment the gate would check, from exactly the code path the gate uses, so “it says wrong environment” never becomes a support ticket about what the environment actually is.
// yourapp --env-info
var app = new VariableAppEnvironment();
Console.WriteLine($"Resolved environment : {app.Name ?? "(unknown — DOTNET_ENVIRONMENT unset)"}");
What environment scoping proves — and what it does not
Be honest in your own threat model about what this binding is.
The environment is self-reported. scope:env is checked against a value the running process reads from its own configuration, and an operator who controls that configuration can set DOTNET_ENVIRONMENT=Production on a staging box and the gate will pass. So this is not a wall against a determined operator who owns the host — it is not meant to be. What it does stop is the accident that is a hundred times more common: the staging key copied into production and quietly running there for a year, the developer key that leaked and now unlocks the production tier, the CI secret that turns out to be a production license. Those are configuration mistakes, and scope:env turns them from silent into a loud, specific refusal with the reason attached.
It is a hygiene and telemetry boundary, not a seat count. Scoping does not limit how many machines run a key — a production key with max-seats still counts seats the way it always did; the scope only limits which tier it will run in. The two are orthogonal, and it is worth keeping them so: a key that is both seat-limited and environment-scoped tells you, in its telemetry, both how many production nodes are live and that none of them are secretly staging.
For an untrusted boundary, scope differently. If “staging” is a different customer’s environment rather than your own tier, self-reported configuration is the wrong instrument entirely — bind to something the other party cannot assert, as the site-license domain binding does, or issue genuinely separate products. Environment scoping earns its place when the environments are all yours, the risk is a mistake rather than an adversary, and you want the key itself — not a deployment runbook — to be the thing that keeps production and staging apart.
A license that runs everywhere is convenient right up to the first leak, when “everywhere” stops being a feature. Writing the environment into the signed key costs one entitlement and one twenty-line gate, it migrates in without a flag day because an unscoped key still runs anywhere, and it gives every validation an answer to the question your audit log has been missing: which environment was this?
Try Nebula.NET
Harden your .NET code in minutes — start with the free edition.