| title | Security Specifications and Auditing |
|---|---|
| description | Technical reference for authentication security, password cryptography, session guards, and CSRF protection. |
| audience | Security Architects, Penetration Testers, Core Developers |
| last_updated | 2026-07-10 |
| related_documents | [Authentication](authentication.md), [Developer Guide](developer-guide.md) |
Home | Architecture | Modules | AI Pipelines | Database | API | Deployment | Roadmap | Developer Guide | Security | Testing | Performance
- Overview
- Authentication Role Separation
- Session Protections
- Password Cryptography & Storage
- Cross-Site Request Forgery (CSRF) Prevention
- Cross-Site Scripting (XSS) Defenses
- SQL Injection (SQLi) Protections
- Cache Control and Secure Headers
- Future Improvements
The Smart Farming AI application implements security controls at multiple layers, protecting user data, safeguarding sessions, and securing endpoints.
Access control is enforced using decorators that check the user's role before executing route logic:
[Incoming Request] ──> [Decorators Validation] ──> [Permit / Block Access]
Routes are protected by decorators in app/utils/decorators.py:
@farmer_required: Restricts routes under/farmerto users withsession["user_type"] == "farmer".@govt_required: Restricts routes under/governmentto users withsession["user_type"] == "govt".@admin_required: Restricts routes under/adminto users withsession["user_type"] == "admin".
User sessions are secured using the following configuration properties:
- Inactivity Timeout: The
@session_requireddecorator checks thelast_activitytimestamp and invalidates sessions after 30 minutes of inactivity. HttpOnlyFlag: Set toTrueto prevent client-side scripts from reading session cookies.SecureFlag: Set toTrueto ensure session cookies are only transmitted over HTTPS connections.SameSiteAttribute: Set toLaxto mitigate Cross-Site Request Forgery (CSRF) risks.
User credentials are secure-hashed before being written to the database:
- Hashing Algorithm: Uses the scrypt key derivation function via Werkzeug's security package.
- Format: Hashes follow the
scrypt:32768:8:1$[salt]$[hash]format. - Verification: User logins are verified using
check_password_hashto protect against timing attacks.
class GovtUser(User):
# Password property setter generates the scrypt hash
@password.setter
def password(self, password):
self.password_hash = generate_password_hash(password)The application implements CSRF protection across all forms:
- Form Bindings: Uses WTForms with Flask-WTF to automatically generate CSRF tokens.
- Token Verification: Forms validate the request token on submission:
<form method="POST" action="/auth/login"> {{ form.csrf_token }} <!-- Form Input Fields --> </form>
- API Protection: AJAX requests to endpoint routes include the CSRF token in the request headers.
To mitigate Cross-Site Scripting (XSS) risks, the application implements the following defenses:
- Output Escaping: Jinja2 templates escape dynamic database fields by default.
- API Escaping: The FarmBot chatbot API escapes all AI-generated response text using
html.escapebefore returning responses to the user:# chatbot_ai.py return html.escape(response.text.strip())
The application uses SQLAlchemy to build database queries:
- Parametrized Queries: SQLAlchemy uses parametrized queries and prepared statements under the hood, protecting routes against SQL injection attacks.
- Raw SQL Prevention: The application does not use raw SQL string concatenation, mitigating the risk of injection vulnerabilities.
To prevent users from viewing private pages after logging out, the /auth/logout route invalidates local session caches:
@auth_bp.route('/logout')
def logout():
session.clear()
response = redirect(url_for('auth.login'))
response.headers['Cache-Control'] = 'no-store, no-cache, must-revalidate'
response.headers['Pragma'] = 'no-cache'
response.headers['Expires'] = '0'
response.delete_cookie('session')
return response- HTTP Strict Transport Security (HSTS): Configure Caddy to enforce HTTPS connections by injecting HSTS headers.
- Content Security Policy (CSP): Implement a strict Content Security Policy to restrict the execution of untrusted external scripts.
Previous: Developer Guide | Next: Testing Suite