/
Oso.ts
338 lines (322 loc) · 10.5 KB
/
Oso.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
import { Polar } from './Polar';
import { Variable } from './Variable';
import { Expression } from './Expression';
import { Pattern } from './Pattern';
import type { Options, CustomError, Class, PolarTerm } from './types';
import {
NotFoundError,
ForbiddenError,
OsoError,
UnregisteredClassError,
} from './errors';
import { parseFilter, Adapter, FilterJson } from './filter';
/** The Oso authorization API. */
// TODO(gj): maybe pass DF options to constructor & try to parametrize a
// `Query` type w/ the return type of the provided buildQuery fn.
export class Oso<
Actor = unknown,
Action = unknown,
Resource = unknown,
Field = unknown,
Request = unknown,
Query = unknown
> extends Polar<Query, Resource> {
#notFoundError: CustomError = NotFoundError;
#forbiddenError: CustomError = ForbiddenError;
#readAction: unknown = 'read';
constructor(opts: Options = {}) {
super(opts);
if (opts.notFoundError) this.#notFoundError = opts.notFoundError;
if (opts.forbiddenError) this.#forbiddenError = opts.forbiddenError;
if (opts.readAction) this.#readAction = opts.readAction;
}
/**
* Query the knowledge base to determine whether an actor is allowed to
* perform an action upon a resource.
*
* @param actor Subject.
* @param action Verb.
* @param resource Object.
* @returns An access control decision.
*/
async isAllowed(
actor: Actor,
action: Action,
resource: Resource
): Promise<boolean> {
return this.queryRuleOnce('allow', actor, action, resource);
}
/**
* Ensure that `actor` is allowed to perform `action` on
* `resource`.
*
* If the action is permitted with an `allow` rule in the policy, then
* this method returns `None`. If the action is not permitted by the
* policy, this method will raise an error.
*
* The error raised by this method depends on whether the actor can perform
* the `"read"` action on the resource. If they cannot read the resource,
* then a `NotFound` error is raised. Otherwise, a `ForbiddenError` is
* raised.
*
* @param actor The actor performing the request.
* @param action The action the actor is attempting to perform.
* @param resource The resource being accessed.
* @param checkRead If set to `false`, a `ForbiddenError` is always
* thrown on authorization failures, regardless of whether the actor can
* read the resource. Default is `true`.
*/
async authorize(
actor: Actor,
action: Action,
resource: Resource,
options: { checkRead?: boolean } = {}
): Promise<void> {
if (typeof options.checkRead === 'undefined') options.checkRead = true;
if (await this.queryRuleOnce('allow', actor, action, resource)) {
return;
}
let isNotFound = false;
if (options.checkRead) {
if (action === this.#readAction) {
isNotFound = true;
} else {
const canRead = await this.queryRuleOnce(
'allow',
actor,
this.#readAction,
resource
);
if (!canRead) {
isNotFound = true;
}
}
}
const ErrorClass = isNotFound ? this.#notFoundError : this.#forbiddenError;
throw new ErrorClass();
}
/**
* Determine the actions `actor` is allowed to take on `resource`.
*
* Collects all actions allowed by allow rules in the Polar policy for the
* given combination of actor and resource.
*
* @param actor The actor for whom to collect allowed actions
* @param resource The resource being accessed
* @param allowWildcard Flag to determine behavior if the policy
* includes a wildcard action. E.g., a rule allowing any action:
* `allow(_actor, _action, _resource)`. If `true`, the method will
* return `["*"]`, if `false`, the method will raise an exception.
* @returns A list of the unique allowed actions.
*/
async authorizedActions(
actor: Actor,
resource: Resource,
options: { allowWildcard?: boolean } = {}
): Promise<Set<Action | '*'>> {
const results = this.queryRule(
'allow',
actor,
new Variable('action'),
resource
);
const actions = new Set<Action | '*'>();
for await (const result of results) {
const action = result.get('action');
if (action instanceof Variable) {
if (!options.allowWildcard) {
throw new OsoError(`
The result of authorizedActions() contained an "unconstrained" action that could represent any action, but allowWildcard was set to False. To fix, set allowWildcard to True and compare with the "*" string.
`);
} else {
return new Set(['*']);
}
}
// TODO(gj): do we need to handle the case where `action` is something
// other than a `Variable` or an `Action`? E.g., if it's an `Expression`?
actions.add(action as Action);
}
return actions;
}
/**
* Ensure that `actor` is allowed to send `request` to the server.
*
* Checks the `allow_request` rule of a policy.
*
* If the request is permitted with an `allow_request` rule in the
* policy, then this method returns nothing. Otherwise, this method raises
* a `ForbiddenError`.
*
* @param actor The actor performing the request.
* @param request An object representing the request that was sent by the
* actor.
*/
async authorizeRequest(actor: Actor, request: Request): Promise<void> {
const isAllowed = await this.queryRuleOnce('allow_request', actor, request);
if (!isAllowed) {
throw new this.#forbiddenError();
}
}
/**
* Ensure that `actor` is allowed to perform `action` on a given
* `resource`'s `field`.
*
* If the action is permitted by an `allow_field` rule in the policy,
* then this method returns nothing. If the action is not permitted by the
* policy, this method will raise a `ForbiddenError`.
*
* @param actor The actor performing the request.
* @param action The action the actor is attempting to perform on the
* field.
* @param resource The resource being accessed.
* @param field The name of the field being accessed.
*/
async authorizeField(
actor: Actor,
action: Action,
resource: Resource,
field: Field
): Promise<void> {
const isAllowed = await this.queryRuleOnce(
'allow_field',
actor,
action,
resource,
field
);
if (!isAllowed) {
throw new this.#forbiddenError();
}
}
/**
* Determine the fields of `resource` on which `actor` is allowed to
* perform `action`.
*
* Uses `allow_field` rules in the policy to find all allowed fields.
*
* @param actor The actor for whom to collect allowed fields.
* @param action The action being taken on the field.
* @param resource The resource being accessed.
* @param allowWildcard Flag to determine behavior if the policy \
* includes a wildcard field. E.g., a rule allowing any field: \
* `allow_field(_actor, _action, _resource, _field)`. If `true`, the \
* method will return `["*"]`, if `false`, the method will raise an \
* exception.
* @returns A list of the unique allowed fields.
*/
async authorizedFields(
actor: Actor,
action: Action,
resource: Resource,
options: { allowWildcard?: boolean } = {}
): Promise<Set<Field | '*'>> {
const results = this.queryRule(
'allow_field',
actor,
action,
resource,
new Variable('field')
);
const fields = new Set<Field | '*'>();
for await (const result of results) {
const field = result.get('field');
if (field instanceof Variable) {
if (!options.allowWildcard) {
throw new OsoError(`
The result of authorizedFields() contained an "unconstrained" field that could represent any field, but allowWildcard was set to False. To fix, set allowWildcard to True and compare with the "*" string.
`);
} else {
return new Set(['*']);
}
}
// TODO(gj): do we need to handle the case where `field` is something
// other than a `Variable` or a `Field`? E.g., if it's an `Expression`?
fields.add(field as Field);
}
return fields;
}
/**
* Create a query for all the resources of type `resourceCls` that `actor` is
* allowed to perform `action` on.
*
* @param actor Subject.
* @param action Verb.
* @param resourceCls Object type.
* @returns A query that selects authorized resources of type `resourceCls`
*/
async authorizedQuery(
actor: Actor,
action: Action,
resourceCls: Class<Resource> | string
): Promise<Query> {
const resource = new Variable('resource');
const host = this.getHost();
let clsName: string | undefined;
if (typeof resourceCls === 'string') {
clsName = resourceCls;
} else {
clsName = host.getType(resourceCls)?.name;
if (clsName === undefined)
throw new UnregisteredClassError(resourceCls.name);
}
const constraint = new Expression('And', [
new Expression('Isa', [
resource,
new Pattern({ tag: clsName, fields: {} }),
]),
]);
const bindings = new Map();
bindings.set('resource', constraint);
const results = this.queryRule(
{
bindings,
acceptExpression: true,
},
'allow',
actor,
action,
resource
);
const queryResults: { bindings: Map<string, PolarTerm> }[] = [];
for await (const result of results) {
queryResults.push({
// convert bindings back into Polar
bindings: new Map(
[...result.entries()].map(([k, v]) => [k, host.toPolar(v)])
),
});
}
const dataFilter = this.getFfi().buildDataFilter(
host.serializeTypes(),
queryResults,
'resource',
clsName
) as FilterJson;
const filter = await parseFilter(dataFilter, host);
return host.adapter.buildQuery(filter);
}
/**
* Determine the resources of type `resourceCls` that `actor`
* is allowed to perform `action` on.
*
* @param actor Subject.
* @param action Verb.
* @param resourceCls Object type or string name of class
* @returns An array of authorized resources.
*/
async authorizedResources(
actor: Actor,
action: Action,
resourceCls: Class<Resource> | string
): Promise<Resource[]> {
const query = await this.authorizedQuery(actor, action, resourceCls);
if (!query) return [];
return this.getHost().adapter.executeQuery(query);
}
/**
* Register adapter for data filtering query functions.
*/
setDataFilteringAdapter(adapter: Adapter<Query, Resource>): void {
this.getHost().adapter = adapter;
}
}