Skip to content

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

lifecycle.js JavaScript · 69 lines
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};

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.