-
Notifications
You must be signed in to change notification settings - Fork 3
feat(config): add shared configuration core #404
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
AprilNEA
wants to merge
2
commits into
xuan/code-537
Choose a base branch
from
xuan/code-543
base: xuan/code-537
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
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
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
795 changes: 795 additions & 0 deletions
795
packages/foundation/common/src/config/__fixtures__/contract-v1.json
Large diffs are not rendered by default.
Oops, something went wrong.
300 changes: 300 additions & 0 deletions
300
packages/foundation/common/src/config/__tests__/contract.test.ts
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,300 @@ | ||
| import { hashes, verify } from '@noble/ed25519'; | ||
| import { sha256, sha512 } from '@noble/hashes/sha2.js'; | ||
| import { describe, expect, it } from 'vitest'; | ||
| import fixture from '../__fixtures__/contract-v1.json'; | ||
| import { | ||
| applyConfigPatch, | ||
| assertConfigPointer, | ||
| assertConfigSnapshot, | ||
| assertEmergencyDocument, | ||
| assertMonotonicVersion, | ||
| canonicalizeJson, | ||
| canonicalSignedPayload, | ||
| canonicalSignedPayloadBytes, | ||
| compareMonotonicVersions, | ||
| conditionMatches, | ||
| decideAntiReplay, | ||
| emergencyTargetMatches, | ||
| matchesVersionRange, | ||
| murmur3X86_32, | ||
| rolloutBucket, | ||
| rolloutMatches, | ||
| targetMatches, | ||
| } from '../contract'; | ||
| import { decodeBase64Url, encodeBase64Url, parseIJson } from '../i-json'; | ||
| import type { AntiReplayState, ConfigCrypto, OverrideCondition } from '../types'; | ||
| import { validateSnapshotBytes, verifyPointerBytes } from '../verification'; | ||
|
|
||
| interface SignedVector { | ||
| readonly canonicalPayload: string; | ||
| readonly canonicalPayloadBase64Url: string; | ||
| readonly document: Record<string, unknown>; | ||
| readonly payloadSha256: string; | ||
| } | ||
|
|
||
| const pointers: Record<string, SignedVector> = fixture.pointers; | ||
| const emergencies: Record<string, SignedVector> = fixture.emergencies; | ||
| const snapshots = fixture.snapshots; | ||
| const normalKeys = fixture.keys.normal as Record<string, string>; | ||
| const emergencyKeys = fixture.keys.emergency as Record<string, string>; | ||
| const encoder = new TextEncoder(); | ||
| hashes.sha512 = sha512; | ||
| const crypto: ConfigCrypto = { | ||
| randomUuid: () => '550e8400-e29b-41d4-a716-446655440000', | ||
| sha256: (bytes) => Promise.resolve(sha256(bytes)), | ||
| verifyEd25519: (publicKey, signature, message) => | ||
| Promise.resolve(verify(signature, message, publicKey, { zip215: false })), | ||
| }; | ||
|
|
||
| describe('configuration contract v1 golden fixture', () => { | ||
| it('locks exact snapshot bytes, size, and SHA-256', () => { | ||
| for (const name of ['current', 'previous'] as const) { | ||
| const vector = snapshots[name]; | ||
| const document = parseIJson(encoder.encode(vector.canonicalPayload)); | ||
| assertConfigSnapshot(document); | ||
| expect(document).toEqual(vector.document); | ||
| const canonical = canonicalizeJson(document); | ||
| const bytes = encoder.encode(canonical); | ||
| expect(canonical, name).toBe(vector.canonicalPayload); | ||
| expect(encodeBase64Url(bytes), name).toBe(vector.canonicalPayloadBase64Url); | ||
| expect(bytes.byteLength, name).toBe(vector.sizeBytes); | ||
| expect(toHex(sha256(bytes)), name).toBe(vector.sha256); | ||
| } | ||
| expect(() => | ||
| assertConfigSnapshot({ ...snapshots.current.document, futureHint: 'optional' }), | ||
| ).not.toThrow(); | ||
| const openOverride: Record<string, unknown> = structuredClone(snapshots.current.document); | ||
| openOverride.overrides = [{ futureHint: 'optional', set: {}, when: { os: 'windows' } }]; | ||
| expect(() => assertConfigSnapshot(openOverride)).not.toThrow(); | ||
| }); | ||
|
|
||
| it('cross-checks snapshot metadata against the trusted pointer after raw integrity', async () => { | ||
| const bytes = decodeBase64Url(snapshots.current.canonicalPayloadBase64Url); | ||
| const pointer: unknown = pointers.normal.document; | ||
| assertConfigPointer(pointer); | ||
| const target = { brandId: 'acme', channel: 'canary', platform: 'desktop' } as const; | ||
| await expect( | ||
| validateSnapshotBytes( | ||
| bytes, | ||
| { ...pointer, configVersion: 'opaque-mismatch' }, | ||
| target, | ||
| crypto, | ||
| ), | ||
| ).rejects.toMatchObject({ code: 'schema-invalid' }); | ||
| await expect( | ||
| validateSnapshotBytes(bytes, { ...pointer, snapshotSchemaVersion: 2 }, target, crypto), | ||
| ).rejects.toMatchObject({ code: 'schema-invalid' }); | ||
| }); | ||
|
|
||
| it('verifies pointer signatures while retaining additive root fields', () => { | ||
| for (const name of [ | ||
| 'normal', | ||
| 'rollback', | ||
| 'rotationWithoutBump', | ||
| 'rotation', | ||
| 'additive', | ||
| 'schemaTooNew', | ||
| ]) { | ||
| const vector = pointers[name]; | ||
| assertConfigPointer(vector.document); | ||
| const payload = canonicalSignedPayloadBytes(vector.document); | ||
| expect(canonicalSignedPayload(vector.document), name).toBe(vector.canonicalPayload); | ||
| expect(encodeBase64Url(payload), name).toBe(vector.canonicalPayloadBase64Url); | ||
| expect(toHex(sha256(payload)), name).toBe(vector.payloadSha256); | ||
| expect( | ||
| verify( | ||
| decodeBase64Url(vector.document.sig), | ||
| payload, | ||
| decodeBase64Url(normalKeys[vector.document.keyId]), | ||
| { zip215: false }, | ||
| ), | ||
| name, | ||
| ).toBe(true); | ||
| } | ||
| expect(pointers.additive.document.futureHint).toBe('optional-and-signed'); | ||
| expect(canonicalSignedPayload(pointers.additive.document)).toContain('futureHint'); | ||
| expect(() => assertConfigPointer(pointers.unsupportedContract.document)).toThrow( | ||
| 'contractVersion', | ||
| ); | ||
| }); | ||
|
|
||
| it('verifies independent emergency signatures and rejects tampering', () => { | ||
| for (const name of ['active', 'clear', 'equivocation']) { | ||
| const vector = emergencies[name]; | ||
| assertEmergencyDocument(vector.document); | ||
| const payload = canonicalSignedPayloadBytes(vector.document); | ||
| expect( | ||
| verify( | ||
| decodeBase64Url(vector.document.sig), | ||
| payload, | ||
| decodeBase64Url(emergencyKeys[vector.document.keyId]), | ||
| { zip215: false }, | ||
| ), | ||
| ).toBe(true); | ||
| } | ||
| expect( | ||
| verify( | ||
| decodeBase64Url(emergencies.tampered.document.sig as string), | ||
| canonicalSignedPayloadBytes(emergencies.tampered.document), | ||
| decodeBase64Url(emergencyKeys['emergency-rfc8032-1']), | ||
| { zip215: false }, | ||
| ), | ||
| ).toBe(false); | ||
| }); | ||
|
|
||
| it('freezes normal and emergency anti-replay decisions', () => { | ||
| for (const entry of fixture.cases.pointerAntiReplay) { | ||
| const candidate = pointers[entry.candidate]; | ||
| const accepted = entry.accepted === null ? null : pointers[entry.accepted]; | ||
| expect( | ||
| decideAntiReplay( | ||
| replayState(candidate, 'activationVersion'), | ||
| accepted ? replayState(accepted, 'activationVersion') : null, | ||
| ), | ||
| entry.name, | ||
| ).toBe(entry.expectedDecision); | ||
| } | ||
| for (const entry of fixture.cases.emergencyAntiReplay) { | ||
| const candidate = emergencies[entry.candidate]; | ||
| const accepted = entry.accepted === null ? null : emergencies[entry.accepted]; | ||
| expect( | ||
| decideAntiReplay( | ||
| replayState(candidate, 'emergencyVersion'), | ||
| accepted ? replayState(accepted, 'emergencyVersion') : null, | ||
| ), | ||
| entry.name, | ||
| ).toBe(entry.expectedDecision); | ||
| } | ||
| expect(compareMonotonicVersions('9007199254740993', '9007199254740992')).toBeGreaterThan(0); | ||
| for (const value of fixture.cases.monotonicVersionErrors) { | ||
| expect(() => assertMonotonicVersion(value), value).toThrow('uint64'); | ||
| } | ||
| }); | ||
|
|
||
| it('applies RFC 7386 independently per atomic dotted key', () => { | ||
| const vector = fixture.cases.mergePatch; | ||
| expect(applyConfigPatch(vector.base, vector.patch)).toEqual(vector.expected); | ||
| expect(vector.expected['ui.theme.primary']).toBe('independent'); | ||
| expect(vector.expected['ui.theme']).toEqual({ | ||
| logoVariant: 'light', | ||
| nested: { add: true, keep: true }, | ||
| primary: '#1D9E75', | ||
| }); | ||
| }); | ||
|
|
||
| it('uses restricted direct SemVer precedence and closed conditions', () => { | ||
| expect(matchesVersionRange('2.4.0-beta.1', '>=2.3.0')).toBe(true); | ||
| expect(matchesVersionRange('2.4.0-beta.1', '>=2.4.0')).toBe(false); | ||
| expect(matchesVersionRange('2.4.0+build.7', '=2.4.0+other')).toBe(true); | ||
| expect(matchesVersionRange('2.4.0', '^2.3.0')).toBe(false); | ||
| expect( | ||
| conditionMatches({ locale: 'k' }, { appVersion: '2.4.0', locale: 'K', os: 'windows' }), | ||
| ).toBe(false); | ||
| for (const entry of fixture.cases.conditions) { | ||
| expect( | ||
| conditionMatches( | ||
| entry.condition as OverrideCondition, | ||
| entry.context as { | ||
| appVersion: string; | ||
| locale: string; | ||
| os: 'android' | 'ios' | 'linux' | 'macos' | 'windows'; | ||
| }, | ||
| ), | ||
| entry.name, | ||
| ).toBe(entry.expectedMatch); | ||
| } | ||
| }); | ||
|
|
||
| it('pins MurmurHash3 x86_32 UTF-8 and rollout boundaries', () => { | ||
| expect(murmur3X86_32('', 0)).toBe(0); | ||
| expect(murmur3X86_32('foo', 0)).toBe(4_138_058_784); | ||
| for (const entry of fixture.cases.rollouts) { | ||
| expect(rolloutBucket(entry.salt, entry.deviceId), entry.salt).toBe(entry.expectedBucket); | ||
| expect(rolloutMatches(entry.salt, entry.deviceId, entry.expectedBucket)).toBe( | ||
| entry.expectedHitAtBoundary, | ||
| ); | ||
| expect(rolloutMatches(entry.salt, entry.deviceId, entry.expectedBucket + 1)).toBe( | ||
| entry.expectedHitAboveBoundary, | ||
| ); | ||
| expect(rolloutMatches(entry.salt, entry.deviceId, 0)).toBe(entry.expectedHitAtZero); | ||
| expect(rolloutMatches(entry.salt, entry.deviceId, 10000)).toBe(entry.expectedHitAtFull); | ||
| } | ||
| }); | ||
|
|
||
| it('rejects cross-target documents independently of valid signatures', () => { | ||
| const pointer: unknown = pointers.normal.document; | ||
| const emergency: unknown = emergencies.active.document; | ||
| assertConfigPointer(pointer); | ||
| assertEmergencyDocument(emergency); | ||
| expect( | ||
| targetMatches(pointer, { brandId: 'acme', channel: 'canary', platform: 'desktop' }), | ||
| ).toBe(true); | ||
| expect( | ||
| targetMatches(pointer, { brandId: 'acme', channel: 'stable', platform: 'desktop' }), | ||
| ).toBe(false); | ||
| expect(emergencyTargetMatches(emergency, { brandId: 'other', platform: 'desktop' })).toBe( | ||
| false, | ||
| ); | ||
| }); | ||
|
|
||
| it('classifies malformed keys, byte lengths, and unavailable Ed25519 distinctly', async () => { | ||
| const document = pointers.normal.document; | ||
| const keyId = document.keyId as string; | ||
| const target = { brandId: 'acme', channel: 'canary', platform: 'desktop' } as const; | ||
| const rawBytes = encoder.encode(JSON.stringify(document)); | ||
| await expect( | ||
| verifyPointerBytes(rawBytes, { crypto, keyring: { [keyId]: 'not+padded=' }, target }), | ||
| ).rejects.toMatchObject({ code: 'malformed-key' }); | ||
| await expect( | ||
| verifyPointerBytes(rawBytes, { | ||
| crypto, | ||
| keyring: { [keyId]: encodeBase64Url(new Uint8Array(31)) }, | ||
| target, | ||
| }), | ||
| ).rejects.toMatchObject({ code: 'invalid-key-length' }); | ||
| await expect( | ||
| verifyPointerBytes( | ||
| encoder.encode(JSON.stringify({ ...document, sig: encodeBase64Url(new Uint8Array(63)) })), | ||
| { crypto, keyring: normalKeys, target }, | ||
| ), | ||
| ).rejects.toMatchObject({ code: 'invalid-signature-length' }); | ||
| await expect( | ||
| verifyPointerBytes(rawBytes, { | ||
| crypto: { ...crypto, verifyEd25519: () => Promise.reject(new Error('unavailable')) }, | ||
| keyring: normalKeys, | ||
| target, | ||
| }), | ||
| ).rejects.toMatchObject({ code: 'crypto-unavailable' }); | ||
| }); | ||
| }); | ||
|
|
||
| describe('I-JSON trust boundary', () => { | ||
| it.each([ | ||
| ['duplicate names', encoder.encode(String.raw`{"a":1,"\u0061":2}`)], | ||
| ['UTF-8 BOM', new Uint8Array([239, 187, 191, 123, 125])], | ||
| ['invalid UTF-8', new Uint8Array([195, 40])], | ||
| ['lone surrogate', encoder.encode(String.raw`{"value":"\ud800"}`)], | ||
| ])('rejects %s', (_name, bytes) => { | ||
| expect(() => parseIJson(bytes)).toThrow(); | ||
| }); | ||
|
|
||
| it('rejects non-integer signed-envelope extensions', () => { | ||
| expect(() => | ||
| canonicalSignedPayload({ ...pointers.normal.document, futureNumber: 1.5 }), | ||
| ).toThrow('safe integers'); | ||
| }); | ||
| }); | ||
|
|
||
| function replayState( | ||
| vector: SignedVector, | ||
| field: 'activationVersion' | 'emergencyVersion', | ||
| ): AntiReplayState { | ||
| return { | ||
| payloadSha256: vector.payloadSha256, | ||
| version: vector.document[field] as string, | ||
| }; | ||
| } | ||
|
|
||
| function toHex(bytes: Uint8Array): string { | ||
| return Array.from(bytes, (byte) => byte.toString(16).padStart(2, '0')).join(''); | ||
| } |
Oops, something went wrong.
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This commit introduces 3,103 lines even after excluding the golden fixture, spanning the contract, parser, persistence, state machine, and tests. That exceeds the repository's 400-line hard limit by several times and prevents the required atomic review history; split these concerns into independently compilable commits.
AGENTS.md reference: AGENTS.md:L48-L48
Useful? React with 👍 / 👎.