-
Notifications
You must be signed in to change notification settings - Fork 90
/
Copy pathapp.ts
335 lines (302 loc) · 9.96 KB
/
app.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
import { Server } from 'http'
import { EventEmitter } from 'events'
import { IocContract } from '@adonisjs/fold'
import { Knex } from 'knex'
import Koa, { DefaultState, DefaultContext } from 'koa'
import bodyParser from 'koa-bodyparser'
import session from 'koa-session'
import cors from '@koa/cors'
import { Logger } from 'pino'
import Router from '@koa/router'
import { IAppConfig } from './config/app'
import { ClientService } from './client/service'
import { GrantService } from './grant/service'
import { AccessTokenRoutes } from './accessToken/routes'
import { createValidatorMiddleware, HttpMethod } from 'openapi'
import {
grantInitiationHttpsigMiddleware,
grantContinueHttpsigMiddleware,
tokenHttpsigMiddleware
} from './signature/middleware'
export interface AppContextData extends DefaultContext {
logger: Logger
closeEmitter: EventEmitter
container: AppContainer
// Set by @koa/router
params: { [key: string]: string }
// Set by koa-generic-session
session: { [key: string]: string }
// TODO: define separate Context used in routes that include httpsig
clientKeyId?: string
}
export type AppContext = Koa.ParameterizedContext<DefaultState, AppContextData>
export interface DatabaseCleanupRule {
/**
* the name of the column containing the starting time from which the age will be computed
* ex: `createdAt` or `updatedAt`
*/
absoluteStartTimeColumnName: string
/**
* the name of the column containing the time offset, in seconds, since
* `absoluteStartTimeColumnName`, which specifies when the row expires
*/
expirationOffsetColumnName: string
/**
* the minimum number of days since expiration before rows of
* this table will be considered safe to delete during clean up
*/
defaultExpirationOffsetDays: number
}
export interface AppServices {
logger: Promise<Logger>
knex: Promise<Knex>
closeEmitter: Promise<EventEmitter>
config: Promise<IAppConfig>
// TODO: Add GNAP-related services
clientService: Promise<ClientService>
grantService: Promise<GrantService>
accessTokenRoutes: Promise<AccessTokenRoutes>
}
export type AppContainer = IocContract<AppServices>
export class App {
private koa!: Koa<DefaultState, AppContext>
private publicRouter!: Router<DefaultState, AppContext>
private server!: Server
private closeEmitter!: EventEmitter
private logger!: Logger
private config!: IAppConfig
private databaseCleanupRules!: {
[tableName: string]: DatabaseCleanupRule | undefined
}
public isShuttingDown = false
public constructor(private container: IocContract<AppServices>) {}
/**
* The boot function exists because the functions that we register on the container with the `bind` method are async.
* We then need to await this function when we call use - which can't be done in the constructor. This is a first pass to
* get the container working. We can refactor this in future. Perhaps don't use private members and just pass around the container?
* Or provide start / shutdown methods on the services in the container?
*/
public async boot(): Promise<void> {
this.config = await this.container.use('config')
this.koa = new Koa<DefaultState, AppContext>()
this.closeEmitter = await this.container.use('closeEmitter')
this.logger = await this.container.use('logger')
this.koa.context.container = this.container
this.koa.context.logger = await this.container.use('logger')
this.koa.context.closeEmitter = await this.container.use('closeEmitter')
this.publicRouter = new Router<DefaultState, AppContext>()
this.databaseCleanupRules = {
accessTokens: {
absoluteStartTimeColumnName: 'createdAt',
expirationOffsetColumnName: 'expiresIn',
defaultExpirationOffsetDays: this.config.accessTokenDeletionDays
}
}
this.koa.use(cors())
this.koa.keys = [this.config.cookieKey]
this.koa.use(
session(
{
key: 'sessionId',
// TODO: make this time shorter?
maxAge: 60 * 1000,
signed: true
},
// Only accepts Middleware<DefaultState, DefaultContext> for some reason, this.koa is Middleware<DefaultState, AppContext>
// eslint-disable-next-line @typescript-eslint/no-explicit-any
this.koa as any
)
)
this.koa.use(
async (
ctx: {
status: number
set: (arg0: string, arg1: string) => void
body: string
},
next: () => void | PromiseLike<void>
): Promise<void> => {
if (this.isShuttingDown) {
ctx.status = 503
ctx.set('Connection', 'close')
ctx.body = 'Server is in the process of restarting'
} else {
return next()
}
}
)
await this._setupRoutes()
if (this.config.env !== 'test') {
for (let i = 0; i < this.config.databaseCleanupWorkers; i++) {
process.nextTick(() => this.processDatabaseCleanup())
}
}
}
public listen(port: number | string): void {
this.server = this.koa.listen(port)
}
public async shutdown(): Promise<void> {
return new Promise((resolve): void => {
if (this.server) {
this.isShuttingDown = true
this.closeEmitter.emit('shutdown')
this.server.close((): void => {
resolve()
})
} else {
resolve()
}
})
}
public getPort(): number {
const address = this.server?.address()
if (address && !(typeof address == 'string')) {
return address.port
}
return 0
}
private async _setupRoutes(): Promise<void> {
this.publicRouter.use(bodyParser())
this.publicRouter.get('/healthz', (ctx: AppContext): void => {
ctx.status = 200
})
this.publicRouter.get('/discovery', (ctx: AppContext): void => {
ctx.body = {
grant_request_endpoint: '/',
interaction_start_modes_supported: ['redirect'],
interaction_finish_modes_supported: ['redirect']
}
})
const accessTokenRoutes = await this.container.use('accessTokenRoutes')
const grantRoutes = await this.container.use('grantRoutes')
const openApi = await this.container.use('openApi')
/* Back-channel GNAP Routes */
// Grant Initiation
this.publicRouter.post(
'/',
createValidatorMiddleware(openApi.authServerSpec, {
path: '/',
method: HttpMethod.POST
}),
this.config.bypassSignatureValidation
? (ctx, next) => next()
: grantInitiationHttpsigMiddleware,
grantRoutes.create
)
// Grant Continue
this.publicRouter.post(
'/continue/:id',
createValidatorMiddleware(openApi.authServerSpec, {
path: '/continue/{id}',
method: HttpMethod.POST
}),
this.config.bypassSignatureValidation
? (ctx, next) => next()
: grantContinueHttpsigMiddleware,
grantRoutes.continue
)
// Token Rotation
this.publicRouter.post(
'/token/:id',
createValidatorMiddleware(openApi.authServerSpec, {
path: '/token/{id}',
method: HttpMethod.POST
}),
this.config.bypassSignatureValidation
? (ctx, next) => next()
: tokenHttpsigMiddleware,
accessTokenRoutes.rotate
)
// Token Revocation
this.publicRouter.delete(
'/token/:id',
createValidatorMiddleware(openApi.authServerSpec, {
path: '/token/{id}',
method: HttpMethod.DELETE
}),
this.config.bypassSignatureValidation
? (ctx, next) => next()
: tokenHttpsigMiddleware,
accessTokenRoutes.revoke
)
/* AS <-> RS Routes */
// Token Introspection
this.publicRouter.post(
'/introspect',
createValidatorMiddleware(openApi.tokenIntrospectionSpec, {
path: '/introspect',
method: HttpMethod.POST
}),
accessTokenRoutes.introspect
)
/* Front Channel Routes */
// TODO: update front-channel routes to have /frontend prefix here and in openapi spec
// Interaction start
this.publicRouter.get(
'/interact/:id/:nonce',
createValidatorMiddleware(openApi.idpSpec, {
path: '/interact/{id}/{nonce}',
method: HttpMethod.GET
}),
grantRoutes.interaction.start
)
// Interaction finish
this.publicRouter.get(
'/interact/:id/:nonce/finish',
createValidatorMiddleware(openApi.idpSpec, {
path: '/interact/{id}/{nonce}/finish',
method: HttpMethod.GET
}),
grantRoutes.interaction.finish
)
// Grant lookup
this.publicRouter.get(
'/grant/:id/:nonce',
createValidatorMiddleware(openApi.idpSpec, {
path: '/grant/{id}/{nonce}',
method: HttpMethod.GET
}),
grantRoutes.interaction.details
)
// Grant accept/reject
this.publicRouter.post(
'/grant/:id/:nonce/:choice',
createValidatorMiddleware(openApi.idpSpec, {
path: '/grant/{id}/{nonce}/{choice}',
method: HttpMethod.POST
}),
grantRoutes.interaction.acceptOrReject
)
this.koa.use(this.publicRouter.middleware())
}
private async processDatabaseCleanup(): Promise<void> {
const knex = await this.container.use('knex')
const tableNames = Object.keys(this.databaseCleanupRules)
for (const tableName of tableNames) {
const rule = this.databaseCleanupRules[tableName]
if (rule) {
try {
/**
* NOTE: do not remove seemingly pointless interpolations such as '${'??'}'
* because they are necessary for preventing SQL injection attacks
*/
await knex(tableName)
.whereRaw(
`?? + make_interval(0, 0, 0, 0, 0, 0, ??) + interval '${'??'}' < NOW()`,
[
rule.absoluteStartTimeColumnName,
rule.expirationOffsetColumnName,
`${rule.defaultExpirationOffsetDays} days`
]
)
.del()
} catch (err) {
this.logger.warn(
{ error: err.message, tableName },
'processDatabaseCleanup error'
)
}
}
}
}
}