File size: 7,062 Bytes
34810d2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
/** Worker-only canonical context construction and bounded value helpers. */
import type { DatabaseSync } from "node:sqlite";
import type { ExecutionIdentityContextV1 } from "../../packages/gateway-protocol/src/index.js";
import { validateExecutionIdentityContextV1 } from "../../packages/gateway-protocol/src/index.js";
import { pseudonymizeExecutionIdentityRef } from "./audit-identity.js";
import type { ExecutionIdentityAdmissionEnvelope } from "./execution-identity-admission.js";
import { sortUniqueExecutionIdentityEntries } from "./execution-identity-ordering.js";
import { executionIdentitySpawnAdmission } from "./execution-identity-spawn-admission.js";

const EXECUTION_IDENTITY_CONTEXT_MAX_BYTES = 16 * 1024;

export function ensureBoundedExecutionIdentityRef(
  value: string,
  label: string,
  maxLength = 256,
): string {
  if (!value || value.length > maxLength) {
    throw new Error(`${label} must be between 1 and ${String(maxLength)} characters`);
  }
  return value;
}

function ensureRawRef(value: string, label: string): string {
  return ensureBoundedExecutionIdentityRef(value, label, 4_096);
}

export function freezeExecutionIdentityContext<T>(value: T, seen = new WeakSet<object>()): T {
  if (!value || typeof value !== "object" || seen.has(value as object)) {
    return value;
  }
  seen.add(value as object);
  for (const nested of Object.values(value as Record<string, unknown>)) {
    freezeExecutionIdentityContext(nested, seen);
  }
  return Object.freeze(value);
}

function hmacRef(
  db: DatabaseSync,
  kind: Parameters<typeof pseudonymizeExecutionIdentityRef>[0]["kind"],
  scope: string,
  value: string,
): string {
  return pseudonymizeExecutionIdentityRef({
    db,
    kind,
    scope: ensureBoundedExecutionIdentityRef(scope, "HMAC scope"),
    value: ensureRawRef(value, "HMAC value"),
  });
}

export function buildExecutionIdentityContext(
  db: DatabaseSync,
  envelope: ExecutionIdentityAdmissionEnvelope,
  fixed: { contextId: string; createdAt: number },
): ExecutionIdentityContextV1 {
  const runId = ensureBoundedExecutionIdentityRef(envelope.runId, "run id");
  const executionId = ensureBoundedExecutionIdentityRef(envelope.executionId, "execution id");
  const agentId = ensureBoundedExecutionIdentityRef(envelope.agentId, "agent id");
  const contextId = ensureBoundedExecutionIdentityRef(fixed.contextId, "context id");
  const domainRef = hmacRef(db, "domain", "gateway-cell", "gateway-cell");
  const runtimeRef = hmacRef(
    db,
    "runtime",
    domainRef,
    ensureRawRef(envelope.runtimeInstanceId, "runtime instance id"),
  );
  const invoker =
    envelope.invoker?.state === "present"
      ? {
          state: "present" as const,
          principal: {
            kind: envelope.invoker.kind,
            domainRef,
            principalRef: hmacRef(
              db,
              "principal",
              `${domainRef}:${envelope.invoker.kind}`,
              envelope.invoker.rawPrincipalRef,
            ),
            ...(envelope.invoker.displayLabel !== undefined
              ? { displayLabel: envelope.invoker.displayLabel }
              : {}),
          },
        }
      : envelope.invoker?.state === "unknown"
        ? { state: "unknown" as const }
        : { state: "absent" as const };
  const assurance = sortUniqueExecutionIdentityEntries(
    envelope.assurance.map((item) => ({
      kind: item.kind,
      evidenceRef: hmacRef(db, "evidence", `${domainRef}:${item.kind}`, item.rawEvidenceRef),
      strength: item.strength,
    })),
    (item) => `${item.kind}\0${item.evidenceRef}\0${item.strength}`,
  );
  const applicableGrants = sortUniqueExecutionIdentityEntries(
    envelope.applicableGrants.map((grant) => ({
      grantRef: hmacRef(db, "grant", domainRef, grant.rawGrantRef),
      state: grant.state,
    })),
    (grant) => `${grant.grantRef}\0${grant.state}`,
  );
  const serializedSpawnFacts = executionIdentitySpawnAdmission({
    operation: "read",
    value: envelope,
  });
  const [lineageFacts, spawnMissingEvidence] = serializedSpawnFacts
    ? executionIdentitySpawnAdmission({ operation: "parse", value: serializedSpawnFacts })
    : [undefined, []];
  const lineage = lineageFacts
    ? {
        ...(typeof lineageFacts.parentContextId === "string"
          ? { parentContextId: lineageFacts.parentContextId }
          : {}),
        ...(typeof lineageFacts.parentExecutionId === "string"
          ? { parentExecutionId: lineageFacts.parentExecutionId }
          : {}),
        ...(typeof lineageFacts.parentRunId === "string"
          ? { parentRunId: lineageFacts.parentRunId }
          : {}),
        parentAgentPrincipal: {
          kind: "agent" as const,
          domainRef,
          principalRef: lineageFacts.parentAgentId,
        },
        delegationRef: hmacRef(
          db,
          "grant",
          `${domainRef}:delegation`,
          JSON.stringify([
            lineageFacts.relation,
            lineageFacts.rawRequesterRef,
            lineageFacts.rawControllerRef,
            lineageFacts.localPolicyRefs,
            lineageFacts.targetPolicyRefs,
          ]),
        ),
        depth: lineageFacts.depth,
      }
    : undefined;
  const missingEvidence = sortUniqueExecutionIdentityEntries(
    [
      ...(envelope.invoker?.state === "present" ? [] : ["invoker.principal"]),
      ...spawnMissingEvidence,
    ],
    (item) => item,
  );
  const context: Record<string, unknown> = {
    schemaVersion: 1,
    contextId,
    executionId,
    runId,
    createdAt: fixed.createdAt,
    trustDomain: { kind: "gateway-cell", domainRef, state: "present" },
    invoker,
    ingress: {
      kind: envelope.ingress.kind,
      boundary: ensureBoundedExecutionIdentityRef(envelope.ingress.boundary, "ingress boundary"),
      state: envelope.ingress.state,
      ...(envelope.ingress.rawSourceRef
        ? {
            sourceRef: hmacRef(
              db,
              "principal",
              `${domainRef}:ingress:${envelope.ingress.kind}`,
              envelope.ingress.rawSourceRef,
            ),
          }
        : {}),
    },
    agentPrincipal: { kind: "agent", domainRef, principalRef: agentId },
    agentDefinition: { definitionRef: agentId, state: "present" },
    runtimeInstance: { runtimeRef, kind: envelope.runtime.kind, state: "present" },
    applicableGrants,
    assurance,
    ...(lineage ? { lineage } : {}),
    coverageState: lineage
      ? "attribution-only"
      : envelope.invoker?.state === "present"
        ? "attribution-only"
        : envelope.invoker?.state === "unknown"
          ? "unknown"
          : "unattributed",
    missingEvidence,
  };
  if (!validateExecutionIdentityContextV1(context)) {
    throw new Error("prepared execution identity context violates the V1 contract");
  }
  const encoded = JSON.stringify(context);
  if (Buffer.byteLength(encoded, "utf8") > EXECUTION_IDENTITY_CONTEXT_MAX_BYTES) {
    throw new Error("prepared execution identity context exceeds 16 KiB");
  }
  return freezeExecutionIdentityContext(context);
}