ChatECNU 0.2.7__tar.gz → 0.2.9__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.
- {chatecnu-0.2.7/src/ChatECNU.egg-info → chatecnu-0.2.9}/PKG-INFO +6 -6
- {chatecnu-0.2.7 → chatecnu-0.2.9}/README.md +4 -4
- {chatecnu-0.2.7 → chatecnu-0.2.9}/pyproject.toml +1 -1
- {chatecnu-0.2.7 → chatecnu-0.2.9/src/ChatECNU.egg-info}/PKG-INFO +6 -6
- {chatecnu-0.2.7 → chatecnu-0.2.9}/src/ChatECNU.egg-info/SOURCES.txt +5 -0
- {chatecnu-0.2.7 → chatecnu-0.2.9}/src/ChatECNU.egg-info/requires.txt +1 -1
- {chatecnu-0.2.7 → chatecnu-0.2.9}/src/chatecnu/__init__.py +1 -1
- {chatecnu-0.2.7 → chatecnu-0.2.9}/src/chatecnu/config.py +3 -0
- {chatecnu-0.2.7 → chatecnu-0.2.9}/src/chatecnu/ecnu/cli.py +39 -17
- {chatecnu-0.2.7 → chatecnu-0.2.9}/src/chatecnu/network_auth.py +1 -0
- chatecnu-0.2.9/src/chatecnu/network_http.py +231 -0
- chatecnu-0.2.9/src/chatecnu/network_protocol.py +76 -0
- chatecnu-0.2.9/tests/test_network_file_independence.py +58 -0
- chatecnu-0.2.9/tests/test_network_http.py +211 -0
- chatecnu-0.2.9/tests/test_sensitive_field_mask.py +10 -0
- {chatecnu-0.2.7 → chatecnu-0.2.9}/tests/test_version.py +3 -3
- {chatecnu-0.2.7 → chatecnu-0.2.9}/LICENSE +0 -0
- {chatecnu-0.2.7 → chatecnu-0.2.9}/MANIFEST.in +0 -0
- {chatecnu-0.2.7 → chatecnu-0.2.9}/setup.cfg +0 -0
- {chatecnu-0.2.7 → chatecnu-0.2.9}/src/ChatECNU.egg-info/dependency_links.txt +0 -0
- {chatecnu-0.2.7 → chatecnu-0.2.9}/src/ChatECNU.egg-info/entry_points.txt +0 -0
- {chatecnu-0.2.7 → chatecnu-0.2.9}/src/ChatECNU.egg-info/top_level.txt +0 -0
- {chatecnu-0.2.7 → chatecnu-0.2.9}/src/chatecnu/bin/linux-x86_64/auth_client +0 -0
- {chatecnu-0.2.7 → chatecnu-0.2.9}/src/chatecnu/cli.py +0 -0
- {chatecnu-0.2.7 → chatecnu-0.2.9}/src/chatecnu/ecnu/__init__.py +0 -0
- {chatecnu-0.2.7 → chatecnu-0.2.9}/src/chatecnu/ecnu/captcha.py +0 -0
- {chatecnu-0.2.7 → chatecnu-0.2.9}/src/chatecnu/ecnu/portal.py +0 -0
- {chatecnu-0.2.7 → chatecnu-0.2.9}/src/chatecnu/ecnu/session_tokens.py +0 -0
- {chatecnu-0.2.7 → chatecnu-0.2.9}/src/chatecnu/network_install.py +0 -0
- {chatecnu-0.2.7 → chatecnu-0.2.9}/tests/test_cli.py +0 -0
- {chatecnu-0.2.7 → chatecnu-0.2.9}/tests/test_docs_contract.py +0 -0
- {chatecnu-0.2.7 → chatecnu-0.2.9}/tests/test_docs_rendering.py +0 -0
- {chatecnu-0.2.7 → chatecnu-0.2.9}/tests/test_network_auth.py +0 -0
- {chatecnu-0.2.7 → chatecnu-0.2.9}/tests/test_network_install.py +0 -0
- {chatecnu-0.2.7 → chatecnu-0.2.9}/tests/test_network_install_cli.py +0 -0
- {chatecnu-0.2.7 → chatecnu-0.2.9}/tests/test_network_install_docs.py +0 -0
- {chatecnu-0.2.7 → chatecnu-0.2.9}/tests/test_token_store_sessions.py +0 -0
- {chatecnu-0.2.7 → chatecnu-0.2.9}/tests/test_workflow_contract.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: ChatECNU
|
|
3
|
-
Version: 0.2.
|
|
3
|
+
Version: 0.2.9
|
|
4
4
|
Summary: ChatArch ECNU campus portal automation CLI
|
|
5
5
|
Author-email: ChatArch <1073853456@qq.com>
|
|
6
6
|
License-Expression: MIT
|
|
@@ -15,7 +15,7 @@ Description-Content-Type: text/markdown
|
|
|
15
15
|
License-File: LICENSE
|
|
16
16
|
Requires-Dist: click>=8.0
|
|
17
17
|
Requires-Dist: chatstyle<0.3.0,>=0.2.0
|
|
18
|
-
Requires-Dist: chatenv<0.3.0,>=0.2.
|
|
18
|
+
Requires-Dist: chatenv<0.3.0,>=0.2.13
|
|
19
19
|
Requires-Dist: ChatNet<0.3.0,>=0.2.4
|
|
20
20
|
Requires-Dist: requests>=2.0
|
|
21
21
|
Requires-Dist: pycryptodome>=3.0
|
|
@@ -63,7 +63,7 @@ pip install "ChatECNU[captcha]"
|
|
|
63
63
|
|
|
64
64
|
### 显式准备校园网工具
|
|
65
65
|
|
|
66
|
-
`pip install`
|
|
66
|
+
`pip install` 不会改用户文件。默认 Python 后端无需安装 auth_client;下面的显式离线安装器只准备 Linux x86_64 binary 兼容后端:
|
|
67
67
|
|
|
68
68
|
```bash
|
|
69
69
|
ecnu net install --dry-run --json
|
|
@@ -126,11 +126,11 @@ ecnu home logout
|
|
|
126
126
|
|
|
127
127
|
```bash
|
|
128
128
|
ecnu net check --json
|
|
129
|
-
ecnu net login -I
|
|
129
|
+
ecnu net login -I
|
|
130
130
|
ecnu net logout -I
|
|
131
|
-
ecnu net ensure-login -I
|
|
131
|
+
ecnu net ensure-login -I
|
|
132
132
|
```
|
|
133
133
|
|
|
134
|
-
|
|
134
|
+
默认 `ECNU_NETWORK_BACKEND=python`:直接执行 SRun HTTP 协议,不运行 `auth_client`,不通过外部进程 argv 传密码。复用 ChatEnv 的 `ECNU_USERNAME` / `ECNU_PASSWORD` 及原生 `ECNU_NETWORK_BASE_URL` / `ECNU_NETWORK_AC_ID`;Python 仅在显式 `--setting-file` 时导入旧格式;登录/退出后重新检查实际在线状态,JSON 返回 `backend=python`。只有显式选择 `ECNU_NETWORK_BACKEND=binary` 才使用旧二进制,且登录仍需 `--allow-argv-password`;`--auth-client` / `ECNU_AUTH_CLIENT` 也仅作用于 binary。默认 Python 路径不需要 `net install`。
|
|
135
135
|
|
|
136
136
|
敏感值(密码、Cookie、短信码、会话)不要打印或提交。
|
|
@@ -26,7 +26,7 @@ pip install "ChatECNU[captcha]"
|
|
|
26
26
|
|
|
27
27
|
### 显式准备校园网工具
|
|
28
28
|
|
|
29
|
-
`pip install`
|
|
29
|
+
`pip install` 不会改用户文件。默认 Python 后端无需安装 auth_client;下面的显式离线安装器只准备 Linux x86_64 binary 兼容后端:
|
|
30
30
|
|
|
31
31
|
```bash
|
|
32
32
|
ecnu net install --dry-run --json
|
|
@@ -89,11 +89,11 @@ ecnu home logout
|
|
|
89
89
|
|
|
90
90
|
```bash
|
|
91
91
|
ecnu net check --json
|
|
92
|
-
ecnu net login -I
|
|
92
|
+
ecnu net login -I
|
|
93
93
|
ecnu net logout -I
|
|
94
|
-
ecnu net ensure-login -I
|
|
94
|
+
ecnu net ensure-login -I
|
|
95
95
|
```
|
|
96
96
|
|
|
97
|
-
|
|
97
|
+
默认 `ECNU_NETWORK_BACKEND=python`:直接执行 SRun HTTP 协议,不运行 `auth_client`,不通过外部进程 argv 传密码。复用 ChatEnv 的 `ECNU_USERNAME` / `ECNU_PASSWORD` 及原生 `ECNU_NETWORK_BASE_URL` / `ECNU_NETWORK_AC_ID`;Python 仅在显式 `--setting-file` 时导入旧格式;登录/退出后重新检查实际在线状态,JSON 返回 `backend=python`。只有显式选择 `ECNU_NETWORK_BACKEND=binary` 才使用旧二进制,且登录仍需 `--allow-argv-password`;`--auth-client` / `ECNU_AUTH_CLIENT` 也仅作用于 binary。默认 Python 路径不需要 `net install`。
|
|
98
98
|
|
|
99
99
|
敏感值(密码、Cookie、短信码、会话)不要打印或提交。
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: ChatECNU
|
|
3
|
-
Version: 0.2.
|
|
3
|
+
Version: 0.2.9
|
|
4
4
|
Summary: ChatArch ECNU campus portal automation CLI
|
|
5
5
|
Author-email: ChatArch <1073853456@qq.com>
|
|
6
6
|
License-Expression: MIT
|
|
@@ -15,7 +15,7 @@ Description-Content-Type: text/markdown
|
|
|
15
15
|
License-File: LICENSE
|
|
16
16
|
Requires-Dist: click>=8.0
|
|
17
17
|
Requires-Dist: chatstyle<0.3.0,>=0.2.0
|
|
18
|
-
Requires-Dist: chatenv<0.3.0,>=0.2.
|
|
18
|
+
Requires-Dist: chatenv<0.3.0,>=0.2.13
|
|
19
19
|
Requires-Dist: ChatNet<0.3.0,>=0.2.4
|
|
20
20
|
Requires-Dist: requests>=2.0
|
|
21
21
|
Requires-Dist: pycryptodome>=3.0
|
|
@@ -63,7 +63,7 @@ pip install "ChatECNU[captcha]"
|
|
|
63
63
|
|
|
64
64
|
### 显式准备校园网工具
|
|
65
65
|
|
|
66
|
-
`pip install`
|
|
66
|
+
`pip install` 不会改用户文件。默认 Python 后端无需安装 auth_client;下面的显式离线安装器只准备 Linux x86_64 binary 兼容后端:
|
|
67
67
|
|
|
68
68
|
```bash
|
|
69
69
|
ecnu net install --dry-run --json
|
|
@@ -126,11 +126,11 @@ ecnu home logout
|
|
|
126
126
|
|
|
127
127
|
```bash
|
|
128
128
|
ecnu net check --json
|
|
129
|
-
ecnu net login -I
|
|
129
|
+
ecnu net login -I
|
|
130
130
|
ecnu net logout -I
|
|
131
|
-
ecnu net ensure-login -I
|
|
131
|
+
ecnu net ensure-login -I
|
|
132
132
|
```
|
|
133
133
|
|
|
134
|
-
|
|
134
|
+
默认 `ECNU_NETWORK_BACKEND=python`:直接执行 SRun HTTP 协议,不运行 `auth_client`,不通过外部进程 argv 传密码。复用 ChatEnv 的 `ECNU_USERNAME` / `ECNU_PASSWORD` 及原生 `ECNU_NETWORK_BASE_URL` / `ECNU_NETWORK_AC_ID`;Python 仅在显式 `--setting-file` 时导入旧格式;登录/退出后重新检查实际在线状态,JSON 返回 `backend=python`。只有显式选择 `ECNU_NETWORK_BACKEND=binary` 才使用旧二进制,且登录仍需 `--allow-argv-password`;`--auth-client` / `ECNU_AUTH_CLIENT` 也仅作用于 binary。默认 Python 路径不需要 `net install`。
|
|
135
135
|
|
|
136
136
|
敏感值(密码、Cookie、短信码、会话)不要打印或提交。
|
|
@@ -12,7 +12,9 @@ src/chatecnu/__init__.py
|
|
|
12
12
|
src/chatecnu/cli.py
|
|
13
13
|
src/chatecnu/config.py
|
|
14
14
|
src/chatecnu/network_auth.py
|
|
15
|
+
src/chatecnu/network_http.py
|
|
15
16
|
src/chatecnu/network_install.py
|
|
17
|
+
src/chatecnu/network_protocol.py
|
|
16
18
|
src/chatecnu/bin/linux-x86_64/auth_client
|
|
17
19
|
src/chatecnu/ecnu/__init__.py
|
|
18
20
|
src/chatecnu/ecnu/captcha.py
|
|
@@ -23,9 +25,12 @@ tests/test_cli.py
|
|
|
23
25
|
tests/test_docs_contract.py
|
|
24
26
|
tests/test_docs_rendering.py
|
|
25
27
|
tests/test_network_auth.py
|
|
28
|
+
tests/test_network_file_independence.py
|
|
29
|
+
tests/test_network_http.py
|
|
26
30
|
tests/test_network_install.py
|
|
27
31
|
tests/test_network_install_cli.py
|
|
28
32
|
tests/test_network_install_docs.py
|
|
33
|
+
tests/test_sensitive_field_mask.py
|
|
29
34
|
tests/test_token_store_sessions.py
|
|
30
35
|
tests/test_version.py
|
|
31
36
|
tests/test_workflow_contract.py
|
|
@@ -18,6 +18,9 @@ class ECNUConfig(BaseEnvConfig):
|
|
|
18
18
|
ECNU_VISITOR_PASSWORD1 = EnvField("ECNU_VISITOR_PASSWORD1", desc="默认访客账号 m1 密码。", is_sensitive=True)
|
|
19
19
|
ECNU_VISITOR_PASSWORD2 = EnvField("ECNU_VISITOR_PASSWORD2", desc="默认访客账号 m2 密码。", is_sensitive=True)
|
|
20
20
|
ECNU_VISITOR_REMARK = EnvField("ECNU_VISITOR_REMARK", default="default", desc="默认访客账号备注。")
|
|
21
|
+
ECNU_NETWORK_BASE_URL = EnvField("ECNU_NETWORK_BASE_URL", default="https://login.ecnu.edu.cn", desc="校园网认证基地址(不同于门户管理ECNU_BASE_URL)。")
|
|
22
|
+
ECNU_NETWORK_AC_ID = EnvField("ECNU_NETWORK_AC_ID", default="1", desc="校园网接入控制器AC ID,正整数。")
|
|
23
|
+
ECNU_NETWORK_BACKEND = EnvField("ECNU_NETWORK_BACKEND", default="python", desc="校园网后端:python(默认)或显式binary兼容。")
|
|
21
24
|
ECNU_AUTH_CLIENT = EnvField("ECNU_AUTH_CLIENT", default="auth_client", desc="auth_client 路径。")
|
|
22
25
|
ECNU_AUTH_SETTING_FILE = EnvField("ECNU_AUTH_SETTING_FILE", desc="auth_client 设置文件。")
|
|
23
26
|
|
|
@@ -22,6 +22,7 @@ from chatstyle import (
|
|
|
22
22
|
|
|
23
23
|
from chatecnu import __version__
|
|
24
24
|
from chatecnu.config import ECNUConfig
|
|
25
|
+
from chatecnu.network_http import PythonNetworkAuthClient
|
|
25
26
|
from chatecnu.network_auth import (
|
|
26
27
|
DEFAULT_SETTING_FILE,
|
|
27
28
|
NetworkAuthClient,
|
|
@@ -407,7 +408,7 @@ def network_auth_install(
|
|
|
407
408
|
|
|
408
409
|
@network_auth_group.command(name="check")
|
|
409
410
|
@click.option("--auth-client", "auth_client_path", default=None, help="auth_client 路径。")
|
|
410
|
-
@click.option("--setting-file", default=None, help="
|
|
411
|
+
@click.option("--setting-file", default=None, help="显式设置文件;Python默认使用ChatEnv原生网络配置。")
|
|
411
412
|
@click.option("--json", "json_output", is_flag=True, help="输出 JSON。")
|
|
412
413
|
@click.pass_context
|
|
413
414
|
def network_auth_check(
|
|
@@ -429,13 +430,13 @@ def network_auth_check(
|
|
|
429
430
|
|
|
430
431
|
@network_auth_group.command(name="login")
|
|
431
432
|
@click.option("--auth-client", "auth_client_path", default=None, help="auth_client 路径。")
|
|
432
|
-
@click.option("--setting-file", default=None, help="
|
|
433
|
+
@click.option("--setting-file", default=None, help="显式设置文件;Python默认使用ChatEnv原生网络配置。")
|
|
433
434
|
@click.option("--username", default=None, help="ECNU 用户名。")
|
|
434
435
|
@click.option("--password", default=None, help="ECNU 密码。")
|
|
435
436
|
@click.option(
|
|
436
437
|
"--allow-argv-password",
|
|
437
438
|
is_flag=True,
|
|
438
|
-
help="
|
|
439
|
+
help="仅binary兼容后端:接受密码放入argv的风险;默认Python后端无需此选项。",
|
|
439
440
|
)
|
|
440
441
|
@click.option("--json", "json_output", is_flag=True, help="输出 JSON。")
|
|
441
442
|
@add_interactive_option
|
|
@@ -470,7 +471,7 @@ def network_auth_login(
|
|
|
470
471
|
|
|
471
472
|
@network_auth_group.command(name="logout")
|
|
472
473
|
@click.option("--auth-client", "auth_client_path", default=None, help="auth_client 路径。")
|
|
473
|
-
@click.option("--setting-file", default=None, help="
|
|
474
|
+
@click.option("--setting-file", default=None, help="显式设置文件;Python默认使用ChatEnv原生网络配置。")
|
|
474
475
|
@click.option("--username", default=None, help="ECNU 用户名。")
|
|
475
476
|
@click.option("--json", "json_output", is_flag=True, help="输出 JSON。")
|
|
476
477
|
@add_interactive_option
|
|
@@ -502,13 +503,13 @@ def network_auth_logout(
|
|
|
502
503
|
|
|
503
504
|
@network_auth_group.command(name="ensure-login")
|
|
504
505
|
@click.option("--auth-client", "auth_client_path", default=None, help="auth_client 路径。")
|
|
505
|
-
@click.option("--setting-file", default=None, help="
|
|
506
|
+
@click.option("--setting-file", default=None, help="显式设置文件;Python默认使用ChatEnv原生网络配置。")
|
|
506
507
|
@click.option("--username", default=None, help="ECNU 用户名。")
|
|
507
508
|
@click.option("--password", default=None, help="ECNU 密码。")
|
|
508
509
|
@click.option(
|
|
509
510
|
"--allow-argv-password",
|
|
510
511
|
is_flag=True,
|
|
511
|
-
help="
|
|
512
|
+
help="仅binary兼容后端:接受密码放入argv的风险;默认Python后端无需此选项。",
|
|
512
513
|
)
|
|
513
514
|
@click.option("--json", "json_output", is_flag=True, help="输出 JSON。")
|
|
514
515
|
@add_interactive_option
|
|
@@ -738,22 +739,43 @@ def make_network_auth_client(
|
|
|
738
739
|
setting_file: str | None,
|
|
739
740
|
allow_argv_password: bool = False,
|
|
740
741
|
prefer_loaded_chatenv: bool = False,
|
|
741
|
-
) -> NetworkAuthClient:
|
|
742
|
-
|
|
743
|
-
"
|
|
744
|
-
ECNUConfig.ECNU_AUTH_CLIENT,
|
|
742
|
+
) -> NetworkAuthClient | PythonNetworkAuthClient:
|
|
743
|
+
backend = resolve_ecnu_config_value(
|
|
744
|
+
"ECNU_NETWORK_BACKEND", ECNUConfig.ECNU_NETWORK_BACKEND,
|
|
745
745
|
prefer_loaded_chatenv=prefer_loaded_chatenv,
|
|
746
|
-
)
|
|
747
|
-
|
|
746
|
+
) or "python"
|
|
747
|
+
if backend not in {"python", "binary"}:
|
|
748
|
+
raise click.UsageError("ECNU_NETWORK_BACKEND must be python or binary.")
|
|
749
|
+
if backend == "python":
|
|
750
|
+
if auth_client_path:
|
|
751
|
+
raise click.UsageError("--auth-client requires explicit ECNU_NETWORK_BACKEND=binary.")
|
|
752
|
+
try:
|
|
753
|
+
if setting_file:
|
|
754
|
+
return PythonNetworkAuthClient.from_setting_file(setting_file)
|
|
755
|
+
base_url = resolve_ecnu_config_value(
|
|
756
|
+
"ECNU_NETWORK_BASE_URL", ECNUConfig.ECNU_NETWORK_BASE_URL,
|
|
757
|
+
prefer_loaded_chatenv=prefer_loaded_chatenv,
|
|
758
|
+
)
|
|
759
|
+
acid = resolve_ecnu_config_value(
|
|
760
|
+
"ECNU_NETWORK_AC_ID", ECNUConfig.ECNU_NETWORK_AC_ID,
|
|
761
|
+
prefer_loaded_chatenv=prefer_loaded_chatenv,
|
|
762
|
+
)
|
|
763
|
+
if not isinstance(acid, str) or not re.fullmatch(r"[0-9]+", acid):
|
|
764
|
+
raise ValueError("Network AC ID must be a positive integer")
|
|
765
|
+
return PythonNetworkAuthClient(base_url, acid=int(acid))
|
|
766
|
+
except ValueError as exc:
|
|
767
|
+
raise click.ClickException(str(exc)) from None
|
|
748
768
|
resolved_setting_file = setting_file or resolve_ecnu_config_value(
|
|
749
|
-
"ECNU_AUTH_SETTING_FILE",
|
|
750
|
-
ECNUConfig.ECNU_AUTH_SETTING_FILE,
|
|
769
|
+
"ECNU_AUTH_SETTING_FILE", ECNUConfig.ECNU_AUTH_SETTING_FILE,
|
|
751
770
|
prefer_loaded_chatenv=prefer_loaded_chatenv,
|
|
752
771
|
) or DEFAULT_SETTING_FILE
|
|
772
|
+
configured_auth_client = auth_client_path or resolve_ecnu_config_value(
|
|
773
|
+
"ECNU_AUTH_CLIENT", ECNUConfig.ECNU_AUTH_CLIENT,
|
|
774
|
+
prefer_loaded_chatenv=prefer_loaded_chatenv,
|
|
775
|
+
)
|
|
753
776
|
return NetworkAuthClient(
|
|
754
|
-
auth_client_path=
|
|
755
|
-
setting_file=resolved_setting_file,
|
|
756
|
-
allow_argv_password=allow_argv_password,
|
|
777
|
+
auth_client_path=resolve_auth_client_path(configured_auth_client),
|
|
778
|
+
setting_file=resolved_setting_file, allow_argv_password=allow_argv_password,
|
|
757
779
|
)
|
|
758
780
|
|
|
759
781
|
|
|
@@ -0,0 +1,231 @@
|
|
|
1
|
+
"""Direct, credential-safe SRun HTTP client; never invokes auth_client."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
from dataclasses import replace
|
|
5
|
+
import ipaddress
|
|
6
|
+
import json
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
import re
|
|
9
|
+
from urllib.parse import parse_qs, urljoin, urlsplit
|
|
10
|
+
|
|
11
|
+
import requests
|
|
12
|
+
|
|
13
|
+
from .network_auth import NetworkAuthCredentials, NetworkAuthResult
|
|
14
|
+
from .network_protocol import build_auth_params
|
|
15
|
+
|
|
16
|
+
try:
|
|
17
|
+
import tomllib
|
|
18
|
+
except ModuleNotFoundError: # Python 3.10
|
|
19
|
+
import tomli as tomllib
|
|
20
|
+
|
|
21
|
+
CALLBACK = 'C_a_l_l_b_a_c_k'
|
|
22
|
+
MAX_BODY = 1024 * 1024
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class PortalProtocolError(ValueError):
|
|
26
|
+
"""An intentionally value-free protocol/transport failure."""
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def _json_body(text: str) -> dict:
|
|
30
|
+
body = text.strip()
|
|
31
|
+
match = re.fullmatch(re.escape(CALLBACK) + r'\((.*)\)\s*;?', body, re.S)
|
|
32
|
+
if match:
|
|
33
|
+
body = match.group(1)
|
|
34
|
+
try:
|
|
35
|
+
result = json.loads(body)
|
|
36
|
+
except (ValueError, TypeError):
|
|
37
|
+
raise PortalProtocolError('Invalid portal JSON response') from None
|
|
38
|
+
if not isinstance(result, dict):
|
|
39
|
+
raise PortalProtocolError('Invalid portal JSON object')
|
|
40
|
+
return result
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
class PythonNetworkAuthClient:
|
|
44
|
+
"""Python implementation sharing the existing NetworkAuthResult contract.
|
|
45
|
+
|
|
46
|
+
Settings are read only. No third-party AC discovery, binary fallback,
|
|
47
|
+
secret-bearing command display, or unsafe redirect/retry is performed.
|
|
48
|
+
"""
|
|
49
|
+
|
|
50
|
+
def __init__(self, base_url: str, *, acid: int = 1, session=None, timeout: float = 10):
|
|
51
|
+
try:
|
|
52
|
+
parsed = urlsplit(base_url)
|
|
53
|
+
valid = (parsed.scheme in {'http', 'https'} and parsed.hostname
|
|
54
|
+
and not parsed.username and not parsed.password
|
|
55
|
+
and parsed.path in {'', '/'} and not parsed.query and not parsed.fragment)
|
|
56
|
+
parsed.port
|
|
57
|
+
except (ValueError, TypeError):
|
|
58
|
+
valid = False
|
|
59
|
+
if not valid:
|
|
60
|
+
raise ValueError('Invalid network portal endpoint')
|
|
61
|
+
if type(acid) is not int or acid < 1:
|
|
62
|
+
raise ValueError('AC ID must be a positive integer')
|
|
63
|
+
if timeout <= 0:
|
|
64
|
+
raise ValueError('Timeout must be positive')
|
|
65
|
+
self.base_url = base_url.rstrip('/')
|
|
66
|
+
self.acid = acid
|
|
67
|
+
self.timeout = timeout
|
|
68
|
+
self.session = session if session is not None else requests.Session()
|
|
69
|
+
self.session.trust_env = False
|
|
70
|
+
|
|
71
|
+
@classmethod
|
|
72
|
+
def from_setting_file(cls, setting_file: str | Path | None = None, **kwargs):
|
|
73
|
+
if not setting_file:
|
|
74
|
+
raise ValueError('Explicit network settings filename required')
|
|
75
|
+
path = Path(setting_file).expanduser()
|
|
76
|
+
if not path.exists():
|
|
77
|
+
raise ValueError('Network settings file not found')
|
|
78
|
+
try:
|
|
79
|
+
data = tomllib.loads(path.read_text(encoding='utf-8'))
|
|
80
|
+
host = data['host']
|
|
81
|
+
acid = data.get('acid', 1)
|
|
82
|
+
if isinstance(acid, str) and re.fullmatch(r'[0-9]+', acid):
|
|
83
|
+
acid = int(acid)
|
|
84
|
+
if not isinstance(host, str):
|
|
85
|
+
raise ValueError
|
|
86
|
+
return cls(host if '://' in host else 'http://' + host, acid=acid, **kwargs)
|
|
87
|
+
except (OSError, UnicodeError, ValueError, KeyError, TypeError):
|
|
88
|
+
raise ValueError('Invalid network settings') from None
|
|
89
|
+
|
|
90
|
+
def _get(self, path: str, params=None, *, mutation: bool = False) -> str:
|
|
91
|
+
url = self.base_url + path
|
|
92
|
+
for _ in range(3):
|
|
93
|
+
response = None
|
|
94
|
+
try:
|
|
95
|
+
response = self.session.get(url, params=params or {}, timeout=self.timeout,
|
|
96
|
+
allow_redirects=False, stream=True)
|
|
97
|
+
if response.status_code in {301, 302, 303, 307, 308}:
|
|
98
|
+
target = urljoin(url, response.headers.get('Location', ''))
|
|
99
|
+
old, new = urlsplit(url), urlsplit(target)
|
|
100
|
+
same_host_upgrade = (old.scheme == 'http' and new.scheme == 'https'
|
|
101
|
+
and old.hostname == new.hostname
|
|
102
|
+
and old.port in {None, 80} and new.port in {None, 443}
|
|
103
|
+
and old.path == new.path and not new.username
|
|
104
|
+
and not new.password and not new.fragment
|
|
105
|
+
and (not new.query or parse_qs(new.query, keep_blank_values=True)
|
|
106
|
+
== {k: [str(v)] for k, v in (params or {}).items()}))
|
|
107
|
+
if mutation or not same_host_upgrade:
|
|
108
|
+
raise PortalProtocolError('Portal redirect refused')
|
|
109
|
+
self.base_url = 'https://' + new.netloc
|
|
110
|
+
url = self.base_url + path
|
|
111
|
+
continue
|
|
112
|
+
if response.status_code != 200:
|
|
113
|
+
raise PortalProtocolError('Portal HTTP request failed')
|
|
114
|
+
chunks = []
|
|
115
|
+
length = 0
|
|
116
|
+
for chunk in response.iter_content(chunk_size=16384):
|
|
117
|
+
length += len(chunk)
|
|
118
|
+
if length > MAX_BODY:
|
|
119
|
+
raise PortalProtocolError('Portal response too large')
|
|
120
|
+
chunks.append(chunk)
|
|
121
|
+
return b''.join(chunks).decode('utf-8')
|
|
122
|
+
except requests.RequestException as exc:
|
|
123
|
+
# requests exceptions can contain a full credential-bearing URL.
|
|
124
|
+
raise PortalProtocolError('Portal transport failed: ' + type(exc).__name__) from None
|
|
125
|
+
except UnicodeError:
|
|
126
|
+
raise PortalProtocolError('Portal response encoding invalid') from None
|
|
127
|
+
finally:
|
|
128
|
+
if response is not None:
|
|
129
|
+
response.close()
|
|
130
|
+
raise PortalProtocolError('Portal redirect limit reached')
|
|
131
|
+
|
|
132
|
+
@staticmethod
|
|
133
|
+
def _result(action: str, success: bool, *, online=None, username=None,
|
|
134
|
+
message: str = '', skipped: bool = False) -> NetworkAuthResult:
|
|
135
|
+
return NetworkAuthResult(action=action, success=success, returncode=0 if success else 1,
|
|
136
|
+
stdout=message if success else '', stderr='' if success else message,
|
|
137
|
+
redacted_command='python-http ' + action, online=online,
|
|
138
|
+
account=username, username=username, skipped=skipped, backend='python')
|
|
139
|
+
|
|
140
|
+
def check(self) -> NetworkAuthResult:
|
|
141
|
+
try:
|
|
142
|
+
text = self._get('/cgi-bin/rad_user_info').strip()
|
|
143
|
+
if text == 'not_online_error':
|
|
144
|
+
return self._result('check', True, online=False)
|
|
145
|
+
if text.startswith(('{', CALLBACK + '(')):
|
|
146
|
+
data = _json_body(text)
|
|
147
|
+
if data.get('error') == 'not_online_error':
|
|
148
|
+
return self._result('check', True, online=False)
|
|
149
|
+
name = data.get('user_name') or data.get('username')
|
|
150
|
+
if data.get('error') == 'ok' and isinstance(name, str) and name:
|
|
151
|
+
return self._result('check', True, online=True, username=name)
|
|
152
|
+
else:
|
|
153
|
+
row = text.split(',')
|
|
154
|
+
if (len(row) >= 9 and re.fullmatch(r'[^\s,<>{}]{1,128}', row[0])
|
|
155
|
+
and all(re.fullmatch(r'[0-9]+(?:\.[0-9]+)?', cell) for cell in row[1:8])):
|
|
156
|
+
try:
|
|
157
|
+
ipaddress.ip_address(row[8])
|
|
158
|
+
except ValueError:
|
|
159
|
+
raise PortalProtocolError('Invalid portal status IP') from None
|
|
160
|
+
return self._result('check', True, online=True, username=row[0])
|
|
161
|
+
raise PortalProtocolError('Unknown portal online status')
|
|
162
|
+
except PortalProtocolError as exc:
|
|
163
|
+
return self._result('check', False, message=str(exc))
|
|
164
|
+
|
|
165
|
+
def _challenge(self, username: str):
|
|
166
|
+
data = _json_body(self._get('/cgi-bin/get_challenge',
|
|
167
|
+
{'callback': CALLBACK, 'double_stack': '1', 'ip': '', 'username': username}))
|
|
168
|
+
token = data.get('challenge')
|
|
169
|
+
error = data.get('error')
|
|
170
|
+
if error is not None and (not isinstance(error, str) or error != 'ok'):
|
|
171
|
+
raise PortalProtocolError('Portal challenge invalid')
|
|
172
|
+
if not isinstance(token, str) or len(token.encode('utf-8')) < 13:
|
|
173
|
+
raise PortalProtocolError('Portal challenge invalid')
|
|
174
|
+
for key in ('client_ip', 'online_ip'):
|
|
175
|
+
value = data.get(key)
|
|
176
|
+
if value is not None and not isinstance(value, str):
|
|
177
|
+
raise PortalProtocolError('Portal client IP invalid')
|
|
178
|
+
ip = data.get('client_ip') or data.get('online_ip')
|
|
179
|
+
if not isinstance(ip, str):
|
|
180
|
+
raise PortalProtocolError('Portal client IP invalid')
|
|
181
|
+
try:
|
|
182
|
+
ipaddress.ip_address(ip)
|
|
183
|
+
except (ValueError, TypeError):
|
|
184
|
+
raise PortalProtocolError('Portal client IP invalid') from None
|
|
185
|
+
return token, ip
|
|
186
|
+
|
|
187
|
+
def _authenticate(self, action: str, username: str, password: str = '') -> NetworkAuthResult:
|
|
188
|
+
if not username or (action == 'login' and not password):
|
|
189
|
+
return self._result(action, False, message='Network credentials missing')
|
|
190
|
+
try:
|
|
191
|
+
token, ip = self._challenge(username)
|
|
192
|
+
params = build_auth_params(username, password, ip, self.acid, token, action=action)
|
|
193
|
+
data = _json_body(self._get('/cgi-bin/srun_portal', params, mutation=True))
|
|
194
|
+
if data.get('error') != 'ok':
|
|
195
|
+
codes = sorted(set(re.findall(r'\bE[0-9]{4}\b', ' '.join(str(data.get(k, '')) for k in ['error','ecode','error_msg']))))
|
|
196
|
+
suffix = ': ' + ','.join(codes) if codes else ''
|
|
197
|
+
raise PortalProtocolError('Portal rejected authentication' + suffix)
|
|
198
|
+
current = self.check()
|
|
199
|
+
expected = action == 'login'
|
|
200
|
+
if not current.success or current.online is not expected:
|
|
201
|
+
return self._result(action, False, online=current.online, message='Authentication state not verified')
|
|
202
|
+
return self._result(action, True, online=current.online, username=current.username,
|
|
203
|
+
message='Login success' if expected else 'Logout success')
|
|
204
|
+
except (PortalProtocolError, ValueError) as exc:
|
|
205
|
+
# Only protocol-owned constant messages may cross this boundary.
|
|
206
|
+
message = str(exc) if isinstance(exc, PortalProtocolError) else 'Invalid authentication parameters'
|
|
207
|
+
return self._result(action, False, message=message)
|
|
208
|
+
|
|
209
|
+
def login(self, credentials: NetworkAuthCredentials) -> NetworkAuthResult:
|
|
210
|
+
return self._authenticate('login', credentials.username, credentials.password)
|
|
211
|
+
|
|
212
|
+
def logout(self, username: str) -> NetworkAuthResult:
|
|
213
|
+
return self._authenticate('logout', username)
|
|
214
|
+
|
|
215
|
+
def logout_current(self) -> NetworkAuthResult:
|
|
216
|
+
current = self.check()
|
|
217
|
+
if not current.success:
|
|
218
|
+
return replace(current, action='logout')
|
|
219
|
+
if not current.online:
|
|
220
|
+
return replace(current, action='logout', skipped=True)
|
|
221
|
+
if not current.username:
|
|
222
|
+
return self._result('logout', False, message='Online username unavailable')
|
|
223
|
+
return self.logout(current.username)
|
|
224
|
+
|
|
225
|
+
def ensure_login(self, credentials: NetworkAuthCredentials) -> NetworkAuthResult:
|
|
226
|
+
current = self.check()
|
|
227
|
+
if not current.success:
|
|
228
|
+
return replace(current, action='ensure-login')
|
|
229
|
+
if current.online:
|
|
230
|
+
return replace(current, action='ensure-login', skipped=True)
|
|
231
|
+
return replace(self.login(credentials), action='ensure-login')
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
"""SRun portal byte-level protocol, recovered against native client vectors."""
|
|
2
|
+
import base64
|
|
3
|
+
import hashlib
|
|
4
|
+
import json
|
|
5
|
+
import struct
|
|
6
|
+
|
|
7
|
+
B64_ALPHABET = 'LVoJPiCN2R8G90yg+hmFHuacZ1OWMnrsSTXkYpUq/3dlbfKwv6xztjI7DeBE45QA'
|
|
8
|
+
STANDARD_B64 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
|
|
9
|
+
TRANSLATE = str.maketrans(STANDARD_B64, B64_ALPHABET)
|
|
10
|
+
MASK32 = 0xFFFFFFFF
|
|
11
|
+
DELTA = 0x9E3779B9
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def _words(data, append_length=False):
|
|
15
|
+
padded = data + b'\0' * (-len(data) % 4)
|
|
16
|
+
words = list(struct.unpack('<' + 'I' * (len(padded) // 4), padded))
|
|
17
|
+
if append_length:
|
|
18
|
+
words.append(len(data))
|
|
19
|
+
return words
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def xencode(data, key):
|
|
23
|
+
if not data:
|
|
24
|
+
return b''
|
|
25
|
+
values = _words(data, True)
|
|
26
|
+
keys = _words(key)
|
|
27
|
+
if len(keys) < 4:
|
|
28
|
+
raise ValueError('Challenge must contain at least four uint32 words')
|
|
29
|
+
n = len(values) - 1
|
|
30
|
+
z = values[n]
|
|
31
|
+
total = 0
|
|
32
|
+
for _ in range(6 + 52 // (n + 1)):
|
|
33
|
+
total = (total + DELTA) & MASK32
|
|
34
|
+
e = (total >> 2) & 3
|
|
35
|
+
for index in range(n + 1):
|
|
36
|
+
y = values[index + 1] if index < n else values[0]
|
|
37
|
+
mix = (z >> 5) ^ (y << 2)
|
|
38
|
+
mix += ((y >> 3) ^ (z << 4)) ^ (total ^ y)
|
|
39
|
+
mix += keys[(index & 3) ^ e] ^ z
|
|
40
|
+
values[index] = z = (values[index] + mix) & MASK32
|
|
41
|
+
return struct.pack('<' + 'I' * len(values), *values)
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def password_digest(password):
|
|
45
|
+
# This binary uses MD5(password), not HMAC-MD5(challenge, password).
|
|
46
|
+
return '{MD5}' + hashlib.md5(password.encode('utf-8')).hexdigest()
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def encode_info(username, password, ip, acid, challenge, *, action="login"):
|
|
50
|
+
info = {'username': username, 'ip': ip, 'acid': str(acid), 'enc_ver': 'srun_bx1'}
|
|
51
|
+
if action == 'login':
|
|
52
|
+
info['password'] = password
|
|
53
|
+
text = json.dumps(info, sort_keys=True, separators=(',', ':'), ensure_ascii=False)
|
|
54
|
+
# Match Go encoding/json's default HTML and line-separator escaping.
|
|
55
|
+
for old, new in [('&', '\\u0026'), ('<', '\\u003c'), ('>', '\\u003e'),
|
|
56
|
+
('\u2028', '\\u2028'), ('\u2029', '\\u2029')]:
|
|
57
|
+
text = text.replace(old, new)
|
|
58
|
+
encoded = xencode(text.encode('utf-8'), challenge.encode('utf-8'))
|
|
59
|
+
return '{SRBX1}' + base64.b64encode(encoded).decode('ascii').translate(TRANSLATE)
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def build_auth_params(username, password, ip, acid, challenge, *, action="login"):
|
|
63
|
+
if action not in {"login", "logout"}:
|
|
64
|
+
raise ValueError("Unsupported authentication action")
|
|
65
|
+
info = encode_info(username, password, ip, acid, challenge, action=action)
|
|
66
|
+
fields = [username]
|
|
67
|
+
result = {'ac_id': str(acid), 'action': action, 'callback': 'C_a_l_l_b_a_c_k',
|
|
68
|
+
'double_stack': '1', 'info': info, 'ip': ip, 'n': '200',
|
|
69
|
+
'type': '1', 'username': username}
|
|
70
|
+
if action == 'login':
|
|
71
|
+
digest = password_digest(password)
|
|
72
|
+
result['password'] = digest
|
|
73
|
+
fields.append(digest.removeprefix('{MD5}'))
|
|
74
|
+
fields.extend([str(acid), ip, '200', '1', info])
|
|
75
|
+
result['chksum'] = hashlib.sha1(''.join(challenge + x for x in fields).encode('utf-8')).hexdigest()
|
|
76
|
+
return result
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
"""The native backend must not depend on legacy binary/settings files."""
|
|
2
|
+
from pathlib import Path
|
|
3
|
+
|
|
4
|
+
import click
|
|
5
|
+
import pytest
|
|
6
|
+
|
|
7
|
+
from chatecnu.config import ECNUConfig
|
|
8
|
+
import chatecnu.ecnu.cli as cli
|
|
9
|
+
from chatecnu.network_http import PythonNetworkAuthClient
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def prepare(monkeypatch):
|
|
13
|
+
monkeypatch.setenv('ECNU_NETWORK_BACKEND', 'python')
|
|
14
|
+
for name in ['ECNU_NETWORK_BACKEND', 'ECNU_AUTH_SETTING_FILE']:
|
|
15
|
+
monkeypatch.setattr(getattr(ECNUConfig, name), 'value', None)
|
|
16
|
+
for name in ['ECNU_NETWORK_BASE_URL', 'ECNU_NETWORK_AC_ID']:
|
|
17
|
+
monkeypatch.delenv(name, raising=False)
|
|
18
|
+
if hasattr(ECNUConfig, name):
|
|
19
|
+
monkeypatch.setattr(getattr(ECNUConfig, name), 'value', None)
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def test_native_default_ignores_missing_legacy_profile_setting(monkeypatch):
|
|
23
|
+
prepare(monkeypatch)
|
|
24
|
+
monkeypatch.setenv('ECNU_AUTH_SETTING_FILE', '/missing/legacy-auth-setting')
|
|
25
|
+
monkeypatch.setattr(PythonNetworkAuthClient, 'from_setting_file', lambda *a, **k: pytest.fail('implicit legacy file read'))
|
|
26
|
+
client = cli.make_network_auth_client(auth_client_path=None, setting_file=None)
|
|
27
|
+
assert client.base_url == 'https://login.ecnu.edu.cn' and client.acid == 1
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def test_native_default_ignores_existing_legacy_home_setting(monkeypatch, tmp_path):
|
|
31
|
+
prepare(monkeypatch)
|
|
32
|
+
monkeypatch.delenv('ECNU_AUTH_SETTING_FILE', raising=False)
|
|
33
|
+
monkeypatch.setattr(Path, 'home', lambda: tmp_path)
|
|
34
|
+
(tmp_path/'.auth-setting').write_text('host="untrusted.example"\nacid="99"\n')
|
|
35
|
+
client = cli.make_network_auth_client(auth_client_path=None, setting_file=None)
|
|
36
|
+
assert client.base_url == 'https://login.ecnu.edu.cn' and client.acid == 1
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def test_native_endpoint_uses_chatenv_values_without_legacy_import(monkeypatch):
|
|
40
|
+
prepare(monkeypatch)
|
|
41
|
+
monkeypatch.setenv('ECNU_AUTH_SETTING_FILE', '/missing/legacy-auth-setting')
|
|
42
|
+
monkeypatch.setenv('ECNU_NETWORK_BASE_URL', 'https://portal.example')
|
|
43
|
+
monkeypatch.setenv('ECNU_NETWORK_AC_ID', '7')
|
|
44
|
+
client = cli.make_network_auth_client(auth_client_path=None, setting_file=None)
|
|
45
|
+
assert client.base_url == 'https://portal.example' and client.acid == 7
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
@pytest.mark.parametrize('acid', ['0','-1','garbage','1.5'])
|
|
49
|
+
def test_native_invalid_ac_id_fails_before_network(monkeypatch, acid):
|
|
50
|
+
prepare(monkeypatch)
|
|
51
|
+
monkeypatch.setenv('ECNU_NETWORK_AC_ID', acid)
|
|
52
|
+
with pytest.raises(click.ClickException):
|
|
53
|
+
cli.make_network_auth_client(auth_client_path=None, setting_file=None)
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def test_explicit_legacy_import_requires_filename():
|
|
57
|
+
with pytest.raises(ValueError):
|
|
58
|
+
PythonNetworkAuthClient.from_setting_file(None)
|
|
@@ -0,0 +1,211 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import importlib
|
|
4
|
+
import json
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
from types import SimpleNamespace
|
|
7
|
+
|
|
8
|
+
import pytest
|
|
9
|
+
import requests
|
|
10
|
+
|
|
11
|
+
GOLDEN = {
|
|
12
|
+
'username': 'offline-fixture-user',
|
|
13
|
+
'password': 'DUMMY_PASSWORD_NOT_A_REAL_ACCOUNT_123!',
|
|
14
|
+
'ip': '192.0.2.23', 'acid': '7', 'token': '0123456789abcdef' * 4,
|
|
15
|
+
'info': '{SRBX1}IMFfp0yaboqcZ5Q9z0n5ULmm/jbFgtSApOj0K5gYbBiB8ItiASHcOY1x6zd2X/mwHymrkYhNTgzVKi3m5wgAOtVQpzKAKO3aCVQg1u3OP5rY/qf8RDT3f39C+ZMnxcdM7iF0D54V/oOxwumTsf3w1nXDwm1hlMr+sTXk8n0KNK8huVJdeP5lGtzTy11siLmh',
|
|
16
|
+
'chksum': 'a11c26880a8c3c31bf71202e26cbcfa2490b855a',
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def protocol():
|
|
21
|
+
assert importlib.util.find_spec('chatecnu.network_protocol'), 'pure protocol is missing'
|
|
22
|
+
return importlib.import_module('chatecnu.network_protocol')
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def client_class():
|
|
26
|
+
assert importlib.util.find_spec('chatecnu.network_http'), 'pure HTTP client is missing'
|
|
27
|
+
return importlib.import_module('chatecnu.network_http').PythonNetworkAuthClient
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
class Response:
|
|
31
|
+
def __init__(self, value, status=200, headers=None):
|
|
32
|
+
self.text = json.dumps(value) if isinstance(value, dict) else value
|
|
33
|
+
self.status_code = status
|
|
34
|
+
self.headers = headers or {}
|
|
35
|
+
def iter_content(self, chunk_size):
|
|
36
|
+
yield self.text.encode()
|
|
37
|
+
def close(self):
|
|
38
|
+
pass
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
class Session:
|
|
42
|
+
def __init__(self, values):
|
|
43
|
+
self.values = iter(values)
|
|
44
|
+
self.calls = []
|
|
45
|
+
self.trust_env = True
|
|
46
|
+
def get(self, url, **kwargs):
|
|
47
|
+
self.calls.append((url, kwargs))
|
|
48
|
+
result = next(self.values)
|
|
49
|
+
if isinstance(result, Exception):
|
|
50
|
+
raise result
|
|
51
|
+
return result if isinstance(result, Response) else Response(result)
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def make(values, **kwargs):
|
|
55
|
+
session = Session(values)
|
|
56
|
+
return client_class()('http://portal.example', acid=7, session=session, **kwargs), session
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def challenge():
|
|
60
|
+
return {'error': 'ok', 'challenge': GOLDEN['token'], 'client_ip': GOLDEN['ip']}
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def test_native_golden_login_parameters():
|
|
64
|
+
p = protocol().build_auth_params(GOLDEN['username'], GOLDEN['password'], GOLDEN['ip'], 7, GOLDEN['token'])
|
|
65
|
+
assert p['password'] == '{MD5}49b95d9f0c28d3d2db688eb59b70e7d6'
|
|
66
|
+
assert p['info'] == GOLDEN['info']
|
|
67
|
+
assert p['chksum'] == GOLDEN['chksum']
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def test_logout_has_no_password_and_distinct_info_checksum():
|
|
71
|
+
p = protocol().build_auth_params('fixture', 'NEVER_IN_LOGOUT', '192.0.2.2', 7, GOLDEN['token'], action='logout')
|
|
72
|
+
empty = protocol().build_auth_params('fixture', '', '192.0.2.2', 7, GOLDEN['token'], action='logout')
|
|
73
|
+
assert p == empty
|
|
74
|
+
assert 'password' not in p and p['action'] == 'logout'
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def test_short_challenge_rejected():
|
|
78
|
+
with pytest.raises(ValueError):
|
|
79
|
+
protocol().build_auth_params('fixture', 'canary', '192.0.2.2', 1, 'short')
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
@pytest.mark.parametrize('text', ['', '<html>login</html>', 'unexpected', '{"error":"unknown"}', 'garbage,a,b,c,d,e,f,g,not-ip'])
|
|
83
|
+
def test_unknown_status_fails_closed(text):
|
|
84
|
+
client, _ = make([text])
|
|
85
|
+
r = client.check()
|
|
86
|
+
assert not r.success and r.online is None
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def test_offline_sentinel_is_not_online():
|
|
90
|
+
client, _ = make(['not_online_error'])
|
|
91
|
+
r = client.check()
|
|
92
|
+
assert r.success and r.online is False and r.username is None
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def test_legacy_csv_online_username():
|
|
96
|
+
client, _ = make(['fixture,0,0,0,0,0,0,0,192.0.2.2'])
|
|
97
|
+
r = client.check()
|
|
98
|
+
assert r.success and r.online is True and r.username == 'fixture'
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def test_json_online_and_offline():
|
|
102
|
+
client, _ = make([{'error':'ok','user_name':'fixture','online_ip':'192.0.2.2'}, {'error':'not_online_error'}])
|
|
103
|
+
assert client.check().online is True
|
|
104
|
+
assert client.check().online is False
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def test_login_uses_http_and_postcheck_without_subprocess(monkeypatch):
|
|
108
|
+
from chatecnu.network_auth import NetworkAuthCredentials
|
|
109
|
+
monkeypatch.setattr('subprocess.run', lambda *a, **k: pytest.fail('binary must not run'))
|
|
110
|
+
client, s = make([challenge(), {'error':'ok','suc_msg':'login_ok'}, 'fixture,0,0,0,0,0,0,0,192.0.2.2'])
|
|
111
|
+
result = client.login(NetworkAuthCredentials('fixture', 'secret-canary'))
|
|
112
|
+
assert result.success and result.online is True and result.backend == 'python'
|
|
113
|
+
assert [u.rsplit('/',1)[-1] for u,k in s.calls] == ['get_challenge','srun_portal','rad_user_info']
|
|
114
|
+
assert 'secret-canary' not in json.dumps(result.to_dict())
|
|
115
|
+
assert s.trust_env is False
|
|
116
|
+
assert all(k['allow_redirects'] is False and k['timeout'] for u,k in s.calls)
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def test_logout_and_fresh_offline_verification():
|
|
120
|
+
client, s = make([challenge(), {'error':'ok','suc_msg':'logout_ok'}, 'not_online_error'])
|
|
121
|
+
result = client.logout('fixture')
|
|
122
|
+
assert result.success and result.online is False
|
|
123
|
+
assert s.calls[1][1]['params']['action'] == 'logout'
|
|
124
|
+
assert 'password' not in s.calls[1][1]['params']
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def test_false_login_success_is_not_verified_online():
|
|
128
|
+
from chatecnu.network_auth import NetworkAuthCredentials
|
|
129
|
+
client, _ = make([challenge(), {'error':'ok'}, 'not_online_error'])
|
|
130
|
+
assert not client.login(NetworkAuthCredentials('fixture','canary')).success
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
def test_portal_failure_does_not_leak_raw_reply_or_request():
|
|
134
|
+
from chatecnu.network_auth import NetworkAuthCredentials
|
|
135
|
+
client, _ = make([challenge(), {'error':'E2901','error_msg':'SECRET_REPLY_RAW'}])
|
|
136
|
+
r = client.login(NetworkAuthCredentials('fixture','secret-canary'))
|
|
137
|
+
out = json.dumps(r.to_dict())
|
|
138
|
+
assert not r.success and 'E2901' in out
|
|
139
|
+
assert all(s not in out for s in ['SECRET_REPLY_RAW','secret-canary',GOLDEN['token'],'{SRBX1}'])
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
def test_transport_error_never_echoes_secret_url():
|
|
143
|
+
client, _ = make([requests.ConnectionError('http://portal.example/?password=SECRET_URL')])
|
|
144
|
+
result = client.check()
|
|
145
|
+
assert not result.success and 'SECRET_URL' not in json.dumps(result.to_dict())
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
def test_only_same_host_upgrade_redirect_is_followed():
|
|
149
|
+
client, s = make([Response('',301,{'Location':'https://portal.example/cgi-bin/rad_user_info'}), 'not_online_error'])
|
|
150
|
+
assert client.check().success
|
|
151
|
+
assert s.calls[-1][0].startswith('https://portal.example/')
|
|
152
|
+
client, s = make([Response('',302,{'Location':'https://other.example/steal'})])
|
|
153
|
+
assert not client.check().success and len(s.calls) == 1
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
@pytest.mark.parametrize('query,accepted', [('username=fixture&ip=',True),('username=other&ip=',False),('username=fixture&ip=&extra=x',False)])
|
|
157
|
+
def test_upgrade_redirect_must_preserve_original_query(query, accepted):
|
|
158
|
+
client, s = make([Response('',301,{'Location':'https://portal.example/cgi-bin/get_challenge?'+query}), '{}'])
|
|
159
|
+
if accepted:
|
|
160
|
+
assert client._get('/cgi-bin/get_challenge', {'username':'fixture','ip':''}) == '{}'
|
|
161
|
+
assert len(s.calls) == 2
|
|
162
|
+
else:
|
|
163
|
+
from chatecnu.network_http import PortalProtocolError
|
|
164
|
+
with pytest.raises(PortalProtocolError):
|
|
165
|
+
client._get('/cgi-bin/get_challenge', {'username':'fixture','ip':''})
|
|
166
|
+
assert len(s.calls) == 1
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
def test_ensure_online_skips_login():
|
|
170
|
+
from chatecnu.network_auth import NetworkAuthCredentials
|
|
171
|
+
client, s = make(['fixture,0,0,0,0,0,0,0,192.0.2.2'])
|
|
172
|
+
r = client.ensure_login(NetworkAuthCredentials('fixture','canary'))
|
|
173
|
+
assert r.success and r.skipped and len(s.calls) == 1
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
@pytest.mark.parametrize('changed', [{'error':[]},{'error':{}},{'client_ip':123},{'client_ip':False},{'client_ip':[]},{'online_ip':{}},{'challenge':123}])
|
|
177
|
+
def test_malformed_challenge_fields_fail_safely(changed):
|
|
178
|
+
from chatecnu.network_auth import NetworkAuthCredentials
|
|
179
|
+
value = challenge()
|
|
180
|
+
value.update(changed)
|
|
181
|
+
client, session = make([value])
|
|
182
|
+
result = client.login(NetworkAuthCredentials('fixture', 'SECRET_CANARY_BAD_RESPONSE'))
|
|
183
|
+
assert result.success is False and result.backend == 'python'
|
|
184
|
+
assert len(session.calls) == 1
|
|
185
|
+
assert 'SECRET_CANARY_BAD_RESPONSE' not in json.dumps(result.to_dict())
|
|
186
|
+
|
|
187
|
+
|
|
188
|
+
def test_credential_mutation_redirect_is_never_followed():
|
|
189
|
+
from chatecnu.network_auth import NetworkAuthCredentials
|
|
190
|
+
client, session = make([challenge(), Response('',302,{'Location':'https://portal.example/cgi-bin/srun_portal'})])
|
|
191
|
+
result = client.login(NetworkAuthCredentials('fixture', 'SECRET_REDIRECT_CANARY'))
|
|
192
|
+
assert result.success is False and len(session.calls) == 2
|
|
193
|
+
assert result.stderr == 'Portal redirect refused'
|
|
194
|
+
assert 'SECRET_REDIRECT_CANARY' not in json.dumps(result.to_dict())
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
def test_from_legacy_toml_accepts_string_acid(tmp_path):
|
|
198
|
+
p = tmp_path/'settings'
|
|
199
|
+
p.write_text('host="portal.example"\nacid="7"\ncampus_url=""\ncampus_postfix=""\n')
|
|
200
|
+
c = client_class().from_setting_file(p)
|
|
201
|
+
assert c.acid == 7 and c.base_url == 'http://portal.example'
|
|
202
|
+
|
|
203
|
+
|
|
204
|
+
def test_cli_factory_defaults_to_python_without_binary_resolution(monkeypatch):
|
|
205
|
+
import chatecnu.ecnu.cli as cli
|
|
206
|
+
monkeypatch.setattr(cli,'resolve_auth_client_path', lambda *a: pytest.fail('binary resolution'))
|
|
207
|
+
monkeypatch.delenv('ECNU_NETWORK_BACKEND',raising=False)
|
|
208
|
+
from chatecnu.config import ECNUConfig
|
|
209
|
+
monkeypatch.setattr(ECNUConfig.ECNU_NETWORK_BACKEND,'value',None)
|
|
210
|
+
c = cli.make_network_auth_client(auth_client_path=None, setting_file=None)
|
|
211
|
+
assert isinstance(c, client_class())
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
from chatecnu.config import ECNUConfig
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
def test_ecnu_password_fields_use_full_shared_masking(monkeypatch):
|
|
5
|
+
canary = 'DUMMY_ECNU_LONG_PASSWORD_CANARY_123456789'
|
|
6
|
+
for name in ['ECNU_PASSWORD', 'ECNU_VISITOR_PASSWORD1', 'ECNU_VISITOR_PASSWORD2']:
|
|
7
|
+
field = getattr(ECNUConfig, name)
|
|
8
|
+
assert field.is_sensitive is True
|
|
9
|
+
monkeypatch.setattr(field, 'value', canary)
|
|
10
|
+
assert field.mask_value() == '*' * len(canary)
|
|
@@ -2,7 +2,7 @@ from chatecnu import __version__
|
|
|
2
2
|
|
|
3
3
|
|
|
4
4
|
def test_version_present():
|
|
5
|
-
assert __version__ == "0.2.
|
|
5
|
+
assert __version__ == "0.2.9"
|
|
6
6
|
|
|
7
7
|
|
|
8
8
|
def test_cli_version_option():
|
|
@@ -12,7 +12,7 @@ def test_cli_version_option():
|
|
|
12
12
|
result = CliRunner().invoke(main, ["--version"])
|
|
13
13
|
|
|
14
14
|
assert result.exit_code == 0
|
|
15
|
-
assert result.output.strip().endswith(", version 0.2.
|
|
15
|
+
assert result.output.strip().endswith(", version 0.2.9")
|
|
16
16
|
|
|
17
17
|
|
|
18
18
|
def test_shared_runtime_dependencies_and_refresh_provider_entry_point_declared():
|
|
@@ -23,7 +23,7 @@ def test_shared_runtime_dependencies_and_refresh_provider_entry_point_declared()
|
|
|
23
23
|
)
|
|
24
24
|
assert '"ChatNet>=0.2.4,<0.3.0"' in pyproject
|
|
25
25
|
assert '"chatstyle>=0.2.0,<0.3.0"' in pyproject
|
|
26
|
-
assert '"chatenv>=0.2.
|
|
26
|
+
assert '"chatenv>=0.2.13,<0.3.0"' in pyproject
|
|
27
27
|
assert 'ecnu = "chatecnu.cli:main"' in pyproject
|
|
28
28
|
assert 'chatecnu = "chatecnu.cli:main"' in pyproject
|
|
29
29
|
assert '[project.entry-points."chatenv.token_refreshers"]' in pyproject
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|