@r2d2bzh/moleculer-authz-helpers 0.0.3 → 2.0.1

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/README.adoc CHANGED
@@ -2,8 +2,18 @@
2
2
  :sectnums:
3
3
  :toc: left
4
4
 
5
+ ifdef::env-github[]
6
+ :tip-caption: :bulb:
7
+ :note-caption: :information_source:
8
+ :important-caption: :heavy_exclamation_mark:
9
+ :caution-caption: :fire:
10
+ :warning-caption: :warning:
11
+ endif::[]
12
+
5
13
  = Moleculer authorization helpers
6
14
 
15
+ == Rationale
16
+
7
17
  The current authorization strategy used by the R2D2 stack is to operate a preflight from the API gateway before it actually calls an action of a backend service.
8
18
  These preflight actions can either decide themselves if the call is authorized or ask other services for an authorization.
9
19
 
@@ -11,17 +21,44 @@ These requests are sent through Moleculer events.
11
21
  Services subscribing to these events will either reply with a boolean (`true` = authorized, `false` = forbidden) or will not reply if they cannot answer (`undefined` answer).
12
22
  An authorization request is considered successful if at least one service has authorized the request and no service has forbidden the request (which means that if nobody answered, the request is implicitly forbidden).
13
23
 
24
+ [NOTE]
25
+ ====
26
+ Events are used instead of actions as the authorization requester does not necessarily know which service answers its authorization requests.
27
+ Moreover, multiple services could be responsible to answer one authorization request.
28
+ ====
29
+
30
+ === Use case
31
+
32
+ The following example considers a shared todo list service.
33
+ This service exposes an action to update a todo item and notify by email the todo list members of this update. +
34
+ Depending on the user, the email sender will authorize or not the notification.
35
+
36
+ The following services are at play:
37
+
38
+ * todo-list: manage todo lists
39
+ * email-sender: send emails
40
+ * members-service: manage users
41
+ * moleculer-web: expose actions
42
+
43
+ image::docs/use-case.svg[]
44
+
45
+ == Helpers
46
+
14
47
  Currently, this library provides the following helpers:
15
48
 
16
49
  * `addPreflightMixin` to build and add a preflight mixin in a service schema
17
50
  * `isAuthorized` to decide whether one or more authorization requests have all succeeded based on the answers provided by the subscribers
18
51
  * `requestAuthorizations` to send multiple authorization requests at once
19
52
 
20
- == `addPreflightMixin`
53
+ === `addPreflightMixin`
21
54
 
22
55
  This helper adds a service mixin used to generate preflight actions for actions exposed through rest.
23
56
  It takes a Moleculer service schema as a parameter and returns the same service schema with the mixin added.
24
57
 
58
+ This helper also adds the `callEventMixin` provided by https://www.npmjs.com/package/@r2d2bzh/moleculer-event-callback[@r2d2bzh/moleculer-event-callback].
59
+ `callEventMixin` injects a `$$callEvent` method to make authorization requests.
60
+ It also provides the callback action needed to receive the return value of authorization requests.
61
+
25
62
  NOTE: A preflight action takes the same parameters as the original action.
26
63
 
27
64
  To define a preflight handler, you must add a preflight attribute to an action:
@@ -67,7 +104,7 @@ Only actions where authorization is disabled do not enforce a preflight:
67
104
  ----
68
105
  ====
69
106
 
70
- == `isAuthorized`
107
+ === `isAuthorized`
71
108
 
72
109
  This helper decides whether or not something is authorized based on the answers to one or more authorization requests.
73
110
  It implements the following rules:
@@ -83,10 +120,26 @@ It implements the following rules:
83
120
  * if any answer is `false`, the whole authorization process fails
84
121
  * if no answer was provided, the whole authorization process fails
85
122
 
86
- == `requestAuthorizations`
123
+ The signature of `isAuthorized` is `(logger) => (answer) => true | false`:
124
+
125
+ . the `logger` curried argument must provide a `warn` method used to issue warnings (default: `console`)
126
+ . the `answer` curried argument is the authorization answer(s) to one or many authorization requests
127
+
128
+ `isAuthorized` will raise a warning in the following cases:
129
+
130
+ * an odd authorization answer was provided, known answers are:
131
+ ** `true`:: the request is authorized
132
+ ** `false`:: the request is denied
133
+ ** `undefined`:: the responder is not able to answer
134
+ * multiple `true` or `false` answers were provided to the same authorization request
135
+
136
+ === `requestAuthorizations`
87
137
 
88
138
  This helper operates multiple authorization requests at once and returns a promise which result can be handled by `isAuthorized`.
89
139
 
140
+ This helper uses the `$$callEvent` method provided by the `callEventMixin` of https://www.npmjs.com/package/@r2d2bzh/moleculer-event-callback[@r2d2bzh/moleculer-event-callback] (see `addPreflightMixin`).
141
+ This allows the retrieval of authorization requests return values.
142
+
90
143
  [source,javascript]
91
144
  ----
92
145
  requestAuthorization(moleculerContext)([
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@r2d2bzh/moleculer-authz-helpers",
3
- "version": "0.0.3",
3
+ "version": "2.0.1",
4
4
  "description": "Moleculer mixin to implement preflight runner",
5
5
  "main": "index.js",
6
6
  "type": "module",
@@ -39,7 +39,10 @@
39
39
  "node": ">=12.0.0"
40
40
  },
41
41
  "peerDependencies": {
42
- "lodash": "^4.17.21",
43
42
  "moleculer": "^0.14.0"
43
+ },
44
+ "dependencies": {
45
+ "@r2d2bzh/moleculer-event-callback": "~0.0.1",
46
+ "lodash": "^4.17.21"
44
47
  }
45
48
  }
@@ -1,11 +1,12 @@
1
1
  import cloneDeep from 'lodash/cloneDeep.js';
2
2
  import moleculer from 'moleculer';
3
+ import { callEventMixin } from '@r2d2bzh/moleculer-event-callback';
3
4
 
4
5
  const {
5
6
  Errors: { MoleculerError },
6
7
  } = moleculer;
7
8
 
8
- export const unsafeAddPreflightMixin = (serviceSchema) => {
9
+ export const unsafeAddPreflightMixin = (serviceSchema, { timeout }) => {
9
10
  const actionsWithPreflight = Object.entries(serviceSchema.actions || {}).filter(
10
11
  ([, actionSpecification]) => actionSpecification?.preflight
11
12
  );
@@ -28,19 +29,20 @@ export const unsafeAddPreflightMixin = (serviceSchema) => {
28
29
  {
29
30
  actions: Object.fromEntries(preflightActions),
30
31
  },
32
+ callEventMixin({ timeout }),
31
33
  ];
32
34
 
33
35
  return schema;
34
36
  };
35
37
 
36
- export default (serviceSchema) => {
38
+ export default (serviceSchema, { timeout = 200 } = {}) => {
37
39
  Object.entries(serviceSchema.actions || {})
38
- .filter(([, actionSpecification]) => actionSpecification?.rest?.authorization !== false)
40
+ .filter(([, actionSpecification]) => actionSpecification?.rest && actionSpecification.rest?.authorization !== false)
39
41
  .forEach(([actionName, actionSpecification]) => {
40
42
  if (!(actionSpecification?.preflight instanceof Function || actionSpecification?.preflight?.handler)) {
41
43
  throw new MoleculerError('missing preflight handler', 500, 'MISSING_PREFLIGHT', { actionName });
42
44
  }
43
45
  });
44
46
 
45
- return unsafeAddPreflightMixin(serviceSchema);
47
+ return unsafeAddPreflightMixin(serviceSchema, { timeout });
46
48
  };
@@ -1,19 +1,62 @@
1
1
  const removeUnanswered = (authzAnswers) => authzAnswers.filter((answer) => answer !== undefined);
2
2
 
3
- const doAnswersAuthorize = (authzAnswers) =>
4
- authzAnswers.length
5
- ? authzAnswers.reduce((isAuthorized, authzAnswer) => isAuthorized && doesAnswerAuthorize(authzAnswer), true)
6
- : false;
3
+ const reduceAnswers = (answers, reducer) =>
4
+ answers.length
5
+ ? answers.reduce(
6
+ ([authorizationStatus, authorizationsCount], answer) =>
7
+ reducer(answer, authorizationStatus, authorizationsCount),
8
+ [true, 0]
9
+ )
10
+ : [false, 0];
7
11
 
8
- const doesAnswerAuthorize = function (something) {
9
- switch (Object.prototype.toString.call(something)) {
10
- case '[object Boolean]':
11
- return something;
12
- case '[object Array]':
13
- return doAnswersAuthorize(removeUnanswered(something));
14
- default:
15
- return false;
16
- }
12
+ const onMultipleAuthorizations =
13
+ (handle) =>
14
+ ([answersAuthorization, authorizationsCount]) => {
15
+ if (authorizationsCount > 1) {
16
+ handle(authorizationsCount);
17
+ }
18
+ return answersAuthorization;
19
+ };
20
+
21
+ const processAndCountManyAnswers = (warn) => {
22
+ const warnOnMultipleAuthorizations = onMultipleAuthorizations((authorizationsCount) =>
23
+ warn(`multiple answers to the same authorization request (${authorizationsCount})`)
24
+ );
25
+ return (answers, authorizationStatus) => {
26
+ const newRequestIsAuthorized = warnOnMultipleAuthorizations(
27
+ reduceAnswers(removeUnanswered(answers), processAndCountAnswer(warn))
28
+ );
29
+ return authorizationStatus && newRequestIsAuthorized;
30
+ };
31
+ };
32
+
33
+ const processAndCountAnswer = (warn) => {
34
+ const doAnswersAuthorize = processAndCountManyAnswers(warn);
35
+ return function (answer, authorizationStatus = true, authorizationsCount = 0) {
36
+ switch (Object.prototype.toString.call(answer)) {
37
+ case '[object Boolean]':
38
+ return [authorizationStatus && answer, authorizationsCount + 1];
39
+ case '[object Array]':
40
+ // A new array means a new authorization request with its own
41
+ // answers count that does not reflect on the current one
42
+ return [doAnswersAuthorize(answer, authorizationStatus), authorizationsCount];
43
+ case '[object Undefined]':
44
+ return [false, authorizationsCount];
45
+ default:
46
+ warn(`odd authorization answer (${answer})`);
47
+ return [false, authorizationsCount];
48
+ }
49
+ };
17
50
  };
18
51
 
19
- export default doesAnswerAuthorize;
52
+ export default (logger) => {
53
+ try {
54
+ const doesAnswerAuthorizeAndWarn = processAndCountAnswer(logger.warn.bind(logger));
55
+ return function (answer) {
56
+ const [authorize] = doesAnswerAuthorizeAndWarn(answer);
57
+ return authorize;
58
+ };
59
+ } catch (e) {
60
+ throw new Error(`logger.warn must be a function`);
61
+ }
62
+ };
@@ -1,2 +1,6 @@
1
1
  export default (ctx) => (requests) =>
2
- Promise.all(requests.map(({ eventName, parameters, options }) => ctx.emit(eventName, parameters, options)));
2
+ Promise.all(
3
+ requests.map(({ eventName, parameters, options }) =>
4
+ ctx.service.$$callEvent(ctx, { eventName, payload: parameters, options })
5
+ )
6
+ );