@oatscenter/trellis 0.100.0-rc.38 → 0.100.0-rc.39

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -160,6 +160,12 @@ export declare class SessionAuthorityOwner {
160
160
  stop(): void;
161
161
  /** Read public verification material using a fresh, pinned-issuer authenticated exchange. */
162
162
  readIssuerMetadata(query: IssuerMetadataQuery): Promise<IssuerMetadataResponse>;
163
+ /**
164
+ * Re-read each rotated-out key still inside its live overlap. Auth sends
165
+ * the issuer notice on revocation too, and a revoked key then stops
166
+ * authorizing live use at once instead of at its signed deadline.
167
+ */
168
+ recheckRetiringIssuers(): Promise<void>;
163
169
  /** Authenticate one signed successor from this owner's existing durable pin. */
164
170
  acceptIssuerRotation(bytes: Uint8Array): Promise<void>;
165
171
  }
package/auth/authority.js CHANGED
@@ -128,6 +128,7 @@ export class SessionAuthorityOwner {
128
128
  instanceId;
129
129
  account;
130
130
  #keys = new Map();
131
+ #liveUntil = new Map();
131
132
  #peers = new Map();
132
133
  #materials = new Map();
133
134
  #pending = new Map();
@@ -468,7 +469,7 @@ export class SessionAuthorityOwner {
468
469
  const issuer = await this.#issuer(keyId);
469
470
  const verified = await verifyAdmissionContextWasm(bytes, issuer, request, subject, reply, this.account, this.#now());
470
471
  if (this.#stopped ||
471
- this.#keys.get(issuer.keyId)?.state !== "active" ||
472
+ this.#liveIssuer(issuer.keyId)?.state !== "active" ||
472
473
  verified.expiresAt <= this.#now())
473
474
  throw new Error("Unavailable");
474
475
  return verified;
@@ -840,7 +841,7 @@ export class SessionAuthorityOwner {
840
841
  assertCurrent(entry) {
841
842
  if (this.#stopped || this.#overloaded || !this.#mirrorCovered)
842
843
  throw new Error("authority owner unavailable");
843
- const issuer = this.#keys.get(entry.authority.issuerKeyId);
844
+ const issuer = this.#liveIssuer(entry.authority.issuerKeyId);
844
845
  if (issuer?.state !== "active")
845
846
  throw new Error("issuer unavailable for live authority");
846
847
  assertSessionAuthorityHandleCurrentWasm(entry.handle, this.policy(), this.#revocations.has(entry.authority.authorizationSessionId));
@@ -1003,8 +1004,10 @@ export class SessionAuthorityOwner {
1003
1004
  assertCurrent,
1004
1005
  });
1005
1006
  if (query.kind === "issuerKey" && response.result.kind === "value") {
1006
- // The shared verifier checked the exact requested key and non-live state.
1007
- const historical = JSON.parse(response.result.payload);
1007
+ // The shared verifier checked the exact requested key, its non-live
1008
+ // state, and that only a retired key carries a live deadline.
1009
+ const answer = JSON.parse(response.result.payload);
1010
+ const historical = answer.key;
1008
1011
  const previous = this.#keys.get(historical.keyId);
1009
1012
  if (previous && previous.publicKey !== historical.publicKey)
1010
1013
  throw new Error("historical issuer conflict");
@@ -1012,8 +1015,15 @@ export class SessionAuthorityOwner {
1012
1015
  throw new Error("historical issuer is a live pin");
1013
1016
  if (!previous && this.#keys.size >= 128)
1014
1017
  throw new Error("issuer history budget exceeded");
1015
- if (previous?.state !== "revoked")
1018
+ if (previous?.state !== "revoked") {
1016
1019
  this.#keys.set(historical.keyId, historical);
1020
+ // A key Auth reports inside its overlap is live until the signed
1021
+ // deadline, as if this owner had followed the chain.
1022
+ if (!previous &&
1023
+ answer.liveUntil !== undefined &&
1024
+ answer.liveUntil > this.#now())
1025
+ this.#liveUntil.set(historical.keyId, answer.liveUntil);
1026
+ }
1017
1027
  }
1018
1028
  if (query.kind === "authorityStatus" &&
1019
1029
  response.result.kind === "value") {
@@ -1052,16 +1062,38 @@ export class SessionAuthorityOwner {
1052
1062
  throw new Error("authority material unavailable");
1053
1063
  return entry.value;
1054
1064
  }
1055
- async #issuer(keyId) {
1056
- let issuer = this.#keys.get(keyId);
1057
- if (!issuer) {
1058
- issuer = await this.#forwardIssuer(keyId);
1065
+ /**
1066
+ * Re-read each rotated-out key still inside its live overlap. Auth sends
1067
+ * the issuer notice on revocation too, and a revoked key then stops
1068
+ * authorizing live use at once instead of at its signed deadline.
1069
+ */
1070
+ async recheckRetiringIssuers() {
1071
+ for (const [keyId, until] of this.#liveUntil) {
1072
+ if (until <= this.#now()) {
1073
+ this.#liveUntil.delete(keyId);
1074
+ continue;
1075
+ }
1076
+ // A failed read leaves the key to its signed deadline.
1077
+ await this.#readIssuerMetadata({ kind: "issuerKey", keyId }, false).catch(() => undefined);
1059
1078
  }
1079
+ }
1080
+ /** A rotated-out key stays live until its signed deadline, as in the Rust owner. */
1081
+ #liveIssuer(keyId) {
1082
+ const issuer = this.#keys.get(keyId);
1083
+ return issuer?.state === "retired" &&
1084
+ (this.#liveUntil.get(keyId) ?? 0) > this.#now()
1085
+ ? { ...issuer, state: "active" }
1086
+ : issuer;
1087
+ }
1088
+ async #issuer(keyId) {
1089
+ let issuer = this.#liveIssuer(keyId);
1090
+ if (!issuer && (await this.#forwardIssuer(keyId)))
1091
+ issuer = this.#liveIssuer(keyId);
1060
1092
  if (!issuer) {
1061
1093
  const response = await this.#readIssuerMetadata({ kind: "issuerKey", keyId }, false);
1062
1094
  if (response.result.kind !== "value")
1063
1095
  throw new Error("historical authority issuer unavailable");
1064
- issuer = this.#keys.get(keyId);
1096
+ issuer = this.#liveIssuer(keyId);
1065
1097
  }
1066
1098
  if (!issuer || issuer.state === "revoked")
1067
1099
  throw new Error("untrusted authority issuer");
@@ -1110,7 +1142,11 @@ export class SessionAuthorityOwner {
1110
1142
  const existing = this.#keys.get(verified.successor.keyId);
1111
1143
  if (existing)
1112
1144
  throw new Error("issuer rotation conflict");
1145
+ const retiredAt = verified.record.previousRetiredAt;
1146
+ if (typeof retiredAt !== "number")
1147
+ throw new Error("invalid rotation");
1113
1148
  this.#keys.set(previous.keyId, { ...previous, state: "retired" });
1149
+ this.#liveUntil.set(previous.keyId, retiredAt);
1114
1150
  this.#keys.set(verified.successor.keyId, verified.successor);
1115
1151
  this.#rotationSequence++;
1116
1152
  this.#authenticatedIssuerSequences.set(verified.successor.keyId, this.#rotationSequence.toString());
@@ -10,6 +10,7 @@ import { loadDefaultRuntimeTransport, } from "../runtime_transport.js";
10
10
  import { TransportGenerationManager, } from "../transport/generations.js";
11
11
  /** Subjects on which Auth announces a new provider of an API the session calls. */
12
12
  const PROVIDERS_NOTICE_SUBJECT_PREFIX = "trellis.auth.providers.";
13
+ const ISSUER_NOTICE_SUBJECT = "trellis.auth.issuers";
13
14
  const policySchema = z.object({
14
15
  format: z.literal("trellis.transport-authorization.v1"),
15
16
  account: z.string(),
@@ -89,6 +90,9 @@ export async function connectAdmitted(options) {
89
90
  let renewalTimer;
90
91
  let renewalAbort;
91
92
  let renewalTask;
93
+ // Set by a notice that arrives while a renewal is in flight: that renewal
94
+ // may already hold Auth's answer from before the change it announces.
95
+ let renewalNoticed = false;
92
96
  let mirrorRecovery;
93
97
  const credentials = new WeakMap();
94
98
  const noticed = new WeakSet();
@@ -343,17 +347,26 @@ export async function connectAdmitted(options) {
343
347
  if (!noticed.has(generation.nc)) {
344
348
  noticed.add(generation.nc);
345
349
  // Routes name the providers that existed at admission. Auth announces
346
- // one added since, and renewing adopts the route to it at once.
350
+ // one added since, and renewing adopts the route to it at once. Auth
351
+ // also announces an issuer key rotation or revocation: renewing moves
352
+ // this session onto authority the current key signed, and the re-check
353
+ // ends a revoked key's overlap.
347
354
  for (const subject of value.admission.policy.subscribeAllow) {
348
- if (!subject.startsWith(PROVIDERS_NOTICE_SUBJECT_PREFIX))
355
+ if (!subject.startsWith(PROVIDERS_NOTICE_SUBJECT_PREFIX) &&
356
+ subject !== ISSUER_NOTICE_SUBJECT)
349
357
  continue;
350
358
  generation.nc.subscribe(subject, {
351
359
  callback: (error) => {
352
360
  if (error || manager.isClosed())
353
361
  return;
354
- void refreshAuthority().catch(() => {
355
- /* typed failure is retained by closed() */
356
- });
362
+ if (renewalTask)
363
+ renewalNoticed = true;
364
+ else
365
+ void refreshAuthority().catch(() => {
366
+ /* typed failure is retained by closed() */
367
+ });
368
+ if (subject === ISSUER_NOTICE_SUBJECT)
369
+ void owner.recheckRetiringIssuers();
357
370
  },
358
371
  });
359
372
  }
@@ -414,6 +427,9 @@ export async function connectAdmitted(options) {
414
427
  const signal = options.signal
415
428
  ? AbortSignal.any([options.signal, renewalAbort.signal])
416
429
  : renewalAbort.signal;
430
+ // Set when the attachment this renewal leased closed under it: ordinary
431
+ // transport recovery then owns readmission, and this failure ends nothing.
432
+ let withdrawn = false;
417
433
  const task = (async () => {
418
434
  // A reduction can withdraw the attachment while the existing admission
419
435
  // pipeline is preparing its replacement. Explicit renewal must join that
@@ -472,13 +488,18 @@ export async function connectAdmitted(options) {
472
488
  manager.authorizationPromoted();
473
489
  scheduleRenewal();
474
490
  }
491
+ catch (error) {
492
+ if (lease.nc.isClosed())
493
+ withdrawn = true;
494
+ throw error;
495
+ }
475
496
  finally {
476
497
  lease.release();
477
498
  }
478
499
  })();
479
500
  renewalTask = task
480
501
  .catch(async (error) => {
481
- if (!signal.aborted && !manager.isClosed()) {
502
+ if (!signal.aborted && !manager.isClosed() && !withdrawn) {
482
503
  await manager.terminate(error instanceof AuthError || error instanceof TransportError
483
504
  ? error
484
505
  : new TransportError({
@@ -495,6 +516,16 @@ export async function connectAdmitted(options) {
495
516
  renewalTask = undefined;
496
517
  renewalAbort = undefined;
497
518
  }
519
+ // One trailing renewal covers every notice received meanwhile.
520
+ if (renewalNoticed &&
521
+ !renewalTask &&
522
+ !manager.isClosed() &&
523
+ !options.signal?.aborted) {
524
+ renewalNoticed = false;
525
+ void refreshAuthority().catch(() => {
526
+ /* typed failure is retained by closed() */
527
+ });
528
+ }
498
529
  });
499
530
  return renewalTask;
500
531
  };
@@ -55,8 +55,17 @@ export async function authenticateIssuerChain(issuer, anchor, target, signal, ex
55
55
  offset += chunk.length;
56
56
  }
57
57
  const chain = issuerChainSchema.parse(JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(bytes)));
58
- for (const rotation of chain.rotations)
58
+ for (const rotation of chain.rotations) {
59
+ // A connected session sharing this owner may already have installed
60
+ // the link, on Auth's issuer notice. The sequence is only a lookup
61
+ // hint; the final trust check below still requires the target.
62
+ const { sequence } = JSON.parse(rotation);
63
+ if (typeof sequence === "string" &&
64
+ /^[0-9]{1,20}$/.test(sequence) &&
65
+ BigInt(sequence) <= BigInt(owner.trustSnapshot.rotationSequence))
66
+ continue;
59
67
  await owner.acceptIssuerRotation(signedBytes(rotation));
68
+ }
60
69
  }
61
70
  const verified = owner.trustForCredential(anchor);
62
71
  if (verified.issuer.keyId !== target.issuer.keyId ||
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "dependencies": {
3
- "@oatscenter/trellis": "^0.100.0-rc.38"
3
+ "@oatscenter/trellis": "^0.100.0-rc.39"
4
4
  },
5
5
  "description": "Generated Trellis APIs and participants.",
6
6
  "exports": {
@@ -1,5 +1,6 @@
1
1
  import { headers as natsHeaders, } from "@nats-io/nats-core";
2
2
  import { TransportError } from "../errors/TransportError.js";
3
+ import { SERVICE_AVAILABILITY_WAIT_MS } from "../session/wire.js";
3
4
  import { encodeEventSubjectParameterToken } from "../helpers.js";
4
5
  import { liveConstants, liveDataSubject, liveGenerateNonce, liveNegotiateMaxDataBodyBytes, liveObserveSubject, liveParseControlResponse, liveParseFrame, liveParseOffer, liveVerifyServerProof, } from "./protocol.js";
5
6
  import { authorityLostEnd, authorityLostFrom, LiveAuthorityGuard, } from "./authority.js";
@@ -57,14 +58,29 @@ async function request(host, subject, payload, deadlineMs) {
57
58
  throw new LiveStreamError("setup_timeout", "live opening reservation elapsed");
58
59
  }
59
60
  const sub = host.nats.subscribe(reply);
61
+ const replies = sub[Symbol.asyncIterator]();
62
+ // The opening is sent again only when the broker reports that no provider
63
+ // received it, as for requests.
64
+ const waitUntil = clock.nowMs() + Math.min(SERVICE_AVAILABILITY_WAIT_MS, remaining);
65
+ let pause = 100;
60
66
  try {
61
- host.nats.publish(subject, payload, {
62
- headers: proofHeaders(proof, host.sessionKey),
63
- reply,
64
- });
65
- const received = await withTimeout(clock, Math.min(host.timeoutMs, remaining), sub[Symbol.asyncIterator]()
66
- .next()
67
- .then((next) => (next.done ? undefined : next.value)));
67
+ let received;
68
+ for (;;) {
69
+ host.nats.publish(subject, payload, {
70
+ headers: proofHeaders(proof, host.sessionKey),
71
+ reply,
72
+ });
73
+ received = await withTimeout(clock, Math.min(host.timeoutMs, Math.max(1, deadlineMs - clock.nowMs())), replies.next().then((next) => (next.done ? undefined : next.value)));
74
+ if (received?.headers?.code !== 503 || clock.nowMs() + pause >= waitUntil)
75
+ break;
76
+ await new Promise((resolve) => {
77
+ const clear = clock.scheduleAt(clock.nowMs() + pause, () => {
78
+ clear();
79
+ resolve();
80
+ });
81
+ });
82
+ pause = Math.min(pause * 2, 1000);
83
+ }
68
84
  if (!received) {
69
85
  throw new LiveStreamError("setup_timeout", "live request timed out");
70
86
  }
package/package.json CHANGED
@@ -51,7 +51,7 @@
51
51
  "@nats-io/obj": "^3.4.0",
52
52
  "@nats-io/transport-node": "^3.4.0",
53
53
  "@noble/hashes": "1.8.0",
54
- "@oatscenter/result": "0.100.0-rc.38",
54
+ "@oatscenter/result": "0.100.0-rc.39",
55
55
  "@opentelemetry/api": "^1.9.1",
56
56
  "@opentelemetry/context-async-hooks": "~2.11.0",
57
57
  "@opentelemetry/core": "~2.11.0",
@@ -71,7 +71,7 @@
71
71
  "uqr": "0.1.3",
72
72
  "zod": "^4.3.6"
73
73
  },
74
- "version": "0.100.0-rc.38",
74
+ "version": "0.100.0-rc.39",
75
75
  "type": "module",
76
76
  "license": "Apache-2.0",
77
77
  "publishConfig": {
package/session/wire.d.ts CHANGED
@@ -38,6 +38,8 @@ export declare function requestFailedTransportError(args: {
38
38
  }): TransportError;
39
39
  /** Bounded catalog outcome for one logical RPC failure. */
40
40
  export declare function outcomeForFailure(error: BaseError): "declared_error" | "denied" | "invalid" | "rate_limited" | "timeout" | "unavailable" | "cancelled" | "error";
41
+ /** How long a request waits for an absent provider, within its own deadline. */
42
+ export declare const SERVICE_AVAILABILITY_WAIT_MS = 5000;
41
43
  export declare function classifyRequestTransportFailure(args: {
42
44
  method?: string;
43
45
  subject: string;
package/session/wire.js CHANGED
@@ -87,6 +87,8 @@ export function outcomeForFailure(error) {
87
87
  }
88
88
  return "error";
89
89
  }
90
+ /** How long a request waits for an absent provider, within its own deadline. */
91
+ export const SERVICE_AVAILABILITY_WAIT_MS = 5_000;
90
92
  export function classifyRequestTransportFailure(args) {
91
93
  const message = args.cause instanceof Error ? args.cause.message : String(args.cause);
92
94
  const isNoResponders = message.includes("no responders");
package/session.js CHANGED
@@ -38,7 +38,7 @@ import { addSurfaceLeaf, } from "./session/facades.js";
38
38
  import {} from "./session/operations.js";
39
39
  import { EMPTY_TRELLIS_API, activeTraceId, causeLogData, causeMessage, ingressRetiredError, isBrowserAuthRequiredError, isRuntimeRpcErrorDesc, payloadByteLength, traceIdFromTraceparent, } from "./session/helpers.js";
40
40
  import { toCatalogAction, verifyLocalAuthorization, } from "./session/local_authorization.js";
41
- import { MAX_PENDING_OPENINGS, base64urlEncode, callerOwnsReply, classifyRequestTransportFailure, createTransportError, encodeRuntimeSchema, mapTransportAcquireFailure, outcomeForFailure, parseRuntimeSchema, requestFailedTransportError, safeJson, } from "./session/wire.js";
41
+ import { MAX_PENDING_OPENINGS, base64urlEncode, callerOwnsReply, classifyRequestTransportFailure, createTransportError, encodeRuntimeSchema, mapTransportAcquireFailure, outcomeForFailure, parseRuntimeSchema, requestFailedTransportError, safeJson, SERVICE_AVAILABILITY_WAIT_MS, } from "./session/wire.js";
42
42
  import { annotateHandlerBoundaryError, callerErrorData, isResultLike, reconstructDeclaredRpcError, recordRuntimeError, } from "./session/handler_errors.js";
43
43
  export { verifyLocalAuthorization, toCatalogAction, } from "./session/local_authorization.js";
44
44
  export { safeJson, classifyRequestTransportFailure, createActionUnavailableError, base64urlEncode, base64urlDecode, toArrayBuffer, sha256, } from "./session/wire.js";
@@ -2694,6 +2694,16 @@ export class Trellis {
2694
2694
  };
2695
2695
  let verified = false;
2696
2696
  let verifying = 0;
2697
+ // Invocation deduplication does not span deployments, so the request
2698
+ // is sent again only when the broker reports that no provider
2699
+ // received it: a provider reconnecting is briefly absent.
2700
+ const waitUntil = Math.min(deadlineMs, Date.now() + SERVICE_AVAILABILITY_WAIT_MS);
2701
+ let pause = 100;
2702
+ let resend;
2703
+ const send = () => {
2704
+ resend = undefined;
2705
+ nc.publish(args.subject, args.payload, { headers, reply });
2706
+ };
2697
2707
  const timer = setTimeout(() => {
2698
2708
  waitFailure = {
2699
2709
  cause: new DOMException("Request timed out", "TimeoutError"),
@@ -2716,7 +2726,15 @@ export class Trellis {
2716
2726
  response.reject(error);
2717
2727
  else if (message.data.length === 0 &&
2718
2728
  message.headers?.code === 503) {
2719
- response.reject(new Error("no responders"));
2729
+ if (!args.signal?.aborted &&
2730
+ resend === undefined &&
2731
+ Date.now() + pause < waitUntil) {
2732
+ resend = setTimeout(send, pause);
2733
+ pause = Math.min(pause * 2, 1000);
2734
+ }
2735
+ else {
2736
+ response.reject(new Error("no responders"));
2737
+ }
2720
2738
  }
2721
2739
  else if (!verified && verifying < 8) {
2722
2740
  // Unauthenticated traffic cannot consume the pending opening.
@@ -2772,13 +2790,14 @@ export class Trellis {
2772
2790
  abort();
2773
2791
  }
2774
2792
  else {
2775
- nc.publish(args.subject, args.payload, { headers, reply });
2793
+ send();
2776
2794
  }
2777
2795
  return await response.promise;
2778
2796
  }
2779
2797
  finally {
2780
2798
  verified = true;
2781
2799
  clearTimeout(timer);
2800
+ clearTimeout(resend);
2782
2801
  args.signal?.removeEventListener("abort", abort);
2783
2802
  stopWatching();
2784
2803
  subscription.unsubscribe();