diff --git a/content/docs/objectos/meta.json b/content/docs/objectos/meta.json index 6cb6f70d85b..640840646e7 100644 --- a/content/docs/objectos/meta.json +++ b/content/docs/objectos/meta.json @@ -8,6 +8,7 @@ "plugin-spec", "config-resolution", "i18n-standard", + "permission-model", "transport" ] } diff --git a/content/docs/objectos/permission-model.mdx b/content/docs/objectos/permission-model.mdx new file mode 100644 index 00000000000..1ebda351c9f --- /dev/null +++ b/content/docs/objectos/permission-model.mdx @@ -0,0 +1,526 @@ +--- +title: Permission Model +description: Three-layer access control architecture for enterprise data security +--- + +import { Shield, Lock, Users, Database, CheckCircle, XCircle } from 'lucide-react'; + +# Permission Model + +ObjectStack provides a three-layer record-level access control system that combines database-level security, application permissions, and business sharing rules. + +## Overview + +The permission model consists of three layers: + +1. **RLS (Row-Level Security)** - Database-level enforcement policies +2. **Permission** - Application-level CRUD permissions +3. **Sharing** - Business rule extensions + +## Precedence Order + +Access rights are calculated using the formula: + +``` +Final Access = RLS ∩ Permission ∩ Sharing +``` + +**Most Restrictive Wins** - The strictest rule takes precedence. + +### Evaluation Flow + +``` +RLS Policies (cannot bypass) + ↓ PASS +Object Permissions (CRUD + VAMA) + ↓ PASS +Sharing Rules (OWD + Criteria) + ↓ PASS +GRANT ACCESS +``` + +## Layer 1: Row-Level Security (RLS) + + + } + title="Database-Level Enforcement" + description="PostgreSQL-inspired policies that cannot be bypassed, even by admins" + /> + + +### Purpose + +Row-Level Security provides database-level policies that filter data before it reaches the application layer. These policies are enforced at the lowest level and cannot be circumvented. + +### When to Use + +- **Multi-tenant data isolation** - Ensure users only access their organization's data +- **Regulatory compliance** - GDPR, HIPAA, and other data protection requirements +- **Hard security boundaries** - Enforce security at the database level + +### Example + +```typescript +const rlsPolicy: RowLevelSecurityPolicy = { + name: 'tenant_isolation', + object: 'account', + operation: 'select', + using: 'tenant_id = current_user.tenant_id', + enabled: true +}; +``` + +### Schema Reference + +See `permission/rls.zod.ts` for the complete schema definition. + +**Key Fields:** +- `name` - Unique policy identifier (snake_case) +- `object` - Target object name +- `operation` - Database operation: `select`, `insert`, `update`, `delete`, `all` +- `using` - Filter condition for SELECT/UPDATE/DELETE +- `check` - Validation for INSERT/UPDATE operations +- `roles` - Restrict policy to specific roles (optional) +- `enabled` - Whether policy is active + +## Layer 2: Object Permissions + + + } + title="Application-Level Control" + description="CRUD permissions with View All and Modify All modifiers" + /> + + +### Purpose + +Application-level CRUD permissions control what operations users can perform on objects. + +### Permission Matrix + +| Permission | Field Name | Grants | +|------------|------------|--------| +| Create | `allowCreate` | Insert new records | +| Read | `allowRead` | View records (subject to RLS/Sharing) | +| Update | `allowEdit` | Edit records (subject to RLS/Sharing) | +| Delete | `allowDelete` | Delete records (subject to RLS/Sharing) | +| View All | `viewAllRecords` | See all records (bypasses sharing) | +| Modify All | `modifyAllRecords` | Edit all records (bypasses sharing) | + +### Lifecycle Permissions + +Additional permissions for enterprise data lifecycle management: + +- `allowTransfer` - Change record ownership +- `allowRestore` - Restore from trash (Undelete) +- `allowPurge` - Permanently delete (Hard Delete/GDPR compliance) + +### Example + +```typescript +const permission: ObjectPermission = { + allowCreate: true, + allowRead: true, + allowEdit: true, + allowDelete: false, + allowTransfer: false, + allowRestore: false, + allowPurge: false, + viewAllRecords: false, + modifyAllRecords: false +}; +``` + +### Permission Set + +```typescript +const permissionSet: PermissionSet = { + name: 'sales_rep', + label: 'Sales Representative', + isProfile: true, + objects: { + 'opportunity': { + allowCreate: true, + allowRead: true, + allowEdit: true, + allowDelete: false, + viewAllRecords: false, + modifyAllRecords: false + } + }, + rowLevelSecurity: [rlsPolicy] +}; +``` + +### Schema Reference + +See `permission/permission.zod.ts` for the complete schema definition. + +## Layer 3: Sharing Rules + + + } + title="Business Rule Extensions" + description="Salesforce-inspired sharing that extends base permissions" + /> + + +### Purpose + +Sharing rules provide Salesforce-inspired extensions to base permissions, allowing you to grant access beyond ownership boundaries. + +### Organization-Wide Defaults (OWD) + +| Level | Meaning | +|-------|---------| +| `private` | Only owner sees record | +| `public_read` | Everyone can read | +| `public_read_write` | Everyone can edit | +| `controlled_by_parent` | Access derived from parent record (Master-Detail) | + +### Sharing Rule Types + +#### Criteria-Based Sharing + +Share records matching specific field criteria: + +```typescript +const criteriaSharingRule: CriteriaSharingRule = { + type: 'criteria', + name: 'share_apac_region', + object: 'opportunity', + condition: 'region = \'APAC\'', + sharedWith: { + type: 'role', + value: 'regional_manager' + }, + accessLevel: 'read', + active: true +}; +``` + +#### Owner-Based Sharing + +Share records based on owner attributes: + +```typescript +const ownerSharingRule: OwnerSharingRule = { + type: 'owner', + name: 'share_sales_team', + object: 'account', + ownedBy: { + type: 'role', + value: 'account_owner' + }, + sharedWith: { + type: 'role', + value: 'sales_team' + }, + accessLevel: 'edit', + active: true +}; +``` + +### Sharing Levels + +- `read` - Read Only +- `edit` - Read / Write +- `full` - Full Access (Transfer, Share, Delete) + +### Recipient Types + +- `user` - Individual user +- `group` - User group +- `role` - Role +- `role_and_subordinates` - Role hierarchy +- `guest` - Public sharing + +### Schema Reference + +See `permission/sharing.zod.ts` for the complete schema definition. + +## Composition Rules + +### Rule 1: RLS is Always Evaluated First + +RLS policies filter data at the database level before any application logic runs. + +**Example:** +- User has `Permission.viewAllRecords = true` +- BUT `tenant_id` RLS policy filters to only their tenant +- **Result:** User can ONLY see their tenant's data (RLS wins) + +### Rule 2: Permission Controls Capabilities + +Object permissions define what operations are possible. + +**Example:** +- User has `Permission.allowRead = false` +- **Result:** User cannot read ANY records (even if sharing grants access) + +### Rule 3: Sharing Extends Access + +Sharing rules can grant access to records beyond ownership. + +**Example:** +- User is NOT owner +- BUT sharing rule grants 'read' access to region='APAC' records +- **Result:** User can read APAC records (sharing extends) + +## Complete Example + +### Scenario + +Sales organization with regional structure. + +### Configuration + +**RLS:** +```typescript +{ + name: 'tenant_isolation', + object: 'opportunity', + operation: 'all', + using: 'tenant_id = current_user.tenant_id', + check: 'tenant_id = current_user.tenant_id', + enabled: true +} +``` + +**Permission:** +```typescript +{ + name: 'sales_rep', + objects: { + 'opportunity': { + allowCreate: true, + allowRead: true, + allowEdit: true, + allowDelete: false, + viewAllRecords: false, + modifyAllRecords: false + } + } +} +``` + +**Sharing:** +```typescript +{ + type: 'criteria', + name: 'share_closed_won', + object: 'opportunity', + condition: 'stage = \'closed_won\'', + sharedWith: { + type: 'role', + value: 'sales_manager' + }, + accessLevel: 'read', + active: true +} +``` + +### Test Cases + +| User | Scenario | Result | Reason | +|------|----------|--------|--------| +| Sales Rep | View own opportunity | ✅ PASS | Owner + Permission.allowRead | +| Sales Rep | View colleague's opp | ❌ FAIL | No sharing rule grants access | +| Sales Manager | View closed_won opp | ✅ PASS | Sharing rule grants read | +| Sales Manager | Edit closed_won opp | ❌ FAIL | Sharing only grants 'read' | +| Admin (different tenant) | View any opp | ❌ FAIL | RLS blocks cross-tenant | + +## Territory Management + +ObjectStack supports territory-based data access control as a parallel hierarchy to roles. + +### Purpose + +- Geographic sales territories (e.g., "EMEA", "APAC") +- Industry verticals (e.g., "Healthcare", "Financial") +- Strategic account management + +### Key Differences + +| Aspect | Role | Territory | +|--------|------|-----------| +| Structure | Hierarchy of PEOPLE | Hierarchy of ACCOUNTS/REVENUE | +| Flexibility | Stable (HR-driven) | Flexible (Sales-driven) | +| Assignment | One role per user | Multiple territories per user | + +### Example + +```typescript +const territory: Territory = { + name: 'west_coast', + label: 'West Coast', + modelId: 'fy2024', + type: 'geography', + assignmentRule: 'BillingCountry = \'US\' AND BillingState IN (\'CA\', \'OR\', \'WA\')', + assignedUsers: ['user_001', 'user_002'], + accountAccess: 'edit', + opportunityAccess: 'edit', + caseAccess: 'read' +}; +``` + +### Schema Reference + +See `permission/territory.zod.ts` for the complete schema definition. + +## Implementation Checklist + +When implementing the permission model: + +- [ ] Define RLS policies for multi-tenant isolation +- [ ] Configure object permissions per role +- [ ] Set Organization-Wide Defaults +- [ ] Create sharing rules for cross-ownership access +- [ ] Configure territory hierarchies (if needed) +- [ ] Write integration tests for each layer +- [ ] Test composition scenarios +- [ ] Document custom permission logic + +## Best Practices + +1. **Start with RLS** - Define hard boundaries first +2. **Use OWD Wisely** - Most objects should be 'private' or 'public_read' +3. **Minimize View All/Modify All** - Reserve for admin roles only +4. **Test Edge Cases** - Verify most restrictive wins +5. **Audit Regularly** - Review permission grants quarterly +6. **Document Territory Logic** - Keep assignment rules clear and maintainable + +## Security Considerations + +### Defense in Depth + +Always implement multiple layers: +- RLS for hard boundaries +- Permissions for capability control +- Sharing for business logic + +### Default Deny + +- No permission = No access +- Explicit grants only +- Audit all "View All" and "Modify All" assignments + +### Context Variables + +Ensure these are always set correctly: +- `current_user.id` +- `current_user.tenant_id` +- `current_user.role` +- `current_user.department` + +### SQL Injection Prevention + +RLS conditions MUST use parameterized queries: +- ✅ Good: `tenant_id = current_user.tenant_id` +- ❌ Bad: Direct string concatenation + +## API Examples + +### Check User Access + +```typescript +import { PermissionSet, RowLevelSecurityPolicy } from '@objectstack/spec/permission'; + +// Evaluate access +const hasAccess = await checkAccess({ + user: currentUser, + object: 'opportunity', + operation: 'read', + recordId: 'opp_123' +}); +``` + +### Query with RLS + +```typescript +// RLS automatically filters results +const opportunities = await db.query({ + object: 'opportunity', + fields: ['name', 'amount', 'stage'], + context: { + userId: currentUser.id, + tenantId: currentUser.tenantId + } +}); +// Returns only records user can access +``` + +## Performance Considerations + +### RLS Performance + +- RLS evaluates at database level (efficient) +- Index fields used in RLS conditions +- Cache RLS evaluation results (default: 5 minutes) +- Pre-fetch user context per request + +### Sharing Rules Performance + +- Criteria-based rules can be expensive +- Limit number of sharing rules per object +- Use owner-based rules when possible +- Consider territory hierarchy depth + +### Optimization Tips + +1. **Index Strategy**: Index all fields in RLS `using` clauses +2. **Cache Context**: Pre-fetch `current_user` data +3. **Batch Queries**: Evaluate permissions in batches +4. **Monitor**: Log slow policy evaluations + +## Migration Guide + +### From Simple RBAC + +1. Map existing roles to Permission Sets +2. Create RLS policies for tenant isolation +3. Set OWD to `private` for sensitive objects +4. Add sharing rules for cross-team collaboration + +### From Salesforce + +1. Profile → `PermissionSet` with `isProfile: true` +2. Permission Set → `PermissionSet` +3. Sharing Rule → `SharingRule` (criteria or owner-based) +4. Role Hierarchy → Territory hierarchy for sales +5. OWD → Direct mapping + +## Troubleshooting + +### User Can't Access Record + +1. Check RLS policies - Are they blocking? +2. Check object permissions - Do they have `allowRead`? +3. Check OWD - Is object `private`? +4. Check sharing rules - Do any grant access? +5. Check ownership - Are they the owner? + +### User Can Access Records They Shouldn't + +1. Check `viewAllRecords` - Should be false +2. Check RLS bypass roles - Are they in the list? +3. Check sharing rules - Are they too permissive? +4. Check territory assignments - Do they have access via territory? + +### Performance Issues + +1. Check RLS policy complexity +2. Add indexes on RLS condition fields +3. Reduce number of sharing rules +4. Enable RLS result caching +5. Profile query execution plans + +## Related Documentation + +- `permission/permission.zod.ts` - Permission schema +- `permission/rls.zod.ts` - RLS policy schema +- `permission/sharing.zod.ts` - Sharing rule schema +- `permission/territory.zod.ts` - Territory management schema