Skip to content

Commit

Permalink
Remove obsolete registrar code
Browse files Browse the repository at this point in the history
  • Loading branch information
vinkabuki committed Sep 21, 2023
1 parent cda3425 commit 26032b6
Show file tree
Hide file tree
Showing 5 changed files with 8 additions and 261 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { jest } from '@jest/globals'
import { LazyModuleLoader } from '@nestjs/core'
import { Test, TestingModule } from '@nestjs/testing'
import { getFactory, prepareStore, type Store, type communities, type identity } from '@quiet/state-manager'
import { type Community, type Identity, type InitCommunityPayload, type LaunchRegistrarPayload } from '@quiet/types'
import { type Community, type Identity, type InitCommunityPayload } from '@quiet/types'
import { type FactoryGirl } from 'factory-girl'
import PeerId from 'peer-id'
import { TestModule } from '../common/test.module'
Expand Down Expand Up @@ -108,10 +108,8 @@ describe('ConnectionsManagerService', () => {
await connectionsManagerService.closeAllServices()

const launchCommunitySpy = jest.spyOn(connectionsManagerService, 'launchCommunity').mockResolvedValue()
const launchRegistrarSpy = jest.spyOn(registrationService, 'launchRegistrar').mockResolvedValue()

await connectionsManagerService.init()
expect(launchRegistrarSpy).not.toHaveBeenCalled()
expect(launchCommunitySpy).toHaveBeenCalledWith(launchCommunityPayload)
})

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -178,10 +178,6 @@ export class ConnectionsManagerService extends EventEmitter implements OnModuleI
if (this.tor && !options.saveTor) {
await this.tor.kill()
}
if (this.registrationService) {
this.logger('Stopping registration service')
await this.registrationService.stop()
}
if (this.storageService) {
this.logger('Stopping orbitdb')
await this.storageService?.stopOrbitDb()
Expand Down
121 changes: 1 addition & 120 deletions packages/backend/src/nest/registration/registration.functions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,20 +9,8 @@ import {
} from '@quiet/identity'
import { IsBase64, IsNotEmpty, validate } from 'class-validator'
import { CertificationRequest } from 'pkijs'
import { Agent } from 'http'
import AbortController from 'abort-controller'
import fetch, { Response } from 'node-fetch'
import { getUsersAddresses } from '../common/utils'
import {
ErrorCodes,
ErrorMessages,
ErrorPayload,
PermsData,
SocketActionTypes,
SuccessfullRegistrarionResponse,
UserCertificatePayload,
UserData,
} from '@quiet/types'
import { ErrorPayload, PermsData, SocketActionTypes, SuccessfullRegistrarionResponse, UserData } from '@quiet/types'
import { CsrContainsFields, IsCsr } from './registration.validators'
import { RegistrationEvents } from './registration.types'
import Logger from '../common/logger'
Expand Down Expand Up @@ -89,113 +77,6 @@ export interface RegistrationResponse {
data: ErrorPayload | SuccessfullRegistrarionResponse
}

export const sendCertificateRegistrationRequest = async (
serviceAddress: string,
userCsr: string,
communityId: string,
requestTimeout = 120000,
socksProxyAgent: Agent
): Promise<RegistrationResponse> => {
const controller = new AbortController()
const timeout = setTimeout(() => {
controller.abort()
}, requestTimeout)

let options = {
method: 'POST',
body: JSON.stringify({ data: userCsr }),
headers: { 'Content-Type': 'application/json' },
signal: controller.signal,
}

options = Object.assign(
{
agent: socksProxyAgent,
},
options
)

let response: Response | null = null

try {
const start = new Date()
response = await fetch(`${serviceAddress}/register`, options)
const end = new Date()
const fetchTime = (end.getTime() - start.getTime()) / 1000
logger(`Fetched ${serviceAddress}, time: ${fetchTime}`)
} catch (e) {
logger.error(e)
return {
eventType: RegistrationEvents.ERROR,
data: {
type: SocketActionTypes.REGISTRAR,
code: ErrorCodes.NOT_FOUND,
message: ErrorMessages.REGISTRAR_NOT_FOUND,
community: communityId,
},
}
} finally {
clearTimeout(timeout)
}

switch (response?.status) {
case 200:
break
case 400:
return {
eventType: RegistrationEvents.ERROR,
data: {
type: SocketActionTypes.REGISTRAR,
code: ErrorCodes.BAD_REQUEST,
message: ErrorMessages.INVALID_USERNAME,
community: communityId,
},
}
case 403:
return {
eventType: RegistrationEvents.ERROR,
data: {
type: SocketActionTypes.REGISTRAR,
code: ErrorCodes.FORBIDDEN,
message: ErrorMessages.USERNAME_TAKEN,
community: communityId,
},
}
case 404:
return {
eventType: RegistrationEvents.ERROR,
data: {
type: SocketActionTypes.REGISTRAR,
code: ErrorCodes.NOT_FOUND,
message: ErrorMessages.REGISTRAR_NOT_FOUND,
community: communityId,
},
}
default:
logger.error(`Registrar responded with ${response?.status} "${response?.statusText}" (${communityId})`)
return {
eventType: RegistrationEvents.ERROR,
data: {
type: SocketActionTypes.REGISTRAR,
code: ErrorCodes.SERVER_ERROR,
message: ErrorMessages.REGISTRATION_FAILED,
community: communityId,
},
}
}

const registrarResponse: UserCertificatePayload = await response.json()

logger(`Sending user certificate (${communityId})`)
return {
eventType: SocketActionTypes.SEND_USER_CERTIFICATE,
data: {
communityId: communityId,
payload: registrarResponse,
},
}
}

export const registerUser = async (
csr: string,
permsData: PermsData,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,11 +12,9 @@ import {
type UserCsr,
} from '@quiet/identity'
import { type DirResult } from 'tmp'
import { ErrorCodes, ErrorMessages, type PermsData, SocketActionTypes } from '@quiet/types'
import { type PermsData } from '@quiet/types'
import { Time } from 'pkijs'
import { registerOwner, registerUser, sendCertificateRegistrationRequest } from './registration.functions'
import createHttpsProxyAgent from 'https-proxy-agent'
import { RegistrationEvents } from './registration.types'
import { registerOwner, registerUser } from './registration.functions'
import { jest } from '@jest/globals'
import { createTmpDir } from '../common/utils'

Expand Down Expand Up @@ -148,24 +146,4 @@ describe('RegistrationService', () => {
const response = await registerUser(csr, permsData, [], 'ownerCert')
expect(response.status).toEqual(400)
})

it('returns 404 if fetching registrar address throws error', async () => {
console.log(fetch)
fetch.default.mockRejectedValue('User aborted request')
const communityId = 'communityID'
const response = await sendCertificateRegistrationRequest(
'QmS9vJkgbea9EgzHvVPqhj1u4tH7YKq7eteDN7gnG5zUmc',
userCsr.userCsr,
communityId,
1000,
createHttpsProxyAgent({ port: '12311', host: 'localhost' })
)
expect(response.eventType).toBe(RegistrationEvents.ERROR)
expect(response.data).toEqual({
type: SocketActionTypes.REGISTRAR,
code: ErrorCodes.NOT_FOUND,
message: ErrorMessages.REGISTRAR_NOT_FOUND,
community: communityId,
})
})
})
114 changes: 4 additions & 110 deletions packages/backend/src/nest/registration/registration.service.ts
Original file line number Diff line number Diff line change
@@ -1,40 +1,18 @@
import { Inject, Injectable, OnModuleInit } from '@nestjs/common'
import express from 'express'
import getPort from 'get-port'
import { Agent, Server } from 'http'
import { Injectable, OnModuleInit } from '@nestjs/common'
import { EventEmitter } from 'events'
import {
registerOwner,
registerUser,
RegistrarResponse,
RegistrationResponse,
sendCertificateRegistrationRequest,
} from './registration.functions'
import {
ConnectionProcessInfo,
ErrorCodes,
ErrorMessages,
LaunchRegistrarPayload,
PermsData,
RegisterOwnerCertificatePayload,
SocketActionTypes,
} from '@quiet/types'
import { EXPRESS_PROVIDER } from '../const'
import { registerOwner, registerUser } from './registration.functions'
import { ErrorCodes, ErrorMessages, PermsData, RegisterOwnerCertificatePayload, SocketActionTypes } from '@quiet/types'
import { RegistrationEvents } from './registration.types'
import { ServiceState } from '../connections-manager/connections-manager.types'
import Logger from '../common/logger'

@Injectable()
export class RegistrationService extends EventEmitter implements OnModuleInit {
private readonly logger = Logger(RegistrationService.name)
private _server: Server
private _port: number
public registrationService: any
public certificates: string[] = []
private _permsData: PermsData
private _ownerCertificate: string

constructor(@Inject(EXPRESS_PROVIDER) public readonly _app: express.Application) {
constructor() {
super()
}

Expand All @@ -49,48 +27,12 @@ export class RegistrationService extends EventEmitter implements OnModuleInit {
}
await this.registerUser(csr)
})
this.setRouting()
}

public setCertificates(certs: string[]) {
this.certificates = certs
}

private pendingPromise: Promise<RegistrarResponse> | null = null

private setRouting() {
// @ts-ignore
this._app.use(express.json())
this._app.post('/register', async (req, res): Promise<void> => {
if (this.pendingPromise) return
this.pendingPromise = this.registerUser(req.body.data)
const result = await this.pendingPromise
if (result) {
res.status(result.status).send(result.body)
}
this.pendingPromise = null
})
}

public async listen(): Promise<void> {
return await new Promise(resolve => {
this._server = this._app.listen(this._port, () => {
this.logger(`Certificate registration service listening on port: ${this._port}`)
resolve()
})
})
}

public async stop(): Promise<void> {
return await new Promise(resolve => {
if (!this._server) resolve()
this._server.close(() => {
this.logger('Certificate registration service closed')
resolve()
})
})
}

public set permsData(perms: PermsData) {
console.log('Setting owner perms data')
this._permsData = {
Expand Down Expand Up @@ -120,59 +62,11 @@ export class RegistrationService extends EventEmitter implements OnModuleInit {
this._ownerCertificate = cert
}

public async sendCertificateRegistrationRequest(
serviceAddress: string,
userCsr: string,
communityId: string,
requestTimeout = 120000,
socksProxyAgent: Agent
): Promise<void> {
const response: RegistrationResponse = await sendCertificateRegistrationRequest(
serviceAddress,
userCsr,
communityId,
requestTimeout,
socksProxyAgent
)
this.emit(SocketActionTypes.CONNECTION_PROCESS_INFO, ConnectionProcessInfo.CONNECTING_TO_COMMUNITY)
this.emit(response.eventType, response.data)
}

public async registerUser(csr: string): Promise<{ status: number; body: any }> {
const result = await registerUser(csr, this._permsData, this.certificates, this._ownerCertificate)
if (result?.status === 200) {
this.emit(RegistrationEvents.NEW_USER, { certificate: result.body.certificate, rootPermsData: this._permsData })
}
return result
}

public async launchRegistrar(payload: LaunchRegistrarPayload): Promise<void> {
this.emit(RegistrationEvents.REGISTRAR_STATE, ServiceState.LAUNCHING)
this._permsData = {
certificate: payload.rootCertString,
privKey: payload.rootKeyString,
}
this.logger(`Initializing registration service for peer ${payload.peerId}...`)
try {
await this.init(payload.privateKey)
} catch (err) {
this.logger.error(`Couldn't initialize certificate registration service: ${err as string}`)
return
}
try {
await this.listen()
} catch (err) {
this.logger.error(`Certificate registration service couldn't start listening: ${err as string}`)
}
this.emit(RegistrationEvents.REGISTRAR_STATE, ServiceState.LAUNCHED)
}

public async init(privKey: string): Promise<void> {
this._port = await getPort()
this.emit(RegistrationEvents.SPAWN_HS_FOR_REGISTRAR, {
port: this._port,
privateKey: privKey,
targetPort: 80,
})
}
}

0 comments on commit 26032b6

Please sign in to comment.