-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutils.py
More file actions
1683 lines (1419 loc) · 61.4 KB
/
Copy pathutils.py
File metadata and controls
1683 lines (1419 loc) · 61.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Utility functions shared across the AI tools discovery system
"""
import functools
import json
import logging
import os
import platform
import re
import shlex
import shutil
import sqlite3
import subprocess
import tempfile
import time
import traceback
from datetime import datetime, timezone
from pathlib import Path
from typing import Any, Dict, FrozenSet, List, NamedTuple, Optional, Tuple
try:
import pwd
except ImportError:
pwd = None # Not available on Windows
from .constants import AUTH_STATUS_TIMEOUT, COMMAND_TIMEOUT, CURSOR_DB_TIMEOUT, CURSOR_PLAN_KEY, DSCL_TIMEOUT, INVALID_SERIAL_VALUES, KEYCHAIN_SERVICE_NAME, KEYCHAIN_TIMEOUT, MACOS_MIN_HUMAN_UID, MACOS_SKIP_USER_DIRS, NON_INTERACTIVE_SHELLS, VERSION_TIMEOUT, WINDOWS_SKIP_USER_DIRS
logger = logging.getLogger(__name__)
def is_valid_serial(serial: str) -> bool:
"""
Check if serial number is valid (not a placeholder value).
Args:
serial: Serial number to validate
Returns:
True if valid, False otherwise
"""
return serial and serial.upper() not in INVALID_SERIAL_VALUES
def extract_version_number(text: str) -> Optional[str]:
"""
Extract clean version number from text.
Examples:
'2.0.37 (Claude Code)' -> '2.0.37'
'Version: 1.2.3' -> '1.2.3'
Args:
text: Text containing version information
Returns:
Version number string or None
"""
if not text:
return None
# Try to extract version pattern (e.g., 2.0.37)
version_match = re.search(r'(\d+\.\d+\.\d+)', text)
if version_match:
return version_match.group(1)
# Fallback: return first line with digits
for line in text.split('\n'):
if any(char.isdigit() for char in line):
return line.strip()
return text.strip() if text.strip() else None
def run_command(command: list, timeout: int = COMMAND_TIMEOUT) -> Optional[str]:
"""
Run a shell command and return its output.
Args:
command: Command and arguments as list
timeout: Command timeout in seconds
Returns:
Command output as string or None if failed
"""
try:
result = subprocess.run(
command,
capture_output=True,
text=True,
timeout=timeout
)
if result.returncode == 0 and result.stdout.strip():
return result.stdout.strip()
except Exception as e:
logger.debug(f"Command {command} failed: {e}")
return None
def resolve_npm_global_tool_bin(
tool: str, user_home: Path, is_root: bool
) -> Optional[str]:
"""Resolve the install path of an npm-global Node CLI (e.g. ``gemini``,
``openclaw``) whose real binary lives at ``<npm global prefix>/bin/<tool>``.
The npm global prefix varies (Homebrew node, nvm, pnpm), so we resolve it
dynamically with ``npm prefix -g`` AND probe a set of static fallbacks.
GUARD (cross-user FP class fixed in commit 93b5fc2): ``npm prefix -g``
resolves the SCANNER's npm config — under a root/MDM multi-user scan that is
NOT the target user's prefix, so honouring it would attribute the scanner's
install to a user who has only residue. The ``npm prefix -g`` probe and the
machine-global ``/opt/homebrew/bin`` fallback are therefore gated behind
``not is_root``. The ``user_home``-relative fallbacks (``~/.npm-global/bin``,
nvm under ``user_home``, pnpm under ``user_home``) are correctly scoped to
the user and stay unconditional. Never raises.
Args:
tool: The CLI/binary name (e.g. ``"gemini"`` / ``"openclaw"``).
user_home: Home dir of the user being scanned.
is_root: Whether the scan is running as root/SYSTEM.
Returns:
Absolute path to the resolved executable as a string, or None.
"""
candidates: List[Path] = []
# 1. Dynamic npm global prefix — SCANNER-scoped, so non-root only.
if not is_root:
prefix = run_command(["npm", "prefix", "-g"], COMMAND_TIMEOUT)
if prefix:
prefix = prefix.strip()
if prefix:
candidates.append(Path(prefix) / "bin" / tool)
# 2. Machine-global Homebrew prefix — non-root only (shared install).
if not is_root:
candidates.append(Path("/opt/homebrew/bin") / tool)
# 3. user_home-relative fallbacks — always safe (scoped to this user).
candidates.append(user_home / ".npm-global" / "bin" / tool)
candidates.append(user_home / ".local" / "share" / "pnpm" / tool) # pnpm global
try:
nvm_node = user_home / ".nvm" / "versions" / "node"
if nvm_node.exists():
for version_dir in sorted(nvm_node.iterdir()):
try:
if version_dir.is_dir():
candidates.append(version_dir / "bin" / tool)
except (PermissionError, OSError):
continue
except (PermissionError, OSError) as e:
logger.debug(f"Could not enumerate nvm node dirs for {tool}: {e}")
for candidate in candidates:
try:
if candidate.exists() and os.access(str(candidate), os.X_OK):
return str(candidate)
except (PermissionError, OSError):
continue
return None
def machine_global_binary_owned_by_user(candidate: Path, user_home: Path) -> bool:
"""Under a root/MDM multi-user scan, decide whether a MACHINE-GLOBAL binary
(Homebrew / /usr/local / /usr/bin) should be attributed to ``user_home``.
- Owned by a REGULAR user (Homebrew on macOS and manual /usr/local installs
are owned by the installing user): attribute to that owner ONLY — this is
what prevents one user's install fanning out to every user (the 93b5fc2
cross-user FP).
- Owned by ROOT/system (uid 0, e.g. /usr/bin/claude from apt/dnf): genuinely
system-wide and available to every user, so attribute to whoever is being
scanned.
Never raises: any stat/pwd failure returns False (do not attribute).
Args:
candidate: Absolute path to a machine-global binary.
user_home: Home dir of the user currently being scanned.
Returns:
True if the binary should be attributed to ``user_home``, else False.
"""
try:
uid = os.stat(str(candidate)).st_uid
except (OSError, PermissionError):
return False
if uid == 0:
return True # system-wide -> available to every scanned user
if pwd is None:
return False # POSIX-only; should never be hit on Windows
try:
owner_home = Path(pwd.getpwuid(uid).pw_dir)
except (KeyError, OSError, AttributeError):
return False
try:
return owner_home.resolve() == user_home.resolve()
except (OSError, RuntimeError):
return owner_home == user_home
def get_hostname() -> str:
"""Get the system hostname."""
return platform.node()
@functools.lru_cache(maxsize=1)
def in_container() -> bool:
"""Best-effort detection of whether we're running inside a container.
Combines several signals because no single one is reliable across runtimes
and kernels:
- ``/.dockerenv`` / ``/run/.containerenv`` — Docker / Podman runtime markers.
- root filesystem mounted as ``overlay`` — cgroup-version-agnostic.
- ``/proc/1/cgroup`` docker/lxc/kube markers — cgroup v1 ONLY (v2 shows
``0::/`` from inside, so this is a fallback, not the primary check).
This is for honest behavioural branching, not security — every marker here
is forgeable by whoever controls the container. Result is cached for the
process lifetime.
"""
try:
if os.path.exists("/.dockerenv") or os.path.exists("/run/.containerenv"):
return True
except OSError:
pass
try:
with open("/proc/mounts", encoding="utf-8") as f:
for line in f:
parts = line.split()
if len(parts) >= 3 and parts[1] == "/" and parts[2] == "overlay":
return True
except OSError:
pass
try:
with open("/proc/1/cgroup", encoding="utf-8") as f:
blob = f.read()
if any(marker in blob for marker in ("/docker", "/lxc", "kubepods", "/containerd")):
return True
except OSError:
pass
return False
class DsclBatchData(NamedTuple):
uid_map: Dict[str, int]
shell_map: Dict[str, str]
hidden_set: FrozenSet[str]
def _parse_dscl_list_output(output: Optional[str]) -> Dict[str, str]:
"""Parse ``dscl . -list`` output into {username: value}."""
if not output:
return {}
result: Dict[str, str] = {}
for line in output.splitlines():
parts = line.split()
if len(parts) >= 2:
result[parts[0]] = parts[-1]
return result
def _fetch_dscl_batch_data() -> DsclBatchData:
"""Fetch UID, shell, and IsHidden data for all users in 3 bulk dscl calls.
Each query is independently try/excepted — a single failure yields
an empty map for that attribute while the others remain populated.
"""
uid_map: Dict[str, int] = {}
shell_map: Dict[str, str] = {}
hidden_set: FrozenSet[str] = frozenset()
try:
raw = run_command(["dscl", ".", "-list", "/Users", "UniqueID"], timeout=DSCL_TIMEOUT)
for name, val in _parse_dscl_list_output(raw).items():
try:
uid_map[name] = int(val)
except ValueError:
pass
except Exception as exc:
logger.debug(f"Batch dscl UniqueID query failed: {exc}")
try:
raw = run_command(["dscl", ".", "-list", "/Users", "UserShell"], timeout=DSCL_TIMEOUT)
shell_map = _parse_dscl_list_output(raw)
except Exception as exc:
logger.debug(f"Batch dscl UserShell query failed: {exc}")
try:
raw = run_command(["dscl", ".", "-list", "/Users", "IsHidden"], timeout=DSCL_TIMEOUT)
hidden_set = frozenset(
name for name, val in _parse_dscl_list_output(raw).items() if val == "1"
)
except Exception as exc:
logger.debug(f"Batch dscl IsHidden query failed: {exc}")
return DsclBatchData(uid_map=uid_map, shell_map=shell_map, hidden_set=hidden_set)
def _is_human_user_macos(username: str, batch_data: DsclBatchData) -> bool:
"""Check if a macOS username is a real human user using batch dscl data.
Empty maps (from failed batch queries) cause that check to pass through.
"""
try:
if batch_data.uid_map and username not in batch_data.uid_map:
logger.debug(f"Filtering user '{username}': not in uid_map")
return False
except Exception as exc:
logger.debug(f"uid_map lookup failed for '{username}': {exc}")
try:
uid = batch_data.uid_map.get(username)
if uid is not None and uid < MACOS_MIN_HUMAN_UID:
logger.debug(f"Filtering user '{username}': UID {uid} < {MACOS_MIN_HUMAN_UID}")
return False
except Exception as exc:
logger.debug(f"UID check failed for '{username}': {exc}")
try:
shell = batch_data.shell_map.get(username)
if shell in NON_INTERACTIVE_SHELLS:
logger.debug(f"Filtering user '{username}': non-interactive shell {shell}")
return False
except Exception as exc:
logger.debug(f"Shell check failed for '{username}': {exc}")
try:
if username in batch_data.hidden_set:
logger.debug(f"Filtering user '{username}': hidden")
return False
except Exception as exc:
logger.debug(f"Hidden check failed for '{username}': {exc}")
return True
def get_all_users_macos() -> List[str]:
"""
Get all user directories from /Users on macOS.
Filters out hidden directories, directories in MACOS_SKIP_USER_DIRS,
and accounts that fail the _is_human_user_macos checks (service
accounts, MDM profiles, etc.).
Returns:
List of usernames (directory names in /Users)
"""
users = []
if platform.system() != "Darwin":
return users
users_dir = Path("/Users")
if not users_dir.exists():
return users
batch_data = _fetch_dscl_batch_data()
try:
for user_dir in users_dir.iterdir():
if (user_dir.is_dir()
and not user_dir.name.startswith('.')
and user_dir.name not in MACOS_SKIP_USER_DIRS
and _is_human_user_macos(user_dir.name, batch_data=batch_data)):
users.append(user_dir.name)
except (PermissionError, OSError) as e:
logger.warning(f"Could not list users from /Users: {e}")
return users
def get_all_users_windows() -> List[str]:
"""
Get all user directory names from C:\\Users on Windows.
Filters out hidden directories and well-known system/service
directories listed in WINDOWS_SKIP_USER_DIRS.
Returns:
List of usernames (directory names under C:\\Users), or an
empty list if not running on Windows or the path does not exist.
"""
if platform.system() != "Windows":
return []
try:
win_users_dir = Path(Path.home().anchor) / "Users"
if not win_users_dir.exists():
return []
users = []
for user_dir in win_users_dir.iterdir():
if (user_dir.is_dir()
and not user_dir.name.startswith('.')
and user_dir.name not in WINDOWS_SKIP_USER_DIRS):
users.append(user_dir.name)
return users
except (PermissionError, OSError) as e:
logger.warning(f"Could not list users from Windows Users directory: {e}")
return []
def get_all_users_linux() -> List[str]:
"""
Get all human user directory names from /home on Linux.
Parses /etc/passwd to filter out system accounts (UID < 1000) and
accounts with non-interactive shells (nologin, false, etc.).
Falls back to listing /home subdirectories when /etc/passwd is unreadable.
Returns:
List of usernames (directory names under /home), or an empty list
if not running on Linux or /home does not exist.
"""
if platform.system() != "Linux":
return []
home_dir = Path("/home")
if not home_dir.exists():
# Docker/CI root-only containers may have no /home at all
if _is_root():
return ["root"]
return []
# Build a set of usernames with UID >= 1000 and interactive shells
# from /etc/passwd so we filter out service accounts.
human_users: set = set()
try:
with open("/etc/passwd", encoding="utf-8", errors="replace") as f:
for line in f:
line = line.strip()
if not line or line.startswith("#"):
continue
parts = line.split(":")
if len(parts) < 7:
continue
username, _, uid_str, _, _, home_path, shell = (
parts[0], parts[1], parts[2], parts[3], parts[4], parts[5], parts[6]
)
try:
uid = int(uid_str)
except ValueError:
continue
if uid < 1000:
continue
if shell in NON_INTERACTIVE_SHELLS:
continue
# Only include users whose home is under /home
if home_path.startswith("/home/"):
human_users.add(username)
except Exception as e:
logger.debug(f"Could not parse /etc/passwd: {e}")
users: List[str] = []
try:
for user_dir in home_dir.iterdir():
if not user_dir.is_dir() or user_dir.name.startswith("."):
continue
# If we got passwd data, require UID >= 1000 filter; otherwise allow all
if human_users and user_dir.name not in human_users:
continue
users.append(user_dir.name)
except (PermissionError, OSError) as e:
logger.warning(f"Could not list users from /home: {e}")
# Always include root's own account when running as root, regardless of /home contents
if _is_root():
root_name = Path("/root").name # "root"
if root_name not in users:
users.append(root_name)
return users
def get_user_info() -> str:
"""
Get current user information (whoami equivalent).
Cross-platform function that returns username.
Gets username directly from system information, not environment variables.
On macOS, when running as root, finds the user with the most storage space
in /Users directory to get the actual user instead of "root".
On Windows, when running as administrator, finds the actual logged-in user
by querying explorer.exe process owner, Win32_ComputerSystem, or active console
session instead of returning "Administrator" or "admin".
Returns:
Current username as string
"""
try:
username = None
if platform.system() == "Windows":
# Use whoami command on Windows (works reliably)
whoami_output = run_command(["whoami"], COMMAND_TIMEOUT)
# Extract just the username if whoami returns DOMAIN\username format
if username and "\\" in username:
username = username.split("\\")[-1]
else:
# On macOS/Linux, check if running as root first
current_user = run_command(["whoami"], COMMAND_TIMEOUT)
# If running as root on macOS, try to find the actual user
if current_user == "root" and platform.system() == "Darwin":
# Method 1: Get console user (most direct and reliable)
username = run_command(["stat", "-f", "%Su", "/dev/console"], COMMAND_TIMEOUT)
# Method 2: Fallback to finding user with most storage space in /Users
# Command: du -sk /Users/* 2>/dev/null | awk '!/\/Shared$/ {print}' | sort -nr | head -1 | awk -F/ '{print $NF}'
# Using shell=True to properly handle glob expansion and pipes
if not username:
try:
result = subprocess.run(
"du -sk /Users/* 2>/dev/null | awk '!/\\/Shared$/ {print}' | sort -nr | head -1 | awk -F/ '{print $NF}'",
shell=True,
capture_output=True,
text=True,
timeout=COMMAND_TIMEOUT
)
if result.returncode == 0 and result.stdout.strip():
username = result.stdout.strip()
except Exception as e:
logger.debug(f"Failed to get user from storage space: {e}")
# If not root or methods above didn't work, use standard methods
if not username:
username = current_user
if not username:
# Fallback to id -un
username = run_command(["id", "-un"], COMMAND_TIMEOUT)
# Final fallback to getpass (uses system user database)
if not username:
import getpass
username = getpass.getuser()
return username or "unknown"
except Exception as e:
logger.warning(f"Could not extract username: {e}")
return "unknown"
def resolve_windows_shortcut(shortcut_path: Path) -> Optional[Path]:
"""
Resolve Windows .lnk shortcut to its target path.
Args:
shortcut_path: Path to the .lnk file
Returns:
Target path or None if resolution failed
"""
try:
ps_command = (
f'$shell = New-Object -ComObject WScript.Shell; '
f'$shortcut = $shell.CreateShortcut({repr(str(shortcut_path))}); '
f'$shortcut.TargetPath'
)
output = run_command(["powershell", "-Command", ps_command], VERSION_TIMEOUT)
if output and Path(output).exists():
return Path(output)
except Exception:
pass
return None
def normalize_url(domain: str) -> str:
"""Normalize domain to proper URL format."""
domain = domain.strip()
if domain.startswith("http://") or domain.startswith("https://"):
url = domain
else:
url = f"https://{domain}"
return url.rstrip('/')
def send_scan_event(
backend_url: str,
api_key: str,
device_id: str,
run_id: str,
scan_event: str,
app_name: Optional[str] = None,
home_user: Optional[str] = None,
scan_error: Optional[Dict] = None,
sentry_context: Optional[Dict] = None
) -> Tuple[bool, bool]:
"""
Send scan lifecycle event to backend (in_progress, completed, failed).
Args:
backend_url: Backend URL to send the event to
api_key: API key for authentication
device_id: Device identifier
run_id: UUID for this scan run (client-generated)
scan_event: Event type - "in_progress", "completed", or "failed"
app_name: Optional application name (e.g., JumpCloud)
home_user: Optional user context (for user-specific failures)
scan_error: Optional error data (required when scan_event="failed")
sentry_context: Optional context dict forwarded to Sentry on failure
Returns:
Tuple of (success, retryable): success=True if sent, retryable=True if caller should queue
"""
payload = {
"device_id": device_id,
"run_id": run_id,
"scan_event": scan_event,
}
if app_name:
payload["app_name"] = app_name
if home_user:
payload["home_user"] = home_user
if scan_error:
payload["scan_error"] = scan_error
return send_report_to_backend(
backend_url,
api_key,
payload,
app_name,
sentry_context
)
def send_report_to_backend(backend_url: str, api_key: str, report: Dict, app_name: Optional[str] = None, sentry_context: Optional[Dict] = None) -> Tuple[bool, bool]:
"""
Send discovery report to backend endpoint using curl with retry logic.
Uses curl subprocess to avoid Zscaler certificate issues with urllib.
Retries up to 3 times with exponential backoff (2s, 4s) for retryable errors.
Non-retryable HTTP errors (400, 401, 403, 404, 405, 422) fail immediately.
For data reports (payloads carrying a non-empty ``tools`` list), tries the
S3 presigned-upload path first (3-step: upload-url → S3 PUT → from-s3). On
any failure, falls through to this legacy direct-POST endpoint, which has
its own retry/queue logic. Scan-lifecycle events bypass S3 and use the
legacy endpoint directly — they are tiny.
Args:
backend_url: Backend URL to send the report to
api_key: API key for authentication
report: Report dictionary to send
app_name: Optional application name (e.g., JumpCloud) to include in request body
sentry_context: Optional context dict forwarded to Sentry on failure
Returns:
Tuple of (success, retryable): success=True if sent, retryable=True if caller should queue
"""
NON_RETRYABLE_CODES = (400, 401, 403, 404, 405, 422)
MAX_ATTEMPTS = 3
BACKOFF_SECONDS = [2, 4]
url = f"{normalize_url(backend_url)}/api/v1/ai-tools/report/"
ctx = sentry_context or {}
if not api_key or not api_key.strip():
logger.error("API key is empty or missing. Please provide a valid API key.")
return (False, False)
payload = dict(report)
if app_name:
payload["app_name"] = app_name
# Stamp tool_name + hash atomically; backend uses both to dedup unchanged re-scans.
from .s3_uploader import compute_payload_hash, should_use_s3, try_s3_upload
tools = payload.get("tools")
if isinstance(tools, list) and len(tools) == 1 and isinstance(tools[0], dict):
raw_name = tools[0].get("name")
if isinstance(raw_name, str) and raw_name.strip():
try:
payload_hash = compute_payload_hash(tools[0])
payload["tool_name"] = raw_name.strip()
payload["payload_hash"] = payload_hash
except Exception as e:
# Hash failure should never block the upload — log and proceed.
logger.warning(f"Could not compute payload hash, dedup disabled for this report: {e}")
if should_use_s3(payload):
s3_success, _ = try_s3_upload(
backend_url, api_key, payload, sentry_context=ctx,
)
if s3_success:
return (True, False)
logger.info("S3 upload path failed; falling back to legacy /api/v1/ai-tools/report/")
payload_json = json.dumps(payload)
ctx = {
**ctx,
"payload_size_bytes": len(payload_json),
"payload_keys": ",".join(sorted(payload.keys())),
}
# Write payload to a temp file to avoid OSError when payload exceeds ARG_MAX.
# The file is written once and reused across retries, then cleaned up in finally.
try:
fd, tmp_path = tempfile.mkstemp(prefix="ai-discovery-payload-", suffix=".json")
except OSError as e:
logger.error(f"Could not create temp file for payload: {e}")
report_to_sentry(e, {**ctx, "phase": "send_report_tmpfile"}, level="warning")
return (False, True)
try:
try:
os.write(fd, payload_json.encode("utf-8"))
finally:
os.close(fd)
for attempt in range(1, MAX_ATTEMPTS + 1):
try:
result = subprocess.run(
[
"curl", "-s",
"-X", "POST",
"-H", f"Authorization: Bearer {api_key}",
"-H", "Content-Type: application/json",
"-H", "User-Agent: AI-Tools-Discovery/1.0",
"-d", f"@{tmp_path}",
"--max-time", "60",
"-w", "\n%{http_code}",
url,
],
capture_output=True,
text=True,
timeout=65,
)
# Parse response: stdout = body + "\n" + http_code
lines = result.stdout.rsplit("\n", 1)
status_str = lines[-1].strip() if lines else ""
response_body = lines[0] if len(lines) > 1 else ""
if result.returncode != 0 or not status_str.isdigit():
# Connection/DNS failure — retryable
error_msg = result.stderr.strip() or f"curl exit code {result.returncode}"
logger.error(f"Attempt {attempt}/{MAX_ATTEMPTS} failed: {error_msg}")
if attempt < MAX_ATTEMPTS:
_backoff(attempt, BACKOFF_SECONDS)
continue
try:
raise RuntimeError(error_msg)
except RuntimeError as exc:
report_to_sentry(exc, {**ctx, "phase": "send_report", "attempt": attempt, "curl_stderr": (result.stderr.strip() or "")[:1024]}, level="warning")
return (False, True)
http_code = int(status_str)
if 200 <= http_code < 300:
return (True, False)
logger.error(f"Attempt {attempt}/{MAX_ATTEMPTS} failed: HTTP {http_code}")
_log_http_error_details(http_code, response_body or None)
# Cloudflare 403s with error 1010 are transient rate limits — allow retry
is_cloudflare_block = http_code == 403 and response_body and "1010" in response_body
if http_code in NON_RETRYABLE_CODES and not is_cloudflare_block:
try:
error_detail = f"HTTP {http_code}"
if response_body:
error_detail += f": {response_body[:200]}"
raise RuntimeError(error_detail)
except RuntimeError as exc:
report_to_sentry(exc, {**ctx, "phase": "send_report", "http_code": http_code, "attempt": attempt, "response_body": (response_body or "")[:1024]}, level="warning")
return (False, False)
if attempt < MAX_ATTEMPTS:
_backoff(attempt, BACKOFF_SECONDS)
else:
try:
error_detail = f"HTTP {http_code}"
if response_body:
error_detail += f": {response_body[:200]}"
raise RuntimeError(error_detail)
except RuntimeError as exc:
report_to_sentry(exc, {**ctx, "phase": "send_report", "http_code": http_code, "attempt": attempt, "response_body": (response_body or "")[:1024]}, level="warning")
return (False, True)
except subprocess.TimeoutExpired:
logger.error(f"Attempt {attempt}/{MAX_ATTEMPTS} timed out")
if attempt < MAX_ATTEMPTS:
_backoff(attempt, BACKOFF_SECONDS)
else:
try:
raise RuntimeError("curl timeout")
except RuntimeError as exc:
report_to_sentry(exc, {**ctx, "phase": "send_report", "attempt": attempt}, level="warning")
return (False, True)
except Exception as e:
logger.error(f"Attempt {attempt}/{MAX_ATTEMPTS} error: {e}")
if attempt < MAX_ATTEMPTS:
_backoff(attempt, BACKOFF_SECONDS)
else:
report_to_sentry(e, {**ctx, "phase": "send_report", "attempt": attempt}, level="warning")
return (False, True)
return (False, True)
finally:
try:
os.unlink(tmp_path)
except OSError:
pass
def _log_http_error_details(code: int, error_body: Optional[str]) -> None:
"""Log contextual details for specific HTTP error codes."""
if code == 403:
if error_body and "1010" in error_body:
logger.error("403 Forbidden - Cloudflare/WAF blocked the request (Error 1010)")
else:
logger.error("403 Forbidden - Authentication failed. Check API key.")
if error_body:
logger.error(f" Backend message: {error_body}")
elif error_body:
logger.error(f"Backend response: {error_body}")
def _backoff(attempt: int, delays: List[int]) -> None:
"""Sleep for the backoff duration corresponding to the given attempt."""
wait = delays[attempt - 1]
logger.info(f" Retrying in {wait}s...")
time.sleep(wait)
# ---------------------------------------------------------------------------
# Persistence: queue failed reports for the next run
# ---------------------------------------------------------------------------
def _get_queue_file_path() -> Path:
"""Return platform-appropriate queue file path.
If AI_DISCOVERY_QUEUE_FILE is set (and non-empty) in the environment,
that path is used verbatim. This lets the test harness redirect the
queue away from the real per-UID /var/tmp file so an interrupted test
can never leave a fixture that a later real agent run would drain and
POST to production.
On Unix, /var/tmp persists across reboots (unlike /tmp).
The filename includes the current UID so that different users
(e.g. root via MDM vs. a regular login user) each get their own
queue file, avoiding PermissionError on files created with 0600.
On Windows, fall back to the standard temp directory (already per-user).
"""
override = (os.environ.get("AI_DISCOVERY_QUEUE_FILE") or "").strip()
if override:
return Path(os.path.expanduser(os.path.expandvars(override)))
if platform.system() == "Windows":
return Path(tempfile.gettempdir()) / "ai-discovery-queue.json"
uid = os.getuid()
return Path(f"/var/tmp/ai-discovery-queue-{uid}.json")
QUEUE_MAX_AGE_SECONDS = 86400 # 24 hours
MAX_QUEUE_SIZE = 100 # Prevent unbounded growth across successive failures
def save_failed_reports(reports: List[Dict]) -> None:
"""Write failed report envelopes to the queue file, merging with any existing entries."""
try:
existing = _load_queue_file_safe()
now_iso = datetime.now(timezone.utc).isoformat()
envelopes = existing + [
{"report": r, "queued_at": now_iso} for r in reports
]
# Keep only the most recent entries to prevent unbounded growth
envelopes = envelopes[-MAX_QUEUE_SIZE:]
queue_file = _get_queue_file_path()
_write_file_secure(queue_file, json.dumps(envelopes).encode())
logger.info(f"Saved {len(reports)} failed report(s) to {queue_file}")
except Exception as e:
logger.warning(f"Could not save failed reports: {e}")
report_to_sentry(e, {"phase": "queue"}, level="warning")
def load_pending_reports() -> List[Dict]:
"""Load pending reports from the queue file and return the list.
Reports older than 24 hours are silently discarded.
"""
old_shared = Path("/var/tmp/ai-discovery-queue.json")
if platform.system() != "Windows" and old_shared.exists():
logger.info(
f"Legacy shared queue file detected at {old_shared}"
f" -- can be removed with: sudo rm {old_shared}"
)
queue_file = _get_queue_file_path()
if not queue_file.exists():
return []
try:
envelopes = json.loads(queue_file.read_text())
except Exception as e:
logger.warning(f"Could not load pending reports: {e}")
report_to_sentry(e, {"phase": "queue"}, level="warning")
return []
now = datetime.now(timezone.utc)
valid: List[Dict] = []
for envelope in envelopes:
try:
queued_at = datetime.fromisoformat(envelope["queued_at"])
if (now - queued_at).total_seconds() > QUEUE_MAX_AGE_SECONDS:
logger.debug("Discarding stale queued report (older than 24h)")
continue
valid.append(envelope["report"])
except Exception:
# Malformed envelope -- keep the report data if present
valid.append(envelope.get("report", envelope))
expired_count = len(envelopes) - len(valid)
logger.info(f"Loaded {len(valid)} pending report(s) from queue ({expired_count} expired)")
return valid
def _load_queue_file_safe() -> List[Dict]:
"""Load existing queue file contents, returning an empty list on any error."""
queue_file = _get_queue_file_path()
if not queue_file.exists():
return []
try:
return json.loads(queue_file.read_text())
except Exception:
return []
def _write_file_secure(path: Path, data: bytes) -> None:
"""Write data to a file with restricted permissions (0600 on Unix)."""
# Ensure the parent exists so a queue-path override with a missing parent
# doesn't silently drop the write (and lose the failed reports).
path.parent.mkdir(parents=True, exist_ok=True)
path.write_bytes(data)
# Restrict permissions to owner-only (rw-------) on Unix systems
try:
path.chmod(0o600)
except OSError:
pass
# ---------------------------------------------------------------------------
# Claude Code subscription plan detection
# ---------------------------------------------------------------------------
def _is_root() -> bool:
"""Check if the current process is running as root (UID 0).
Returns False on Windows where os.getuid() is not available.
"""
try:
return os.getuid() == 0
except AttributeError:
return False
def _get_uid_for_user(username: str) -> Optional[int]:
"""Resolve username to UID via the pwd module.
Returns the numeric UID or None if the user cannot be found.
"""
if pwd is None:
return None
try:
return pwd.getpwnam(username).pw_uid
except (KeyError, ImportError):
return None
def _is_daemon_container() -> bool:
"""Detect if running inside a macOS Daemon Container (e.g. Rippling MDM).
Daemon Containers redirect Path.home() to a path under
~/Library/Daemon Containers/<UUID>/Data/Downloads.
"""
return "Daemon Containers" in str(Path.home())
def _get_real_home(username: str) -> Optional[str]:
"""Resolve the real home directory for a user via the pwd module.
Returns the home directory path or None if it cannot be resolved.
"""
if pwd is None:
return None
try:
return pwd.getpwnam(username).pw_dir
except (KeyError, ImportError):
return None
_COMPATIBLE_SHELLS = frozenset({"/bin/bash", "/bin/zsh", "/bin/sh"})