-
-
Notifications
You must be signed in to change notification settings - Fork 18
/
Copy pathguard.ts
312 lines (267 loc) · 8.52 KB
/
guard.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
import lambdaRateLimiter from 'lambda-rate-limiter'
import type {
Context,
PrismaClient,
QueryParams,
Shield,
ShieldAuthorization,
ShieldRule,
} from './types'
import { DebugTestingKey } from './consts'
import { decode, encode, filterXSS, isEmpty, isMatchingGlob, merge, walk } from './utils'
import { CustomError } from './inspector'
// https:// github.com/blackflux/lambda-rate-limiter
const limiter = lambdaRateLimiter({
interval: 60 * 1000, // 60 seconds = 1 minute
uniqueTokenPerInterval: 1000,
})
/**
* #### Sanitize data (parse xss + encode html).
*
* @param {any} data
* @returns any
*/
export async function sanitize(data: any): Promise<any> {
return await walk(data, async ({ key, value }, node) => {
if (typeof key === 'string' && key === DebugTestingKey)
node.ignoreChilds()
if (typeof value === 'string')
value = encode(filterXSS(value))
return { key, value }
})
}
/**
* #### Clarify data (decode html).
*
* @param {any} data
* @returns any
*/
export async function clarify(data: any): Promise<any> {
return await walk(data, async ({ key, value }, node) => {
if (typeof key === 'string' && key === DebugTestingKey)
node.ignoreChilds()
if (typeof value === 'string')
value = decode(value)
return { key, value }
})
}
/**
* #### Returns an Shield authorization object for a given field.
*
* @param {any} options
* @param {Shield} options.shield
* @param {ShieldRule} options.shieldRule
* @param {string} options.globPattern
* @param {string} options.matcher
* @param {Context} options.context
* @returns Promise<ShieldAuthorization>
*/
async function getFieldAuthorization(
{ shield, shieldRule, globPattern, matcher, context }:
{
shield: Shield
shieldRule: ShieldRule
globPattern: string
matcher: string
context: Context
},
): Promise<ShieldAuthorization> {
const authorization: ShieldAuthorization = {
canAccess: true,
reason: String(),
prismaFilter: {},
matcher: String(),
globPattern: String(),
}
if (typeof shieldRule === 'boolean') {
authorization.canAccess = shield[matcher] as boolean
}
else {
if (typeof shieldRule.rule === 'undefined')
throw new Error('Badly formed shield rule.')
if (typeof shieldRule.rule === 'boolean') {
authorization.canAccess = shieldRule.rule
}
else if (typeof shieldRule.rule === 'function') {
const ruleResult = shieldRule.rule(context)
if (ruleResult instanceof Promise)
authorization.canAccess = await ruleResult
else if (typeof ruleResult === 'boolean')
authorization.canAccess = ruleResult
else
throw new Error('Shield rule must return a boolean.')
}
else {
authorization.canAccess = true
if (!authorization.prismaFilter)
authorization.prismaFilter = {}
authorization.prismaFilter = merge(authorization.prismaFilter, shieldRule.rule)
}
}
authorization.matcher = matcher
authorization.globPattern = globPattern
const isReasonDefined = typeof shieldRule !== 'boolean' && typeof shieldRule.reason !== 'undefined'
let reason = `Matcher: ${authorization.matcher}`
if (isReasonDefined && typeof shieldRule.reason === 'function')
reason = shieldRule.reason({ action: context.action, model: context.model?.singular || context.action })
else if (isReasonDefined && typeof shieldRule.reason === 'string')
reason = shieldRule.reason
authorization.reason = reason
return authorization
}
/**
* #### Returns an authorization object from a Shield configuration passed as input.
*
* @param {Shield} options.shield
* @param {string[]} options.paths
* @param {Context} options.context
* @returns ShieldAuthorization
*/
export async function getShieldAuthorization({
shield,
paths,
context,
}: {
shield: Shield
paths: string[]
context: Context
}): Promise<ShieldAuthorization> {
let authorization: ShieldAuthorization = {
canAccess: true,
reason: String(),
prismaFilter: {},
matcher: String(),
globPattern: String(),
}
for (const matcher in shield) {
const concurrentFieldsAuthCheck: Promise<any>[] = []
const globPattern = matcher
for (let i = paths.length - 1; i >= 0; i--) {
const reqPath: string = paths[i]
if (isMatchingGlob(reqPath, globPattern)) {
const shieldRule = shield[matcher]
concurrentFieldsAuthCheck.push(
getFieldAuthorization({ shield, shieldRule, globPattern, matcher, context }),
)
}
}
const fieldsAuthCheckResults = await Promise.allSettled(concurrentFieldsAuthCheck)
for (let fieldIndex = 0; fieldIndex < fieldsAuthCheckResults.length; fieldIndex++) {
const fieldAuthCheckResult = fieldsAuthCheckResults[fieldIndex]
if (fieldAuthCheckResult.status === 'rejected') {
throw new CustomError(fieldAuthCheckResult.reason, { type: 'INTERNAL_SERVER_ERROR' })
}
else {
authorization = fieldAuthCheckResult.value
if (!fieldAuthCheckResult.value.canAccess)
break
}
}
}
return authorization
}
/**
* #### Returns GraphQL query depth for any given Query.
*
* @param {any} options
* @param {string[]} options.paths
* @param {Context} options.context
* @param {any} options.fieldsMapping
* @returns number
*/
export function getDepth(
{ paths, context, fieldsMapping }:
{ paths: string[]; context: Context; fieldsMapping: any },
): number {
let depth = 0
const stopPaths: string[] = []
if (!isEmpty(fieldsMapping)) {
for (const fieldMap in fieldsMapping) {
if (fieldsMapping[fieldMap].type.toLowerCase() === 'json')
stopPaths.push(String(fieldMap))
}
}
paths.forEach((path: string) => {
const stopPath = stopPaths.find((p: string) => path.includes(p))
const stopIndex = stopPath ? stopPath.split('/').length - 1 : undefined
const parts = path.split('/').filter(Boolean).slice(1, stopIndex ? stopIndex + 1 : undefined)
const pathDepth = parts.length
if (pathDepth > depth)
depth = pathDepth
})
if (context.model === null)
depth += 1
return depth
}
/**
* #### Execute hooks that apply to a given Query.
*
* @param {any} options
* @param {'before' | 'after'} options.when
* @param {any} options.hooks
* @param {PrismaClient} options.prismaClient
* @param {QueryParams} options.QueryParams
* @param {any | any[]} options.result
* @returns Promise<void | any>
*/
export async function runHooks({
when,
hooks,
prismaClient,
QueryParams,
result,
}: {
when: 'before' | 'after'
hooks: any
prismaClient: PrismaClient
QueryParams: QueryParams
result?: any | any[]
}): Promise<void | any> {
const matchingHooks = Object.keys(hooks).filter((hookPath: string) => {
const hookParts = hookPath.split(':')
const hookWhen = hookParts[0]
const hookGlob = hookParts[1]
const currentPath = QueryParams.operation
return hookWhen === when && isMatchingGlob(currentPath, hookGlob)
})
let hookResponse = when === 'after'
? { ...QueryParams, result }
: QueryParams
if (matchingHooks.length > 0) {
for (let index = 0; index < matchingHooks.length; index++) {
const hookPath = matchingHooks[index]
if (Object.prototype.hasOwnProperty.call(hooks, hookPath)) {
hookResponse = await hooks[hookPath]({
...QueryParams,
...(typeof result !== 'undefined' && when === 'after' && { result }),
prismaClient,
})
}
}
}
return hookResponse
}
export async function preventDOS({
callerUuid,
maxReqPerMinute,
}: {
callerUuid: string
maxReqPerMinute: number
}): Promise<{
limitExceeded: boolean
count: number
}> {
let limitExceeded = false
let count = -1
try {
count = await limiter.check(maxReqPerMinute, callerUuid)
}
catch (error) {
limitExceeded = true
count = maxReqPerMinute
}
return {
limitExceeded,
count,
}
}