Skip to content

Commit

Permalink
Fix the duplicated/unregistered bug
Browse files Browse the repository at this point in the history
  • Loading branch information
islathehut committed Nov 4, 2024
1 parent be5c80c commit 968c249
Show file tree
Hide file tree
Showing 6 changed files with 33 additions and 21 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -451,7 +451,7 @@ export class ConnectionsManagerService extends EventEmitter implements OnModuleI
const existingKeyPair: CryptoKeyPair = { privateKey, publicKey }

createUserCsrPayload = {
nickname: nickname,
nickname,
commonName: identity.hiddenService.onionAddress,
peerId: identity.peerId.id,
signAlg: config.signAlg,
Expand All @@ -461,7 +461,7 @@ export class ConnectionsManagerService extends EventEmitter implements OnModuleI
} else {
this.logger.info('Creating new user CSR')
createUserCsrPayload = {
nickname: nickname,
nickname,
commonName: identity.hiddenService.onionAddress,
peerId: identity.peerId.id,
signAlg: config.signAlg,
Expand All @@ -471,6 +471,7 @@ export class ConnectionsManagerService extends EventEmitter implements OnModuleI

let userCsr: UserCsr
try {
this.logger.info(`Creating user csr for username ${createUserCsrPayload.nickname}`)
userCsr = await createUserCsr(createUserCsrPayload)
} catch (e) {
emitError(this.serverIoProvider.io, {
Expand All @@ -481,9 +482,10 @@ export class ConnectionsManagerService extends EventEmitter implements OnModuleI
return
}

identity = { ...identity, userCsr: userCsr, nickname: nickname }
identity = { ...identity, userCsr, nickname }
this.logger.info('Created user CSR')
await this.storageService.setIdentity(identity)
this.logger.info(`Current identity in storage: ${await this.storageService.getIdentity(identity.id)}`)
if (payload.isUsernameTaken) {
await this.storageService.saveCSR({ csr: userCsr.userCsr })
}
Expand Down Expand Up @@ -1003,8 +1005,8 @@ export class ConnectionsManagerService extends EventEmitter implements OnModuleI
this.logger.info(`Storage - ${StorageEvents.CSRS_STORED}`)
const users = await getUsersFromCsrs(payload.csrs)
this.logger.info(`CSRS => Users`, payload.csrs, users)
this.libp2pService.dialUsers(users)
this.serverIoProvider.io.emit(SocketActionTypes.CSRS_STORED, payload)
this.libp2pService.dialUsers(users)
this.registrationService.emit(RegistrationEvents.REGISTER_USER_CERTIFICATE, payload)
})
this.storageService.on(StorageEvents.COMMUNITY_METADATA_STORED, async (meta: CommunityMetadata) => {
Expand Down
2 changes: 1 addition & 1 deletion packages/backend/src/nest/local-db/local-db.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -144,7 +144,7 @@ export class LocalDbService {

// temporarily shoving identity creation here
public async setIdentity(identity: Identity) {
await this.put(LocalDBKeys.IDENTITIES, identity)
this.logger.info(`Setting identity`, JSON.stringify({ ...identity, userCsr: identity.userCsr?.userCsr }, null, 2))
let identities = await this.get(LocalDBKeys.IDENTITIES)
if (!identities) {
identities = {}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { getCrypto } from 'pkijs'
import { type LogEntry, type EventsType, IPFSAccessController } from '@orbitdb/core'
import { NoCryptoEngineError } from '@quiet/types'
import { loadCSR, keyFromCertificate } from '@quiet/identity'
import { loadCSR, keyFromCertificate, CertFieldsTypes, getReqFieldValue } from '@quiet/identity'
import { StorageEvents } from '../storage.types'
import { validate } from 'class-validator'
import { UserCsrData } from '../../registration/registration.functions'
Expand Down Expand Up @@ -42,8 +42,9 @@ export class CertificatesRequestsStore extends EventStoreBase<string> {
}

public async loadedCertificateRequests() {
const csrs = await this.getEntries()
this.emit(StorageEvents.CSRS_STORED, {
csrs: await this.getEntries(),
csrs,
})
}

Expand All @@ -52,8 +53,7 @@ export class CertificatesRequestsStore extends EventStoreBase<string> {
throw new Error('Store is not initialized')
}
this.logger.info('Adding CSR to database')
await this.getStore().add(csr)
this.loadedCertificateRequests()
await this.store.add(csr)
return csr
}

Expand Down Expand Up @@ -90,9 +90,8 @@ export class CertificatesRequestsStore extends EventStoreBase<string> {

this.logger.info('Total CSRs:', allEntries.length)

const allCsrsUnique = [...new Set(allEntries)]
await Promise.all(
allCsrsUnique
allEntries
.filter(async csr => {
const validation = await this.validateUserCsr(csr)
if (validation) return true
Expand All @@ -103,7 +102,8 @@ export class CertificatesRequestsStore extends EventStoreBase<string> {
const pubKey = keyFromCertificate(parsedCsr)

if (filteredCsrsMap.has(pubKey)) {
filteredCsrsMap.delete(pubKey)
this.logger.warn(`Skipping csr due to existing pubkey`, pubKey)
return
}
filteredCsrsMap.set(pubKey, csr)
})
Expand Down
14 changes: 7 additions & 7 deletions packages/e2e-tests/src/tests/multipleClients.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,7 @@ describe('Multiple Clients', () => {
expect(isJoinModal).toBeTruthy()
await joinModal.switchToCreateCommunity()
})

it('Owner submits valid community name', async () => {
const createModal = new CreateCommunityModal(users.owner.app.driver)
const isCreateModal = await createModal.element.isDisplayed()
Expand Down Expand Up @@ -303,19 +304,17 @@ describe('Multiple Clients', () => {
await promiseWithRetries(loadNewUser(), failureReason, retryConfig, onTimeout)
})

// TODO: figure out why the message is still showing `Duplicate` and why the username is still the old duplicated username on the message
it('Second user can send a message, they see their message tagged as "unregistered"', async () => {
logger.info('Second guest FETCHING CHANNEL MESSAGES!')
await sleep(15000)
await generalChannelUser3.sendMessage(users.user3.messages[0], users.user1.username)
await generalChannelUser3.sendMessage(users.user3.messages[0], users.user3.username)
generalChannelUser3 = new Channel(users.user3.app.driver, generalChannelName)
// await generalChannelUser3.waitForLabel(users.user3.username, 'Unregistered')
await generalChannelUser3.waitForLabel(users.user3.username, 'Unregistered')
})

// TODO: figure out why the message is still showing `Duplicate` and why the username is still the old duplicated username on the message
it('First user sees that unregistered user\'s messages are marked as "unregistered"', async () => {
await generalChannelUser1.getMessageIdsByText(users.user3.messages[0], users.user1.username)
// await generalChannelUser1.waitForLabel(users.user3.username, 'Unregistered')
await generalChannelUser1.getMessageIdsByText(users.user3.messages[0], users.user3.username)
await generalChannelUser1.waitForLabel(users.user3.username, 'Unregistered')
})
})

Expand Down Expand Up @@ -403,7 +402,8 @@ describe('Multiple Clients', () => {
const settingsModal = await new Sidebar(users.user1.app.driver).openSettings()
const isSettingsModal = await settingsModal.element.isDisplayed()
expect(isSettingsModal).toBeTruthy()
await settingsModal.openLeaveCommunityModal()
await settingsModal.switchTab('leave-community')
await sleep(2000)
await settingsModal.leaveCommunityButton()
})

Expand Down
12 changes: 11 additions & 1 deletion packages/state-manager/src/sagas/identity/identity.slice.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,9 @@ import {
type RegisterUsernamePayload,
SendCsrsResponse,
} from '@quiet/types'
import { createLogger } from '../../utils/logger'

const logger = createLogger('identity:slice')

export class IdentityState {
public identities: EntityState<Identity> = identityAdapter.getInitialState()
Expand All @@ -26,9 +29,16 @@ export const identitySlice = createSlice({
updateIdentity: (state, action: PayloadAction<Identity>) => {
// addOne if action.payload.id is not in state.identities
if (!state.identities.ids.includes(action.payload.id)) {
console.log('Adding new identity')
logger.info(
'Adding new identity',
JSON.stringify({ ...action.payload, userCsr: action.payload.userCsr?.userCsr }, null, 2)
)
identityAdapter.addOne(state.identities, action.payload)
} else {
logger.info(
'Updating existing identity',
JSON.stringify({ ...action.payload, userCsr: action.payload.userCsr?.userCsr }, null, 2)
)
identityAdapter.updateOne(state.identities, {
id: action.payload.id,
changes: action.payload,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ export function* registerUsernameSaga(
socket: Socket,
action: PayloadAction<ReturnType<typeof identityActions.registerUsername>['payload']>
): Generator {
logger.info('Registering username')
logger.info('Registering username', action.payload.nickname)

// Nickname can differ between saga calls

Expand Down

0 comments on commit 968c249

Please sign in to comment.