@budibase/worker 2.4.44-alpha.1 → 2.4.44-alpha.11

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.
@@ -1,5 +1,5 @@
1
1
  import Router from "@koa/router"
2
- import { api } from "@budibase/pro"
2
+ import { api as pro } from "@budibase/pro"
3
3
  import userRoutes from "./global/users"
4
4
  import configRoutes from "./global/configs"
5
5
  import workspaceRoutes from "./global/workspaces"
@@ -17,9 +17,6 @@ import migrationRoutes from "./system/migrations"
17
17
  import accountRoutes from "./system/accounts"
18
18
  import restoreRoutes from "./system/restore"
19
19
 
20
- let userGroupRoutes = api.groups
21
- let auditLogRoutes = api.auditLogs
22
-
23
20
  export const routes: Router[] = [
24
21
  configRoutes,
25
22
  userRoutes,
@@ -33,10 +30,11 @@ export const routes: Router[] = [
33
30
  statusRoutes,
34
31
  selfRoutes,
35
32
  licenseRoutes,
36
- userGroupRoutes,
37
- auditLogRoutes,
33
+ pro.groups,
34
+ pro.auditLogs,
38
35
  migrationRoutes,
39
36
  accountRoutes,
40
37
  restoreRoutes,
41
38
  eventRoutes,
39
+ pro.scim,
42
40
  ]
@@ -47,7 +47,6 @@ const environment = {
47
47
  // flags
48
48
  NODE_ENV: process.env.NODE_ENV,
49
49
  SELF_HOSTED: !!parseInt(process.env.SELF_HOSTED || ""),
50
- LOG_LEVEL: process.env.LOG_LEVEL,
51
50
  MULTI_TENANCY: process.env.MULTI_TENANCY,
52
51
  DISABLE_ACCOUNT_PORTAL: process.env.DISABLE_ACCOUNT_PORTAL,
53
52
  SMTP_FALLBACK_ENABLED: process.env.SMTP_FALLBACK_ENABLED,
package/src/index.ts CHANGED
@@ -2,10 +2,6 @@ if (process.env.DD_APM_ENABLED) {
2
2
  require("./ddApm")
3
3
  }
4
4
 
5
- if (process.env.ELASTIC_APM_ENABLED) {
6
- require("./elasticApm")
7
- }
8
-
9
5
  // need to load environment first
10
6
  import env from "./environment"
11
7
  import { Scope } from "@sentry/node"
@@ -31,10 +27,11 @@ import api from "./api"
31
27
  import * as redis from "./utilities/redis"
32
28
  const Sentry = require("@sentry/node")
33
29
  const koaSession = require("koa-session")
34
- const logger = require("koa-pino-logger")
35
30
  const { userAgent } = require("koa-useragent")
36
31
 
37
32
  import destroyable from "server-destroy"
33
+ import { initPro } from "./initPro"
34
+ import { handleScimBody } from "./middleware/handleScimBody"
38
35
 
39
36
  // configure events to use the pro audit log write
40
37
  // can't integrate directly into backend-core due to cyclic issues
@@ -54,10 +51,12 @@ const app: Application = new Koa()
54
51
  app.keys = ["secret", "key"]
55
52
 
56
53
  // set up top level koa middleware
54
+ app.use(handleScimBody)
57
55
  app.use(koaBody({ multipart: true }))
56
+
58
57
  app.use(koaSession(app))
59
- app.use(middleware.logging)
60
- app.use(logger(logging.pinoSettings()))
58
+ app.use(middleware.correlation)
59
+ app.use(middleware.pino)
61
60
  app.use(userAgent)
62
61
 
63
62
  // authentication
@@ -108,6 +107,7 @@ const shutdown = () => {
108
107
 
109
108
  export default server.listen(parseInt(env.PORT || "4002"), async () => {
110
109
  console.log(`Worker running on ${JSON.stringify(server.address())}`)
110
+ await initPro()
111
111
  await redis.init()
112
112
  })
113
113
 
package/src/initPro.ts ADDED
@@ -0,0 +1,13 @@
1
+ import { sdk as proSdk } from "@budibase/pro"
2
+ import * as userSdk from "./sdk/users"
3
+
4
+ export const initPro = async () => {
5
+ await proSdk.init({
6
+ scimUserServiceConfig: {
7
+ functions: {
8
+ saveUser: userSdk.save,
9
+ removeUser: (id: string) => userSdk.destroy(id),
10
+ },
11
+ },
12
+ })
13
+ }
@@ -0,0 +1,12 @@
1
+ import { Ctx } from "@budibase/types"
2
+
3
+ export const handleScimBody = (ctx: Ctx, next: any) => {
4
+ var type = ctx.req.headers["content-type"] || ""
5
+ type = type.split(";")[0]
6
+
7
+ if (type === "application/scim+json") {
8
+ ctx.req.headers["content-type"] = "application/json"
9
+ }
10
+
11
+ return next()
12
+ }
@@ -15,6 +15,7 @@ import {
15
15
  utils,
16
16
  ViewName,
17
17
  env as coreEnv,
18
+ context,
18
19
  } from "@budibase/backend-core"
19
20
  import {
20
21
  AccountMetadata,
@@ -37,8 +38,6 @@ import { EmailTemplatePurpose } from "../../constants"
37
38
  import * as pro from "@budibase/pro"
38
39
  import * as accountSdk from "../accounts"
39
40
 
40
- const PAGE_LIMIT = 8
41
-
42
41
  export const allUsers = async () => {
43
42
  const db = tenancy.getGlobalDB()
44
43
  const response = await db.allDocs(
@@ -68,43 +67,6 @@ export const getUsersByAppAccess = async (appId?: string) => {
68
67
  return response
69
68
  }
70
69
 
71
- export const paginatedUsers = async ({
72
- page,
73
- email,
74
- appId,
75
- }: SearchUsersRequest = {}) => {
76
- const db = tenancy.getGlobalDB()
77
- // get one extra document, to have the next page
78
- const opts: any = {
79
- include_docs: true,
80
- limit: PAGE_LIMIT + 1,
81
- }
82
- // add a startkey if the page was specified (anchor)
83
- if (page) {
84
- opts.startkey = page
85
- }
86
- // property specifies what to use for the page/anchor
87
- let userList,
88
- property = "_id",
89
- getKey
90
- if (appId) {
91
- userList = await usersCore.searchGlobalUsersByApp(appId, opts)
92
- getKey = (doc: any) => usersCore.getGlobalUserByAppPage(appId, doc)
93
- } else if (email) {
94
- userList = await usersCore.searchGlobalUsersByEmail(email, opts)
95
- property = "email"
96
- } else {
97
- // no search, query allDocs
98
- const response = await db.allDocs(dbUtils.getGlobalUserParams(null, opts))
99
- userList = response.rows.map((row: any) => row.doc)
100
- }
101
- return dbUtils.pagination(userList, PAGE_LIMIT, {
102
- paginate: true,
103
- property,
104
- getKey,
105
- })
106
- }
107
-
108
70
  export async function getUserByEmail(email: string) {
109
71
  return usersCore.getGlobalUserByEmail(email)
110
72
  }
@@ -576,7 +538,7 @@ export const bulkDelete = async (
576
538
  return response
577
539
  }
578
540
 
579
- export const destroy = async (id: string, currentUser: any) => {
541
+ export const destroy = async (id: string) => {
580
542
  const db = tenancy.getGlobalDB()
581
543
  const dbUser = (await db.get(id)) as User
582
544
  const userId = dbUser._id as string
@@ -586,7 +548,7 @@ export const destroy = async (id: string, currentUser: any) => {
586
548
  const email = dbUser.email
587
549
  const account = await accounts.getAccount(email)
588
550
  if (account) {
589
- if (email === currentUser.email) {
551
+ if (dbUser.userId === context.getIdentity()!._id) {
590
552
  throw new HTTPError('Please visit "Account" to delete this user', 400)
591
553
  } else {
592
554
  throw new HTTPError("Account holder cannot be deleted", 400)
@@ -20,9 +20,18 @@ import {
20
20
  auth,
21
21
  constants,
22
22
  env as coreEnv,
23
+ db as dbCore,
24
+ encryption,
25
+ utils,
23
26
  } from "@budibase/backend-core"
24
27
  import structures, { CSRF_TOKEN } from "./structures"
25
- import { SaveUserResponse, User, AuthToken } from "@budibase/types"
28
+ import {
29
+ SaveUserResponse,
30
+ User,
31
+ AuthToken,
32
+ SCIMConfig,
33
+ ConfigType,
34
+ } from "@budibase/types"
26
35
  import API from "./api"
27
36
 
28
37
  class TestConfiguration {
@@ -31,6 +40,7 @@ class TestConfiguration {
31
40
  api: API
32
41
  tenantId: string
33
42
  user?: User
43
+ apiKey?: string
34
44
  userPassword = "test"
35
45
 
36
46
  constructor(opts: { openServer: boolean } = { openServer: true }) {
@@ -49,6 +59,12 @@ class TestConfiguration {
49
59
  this.api = new API(this)
50
60
  }
51
61
 
62
+ async useNewTenant() {
63
+ this.tenantId = structures.tenant.id()
64
+
65
+ await this.beforeAll()
66
+ }
67
+
52
68
  getRequest() {
53
69
  return this.request
54
70
  }
@@ -201,6 +217,12 @@ class TestConfiguration {
201
217
  return { [constants.Header.API_KEY]: coreEnv.INTERNAL_API_KEY }
202
218
  }
203
219
 
220
+ bearerAPIHeaders() {
221
+ return {
222
+ [constants.Header.AUTHORIZATION]: `Bearer ${this.apiKey}`,
223
+ }
224
+ }
225
+
204
226
  adminOnlyResponse = () => {
205
227
  return { message: "Admin user only endpoint.", status: 403 }
206
228
  }
@@ -213,6 +235,20 @@ class TestConfiguration {
213
235
  })
214
236
  await context.doInTenant(this.tenantId!, async () => {
215
237
  this.user = await this.createUser(user)
238
+
239
+ const db = context.getGlobalDB()
240
+
241
+ const id = dbCore.generateDevInfoID(this.user._id)
242
+ // TODO: dry
243
+ this.apiKey = encryption.encrypt(
244
+ `${this.tenantId}${dbCore.SEPARATOR}${utils.newid()}`
245
+ )
246
+ const devInfo = {
247
+ _id: id,
248
+ userId: this.user._id,
249
+ apiKey: this.apiKey,
250
+ }
251
+ await db.put(devInfo)
216
252
  })
217
253
  }
218
254
 
@@ -305,6 +341,19 @@ class TestConfiguration {
305
341
  controllers.config.save
306
342
  )
307
343
  }
344
+
345
+ // CONFIGS - SCIM
346
+
347
+ async setSCIMConfig(enabled: boolean) {
348
+ await this.deleteConfig(Config.SCIM)
349
+ const config: SCIMConfig = {
350
+ type: ConfigType.SCIM,
351
+ config: { enabled },
352
+ }
353
+
354
+ await this._req(config, null, controllers.config.save)
355
+ return config
356
+ }
308
357
  }
309
358
 
310
359
  export default TestConfiguration
@@ -15,6 +15,9 @@ import { RolesAPI } from "./roles"
15
15
  import { TemplatesAPI } from "./templates"
16
16
  import { LicenseAPI } from "./license"
17
17
  import { AuditLogAPI } from "./auditLogs"
18
+ import { ScimUsersAPI } from "./scim/users"
19
+ import { ScimGroupsAPI } from "./scim/groups"
20
+
18
21
  export default class API {
19
22
  accounts: AccountAPI
20
23
  auth: AuthAPI
@@ -32,6 +35,8 @@ export default class API {
32
35
  templates: TemplatesAPI
33
36
  license: LicenseAPI
34
37
  auditLogs: AuditLogAPI
38
+ scimUsersAPI: ScimUsersAPI
39
+ scimGroupsAPI: ScimGroupsAPI
35
40
 
36
41
  constructor(config: TestConfiguration) {
37
42
  this.accounts = new AccountAPI(config)
@@ -50,5 +55,7 @@ export default class API {
50
55
  this.templates = new TemplatesAPI(config)
51
56
  this.license = new LicenseAPI(config)
52
57
  this.auditLogs = new AuditLogAPI(config)
58
+ this.scimUsersAPI = new ScimUsersAPI(config)
59
+ this.scimGroupsAPI = new ScimGroupsAPI(config)
53
60
  }
54
61
  }
@@ -0,0 +1,94 @@
1
+ import {
2
+ ScimCreateGroupRequest,
3
+ ScimGroupListResponse,
4
+ ScimGroupResponse,
5
+ ScimUpdateRequest,
6
+ } from "@budibase/types"
7
+ import TestConfiguration from "../../TestConfiguration"
8
+ import { RequestSettings, ScimTestAPI } from "./shared"
9
+
10
+ export class ScimGroupsAPI extends ScimTestAPI {
11
+ constructor(config: TestConfiguration) {
12
+ super(config)
13
+ }
14
+
15
+ get = async (
16
+ requestSettings?: Partial<RequestSettings> & {
17
+ params?: {
18
+ startIndex?: number
19
+ pageSize?: number
20
+ filter?: string
21
+ }
22
+ }
23
+ ) => {
24
+ let url = `/api/global/scim/v2/groups?`
25
+ const params = requestSettings?.params
26
+ if (params?.pageSize) {
27
+ url += `count=${params.pageSize}&`
28
+ }
29
+ if (params?.startIndex) {
30
+ url += `startIndex=${params.startIndex}&`
31
+ }
32
+ if (params?.filter) {
33
+ url += `filter=${params.filter}&`
34
+ }
35
+ const res = await this.call(url, "get", requestSettings)
36
+ return res.body as ScimGroupListResponse
37
+ }
38
+
39
+ post = async (
40
+ {
41
+ body,
42
+ }: {
43
+ body: ScimCreateGroupRequest
44
+ },
45
+ requestSettings?: Partial<RequestSettings>
46
+ ) => {
47
+ const res = await this.call(
48
+ `/api/global/scim/v2/groups`,
49
+ "post",
50
+ requestSettings,
51
+ body
52
+ )
53
+
54
+ return res.body as ScimGroupResponse
55
+ }
56
+
57
+ find = async (id: string, requestSettings?: Partial<RequestSettings>) => {
58
+ const res = await this.call(
59
+ `/api/global/scim/v2/groups/${id}`,
60
+ "get",
61
+ requestSettings
62
+ )
63
+ return res.body as ScimGroupResponse
64
+ }
65
+
66
+ delete = async (id: string, requestSettings?: Partial<RequestSettings>) => {
67
+ const res = await this.call(
68
+ `/api/global/scim/v2/groups/${id}`,
69
+ "delete",
70
+ requestSettings
71
+ )
72
+ return res.body as ScimGroupResponse
73
+ }
74
+
75
+ patch = async (
76
+ {
77
+ id,
78
+ body,
79
+ }: {
80
+ id: string
81
+ body: ScimUpdateRequest
82
+ },
83
+ requestSettings?: Partial<RequestSettings>
84
+ ) => {
85
+ const res = await this.call(
86
+ `/api/global/scim/v2/groups/${id}`,
87
+ "patch",
88
+ requestSettings,
89
+ body
90
+ )
91
+
92
+ return res.body as ScimGroupResponse
93
+ }
94
+ }
@@ -0,0 +1,44 @@
1
+ import TestConfiguration from "../../TestConfiguration"
2
+ import { TestAPI } from "../base"
3
+
4
+ const defaultConfig = {
5
+ expect: 200,
6
+ setHeaders: true,
7
+ skipContentTypeCheck: false,
8
+ }
9
+
10
+ export type RequestSettings = typeof defaultConfig
11
+
12
+ export abstract class ScimTestAPI extends TestAPI {
13
+ constructor(config: TestConfiguration) {
14
+ super(config)
15
+ }
16
+
17
+ call = (
18
+ url: string,
19
+ method: "get" | "post" | "patch" | "delete",
20
+ requestSettings?: Partial<RequestSettings>,
21
+ body?: object
22
+ ) => {
23
+ const { expect, setHeaders } = { ...defaultConfig, ...requestSettings }
24
+ let request = this.request[method](url).expect(expect)
25
+
26
+ request = request.set(
27
+ "content-type",
28
+ "application/scim+json; charset=utf-8"
29
+ )
30
+
31
+ if (method !== "delete" && !requestSettings?.skipContentTypeCheck) {
32
+ request = request.expect("Content-Type", /json/)
33
+ }
34
+
35
+ if (body) {
36
+ request = request.send(body)
37
+ }
38
+
39
+ if (setHeaders) {
40
+ request = request.set(this.config.bearerAPIHeaders())
41
+ }
42
+ return request
43
+ }
44
+ }
@@ -0,0 +1,94 @@
1
+ import {
2
+ ScimUserListResponse,
3
+ ScimCreateUserRequest,
4
+ ScimUserResponse,
5
+ ScimUpdateRequest,
6
+ } from "@budibase/types"
7
+ import TestConfiguration from "../../TestConfiguration"
8
+ import { RequestSettings, ScimTestAPI } from "./shared"
9
+
10
+ export class ScimUsersAPI extends ScimTestAPI {
11
+ constructor(config: TestConfiguration) {
12
+ super(config)
13
+ }
14
+
15
+ get = async (
16
+ requestSettings?: Partial<RequestSettings> & {
17
+ params?: {
18
+ startIndex?: number
19
+ pageSize?: number
20
+ filter?: string
21
+ }
22
+ }
23
+ ) => {
24
+ let url = `/api/global/scim/v2/users?`
25
+ const params = requestSettings?.params
26
+ if (params?.pageSize) {
27
+ url += `count=${params.pageSize}&`
28
+ }
29
+ if (params?.startIndex) {
30
+ url += `startIndex=${params.startIndex}&`
31
+ }
32
+ if (params?.filter) {
33
+ url += `filter=${params.filter}&`
34
+ }
35
+ const res = await this.call(url, "get", requestSettings)
36
+ return res.body as ScimUserListResponse
37
+ }
38
+
39
+ find = async (id: string, requestSettings?: Partial<RequestSettings>) => {
40
+ const res = await this.call(
41
+ `/api/global/scim/v2/users/${id}`,
42
+ "get",
43
+ requestSettings
44
+ )
45
+ return res.body as ScimUserResponse
46
+ }
47
+
48
+ post = async (
49
+ {
50
+ body,
51
+ }: {
52
+ body: ScimCreateUserRequest
53
+ },
54
+ requestSettings?: Partial<RequestSettings>
55
+ ) => {
56
+ const res = await this.call(
57
+ `/api/global/scim/v2/users`,
58
+ "post",
59
+ requestSettings,
60
+ body
61
+ )
62
+
63
+ return res.body as ScimUserResponse
64
+ }
65
+
66
+ patch = async (
67
+ {
68
+ id,
69
+ body,
70
+ }: {
71
+ id: string
72
+ body: ScimUpdateRequest
73
+ },
74
+ requestSettings?: Partial<RequestSettings>
75
+ ) => {
76
+ const res = await this.call(
77
+ `/api/global/scim/v2/users/${id}`,
78
+ "patch",
79
+ requestSettings,
80
+ body
81
+ )
82
+
83
+ return res.body as ScimUserResponse
84
+ }
85
+
86
+ delete = async (id: string, requestSettings?: Partial<RequestSettings>) => {
87
+ const res = await this.call(
88
+ `/api/global/scim/v2/users/${id}`,
89
+ "delete",
90
+ requestSettings
91
+ )
92
+ return res.body as ScimUserResponse
93
+ }
94
+ }
@@ -2,7 +2,6 @@ process.env.SELF_HOSTED = "0"
2
2
  process.env.NODE_ENV = "jest"
3
3
  process.env.JWT_SECRET = "test-jwtsecret"
4
4
  process.env.LOG_LEVEL = process.env.LOG_LEVEL || "error"
5
- process.env.ENABLE_4XX_HTTP_LOGGING = "0"
6
5
  process.env.MULTI_TENANCY = "1"
7
6
  process.env.MINIO_URL = "http://localhost"
8
7
  process.env.MINIO_ACCESS_KEY = "test"
@@ -1,5 +1,3 @@
1
- import "./logging"
2
-
3
1
  import { mocks, testContainerUtils } from "@budibase/backend-core/tests"
4
2
  import env from "../environment"
5
3
  import { env as coreEnv, timers } from "@budibase/backend-core"
package/src/elasticApm.ts DELETED
@@ -1,10 +0,0 @@
1
- import apm from "elastic-apm-node"
2
-
3
- // enable APM if configured
4
- if (process.env.ELASTIC_APM_ENABLED) {
5
- console.log("Starting elastic-apm-node")
6
- apm.start({
7
- serviceName: process.env.SERVICE,
8
- environment: process.env.BUDIBASE_ENVIRONMENT,
9
- })
10
- }
@@ -1,34 +0,0 @@
1
- export enum LogLevel {
2
- TRACE = "trace",
3
- DEBUG = "debug",
4
- INFO = "info",
5
- WARN = "warn",
6
- ERROR = "error",
7
- }
8
-
9
- const LOG_INDEX: { [key in LogLevel]: number } = {
10
- [LogLevel.TRACE]: 1,
11
- [LogLevel.DEBUG]: 2,
12
- [LogLevel.INFO]: 3,
13
- [LogLevel.WARN]: 4,
14
- [LogLevel.ERROR]: 5,
15
- }
16
-
17
- const setIndex = LOG_INDEX[process.env.LOG_LEVEL as LogLevel]
18
-
19
- if (setIndex > LOG_INDEX.trace) {
20
- global.console.trace = jest.fn()
21
- }
22
-
23
- if (setIndex > LOG_INDEX.debug) {
24
- global.console.debug = jest.fn()
25
- }
26
-
27
- if (setIndex > LOG_INDEX.info) {
28
- global.console.info = jest.fn()
29
- global.console.log = jest.fn()
30
- }
31
-
32
- if (setIndex > LOG_INDEX.warn) {
33
- global.console.warn = jest.fn()
34
- }