# Documents Management System Implementation
## Overview
A secure documents management system with encryption and explicit access control for multivendoring mode.
## Security Features
### Encryption
- **File Storage**: All files stored in encrypted format on secure disk
- **Metadata Encryption**: File names, descriptions, and tags are encrypted in the database
- **Encryption Service**: `DocumentEncryptionService` using Laravel's built-in Crypt (AES-256-GCM)
- **Key Management**: Each document has a unique encryption key ID for tracking
### Access Control
- **Explicit Grants**: Documents require explicit access grants for users/roles
- **Grant Types**: view, download, edit, delete, share
- **Time-based Access**: Grants can expire after specified date
- **Access Limits**: Optional maximum access count per grant
- **Access Conditions**: IP restrictions, time restrictions, day restrictions
- **Multivendor Isolation**: Documents are scoped to companies
### Audit Trail
- **Complete Logging**: All document actions are logged (view, download, edit, delete, share, create)
- **Access Details**: IP address, user agent, success/failure status
- **Grant Tracking**: Which grant was used for access
## Database Schema
### documents Table
- `company_id`: Company ownership for multivendor isolation
- `document_type`: Type categorization (general, contract, invoice, etc.)
- `category`: Optional category
- `encrypted_file_path`: Encrypted storage path
- `encrypted_file_name`: Encrypted file name
- `encrypted_file_type`: Encrypted MIME type
- `file_size`: File size in bytes
- `encrypted_description`: Encrypted description
- `encrypted_tags`: Encrypted tags array
- `status`: active, archived, deleted
- `is_public`: Public access flag
- `access_level`: restricted, confidential, secret
- `expires_at`: Optional expiry date
- `encryption_key_id`: Encryption key identifier
- `version`: Version number for versioning
### document_access_grants Table
- `document_id`: Reference to document
- `grantee_type`: User or Role (polymorphic)
- `grantee_id`: ID of grantee
- `grant_type`: view, download, edit, delete, share
- `status`: active, revoked, expired
- `expires_at`: Optional expiry
- `granted_by`: User who granted access
- `access_conditions`: JSON conditions (IP, time, day restrictions)
- `max_access_count`: Optional access limit
- `access_count`: Current access count
### document_access_logs Table
- `document_id`: Reference to document
- `user_id`: User who accessed
- `action`: Action performed
- `ip_address`: IP address
- `user_agent`: Browser user agent
- `document_access_grant_id`: Grant used (if any)
- `success`: Success/failure status
- `failure_reason`: Reason for failure
- `accessed_at`: Timestamp
## Components Created
### Models
1. **Document** (`app/Models/Document.php`)
- Encryption/decryption accessors and mutators
- Access control methods
- Versioning support
- Audit logging
2. **DocumentAccessGrant** (`app/Models/DocumentAccessGrant.php`)
- Grant validation
- Access condition checking
- Expiry management
3. **DocumentAccessLog** (`app/Models/DocumentAccessLog.php`)
- Audit trail logging
- Query scopes for filtering
### Services
1. **DocumentEncryptionService** (`app/Services/DocumentEncryptionService.php`)
- Encrypt/decrypt strings
- Encrypt/decrypt arrays
- File path encryption
- Hash generation for integrity
### Policies
1. **DocumentPolicy** (`app/Policies/DocumentPolicy.php`)
- view, viewAny, create, update, delete
- download, share, grantAccess, revokeAccess
- viewAccessLogs, restore, forceDelete
### Controllers
1. **DocumentController** (`app/Http/Controllers/DocumentController.php`)
- index, create, store, show, edit, update, destroy
- download, grantAccess, revokeAccess, accessLogs, bulkDelete
### Views
1. **index.blade.php** - Document listing with filters
2. **create.blade.php** - Document upload form
3. **edit.blade.php** - Document edit form
4. **show.blade.php** - Document details with access grants
5. **access-logs.blade.php** - Access logs view
### Migrations
1. **create_documents_table** - Main documents table
2. **create_document_access_grants_table** - Access grants
3. **create_document_access_logs_table** - Audit logs
### Configuration
- Added `secure` disk to `config/filesystems.php`
- Storage path: `storage/app/secure`
- Visibility: private
### Routes
All routes under `/company-admin/documents`:
- GET `/` - Index
- GET `/create` - Create form
- POST `/` - Store
- GET `/{document}` - Show
- GET `/{document}/edit` - Edit form
- PUT `/{document}` - Update
- DELETE `/{document}` - Delete
- GET `/{document}/download` - Download
- POST `/{document}/grant-access` - Grant access
- POST `/{document}/revoke-access/{grant}` - Revoke access
- GET `/{document}/access-logs` - Access logs
- POST `/bulk-delete` - Bulk delete
### Translations
Added comprehensive translations for:
- English (`resources/lang/en.json`)
- Bulgarian (`resources/lang/bg.json`)
## Access Control Logic
### Default Access
- **Document Owner**: Full access to own documents
- **Company Admins**: Full access to company documents
- **Explicit Grants**: Required for other users/roles
### Grant Validation
- Grant must be active
- Grant must not be expired
- Access count must not exceed limit
- Access conditions must be met (IP, time, day)
### Policy Checks
All actions go through DocumentPolicy:
- `view()`: Check view grant or ownership
- `download()`: Check download grant or ownership
- `edit()`: Check edit grant or ownership
- `delete()`: Check delete grant or ownership
- `share()`: Check share grant or ownership
- `grantAccess()`: Only owner or company admin
- `revokeAccess()`: Only owner or company admin
- `viewAccessLogs()`: Only owner or company admin
## File Storage
### Secure Disk Configuration
```php
'secure' => [
'driver' => 'local',
'root' => storage_path('app/secure'),
'visibility' => 'private',
'throw' => false,
'report' => false,
],
```
### File Upload Process
1. File uploaded via form
2. Stored in `documents/{company_id}/` on secure disk
3. File path encrypted before storing in database
4. File name encrypted before storing
5. Metadata encrypted
### File Download Process
1. User requests download
2. Policy check performed
3. File path decrypted
4. File retrieved from secure disk
5. Access logged
6. File served to user
## Security Best Practices Implemented
1. **Encryption at Rest**: All sensitive data encrypted
2. **Encryption in Transit**: HTTPS assumed for production
3. **Least Privilege**: Default deny, explicit allow
4. **Audit Trail**: Complete logging of all actions
5. **Multivendor Isolation**: Company-scoped data access
6. **Input Validation**: Server-side validation on all inputs
7. **CSRF Protection**: All forms use CSRF tokens
8. **Authorization**: Policy-based access control
9. **Soft Deletes**: Documents soft-deleted by default
10. **Version Control**: Document versioning support
## Usage Example
### Upload a Document
```php
// User navigates to /company-admin/documents/create
// Fills in form with file, type, description, access level
// Document is encrypted and stored
// Access logged
```
### Grant Access
```php
// Document owner or admin clicks "Grant Access"
// Selects user/role and permission type
// Sets optional expiry and access limits
// Grant created and logged
```
### Download Document
```php
// User with access grant requests download
// Policy validates access
// File path decrypted
// File retrieved from secure storage
// Access logged
// File served
```
## Next Steps for Deployment
1. Run migrations:
```bash
php artisan migrate
```
2. Ensure secure storage directory exists:
```bash
php artisan storage:link
mkdir -p storage/app/secure
```
3. Set appropriate permissions on storage directories
4. Test encryption/decryption functionality
5. Test access control with different user roles
6. Configure backup strategy for encrypted documents
7. Set up monitoring for access logs
## Notes
- Laravel's auto-discovery will automatically find the DocumentPolicy
- The secure disk should be backed up separately with encryption keys
- Consider implementing document expiration job for automatic cleanup
- Consider implementing document version restoration feature
- Email notifications can be added for access grants and expiry warnings