@objectstack/plugin-security 2.0.4
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/.turbo/turbo-build.log +22 -0
- package/LICENSE +202 -0
- package/dist/index.d.mts +120 -0
- package/dist/index.d.ts +120 -0
- package/dist/index.js +333 -0
- package/dist/index.js.map +1 -0
- package/dist/index.mjs +303 -0
- package/dist/index.mjs.map +1 -0
- package/package.json +28 -0
- package/src/field-masker.ts +75 -0
- package/src/index.ts +13 -0
- package/src/permission-evaluator.ts +112 -0
- package/src/rls-compiler.ts +143 -0
- package/src/security-plugin.ts +153 -0
- package/tsconfig.json +9 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/permission-evaluator.ts","../src/rls-compiler.ts","../src/field-masker.ts","../src/security-plugin.ts"],"sourcesContent":["// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport type { PermissionSet, ObjectPermission, FieldPermission } from '@objectstack/spec/security';\n\n/**\n * Operation type mapping to permission checks\n */\nconst OPERATION_TO_PERMISSION: Record<string, keyof ObjectPermission> = {\n find: 'allowRead',\n findOne: 'allowRead',\n count: 'allowRead',\n aggregate: 'allowRead',\n insert: 'allowCreate',\n update: 'allowEdit',\n delete: 'allowDelete',\n};\n\n/**\n * PermissionEvaluator\n * \n * Runtime evaluator for PermissionSet definitions.\n * Resolves aggregated permissions from roles to concrete allow/deny decisions.\n */\nexport class PermissionEvaluator {\n /**\n * Check if an operation is allowed on an object for the given permission sets.\n * Uses \"most permissive\" merging: if ANY permission set allows, it's allowed.\n */\n checkObjectPermission(\n operation: string,\n objectName: string,\n permissionSets: PermissionSet[]\n ): boolean {\n const permKey = OPERATION_TO_PERMISSION[operation];\n if (!permKey) return true; // Unknown operations are allowed by default\n\n for (const ps of permissionSets) {\n const objPerm = ps.objects?.[objectName];\n if (objPerm) {\n // Check if modifyAllRecords is set (super-user bypass for write ops)\n if (['allowEdit', 'allowDelete'].includes(permKey) && objPerm.modifyAllRecords) {\n return true;\n }\n // Check if viewAllRecords is set (super-user bypass for read ops)\n if (permKey === 'allowRead' && (objPerm.viewAllRecords || objPerm.modifyAllRecords)) {\n return true;\n }\n // Check the specific permission\n if (objPerm[permKey]) {\n return true;\n }\n }\n }\n\n return false;\n }\n\n /**\n * Get the merged field permissions for an object.\n * Returns a map of field names to their effective permissions.\n * Uses \"most permissive\" merging.\n */\n getFieldPermissions(\n objectName: string,\n permissionSets: PermissionSet[]\n ): Record<string, FieldPermission> {\n const result: Record<string, FieldPermission> = {};\n\n for (const ps of permissionSets) {\n if (!ps.fields) continue;\n\n for (const [key, perm] of Object.entries(ps.fields)) {\n // Field keys are in format: \"object_name.field_name\"\n if (!key.startsWith(`${objectName}.`)) continue;\n const fieldName = key.substring(objectName.length + 1);\n\n if (!result[fieldName]) {\n result[fieldName] = { readable: false, editable: false };\n }\n\n // Most permissive merge\n if (perm.readable) result[fieldName].readable = true;\n if (perm.editable) result[fieldName].editable = true;\n }\n }\n\n return result;\n }\n\n /**\n * Resolve permission sets for a list of role names from metadata.\n */\n resolvePermissionSets(\n roles: string[],\n metadataService: any\n ): PermissionSet[] {\n const result: PermissionSet[] = [];\n\n // Get all permission sets from metadata\n const allPermSets = metadataService.list?.('permissions') || [];\n\n for (const ps of allPermSets) {\n // A permission set is relevant if it's a profile assigned to any of the user's roles,\n // or if the role name matches the permission set name\n if (roles.includes(ps.name)) {\n result.push(ps);\n }\n }\n\n return result;\n }\n}\n","// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport type { RowLevelSecurityPolicy } from '@objectstack/spec/security';\nimport type { ExecutionContext } from '@objectstack/spec/kernel';\n\n/**\n * RLS User Context\n * Variables available for RLS expression evaluation.\n */\ninterface RLSUserContext {\n id?: string;\n tenant_id?: string;\n roles?: string[];\n [key: string]: unknown;\n}\n\n/**\n * RLSCompiler\n * \n * Compiles Row-Level Security policy expressions into query filters.\n * Converts `using` / `check` expressions into ObjectQL-compatible filter conditions.\n */\nexport class RLSCompiler {\n /**\n * Compile RLS policies into a query filter for the given user context.\n * Multiple policies for the same object/operation are OR-combined (any match allows access).\n */\n compileFilter(\n policies: RowLevelSecurityPolicy[],\n executionContext?: ExecutionContext\n ): Record<string, unknown> | null {\n if (policies.length === 0) return null;\n\n const userCtx: RLSUserContext = {\n id: executionContext?.userId,\n tenant_id: executionContext?.tenantId,\n roles: executionContext?.roles,\n };\n\n const filters: Record<string, unknown>[] = [];\n\n for (const policy of policies) {\n if (!policy.using) continue;\n const filter = this.compileExpression(policy.using, userCtx);\n if (filter) {\n filters.push(filter);\n }\n }\n\n if (filters.length === 0) return null;\n if (filters.length === 1) return filters[0];\n\n // Multiple policies: OR-combine (any policy allows access)\n return { $or: filters };\n }\n\n /**\n * Compile a single RLS expression into a query filter.\n * \n * Supports simple expressions like:\n * - \"field_name = current_user.property\"\n * - \"field_name IN (current_user.array_property)\"\n * - \"field_name = 'literal_value'\"\n */\n compileExpression(\n expression: string,\n userCtx: RLSUserContext\n ): Record<string, unknown> | null {\n if (!expression) return null;\n\n // Handle simple equality: \"field = current_user.property\"\n const eqMatch = expression.match(/^\\s*(\\w+)\\s*=\\s*current_user\\.(\\w+)\\s*$/);\n if (eqMatch) {\n const [, field, prop] = eqMatch;\n const value = userCtx[prop];\n if (value === undefined) return null;\n return { [field]: value };\n }\n\n // Handle literal equality: \"field = 'value'\"\n const litMatch = expression.match(/^\\s*(\\w+)\\s*=\\s*'([^']*)'\\s*$/);\n if (litMatch) {\n const [, field, value] = litMatch;\n return { [field]: value };\n }\n\n // Handle IN: \"field IN (current_user.array_property)\"\n const inMatch = expression.match(/^\\s*(\\w+)\\s+IN\\s+\\(\\s*current_user\\.(\\w+)\\s*\\)\\s*$/i);\n if (inMatch) {\n const [, field, prop] = inMatch;\n const value = userCtx[prop];\n if (!Array.isArray(value)) return null;\n return { [field]: { $in: value } };\n }\n\n // Unsupported expression: return null (no additional RLS filter applied).\n // Note: callers should treat absence of RLS policies as \"allow all\" only when\n // no policies are defined. If policies exist but cannot be compiled, the caller\n // may want to deny access as a safety measure.\n return null;\n }\n\n /**\n * Get applicable RLS policies for a given object and operation.\n */\n getApplicablePolicies(\n objectName: string,\n operation: string,\n allPolicies: RowLevelSecurityPolicy[]\n ): RowLevelSecurityPolicy[] {\n // Map engine operation to RLS operation type\n const rlsOp = this.mapOperationToRLS(operation);\n\n return allPolicies.filter(policy => {\n // Check object match\n if (policy.object !== objectName && policy.object !== '*') return false;\n\n // Check operation match\n if (policy.operation === 'all') return true;\n if (policy.operation === rlsOp) return true;\n\n return false;\n });\n }\n\n private mapOperationToRLS(operation: string): string {\n switch (operation) {\n case 'find':\n case 'findOne':\n case 'count':\n case 'aggregate':\n return 'select';\n case 'insert':\n return 'insert';\n case 'update':\n return 'update';\n case 'delete':\n return 'delete';\n default:\n return 'select';\n }\n }\n}\n","// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport type { FieldPermission } from '@objectstack/spec/security';\n\n/**\n * FieldMasker\n * \n * Applies field-level security by stripping restricted fields from query results.\n */\nexport class FieldMasker {\n /**\n * Mask fields in query results based on field permissions.\n * Removes fields that the user does not have read access to.\n */\n maskResults(\n results: any | any[],\n fieldPermissions: Record<string, FieldPermission>,\n _objectName: string\n ): any | any[] {\n // If no field permissions defined, return results as-is\n if (Object.keys(fieldPermissions).length === 0) return results;\n\n // Get list of non-readable fields\n const hiddenFields = Object.entries(fieldPermissions)\n .filter(([, perm]) => !perm.readable)\n .map(([field]) => field);\n\n if (hiddenFields.length === 0) return results;\n\n if (Array.isArray(results)) {\n return results.map(record => this.maskRecord(record, hiddenFields));\n }\n\n return this.maskRecord(results, hiddenFields);\n }\n\n /**\n * Get non-editable fields for use in write operations.\n * Returns a list of field names that should be stripped from incoming data.\n */\n getNonEditableFields(\n fieldPermissions: Record<string, FieldPermission>\n ): string[] {\n return Object.entries(fieldPermissions)\n .filter(([, perm]) => !perm.editable)\n .map(([field]) => field);\n }\n\n /**\n * Strip non-editable fields from write data.\n */\n stripNonEditableFields(\n data: Record<string, any>,\n fieldPermissions: Record<string, FieldPermission>\n ): Record<string, any> {\n const nonEditable = this.getNonEditableFields(fieldPermissions);\n if (nonEditable.length === 0) return data;\n\n const result = { ...data };\n for (const field of nonEditable) {\n delete result[field];\n }\n return result;\n }\n\n private maskRecord(record: any, hiddenFields: string[]): any {\n if (!record || typeof record !== 'object') return record;\n\n const result = { ...record };\n for (const field of hiddenFields) {\n delete result[field];\n }\n return result;\n }\n}\n","// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { Plugin, PluginContext } from '@objectstack/core';\nimport type { PermissionSet, RowLevelSecurityPolicy } from '@objectstack/spec/security';\nimport { PermissionEvaluator } from './permission-evaluator.js';\nimport { RLSCompiler } from './rls-compiler.js';\nimport { FieldMasker } from './field-masker.js';\n\n/**\n * SecurityPlugin\n * \n * Provides RBAC, Row-Level Security, and Field-Level Security runtime.\n * Registers as an engine middleware on the ObjectQL engine.\n * \n * This plugin is fully optional — without it, the system operates\n * without permission checks (same as current behavior).\n * \n * Dependencies:\n * - objectql service (ObjectQL engine with middleware support)\n * - metadata service (MetadataFacade for reading permission sets and RLS policies)\n */\nexport class SecurityPlugin implements Plugin {\n name = 'com.objectstack.security';\n type = 'standard';\n version = '1.0.0';\n dependencies = ['com.objectstack.engine.objectql'];\n\n private permissionEvaluator = new PermissionEvaluator();\n private rlsCompiler = new RLSCompiler();\n private fieldMasker = new FieldMasker();\n\n async init(ctx: PluginContext): Promise<void> {\n ctx.logger.info('Initializing Security Plugin...');\n \n // Register security services\n ctx.registerService('security.permissions', this.permissionEvaluator);\n ctx.registerService('security.rls', this.rlsCompiler);\n ctx.registerService('security.fieldMasker', this.fieldMasker);\n \n ctx.logger.info('Security Plugin initialized');\n }\n\n async start(ctx: PluginContext): Promise<void> {\n ctx.logger.info('Starting Security Plugin...');\n\n // Get required services\n let ql: any;\n let metadata: any;\n\n try {\n ql = ctx.getService('objectql');\n metadata = ctx.getService('metadata');\n } catch (e) {\n ctx.logger.warn('ObjectQL or metadata service not available, security middleware not registered');\n return;\n }\n\n if (!ql || typeof ql.registerMiddleware !== 'function') {\n ctx.logger.warn('ObjectQL engine does not support middleware, security middleware not registered');\n return;\n }\n\n // Register security middleware\n ql.registerMiddleware(async (opCtx: any, next: () => Promise<void>) => {\n // System operations bypass security\n if (opCtx.context?.isSystem) {\n return next();\n }\n\n const roles = opCtx.context?.roles ?? [];\n\n // Skip security checks if no roles (anonymous/unauthenticated)\n // The auth middleware should handle authentication separately\n if (roles.length === 0 && !opCtx.context?.userId) {\n return next();\n }\n\n // 1. Resolve permission sets for the user's roles\n let permissionSets: PermissionSet[] = [];\n try {\n permissionSets = this.permissionEvaluator.resolvePermissionSets(roles, metadata);\n } catch (e) {\n // If metadata service is misconfigured, log and continue without permission checks\n // rather than blocking all operations\n return next();\n }\n\n // 2. CRUD permission check\n if (permissionSets.length > 0) {\n const allowed = this.permissionEvaluator.checkObjectPermission(\n opCtx.operation,\n opCtx.object,\n permissionSets\n );\n\n if (!allowed) {\n throw new Error(\n `[Security] Access denied: operation '${opCtx.operation}' on object '${opCtx.object}' ` +\n `is not permitted for roles [${roles.join(', ')}]`\n );\n }\n }\n\n // 3. RLS filter injection\n const allRlsPolicies = this.collectRLSPolicies(permissionSets, opCtx.object, opCtx.operation);\n if (allRlsPolicies.length > 0 && opCtx.ast) {\n const rlsFilter = this.rlsCompiler.compileFilter(allRlsPolicies, opCtx.context);\n if (rlsFilter) {\n if (opCtx.ast.where) {\n opCtx.ast.where = { $and: [opCtx.ast.where, rlsFilter] };\n } else {\n opCtx.ast.where = rlsFilter;\n }\n }\n }\n\n await next();\n\n // 4. Field-level security: mask restricted fields in read results\n if (opCtx.result && ['find', 'findOne'].includes(opCtx.operation)) {\n const fieldPerms = this.permissionEvaluator.getFieldPermissions(opCtx.object, permissionSets);\n if (Object.keys(fieldPerms).length > 0) {\n opCtx.result = this.fieldMasker.maskResults(opCtx.result, fieldPerms, opCtx.object);\n }\n }\n });\n\n ctx.logger.info('Security middleware registered on ObjectQL engine');\n }\n\n async destroy(): Promise<void> {\n // No cleanup needed\n }\n\n /**\n * Collect all RLS policies from permission sets applicable to the given object/operation.\n */\n private collectRLSPolicies(\n permissionSets: PermissionSet[],\n objectName: string,\n operation: string\n ): RowLevelSecurityPolicy[] {\n const allPolicies: RowLevelSecurityPolicy[] = [];\n\n for (const ps of permissionSets) {\n if (ps.rowLevelSecurity) {\n allPolicies.push(...ps.rowLevelSecurity);\n }\n }\n\n return this.rlsCompiler.getApplicablePolicies(objectName, operation, allPolicies);\n }\n}\n"],"mappings":";AAOA,IAAM,0BAAkE;AAAA,EACtE,MAAM;AAAA,EACN,SAAS;AAAA,EACT,OAAO;AAAA,EACP,WAAW;AAAA,EACX,QAAQ;AAAA,EACR,QAAQ;AAAA,EACR,QAAQ;AACV;AAQO,IAAM,sBAAN,MAA0B;AAAA;AAAA;AAAA;AAAA;AAAA,EAK/B,sBACE,WACA,YACA,gBACS;AACT,UAAM,UAAU,wBAAwB,SAAS;AACjD,QAAI,CAAC,QAAS,QAAO;AAErB,eAAW,MAAM,gBAAgB;AAC/B,YAAM,UAAU,GAAG,UAAU,UAAU;AACvC,UAAI,SAAS;AAEX,YAAI,CAAC,aAAa,aAAa,EAAE,SAAS,OAAO,KAAK,QAAQ,kBAAkB;AAC9E,iBAAO;AAAA,QACT;AAEA,YAAI,YAAY,gBAAgB,QAAQ,kBAAkB,QAAQ,mBAAmB;AACnF,iBAAO;AAAA,QACT;AAEA,YAAI,QAAQ,OAAO,GAAG;AACpB,iBAAO;AAAA,QACT;AAAA,MACF;AAAA,IACF;AAEA,WAAO;AAAA,EACT;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOA,oBACE,YACA,gBACiC;AACjC,UAAM,SAA0C,CAAC;AAEjD,eAAW,MAAM,gBAAgB;AAC/B,UAAI,CAAC,GAAG,OAAQ;AAEhB,iBAAW,CAAC,KA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ADDED
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@objectstack/plugin-security",
|
|
3
|
+
"version": "2.0.4",
|
|
4
|
+
"license": "Apache-2.0",
|
|
5
|
+
"description": "Security Plugin for ObjectStack — RBAC, RLS, and Field-Level Security Runtime",
|
|
6
|
+
"main": "dist/index.js",
|
|
7
|
+
"types": "dist/index.d.ts",
|
|
8
|
+
"exports": {
|
|
9
|
+
".": {
|
|
10
|
+
"types": "./dist/index.d.ts",
|
|
11
|
+
"import": "./dist/index.mjs",
|
|
12
|
+
"require": "./dist/index.js"
|
|
13
|
+
}
|
|
14
|
+
},
|
|
15
|
+
"dependencies": {
|
|
16
|
+
"@objectstack/core": "2.0.4",
|
|
17
|
+
"@objectstack/spec": "2.0.4"
|
|
18
|
+
},
|
|
19
|
+
"devDependencies": {
|
|
20
|
+
"@types/node": "^25.2.2",
|
|
21
|
+
"typescript": "^5.0.0",
|
|
22
|
+
"vitest": "^4.0.18"
|
|
23
|
+
},
|
|
24
|
+
"scripts": {
|
|
25
|
+
"build": "tsup --config ../../../tsup.config.ts",
|
|
26
|
+
"test": "vitest run"
|
|
27
|
+
}
|
|
28
|
+
}
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.
|
|
2
|
+
|
|
3
|
+
import type { FieldPermission } from '@objectstack/spec/security';
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* FieldMasker
|
|
7
|
+
*
|
|
8
|
+
* Applies field-level security by stripping restricted fields from query results.
|
|
9
|
+
*/
|
|
10
|
+
export class FieldMasker {
|
|
11
|
+
/**
|
|
12
|
+
* Mask fields in query results based on field permissions.
|
|
13
|
+
* Removes fields that the user does not have read access to.
|
|
14
|
+
*/
|
|
15
|
+
maskResults(
|
|
16
|
+
results: any | any[],
|
|
17
|
+
fieldPermissions: Record<string, FieldPermission>,
|
|
18
|
+
_objectName: string
|
|
19
|
+
): any | any[] {
|
|
20
|
+
// If no field permissions defined, return results as-is
|
|
21
|
+
if (Object.keys(fieldPermissions).length === 0) return results;
|
|
22
|
+
|
|
23
|
+
// Get list of non-readable fields
|
|
24
|
+
const hiddenFields = Object.entries(fieldPermissions)
|
|
25
|
+
.filter(([, perm]) => !perm.readable)
|
|
26
|
+
.map(([field]) => field);
|
|
27
|
+
|
|
28
|
+
if (hiddenFields.length === 0) return results;
|
|
29
|
+
|
|
30
|
+
if (Array.isArray(results)) {
|
|
31
|
+
return results.map(record => this.maskRecord(record, hiddenFields));
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
return this.maskRecord(results, hiddenFields);
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* Get non-editable fields for use in write operations.
|
|
39
|
+
* Returns a list of field names that should be stripped from incoming data.
|
|
40
|
+
*/
|
|
41
|
+
getNonEditableFields(
|
|
42
|
+
fieldPermissions: Record<string, FieldPermission>
|
|
43
|
+
): string[] {
|
|
44
|
+
return Object.entries(fieldPermissions)
|
|
45
|
+
.filter(([, perm]) => !perm.editable)
|
|
46
|
+
.map(([field]) => field);
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* Strip non-editable fields from write data.
|
|
51
|
+
*/
|
|
52
|
+
stripNonEditableFields(
|
|
53
|
+
data: Record<string, any>,
|
|
54
|
+
fieldPermissions: Record<string, FieldPermission>
|
|
55
|
+
): Record<string, any> {
|
|
56
|
+
const nonEditable = this.getNonEditableFields(fieldPermissions);
|
|
57
|
+
if (nonEditable.length === 0) return data;
|
|
58
|
+
|
|
59
|
+
const result = { ...data };
|
|
60
|
+
for (const field of nonEditable) {
|
|
61
|
+
delete result[field];
|
|
62
|
+
}
|
|
63
|
+
return result;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
private maskRecord(record: any, hiddenFields: string[]): any {
|
|
67
|
+
if (!record || typeof record !== 'object') return record;
|
|
68
|
+
|
|
69
|
+
const result = { ...record };
|
|
70
|
+
for (const field of hiddenFields) {
|
|
71
|
+
delete result[field];
|
|
72
|
+
}
|
|
73
|
+
return result;
|
|
74
|
+
}
|
|
75
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* @objectstack/plugin-security
|
|
5
|
+
*
|
|
6
|
+
* Security Plugin for ObjectStack
|
|
7
|
+
* Provides RBAC, Row-Level Security (RLS), and Field-Level Security runtime.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
export { SecurityPlugin } from './security-plugin.js';
|
|
11
|
+
export { PermissionEvaluator } from './permission-evaluator.js';
|
|
12
|
+
export { RLSCompiler } from './rls-compiler.js';
|
|
13
|
+
export { FieldMasker } from './field-masker.js';
|
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.
|
|
2
|
+
|
|
3
|
+
import type { PermissionSet, ObjectPermission, FieldPermission } from '@objectstack/spec/security';
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Operation type mapping to permission checks
|
|
7
|
+
*/
|
|
8
|
+
const OPERATION_TO_PERMISSION: Record<string, keyof ObjectPermission> = {
|
|
9
|
+
find: 'allowRead',
|
|
10
|
+
findOne: 'allowRead',
|
|
11
|
+
count: 'allowRead',
|
|
12
|
+
aggregate: 'allowRead',
|
|
13
|
+
insert: 'allowCreate',
|
|
14
|
+
update: 'allowEdit',
|
|
15
|
+
delete: 'allowDelete',
|
|
16
|
+
};
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* PermissionEvaluator
|
|
20
|
+
*
|
|
21
|
+
* Runtime evaluator for PermissionSet definitions.
|
|
22
|
+
* Resolves aggregated permissions from roles to concrete allow/deny decisions.
|
|
23
|
+
*/
|
|
24
|
+
export class PermissionEvaluator {
|
|
25
|
+
/**
|
|
26
|
+
* Check if an operation is allowed on an object for the given permission sets.
|
|
27
|
+
* Uses "most permissive" merging: if ANY permission set allows, it's allowed.
|
|
28
|
+
*/
|
|
29
|
+
checkObjectPermission(
|
|
30
|
+
operation: string,
|
|
31
|
+
objectName: string,
|
|
32
|
+
permissionSets: PermissionSet[]
|
|
33
|
+
): boolean {
|
|
34
|
+
const permKey = OPERATION_TO_PERMISSION[operation];
|
|
35
|
+
if (!permKey) return true; // Unknown operations are allowed by default
|
|
36
|
+
|
|
37
|
+
for (const ps of permissionSets) {
|
|
38
|
+
const objPerm = ps.objects?.[objectName];
|
|
39
|
+
if (objPerm) {
|
|
40
|
+
// Check if modifyAllRecords is set (super-user bypass for write ops)
|
|
41
|
+
if (['allowEdit', 'allowDelete'].includes(permKey) && objPerm.modifyAllRecords) {
|
|
42
|
+
return true;
|
|
43
|
+
}
|
|
44
|
+
// Check if viewAllRecords is set (super-user bypass for read ops)
|
|
45
|
+
if (permKey === 'allowRead' && (objPerm.viewAllRecords || objPerm.modifyAllRecords)) {
|
|
46
|
+
return true;
|
|
47
|
+
}
|
|
48
|
+
// Check the specific permission
|
|
49
|
+
if (objPerm[permKey]) {
|
|
50
|
+
return true;
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
return false;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* Get the merged field permissions for an object.
|
|
60
|
+
* Returns a map of field names to their effective permissions.
|
|
61
|
+
* Uses "most permissive" merging.
|
|
62
|
+
*/
|
|
63
|
+
getFieldPermissions(
|
|
64
|
+
objectName: string,
|
|
65
|
+
permissionSets: PermissionSet[]
|
|
66
|
+
): Record<string, FieldPermission> {
|
|
67
|
+
const result: Record<string, FieldPermission> = {};
|
|
68
|
+
|
|
69
|
+
for (const ps of permissionSets) {
|
|
70
|
+
if (!ps.fields) continue;
|
|
71
|
+
|
|
72
|
+
for (const [key, perm] of Object.entries(ps.fields)) {
|
|
73
|
+
// Field keys are in format: "object_name.field_name"
|
|
74
|
+
if (!key.startsWith(`${objectName}.`)) continue;
|
|
75
|
+
const fieldName = key.substring(objectName.length + 1);
|
|
76
|
+
|
|
77
|
+
if (!result[fieldName]) {
|
|
78
|
+
result[fieldName] = { readable: false, editable: false };
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
// Most permissive merge
|
|
82
|
+
if (perm.readable) result[fieldName].readable = true;
|
|
83
|
+
if (perm.editable) result[fieldName].editable = true;
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
return result;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/**
|
|
91
|
+
* Resolve permission sets for a list of role names from metadata.
|
|
92
|
+
*/
|
|
93
|
+
resolvePermissionSets(
|
|
94
|
+
roles: string[],
|
|
95
|
+
metadataService: any
|
|
96
|
+
): PermissionSet[] {
|
|
97
|
+
const result: PermissionSet[] = [];
|
|
98
|
+
|
|
99
|
+
// Get all permission sets from metadata
|
|
100
|
+
const allPermSets = metadataService.list?.('permissions') || [];
|
|
101
|
+
|
|
102
|
+
for (const ps of allPermSets) {
|
|
103
|
+
// A permission set is relevant if it's a profile assigned to any of the user's roles,
|
|
104
|
+
// or if the role name matches the permission set name
|
|
105
|
+
if (roles.includes(ps.name)) {
|
|
106
|
+
result.push(ps);
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
return result;
|
|
111
|
+
}
|
|
112
|
+
}
|
|
@@ -0,0 +1,143 @@
|
|
|
1
|
+
// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.
|
|
2
|
+
|
|
3
|
+
import type { RowLevelSecurityPolicy } from '@objectstack/spec/security';
|
|
4
|
+
import type { ExecutionContext } from '@objectstack/spec/kernel';
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* RLS User Context
|
|
8
|
+
* Variables available for RLS expression evaluation.
|
|
9
|
+
*/
|
|
10
|
+
interface RLSUserContext {
|
|
11
|
+
id?: string;
|
|
12
|
+
tenant_id?: string;
|
|
13
|
+
roles?: string[];
|
|
14
|
+
[key: string]: unknown;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* RLSCompiler
|
|
19
|
+
*
|
|
20
|
+
* Compiles Row-Level Security policy expressions into query filters.
|
|
21
|
+
* Converts `using` / `check` expressions into ObjectQL-compatible filter conditions.
|
|
22
|
+
*/
|
|
23
|
+
export class RLSCompiler {
|
|
24
|
+
/**
|
|
25
|
+
* Compile RLS policies into a query filter for the given user context.
|
|
26
|
+
* Multiple policies for the same object/operation are OR-combined (any match allows access).
|
|
27
|
+
*/
|
|
28
|
+
compileFilter(
|
|
29
|
+
policies: RowLevelSecurityPolicy[],
|
|
30
|
+
executionContext?: ExecutionContext
|
|
31
|
+
): Record<string, unknown> | null {
|
|
32
|
+
if (policies.length === 0) return null;
|
|
33
|
+
|
|
34
|
+
const userCtx: RLSUserContext = {
|
|
35
|
+
id: executionContext?.userId,
|
|
36
|
+
tenant_id: executionContext?.tenantId,
|
|
37
|
+
roles: executionContext?.roles,
|
|
38
|
+
};
|
|
39
|
+
|
|
40
|
+
const filters: Record<string, unknown>[] = [];
|
|
41
|
+
|
|
42
|
+
for (const policy of policies) {
|
|
43
|
+
if (!policy.using) continue;
|
|
44
|
+
const filter = this.compileExpression(policy.using, userCtx);
|
|
45
|
+
if (filter) {
|
|
46
|
+
filters.push(filter);
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
if (filters.length === 0) return null;
|
|
51
|
+
if (filters.length === 1) return filters[0];
|
|
52
|
+
|
|
53
|
+
// Multiple policies: OR-combine (any policy allows access)
|
|
54
|
+
return { $or: filters };
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* Compile a single RLS expression into a query filter.
|
|
59
|
+
*
|
|
60
|
+
* Supports simple expressions like:
|
|
61
|
+
* - "field_name = current_user.property"
|
|
62
|
+
* - "field_name IN (current_user.array_property)"
|
|
63
|
+
* - "field_name = 'literal_value'"
|
|
64
|
+
*/
|
|
65
|
+
compileExpression(
|
|
66
|
+
expression: string,
|
|
67
|
+
userCtx: RLSUserContext
|
|
68
|
+
): Record<string, unknown> | null {
|
|
69
|
+
if (!expression) return null;
|
|
70
|
+
|
|
71
|
+
// Handle simple equality: "field = current_user.property"
|
|
72
|
+
const eqMatch = expression.match(/^\s*(\w+)\s*=\s*current_user\.(\w+)\s*$/);
|
|
73
|
+
if (eqMatch) {
|
|
74
|
+
const [, field, prop] = eqMatch;
|
|
75
|
+
const value = userCtx[prop];
|
|
76
|
+
if (value === undefined) return null;
|
|
77
|
+
return { [field]: value };
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
// Handle literal equality: "field = 'value'"
|
|
81
|
+
const litMatch = expression.match(/^\s*(\w+)\s*=\s*'([^']*)'\s*$/);
|
|
82
|
+
if (litMatch) {
|
|
83
|
+
const [, field, value] = litMatch;
|
|
84
|
+
return { [field]: value };
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
// Handle IN: "field IN (current_user.array_property)"
|
|
88
|
+
const inMatch = expression.match(/^\s*(\w+)\s+IN\s+\(\s*current_user\.(\w+)\s*\)\s*$/i);
|
|
89
|
+
if (inMatch) {
|
|
90
|
+
const [, field, prop] = inMatch;
|
|
91
|
+
const value = userCtx[prop];
|
|
92
|
+
if (!Array.isArray(value)) return null;
|
|
93
|
+
return { [field]: { $in: value } };
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
// Unsupported expression: return null (no additional RLS filter applied).
|
|
97
|
+
// Note: callers should treat absence of RLS policies as "allow all" only when
|
|
98
|
+
// no policies are defined. If policies exist but cannot be compiled, the caller
|
|
99
|
+
// may want to deny access as a safety measure.
|
|
100
|
+
return null;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/**
|
|
104
|
+
* Get applicable RLS policies for a given object and operation.
|
|
105
|
+
*/
|
|
106
|
+
getApplicablePolicies(
|
|
107
|
+
objectName: string,
|
|
108
|
+
operation: string,
|
|
109
|
+
allPolicies: RowLevelSecurityPolicy[]
|
|
110
|
+
): RowLevelSecurityPolicy[] {
|
|
111
|
+
// Map engine operation to RLS operation type
|
|
112
|
+
const rlsOp = this.mapOperationToRLS(operation);
|
|
113
|
+
|
|
114
|
+
return allPolicies.filter(policy => {
|
|
115
|
+
// Check object match
|
|
116
|
+
if (policy.object !== objectName && policy.object !== '*') return false;
|
|
117
|
+
|
|
118
|
+
// Check operation match
|
|
119
|
+
if (policy.operation === 'all') return true;
|
|
120
|
+
if (policy.operation === rlsOp) return true;
|
|
121
|
+
|
|
122
|
+
return false;
|
|
123
|
+
});
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
private mapOperationToRLS(operation: string): string {
|
|
127
|
+
switch (operation) {
|
|
128
|
+
case 'find':
|
|
129
|
+
case 'findOne':
|
|
130
|
+
case 'count':
|
|
131
|
+
case 'aggregate':
|
|
132
|
+
return 'select';
|
|
133
|
+
case 'insert':
|
|
134
|
+
return 'insert';
|
|
135
|
+
case 'update':
|
|
136
|
+
return 'update';
|
|
137
|
+
case 'delete':
|
|
138
|
+
return 'delete';
|
|
139
|
+
default:
|
|
140
|
+
return 'select';
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
}
|
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.
|
|
2
|
+
|
|
3
|
+
import { Plugin, PluginContext } from '@objectstack/core';
|
|
4
|
+
import type { PermissionSet, RowLevelSecurityPolicy } from '@objectstack/spec/security';
|
|
5
|
+
import { PermissionEvaluator } from './permission-evaluator.js';
|
|
6
|
+
import { RLSCompiler } from './rls-compiler.js';
|
|
7
|
+
import { FieldMasker } from './field-masker.js';
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* SecurityPlugin
|
|
11
|
+
*
|
|
12
|
+
* Provides RBAC, Row-Level Security, and Field-Level Security runtime.
|
|
13
|
+
* Registers as an engine middleware on the ObjectQL engine.
|
|
14
|
+
*
|
|
15
|
+
* This plugin is fully optional — without it, the system operates
|
|
16
|
+
* without permission checks (same as current behavior).
|
|
17
|
+
*
|
|
18
|
+
* Dependencies:
|
|
19
|
+
* - objectql service (ObjectQL engine with middleware support)
|
|
20
|
+
* - metadata service (MetadataFacade for reading permission sets and RLS policies)
|
|
21
|
+
*/
|
|
22
|
+
export class SecurityPlugin implements Plugin {
|
|
23
|
+
name = 'com.objectstack.security';
|
|
24
|
+
type = 'standard';
|
|
25
|
+
version = '1.0.0';
|
|
26
|
+
dependencies = ['com.objectstack.engine.objectql'];
|
|
27
|
+
|
|
28
|
+
private permissionEvaluator = new PermissionEvaluator();
|
|
29
|
+
private rlsCompiler = new RLSCompiler();
|
|
30
|
+
private fieldMasker = new FieldMasker();
|
|
31
|
+
|
|
32
|
+
async init(ctx: PluginContext): Promise<void> {
|
|
33
|
+
ctx.logger.info('Initializing Security Plugin...');
|
|
34
|
+
|
|
35
|
+
// Register security services
|
|
36
|
+
ctx.registerService('security.permissions', this.permissionEvaluator);
|
|
37
|
+
ctx.registerService('security.rls', this.rlsCompiler);
|
|
38
|
+
ctx.registerService('security.fieldMasker', this.fieldMasker);
|
|
39
|
+
|
|
40
|
+
ctx.logger.info('Security Plugin initialized');
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
async start(ctx: PluginContext): Promise<void> {
|
|
44
|
+
ctx.logger.info('Starting Security Plugin...');
|
|
45
|
+
|
|
46
|
+
// Get required services
|
|
47
|
+
let ql: any;
|
|
48
|
+
let metadata: any;
|
|
49
|
+
|
|
50
|
+
try {
|
|
51
|
+
ql = ctx.getService('objectql');
|
|
52
|
+
metadata = ctx.getService('metadata');
|
|
53
|
+
} catch (e) {
|
|
54
|
+
ctx.logger.warn('ObjectQL or metadata service not available, security middleware not registered');
|
|
55
|
+
return;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
if (!ql || typeof ql.registerMiddleware !== 'function') {
|
|
59
|
+
ctx.logger.warn('ObjectQL engine does not support middleware, security middleware not registered');
|
|
60
|
+
return;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
// Register security middleware
|
|
64
|
+
ql.registerMiddleware(async (opCtx: any, next: () => Promise<void>) => {
|
|
65
|
+
// System operations bypass security
|
|
66
|
+
if (opCtx.context?.isSystem) {
|
|
67
|
+
return next();
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
const roles = opCtx.context?.roles ?? [];
|
|
71
|
+
|
|
72
|
+
// Skip security checks if no roles (anonymous/unauthenticated)
|
|
73
|
+
// The auth middleware should handle authentication separately
|
|
74
|
+
if (roles.length === 0 && !opCtx.context?.userId) {
|
|
75
|
+
return next();
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
// 1. Resolve permission sets for the user's roles
|
|
79
|
+
let permissionSets: PermissionSet[] = [];
|
|
80
|
+
try {
|
|
81
|
+
permissionSets = this.permissionEvaluator.resolvePermissionSets(roles, metadata);
|
|
82
|
+
} catch (e) {
|
|
83
|
+
// If metadata service is misconfigured, log and continue without permission checks
|
|
84
|
+
// rather than blocking all operations
|
|
85
|
+
return next();
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
// 2. CRUD permission check
|
|
89
|
+
if (permissionSets.length > 0) {
|
|
90
|
+
const allowed = this.permissionEvaluator.checkObjectPermission(
|
|
91
|
+
opCtx.operation,
|
|
92
|
+
opCtx.object,
|
|
93
|
+
permissionSets
|
|
94
|
+
);
|
|
95
|
+
|
|
96
|
+
if (!allowed) {
|
|
97
|
+
throw new Error(
|
|
98
|
+
`[Security] Access denied: operation '${opCtx.operation}' on object '${opCtx.object}' ` +
|
|
99
|
+
`is not permitted for roles [${roles.join(', ')}]`
|
|
100
|
+
);
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
// 3. RLS filter injection
|
|
105
|
+
const allRlsPolicies = this.collectRLSPolicies(permissionSets, opCtx.object, opCtx.operation);
|
|
106
|
+
if (allRlsPolicies.length > 0 && opCtx.ast) {
|
|
107
|
+
const rlsFilter = this.rlsCompiler.compileFilter(allRlsPolicies, opCtx.context);
|
|
108
|
+
if (rlsFilter) {
|
|
109
|
+
if (opCtx.ast.where) {
|
|
110
|
+
opCtx.ast.where = { $and: [opCtx.ast.where, rlsFilter] };
|
|
111
|
+
} else {
|
|
112
|
+
opCtx.ast.where = rlsFilter;
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
await next();
|
|
118
|
+
|
|
119
|
+
// 4. Field-level security: mask restricted fields in read results
|
|
120
|
+
if (opCtx.result && ['find', 'findOne'].includes(opCtx.operation)) {
|
|
121
|
+
const fieldPerms = this.permissionEvaluator.getFieldPermissions(opCtx.object, permissionSets);
|
|
122
|
+
if (Object.keys(fieldPerms).length > 0) {
|
|
123
|
+
opCtx.result = this.fieldMasker.maskResults(opCtx.result, fieldPerms, opCtx.object);
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
});
|
|
127
|
+
|
|
128
|
+
ctx.logger.info('Security middleware registered on ObjectQL engine');
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
async destroy(): Promise<void> {
|
|
132
|
+
// No cleanup needed
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
/**
|
|
136
|
+
* Collect all RLS policies from permission sets applicable to the given object/operation.
|
|
137
|
+
*/
|
|
138
|
+
private collectRLSPolicies(
|
|
139
|
+
permissionSets: PermissionSet[],
|
|
140
|
+
objectName: string,
|
|
141
|
+
operation: string
|
|
142
|
+
): RowLevelSecurityPolicy[] {
|
|
143
|
+
const allPolicies: RowLevelSecurityPolicy[] = [];
|
|
144
|
+
|
|
145
|
+
for (const ps of permissionSets) {
|
|
146
|
+
if (ps.rowLevelSecurity) {
|
|
147
|
+
allPolicies.push(...ps.rowLevelSecurity);
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
return this.rlsCompiler.getApplicablePolicies(objectName, operation, allPolicies);
|
|
152
|
+
}
|
|
153
|
+
}
|