Skip to content

Commit dd2d5e4

Browse files
Merge pull request #19 from CivicDataLab/security_policy
add security policy
2 parents bbb98e3 + 3dfce6c commit dd2d5e4

File tree

1 file changed

+295
-0
lines changed

1 file changed

+295
-0
lines changed

SECURITY.md

Lines changed: 295 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,295 @@
1+
# Security Policy
2+
3+
## Supported Versions
4+
5+
We release patches for security vulnerabilities in the following versions:
6+
7+
| Version | Supported |
8+
| ------- | ------------------ |
9+
| 1.x.x | :white_check_mark: |
10+
| < 1.0 | :x: |
11+
12+
## Reporting a Vulnerability
13+
14+
We take the security of DataSpace Backend seriously. If you believe you have found a security vulnerability, please report it to us as described below.
15+
16+
### How to Report
17+
18+
**Please do not report security vulnerabilities through public GitHub issues.**
19+
20+
Instead, please report them via email to:
21+
- **Email**: [email protected]
22+
- **Subject**: [SECURITY] DataSpace Backend - Brief Description
23+
24+
You should receive a response within 48 hours. If for some reason you do not, please follow up via email to ensure we received your original message.
25+
26+
### What to Include
27+
28+
Please include the following information in your report:
29+
30+
- Type of vulnerability (e.g., SQL injection, authentication bypass, privilege escalation, etc.)
31+
- Full paths of source file(s) related to the vulnerability
32+
- The location of the affected source code (tag/branch/commit or direct URL)
33+
- Step-by-step instructions to reproduce the issue
34+
- Proof-of-concept or exploit code (if possible)
35+
- Impact of the issue, including how an attacker might exploit it
36+
37+
### Response Process
38+
39+
1. **Acknowledgment**: We will acknowledge receipt of your vulnerability report within 48 hours
40+
2. **Assessment**: Our security team will investigate and assess the vulnerability
41+
3. **Updates**: We will keep you informed about the progress of fixing the vulnerability
42+
4. **Resolution**: Once fixed, we will notify you and publicly disclose the vulnerability (with credit to you, if desired)
43+
44+
## Security Best Practices
45+
46+
### For Contributors
47+
48+
When contributing to this project, please follow these security guidelines:
49+
50+
#### Authentication & Authorization
51+
- Never commit credentials, API keys, or secrets to the repository
52+
- Use environment variables for all sensitive configuration (`.env` file)
53+
- Implement proper permission checks for all API endpoints
54+
- Validate Keycloak tokens on every protected endpoint
55+
- Use role-based access control (RBAC) appropriately
56+
- Never bypass authentication checks, even in development
57+
58+
#### Data Protection
59+
- Always use parameterized queries to prevent SQL injection
60+
- Sanitize and validate all user inputs
61+
- Encrypt sensitive data at rest and in transit
62+
- Never log sensitive information (passwords, tokens, PII)
63+
- Implement proper data access controls
64+
- Use Django's built-in security features
65+
66+
#### API Security
67+
- Validate all GraphQL queries and mutations
68+
- Implement proper rate limiting
69+
- Use CORS policies appropriately
70+
- Validate file uploads (type, size, content)
71+
- Implement proper error handling without exposing sensitive details
72+
- Use HTTPS only in production
73+
74+
#### Dependencies
75+
- Regularly update dependencies to patch known vulnerabilities
76+
- Run security audits before deploying
77+
- Review security advisories for critical dependencies
78+
- Pin dependency versions in requirements.txt
79+
- Use virtual environments for isolation
80+
81+
#### Code Quality
82+
- Follow Django security best practices
83+
- Use Django's ORM to prevent SQL injection
84+
- Implement CSRF protection for state-changing operations
85+
- Validate and sanitize all user-generated content
86+
- Use type hints and static analysis (mypy)
87+
- Follow the principle of least privilege
88+
89+
### For Deployment
90+
91+
#### Environment Configuration
92+
- Use strong, unique `SECRET_KEY` in production
93+
- Configure Keycloak with proper security settings
94+
- Enable HTTPS and HSTS in production
95+
- Set `DEBUG=False` in production
96+
- Configure proper database credentials
97+
- Use secure session and cookie settings
98+
- Set appropriate CORS and CSRF settings
99+
100+
#### Database Security
101+
- Use strong database passwords
102+
- Limit database user permissions
103+
- Enable SSL/TLS for database connections
104+
- Regular database backups
105+
- Implement proper data retention policies
106+
- Use connection pooling securely
107+
108+
#### Infrastructure
109+
- Keep Python and system packages updated
110+
- Use security headers (HSTS, X-Frame-Options, CSP, etc.)
111+
- Implement rate limiting at multiple levels
112+
- Regular security audits and penetration testing
113+
- Monitor for suspicious activity
114+
- Use a Web Application Firewall (WAF)
115+
116+
#### Monitoring & Logging
117+
- Enable OpenTelemetry for distributed tracing
118+
- Implement structured logging with `structlog`
119+
- Monitor for security events and anomalies
120+
- Set up alerts for critical security issues
121+
- Regular log analysis
122+
- Exclude sensitive data from logs
123+
124+
## Known Security Considerations
125+
126+
### Authentication System
127+
- **Keycloak Integration**: All authentication is handled through Keycloak
128+
- **Token Validation**: JWT tokens are validated on every request
129+
- **No Development Bypass**: No fallback authentication mechanisms
130+
- **User Synchronization**: User data synced from Keycloak using KeycloakAdmin
131+
- **Session Management**: Follows OWASP session management guidelines
132+
133+
### API Security
134+
- **GraphQL**: Implements query complexity limits and depth restrictions
135+
- **REST API**: Rate limiting and throttling enabled
136+
- **File Uploads**: Validated for type, size, and content
137+
- **Data Versioning**: DVC integration for data versioning and tracking
138+
139+
### Data Protection
140+
- **Encryption**: All data encrypted in transit (TLS 1.2+)
141+
- **Database**: PostgreSQL with proper access controls
142+
- **Search**: Elasticsearch with authentication enabled
143+
- **Caching**: Redis with secure configuration
144+
- **File Storage**: Secure file handling and validation
145+
146+
### Third-Party Services
147+
- **Keycloak**: Ensure proper realm and client configuration
148+
- **Elasticsearch**: Enable security features and authentication
149+
- **Redis**: Use password protection and disable dangerous commands
150+
- **OpenTelemetry**: Configure to exclude sensitive data
151+
- **DVC**: Secure data versioning and storage
152+
153+
## Security Checklist for Pull Requests
154+
155+
Before submitting a PR, ensure:
156+
157+
- [ ] No hardcoded secrets or credentials
158+
- [ ] All user inputs are validated and sanitized
159+
- [ ] SQL injection prevention (use ORM or parameterized queries)
160+
- [ ] Authentication and authorization checks are in place
161+
- [ ] Dependencies are up to date and audited
162+
- [ ] Error messages don't expose sensitive information
163+
- [ ] Rate limiting is implemented where needed
164+
- [ ] CORS and CSRF policies are properly configured
165+
- [ ] Type hints are used and mypy checks pass
166+
- [ ] Security-related changes are documented
167+
- [ ] Tests include security scenarios
168+
169+
## Common Vulnerabilities to Avoid
170+
171+
### SQL Injection
172+
```python
173+
# ❌ Bad - Vulnerable to SQL injection
174+
User.objects.raw(f"SELECT * FROM users WHERE username = '{username}'")
175+
176+
# ✅ Good - Use ORM or parameterized queries
177+
User.objects.filter(username=username)
178+
```
179+
180+
### XSS Prevention
181+
```python
182+
# ❌ Bad - Unescaped user input
183+
return HttpResponse(f"<h1>Hello {user_input}</h1>")
184+
185+
# ✅ Good - Use Django templates or escape manually
186+
from django.utils.html import escape
187+
return HttpResponse(f"<h1>Hello {escape(user_input)}</h1>")
188+
```
189+
190+
### Authentication Bypass
191+
```python
192+
# ❌ Bad - Skipping authentication
193+
if settings.DEBUG:
194+
return True # Allow access in debug mode
195+
196+
# ✅ Good - Always validate authentication
197+
if not request.user.is_authenticated:
198+
raise PermissionDenied()
199+
```
200+
201+
### Insecure Direct Object References
202+
```python
203+
# ❌ Bad - No authorization check
204+
dataset = Dataset.objects.get(id=dataset_id)
205+
206+
# ✅ Good - Check user permissions
207+
dataset = Dataset.objects.get(id=dataset_id)
208+
if not user.has_perm('view_dataset', dataset):
209+
raise PermissionDenied()
210+
```
211+
212+
## Vulnerability Disclosure Policy
213+
214+
When we receive a security bug report, we will:
215+
216+
1. Confirm the problem and determine affected versions
217+
2. Audit code to find similar problems
218+
3. Prepare fixes for all supported versions
219+
4. Release new versions as soon as possible
220+
5. Prominently announce the issue in release notes
221+
6. Update this security policy if needed
222+
223+
## Security Updates
224+
225+
Security updates will be released as patch versions and will be clearly marked in the release notes.
226+
227+
Subscribe to our GitHub releases to stay informed about security updates.
228+
229+
## Security Testing
230+
231+
We recommend the following security testing practices:
232+
233+
### Static Analysis
234+
```bash
235+
# Run mypy for type checking
236+
mypy .
237+
238+
# Run flake8 for code quality
239+
flake8 .
240+
241+
# Run bandit for security issues
242+
bandit -r api/ authorization/ search/
243+
```
244+
245+
### Dependency Scanning
246+
```bash
247+
# Check for known vulnerabilities
248+
pip-audit
249+
250+
# Or use safety
251+
safety check
252+
```
253+
254+
### Pre-commit Hooks
255+
We use pre-commit hooks to enforce security checks. Install them with:
256+
```bash
257+
pre-commit install
258+
```
259+
260+
## Compliance
261+
262+
This project aims to comply with:
263+
- OWASP Top 10 security risks
264+
- GDPR data protection requirements
265+
- Industry-standard security practices
266+
- Django security best practices
267+
268+
## Additional Resources
269+
270+
- [OWASP Top 10](https://owasp.org/www-project-top-ten/)
271+
- [Django Security Documentation](https://docs.djangoproject.com/en/stable/topics/security/)
272+
- [GraphQL Security Best Practices](https://cheatsheetseries.owasp.org/cheatsheets/GraphQL_Cheat_Sheet.html)
273+
- [Keycloak Security Documentation](https://www.keycloak.org/docs/latest/server_admin/)
274+
- [Python Security Best Practices](https://python.readthedocs.io/en/stable/library/security_warnings.html)
275+
276+
## Security Contacts
277+
278+
For any security-related questions or concerns, please contact:
279+
- **Email**: [email protected]
280+
- **GitHub**: [CivicDataLab/DataSpaceBackend](https://github.com/CivicDataLab/DataSpaceBackend)
281+
282+
## Security Incident Response
283+
284+
In case of a security incident:
285+
286+
1. **Immediate Response**: Isolate affected systems
287+
2. **Assessment**: Determine scope and impact
288+
3. **Containment**: Prevent further damage
289+
4. **Eradication**: Remove the threat
290+
5. **Recovery**: Restore normal operations
291+
6. **Post-Incident**: Document and learn from the incident
292+
293+
---
294+
295+
Last Updated: October 2025

0 commit comments

Comments
 (0)