@contember/engine-http 2.2.0-alpha.17 → 2.2.0-alpha.19
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/development/index.cjs +3 -1
- package/dist/development/index.cjs.map +1 -1
- package/dist/development/index.js +4 -2
- package/dist/development/index.js.map +1 -1
- package/dist/development/src/MasterContainer.cjs +5 -4
- package/dist/development/src/MasterContainer.cjs.map +1 -1
- package/dist/development/src/MasterContainer.js +5 -4
- package/dist/development/src/MasterContainer.js.map +1 -1
- package/dist/development/src/application/PanelApiMount.cjs.map +1 -1
- package/dist/development/src/application/PanelApiMount.js.map +1 -1
- package/dist/development/src/application/application.cjs +27 -21
- package/dist/development/src/application/application.cjs.map +1 -1
- package/dist/development/src/application/application.js +27 -21
- package/dist/development/src/application/application.js.map +1 -1
- package/dist/development/src/application/compression.cjs +99 -0
- package/dist/development/src/application/compression.cjs.map +1 -0
- package/dist/development/src/application/compression.js +82 -0
- package/dist/development/src/application/compression.js.map +1 -0
- package/dist/development/src/application/cors.cjs +52 -0
- package/dist/development/src/application/cors.cjs.map +1 -0
- package/dist/development/src/application/cors.js +52 -0
- package/dist/development/src/application/cors.js.map +1 -0
- package/dist/development/src/application/requestBody.cjs +242 -0
- package/dist/development/src/application/requestBody.cjs.map +1 -0
- package/dist/development/src/application/requestBody.js +242 -0
- package/dist/development/src/application/requestBody.js.map +1 -0
- package/dist/development/src/application/requestBodyMasking.cjs +97 -0
- package/dist/development/src/application/requestBodyMasking.cjs.map +1 -0
- package/dist/development/src/application/requestBodyMasking.js +97 -0
- package/dist/development/src/application/requestBodyMasking.js.map +1 -0
- package/dist/development/src/config/configSchema.cjs +36 -1
- package/dist/development/src/config/configSchema.cjs.map +1 -1
- package/dist/development/src/config/configSchema.js +36 -1
- package/dist/development/src/config/configSchema.js.map +1 -1
- package/dist/development/src/config/configTemplate.cjs +5 -0
- package/dist/development/src/config/configTemplate.cjs.map +1 -1
- package/dist/development/src/config/configTemplate.js +5 -0
- package/dist/development/src/config/configTemplate.js.map +1 -1
- package/dist/development/src/content/ProjectMembershipResolver.cjs +10 -3
- package/dist/development/src/content/ProjectMembershipResolver.cjs.map +1 -1
- package/dist/development/src/content/ProjectMembershipResolver.js +10 -3
- package/dist/development/src/content/ProjectMembershipResolver.js.map +1 -1
- package/dist/development/src/graphql/execution.cjs +3 -9
- package/dist/development/src/graphql/execution.cjs.map +1 -1
- package/dist/development/src/graphql/execution.js +3 -9
- package/dist/development/src/graphql/execution.js.map +1 -1
- package/dist/development/src/project/ProjectContainer.cjs +1 -1
- package/dist/development/src/project/ProjectContainer.js +1 -1
- package/dist/development/src/projectGroup/ProjectGroupContainer.cjs +3 -2
- package/dist/development/src/projectGroup/ProjectGroupContainer.cjs.map +1 -1
- package/dist/development/src/projectGroup/ProjectGroupContainer.js +3 -2
- package/dist/development/src/projectGroup/ProjectGroupContainer.js.map +1 -1
- package/dist/development/src/providers.cjs +2 -2
- package/dist/development/src/providers.cjs.map +1 -1
- package/dist/development/src/providers.js +2 -2
- package/dist/development/src/providers.js.map +1 -1
- package/dist/development/src/transfer/ImportApiMiddlewareFactory.cjs +2 -2
- package/dist/development/src/transfer/ImportApiMiddlewareFactory.cjs.map +1 -1
- package/dist/development/src/transfer/ImportExecutor.cjs +33 -5
- package/dist/development/src/transfer/ImportExecutor.cjs.map +1 -1
- package/dist/development/src/transfer/ImportExecutor.js +33 -5
- package/dist/development/src/transfer/ImportExecutor.js.map +1 -1
- package/dist/development/src/utils/CryptoWrapper.cjs +11 -0
- package/dist/development/src/utils/CryptoWrapper.cjs.map +1 -1
- package/dist/development/src/utils/CryptoWrapper.js +11 -0
- package/dist/development/src/utils/CryptoWrapper.js.map +1 -1
- package/dist/development/src/utils/sentry.cjs +32 -49
- package/dist/development/src/utils/sentry.cjs.map +1 -1
- package/dist/development/src/utils/sentry.js +33 -33
- package/dist/development/src/utils/sentry.js.map +1 -1
- package/dist/development/src/utils/serverStartup.cjs +5 -3
- package/dist/development/src/utils/serverStartup.cjs.map +1 -1
- package/dist/development/src/utils/serverStartup.js +5 -3
- package/dist/development/src/utils/serverStartup.js.map +1 -1
- package/dist/production/index.cjs +3 -1
- package/dist/production/index.cjs.map +1 -1
- package/dist/production/index.js +4 -2
- package/dist/production/index.js.map +1 -1
- package/dist/production/src/MasterContainer.cjs +5 -4
- package/dist/production/src/MasterContainer.cjs.map +1 -1
- package/dist/production/src/MasterContainer.js +5 -4
- package/dist/production/src/MasterContainer.js.map +1 -1
- package/dist/production/src/application/PanelApiMount.cjs.map +1 -1
- package/dist/production/src/application/PanelApiMount.js.map +1 -1
- package/dist/production/src/application/application.cjs +27 -21
- package/dist/production/src/application/application.cjs.map +1 -1
- package/dist/production/src/application/application.js +27 -21
- package/dist/production/src/application/application.js.map +1 -1
- package/dist/production/src/application/compression.cjs +99 -0
- package/dist/production/src/application/compression.cjs.map +1 -0
- package/dist/production/src/application/compression.js +82 -0
- package/dist/production/src/application/compression.js.map +1 -0
- package/dist/production/src/application/cors.cjs +52 -0
- package/dist/production/src/application/cors.cjs.map +1 -0
- package/dist/production/src/application/cors.js +52 -0
- package/dist/production/src/application/cors.js.map +1 -0
- package/dist/production/src/application/requestBody.cjs +242 -0
- package/dist/production/src/application/requestBody.cjs.map +1 -0
- package/dist/production/src/application/requestBody.js +242 -0
- package/dist/production/src/application/requestBody.js.map +1 -0
- package/dist/production/src/application/requestBodyMasking.cjs +97 -0
- package/dist/production/src/application/requestBodyMasking.cjs.map +1 -0
- package/dist/production/src/application/requestBodyMasking.js +97 -0
- package/dist/production/src/application/requestBodyMasking.js.map +1 -0
- package/dist/production/src/config/configSchema.cjs +36 -1
- package/dist/production/src/config/configSchema.cjs.map +1 -1
- package/dist/production/src/config/configSchema.js +36 -1
- package/dist/production/src/config/configSchema.js.map +1 -1
- package/dist/production/src/config/configTemplate.cjs +5 -0
- package/dist/production/src/config/configTemplate.cjs.map +1 -1
- package/dist/production/src/config/configTemplate.js +5 -0
- package/dist/production/src/config/configTemplate.js.map +1 -1
- package/dist/production/src/content/ProjectMembershipResolver.cjs +10 -3
- package/dist/production/src/content/ProjectMembershipResolver.cjs.map +1 -1
- package/dist/production/src/content/ProjectMembershipResolver.js +10 -3
- package/dist/production/src/content/ProjectMembershipResolver.js.map +1 -1
- package/dist/production/src/graphql/execution.cjs +3 -9
- package/dist/production/src/graphql/execution.cjs.map +1 -1
- package/dist/production/src/graphql/execution.js +3 -9
- package/dist/production/src/graphql/execution.js.map +1 -1
- package/dist/production/src/project/ProjectContainer.cjs +1 -1
- package/dist/production/src/project/ProjectContainer.js +1 -1
- package/dist/production/src/projectGroup/ProjectGroupContainer.cjs +3 -2
- package/dist/production/src/projectGroup/ProjectGroupContainer.cjs.map +1 -1
- package/dist/production/src/projectGroup/ProjectGroupContainer.js +3 -2
- package/dist/production/src/projectGroup/ProjectGroupContainer.js.map +1 -1
- package/dist/production/src/providers.cjs +2 -2
- package/dist/production/src/providers.cjs.map +1 -1
- package/dist/production/src/providers.js +2 -2
- package/dist/production/src/providers.js.map +1 -1
- package/dist/production/src/transfer/ImportApiMiddlewareFactory.cjs +2 -2
- package/dist/production/src/transfer/ImportApiMiddlewareFactory.cjs.map +1 -1
- package/dist/production/src/transfer/ImportExecutor.cjs +33 -5
- package/dist/production/src/transfer/ImportExecutor.cjs.map +1 -1
- package/dist/production/src/transfer/ImportExecutor.js +33 -5
- package/dist/production/src/transfer/ImportExecutor.js.map +1 -1
- package/dist/production/src/utils/CryptoWrapper.cjs +11 -0
- package/dist/production/src/utils/CryptoWrapper.cjs.map +1 -1
- package/dist/production/src/utils/CryptoWrapper.js +11 -0
- package/dist/production/src/utils/CryptoWrapper.js.map +1 -1
- package/dist/production/src/utils/sentry.cjs +32 -49
- package/dist/production/src/utils/sentry.cjs.map +1 -1
- package/dist/production/src/utils/sentry.js +33 -33
- package/dist/production/src/utils/sentry.js.map +1 -1
- package/dist/production/src/utils/serverStartup.cjs +5 -3
- package/dist/production/src/utils/serverStartup.cjs.map +1 -1
- package/dist/production/src/utils/serverStartup.js +5 -3
- package/dist/production/src/utils/serverStartup.js.map +1 -1
- package/dist/tests/cases/unit/compression.test.d.ts +2 -0
- package/dist/tests/cases/unit/compression.test.d.ts.map +1 -0
- package/dist/tests/cases/unit/cors.test.d.ts +2 -0
- package/dist/tests/cases/unit/cors.test.d.ts.map +1 -0
- package/dist/tests/cases/unit/requestBody.test.d.ts +2 -0
- package/dist/tests/cases/unit/requestBody.test.d.ts.map +1 -0
- package/dist/tests/cases/unit/requestBodyLogging.test.d.ts +2 -0
- package/dist/tests/cases/unit/requestBodyLogging.test.d.ts.map +1 -0
- package/dist/tests/cases/unit/requestBodyMasking.test.d.ts +2 -0
- package/dist/tests/cases/unit/requestBodyMasking.test.d.ts.map +1 -0
- package/dist/tests/tsconfig.tsbuildinfo +1 -1
- package/dist/types/MasterContainer.d.ts +8 -1
- package/dist/types/MasterContainer.d.ts.map +1 -1
- package/dist/types/application/PanelApiMount.d.ts +2 -0
- package/dist/types/application/PanelApiMount.d.ts.map +1 -1
- package/dist/types/application/application.d.ts +7 -1
- package/dist/types/application/application.d.ts.map +1 -1
- package/dist/types/application/compression.d.ts +19 -0
- package/dist/types/application/compression.d.ts.map +1 -0
- package/dist/types/application/cors.d.ts +10 -0
- package/dist/types/application/cors.d.ts.map +1 -0
- package/dist/types/application/index.d.ts +1 -0
- package/dist/types/application/index.d.ts.map +1 -1
- package/dist/types/application/requestBody.d.ts +45 -0
- package/dist/types/application/requestBody.d.ts.map +1 -0
- package/dist/types/application/requestBodyMasking.d.ts +10 -0
- package/dist/types/application/requestBodyMasking.d.ts.map +1 -0
- package/dist/types/config/configSchema.d.ts +13 -3
- package/dist/types/config/configSchema.d.ts.map +1 -1
- package/dist/types/config/configTemplate.d.ts.map +1 -1
- package/dist/types/content/ProjectMembershipResolver.d.ts.map +1 -1
- package/dist/types/graphql/execution.d.ts.map +1 -1
- package/dist/types/projectGroup/ProjectGroupContainer.d.ts.map +1 -1
- package/dist/types/transfer/ImportExecutor.d.ts +2 -0
- package/dist/types/transfer/ImportExecutor.d.ts.map +1 -1
- package/dist/types/tsconfig.tsbuildinfo +1 -1
- package/dist/types/utils/CryptoWrapper.d.ts +5 -0
- package/dist/types/utils/CryptoWrapper.d.ts.map +1 -1
- package/dist/types/utils/sentry.d.ts +13 -6
- package/dist/types/utils/sentry.d.ts.map +1 -1
- package/dist/types/utils/serverStartup.d.ts.map +1 -1
- package/package.json +18 -24
- package/src/MasterContainer.ts +5 -3
- package/src/application/PanelApiMount.ts +2 -0
- package/src/application/application.ts +38 -20
- package/src/application/compression.ts +118 -0
- package/src/application/cors.ts +61 -0
- package/src/application/index.ts +1 -0
- package/src/application/requestBody.ts +295 -0
- package/src/application/requestBodyMasking.ts +117 -0
- package/src/config/configSchema.ts +38 -1
- package/src/config/configTemplate.ts +5 -0
- package/src/content/ProjectMembershipResolver.ts +13 -5
- package/src/graphql/execution.ts +3 -9
- package/src/projectGroup/ProjectGroupContainer.ts +1 -0
- package/src/providers.ts +2 -2
- package/src/transfer/ImportExecutor.ts +37 -5
- package/src/tsconfig.json +3 -1
- package/src/utils/CryptoWrapper.ts +12 -0
- package/src/utils/sentry.ts +42 -39
- package/src/utils/serverStartup.ts +7 -5
- package/tests/cases/unit/compression.test.ts +172 -0
- package/tests/cases/unit/cors.test.ts +106 -0
- package/tests/cases/unit/crypto.test.ts +16 -0
- package/tests/cases/unit/projectMembershipResolver.test.ts +50 -0
- package/tests/cases/unit/requestBody.test.ts +333 -0
- package/tests/cases/unit/requestBodyLogging.test.ts +89 -0
- package/tests/cases/unit/requestBodyMasking.test.ts +102 -0
- package/tests/cases/unit/sentryLoggerHandler.test.ts +74 -20
- package/tests/cases/unit/serverConfig.test.ts +42 -0
- package/dist/tests/cases/unit/sentryIntegrations.test.d.ts +0 -2
- package/dist/tests/cases/unit/sentryIntegrations.test.d.ts.map +0 -1
- package/tests/cases/unit/sentryIntegrations.test.ts +0 -15
|
@@ -4,6 +4,7 @@ import * as Typesafe from '@contember/typesafe'
|
|
|
4
4
|
import { ParseError } from '@contember/typesafe'
|
|
5
5
|
import { Command, CommandArgsMap, CommandName } from './Command.js'
|
|
6
6
|
import { DatabaseContext, StageBySlugQuery } from '@contember/engine-system-api'
|
|
7
|
+
import { isImpossibleCalendarDate } from '@contember/engine-content-api'
|
|
7
8
|
import { DbColumnSchema, TransferMapping, TransferTableMapping } from './TransferMapping.js'
|
|
8
9
|
import { ContentSchemaTransferMappingFactory } from './ContentSchemaTransferMappingFactory.js'
|
|
9
10
|
import { SystemSchemaTransferMappingFactory } from './SystemSchemaTransferMappingFactory.js'
|
|
@@ -66,6 +67,15 @@ const listType = <T extends Typesafe.Json>(arrayType: Typesafe.Type<T>): Typesaf
|
|
|
66
67
|
}
|
|
67
68
|
}
|
|
68
69
|
|
|
70
|
+
// PostgreSQL would fail the whole batch insert on an impossible date with a server error that names neither column nor row.
|
|
71
|
+
const calendarDate: Typesafe.Type<string> = (input: unknown, path: PropertyKey[] = []) => {
|
|
72
|
+
const value = Typesafe.string(input, path)
|
|
73
|
+
if (isImpossibleCalendarDate(value)) {
|
|
74
|
+
throw new ParseError(path, `${JSON.stringify(value)} is not a valid date`)
|
|
75
|
+
}
|
|
76
|
+
return value
|
|
77
|
+
}
|
|
78
|
+
|
|
69
79
|
type CommandProcessor<T extends CommandName> = (it: CommandIterator<T>) => Promise<CommandIterator | null>
|
|
70
80
|
type CommandProcessorMap<T extends CommandName> = { [N in CommandName]?: N extends T ? CommandProcessor<N> : undefined }
|
|
71
81
|
|
|
@@ -159,6 +169,7 @@ export class ImportExecutor {
|
|
|
159
169
|
await this.requireImportAccess(groupContainer, contentSchema.schema, authResult, options.project, 'content')
|
|
160
170
|
const contentDatabaseClient = projectContainer.connection.createClient(stage.schema, {})
|
|
161
171
|
const mapping = this.contentSchemaTransferMappingFactory.createContentSchemaMapping(contentSchema.schema)
|
|
172
|
+
this.requireMappedTables(mapping, options.tables, `content schema of project ${options.project}`)
|
|
162
173
|
|
|
163
174
|
return await contentDatabaseClient.transaction(async db => {
|
|
164
175
|
await this.disableTimeouts(db)
|
|
@@ -198,6 +209,7 @@ export class ImportExecutor {
|
|
|
198
209
|
await this.requireImportAccess(groupContainer, schema, authResult, options.project, 'system')
|
|
199
210
|
const systemDatabaseContext = projectContainer.systemDatabaseContext
|
|
200
211
|
const mapping = this.systemSchemaTransferMappingFactory.build()
|
|
212
|
+
this.requireMappedTables(mapping, options.tables, `system schema of project ${options.project}`)
|
|
201
213
|
|
|
202
214
|
return await systemDatabaseContext.client.transaction(async db => {
|
|
203
215
|
await this.disableTimeouts(db)
|
|
@@ -219,6 +231,9 @@ export class ImportExecutor {
|
|
|
219
231
|
it: CommandIterator<'importSequence'>,
|
|
220
232
|
): Promise<CommandIterator | null> {
|
|
221
233
|
const [options] = it.commandArgs
|
|
234
|
+
if (!Object.hasOwn(mapping.tables, options.table) || !Object.hasOwn(mapping.tables[options.table].columns, options.column)) {
|
|
235
|
+
throw new ImportError(`Unknown column ${options.table}.${options.column}`)
|
|
236
|
+
}
|
|
222
237
|
|
|
223
238
|
await db.query(
|
|
224
239
|
'SELECT setval(pg_get_serial_sequence(?, ?), ?)',
|
|
@@ -248,7 +263,14 @@ export class ImportExecutor {
|
|
|
248
263
|
insertContext.rows.push(insertContext.rowParser(values))
|
|
249
264
|
} catch (e) {
|
|
250
265
|
if (e instanceof ParseError) {
|
|
251
|
-
|
|
266
|
+
const rowNumber = insertContext.insertedRowCount + insertContext.rows.length + 1
|
|
267
|
+
// The row parser is a tuple over the insertBegin columns, so the first path segment is the column index.
|
|
268
|
+
const [columnIndex, ...valuePath] = e.path
|
|
269
|
+
const columnName = columnIndex !== undefined ? options.columns[Number(columnIndex)] : undefined
|
|
270
|
+
const elementLocation = valuePath.length > 0 ? `, element /${valuePath.map(String).join('/')}` : ''
|
|
271
|
+
const location = columnName !== undefined ? `table ${options.table}, column ${columnName}${elementLocation}` : `table ${options.table}`
|
|
272
|
+
const reason = columnName !== undefined ? e.reason : e.message
|
|
273
|
+
throw new ImportError(`Invalid row #${rowNumber} ${JSON.stringify(values)} for ${location}: ${reason}`)
|
|
252
274
|
} else {
|
|
253
275
|
throw e
|
|
254
276
|
}
|
|
@@ -314,6 +336,15 @@ export class ImportExecutor {
|
|
|
314
336
|
}
|
|
315
337
|
}
|
|
316
338
|
|
|
339
|
+
/** The tables an import truncates must come from the same mapping an export of this schema lists. */
|
|
340
|
+
private requireMappedTables(mapping: TransferMapping, tableNames: readonly string[], target: string) {
|
|
341
|
+
for (const tableName of tableNames) {
|
|
342
|
+
if (!Object.hasOwn(mapping.tables, tableName)) {
|
|
343
|
+
throw new ImportError(`Table ${tableName} is not part of the ${target}`)
|
|
344
|
+
}
|
|
345
|
+
}
|
|
346
|
+
}
|
|
347
|
+
|
|
317
348
|
private async fetchStageBySlug(systemDatabaseContext: DatabaseContext, projectSlug: string, stageSlug: string) {
|
|
318
349
|
const stage = await systemDatabaseContext.queryHandler.fetch(new StageBySlugQuery(stageSlug))
|
|
319
350
|
|
|
@@ -374,7 +405,7 @@ export class ImportExecutor {
|
|
|
374
405
|
tableName: string,
|
|
375
406
|
columnNames: readonly string[],
|
|
376
407
|
): Promise<InsertContext> {
|
|
377
|
-
const tableMapping = mapping.tables[tableName]
|
|
408
|
+
const tableMapping = Object.hasOwn(mapping.tables, tableName) ? mapping.tables[tableName] : undefined
|
|
378
409
|
const columns = []
|
|
379
410
|
|
|
380
411
|
if (tableMapping === undefined) {
|
|
@@ -382,7 +413,7 @@ export class ImportExecutor {
|
|
|
382
413
|
}
|
|
383
414
|
|
|
384
415
|
for (const columnName of columnNames) {
|
|
385
|
-
const column = tableMapping.columns[columnName]
|
|
416
|
+
const column = Object.hasOwn(tableMapping.columns, columnName) ? tableMapping.columns[columnName] : undefined
|
|
386
417
|
|
|
387
418
|
if (column === undefined) {
|
|
388
419
|
throw new ImportError(`Unknown column ${tableName}.${columnName}`)
|
|
@@ -429,13 +460,14 @@ export class ImportExecutor {
|
|
|
429
460
|
case Model.ColumnType.Uuid:
|
|
430
461
|
case Model.ColumnType.String:
|
|
431
462
|
case Model.ColumnType.Enum:
|
|
432
|
-
case Model.ColumnType.DateTime:
|
|
433
463
|
case Model.ColumnType.Time:
|
|
434
|
-
case Model.ColumnType.Date:
|
|
435
464
|
case Model.ColumnType.Json:
|
|
436
465
|
// Numeric is transferred as a string to avoid JS float precision loss.
|
|
437
466
|
case Model.ColumnType.Numeric:
|
|
438
467
|
return column.list ? listType(Typesafe.array(Typesafe.string)) : Typesafe.string
|
|
468
|
+
case Model.ColumnType.Date:
|
|
469
|
+
case Model.ColumnType.DateTime:
|
|
470
|
+
return column.list ? listType(Typesafe.array(calendarDate)) : calendarDate
|
|
439
471
|
case Model.ColumnType.Int:
|
|
440
472
|
case Model.ColumnType.Double:
|
|
441
473
|
return column.list ? listType(Typesafe.array(Typesafe.number)) : Typesafe.number
|
package/src/tsconfig.json
CHANGED
|
@@ -19,7 +19,9 @@
|
|
|
19
19
|
{ "path": "../../schema-migrations/src" },
|
|
20
20
|
{ "path": "../../schema-utils/src" },
|
|
21
21
|
{ "path": "../../schema-utils/src" },
|
|
22
|
+
{ "path": "../../sentry-client/src" },
|
|
22
23
|
{ "path": "../../telemetry/src" },
|
|
23
|
-
{ "path": "../../typesafe/src" }
|
|
24
|
+
{ "path": "../../typesafe/src" },
|
|
25
|
+
{ "path": "../../utilities/src" }
|
|
24
26
|
]
|
|
25
27
|
}
|
|
@@ -27,6 +27,18 @@ export class CryptoWrapper {
|
|
|
27
27
|
}
|
|
28
28
|
}
|
|
29
29
|
|
|
30
|
+
/**
|
|
31
|
+
* HMAC-SHA256 under a key derived (HKDF) from the encryption key for `purpose`, so signatures never use the
|
|
32
|
+
* encryption key itself and a signature made for one purpose does not verify for another.
|
|
33
|
+
*/
|
|
34
|
+
sign(purpose: string, value: Buffer): Buffer {
|
|
35
|
+
if (!this.encryptionKey) {
|
|
36
|
+
throw new Error('encryption key not provided')
|
|
37
|
+
}
|
|
38
|
+
const signingKey = Buffer.from(crypto.hkdfSync('sha256', this.encryptionKey, Buffer.alloc(0), `contember-signing:${purpose}`, 32))
|
|
39
|
+
return crypto.createHmac('sha256', signingKey).update(value).digest()
|
|
40
|
+
}
|
|
41
|
+
|
|
30
42
|
async decrypt(value: Buffer, version: number): Promise<{ value: Buffer; needsReEncrypt: boolean }> {
|
|
31
43
|
if (!this.encryptionKey) {
|
|
32
44
|
throw new Error('encryption key not provided')
|
package/src/utils/sentry.ts
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import * as Sentry from '@sentry/node'
|
|
2
1
|
import { LogEntry, LoggerHandler, LogLevel, LogLevelName, LogLevels } from '@contember/logger'
|
|
2
|
+
import { createSentryClient, installProcessHandlers, SentryClient, SeverityLevel } from '@contember/sentry-client'
|
|
3
3
|
import { LoggerRequestBody } from '../application/index.js'
|
|
4
4
|
|
|
5
|
-
const logLevelMapping: Record<LogLevelName,
|
|
5
|
+
const logLevelMapping: Record<LogLevelName, SeverityLevel> = {
|
|
6
6
|
crit: 'fatal',
|
|
7
7
|
error: 'error',
|
|
8
8
|
warn: 'warning',
|
|
@@ -10,9 +10,12 @@ const logLevelMapping: Record<LogLevelName, Sentry.SeverityLevel> = {
|
|
|
10
10
|
info: 'info',
|
|
11
11
|
}
|
|
12
12
|
|
|
13
|
+
const stringAttribute = (value: unknown): string | undefined => typeof value === 'string' ? value : undefined
|
|
14
|
+
|
|
13
15
|
export class SentryLoggerHandler implements LoggerHandler {
|
|
14
16
|
constructor(
|
|
15
17
|
private readonly logLevel: LogLevel,
|
|
18
|
+
private readonly client: SentryClient,
|
|
16
19
|
) {
|
|
17
20
|
}
|
|
18
21
|
|
|
@@ -24,31 +27,17 @@ export class SentryLoggerHandler implements LoggerHandler {
|
|
|
24
27
|
if (!entry.error || entry.level.value < this.logLevel.value) {
|
|
25
28
|
return
|
|
26
29
|
}
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
}
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
const traceId = entry.loggerAttributes.traceId
|
|
39
|
-
const spanId = entry.loggerAttributes.spanId
|
|
40
|
-
return {
|
|
41
|
-
...event,
|
|
42
|
-
request: {
|
|
43
|
-
url: entry.loggerAttributes.url ?? entry.ownAttributes.url,
|
|
44
|
-
data: entry.loggerAttributes[LoggerRequestBody],
|
|
45
|
-
},
|
|
46
|
-
...(typeof traceId === 'string' && typeof spanId === 'string'
|
|
47
|
-
? { contexts: { ...event.contexts, trace: { trace_id: traceId, span_id: spanId } } }
|
|
48
|
-
: {}),
|
|
49
|
-
}
|
|
50
|
-
})
|
|
51
|
-
return scope
|
|
30
|
+
const attribute = (name: string): string | undefined => stringAttribute(entry.loggerAttributes[name] ?? entry.ownAttributes[name])
|
|
31
|
+
const traceId = stringAttribute(entry.loggerAttributes.traceId)
|
|
32
|
+
const spanId = stringAttribute(entry.loggerAttributes.spanId)
|
|
33
|
+
this.client.captureException(entry.error, {
|
|
34
|
+
level: logLevelMapping[entry.level.name],
|
|
35
|
+
tags: { project: attribute('project'), projectGroup: attribute('projectGroup'), module: attribute('module') },
|
|
36
|
+
user: { id: attribute('user') },
|
|
37
|
+
extra: { requestId: entry.loggerAttributes.requestId },
|
|
38
|
+
// the request logger sets `uri`, already masked by maskRequestUri
|
|
39
|
+
request: { url: attribute('uri'), data: entry.loggerAttributes[LoggerRequestBody] },
|
|
40
|
+
...(traceId !== undefined && spanId !== undefined ? { contexts: { trace: { trace_id: traceId, span_id: spanId } } } : {}),
|
|
52
41
|
})
|
|
53
42
|
}
|
|
54
43
|
|
|
@@ -56,20 +45,34 @@ export class SentryLoggerHandler implements LoggerHandler {
|
|
|
56
45
|
}
|
|
57
46
|
}
|
|
58
47
|
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
export const filterSentryIntegrations = (integrations: SentryIntegration[]): SentryIntegration[] =>
|
|
64
|
-
integrations.filter(integration => !['Console', 'Http', 'Undici'].includes(integration.name))
|
|
48
|
+
export interface SentryLoggerHandlerOptions {
|
|
49
|
+
/** Reported as the SDK version; the client is released together with the server, so this is the server version. */
|
|
50
|
+
readonly version?: string
|
|
51
|
+
}
|
|
65
52
|
|
|
66
|
-
|
|
53
|
+
/**
|
|
54
|
+
* Reports logged errors (warn and up) and uncaught exceptions and unhandled rejections of the process.
|
|
55
|
+
* Release, environment and server name come from SENTRY_RELEASE, SENTRY_ENVIRONMENT and SENTRY_NAME (default: the host name). Nothing instruments outgoing requests, whose
|
|
56
|
+
* URLs may carry a webhook credential.
|
|
57
|
+
*/
|
|
58
|
+
export const createSentryLoggerHandler = (dsn?: string, options: SentryLoggerHandlerOptions = {}): null | LoggerHandler => {
|
|
67
59
|
if (!dsn) {
|
|
68
60
|
return null
|
|
69
61
|
}
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
62
|
+
let client: SentryClient
|
|
63
|
+
try {
|
|
64
|
+
client = createSentryClient({
|
|
65
|
+
dsn,
|
|
66
|
+
release: process.env.SENTRY_RELEASE || undefined,
|
|
67
|
+
environment: process.env.SENTRY_ENVIRONMENT || undefined,
|
|
68
|
+
serverName: process.env.SENTRY_NAME || undefined,
|
|
69
|
+
version: options.version,
|
|
70
|
+
})
|
|
71
|
+
} catch (error) {
|
|
72
|
+
// as before: an invalid DSN turns reporting off instead of keeping the server from starting
|
|
73
|
+
console.error(`${error instanceof Error ? error.message : String(error)}; errors are not reported to Sentry`)
|
|
74
|
+
return null
|
|
75
|
+
}
|
|
76
|
+
installProcessHandlers(client)
|
|
77
|
+
return new SentryLoggerHandler(LogLevels.warn, client)
|
|
75
78
|
}
|
|
@@ -50,15 +50,17 @@ export const createDefaultLogger = (): Logger => {
|
|
|
50
50
|
formatters: {
|
|
51
51
|
pid: () => undefined,
|
|
52
52
|
loggerId: () => undefined,
|
|
53
|
-
uri: ({ attributes,
|
|
53
|
+
uri: ({ attributes, style }) => {
|
|
54
54
|
const color = attributes.status === undefined
|
|
55
|
-
?
|
|
55
|
+
? 'cyan'
|
|
56
56
|
: attributes.status < 300
|
|
57
|
-
?
|
|
58
|
-
:
|
|
57
|
+
? 'green'
|
|
58
|
+
: 'yellowBright'
|
|
59
59
|
const timeInfo = attributes.totalTimeMs !== undefined ? ` ${attributes.totalTimeMs}ms` : ''
|
|
60
60
|
const statusInfo = attributes.status !== undefined ? ` [${attributes.status}]` : ''
|
|
61
|
-
return {
|
|
61
|
+
return {
|
|
62
|
+
line: style(color, `${attributes.method}${statusInfo} ${attributes.uri}${timeInfo} ${style(['white', 'dim'], '#' + attributes.requestId)}`),
|
|
63
|
+
}
|
|
62
64
|
},
|
|
63
65
|
method: () => undefined,
|
|
64
66
|
requestId: () => undefined,
|
|
@@ -0,0 +1,172 @@
|
|
|
1
|
+
import { afterAll, beforeAll, describe, expect, test } from 'bun:test'
|
|
2
|
+
import Koa from 'koa'
|
|
3
|
+
import { IncomingHttpHeaders, request, Server } from 'node:http'
|
|
4
|
+
import { AddressInfo } from 'node:net'
|
|
5
|
+
import { Readable } from 'node:stream'
|
|
6
|
+
import { gunzipSync, gzipSync, inflateSync, zstdDecompressSync } from 'node:zlib'
|
|
7
|
+
import { createCompressionMiddleware, isCompressibleType, negotiateEncoding } from '../../../src/application/compression.js'
|
|
8
|
+
|
|
9
|
+
describe('negotiateEncoding', () => {
|
|
10
|
+
test('no header, identity, or only unsupported encodings: no compression', () => {
|
|
11
|
+
for (const header of ['', 'identity', 'br', 'compress', 'gzip;q=0', 'GZIP;q=0, deflate;q=0']) {
|
|
12
|
+
expect(negotiateEncoding(header)).toBeUndefined()
|
|
13
|
+
}
|
|
14
|
+
})
|
|
15
|
+
|
|
16
|
+
test('prefers zstd, then gzip, then deflate, at equal quality', () => {
|
|
17
|
+
expect(negotiateEncoding('gzip, deflate, br, zstd')).toBe('zstd')
|
|
18
|
+
expect(negotiateEncoding('deflate, gzip, br')).toBe('gzip')
|
|
19
|
+
expect(negotiateEncoding('deflate')).toBe('deflate')
|
|
20
|
+
expect(negotiateEncoding('GZip')).toBe('gzip')
|
|
21
|
+
})
|
|
22
|
+
|
|
23
|
+
test('quality decides first', () => {
|
|
24
|
+
expect(negotiateEncoding('gzip;q=0.5, deflate')).toBe('deflate')
|
|
25
|
+
expect(negotiateEncoding('zstd;q=0.9, deflate;q=1')).toBe('deflate')
|
|
26
|
+
expect(negotiateEncoding('gzip;q=abc, deflate;q=0.1')).toBe('deflate')
|
|
27
|
+
})
|
|
28
|
+
|
|
29
|
+
test('a bare * is gzip, and * covers what is not listed', () => {
|
|
30
|
+
expect(negotiateEncoding('*')).toBe('gzip')
|
|
31
|
+
expect(negotiateEncoding('*;q=0.5, zstd;q=0.1')).toBe('gzip')
|
|
32
|
+
expect(negotiateEncoding('*, identity;q=0')).toBe('zstd')
|
|
33
|
+
})
|
|
34
|
+
|
|
35
|
+
test('identity wins only with a higher quality', () => {
|
|
36
|
+
expect(negotiateEncoding('identity;q=1, gzip;q=0.5')).toBeUndefined()
|
|
37
|
+
expect(negotiateEncoding('identity, gzip')).toBe('gzip')
|
|
38
|
+
expect(negotiateEncoding('identity;q=0, gzip;q=0.1')).toBe('gzip')
|
|
39
|
+
})
|
|
40
|
+
})
|
|
41
|
+
|
|
42
|
+
test('isCompressibleType', () => {
|
|
43
|
+
for (
|
|
44
|
+
const type of [
|
|
45
|
+
'application/json',
|
|
46
|
+
'text/html',
|
|
47
|
+
'text/plain',
|
|
48
|
+
'text/css',
|
|
49
|
+
'text/javascript',
|
|
50
|
+
'application/javascript',
|
|
51
|
+
'image/svg+xml',
|
|
52
|
+
'application/manifest+json',
|
|
53
|
+
'Application/JSON',
|
|
54
|
+
]
|
|
55
|
+
) {
|
|
56
|
+
expect(isCompressibleType(type)).toBe(true)
|
|
57
|
+
}
|
|
58
|
+
for (const type of ['', 'image/png', 'font/woff2', 'application/octet-stream', 'application/x-ndjson']) {
|
|
59
|
+
expect(isCompressibleType(type)).toBe(false)
|
|
60
|
+
}
|
|
61
|
+
})
|
|
62
|
+
|
|
63
|
+
type Response = { status: number; headers: IncomingHttpHeaders; body: Buffer }
|
|
64
|
+
|
|
65
|
+
const get = (port: number, path: string, headers: Record<string, string>, method = 'GET'): Promise<Response> =>
|
|
66
|
+
new Promise((resolve, reject) => {
|
|
67
|
+
const req = request({ host: '127.0.0.1', port, path, method, headers }, res => {
|
|
68
|
+
const chunks: Buffer[] = []
|
|
69
|
+
res.on('data', chunk => chunks.push(chunk))
|
|
70
|
+
res.on('end', () => resolve({ status: res.statusCode ?? 0, headers: res.headers, body: Buffer.concat(chunks) }))
|
|
71
|
+
})
|
|
72
|
+
req.on('error', reject)
|
|
73
|
+
req.end()
|
|
74
|
+
})
|
|
75
|
+
|
|
76
|
+
describe('compression middleware', () => {
|
|
77
|
+
let server: Server
|
|
78
|
+
let port: number
|
|
79
|
+
const large = { data: 'x'.repeat(2000) }
|
|
80
|
+
const ndjson = '{"a":1}\n'.repeat(5)
|
|
81
|
+
|
|
82
|
+
beforeAll(async () => {
|
|
83
|
+
const koa = new Koa()
|
|
84
|
+
koa.silent = true
|
|
85
|
+
koa.use(createCompressionMiddleware())
|
|
86
|
+
koa.use(async ctx => {
|
|
87
|
+
switch (ctx.path) {
|
|
88
|
+
case '/large':
|
|
89
|
+
ctx.body = large
|
|
90
|
+
break
|
|
91
|
+
case '/small':
|
|
92
|
+
ctx.body = { data: 'x' }
|
|
93
|
+
break
|
|
94
|
+
case '/png':
|
|
95
|
+
ctx.type = 'image/png'
|
|
96
|
+
ctx.body = Buffer.alloc(2000)
|
|
97
|
+
break
|
|
98
|
+
case '/ndjson':
|
|
99
|
+
ctx.compress = true
|
|
100
|
+
ctx.type = 'application/x-ndjson'
|
|
101
|
+
ctx.body = Readable.from([ndjson])
|
|
102
|
+
break
|
|
103
|
+
case '/disabled':
|
|
104
|
+
ctx.compress = false
|
|
105
|
+
ctx.body = large
|
|
106
|
+
break
|
|
107
|
+
case '/no-transform':
|
|
108
|
+
ctx.set('Cache-Control', 'private, no-transform')
|
|
109
|
+
ctx.body = large
|
|
110
|
+
break
|
|
111
|
+
case '/encoded':
|
|
112
|
+
ctx.set('Content-Encoding', 'gzip')
|
|
113
|
+
ctx.type = 'text/plain'
|
|
114
|
+
ctx.body = gzipSync('y'.repeat(2000))
|
|
115
|
+
break
|
|
116
|
+
case '/empty':
|
|
117
|
+
ctx.status = 204
|
|
118
|
+
break
|
|
119
|
+
}
|
|
120
|
+
})
|
|
121
|
+
server = koa.listen(0)
|
|
122
|
+
await new Promise(resolve => server.once('listening', resolve))
|
|
123
|
+
port = (server.address() as AddressInfo).port
|
|
124
|
+
})
|
|
125
|
+
|
|
126
|
+
afterAll(() => {
|
|
127
|
+
server.close()
|
|
128
|
+
})
|
|
129
|
+
|
|
130
|
+
test('compresses a large JSON body with the negotiated encoding', async () => {
|
|
131
|
+
const gzip = await get(port, '/large', { 'Accept-Encoding': 'gzip, deflate' })
|
|
132
|
+
expect(gzip.headers['content-encoding']).toBe('gzip')
|
|
133
|
+
expect(gzip.headers['content-length']).toBeUndefined()
|
|
134
|
+
expect(gzip.headers.vary).toBe('Accept-Encoding')
|
|
135
|
+
expect(gzip.headers['content-type']).toBe('application/json; charset=utf-8')
|
|
136
|
+
expect(JSON.parse(gunzipSync(gzip.body).toString())).toEqual(large)
|
|
137
|
+
|
|
138
|
+
const deflate = await get(port, '/large', { 'Accept-Encoding': 'deflate' })
|
|
139
|
+
expect(JSON.parse(inflateSync(deflate.body).toString())).toEqual(large)
|
|
140
|
+
|
|
141
|
+
const zstd = await get(port, '/large', { 'Accept-Encoding': 'zstd, gzip' })
|
|
142
|
+
expect(zstd.headers['content-encoding']).toBe('zstd')
|
|
143
|
+
expect(JSON.parse(zstdDecompressSync(zstd.body).toString())).toEqual(large)
|
|
144
|
+
})
|
|
145
|
+
|
|
146
|
+
test('leaves the body alone without an accepted encoding', async () => {
|
|
147
|
+
const response = await get(port, '/large', {})
|
|
148
|
+
expect(response.headers['content-encoding']).toBeUndefined()
|
|
149
|
+
expect(response.headers.vary).toBe('Accept-Encoding')
|
|
150
|
+
expect(JSON.parse(response.body.toString())).toEqual(large)
|
|
151
|
+
})
|
|
152
|
+
|
|
153
|
+
test('a forced stream of a non-compressible type is compressed', async () => {
|
|
154
|
+
const response = await get(port, '/ndjson', { 'Accept-Encoding': 'gzip' })
|
|
155
|
+
expect(response.headers['content-encoding']).toBe('gzip')
|
|
156
|
+
expect(response.headers['content-type']).toBe('application/x-ndjson')
|
|
157
|
+
expect(gunzipSync(response.body).toString()).toBe(ndjson)
|
|
158
|
+
})
|
|
159
|
+
|
|
160
|
+
test('skips small, binary, opted-out, no-transform, already encoded, empty and HEAD responses', async () => {
|
|
161
|
+
for (const path of ['/small', '/png', '/disabled', '/no-transform']) {
|
|
162
|
+
const response = await get(port, path, { 'Accept-Encoding': 'gzip' })
|
|
163
|
+
expect([path, response.headers['content-encoding']]).toEqual([path, undefined])
|
|
164
|
+
}
|
|
165
|
+
const encoded = await get(port, '/encoded', { 'Accept-Encoding': 'zstd, deflate' })
|
|
166
|
+
expect(encoded.headers['content-encoding']).toBe('gzip')
|
|
167
|
+
expect(gunzipSync(encoded.body).toString()).toBe('y'.repeat(2000))
|
|
168
|
+
expect((await get(port, '/empty', { 'Accept-Encoding': 'gzip' })).headers['content-encoding']).toBeUndefined()
|
|
169
|
+
const head = await get(port, '/large', { 'Accept-Encoding': 'gzip' }, 'HEAD')
|
|
170
|
+
expect(head.headers['content-encoding']).toBeUndefined()
|
|
171
|
+
})
|
|
172
|
+
})
|
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
import { afterAll, beforeAll, describe, expect, test } from 'bun:test'
|
|
2
|
+
import Koa from 'koa'
|
|
3
|
+
import { IncomingHttpHeaders, request, Server } from 'node:http'
|
|
4
|
+
import { createCorsMiddleware } from '../../../src/application/cors.js'
|
|
5
|
+
|
|
6
|
+
type Response = { status: number; headers: IncomingHttpHeaders; body: string }
|
|
7
|
+
|
|
8
|
+
// node:http instead of fetch: the test preload installs a browser fetch that enforces CORS itself.
|
|
9
|
+
const send = (port: number, path: string, method: string, headers: Record<string, string> = {}): Promise<Response> =>
|
|
10
|
+
new Promise((resolve, reject) => {
|
|
11
|
+
const req = request({ host: '127.0.0.1', port, path, method, headers }, res => {
|
|
12
|
+
let body = ''
|
|
13
|
+
res.setEncoding('utf8')
|
|
14
|
+
res.on('data', chunk => body += chunk)
|
|
15
|
+
res.on('end', () => resolve({ status: res.statusCode ?? 0, headers: res.headers, body }))
|
|
16
|
+
})
|
|
17
|
+
req.on('error', reject)
|
|
18
|
+
req.end()
|
|
19
|
+
})
|
|
20
|
+
|
|
21
|
+
describe('CORS middleware', () => {
|
|
22
|
+
let server: Server
|
|
23
|
+
let port: number
|
|
24
|
+
|
|
25
|
+
beforeAll(async () => {
|
|
26
|
+
const koa = new Koa()
|
|
27
|
+
koa.silent = true
|
|
28
|
+
koa.use(createCorsMiddleware({ exposeHeaders: ['X-Contember-Mutation'] }))
|
|
29
|
+
koa.use(async ctx => {
|
|
30
|
+
if (ctx.path === '/fail-plain') {
|
|
31
|
+
throw Object.assign(new Error('boom'), { status: 409, expose: true })
|
|
32
|
+
}
|
|
33
|
+
if (ctx.path === '/fail') {
|
|
34
|
+
throw Object.assign(new Error('boom'), { status: 418, expose: true, headers: { 'X-Custom': 'kept', Vary: 'Accept' } })
|
|
35
|
+
}
|
|
36
|
+
ctx.set('X-Contember-Mutation', 'ok')
|
|
37
|
+
ctx.body = { method: ctx.method }
|
|
38
|
+
})
|
|
39
|
+
server = koa.listen(0)
|
|
40
|
+
await new Promise(resolve => server.once('listening', resolve))
|
|
41
|
+
const address = server.address()
|
|
42
|
+
if (address === null || typeof address === 'string') {
|
|
43
|
+
throw new Error('Expected a TCP address')
|
|
44
|
+
}
|
|
45
|
+
port = address.port
|
|
46
|
+
})
|
|
47
|
+
|
|
48
|
+
afterAll(() => {
|
|
49
|
+
server.close()
|
|
50
|
+
})
|
|
51
|
+
|
|
52
|
+
test('simple request gets allow-origin and expose-headers', async () => {
|
|
53
|
+
const response = await send(port, '/', 'POST', { Origin: 'https://example.com' })
|
|
54
|
+
expect(response.status).toBe(200)
|
|
55
|
+
expect(response.headers['access-control-allow-origin']).toBe('*')
|
|
56
|
+
expect(response.headers['access-control-expose-headers']).toBe('X-Contember-Mutation')
|
|
57
|
+
expect(response.headers['access-control-allow-credentials']).toBeUndefined()
|
|
58
|
+
expect(response.headers['vary']).toBe('Origin')
|
|
59
|
+
expect(JSON.parse(response.body)).toEqual({ method: 'POST' })
|
|
60
|
+
})
|
|
61
|
+
|
|
62
|
+
test('preflight answers 204 and echoes the requested headers', async () => {
|
|
63
|
+
const response = await send(port, '/', 'OPTIONS', {
|
|
64
|
+
Origin: 'https://example.com',
|
|
65
|
+
'Access-Control-Request-Method': 'POST',
|
|
66
|
+
'Access-Control-Request-Headers': 'authorization,content-type',
|
|
67
|
+
})
|
|
68
|
+
expect(response.status).toBe(204)
|
|
69
|
+
expect(response.headers['access-control-allow-origin']).toBe('*')
|
|
70
|
+
expect(response.headers['access-control-allow-methods']).toBe('GET,HEAD,PUT,POST,DELETE,PATCH')
|
|
71
|
+
expect(response.headers['access-control-allow-headers']).toBe('authorization,content-type')
|
|
72
|
+
expect(response.headers['access-control-expose-headers']).toBeUndefined()
|
|
73
|
+
expect(response.headers['vary']).toBe('Origin')
|
|
74
|
+
expect(response.body).toBe('')
|
|
75
|
+
})
|
|
76
|
+
|
|
77
|
+
test('preflight without requested headers sets no allow-headers', async () => {
|
|
78
|
+
const response = await send(port, '/', 'OPTIONS', { 'Access-Control-Request-Method': 'GET' })
|
|
79
|
+
expect(response.status).toBe(204)
|
|
80
|
+
expect(response.headers['access-control-allow-headers']).toBeUndefined()
|
|
81
|
+
})
|
|
82
|
+
|
|
83
|
+
test('OPTIONS without request method is not a preflight', async () => {
|
|
84
|
+
const response = await send(port, '/', 'OPTIONS')
|
|
85
|
+
expect(response.status).toBe(200)
|
|
86
|
+
expect(response.headers['access-control-allow-origin']).toBeUndefined()
|
|
87
|
+
expect(JSON.parse(response.body)).toEqual({ method: 'OPTIONS' })
|
|
88
|
+
})
|
|
89
|
+
|
|
90
|
+
test('CORS headers survive a thrown error', async () => {
|
|
91
|
+
const response = await send(port, '/fail', 'GET', { Origin: 'https://example.com' })
|
|
92
|
+
expect(response.status).toBe(418)
|
|
93
|
+
expect(response.headers['access-control-allow-origin']).toBe('*')
|
|
94
|
+
expect(response.headers['access-control-expose-headers']).toBe('X-Contember-Mutation')
|
|
95
|
+
expect(response.headers['x-custom']).toBe('kept')
|
|
96
|
+
expect(response.headers['vary']).toBe('Accept, Origin')
|
|
97
|
+
})
|
|
98
|
+
|
|
99
|
+
test('CORS headers survive a thrown error without own headers', async () => {
|
|
100
|
+
const response = await send(port, '/fail-plain', 'GET', { Origin: 'https://example.com' })
|
|
101
|
+
expect(response.status).toBe(409)
|
|
102
|
+
expect(response.headers['access-control-allow-origin']).toBe('*')
|
|
103
|
+
expect(response.headers['access-control-expose-headers']).toBe('X-Contember-Mutation')
|
|
104
|
+
expect(response.headers['vary']).toBe('Origin')
|
|
105
|
+
})
|
|
106
|
+
})
|
|
@@ -74,3 +74,19 @@ test('encryption v2: corrupted auth key', async () => {
|
|
|
74
74
|
}
|
|
75
75
|
assert.strictEqual('Unsupported state or unable to authenticate data', err.message)
|
|
76
76
|
})
|
|
77
|
+
|
|
78
|
+
test('signing is deterministic and bound to its purpose and key', () => {
|
|
79
|
+
const cryptoWrapper = new CryptoWrapper(encryptionKey)
|
|
80
|
+
const value = Buffer.from('payload')
|
|
81
|
+
const signature = cryptoWrapper.sign('first', value)
|
|
82
|
+
expect(signature).toHaveLength(32)
|
|
83
|
+
expect(cryptoWrapper.sign('first', value).equals(signature)).toBe(true)
|
|
84
|
+
expect(cryptoWrapper.sign('second', value).equals(signature)).toBe(false)
|
|
85
|
+
expect(crypto.createHmac('sha256', encryptionKey).update(value).digest().equals(signature)).toBe(false)
|
|
86
|
+
const otherKey = crypto.createSecretKey(Buffer.alloc(32, 1))
|
|
87
|
+
expect(new CryptoWrapper(otherKey).sign('first', value).equals(signature)).toBe(false)
|
|
88
|
+
})
|
|
89
|
+
|
|
90
|
+
test('signing without an encryption key fails', () => {
|
|
91
|
+
expect(() => new CryptoWrapper().sign('first', Buffer.from('payload'))).toThrow('encryption key not provided')
|
|
92
|
+
})
|
|
@@ -2,6 +2,7 @@ import { describe, expect, it } from 'bun:test'
|
|
|
2
2
|
import { ProjectMembershipFetcher, ProjectMembershipResolver } from '../../../src/index.js'
|
|
3
3
|
import { createMock } from '../../utils.js'
|
|
4
4
|
import { Acl } from '@contember/schema'
|
|
5
|
+
import { HttpErrorResponse } from '../../../src/common/HttpResponse.js'
|
|
5
6
|
|
|
6
7
|
describe('membership resolver', () => {
|
|
7
8
|
it('should return implicit role', async () => {
|
|
@@ -215,4 +216,53 @@ describe('membership resolver', () => {
|
|
|
215
216
|
variables: [{ name: 'lang', condition: { eq: 'cs' } }],
|
|
216
217
|
}])
|
|
217
218
|
})
|
|
219
|
+
|
|
220
|
+
const resolveWithAssumeHeader = async (header: string, storedMemberships: readonly Acl.Membership[]): Promise<unknown> => {
|
|
221
|
+
const membershipResolver = new ProjectMembershipResolver(
|
|
222
|
+
false,
|
|
223
|
+
createMock<ProjectMembershipFetcher>({
|
|
224
|
+
fetchMemberships: () => Promise.resolve(storedMemberships),
|
|
225
|
+
}),
|
|
226
|
+
)
|
|
227
|
+
try {
|
|
228
|
+
await membershipResolver.resolveMemberships({
|
|
229
|
+
request: { body: {}, get: name => name === 'x-contember-assume-membership' ? header : '' },
|
|
230
|
+
projectSlug: 'test',
|
|
231
|
+
identity: { identityId: 'd4141336-6512-41ef-a25a-374de35a2806', roles: [] },
|
|
232
|
+
acl: {
|
|
233
|
+
roles: {
|
|
234
|
+
editor: { variables: {}, entities: {}, content: { assumeMembership: { viewer: true } } },
|
|
235
|
+
viewer: { variables: {}, entities: {} },
|
|
236
|
+
},
|
|
237
|
+
},
|
|
238
|
+
})
|
|
239
|
+
return null
|
|
240
|
+
} catch (e) {
|
|
241
|
+
return e
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
it('answers 400 for an assume-membership header that is not JSON', async () => {
|
|
246
|
+
const error = await resolveWithAssumeHeader('{not json', [{ role: 'editor', variables: [] }])
|
|
247
|
+
expect(error).toBeInstanceOf(HttpErrorResponse)
|
|
248
|
+
expect(error).toMatchObject({ code: 400, message: 'Invalid JSON in x-contember-assume-membership header' })
|
|
249
|
+
})
|
|
250
|
+
|
|
251
|
+
it('answers 400 for an assume-membership header of a wrong shape', async () => {
|
|
252
|
+
const error = await resolveWithAssumeHeader('{"memberships": "viewer"}', [{ role: 'editor', variables: [] }])
|
|
253
|
+
expect(error).toBeInstanceOf(HttpErrorResponse)
|
|
254
|
+
expect(error).toMatchObject({ code: 400 })
|
|
255
|
+
})
|
|
256
|
+
|
|
257
|
+
it('a stored role missing from the ACL may not assume a membership', async () => {
|
|
258
|
+
const header = JSON.stringify({ memberships: [{ role: 'viewer', variables: [] }] })
|
|
259
|
+
const error = await resolveWithAssumeHeader(header, [{ role: 'removed', variables: [] }])
|
|
260
|
+
expect(error).toBeInstanceOf(HttpErrorResponse)
|
|
261
|
+
expect(error).toMatchObject({ code: 403 })
|
|
262
|
+
})
|
|
263
|
+
|
|
264
|
+
it('a stored role with an assume rule still assumes the allowed membership', async () => {
|
|
265
|
+
const header = JSON.stringify({ memberships: [{ role: 'viewer', variables: [] }] })
|
|
266
|
+
expect(await resolveWithAssumeHeader(header, [{ role: 'editor', variables: [] }])).toBeNull()
|
|
267
|
+
})
|
|
218
268
|
})
|