Share
## https://sploitus.com/exploit?id=6E6AA518-4140-5382-A418-12B7A597AE98
# SafeVault - Security and Authentication Capstone Project

A production-ready Flask-based authentication and authorization system demonstrating enterprise-grade security practices for the Coursera "Security and Authentication with Microsoft Copilot" course.

## ๐ŸŽฏ Project Overview

SafeVault implements a complete secure user authentication and authorization system with:

- **Secure User Registration & Login** - Password hashing with werkzeug, JWT tokens
- **Role-Based Access Control (RBAC)** - Admin and user roles with decorators
- **SQL Injection Prevention** - Parameterized queries for all database operations
- **XSS Prevention** - Input validation and output escaping
- **Comprehensive Testing** - 30+ security tests covering all vulnerabilities
- **Audit Logging** - Complete security event tracking

## ๐Ÿ“ Project Structure

```
SafeVault/
โ”œโ”€โ”€ app.py                    # Main Flask application & routes
โ”œโ”€โ”€ auth.py                   # JWT authentication & RBAC
โ”œโ”€โ”€ models.py                 # SQLite models with parameterized queries
โ”œโ”€โ”€ validators.py             # Marshmallow input validation schemas
โ”œโ”€โ”€ requirements.txt          # Python dependencies
โ”œโ”€โ”€ .gitignore               # Git configuration
โ”œโ”€โ”€ README.md                # This file
โ”œโ”€โ”€ SECURITY_FIXES.md        # Detailed vulnerability breakdown
โ””โ”€โ”€ tests/
    โ””โ”€โ”€ test_security.py     # Comprehensive security test suite
```

## ๐Ÿ› ๏ธ Tech Stack

- **Python 3.10+** - Programming language
- **Flask 2.3** - Web framework
- **SQLite** - Database
- **Flask-JWT-Extended 4.5** - JWT authentication
- **Marshmallow 3.20** - Input validation
- **werkzeug 2.3** - Password hashing
- **pytest 7.4** - Testing framework

## ๐Ÿš€ Quick Start

### Prerequisites

- Python 3.10 or higher
- pip (Python package manager)

### Installation

1. **Clone or download the project**
   ```bash
   cd SafeVault
   ```

2. **Create virtual environment** (recommended)
   ```bash
   python -m venv venv
   # On Windows:
   venv\Scripts\activate
   # On macOS/Linux:
   source venv/bin/activate
   ```

3. **Install dependencies**
   ```bash
   pip install -r requirements.txt
   ```

4. **Run the application**
   ```bash
   python app.py
   ```
   
   Server will start at `http://127.0.0.1:5000`

5. **Run security tests**
   ```bash
   python -m pytest tests/test_security.py -v
   ```

## ๐Ÿ“ Coursera Project Summary

### **Vulnerabilities Identified:**

1. **SQL Injection (SQLi)**
   - Risk: Attacker could execute arbitrary SQL commands
   - Attack Surface: Login username, search fields, registration data
   - Impact: Unauthorized data access, data modification, or deletion

2. **Cross-Site Scripting (XSS)**
   - Risk: Attacker could execute malicious scripts in user browsers
   - Attack Surface: User profile names, search results, displayed data
   - Impact: Session hijacking, credential theft, malware injection

3. **Broken Authentication**
   - Risk: Weak passwords, plaintext password storage
   - Attack Surface: Registration and login endpoints
   - Impact: Unauthorized account access

4. **Insecure Direct Object References (IDOR)**
   - Risk: Direct access to user resources without proper authorization
   - Attack Surface: Admin endpoints, audit logs
   - Impact: Unauthorized data access to other users' information

5. **Insufficient Access Control**
   - Risk: Non-admin users accessing admin-only endpoints
   - Attack Surface: All admin endpoints (`/api/admin/*`)
   - Impact: Privilege escalation

### **Fixes Applied:**

#### 1. SQL Injection Prevention
**Implementation:** Parameterized Queries (? Placeholders)

```python
# โŒ VULNERABLE (NEVER USE)
username = user_input  # "admin' OR '1'='1"
query = f"SELECT * FROM users WHERE username = '{username}'"
cursor.execute(query)  # SQL injection happens here!

# โœ… SECURE (USED IN SAFEVAULT)
query = "SELECT * FROM users WHERE username = ?"
cursor.execute(query, (username,))  # Data and code are separated
```

All 15+ database queries in `models.py` use parameterized queries:
- `UserModel.create_user()` - User creation
- `UserModel.get_user_by_username()` - User lookup
- `UserModel.search_users()` - Safe search with LIKE
- `AuditLog.log_action()` - Audit trail recording

**Testing:** `test_sql_injection_in_login_username`, `test_sql_injection_union_in_login`, `test_sql_injection_drop_table`

#### 2. XSS Prevention
**Implementation:** Input Validation + Output Escaping

**Input Layer (validators.py):**
```python
# Marshmallow schemas enforce strict data types
class FullNameField(fields.String):
    def _deserialize(self, value, attr, data, **kwargs):
        # Only allow letters, spaces, hyphens, apostrophes
        if not re.match(r"^[a-zA-Z\s\-']+$", value):
            raise ValidationError("Full name contains invalid characters")
        return value
```

**Output Layer (app.py):**
```python
# All user-generated content is HTML-escaped
return jsonify({
    'user': {
        'username': html.escape(user['username']),  # Converts ` - Admin only
- `/api/admin/audit-logs/` - Admin only
- `/api/profile` - Any authenticated user

**Testing:** `test_non_admin_cannot_access_dashboard`, `test_admin_can_access_dashboard`, `test_rbac_authorization`

#### 5. Input Validation with Marshmallow
**Implementation:** Schema-based validation before database operations

```python
# Define strict validation schema
class RegisterSchema(Schema):
    username = UsernameField(required=True)     # 3-32 alphanumeric + _
    email = StrictEmail(required=True)          # RFC format, max 254 chars
    password = PasswordField(required=True)     # Strong policy
    full_name = FullNameField(required=True)    # Letters, spaces, hyphens only

# Validate before use
is_valid, data, error_msg = validate_input(request_json, RegisterSchema())
if not is_valid:
    return {'error': error_msg}, 400  # Reject invalid input
```

**Testing:** `test_invalid_email_format`, `test_password_too_short`, `test_username_invalid_characters`

#### 6. Error Handling (No Sensitive Information Leakage)
**Implementation:** Generic error messages to clients

```python
# โŒ VULNERABLE - Leaks implementation details
except Exception as e:
    return {'error': str(e)}, 500  # "Column 'xyz' not found"

# โœ… SECURE - Generic message
except Exception as e:
    print(f"Error: {str(e)}")  # Log internally
    return {'error': 'An error occurred'}, 500  # Generic to client
```

All error handlers in `app.py` return generic messages without stack traces.

#### 7. Audit Logging
**Implementation:** Complete security event tracking

```python
# Log all authentication attempts
AuditLog.log_action(
    user_id=user_id,
    action='login_attempt',
    resource='authentication',
    status='success' or 'failure',
    ip_address=request.remote_addr
)
```

**Events Logged:**
- User registration
- Login attempts (success/failure)
- Profile updates
- Authorization failures
- Admin access

**Testing:** `test_login_logged`, `test_failed_login_logged`

### **How Copilot Assisted:**

1. **Code Generation & Templates**
   - Generated secure Flask route templates with proper error handling
   - Created Marshmallow schema base classes with validation best practices
   - Provided parameterized query examples for all common CRUD operations

2. **Security Best Practices**
   - Suggested werkzeug for password hashing (industry standard)
   - Recommended JWT for stateless authentication
   - Advised on XSS prevention: input validation + output escaping

3. **RBAC Implementation**
   - Designed `@require_role()` decorator pattern
   - Showed JWT claims usage for role extraction
   - Provided role-based endpoint protection examples

4. **Testing Strategy**
   - Generated comprehensive pytest fixtures for test setup
   - Created SQL injection test patterns
   - Provided XSS test cases with actual attack strings
   - Built RBAC test scenarios

5. **Documentation**
   - Generated inline code comments explaining security rationale
   - Created VULNERABLE vs SECURE code examples
   - Provided detailed docstrings for all security functions

## ๐Ÿ“Š Security Test Coverage

### Test Suite: 30+ Tests

| Category | Tests | Status |
|----------|-------|--------|
| Valid Authentication | 3 | โœ… |
| Input Validation | 8 | โœ… |
| SQL Injection | 5 | โœ… |
| XSS Prevention | 3 | โœ… |
| RBAC Authorization | 6 | โœ… |
| Authentication Failures | 3 | โœ… |
| Audit Logging | 2 | โœ… |

### Running Tests

```bash
# Run all tests with verbose output
python -m pytest tests/test_security.py -v

# Run specific test class
python -m pytest tests/test_security.py::TestSQLInjectionPrevention -v

# Run with coverage report
python -m pytest tests/test_security.py --cov=. --cov-report=html
```

### Example Test: SQL Injection Prevention

```python
def test_sql_injection_in_login_username(self, client):
    """Test SQL injection attempt in login username field."""
    response = client.post('/api/auth/login', json={
        'username': "admin' OR '1'='1",  # Malicious input
        'password': 'anypassword'
    })
    
    # Parameterized queries prevent SQL execution
    assert response.status_code == 401
    data = json.loads(response.data)
    assert 'Invalid credentials' in data.get('error', '')
```

## ๐Ÿ”’ Security Features Checklist

- โœ… **Parameterized Queries** - All 15+ SQL operations use `?` placeholders
- โœ… **Password Hashing** - PBKDF2 with SHA256, never stored plaintext
- โœ… **Input Validation** - Marshmallow schemas for all endpoints
- โœ… **Output Escaping** - `html.escape()` on all user-generated content
- โœ… **JWT Authentication** - Secure token-based authentication
- โœ… **RBAC** - Role-based access control with decorators
- โœ… **Audit Logging** - Complete security event tracking
- โœ… **Error Handling** - No sensitive information leakage
- โœ… **CORS Ready** - Configured for production CORS
- โœ… **Comprehensive Tests** - 30+ security test cases

## ๐Ÿ“š API Endpoints

### Authentication

```bash
# Register
POST /api/auth/register
Content-Type: application/json
{
  "username": "john_doe",
  "email": "john@example.com",
  "password": "SecurePass123!",
  "password_confirm": "SecurePass123!",
  "full_name": "John Doe"
}

# Login
POST /api/auth/login
{
  "username": "john_doe",
  "password": "SecurePass123!"
}
# Returns: {"access_token": "eyJ0eXAiOiJKV1QiLCJhbGc..."}
```

### User Profile

```bash
# Get Profile (requires JWT token)
GET /api/profile
Authorization: Bearer 

# Update Profile
PUT /api/profile
Authorization: Bearer 
{
  "full_name": "John Smith"
}

# Search Users
GET /api/users/search?q=john
Authorization: Bearer 
```

### Admin Endpoints (Admin only)

```bash
# Admin Dashboard
GET /api/admin/dashboard
Authorization: Bearer 

# List All Users
GET /api/admin/users
Authorization: Bearer 

# Get User Details
GET /api/admin/users/
Authorization: Bearer 

# View Audit Logs
GET /api/admin/audit-logs/
Authorization: Bearer 
```

## ๐Ÿงช Example Usage

### 1. Register a User

```bash
curl -X POST http://localhost:5000/api/auth/register \
  -H "Content-Type: application/json" \
  -d '{
    "username": "alice",
    "email": "alice@example.com",
    "password": "SecurePass123!",
    "password_confirm": "SecurePass123!",
    "full_name": "Alice Smith"
  }'
```

### 2. Login

```bash
curl -X POST http://localhost:5000/api/auth/login \
  -H "Content-Type: application/json" \
  -d '{
    "username": "alice",
    "password": "SecurePass123!"
  }'
```

### 3. Access Protected Route

```bash
curl -X GET http://localhost:5000/api/profile \
  -H "Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGc..."
```

## ๐Ÿ“‹ Grading Rubric Mapping

| Requirement | Points | Implementation | File(s) |
|------------|--------|----------------|---------|
| GitHub Ready | 5 | Clean structure, `.gitignore`, `requirements.txt` | Project root |
| Secure Code | 5 | Input validation, parameterized queries | `validators.py`, `models.py` |
| AuthN/AuthZ + RBAC | 5 | JWT login/register, `@require_role` decorator | `auth.py`, `app.py` |
| Debugged Vulnerabilities | 5 | VULNERABLE vs SECURE comments, SECURITY_FIXES.md | `models.py`, `SECURITY_FIXES.md` |
| Security Tests | 5 | 30+ pytest cases (SQLi, XSS, RBAC, auth) | `tests/test_security.py` |
| Coursera Summary | 5 | This README.md section | `README.md` |

**Total: 30 Points**

## ๐Ÿ”ง Production Considerations

1. **Environment Variables**
   ```bash
   export JWT_SECRET_KEY="your-long-random-secret-key"
   export FLASK_ENV="production"
   ```

2. **Database**
   - Use PostgreSQL/MySQL for production (instead of SQLite)
   - Implement connection pooling
   - Regular backups

3. **Server**
   - Use Gunicorn or uWSGI
   - Deploy behind nginx/Apache
   - Enable HTTPS/TLS only

4. **Monitoring**
   - Log all security events
   - Set up alerts for suspicious activity
   - Regular security audits

## ๐Ÿ“– Files Reference

- **app.py** (450 lines) - Main Flask application with all routes
- **auth.py** (380 lines) - Authentication and RBAC implementation
- **models.py** (350 lines) - Parameterized database queries
- **validators.py** (280 lines) - Marshmallow input validation
- **tests/test_security.py** (600 lines) - Comprehensive test suite

## ๐ŸŽ“ Learning Outcomes

After completing this project, you will understand:

1. How to prevent SQL injection with parameterized queries
2. How to prevent XSS with input validation and output escaping
3. How to implement secure authentication with JWT
4. How to implement Role-Based Access Control (RBAC)
5. How to validate user input with Marshmallow
6. How to hash passwords securely
7. How to write comprehensive security tests
8. How to audit and log security events

## ๐Ÿ“ License

This project is provided for educational purposes as part of the Coursera "Security and Authentication with Microsoft Copilot" course.

## ๐Ÿค Support

For questions or issues:
1. Review the SECURITY_FIXES.md for detailed vulnerability explanations
2. Check test_security.py for usage examples
3. Review inline code comments for implementation details

---

**Created for Coursera's "Security and Authentication with Microsoft Copilot" Course**
**Status: Production-Ready โœ…**