sdtk-code-kit 0.4.3 → 0.5.0
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.
- package/LICENSE +21 -0
- package/README.md +1 -1
- package/assets/manifest/toolkit-bundle.manifest.json +82 -12
- package/assets/manifest/toolkit-bundle.sha256.txt +21 -7
- package/assets/toolkit/toolkit/AGENTS.md +1 -1
- package/assets/toolkit/toolkit/SDTKCODE_TOOLKIT.md +2 -2
- package/assets/toolkit/toolkit/scripts/install-claude-skills.ps1 +4 -4
- package/assets/toolkit/toolkit/scripts/install-codex-skills.ps1 +4 -4
- package/assets/toolkit/toolkit/scripts/uninstall-claude-skills.ps1 +2 -2
- package/assets/toolkit/toolkit/scripts/uninstall-codex-skills.ps1 +2 -2
- package/assets/toolkit/toolkit/skills/code-discover/SKILL.md +3 -1
- package/assets/toolkit/toolkit/skills/code-ui-e2e/SKILL.md +97 -0
- package/assets/toolkit/toolkit/skills/code-ui-e2e/references/PROFILE_TEMPLATE.md +30 -0
- package/assets/toolkit/toolkit/skills/code-ui-e2e/references/SAFETY.md +17 -0
- package/assets/toolkit/toolkit/skills/code-ui-e2e/references/TEST_HOOKS.md +32 -0
- package/assets/toolkit/toolkit/skills/code-ui-e2e/scripts/app_profile.py +118 -0
- package/assets/toolkit/toolkit/skills/code-ui-e2e/scripts/build_test_app.py +140 -0
- package/assets/toolkit/toolkit/skills/code-ui-e2e/scripts/cli.py +46 -0
- package/assets/toolkit/toolkit/skills/code-ui-e2e/scripts/fault_proxy.py +381 -0
- package/assets/toolkit/toolkit/skills/code-ui-e2e/scripts/run_smoke.py +242 -0
- package/assets/toolkit/toolkit/skills/code-ui-e2e/scripts/test_app_profile.py +79 -0
- package/assets/toolkit/toolkit/skills/code-ui-e2e/scripts/test_fault_proxy.py +327 -0
- package/assets/toolkit/toolkit/skills/code-ui-e2e/scripts/test_run_smoke.py +79 -0
- package/assets/toolkit/toolkit/skills/code-ui-e2e/scripts/uia_base.py +127 -0
- package/assets/toolkit/toolkit/skills/code-ui-e2e/scripts/waits.py +40 -0
- package/package.json +1 -1
- package/src/lib/scope.js +1 -0
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
"""What the app under test leaves on the machine, and keeping the machine owner's copy of it safe while tests run.
|
|
3
|
+
|
|
4
|
+
The project's e2e profile (`docs/qa/e2e_profile.json`, see references/PROFILE_TEMPLATE.md) declares one entry per
|
|
5
|
+
generation of the app (a product rename changes the exe, data folder and registry key):
|
|
6
|
+
|
|
7
|
+
{"generations": [{"exe_name": "App.exe", "data_dir": "%LOCALAPPDATA%\\\\App", "registry_key": "Software\\\\App",
|
|
8
|
+
"data_files": ["app.db", "app.db-wal", "app.db-shm"]}],
|
|
9
|
+
"profile_values": {"BaseFolderPath": "{work}\\\\{label}"}, # registry values set per test account
|
|
10
|
+
"clear_values": ["Session"]} # never resume another account's sign-in
|
|
11
|
+
|
|
12
|
+
A test build of the product usually has the SAME identity as the copy the machine owner uses every day: started as is,
|
|
13
|
+
it signs in with the owner's saved session and runs on the owner's database. OwnerState parks the owner's data files
|
|
14
|
+
and registry key before the run and puts them back after; it refuses while that exe is running, and keeps a copy of
|
|
15
|
+
the data files that nothing here ever deletes.
|
|
16
|
+
"""
|
|
17
|
+
import json
|
|
18
|
+
import os
|
|
19
|
+
import shutil
|
|
20
|
+
import subprocess
|
|
21
|
+
import time
|
|
22
|
+
import winreg
|
|
23
|
+
from dataclasses import dataclass, field
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
@dataclass(frozen=True)
|
|
27
|
+
class Identity:
|
|
28
|
+
exe_name: str
|
|
29
|
+
data_dir: str
|
|
30
|
+
registry_key: str
|
|
31
|
+
data_files: tuple = ()
|
|
32
|
+
extra: dict = field(default_factory=dict, hash=False, compare=False)
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def load(path) -> dict:
|
|
36
|
+
with open(path, encoding="utf-8") as f:
|
|
37
|
+
return json.load(f)
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def identity(cfg: dict, exe_path: str | None = None) -> Identity:
|
|
41
|
+
"""The generation whose exe_name is the file name of `exe_path` (else the first one)."""
|
|
42
|
+
gens = cfg["generations"]
|
|
43
|
+
name = os.path.basename(exe_path or "").lower()
|
|
44
|
+
g = next((g for g in gens if g["exe_name"].lower() == name), gens[0])
|
|
45
|
+
return Identity(g["exe_name"], os.path.expandvars(g["data_dir"]), g["registry_key"], tuple(g.get("data_files", ())),
|
|
46
|
+
{k: v for k, v in g.items() if k not in ("exe_name", "data_dir", "registry_key", "data_files")})
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def process_running(exe_name: str) -> bool:
|
|
50
|
+
out = subprocess.run(["tasklist", "/FI", f"IMAGENAME eq {exe_name}", "/NH"], capture_output=True, text=True).stdout
|
|
51
|
+
return exe_name.lower() in out.lower()
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
class OwnerState:
|
|
55
|
+
def __init__(self, ident: Identity, cfg: dict, state_dir: str, work_root: str, running=process_running):
|
|
56
|
+
self.ident, self.cfg, self.state_dir, self.work_root, self.running = ident, cfg, state_dir, work_root, running
|
|
57
|
+
self.original_dir = os.path.join(state_dir, "_original")
|
|
58
|
+
self.backup_reg = os.path.join(state_dir, "_original.reg")
|
|
59
|
+
self.current = None
|
|
60
|
+
|
|
61
|
+
def _move(self, src_dir, dst_dir):
|
|
62
|
+
os.makedirs(dst_dir, exist_ok=True)
|
|
63
|
+
for name in self.ident.data_files:
|
|
64
|
+
src = os.path.join(src_dir, name)
|
|
65
|
+
if os.path.exists(src):
|
|
66
|
+
dst = os.path.join(dst_dir, name)
|
|
67
|
+
if os.path.exists(dst):
|
|
68
|
+
os.remove(dst)
|
|
69
|
+
shutil.move(src, dst)
|
|
70
|
+
|
|
71
|
+
def park(self):
|
|
72
|
+
"""Parks the owner's data files and exports their registry key. Call once, with the app stopped."""
|
|
73
|
+
if self.running(self.ident.exe_name):
|
|
74
|
+
raise RuntimeError(f"{self.ident.exe_name} is running (the owner's app?): close it first; nothing changed")
|
|
75
|
+
if os.path.exists(self.backup_reg):
|
|
76
|
+
raise RuntimeError(f"{self.backup_reg} exists: a previous run did not restore; restore first")
|
|
77
|
+
os.makedirs(self.state_dir, exist_ok=True)
|
|
78
|
+
subprocess.run(["reg", "export", "HKCU\\" + self.ident.registry_key, self.backup_reg, "/y"], capture_output=True)
|
|
79
|
+
if not os.path.exists(self.backup_reg):
|
|
80
|
+
open(self.backup_reg, "w").close() # no key yet: restoring means deleting it
|
|
81
|
+
keep = os.path.join(self.state_dir, "_owner_backup_" + time.strftime("%Y%m%d-%H%M%S"))
|
|
82
|
+
os.makedirs(keep, exist_ok=True)
|
|
83
|
+
for name in self.ident.data_files:
|
|
84
|
+
if os.path.exists(os.path.join(self.ident.data_dir, name)):
|
|
85
|
+
shutil.copy2(os.path.join(self.ident.data_dir, name), keep)
|
|
86
|
+
self._move(self.ident.data_dir, self.original_dir)
|
|
87
|
+
|
|
88
|
+
def switch_to(self, label: str):
|
|
89
|
+
"""Brings back `label`'s own data files (none on its first run) and sets its registry values. App stopped."""
|
|
90
|
+
if self.running(self.ident.exe_name):
|
|
91
|
+
raise RuntimeError(f"{self.ident.exe_name} is running: stop it before switching accounts")
|
|
92
|
+
if self.current:
|
|
93
|
+
self._move(self.ident.data_dir, os.path.join(self.state_dir, self.current))
|
|
94
|
+
self._move(os.path.join(self.state_dir, label), self.ident.data_dir)
|
|
95
|
+
with winreg.CreateKey(winreg.HKEY_CURRENT_USER, self.ident.registry_key) as key:
|
|
96
|
+
for name, template in self.cfg.get("profile_values", {}).items():
|
|
97
|
+
value = template.format(work=self.work_root, label=label)
|
|
98
|
+
if name.lower().endswith(("path", "folder")):
|
|
99
|
+
os.makedirs(value, exist_ok=True) # the account's own folder, under the test work root
|
|
100
|
+
winreg.SetValueEx(key, name, 0, winreg.REG_SZ, value)
|
|
101
|
+
for name in self.cfg.get("clear_values", []):
|
|
102
|
+
try:
|
|
103
|
+
winreg.DeleteValue(key, name)
|
|
104
|
+
except FileNotFoundError:
|
|
105
|
+
pass
|
|
106
|
+
self.current = label
|
|
107
|
+
|
|
108
|
+
def restore(self):
|
|
109
|
+
"""Parks the last account's data files and puts the owner's data files and registry key back."""
|
|
110
|
+
if self.current:
|
|
111
|
+
self._move(self.ident.data_dir, os.path.join(self.state_dir, self.current))
|
|
112
|
+
self.current = None
|
|
113
|
+
self._move(self.original_dir, self.ident.data_dir)
|
|
114
|
+
if os.path.exists(self.backup_reg):
|
|
115
|
+
subprocess.run(["reg", "delete", "HKCU\\" + self.ident.registry_key, "/f"], capture_output=True)
|
|
116
|
+
if os.path.getsize(self.backup_reg) > 0:
|
|
117
|
+
subprocess.run(["reg", "import", self.backup_reg], check=True, capture_output=True)
|
|
118
|
+
os.remove(self.backup_reg)
|
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
"""Builds the app under test from the product repository plus a private test patch (UI Automation names, test hooks).
|
|
3
|
+
|
|
4
|
+
python build_test_app.py --repo <product repo> --project src/App/App.csproj --ref origin/main --patch <tool repo>\\app_patch\\uia-hooks.patch
|
|
5
|
+
python build_test_app.py --repo <product repo> --project src/App/App.csproj --ref origin/feature/x --patch -
|
|
6
|
+
|
|
7
|
+
The product repository is only READ: `git archive` exports the ref into a new folder that is not a git repository,
|
|
8
|
+
the patch is applied there and the app is built into <out-root>\\<ref>-<sha7>\\out. Nothing is ever committed, branched
|
|
9
|
+
or pushed to the product repository: when that repository belongs to a customer, even a pushed branch is visible to
|
|
10
|
+
them, so test-only code stays a patch in the team's own tool repository.
|
|
11
|
+
A folder that already holds the same commit built with the same patch is reused unless --rebuild is given.
|
|
12
|
+
The build command is `dotnet build <project>`; for another stack, replace build() (one function).
|
|
13
|
+
"""
|
|
14
|
+
import argparse
|
|
15
|
+
import hashlib
|
|
16
|
+
import json
|
|
17
|
+
import os
|
|
18
|
+
import re
|
|
19
|
+
import shutil
|
|
20
|
+
import subprocess
|
|
21
|
+
import sys
|
|
22
|
+
import tarfile
|
|
23
|
+
import time
|
|
24
|
+
|
|
25
|
+
sys.stdout.reconfigure(encoding="utf-8")
|
|
26
|
+
HERE = os.path.dirname(os.path.abspath(__file__))
|
|
27
|
+
# Outside every repository: `git apply` inside one resolves the patch paths from that repository's root.
|
|
28
|
+
DEFAULT_OUT_ROOT = os.environ.get("TEST_BUILD_ROOT") or os.path.join(os.path.expanduser("~"), "_testbuild")
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
class BuildError(RuntimeError):
|
|
32
|
+
pass
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def git(repo, *args, binary=False):
|
|
36
|
+
r = subprocess.run(["git", "-C", repo, *args], capture_output=True)
|
|
37
|
+
if r.returncode:
|
|
38
|
+
raise BuildError(f"git {' '.join(args)}: {r.stderr.decode('utf-8', 'replace').strip()}")
|
|
39
|
+
return r.stdout if binary else r.stdout.decode("utf-8").strip()
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def inside_git_repo(path) -> bool:
|
|
43
|
+
"""`git apply` in a folder inside some repository resolves the patch's paths from that repository's root."""
|
|
44
|
+
probe = path
|
|
45
|
+
while not os.path.exists(probe):
|
|
46
|
+
probe = os.path.dirname(probe)
|
|
47
|
+
return subprocess.run(["git", "-C", probe, "rev-parse", "--show-toplevel"], capture_output=True).returncode == 0
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def sha256(path) -> str:
|
|
51
|
+
return hashlib.sha256(open(path, "rb").read()).hexdigest() if path else ""
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def export(repo, sha, dest):
|
|
55
|
+
"""The commit's files, without a .git: nothing done here can reach the customer's repository."""
|
|
56
|
+
archive = git(repo, "archive", "--format=tar", sha, binary=True)
|
|
57
|
+
tar_path = dest + ".tar"
|
|
58
|
+
with open(tar_path, "wb") as f:
|
|
59
|
+
f.write(archive)
|
|
60
|
+
with tarfile.open(tar_path) as t:
|
|
61
|
+
t.extractall(dest, filter="data")
|
|
62
|
+
os.remove(tar_path)
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def apply_patch(src, patch):
|
|
66
|
+
r = subprocess.run(["git", "apply", "--whitespace=nowarn", "-p1", patch], cwd=src, capture_output=True)
|
|
67
|
+
if r.returncode:
|
|
68
|
+
failed = sorted(set(re.findall(r"patch failed: ([^:]+):", r.stderr.decode("utf-8", "replace"))))
|
|
69
|
+
raise BuildError("the patch does not apply to this commit; refresh it for: " + (", ".join(failed) or
|
|
70
|
+
r.stderr.decode("utf-8", "replace").strip()))
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def build(src, out, config, project):
|
|
74
|
+
r = subprocess.run(["dotnet", "build", os.path.join(src, project), "-c", config, "-o", out, "-nologo", "-v", "q"],
|
|
75
|
+
capture_output=True, text=True, encoding="utf-8", errors="replace")
|
|
76
|
+
if r.returncode:
|
|
77
|
+
tail = "\n".join((r.stdout + r.stderr).strip().splitlines()[-15:])
|
|
78
|
+
raise BuildError("dotnet build failed:\n" + tail)
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def find_exe(out):
|
|
82
|
+
exes = [f for f in os.listdir(out) if f.lower().endswith(".exe") and f.lower() not in ("createdump.exe",)]
|
|
83
|
+
if len(exes) != 1:
|
|
84
|
+
raise BuildError(f"expected one app exe in {out}, found {exes}")
|
|
85
|
+
return os.path.join(out, exes[0])
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def main(argv=None):
|
|
89
|
+
a = argparse.ArgumentParser(description=__doc__.split("\n")[0])
|
|
90
|
+
a.add_argument("--repo", required=True, help="the customer's repository (read only)")
|
|
91
|
+
a.add_argument("--ref", default="origin/main", help="commit, branch or tag to build")
|
|
92
|
+
a.add_argument("--project", required=True, help="project file to build, relative to the repository root")
|
|
93
|
+
a.add_argument("--patch", required=True, help="private test patch applied on top; '-' for none")
|
|
94
|
+
a.add_argument("--out-root", default=DEFAULT_OUT_ROOT)
|
|
95
|
+
a.add_argument("--config", default="Release")
|
|
96
|
+
a.add_argument("--rebuild", action="store_true")
|
|
97
|
+
args = a.parse_args(argv)
|
|
98
|
+
|
|
99
|
+
patch = None if args.patch == "-" else os.path.abspath(args.patch)
|
|
100
|
+
out_root = os.path.abspath(args.out_root)
|
|
101
|
+
if inside_git_repo(out_root):
|
|
102
|
+
raise BuildError(f"{out_root} is inside a git repository: choose --out-root outside any repository")
|
|
103
|
+
sha = git(args.repo, "rev-parse", "--verify", args.ref + "^{commit}")
|
|
104
|
+
name = re.sub(r"[^A-Za-z0-9._-]+", "-", args.ref.replace("origin/", "")).strip("-") + "-" + sha[:7]
|
|
105
|
+
dest = os.path.join(out_root, name)
|
|
106
|
+
info_path = os.path.join(dest, "build_info.json")
|
|
107
|
+
info = {"repo": os.path.abspath(args.repo), "project": args.project, "ref": args.ref, "sha": sha, "config": args.config,
|
|
108
|
+
"patch": patch, "patch_sha256": sha256(patch)}
|
|
109
|
+
|
|
110
|
+
if not args.rebuild and os.path.exists(info_path):
|
|
111
|
+
old = json.load(open(info_path, encoding="utf-8"))
|
|
112
|
+
if all(old.get(k) == v for k, v in info.items()) and os.path.exists(old.get("exe", "")):
|
|
113
|
+
print("up to date:", old["exe"])
|
|
114
|
+
return old["exe"]
|
|
115
|
+
if os.path.exists(dest):
|
|
116
|
+
# Only a folder this script made (build_info.json, or just src/out from a build that stopped half-way).
|
|
117
|
+
if not os.path.exists(info_path) and not set(os.listdir(dest)) <= {"src", "out", "src.tar"}:
|
|
118
|
+
raise BuildError(f"{dest} exists and was not made by this script: nothing deleted")
|
|
119
|
+
shutil.rmtree(dest)
|
|
120
|
+
src, out = os.path.join(dest, "src"), os.path.join(dest, "out")
|
|
121
|
+
os.makedirs(src)
|
|
122
|
+
print(f"export {args.ref} ({sha[:7]}) -> {src}")
|
|
123
|
+
export(args.repo, sha, src)
|
|
124
|
+
if patch:
|
|
125
|
+
print("apply", os.path.basename(patch))
|
|
126
|
+
apply_patch(src, patch)
|
|
127
|
+
print(f"dotnet build -c {args.config} -> {out}")
|
|
128
|
+
build(src, out, args.config, args.project)
|
|
129
|
+
info.update(exe=find_exe(out), built_at=time.strftime("%Y-%m-%d %H:%M:%S"))
|
|
130
|
+
json.dump(info, open(info_path, "w", encoding="utf-8"), ensure_ascii=False, indent=1)
|
|
131
|
+
print("built:", info["exe"])
|
|
132
|
+
return info["exe"]
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
if __name__ == "__main__":
|
|
136
|
+
try:
|
|
137
|
+
main()
|
|
138
|
+
except BuildError as e:
|
|
139
|
+
print("ERROR:", e)
|
|
140
|
+
sys.exit(1)
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
"""Runs the app's command-line entry points (a second process handing a request to the running app, a one-shot
|
|
3
|
+
mode, an integration called by another program) and reports exit code and timing.
|
|
4
|
+
|
|
5
|
+
r = cli.run(exe, ["--some-command=<id>", "--path=C:\\a b"])
|
|
6
|
+
ctx.check(r.accepted, f"accepted: {r}")
|
|
7
|
+
|
|
8
|
+
Each argument is one argv entry, so a path with spaces arrives whole. A process that has not exited at the timeout
|
|
9
|
+
is killed — it is the one this call started, never the running app (another pid). Most hand-over commands return as
|
|
10
|
+
soon as the request is accepted: check the effect separately (waits.py).
|
|
11
|
+
"""
|
|
12
|
+
import os
|
|
13
|
+
import subprocess
|
|
14
|
+
import time
|
|
15
|
+
from dataclasses import dataclass
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
@dataclass
|
|
19
|
+
class CliResult:
|
|
20
|
+
args: list
|
|
21
|
+
code: int | None # None: still running at the timeout (then killed)
|
|
22
|
+
seconds: float
|
|
23
|
+
stdout: str
|
|
24
|
+
stderr: str
|
|
25
|
+
|
|
26
|
+
@property
|
|
27
|
+
def accepted(self) -> bool:
|
|
28
|
+
return self.code == 0
|
|
29
|
+
|
|
30
|
+
def __str__(self):
|
|
31
|
+
return f"exit {self.code} in {self.seconds:.1f}s: {' '.join(self.args[1:])}"
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def run(exe: str, args: list[str], timeout: float = 60) -> CliResult:
|
|
35
|
+
cmd = [exe, *args]
|
|
36
|
+
started = time.time()
|
|
37
|
+
p = subprocess.Popen(cmd, cwd=os.path.dirname(exe) or None, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
|
|
38
|
+
try:
|
|
39
|
+
out, err = p.communicate(timeout=timeout)
|
|
40
|
+
code = p.returncode
|
|
41
|
+
except subprocess.TimeoutExpired:
|
|
42
|
+
p.kill()
|
|
43
|
+
out, err = p.communicate()
|
|
44
|
+
code = None
|
|
45
|
+
return CliResult(cmd, code, time.time() - started,
|
|
46
|
+
out.decode("utf-8", "replace"), err.decode("utf-8", "replace"))
|
|
@@ -0,0 +1,381 @@
|
|
|
1
|
+
#!/usr/bin/env python
|
|
2
|
+
"""A proxy that can be told to misbehave, so connection-failure handling can be checked on the real app.
|
|
3
|
+
|
|
4
|
+
python fault_proxy.py # listens on 127.0.0.1:8899, mode p
|
|
5
|
+
python fault_proxy.py --port 9000 --mode 5
|
|
6
|
+
|
|
7
|
+
Point the app's proxy setting at 127.0.0.1:8899 (no user / password). The mode changes while it runs, either with one
|
|
8
|
+
key in the console (no Enter) or, for a script, with a request the proxy answers itself and never forwards (only from
|
|
9
|
+
127.0.0.1):
|
|
10
|
+
|
|
11
|
+
curl http://127.0.0.1:8899/__fault/mode/5 # -> 200 mode=5
|
|
12
|
+
curl http://127.0.0.1:8899/__fault/mode # -> 200 mode=<current>
|
|
13
|
+
curl http://127.0.0.1:8899/__fault/rule/<url-encoded JSON rule> # see RULES below; /__fault/rule/- clears them
|
|
14
|
+
|
|
15
|
+
The keys:
|
|
16
|
+
|
|
17
|
+
p pass forward everything, as a healthy network would
|
|
18
|
+
5 503 answer every plain-HTTP request with 503 (a server in maintenance)
|
|
19
|
+
h hang accept the connection and never answer (a server that is up but not responding)
|
|
20
|
+
d drop cut the connection at once (the network is gone / the server refuses)
|
|
21
|
+
7 407 answer with "Proxy Authentication Required"
|
|
22
|
+
r 302 answer with a redirect, as a hotel Wi-Fi login page does
|
|
23
|
+
q quit
|
|
24
|
+
|
|
25
|
+
Write down, per mode, what the app must show (an error state, offline, retry) in the project's e2e profile: the proxy
|
|
26
|
+
only produces the fault, the test case states the expected reaction.
|
|
27
|
+
|
|
28
|
+
HTTPS goes through CONNECT (e.g. pre-signed storage URLs). The proxy cannot see inside a tunnel, so in modes 5/7/r a
|
|
29
|
+
CONNECT is answered with that status on the CONNECT itself - the client reports a failed connection. The API address
|
|
30
|
+
must be plain http for 5/7/r to be seen as HTTP answers.
|
|
31
|
+
|
|
32
|
+
If the API address is a loopback address, .NET may skip the proxy for it entirely and this window will show nothing.
|
|
33
|
+
Use the machine's LAN address in the app's settings for the check, and look for the request lines below.
|
|
34
|
+
|
|
35
|
+
Stdlib only - no install. Windows console (single-key input); elsewhere type the letter and press Enter.
|
|
36
|
+
Its own tests: python -m unittest test_fault_proxy (from this folder)
|
|
37
|
+
"""
|
|
38
|
+
import argparse, json, socket, struct, sys, threading, time
|
|
39
|
+
from urllib.parse import unquote, urlsplit
|
|
40
|
+
|
|
41
|
+
LOCK = threading.Lock()
|
|
42
|
+
MODE = "p"
|
|
43
|
+
# What the app's version check (POST .../system-limit-version) is answered with while the mode is p; None = ask the real server.
|
|
44
|
+
VERSION_BODY = None
|
|
45
|
+
VERSION_PATH = "/system-limit-version"
|
|
46
|
+
# Answer rules for ordinary API requests while the mode is p: {"match": substring of the URL path, "not_match": substring it must NOT
|
|
47
|
+
# contain, "status": int, "body": str, "times": how many requests it answers (omitted = every one)}. First matching rule wins.
|
|
48
|
+
# "websocket": true limits a rule to WebSocket handshakes (Upgrade: websocket) - the app's realtime channel, plain ws:// through
|
|
49
|
+
# the proxy. {"connect": substring of host:port} makes a rule answer a CONNECT instead (a wss:// or https:// tunnel): the
|
|
50
|
+
# tunnel is refused with that status, ordinary requests are never matched by it.
|
|
51
|
+
RULES = []
|
|
52
|
+
MODES = {
|
|
53
|
+
"p": "pass",
|
|
54
|
+
"5": "503 Service Unavailable",
|
|
55
|
+
"h": "hang (no answer)",
|
|
56
|
+
"d": "drop (cut connection)",
|
|
57
|
+
"7": "407 Proxy Authentication Required",
|
|
58
|
+
"r": "302 redirect",
|
|
59
|
+
}
|
|
60
|
+
CANNED = {
|
|
61
|
+
"5": (503, "Service Unavailable", ""),
|
|
62
|
+
"7": (407, "Proxy Authentication Required", 'Proxy-Authenticate: Basic realm="fault_proxy"\r\n'),
|
|
63
|
+
"r": (302, "Found", "Location: http://captive.example.invalid/login\r\n"),
|
|
64
|
+
}
|
|
65
|
+
CONNECT_TIMEOUT = 10
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def log(*a):
|
|
69
|
+
with LOCK:
|
|
70
|
+
print(time.strftime("%H:%M:%S"), *a, flush=True)
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def read_head(sock):
|
|
74
|
+
"""Reads up to the blank line. Returns (header lines, bytes already read past it), or (None, b"")."""
|
|
75
|
+
buf = b""
|
|
76
|
+
while b"\r\n\r\n" not in buf:
|
|
77
|
+
chunk = sock.recv(65536)
|
|
78
|
+
if not chunk:
|
|
79
|
+
return None, b""
|
|
80
|
+
buf += chunk
|
|
81
|
+
if len(buf) > 1 << 20:
|
|
82
|
+
return None, b""
|
|
83
|
+
head, _, rest = buf.partition(b"\r\n\r\n")
|
|
84
|
+
return head.decode("latin-1").split("\r\n"), rest
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def answer(sock, code, reason, extra="", body=""):
|
|
88
|
+
data = body.encode("utf-8")
|
|
89
|
+
sock.sendall((f"HTTP/1.1 {code} {reason}\r\n{extra}Content-Length: {len(data)}\r\nConnection: close\r\n\r\n"
|
|
90
|
+
).encode("latin-1") + data)
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def reset(sock):
|
|
94
|
+
"""Closes with RST rather than FIN, which is what a connection killed by the network looks like."""
|
|
95
|
+
try:
|
|
96
|
+
sock.setsockopt(socket.SOL_SOCKET, socket.SO_LINGER, struct.pack("ii", 1, 0))
|
|
97
|
+
except OSError:
|
|
98
|
+
pass
|
|
99
|
+
try:
|
|
100
|
+
# Wakes a thread blocked in recv() on this socket (close() alone does not on Linux); sends nothing.
|
|
101
|
+
sock.shutdown(socket.SHUT_RD)
|
|
102
|
+
except OSError:
|
|
103
|
+
pass
|
|
104
|
+
sock.close()
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def hang(sock):
|
|
108
|
+
"""Holds the connection open, saying nothing, until the client gives up on its own."""
|
|
109
|
+
sock.settimeout(None)
|
|
110
|
+
try:
|
|
111
|
+
while sock.recv(4096):
|
|
112
|
+
pass
|
|
113
|
+
except OSError:
|
|
114
|
+
pass
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def pipe(src, dst):
|
|
118
|
+
try:
|
|
119
|
+
while True:
|
|
120
|
+
data = src.recv(65536)
|
|
121
|
+
if not data:
|
|
122
|
+
break
|
|
123
|
+
dst.sendall(data)
|
|
124
|
+
except OSError:
|
|
125
|
+
pass
|
|
126
|
+
finally:
|
|
127
|
+
try:
|
|
128
|
+
dst.shutdown(socket.SHUT_WR)
|
|
129
|
+
except OSError:
|
|
130
|
+
pass
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
ACTIVE = set() # sockets of the exchanges being relayed right now: a fault mode cuts them too
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def cut_active():
|
|
137
|
+
"""Resets every exchange in flight (an upload already under way), as a dropped network would."""
|
|
138
|
+
with LOCK:
|
|
139
|
+
socks = list(ACTIVE)
|
|
140
|
+
ACTIVE.clear()
|
|
141
|
+
for sk in socks:
|
|
142
|
+
reset(sk)
|
|
143
|
+
if socks:
|
|
144
|
+
log(f"cut {len(socks)} exchange(s) in flight")
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
def relay(a, b):
|
|
148
|
+
with LOCK:
|
|
149
|
+
ACTIVE.update((a, b))
|
|
150
|
+
t = threading.Thread(target=pipe, args=(b, a), daemon=True)
|
|
151
|
+
t.start()
|
|
152
|
+
pipe(a, b)
|
|
153
|
+
t.join(timeout=5)
|
|
154
|
+
with LOCK:
|
|
155
|
+
ACTIVE.discard(a)
|
|
156
|
+
ACTIVE.discard(b)
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
CONTROL_PREFIX = "/__fault/mode"
|
|
160
|
+
VERSION_CONTROL = "/__fault/versionbody"
|
|
161
|
+
RULE_CONTROL = "/__fault/rule"
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
def control(client, addr, target):
|
|
165
|
+
"""Answers a /__fault/mode request itself. True when the request was one (whatever the answer)."""
|
|
166
|
+
global VERSION_BODY
|
|
167
|
+
path = urlsplit(target).path
|
|
168
|
+
if path.startswith(RULE_CONTROL):
|
|
169
|
+
# GET /__fault/rule/<url-encoded JSON rule> adds a rule; /__fault/rule/- removes them all; no argument lists them.
|
|
170
|
+
if addr[0] != "127.0.0.1":
|
|
171
|
+
answer(client, 403, "Forbidden")
|
|
172
|
+
return True
|
|
173
|
+
wanted = unquote(path[len(RULE_CONTROL):].lstrip("/"))
|
|
174
|
+
with LOCK:
|
|
175
|
+
if wanted == "-":
|
|
176
|
+
RULES.clear()
|
|
177
|
+
elif wanted:
|
|
178
|
+
RULES.append(json.loads(wanted))
|
|
179
|
+
shown = json.dumps(RULES, ensure_ascii=False)
|
|
180
|
+
log(f"RULES -> {shown}")
|
|
181
|
+
answer(client, 200, "OK", "", shown)
|
|
182
|
+
return True
|
|
183
|
+
if path.startswith(VERSION_CONTROL):
|
|
184
|
+
# GET /__fault/versionbody/<body>: the version check is answered with that body (200, JSON) instead of the server's.
|
|
185
|
+
# "-" puts the real answer back, "__empty__" is an empty body, no argument reports what is set.
|
|
186
|
+
if addr[0] != "127.0.0.1":
|
|
187
|
+
answer(client, 403, "Forbidden")
|
|
188
|
+
return True
|
|
189
|
+
wanted = unquote(path[len(VERSION_CONTROL):].lstrip("/"))
|
|
190
|
+
if wanted == "-":
|
|
191
|
+
VERSION_BODY = None
|
|
192
|
+
elif wanted == "__empty__":
|
|
193
|
+
VERSION_BODY = ""
|
|
194
|
+
elif wanted:
|
|
195
|
+
VERSION_BODY = wanted
|
|
196
|
+
log(f"VERSION BODY -> {VERSION_BODY!r}")
|
|
197
|
+
answer(client, 200, "OK", "", f"versionbody={VERSION_BODY!r}")
|
|
198
|
+
return True
|
|
199
|
+
if not path.startswith(CONTROL_PREFIX):
|
|
200
|
+
return False
|
|
201
|
+
if addr[0] != "127.0.0.1":
|
|
202
|
+
answer(client, 403, "Forbidden")
|
|
203
|
+
return True
|
|
204
|
+
wanted = path[len(CONTROL_PREFIX):].strip("/")
|
|
205
|
+
if wanted and wanted not in MODES:
|
|
206
|
+
answer(client, 400, "Bad Request", "", f"unknown mode {wanted!r}; use one of {''.join(MODES)}")
|
|
207
|
+
return True
|
|
208
|
+
if wanted:
|
|
209
|
+
set_mode(wanted)
|
|
210
|
+
answer(client, 200, "OK", "", f"mode={MODE}")
|
|
211
|
+
return True
|
|
212
|
+
|
|
213
|
+
|
|
214
|
+
def rule_matches(rule, method, target, lines):
|
|
215
|
+
"""Whether `rule` answers this request (see RULES)."""
|
|
216
|
+
if method.upper() == "CONNECT":
|
|
217
|
+
return "connect" in rule and rule["connect"] in target
|
|
218
|
+
if "connect" in rule:
|
|
219
|
+
return False
|
|
220
|
+
if rule.get("websocket") and not any(l.split(":", 1)[0].strip().lower() == "upgrade"
|
|
221
|
+
and l.split(":", 1)[1].strip().lower() == "websocket" for l in lines[1:] if ":" in l):
|
|
222
|
+
return False
|
|
223
|
+
path = urlsplit(target).path
|
|
224
|
+
return rule.get("match", "") in path and (not rule.get("not_match") or rule["not_match"] not in path)
|
|
225
|
+
|
|
226
|
+
|
|
227
|
+
def drain_body(client, lines, rest):
|
|
228
|
+
"""Reads (and drops) the request body, so the answer is not sent into a half-read request."""
|
|
229
|
+
length = 0
|
|
230
|
+
for l in lines[1:]:
|
|
231
|
+
if l.lower().startswith("content-length:"):
|
|
232
|
+
length = int(l.split(":", 1)[1])
|
|
233
|
+
need = length - len(rest)
|
|
234
|
+
while need > 0:
|
|
235
|
+
chunk = client.recv(min(need, 4096))
|
|
236
|
+
if not chunk:
|
|
237
|
+
break
|
|
238
|
+
need -= len(chunk)
|
|
239
|
+
|
|
240
|
+
|
|
241
|
+
def handle(client, addr):
|
|
242
|
+
try:
|
|
243
|
+
client.settimeout(30)
|
|
244
|
+
lines, rest = read_head(client)
|
|
245
|
+
if not lines:
|
|
246
|
+
return
|
|
247
|
+
method, target, version = (lines[0].split(" ", 2) + ["", ""])[:3]
|
|
248
|
+
# Before the mode is looked at: the way out of `h` or `d` has to work while they are on.
|
|
249
|
+
if method.upper() == "GET" and control(client, addr, target):
|
|
250
|
+
return
|
|
251
|
+
mode = MODE
|
|
252
|
+
label = MODES[mode]
|
|
253
|
+
|
|
254
|
+
if mode == "p" and RULES:
|
|
255
|
+
hit = None
|
|
256
|
+
with LOCK:
|
|
257
|
+
for r in RULES:
|
|
258
|
+
if rule_matches(r, method, target, lines):
|
|
259
|
+
hit = r
|
|
260
|
+
if "times" in r:
|
|
261
|
+
r["times"] -= 1
|
|
262
|
+
if r["times"] <= 0:
|
|
263
|
+
RULES.remove(r)
|
|
264
|
+
break
|
|
265
|
+
if hit:
|
|
266
|
+
drain_body(client, lines, rest)
|
|
267
|
+
log(f"[rule] {method} {target} -> {hit['status']}")
|
|
268
|
+
answer(client, hit["status"], "Rule", "Content-Type: application/json" + chr(13) + chr(10), hit.get("body", ""))
|
|
269
|
+
return
|
|
270
|
+
|
|
271
|
+
if mode == "p" and VERSION_BODY is not None and method.upper() == "POST" and urlsplit(target).path.endswith(VERSION_PATH):
|
|
272
|
+
drain_body(client, lines, rest)
|
|
273
|
+
log(f"[version] {method} {target} -> 200 {VERSION_BODY!r}")
|
|
274
|
+
answer(client, 200, "OK", "Content-Type: application/json" + chr(13) + chr(10), VERSION_BODY)
|
|
275
|
+
return
|
|
276
|
+
|
|
277
|
+
if mode == "d":
|
|
278
|
+
log(f"[{label}] {method} {target}")
|
|
279
|
+
reset(client)
|
|
280
|
+
client = None
|
|
281
|
+
return
|
|
282
|
+
if mode == "h":
|
|
283
|
+
log(f"[{label}] {method} {target}")
|
|
284
|
+
hang(client)
|
|
285
|
+
return
|
|
286
|
+
if mode in CANNED:
|
|
287
|
+
code, reason, extra = CANNED[mode]
|
|
288
|
+
log(f"[{label}] {method} {target} -> {code}")
|
|
289
|
+
answer(client, code, reason, extra)
|
|
290
|
+
return
|
|
291
|
+
|
|
292
|
+
if method.upper() == "CONNECT":
|
|
293
|
+
host, _, port = target.rpartition(":")
|
|
294
|
+
upstream = socket.create_connection((host, int(port or 443)), timeout=CONNECT_TIMEOUT)
|
|
295
|
+
client.sendall(b"HTTP/1.1 200 Connection Established\r\n\r\n")
|
|
296
|
+
log(f"[pass] CONNECT {target}")
|
|
297
|
+
upstream.settimeout(None)
|
|
298
|
+
client.settimeout(None)
|
|
299
|
+
relay(client, upstream)
|
|
300
|
+
upstream.close()
|
|
301
|
+
return
|
|
302
|
+
|
|
303
|
+
url = urlsplit(target)
|
|
304
|
+
host, port = url.hostname, url.port or 80
|
|
305
|
+
path = (url.path or "/") + (f"?{url.query}" if url.query else "")
|
|
306
|
+
upstream = socket.create_connection((host, port), timeout=CONNECT_TIMEOUT)
|
|
307
|
+
# Origin-form request, one exchange per connection: asking upstream to close lets the relay end on its own.
|
|
308
|
+
kept = [l for l in lines[1:] if l.split(":", 1)[0].lower() not in ("proxy-connection", "connection", "proxy-authorization")]
|
|
309
|
+
head = f"{method} {path} {version}\r\n" + "\r\n".join(kept) + "\r\nConnection: close\r\n\r\n"
|
|
310
|
+
upstream.sendall(head.encode("latin-1") + rest)
|
|
311
|
+
log(f"[pass] {method} {target}")
|
|
312
|
+
upstream.settimeout(None)
|
|
313
|
+
client.settimeout(None)
|
|
314
|
+
relay(client, upstream)
|
|
315
|
+
upstream.close()
|
|
316
|
+
except OSError as e:
|
|
317
|
+
log(f"[error] {addr}: {e}")
|
|
318
|
+
finally:
|
|
319
|
+
if client is not None:
|
|
320
|
+
try:
|
|
321
|
+
client.close()
|
|
322
|
+
except OSError:
|
|
323
|
+
pass
|
|
324
|
+
|
|
325
|
+
|
|
326
|
+
def listen(port):
|
|
327
|
+
"""Binds 127.0.0.1:<port> (0 = any free port) and returns the listening socket."""
|
|
328
|
+
server = socket.socket()
|
|
329
|
+
server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
|
|
330
|
+
server.bind(("127.0.0.1", port))
|
|
331
|
+
server.listen(64)
|
|
332
|
+
return server
|
|
333
|
+
|
|
334
|
+
|
|
335
|
+
def serve(server):
|
|
336
|
+
while True:
|
|
337
|
+
client, addr = server.accept()
|
|
338
|
+
threading.Thread(target=handle, args=(client, addr), daemon=True).start()
|
|
339
|
+
|
|
340
|
+
|
|
341
|
+
def set_mode(key):
|
|
342
|
+
global MODE
|
|
343
|
+
if key == "q":
|
|
344
|
+
raise SystemExit(0)
|
|
345
|
+
if key in MODES:
|
|
346
|
+
MODE = key
|
|
347
|
+
log(f"MODE -> {key}: {MODES[key]}")
|
|
348
|
+
if key != "p":
|
|
349
|
+
cut_active()
|
|
350
|
+
|
|
351
|
+
|
|
352
|
+
def keys():
|
|
353
|
+
try:
|
|
354
|
+
import msvcrt
|
|
355
|
+
while True:
|
|
356
|
+
yield msvcrt.getwch()
|
|
357
|
+
except ImportError:
|
|
358
|
+
for line in sys.stdin:
|
|
359
|
+
if line.strip():
|
|
360
|
+
yield line.strip()[0]
|
|
361
|
+
|
|
362
|
+
|
|
363
|
+
def main():
|
|
364
|
+
ap = argparse.ArgumentParser(description=__doc__.split("\n")[0])
|
|
365
|
+
ap.add_argument("--port", type=int, default=8899)
|
|
366
|
+
ap.add_argument("--mode", choices=list(MODES), default="p", help="the mode to start in (default p)")
|
|
367
|
+
args = ap.parse_args()
|
|
368
|
+
server = listen(args.port)
|
|
369
|
+
threading.Thread(target=serve, args=(server,), daemon=True).start()
|
|
370
|
+
log(f"fault_proxy on 127.0.0.1:{args.port} - keys: p pass, 5 503, h hang, d drop, 7 407, r 302, q quit; "
|
|
371
|
+
f"or GET /__fault/mode/<key>")
|
|
372
|
+
set_mode(args.mode)
|
|
373
|
+
try:
|
|
374
|
+
for key in keys():
|
|
375
|
+
set_mode(key)
|
|
376
|
+
except (KeyboardInterrupt, SystemExit):
|
|
377
|
+
pass
|
|
378
|
+
|
|
379
|
+
|
|
380
|
+
if __name__ == "__main__":
|
|
381
|
+
main()
|