refactor context sent to opa

This commit is contained in:
Gsk54 2023-01-18 15:50:42 +01:00
parent 7dc6e7795f
commit a578417d31
4 changed files with 37 additions and 13 deletions

View File

@ -3,5 +3,5 @@ package user.list
default allow := false default allow := false
allow := true { allow := true {
input.uuid == "96d99d44-e0a6-458e-a656-de2a400d60a9" input.role == "admin"
} }

View File

@ -3,5 +3,9 @@ package user.read
default allow := false default allow := false
allow := true { allow := true {
input.uuid == "96d99d44-e0a6-458e-a656-de2a400d60a8" input.uuid == input.owner
}
allow := true {
input.role == "admin"
} }

View File

@ -24,17 +24,25 @@ export class OpaDecisionMaker extends IMakeDecision {
action: Action, action: Action,
context: Array<ContextItem>, context: Array<ContextItem>,
): Promise<Authorization> { ): Promise<Authorization> {
const reducedContext = context.reduce(
(obj, item) => Object.assign(obj, { [item.name]: item.value }),
{},
);
try {
const { data } = await lastValueFrom( const { data } = await lastValueFrom(
this._httpService.post<Decision>( this._httpService.post<Decision>(
this._configService.get<string>('OPA_URL') + domain + '/' + action, this._configService.get<string>('OPA_URL') + domain + '/' + action,
{ {
input: { input: {
uuid, uuid,
...context, ...reducedContext,
}, },
}, },
), ),
); );
return new Authorization(data.result.allow); return new Authorization(data.result.allow);
} catch (e) {
return new Authorization(false);
}
} }
} }

View File

@ -30,6 +30,9 @@ const mockHttpService = {
}, },
}, },
}); });
})
.mockImplementationOnce(() => {
throw new Error();
}), }),
}; };
@ -84,5 +87,14 @@ describe('OpaDecisionMaker', () => {
); );
expect(authorization.allow).toBeFalsy(); 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();
});
}); });
}); });