Event context and secret-cache lifetime lab
Exercises producer context, tenant scope, duplicate events, warm-process reuse, and fail-closed cache refresh in a local model.
Cloud Security 2 min read
Implementation
labs/request-lifecycle/lifecycle.js
1"use strict";
2
3// Tested local teaching model. Context authentication and durable idempotency are
4// deliberately external; this is not AWS Lambda, Vault or an event-source emulator.
5class SecretCache {
6 constructor(provider, clock, maxAgeMs = 1000) {
7 this.provider = provider;
8 this.clock = clock;
9 this.maxAgeMs = maxAgeMs;
10 this.cached = null;
11 }
12 async get() {
13 const now = this.clock();
14 if (this.cached && now < this.cached.expires) return this.cached.value;
15 // Never return an expired value if refresh fails.
16 this.cached = null;
17 const value = await this.provider();
18 if (!value || typeof value.value !== "string" || typeof value.version !== "string") {
19 throw new Error("SECRET_UNAVAILABLE");
20 }
21 this.cached = {value, expires: now + this.maxAgeMs};
22 return value;
23 }
24}
25
26class EventHandler {
27 constructor({clock, secrets, execute}) {
28 this.clock = clock;
29 this.secrets = secrets;
30 this.execute = execute;
31 this.completed = new Map();
32 this.audit = [];
33 this.pending = Promise.resolve();
34 }
35 handle(context, event) {
36 // Serialize the toy in-process ledger. A real consumer needs durable atomic
37 // idempotency and reconciliation at the actual downstream side effect.
38 const result = this.pending.then(() => this.process(context, event));
39 this.pending = result.catch(() => {});
40 return result;
41 }
42 async process(context, event) {
43 const deny = code => {
44 this.audit.push({event: "event_decision", outcome: "deny", code});
45 throw new Error(code);
46 };
47 if (!context || context.verified !== true || context.producer !== "owned-queue") deny("PRODUCER_DENIED");
48 if (!event || typeof event !== "object" || Array.isArray(event) ||
49 Object.keys(event).sort().join(",") !== "id,issuedAt,tenant,value" ||
50 !/^[a-z0-9-]{1,40}$/.test(event.id) || !Number.isSafeInteger(event.issuedAt) ||
51 typeof event.value !== "string" || event.value.length > 100) deny("EVENT_INVALID");
52 if (!context.tenant || context.tenant !== event.tenant) deny("TENANT_DENIED");
53 if (event.issuedAt > this.clock() || this.clock() - event.issuedAt > 1000) deny("EVENT_STALE");
54 const key = JSON.stringify([context.tenant, event.id]);
55 if (this.completed.has(key)) {
56 if (this.completed.get(key) !== JSON.stringify(event)) deny("IDEMPOTENCY_CONFLICT");
57 this.audit.push({event: "event_decision", outcome: "duplicate"});
58 return {status: "duplicate"};
59 }
60 const secret = await this.secrets.get();
61 // No tenant/event retained in a shared global for later invocations.
62 await this.execute({tenant: context.tenant, value: event.value, secret: secret.value});
63 this.completed.set(key, JSON.stringify(event));
64 this.audit.push({event: "event_decision", outcome: "allow", secretVersion: secret.version});
65 return {status: "completed"};
66 }
67}
68
69module.exports = {EventHandler, SecretCache};
1"use strict";
2const assert = require("node:assert/strict");
3const test = require("node:test");
4const {EventHandler, SecretCache} = require("./lifecycle");
5
6function fixture() {
7 let now = 100;
8 let version = 1;
9 let unavailable = false;
10 const calls = [];
11 const cache = new SecretCache(async () => {
12 if (unavailable) throw new Error("SECRET_UNAVAILABLE");
13 return {version: `version-${version}`, value: `<synthetic-secret-${version}>`};
14 }, () => now, 1000);
15 const handler = new EventHandler({clock: () => now, secrets: cache, execute: async call => calls.push(call)});
16 return {handler, calls, cache, advance: ms => { now += ms; }, rotate: () => { version++; },
17 failProvider: () => { unavailable = true; }};
18}
19const context = {verified: true, producer: "owned-queue", tenant: "tenant-a"};
20const event = {id: "event-a", tenant: "tenant-a", issuedAt: 100, value: "<synthetic-payload>"};
21
22test("valid event, duplicate and concurrent duplicate produce one side effect", async () => {
23 const f = fixture();
24 const results = await Promise.all([f.handler.handle(context, event), f.handler.handle(context, event)]);
25 assert.deepEqual(results.map(r => r.status), ["completed", "duplicate"]);
26 assert.equal(f.calls.length, 1);
27});
28
29test("producer, tenant, time and schema failures have no side effect", async () => {
30 const f = fixture();
31 for (const [ctx, input, reason] of [
32 [{...context, verified: false}, event, "PRODUCER_DENIED"],
33 [{...context, producer: "other-queue"}, event, "PRODUCER_DENIED"],
34 [context, {...event, tenant: "tenant-b"}, "TENANT_DENIED"],
35 [context, {...event, issuedAt: 101}, "EVENT_STALE"],
36 [context, {...event, issuedAt: -1000}, "EVENT_STALE"],
37 [context, {...event, admin: true}, "EVENT_INVALID"],
38 [context, {...event, value: "x".repeat(101)}, "EVENT_INVALID"],
39 ]) await assert.rejects(f.handler.handle(ctx, input), new RegExp(reason));
40 assert.equal(f.calls.length, 0);
41});
42
43test("same event ID cannot hide changed payload", async () => {
44 const f = fixture();
45 await f.handler.handle(context, event);
46 await assert.rejects(f.handler.handle(context, {...event, value: "changed"}), /IDEMPOTENCY_CONFLICT/);
47 assert.equal(f.calls.length, 1);
48});
49
50test("warm process preserves distinct tenant context and tenant-scoped IDs", async () => {
51 const f = fixture();
52 await f.handler.handle(context, event);
53 await f.handler.handle({...context, tenant: "tenant-b"}, {...event, tenant: "tenant-b"});
54 assert.deepEqual(f.calls.map(call => call.tenant), ["tenant-a", "tenant-b"]);
55});
56
57test("cache has measured deterministic refresh boundary and fails closed on outage", async () => {
58 const f = fixture();
59 assert.equal((await f.cache.get()).version, "version-1");
60 f.rotate();
61 f.advance(999);
62 assert.equal((await f.cache.get()).version, "version-1");
63 f.advance(1);
64 assert.equal((await f.cache.get()).version, "version-2");
65 f.failProvider();
66 f.advance(1000);
67 await assert.rejects(f.cache.get(), /SECRET_UNAVAILABLE/);
68 assert.equal(f.cache.cached, null);
69});
70
71test("failed secret refresh cannot execute an event or leak payload in audit", async () => {
72 const f = fixture();
73 f.failProvider();
74 await assert.rejects(f.handler.handle(context, event), /SECRET_UNAVAILABLE/);
75 assert.equal(f.calls.length, 0);
76 assert.ok(!JSON.stringify(f.handler.audit).includes(event.value));
77 assert.ok(!JSON.stringify(f.handler.audit).includes("synthetic-secret"));
78});
Run it
node --test labs/request-lifecycle/lifecycle.test.js
Tested teaching model. This is not a Lambda, event-source, Vault or Secrets Manager implementation. Context authentication is injected, not cryptographically verified. No cloud resource or real secret exists.
Objective and threat model¶
An event sender controls IDs, tenant and payload. The model trusts a separately verified producer context, derives execution tenant from it, and rejects stale, foreign or schema-invalid input. A duplicate must not repeat a simulated side effect. A long-lived process must not reuse another request's tenant context.
flowchart LR
E[Untrusted event] --> H[Verified-context handler]
C[Trusted producer and tenant context] --> H
H --> I[Serialized local idempotency ledger]
I --> S[Versioned secret cache]
S --> X[Fake executor]
Prerequisites, setup and validation¶
Node.js 22+; no package install, container, network, credential or cloud account. From repository root:
node --test labs/request-lifecycle/lifecycle.test.js
Expected: six passing methods. Negative producer/tenant/schema/time cases assert zero executor calls; the concurrent duplicate case asserts one call; warm reuse asserts separate tenants. Cache tests inject a clock: old version at 999 ms, new version at 1000 ms, refresh failure after expiry rejects without a stale fallback. This measures the model's exact timer contract, not provider rotation latency.
Evidence, cost and teardown¶
mkdir -p .artifacts/research
node --test labs/request-lifecycle/lifecycle.test.js > .artifacts/research/lifecycle.tap
The process exits and all memory state disappears. Delete the evidence after review. There is no service, persistent state, infrastructure, cloud cost or destroy step. CPU/memory are small local test-process costs; production overhead is not measured.
Failure modes and limitations¶
The ledger intentionally retains event data in memory to compare payload reuse; it has no retention cap, durable transaction or distributed reconciliation. A failure after an external side effect but before ledger completion could duplicate work. Do not treat this serialization as production exactly-once execution. Secret material remains in process memory; the cache cannot revoke already issued values or existing downstream sessions. A real provider, queue and storage system need separate tests and lifecycle controls. Audit is memory-only and omits error events when the secret provider throws; detection coverage for that path is incomplete.