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/csv_check.py ADDED
@@ -0,0 +1,909 @@
1
+ """
2
+ License GPL3
3
+ (C) 2026 Created by Maikel Mardjan - https://nocomplexity.com/
4
+ FileAudit - CSV File Security Checker
5
+ """
6
+ import csv
7
+ import inspect
8
+ import io
9
+ import re
10
+ import threading
11
+ import urllib.error
12
+ import urllib.request
13
+ from functools import wraps
14
+ from pathlib import Path
15
+ from urllib.parse import urlparse
16
+
17
+ # ---------------------------------------------------------------------------
18
+ # Defaults
19
+ # ---------------------------------------------------------------------------
20
+
21
+ DEFAULT_MAX_FILE_SIZE = 10 * 1024 * 1024 # 10 MB
22
+ DEFAULT_MAX_ROWS = 100_000
23
+ DEFAULT_MAX_COLUMNS = 1_000
24
+ DEFAULT_MAX_FIELD_SIZE = 1 * 1024 * 1024 # 1 MB
25
+ DEFAULT_MAX_TOTAL_FIELDS = 10_000_000
26
+ DEFAULT_MAX_ROW_SIZE = 5 * 1024 * 1024 # 5 MB
27
+ DEFAULT_MAX_FILENAME_LENGTH = 255
28
+ DEFAULT_REMOTE_TIMEOUT = 30
29
+ DEFAULT_READ_CHUNK_SIZE = 64 * 1024
30
+
31
+
32
+ # Spreadsheet formula injection prefixes.
33
+ DEFAULT_DANGEROUS_FORMULA_PREFIXES = (
34
+ "=",
35
+ "+",
36
+ "-",
37
+ "@",
38
+ )
39
+
40
+
41
+ # csv.field_size_limit() is process-global.
42
+ _CSV_FIELD_SIZE_LOCK = threading.Lock()
43
+
44
+
45
+ # Windows drive path, e.g. C:\data\file.csv or C:/data/file.csv.
46
+ _WINDOWS_DRIVE_PATH = re.compile(r"^[A-Za-z]:[\\/]")
47
+
48
+
49
+ # ---------------------------------------------------------------------------
50
+ # Exceptions
51
+ # ---------------------------------------------------------------------------
52
+
53
+ class CsvValidationError(Exception):
54
+ """Custom exception for CSV validation failures in FileAudit."""
55
+
56
+ def __init__(self, message):
57
+ self.prefix = "FileAudit Security Validation Failed -"
58
+ self.original_message = str(message)
59
+ super().__init__(f"{self.prefix} {self.original_message}")
60
+
61
+
62
+ # ---------------------------------------------------------------------------
63
+ # Input classification
64
+ # ---------------------------------------------------------------------------
65
+
66
+ def _classify_input(value):
67
+ """
68
+ Classify a CSV source as either a local filesystem path or HTTPS URL.
69
+
70
+ Returns:
71
+ ("local", Path)
72
+ ("https", str)
73
+
74
+ Raises:
75
+ CsvValidationError: if the input is invalid or uses an unsupported
76
+ URL scheme.
77
+ """
78
+ if isinstance(value, Path):
79
+ return "local", value
80
+
81
+ if not isinstance(value, str):
82
+ raise CsvValidationError(
83
+ f"Expected a local path or HTTPS URL, "
84
+ f"got {type(value).__name__}"
85
+ )
86
+
87
+ value = value.strip()
88
+
89
+ if not value:
90
+ raise CsvValidationError("CSV path/URL cannot be empty")
91
+
92
+ # Windows paths must be checked before urlparse().
93
+ #
94
+ # urlparse("C:\\data\\file.csv") interprets "C" as a URL scheme.
95
+ if _WINDOWS_DRIVE_PATH.match(value):
96
+ return "local", Path(value)
97
+
98
+ parsed = urlparse(value)
99
+
100
+ if parsed.scheme:
101
+ scheme = parsed.scheme.lower()
102
+
103
+ if scheme != "https":
104
+ raise CsvValidationError(
105
+ f"Unsupported URL scheme '{parsed.scheme}': "
106
+ "only HTTPS URLs are allowed."
107
+ )
108
+
109
+ if not parsed.netloc:
110
+ raise CsvValidationError(
111
+ f"Invalid HTTPS URL: {value!r}"
112
+ )
113
+
114
+ # Userinfo in URLs is unnecessary and should not be accepted.
115
+ if parsed.username is not None or parsed.password is not None:
116
+ raise CsvValidationError(
117
+ "HTTPS URLs containing username/password credentials "
118
+ "are not allowed."
119
+ )
120
+
121
+ return "https", value
122
+
123
+ # No URL scheme => local filesystem path.
124
+ return "local", Path(value)
125
+
126
+
127
+ # ---------------------------------------------------------------------------
128
+ # Remote HTTPS handling
129
+ # ---------------------------------------------------------------------------
130
+
131
+ class _HttpsOnlyRedirectHandler(urllib.request.HTTPRedirectHandler):
132
+ """
133
+ Allow redirects only when the destination remains HTTPS.
134
+
135
+ This prevents an HTTPS URL from silently redirecting to HTTP.
136
+ """
137
+
138
+ def redirect_request(
139
+ self,
140
+ req,
141
+ fp,
142
+ code,
143
+ msg,
144
+ headers,
145
+ newurl,
146
+ ):
147
+ parsed = urlparse(newurl)
148
+
149
+ if parsed.scheme.lower() != "https":
150
+ raise CsvValidationError(
151
+ "Remote URL redirected to a non-HTTPS location; "
152
+ "redirect rejected."
153
+ )
154
+
155
+ if not parsed.netloc:
156
+ raise CsvValidationError(
157
+ f"Invalid HTTPS redirect target: {newurl!r}"
158
+ )
159
+
160
+ if parsed.username is not None or parsed.password is not None:
161
+ raise CsvValidationError(
162
+ "HTTPS redirects containing username/password "
163
+ "credentials are not allowed."
164
+ )
165
+
166
+ return super().redirect_request(
167
+ req,
168
+ fp,
169
+ code,
170
+ msg,
171
+ headers,
172
+ newurl,
173
+ )
174
+
175
+
176
+ _HTTPS_OPENER = urllib.request.build_opener(
177
+ _HttpsOnlyRedirectHandler()
178
+ )
179
+
180
+
181
+ # ---------------------------------------------------------------------------
182
+ # Individual CSV checks
183
+ # ---------------------------------------------------------------------------
184
+
185
+ def _check_csv_field(
186
+ value,
187
+ row_number,
188
+ column_number,
189
+ max_field_size,
190
+ reject_formula_injection,
191
+ reject_control_characters,
192
+ encoding,
193
+ ):
194
+ """Validate one CSV field for common security issues."""
195
+
196
+ if not isinstance(value, str):
197
+ raise CsvValidationError(
198
+ f"Invalid field type at row {row_number}, "
199
+ f"column {column_number}"
200
+ )
201
+
202
+ if reject_control_characters:
203
+ for char in value:
204
+ codepoint = ord(char)
205
+
206
+ # Permit tab, newline and carriage return.
207
+ if codepoint < 32 and codepoint not in (9, 10, 13):
208
+ raise CsvValidationError(
209
+ f"Rejected field at row {row_number}, "
210
+ f"column {column_number}: "
211
+ f"contains control character U+{codepoint:04X}"
212
+ )
213
+
214
+ # NUL deserves an explicit security error regardless of the
215
+ # control-character setting.
216
+ if "\x00" in value:
217
+ raise CsvValidationError(
218
+ f"Rejected field at row {row_number}, "
219
+ f"column {column_number}: contains NUL byte"
220
+ )
221
+
222
+ try:
223
+ field_size = len(value.encode(encoding))
224
+ except UnicodeEncodeError as exc:
225
+ raise CsvValidationError(
226
+ f"Field at row {row_number}, column {column_number} "
227
+ f"cannot be encoded using {encoding!r}"
228
+ ) from exc
229
+
230
+ if field_size > max_field_size:
231
+ raise CsvValidationError(
232
+ f"Rejected field at row {row_number}, "
233
+ f"column {column_number}: field size exceeds "
234
+ f"maximum of {max_field_size} bytes"
235
+ )
236
+
237
+ if reject_formula_injection:
238
+ stripped = value.lstrip()
239
+
240
+ if stripped.startswith(DEFAULT_DANGEROUS_FORMULA_PREFIXES):
241
+ raise CsvValidationError(
242
+ f"Rejected field at row {row_number}, "
243
+ f"column {column_number}: possible spreadsheet "
244
+ f"formula injection"
245
+ )
246
+
247
+
248
+ def _check_csv_row(
249
+ row,
250
+ row_number,
251
+ max_columns,
252
+ max_field_size,
253
+ max_row_size,
254
+ reject_formula_injection,
255
+ reject_control_characters,
256
+ encoding,
257
+ ):
258
+ """Validate a single parsed CSV row."""
259
+
260
+ if len(row) > max_columns:
261
+ raise CsvValidationError(
262
+ f"Rejected row {row_number}: contains {len(row)} columns, "
263
+ f"exceeding maximum of {max_columns}"
264
+ )
265
+
266
+ row_size = 0
267
+
268
+ for column_number, value in enumerate(row, start=1):
269
+ _check_csv_field(
270
+ value=value,
271
+ row_number=row_number,
272
+ column_number=column_number,
273
+ max_field_size=max_field_size,
274
+ reject_formula_injection=reject_formula_injection,
275
+ reject_control_characters=reject_control_characters,
276
+ encoding=encoding,
277
+ )
278
+
279
+ row_size += len(value.encode(encoding))
280
+
281
+ if row_size > max_row_size:
282
+ raise CsvValidationError(
283
+ f"Rejected row {row_number}: row size ({row_size} bytes) "
284
+ f"exceeds maximum of {max_row_size} bytes"
285
+ )
286
+
287
+
288
+ # ---------------------------------------------------------------------------
289
+ # Configuration validation
290
+ # ---------------------------------------------------------------------------
291
+
292
+ def _validate_positive_integer(name, value):
293
+ if not isinstance(value, int) or isinstance(value, bool):
294
+ raise CsvValidationError(
295
+ f"{name} must be a positive integer"
296
+ )
297
+
298
+ if value <= 0:
299
+ raise CsvValidationError(
300
+ f"{name} must be greater than zero"
301
+ )
302
+
303
+
304
+ def _validate_configuration(
305
+ max_file_size,
306
+ max_rows,
307
+ max_columns,
308
+ max_field_size,
309
+ max_total_fields,
310
+ max_row_size,
311
+ max_filename_length,
312
+ ):
313
+ values = {
314
+ "max_file_size": max_file_size,
315
+ "max_rows": max_rows,
316
+ "max_columns": max_columns,
317
+ "max_field_size": max_field_size,
318
+ "max_total_fields": max_total_fields,
319
+ "max_row_size": max_row_size,
320
+ "max_filename_length": max_filename_length,
321
+ }
322
+
323
+ for name, value in values.items():
324
+ _validate_positive_integer(name, value)
325
+
326
+
327
+ # ---------------------------------------------------------------------------
328
+ # Internal file validation
329
+ # ---------------------------------------------------------------------------
330
+
331
+ def _read_https_csv(url, max_file_size):
332
+ """Download an HTTPS CSV while enforcing a hard byte limit."""
333
+
334
+ parsed = urlparse(url)
335
+
336
+ if parsed.scheme.lower() != "https":
337
+ raise CsvValidationError(
338
+ "Only HTTPS URLs are allowed for remote files."
339
+ )
340
+
341
+ if not parsed.netloc:
342
+ raise CsvValidationError(
343
+ f"Invalid HTTPS URL: {url!r}"
344
+ )
345
+
346
+ if parsed.username is not None or parsed.password is not None:
347
+ raise CsvValidationError(
348
+ "HTTPS URLs containing username/password credentials "
349
+ "are not allowed."
350
+ )
351
+
352
+ if not (parsed.path or "").lower().endswith(".csv"):
353
+ raise CsvValidationError(
354
+ f"Remote URL does not point to a .csv file: {url}"
355
+ )
356
+
357
+ request = urllib.request.Request(
358
+ url,
359
+ headers={
360
+ "User-Agent": "FileAudit-CSVValidator/1.0",
361
+ },
362
+ method="GET",
363
+ )
364
+
365
+ with _HTTPS_OPENER.open(
366
+ request,
367
+ timeout=DEFAULT_REMOTE_TIMEOUT,
368
+ ) as response:
369
+
370
+ content_length = response.headers.get("Content-Length")
371
+
372
+ if content_length is not None:
373
+ try:
374
+ declared_size = int(content_length)
375
+ except ValueError as exc:
376
+ raise CsvValidationError(
377
+ f"Remote server returned invalid "
378
+ f"Content-Length: {content_length!r}"
379
+ ) from exc
380
+
381
+ if declared_size < 0:
382
+ raise CsvValidationError(
383
+ "Negative Content-Length is invalid"
384
+ )
385
+
386
+ if declared_size > max_file_size:
387
+ raise CsvValidationError(
388
+ f"Remote file size ({declared_size} bytes) "
389
+ f"exceeds maximum of {max_file_size} bytes"
390
+ )
391
+
392
+ chunks = []
393
+ total_size = 0
394
+
395
+ while True:
396
+ chunk = response.read(DEFAULT_READ_CHUNK_SIZE)
397
+
398
+ if not chunk:
399
+ break
400
+
401
+ total_size += len(chunk)
402
+
403
+ if total_size > max_file_size:
404
+ raise CsvValidationError(
405
+ f"Remote file exceeds maximum size of "
406
+ f"{max_file_size} bytes"
407
+ )
408
+
409
+ chunks.append(chunk)
410
+
411
+ return b"".join(chunks)
412
+
413
+
414
+ def _read_local_csv(path, max_file_size, max_filename_length):
415
+ """Read a local CSV while enforcing the configured size limits."""
416
+
417
+ local_path = Path(path)
418
+
419
+ if len(local_path.name) > max_filename_length:
420
+ raise CsvValidationError(
421
+ f"Filename length ({len(local_path.name)}) exceeds "
422
+ f"maximum of {max_filename_length} characters"
423
+ )
424
+
425
+ if local_path.suffix.lower() != ".csv":
426
+ raise CsvValidationError(
427
+ f"Expected a .csv file, got "
428
+ f"'{local_path.suffix or '[no extension]'}'"
429
+ )
430
+
431
+ try:
432
+ # Open first rather than stat() followed by open(), reducing
433
+ # the TOCTOU window.
434
+ with local_path.open("rb") as file:
435
+ csv_data = file.read(max_file_size + 1)
436
+ except FileNotFoundError as exc:
437
+ raise CsvValidationError(
438
+ f"File not found: {local_path}"
439
+ ) from exc
440
+ except IsADirectoryError as exc:
441
+ raise CsvValidationError(
442
+ f"Path is not a file: {local_path}"
443
+ ) from exc
444
+ except OSError as exc:
445
+ raise CsvValidationError(
446
+ f"Failed to access local file: {exc}"
447
+ ) from exc
448
+
449
+ if len(csv_data) > max_file_size:
450
+ raise CsvValidationError(
451
+ f"File size exceeds maximum of {max_file_size} bytes"
452
+ )
453
+
454
+ return csv_data
455
+
456
+
457
+ def _validate_csv_file(
458
+ path,
459
+ max_file_size,
460
+ max_rows,
461
+ max_columns,
462
+ max_field_size,
463
+ max_total_fields,
464
+ max_row_size,
465
+ max_filename_length,
466
+ reject_formula_injection,
467
+ reject_control_characters,
468
+ encoding,
469
+ dialect,
470
+ ):
471
+ """
472
+ Validate a local CSV file or an HTTPS CSV URL.
473
+
474
+ No CSV content is executed or imported.
475
+ """
476
+
477
+ _validate_configuration(
478
+ max_file_size=max_file_size,
479
+ max_rows=max_rows,
480
+ max_columns=max_columns,
481
+ max_field_size=max_field_size,
482
+ max_total_fields=max_total_fields,
483
+ max_row_size=max_row_size,
484
+ max_filename_length=max_filename_length,
485
+ )
486
+
487
+ source_type, source = _classify_input(path)
488
+
489
+ # ---------------------------------------------------------------
490
+ # Read bytes
491
+ # ---------------------------------------------------------------
492
+
493
+ if source_type == "https":
494
+ try:
495
+ csv_data = _read_https_csv(
496
+ source,
497
+ max_file_size=max_file_size,
498
+ )
499
+ except urllib.error.HTTPError as exc:
500
+ raise CsvValidationError(
501
+ f"Remote file unreachable (HTTP {exc.code})"
502
+ ) from exc
503
+ except urllib.error.URLError as exc:
504
+ raise CsvValidationError(
505
+ f"Could not reach remote file: {exc.reason}"
506
+ ) from exc
507
+
508
+ else:
509
+ csv_data = _read_local_csv(
510
+ source,
511
+ max_file_size=max_file_size,
512
+ max_filename_length=max_filename_length,
513
+ )
514
+
515
+ # ---------------------------------------------------------------
516
+ # Decode
517
+ # ---------------------------------------------------------------
518
+
519
+ try:
520
+ text = csv_data.decode(encoding)
521
+ except UnicodeDecodeError as exc:
522
+ raise CsvValidationError(
523
+ f"CSV is not valid {encoding} text: {exc}"
524
+ ) from exc
525
+
526
+ if encoding.lower().replace("_", "-") == "utf-8":
527
+ if text.startswith("\ufeff"):
528
+ raise CsvValidationError(
529
+ "CSV contains a UTF-8 BOM; use encoding='utf-8-sig' "
530
+ "if BOMs are intentionally supported"
531
+ )
532
+
533
+ if "\x00" in text:
534
+ raise CsvValidationError(
535
+ r"Null byte (\0) found in CSV content - rejected"
536
+ )
537
+
538
+ # ---------------------------------------------------------------
539
+ # CSV parsing and validation
540
+ # ---------------------------------------------------------------
541
+
542
+ previous_limit = csv.field_size_limit()
543
+
544
+ try:
545
+ with _CSV_FIELD_SIZE_LOCK:
546
+ csv.field_size_limit(max_field_size)
547
+
548
+ reader = csv.reader(
549
+ io.StringIO(text, newline=""),
550
+ dialect=dialect,
551
+ )
552
+
553
+ row_count = 0
554
+ total_fields = 0
555
+
556
+ try:
557
+ for row_number, row in enumerate(reader, start=1):
558
+ row_count += 1
559
+
560
+ if row_count > max_rows:
561
+ raise CsvValidationError(
562
+ f"CSV contains more than {max_rows} rows"
563
+ )
564
+
565
+ total_fields += len(row)
566
+
567
+ if total_fields > max_total_fields:
568
+ raise CsvValidationError(
569
+ f"CSV contains more than "
570
+ f"{max_total_fields} fields"
571
+ )
572
+
573
+ _check_csv_row(
574
+ row=row,
575
+ row_number=row_number,
576
+ max_columns=max_columns,
577
+ max_field_size=max_field_size,
578
+ max_row_size=max_row_size,
579
+ reject_formula_injection=reject_formula_injection,
580
+ reject_control_characters=reject_control_characters,
581
+ encoding=encoding,
582
+ )
583
+
584
+ except csv.Error as exc:
585
+ raise CsvValidationError(
586
+ f"Invalid CSV format: {exc}"
587
+ ) from exc
588
+
589
+ except CsvValidationError:
590
+ raise
591
+
592
+ except (OverflowError, ValueError) as exc:
593
+ raise CsvValidationError(
594
+ f"Invalid CSV parser configuration: {exc}"
595
+ ) from exc
596
+
597
+ finally:
598
+ with _CSV_FIELD_SIZE_LOCK:
599
+ csv.field_size_limit(previous_limit)
600
+
601
+
602
+ # ---------------------------------------------------------------------------
603
+ # Public API
604
+ # ---------------------------------------------------------------------------
605
+ def validate_csv(
606
+ func_or_path=None,
607
+ max_file_size=None,
608
+ max_rows=None,
609
+ max_columns=None,
610
+ max_field_size=None,
611
+ max_total_fields=None,
612
+ max_row_size=None,
613
+ max_filename_length=None,
614
+ reject_formula_injection=True,
615
+ reject_control_characters=True,
616
+ encoding="utf-8",
617
+ dialect="excel",
618
+ ):
619
+ """Validate a CSV file directly or validate CSV arguments with a decorator.
620
+
621
+ This function supports both direct CSV validation and decorator usage.
622
+
623
+ In direct-invocation mode, the CSV file is validated immediately and the
624
+ function returns ``True`` when validation succeeds or ``False`` when
625
+ validation fails. Local file paths, ``Path`` objects, and URLs are
626
+ supported.
627
+
628
+ In decorator mode, the decorated function is called only after its CSV
629
+ argument has successfully passed validation. A validation failure raises
630
+ ``CsvValidationError``.
631
+
632
+ ``func_or_path`` is interpreted based on its value. A callable is treated
633
+ as the function to decorate. A ``Path`` or a string that looks like a file
634
+ path or URL is treated as a CSV source for direct validation. A string
635
+ that does not look like a path or URL can be used to explicitly identify
636
+ the decorated function argument containing the CSV path.
637
+
638
+ Examples:
639
+
640
+ Validate a local CSV file::
641
+
642
+ validate_csv("data.csv")
643
+
644
+ Validate a CSV file from a URL::
645
+
646
+ validate_csv("https://example.com/data.csv")
647
+
648
+ Use as a decorator, using the first function argument as the CSV path::
649
+
650
+ @validate_csv
651
+ def process_csv(csv_path):
652
+ ...
653
+
654
+ Use as a decorator with default validation options::
655
+
656
+ @validate_csv()
657
+ def process_csv(csv_path):
658
+ ...
659
+
660
+ Specify the decorated function argument containing the CSV path::
661
+
662
+ @validate_csv("input_file")
663
+ def process_csv(input_file):
664
+ ...
665
+
666
+ Configure validation limits::
667
+
668
+ @validate_csv(
669
+ max_file_size=10 * 1024 * 1024,
670
+ max_rows=10_000,
671
+ max_columns=50,
672
+ )
673
+ def process_csv(csv_path):
674
+ ...
675
+
676
+ The explicit argument name must match a parameter of the decorated
677
+ function. Otherwise, the decorator uses the function's first
678
+ parameter as the CSV path::
679
+
680
+ @validate_csv("csv_path")
681
+ def process_csv(csv_path):
682
+ ...
683
+
684
+ Args:
685
+ func_or_path: Controls whether the function operates in direct or
686
+ decorator mode. A callable is treated as the function to decorate.
687
+ A ``Path`` or a string that looks like a file path or URL is
688
+ treated as a CSV source for direct validation. A string that does
689
+ not look like a file path or URL is treated as the name of the
690
+ decorated function argument containing the CSV path. If that name
691
+ does not match a function parameter, the first function parameter
692
+ is used instead. ``None`` creates a decorator that uses the first
693
+ function parameter as the CSV path.
694
+ max_file_size: Maximum allowed CSV file size in bytes. If ``None``,
695
+ uses the default maximum file size.
696
+ max_rows: Maximum number of rows allowed in the CSV file. If ``None``,
697
+ uses the default maximum number of rows.
698
+ max_columns: Maximum number of columns allowed in the CSV file. If
699
+ ``None``, uses the default maximum number of columns.
700
+ max_field_size: Maximum allowed size of an individual CSV field. If
701
+ ``None``, uses the default maximum field size.
702
+ max_total_fields: Maximum total number of fields allowed in the CSV
703
+ file. If ``None``, uses the default maximum.
704
+ max_row_size: Maximum allowed size of an individual CSV row. If
705
+ ``None``, uses the default maximum row size.
706
+ max_filename_length: Maximum allowed length of the CSV filename. If
707
+ ``None``, uses the default maximum filename length.
708
+ reject_formula_injection: Whether to reject fields that could be
709
+ interpreted as spreadsheet formulas. Defaults to ``True``.
710
+ reject_control_characters: Whether to reject disallowed control
711
+ characters in CSV fields. Defaults to ``True``.
712
+ encoding: Character encoding used to read the CSV file. Defaults to
713
+ ``"utf-8"``.
714
+ dialect: CSV dialect used when parsing the file. Defaults to
715
+ ``"excel"``.
716
+
717
+ Returns:
718
+ In direct-invocation mode, ``True`` if the CSV passes validation or
719
+ ``False`` if validation fails.
720
+
721
+ In decorator mode, the decorated function's wrapped callable is
722
+ returned. When invoked, the wrapped function returns the original
723
+ function's return value after successful CSV validation.
724
+
725
+ Raises:
726
+ CsvValidationError: If ``func_or_path`` is not a callable, ``Path``,
727
+ string, or ``None``.
728
+ CsvValidationError: If a decorated function has no parameters.
729
+ CsvValidationError: If the decorated function is called with an
730
+ invalid argument signature.
731
+ CsvValidationError: If the CSV path argument is missing or is neither
732
+ a string nor a ``Path``.
733
+ CsvValidationError: If CSV validation fails while the function is
734
+ used as a decorator.
735
+ """
736
+ resolved_file_size = (
737
+ DEFAULT_MAX_FILE_SIZE
738
+ if max_file_size is None
739
+ else max_file_size
740
+ )
741
+
742
+ resolved_rows = (
743
+ DEFAULT_MAX_ROWS
744
+ if max_rows is None
745
+ else max_rows
746
+ )
747
+
748
+ resolved_columns = (
749
+ DEFAULT_MAX_COLUMNS
750
+ if max_columns is None
751
+ else max_columns
752
+ )
753
+
754
+ resolved_field_size = (
755
+ DEFAULT_MAX_FIELD_SIZE
756
+ if max_field_size is None
757
+ else max_field_size
758
+ )
759
+
760
+ resolved_total_fields = (
761
+ DEFAULT_MAX_TOTAL_FIELDS
762
+ if max_total_fields is None
763
+ else max_total_fields
764
+ )
765
+
766
+ resolved_row_size = (
767
+ DEFAULT_MAX_ROW_SIZE
768
+ if max_row_size is None
769
+ else max_row_size
770
+ )
771
+
772
+ resolved_filename_length = (
773
+ DEFAULT_MAX_FILENAME_LENGTH
774
+ if max_filename_length is None
775
+ else max_filename_length
776
+ )
777
+
778
+ def _validate(path):
779
+ _validate_csv_file(
780
+ path=path,
781
+ max_file_size=resolved_file_size,
782
+ max_rows=resolved_rows,
783
+ max_columns=resolved_columns,
784
+ max_field_size=resolved_field_size,
785
+ max_total_fields=resolved_total_fields,
786
+ max_row_size=resolved_row_size,
787
+ max_filename_length=resolved_filename_length,
788
+ reject_formula_injection=reject_formula_injection,
789
+ reject_control_characters=reject_control_characters,
790
+ encoding=encoding,
791
+ dialect=dialect,
792
+ )
793
+
794
+ # ---------------------------------------------------------------
795
+ # Determine decorator vs direct invocation
796
+ # ---------------------------------------------------------------
797
+
798
+ def _looks_like_file_path(value):
799
+ if _WINDOWS_DRIVE_PATH.match(value):
800
+ return True
801
+
802
+ parsed = urlparse(value)
803
+
804
+ if parsed.scheme:
805
+ return True
806
+
807
+ if value.startswith(("/", "\\")):
808
+ return True
809
+
810
+ if "/" in value or "\\" in value:
811
+ return True
812
+
813
+ if value.lower().endswith(".csv"):
814
+ return True
815
+
816
+ return False
817
+
818
+ if func_or_path is None:
819
+ is_decorator_mode = True
820
+
821
+ elif callable(func_or_path):
822
+ is_decorator_mode = True
823
+
824
+ elif isinstance(func_or_path, Path):
825
+ is_decorator_mode = False
826
+
827
+ elif isinstance(func_or_path, str):
828
+ is_decorator_mode = not _looks_like_file_path(
829
+ func_or_path
830
+ )
831
+
832
+ else:
833
+ raise CsvValidationError(
834
+ f"Expected callable, Path, str, or None; "
835
+ f"got {type(func_or_path).__name__}"
836
+ )
837
+
838
+ # ---------------------------------------------------------------
839
+ # Direct / CLI mode
840
+ # ---------------------------------------------------------------
841
+
842
+ if (
843
+ not is_decorator_mode
844
+ and isinstance(func_or_path, (str, Path))
845
+ ):
846
+ try:
847
+ _validate(func_or_path)
848
+ return True
849
+ except CsvValidationError as exc:
850
+ print(f"Exception: {exc}")
851
+ return False
852
+
853
+ # ---------------------------------------------------------------
854
+ # Decorator mode
855
+ # ---------------------------------------------------------------
856
+
857
+ def decorator(function):
858
+ signature = inspect.signature(function)
859
+ params = list(signature.parameters.keys())
860
+
861
+ if not params:
862
+ raise CsvValidationError(
863
+ f"Decorator applied to '{function.__name__}', "
864
+ "but it has no arguments."
865
+ )
866
+
867
+ # Explicit argument name:
868
+ # @validate_csv("csv_path")
869
+ if (
870
+ isinstance(func_or_path, str)
871
+ and func_or_path in params
872
+ ):
873
+ target_arg = func_or_path
874
+ else:
875
+ target_arg = params[0]
876
+
877
+ @wraps(function)
878
+ def wrapper(*args, **kwargs):
879
+ try:
880
+ bound_args = signature.bind(*args, **kwargs)
881
+ bound_args.apply_defaults()
882
+ except TypeError as exc:
883
+ raise CsvValidationError(
884
+ f"Invalid function call signature: {exc}"
885
+ ) from exc
886
+
887
+ csv_path = bound_args.arguments.get(target_arg)
888
+
889
+ if csv_path is None:
890
+ raise CsvValidationError(
891
+ f"Missing required argument: {target_arg}"
892
+ )
893
+
894
+ if not isinstance(csv_path, (str, Path)):
895
+ raise CsvValidationError(
896
+ f"Expected Path or str for {target_arg}, "
897
+ f"got {type(csv_path).__name__}"
898
+ )
899
+
900
+ _validate(csv_path)
901
+
902
+ return function(*args, **kwargs)
903
+
904
+ return wrapper
905
+
906
+ if callable(func_or_path):
907
+ return decorator(func_or_path)
908
+
909
+ return decorator