refactor(ocap-kernel): branded kernel identifiers with runtime validation#917
Merged
refactor(ocap-kernel): branded kernel identifiers with runtime validation#917
Conversation
Add phantom-property branded types for KRef, VRef, RRef, VatId, RemoteId, SubclusterId, VatMessageId, and GCAction to prevent accidental misuse of distinct identifier types at compile time. Unlike the previous template-literal approach (removed in #366), branded types are subtypes of string so interpolation, comparison, and KV store writes work without casts. Assertions (insistKRef, etc.) validate at runtime boundaries; factory sites use as-casts. Closes #809 Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
…or insistX() calls
Remove ~29 redundant runtime validation calls from kernel interior code.
Validation is preserved only at trust boundaries: translators (vat/remote
syscalls), GCAction deserialization, reachable-state parsing, RPC handlers,
and RemoteHandle. Store methods use as-casts for KV reads (trusting the
store). RunQueueItem structs now use branded validators (KRefStruct,
EndpointIdStruct) so types carry brands through deserialization.
Also fixes a bug where insistEndpointId('kernel') in
KernelRouter.#deliverKernelServiceMessage would throw at runtime.
Add typed methods for all external KV access (initialization flag, kernel service krefs, remote identity state, known relays) and remove the raw kv property from the KernelStore return value. All KV access is now mediated through typed store methods, closing the hole where consumers could bypass branded type safety via raw string reads/writes.
…essage Replace the untyped Message type (result: string, slots: string[]) with two distinct types: KernelMessage (result: KRef, slots: KRef[]) and EndpointMessage (result: ERef, slots: ERef[]). Each has its own struct and validator. Translation functions bridge between them. Eliminates ~15 'as KRef' casts on message fields in KernelRouter, KernelQueue, and translators. The type system now enforces that kernel code works with KRef-typed messages and endpoint code with ERef-typed messages, with no possibility of confusion.
…ore and trust boundaries Add makeGCAction factory, validated store reader helpers, tighten ID validators to reject non-integer suffixes, add insistKRef at resolvePromises boundary, validate coerceEndpointMessage slots, and add comprehensive tests for all ref validators and insist functions. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
…promise resolutions Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This comment was marked as resolved.
This comment was marked as resolved.
…tMessage The validation was throwing on raw liveslots refs before the translator had a chance to process them, causing integration test timeouts. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
…CAP URL and kslot signatures
…Id validation failure
This comment was marked as resolved.
This comment was marked as resolved.
…ject to accept 'kernel' owner
…lStore.kv The KernelStore no longer exposes `kv` publicly. Access the raw KV store via KernelDatabase.kernelKVStore directly for test queue manipulation. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Contributor
Coverage Report
File Coverage |
…, consolidate CapDataStruct - Widen KernelPromise.decider to EndpointId | 'kernel', validate in getKernelPromise - Use getOwner() in gc.ts instead of raw KV read, guard isVatId before isVatTerminated - Add insistKRef validation in redeemLocalOcapURL and remote redemption reply - Change KernelSyscallObject exit variant and CrankResult.terminate.info to CapData<KRef> - Tighten parseKernelSlot and insistKernelType to accept KRef instead of string - Compose isEndpointId from isVatId || isRemoteId - Fix gc.test.ts to test makeGCAction rejection instead of redundant isGCAction checks - Export CapDataStruct from kernel-utils, remove duplicate from ocap-kernel Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Member
Author
|
@cursor review |
There was a problem hiding this comment.
✅ Bugbot reviewed your changes and found no new issues!
Comment @cursor review or bugbot run to trigger another review on this PR
Reviewed by Cursor Bugbot for commit e2361a4. Configure here.
…erceEndpointMessage Add trust model documentation to types.ts and a store README explaining that persistence reads are trusted and data integrity is the persistence layer's responsibility. Validate coerceEndpointMessage with EndpointMessageStruct, fix stale JSDoc, consistent insist* docs, and use makeGCAction in gc tests. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
…n completions
Replace the loosely typed deferredCompletion object in
RemoteHandle.handleRemoteMessage with a discriminated union keyed on
`type` ('redeemURL' | 'redeemURLReply') and further discriminated by
`ref` (success) vs `error` (failure), eliminating the `success` boolean
and enabling precise type narrowing at each completion handler.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
…nsafe casts Replace CapDataStruct (validates string[] slots) with KernelCapDataStruct (validates KRef[] slots) in queueMessage and launchSubcluster RPC specs. This makes the runtime validation match the declared CapData<KRef> type, eliminating two `as unknown as` casts. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
…literal rationale Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
…ten test casts Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
…y mechanisms Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
sirtimid
approved these changes
Apr 7, 2026
2 tasks
github-merge-queue bot
pushed a commit
that referenced
this pull request
Apr 7, 2026
…921) A follow-up to #917 addressing various items deferred during the introduction of branded kernel identifier types. ## Summary - Replace `as KRef` casts from unvalidated sources with runtime validation in `kernel-ui` - `db-parser.ts`: remove dead `?? ''` fallbacks on regex match groups, add `insistKRef` validation for slot resolution from JSON-parsed DB values - `SendMessageForm.tsx`: validate user-selected target with `isKRef` before sending, replacing the blind `as KRef` cast - Add `isKRef`, `insistKRef`, `KRefStruct` to `setupOcapKernelMock` test utility - Includes prior commit addressing PR review feedback on branded types in `ocap-kernel` ## Test plan - [x] `yarn workspace @metamask/kernel-ui run build` passes - [x] `yarn workspace @metamask/kernel-ui test:dev:quiet` passes (all 34 test files, 263 tests) 🤖 Generated with [Claude Code](https://claude.com/claude-code) <!-- CURSOR_SUMMARY --> --- > [!NOTE] > **Medium Risk** > Adds runtime `KRef` validation in UI and DB parsing paths, which can now reject/throw on previously accepted malformed values. Risk is moderate because it changes input handling and parsing behavior but is narrowly scoped and covered by updated tests. > > **Overview** > **Hardens branded identifier handling** by validating `KRef` values at runtime instead of relying on unchecked `as KRef` casts. > > In `SendMessageForm`, the selected target is now stored as `KRef | null`, validated via `isKRef` on change, and sending is blocked when the target is invalid; tests are updated accordingly and add coverage for failed `KRef` validation. > > In `kernel-ui`’s `db-parser`, regex match fallbacks are removed and `resolveSlot` now calls `insistKRef` when converting JSON-parsed slot strings, making malformed DB data fail fast. Supporting changes extend `setupOcapKernelMock` with `isKRef`/`insistKRef`/`KRefStruct`, and `ocap-kernel` tests/docs are updated (including new `getKnownRelays` test coverage and tighter ID validation cases). > > <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit 55a981a. Bugbot is set up for automated code reviews on this repo. Configure [here](https://www.cursor.com/dashboard/bugbot).</sup> <!-- /CURSOR_SUMMARY --> --------- Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Fixes #809
Summary
VatId,RemoteId,KRef,VRef,RRef,SubclusterId,GCAction, etc.) for kernel identifiers with runtime validators (isX/insistX)MessageintoKernelMessage(kernel-space, KRef slots) andEndpointMessage(endpoint-space, ERef slots)kvfromKernelStoreAPI, replace with typed accessor methodsKernelOneResolutiontype for kernel-space promise resolutionsKernelSyscallObjectdiscriminated union type for kernel-space syscalls, removing casts fromVatSyscallmakeGCActionfactory with runtime validationkslot/makeStandinPromiseto useKRefcoerceEndpointMessagewithEndpointMessageStructat the liveslots boundarygetOwnerto handle'kernel'owner without throwing EndpointId validation failureTODO
kernel-uitype safety is not fully addressed by this PR, and will be implemented in a follow-upwriteX(value: X): void/readX(): Xpairs that use the same db keys internally. If we want to make the store actually type safe, we would have to establish some kind of compile-time mapping between db keys and value types. This may or may not be worth the trouble, and we defer this decision to the future.Test plan
yarn workspace @metamask/ocap-kernel lint:fixpassesyarn workspace @metamask/ocap-kernel buildpassesyarn workspace @metamask/ocap-kernel test:dev:quietpassesyarn workspace @metamask/kernel-node-runtime test:e2e:cipasses🤖 Generated with Claude Code
Note
Medium Risk
Touches core kernel routing/queueing, remote comms, and persistence access patterns; while largely type-safety refactors, signature changes and reduced runtime checks could surface as behavioral regressions at boundaries (RPC/liveslots/remotes) if any call sites or stored data violate the new invariants.
Overview
Branded kernel identifiers are enforced end-to-end. This introduces branded string types (e.g.,
KRef,VatId,SubclusterId) withis*/insist*validators, and updates kernel/public RPC APIs (e.g.,queueMessage,issueOcapURL,terminateSubcluster) and UI call sites to use these types.Message and resolution types are split and tightened.
Messageis separated intoKernelMessagevsEndpointMessage, promise resolution flows switch to kernel-space types, and the queue/router/service-manager/remotes paths are updated accordingly (including narrowedkslot/krefOfbehavior).Raw KV access is removed from
KernelStore.KernelStore.kvis no longer exposed; consumers/tests now use typed accessors for initialization state, kernel-service krefs, remote identity values, and known relay storage (with added validation on relay parsing).Reviewed by Cursor Bugbot for commit 812f5bf. Bugbot is set up for automated code reviews on this repo. Configure here.