@teamkeel/functions-runtime 0.331.0 → 0.333.0

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@teamkeel/functions-runtime",
3
- "version": "0.331.0",
3
+ "version": "0.333.0",
4
4
  "description": "Internal package used by @teamkeel/sdk",
5
5
  "main": "src/index.js",
6
6
  "scripts": {
package/src/database.js CHANGED
@@ -1,6 +1,27 @@
1
1
  const { Kysely, PostgresDialect } = require("kysely");
2
2
  const { AsyncLocalStorage } = require("async_hooks");
3
3
  const pg = require("pg");
4
+ const { PROTO_ACTION_TYPES } = require("./consts");
5
+
6
+ // withTransaction wraps the containing code with a transaction
7
+ // and sets the transaction in the AsyncLocalStorage so consumers further
8
+ // down the hierarchy can access the current transaction.
9
+ // For read type operations such as list & get, no transaction is used
10
+ async function withTransaction(db, actionType, cb) {
11
+ switch (actionType) {
12
+ case PROTO_ACTION_TYPES.GET:
13
+ case PROTO_ACTION_TYPES.LIST:
14
+ return dbInstance.run(db, async () => {
15
+ return cb({ transaction: db });
16
+ });
17
+ default:
18
+ return db.transaction().execute(async (transaction) => {
19
+ return dbInstance.run(transaction, async () => {
20
+ return cb({ transaction });
21
+ });
22
+ });
23
+ }
24
+ }
4
25
 
5
26
  function mustEnv(key) {
6
27
  const v = process.env[key];
@@ -47,5 +68,5 @@ function getDatabase() {
47
68
  return db;
48
69
  }
49
70
 
50
- module.exports.dbInstance = dbInstance;
51
71
  module.exports.getDatabase = getDatabase;
72
+ module.exports.withTransaction = withTransaction;
@@ -3,18 +3,11 @@ const {
3
3
  createJSONRPCSuccessResponse,
4
4
  JSONRPCErrorCode,
5
5
  } = require("json-rpc-2.0");
6
- const { getDatabase, dbInstance } = require("./database");
7
- const {
8
- PERMISSION_STATE,
9
- Permissions,
10
- PermissionError,
11
- checkBuiltInPermissions,
12
- permissionsApiInstance,
13
- } = require("./permissions");
14
- const { PROTO_ACTION_TYPES } = require("./consts");
6
+ const { getDatabase } = require("./database");
7
+ const { tryExecuteFunction } = require("./tryExecuteFunction");
15
8
  const { errorToJSONRPCResponse, RuntimeErrors } = require("./errors");
16
9
  const opentelemetry = require("@opentelemetry/api");
17
- const { getTracer, withSpan } = require("./tracing");
10
+ const { withSpan } = require("./tracing");
18
11
 
19
12
  // Generic handler function that is agnostic to runtime environment (local or lambda)
20
13
  // to execute a custom function based on the contents of a jsonrpc-2.0 payload object.
@@ -56,80 +49,29 @@ async function handleRequest(request, config) {
56
49
  meta: request.meta,
57
50
  });
58
51
 
52
+ // The Go runtime does *some* permissions checks up front before the request reaches
53
+ // this method, so we pass in a permissionState object on the request.meta object that
54
+ // indicates whether a call to a custom function has already been authorised
59
55
  const permitted =
60
56
  request.meta && request.meta.permissionState.status === "granted"
61
57
  ? true
62
58
  : null;
63
59
 
64
60
  const db = getDatabase();
65
- const permissions = new Permissions();
66
-
67
- const result = await permissionsApiInstance.run(
68
- { permitted: permitted },
69
- () => {
70
- // We want to wrap the execution of the custom function in a transaction so that any call the user makes
71
- // to any of the model apis we provide to the custom function is processed in a transaction.
72
- // This is useful for permissions where we want to only proceed with database writes if all permission rules
73
- // have been validated.
74
-
75
- return db.transaction().execute(async (transaction) => {
76
- return dbInstance.run(transaction, async () => {
77
- // Call the user's custom function!
78
- const customFunction = functions[request.method];
79
- const fnResult = await customFunction(ctx, request.params);
80
-
81
- // api.permissions maintains an internal state of whether the current operation has been *explicitly* permitted/denied by the user in the course of their custom function, or if execution has already been permitted by a role based permission (evaluated in the main runtime).
82
- // we need to check that the final state is permitted or unpermitted. if it's not, then it means that the user has taken no explicit action to permit/deny
83
- // and therefore we default to checking the permissions defined in the schema automatically.
84
- switch (permissions.getState()) {
85
- case PERMISSION_STATE.PERMITTED:
86
- return fnResult;
87
- case PERMISSION_STATE.UNPERMITTED:
88
- throw new PermissionError(
89
- `Not permitted to access ${request.method}`
90
- );
91
- default:
92
- // unknown state, proceed with checking against the built in permissions in the schema
93
- const relevantPermissions = permissionFns[request.method];
94
- const actionType = actionTypes[request.method];
95
-
96
- const peakInsideTransaction =
97
- actionType === PROTO_ACTION_TYPES.CREATE;
98
-
99
- let rowsForPermissions = [];
100
- switch (actionType) {
101
- case PROTO_ACTION_TYPES.LIST:
102
- rowsForPermissions = fnResult;
103
- break;
104
- case PROTO_ACTION_TYPES.DELETE:
105
- rowsForPermissions = [{ id: fnResult }];
106
- break;
107
- default:
108
- rowsForPermissions = [fnResult];
109
- break;
110
- }
111
-
112
- // check will throw a PermissionError if a permission rule is invalid
113
- await checkBuiltInPermissions({
114
- rows: rowsForPermissions,
115
- permissionFns: relevantPermissions,
116
- // it is important that we pass db here as db represents the connection to the database
117
- // *outside* of the current transaction. Given that any changes inside of a transaction
118
- // are opaque to the outside, we can utilize this when running permission rules and then deciding to
119
- // rollback any changes if they do not pass. However, for creates we need to be able to 'peak' inside the transaction to read the created record, as this won't exist outside of the transaction.
120
- db: peakInsideTransaction ? transaction : db,
121
- ctx,
122
- functionName: request.method,
123
- });
124
-
125
- // If the built in permission check above doesn't throw, then it means that the request is permitted and we can continue returning the return value from the custom function out of the transaction
126
- return fnResult;
127
- }
128
- });
129
- });
61
+ const customFunction = functions[request.method];
62
+
63
+ const result = await tryExecuteFunction(
64
+ { request, ctx, permitted, db, permissionFns, actionTypes },
65
+ async () => {
66
+ // Return the custom function to the containing tryExecuteFunction block
67
+ // Once the custom function is called, tryExecuteFunction will check the schema's permission rules to see if it can continue committing
68
+ // the transaction to the db. If a permission rule is violated, any changes made inside the transaction are rolled back.
69
+ return customFunction(ctx, request.params);
130
70
  }
131
71
  );
132
72
 
73
+ // Sometimes a custom function may be coded in such a way that nothing is returned from it.
74
+ // We see this as an error so handle accordingly.
133
75
  if (result === undefined) {
134
76
  // no result returned from custom function
135
77
  return createJSONRPCErrorResponse(
@@ -232,6 +232,10 @@ describe("ModelAPI error handling", () => {
232
232
 
233
233
  functionConfig = {
234
234
  permissionFns: {},
235
+ actionTypes: {
236
+ createPost: PROTO_ACTION_TYPES.CREATE,
237
+ deletePost: PROTO_ACTION_TYPES.DELETE,
238
+ },
235
239
  functions: {
236
240
  createPost: async (ctx, inputs) => {
237
241
  new Permissions().allow();
@@ -8,6 +8,16 @@ const PERMISSION_STATE = {
8
8
  UNPERMITTED: "unpermitted",
9
9
  };
10
10
 
11
+ // withPermissions sets the initial permission state from the go runtime in the AsyncLocalStorage so consumers further down the hierarchy can read or mutate the state
12
+ // at will
13
+ const withPermissions = async (initialValue, cb) => {
14
+ const permissions = new Permissions();
15
+
16
+ return await permissionsApiInstance.run({ permitted: initialValue }, () => {
17
+ return cb({ getPermissionState: permissions.getState });
18
+ });
19
+ };
20
+
11
21
  const permissionsApiInstance = new AsyncLocalStorage();
12
22
 
13
23
  class Permissions {
@@ -61,8 +71,9 @@ const checkBuiltInPermissions = async ({
61
71
  throw new PermissionError(`Not permitted to access ${functionName}`);
62
72
  };
63
73
 
64
- module.exports.permissionsApiInstance = permissionsApiInstance;
65
74
  module.exports.checkBuiltInPermissions = checkBuiltInPermissions;
66
75
  module.exports.PermissionError = PermissionError;
67
76
  module.exports.PERMISSION_STATE = PERMISSION_STATE;
68
77
  module.exports.Permissions = Permissions;
78
+ module.exports.withPermissions = withPermissions;
79
+ module.exports.permissionsApiInstance = permissionsApiInstance;
@@ -0,0 +1,72 @@
1
+ const { withTransaction } = require("./database");
2
+ const {
3
+ withPermissions,
4
+ PERMISSION_STATE,
5
+ PermissionError,
6
+ checkBuiltInPermissions,
7
+ } = require("./permissions");
8
+ const { PROTO_ACTION_TYPES } = require("./consts");
9
+
10
+ // tryExecuteFunction will create a new database transaction around a function call
11
+ // and handle any permissions checks. If a permission check fails, then an Error will be thrown and the catch block will be hit.
12
+ function tryExecuteFunction(
13
+ { db, permitted, permissionFns, actionTypes, request, ctx },
14
+ cb
15
+ ) {
16
+ const actionType = actionTypes[request.method];
17
+
18
+ return withPermissions(permitted, async ({ getPermissionState }) => {
19
+ return withTransaction(db, actionType, async ({ transaction }) => {
20
+ const fnResult = await cb();
21
+
22
+ // api.permissions maintains an internal state of whether the current operation has been *explicitly* permitted/denied by the user in the course of their custom function, or if execution has already been permitted by a role based permission (evaluated in the main runtime).
23
+ // we need to check that the final state is permitted or unpermitted. if it's not, then it means that the user has taken no explicit action to permit/deny
24
+ // and therefore we default to checking the permissions defined in the schema automatically.
25
+ switch (getPermissionState()) {
26
+ case PERMISSION_STATE.PERMITTED:
27
+ return fnResult;
28
+ case PERMISSION_STATE.UNPERMITTED:
29
+ throw new PermissionError(
30
+ `Not permitted to access ${request.method}`
31
+ );
32
+ default:
33
+ // unknown state, proceed with checking against the built in permissions in the schema
34
+ const relevantPermissions = permissionFns[request.method];
35
+
36
+ const peakInsideTransaction =
37
+ actionType === PROTO_ACTION_TYPES.CREATE;
38
+
39
+ let rowsForPermissions = [];
40
+ switch (actionType) {
41
+ case PROTO_ACTION_TYPES.LIST:
42
+ rowsForPermissions = fnResult;
43
+ break;
44
+ case PROTO_ACTION_TYPES.DELETE:
45
+ rowsForPermissions = [{ id: fnResult }];
46
+ break;
47
+ default:
48
+ rowsForPermissions = [fnResult];
49
+ break;
50
+ }
51
+
52
+ // check will throw a PermissionError if a permission rule is invalid
53
+ await checkBuiltInPermissions({
54
+ rows: rowsForPermissions,
55
+ permissionFns: relevantPermissions,
56
+ // it is important that we pass db here as db represents the connection to the database
57
+ // *outside* of the current transaction. Given that any changes inside of a transaction
58
+ // are opaque to the outside, we can utilize this when running permission rules and then deciding to
59
+ // rollback any changes if they do not pass. However, for creates we need to be able to 'peak' inside the transaction to read the created record, as this won't exist outside of the transaction.
60
+ db: peakInsideTransaction ? transaction : db,
61
+ ctx,
62
+ functionName: request.method,
63
+ });
64
+
65
+ // If the built in permission check above doesn't throw, then it means that the request is permitted and we can continue returning the return value from the custom function out of the transaction
66
+ return fnResult;
67
+ }
68
+ });
69
+ });
70
+ }
71
+
72
+ module.exports.tryExecuteFunction = tryExecuteFunction;