Skip to content

Commit

Permalink
Merge pull request #435 from hmcts/feature/EUI-1685-global-tokens
Browse files Browse the repository at this point in the history
Feature/eui 1685 global tokens
  • Loading branch information
Mo-Lala84 authored Mar 30, 2020
2 parents 7fc425c + dd36e25 commit 7d0b81c
Show file tree
Hide file tree
Showing 16 changed files with 128 additions and 100 deletions.
11 changes: 4 additions & 7 deletions api/amendedJurisdictions/index.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,16 +4,13 @@ import 'mocha'
import * as sinon from 'sinon'
import * as sinonChai from 'sinon-chai'
import { mockReq, mockRes } from 'sinon-express-mock'
import { getConfigValue } from '../configuration'
import { SERVICES_CCD_COMPONENT_API_PATH } from '../configuration/references'
import { http } from '../lib/http'
import * as amendedJurisdictions from './index'

chai.use(sinonChai)

import {getConfigValue} from '../configuration'
import {
SERVICES_CCD_COMPONENT_API_PATH,
} from '../configuration/references'
import {http} from '../lib/http'
import * as amendedJurisdictions from './index'

describe('Amended Jurisdiction', () => {

let next
Expand Down
28 changes: 13 additions & 15 deletions api/documents/DMStore.spec.ts
Original file line number Diff line number Diff line change
@@ -1,19 +1,17 @@
import * as chai from 'chai'
import {expect} from 'chai'
import {Fields, File, Files} from 'formidable'
import { expect } from 'chai'
import { Fields, File, Files } from 'formidable'
import 'mocha'
import * as sinon from 'sinon'
import * as sinonChai from 'sinon-chai'
import {getConfigValue} from '../configuration'
import {
SERVICES_DOCUMENTS_API_PATH,
} from '../configuration/references'
import { getConfigValue } from '../configuration'
import { SERVICES_DOCUMENTS_API_PATH } from '../configuration/references'
import { http } from '../lib/http'
import { EnhancedRequest } from '../lib/models'
import * as DMStore from './DMStore'

chai.use(sinonChai)

import {http} from '../lib/http'
import * as DMStore from './DMStore'

describe('DMStore', () => {
const res = {
data: 'okay',
Expand Down Expand Up @@ -52,13 +50,13 @@ describe('DMStore', () => {

it('Should make a http.get call based on the document Id', async () => {

await DMStore.getDocument(documentId)
await DMStore.getDocument(documentId, {} as EnhancedRequest)
expect(spy).to.be.calledWith(`${url}/documents/${documentId}`)
})

it('Should return the data property of the return of a http.get call', async () => {

expect(await DMStore.getDocument(documentId)).to.equal('okay')
expect(await DMStore.getDocument(documentId, {} as EnhancedRequest)).to.equal('okay')
})

})
Expand All @@ -69,13 +67,13 @@ describe('DMStore', () => {

it('Should make a http.get call based on the document Id', async () => {

await DMStore.getDocumentBinary(documentId)
await DMStore.getDocumentBinary(documentId, {} as EnhancedRequest)
expect(spy).to.be.calledWith(`${url}/documents/${documentId}/binary`)
})

it('Should return the data property of the return of the http.get call', async () => {

expect(await DMStore.getDocumentBinary(documentId)).to.equal('okay')
expect(await DMStore.getDocumentBinary(documentId, {} as EnhancedRequest)).to.equal('okay')
})
})

Expand All @@ -96,12 +94,12 @@ describe('DMStore', () => {
const files: Files = { file }

it('Should make a http.post call', async () => {
await DMStore.postDocuments(fields, files)
await DMStore.postDocuments(fields, files, {} as EnhancedRequest)
expect(spyPost).to.be.calledWith(`${url}/documents/`)
})

it('Should return the data property of the return of the http.post call', async () => {
expect(await DMStore.postDocuments(fields, files)).to.equal('okay')
expect(await DMStore.postDocuments(fields, files, {} as EnhancedRequest)).to.equal('okay')
})
})

Expand Down
31 changes: 17 additions & 14 deletions api/documents/DMStore.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,15 @@
import {AxiosResponse} from 'axios'
import { AxiosResponse } from 'axios'
import * as FormData from 'form-data'
import {Fields, File, Files} from 'formidable'
import { Fields, File, Files } from 'formidable'
import * as fs from 'fs'
import {getConfigValue} from '../configuration'
import {
SERVICES_DOCUMENTS_API_PATH,
} from '../configuration/references'
import { getConfigValue } from '../configuration'
import { SERVICES_DOCUMENTS_API_PATH } from '../configuration/references'
import { http } from '../lib/http'
import * as log4jui from '../lib/log4jui'
import {JUILogger} from "../lib/models"
import { EnhancedRequest, JUILogger } from "../lib/models"
import { setHeaders } from '../lib/proxy'
import { asyncReturnOrError } from '../lib/util'
import {DMDocument, DMDocuments} from './document.interface'
import { DMDocument, DMDocuments } from './document.interface'

const url: string = getConfigValue(SERVICES_DOCUMENTS_API_PATH)

Expand All @@ -21,9 +20,10 @@ const logger: JUILogger = log4jui.getLogger('dm-store')
* @param documentId
* @returns Promise<DMDocument>|null
*/
export async function getDocument(documentId: string): Promise<DMDocument> {
export async function getDocument(documentId: string, req: EnhancedRequest): Promise<DMDocument> {
const headers = setHeaders(req)
const response: AxiosResponse<DMDocument> = await asyncReturnOrError(
http.get(`${url}/documents/${documentId}`),
http.get(`${url}/documents/${documentId}`, { headers }),
`Error getting document ${documentId}`,
null,
logger,
Expand All @@ -38,9 +38,10 @@ export async function getDocument(documentId: string): Promise<DMDocument> {
* @param documentId
* @returns Promise<any>
*/
export async function getDocumentBinary(documentId: string): Promise<any> {
export async function getDocumentBinary(documentId: string, req: EnhancedRequest): Promise<any> {
const headers = setHeaders(req)
const response: AxiosResponse<any> = await asyncReturnOrError(
http.get(`${url}/documents/${documentId}/binary`, { responseType: 'stream' }),
http.get(`${url}/documents/${documentId}/binary`, { responseType: 'stream', headers }),
`Error getting Binary for document ${documentId}`,
null,
logger,
Expand All @@ -56,7 +57,7 @@ export async function getDocumentBinary(documentId: string): Promise<any> {
* @param files
* @returns Promise<DMDocuments>
*/
export async function postDocuments(fields: Fields, files: Files): Promise<DMDocuments> {
export async function postDocuments(fields: Fields, files: Files, req: EnhancedRequest): Promise<DMDocuments> {

const formData: FormData = new FormData()

Expand All @@ -69,11 +70,13 @@ export async function postDocuments(fields: Fields, files: Files): Promise<DMDoc
formData.append(field, fields[field])
})

const headers = setHeaders(req)

// we explicitly set upload limit to 100MB here, rejection is handled by dm-store
const response: AxiosResponse<DMDocuments> = await asyncReturnOrError(
http.post(`${url}/documents/`, formData,
{
headers: formData.getHeaders(),
headers: { ...headers, ...formData.getHeaders() },
maxContentLength: 524300000,
}),
`Error posting documents`,
Expand Down
8 changes: 4 additions & 4 deletions api/documents/index.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import * as express from 'express'
import * as formidable from 'formidable'
import {EnhancedRequest} from '../lib/models'
import { EnhancedRequest } from '../lib/models'
import * as DMStore from './DMStore'

/**
Expand All @@ -10,7 +10,7 @@ import * as DMStore from './DMStore'
*/
export async function getDocumentRoute(req: express.Request, res: express.Response) {
const documentId = req.params.document_id
const document = await DMStore.getDocument(documentId)
const document = await DMStore.getDocument(documentId, req)
if (document) {
res.status(200).send(document)
} else {
Expand All @@ -24,7 +24,7 @@ export async function getDocumentRoute(req: express.Request, res: express.Respon
* @param res
*/
export async function getDocumentBinaryRoute(req: express.Request, res: express.Response) {
const binary = await DMStore.getDocumentBinary(req.params.document_id)
const binary = await DMStore.getDocumentBinary(req.params.document_id, req)

if (binary) {
const headers = binary.headers
Expand All @@ -49,7 +49,7 @@ export async function postDocuments(req: EnhancedRequest, res: express.Response)

await form.parse(req, async (err, fields: formidable.Fields, files: formidable.Files) => {

const documents = await DMStore.postDocuments(fields, files)
const documents = await DMStore.postDocuments(fields, files, req)

if (documents) {
res.status(200).send(documents)
Expand Down
8 changes: 4 additions & 4 deletions api/emAnno/emAnnoService.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ describe('enAnnoService', () => {
it('should make a get request', async () => {
spy = sandbox.stub(http, 'get').resolves(res)
const emAnnoPath = '/em-anno/12345'
const response = await handleGet(emAnnoPath)
const response = await handleGet(emAnnoPath, req)
expect(response).to.equal('ok')
})
})
Expand All @@ -56,7 +56,7 @@ describe('enAnnoService', () => {
it('should make a post request', async () => {
spy = sandbox.stub(http, 'post').resolves(res)
const emAnnoPath = '/em-anno/12345'
const response = await handlePost(emAnnoPath, dummyAnnotation)
const response = await handlePost(emAnnoPath, dummyAnnotation, req)
expect(response).to.equal('ok')
})
})
Expand All @@ -65,7 +65,7 @@ describe('enAnnoService', () => {
it('should make a put request', async () => {
spy = sandbox.stub(http, 'put').resolves(res)
const emAnnoPath = '/em-anno/12345'
const response = await handlePut(emAnnoPath, dummyAnnotation)
const response = await handlePut(emAnnoPath, dummyAnnotation, req)
expect(response).to.equal('ok')
})
})
Expand All @@ -74,7 +74,7 @@ describe('enAnnoService', () => {
it('should make a delete request', async () => {
spy = sandbox.stub(http, 'delete').resolves(res)
const emAnnoPath = '/em-anno/12345'
const response = await handleDelete(emAnnoPath)
const response = await handleDelete(emAnnoPath, req)
expect(response).to.equal('ok')
})
})
Expand Down
25 changes: 15 additions & 10 deletions api/emAnno/emAnnoService.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import {http} from '../lib/http'
import { http } from '../lib/http'
import * as log4jui from '../lib/log4jui'
import {JUILogger} from '../lib/models'
import { EnhancedRequest, JUILogger } from '../lib/models'
import { setHeaders } from '../lib/proxy'
import { Annotation, Annotations } from './models'

const logger: JUILogger = log4jui.getLogger('em-anno-service')
Expand All @@ -11,11 +12,12 @@ const logger: JUILogger = log4jui.getLogger('em-anno-service')
* @param annotationsPath
* @returns {Promise<null>}
*/
export async function handleGet(annotationsPath: string): Promise<Annotations> {
export async function handleGet(annotationsPath: string, req: EnhancedRequest): Promise<Annotations> {

try {
logger.info('getting annotations', annotationsPath)
const response: { data?: Annotations} = await http.get(annotationsPath)
const headers = setHeaders(req)
const response: { data?: Annotations} = await http.get(annotationsPath, { headers })
return response.data
} catch (e) {
logger.error(e.message)
Expand All @@ -31,11 +33,12 @@ export async function handleGet(annotationsPath: string): Promise<Annotations> {
* @param body
* @returns {Promise<null>}
*/
export async function handlePost(annotationsPath: string, body: Annotation): Promise<Annotation> {
export async function handlePost(annotationsPath: string, body: Annotation, req: EnhancedRequest): Promise<Annotation> {

try {
logger.info('posting annotations', annotationsPath)
const response: { data?: Annotation} = await http.post(annotationsPath, body)
const headers = setHeaders(req)
const response: { data?: Annotation} = await http.post(annotationsPath, body, { headers })
return response.data
} catch (e) {
logger.error(e.message)
Expand All @@ -51,11 +54,12 @@ export async function handlePost(annotationsPath: string, body: Annotation): Pro
* @param body
* @returns {Promise<null>}
*/
export async function handlePut(annotationsPath: string, body: Annotation): Promise<Annotation> {
export async function handlePut(annotationsPath: string, body: Annotation, req: EnhancedRequest): Promise<Annotation> {

try {
logger.info('putting annotations', annotationsPath)
const response: { data?: Annotation} = await http.put(annotationsPath, body)
const headers = setHeaders(req)
const response: { data?: Annotation} = await http.put(annotationsPath, body, { headers })
return response.data
} catch (e) {
logger.error(e.message)
Expand All @@ -70,11 +74,12 @@ export async function handlePut(annotationsPath: string, body: Annotation): Prom
* @param annotationsPath
* @returns {Promise<null>}
*/
export async function handleDelete(annotationsPath: string): Promise<Annotation> {
export async function handleDelete(annotationsPath: string, req: EnhancedRequest): Promise<Annotation> {

try {
logger.info('deleting annotations', annotationsPath)
const response: { data?: Annotation} = await http.delete(annotationsPath)
const headers = setHeaders(req)
const response: { data?: Annotation} = await http.delete(annotationsPath, { headers })
return response.data
} catch (e) {
logger.error(e.message)
Expand Down
18 changes: 8 additions & 10 deletions api/emAnno/index.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,8 @@
import * as express from 'express'
import {getConfigValue} from '../configuration'
import {
SERVICES_EM_ANNO_API_URL,
} from '../configuration/references'
import {EnhancedRequest} from '../lib/models'
import {handleDelete, handleGet, handlePost, handlePut} from './emAnnoService'
import { getConfigValue } from '../configuration'
import { SERVICES_EM_ANNO_API_URL } from '../configuration/references'
import { EnhancedRequest } from '../lib/models'
import { handleDelete, handleGet, handlePost, handlePut } from './emAnnoService'
import { Annotation, Annotations } from './models'

const url: string = getConfigValue(SERVICES_EM_ANNO_API_URL)
Expand All @@ -17,7 +15,7 @@ export async function getAnnotations(req: EnhancedRequest, res: express.Response
const annotationsPath: string = url + req.originalUrl.replace('/em-anno/', '/api/')

try {
const jsonResponse: Annotations = await handleGet(annotationsPath)
const jsonResponse: Annotations = await handleGet(annotationsPath, req)
res.status(200).send(jsonResponse)
} catch (error) {
res.status(error.status).send({
Expand All @@ -36,7 +34,7 @@ export async function postAnnotations(req: EnhancedRequest, res: express.Respons
const body: Annotation = req.body

try {
const jsonResponse: Annotation = await handlePost(annotationsPath, body)
const jsonResponse: Annotation = await handlePost(annotationsPath, body, req)
res.status(200).send(jsonResponse)
} catch (error) {
res.status(error.status).send({
Expand All @@ -55,7 +53,7 @@ export async function putAnnotations(req: EnhancedRequest, res: express.Response
const body: Annotation = req.body

try {
const jsonResponse: Annotation = await handlePut(annotationsPath, body)
const jsonResponse: Annotation = await handlePut(annotationsPath, body, req)
res.status(200).send(jsonResponse)
} catch (error) {
res.status(error.status).send({
Expand All @@ -73,7 +71,7 @@ export async function deleteAnnotations(req: EnhancedRequest, res: express.Respo
const annotationsPath: string = url + req.originalUrl.replace('/em-anno/', '/api/')

try {
const jsonResponse: Annotation = await handleDelete(annotationsPath)
const jsonResponse: Annotation = await handleDelete(annotationsPath, req)
res.status(200).send(jsonResponse)
} catch (error) {
res.status(error.status).send({
Expand Down
23 changes: 14 additions & 9 deletions api/lib/middleware/auth.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
import axios from 'axios'
/**
* Note that authorization headers have been moved from this file to proxy.ts
* to achieve better security.
*/

import * as jwtDecode from 'jwt-decode'
import * as auth from '../../auth'
import {getConfigValue} from '../../configuration'
import {
COOKIES_TOKEN,
COOKIES_USER_ID,
SERVICES_IDAM_API_URL,
} from '../../configuration/references'
import { getConfigValue } from '../../configuration'
import { COOKIES_TOKEN, COOKIES_USER_ID, SERVICES_IDAM_API_URL } from '../../configuration/references'
import * as log4jui from '../../lib/log4jui'
import { getDetails } from '../../services/idam'
import { asyncReturnOrError } from '../util'
Expand Down Expand Up @@ -65,8 +65,13 @@ export default async (req, res, next) => {
req.auth.token = jwt
req.auth.userId = userId

axios.defaults.headers.common.Authorization = `Bearer ${req.auth.token}`
axios.defaults.headers.common['user-roles'] = req.auth.data.roles.join()
// !!!
// The commented lines below have been moved to proxy.ts, where the information
// is added to the request JIT, instead of setting it as a global default
// to improve security.

// axios.defaults.headers.common.Authorization = `Bearer ${req.auth.token}`
// axios.defaults.headers.common['user-roles'] = req.auth.data.roles.join()

logger.info('Auth token: ' + `Bearer ${req.auth.token}`)

Expand Down
Loading

0 comments on commit 7d0b81c

Please sign in to comment.