Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

SqlEventLogServerEncrypted.test.ts

249 lines10.4 KB

1import { SqliteClient } from "@effect/sql-sqlite-node"
2import { assert, describe, it } from "@effect/vitest"
3import { Effect, Layer, Queue, Redacted, Stream } from "effect"
4import * as EventJournal from "effect/unstable/eventlog/EventJournal"
5import * as EventLog from "effect/unstable/eventlog/EventLog"
6import * as EventLogEncryption from "effect/unstable/eventlog/EventLogEncryption"
7import * as EventLogMessage from "effect/unstable/eventlog/EventLogMessage"
8import type { StoreId } from "effect/unstable/eventlog/EventLogMessage"
9import * as EventLogServer from "effect/unstable/eventlog/EventLogServerEncrypted"
10import * as EventLogSessionAuth from "effect/unstable/eventlog/EventLogSessionAuth"
11import { makeGetIdentityRootSecretMaterial } from "effect/unstable/eventlog/internal/identityRootSecretDerivation"
12import * as SqlEventLogServer from "effect/unstable/eventlog/SqlEventLogServerEncrypted"
13import { Reactivity } from "effect/unstable/reactivity"
14import * as RpcTest from "effect/unstable/rpc/RpcTest"
15import * as SqlClient from "effect/unstable/sql/SqlClient"
16​
17const storeIdA = "store-a" as StoreId
18const storeIdB = "store-b" as StoreId
19​
20const makeEntry = (value: number) =>
21 new EventJournal.Entry({
22 id: EventJournal.makeEntryIdUnsafe(),
23 event: "UserCreated",
24 primaryKey: `user-${value}`,
25 payload: new Uint8Array([value])
26 }, { disableChecks: true })
27​
28const persistEntries = (
29 encryption: EventLogEncryption.EventLogEncryption["Service"],
30 identity: EventLog.Identity["Service"],
31 entries: ReadonlyArray<EventJournal.Entry>
32) =>
33 Effect.gen(function*() {
34 const encrypted = yield* encryption.encrypt(identity, entries)
35 return encrypted.encryptedEntries.map((encryptedEntry, index) =>
36 new EventLogServer.PersistedEntry({
37 entryId: entries[index].id,
38 iv: encrypted.iv,
39 encryptedEntry
40 })
41 )
42 })
43​
44const makePersistedEntry = (index: number, entryId = EventJournal.makeEntryIdUnsafe()) =>
45 new EventLogServer.PersistedEntry({
46 entryId,
47 iv: new Uint8Array(12),
48 encryptedEntry: Uint8Array.of(index)
49 })
50​
51const getIdentityRootSecretMaterial = makeGetIdentityRootSecretMaterial(globalThis.crypto)
52​
53const makeAuthenticateRequest = Effect.fnUntraced(function*(options: {
54 readonly identity: EventLog.Identity["Service"]
55 readonly challenge: Uint8Array
56 readonly remoteId: EventJournal.RemoteId
57}) {
58 const rootSecretMaterial = yield* getIdentityRootSecretMaterial(options.identity)
59 const signature = yield* EventLogSessionAuth.signSessionAuthPayload({
60 remoteId: options.remoteId,
61 challenge: options.challenge,
62 publicKey: options.identity.publicKey,
63 signingPublicKey: rootSecretMaterial.signingPublicKey,
64 signingPrivateKey: Redacted.value(rootSecretMaterial.signingPrivateKey)
65 })
66 return new EventLogMessage.Authenticate({
67 publicKey: options.identity.publicKey,
68 signingPublicKey: rootSecretMaterial.signingPublicKey,
69 signature,
70 algorithm: "Ed25519"
71 })
72})
73​
74describe("SqlEventLogServer", () => {
75 it.effect("persists remote id across storage instances", () =>
76 Effect.gen(function*() {
77 const sql = yield* SqliteClient.make({ filename: ":memory:" })
78 const storageA = yield* SqlEventLogServer.makeStorage().pipe(
79 Effect.provideService(SqlClient.SqlClient, sql)
80 )
81 const storageB = yield* SqlEventLogServer.makeStorage().pipe(
82 Effect.provideService(SqlClient.SqlClient, sql)
83 )
84 const idA = yield* storageA.getId
85 const idB = yield* storageB.getId
86 assert.deepStrictEqual(idA, idB)
87 }).pipe(Effect.provide([Reactivity.layer, EventLogEncryption.layerSubtle])))
88​
89 it.effect("rejects session-auth rebinding for an existing publicKey", () =>
90 Effect.gen(function*() {
91 const sql = yield* SqliteClient.make({ filename: ":memory:" })
92 const storage = yield* SqlEventLogServer.makeStorage().pipe(
93 Effect.provideService(SqlClient.SqlClient, sql)
94 )
95 const rpcClient = yield* RpcTest.makeClient(EventLogMessage.EventLogRemoteRpcs).pipe(
96 Effect.provide(
97 EventLogServer.layerRpcHandlers.pipe(
98 Layer.provide(Layer.succeed(EventLogServer.Storage, storage))
99 )
100 )
101 )
102​
103 const firstIdentity = yield* EventLog.makeIdentity
104 const secondIdentitySeed = yield* EventLog.makeIdentity
105 const secondIdentity: EventLog.Identity["Service"] = {
106 publicKey: firstIdentity.publicKey,
107 privateKey: secondIdentitySeed.privateKey
108 }
109​
110 const firstMaterial = yield* getIdentityRootSecretMaterial(firstIdentity)
111 const secondMaterial = yield* getIdentityRootSecretMaterial(secondIdentity)
112 const sameSigningPublicKey =
113 firstMaterial.signingPublicKey.byteLength === secondMaterial.signingPublicKey.byteLength &&
114 firstMaterial.signingPublicKey.every((byte, index) => byte === secondMaterial.signingPublicKey[index])
115 assert.strictEqual(sameSigningPublicKey, false)
116​
117 const firstHello = yield* rpcClient["EventLog.Hello"]()
118 yield* rpcClient["EventLog.Authenticate"](
119 yield* makeAuthenticateRequest({
120 identity: firstIdentity,
121 challenge: firstHello.challenge,
122 remoteId: firstHello.remoteId
123 })
124 )
125​
126 const secondHello = yield* rpcClient["EventLog.Hello"]()
127 const error = yield* rpcClient["EventLog.Authenticate"](
128 yield* makeAuthenticateRequest({
129 identity: secondIdentity,
130 challenge: secondHello.challenge,
131 remoteId: secondHello.remoteId
132 })
133 ).pipe(Effect.flip)
134​
135 assert.instanceOf(error, EventLogMessage.EventLogProtocolError)
136 assert.strictEqual(error.code, "Forbidden")
137 assert.strictEqual(error.message, "Session auth signature verification failed")
138 }).pipe(Effect.provide([Reactivity.layer, EventLogEncryption.layerSubtle])))
139​
140 it.effect("writes entries and streams changes", () =>
141 Effect.gen(function*() {
142 const sql = yield* SqliteClient.make({ filename: ":memory:" })
143 const storage = yield* SqlEventLogServer.makeStorage().pipe(
144 Effect.provideService(SqlClient.SqlClient, sql)
145 )
146 const encryption = yield* EventLogEncryption.EventLogEncryption
147 const identity = yield* encryption.generateIdentity
148 const entries = [makeEntry(1), makeEntry(2)]
149 const persisted = yield* persistEntries(encryption, identity, entries)
150 const written = yield* storage.write(identity.publicKey, storeIdA, persisted)
151 assert.deepStrictEqual(written.map((entry) => entry.sequence), [1, 2])
152​
153 const changes = yield* storage.changes(identity.publicKey, storeIdA, 0).pipe(
154 Stream.toQueue({ capacity: "unbounded" })
155 )
156 const taken = yield* Queue.takeAll(changes)
157 assert.deepStrictEqual(taken.map((entry) => entry.sequence), [1, 2])
158​
159 const nextEntry = makeEntry(3)
160 const nextPersisted = yield* persistEntries(encryption, identity, [nextEntry])
161 const updated = yield* storage.write(identity.publicKey, storeIdA, nextPersisted)
162 assert.deepStrictEqual(updated.map((entry) => entry.sequence), [3])
163​
164 const next = yield* Queue.take(changes)
165 assert.strictEqual(next.sequence, 3)
166 }).pipe(Effect.provide([Reactivity.layer, EventLogEncryption.layerSubtle])))
167​
168 it.effect("isolates same publicKey across storeIds", () =>
169 Effect.gen(function*() {
170 const sql = yield* SqliteClient.make({ filename: ":memory:" })
171 const storage = yield* SqlEventLogServer.makeStorage().pipe(
172 Effect.provideService(SqlClient.SqlClient, sql)
173 )
174​
175 yield* storage.write("client-1", storeIdA, [makePersistedEntry(1)])
176 yield* storage.write("client-1", storeIdB, [makePersistedEntry(2)])
177​
178 const storeAEntries = yield* storage.changes("client-1", storeIdA, 0).pipe(
179 Stream.take(1),
180 Stream.runCollect
181 )
182 const storeBEntries = yield* storage.changes("client-1", storeIdB, 0).pipe(
183 Stream.take(1),
184 Stream.runCollect
185 )
186​
187 assert.deepStrictEqual(storeAEntries.map((entry) => entry.sequence), [1])
188 assert.deepStrictEqual(storeBEntries.map((entry) => entry.sequence), [1])
189 }).pipe(Effect.provide([Reactivity.layer, EventLogEncryption.layerSubtle])))
190​
191 it.effect("isolates same storeId across publicKeys", () =>
192 Effect.gen(function*() {
193 const sql = yield* SqliteClient.make({ filename: ":memory:" })
194 const storage = yield* SqlEventLogServer.makeStorage().pipe(
195 Effect.provideService(SqlClient.SqlClient, sql)
196 )
197​
198 yield* storage.write("client-1", storeIdA, [makePersistedEntry(1)])
199 yield* storage.write("client-2", storeIdA, [makePersistedEntry(2)])
200​
201 const clientOneEntries = yield* storage.changes("client-1", storeIdA, 0).pipe(
202 Stream.take(1),
203 Stream.runCollect
204 )
205 const clientTwoEntries = yield* storage.changes("client-2", storeIdA, 0).pipe(
206 Stream.take(1),
207 Stream.runCollect
208 )
209​
210 assert.deepStrictEqual(clientOneEntries.map((entry) => entry.sequence), [1])
211 assert.deepStrictEqual(clientTwoEntries.map((entry) => entry.sequence), [1])
212 }).pipe(Effect.provide([Reactivity.layer, EventLogEncryption.layerSubtle])))
213​
214 it.effect("keeps deduplication isolated per encrypted scope", () =>
215 Effect.gen(function*() {
216 const sql = yield* SqliteClient.make({ filename: ":memory:" })
217 const storage = yield* SqlEventLogServer.makeStorage().pipe(
218 Effect.provideService(SqlClient.SqlClient, sql)
219 )
220 const sharedEntryId = EventJournal.makeEntryIdUnsafe()
221​
222 yield* storage.write("client-1", storeIdA, [makePersistedEntry(1, sharedEntryId)])
223 yield* storage.write("client-1", storeIdA, [makePersistedEntry(2, sharedEntryId)])
224 yield* storage.write("client-1", storeIdB, [makePersistedEntry(3, sharedEntryId)])
225 yield* storage.write("client-2", storeIdA, [makePersistedEntry(4, sharedEntryId)])
226​
227 assert.deepStrictEqual(
228 (yield* storage.changes("client-1", storeIdA, 0).pipe(
229 Stream.take(1),
230 Stream.runCollect
231 )).map((entry) => entry.sequence),
232 [1]
233 )
234 assert.deepStrictEqual(
235 (yield* storage.changes("client-1", storeIdB, 0).pipe(
236 Stream.take(1),
237 Stream.runCollect
238 )).map((entry) => entry.sequence),
239 [1]
240 )
241 assert.deepStrictEqual(
242 (yield* storage.changes("client-2", storeIdA, 0).pipe(
243 Stream.take(1),
244 Stream.runCollect
245 )).map((entry) => entry.sequence),
246 [1]
247 )
248 }).pipe(Effect.provide([Reactivity.layer, EventLogEncryption.layerSubtle])))
249})