safeuploads 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,7 @@
1
+ Copyright (c) 2025 João Vitória Silva
2
+
3
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
4
+
5
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
6
+
7
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
@@ -0,0 +1,170 @@
1
+ Metadata-Version: 2.4
2
+ Name: safeuploads
3
+ Version: 0.1.0
4
+ Summary: A comprehensive file security system for validating uploads and preventing attacks
5
+ License: MIT
6
+ License-File: LICENSE.md
7
+ Author: João Vitória Silva
8
+ Author-email: joao@endurain.com
9
+ Requires-Python: >=3.13
10
+ Classifier: License :: OSI Approved :: MIT License
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Programming Language :: Python :: 3.13
13
+ Classifier: Programming Language :: Python :: 3.14
14
+ Provides-Extra: dev
15
+ Provides-Extra: fastapi
16
+ Requires-Dist: fastapi (>=0.110,<1.0) ; extra == "fastapi"
17
+ Requires-Dist: pytest (>=8.0,<9.0) ; extra == "dev"
18
+ Requires-Dist: pytest-asyncio (>=0.23,<1.0) ; extra == "dev"
19
+ Requires-Dist: pytest-cov (>=4.1,<5.0) ; extra == "dev"
20
+ Requires-Dist: python-magic (>=0.4.27,<0.5.0)
21
+ Description-Content-Type: text/markdown
22
+
23
+ # safeuploads
24
+
25
+ ![License](https://img.shields.io/github/license/joaovitoriasilva/safeuploads)
26
+ [![GitHub release](https://img.shields.io/github/v/release/joaovitoriasilva/safeuploads)](https://github.com/joaovitoriasilva/safeuploads/releases)
27
+ [![GitHub stars](https://img.shields.io/github/stars/joaovitoriasilva/safeuploads.svg?style=social&label=Star)](https://github.com/joaovitoriasilva/safeuploads/stargazers)
28
+
29
+ Secure file upload validation for Python 3.13+ applications. Catches dangerous filenames, malicious extensions, Windows reserved names, and compression-based attacks before you accept an upload.
30
+
31
+ ## Features
32
+
33
+ - **Framework-agnostic** async validation (FastAPI, generic)
34
+ - Filename sanitization and Unicode security checks
35
+ - Extension validation with configurable allow/block lists
36
+ - ZIP bomb detection and content inspection
37
+ - MIME type verification with signature validation
38
+ - Rich exception hierarchy for precise error handling
39
+ - Zero configuration required—secure defaults out of the box
40
+
41
+ ## Installation
42
+
43
+ ```bash
44
+ pip install safeuploads
45
+ ```
46
+
47
+ For FastAPI integration:
48
+ ```bash
49
+ pip install safeuploads[fastapi]
50
+ ```
51
+
52
+ ## Quick Start
53
+
54
+ ```python
55
+ from fastapi import FastAPI, UploadFile, HTTPException
56
+ from safeuploads import FileValidator
57
+ from safeuploads.exceptions import FileValidationError
58
+
59
+ app = FastAPI()
60
+ validator = FileValidator()
61
+
62
+ @app.post("/upload")
63
+ async def upload_image(file: UploadFile):
64
+ try:
65
+ await validator.validate_image_file(file)
66
+ except FileValidationError as e:
67
+ raise HTTPException(status_code=400, detail=str(e))
68
+
69
+ return {"status": "success", "filename": file.filename}
70
+ ```
71
+
72
+ ## Configuration
73
+
74
+ ```python
75
+ from safeuploads import FileValidator, FileSecurityConfig
76
+
77
+ # Use default secure configuration
78
+ validator = FileValidator()
79
+
80
+ # Or customize limits
81
+ config = FileSecurityConfig()
82
+ config.limits.max_image_size = 10 * 1024 * 1024 # 10 MiB
83
+ config.limits.max_compression_ratio = 50
84
+
85
+ validator = FileValidator(config=config)
86
+ ```
87
+
88
+ ## Exception Handling
89
+
90
+ ```python
91
+ from safeuploads.exceptions import (
92
+ FileValidationError, # Base exception
93
+ FileSizeError, # File too large
94
+ ExtensionSecurityError, # Dangerous extension
95
+ ZipBombError, # Compression attack
96
+ )
97
+
98
+ try:
99
+ await validator.validate_image_file(file)
100
+ except FileSizeError as err:
101
+ return {"error": "File too large", "max_size": err.max_size}
102
+ except ExtensionSecurityError as err:
103
+ return {"error": "File type not allowed", "extension": err.extension}
104
+ except FileValidationError as err:
105
+ return {"error": str(err), "code": err.error_code}
106
+ ```
107
+
108
+ ## Current Status & Roadmap
109
+
110
+ ### What's Working
111
+
112
+ - **Filename Security**: Unicode normalization, directory traversal prevention, Windows reserved names blocking
113
+ - **Extension Validation**: Allow/block lists with configurable rules, dangerous extension detection
114
+ - **Compression Security**: ZIP bomb detection, nested archive inspection, size and ratio limits
115
+ - **Content Inspection**: Deep ZIP content analysis with configurable depth and entry limits
116
+ - **MIME Type Verification**: Magic number validation for common file types
117
+ - **Rich Exception System**: Machine-readable error codes with detailed context
118
+
119
+ ### Planned Improvements
120
+
121
+ #### Critical (Pre-1.0)
122
+ - **Streaming Validation**: Memory-efficient processing for large files to prevent resource exhaustion
123
+ - **Resource Limits**: CPU and memory monitoring during validation operations
124
+ - **Rate Limiting Guide**: Documentation and examples for production deployments
125
+
126
+ #### High Priority
127
+ - **Enhanced ZIP Security**: Protection against recursive ZIP structures and algorithmic complexity attacks
128
+ - **Audit Logging**: Structured logging for security-relevant events with request correlation
129
+ - **Performance Optimizations**: Pattern caching, compiled regex optimization, async I/O improvements
130
+
131
+ #### Future Enhancements
132
+ - **Additional File Types**: .gpx, .tcx, .fit, .gz
133
+ - **Content Analysis**: Malware signature detection, embedded script scanning
134
+ - **Fuzzing Tests**: Automated testing with malformed and malicious payloads
135
+ - **Security Documentation**: Threat model, architecture diagrams, integration security checklist
136
+
137
+ ### Production Readiness
138
+
139
+ **Status**: Beta - suitable for testing, not yet recommended for production use
140
+
141
+ **Before Production**:
142
+ 1. Address memory exhaustion vulnerability in ZIP inspection
143
+ 2. Implement streaming validation for large files
144
+ 3. Complete security audit and penetration testing
145
+
146
+ **Known Limitations**:
147
+ - No built-in rate limiting (must be implemented at application level)
148
+ - Limited to synchronous content reading in ZIP inspection
149
+ - Performance not yet optimized for high-throughput scenarios
150
+
151
+ ## Documentation
152
+
153
+ Full documentation available at [link to your docs].
154
+
155
+ ## Sponsors
156
+
157
+ A huge thank you to the project sponsors! Your support helps keep this project going.
158
+
159
+ Consider [sponsoring safeuploads on GitHub](https://github.com/sponsors/joaovitoriasilva) to ensure continuous development.
160
+
161
+ ## License
162
+
163
+ This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.
164
+
165
+ ## Contributing
166
+
167
+ Contributions welcome! See [Contributing Guidelines](CONTRIBUTING.md) for guidelines.
168
+
169
+
170
+
@@ -0,0 +1,147 @@
1
+ # safeuploads
2
+
3
+ ![License](https://img.shields.io/github/license/joaovitoriasilva/safeuploads)
4
+ [![GitHub release](https://img.shields.io/github/v/release/joaovitoriasilva/safeuploads)](https://github.com/joaovitoriasilva/safeuploads/releases)
5
+ [![GitHub stars](https://img.shields.io/github/stars/joaovitoriasilva/safeuploads.svg?style=social&label=Star)](https://github.com/joaovitoriasilva/safeuploads/stargazers)
6
+
7
+ Secure file upload validation for Python 3.13+ applications. Catches dangerous filenames, malicious extensions, Windows reserved names, and compression-based attacks before you accept an upload.
8
+
9
+ ## Features
10
+
11
+ - **Framework-agnostic** async validation (FastAPI, generic)
12
+ - Filename sanitization and Unicode security checks
13
+ - Extension validation with configurable allow/block lists
14
+ - ZIP bomb detection and content inspection
15
+ - MIME type verification with signature validation
16
+ - Rich exception hierarchy for precise error handling
17
+ - Zero configuration required—secure defaults out of the box
18
+
19
+ ## Installation
20
+
21
+ ```bash
22
+ pip install safeuploads
23
+ ```
24
+
25
+ For FastAPI integration:
26
+ ```bash
27
+ pip install safeuploads[fastapi]
28
+ ```
29
+
30
+ ## Quick Start
31
+
32
+ ```python
33
+ from fastapi import FastAPI, UploadFile, HTTPException
34
+ from safeuploads import FileValidator
35
+ from safeuploads.exceptions import FileValidationError
36
+
37
+ app = FastAPI()
38
+ validator = FileValidator()
39
+
40
+ @app.post("/upload")
41
+ async def upload_image(file: UploadFile):
42
+ try:
43
+ await validator.validate_image_file(file)
44
+ except FileValidationError as e:
45
+ raise HTTPException(status_code=400, detail=str(e))
46
+
47
+ return {"status": "success", "filename": file.filename}
48
+ ```
49
+
50
+ ## Configuration
51
+
52
+ ```python
53
+ from safeuploads import FileValidator, FileSecurityConfig
54
+
55
+ # Use default secure configuration
56
+ validator = FileValidator()
57
+
58
+ # Or customize limits
59
+ config = FileSecurityConfig()
60
+ config.limits.max_image_size = 10 * 1024 * 1024 # 10 MiB
61
+ config.limits.max_compression_ratio = 50
62
+
63
+ validator = FileValidator(config=config)
64
+ ```
65
+
66
+ ## Exception Handling
67
+
68
+ ```python
69
+ from safeuploads.exceptions import (
70
+ FileValidationError, # Base exception
71
+ FileSizeError, # File too large
72
+ ExtensionSecurityError, # Dangerous extension
73
+ ZipBombError, # Compression attack
74
+ )
75
+
76
+ try:
77
+ await validator.validate_image_file(file)
78
+ except FileSizeError as err:
79
+ return {"error": "File too large", "max_size": err.max_size}
80
+ except ExtensionSecurityError as err:
81
+ return {"error": "File type not allowed", "extension": err.extension}
82
+ except FileValidationError as err:
83
+ return {"error": str(err), "code": err.error_code}
84
+ ```
85
+
86
+ ## Current Status & Roadmap
87
+
88
+ ### What's Working
89
+
90
+ - **Filename Security**: Unicode normalization, directory traversal prevention, Windows reserved names blocking
91
+ - **Extension Validation**: Allow/block lists with configurable rules, dangerous extension detection
92
+ - **Compression Security**: ZIP bomb detection, nested archive inspection, size and ratio limits
93
+ - **Content Inspection**: Deep ZIP content analysis with configurable depth and entry limits
94
+ - **MIME Type Verification**: Magic number validation for common file types
95
+ - **Rich Exception System**: Machine-readable error codes with detailed context
96
+
97
+ ### Planned Improvements
98
+
99
+ #### Critical (Pre-1.0)
100
+ - **Streaming Validation**: Memory-efficient processing for large files to prevent resource exhaustion
101
+ - **Resource Limits**: CPU and memory monitoring during validation operations
102
+ - **Rate Limiting Guide**: Documentation and examples for production deployments
103
+
104
+ #### High Priority
105
+ - **Enhanced ZIP Security**: Protection against recursive ZIP structures and algorithmic complexity attacks
106
+ - **Audit Logging**: Structured logging for security-relevant events with request correlation
107
+ - **Performance Optimizations**: Pattern caching, compiled regex optimization, async I/O improvements
108
+
109
+ #### Future Enhancements
110
+ - **Additional File Types**: .gpx, .tcx, .fit, .gz
111
+ - **Content Analysis**: Malware signature detection, embedded script scanning
112
+ - **Fuzzing Tests**: Automated testing with malformed and malicious payloads
113
+ - **Security Documentation**: Threat model, architecture diagrams, integration security checklist
114
+
115
+ ### Production Readiness
116
+
117
+ **Status**: Beta - suitable for testing, not yet recommended for production use
118
+
119
+ **Before Production**:
120
+ 1. Address memory exhaustion vulnerability in ZIP inspection
121
+ 2. Implement streaming validation for large files
122
+ 3. Complete security audit and penetration testing
123
+
124
+ **Known Limitations**:
125
+ - No built-in rate limiting (must be implemented at application level)
126
+ - Limited to synchronous content reading in ZIP inspection
127
+ - Performance not yet optimized for high-throughput scenarios
128
+
129
+ ## Documentation
130
+
131
+ Full documentation available at [link to your docs].
132
+
133
+ ## Sponsors
134
+
135
+ A huge thank you to the project sponsors! Your support helps keep this project going.
136
+
137
+ Consider [sponsoring safeuploads on GitHub](https://github.com/sponsors/joaovitoriasilva) to ensure continuous development.
138
+
139
+ ## License
140
+
141
+ This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.
142
+
143
+ ## Contributing
144
+
145
+ Contributions welcome! See [Contributing Guidelines](CONTRIBUTING.md) for guidelines.
146
+
147
+
@@ -0,0 +1,65 @@
1
+ [project]
2
+ name = "safeuploads"
3
+ version = "0.1.0"
4
+ description = "A comprehensive file security system for validating uploads and preventing attacks"
5
+ authors = [
6
+ {name = "João Vitória Silva",email = "joao@endurain.com"}
7
+ ]
8
+ license = {text = "MIT"}
9
+ readme = "README.md"
10
+ requires-python = ">=3.13"
11
+ dependencies = [
12
+ "python-magic (>=0.4.27,<0.5.0)",
13
+ ]
14
+
15
+ [project.optional-dependencies]
16
+ fastapi = ["fastapi (>=0.110,<1.0)"]
17
+ dev = [
18
+ "pytest (>=8.0,<9.0)",
19
+ "pytest-asyncio (>=0.23,<1.0)",
20
+ "pytest-cov (>=4.1,<5.0)",
21
+ ]
22
+
23
+
24
+ [build-system]
25
+ requires = ["poetry-core>=2.0.0,<3.0.0"]
26
+ build-backend = "poetry.core.masonry.api"
27
+
28
+ [tool.pytest.ini_options]
29
+ testpaths = ["tests"]
30
+ python_files = ["test_*.py"]
31
+ python_classes = ["Test*"]
32
+ python_functions = ["test_*"]
33
+ asyncio_mode = "auto"
34
+ addopts = [
35
+ "--strict-markers",
36
+ "--strict-config",
37
+ "-ra",
38
+ "--cov=safeuploads",
39
+ "--cov-report=term-missing",
40
+ "--cov-report=html",
41
+ ]
42
+ markers = [
43
+ "unit: Unit tests",
44
+ "integration: Integration tests",
45
+ "slow: Slow running tests",
46
+ "performance: Performance and benchmarking tests",
47
+ ]
48
+
49
+ [tool.coverage.run]
50
+ source = ["safeuploads"]
51
+ omit = ["*/tests/*", "*/__pycache__/*"]
52
+
53
+ [tool.coverage.report]
54
+ precision = 2
55
+ show_missing = true
56
+ skip_covered = false
57
+ exclude_lines = [
58
+ "pragma: no cover",
59
+ "def __repr__",
60
+ "raise AssertionError",
61
+ "raise NotImplementedError",
62
+ "if __name__ == .__main__.:",
63
+ "if TYPE_CHECKING:",
64
+ "@abstractmethod",
65
+ ]
@@ -0,0 +1,92 @@
1
+ """
2
+ File Security Module
3
+
4
+ A comprehensive file security system for validating uploads and preventing attacks.
5
+ """
6
+
7
+ # Core classes and configurations
8
+ from .config import SecurityLimits, FileSecurityConfig
9
+ from .exceptions import (
10
+ ConfigValidationError,
11
+ FileSecurityConfigurationError,
12
+ ErrorCode,
13
+ FileSecurityError,
14
+ FileValidationError,
15
+ FilenameSecurityError,
16
+ UnicodeSecurityError,
17
+ ExtensionSecurityError,
18
+ WindowsReservedNameError,
19
+ FileSizeError,
20
+ MimeTypeError,
21
+ FileSignatureError,
22
+ CompressionSecurityError,
23
+ ZipBombError,
24
+ ZipContentError,
25
+ FileProcessingError,
26
+ )
27
+ from .enums import (
28
+ DangerousExtensionCategory,
29
+ CompoundExtensionCategory,
30
+ UnicodeAttackCategory,
31
+ SuspiciousFilePattern,
32
+ ZipThreatCategory,
33
+ )
34
+
35
+ # Main validator
36
+ from .file_validator import FileValidator
37
+
38
+ # Specialized validators
39
+ from .validators import (
40
+ BaseValidator,
41
+ UnicodeSecurityValidator,
42
+ ExtensionSecurityValidator,
43
+ WindowsSecurityValidator,
44
+ CompressionSecurityValidator,
45
+ )
46
+
47
+ # Inspectors
48
+ from .inspectors import ZipContentInspector
49
+
50
+ # Perform configuration validation when module is imported
51
+ # This ensures configuration issues are caught early during application startup
52
+ FileSecurityConfig.validate_and_report(strict=False)
53
+
54
+ # Export all public APIs
55
+ __all__ = [
56
+ # Core configuration
57
+ "SecurityLimits",
58
+ "FileSecurityConfig",
59
+ # Exceptions
60
+ "ConfigValidationError",
61
+ "FileSecurityConfigurationError",
62
+ "ErrorCode",
63
+ "FileSecurityError",
64
+ "FileValidationError",
65
+ "FilenameSecurityError",
66
+ "UnicodeSecurityError",
67
+ "ExtensionSecurityError",
68
+ "WindowsReservedNameError",
69
+ "FileSizeError",
70
+ "MimeTypeError",
71
+ "FileSignatureError",
72
+ "CompressionSecurityError",
73
+ "ZipBombError",
74
+ "ZipContentError",
75
+ "FileProcessingError",
76
+ # Enums
77
+ "DangerousExtensionCategory",
78
+ "CompoundExtensionCategory",
79
+ "UnicodeAttackCategory",
80
+ "SuspiciousFilePattern",
81
+ "ZipThreatCategory",
82
+ # Main validator
83
+ "FileValidator",
84
+ # Specialized validators
85
+ "BaseValidator",
86
+ "UnicodeSecurityValidator",
87
+ "ExtensionSecurityValidator",
88
+ "WindowsSecurityValidator",
89
+ "CompressionSecurityValidator",
90
+ # Inspectors
91
+ "ZipContentInspector",
92
+ ]