Repository navigation
Expand file tree
/
Copy pathsync_security.py
More file actions
209 lines (181 loc) · 6.7 KB
/
Copy pathsync_security.py
File metadata and controls
209 lines (181 loc) · 6.7 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
# =============================================================================
# sync_security.py - Shared Input Sanitization, Secret Loader & File Scanner
# Designed and programmed by Mr.T
# =============================================================================
import json
from pathlib import Path, PurePosixPath
import re
DEFAULT_IGNORED_DIRS = {
".git",
".github",
"__pycache__",
".buildozer",
"bin",
".gradle",
".idea",
".vscode",
"node_modules",
}
DEFAULT_SECRET_FILENAMES = {
".env",
".env.local",
".env.production",
".env.development",
".pypirc",
".npmrc",
"credentials.json",
"client_secret.json",
"service_account.json",
"service-account.json",
"secrets.json",
"token.json",
"gh_token.txt",
"gdrive_token.json",
"gdrive_token.txt",
"onedrive_token.json",
"onedrive_token.txt",
"id_rsa",
"id_ed25519",
}
DEFAULT_SECRET_EXTENSIONS = {".pem", ".key", ".p12", ".pfx"}
SLUG_RE = re.compile(r"^[A-Za-z0-9_.-]+$")
BRANCH_RE = re.compile(r"^[A-Za-z0-9_./-]+$")
def sanitize_repo_slug(value: str, label: str) -> str:
cleaned = (value or "").strip()
if not cleaned or not SLUG_RE.match(cleaned) or cleaned in (".", ".."):
raise ValueError(f"Invalid {label}: use letters, numbers, '.', '_' or '-' only.")
return cleaned
def sanitize_branch_name(branch: str) -> str:
cleaned = (branch or "main").strip()
if (
not cleaned
or not BRANCH_RE.match(cleaned)
or ".." in cleaned
or cleaned.startswith("/")
or cleaned.endswith("/")
):
raise ValueError("Invalid branch name.")
return cleaned
def sanitize_remote_prefix(prefix: str) -> str:
raw = (prefix or "").strip().replace("\\", "/").strip("/")
if not raw:
return ""
if any(ord(ch) < 32 for ch in raw):
raise ValueError("Remote folder path cannot contain control characters.")
parts: list[str] = []
for seg in raw.split("/"):
seg = seg.strip()
if not seg or seg == ".":
continue
if seg == "..":
raise ValueError("Remote folder path cannot contain '..' traversal segments.")
parts.append(seg)
return "/".join(parts)
def parse_credential_input(raw_input: str, file_path_str: str = "") -> dict:
"""
Parse either a raw Bearer token string or a JSON credential payload
(from direct input or a local file outside the synced folder).
"""
source_text = (raw_input or "").strip()
if not source_text and file_path_str:
cleaned_path = file_path_str.strip().strip('"').strip("'")
if cleaned_path:
p = Path(cleaned_path)
if not p.exists() or not p.is_file():
raise ValueError("Credential file path does not exist or is not a file.")
try:
source_text = p.read_text(encoding="utf-8").strip()
except OSError as exc:
raise ValueError(f"Unable to read credential file: {exc}") from exc
if not source_text:
return {}
if source_text.startswith("{"):
try:
parsed = json.loads(source_text)
except json.JSONDecodeError as exc:
raise ValueError("Invalid JSON format in credential input/file.") from exc
if not isinstance(parsed, dict):
raise ValueError("JSON credential payload must be a JSON object.")
if "installed" in parsed and isinstance(parsed["installed"], dict):
merged = dict(parsed["installed"])
for k in ("refresh_token", "access_token", "token", "tenant"):
if k in parsed:
merged[k] = parsed[k]
parsed = merged
elif "web" in parsed and isinstance(parsed["web"], dict):
merged = dict(parsed["web"])
for k in ("refresh_token", "access_token", "token", "tenant"):
if k in parsed:
merged[k] = parsed[k]
parsed = merged
token_val = (
parsed.get("access_token")
or parsed.get("token")
or parsed.get("bearer_token")
or ""
)
return {
"access_token": str(token_val).strip(),
"refresh_token": str(parsed.get("refresh_token", "")).strip(),
"client_id": str(parsed.get("client_id", "")).strip(),
"client_secret": str(parsed.get("client_secret", "")).strip(),
"tenant": str(parsed.get("tenant", "")).strip(),
}
return {
"access_token": source_text,
"refresh_token": "",
"client_id": "",
"client_secret": "",
"tenant": "",
}
def collect_local_files(
local_folder: str,
excluded_files: set[Path] | None = None,
) -> tuple[Path, list[tuple[Path, str]], list[str]]:
cleaned = (local_folder or "").strip().strip('"').strip("'")
if not cleaned:
raise ValueError("Local folder path is required.")
root = Path(cleaned).expanduser().resolve()
if not root.exists() or not root.is_dir():
raise ValueError(f"Local folder does not exist: {cleaned}")
resolved_exclusions: set[Path] = set()
if excluded_files:
for item in excluded_files:
try:
resolved_exclusions.add(Path(item).expanduser().resolve())
except OSError:
pass
files: list[tuple[Path, str]] = []
skip_logs: list[str] = []
def _walk(current_dir: Path):
try:
entries = sorted(current_dir.iterdir(), key=lambda p: p.name.lower())
except OSError as exc:
skip_logs.append(f"[WARN] Cannot read directory {current_dir.name}: {exc}")
return
for entry in entries:
if entry.is_symlink():
continue
if entry.is_dir():
if entry.name in DEFAULT_IGNORED_DIRS:
continue
_walk(entry)
elif entry.is_file():
resolved_entry = entry.resolve()
rel_posix = PurePosixPath(entry.relative_to(root).as_posix()).as_posix()
if (
resolved_entry in resolved_exclusions
or entry.name.lower() in DEFAULT_SECRET_FILENAMES
or entry.suffix.lower() in DEFAULT_SECRET_EXTENSIONS
):
skip_logs.append(f"[SECURITY SKIP] {rel_posix} (protected secret file)")
continue
files.append((entry, rel_posix))
_walk(root)
return root, files, skip_logs
def redact_secrets(message: str, secrets: list[str]) -> str:
safe = str(message)
for sec in secrets:
if sec and len(sec) >= 6 and sec in safe:
safe = safe.replace(sec, "***REDACTED***")
return safe