oak-domain 6.1.0 → 6.1.2
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/es/base-app-domain/ActionDefDict.d.ts +1 -0
- package/es/base-app-domain/ActionDefDict.js +3 -1
- package/es/base-app-domain/EntityDict.d.ts +86 -1
- package/es/base-app-domain/Log/Storage.js +4 -0
- package/es/base-app-domain/Log/_baseSchema.d.ts +5 -0
- package/es/base-app-domain/Storage.js +3 -1
- package/es/base-app-domain/StyleDict.js +3 -1
- package/es/base-app-domain/Version/Action.d.ts +6 -0
- package/es/base-app-domain/Version/Action.js +2 -0
- package/es/base-app-domain/Version/Schema.d.ts +19 -0
- package/es/base-app-domain/Version/Schema.js +1 -0
- package/es/base-app-domain/Version/Storage.d.ts +3 -0
- package/es/base-app-domain/Version/Storage.js +54 -0
- package/es/base-app-domain/Version/Style.d.ts +3 -0
- package/es/base-app-domain/Version/Style.js +6 -0
- package/es/base-app-domain/Version/_baseSchema.d.ts +57 -0
- package/es/base-app-domain/Version/_baseSchema.js +1 -0
- package/es/compiler/dependencyBuilder.d.ts +1 -0
- package/es/compiler/dependencyBuilder.js +173 -55
- package/es/compiler/routerBuilder.d.ts +4 -1
- package/es/compiler/routerBuilder.js +22 -19
- package/es/compiler/schemaBuilder.d.ts +5 -1
- package/es/compiler/schemaBuilder.js +10 -0
- package/es/context/BackendRuntimeContext.d.ts +9 -1
- package/es/context/BackendRuntimeContext.js +13 -1
- package/es/entities/Log.d.ts +2 -0
- package/es/entities/Log.js +2 -0
- package/es/entities/Version.d.ts +14 -0
- package/es/entities/Version.js +42 -0
- package/es/store/AsyncRowStore.d.ts +4 -1
- package/es/store/AsyncRowStore.js +7 -0
- package/es/store/CascadeStore.js +22 -0
- package/es/store/RelationAuth/authorizationFilter.d.ts +11 -0
- package/es/store/RelationAuth/authorizationFilter.js +104 -0
- package/es/store/RelationAuth/continuation.d.ts +9 -0
- package/es/store/RelationAuth/continuation.js +33 -0
- package/es/store/RelationAuth/index.d.ts +141 -0
- package/es/store/RelationAuth/index.js +1440 -0
- package/es/store/RelationAuth/model.d.ts +38 -0
- package/es/store/RelationAuth/model.js +24 -0
- package/es/store/RelationAuth/userLookup.d.ts +21 -0
- package/es/store/RelationAuth/userLookup.js +102 -0
- package/es/store/SyncRowStore.d.ts +2 -1
- package/es/store/SyncRowStore.js +3 -0
- package/es/store/filter.fix.d.ts +128 -0
- package/es/store/filter.fix.js +2862 -0
- package/es/store/filter.js +14 -9
- package/es/store/triggers.js +239 -44
- package/es/types/Context.d.ts +2 -1
- package/es/types/Demand.d.ts +11 -1
- package/es/types/Environment.d.ts +13 -2
- package/es/types/Exception.d.ts +3 -3
- package/es/types/Exception.js +25 -22
- package/es/types/Expression.d.ts +4 -1
- package/es/types/Expression.js +1 -1
- package/es/types/Storage.d.ts +15 -2
- package/es/utils/SimpleConnector.js +5 -2
- package/es/utils/decimal.js +2 -1
- package/es/utils/fetch/index.ali.d.ts +3 -0
- package/es/utils/fetch/index.ali.js +31 -0
- package/es/utils/fetch/index.d.ts +3 -0
- package/es/utils/fetch/index.js +5 -0
- package/es/utils/fetch/index.mp.d.ts +5 -3
- package/es/utils/fetch/index.mp.js +5 -280
- package/es/utils/fetch/index.wechat.d.ts +5 -0
- package/es/utils/fetch/index.wechat.js +174 -0
- package/es/utils/fetch/mini-program.shared.d.ts +37 -0
- package/es/utils/fetch/mini-program.shared.js +85 -0
- package/es/utils/geo.d.ts +1 -1
- package/es/utils/geo.js +1 -1
- package/es/utils/random/random.ali.d.ts +6 -0
- package/es/utils/random/random.ali.js +21 -0
- package/es/utils/random/random.mp.d.ts +5 -1
- package/es/utils/random/random.mp.js +11 -5
- package/es/utils/random/random.native.d.ts +1 -1
- package/es/utils/random/random.native.js +7 -4
- package/es/utils/random/random.wechat.d.ts +1 -0
- package/es/utils/random/random.wechat.js +10 -0
- package/lib/base-app-domain/ActionDefDict.d.ts +1 -0
- package/lib/base-app-domain/ActionDefDict.js +3 -1
- package/lib/base-app-domain/EntityDict.d.ts +86 -1
- package/lib/base-app-domain/Log/Storage.js +4 -0
- package/lib/base-app-domain/Log/_baseSchema.d.ts +5 -0
- package/lib/base-app-domain/Storage.js +3 -1
- package/lib/base-app-domain/StyleDict.js +3 -1
- package/lib/base-app-domain/Version/Action.d.ts +6 -0
- package/lib/base-app-domain/Version/Action.js +5 -0
- package/lib/base-app-domain/Version/Schema.d.ts +19 -0
- package/lib/base-app-domain/Version/Schema.js +4 -0
- package/lib/base-app-domain/Version/Storage.d.ts +3 -0
- package/lib/base-app-domain/Version/Storage.js +57 -0
- package/lib/base-app-domain/Version/Style.d.ts +3 -0
- package/lib/base-app-domain/Version/Style.js +9 -0
- package/lib/base-app-domain/Version/_baseSchema.d.ts +57 -0
- package/lib/base-app-domain/Version/_baseSchema.js +2 -0
- package/lib/compiler/dependencyBuilder.d.ts +1 -0
- package/lib/compiler/dependencyBuilder.js +173 -54
- package/lib/compiler/routerBuilder.d.ts +4 -1
- package/lib/compiler/routerBuilder.js +22 -19
- package/lib/compiler/schemaBuilder.d.ts +5 -1
- package/lib/compiler/schemaBuilder.js +10 -0
- package/lib/context/BackendRuntimeContext.d.ts +9 -1
- package/lib/context/BackendRuntimeContext.js +13 -1
- package/lib/entities/Log.d.ts +2 -0
- package/lib/entities/Log.js +2 -0
- package/lib/entities/Version.d.ts +14 -0
- package/lib/entities/Version.js +43 -0
- package/lib/store/AsyncRowStore.d.ts +4 -1
- package/lib/store/AsyncRowStore.js +7 -0
- package/lib/store/CascadeStore.js +22 -0
- package/lib/store/RelationAuth/authorizationFilter.d.ts +11 -0
- package/lib/store/RelationAuth/authorizationFilter.js +110 -0
- package/lib/store/RelationAuth/continuation.d.ts +9 -0
- package/lib/store/RelationAuth/continuation.js +37 -0
- package/lib/store/RelationAuth/index.d.ts +141 -0
- package/lib/store/RelationAuth/index.js +1445 -0
- package/lib/store/RelationAuth/model.d.ts +38 -0
- package/lib/store/RelationAuth/model.js +27 -0
- package/lib/store/RelationAuth/userLookup.d.ts +21 -0
- package/lib/store/RelationAuth/userLookup.js +105 -0
- package/lib/store/SyncRowStore.d.ts +2 -1
- package/lib/store/SyncRowStore.js +3 -0
- package/lib/store/filter.fix.d.ts +128 -0
- package/lib/store/filter.fix.js +2876 -0
- package/lib/store/filter.js +14 -9
- package/lib/store/triggers.js +239 -44
- package/lib/types/Context.d.ts +2 -1
- package/lib/types/Demand.d.ts +11 -1
- package/lib/types/Environment.d.ts +13 -2
- package/lib/types/Exception.d.ts +3 -3
- package/lib/types/Exception.js +25 -22
- package/lib/types/Expression.d.ts +4 -1
- package/lib/types/Expression.js +1 -1
- package/lib/types/Storage.d.ts +15 -2
- package/lib/utils/SimpleConnector.js +5 -2
- package/lib/utils/decimal.js +2 -1
- package/lib/utils/fetch/index.ali.d.ts +3 -0
- package/lib/utils/fetch/index.ali.js +36 -0
- package/lib/utils/fetch/index.d.ts +3 -0
- package/lib/utils/fetch/index.js +7 -0
- package/lib/utils/fetch/index.mp.d.ts +5 -3
- package/lib/utils/fetch/index.mp.js +5 -282
- package/lib/utils/fetch/index.wechat.d.ts +5 -0
- package/lib/utils/fetch/index.wechat.js +180 -0
- package/lib/utils/fetch/mini-program.shared.d.ts +37 -0
- package/lib/utils/fetch/mini-program.shared.js +96 -0
- package/lib/utils/geo.d.ts +1 -1
- package/lib/utils/geo.js +1 -1
- package/lib/utils/random/random.ali.d.ts +6 -0
- package/lib/utils/random/random.ali.js +24 -0
- package/lib/utils/random/random.mp.d.ts +5 -1
- package/lib/utils/random/random.mp.js +11 -5
- package/lib/utils/random/random.native.d.ts +1 -1
- package/lib/utils/random/random.native.js +7 -5
- package/lib/utils/random/random.wechat.d.ts +1 -0
- package/lib/utils/random/random.wechat.js +13 -0
- package/package.json +8 -5
- package/es/store/RelationAuth.d.ts +0 -115
- package/es/store/RelationAuth.js +0 -1340
- package/lib/store/RelationAuth.d.ts +0 -115
- package/lib/store/RelationAuth.js +0 -1345
|
@@ -0,0 +1,1440 @@
|
|
|
1
|
+
import { assert } from '../../utils/assert';
|
|
2
|
+
import { OakUnloggedInException, OakDataInvisibleException, OakOperationUnpermittedException, PrimaryKeyAttribute } from "../../types";
|
|
3
|
+
import { checkFilterContains, combineFilters, getRelevantIds, translateCreateDataToFilter } from "../filter.fix";
|
|
4
|
+
import { allBind, bind } from './continuation';
|
|
5
|
+
import { hasCyclicFilter, minimizeAuthorizationUnion, stableFilterKey } from './authorizationFilter';
|
|
6
|
+
import { deriveChildPath } from './model';
|
|
7
|
+
import { judgeRelation } from "../relation";
|
|
8
|
+
import { readOnlyActions } from '../../actions/action';
|
|
9
|
+
import { difference, intersection, uniq, cloneDeep } from '../../utils/toolkit';
|
|
10
|
+
import { SYSTEM_RESERVE_ENTITIES } from "../../compiler/entities";
|
|
11
|
+
/**
|
|
12
|
+
* RelationAuth —— 按 docs/permission-model.md(v0.5)重写的权限判定内核。
|
|
13
|
+
*
|
|
14
|
+
* 不变量映射:
|
|
15
|
+
* - I2 逐层必检:读路径以 `ReadTask` 链表达投影 OTM 骨架上的每个节点任务(D1/D2/D6),
|
|
16
|
+
* 根任务无条件执行;MTO 投影不构成任务(D5/I3)。
|
|
17
|
+
* - I3 MTO 零成本:`buildReadTasks` 不沿 MTO 边下降,不为其发起任何查询。
|
|
18
|
+
* - I4 双模式同结果:判定逻辑单源;sync/async 分叉只发生在 IO 叶子,由 `bind`/`allBind`
|
|
19
|
+
* 统一接续(同步输入 ⇒ 同步输出,不产生 Promise)。
|
|
20
|
+
* - I5 deduce 单点:`edgeRuleOf(...) === 'deduce'` 是唯一策略谓词;树形剪枝、投影不展开、
|
|
21
|
+
* 写侧放行、多态折算全部经它分派。
|
|
22
|
+
* - I6 豁免粒度:selectFree/updateFree 只把任务标记为 exempt(豁免节点自身行集要求),
|
|
23
|
+
* 不删除任务、不豁免链上其它节点(D4)。
|
|
24
|
+
* - I7 写语义保持:destructOperation/checkOperationTree 结构与现实现同构,仅把路径
|
|
25
|
+
* 拼接替换为 I8 原语。
|
|
26
|
+
* - I8 边传播单源:`deriveChildPath` 是唯一的授权路径派生原语——OTM 前缀边属性名、
|
|
27
|
+
* MTO 剥首段、deduce 零检查;读写共用。
|
|
28
|
+
* - E1 自顶向下短路:任务链按根→叶顺序求值,首个失败立即返回(异常在 checkActions
|
|
29
|
+
* 唯一汇点抛出,种类与时机读写一致)。
|
|
30
|
+
* - E2 扩展路径快路:父任务经见证 actionAuth 行通过后,其路径沿边派生为子任务候选见证,
|
|
31
|
+
* 仍以 actionAuth 数据存在为生效条件;E3 禁止无数据合成继承。
|
|
32
|
+
* - 保守拒绝:判别器伪造、目标歧义(反查 2 行封顶)、未知属性、$not/$xor 删减、环结构
|
|
33
|
+
* filter 一律不放大授权面。
|
|
34
|
+
*/
|
|
35
|
+
export class RelationAuth {
|
|
36
|
+
authDeduceRelationMap;
|
|
37
|
+
schema;
|
|
38
|
+
static SPECIAL_ENTITIES = SYSTEM_RESERVE_ENTITIES;
|
|
39
|
+
selectFreeEntities;
|
|
40
|
+
updateFreeDict;
|
|
41
|
+
constructor(schema, authDeduceRelationMap, selectFreeEntities, updateFreeDict) {
|
|
42
|
+
this.schema = schema;
|
|
43
|
+
this.selectFreeEntities = selectFreeEntities || [];
|
|
44
|
+
this.updateFreeDict = updateFreeDict || {};
|
|
45
|
+
this.authDeduceRelationMap = Object.assign({}, authDeduceRelationMap, {
|
|
46
|
+
modi: 'entity',
|
|
47
|
+
});
|
|
48
|
+
}
|
|
49
|
+
// 前台检查filter是否满足relation约束
|
|
50
|
+
checkRelationSync(entity, operation, context) {
|
|
51
|
+
if (context.isRoot()) {
|
|
52
|
+
return;
|
|
53
|
+
}
|
|
54
|
+
// @oak-ignore 这里只有纯前台会跑到,一定是同步的
|
|
55
|
+
this.checkActions(entity, operation, context);
|
|
56
|
+
}
|
|
57
|
+
// 后台检查filter是否满足relation约束
|
|
58
|
+
async checkRelationAsync(entity, operation, context) {
|
|
59
|
+
if (context.isRoot()) {
|
|
60
|
+
return;
|
|
61
|
+
}
|
|
62
|
+
await this.checkActions(entity, operation, context);
|
|
63
|
+
}
|
|
64
|
+
/** 节点自身是否不参与对象授权判定:selectFree 只豁免自身,特殊系统实体沿用旧行为整节点豁免。 */
|
|
65
|
+
isSelfExemptEntity(entity) {
|
|
66
|
+
return this.selectFreeEntities.includes(entity)
|
|
67
|
+
|| RelationAuth.SPECIAL_ENTITIES.includes(entity);
|
|
68
|
+
}
|
|
69
|
+
/** I5:deduce 策略唯一定义点 */
|
|
70
|
+
edgeRuleOf(entity, attr) {
|
|
71
|
+
if (this.authDeduceRelationMap[entity] === 'entity' && attr === 'entity') {
|
|
72
|
+
return 'deduce';
|
|
73
|
+
}
|
|
74
|
+
// 未识别/不可解析属性保守归为 plain:不产生传播见证,节点回落到自身包含性判定。
|
|
75
|
+
let rel;
|
|
76
|
+
try {
|
|
77
|
+
rel = judgeRelation(this.schema, entity, attr, true);
|
|
78
|
+
}
|
|
79
|
+
catch {
|
|
80
|
+
return 'plain';
|
|
81
|
+
}
|
|
82
|
+
if (rel === 2) {
|
|
83
|
+
return 'polymorphic';
|
|
84
|
+
}
|
|
85
|
+
if (typeof rel === 'string') {
|
|
86
|
+
return 'mto';
|
|
87
|
+
}
|
|
88
|
+
if (rel instanceof Array) {
|
|
89
|
+
return 'otm';
|
|
90
|
+
}
|
|
91
|
+
return 'plain';
|
|
92
|
+
}
|
|
93
|
+
/**
|
|
94
|
+
* 检查当前用户有无权限对filter约束的userRelation进行action操作(§6 特殊实体)
|
|
95
|
+
*/
|
|
96
|
+
checkUserRelation(context, action, filter) {
|
|
97
|
+
const userId = context.getCurrentUserId();
|
|
98
|
+
/** 检查对某一个relationId是否有操作资格 */
|
|
99
|
+
const checkOnRelationId = (entity, destRelationId, filter) => {
|
|
100
|
+
/** 找到能创建此relation的所有父级relation,只要user和其中一个有关联即可以通过 */
|
|
101
|
+
// @oak-ignore
|
|
102
|
+
const relationAuths = context.select('relationAuth', {
|
|
103
|
+
data: {
|
|
104
|
+
id: 1,
|
|
105
|
+
pathId: 1,
|
|
106
|
+
path: {
|
|
107
|
+
id: 1,
|
|
108
|
+
sourceEntity: 1,
|
|
109
|
+
destEntity: 1,
|
|
110
|
+
value: 1,
|
|
111
|
+
recursive: 1,
|
|
112
|
+
},
|
|
113
|
+
sourceRelationId: 1,
|
|
114
|
+
sourceRelation: {
|
|
115
|
+
id: 1,
|
|
116
|
+
entity: 1,
|
|
117
|
+
entityId: 1,
|
|
118
|
+
},
|
|
119
|
+
destRelationId: 1,
|
|
120
|
+
destRelation: {
|
|
121
|
+
id: 1,
|
|
122
|
+
entity: 1,
|
|
123
|
+
entityId: 1,
|
|
124
|
+
},
|
|
125
|
+
},
|
|
126
|
+
filter: {
|
|
127
|
+
destRelationId,
|
|
128
|
+
},
|
|
129
|
+
}, { dontCollect: true });
|
|
130
|
+
const checkRelationAuth = (relationAuth) => {
|
|
131
|
+
const { destRelation, sourceRelationId, path } = relationAuth;
|
|
132
|
+
assert(entity === destRelation.entity);
|
|
133
|
+
let destEntityFilter = this.makePathFilter(entity, path, this.schema, {
|
|
134
|
+
userRelation$entity: {
|
|
135
|
+
userId,
|
|
136
|
+
relationId: sourceRelationId,
|
|
137
|
+
},
|
|
138
|
+
});
|
|
139
|
+
if (filter) {
|
|
140
|
+
destEntityFilter = combineFilters(entity, this.schema, [destEntityFilter, filter]);
|
|
141
|
+
}
|
|
142
|
+
// @oak-ignore
|
|
143
|
+
return context.count(destRelation.entity, {
|
|
144
|
+
filter: destEntityFilter,
|
|
145
|
+
}, { ignoreAttrMiss: true });
|
|
146
|
+
};
|
|
147
|
+
// I4:单一聚合,判定逻辑与 IO 形态解耦
|
|
148
|
+
return bind(relationAuths, (ras) => bind(allBind(ras.map((ra) => bind(checkRelationAuth(ra), (n) => n > 0)), (values) => values), (values) => values.includes(true)));
|
|
149
|
+
};
|
|
150
|
+
/**
|
|
151
|
+
* 检查对超过一个的relationId是否有操作资格
|
|
152
|
+
* @param intersectionSemantics 是否交集(对每个relationId都得有权限)
|
|
153
|
+
*/
|
|
154
|
+
const checkOnMultipleRelations = (relationFilter, intersectionSemantics, entityFilter, entity) => {
|
|
155
|
+
let entity2 = entity;
|
|
156
|
+
const getRelationIds = () => {
|
|
157
|
+
const relevantIds = getRelevantIds(relationFilter);
|
|
158
|
+
if (relevantIds.length > 0) {
|
|
159
|
+
return relevantIds;
|
|
160
|
+
}
|
|
161
|
+
// @oak-ignore
|
|
162
|
+
const relations = context.select('relation', {
|
|
163
|
+
data: {
|
|
164
|
+
id: 1,
|
|
165
|
+
entity: 1,
|
|
166
|
+
entityId: 1,
|
|
167
|
+
},
|
|
168
|
+
filter: relationFilter
|
|
169
|
+
}, { dontCollect: true });
|
|
170
|
+
return bind(relations, (rs) => {
|
|
171
|
+
if (!entity2) {
|
|
172
|
+
entity2 = rs[0]?.entity;
|
|
173
|
+
}
|
|
174
|
+
else if (rs.length) {
|
|
175
|
+
assert(entity2 === rs[0]?.entity);
|
|
176
|
+
}
|
|
177
|
+
return rs.map(ele => ele.id);
|
|
178
|
+
});
|
|
179
|
+
};
|
|
180
|
+
// I4:静态可解析 ids 与查询所得 ids、同步与异步走同一条聚合(Promise 不会混入判定)。
|
|
181
|
+
// 空集 ⇒ false 失败关闭,两种模式同结论(§7.3 漂移消除;不再保留“异步 assert 裸抛”)。
|
|
182
|
+
return bind(getRelationIds(), (ids) => {
|
|
183
|
+
if (ids.length === 0) {
|
|
184
|
+
return false;
|
|
185
|
+
}
|
|
186
|
+
return bind(allBind(ids.map((ele) => checkOnRelationId(entity2, ele, entityFilter)), (value) => value), (value) => intersectionSemantics ? !value.includes(false) : value.includes(true));
|
|
187
|
+
});
|
|
188
|
+
};
|
|
189
|
+
if (action === 'create') {
|
|
190
|
+
const { entity, entityId, relationId } = filter;
|
|
191
|
+
assert(typeof entity === 'string');
|
|
192
|
+
let entityFilter;
|
|
193
|
+
if (entityId !== undefined && entityId !== null) {
|
|
194
|
+
entityFilter = {
|
|
195
|
+
id: entityId,
|
|
196
|
+
};
|
|
197
|
+
}
|
|
198
|
+
else {
|
|
199
|
+
// userEntityGrant会有这种情况,限定某个对象的范围进行授权
|
|
200
|
+
entityFilter = filter[entity];
|
|
201
|
+
}
|
|
202
|
+
if (relationId !== undefined && relationId !== null) {
|
|
203
|
+
// 如果指定relation,则测试该relation上是否可行
|
|
204
|
+
// 目前可能会有多个relationIds传入(userEntityGrant做测试),但一定是可以确定的relationId集合
|
|
205
|
+
return checkOnMultipleRelations({ id: relationId }, true, entityFilter, entity);
|
|
206
|
+
}
|
|
207
|
+
else {
|
|
208
|
+
// 否则为测试“能否”有权限管理的资格,此时只要有一个就可以
|
|
209
|
+
// 这是为上层的menu所有,真正的创建不可能走到这里
|
|
210
|
+
assert(entityId !== undefined && entityId !== null);
|
|
211
|
+
return checkOnMultipleRelations({
|
|
212
|
+
entity,
|
|
213
|
+
$or: [
|
|
214
|
+
{
|
|
215
|
+
entityId: {
|
|
216
|
+
$exists: false,
|
|
217
|
+
},
|
|
218
|
+
},
|
|
219
|
+
{
|
|
220
|
+
entityId,
|
|
221
|
+
}
|
|
222
|
+
]
|
|
223
|
+
}, false, entityFilter, entity);
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
else {
|
|
227
|
+
assert(action === 'remove');
|
|
228
|
+
// 有可能是删除多个userRelation,这时必须检查每一个relation都有对应的权限(有一个不能删除那就不能删除)
|
|
229
|
+
return checkOnMultipleRelations({
|
|
230
|
+
userRelation$relation: filter,
|
|
231
|
+
}, false, {
|
|
232
|
+
userRelation$entity: filter,
|
|
233
|
+
}, filter.entity);
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
checkOperateSpecialEntities(entity2, action, filter, context) {
|
|
237
|
+
switch (entity2) {
|
|
238
|
+
case 'userRelation': {
|
|
239
|
+
assert(!(filter instanceof Array));
|
|
240
|
+
return this.checkUserRelation(context, action, filter);
|
|
241
|
+
}
|
|
242
|
+
case 'user': {
|
|
243
|
+
// 对用户的操作由应用自己去管理权限,这里只检查grant/revoke
|
|
244
|
+
if (['grant', 'revoke'].includes(action)) {
|
|
245
|
+
return true;
|
|
246
|
+
}
|
|
247
|
+
else {
|
|
248
|
+
// 应用允许用户操作其它用户的逻辑请通过编写类型为relation的checker去控制,在这里不能加以限制
|
|
249
|
+
return true;
|
|
250
|
+
}
|
|
251
|
+
}
|
|
252
|
+
case 'modi': {
|
|
253
|
+
/** 正常情况下对modi的生成是在触发器下openRootMode,不会走到这里
|
|
254
|
+
* 但是有些例外,如extraFile如果在modi中创建,上传成功之后需要显式生成一条modi,这时对modi的
|
|
255
|
+
* 检查可以转化为对其父entity的update权限检查
|
|
256
|
+
*/
|
|
257
|
+
assert(action === 'create');
|
|
258
|
+
const { entity, entityId } = filter;
|
|
259
|
+
return this.checkOperation(entity, {
|
|
260
|
+
action: 'update',
|
|
261
|
+
data: {},
|
|
262
|
+
filter: {
|
|
263
|
+
id: entityId,
|
|
264
|
+
},
|
|
265
|
+
}, context);
|
|
266
|
+
}
|
|
267
|
+
case 'relation': {
|
|
268
|
+
// 创建relation目前不支持,以后再说
|
|
269
|
+
return false;
|
|
270
|
+
}
|
|
271
|
+
case 'userEntityGrant': {
|
|
272
|
+
// userEntityGrant的创建相当于授权,领取相当于赋权
|
|
273
|
+
if (['create', 'update', 'remove'].includes(action)) {
|
|
274
|
+
if (action === 'create') {
|
|
275
|
+
const { relationEntity, relationEntityFilter, relationIds } = filter;
|
|
276
|
+
return this.checkOperateSpecialEntities('userRelation', 'create', {
|
|
277
|
+
entity: relationEntity,
|
|
278
|
+
[relationEntity]: relationEntityFilter,
|
|
279
|
+
relationId: {
|
|
280
|
+
$in: relationIds,
|
|
281
|
+
},
|
|
282
|
+
}, context);
|
|
283
|
+
}
|
|
284
|
+
return this.checkOperateSpecialEntities('userRelation', 'remove', {
|
|
285
|
+
relation: {
|
|
286
|
+
userEntityGrant$relation: filter,
|
|
287
|
+
},
|
|
288
|
+
}, context);
|
|
289
|
+
}
|
|
290
|
+
return true;
|
|
291
|
+
}
|
|
292
|
+
default: {
|
|
293
|
+
assert(false, `对象${entity2}的权限控制没有加以控制`);
|
|
294
|
+
}
|
|
295
|
+
}
|
|
296
|
+
}
|
|
297
|
+
isKnownEntity(candidate) {
|
|
298
|
+
return typeof candidate === 'string'
|
|
299
|
+
&& Object.prototype.hasOwnProperty.call(this.schema, candidate);
|
|
300
|
+
}
|
|
301
|
+
collectStaticDeduceTargets(entity, filter) {
|
|
302
|
+
const result = [];
|
|
303
|
+
const seen = new Set();
|
|
304
|
+
const filterRecord = filter;
|
|
305
|
+
const { ref } = this.schema[entity].attributes.entity;
|
|
306
|
+
const hasValue = (key) => Object.prototype.hasOwnProperty.call(filterRecord, key)
|
|
307
|
+
&& filterRecord[key] !== undefined
|
|
308
|
+
&& filterRecord[key] !== null;
|
|
309
|
+
const addTarget = (targetEntity, targetFilter) => {
|
|
310
|
+
if (!this.isKnownEntity(targetEntity) || !Array.isArray(ref) || !ref.includes(targetEntity)) {
|
|
311
|
+
console.warn(`RelationAuth: invalid polymorphic target entity ${String(targetEntity)}; preserving the root authorization candidate`);
|
|
312
|
+
return;
|
|
313
|
+
}
|
|
314
|
+
const key = `${String(targetEntity)}:${stableFilterKey(targetFilter)}`;
|
|
315
|
+
if (!seen.has(key)) {
|
|
316
|
+
seen.add(key);
|
|
317
|
+
result.push({ entity: targetEntity, filter: targetFilter });
|
|
318
|
+
}
|
|
319
|
+
};
|
|
320
|
+
// 多态目标的候选集合是并集:不能因为第一个 refEntity 命中就 break。
|
|
321
|
+
if (typeof filterRecord.entity === 'string' && hasValue('entityId')) {
|
|
322
|
+
addTarget(filterRecord.entity, { id: filterRecord.entityId });
|
|
323
|
+
}
|
|
324
|
+
else {
|
|
325
|
+
assert(ref instanceof Array);
|
|
326
|
+
for (const refEntity of ref) {
|
|
327
|
+
if (Object.prototype.hasOwnProperty.call(filterRecord, refEntity)
|
|
328
|
+
&& filterRecord[refEntity] !== undefined
|
|
329
|
+
&& filterRecord[refEntity] !== null) {
|
|
330
|
+
addTarget(refEntity, filterRecord[refEntity]);
|
|
331
|
+
}
|
|
332
|
+
}
|
|
333
|
+
}
|
|
334
|
+
return result;
|
|
335
|
+
}
|
|
336
|
+
/**
|
|
337
|
+
* deduce 折算(I5 消费方):实体权限可折算为其多态 entity/entityId 所指父对象的权限。
|
|
338
|
+
* 候选集合是并集 U(root) ∪ ⋃U(targetᵢ);任何不能静态确证目标的情形都只保留根候选
|
|
339
|
+
* (宁可保守拒绝,不能任选一行扩大授权)。
|
|
340
|
+
*/
|
|
341
|
+
getDeducedEntityFilters(entity, filter, actions, context) {
|
|
342
|
+
const entityFilters = [{
|
|
343
|
+
entity,
|
|
344
|
+
filter,
|
|
345
|
+
actions,
|
|
346
|
+
}];
|
|
347
|
+
if (this.edgeRuleOf(entity, 'entity') !== 'deduce') {
|
|
348
|
+
return entityFilters;
|
|
349
|
+
}
|
|
350
|
+
const filterRecord = filter;
|
|
351
|
+
const targetCandidates = this.collectStaticDeduceTargets(entity, filter);
|
|
352
|
+
const getRecursiveDeducedFilters = (deduceEntity, deduceFilter) => {
|
|
353
|
+
const excludeActions = readOnlyActions.concat([ /* 'create', 'remove' */]);
|
|
354
|
+
const updateActions = this.schema[deduceEntity].actions.filter((a) => !excludeActions.includes(a));
|
|
355
|
+
return this.getDeducedEntityFilters(deduceEntity, deduceFilter, actions[0] === 'select' ? actions : updateActions, context);
|
|
356
|
+
};
|
|
357
|
+
if (targetCandidates.length > 0) {
|
|
358
|
+
return bind(allBind(targetCandidates.map(({ entity: targetEntity, filter: targetFilter }) => getRecursiveDeducedFilters(targetEntity, targetFilter)), (groups) => groups), (groups) => {
|
|
359
|
+
groups.forEach(group => entityFilters.push(...group));
|
|
360
|
+
return entityFilters;
|
|
361
|
+
});
|
|
362
|
+
}
|
|
363
|
+
/**
|
|
364
|
+
* filter 无法静态确定多态目标时,通过真实行反查 entity/entityId。
|
|
365
|
+
* 若结果超过一行,目标不唯一;此时只保留根候选。
|
|
366
|
+
*/
|
|
367
|
+
// @oak-ignore
|
|
368
|
+
const rows2 = context.select(entity, {
|
|
369
|
+
data: {
|
|
370
|
+
id: 1,
|
|
371
|
+
entity: 1,
|
|
372
|
+
entityId: 1,
|
|
373
|
+
},
|
|
374
|
+
filter,
|
|
375
|
+
indexFrom: 0,
|
|
376
|
+
// 这里只区分 0、1、至少 2 行;更多行不会改变唯一性判断。
|
|
377
|
+
count: 2,
|
|
378
|
+
}, { dontCollect: true, blockTrigger: true });
|
|
379
|
+
return bind(rows2, (rows) => {
|
|
380
|
+
if (rows.length > 1) {
|
|
381
|
+
console.warn(`RelationAuth: polymorphic target for ${entity} is ambiguous (${rows.length} rows); preserving the root authorization candidate`);
|
|
382
|
+
return entityFilters;
|
|
383
|
+
}
|
|
384
|
+
if (rows.length === 0) {
|
|
385
|
+
// 指定 id 的更新可能仍只有 modi 记录可供推导;空字符串 ID 也属于有效键值。
|
|
386
|
+
if (Object.prototype.hasOwnProperty.call(filterRecord, 'id')
|
|
387
|
+
&& filterRecord.id !== undefined && filterRecord.id !== null) {
|
|
388
|
+
// @oak-ignore
|
|
389
|
+
const modies = context.select('modi', {
|
|
390
|
+
data: {
|
|
391
|
+
id: 1,
|
|
392
|
+
data: 1,
|
|
393
|
+
entity: 1,
|
|
394
|
+
entityId: 1,
|
|
395
|
+
},
|
|
396
|
+
filter: {
|
|
397
|
+
filter,
|
|
398
|
+
}
|
|
399
|
+
}, {});
|
|
400
|
+
return bind(modies, (modiRows) => {
|
|
401
|
+
if (modiRows[0]) {
|
|
402
|
+
const { entity: modiEntity, entityId } = modiRows[0];
|
|
403
|
+
if (this.isKnownEntity(modiEntity) && entityId !== undefined && entityId !== null) {
|
|
404
|
+
entityFilters.push({
|
|
405
|
+
entity: modiEntity,
|
|
406
|
+
filter: { id: entityId },
|
|
407
|
+
actions: ['update'],
|
|
408
|
+
});
|
|
409
|
+
}
|
|
410
|
+
else if (modiEntity !== undefined && modiEntity !== null) {
|
|
411
|
+
console.warn(`RelationAuth: unknown modi target entity ${String(modiEntity)}; preserving the root authorization candidate`);
|
|
412
|
+
}
|
|
413
|
+
}
|
|
414
|
+
return entityFilters;
|
|
415
|
+
});
|
|
416
|
+
}
|
|
417
|
+
return entityFilters;
|
|
418
|
+
}
|
|
419
|
+
const { entity: deducedEntity, entityId: deducedEntityId } = rows[0];
|
|
420
|
+
if (deducedEntityId === undefined || deducedEntityId === null) {
|
|
421
|
+
return entityFilters;
|
|
422
|
+
}
|
|
423
|
+
if (!this.isKnownEntity(deducedEntity)) {
|
|
424
|
+
console.warn(`RelationAuth: unknown deduced target entity ${String(deducedEntity)}; preserving the root authorization candidate`);
|
|
425
|
+
return entityFilters;
|
|
426
|
+
}
|
|
427
|
+
return bind(getRecursiveDeducedFilters(deducedEntity, {
|
|
428
|
+
id: deducedEntityId,
|
|
429
|
+
}), (group) => {
|
|
430
|
+
entityFilters.push(...group);
|
|
431
|
+
return entityFilters;
|
|
432
|
+
});
|
|
433
|
+
});
|
|
434
|
+
}
|
|
435
|
+
/**
|
|
436
|
+
* 投影侧 filter 精修(§4.1 filter 三语义位置):
|
|
437
|
+
* 只保留能约束授权路径的属性,同时返回投影是否保持了原表达式。
|
|
438
|
+
* 若原查询为 Q=A∧B,删除 B 得到 A,则 Q⊆A,适合作为授权检查的安全上界;
|
|
439
|
+
* 若 Q=A∨B,只要每个分支都向上近似,A∨B⊆A'∨B' 仍成立。
|
|
440
|
+
* 但 NOT 和 XOR 不满足这种单调性:其内部发生删减时丢弃整个 NOT/XOR,
|
|
441
|
+
* 宁可少优化也不能误拒绝或扩大授权。
|
|
442
|
+
*/
|
|
443
|
+
refineFilter(entity, originFilter) {
|
|
444
|
+
if (!originFilter || typeof originFilter !== 'object' || Array.isArray(originFilter)) {
|
|
445
|
+
console.warn(`RelationAuth: malformed filter on ${String(entity)}; preserving an opaque authorization candidate`);
|
|
446
|
+
return { filter: {}, exact: false };
|
|
447
|
+
}
|
|
448
|
+
const filter2 = {};
|
|
449
|
+
let exact = true;
|
|
450
|
+
const entries = Object.entries(originFilter);
|
|
451
|
+
for (const [attr, operand] of entries) {
|
|
452
|
+
if (attr === '$and' || attr === '$or') {
|
|
453
|
+
if (!Array.isArray(operand)) {
|
|
454
|
+
exact = false;
|
|
455
|
+
continue;
|
|
456
|
+
}
|
|
457
|
+
const refined = operand.map((branch) => this.refineFilter(entity, branch));
|
|
458
|
+
filter2[attr] = refined.map(({ filter }) => filter);
|
|
459
|
+
exact = exact && refined.every(({ exact: branchExact }) => branchExact);
|
|
460
|
+
continue;
|
|
461
|
+
}
|
|
462
|
+
if (attr === '$xor') {
|
|
463
|
+
if (!Array.isArray(operand)) {
|
|
464
|
+
exact = false;
|
|
465
|
+
continue;
|
|
466
|
+
}
|
|
467
|
+
const refined = operand.map((branch) => this.refineFilter(entity, branch));
|
|
468
|
+
if (refined.every(({ exact: branchExact }) => branchExact)) {
|
|
469
|
+
filter2[attr] = refined.map(({ filter }) => filter);
|
|
470
|
+
}
|
|
471
|
+
else {
|
|
472
|
+
exact = false;
|
|
473
|
+
}
|
|
474
|
+
continue;
|
|
475
|
+
}
|
|
476
|
+
if (attr === '$not') {
|
|
477
|
+
if (!operand || typeof operand !== 'object' || Array.isArray(operand)) {
|
|
478
|
+
exact = false;
|
|
479
|
+
continue;
|
|
480
|
+
}
|
|
481
|
+
const refined = this.refineFilter(entity, operand);
|
|
482
|
+
if (refined.exact) {
|
|
483
|
+
filter2[attr] = refined.filter;
|
|
484
|
+
}
|
|
485
|
+
else {
|
|
486
|
+
// P⊆P' does not imply ¬P⊆¬P';删除整个否定项才是安全上界。
|
|
487
|
+
exact = false;
|
|
488
|
+
}
|
|
489
|
+
continue;
|
|
490
|
+
}
|
|
491
|
+
if (attr.startsWith('$') || attr.startsWith('#')) {
|
|
492
|
+
// $expr、$text 和元数据可能继续缩小结果,忽略它们会失去等价性。
|
|
493
|
+
exact = false;
|
|
494
|
+
continue;
|
|
495
|
+
}
|
|
496
|
+
let rel;
|
|
497
|
+
try {
|
|
498
|
+
rel = judgeRelation(this.schema, entity, attr);
|
|
499
|
+
}
|
|
500
|
+
catch {
|
|
501
|
+
// 未知属性无法证明其对授权路径的单调性;忽略它相当于向上近似,
|
|
502
|
+
// 但必须告警并保留 exact=false,避免把它误当成精确授权条件。
|
|
503
|
+
console.warn(`RelationAuth: unknown filter attribute ${attr} on ${String(entity)}; preserving an opaque authorization candidate`);
|
|
504
|
+
exact = false;
|
|
505
|
+
continue;
|
|
506
|
+
}
|
|
507
|
+
if (rel === 1) {
|
|
508
|
+
const attribute = this.schema[entity].attributes[attr];
|
|
509
|
+
if ([PrimaryKeyAttribute, 'entity', 'entityId'].includes(attr) || attribute?.type === 'ref') {
|
|
510
|
+
filter2[attr] = operand;
|
|
511
|
+
}
|
|
512
|
+
else {
|
|
513
|
+
exact = false;
|
|
514
|
+
}
|
|
515
|
+
}
|
|
516
|
+
else if (rel === 2) {
|
|
517
|
+
const refined = this.refineFilter(attr, operand);
|
|
518
|
+
filter2[attr] = refined.filter;
|
|
519
|
+
exact = exact && refined.exact;
|
|
520
|
+
}
|
|
521
|
+
else if (typeof rel === 'string') {
|
|
522
|
+
const refined = this.refineFilter(rel, operand);
|
|
523
|
+
filter2[attr] = refined.filter;
|
|
524
|
+
exact = exact && refined.exact;
|
|
525
|
+
}
|
|
526
|
+
else if (rel instanceof Array) {
|
|
527
|
+
const sqp = operand && typeof operand === 'object' && !Array.isArray(operand)
|
|
528
|
+
? operand['#sqp']
|
|
529
|
+
: undefined;
|
|
530
|
+
// filter 侧一对多子查询目前只能表达 in 量词;其它量词不保留,避免改变集合语义。
|
|
531
|
+
if (!sqp || sqp === 'in') {
|
|
532
|
+
const refined = this.refineFilter(rel[0], operand);
|
|
533
|
+
filter2[attr] = refined.filter;
|
|
534
|
+
exact = exact && refined.exact;
|
|
535
|
+
}
|
|
536
|
+
else {
|
|
537
|
+
exact = false;
|
|
538
|
+
}
|
|
539
|
+
}
|
|
540
|
+
else {
|
|
541
|
+
exact = false;
|
|
542
|
+
}
|
|
543
|
+
}
|
|
544
|
+
return { filter: filter2, exact };
|
|
545
|
+
}
|
|
546
|
+
/**
|
|
547
|
+
* 读路径任务链(D1/D2/D6,I2 逐层必检):
|
|
548
|
+
* 投影 OTM 骨架上每个节点生成一个独立任务;任务 filter = 精修后的根 filter 沿
|
|
549
|
+
* OTM 链逐层压平(left-join 语义下父链约束只由外键嵌入表达,不含子存在性约束,D6)。
|
|
550
|
+
* MTO 投影不生成任务(D5/I3);deduce 节点不展开(I5),其可见性由锚点节点任务担保。
|
|
551
|
+
* 根任务无条件生成——包括根下挂 OTM(旧"只检最深叶"的托付已废弃,D3)与根 selectFree
|
|
552
|
+
* (selectFree 只豁免自身,链上其它节点照常生成任务;根自身的豁免由 exempt 标记表达)。
|
|
553
|
+
*/
|
|
554
|
+
buildReadTasks(entity, selection) {
|
|
555
|
+
const tasks = [];
|
|
556
|
+
const walk = (entity2, projection2, filter2, parentEntity, edgeAttr) => {
|
|
557
|
+
let hasOneToMany = false;
|
|
558
|
+
for (const attr in projection2) {
|
|
559
|
+
const rel = judgeRelation(this.schema, entity2, attr);
|
|
560
|
+
if (!(rel instanceof Array)) {
|
|
561
|
+
continue;
|
|
562
|
+
}
|
|
563
|
+
const [e, foreignKey] = rel;
|
|
564
|
+
// I5:deduce 节点不作为独立任务展开(其权限折算为锚点对象权限)
|
|
565
|
+
if (this.edgeRuleOf(e, 'entity') === 'deduce') {
|
|
566
|
+
continue;
|
|
567
|
+
}
|
|
568
|
+
hasOneToMany = true;
|
|
569
|
+
const { data: subProjection, filter: subFilter } = projection2[attr];
|
|
570
|
+
const refinedSubFilter = subFilter && this.refineFilter(e, subFilter);
|
|
571
|
+
const subFilter2 = combineFilters(e, this.schema, [refinedSubFilter?.filter, {
|
|
572
|
+
[foreignKey ? foreignKey.slice(0, foreignKey.length - 2) : entity2]: filter2,
|
|
573
|
+
}]);
|
|
574
|
+
walk(e, subProjection, subFilter2, entity2, attr);
|
|
575
|
+
}
|
|
576
|
+
// I2/D4:本节点任务无条件生成;selectFree/特殊实体仅标记自身豁免。
|
|
577
|
+
tasks.push({
|
|
578
|
+
entity: entity2,
|
|
579
|
+
filter: filter2,
|
|
580
|
+
exempt: this.isSelfExemptEntity(entity2),
|
|
581
|
+
parentEntity,
|
|
582
|
+
edgeAttr,
|
|
583
|
+
});
|
|
584
|
+
};
|
|
585
|
+
walk(entity, selection.data, this.refineFilter(entity, selection.filter || {}).filter);
|
|
586
|
+
// 任务链顺序为叶→根(walk 后序),E1 要求自顶向下短路:反转为根→叶。
|
|
587
|
+
return tasks.reverse();
|
|
588
|
+
}
|
|
589
|
+
/**
|
|
590
|
+
* 单个读任务的包含性判定:filter ⊆ Auth(entity,'select')。
|
|
591
|
+
* 返回 [是否通过, 通过见证(可用于 E2 扩展的 actionAuth 行)]。
|
|
592
|
+
*/
|
|
593
|
+
checkReadTask(task, context, witnesses) {
|
|
594
|
+
// I5:读侧与写侧共用同一 deduce 折算(含静态目标、行反查、modi 回退)。
|
|
595
|
+
return bind(this.getDeducedEntityFilters(task.entity, task.filter, ['select'], context), (candidates) => {
|
|
596
|
+
const targetEntities = uniq(candidates.map((candidate) => candidate.entity));
|
|
597
|
+
const userId = context.getCurrentUserId();
|
|
598
|
+
if (!userId) {
|
|
599
|
+
throw new OakUnloggedInException();
|
|
600
|
+
}
|
|
601
|
+
// E2 扩展路径快路:候选见证先查(数据存在才生效,禁止无数据合成继承)
|
|
602
|
+
return bind(this.probeWitnesses(task, context, witnesses), (witnessPass) => {
|
|
603
|
+
if (witnessPass) {
|
|
604
|
+
return [true, []];
|
|
605
|
+
}
|
|
606
|
+
const restrictedCandidates = candidates.filter((candidate) => !this.isSelfExemptEntity(candidate.entity));
|
|
607
|
+
if (restrictedCandidates.length === 0) {
|
|
608
|
+
// I6:全部候选均被自身豁免 ⇒ 本任务通过,无需授权数据
|
|
609
|
+
return [true, []];
|
|
610
|
+
}
|
|
611
|
+
// @oak-ignore sync/async 双形态 IO 叶子
|
|
612
|
+
const actionAuths = context.select('actionAuth', {
|
|
613
|
+
data: {
|
|
614
|
+
path: {
|
|
615
|
+
value: 1,
|
|
616
|
+
destEntity: 1,
|
|
617
|
+
recursive: 1,
|
|
618
|
+
},
|
|
619
|
+
deActions: 1,
|
|
620
|
+
relationId: 1,
|
|
621
|
+
},
|
|
622
|
+
filter: {
|
|
623
|
+
deActions: {
|
|
624
|
+
$contains: 'select',
|
|
625
|
+
},
|
|
626
|
+
path: {
|
|
627
|
+
destEntity: {
|
|
628
|
+
$in: targetEntities,
|
|
629
|
+
},
|
|
630
|
+
},
|
|
631
|
+
// E3:role-bound actionAuth 只有当前用户属于该 relation 时才是可用授权臂;
|
|
632
|
+
// relationId 为空(直达 user)的规则作为另一并集臂保留。
|
|
633
|
+
$or: [
|
|
634
|
+
{ relationId: { $exists: false } },
|
|
635
|
+
{ relation: { userRelation$relation: { userId } } },
|
|
636
|
+
],
|
|
637
|
+
}
|
|
638
|
+
}, { dontCollect: true, ignoreAttrMiss: true });
|
|
639
|
+
return bind(actionAuths, (authRows) => bind(this.checkTaskAgainstAuths(candidates, authRows, context), (matched) => {
|
|
640
|
+
if (matched.length === 0 && process.env.NODE_ENV === 'development') {
|
|
641
|
+
console.warn('对象的select权限被否决,请检查', task);
|
|
642
|
+
}
|
|
643
|
+
return [matched.length > 0, matched];
|
|
644
|
+
}));
|
|
645
|
+
});
|
|
646
|
+
});
|
|
647
|
+
}
|
|
648
|
+
/**
|
|
649
|
+
* E2:把父任务通过见证沿边派生为子任务的扩展路径(I8 原语),
|
|
650
|
+
* 并在 actionAuth 中以数据见证确认扩展路径的授权行存在;不存在则回落正常判定。
|
|
651
|
+
*/
|
|
652
|
+
probeWitnesses(task, context, witnesses) {
|
|
653
|
+
if (!task.parentEntity || !task.edgeAttr || witnesses.length === 0) {
|
|
654
|
+
return false;
|
|
655
|
+
}
|
|
656
|
+
const userId = context.getCurrentUserId();
|
|
657
|
+
if (!userId) {
|
|
658
|
+
return false;
|
|
659
|
+
}
|
|
660
|
+
// 读任务只沿 OTM 边生成(buildReadTasks),键形 `子实体$子指向父的边名`;
|
|
661
|
+
// 见证一律按 OTM 前缀派生(I8 的另一侧:写树 MTO 键由 resolveTreeEdge 判向)。
|
|
662
|
+
const edgeName = task.edgeAttr.split('$')[1];
|
|
663
|
+
const extended = uniq(witnesses
|
|
664
|
+
.map((value) => deriveChildPath('otm', edgeName, value))
|
|
665
|
+
.filter((value) => value !== undefined));
|
|
666
|
+
if (extended.length === 0) {
|
|
667
|
+
return false;
|
|
668
|
+
}
|
|
669
|
+
// @oak-ignore
|
|
670
|
+
const rows = context.select('actionAuth', {
|
|
671
|
+
data: {
|
|
672
|
+
id: 1,
|
|
673
|
+
},
|
|
674
|
+
filter: {
|
|
675
|
+
path: {
|
|
676
|
+
value: {
|
|
677
|
+
$in: extended,
|
|
678
|
+
},
|
|
679
|
+
destEntity: task.entity,
|
|
680
|
+
},
|
|
681
|
+
deActions: {
|
|
682
|
+
$contains: 'select',
|
|
683
|
+
},
|
|
684
|
+
// E3:role-bound 授权行只有当前用户属于该 relation 时才能作为数据见证。
|
|
685
|
+
$or: [
|
|
686
|
+
{ relationId: { $exists: false } },
|
|
687
|
+
{ relation: { userRelation$relation: { userId } } },
|
|
688
|
+
],
|
|
689
|
+
}
|
|
690
|
+
}, { dontCollect: true, ignoreAttrMiss: true });
|
|
691
|
+
return bind(rows, (r) => r.length > 0);
|
|
692
|
+
}
|
|
693
|
+
/**
|
|
694
|
+
* 任务的授权并集判定:对每个 deduce 候选(OR 语义,通过一个即可),
|
|
695
|
+
* 以该实体全部可用 actionAuth 的 scope 并集(§3.3)做包含性检查(静态优先,
|
|
696
|
+
* 数据比对兜底,不确定即拒绝)。返回所有使任务通过的见证行(供 E2)。
|
|
697
|
+
*/
|
|
698
|
+
checkTaskAgainstAuths(candidates, actionAuths, context) {
|
|
699
|
+
let index = 0;
|
|
700
|
+
const step = () => {
|
|
701
|
+
while (index < candidates.length) {
|
|
702
|
+
const { entity, filter } = candidates[index++];
|
|
703
|
+
const matched = this.collectScopeAuths(entity, actionAuths);
|
|
704
|
+
const proceed = (allowed) => allowed ? matched : undefined;
|
|
705
|
+
const result = bind(this.scopeContainsFilter(entity, filter, matched, context), proceed);
|
|
706
|
+
if (result instanceof Promise) {
|
|
707
|
+
// @oak-ignore trampolin 续延:Promise 形态由外层统一接续
|
|
708
|
+
return result.then((passed) => passed && passed.length > 0 ? passed : step());
|
|
709
|
+
}
|
|
710
|
+
if (result) {
|
|
711
|
+
return result;
|
|
712
|
+
}
|
|
713
|
+
}
|
|
714
|
+
return [];
|
|
715
|
+
};
|
|
716
|
+
return step();
|
|
717
|
+
}
|
|
718
|
+
/** scope 合成:destEntity 匹配的授权行(并集成员,§3.3) */
|
|
719
|
+
collectScopeAuths(entity, actionAuths) {
|
|
720
|
+
return actionAuths.filter(ele => ele.path.destEntity === entity);
|
|
721
|
+
}
|
|
722
|
+
/** F ⊆ ⋃scope(minimize 后合成,数据比对兜底) */
|
|
723
|
+
scopeContainsFilter(entity, filter, actionAuths, context) {
|
|
724
|
+
const filters = minimizeAuthorizationUnion(entity, this.schema, actionAuths.map((ele) => {
|
|
725
|
+
const { path, relationId } = ele;
|
|
726
|
+
if (relationId !== undefined && relationId !== null) {
|
|
727
|
+
return this.makePathFilter(entity, path, this.schema, {
|
|
728
|
+
userRelation$entity: {
|
|
729
|
+
userId: context.getCurrentUserId(),
|
|
730
|
+
relationId,
|
|
731
|
+
}
|
|
732
|
+
});
|
|
733
|
+
}
|
|
734
|
+
// 说明是通过userId关联
|
|
735
|
+
return this.makePathFilter(entity, path, this.schema, {
|
|
736
|
+
id: context.getCurrentUserId(),
|
|
737
|
+
});
|
|
738
|
+
}));
|
|
739
|
+
const groupFilter = combineFilters(entity, this.schema, filters, true);
|
|
740
|
+
if (!groupFilter) {
|
|
741
|
+
return false;
|
|
742
|
+
}
|
|
743
|
+
// F ⊆ S:请求行集必须被授权 scope 包含(contained=scope)
|
|
744
|
+
return checkFilterContains(entity, context, groupFilter, filter, true);
|
|
745
|
+
}
|
|
746
|
+
checkSelection(entity, selection, context) {
|
|
747
|
+
const tasks = this.buildReadTasks(entity, selection);
|
|
748
|
+
// 去重相同 (entity, filter) 的任务(无依赖 IO 的纯优化)
|
|
749
|
+
const seen = new Set();
|
|
750
|
+
const chain = tasks.filter((task) => {
|
|
751
|
+
if (hasCyclicFilter(task.filter)) {
|
|
752
|
+
console.warn('RelationAuth: cyclic task filter; preserving the required authorization task');
|
|
753
|
+
return true;
|
|
754
|
+
}
|
|
755
|
+
const key = JSON.stringify([String(task.entity), stableFilterKey(task.filter)]);
|
|
756
|
+
if (seen.has(key)) {
|
|
757
|
+
return false;
|
|
758
|
+
}
|
|
759
|
+
seen.add(key);
|
|
760
|
+
return true;
|
|
761
|
+
});
|
|
762
|
+
// I6:全部任务只被自身豁免 ⇒ 无 IO、无登录要求
|
|
763
|
+
const restricted = chain.filter((task) => !task.exempt);
|
|
764
|
+
if (restricted.length === 0) {
|
|
765
|
+
return true;
|
|
766
|
+
}
|
|
767
|
+
if (!context.getCurrentUserId()) {
|
|
768
|
+
throw new OakUnloggedInException();
|
|
769
|
+
}
|
|
770
|
+
// 根→叶顺序求值;父任务通过后其见证路径派生给子任务作 E2 候选。
|
|
771
|
+
let index = 0;
|
|
772
|
+
const witnessByTask = new Map();
|
|
773
|
+
const getWitnesses = (taskIndex) => {
|
|
774
|
+
const task = chain[taskIndex];
|
|
775
|
+
if (!task.parentEntity) {
|
|
776
|
+
return [];
|
|
777
|
+
}
|
|
778
|
+
const parentIndex = chain.findIndex((candidate, i) => i < taskIndex
|
|
779
|
+
&& candidate.entity === task.parentEntity
|
|
780
|
+
&& !candidate.exempt);
|
|
781
|
+
if (parentIndex < 0) {
|
|
782
|
+
return [];
|
|
783
|
+
}
|
|
784
|
+
return witnessByTask.get(parentIndex) ?? [];
|
|
785
|
+
};
|
|
786
|
+
const step = () => {
|
|
787
|
+
while (index < chain.length) {
|
|
788
|
+
const taskIndex = index++;
|
|
789
|
+
const task = chain[taskIndex];
|
|
790
|
+
// I6:exempt 任务豁免自身行集要求,直接通过(链上其它任务不受影响)
|
|
791
|
+
if (task.exempt) {
|
|
792
|
+
continue;
|
|
793
|
+
}
|
|
794
|
+
const result = this.checkReadTask(task, context, getWitnesses(taskIndex));
|
|
795
|
+
const proceed = (verdict) => {
|
|
796
|
+
if (!verdict[0]) {
|
|
797
|
+
return false;
|
|
798
|
+
}
|
|
799
|
+
witnessByTask.set(taskIndex, uniq(verdict[1].map((auth) => auth.path?.value ?? '')));
|
|
800
|
+
// @oak-ignore trampolin 续延:Promise 形态由外层统一接续
|
|
801
|
+
return step();
|
|
802
|
+
};
|
|
803
|
+
if (result instanceof Promise) {
|
|
804
|
+
return result.then(proceed);
|
|
805
|
+
}
|
|
806
|
+
const synced = proceed(result);
|
|
807
|
+
if (synced instanceof Promise) {
|
|
808
|
+
return synced;
|
|
809
|
+
}
|
|
810
|
+
if (synced === false) {
|
|
811
|
+
return false;
|
|
812
|
+
}
|
|
813
|
+
}
|
|
814
|
+
return true;
|
|
815
|
+
};
|
|
816
|
+
// @oak-ignore trampolin 起点:同步链同步完成,异步链以 Promise 返回给 checkActions 统一 await
|
|
817
|
+
return step();
|
|
818
|
+
}
|
|
819
|
+
/**
|
|
820
|
+
* 对于operation,解构出一个树形结构,以方便自顶向下的进行访问
|
|
821
|
+
* 但对于deduce的子对象,不必再向底层查看(I5:addChild 内经 edgeRuleOf 剪枝)
|
|
822
|
+
*/
|
|
823
|
+
destructOperation(entity2, operation2, userId) {
|
|
824
|
+
/**
|
|
825
|
+
* 对create动作,把data中的cascade部分剔除后作为filter参与后续的检验
|
|
826
|
+
*/
|
|
827
|
+
const makeCreateFilter = (entity, operation) => {
|
|
828
|
+
const { data, filter, bornAt } = operation;
|
|
829
|
+
if (data instanceof Array) {
|
|
830
|
+
// A multi-create operation represents a union of concrete rows.
|
|
831
|
+
// Keep the rows under `$or`: containment against this filter then
|
|
832
|
+
// requires the authorization scope to contain every row. Using
|
|
833
|
+
// `$and` would describe their intersection and could authorize an
|
|
834
|
+
// operation whose actual rows are not all permitted.
|
|
835
|
+
const filters = data.map((item) => translateCreateDataToFilter(this.schema, entity, item, !!bornAt));
|
|
836
|
+
return filters.length === 1 ? filters[0] : { $or: filters };
|
|
837
|
+
}
|
|
838
|
+
if (data) {
|
|
839
|
+
return translateCreateDataToFilter(this.schema, entity, data, !!bornAt);
|
|
840
|
+
}
|
|
841
|
+
return filter;
|
|
842
|
+
};
|
|
843
|
+
const addChild = (node, path, child) => {
|
|
844
|
+
// I5:deduce 子节点剪枝——其权限已折算为父对象权限,重复检查反而会误拒
|
|
845
|
+
const paths = path.split('$');
|
|
846
|
+
assert(paths.length >= 2);
|
|
847
|
+
if (this.edgeRuleOf(child.entity, 'entity') === 'deduce' && paths[1] === 'entity') {
|
|
848
|
+
return false;
|
|
849
|
+
}
|
|
850
|
+
if (node.children[path]) {
|
|
851
|
+
if (node.children[path] instanceof Array) {
|
|
852
|
+
node.children[path].push(child);
|
|
853
|
+
}
|
|
854
|
+
else {
|
|
855
|
+
node.children[path] = [node.children[path], child];
|
|
856
|
+
}
|
|
857
|
+
}
|
|
858
|
+
else {
|
|
859
|
+
Object.assign(node.children, {
|
|
860
|
+
[path]: child,
|
|
861
|
+
});
|
|
862
|
+
}
|
|
863
|
+
return true;
|
|
864
|
+
};
|
|
865
|
+
const destructInner = (entity, operation, path, child, hasParent, extraFilter) => {
|
|
866
|
+
const { action, data, filter } = operation;
|
|
867
|
+
const filter2 = action === 'create' ? makeCreateFilter(entity, operation) : filter ? cloneDeep(filter) : {};
|
|
868
|
+
assert(filter2);
|
|
869
|
+
if (extraFilter) {
|
|
870
|
+
Object.assign(filter2, extraFilter);
|
|
871
|
+
}
|
|
872
|
+
const me = {
|
|
873
|
+
entity: entity,
|
|
874
|
+
filter: filter2,
|
|
875
|
+
children: {},
|
|
876
|
+
action,
|
|
877
|
+
};
|
|
878
|
+
let root = me;
|
|
879
|
+
// 如果当前对象是一个toModi的,意味着它的cascadeUpdate会全部被变为modi去缓存,因此不需要再向下检查了
|
|
880
|
+
// modi被apply时,这些modi产生的更新才会被实际检查
|
|
881
|
+
const isModiUpdate = this.schema[entity].toModi && action !== 'remove';
|
|
882
|
+
const isBatchOperation = data instanceof Array;
|
|
883
|
+
if (child) {
|
|
884
|
+
assert(path);
|
|
885
|
+
addChild(me, path, child);
|
|
886
|
+
}
|
|
887
|
+
const dataItems = data instanceof Array ? data : [data];
|
|
888
|
+
for (const dataItem of dataItems) {
|
|
889
|
+
for (const attr in dataItem) {
|
|
890
|
+
const rel = judgeRelation(this.schema, entity, attr, !!operation.bornAt);
|
|
891
|
+
if (rel === 2 && !isModiUpdate) {
|
|
892
|
+
assert(root === me && !hasParent, 'cascadeUpdate必须是树结构,避免森林');
|
|
893
|
+
const mtoOperation = dataItem[attr];
|
|
894
|
+
if (isBatchOperation) {
|
|
895
|
+
const son = destructInner(attr, mtoOperation, undefined, undefined, true);
|
|
896
|
+
addChild(me, `${entity}$entity`, son);
|
|
897
|
+
}
|
|
898
|
+
else {
|
|
899
|
+
root = destructInner(attr, mtoOperation, `${entity}$entity`, me);
|
|
900
|
+
}
|
|
901
|
+
}
|
|
902
|
+
else if (typeof rel === 'string' && !isModiUpdate) {
|
|
903
|
+
assert(root === me && !hasParent, 'cascadeUpdate必须是树结构,避免森林');
|
|
904
|
+
if (isBatchOperation) {
|
|
905
|
+
const son = destructInner(rel, dataItem[attr], undefined, undefined, true);
|
|
906
|
+
addChild(me, `${entity}$${attr}`, son);
|
|
907
|
+
}
|
|
908
|
+
else {
|
|
909
|
+
root = destructInner(rel, dataItem[attr], `${entity}$${attr}`, me);
|
|
910
|
+
}
|
|
911
|
+
}
|
|
912
|
+
else if (rel instanceof Array && !isModiUpdate) {
|
|
913
|
+
const [e, f] = rel;
|
|
914
|
+
const otmOperations = dataItem[attr];
|
|
915
|
+
/**
|
|
916
|
+
* 目前只有当一对多个userRelation的操作需要将entity和entityId复制到子对象上
|
|
917
|
+
* 因为对userRelation的判断是走的特殊路径,无法利用父对象的actionAuth
|
|
918
|
+
*/
|
|
919
|
+
let extraFilter;
|
|
920
|
+
if (e === 'userRelation' && entity !== 'user') {
|
|
921
|
+
me.userRelations = [];
|
|
922
|
+
extraFilter = {
|
|
923
|
+
entity,
|
|
924
|
+
entityId: 'id' in filter2 ? filter2.id : undefined,
|
|
925
|
+
};
|
|
926
|
+
const dealWithUserRelation = (userRelation) => {
|
|
927
|
+
const { action, data } = userRelation;
|
|
928
|
+
if (action === 'create') {
|
|
929
|
+
const attrs = Object.keys(data);
|
|
930
|
+
assert(difference(attrs, Object.keys(this.schema.userRelation.attributes).concat('id')).length === 0);
|
|
931
|
+
if (data.userId === userId) {
|
|
932
|
+
me.userRelations?.push(data);
|
|
933
|
+
}
|
|
934
|
+
assert('id' in filter2 && filter2.id);
|
|
935
|
+
}
|
|
936
|
+
};
|
|
937
|
+
if (otmOperations instanceof Array) {
|
|
938
|
+
otmOperations.forEach((otmOperation) => dealWithUserRelation(otmOperation));
|
|
939
|
+
}
|
|
940
|
+
else {
|
|
941
|
+
dealWithUserRelation(otmOperations);
|
|
942
|
+
}
|
|
943
|
+
}
|
|
944
|
+
if (otmOperations instanceof Array) {
|
|
945
|
+
otmOperations.forEach((otmOperation) => {
|
|
946
|
+
const son = destructInner(e, otmOperation, undefined, undefined, true, extraFilter);
|
|
947
|
+
addChild(me, attr, son);
|
|
948
|
+
});
|
|
949
|
+
}
|
|
950
|
+
else {
|
|
951
|
+
const son = destructInner(e, otmOperations, undefined, undefined, true, extraFilter);
|
|
952
|
+
addChild(me, attr, son);
|
|
953
|
+
}
|
|
954
|
+
}
|
|
955
|
+
}
|
|
956
|
+
}
|
|
957
|
+
return root;
|
|
958
|
+
};
|
|
959
|
+
return destructInner(entity2, operation2);
|
|
960
|
+
}
|
|
961
|
+
/**
|
|
962
|
+
* 授权 scope filter 展开:把 path(destEntity 走向 user 的属性链)与末端谓词 filter
|
|
963
|
+
* 合成为 destEntity 上的 filter。
|
|
964
|
+
*/
|
|
965
|
+
makePathFilter(entity, path, schema, filter) {
|
|
966
|
+
const { value, recursive } = path;
|
|
967
|
+
if (value === '') {
|
|
968
|
+
assert(!recursive);
|
|
969
|
+
return filter;
|
|
970
|
+
}
|
|
971
|
+
const paths = value.split('.');
|
|
972
|
+
const makeRecursiveFilter = (recursiveDepth) => {
|
|
973
|
+
if (recursiveDepth > 0) {
|
|
974
|
+
return {
|
|
975
|
+
$or: [
|
|
976
|
+
filter,
|
|
977
|
+
{
|
|
978
|
+
parent: makeRecursiveFilter(recursiveDepth - 1)
|
|
979
|
+
}
|
|
980
|
+
]
|
|
981
|
+
};
|
|
982
|
+
}
|
|
983
|
+
return filter;
|
|
984
|
+
};
|
|
985
|
+
const makeInner = (idx, e2) => {
|
|
986
|
+
const attr = paths[idx];
|
|
987
|
+
if (idx === paths.length) {
|
|
988
|
+
if (!recursive) {
|
|
989
|
+
return filter;
|
|
990
|
+
}
|
|
991
|
+
else {
|
|
992
|
+
// 在最后一个对象上存在递归,用or连接处理
|
|
993
|
+
const { recursiveDepth } = schema[e2];
|
|
994
|
+
assert(recursiveDepth > 0);
|
|
995
|
+
return makeRecursiveFilter(recursiveDepth);
|
|
996
|
+
}
|
|
997
|
+
}
|
|
998
|
+
else {
|
|
999
|
+
const rel = judgeRelation(schema, e2, attr);
|
|
1000
|
+
let e3;
|
|
1001
|
+
if (rel === 2) {
|
|
1002
|
+
e3 = attr;
|
|
1003
|
+
}
|
|
1004
|
+
else if (typeof rel === 'string') {
|
|
1005
|
+
e3 = rel;
|
|
1006
|
+
}
|
|
1007
|
+
else {
|
|
1008
|
+
assert(rel instanceof Array);
|
|
1009
|
+
e3 = rel[0];
|
|
1010
|
+
}
|
|
1011
|
+
const f = makeInner(idx + 1, e3);
|
|
1012
|
+
// 左连接缺少目标行时,目标字段谓词可能产生 SQL NULL;补充 id 存在约束后,
|
|
1013
|
+
// 关系分支退化为二值谓词:P(path) = targetExists ∧ P(related rows)。
|
|
1014
|
+
// 这样在补集计算中可安全使用 ¬(P₁ ∨ … ∨ Pₙ) = ¬P₁ ∧ … ∧ ¬Pₙ,
|
|
1015
|
+
// 不会把 NULL 错当成 UNKNOWN 而丢失未授权行。
|
|
1016
|
+
return {
|
|
1017
|
+
// 不能用 combineFilters 合并这两个条件:它会把
|
|
1018
|
+
// `id IS NOT NULL ∧ id = v` 化简成 `id = v`,在 LEFT JOIN
|
|
1019
|
+
// 下又会让缺失目标行产生 UNKNOWN。显式保留 AND。
|
|
1020
|
+
[attr]: {
|
|
1021
|
+
$and: [
|
|
1022
|
+
{ id: { $exists: true } },
|
|
1023
|
+
f,
|
|
1024
|
+
],
|
|
1025
|
+
},
|
|
1026
|
+
};
|
|
1027
|
+
}
|
|
1028
|
+
};
|
|
1029
|
+
return makeInner(0, entity);
|
|
1030
|
+
}
|
|
1031
|
+
/**
|
|
1032
|
+
* 对所有满足操作要求的actionAuth加以判断,找到可以满足当前用户身份的actionAuth
|
|
1033
|
+
*/
|
|
1034
|
+
filterActionAuths(entity, filter, actionAuths, context) {
|
|
1035
|
+
const result = actionAuths.map((auth) => {
|
|
1036
|
+
const { path, relation, relationId } = auth;
|
|
1037
|
+
const acceptWithTerminal = (terminalFilter) => {
|
|
1038
|
+
const pathFilter = this.makePathFilter(entity, path, this.schema, terminalFilter);
|
|
1039
|
+
// @oak-ignore 判定内核续延:同步/异步由 bind 在 IO 叶子收敛
|
|
1040
|
+
return bind(checkFilterContains(entity, context, pathFilter, filter, true), (contained) => contained ? auth : undefined);
|
|
1041
|
+
};
|
|
1042
|
+
// 在cache中,可能出现relation外键指向的对象为null的情况,要容错
|
|
1043
|
+
if (relationId !== undefined && relationId !== null) {
|
|
1044
|
+
if (!relation) {
|
|
1045
|
+
console.warn('RelationAuth: actionAuth relation object is missing; rejecting the cached authorization branch');
|
|
1046
|
+
return undefined;
|
|
1047
|
+
}
|
|
1048
|
+
const { userRelation$relation: userRelations } = relation;
|
|
1049
|
+
if (!Array.isArray(userRelations)) {
|
|
1050
|
+
console.warn('RelationAuth: actionAuth relation membership is missing; rejecting the cached authorization branch');
|
|
1051
|
+
return undefined;
|
|
1052
|
+
}
|
|
1053
|
+
const entityIds = uniq(userRelations.map((userRelation) => userRelation.entityId).filter((entityId) => entityId !== undefined && entityId !== null));
|
|
1054
|
+
if (entityIds.length === 0) {
|
|
1055
|
+
return undefined;
|
|
1056
|
+
}
|
|
1057
|
+
return acceptWithTerminal({ id: { $in: entityIds } });
|
|
1058
|
+
}
|
|
1059
|
+
// 说明是通过userId关联
|
|
1060
|
+
return acceptWithTerminal({ id: context.getCurrentUserId() });
|
|
1061
|
+
});
|
|
1062
|
+
// @oak-ignore 判定内核续延:同步/异步由 bind 在 IO 叶子收敛
|
|
1063
|
+
return bind(allBind(result, (values) => values), (values) => values.filter((auth) => !!auth));
|
|
1064
|
+
}
|
|
1065
|
+
/**
|
|
1066
|
+
* 对于有些特殊的查询(带很多$or的查询,多发生在系统级别),单个actionAuth无法满足,需要共同加以判定
|
|
1067
|
+
*/
|
|
1068
|
+
checkActionAuthInGroup(entity, filter, actionAuths, context) {
|
|
1069
|
+
return this.scopeContainsFilter(entity, filter, this.collectScopeAuths(entity, actionAuths), context);
|
|
1070
|
+
}
|
|
1071
|
+
/**
|
|
1072
|
+
* 此函数判定一个结点是否能通过权限检测,同时寻找该结点本身对象上成立的actionAuth,用于本结点子孙结点的快速检测
|
|
1073
|
+
* 如果结点因其deduce的对象通过了检测,其被推断对象的actionAuth无法用于更低对象的权限检测
|
|
1074
|
+
*/
|
|
1075
|
+
findActionAuthsOnNode(node, context) {
|
|
1076
|
+
const { entity, filter, action, userRelations } = node;
|
|
1077
|
+
assert(filter);
|
|
1078
|
+
/**
|
|
1079
|
+
* 搜索判定是否允许自建对象,自建的条件是 path = '',destEntity === entity
|
|
1080
|
+
*/
|
|
1081
|
+
const findOwnCreateUserRelation = (actionAuths) => {
|
|
1082
|
+
if (userRelations && userRelations.length > 0) {
|
|
1083
|
+
const ars = actionAuths.filter((ar) => !!userRelations.find((ur) => ur.relationId === ar.relationId) && ar.path.value === '' && ar.path.destEntity === entity);
|
|
1084
|
+
if (ars.length > 0) {
|
|
1085
|
+
return ars;
|
|
1086
|
+
}
|
|
1087
|
+
}
|
|
1088
|
+
};
|
|
1089
|
+
return bind(this.getDeducedEntityFilters(entity, filter, [action], context), (deducedEntityFilters) => {
|
|
1090
|
+
const actionAuthOnEntities = [];
|
|
1091
|
+
const specialEntities = deducedEntityFilters.filter(ele => RelationAuth.SPECIAL_ENTITIES.includes(ele.entity));
|
|
1092
|
+
const unspecicalEntities = deducedEntityFilters.filter(ele => !RelationAuth.SPECIAL_ENTITIES.includes(ele.entity));
|
|
1093
|
+
const result = [];
|
|
1094
|
+
if (specialEntities.length > 0) {
|
|
1095
|
+
// 对于deduce出来的special对象,直接判定create应该问题不大,否则写起来太烦琐(具体情况遇到了再调试)
|
|
1096
|
+
result.push(...specialEntities.map(
|
|
1097
|
+
// @oak-ignore
|
|
1098
|
+
ele => bind(this.checkOperateSpecialEntities(ele.entity, ele.entity === entity ? node.action : 'create', ele.filter, context), (v) => v)));
|
|
1099
|
+
}
|
|
1100
|
+
if (unspecicalEntities.length > 0) {
|
|
1101
|
+
const allEntities = unspecicalEntities.map(ele => ele.entity);
|
|
1102
|
+
const allActions = uniq(unspecicalEntities.map(ele => ele.actions).flat());
|
|
1103
|
+
// @oak-ignore sync/async 双形态 IO 叶子
|
|
1104
|
+
const actionAuths2 = context.select('actionAuth', {
|
|
1105
|
+
data: {
|
|
1106
|
+
id: 1,
|
|
1107
|
+
path: {
|
|
1108
|
+
id: 1,
|
|
1109
|
+
destEntity: 1,
|
|
1110
|
+
sourceEntity: 1,
|
|
1111
|
+
value: 1,
|
|
1112
|
+
recursive: 1,
|
|
1113
|
+
},
|
|
1114
|
+
pathId: 1,
|
|
1115
|
+
deActions: 1,
|
|
1116
|
+
relationId: 1,
|
|
1117
|
+
// cache 容错(filterActionAuths)依赖 relation 成员身份投影,不可省略
|
|
1118
|
+
relation: {
|
|
1119
|
+
id: 1,
|
|
1120
|
+
entity: 1,
|
|
1121
|
+
entityId: 1,
|
|
1122
|
+
userRelation$relation: {
|
|
1123
|
+
$entity: 'userRelation',
|
|
1124
|
+
data: {
|
|
1125
|
+
id: 1,
|
|
1126
|
+
entity: 1,
|
|
1127
|
+
entityId: 1,
|
|
1128
|
+
userId: 1,
|
|
1129
|
+
relationId: 1,
|
|
1130
|
+
},
|
|
1131
|
+
filter: {
|
|
1132
|
+
userId: context.getCurrentUserId(),
|
|
1133
|
+
},
|
|
1134
|
+
},
|
|
1135
|
+
},
|
|
1136
|
+
},
|
|
1137
|
+
filter: {
|
|
1138
|
+
path: {
|
|
1139
|
+
destEntity: {
|
|
1140
|
+
$in: allEntities,
|
|
1141
|
+
}
|
|
1142
|
+
},
|
|
1143
|
+
deActions: {
|
|
1144
|
+
$overlaps: allActions,
|
|
1145
|
+
},
|
|
1146
|
+
}
|
|
1147
|
+
}, { dontCollect: true, ignoreAttrMiss: true });
|
|
1148
|
+
const checkActionAuths = (actionAuths) => {
|
|
1149
|
+
const created = findOwnCreateUserRelation(actionAuths);
|
|
1150
|
+
if (created) {
|
|
1151
|
+
actionAuthOnEntities.push(...created);
|
|
1152
|
+
return true;
|
|
1153
|
+
}
|
|
1154
|
+
// OR 语义:任一候选(自身或 deduce 目标)包含性成立即可;
|
|
1155
|
+
// 只有 destEntity === 本节点实体的通过授权才可喂给子孙快路。
|
|
1156
|
+
let candidateIndex = 0;
|
|
1157
|
+
const step = () => {
|
|
1158
|
+
while (candidateIndex < deducedEntityFilters.length) {
|
|
1159
|
+
const ele = deducedEntityFilters[candidateIndex++];
|
|
1160
|
+
const ars2 = actionAuths.filter(ele2 => ele2.path.destEntity === ele.entity && intersection(ele2.deActions, ele.actions).length > 0 // 这里只要overlap就可以了
|
|
1161
|
+
);
|
|
1162
|
+
const proceed = (actionAuths2) => {
|
|
1163
|
+
if (actionAuths2.length > 0) {
|
|
1164
|
+
if (ele.entity === entity) {
|
|
1165
|
+
actionAuthOnEntities.push(...actionAuths2);
|
|
1166
|
+
}
|
|
1167
|
+
return true;
|
|
1168
|
+
}
|
|
1169
|
+
return false;
|
|
1170
|
+
};
|
|
1171
|
+
const filtered = this.filterActionAuths(ele.entity, ele.filter, ars2, context);
|
|
1172
|
+
if (filtered instanceof Promise) {
|
|
1173
|
+
// @oak-ignore trampolin 续延:Promise 形态由外层统一接续
|
|
1174
|
+
return filtered.then((passed) => proceed(passed) || step());
|
|
1175
|
+
}
|
|
1176
|
+
if (proceed(filtered)) {
|
|
1177
|
+
return true;
|
|
1178
|
+
}
|
|
1179
|
+
}
|
|
1180
|
+
return false;
|
|
1181
|
+
};
|
|
1182
|
+
// @oak-ignore trampolin 起点:同步链同步完成
|
|
1183
|
+
return step();
|
|
1184
|
+
};
|
|
1185
|
+
result.push(
|
|
1186
|
+
// @oak-ignore 判定内核续延:同步/异步由 bind 在 IO 叶子收敛
|
|
1187
|
+
bind(actionAuths2, (ars2) => checkActionAuths(ars2)));
|
|
1188
|
+
}
|
|
1189
|
+
return bind(allBind(result, (values) => values), (r2) => {
|
|
1190
|
+
// r2中只有一个通过就能通过
|
|
1191
|
+
if (r2.includes(true)) {
|
|
1192
|
+
return actionAuthOnEntities;
|
|
1193
|
+
}
|
|
1194
|
+
return false;
|
|
1195
|
+
});
|
|
1196
|
+
});
|
|
1197
|
+
}
|
|
1198
|
+
/**
|
|
1199
|
+
* 级联树边解析(I8 前置)。destructOperation 的键形:
|
|
1200
|
+
* - OTM 反指:键 = 父数据上的反指属性名 `子实体名$边名`('comment$post'),
|
|
1201
|
+
* 前缀传播,边名 = 尾段;
|
|
1202
|
+
* - MTO 正向/多态折算:键 = `父实体名$attr`('comment$user'、批式 'post$entity')或
|
|
1203
|
+
* 裸 attr(历史手工树),剥首段,边名 = 子指向父的外键基名。
|
|
1204
|
+
* 键形约定存在碰撞(如 'post$entity'),以 schema 双向外键探测定方向:
|
|
1205
|
+
* 父侧存在名为尾段的 ref→子 外键 ⇒ MTO;否则子侧存在 ⇒ OTM;再否则多态折算 ⇒ MTO
|
|
1206
|
+
* 以 'entity' 折算边;都不可解析 ⇒ 保守不传播。
|
|
1207
|
+
*/
|
|
1208
|
+
resolveTreeEdge(nodeEntity, childEntity, childPath) {
|
|
1209
|
+
const attributesOf = (e) => this.schema[e].attributes ?? {};
|
|
1210
|
+
/** e 上是否存在名为 attr 的正向外键(attr/attrId ref 形态或多态 entity 折算)指向 target */
|
|
1211
|
+
const refAttr = (e, attr, target) => {
|
|
1212
|
+
const attributes = attributesOf(e);
|
|
1213
|
+
const direct = attributes[attr];
|
|
1214
|
+
if (direct && !Array.isArray(direct) && direct.type === 'ref' && direct.ref === target) {
|
|
1215
|
+
return true;
|
|
1216
|
+
}
|
|
1217
|
+
const fk = attributes[`${attr}Id`];
|
|
1218
|
+
if (fk && !Array.isArray(fk) && fk.type === 'ref' && fk.ref === target) {
|
|
1219
|
+
return true;
|
|
1220
|
+
}
|
|
1221
|
+
const entityAttr = attributes.entity;
|
|
1222
|
+
return attr === 'entity' && !!entityAttr && !Array.isArray(entityAttr)
|
|
1223
|
+
&& Array.isArray(entityAttr.ref) && entityAttr.ref.includes(target);
|
|
1224
|
+
};
|
|
1225
|
+
/** e 上所有指向 target 的外键基名(剥段/前缀的候选边名) */
|
|
1226
|
+
const edgeNamesTo = (e, target) => {
|
|
1227
|
+
const attributes = attributesOf(e);
|
|
1228
|
+
const bases = uniq(Object.keys(attributes)
|
|
1229
|
+
.filter((name) => name !== 'entityId' && name.endsWith('Id')
|
|
1230
|
+
&& attributes[name]?.type === 'ref' && attributes[name]?.ref === target)
|
|
1231
|
+
.map((name) => name.slice(0, -2)));
|
|
1232
|
+
const entityAttr = attributes.entity;
|
|
1233
|
+
if (entityAttr && !Array.isArray(entityAttr)
|
|
1234
|
+
&& Array.isArray(entityAttr.ref) && entityAttr.ref.includes(target)) {
|
|
1235
|
+
bases.push('entity');
|
|
1236
|
+
}
|
|
1237
|
+
return bases;
|
|
1238
|
+
};
|
|
1239
|
+
const head = childPath.includes('$') ? childPath.slice(0, childPath.indexOf('$')) : childPath;
|
|
1240
|
+
const tail = childPath.includes('$') ? childPath.slice(childPath.indexOf('$') + 1) : childPath;
|
|
1241
|
+
const childEdges = edgeNamesTo(childEntity, nodeEntity);
|
|
1242
|
+
if (!childPath.includes('$')) {
|
|
1243
|
+
// 裸 attr 键:子侧外键命中 ⇒ OTM 反指;否则父侧外键(attr/attrId 指子)⇒ MTO 剥段
|
|
1244
|
+
if (childEdges.includes(tail)) {
|
|
1245
|
+
return { mto: false, edgeName: tail };
|
|
1246
|
+
}
|
|
1247
|
+
return refAttr(nodeEntity, tail, childEntity)
|
|
1248
|
+
? { mto: true, edgeName: tail }
|
|
1249
|
+
: { mto: false, edgeName: '' };
|
|
1250
|
+
}
|
|
1251
|
+
// 父侧外键名为尾段 ⇒ 键是 `父实体名$attr` 的 MTO 向上级联
|
|
1252
|
+
if (head !== String(childEntity) && refAttr(nodeEntity, tail, childEntity)) {
|
|
1253
|
+
return { mto: true, edgeName: tail };
|
|
1254
|
+
}
|
|
1255
|
+
// 子侧外键 ⇒ OTM 反指(头段=子实体名)
|
|
1256
|
+
if (childEdges.includes(tail)) {
|
|
1257
|
+
return { mto: false, edgeName: tail };
|
|
1258
|
+
}
|
|
1259
|
+
if (head === String(nodeEntity) && tail === 'entity') {
|
|
1260
|
+
// 批式多态折算键 `父实体名$entity`:子经 entity/entityId 指父 ⇒ 剥首段
|
|
1261
|
+
return { mto: true, edgeName: 'entity' };
|
|
1262
|
+
}
|
|
1263
|
+
if (head === String(childEntity)) {
|
|
1264
|
+
// 键头段=子实体名 ⇒ OTM 反指键
|
|
1265
|
+
return { mto: false, edgeName: tail };
|
|
1266
|
+
}
|
|
1267
|
+
if (childEdges.length === 1) {
|
|
1268
|
+
return { mto: true, edgeName: childEdges[0] };
|
|
1269
|
+
}
|
|
1270
|
+
return { mto: false, edgeName: '' };
|
|
1271
|
+
}
|
|
1272
|
+
checkOperationTree(tree, context) {
|
|
1273
|
+
const checkNode = (node, actionAuths) => {
|
|
1274
|
+
const checkChildren = (legalPaths) => {
|
|
1275
|
+
const { children } = node;
|
|
1276
|
+
const childPaths = Object.keys(children);
|
|
1277
|
+
if (childPaths.length === 0) {
|
|
1278
|
+
return true;
|
|
1279
|
+
}
|
|
1280
|
+
let pathIndex = 0;
|
|
1281
|
+
const stepChild = () => {
|
|
1282
|
+
while (pathIndex < childPaths.length) {
|
|
1283
|
+
const childPath = childPaths[pathIndex++];
|
|
1284
|
+
const child = children[childPath];
|
|
1285
|
+
const childEntity = child instanceof Array ? child[0].entity : child.entity;
|
|
1286
|
+
// I5:deduce 零检查——deduced 子实体以"多态反指"挂到本节点时
|
|
1287
|
+
// (子有 entity/entityId 且 entity 值域含父实体,如 userRelation 挂 'post'),
|
|
1288
|
+
// 其权限已折算为本节点权限,不再判定。
|
|
1289
|
+
if (this.edgeRuleOf(childEntity, 'entity') === 'deduce'
|
|
1290
|
+
&& this.edgeRuleOf(childEntity, childPath) === 'polymorphic') {
|
|
1291
|
+
continue;
|
|
1292
|
+
}
|
|
1293
|
+
// I8:边传播单源(resolveTreeEdge 判向 + deriveChildPath 派生):
|
|
1294
|
+
// OTM 前缀子指向父的边属性名、MTO 剥首段、不可解析边不传播(回落自查)。
|
|
1295
|
+
const { mto, edgeName } = this.resolveTreeEdge(node.entity, childEntity, childPath);
|
|
1296
|
+
const deriveFrom = (ele) => {
|
|
1297
|
+
const { path: { value: pv } } = ele;
|
|
1298
|
+
if (!edgeName) {
|
|
1299
|
+
return undefined;
|
|
1300
|
+
}
|
|
1301
|
+
return deriveChildPath(mto ? 'mto' : 'otm', edgeName, pv ?? '');
|
|
1302
|
+
};
|
|
1303
|
+
const childLegalAuthsFor = (parentAuths) => {
|
|
1304
|
+
const queries = parentAuths.map((ele) => {
|
|
1305
|
+
const value = deriveFrom(ele);
|
|
1306
|
+
if (value === undefined) {
|
|
1307
|
+
return undefined;
|
|
1308
|
+
}
|
|
1309
|
+
const { relationId } = ele;
|
|
1310
|
+
// @oak-ignore
|
|
1311
|
+
return context.select('actionAuth', {
|
|
1312
|
+
data: {
|
|
1313
|
+
id: 1,
|
|
1314
|
+
},
|
|
1315
|
+
filter: {
|
|
1316
|
+
path: {
|
|
1317
|
+
value,
|
|
1318
|
+
destEntity: childEntity,
|
|
1319
|
+
},
|
|
1320
|
+
deActions: {
|
|
1321
|
+
$overlaps: child instanceof Array ? child.map(el => el.action) : child.action,
|
|
1322
|
+
},
|
|
1323
|
+
relationId: relationId || {
|
|
1324
|
+
$exists: false,
|
|
1325
|
+
},
|
|
1326
|
+
}
|
|
1327
|
+
}, { dontCollect: true });
|
|
1328
|
+
}).filter((q) => q !== undefined);
|
|
1329
|
+
if (queries.length === 0) {
|
|
1330
|
+
return [];
|
|
1331
|
+
}
|
|
1332
|
+
return bind(allBind(queries, (groups) => groups), (groups) => groups.flat());
|
|
1333
|
+
};
|
|
1334
|
+
const proceed = (legalAuths) => {
|
|
1335
|
+
const results = child instanceof Array
|
|
1336
|
+
// @oak-ignore 判定内核续延:级联子树判定的 Promise 由 allBind 统一接续
|
|
1337
|
+
? child.map((c) => checkNode(c, legalAuths))
|
|
1338
|
+
: [checkNode(child, legalAuths)];
|
|
1339
|
+
return bind(allBind(results, (vs) => vs), (r) => !r.includes(false));
|
|
1340
|
+
};
|
|
1341
|
+
// I7:保持写侧既有判定序——父层有见证时只走快路(数据见证,无合成回落)
|
|
1342
|
+
const result = bind(childLegalAuthsFor(legalPaths), (legalAuths) => proceed(legalAuths));
|
|
1343
|
+
if (result instanceof Promise) {
|
|
1344
|
+
// @oak-ignore trampolin 续延:Promise 形态由外层统一接续
|
|
1345
|
+
return result.then((ok) => ok ? stepChild() : false);
|
|
1346
|
+
}
|
|
1347
|
+
if (!result) {
|
|
1348
|
+
return false;
|
|
1349
|
+
}
|
|
1350
|
+
}
|
|
1351
|
+
return true;
|
|
1352
|
+
};
|
|
1353
|
+
// @oak-ignore trampolin 起点:子树判定同步链同步完成
|
|
1354
|
+
return stepChild();
|
|
1355
|
+
};
|
|
1356
|
+
// 先根据parent传下来的合法auths来搜寻,只需要查找actionAuth,降低开销
|
|
1357
|
+
if (actionAuths && actionAuths.length > 0) {
|
|
1358
|
+
return checkChildren(actionAuths);
|
|
1359
|
+
}
|
|
1360
|
+
// 节点级豁免(I6:只豁免本节点,照常下探子节点)
|
|
1361
|
+
const { action, entity } = node;
|
|
1362
|
+
if (this.updateFreeDict[entity] && this.updateFreeDict[entity].includes(action)) {
|
|
1363
|
+
return checkChildren([]);
|
|
1364
|
+
}
|
|
1365
|
+
// 没有能根据父亲传下来的actionAuth判定,只能自己找
|
|
1366
|
+
return bind(this.findActionAuthsOnNode(node, context), (result2) => {
|
|
1367
|
+
if (result2 === false) {
|
|
1368
|
+
return false;
|
|
1369
|
+
}
|
|
1370
|
+
// 如果是对user对象操作通过,需要增添一条虚假的的actionAuth
|
|
1371
|
+
if (node.entity === 'user') {
|
|
1372
|
+
result2.push({
|
|
1373
|
+
id: 'temp',
|
|
1374
|
+
pathId: 'path_temp',
|
|
1375
|
+
path: {
|
|
1376
|
+
id: 'path_temp',
|
|
1377
|
+
destEntity: 'user',
|
|
1378
|
+
sourceEntity: 'any',
|
|
1379
|
+
value: '',
|
|
1380
|
+
$$createAt$$: 1,
|
|
1381
|
+
$$updateAt$$: 1,
|
|
1382
|
+
$$seq$$: 123,
|
|
1383
|
+
recursive: false,
|
|
1384
|
+
},
|
|
1385
|
+
$$createAt$$: 1,
|
|
1386
|
+
$$updateAt$$: 1,
|
|
1387
|
+
$$seq$$: 123,
|
|
1388
|
+
deActions: [node.action],
|
|
1389
|
+
});
|
|
1390
|
+
}
|
|
1391
|
+
return checkChildren(result2);
|
|
1392
|
+
});
|
|
1393
|
+
};
|
|
1394
|
+
return checkNode(tree);
|
|
1395
|
+
}
|
|
1396
|
+
checkOperation(entity, operation, context) {
|
|
1397
|
+
const { action, filter, data } = operation;
|
|
1398
|
+
const userId = context.getCurrentUserId();
|
|
1399
|
+
if (!userId) {
|
|
1400
|
+
throw new OakUnloggedInException();
|
|
1401
|
+
}
|
|
1402
|
+
if (!filter && (!data || action !== 'create')) {
|
|
1403
|
+
if (process.env.NODE_ENV === 'development') {
|
|
1404
|
+
console.warn('operation不能没有限制条件', operation);
|
|
1405
|
+
}
|
|
1406
|
+
return false;
|
|
1407
|
+
}
|
|
1408
|
+
const updateTree = this.destructOperation(entity, operation, userId);
|
|
1409
|
+
return this.checkOperationTree(updateTree, context);
|
|
1410
|
+
}
|
|
1411
|
+
/**
|
|
1412
|
+
* 检查一个operation是否能被通过权限测试。
|
|
1413
|
+
* 判定汇点唯一(I4):读→任务链(E1 短路,失败 OakDataInvisible),
|
|
1414
|
+
* 写→级联树自顶向下(失败 OakOperationUnpermitted);
|
|
1415
|
+
* 异常种类与时机由本函数单点决定,读写内核不再各自抛异常。
|
|
1416
|
+
*/
|
|
1417
|
+
checkActions(entity, operation, context) {
|
|
1418
|
+
const { action } = operation;
|
|
1419
|
+
const isRead = !action || readOnlyActions.includes(action);
|
|
1420
|
+
const failure = (ok) => {
|
|
1421
|
+
if (ok) {
|
|
1422
|
+
return;
|
|
1423
|
+
}
|
|
1424
|
+
if (isRead) {
|
|
1425
|
+
throw new OakDataInvisibleException(entity, operation, context.getCurrentUserId());
|
|
1426
|
+
}
|
|
1427
|
+
throw new OakOperationUnpermittedException(entity, operation, context.getCurrentUserId());
|
|
1428
|
+
};
|
|
1429
|
+
// @oak-ignore 判定汇点:Promise 结果由本函数统一 then 接续(失败在 failure 单点抛异常)
|
|
1430
|
+
const result = isRead
|
|
1431
|
+
? this.checkSelection(entity, operation, context)
|
|
1432
|
+
: this.checkOperation(entity, operation, context);
|
|
1433
|
+
if (result instanceof Promise) {
|
|
1434
|
+
return result.then(failure);
|
|
1435
|
+
}
|
|
1436
|
+
failure(result);
|
|
1437
|
+
}
|
|
1438
|
+
}
|
|
1439
|
+
;
|
|
1440
|
+
export { getUserRelationsByActions } from './userLookup';
|