zt-apollo-cli 0.4.0__tar.gz → 0.5.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.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: zt-apollo-cli
3
- Version: 0.4.0
3
+ Version: 0.5.0
4
4
  Summary: Apollo configuration management CLI
5
5
  Requires-Python: >=3.10
6
6
  Description-Content-Type: text/markdown
@@ -46,6 +46,20 @@ uv publish --token <your_token>
46
46
  zt-apollo-cli login
47
47
  ```
48
48
 
49
+ 有界面登录:
50
+
51
+ ```bash
52
+ zt-apollo-cli login --headed
53
+ ```
54
+
55
+ 也可以导入已经验证过的浏览器 SESSION。`cookie-file` 支持
56
+ `{"SESSION": "..."}` 对象或 Playwright cookie 数组;导入后 CLI 会先调用
57
+ Apollo 业务接口验证,成功后才覆盖本地缓存。
58
+
59
+ ```bash
60
+ zt-apollo-cli login --cookie-file ./cookies.json
61
+ ```
62
+
49
63
  ### 2) 查看部门列表
50
64
 
51
65
  ```bash
@@ -182,7 +196,9 @@ browser_channel: chromium
182
196
 
183
197
  支持通过环境变量自动填充登录页账号密码(如 SSO 页面字段可用):
184
198
 
185
- - `ZT_SSO_USERNAME`
186
- - `ZT_SSO_PASSWORD`
199
+ - `ZT_APOLLO_USERNAME`
200
+ - `ZT_APOLLO_PASSWORD`
201
+
202
+ 旧变量名 `ZT_SSO_USERNAME` / `ZT_SSO_PASSWORD` 仍然兼容。
187
203
 
188
204
  未设置时可在浏览器中手动完成登录。
@@ -33,6 +33,20 @@ uv publish --token <your_token>
33
33
  zt-apollo-cli login
34
34
  ```
35
35
 
36
+ 有界面登录:
37
+
38
+ ```bash
39
+ zt-apollo-cli login --headed
40
+ ```
41
+
42
+ 也可以导入已经验证过的浏览器 SESSION。`cookie-file` 支持
43
+ `{"SESSION": "..."}` 对象或 Playwright cookie 数组;导入后 CLI 会先调用
44
+ Apollo 业务接口验证,成功后才覆盖本地缓存。
45
+
46
+ ```bash
47
+ zt-apollo-cli login --cookie-file ./cookies.json
48
+ ```
49
+
36
50
  ### 2) 查看部门列表
37
51
 
38
52
  ```bash
@@ -169,7 +183,9 @@ browser_channel: chromium
169
183
 
170
184
  支持通过环境变量自动填充登录页账号密码(如 SSO 页面字段可用):
171
185
 
172
- - `ZT_SSO_USERNAME`
173
- - `ZT_SSO_PASSWORD`
186
+ - `ZT_APOLLO_USERNAME`
187
+ - `ZT_APOLLO_PASSWORD`
188
+
189
+ 旧变量名 `ZT_SSO_USERNAME` / `ZT_SSO_PASSWORD` 仍然兼容。
174
190
 
175
191
  未设置时可在浏览器中手动完成登录。
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "zt-apollo-cli"
7
- version = "0.4.0"
7
+ version = "0.5.0"
8
8
  description = "Apollo configuration management CLI"
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.10"
@@ -15,7 +15,8 @@ class ApolloApi:
15
15
  """发送 API 请求;认证失效时自动重新登录并重试一次"""
16
16
  cookies = get_auth_cookies()
17
17
  headers = get_auth_headers(cookies)
18
- extra_headers = kwargs.pop("headers", None)
18
+ request_kwargs = dict(kwargs)
19
+ extra_headers = request_kwargs.pop("headers", None)
19
20
  if extra_headers:
20
21
  headers.update(extra_headers)
21
22
  url = f"{self.base_url}/{path.lstrip('/')}"
@@ -25,7 +26,7 @@ class ApolloApi:
25
26
  url=url,
26
27
  headers=headers,
27
28
  cookies=cookies,
28
- **kwargs
29
+ **request_kwargs
29
30
  )
30
31
 
31
32
  if is_auth_error(response):
@@ -35,7 +36,11 @@ class ApolloApi:
35
36
  f"{response.status_code} {response.text[:500]}"
36
37
  )
37
38
  print("检测到认证失效,正在自动重新登录...")
38
- login()
39
+ refreshed_cookies = login()
40
+ if not refreshed_cookies or not refreshed_cookies.get("SESSION"):
41
+ raise RuntimeError(
42
+ "自动重新登录未返回有效 Apollo SESSION,已停止重试。"
43
+ )
39
44
  return self._request(method, path, _retried=True, **kwargs)
40
45
 
41
46
  if response.status_code >= 400:
@@ -0,0 +1,453 @@
1
+ """认证模块 - 通过 Playwright 获取浏览器 cookie"""
2
+ import json
3
+ import os
4
+ import sys
5
+ import tempfile
6
+ import time
7
+ from dataclasses import dataclass
8
+ from pathlib import Path
9
+ from typing import Mapping
10
+
11
+ import requests
12
+ from playwright.sync_api import Error as PlaywrightError
13
+ from playwright.sync_api import sync_playwright
14
+
15
+ from .config import config
16
+
17
+
18
+ APOLLO_DOMAIN = ".eminxing.com"
19
+ REQUIRED_COOKIES = ["SESSION"]
20
+ AUTH_PROBE_PATH = "/apps/search/by-appid-or-name"
21
+ _LOGIN_PATH_KEYWORDS = ("login", "sso", "auth", "signin", "cas", "oauth")
22
+ _LOGIN_FAILURE_HINTS = (
23
+ "incorrect username or password",
24
+ "invalid username or password",
25
+ "用户名或密码错误",
26
+ "账号或密码错误",
27
+ )
28
+
29
+
30
+ class LoginError(RuntimeError):
31
+ """登录流程失败,可安全展示给 CLI 用户。"""
32
+
33
+
34
+ class LoginTimeoutError(LoginError):
35
+ """等待用户完成登录超时。"""
36
+
37
+
38
+ @dataclass(frozen=True)
39
+ class AuthProbeResult:
40
+ authenticated: bool
41
+ status: int | None
42
+ content_type: str
43
+ error: str | None = None
44
+
45
+
46
+ def _cookie_domain_matches(domain: str) -> bool:
47
+ return domain == APOLLO_DOMAIN or APOLLO_DOMAIN in domain
48
+
49
+
50
+ def _auth_probe_url() -> str:
51
+ return (
52
+ f"{config.base_url}{AUTH_PROBE_PATH}"
53
+ "?query=&page=0&size=1"
54
+ )
55
+
56
+
57
+ def _get_response_header(response, name: str) -> str:
58
+ headers = getattr(response, "headers", None) or {}
59
+ for key, value in headers.items():
60
+ if key.lower() == name.lower():
61
+ return str(value)
62
+ return ""
63
+
64
+
65
+ def _evaluate_probe_response(response) -> AuthProbeResult:
66
+ status = getattr(response, "status", None)
67
+ if status is None:
68
+ status = getattr(response, "status_code", None)
69
+ content_type = _get_response_header(response, "content-type").lower()
70
+ authenticated = (
71
+ status == 200
72
+ and "application/json" in content_type
73
+ )
74
+ return AuthProbeResult(
75
+ authenticated=authenticated,
76
+ status=status,
77
+ content_type=content_type,
78
+ )
79
+
80
+
81
+ def _probe_browser_auth(page) -> AuthProbeResult:
82
+ try:
83
+ response = page.request.get(
84
+ _auth_probe_url(),
85
+ headers={
86
+ "Accept": "application/json, text/plain, */*",
87
+ "X-Requested-With": "XMLHttpRequest",
88
+ },
89
+ timeout=10000,
90
+ )
91
+ except Exception as exc:
92
+ return AuthProbeResult(
93
+ authenticated=False,
94
+ status=None,
95
+ content_type="",
96
+ error=str(exc),
97
+ )
98
+ return _evaluate_probe_response(response)
99
+
100
+
101
+ def _probe_cookie_auth(cookies: Mapping[str, str]) -> AuthProbeResult:
102
+ try:
103
+ response = requests.get(
104
+ _auth_probe_url(),
105
+ headers=get_auth_headers(dict(cookies)),
106
+ timeout=15,
107
+ )
108
+ except requests.RequestException as exc:
109
+ return AuthProbeResult(
110
+ authenticated=False,
111
+ status=None,
112
+ content_type="",
113
+ error=str(exc),
114
+ )
115
+ return _evaluate_probe_response(response)
116
+
117
+
118
+ def _probe_failure_detail(result: AuthProbeResult) -> str:
119
+ details = []
120
+ if result.status is not None:
121
+ details.append(f"status={result.status}")
122
+ if result.content_type:
123
+ details.append(f"content-type={result.content_type}")
124
+ if result.error:
125
+ details.append(f"error={result.error}")
126
+ return ", ".join(details) or "未收到有效响应"
127
+
128
+
129
+ def _wait_for_authenticated_page(
130
+ page,
131
+ *,
132
+ timeout_ms: int = 300000,
133
+ poll_interval_ms: int = 1000,
134
+ fail_on_login_error: bool = False,
135
+ ) -> None:
136
+ """轮询业务接口,确认服务端已经接受当前浏览器会话。"""
137
+ print("等待 Apollo 业务接口确认登录状态...")
138
+ deadline = time.monotonic() + max(timeout_ms, 0) / 1000
139
+ last_result = AuthProbeResult(False, None, "")
140
+
141
+ while True:
142
+ last_result = _probe_browser_auth(page)
143
+ if last_result.authenticated:
144
+ print("登录成功. 业务接口验证通过")
145
+ return
146
+
147
+ if fail_on_login_error:
148
+ login_error = _detect_login_error(page)
149
+ if login_error:
150
+ raise LoginError(f"自动登录失败: {login_error}")
151
+
152
+ if time.monotonic() >= deadline:
153
+ break
154
+ page.wait_for_timeout(poll_interval_ms)
155
+
156
+ raise LoginTimeoutError(
157
+ "登录超时,Apollo 业务接口仍未确认有效会话 "
158
+ f"({_probe_failure_detail(last_result)})。请重试并确认账号登录成功。"
159
+ )
160
+
161
+
162
+ def _detect_login_error(page) -> str | None:
163
+ try:
164
+ body_text = page.locator("body").inner_text(timeout=500).casefold()
165
+ except Exception:
166
+ return None
167
+
168
+ for hint in _LOGIN_FAILURE_HINTS:
169
+ if hint.casefold() in body_text:
170
+ return hint
171
+ return None
172
+
173
+
174
+ def save_cookies(cookies: dict):
175
+ """原子写入 cookie,避免失败登录覆盖已有凭据。"""
176
+ config.CONFIG_DIR.mkdir(parents=True, exist_ok=True)
177
+ fd, temp_path = tempfile.mkstemp(
178
+ prefix=f".{config.COOKIE_FILE.name}.",
179
+ dir=config.CONFIG_DIR,
180
+ )
181
+ try:
182
+ with os.fdopen(fd, "w") as f:
183
+ json.dump(cookies, f)
184
+ f.flush()
185
+ os.fsync(f.fileno())
186
+ os.chmod(temp_path, 0o600)
187
+ os.replace(temp_path, config.COOKIE_FILE)
188
+ finally:
189
+ if os.path.exists(temp_path):
190
+ os.unlink(temp_path)
191
+
192
+
193
+ def load_cookies() -> dict:
194
+ """从缓存文件加载 cookie"""
195
+ if config.COOKIE_FILE.exists():
196
+ try:
197
+ with open(config.COOKIE_FILE) as f:
198
+ data = json.load(f)
199
+ return data if isinstance(data, dict) else {}
200
+ except (OSError, ValueError):
201
+ return {}
202
+ return {}
203
+
204
+ def is_auth_error(response: requests.Response) -> bool:
205
+ """判断 HTTP 响应是否为认证失效(需重新登录)"""
206
+ if response.status_code == 401:
207
+ return True
208
+
209
+ if response.status_code in (301, 302, 303, 307, 308):
210
+ location = response.headers.get("Location", "").lower()
211
+ if any(keyword in location for keyword in _LOGIN_PATH_KEYWORDS):
212
+ return True
213
+
214
+ content_type = response.headers.get("Content-Type", "").lower()
215
+ if 200 <= response.status_code < 400 and "text/html" in content_type:
216
+ return True
217
+
218
+ return False
219
+
220
+
221
+ def get_auth_headers(cookies: dict) -> dict:
222
+ """从 cookie 构建认证请求头"""
223
+ session_cookie = "; ".join(f"{k}={v}" for k, v in cookies.items())
224
+ return {
225
+ "Accept": "application/json, text/plain, */*",
226
+ "Accept-Language": "zh-CN,zh;q=0.9",
227
+ "Connection": "keep-alive",
228
+ "Referer": f"{config.base_url}/",
229
+ "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/144.0.0.0 Safari/537.36",
230
+ "Cookie": session_cookie,
231
+ "X-Requested-With": "XMLHttpRequest",
232
+ }
233
+
234
+ def get_auth_cookies() -> dict:
235
+ """获取认证 cookie,优先使用缓存,失效则重新获取"""
236
+ cookies = load_cookies()
237
+ if all(cookies.get(k) for k in REQUIRED_COOKIES):
238
+ return cookies
239
+
240
+ # 缓存失效,重新获取
241
+ cookies = get_cookies_from_browser()
242
+ save_cookies(cookies)
243
+
244
+ print("已获取新的 Apollo Cookie")
245
+ return cookies
246
+
247
+
248
+ def _get_login_credentials() -> tuple[str | None, str | None]:
249
+ """兼容新旧环境变量,优先使用 Apollo 专用名称。"""
250
+ username = (
251
+ os.environ.get("ZT_APOLLO_USERNAME")
252
+ or os.environ.get("ZT_SSO_USERNAME")
253
+ )
254
+ password = (
255
+ os.environ.get("ZT_APOLLO_PASSWORD")
256
+ or os.environ.get("ZT_SSO_PASSWORD")
257
+ )
258
+ return username, password
259
+
260
+
261
+ def open_login_page(
262
+ page,
263
+ credentials: tuple[str | None, str | None] | None = None,
264
+ ) -> bool:
265
+ """自动登录 - 尝试读取环境变量自动填写账号密码"""
266
+ username, password = credentials or _get_login_credentials()
267
+
268
+ if not username or not password:
269
+ return False
270
+
271
+ print(f"检测到环境变量,自动登录中...")
272
+
273
+ try:
274
+ # 兼容常见账号密码输入框
275
+ user_selector = "#username, input[name='username'], input[type='text']"
276
+ pass_selector = "#password, #password2, input[name='password'], input[type='password']"
277
+ login_selector = ".login_in, button[type='submit'], .btn-login"
278
+
279
+ page.wait_for_selector(user_selector, timeout=15000)
280
+ page.fill(user_selector, username)
281
+ page.fill(pass_selector, password)
282
+ page.click(login_selector)
283
+ print("已尝试自动提交登录")
284
+
285
+ return True
286
+
287
+ except Exception as e:
288
+ print(f"自动登录失败: {e}")
289
+
290
+ return False
291
+
292
+
293
+ def _ensure_headed_browser_available() -> None:
294
+ if (
295
+ sys.platform.startswith("linux")
296
+ and not os.environ.get("DISPLAY")
297
+ and not os.environ.get("WAYLAND_DISPLAY")
298
+ ):
299
+ raise LoginError(
300
+ "当前会话没有图形显示,无法使用 --headed 登录。"
301
+ "请在有桌面环境的终端重试,或设置 ZT_APOLLO_USERNAME / "
302
+ "ZT_APOLLO_PASSWORD 使用无头自动登录。"
303
+ )
304
+
305
+
306
+ def _extract_apollo_cookies(context) -> dict:
307
+ cookie_dict = {}
308
+ for cookie in context.cookies():
309
+ if _cookie_domain_matches(cookie["domain"]):
310
+ cookie_dict[cookie["name"]] = cookie["value"]
311
+ return cookie_dict
312
+
313
+
314
+ def get_cookies_from_browser(
315
+ headless: bool = True,
316
+ *,
317
+ timeout_ms: int = 300000,
318
+ ) -> dict:
319
+ """通过 Playwright 从浏览器获取 cookie"""
320
+ credentials = _get_login_credentials()
321
+ if headless and not all(credentials):
322
+ raise LoginError(
323
+ "无头登录需要环境变量 ZT_APOLLO_USERNAME / "
324
+ "ZT_APOLLO_PASSWORD(兼容 ZT_SSO_USERNAME / "
325
+ "ZT_SSO_PASSWORD),或执行 zt-apollo-cli login "
326
+ "--headed 使用有界面浏览器登录。"
327
+ )
328
+
329
+ if headless:
330
+ print("正在启动浏览器(无头模式),请登录...")
331
+ else:
332
+ _ensure_headed_browser_available()
333
+ print("正在打开浏览器,请登录...")
334
+
335
+ with sync_playwright() as p:
336
+ try:
337
+ browser = p.chromium.launch(headless=headless)
338
+ except PlaywrightError as exc:
339
+ if headless:
340
+ raise LoginError(f"浏览器启动失败: {exc}") from exc
341
+ raise LoginError(
342
+ "有界面浏览器启动失败,请确认当前环境允许打开浏览器。"
343
+ f" 原始错误: {exc}"
344
+ ) from exc
345
+
346
+ try:
347
+ context = browser.new_context()
348
+ page = context.new_page()
349
+ page.goto(config.base_url, wait_until="domcontentloaded")
350
+
351
+ # 尝试自动登录
352
+ if not open_login_page(page, credentials=credentials):
353
+ if headless:
354
+ raise LoginError(
355
+ "检测到登录环境变量,但无法自动定位 Apollo "
356
+ "登录表单。请检查登录页结构,或使用 "
357
+ "zt-apollo-cli login --headed 登录。"
358
+ )
359
+ print(
360
+ "未自动登录. 请在浏览器中完成登录,"
361
+ "登录成功后会自动继续..."
362
+ )
363
+
364
+ _wait_for_authenticated_page(
365
+ page,
366
+ timeout_ms=timeout_ms,
367
+ fail_on_login_error=headless,
368
+ )
369
+ cookie_dict = _extract_apollo_cookies(context)
370
+ finally:
371
+ browser.close()
372
+
373
+ missing_cookies = [
374
+ name for name in REQUIRED_COOKIES if not cookie_dict.get(name)
375
+ ]
376
+ if missing_cookies:
377
+ raise LoginError(
378
+ "业务接口验证通过,但浏览器中缺少必要 cookie: "
379
+ + ", ".join(missing_cookies)
380
+ )
381
+ return cookie_dict
382
+
383
+
384
+ def load_cookie_file(path: str | Path) -> dict:
385
+ """读取普通 cookie 对象或 Playwright cookie 数组。"""
386
+ cookie_path = Path(path).expanduser()
387
+ try:
388
+ with open(cookie_path) as f:
389
+ data = json.load(f)
390
+ except (OSError, ValueError) as exc:
391
+ raise LoginError(f"无法读取 cookie 文件 {cookie_path}: {exc}") from exc
392
+
393
+ if isinstance(data, dict) and isinstance(data.get("cookies"), list):
394
+ data = data["cookies"]
395
+
396
+ if isinstance(data, dict):
397
+ cookies = {
398
+ str(name): str(value)
399
+ for name, value in data.items()
400
+ if value is not None
401
+ }
402
+ elif isinstance(data, list):
403
+ cookies = {}
404
+ for item in data:
405
+ if not isinstance(item, dict):
406
+ continue
407
+ domain = str(item.get("domain", ""))
408
+ name = item.get("name")
409
+ value = item.get("value")
410
+ if name and value is not None and (
411
+ not domain or _cookie_domain_matches(domain)
412
+ ):
413
+ cookies[str(name)] = str(value)
414
+ else:
415
+ raise LoginError(
416
+ "cookie 文件格式无效,应为 name/value 对象或 "
417
+ "Playwright cookie 数组。"
418
+ )
419
+
420
+ missing_cookies = [
421
+ name for name in REQUIRED_COOKIES if not cookies.get(name)
422
+ ]
423
+ if missing_cookies:
424
+ raise LoginError(
425
+ "cookie 文件缺少必要字段: " + ", ".join(missing_cookies)
426
+ )
427
+ return cookies
428
+
429
+
430
+ def login_with_cookie_file(path: str | Path) -> dict:
431
+ """导入 cookie 文件,验证通过后才写入缓存。"""
432
+ cookies = load_cookie_file(path)
433
+ result = _probe_cookie_auth(cookies)
434
+ if not result.authenticated:
435
+ raise LoginError(
436
+ "导入的 Apollo 会话无效 "
437
+ f"({_probe_failure_detail(result)})。"
438
+ )
439
+
440
+ save_cookies(cookies)
441
+ print("登录成功,Apollo cookie 已缓存!")
442
+ return cookies
443
+
444
+
445
+ def login(headless: bool = True) -> dict:
446
+ """登录并缓存 cookie"""
447
+ cookies = get_cookies_from_browser(headless=headless)
448
+ save_cookies(cookies)
449
+ print("登录成功,Apollo cookie 已缓存!")
450
+ return cookies
451
+
452
+ if __name__ == "__main__":
453
+ print(login())
@@ -4,7 +4,7 @@ import json
4
4
  import shutil
5
5
  from datetime import datetime
6
6
  from .api import ApolloApi
7
- from .auth import login
7
+ from .auth import LoginError, login, login_with_cookie_file
8
8
  from .config import config
9
9
 
10
10
  def _normalize_cell(value):
@@ -111,9 +111,24 @@ def cli(ctx, output_format, base_url):
111
111
  is_flag=True,
112
112
  help="显示浏览器窗口,用于无环境变量时的手动登录",
113
113
  )
114
- def cmd_login(headed):
114
+ @click.option(
115
+ "--cookie-file",
116
+ type=click.Path(exists=True, dir_okay=False, path_type=str),
117
+ help="从 JSON cookie 文件导入已有登录态",
118
+ )
119
+ def cmd_login(headed, cookie_file):
115
120
  """登录并缓存 Cookie"""
116
- login(headless=not headed)
121
+ try:
122
+ if cookie_file:
123
+ if headed:
124
+ raise click.UsageError(
125
+ "--cookie-file 与 --headed 不能同时使用"
126
+ )
127
+ login_with_cookie_file(cookie_file)
128
+ else:
129
+ login(headless=not headed)
130
+ except LoginError as exc:
131
+ raise click.ClickException(str(exc)) from exc
117
132
 
118
133
 
119
134
  @cli.group()
@@ -525,4 +540,4 @@ def main():
525
540
  cli()
526
541
 
527
542
  if __name__ == "__main__":
528
- main()
543
+ main()
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: zt-apollo-cli
3
- Version: 0.4.0
3
+ Version: 0.5.0
4
4
  Summary: Apollo configuration management CLI
5
5
  Requires-Python: >=3.10
6
6
  Description-Content-Type: text/markdown
@@ -46,6 +46,20 @@ uv publish --token <your_token>
46
46
  zt-apollo-cli login
47
47
  ```
48
48
 
49
+ 有界面登录:
50
+
51
+ ```bash
52
+ zt-apollo-cli login --headed
53
+ ```
54
+
55
+ 也可以导入已经验证过的浏览器 SESSION。`cookie-file` 支持
56
+ `{"SESSION": "..."}` 对象或 Playwright cookie 数组;导入后 CLI 会先调用
57
+ Apollo 业务接口验证,成功后才覆盖本地缓存。
58
+
59
+ ```bash
60
+ zt-apollo-cli login --cookie-file ./cookies.json
61
+ ```
62
+
49
63
  ### 2) 查看部门列表
50
64
 
51
65
  ```bash
@@ -182,7 +196,9 @@ browser_channel: chromium
182
196
 
183
197
  支持通过环境变量自动填充登录页账号密码(如 SSO 页面字段可用):
184
198
 
185
- - `ZT_SSO_USERNAME`
186
- - `ZT_SSO_PASSWORD`
199
+ - `ZT_APOLLO_USERNAME`
200
+ - `ZT_APOLLO_PASSWORD`
201
+
202
+ 旧变量名 `ZT_SSO_USERNAME` / `ZT_SSO_PASSWORD` 仍然兼容。
187
203
 
188
204
  未设置时可在浏览器中手动完成登录。
@@ -10,4 +10,6 @@ src/zt_apollo_cli.egg-info/SOURCES.txt
10
10
  src/zt_apollo_cli.egg-info/dependency_links.txt
11
11
  src/zt_apollo_cli.egg-info/entry_points.txt
12
12
  src/zt_apollo_cli.egg-info/requires.txt
13
- src/zt_apollo_cli.egg-info/top_level.txt
13
+ src/zt_apollo_cli.egg-info/top_level.txt
14
+ tests/test_api.py
15
+ tests/test_auth.py
@@ -0,0 +1,74 @@
1
+ import unittest
2
+ from unittest.mock import patch
3
+
4
+ from apollo_cli.api import ApolloApi
5
+
6
+
7
+ class FakeResponse:
8
+ def __init__(self, status_code=200, content_type="application/json", data=None):
9
+ self.status_code = status_code
10
+ self.headers = {"Content-Type": content_type}
11
+ self.text = "<html>login</html>" if "html" in content_type else ""
12
+ self._data = data or {}
13
+
14
+ def json(self):
15
+ return self._data
16
+
17
+
18
+ class ApiAuthRetryTests(unittest.TestCase):
19
+ def setUp(self):
20
+ self.api = ApolloApi()
21
+
22
+ def test_reauthenticates_and_retries_after_html_login_page(self):
23
+ responses = [
24
+ FakeResponse(content_type="text/html"),
25
+ FakeResponse(data={"content": []}),
26
+ ]
27
+ with (
28
+ patch(
29
+ "apollo_cli.api.get_auth_cookies",
30
+ return_value={"SESSION": "expired"},
31
+ ),
32
+ patch(
33
+ "apollo_cli.api.get_auth_headers",
34
+ return_value={"Cookie": "SESSION=expired"},
35
+ ),
36
+ patch(
37
+ "apollo_cli.api.login",
38
+ return_value={"SESSION": "fresh"},
39
+ ) as login,
40
+ patch(
41
+ "apollo_cli.api.requests.request",
42
+ side_effect=responses,
43
+ ) as request,
44
+ ):
45
+ result = self.api.search_apps("")
46
+
47
+ self.assertEqual(result, {"content": []})
48
+ self.assertEqual(request.call_count, 2)
49
+ login.assert_called_once_with()
50
+
51
+ def test_stops_retry_when_login_returns_no_session(self):
52
+ with (
53
+ patch(
54
+ "apollo_cli.api.get_auth_cookies",
55
+ return_value={"SESSION": "expired"},
56
+ ),
57
+ patch(
58
+ "apollo_cli.api.get_auth_headers",
59
+ return_value={"Cookie": "SESSION=expired"},
60
+ ),
61
+ patch("apollo_cli.api.login", return_value={}),
62
+ patch(
63
+ "apollo_cli.api.requests.request",
64
+ return_value=FakeResponse(content_type="text/html"),
65
+ ) as request,
66
+ ):
67
+ with self.assertRaisesRegex(RuntimeError, "未返回有效 Apollo SESSION"):
68
+ self.api.search_apps("")
69
+
70
+ request.assert_called_once()
71
+
72
+
73
+ if __name__ == "__main__":
74
+ unittest.main()
@@ -0,0 +1,196 @@
1
+ import json
2
+ import os
3
+ import stat
4
+ import tempfile
5
+ import unittest
6
+ from pathlib import Path
7
+ from unittest.mock import patch
8
+
9
+ from apollo_cli import auth
10
+
11
+
12
+ class FakeResponse:
13
+ def __init__(self, status=200, content_type="application/json"):
14
+ self.status = status
15
+ self.status_code = status
16
+ self.headers = {"content-type": content_type}
17
+
18
+
19
+ class FakePage:
20
+ def __init__(self, responses, body_text=""):
21
+ self.request = self
22
+ self.responses = iter(responses)
23
+ self.wait_calls = []
24
+ self.body_text = body_text
25
+
26
+ def get(self, *_args, **_kwargs):
27
+ response = next(self.responses)
28
+ if isinstance(response, Exception):
29
+ raise response
30
+ return response
31
+
32
+ def wait_for_timeout(self, timeout):
33
+ self.wait_calls.append(timeout)
34
+
35
+ def locator(self, _selector):
36
+ return self
37
+
38
+ def inner_text(self, **_kwargs):
39
+ return self.body_text
40
+
41
+
42
+ class AuthProbeTests(unittest.TestCase):
43
+ def test_probe_requires_json_response(self):
44
+ authenticated = auth._evaluate_probe_response(FakeResponse())
45
+ login_page = auth._evaluate_probe_response(
46
+ FakeResponse(content_type="text/html")
47
+ )
48
+
49
+ self.assertTrue(authenticated.authenticated)
50
+ self.assertFalse(login_page.authenticated)
51
+
52
+ def test_html_server_error_is_not_an_auth_error(self):
53
+ response = FakeResponse(status=500, content_type="text/html")
54
+
55
+ self.assertFalse(auth.is_auth_error(response))
56
+
57
+ def test_wait_accepts_authenticated_session(self):
58
+ page = FakePage([FakeResponse()])
59
+
60
+ auth._wait_for_authenticated_page(page, timeout_ms=0)
61
+
62
+ self.assertEqual(page.wait_calls, [])
63
+
64
+ def test_wait_times_out_without_authenticated_session(self):
65
+ page = FakePage([FakeResponse(content_type="text/html")])
66
+
67
+ with self.assertRaises(auth.LoginTimeoutError) as raised:
68
+ auth._wait_for_authenticated_page(page, timeout_ms=0)
69
+
70
+ self.assertIn("status=200", str(raised.exception))
71
+ self.assertIn("text/html", str(raised.exception))
72
+
73
+ def test_headless_login_fails_fast_on_credential_error(self):
74
+ page = FakePage(
75
+ [FakeResponse(content_type="text/html")],
76
+ body_text="Incorrect username or password",
77
+ )
78
+
79
+ with self.assertRaisesRegex(auth.LoginError, "自动登录失败"):
80
+ auth._wait_for_authenticated_page(
81
+ page,
82
+ timeout_ms=300000,
83
+ fail_on_login_error=True,
84
+ )
85
+
86
+ self.assertEqual(page.wait_calls, [])
87
+
88
+
89
+ class CredentialTests(unittest.TestCase):
90
+ def test_apollo_credentials_take_priority(self):
91
+ environment = {
92
+ "ZT_APOLLO_USERNAME": "apollo-user",
93
+ "ZT_APOLLO_PASSWORD": "apollo-password",
94
+ "ZT_SSO_USERNAME": "sso-user",
95
+ "ZT_SSO_PASSWORD": "sso-password",
96
+ }
97
+ with patch.dict(os.environ, environment, clear=True):
98
+ credentials = auth._get_login_credentials()
99
+
100
+ self.assertEqual(credentials, ("apollo-user", "apollo-password"))
101
+
102
+ def test_legacy_sso_credentials_remain_supported(self):
103
+ environment = {
104
+ "ZT_SSO_USERNAME": "sso-user",
105
+ "ZT_SSO_PASSWORD": "sso-password",
106
+ }
107
+ with patch.dict(os.environ, environment, clear=True):
108
+ credentials = auth._get_login_credentials()
109
+
110
+ self.assertEqual(credentials, ("sso-user", "sso-password"))
111
+
112
+
113
+ class CookiePersistenceTests(unittest.TestCase):
114
+ def test_save_cookies_is_private_and_atomic(self):
115
+ with tempfile.TemporaryDirectory() as temp_dir:
116
+ config_dir = Path(temp_dir)
117
+ cookie_file = config_dir / "cookies.json"
118
+ with (
119
+ patch.object(auth.config, "CONFIG_DIR", config_dir),
120
+ patch.object(auth.config, "COOKIE_FILE", cookie_file),
121
+ ):
122
+ auth.save_cookies({"SESSION": "valid-session"})
123
+
124
+ self.assertEqual(
125
+ json.loads(cookie_file.read_text()),
126
+ {"SESSION": "valid-session"},
127
+ )
128
+ self.assertEqual(
129
+ stat.S_IMODE(cookie_file.stat().st_mode),
130
+ 0o600,
131
+ )
132
+
133
+ def test_failed_login_does_not_save_cookies(self):
134
+ with (
135
+ patch.object(
136
+ auth,
137
+ "get_cookies_from_browser",
138
+ side_effect=auth.LoginError("failed"),
139
+ ),
140
+ patch.object(auth, "save_cookies") as save_cookies,
141
+ ):
142
+ with self.assertRaises(auth.LoginError):
143
+ auth.login()
144
+
145
+ save_cookies.assert_not_called()
146
+
147
+
148
+ class CookieFileTests(unittest.TestCase):
149
+ def test_load_plain_cookie_object(self):
150
+ with tempfile.TemporaryDirectory() as temp_dir:
151
+ path = Path(temp_dir) / "cookies.json"
152
+ path.write_text('{"SESSION": "session-value"}')
153
+
154
+ cookies = auth.load_cookie_file(path)
155
+
156
+ self.assertEqual(cookies, {"SESSION": "session-value"})
157
+
158
+ def test_load_playwright_cookie_array(self):
159
+ with tempfile.TemporaryDirectory() as temp_dir:
160
+ path = Path(temp_dir) / "cookies.json"
161
+ path.write_text(json.dumps([
162
+ {
163
+ "name": "SESSION",
164
+ "value": "session-value",
165
+ "domain": ".eminxing.com",
166
+ }
167
+ ]))
168
+
169
+ cookies = auth.load_cookie_file(path)
170
+
171
+ self.assertEqual(cookies, {"SESSION": "session-value"})
172
+
173
+ def test_invalid_import_does_not_save_cookies(self):
174
+ with tempfile.TemporaryDirectory() as temp_dir:
175
+ path = Path(temp_dir) / "cookies.json"
176
+ path.write_text('{"SESSION": "invalid-session"}')
177
+ with (
178
+ patch.object(
179
+ auth,
180
+ "_probe_cookie_auth",
181
+ return_value=auth.AuthProbeResult(
182
+ False,
183
+ 200,
184
+ "text/html",
185
+ ),
186
+ ),
187
+ patch.object(auth, "save_cookies") as save_cookies,
188
+ ):
189
+ with self.assertRaisesRegex(auth.LoginError, "会话无效"):
190
+ auth.login_with_cookie_file(path)
191
+
192
+ save_cookies.assert_not_called()
193
+
194
+
195
+ if __name__ == "__main__":
196
+ unittest.main()
@@ -1,169 +0,0 @@
1
- """认证模块 - 通过 Playwright 获取浏览器 cookie"""
2
- import json
3
- import os
4
-
5
- import requests
6
- from playwright.sync_api import sync_playwright
7
-
8
- from .config import config
9
-
10
-
11
- APOLLO_DOMAIN = ".eminxing.com"
12
- REQUIRED_COOKIES = ["SESSION"]
13
- _LOGIN_PATH_KEYWORDS = ("login", "sso", "auth", "signin", "cas", "oauth")
14
- _LOGIN_PAGE_HINTS = (
15
- 'id="username"',
16
- 'name="username"',
17
- 'type="password"',
18
- "login_in",
19
- "btn-login",
20
- "请登录",
21
- "未登录",
22
- )
23
-
24
- def save_cookies(cookies: dict):
25
- """保存 cookie 到缓存文件"""
26
- config.CONFIG_DIR.mkdir(parents=True, exist_ok=True)
27
- with open(config.COOKIE_FILE, "w") as f:
28
- json.dump(cookies, f)
29
-
30
- def load_cookies() -> dict:
31
- """从缓存文件加载 cookie"""
32
- if config.COOKIE_FILE.exists():
33
- with open(config.COOKIE_FILE) as f:
34
- return json.load(f)
35
- return {}
36
-
37
- def is_auth_error(response: requests.Response) -> bool:
38
- """判断 HTTP 响应是否为认证失效(需重新登录)"""
39
- if response.status_code == 401:
40
- return True
41
-
42
- if response.status_code in (301, 302, 303, 307, 308):
43
- location = response.headers.get("Location", "").lower()
44
- if any(keyword in location for keyword in _LOGIN_PATH_KEYWORDS):
45
- return True
46
-
47
- content_type = response.headers.get("Content-Type", "").lower()
48
- if "text/html" in content_type:
49
- body = response.text
50
- if any(hint in body for hint in _LOGIN_PAGE_HINTS):
51
- return True
52
-
53
- return False
54
-
55
-
56
- def get_auth_headers(cookies: dict) -> dict:
57
- """从 cookie 构建认证请求头"""
58
- session_cookie = "; ".join(f"{k}={v}" for k, v in cookies.items())
59
- return {
60
- "Accept": "application/json, text/plain, */*",
61
- "Accept-Language": "zh-CN,zh;q=0.9",
62
- "Connection": "keep-alive",
63
- "Referer": f"{config.base_url}/",
64
- "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/144.0.0.0 Safari/537.36",
65
- "Cookie": session_cookie,
66
- "X-Requested-With": "XMLHttpRequest",
67
- }
68
-
69
- def get_auth_cookies() -> dict:
70
- """获取认证 cookie,优先使用缓存,失效则重新获取"""
71
- cookies = load_cookies()
72
- if all(cookies.get(k) for k in REQUIRED_COOKIES):
73
- return cookies
74
-
75
- # 缓存失效,重新获取
76
- cookies = get_cookies_from_browser()
77
- save_cookies(cookies)
78
-
79
- print("已获取新的 Apollo Cookie")
80
- return cookies
81
-
82
- def open_login_page(page) -> bool:
83
- """自动登录 - 尝试读取环境变量自动填写账号密码"""
84
- username = os.environ.get("ZT_SSO_USERNAME")
85
- password = os.environ.get("ZT_SSO_PASSWORD")
86
-
87
- if not username or not password:
88
- return False
89
-
90
- print(f"检测到环境变量,自动登录中...")
91
-
92
- try:
93
- # 兼容常见账号密码输入框
94
- user_selector = "#username, input[name='username'], input[type='text']"
95
- pass_selector = "#password, #password2, input[name='password'], input[type='password']"
96
- login_selector = ".login_in, button[type='submit'], .btn-login"
97
-
98
- page.wait_for_selector(user_selector, timeout=15000)
99
- page.fill(user_selector, username)
100
- page.fill(pass_selector, password)
101
- page.click(login_selector)
102
- print("已尝试自动提交登录")
103
-
104
- return True
105
-
106
- except Exception as e:
107
- print(f"自动登录失败: {e}")
108
-
109
- return False
110
-
111
- def get_cookies_from_browser(headless: bool = True) -> dict:
112
- """通过 Playwright 从浏览器获取 cookie"""
113
- if headless:
114
- print("正在启动浏览器(无头模式),请登录...")
115
- else:
116
- print("正在打开浏览器,请登录...")
117
-
118
- with sync_playwright() as p:
119
- browser = p.chromium.launch(headless=headless)
120
- context = browser.new_context()
121
- page = context.new_page()
122
-
123
- page.goto(config.base_url)
124
-
125
- # 尝试自动登录
126
- if not open_login_page(page):
127
- if headless:
128
- raise RuntimeError(
129
- "无头模式下无法完成交互式登录。请设置环境变量 ZT_APOLLO_USERNAME 与 ZT_APOLLO_PASSWORD,"
130
- "或执行 zt-apollo-cli login --headed 使用有界面浏览器登录。"
131
- )
132
- print("自动登陆失败. 请在浏览器中完成登录,登录成功后会自动继续...")
133
-
134
- print("登陆中. 检测关键 cookie 出现")
135
- page.wait_for_function(
136
- f"""() => {{
137
- const cookies = document.cookie;
138
- return cookies.includes('NG_TRANSLATE_LANG_KEY');
139
- }}""",
140
- timeout=300000 # 5分钟超时
141
- )
142
-
143
- print("登陆成功. 已获取关键 cookie")
144
-
145
- cookies = context.cookies()
146
-
147
- cookie_dict = {}
148
- for cookie in cookies:
149
- if cookie["domain"] == APOLLO_DOMAIN or APOLLO_DOMAIN in cookie["domain"]:
150
- cookie_dict[cookie["name"]] = cookie["value"]
151
-
152
-
153
- browser.close()
154
-
155
- return cookie_dict
156
-
157
- def login(headless: bool = True) -> dict:
158
- """登录并缓存 cookie"""
159
- if headless:
160
- print("正在启动浏览器(无头模式),请登录...")
161
- else:
162
- print("正在打开浏览器,请登录...")
163
- cookies = get_cookies_from_browser(headless=headless)
164
- save_cookies(cookies)
165
- print("登录成功,Apollo cookie 已缓存!")
166
- return cookies
167
-
168
- if __name__ == "__main__":
169
- print(login())
File without changes