From a578417d312ca3400e4d2746434f05405c6fb152 Mon Sep 17 00:00:00 2001 From: Gsk54 Date: Wed, 18 Jan 2023 15:50:42 +0100 Subject: [PATCH] refactor context sent to opa --- opa/user/list.rego | 2 +- opa/user/read.rego | 6 +++- .../secondaries/opa.decision-maker.ts | 30 ++++++++++++------- .../tests/unit/opa.decision-maker.spec.ts | 12 ++++++++ 4 files changed, 37 insertions(+), 13 deletions(-) diff --git a/opa/user/list.rego b/opa/user/list.rego index f643c93..4d92535 100644 --- a/opa/user/list.rego +++ b/opa/user/list.rego @@ -3,5 +3,5 @@ package user.list default allow := false allow := true { - input.uuid == "96d99d44-e0a6-458e-a656-de2a400d60a9" + input.role == "admin" } diff --git a/opa/user/read.rego b/opa/user/read.rego index 15fd6ea..16132e4 100644 --- a/opa/user/read.rego +++ b/opa/user/read.rego @@ -3,5 +3,9 @@ package user.read default allow := false allow := true { - input.uuid == "96d99d44-e0a6-458e-a656-de2a400d60a8" + input.uuid == input.owner +} + +allow := true { + input.role == "admin" } diff --git a/src/modules/authorization/adapters/secondaries/opa.decision-maker.ts b/src/modules/authorization/adapters/secondaries/opa.decision-maker.ts index fbefa35..0e9d5e8 100644 --- a/src/modules/authorization/adapters/secondaries/opa.decision-maker.ts +++ b/src/modules/authorization/adapters/secondaries/opa.decision-maker.ts @@ -24,17 +24,25 @@ export class OpaDecisionMaker extends IMakeDecision { action: Action, context: Array, ): Promise { - const { data } = await lastValueFrom( - this._httpService.post( - this._configService.get('OPA_URL') + domain + '/' + action, - { - input: { - uuid, - ...context, - }, - }, - ), + const reducedContext = context.reduce( + (obj, item) => Object.assign(obj, { [item.name]: item.value }), + {}, ); - return new Authorization(data.result.allow); + try { + const { data } = await lastValueFrom( + this._httpService.post( + this._configService.get('OPA_URL') + domain + '/' + action, + { + input: { + uuid, + ...reducedContext, + }, + }, + ), + ); + return new Authorization(data.result.allow); + } catch (e) { + return new Authorization(false); + } } } diff --git a/src/modules/authorization/tests/unit/opa.decision-maker.spec.ts b/src/modules/authorization/tests/unit/opa.decision-maker.spec.ts index 33901e2..52c85e2 100644 --- a/src/modules/authorization/tests/unit/opa.decision-maker.spec.ts +++ b/src/modules/authorization/tests/unit/opa.decision-maker.spec.ts @@ -30,6 +30,9 @@ const mockHttpService = { }, }, }); + }) + .mockImplementationOnce(() => { + throw new Error(); }), }; @@ -84,5 +87,14 @@ describe('OpaDecisionMaker', () => { ); expect(authorization.allow).toBeFalsy(); }); + it('should return a falsy authorization when an error happens', async () => { + const authorization = await opaDecisionMaker.decide( + 'bb281075-1b98-4456-89d6-c643d3044a91', + Domain.user, + Action.read, + [], + ); + expect(authorization.allow).toBeFalsy(); + }); }); });