Skip to content

Commit

Permalink
feel it out
Browse files Browse the repository at this point in the history
  • Loading branch information
rsdmike committed Nov 22, 2022
1 parent 082a915 commit 42c25a6
Show file tree
Hide file tree
Showing 15 changed files with 49 additions and 28 deletions.
4 changes: 3 additions & 1 deletion src/amt/ConnectedDevice.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,11 +12,13 @@ export class ConnectedDevice {
ciraSocket: CIRASocket
limiter: Bottleneck
kvmConnect: boolean
tenantId: string

constructor (ciraSocket: CIRASocket, readonly username: string, readonly password: string) {
constructor (ciraSocket: CIRASocket, readonly username: string, readonly password: string, tenantId: string) {
this.ciraSocket = ciraSocket
this.httpHandler = new HttpHandler()
this.kvmConnect = false
this.tenantId = tenantId
this.limiter = new Bottleneck({
maxConcurrent: 3,
minTime: 250
Expand Down
2 changes: 1 addition & 1 deletion src/amt/connectedDevice.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ const socket: CIRASocket = null

describe('Connected Device', () => {
it('should initialize', () => {
const device = new ConnectedDevice(socket, 'admin', 'P@ssw0rd')
const device = new ConnectedDevice(socket, 'admin', 'P@ssw0rd','')
expect(device.ciraSocket).toBeNull()
expect(device.httpHandler).toBeDefined()
})
Expand Down
32 changes: 25 additions & 7 deletions src/middleware/tenant.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,15 +4,33 @@
**********************************************************************/

import { Request, Response } from 'express'
import jws from 'jws'
import { devices } from '../server/mpsserver'
import { Environment } from '../utils/Environment'

const tenantMiddleware = (req: Request, res: Response, next): void => {
const jwtTokenHeader = Environment.Config.jwtTokenHeader ?? 'x-tenant-id'
const decodedToken = jws.decode(jwtTokenHeader)
const tenantProp = Environment.Config.jwtTenantProperty ?? ''
req.tenantId = decodedToken?.payload[tenantProp] ?? ''
req.next()
const jwtTokenHeader = Environment.Config.jwt_token_header ?? 'x-tenant-id'
const token = req.headers[jwtTokenHeader]
req.tenantId = ''
if (token != null && token !== '') {
try {
const decodedToken = Buffer.from(token as string, 'base64').toString()
if (decodedToken != null && decodedToken !== '') {
const dt = JSON.parse(decodedToken)
const tenantProp = Environment.Config.jwt_tenant_property ?? ''
req.tenantId = dt[tenantProp] ?? ''
}
} catch (err) {
console.error(err)
}
}
next()
}

export default tenantMiddleware
const tenantHasAccess = (req: Request, res: Response, next): void => {
if (req.tenantId === devices[req.params.guid].tenantId) {
next()
} else {
res.send(401).end()
}
}
export { tenantMiddleware, tenantHasAccess }
4 changes: 2 additions & 2 deletions src/models/Config.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,8 +38,8 @@ export interface configType {
instance_name: string
redirection_expiration_time: number
web_auth_enabled: boolean
jwtTokenHeader: string
jwtTenantProperty: string
jwt_token_header: string
jwt_tenant_property: string
}

export interface certificatesType {
Expand Down
4 changes: 2 additions & 2 deletions src/routes/devices/delete.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,11 @@ import { logger, messages } from '../../logging'

export async function deleteDevice (req: Request, res: Response): Promise<void> {
try {
const device = await req.db.devices.getById(req.params.guid)
const device = await req.db.devices.getById(req.params.guid, req.tenantId)
if (device == null) {
res.status(404).json({ error: 'NOT FOUND', message: `Device ID ${req.params.guid} not found` }).end()
} else {
const results = await req.db.devices.delete(req.params.guid)
const results = await req.db.devices.delete(req.params.guid, req.tenantId)
if (results) {
res.status(204).end()
}
Expand Down
2 changes: 1 addition & 1 deletion src/routes/devices/get.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ export async function getDevice (req: Request, res: Response): Promise<void> {
if (tenantId == null || tenantId === '') {
tenantId = req.query.tenantId as string
}
const result = await req.db.devices.getById(req.params.guid)
const result = await req.db.devices.getById(req.params.guid, tenantId)
if (result != null) {
if (result.tenantId === tenantId) {
res.status(200).json(result).end()
Expand Down
8 changes: 4 additions & 4 deletions src/routes/devices/getAll.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,12 +14,12 @@ export async function getAllDevices (req: Request, res: Response): Promise<void>
let list: Device[] = []

if (req.query.hostname != null) {
list = await req.db.devices.getByHostname(req.query.hostname as string)
list = await req.db.devices.getByHostname(req.query.hostname as string, req.tenantId)
} else if (req.query.tags != null) {
const tags = (req.query.tags as string).split(',')
list = await req.db.devices.getByTags(tags, req.query.method as string, req.query.$top as any, req.query.$skip as any)
list = await req.db.devices.getByTags(tags, req.query.method as string, req.query.$top as any, req.query.$skip as any, req.tenantId)
} else {
list = await req.db.devices.get(req.query.$top as any, req.query.$skip as any)
list = await req.db.devices.get(req.query.$top as any, req.query.$skip as any, req.tenantId)
}
if (req.query.status != null) {
list = list.filter(x => {
Expand All @@ -28,7 +28,7 @@ export async function getAllDevices (req: Request, res: Response): Promise<void>
})
}
if (count != null && count) {
const count: number = await req.db.devices.getCount()
const count: number = await req.db.devices.getCount(req.tenantId)
const dataWithCount: DataWithCount = {
data: list,
totalCount: count
Expand Down
4 changes: 2 additions & 2 deletions src/routes/devices/stats.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,8 @@ import { messages } from '../../logging/messages'

export async function stats (req: Request, res: Response): Promise<void> {
try {
const connectedCount = await req.db.devices.getConnectedDevices()
const totalCount = await req.db.devices.getCount()
const connectedCount = await req.db.devices.getConnectedDevices(req.tenantId)
const totalCount = await req.db.devices.getCount(req.tenantId)
res.json({
totalCount,
connectedCount,
Expand Down
2 changes: 1 addition & 1 deletion src/routes/devices/tags.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import { Request, Response } from 'express'

export async function getDistinctTags (req: Request, res: Response): Promise<void> {
try {
const results = await req.db.devices.getDistinctTags()
const results = await req.db.devices.getDistinctTags(req.tenantId)
if (results != null) {
res.status(200).json(results).end()
} else {
Expand Down
2 changes: 1 addition & 1 deletion src/routes/devices/update.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import { Request, Response } from 'express'
export async function updateDevice (req: Request, res: Response): Promise<void> {
const guid: string = req.body.guid
try {
let device = await req.db.devices.getById(guid)
let device = await req.db.devices.getById(guid, req.tenantId)
if (device == null) {
res.status(404).json({ error: 'NOT FOUND', message: `Device ID ${guid} not found` }).end()
} else {
Expand Down
3 changes: 2 additions & 1 deletion src/routes/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,13 +10,14 @@ import authRouter from './auth/index'
import amtRouter from './amt/index'
import healthRouter from './health'
import version from './version'
import { tenantHasAccess } from '../middleware/tenant'

const router: Router = Router()

router.use('/authorize', authRouter)
router.use('/devices', deviceRouter)
router.get('/ciracert', mpsrootcert)
router.use('/amt', amtRouter)
router.use('/amt', tenantHasAccess, amtRouter)
router.use('/health', healthRouter)
router.use('/version', version)

Expand Down
2 changes: 1 addition & 1 deletion src/server/mpsserver.ts
Original file line number Diff line number Diff line change
Expand Up @@ -108,7 +108,7 @@ export class MPSServer {
logger.debug(`${messages.MPS_CIRA_AUTHENTICATION_SUCCESS} for: ${username}`)
const cred = await this.secrets.getAMTCredentials(socket.tag.SystemId)

devices[socket.tag.SystemId] = new ConnectedDevice(socket, cred[0], cred[1])
devices[socket.tag.SystemId] = new ConnectedDevice(socket, cred[0], cred[1], device.tenantId)
this.events.emit('connected', socket.tag.SystemId)
await this.handleDeviceConnect(socket.tag.SystemId)
APFProcessor.SendUserAuthSuccess(socket) // Notify the auth success on the CIRA connection
Expand Down
2 changes: 1 addition & 1 deletion src/server/webserver.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ import { Environment } from '../utils/Environment'
import { ISecretManagerService } from '../interfaces/ISecretManagerService'
import { WsRedirect } from '../utils/wsRedirect'
import { devices } from './mpsserver'
import tenantMiddleware from '../middleware/tenant'
import { tenantMiddleware } from '../middleware/tenant'

export class WebServer {
app: express.Express
Expand Down
4 changes: 2 additions & 2 deletions src/test/helper/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,8 +29,8 @@ export const config: configType = {
db_provider: 'postgres',
connection_string: 'postgresql://<USERNAME>:<PASSWORD>@localhost:5432/mpsdb?sslmode=no-verify',
instance_name: 'localhost',
jwtTokenHeader: '',
jwtTenantProperty: '',
jwt_token_header: '',
jwt_tenant_property: '',
mps_tls_config: {
key: '../private/mpsserver-cert-private.key',
cert: '../private/mpsserver-cert-public.crt',
Expand Down
2 changes: 1 addition & 1 deletion src/utils/wsRedirect.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ describe('WsRedirect tests', () => {
url: `https://iotg.com?tls=0&host=${fakeGuid}`

}
devices[fakeGuid] = new ConnectedDevice(null, 'admin', 'P@ssw0rd')
devices[fakeGuid] = new ConnectedDevice(null, 'admin', 'P@ssw0rd', '')

const setNormalTCPSpy = jest.spyOn(wsRedirect, 'setNormalTCP').mockReturnValue()
const publishEventSpy = jest.spyOn(MqttProvider, 'publishEvent')
Expand Down

0 comments on commit 42c25a6

Please sign in to comment.