fileaudit 0.2.0__py3-none-any.whl

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.
fileaudit/__about__.py ADDED
@@ -0,0 +1,5 @@
1
+ # SPDX-FileCopyrightText: 2025-present Maikel Mardjan
2
+ #
3
+ # SPDX-License-Identifier: GPL-3.0-or-later
4
+
5
+ __version__ = "0.2.0"
fileaudit/__init__.py ADDED
File without changes
fileaudit/cli.py ADDED
@@ -0,0 +1,264 @@
1
+ """
2
+ License GPL3
3
+ (C) 2026 Created by Maikel Mardjan - https://nocomplexity.com/
4
+ FileAudit - File Security Checker
5
+ """
6
+ import os
7
+ import sys
8
+ import tempfile
9
+ import urllib.request
10
+ import urllib.error
11
+ from urllib.parse import urlparse
12
+ import fire
13
+ from fileaudit.__about__ import __version__
14
+ from fileaudit.json_check import validate_json
15
+ from fileaudit.targz_check import validate_tar_gz
16
+ from fileaudit.xml_check import validate_xml
17
+ from fileaudit.tar_check import validate_tar
18
+ from fileaudit.zip_check import validate_zip
19
+ from fileaudit.gz_check import validate_gz
20
+ from fileaudit.csv_check import validate_csv
21
+ from fileaudit.python_check import validate_python
22
+
23
+ fileaudit_ascii_art = r"""
24
+ --------------------------------
25
+ __ _
26
+ |_ o | _ |_| _| o _|_
27
+ | | | (/_ | ||_|(_| | |_
28
+ --------------------------------
29
+ """
30
+
31
+
32
+ # Mapping of file extensions to validation functions
33
+ VALIDATORS = {
34
+ '.json': validate_json,
35
+ '.xml': validate_xml,
36
+ '.csv': validate_csv,
37
+ '.py': validate_python,
38
+ '.zip': validate_zip,
39
+ '.tar': validate_tar,
40
+ '.gz': validate_gz,
41
+ '.tgz': validate_tar_gz,
42
+ '.tar.gz': validate_tar_gz,
43
+ }
44
+
45
+ # Supported file types for help display
46
+ SUPPORTED_TYPES = {
47
+ 'json': 'JSON files',
48
+ 'xml': 'XML files',
49
+ 'csv': 'CSV files',
50
+ 'py': 'Python source files',
51
+ 'zip': 'ZIP archives',
52
+ 'tar': 'TAR archives',
53
+ 'gz': 'GZIP files',
54
+ 'tar-gz': 'TAR.GZ archives',
55
+ 'tgz': 'TAR.GZ archives',
56
+ }
57
+
58
+ TYPE_MAP = {
59
+ 'json': validate_json,
60
+ 'xml': validate_xml,
61
+ 'csv': validate_csv,
62
+ 'py': validate_python,
63
+ 'zip': validate_zip,
64
+ 'tar': validate_tar,
65
+ 'gz': validate_gz,
66
+ 'tar-gz': validate_tar_gz,
67
+ 'tgz': validate_tar_gz,
68
+ }
69
+
70
+
71
+ class FileAudit:
72
+ """🔒 Python File Audit - Secure your Python Programs with one simple line!"""
73
+
74
+ def __init__(self):
75
+ self.version = __version__
76
+
77
+ def check(self, filepath, type=None):
78
+ """
79
+ Validate a file for security issues.
80
+
81
+ Args:
82
+ filepath: Path to file or URL to audit
83
+ type: Optional manual type specification (json, xml, csv, python, zip, tar, gz, tar-gz)
84
+ """
85
+ if not filepath:
86
+ print("❌ Error: Please specify a file or URL to check")
87
+ print("Usage: fileaudit check <FILE|URL> [--type TYPE]")
88
+ return 1
89
+
90
+ # Check if it's a URL or local file
91
+ is_url = filepath.startswith(('http://', 'https://'))
92
+
93
+ # If type is specified, map to validator
94
+ if type:
95
+ validator = TYPE_MAP.get(type.lower())
96
+ if not validator:
97
+ print(f"❌ Error: Unsupported file type '{type}'")
98
+ print(f"Supported types: {', '.join(sorted(TYPE_MAP.keys()))}")
99
+ return 1
100
+ else:
101
+ # Auto-detect
102
+ validator = self._detect_file_type(filepath)
103
+ if not validator:
104
+ print(f"❌ Error: Could not detect file type for '{filepath}'")
105
+ print("Please specify file type with --type option")
106
+ print(f"Supported types: {', '.join(sorted(SUPPORTED_TYPES.keys()))}")
107
+ return 1
108
+
109
+ temp_path = None
110
+ try:
111
+ print(f"🔍 Auditing: {filepath}")
112
+
113
+ if is_url:
114
+ print("📡 Downloading from remote URL...")
115
+ temp_path = self._download_url(filepath)
116
+ local_path = temp_path
117
+ else:
118
+ print("📁 Local file detected")
119
+ if not os.path.isfile(filepath):
120
+ print(f"❌ Error: Local file not found: {filepath}")
121
+ return 1
122
+ local_path = filepath
123
+
124
+ # Call the validator (on a real local file)
125
+ result = validator(local_path)
126
+
127
+ # Treat an explicit False return value as failure
128
+ if result is False:
129
+ print(f"❌ Security audit failed for {filepath}")
130
+ return 1
131
+
132
+ print(f"✅ Security audit passed for {filepath}")
133
+ return 0
134
+
135
+ except Exception as e:
136
+ print(f"❌ Security audit failed: {e}")
137
+ return 1
138
+ finally:
139
+ # Always clean up the temporary file
140
+ if temp_path and os.path.exists(temp_path):
141
+ try:
142
+ os.unlink(temp_path)
143
+ except OSError:
144
+ pass
145
+
146
+ def _download_url(self, url, timeout=30):
147
+ """
148
+ Download a remote URL to a temporary file.
149
+ Raises on network / HTTP errors so the caller can report failure.
150
+ """
151
+ # Preserve a sensible suffix so validators that look at the extension still work
152
+ suffix = self._get_file_extension(url) or ''
153
+ fd, temp_path = tempfile.mkstemp(suffix=suffix)
154
+ os.close(fd)
155
+
156
+ try:
157
+ request = urllib.request.Request(
158
+ url,
159
+ headers={'User-Agent': f'FileAudit/{__version__}'}
160
+ )
161
+ with urllib.request.urlopen(request, timeout=timeout) as response:
162
+ if response.status >= 400:
163
+ raise urllib.error.HTTPError(
164
+ url, response.status, response.reason, response.headers, None
165
+ )
166
+ with open(temp_path, 'wb') as out:
167
+ while True:
168
+ chunk = response.read(8192)
169
+ if not chunk:
170
+ break
171
+ out.write(chunk)
172
+ return temp_path
173
+ except Exception:
174
+ # Clean up the empty/partial temp file on any failure
175
+ if os.path.exists(temp_path):
176
+ os.unlink(temp_path)
177
+ raise
178
+
179
+ def _detect_file_type(self, filepath):
180
+ """Auto-detect file type from extension"""
181
+ ext = self._get_file_extension(filepath)
182
+ if ext in VALIDATORS:
183
+ return VALIDATORS[ext]
184
+ # If no extension found or unsupported, try to detect from URL path
185
+ if filepath.startswith(('http://', 'https://')):
186
+ parsed = urlparse(filepath)
187
+ path = parsed.path
188
+ ext = self._get_file_extension(path)
189
+ if ext in VALIDATORS:
190
+ return VALIDATORS[ext]
191
+ return None
192
+
193
+ def _get_file_extension(self, filename):
194
+ """Extract file extension, handling special cases like .tar.gz"""
195
+ if filename.endswith('.tar.gz'):
196
+ return '.tar.gz'
197
+ # Handle URLs with query parameters
198
+ if '?' in filename:
199
+ filename = filename.split('?')[0]
200
+ ext = os.path.splitext(filename)[1].lower()
201
+ return ext
202
+
203
+ def version(self):
204
+ """Display version information"""
205
+ print(f"FileAudit version: {__version__}")
206
+
207
+ def help(self):
208
+ """Show detailed help for using FileAudit tool"""
209
+ print(fileaudit_ascii_art)
210
+ print("Python File Audit - Secure your programs with one simple command.")
211
+ print("Usage:")
212
+ print(" fileaudit <command> [options]\n")
213
+ print("Commands:")
214
+ print(" check <FILE|URL> [--type TYPE] Run a security audit on a local file or HTTPS URL")
215
+ print(" version Print version and exit")
216
+ print(" help Show this help\n")
217
+ print("Options for check:")
218
+ print(" --type TYPE Force file type instead of auto-detection")
219
+ print("Supported types (auto-detected from extension):")
220
+ for ftype, description in sorted(SUPPORTED_TYPES.items()):
221
+ print(f" {ftype:<12} {description}")
222
+ print("\nExamples:")
223
+ print(" fileaudit check app.py")
224
+ print(" fileaudit check data.json")
225
+ print(" fileaudit check https://example.com/archive.zip")
226
+ print(" fileaudit check unknown.dat --type json")
227
+ print("\nCheck the Documentation: https://fileaudit.nocomplexity.com")
228
+
229
+
230
+ def main():
231
+ """Entry point for the CLI application."""
232
+ if len(sys.argv) == 1:
233
+ FileAudit().help()
234
+ return
235
+
236
+ first_arg = sys.argv[1]
237
+
238
+ # Check if it's a URL or an existing file path
239
+ is_file_or_url = (
240
+ first_arg.startswith(('http://', 'https://')) or
241
+ (os.path.isfile(first_arg) and not first_arg.startswith('-'))
242
+ )
243
+
244
+ # Also handle if it looks like a file with extension
245
+ if not is_file_or_url and '.' in first_arg and not first_arg.startswith('-'):
246
+ # Make sure it's not just '.' or '..' or a directory
247
+ last_part = os.path.basename(first_arg)
248
+ if last_part not in ['.', '..'] and '.' in last_part[1:]: # Not starting with dot
249
+ # Check if there are characters after the last dot
250
+ dot_index = last_part.rfind('.')
251
+ if dot_index < len(last_part) - 1:
252
+ is_file_or_url = True
253
+
254
+ if is_file_or_url:
255
+ sys.argv.insert(1, 'check')
256
+
257
+ # Run Fire and turn an integer return value into a real process exit code
258
+ result = fire.Fire(FileAudit, name='fileaudit')
259
+ if isinstance(result, int):
260
+ sys.exit(result)
261
+
262
+
263
+ if __name__ == "__main__":
264
+ main()