-
Notifications
You must be signed in to change notification settings - Fork 7
Aauth v2 #95
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Aauth v2 #95
Conversation
- Updated config structure (aauth.php, added aauth-permissions.php) - Added parameters JSON column to role_permission table - Added panel_id column to roles table - Added defensive code for soft deprecation of type enum
- Add parameter support to AAuth::can() - Integrate Laravel Gate via Gate::before() - Keep permission logic centralized in AAuth.php - Update helper functions and Blade directives
- Implement request-level cache using Laravel Context API in AAuth.php - Add in-memory request cache via $requestCache property - Optimize eager loading for roles, permissions, and ABAC rules - Invalidate cached context using model observers - Introduce context lifecycle helpers (loadAndCacheContext, clearContext)
# Conflicts: # src/AAuth.php
…r bindings - Introduce permission-based authorization middleware - Add role-based access control middleware - Implement organization scope enforcement middleware - Register AAuth middleware in AAuthServiceProvider
- Add role lifecycle and assignment events - Add permission change events - Fire relevant events from role and permission observers - Leverage existing observer registrations in AAuthServiceProvider
- Add migration to make roles.type column nullable - Update unique constraint to use organization scope - Adjust indexes to reflect new role scoping model - Add defensive schema checks for safe migrations
- Add static factory methods for panel-scoped usage - Introduce panel-aware instance methods without affecting existing API - Provide static helpers for panel role resolution and panel detection - Add global helper functions for Filament panel context - Register Blade directives for panel-based authorization checks
Validation fixes: - Change name field minimum length from 5 to 3 in all FormRequests - Fix UpdateRoleRequest unique validation (permissions → roles table) - Add missing authorize() and rules() methods to StoreOrganizationScopeRequest Filament panel integration (Phase 7): - Add optional panelId parameter to AAuth constructor for Filament context - Add factory methods and panel-aware helpers (forPanel, forCurrentPanel, isInPanel) - Add Blade directives (@panel, @aauth_panel_can) and helper functions - Auto-detect Filament panel context in singleton binding
- Add recursive depth limit (max 10) and SQL injection prevention via regex validation - Add strict JSON decode error handling and operator whitelist check - Support multiple value types and user attribute references (@user.attribute)
- Add role and switchableRoles caching with config-driven enable/disable (default: false for safety) - Fix cache invalidation in observers and service methods for immediate effect on role/permission changes - Create performance indexes (panel_id, role_permission, user_role joins, org paths) with Laravel 11 + PostgreSQL/MySQL compatibility Backward compatible: Cache disabled by default (opt-in via config), defensive hasIndex() prevents duplicate errors Performance: Query optimization via composite indexes, cache TTL configurable
- Add getAccessibleOrganizationNodes() method with depth/scope filtering (minDepth, maxDepth, scopeName, scopeLevel) - Create EN/TR language files for exception messages (resources/lang/en/aauth.php, resources/lang/tr/aauth.php) - Add translation support to MissingRoleException with fallback for backward compatibility Backward compatible: New method added, existing API unchanged. Translation opt-in via lang files. SQL: MySQL + PostgreSQL compatible depth calculation using LENGTH(path) - LENGTH(REPLACE(path, '/', ''))
- Update README.md with v2 features (Filament Panel, Performance, i18n, Depth Filtering) - Create UPGRADE.md for v1 to v2 migration guide with breaking changes and troubleshooting - Create API.md with complete method documentation for AAuth, services, helpers, and directives
V2 Test Suite (99 new tests): - AAuthCoreTest: Core method tests (currentRole, permissions, organizationNodes) - PanelSupportTest: Panel context, forPanel, switchableRolesForPanel - ExceptionTest: Exception handling coverage - MiddlewareTest: Middleware tests - V2FeaturesTest: Context caching, parametric permissions, super admin Bug Fixes: - Fix isset() returning false for null permission params (array_key_exists) - Fix Observer not triggering on permission changes (use Eloquent instead of DB::table) - Add Context clearing in RolePermissionObserver for cache invalidation - Load rolePermissions relationship after context reload CI: - Run tests on all branches, not just main Config: - Add aauth-advanced.php for cache and performance settings
V2 Test Suite (99 new tests): - AAuthCoreTest: Core method tests (currentRole, permissions, organizationNodes) - PanelSupportTest: Panel context, forPanel, switchableRolesForPanel - ExceptionTest: Exception handling coverage - MiddlewareTest: Middleware tests - V2FeaturesTest: Context caching, parametric permissions, super admin Bug Fixes: - Fix isset() returning false for null permission params (array_key_exists) - Fix Observer not triggering on permission changes (use Eloquent instead of DB::table) - Add Context clearing in RolePermissionObserver for cache invalidation - Load rolePermissions relationship after context reload CI: - Run tests on all branches, not just main Config: - Add aauth-advanced.php for cache and performance settings
AAuth v2 Release - Comprehensive Code ReviewOverviewThis is a major release with 4,349 additions and 170 deletions across 47 files. The v2 introduces significant features including Filament panel support, request-level caching, parametric permissions, and performance optimizations. Overall implementation is solid with excellent test coverage (99 new tests), but there are critical security gaps that must be addressed. 🔴 Critical Issues (Must Fix Before Merge)1. ABAC Security Features NOT ImplementedIssue: Commit message claims "ABAC validation hardening (SQL injection prevention, depth limits, operator whitelisting)" but these features are not actually implemented. Missing Security Features:
Impact: Attackers could inject malicious SQL via ABAC attribute names or cause DoS via deeply nested rules. 2. SQL Injection RisksLocation: src/AAuth.php:415-449 - can() method Location: src/AAuth.php:713, 717 - Depth filtering 3. Database Migration Not Database-AgnosticLocation: database/migrations/2024_01_01_000003_make_type_nullable_in_roles.php 4. Unsafe Serialization in Cache KeysLocation: src/AAuth.php:515 🟡 High Priority Issues (Should Fix)5. Race Condition in Cache Invalidation
6. N+1 Query Problem
7. Generic Exception Catching
8. Memory Leak Potential
9. Cache Stampede Risk
🟢 Strengths
📋 Testing GapsMissing critical tests:
🔧 Code Quality Issues
✅ RecommendationsBefore Merging (Critical):
High Priority (Post-Merge):
🎯 Overall AssessmentGrade: B+ (would be A- with security fixes) This is an impressive v2 release with excellent features and solid architecture. However, the critical gap between claimed and actual ABAC security features is concerning. Recommendation: Do not merge until:
Once these critical issues are resolved, this will be a production-ready release. Review completed with automated code analysis and manual security audit. |
- Replace serialize() with json_encode() in cache key generation (AAuth.php:515) - Make migration database-agnostic using Laravel Schema builder instead of MySQL-specific syntax
Code Review: AAuth v2OverviewThis is a major version upgrade introducing parametric permissions, Filament panel support, caching, super admin functionality, and comprehensive test coverage. The PR adds 4,353 lines across 47 files with excellent documentation. ✅ Strengths1. Architecture & Design
2. Performance
3. Documentation
4. Test Coverage
|
|
🟡 Security Concerns4. Weak Error Messages (Middleware files) All middleware classes catch exceptions without logging. Recommendation: } catch (\Throwable $e) {
\Log::warning('AAuth authorization failed', [
'exception' => $e->getMessage(),
'user' => $request->user()?->id,
'permission' => $permission,
]);
abort(403, 'Unauthorized action.');
}5. Cache Key Collision Risk (AAuth.php:515) Add JSON_THROW_ON_ERROR to prevent silent failures: protected function getPermissionCacheKey(string $permission, array $arguments): string
{
$serialized = json_encode($arguments, JSON_THROW_ON_ERROR);
return $permission . ':' . md5($serialized);
} |
🟠 Code Quality Issues6. Inconsistent Null Checks (AAuth.php:42-43) throw_unless($roleId !== null && $roleId > 0, new MissingRoleException());7. Dead Code (AAuth.php:653-657) 8. TODOs in Production Code 9. Potential Null Reference (RolePermissionService.php:70-72) $roleModel = Role::find($id);
if (!$roleModel) {
return null;
}
return $roleModel->update($role) ? $roleModel : null;10. Type Coercion (AAuth.php:648) |
🔵 Performance Considerations11. Repeated Schema Checks 12. Path Query Performance (AAuth.php:586-607) $rootNodes = OrganizationNode::whereIn('id', $this->organizationNodeIds)->get();
return OrganizationNode::where(function ($query) use ($rootNodes, $includeRootNode) {
foreach ($rootNodes as $rootNode) {
$query->orWhere('path', 'like', $rootNode->path . '/%');
if ($includeRootNode) {
$query->orWhere('path', $rootNode->path);
}
}
})📋 Minor Issues
|
🎯 RecommendationsMust Fix Before Merge:
Should Fix Before Merge:
Nice to Have:
🏆 Overall AssessmentThis is a well-architected major upgrade with excellent backward compatibility, comprehensive documentation, and good test coverage. The core design decisions (observers, caching strategy, helper functions) are solid. However, there are 3 critical issues that must be addressed before merging:
Once these are resolved, this will be a significant improvement to the package. Recommendation: Request changes for critical issues, then approve after fixes. Review generated by Claude Code |
- Fix RoleObserver N+1 query with direct pivot table query - Fix cache race condition by refreshing role on context reload
AAuth v2 Pull Request ReviewThis is a significant release introducing v2 features with backward compatibility. The implementation demonstrates careful attention to migration concerns and comprehensive testing. Below are my findings: ✅ Strengths1. Excellent Backward Compatibility
2. Strong Test Coverage
3. Performance Optimizations
4. Event System
5. Filament Panel Integration
6. Documentation
|
No description provided.