@nodii/grpc-auth
v0.22.0
Published
gRPC service-to-service auth for Nodii microservices: server + client interceptors, JWKS fetch from S3, JWT verifier, token manager.
Maintainers
Readme
@nodii/grpc-auth
Service-to-service gRPC auth for the Nodii microservice stack.
Provides:
createServerAuthInterceptor— verifies an incomingBearertoken from theauthorizationmetadata header and attaches anS2SAuthContextto the call.createClientAuthInterceptor— acquires a token via anS2STokenManagerand attaches it to outgoing calls.S2STokenManager— caches tokens from a SigV4-signed API Gateway endpoint and reuses each one for its lifetime (hub decision D845). Refreshes early without blocking callers. Every mint is bounded bymintTimeoutMs(default 1500 ms): a mint that takes longer fails as a transientS2STokenMintError, so a hung issuer cannot hang a caller, and a cached token keeps being served. Build one per process: a manager built per call never hits its cache.verifyS2SToken— JWT verifier with JWKS resolution.createSigV4S3JWKSet— JWKS resolver that pulls a private.well-known/jwks.jsonfrom S3 using SigV4 (not anonymous HTTPS).withAuthUnary+requireScope— handler-level wrapper for unary RPC scope enforcement.
Inbound webhooks
verifyWebhook, from @nodii/grpc-auth/webhook, is the one verifier for inbound provider webhooks (S12-24). Each provider keeps its own signature scheme, so the scheme is configuration. Pass the raw bytes, before any parse:
import { verifyWebhook, type WebhookScheme } from "@nodii/grpc-auth/webhook";
const stripe: WebhookScheme = {
kind: "hmac",
algorithm: "sha256",
signature: { header: "stripe-signature", encoding: "hex", separator: ",", prefix: "v1=" },
timestamp: { header: "stripe-signature", separator: ",", prefix: "t=", format: "unix-seconds", toleranceSeconds: 300 },
signed: { parts: [{ field: "timestamp" }, { literal: "." }, { field: "body" }] },
};
const verdict = verifyWebhook(stripe, [{ secret, id: "current" }], {
rawBody,
headers: c.req.raw.headers,
});
if (verdict.status === "refused") return c.json({ error: "unauthorized" }, 401); // log verdict.reason- Verdicts:
verified,skipped(acredentialscheme matched; nothing was verified over the body, S12-16) orrefusedwith areason. The reason is for the security log, never the response. A refused request changes no state. - The helper decides no policy: the timestamp window is required on a scheme with a timestamp, and a key's overlap is the
notAfteryou give it. The helper logs nothing and holds no provider table. precheckWebhookruns every check that needs no key, so a service can refuse a malformed request before it pays to decrypt one.- A provider that signs something other than the raw body: compute the string yourself and pass it in
values, named by{ value: "..." }in the scheme (Twilio's URL and sorted parameters, SNS's canonical fields). For a public-key provider whose key comes from a certificate, resolve the certificate first and pass the base64 DER SPKI as the key.
The shared vectors are in scripts/parity/webhook-cases.json; they include a scheme for each signature shape in S12 §5.
The edge's signed step-up instant
The edge forwards the token's step_up_at (the session's last second factor, epoch seconds) as x-nodii-step-up-at, with x-nodii-step-up-at-signature: the gateway HMAC over purpose step-up-at, the value, the principal's x-nodii-jti and the x-request-id. It sends neither header when the token has no step_up_at. verifyGatewayStepUpAt({ stepUpAt, signature, jti, requestId, secrets }) returns verified with the instant, absent, or invalid with a reason (PARTIAL, UNBOUND, MALFORMED, BAD_BASE64URL, MISMATCH, OUT_OF_ROTATION_GRACE). Verify the principal bundle first and pass its jti. Then decide freshness with @nodii/auth-sdk's evaluateStepUp, which also needs a second factor in amr; treat absent and invalid as no step-up. On Hono, @nodii/auth-sdk/gateway's requireStepUp({ maxAgeSeconds }) does all of this. Python (verify_gateway_step_up_at) and Go (VerifyGatewayStepUpAt) run the same shared vectors, scripts/parity/step-up-at-cases.json.
Install
bun add @nodii/grpc-auth
# peer deps
bun add @grpc/grpc-js joseServer: verify incoming tokens
import * as grpc from "@grpc/grpc-js";
import {
createServerAuthInterceptor,
createSigV4S3JWKSet,
setJwksResolver,
} from "@nodii/grpc-auth";
// Configure JWKS source once, at boot.
setJwksResolver(
createSigV4S3JWKSet({
region: "ap-south-1",
bucket: "nucleus-cloud-s2s-auth",
key: ".well-known/jwks.json",
cacheMaxAgeMs: 60_000,
cooldownDurationMs: 5_000,
}),
);
const server = new grpc.Server({
interceptors: [
createServerAuthInterceptor({
expectedIssuer: "nucleus-s2s-auth",
expectedAudience: "nucleus-internal",
}),
],
});The interceptor extracts Bearer <token>, calls verifyS2SToken, and attaches the auth context to the call as (call as any).auth. Handlers read it via the same path:
function handler(call: ServerUnaryCall<Req, Res>, cb: sendUnaryData<Res>) {
const auth = (call as any).auth as S2SAuthContext | undefined;
// auth.serviceName, auth.scopes, ...
}Note.
(call as any).authis the production-proven pattern from provisioning. A typedgetCallContext(call)helper is planned for v0.3.0 (lifted from inventory). It will live alongside the legacy reader, not replace it.
Server: per-handler scope enforcement
import { withAuthUnary } from "@nodii/grpc-auth";
const REQUIRED_SCOPES_BY_METHOD: Record<string, string> = {
createCustomer: "provisioning:customers:write",
getCurrentIpAssignmentsForIp: "provisioning:ip_assignments:read",
};
const wrap = withAuthUnary({
expectedIssuer: "nucleus-s2s-auth",
expectedAudience: "nucleus-internal",
requiredScopesByMethod: REQUIRED_SCOPES_BY_METHOD,
// Optional: skip auth in local dev. Defaults to false.
skipAuth: () => process.env.LOCAL === "true",
});
server.addService(MyServiceDefinition, {
createCustomer: wrap("createCustomer", impl.createCustomer),
// ...
});Client: acquire and attach a token
import {
S2STokenManager,
createClientAuthInterceptor,
} from "@nodii/grpc-auth";
const tokenManager = new S2STokenManager({
apiBaseUrl: process.env.S2S_AUTH_API_BASE!,
region: process.env.AWS_REGION ?? "ap-south-1",
refreshSkewSeconds: 30,
// Bound on ONE mint (issue 816). Default 1500; values above 9000 are clamped to 9000.
mintTimeoutMs: 1500,
});
const client = new MyGrpcServiceClient(target, credentials, {
interceptors: [
createClientAuthInterceptor({
tokenManager,
audience: "nucleus-internal",
scopes: ["flows:write"],
instanceId: process.env.INSTANCE_ID,
}),
],
});Transport: TLS between services
NODII_DEPLOY_ENV is the switch. It is required and has no default.
| NODII_DEPLOY_ENV | Listener | Client |
|---|---|---|
| uat, prod | TLS | Verifies the peer against our CA. Plaintext is refused |
| dev, test | Plaintext | Plaintext |
In uat and prod, set up the transport at start-up, before the process dials or listens. It reads Secrets Manager, so the task role needs read access.
import {
grpcChannelCredentials,
grpcServerCredentials,
initGrpcTransport,
} from "@nodii/grpc-auth";
await initGrpcTransport({ serviceName: "auth-service" });
server.bindAsync(address, grpcServerCredentials(), onBound);
const client = new PeerClient(target, grpcChannelCredentials());- The CA comes from
nodii/<env>/tls/ca(GRPC_TLS_CA). The listener's certificate and key come fromnodii/<env>/tls/<serviceName>(GRPC_TLS_CERT,GRPC_TLS_KEY). - A process that only dials leaves out
serviceNameand needs only the CA. - An unreadable secret, an empty value, invalid PEM or a key that does not match its certificate stops the process at start-up.
GrpcTransportConfigError.codenames the refusal. - In
uatandprod,grpcChannelCredentials()andgrpcServerCredentials()throwgrpc_tls_not_configureduntil the transport is set up.buildS2SClient, the approval clients and the role-catalog client use these credentials by default. - Secrets are reread every
reloadIntervalMs(default five minutes), and a rotated listener certificate takes effect with no restart. A failed reload is logged, keeps the current certificate and callsonReloadError. - To roll the CA, publish a bundle holding the old and new CA, restart, issue from the new CA, then remove the old one. Only channels built after a reload are sure to hold a new CA.
- Hot reload needs Bun 1.4.4 or later. On Bun 1.3 a listener built this way presents no certificate.
The Go port (InitGrpcTransport) and the Python port (init_grpc_transport) follow the same switch and use the same codes.
Versioning notes
v0.1.0 is a 1:1 lift of provisioning's S2S auth code (production-proven, also running in traffic-logs). Two narrow changes vs the source:
- The JWKS source is configured via
setJwksResolver(...)instead of a module-level constant. Provisioning's hardcodedregion: "ap-south-1",bucket: "nucleus-cloud-s2s-auth",key: ".well-known/jwks.json"move into the consumer's bootstrap. withAuthUnaryacceptsrequiredScopesByMethodandskipAuthas parameters instead of importing them from a service-specific env.
These are dependency-injection refactors, not behavior changes. Verifier semantics (algorithms, clock skew, claim shape, scope parsing), token cache logic, and JWKS refresh+cooldown are unchanged.
Planned follow-ups:
v0.2.0— pluggable test JWKS source (TEST_S2S_JWKS_PATHpattern from traffic-logs).v0.3.0— typedCallContext/getCallContext/mutateCallContextAPI alongside the legacy(call as any).authreads (pattern from inventory).v0.4.0— pluggable logger (replacesconsole.logcalls; quiet by default).
