Skip to content

Commit

Permalink
feat: Add CSRs store and validation
Browse files Browse the repository at this point in the history
  • Loading branch information
vinkabuki committed Nov 15, 2023
1 parent 032585e commit 1107847
Show file tree
Hide file tree
Showing 6 changed files with 299 additions and 209 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import Logger from '../common/logger'
import { load } from 'mock-fs'

const logger = Logger('registration.functions')
class UserCsrData {
export class UserCsrData {
@IsNotEmpty()
@IsBase64()
@IsCsr()
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
describe('CertificatesRequestsStore csr validation methods', () => {
it('validateUserCsr')
it('validateCsrFormat')
})

// it('getCsrs - remove old csrs and replace with new for each pubkey', async () => {
// await storageService.init(peerId)
// const allCsrs = [
// 'MIIDITCCAsYCAQAwSTFHMEUGA1UEAxM+anR3c3hxMnZ1dWthY3JodWhvdnAzd2JxbzRxNXc0d2s3Nm1qbWJ3cXk3eGNma2FsdmRxb3hhYWQub25pb24wWTATBgcqhkjOPQIBBggqhkjOPQMBBwNCAAQE2q6iS+WCmIVCSFI2AjHrW6ujUdrceD5T2xkcTJBTn0y50WphcupUajCRgkXaTBkTsGNJ3qWRZAKX7CiuehBJoIICGTAuBgkqhkiG9w0BCQ4xITAfMB0GA1UdDgQWBBQuE5JgPY/BYBpgG5pnjMkEEIkrGjCCAUcGCSqGSIb3DQEJDDGCATgEggE0BDlx84glBl72q82F2a+y8iTVKM8IMiXYYrmNyhFPj6XsfVQpvLhNviZ5zHdMBWbFj44vTSUIasNP9I9eCWSEAaEJqjngEh18WCRS/XbvQxI/8qB5pzcfghvM8BCgSLbSEjK2GMYVhCXmRH1YGHIZu0+Ii9pe5nwG154JlPUsmIRgu6ruY6PQk65Aoo4OyhPn5CCUFInptHcz1JpAiCRe0Z6wuQHud03VY50fx4ETdmUNJBEIPOyd/Xn6lMOi6SaWGHbCWiufeJRm+mRdoHJAEt6kPLhGIYGyduNT/8cGoe2xKyQDvNoTr4dqqRZ2HgZ18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dSP9iNY+9T26yxGKBM6ah0KHxTY5rODLV29+ll/+wftIGsixYNJoo5HUEmZnWRSPVKri50scOJAI4C6l9HJfNgEBoNFEwFgYKKwYBBAGDjBsCATEIEwZrYWNwZXIwPQYJKwYBAgEPAwEBMTATLlFtY01LdlpWNWJZcEZ4eW9TRFlUcE1RY2VBdnRDa2taZnQ2TlRDVVB0VVAyTXkwRwYDVR0RMUATPnU3bmtoMjRwb210bDc1b2FhYm13eXRrdHUzYzZseGlvbmdiM2JtY2prbmVwZmVhdzJpNmR3ZGFkLm9uaW9uMAoGCCqGSM49BAMCA0gAMEUCIFsTfZsGWX3g44QnEksCh0naujBG60DuNNh83YHcl12FAiEAm9qALhC6ctx9JvakesWQhtDT4WFAGyEkuIB5Xtw68eg=',
// ]

// const mockGetAllEventLogEntries = jest.fn()
// // @ts-ignore - Property 'getAllEventLogEntries' is protected
// storageService.getAllEventLogEntries = mockGetAllEventLogEntries
// mockGetAllEventLogEntries.mockReturnValue(allCsrs)

// const filteredCsrs = await storageService.getCsrs()

// expect(filteredCsrs.length).toEqual(allCsrs.length - 1)

// expect(filteredCsrs).toEqual([
// 'MIIDITCCAsYCAQAwSTFHMEUGA1UEAxM+anR3c3hxMnZ1dWthY3JodWhvdnAzd2JxbzRxNXc0d2s3Nm1qbWJ3cXk3eGNma2FsdmRxb3hhYWQub25pb24wWTATBgcqhkjOPQIBBggqhkjOPQMBBwNCAAQE2q6iS+WCmIVCSFI2AjHrW6ujUdrceD5T2xkcTJBTn0y50WphcupUajCRgkXaTBkTsGNJ3qWRZAKX7CiuehBJoIICGTAuBgkqhkiG9w0BCQ4xITAfMB0GA1UdDgQWBBQuE5JgPY/BYBpgG5pnjMkEEIkrGjCCAUcGCSqGSIb3DQEJDDGCATgEggE0BDlx84glBl72q82F2a+y8iTVKM8IMiXYYrmNyhFPj6XsfVQpvLhNviZ5zHdMBWbFj44vTSUIasNP9I9eCWSEAaEJqjngEh18WCRS/XbvQxI/8qB5pzcfghvM8BCgS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lSsDfd702Ter0uNJToSbm7X1NlYm/WXCtLeUEsXOV1G0kOcv2uthpaV7NSlWd4jtRDHidLrd/X/iJWHMsmi4KyLM/p7dCGEqk24aobLfJA9cYN540Q0Sp93tJAXw3Y3Gh5CUwItNolhMk/rVpS3niKIpxjMk2OtLrV0epBKhMVV7jDqKsxZX9I0gDMNTRdixIEXbKHacVY4dSP9iNY+9T26yxGKBM6ah0KHxTY5rODLV29+ll/+wftIGsixYNJoo5HUEmZnWRSPVKri50scOJAI4C6l9HJfNgEBoNFEwFgYKKwYBBAGDjBsCATEIEwZrYWNwZXIwPQYJKwYBAgEPAwEBMTATLlFtY01LdlpWNWJZcEZ4eW9TRFlUcE1RY2VBdnRDa2taZnQ2TlRDVVB0VVAyTXkwRwYDVR0RMUATPnU3bmtoMjRwb210bDc1b2FhYm13eXRrdHUzYzZseGlvbmdiM2JtY2prbmVwZmVhdzJpNmR3ZGFkLm9uaW9uMAoGCCqGSM49BAMCA0gAMEUCIFsTfZsGWX3g44QnEksCh0naujBG60DuNNh83YHcl12FAiEAm9qALhC6ctx9JvakesWQhtDT4WFAGyEkuIB5Xtw68eg=',
// ])
// })

// describe('replicate certificatesRequests event', () => {
// const replicatedEvent = async () => {
// certificatesRequestsStore.events.emit('replicated')
// await new Promise<void>(resolve => setTimeout(() => resolve(), 2000))
// }

// it('replicated event ', async () => {
// await storageService.init(peerId)
// const spyOnUpdatePeersList = jest.spyOn(storageService, 'updatePeersList')
// await replicatedEvent()
// expect(spyOnUpdatePeersList).toBeCalledTimes(1)
// })

// it('2 replicated events - first not resolved ', async () => {
// await storageService.init(peerId)
// const spyOnUpdatePeersList = jest.spyOn(storageService, 'updatePeersList')
// await replicatedEvent()
// await replicatedEvent()
// expect(spyOnUpdatePeersList).toBeCalledTimes(1)
// })

// it('2 replicated events - first resolved ', async () => {
// await storageService.init(peerId)
// const spyOnUpdatePeersList = jest.spyOn(storageService, 'updatePeersList')
// await replicatedEvent()
// await replicatedEvent()
// storageService.resolveCsrReplicatedPromise(1)
// await new Promise<void>(resolve => setTimeout(() => resolve(), 500))
// expect(spyOnUpdatePeersList).toBeCalledTimes(2)
// })

// it('3 replicated events - no resolved promises', async () => {
// await storageService.init(peerId)
// const spyOnUpdatePeersList = jest.spyOn(storageService, 'updatePeersList')

// await replicatedEvent()
// await replicatedEvent()
// await replicatedEvent()

// expect(spyOnUpdatePeersList).toBeCalledTimes(1)
// })

// it('3 replicated events - two resolved promises ', async () => {
// await storageService.init(peerId)
// const spyOnUpdatePeersList = jest.spyOn(storageService, 'updatePeersList')

// await replicatedEvent()
// await replicatedEvent()
// storageService.resolveCsrReplicatedPromise(1)
// await new Promise<void>(resolve => setTimeout(() => resolve(), 500))
// await replicatedEvent()
// storageService.resolveCsrReplicatedPromise(2)
// await new Promise<void>(resolve => setTimeout(() => resolve(), 500))

// expect(spyOnUpdatePeersList).toBeCalledTimes(3)
// })
// })
169 changes: 169 additions & 0 deletions packages/backend/src/nest/storage/certificatesRequestsStore.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,169 @@
import { getCrypto } from 'pkijs'
import { EventEmitter } from 'events'
import EventStore from 'orbit-db-eventstore'
import OrbitDB from 'orbit-db'

import { NoCryptoEngineError } from '@quiet/types'
import { loadCSR, keyFromCertificate } from '@quiet/identity'

import { StorageEvents } from './storage.types'
import createLogger from '../common/logger'

import { validate } from 'class-validator'
import { UserCsrData } from '../registration/registration.functions'

const logger = createLogger('CertificatesRequestsStore')

interface CsrReplicatedPromiseValues {
promise: Promise<unknown>
resolveFunction: any
}

export class CertificatesRequestsStore {
public orbitDb: OrbitDB
public store: EventStore<string>
public csrReplicatedPromiseMap: Map<number, CsrReplicatedPromiseValues> = new Map()
private csrReplicatedPromiseId: number = 0

constructor(orbitDb: OrbitDB) {
this.orbitDb = orbitDb
}

public async init(emitter: EventEmitter) {
logger('Initializing...')
this.store = await this.orbitDb.log<string>('csrs', {
replicate: false,
accessController: {
write: ['*'],
},
})

this.store.events.on('write', async (_address, entry) => {
logger('Added CSR to database')
emitter.emit(StorageEvents.LOADED_USER_CSRS, {
csrs: await this.getCsrs(),
id: this.csrReplicatedPromiseId,
})
})

this.store.events.on('replicated', async () => {
logger('Replicated CSRS')
// @ts-expect-error - OrbitDB's type declaration of `load` lacks 'options'
await this.store.load({ fetchEntryTimeout: 15000 })

this.csrReplicatedPromiseId++
const filteredCsrs = await this.getCsrs()
this.createCsrReplicatedPromise(this.csrReplicatedPromiseId)

// Lock replicated event until previous event is processed by registration service
if (this.csrReplicatedPromiseId > 1) {
const csrReplicatedPromiseMapId = this.csrReplicatedPromiseMap.get(this.csrReplicatedPromiseId - 1)

if (csrReplicatedPromiseMapId?.promise) {
await csrReplicatedPromiseMapId.promise
}
}

emitter.emit(StorageEvents.LOADED_USER_CSRS, {
csrs: filteredCsrs,
id: this.csrReplicatedPromiseId,
})
})

// @ts-expect-error - OrbitDB's type declaration of `load` lacks 'options'
await this.store.load({ fetchEntryTimeout: 15000 })
emitter.emit(StorageEvents.LOADED_USER_CSRS, {
csrs: await this.getCsrs(),
id: this.csrReplicatedPromiseId,
})
logger('Initialized')
}

public async close() {
logger('Closing...')
await this.store?.close()
logger('Closed')
}

public getAddress() {
return this.store?.address
}

public resetCsrReplicatedMapAndId() {
this.csrReplicatedPromiseMap = new Map()
this.csrReplicatedPromiseId = 0
}

private createCsrReplicatedPromise(id: number) {
let resolveFunction
const promise = new Promise(resolve => {
resolveFunction = resolve
})
this.csrReplicatedPromiseMap.set(id, { promise, resolveFunction })
}

public resolveCsrReplicatedPromise(id: number) {
const csrReplicatedPromiseMapId = this.csrReplicatedPromiseMap.get(id)
if (csrReplicatedPromiseMapId) {
csrReplicatedPromiseMapId?.resolveFunction(id)
this.csrReplicatedPromiseMap.delete(id)
} else {
logger.error(`No promise with ID ${id} found.`)
return
}
}

public async addUserCsr(csr: string) {
await this.store.add(csr)
return true
}

public static async validateUserCsr(csr: string) {
try {
const crypto = getCrypto()
if (!crypto) {
throw new NoCryptoEngineError()
}
const parsedCsr = await loadCSR(csr)
await parsedCsr.verify()
await this.validateCsrFormat(csr)
} catch (err) {
logger.error('Failed to validate user csr:', csr, err?.message)
return false
}
return true
}

public static async validateCsrFormat(csr: string) {
const userData = new UserCsrData()
userData.csr = csr
const validationErrors = await validate(userData)
return validationErrors
}

protected async getCsrs() {
const filteredCsrsMap: Map<string, string> = new Map()

const allCsrs = this.store
.iterator({ limit: -1 })
.collect()
.map(e => e.payload.value)
await Promise.all(
allCsrs.filter(async csr => {
// const parsedCsr = await loadCSR(csr)
const validation = await CertificatesRequestsStore.validateUserCsr(csr)
if (validation) return true
return false
}).map(async csr => {
const parsedCsr = await loadCSR(csr)
const pubKey = keyFromCertificate(parsedCsr)

if (filteredCsrsMap.has(pubKey)) {
filteredCsrsMap.delete(pubKey)
}
filteredCsrsMap.set(pubKey, csr)
})
)
return [...filteredCsrsMap.values()]
}
}
Loading

0 comments on commit 1107847

Please sign in to comment.