qmpass-cli 0.2.0__py3-none-any.whl

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.
qmpass_cli/__init__.py ADDED
@@ -0,0 +1,3 @@
1
+ """Qmpass CLI: run release gate evaluations from a CI/CD pipeline."""
2
+
3
+ __version__ = "0.2.0"
qmpass_cli/agent.py ADDED
@@ -0,0 +1,105 @@
1
+ """The temporary agent container for ``--agent auto`` (CI_GATE_EVALUATION §6).
2
+
3
+ The agent token from the start answer goes to ``docker run`` only through the environment (``-e QMPASS_TOKEN``
4
+ without a value), never on the command line, so it doesn't show in process lists or logs.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import os
10
+ import shutil
11
+ import subprocess
12
+ from collections import deque
13
+ from pathlib import Path
14
+ from typing import List, Optional, Sequence, Tuple
15
+ from urllib.parse import urlsplit, urlunsplit
16
+
17
+ # The released test agent the CLI was tested with (ECR Public, pulled without login). --agent-image overrides it.
18
+ DEFAULT_AGENT_IMAGE = "public.ecr.aws/qmpass/test-agent:1.0.21"
19
+ LOCAL_HOSTS = {"localhost", "127.0.0.1", "::1"}
20
+
21
+
22
+ def image_for(image: Optional[str], variant: Optional[str]) -> str:
23
+ """The image to run: the override as given, else the pinned release (``-rpa`` variant on request)."""
24
+ if image:
25
+ return image
26
+ if variant == "rpa":
27
+ return DEFAULT_AGENT_IMAGE + "-rpa"
28
+ return DEFAULT_AGENT_IMAGE
29
+
30
+
31
+ def docker_problem() -> Optional[str]:
32
+ """Why Docker can't run the agent here, or None when it can."""
33
+ if not shutil.which("docker"):
34
+ return "Docker isn't installed on this runner."
35
+ try:
36
+ done = subprocess.run(
37
+ ["docker", "version", "--format", "{{.Server.Version}}"],
38
+ capture_output=True, text=True, timeout=30,
39
+ )
40
+ except (OSError, subprocess.TimeoutExpired):
41
+ return "Docker didn't answer on this runner."
42
+ if done.returncode != 0:
43
+ return "Docker is installed but its daemon isn't reachable (Bitbucket: add the docker service to the step)."
44
+ return None
45
+
46
+
47
+ def container_url(qmpass_url: str) -> Tuple[str, List[str]]:
48
+ """QMPASS_URL as seen from inside the container: a local stack is reached through host.docker.internal."""
49
+ parts = urlsplit(qmpass_url)
50
+ host = (parts.hostname or "").lower()
51
+ if host not in LOCAL_HOSTS:
52
+ return qmpass_url, []
53
+ netloc = "host.docker.internal" + (f":{parts.port}" if parts.port else "")
54
+ return (urlunsplit((parts.scheme, netloc, parts.path, parts.query, parts.fragment)),
55
+ ["--add-host", "host.docker.internal:host-gateway"])
56
+
57
+
58
+ def run_command(image: str, name: str, extra: Sequence[str] = ()) -> List[str]:
59
+ return ["docker", "run", "--rm", "--pull=missing", "--name", name,
60
+ "-e", "QMPASS_TOKEN", "-e", "QMPASS_URL", *extra, image]
61
+
62
+
63
+ class AgentContainer:
64
+ """One agent container: started with the evaluation's agent token, stopped when the CLI is done."""
65
+
66
+ def __init__(self, image: str, name: str, log_path: Path):
67
+ self.image = image
68
+ self.name = name
69
+ self.log_path = log_path
70
+ self._proc: Optional[subprocess.Popen] = None
71
+ self._log = None
72
+
73
+ def start(self, agent_token: str, qmpass_url: str) -> None:
74
+ url, extra = container_url(qmpass_url)
75
+ env = dict(os.environ)
76
+ env["QMPASS_TOKEN"] = agent_token
77
+ env["QMPASS_URL"] = url
78
+ self._log = open(self.log_path, "w", encoding="utf-8")
79
+ self._proc = subprocess.Popen(
80
+ run_command(self.image, self.name, extra), stdout=self._log, stderr=subprocess.STDOUT, env=env,
81
+ )
82
+
83
+ def exited(self) -> Optional[int]:
84
+ """The container's exit code once it stopped, else None."""
85
+ return self._proc.poll() if self._proc else None
86
+
87
+ def stop(self) -> None:
88
+ if not self._proc:
89
+ return
90
+ if self._proc.poll() is None:
91
+ subprocess.run(["docker", "stop", "-t", "10", self.name], capture_output=True, timeout=60)
92
+ try:
93
+ self._proc.wait(timeout=30)
94
+ except subprocess.TimeoutExpired:
95
+ self._proc.kill()
96
+ if self._log:
97
+ self._log.close()
98
+ self._log = None
99
+
100
+ def log_tail(self, lines: int = 15) -> List[str]:
101
+ try:
102
+ with open(self.log_path, encoding="utf-8", errors="replace") as f:
103
+ return [line.rstrip("\n") for line in deque(f, maxlen=lines)]
104
+ except OSError:
105
+ return []
qmpass_cli/api.py ADDED
@@ -0,0 +1,87 @@
1
+ """Qmpass CI endpoint client (``/api/v1/projects/current/ci/gate-evaluations``, CI_GATE_EVALUATION §4)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import time
6
+ from typing import Any, Callable, Dict, Optional
7
+
8
+ import httpx
9
+
10
+ from . import __version__
11
+
12
+ DEFAULT_URL = "https://api.qmpass.ai"
13
+ # Network errors, rate limits and platform hiccups are retried; a start is safe to retry (Idempotency-Key).
14
+ RETRY_STATUSES = {429, 502, 503, 504}
15
+
16
+
17
+ class ApiError(Exception):
18
+ """Qmpass refused the call (or couldn't be reached). ``code`` is the platform's errorType when it sent one."""
19
+
20
+ def __init__(self, message: str, status: Optional[int] = None, code: Optional[str] = None):
21
+ super().__init__(message)
22
+ self.status = status
23
+ self.code = code
24
+
25
+
26
+ class QmpassApi:
27
+ def __init__(
28
+ self,
29
+ base_url: str,
30
+ token: str,
31
+ *,
32
+ transport: Optional[httpx.BaseTransport] = None,
33
+ retries: int = 4,
34
+ sleep: Callable[[float], None] = time.sleep,
35
+ ):
36
+ self._retries = retries
37
+ self._sleep = sleep
38
+ self._client = httpx.Client(
39
+ base_url=base_url.rstrip("/"),
40
+ headers={"Authorization": f"Bearer {token}", "User-Agent": f"qmpass-cli/{__version__}"},
41
+ timeout=httpx.Timeout(30.0),
42
+ transport=transport,
43
+ )
44
+
45
+ def close(self) -> None:
46
+ self._client.close()
47
+
48
+ def _path(self, suffix: str = "") -> str:
49
+ # `current` = the token's own project (the gateway puts in its id): a token can only reach its project.
50
+ return f"/api/v1/projects/current/ci/gate-evaluations{suffix}"
51
+
52
+ def start(self, idempotency_key: str, body: Dict[str, Any]) -> Dict[str, Any]:
53
+ return self._call("POST", self._path(), json=body, headers={"Idempotency-Key": idempotency_key})
54
+
55
+ def status(self, evaluation: str) -> Dict[str, Any]:
56
+ return self._call("GET", self._path(f"/{evaluation}"))
57
+
58
+ def cancel(self, evaluation: str) -> Dict[str, Any]:
59
+ return self._call("POST", self._path(f"/{evaluation}/cancel"))
60
+
61
+ def _call(self, method: str, path: str, **kwargs: Any) -> Dict[str, Any]:
62
+ attempt = 0
63
+ while True:
64
+ try:
65
+ response = self._client.request(method, path, **kwargs)
66
+ except httpx.HTTPError as e:
67
+ if attempt >= self._retries:
68
+ raise ApiError(f"Couldn't reach Qmpass: {e.__class__.__name__}") from e
69
+ else:
70
+ if response.status_code < 400:
71
+ return response.json() if response.content else {}
72
+ if response.status_code not in RETRY_STATUSES or attempt >= self._retries:
73
+ raise _error(response)
74
+ attempt += 1
75
+ self._sleep(min(2 ** attempt, 20))
76
+
77
+
78
+ def _error(response: httpx.Response) -> ApiError:
79
+ message, code = None, None
80
+ try:
81
+ body = response.json()
82
+ message, code = body.get("message"), body.get("errorType")
83
+ except ValueError:
84
+ pass
85
+ if response.status_code in (401, 403) and not message:
86
+ message = "Qmpass refused the token: check QMPASS_TOKEN (a project API token with write access)."
87
+ return ApiError(message or f"Qmpass answered HTTP {response.status_code}", response.status_code, code)
qmpass_cli/ci_env.py ADDED
@@ -0,0 +1,89 @@
1
+ """What the CI system tells us about this pipeline run (CI_GATE_EVALUATION §8)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ from dataclasses import dataclass
7
+ from typing import Mapping, Optional
8
+
9
+
10
+ @dataclass(frozen=True)
11
+ class CiRun:
12
+ """One pipeline run. ``run_key`` is stable across re-runs of the same run (not per attempt)."""
13
+
14
+ ci: str
15
+ run_key: Optional[str] = None
16
+ pipeline: Optional[str] = None
17
+ number: Optional[str] = None
18
+ commit: Optional[str] = None
19
+ branch: Optional[str] = None
20
+ build_url: Optional[str] = None
21
+
22
+
23
+ def _get(env: Mapping[str, str], name: str) -> Optional[str]:
24
+ value = (env.get(name) or "").strip()
25
+ return value or None
26
+
27
+
28
+ def detect(env: Optional[Mapping[str, str]] = None) -> CiRun:
29
+ """The CI run from well-known environment variables; ``ci="other"`` when none is recognized."""
30
+ e = os.environ if env is None else env
31
+ if _get(e, "GITHUB_ACTIONS"):
32
+ repo, run_id = _get(e, "GITHUB_REPOSITORY"), _get(e, "GITHUB_RUN_ID")
33
+ server = _get(e, "GITHUB_SERVER_URL") or "https://github.com"
34
+ return CiRun(
35
+ ci="github",
36
+ run_key=f"github:{repo}:{run_id}" if run_id else None,
37
+ pipeline=_get(e, "GITHUB_WORKFLOW"),
38
+ number=_get(e, "GITHUB_RUN_NUMBER"),
39
+ commit=_get(e, "GITHUB_SHA"),
40
+ branch=_get(e, "GITHUB_HEAD_REF") or _get(e, "GITHUB_REF_NAME"),
41
+ build_url=f"{server}/{repo}/actions/runs/{run_id}" if repo and run_id else None,
42
+ )
43
+ if _get(e, "BITBUCKET_BUILD_NUMBER"):
44
+ full, number = _get(e, "BITBUCKET_REPO_FULL_NAME"), _get(e, "BITBUCKET_BUILD_NUMBER")
45
+ uuid = _get(e, "BITBUCKET_PIPELINE_UUID")
46
+ return CiRun(
47
+ ci="bitbucket",
48
+ run_key=f"bitbucket:{uuid}" if uuid else f"bitbucket:{full}:{number}",
49
+ pipeline=_get(e, "BITBUCKET_REPO_SLUG"),
50
+ number=number,
51
+ commit=_get(e, "BITBUCKET_COMMIT"),
52
+ branch=_get(e, "BITBUCKET_BRANCH") or _get(e, "BITBUCKET_TAG"),
53
+ build_url=f"https://bitbucket.org/{full}/pipelines/results/{number}" if full else None,
54
+ )
55
+ if _get(e, "GITLAB_CI"):
56
+ pipeline_id = _get(e, "CI_PIPELINE_ID")
57
+ return CiRun(
58
+ ci="gitlab",
59
+ run_key=f"gitlab:{_get(e, 'CI_PROJECT_PATH')}:{pipeline_id}" if pipeline_id else None,
60
+ pipeline=_get(e, "CI_PIPELINE_NAME") or _get(e, "CI_PROJECT_NAME"),
61
+ number=_get(e, "CI_PIPELINE_IID"),
62
+ commit=_get(e, "CI_COMMIT_SHA"),
63
+ branch=_get(e, "CI_COMMIT_REF_NAME"),
64
+ build_url=_get(e, "CI_PIPELINE_URL"),
65
+ )
66
+ if _get(e, "TF_BUILD"):
67
+ build_id = _get(e, "BUILD_BUILDID")
68
+ collection, project = _get(e, "SYSTEM_COLLECTIONURI"), _get(e, "SYSTEM_TEAMPROJECT")
69
+ return CiRun(
70
+ ci="azure",
71
+ run_key=f"azure:{collection}:{build_id}" if build_id else None,
72
+ pipeline=_get(e, "BUILD_DEFINITIONNAME"),
73
+ number=_get(e, "BUILD_BUILDNUMBER"),
74
+ commit=_get(e, "BUILD_SOURCEVERSION"),
75
+ branch=_get(e, "BUILD_SOURCEBRANCHNAME"),
76
+ build_url=(f"{collection}{project}/_build/results?buildId={build_id}"
77
+ if collection and project and build_id else None),
78
+ )
79
+ if _get(e, "JENKINS_URL") or _get(e, "BUILD_TAG"):
80
+ return CiRun(
81
+ ci="jenkins",
82
+ run_key=f"jenkins:{_get(e, 'BUILD_TAG')}" if _get(e, "BUILD_TAG") else None,
83
+ pipeline=_get(e, "JOB_NAME"),
84
+ number=_get(e, "BUILD_NUMBER"),
85
+ commit=_get(e, "GIT_COMMIT"),
86
+ branch=_get(e, "BRANCH_NAME") or _get(e, "GIT_BRANCH"),
87
+ build_url=_get(e, "BUILD_URL"),
88
+ )
89
+ return CiRun(ci="other")
qmpass_cli/evaluate.py ADDED
@@ -0,0 +1,221 @@
1
+ """``qmpass-cli gate evaluate``: start a gate evaluation, run the temporary agent, follow it, report."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import os
7
+ import time
8
+ import uuid
9
+ from dataclasses import dataclass, field
10
+ from pathlib import Path
11
+ from typing import Any, Callable, Dict, Optional, TextIO
12
+
13
+ from . import agent as agent_mod
14
+ from . import report
15
+ from .api import ApiError, QmpassApi
16
+ from .ci_env import CiRun
17
+
18
+ POLL_SECONDS = 15
19
+ MAX_STATUS_FAILURES = 8
20
+
21
+
22
+ class Interrupted(Exception):
23
+ """The pipeline cancelled the job (SIGTERM / SIGINT)."""
24
+
25
+
26
+ @dataclass
27
+ class Options:
28
+ url: str
29
+ gate: Optional[str] = None
30
+ release: Optional[str] = None
31
+ stage: Optional[str] = None
32
+ agent: str = "auto"
33
+ name: Optional[str] = None
34
+ pipeline_name: Optional[str] = None
35
+ build_number: Optional[str] = None
36
+ version: Optional[str] = None
37
+ commit: Optional[str] = None
38
+ branch: Optional[str] = None
39
+ build_url: Optional[str] = None
40
+ idempotency_key: Optional[str] = None
41
+ wait: bool = True
42
+ timeout_seconds: int = 45 * 60
43
+ agent_image: Optional[str] = None
44
+ agent_variant: Optional[str] = None
45
+ json_file: Optional[str] = "qmpass-evaluation.json"
46
+ env: Dict[str, str] = field(default_factory=lambda: dict(os.environ))
47
+
48
+ @property
49
+ def temporary_agent(self) -> bool:
50
+ return self.agent.strip().lower() in ("", "auto")
51
+
52
+
53
+ def request_body(opts: Options, ci: CiRun) -> Dict[str, Any]:
54
+ build = {
55
+ "pipeline": opts.pipeline_name or ci.pipeline,
56
+ "number": opts.build_number or ci.number,
57
+ "version": opts.version,
58
+ "commitSha": opts.commit or ci.commit,
59
+ "branch": opts.branch or ci.branch,
60
+ "buildUrl": opts.build_url or ci.build_url,
61
+ "ci": ci.ci,
62
+ }
63
+ body: Dict[str, Any] = {
64
+ "gate": opts.gate,
65
+ "release": opts.release,
66
+ "stage": opts.stage,
67
+ "agent": "auto" if opts.temporary_agent else opts.agent.strip(),
68
+ "name": opts.name,
69
+ "build": {k: v for k, v in build.items() if v},
70
+ }
71
+ return {k: v for k, v in body.items() if v}
72
+
73
+
74
+ def run(
75
+ opts: Options,
76
+ api: QmpassApi,
77
+ ci: CiRun,
78
+ out: TextIO,
79
+ *,
80
+ sleep: Callable[[float], None] = time.sleep,
81
+ clock: Callable[[], float] = time.monotonic,
82
+ docker_problem: Callable[[], Optional[str]] = agent_mod.docker_problem,
83
+ container_factory: Callable[..., Any] = agent_mod.AgentContainer,
84
+ ) -> int:
85
+ def say(line: str) -> None:
86
+ print(line, file=out, flush=True)
87
+
88
+ if not opts.gate and not (opts.release and opts.stage):
89
+ say("Name the gate: --gate PGT-… , or --release <release id> --stage PST-…")
90
+ return report.EXIT_SETUP
91
+ if opts.temporary_agent:
92
+ if not opts.wait:
93
+ say("--no-wait needs a named agent (--agent <name>): the temporary agent lives only while the CLI runs.")
94
+ return report.EXIT_SETUP
95
+ problem = docker_problem()
96
+ if problem:
97
+ say(f"{problem} --agent auto runs the agent in Docker; use --agent <name> for an agent your team runs.")
98
+ return report.EXIT_SETUP
99
+
100
+ key = opts.idempotency_key or ci.run_key
101
+ if not key:
102
+ key = f"local:{uuid.uuid4()}"
103
+ say("Not in a known CI system: this call starts a new evaluation (pass --idempotency-key to retry safely).")
104
+
105
+ try:
106
+ status = api.start(key, request_body(opts, ci))
107
+ except ApiError as e:
108
+ say(f"Qmpass refused to start the evaluation: {e}")
109
+ return report.EXIT_SETUP
110
+
111
+ evaluation = status.get("evaluation")
112
+ say(f"Evaluating {status.get('stageName') or status.get('stage')} gate {status.get('gate')}"
113
+ f" (release {status.get('release')}): {evaluation} “{status.get('name')}”")
114
+ if status.get("evaluationUrl"):
115
+ say(f"Open in Qmpass: {status['evaluationUrl']}")
116
+
117
+ container = None
118
+ try:
119
+ agent_token = (status.get("agent") or {}).get("token")
120
+ if agent_token:
121
+ if opts.env.get("GITHUB_ACTIONS"):
122
+ say(f"::add-mask::{agent_token}")
123
+ image = agent_mod.image_for(opts.agent_image, opts.agent_variant)
124
+ container = container_factory(image, f"qmpass-agent-{evaluation}".lower(), Path("qmpass-agent.log"))
125
+ container.start(agent_token, opts.url)
126
+ say(f"Started the temporary agent ({image}); its log: qmpass-agent.log")
127
+
128
+ if not opts.wait:
129
+ _write_outputs(opts, status, say)
130
+ say(f"Not waiting (--no-wait): {report.progress_line(status)}")
131
+ return report.EXIT_PASSED
132
+
133
+ status = _follow(opts, api, status, container, say, sleep, clock)
134
+ except Interrupted:
135
+ say("The pipeline stopped the job: cancelling the evaluation.")
136
+ status = _cancel(api, evaluation, say) or status
137
+ _write_outputs(opts, status, say)
138
+ return report.EXIT_SETUP
139
+ except _GiveUp as e:
140
+ say(str(e))
141
+ if e.tail:
142
+ say("Last lines of the agent log:")
143
+ for line in e.tail:
144
+ say(f" {line}")
145
+ status = _cancel(api, evaluation, say) or status
146
+ _write_outputs(opts, status, say)
147
+ return report.EXIT_SETUP
148
+ finally:
149
+ if container is not None:
150
+ container.stop()
151
+
152
+ _write_outputs(opts, status, say)
153
+ say("")
154
+ say(report.summary_text(status))
155
+ return report.exit_code(status)
156
+
157
+
158
+ class _GiveUp(Exception):
159
+ def __init__(self, message: str, tail=None):
160
+ super().__init__(message)
161
+ self.tail = tail or []
162
+
163
+
164
+ def _follow(opts, api, status, container, say, sleep, clock) -> Dict[str, Any]:
165
+ deadline = clock() + opts.timeout_seconds
166
+ last_line = report.progress_line(status)
167
+ say(last_line)
168
+ failures = 0
169
+ while status.get("state") not in report.FINAL_STATES:
170
+ if clock() >= deadline:
171
+ raise _GiveUp(f"Timed out after {opts.timeout_seconds // 60} min (--timeout).")
172
+ sleep(POLL_SECONDS)
173
+ exited = container.exited() if container is not None else None
174
+ try:
175
+ status = api.status(status.get("evaluation"))
176
+ failures = 0
177
+ except ApiError as e:
178
+ failures += 1
179
+ if failures >= MAX_STATUS_FAILURES:
180
+ raise _GiveUp(f"Lost contact with Qmpass: {e}")
181
+ continue
182
+ if exited is not None and status.get("state") not in report.FINAL_STATES:
183
+ # The agent stopped before the automated checks finished (bad image, refused, crashed).
184
+ raise _GiveUp(f"The agent container stopped (exit code {exited}) before the checks finished.",
185
+ container.log_tail())
186
+ line = report.progress_line(status)
187
+ if line != last_line:
188
+ say(line)
189
+ last_line = line
190
+ return status
191
+
192
+
193
+ def _cancel(api: QmpassApi, evaluation: Optional[str], say) -> Optional[Dict[str, Any]]:
194
+ if not evaluation:
195
+ return None
196
+ try:
197
+ return api.cancel(evaluation)
198
+ except ApiError as e:
199
+ say(f"Couldn't cancel {evaluation}: {e}")
200
+ return None
201
+
202
+
203
+ def _write_outputs(opts: Options, status: Dict[str, Any], say) -> None:
204
+ safe = {k: v for k, v in status.items() if k != "agent"}
205
+ agent = status.get("agent")
206
+ if agent:
207
+ safe["agent"] = {k: v for k, v in agent.items() if k != "token"} # never write the agent token
208
+ if opts.json_file:
209
+ try:
210
+ Path(opts.json_file).write_text(json.dumps(safe, indent=2) + "\n", encoding="utf-8")
211
+ except OSError as e:
212
+ say(f"Couldn't write {opts.json_file}: {e}")
213
+ summary_path = opts.env.get("GITHUB_STEP_SUMMARY")
214
+ if summary_path and status.get("state") in report.FINAL_STATES:
215
+ with open(summary_path, "a", encoding="utf-8") as f:
216
+ f.write(report.step_summary_markdown(status))
217
+ output_path = opts.env.get("GITHUB_OUTPUT")
218
+ if output_path:
219
+ with open(output_path, "a", encoding="utf-8") as f:
220
+ for key, value in report.github_outputs(status).items():
221
+ f.write(f"{key}={value}\n")
qmpass_cli/main.py ADDED
@@ -0,0 +1,106 @@
1
+ """``qmpass-cli`` entry point."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import os
7
+ import re
8
+ import signal
9
+ import sys
10
+ from typing import List, Optional
11
+
12
+ from . import __version__
13
+ from .api import DEFAULT_URL, QmpassApi
14
+ from .ci_env import detect
15
+ from .evaluate import Interrupted, Options, run
16
+ from .report import EXIT_SETUP
17
+
18
+
19
+ def parse_duration(value: str) -> int:
20
+ """``45m``, ``1h30m``, ``90s`` or plain seconds → seconds."""
21
+ text = value.strip().lower()
22
+ if text.isdigit():
23
+ return int(text)
24
+ match = re.fullmatch(r"(?:(\d+)h)?(?:(\d+)m)?(?:(\d+)s)?", text)
25
+ if not match or not any(match.groups()):
26
+ raise argparse.ArgumentTypeError(f"not a duration: {value!r} (e.g. 45m, 1h30m)")
27
+ h, m, s = (int(g) if g else 0 for g in match.groups())
28
+ return h * 3600 + m * 60 + s
29
+
30
+
31
+ def build_parser() -> argparse.ArgumentParser:
32
+ parser = argparse.ArgumentParser(
33
+ prog="qmpass-cli",
34
+ description="Run Qmpass release gate evaluations from your pipeline.",
35
+ )
36
+ parser.add_argument("--version", action="version", version=f"qmpass-cli {__version__}")
37
+ commands = parser.add_subparsers(dest="command", required=True)
38
+ gate = commands.add_parser("gate", help="Release gates").add_subparsers(dest="gate_command", required=True)
39
+ ev = gate.add_parser(
40
+ "evaluate",
41
+ help="Start a gate evaluation, run its automated checks, and exit with their result.",
42
+ description=(
43
+ "Starts an evaluation of the gate on the stage's App Address and runs its automated checks. "
44
+ "Exit codes: 0 automated checks passed (manual checks may still be open in Qmpass), "
45
+ "1 an automated check failed or couldn't run, 3 setup or infrastructure problem."
46
+ ),
47
+ )
48
+ where = ev.add_argument_group("which gate")
49
+ where.add_argument("--gate", help="Gate ref, e.g. PGT-0007")
50
+ where.add_argument("--release", help="Release id (with --stage), e.g. 10023")
51
+ where.add_argument("--stage", help="Stage ref (with --release), e.g. PST-02")
52
+ run_group = ev.add_argument_group("how it runs")
53
+ run_group.add_argument("--agent", default="auto",
54
+ help="auto (default): a temporary agent in Docker on this runner; or the name/id of an agent your team runs")
55
+ run_group.add_argument("--agent-image", default=os.environ.get("QMPASS_AGENT_IMAGE"),
56
+ help="Agent image for --agent auto (default: the release this CLI was tested with; env QMPASS_AGENT_IMAGE)")
57
+ run_group.add_argument("--agent-variant", choices=["rpa"],
58
+ help="Use the agent image with the RPA framework (Salesforce, Excel, PDF, Email, …)")
59
+ run_group.add_argument("--timeout", type=parse_duration, default=parse_duration("45m"),
60
+ help="Stop waiting after this long (default 45m); the evaluation is then cancelled")
61
+ run_group.add_argument("--no-wait", dest="wait", action="store_false",
62
+ help="Start and exit 0 (named agents only); follow it in Qmpass")
63
+ build = ev.add_argument_group("build details (default: from the CI environment)")
64
+ build.add_argument("--name", help="Evaluation name (default: '<pipeline> #<build number>')")
65
+ build.add_argument("--pipeline-name")
66
+ build.add_argument("--build-number")
67
+ build.add_argument("--build-version", dest="build_version", help="The version being tested, e.g. 2.4.0-rc.3")
68
+ build.add_argument("--commit")
69
+ build.add_argument("--branch")
70
+ build.add_argument("--build-url", help="Link to this pipeline run (https)")
71
+ build.add_argument("--idempotency-key", help="Same key = same evaluation (default: the CI run id)")
72
+ conn = ev.add_argument_group("connection (default: environment)")
73
+ conn.add_argument("--url", default=os.environ.get("QMPASS_URL") or DEFAULT_URL, help="Qmpass API (env QMPASS_URL)")
74
+ ev.add_argument("--json-file", default="qmpass-evaluation.json", help="Where to write the final status ('' for none)")
75
+ return parser
76
+
77
+
78
+ def _on_signal(signum, frame): # pragma: no cover - exercised by the pipeline
79
+ raise Interrupted()
80
+
81
+
82
+ def main(argv: Optional[List[str]] = None) -> int:
83
+ args = build_parser().parse_args(argv)
84
+ token = (os.environ.get("QMPASS_TOKEN") or "").strip()
85
+ if not token:
86
+ print("Set QMPASS_TOKEN to a project API token (Project settings → API tokens).", file=sys.stderr)
87
+ return EXIT_SETUP
88
+
89
+ opts = Options(
90
+ url=args.url, gate=args.gate, release=args.release, stage=args.stage,
91
+ agent=args.agent, name=args.name, pipeline_name=args.pipeline_name, build_number=args.build_number,
92
+ version=args.build_version, commit=args.commit, branch=args.branch, build_url=args.build_url,
93
+ idempotency_key=args.idempotency_key, wait=args.wait, timeout_seconds=args.timeout,
94
+ agent_image=args.agent_image, agent_variant=args.agent_variant, json_file=args.json_file or None,
95
+ )
96
+ signal.signal(signal.SIGTERM, _on_signal)
97
+ signal.signal(signal.SIGINT, _on_signal)
98
+ api = QmpassApi(opts.url, token)
99
+ try:
100
+ return run(opts, api, detect(), sys.stdout)
101
+ finally:
102
+ api.close()
103
+
104
+
105
+ if __name__ == "__main__": # pragma: no cover
106
+ sys.exit(main())
qmpass_cli/report.py ADDED
@@ -0,0 +1,110 @@
1
+ """What the CLI prints and writes about an evaluation, and its exit code (CI_GATE_EVALUATION §8)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any, Dict, List, Optional
6
+
7
+ EXIT_PASSED = 0 # the automated checks passed (manual checks may still be open in Qmpass)
8
+ EXIT_FAILED = 1 # an automated check failed, was blocked or couldn't run
9
+ EXIT_SETUP = 3 # setup or infrastructure: token, gate, agent, Docker, timeout, abandoned
10
+
11
+ # The pipeline stops following the evaluation here; it never waits for manual checks.
12
+ FINAL_STATES = {"done", "waiting_for_manual", "abandoned", "error"}
13
+
14
+
15
+ def exit_code(status: Dict[str, Any]) -> int:
16
+ state = status.get("state")
17
+ if state in ("abandoned", "error"):
18
+ return EXIT_SETUP
19
+ return EXIT_PASSED if status.get("automatedOutcome") == "passed" else EXIT_FAILED
20
+
21
+
22
+ def progress_line(status: Dict[str, Any]) -> str:
23
+ a = status.get("automated") or {}
24
+ parts = [f"{n} {label}" for n, label in (
25
+ (a.get("passed", 0), "passed"), (a.get("failed", 0), "failed"), (a.get("blocked", 0), "blocked"),
26
+ (a.get("running", 0), "running"), (a.get("notRun", 0), "not run"),
27
+ ) if n]
28
+ state = (status.get("state") or "").replace("_", " ")
29
+ return f"{status.get('evaluation')} {state}" + (f" · {' · '.join(parts)}" if parts else "")
30
+
31
+
32
+ def _verdict(status: Dict[str, Any]) -> str:
33
+ state = status.get("state")
34
+ if state == "error":
35
+ error = status.get("error") or {}
36
+ return f"Couldn't finish: {error.get('message') or error.get('code') or 'unknown error'}"
37
+ if state == "abandoned":
38
+ return "The evaluation was abandoned."
39
+ if status.get("automatedOutcome") == "passed":
40
+ return "Automated checks passed."
41
+ return "Automated checks failed."
42
+
43
+
44
+ def _manual_note(status: Dict[str, Any]) -> Optional[str]:
45
+ open_ = (status.get("manual") or {}).get("open", 0)
46
+ if status.get("state") == "waiting_for_manual" and open_:
47
+ return f"{open_} manual check{'s' if open_ != 1 else ''} left for testers — the evaluation stays open in Qmpass."
48
+ return None
49
+
50
+
51
+ def _failed_lines(status: Dict[str, Any]) -> List[str]:
52
+ lines = []
53
+ for f in status.get("failed") or []:
54
+ where = " · ".join(x for x in (f.get("milestone"), f.get("checkpoint"), f.get("target")) if x)
55
+ line = f"{(f.get('status') or 'fail').upper()} {where}"
56
+ if f.get("message"):
57
+ line += f" — {f['message']}"
58
+ if f.get("sessionUrl"):
59
+ line += f" ({f['sessionUrl']})"
60
+ lines.append(line)
61
+ return lines
62
+
63
+
64
+ def summary_text(status: Dict[str, Any]) -> str:
65
+ name = status.get("name") or ""
66
+ lines = [f"{status.get('evaluation')} {name} — {status.get('stageName') or status.get('stage') or ''} gate"
67
+ f" ({status.get('gate')})".replace(" ", " "), _verdict(status)]
68
+ lines += [f" {line}" for line in _failed_lines(status)]
69
+ note = _manual_note(status)
70
+ if note:
71
+ lines.append(note)
72
+ if status.get("evaluationUrl"):
73
+ lines.append(f"Open in Qmpass: {status['evaluationUrl']}")
74
+ return "\n".join(lines)
75
+
76
+
77
+ def step_summary_markdown(status: Dict[str, Any]) -> str:
78
+ """GitHub job summary ($GITHUB_STEP_SUMMARY)."""
79
+ a = status.get("automated") or {}
80
+ ref = status.get("evaluation")
81
+ title = f"[{ref}]({status['evaluationUrl']})" if status.get("evaluationUrl") else ref
82
+ md = [
83
+ f"### Qmpass gate evaluation {title}",
84
+ f"**{status.get('name') or ''}** · {status.get('stageName') or status.get('stage') or ''} gate"
85
+ f" `{status.get('gate')}` · release `{status.get('release')}`",
86
+ "",
87
+ _verdict(status),
88
+ "",
89
+ "| Passed | Failed | Blocked | Not run | Manual open |",
90
+ "|---|---|---|---|---|",
91
+ f"| {a.get('passed', 0)} | {a.get('failed', 0)} | {a.get('blocked', 0)} | {a.get('notRun', 0)}"
92
+ f" | {(status.get('manual') or {}).get('open', 0)} |",
93
+ ]
94
+ failed = _failed_lines(status)
95
+ if failed:
96
+ md += ["", "**Failed checks**", *[f"- {line}" for line in failed]]
97
+ note = _manual_note(status)
98
+ if note:
99
+ md += ["", note]
100
+ return "\n".join(md) + "\n"
101
+
102
+
103
+ def github_outputs(status: Dict[str, Any]) -> Dict[str, str]:
104
+ """Step outputs for the GitHub Action ($GITHUB_OUTPUT)."""
105
+ return {
106
+ "evaluation": status.get("evaluation") or "",
107
+ "state": status.get("state") or "",
108
+ "outcome": status.get("automatedOutcome") or "",
109
+ "url": status.get("evaluationUrl") or "",
110
+ }
@@ -0,0 +1,191 @@
1
+ Metadata-Version: 2.4
2
+ Name: qmpass-cli
3
+ Version: 0.2.0
4
+ Summary: Run Qmpass release gate evaluations from your CI/CD pipeline.
5
+ Author: Qmpass
6
+ License-Expression: LicenseRef-Proprietary
7
+ Requires-Python: >=3.10
8
+ Description-Content-Type: text/markdown
9
+ License-File: LICENSE
10
+ Requires-Dist: httpx==0.28.1
11
+ Provides-Extra: dev
12
+ Requires-Dist: pytest>=7.0.0; extra == "dev"
13
+ Requires-Dist: ruff>=0.6.0; extra == "dev"
14
+ Dynamic: license-file
15
+
16
+ # Qmpass CLI
17
+
18
+ Run a [Qmpass](https://qmpass.ai) release gate evaluation from your CI/CD pipeline. The pipeline
19
+ deploys a release candidate, `qmpass-cli` evaluates the stage's gate, and the job passes or fails on
20
+ the gate's automated checks. Manual checks stay open in Qmpass for your testers — the pipeline never
21
+ waits for them.
22
+
23
+ ## Requirements
24
+
25
+ - Python 3.10 or newer
26
+ - A project API token with **write** access: **Project settings → API tokens** (Pro plan and up)
27
+ - For `--agent auto` (the default): Docker on the runner. Otherwise, an agent your team runs (see "Which agent runs the checks"
28
+ below).
29
+
30
+ ## Install
31
+
32
+ ```bash
33
+ pipx install qmpass-cli
34
+ ```
35
+
36
+ Use pipx (or `pipx run`) so the CLI gets its own environment and never clashes with your job's
37
+ packages. Pin the version in pipelines (`qmpass-cli==0.2.0`) to upgrade on your schedule.
38
+
39
+ ## Run
40
+
41
+ ```bash
42
+ export QMPASS_TOKEN=qmp_proj_… # keep it in your CI secrets
43
+ qmpass-cli gate evaluate --release 10023 --stage PST-02
44
+ ```
45
+
46
+ Name the gate by its ref (`--gate PGT-0007`, shown at the end of the gate page's breadcrumb) or by
47
+ release id + stage ref (`--release 10023 --stage PST-02`, stage refs are in Project settings →
48
+ Release stages). The evaluation tests the stage's **App Address**.
49
+
50
+ | Option | Default | |
51
+ |---|---|---|
52
+ | `--agent` | `auto` | `auto` starts a temporary agent in Docker on the runner and removes it afterwards. Or the name of an agent your team runs (it must be online). |
53
+ | `--timeout` | `45m` | Stop waiting and cancel the evaluation. |
54
+ | `--no-wait` | | Start and exit 0 (named agents only). |
55
+ | `--name` | `<pipeline> #<build number>` | Evaluation name in Qmpass. |
56
+ | `--build-version`, `--commit`, `--branch`, `--build-url` | from the CI environment | Shown on the Evaluation page. |
57
+ | `--idempotency-key` | the CI run id | Same key = same evaluation, so a re-run of the job doesn't start a second one. |
58
+ | `--agent-image` | the release this CLI was tested with | Another agent image (env `QMPASS_AGENT_IMAGE`). |
59
+ | `--agent-variant rpa` | | The agent image with the RPA framework (Salesforce, Excel, PDF, Email, …). |
60
+
61
+ `QMPASS_URL` defaults to `https://api.qmpass.ai`.
62
+
63
+ ## Which agent runs the checks
64
+
65
+ The CLI only needs the **project API token** (`QMPASS_TOKEN`). It never needs an agent token.
66
+
67
+ **`--agent auto` (default) — a temporary agent on the runner**
68
+
69
+ ```bash
70
+ qmpass-cli gate evaluate --release 10023 --stage PST-02
71
+ ```
72
+
73
+ 1. The CLI starts the evaluation; Qmpass creates a temporary agent for this evaluation only.
74
+ 2. The CLI runs the Qmpass test agent image with `docker run` on the runner.
75
+ 3. The agent connects to Qmpass, runs the gate's automated checks and reports the results.
76
+ 4. When the checks are done, Qmpass removes the agent and its token, and the container stops.
77
+
78
+ Needs Docker on the runner. The agent runs on the runner, so it reaches whatever the runner reaches —
79
+ preview deploys, or internal URLs on self-hosted runners. Use `--agent-variant rpa` when the gate's
80
+ runbooks use the RPA framework.
81
+
82
+ **`--agent "<name>"` — an agent your team runs**
83
+
84
+ ```bash
85
+ qmpass-cli gate evaluate --release 10023 --stage PST-02 --agent "QA runner"
86
+ ```
87
+
88
+ The checks run on an agent you installed and connected beforehand (`pipx install qmpass-test-agent`,
89
+ then `qmpass-agent run` with that agent's own token from **Project settings → Agents**). It must be
90
+ online when the evaluation starts, otherwise the CLI stops with exit code 3. Use it when:
91
+
92
+ - the runner has no Docker;
93
+ - the app under test is reachable only from a particular machine (private network, VPN);
94
+ - the checks need a desktop or Windows machine.
95
+
96
+ With a named agent, `--no-wait` starts the evaluation and exits straight away; follow it in Qmpass.
97
+
98
+ Either way the CLI waits only for the automated checks — manual checks stay open in Qmpass for your
99
+ testers.
100
+
101
+ Build details are read from GitHub Actions, Bitbucket Pipelines, GitLab CI, Jenkins and Azure
102
+ Pipelines.
103
+
104
+ ### Exit codes
105
+
106
+ | Code | Meaning |
107
+ |---|---|
108
+ | `0` | The automated checks passed. Manual checks may still be open in Qmpass. |
109
+ | `1` | An automated check failed, was blocked or couldn't run. |
110
+ | `3` | Setup or infrastructure: token, gate not found, agent offline or not started, Docker missing, timeout, evaluation abandoned. |
111
+
112
+ Qmpass is an advisory gate: if you don't want a failed check to fail the job, allow the step to fail
113
+ (`continue-on-error` / `allow_failure`).
114
+
115
+ The CLI prints progress and a summary with the failed checks and a link to the evaluation, and writes
116
+ `qmpass-evaluation.json`. On GitHub Actions it also writes the job summary and the step outputs
117
+ `evaluation`, `state`, `outcome` and `url`.
118
+
119
+ ## In your pipeline
120
+
121
+ Two commands in any CI: install the CLI, then evaluate. Keep `QMPASS_TOKEN` in your CI's secrets — the token
122
+ belongs to one project, so nothing else is needed. `--agent auto` (the default) needs Docker on the runner.
123
+
124
+ GitHub Actions (`ubuntu-*` runners have pipx and Docker):
125
+
126
+ ```yaml
127
+ - name: Qmpass gate
128
+ run: |
129
+ pipx install qmpass-cli==0.2.0
130
+ qmpass-cli gate evaluate --release 10023 --stage PST-02 --build-version "${{ github.ref_name }}"
131
+ env:
132
+ QMPASS_TOKEN: ${{ secrets.QMPASS_TOKEN }}
133
+ ```
134
+
135
+ On GitHub the CLI also writes the job summary and the step outputs `evaluation`, `state`, `outcome`, `url`.
136
+
137
+ Bitbucket Pipelines (secured repository variable `QMPASS_TOKEN`; the `docker` service runs the temporary agent):
138
+
139
+ ```yaml
140
+ - step:
141
+ name: Qmpass gate
142
+ image: python:3.12
143
+ services: [docker]
144
+ script:
145
+ - python3 -m pip install pipx
146
+ - python3 -m pipx run --spec qmpass-cli==0.2.0 qmpass-cli gate evaluate --release 10023 --stage PST-02
147
+ ```
148
+
149
+ GitLab CI (masked CI/CD variable `QMPASS_TOKEN`; Docker-in-Docker for the agent):
150
+
151
+ ```yaml
152
+ qmpass-gate:
153
+ image: python:3.12
154
+ services: [docker:dind]
155
+ variables: { DOCKER_HOST: "tcp://docker:2375" }
156
+ script:
157
+ - python3 -m pip install pipx
158
+ - python3 -m pipx run --spec qmpass-cli==0.2.0 qmpass-cli gate evaluate --release 10023 --stage PST-02
159
+ ```
160
+
161
+ Azure DevOps (secret variable `QMPASS_TOKEN` — secrets must be mapped into `env`; Microsoft-hosted
162
+ `ubuntu-latest` has pipx and Docker):
163
+
164
+ ```yaml
165
+ - script: |
166
+ pipx install qmpass-cli==0.2.0
167
+ qmpass-cli gate evaluate --release 10023 --stage PST-02
168
+ displayName: Qmpass gate
169
+ env:
170
+ QMPASS_TOKEN: $(QMPASS_TOKEN)
171
+ ```
172
+
173
+ Jenkins (declarative; a secret-text credential `qmpass-token`; the agent needs Python 3.10+, pipx and Docker):
174
+
175
+ ```groovy
176
+ stage('Qmpass gate') {
177
+ environment {
178
+ QMPASS_TOKEN = credentials('qmpass-token')
179
+ }
180
+ steps {
181
+ sh 'pipx install qmpass-cli==0.2.0'
182
+ sh 'qmpass-cli gate evaluate --release 10023 --stage PST-02'
183
+ }
184
+ }
185
+ ```
186
+
187
+ No Docker on the runner? Run the Qmpass agent on a machine your team controls and add `--agent <name>`.
188
+
189
+ The temporary agent runs on your runner, so it reaches whatever the runner reaches (preview
190
+ deploys, internal URLs on self-hosted runners). Its token is issued for this evaluation only and
191
+ is removed when the evaluation is done with it.
@@ -0,0 +1,13 @@
1
+ qmpass_cli/__init__.py,sha256=lIzOz67p5xwCG9UwlDMoyBblv4th9rX0Ix1USRQowHc,93
2
+ qmpass_cli/agent.py,sha256=iuGTOqS7BbtxNmfcaf8YeOkQWjE_zNVYvJ3Mk_h2Hwk,4129
3
+ qmpass_cli/api.py,sha256=ARgbtwJ42HcE7K-PhMZZxRU3M8Dq2YhtV3ULV2VkUOA,3288
4
+ qmpass_cli/ci_env.py,sha256=Pp5xRaq4H5iFbM1DuWc6aEG9fDQ8lqgN39Q-Nx_3Dn0,3782
5
+ qmpass_cli/evaluate.py,sha256=TFe7vWcLhchTV5v7PT1zbNfwOcvDhdV563blkPmF8kA,8051
6
+ qmpass_cli/main.py,sha256=o17YGihNZ44cb8udMHY3bLYiFrrVU7seyPd14uapadQ,5253
7
+ qmpass_cli/report.py,sha256=SzzNttUoeC3fp5g1SER3EXvIP6UHetiRRM7k-VE-alg,4511
8
+ qmpass_cli-0.2.0.dist-info/licenses/LICENSE,sha256=rmfgLGbjONRIAOUhbXzP6awS4EQxhvXVt2eMgwrO3x0,242
9
+ qmpass_cli-0.2.0.dist-info/METADATA,sha256=1wqAcnP7Dwkg6Jlk3C7jzAhBK0r_WXN426IT1DwvZ1M,7447
10
+ qmpass_cli-0.2.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
11
+ qmpass_cli-0.2.0.dist-info/entry_points.txt,sha256=Neg-Iro1xaN2oA__t1RSN2vxQN7Ou_CFBGrrIVSWqPY,52
12
+ qmpass_cli-0.2.0.dist-info/top_level.txt,sha256=PzTuTKfArN16IFUP3vjmRatWGytBGLOMGcKpwnnm2vQ,11
13
+ qmpass_cli-0.2.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ qmpass-cli = qmpass_cli.main:main
@@ -0,0 +1,5 @@
1
+ Qmpass Test CLI
2
+ Copyright (c) 2026 Qmpass. All rights reserved.
3
+
4
+ This software is proprietary. It is made available solely for use with a Qmpass subscription, to
5
+ start and follow Qmpass release gate evaluations from your own CI/CD pipelines.
@@ -0,0 +1 @@
1
+ qmpass_cli