vault.test.ts
This file
Path
packages/visibility/test/vault.test.ts
310 lines · 9.2 KiB · TypeScript
Last changed by
Merge build/maintainer-wording into mainoscabrielbefore adoption4c1a571
History of this fileTake it
The walk stopped after 200 commits: lines older than 678c8b8 point at it.
Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8
lines 1–8why, one step back1import { describe, expect, it } from "@effect/vitest";2import { Brand } from "@repo/brand";3import { EnvKey } from "@repo/protocol/ids";4import { Refusal, ValueTooShort } from "@repo/protocol/refusal";5import {6 Cause,7 Effect,8 Exit,Merge build/1007oscabrielbefore adoption77fa97a
line 9why, one step back9 Layer,Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8
lines 10–141why, one step back10 Option,11 Predicate,12 Redacted,13 Result,14 Schema,15} from "effect";1617import {18 SealedValue,19 SealedValueUnopenable,20 WriteOnlyValues,21} from "../src/vault.ts";22import { WriteOnlyValuesWebCrypto } from "../src/vault/webcrypto.ts";2324const masterKey = WriteOnlyValuesWebCrypto(25 Redacted.make(26 "00112233445566778899aabbccddeeff00112233445566778899AABBCCDDEEFF"27 )28);2930const otherMasterKey = WriteOnlyValuesWebCrypto(31 Redacted.make(32 "ffeeddccbbaa99887766554433221100ffeeddccbbaa99887766554433221100"33 )34);3536const key = EnvKey.make("SENTRY_AUTH_TOKEN");3738const token = "sntrys_eyJpYXQiOjE3MjA";3940const put = (value: string, acknowledgeShort = false) =>41 WriteOnlyValues.use((values) =>42 values.put({ acknowledgeShort, key, value: Redacted.make(value) })43 );4445const open = (sealed: SealedValue) =>46 WriteOnlyValues.use((values) => values.open(sealed)).pipe(47 Effect.map((value) => Redacted.value(value))48 );4950const tampered = (51 sealed: SealedValue,52 field: "ciphertext" | "iv" | "wrappedKey"53): SealedValue => {54 const bytes = Schema.decodeSync(Schema.Uint8ArrayFromBase64)(sealed[field]);5556 return {57 ...sealed,58 [field]: Schema.encodeSync(Schema.Uint8ArrayFromBase64)(59 bytes.map((byte, index) => (index === 0 ? (byte + 1) % 256 : byte))60 ),61 };62};6364const base64 = Schema.encodeSync(Schema.StringFromBase64);6566const refusalOf = <A, E, R>(effect: Effect.Effect<A, E, R>) =>67 Effect.result(effect).pipe(Effect.map(Result.getFailure));6869const defectOf = <A, E>(exit: Exit.Exit<A, E>) =>70 Exit.isFailure(exit) ? Cause.squash(exit.cause) : undefined;7172describe("write-only values over WebCrypto", () => {73 it.effect("opens what it sealed", () =>74 Effect.gen(function* () {75 const sealed = yield* put(token);7677 expect(sealed.keyVersion).toBe(1);78 expect(yield* open(sealed)).toBe(token);79 }).pipe(Effect.provide(masterKey))80 );8182 it.effect(83 "opens a value byte for byte: trailing NULs, a leading BOM, a long one",84 () =>85 Effect.gen(function* () {86 const odd = [87 `${token}\u0000\u0000`,88 `${token}`,89 "-----BEGIN PRIVATE KEY-----\n".padEnd(1700, "A"),90 ];9192 const opened = yield* Effect.forEach(odd, (value) =>93 put(value).pipe(Effect.flatMap(open))94 );9596 expect(opened).toStrictEqual(odd);97 }).pipe(Effect.provide(masterKey))98 );99100 it.effect("seals the same value twice under fresh data keys and IVs", () =>101 Effect.gen(function* () {102 const first = yield* put(token);103 const second = yield* put(token);104105 expect(second.ciphertext).not.toBe(first.ciphertext);106 expect(second.wrappedKey).not.toBe(first.wrappedKey);107 expect(second.iv).not.toBe(first.iv);108 expect(yield* open(second)).toBe(token);109 }).pipe(Effect.provide(masterKey))110 );111112 it.effect(113 "will not start on a master key that is not 32 bytes of hex, and never says the key",114 () =>115 Effect.gen(function* () {116 const shortKey = "00112233445566778899aabbccddeeff0011223344556677";117 const notHex = "zz".repeat(32);118119 const defects = yield* Effect.forEach([shortKey, notHex], (text) =>120 Effect.exit(121 put(token).pipe(122 Effect.provide(WriteOnlyValuesWebCrypto(Redacted.make(text)))123 )124 ).pipe(125 Effect.map((exit) => {126 const defect = defectOf(exit);127128 return [129 Predicate.isTagged(defect, "MasterKeyUnusable"),130 JSON.stringify(defect).includes(text),131 ];132 })133 )134 );135136 expect(defects).toStrictEqual([137 [true, false],138 [true, false],139 ]);140 })141 );Merge build/1007oscabrielbefore adoption77fa97a
lines 142–153why, one step back142143 it("is built at once, awaiting nothing: the master key is imported per call", () => {144 // The platform builds its router at module load and refuses a build145 // that awaits (`router-build.ts`), so the vault's layer must build synchronously.146 const built = Effect.runSyncExit(147 Layer.build(masterKey).pipe(Effect.scoped)148 );149150 expect(Exit.isFailure(built) ? Cause.pretty(built.cause) : "built").toBe(151 "built"152 );153 });Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8
lines 154–203why, one step back154155 it.effect("does not open a value under another master key", () =>156 Effect.gen(function* () {157 const sealed = yield* put(token).pipe(Effect.provide(masterKey));158159 const exit = yield* Effect.exit(160 open(sealed).pipe(Effect.provide(otherMasterKey))161 );162163 expect(defectOf(exit)).toStrictEqual(164 new SealedValueUnopenable({ step: "unwrap" })165 );166 })167 );168169 it.effect(170 "does not open a value with a byte changed in any of its fields",171 () =>172 Effect.gen(function* () {173 const sealed = yield* put(token);174175 const steps = yield* Effect.forEach(176 ["ciphertext", "iv", "wrappedKey"] as const,177 (field) =>178 Effect.exit(open(tampered(sealed, field))).pipe(179 Effect.map(defectOf)180 )181 );182183 expect(steps).toStrictEqual([184 new SealedValueUnopenable({ step: "decrypt" }),185 new SealedValueUnopenable({ step: "decrypt" }),186 new SealedValueUnopenable({ step: "unwrap" }),187 ]);188 }).pipe(Effect.provide(masterKey))189 );190191 it.effect("does not open a value sealed under a key version it lacks", () =>192 Effect.gen(function* () {193 const sealed = yield* put(token);194195 const exit = yield* Effect.exit(open({ ...sealed, keyVersion: 2 }));196197 expect(defectOf(exit)).toStrictEqual(198 new SealedValueUnopenable({ step: "keyVersion" })199 );200 }).pipe(Effect.provide(masterKey))201 );202203 it.effect(Merge build/maintainer-wording into mainoscabrielbefore adoption4c1a571
line 204why, one step back204 "refuses an 11-character value unless the maintainer acknowledges it",Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8
lines 205–310why, one step back205 () =>206 Effect.gen(function* () {207 const short = "abcdefghijk";208209 expect(yield* refusalOf(put(short))).toStrictEqual(210 Option.some(ValueTooShort.of(key, 12))211 );212 expect(yield* open(yield* put(short, true))).toBe(short);213 }).pipe(Effect.provide(masterKey))214 );215216 it.effect(217 "refuses a 2-character value even acknowledged, and says to set a longer one",218 () =>219 Effect.gen(function* () {220 expect(yield* refusalOf(put("ab", true))).toStrictEqual(221 Option.some(222 new ValueTooShort({223 key,224 minimum: 3,225 next: `${Brand.cli} env set SENTRY_AUTH_TOKEN`,226 })227 )228 );229 expect(yield* open(yield* put("abc", true))).toBe("abc");230 }).pipe(Effect.provide(masterKey))231 );232233 it.effect("counts an emoji as one character", () =>234 Effect.gen(function* () {235 // Eleven characters in 22 UTF-16 units.236 const emoji = "🔑".repeat(11);237238 expect(yield* refusalOf(put(emoji))).toStrictEqual(239 Option.some(ValueTooShort.of(key, 12))240 );241 expect(yield* open(yield* put(`${emoji}x`))).toBe(`${emoji}x`);242 }).pipe(Effect.provide(masterKey))243 );244245 it.effect("keeps neither the value nor its length in what it seals", () =>246 Effect.gen(function* () {247 const twelve = "x7Kq2mVp9Lw4";248 const forty = "Zr8nT3vQ6yHc1Pw5Ks9Ld2Fg7Jb4Mx0Ae6Nu3Wt8";249 const sealing = [twelve, forty, token];250251 const sealed = yield* Effect.forEach(sealing, (value) =>252 put(value).pipe(253 Effect.flatMap(Schema.encodeEffect(SealedValue)),254 Effect.map((encoded) => JSON.stringify(encoded))255 )256 );257258 expect(259 sealed.filter(260 (json, index) =>261 json.includes(sealing[index] ?? "") ||262 json.includes(base64(sealing[index] ?? ""))263 )264 ).toStrictEqual([]);265 // Values of 12, 40 and 22 characters seal to the same size: the266 // ciphertext's length says nothing about the value's.267 expect(new Set(sealed.map(({ length }) => length)).size).toBe(1);268 }).pipe(Effect.provide(masterKey))269 );270271 it.effect("refuses, and fails to open, without the value or its length", () =>272 Effect.gen(function* () {273 const short = [274 { acknowledged: false, value: "abcdefghijk" },275 { acknowledged: true, value: "q7" },276 ];277278 const refusals = yield* Effect.forEach(short, ({ acknowledged, value }) =>279 Effect.flip(put(value, acknowledged)).pipe(280 Effect.flatMap(Schema.encodeEffect(Refusal)),281 Effect.map((encoded) => JSON.stringify(encoded))282 )283 );284285 const exit = yield* Effect.exit(286 open(tampered(yield* put(token), "ciphertext"))287 );288289 const defect = yield* Schema.encodeUnknownEffect(SealedValueUnopenable)(290 defectOf(exit)291 ).pipe(Effect.map((encoded) => JSON.stringify(encoded)));292293 expect(refusals).toStrictEqual([294 expect.stringContaining('"minimum":12'),295 expect.stringContaining('"minimum":3'),296 ]);297 expect(298 [...refusals, defect].map((json, index) => {299 const { value } = short[index] ?? { value: token };300301 return [json.includes(value), json.includes(String(value.length))];302 })303 ).toStrictEqual([304 [false, false],305 [false, false],306 [false, false],307 ]);308 }).pipe(Effect.provide(masterKey))309 );310});