tenantguard-cli 0.1.1__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.
@@ -0,0 +1,13 @@
1
+ __pycache__/
2
+ *.py[cod]
3
+ *.egg-info/
4
+ .eggs/
5
+ .venv/
6
+ venv/
7
+ build/
8
+ dist/
9
+ .pytest_cache/
10
+ .coverage
11
+ htmlcov/
12
+ .mypy_cache/
13
+ .ruff_cache/
@@ -0,0 +1,190 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the
44
+ purposes of this License, Derivative Works shall not include works
45
+ that remain separable from, or merely link (or bind by name) to the
46
+ interfaces of, the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including the
49
+ original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing
141
+ the origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ Copyright 2026 Rudrendu Paul
179
+
180
+ Licensed under the Apache License, Version 2.0 (the "License");
181
+ you may not use this file except in compliance with the License.
182
+ You may obtain a copy of the License at
183
+
184
+ http://www.apache.org/licenses/LICENSE-2.0
185
+
186
+ Unless required by applicable law or agreed to in writing, software
187
+ distributed under the License is distributed on an "AS IS" BASIS,
188
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
189
+ See the License for the specific language governing permissions and
190
+ limitations under the License.
@@ -0,0 +1,86 @@
1
+ Metadata-Version: 2.4
2
+ Name: tenantguard-cli
3
+ Version: 0.1.1
4
+ Summary: PyPI wrapper for TenantGuard, a tenant-isolation security-audit CLI for self-hosted multi-tenant AI-agent platforms. Downloads and runs the official prebuilt Go binary from GitHub Releases.
5
+ Project-URL: Homepage, https://github.com/RudrenduPaul/TenantGuard
6
+ Project-URL: Repository, https://github.com/RudrenduPaul/TenantGuard
7
+ Project-URL: Bug Tracker, https://github.com/RudrenduPaul/TenantGuard/issues
8
+ Project-URL: Changelog, https://github.com/RudrenduPaul/TenantGuard/blob/main/CHANGELOG.md
9
+ Project-URL: Author - Rudrendu Paul, https://github.com/RudrenduPaul
10
+ Author: Rudrendu Paul
11
+ License-Expression: Apache-2.0
12
+ License-File: LICENSE
13
+ Keywords: ai-agent,cli,hipaa,multi-tenant,opa,rego,sarif,security,tenant-isolation
14
+ Classifier: Development Status :: 4 - Beta
15
+ Classifier: Environment :: Console
16
+ Classifier: Intended Audience :: Developers
17
+ Classifier: License :: OSI Approved :: Apache Software License
18
+ Classifier: Operating System :: OS Independent
19
+ Classifier: Programming Language :: Python :: 3
20
+ Classifier: Programming Language :: Python :: 3.9
21
+ Classifier: Programming Language :: Python :: 3.10
22
+ Classifier: Programming Language :: Python :: 3.11
23
+ Classifier: Programming Language :: Python :: 3.12
24
+ Classifier: Programming Language :: Python :: 3.13
25
+ Classifier: Topic :: Security
26
+ Classifier: Topic :: Utilities
27
+ Requires-Python: >=3.9
28
+ Requires-Dist: sigstore<5,>=4.0
29
+ Provides-Extra: dev
30
+ Requires-Dist: build<2,>=1.0; extra == 'dev'
31
+ Requires-Dist: pytest<9,>=7.0; extra == 'dev'
32
+ Requires-Dist: twine<7,>=5.0; extra == 'dev'
33
+ Description-Content-Type: text/markdown
34
+
35
+ # tenantguard-cli (PyPI)
36
+
37
+ PyPI wrapper for [TenantGuard](https://github.com/RudrenduPaul/TenantGuard),
38
+ a tenant-isolation security-audit CLI for self-hosted multi-tenant AI-agent
39
+ platforms. This package does not reimplement TenantGuard in Python -- it
40
+ downloads the official prebuilt `tenantguard` binary for your platform from
41
+ TenantGuard's [GitHub Releases](https://github.com/RudrenduPaul/TenantGuard/releases)
42
+ (published by goreleaser), verifies its SHA-256 checksum, caches it locally,
43
+ and execs it.
44
+
45
+ ## Install
46
+
47
+ ```bash
48
+ pip install tenantguard-cli
49
+ ```
50
+
51
+ or run without installing:
52
+
53
+ ```bash
54
+ uvx tenantguard-cli scan --demo
55
+ ```
56
+
57
+ ## Usage
58
+
59
+ ```bash
60
+ tenantguard scan --demo
61
+ tenantguard scan --format sarif
62
+ tenantguard scan --format json
63
+ ```
64
+
65
+ See the main [TenantGuard README](https://github.com/RudrenduPaul/TenantGuard#readme)
66
+ for the full rule reference (TA01-TA16), SARIF/JSON output schema, and the
67
+ GitHub Action.
68
+
69
+ ## How this differs from the npm package
70
+
71
+ The `tenantguard-cli` npm package ships six platform-specific
72
+ `optionalDependencies`, each embedding a cosign-verified binary at publish
73
+ time -- no network access happens on an end user's `npm install`. A single
74
+ pure-Python wheel can't embed six platform binaries the same way, so this
75
+ package instead downloads the matching release archive the first time you
76
+ run `tenantguard`, verifies its SHA-256 against the release's
77
+ `checksums.txt`, and caches the verified binary locally (per package
78
+ version) -- every run after that is offline. See `src/tenantguard_cli/cli.py`
79
+ for the exact verification logic.
80
+
81
+ Other distribution channels for TenantGuard: Homebrew, `go install`, and
82
+ GitHub Releases directly -- see the main README for details.
83
+
84
+ ## License
85
+
86
+ Apache-2.0, matching the main TenantGuard repository.
@@ -0,0 +1,52 @@
1
+ # tenantguard-cli (PyPI)
2
+
3
+ PyPI wrapper for [TenantGuard](https://github.com/RudrenduPaul/TenantGuard),
4
+ a tenant-isolation security-audit CLI for self-hosted multi-tenant AI-agent
5
+ platforms. This package does not reimplement TenantGuard in Python -- it
6
+ downloads the official prebuilt `tenantguard` binary for your platform from
7
+ TenantGuard's [GitHub Releases](https://github.com/RudrenduPaul/TenantGuard/releases)
8
+ (published by goreleaser), verifies its SHA-256 checksum, caches it locally,
9
+ and execs it.
10
+
11
+ ## Install
12
+
13
+ ```bash
14
+ pip install tenantguard-cli
15
+ ```
16
+
17
+ or run without installing:
18
+
19
+ ```bash
20
+ uvx tenantguard-cli scan --demo
21
+ ```
22
+
23
+ ## Usage
24
+
25
+ ```bash
26
+ tenantguard scan --demo
27
+ tenantguard scan --format sarif
28
+ tenantguard scan --format json
29
+ ```
30
+
31
+ See the main [TenantGuard README](https://github.com/RudrenduPaul/TenantGuard#readme)
32
+ for the full rule reference (TA01-TA16), SARIF/JSON output schema, and the
33
+ GitHub Action.
34
+
35
+ ## How this differs from the npm package
36
+
37
+ The `tenantguard-cli` npm package ships six platform-specific
38
+ `optionalDependencies`, each embedding a cosign-verified binary at publish
39
+ time -- no network access happens on an end user's `npm install`. A single
40
+ pure-Python wheel can't embed six platform binaries the same way, so this
41
+ package instead downloads the matching release archive the first time you
42
+ run `tenantguard`, verifies its SHA-256 against the release's
43
+ `checksums.txt`, and caches the verified binary locally (per package
44
+ version) -- every run after that is offline. See `src/tenantguard_cli/cli.py`
45
+ for the exact verification logic.
46
+
47
+ Other distribution channels for TenantGuard: Homebrew, `go install`, and
48
+ GitHub Releases directly -- see the main README for details.
49
+
50
+ ## License
51
+
52
+ Apache-2.0, matching the main TenantGuard repository.
@@ -0,0 +1,79 @@
1
+ [build-system]
2
+ requires = ["hatchling"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "tenantguard-cli"
7
+ version = "0.1.1"
8
+ description = "PyPI wrapper for TenantGuard, a tenant-isolation security-audit CLI for self-hosted multi-tenant AI-agent platforms. Downloads and runs the official prebuilt Go binary from GitHub Releases."
9
+ readme = "README.md"
10
+ requires-python = ">=3.9"
11
+ license = "Apache-2.0"
12
+ authors = [
13
+ { name = "Rudrendu Paul" },
14
+ ]
15
+ keywords = ["security", "tenant-isolation", "multi-tenant", "ai-agent", "sarif", "opa", "rego", "hipaa", "cli"]
16
+ classifiers = [
17
+ "Development Status :: 4 - Beta",
18
+ "Environment :: Console",
19
+ "Intended Audience :: Developers",
20
+ "License :: OSI Approved :: Apache Software License",
21
+ "Operating System :: OS Independent",
22
+ "Programming Language :: Python :: 3",
23
+ "Programming Language :: Python :: 3.9",
24
+ "Programming Language :: Python :: 3.10",
25
+ "Programming Language :: Python :: 3.11",
26
+ "Programming Language :: Python :: 3.12",
27
+ "Programming Language :: Python :: 3.13",
28
+ "Topic :: Security",
29
+ "Topic :: Utilities",
30
+ ]
31
+ dependencies = [
32
+ # Pinned to the 4.x line: cli.py's signature-verification code relies on a
33
+ # documented-but-internal Verifier attribute (`_rekor`) for handling
34
+ # detached checksums.txt.sig/.pem materials, the same mechanism
35
+ # sigstore-python's own CLI uses internally for this case. Widen the upper
36
+ # bound only after re-verifying that internal surface against a new major.
37
+ "sigstore>=4.0,<5",
38
+ ]
39
+
40
+ [project.optional-dependencies]
41
+ dev = [
42
+ "pytest>=7.0,<9",
43
+ "build>=1.0,<2",
44
+ "twine>=5.0,<7",
45
+ ]
46
+
47
+ [project.urls]
48
+ Homepage = "https://github.com/RudrenduPaul/TenantGuard"
49
+ Repository = "https://github.com/RudrenduPaul/TenantGuard"
50
+ "Bug Tracker" = "https://github.com/RudrenduPaul/TenantGuard/issues"
51
+ Changelog = "https://github.com/RudrenduPaul/TenantGuard/blob/main/CHANGELOG.md"
52
+ "Author - Rudrendu Paul" = "https://github.com/RudrenduPaul"
53
+
54
+ [project.scripts]
55
+ tenantguard = "tenantguard_cli.cli:main"
56
+
57
+ [tool.hatch.build]
58
+ # This package lives in a subdirectory (python/) of a larger monorepo whose
59
+ # .git directory is at the repo root, alongside the sibling Go module and npm
60
+ # package. Hatchling's default VCS-aware file source walks up to that root
61
+ # .git and pulls in root-level files (Go sources, npm/, action/, etc.) that
62
+ # have nothing to do with this Python package. ignore-vcs disables that
63
+ # VCS-based default source so only the explicit include/only-include lists
64
+ # below decide what ships.
65
+ ignore-vcs = true
66
+
67
+ [tool.hatch.build.targets.wheel]
68
+ packages = ["src/tenantguard_cli"]
69
+
70
+ [tool.hatch.build.targets.sdist]
71
+ only-include = [
72
+ "src/tenantguard_cli",
73
+ "tests",
74
+ "README.md",
75
+ "LICENSE",
76
+ ]
77
+
78
+ [tool.pytest.ini_options]
79
+ testpaths = ["tests"]
@@ -0,0 +1,17 @@
1
+ """tenantguard-cli: a thin PyPI wrapper around the TenantGuard Go binary.
2
+
3
+ This package does not reimplement TenantGuard in Python. It resolves the
4
+ correct prebuilt binary for the running platform from TenantGuard's GitHub
5
+ Releases (published by goreleaser), caches it locally, and execs it,
6
+ forwarding argv/stdio/exit-code unchanged. See ``tenantguard_cli.cli`` and
7
+ ``tenantguard_cli.platforms`` for the implementation.
8
+ """
9
+
10
+ __version__ = "0.1.1"
11
+
12
+ # The GitHub release tag this package version is pinned to. Kept in lockstep
13
+ # with __version__ (and with the npm wrapper's RELEASE_TAG in
14
+ # npm/scripts/fetch-binary.js) -- a new TenantGuard release means a new
15
+ # tenantguard-cli release pinned to the matching tag, never a silent
16
+ # "latest" resolution at install or run time.
17
+ RELEASE_TAG = f"v{__version__}"
@@ -0,0 +1,315 @@
1
+ """Runtime entry point for the `tenantguard` console script.
2
+
3
+ On first invocation for a given (package version, platform, arch), this
4
+ downloads the matching TenantGuard release archive from GitHub Releases,
5
+ verifies checksums.txt's Sigstore signature (keyless, GitHub Actions OIDC)
6
+ before trusting any digest inside it, verifies the archive against that
7
+ digest (SHA-256), extracts the binary into a local cache directory, then
8
+ execs it -- forwarding argv, stdio, and exit code unchanged. Subsequent
9
+ invocations reuse the cached binary; no network access happens once it's
10
+ cached.
11
+
12
+ Signature verification uses the `sigstore` PyPI package (a pure-Python
13
+ Sigstore client, see https://pypi.org/project/sigstore/), not the `cosign`
14
+ CLI binary that npm/scripts/fetch-binary.js shells out to. That script runs
15
+ only at *publish* time, on the maintainer's own CI runner, where installing
16
+ an extra CLI binary is a reasonable ask. This package's download happens on
17
+ the *end user's* machine at first run instead -- a single pure-Python wheel
18
+ can't embed all platform binaries the way npm's per-platform packages can --
19
+ so requiring end users to separately install `cosign` would be a real
20
+ usability regression. sigstore-python avoids that tradeoff: the same
21
+ verification guarantee (checksums.txt must carry a valid Sigstore signature
22
+ from this repo's own release workflow, keyless via GitHub Actions OIDC, with
23
+ certificate identity and issuer checked against the pinned RELEASE_TAG) with
24
+ no extra binary for the end user to install.
25
+
26
+ checksums.txt.sig and checksums.txt.pem (the same release assets the npm
27
+ script already consumes) are fetched alongside checksums.txt and verified
28
+ BEFORE any digest is parsed out of it. That ordering is what actually closes
29
+ the gap SHA-256-over-HTTPS alone leaves open: if checksums.txt and a
30
+ malicious archive were served together from a single compromised source,
31
+ they'd still agree with each other and pass a bare digest check. Requiring a
32
+ valid signature from the real release workflow first means an attacker would
33
+ also need to forge that signature, not just serve consistent bytes.
34
+ """
35
+
36
+ from __future__ import annotations
37
+
38
+ import hashlib
39
+ import io
40
+ import os
41
+ import stat
42
+ import subprocess
43
+ import sys
44
+ import tarfile
45
+ import urllib.error
46
+ import urllib.request
47
+ import zipfile
48
+ from pathlib import Path
49
+
50
+ from cryptography.x509 import load_pem_x509_certificate
51
+ from sigstore._internal.rekor import _hashedrekord_from_parts
52
+ from sigstore.hashes import HashAlgorithm, Hashed
53
+ from sigstore.models import Bundle
54
+ from sigstore.verify import Verifier
55
+ from sigstore.verify import policy as sigstore_policy
56
+
57
+ from . import RELEASE_TAG, __version__
58
+ from .platforms import (
59
+ UnsupportedPlatformError,
60
+ archive_ext,
61
+ archive_name,
62
+ binary_name,
63
+ resolve_goarch,
64
+ resolve_goos,
65
+ )
66
+
67
+ REPO = "RudrenduPaul/TenantGuard"
68
+ PROJECT_NAME = "tenantguard"
69
+ RELEASE_BASE = f"https://github.com/{REPO}/releases/download/{RELEASE_TAG}"
70
+ USER_AGENT = "tenantguard-cli-pypi-wrapper"
71
+ REQUEST_TIMEOUT_SECONDS = 30
72
+
73
+ # Same identity/issuer the release workflow (.github/workflows/release.yml)
74
+ # signs checksums.txt with, and that npm/scripts/fetch-binary.js's cosign
75
+ # check already verifies against -- keyless Sigstore signing via GitHub
76
+ # Actions OIDC, scoped to this exact release workflow run for this exact tag.
77
+ SIGSTORE_OIDC_ISSUER = "https://token.actions.githubusercontent.com"
78
+
79
+
80
+ def _sigstore_certificate_identity() -> str:
81
+ return f"https://github.com/{REPO}/.github/workflows/release.yml@refs/tags/{RELEASE_TAG}"
82
+
83
+
84
+ def _cache_dir() -> Path:
85
+ """Version-scoped cache directory. A new pinned RELEASE_TAG (i.e. a new
86
+ tenantguard-cli release) gets its own subdirectory, so upgrading this
87
+ package always re-downloads rather than silently reusing a stale binary.
88
+ """
89
+ base = os.environ.get("TENANTGUARD_CLI_CACHE_DIR")
90
+ if base:
91
+ root = Path(base)
92
+ elif sys.platform == "win32":
93
+ root = Path(os.environ.get("LOCALAPPDATA", Path.home() / "AppData" / "Local")) / "tenantguard-cli"
94
+ elif sys.platform == "darwin":
95
+ root = Path.home() / "Library" / "Caches" / "tenantguard-cli"
96
+ else:
97
+ xdg = os.environ.get("XDG_CACHE_HOME")
98
+ root = Path(xdg) / "tenantguard-cli" if xdg else Path.home() / ".cache" / "tenantguard-cli"
99
+ return root / __version__
100
+
101
+
102
+ def _fetch(url: str) -> bytes:
103
+ request = urllib.request.Request(url, headers={"User-Agent": USER_AGENT})
104
+ try:
105
+ with urllib.request.urlopen(request, timeout=REQUEST_TIMEOUT_SECONDS) as response:
106
+ return response.read()
107
+ except urllib.error.HTTPError as exc:
108
+ raise RuntimeError(f"tenantguard-cli: GET {url} failed: HTTP {exc.code}") from exc
109
+ except urllib.error.URLError as exc:
110
+ raise RuntimeError(f"tenantguard-cli: GET {url} failed: {exc.reason}") from exc
111
+
112
+
113
+ def _sha256_hex(data: bytes) -> str:
114
+ return hashlib.sha256(data).hexdigest()
115
+
116
+
117
+ def _build_sigstore_verifier() -> Verifier:
118
+ """Split out so tests can monkeypatch it instead of hitting the real
119
+ Sigstore trust root / TUF refresh."""
120
+ return Verifier.production()
121
+
122
+
123
+ def _retrieve_sigstore_log_entry(verifier: Verifier, certificate, signature: bytes, hashed: Hashed):
124
+ """Looks up the Rekor transparency-log entry matching a *detached*
125
+ signature + certificate pair (i.e. separate .sig/.pem files, the same
126
+ shape cosign produces and that checksums.txt.sig/.pem already are) --
127
+ mirrors what sigstore-python's own CLI does internally for this exact
128
+ "detached materials" case (see sigstore.verify.Verifier's `_rekor`
129
+ attribute and its "ugly hack needed for verifying detached materials"
130
+ comment). A `Bundle` built via `Bundle.from_parts` requires this log
131
+ entry, so it has to be fetched before verification can proceed. Split out
132
+ so tests can monkeypatch it instead of hitting the real transparency log.
133
+ """
134
+ return verifier._rekor.log.entries.retrieve.post( # noqa: SLF001
135
+ _hashedrekord_from_parts(certificate, signature, hashed)
136
+ )
137
+
138
+
139
+ def _verify_checksums_signature(checksums_bytes: bytes, cert_pem_bytes: bytes, sig_bytes: bytes) -> None:
140
+ """Verifies checksums.txt was signed by this repo's own release workflow
141
+ via Sigstore keyless signing (GitHub Actions OIDC), using the pure-Python
142
+ `sigstore` library. `cert_pem_bytes`/`sig_bytes` are the raw bytes
143
+ downloaded from checksums.txt.pem / checksums.txt.sig -- the same release
144
+ assets npm/scripts/fetch-binary.js's cosign check already consumes.
145
+
146
+ Raises RuntimeError on any failure: a certificate that doesn't parse, no
147
+ matching transparency-log entry, a signature that doesn't verify, or a
148
+ certificate identity/issuer that doesn't match this exact release
149
+ workflow run. Must be called, and must succeed, before any digest parsed
150
+ out of checksums.txt is trusted.
151
+ """
152
+ try:
153
+ certificate = load_pem_x509_certificate(cert_pem_bytes)
154
+ except ValueError as exc:
155
+ raise RuntimeError(
156
+ f"tenantguard-cli: could not parse checksums.txt.pem as a PEM certificate: {exc}"
157
+ ) from exc
158
+
159
+ hashed = Hashed(algorithm=HashAlgorithm.SHA2_256, digest=hashlib.sha256(checksums_bytes).digest())
160
+ verifier = _build_sigstore_verifier()
161
+
162
+ try:
163
+ log_entry = _retrieve_sigstore_log_entry(verifier, certificate, sig_bytes, hashed)
164
+ except Exception as exc:
165
+ raise RuntimeError(
166
+ "tenantguard-cli: failed to look up checksums.txt's signature in the Sigstore "
167
+ f"transparency log: {exc}"
168
+ ) from exc
169
+
170
+ if log_entry is None:
171
+ raise RuntimeError(
172
+ "tenantguard-cli: no matching Sigstore transparency log entry found for "
173
+ "checksums.txt.sig/checksums.txt.pem -- refusing to trust checksums.txt."
174
+ )
175
+
176
+ try:
177
+ bundle = Bundle.from_parts(certificate, sig_bytes, log_entry)
178
+ except Exception as exc:
179
+ raise RuntimeError(
180
+ f"tenantguard-cli: could not assemble a Sigstore bundle for checksums.txt: {exc}"
181
+ ) from exc
182
+
183
+ verification_policy = sigstore_policy.Identity(
184
+ identity=_sigstore_certificate_identity(),
185
+ issuer=SIGSTORE_OIDC_ISSUER,
186
+ )
187
+
188
+ try:
189
+ verifier.verify_artifact(checksums_bytes, bundle, verification_policy)
190
+ except Exception as exc:
191
+ raise RuntimeError(
192
+ f"tenantguard-cli: Sigstore signature verification failed for checksums.txt: {exc}"
193
+ ) from exc
194
+
195
+ print(
196
+ "tenantguard-cli: sigstore signature verified for checksums.txt "
197
+ "(keyless, GitHub Actions OIDC)",
198
+ file=sys.stderr,
199
+ )
200
+
201
+
202
+ def _parse_checksums(text: str) -> dict[str, str]:
203
+ """checksums.txt lines look like "<64 hex chars> <filename>" (goreleaser's
204
+ default sha256sum-compatible format; tolerate an optional leading "*")."""
205
+ checksums: dict[str, str] = {}
206
+ for raw_line in text.splitlines():
207
+ line = raw_line.strip()
208
+ if not line:
209
+ continue
210
+ parts = line.split(None, 1)
211
+ if len(parts) != 2:
212
+ continue
213
+ digest, filename = parts
214
+ digest = digest.strip().lower()
215
+ filename = filename.lstrip("*").strip()
216
+ if len(digest) == 64:
217
+ checksums[filename] = digest
218
+ return checksums
219
+
220
+
221
+ def _extract_binary(archive_bytes: bytes, ext: str, target_basename: str) -> bytes:
222
+ if ext == "zip":
223
+ with zipfile.ZipFile(io.BytesIO(archive_bytes)) as zf:
224
+ for name in zf.namelist():
225
+ if os.path.basename(name) == target_basename:
226
+ return zf.read(name)
227
+ else:
228
+ with tarfile.open(fileobj=io.BytesIO(archive_bytes), mode="r:gz") as tf:
229
+ for member in tf.getmembers():
230
+ if os.path.basename(member.name) == target_basename:
231
+ extracted = tf.extractfile(member)
232
+ if extracted is None:
233
+ break
234
+ return extracted.read()
235
+ raise RuntimeError(
236
+ f"tenantguard-cli: could not find '{target_basename}' inside the downloaded archive."
237
+ )
238
+
239
+
240
+ def ensure_binary() -> Path:
241
+ """Returns the path to a verified, cached tenantguard binary for the
242
+ current platform, downloading and extracting it first if needed.
243
+ """
244
+ goos = resolve_goos()
245
+ goarch = resolve_goarch()
246
+ bin_name = binary_name(goos)
247
+
248
+ cache_dir = _cache_dir()
249
+ cached_path = cache_dir / bin_name
250
+ if cached_path.is_file() and os.access(cached_path, os.X_OK):
251
+ return cached_path
252
+
253
+ asset_name = archive_name(PROJECT_NAME, goos, goarch)
254
+ archive_url = f"{RELEASE_BASE}/{asset_name}"
255
+ checksums_url = f"{RELEASE_BASE}/checksums.txt"
256
+ checksums_sig_url = f"{checksums_url}.sig"
257
+ checksums_cert_url = f"{checksums_url}.pem"
258
+
259
+ print(f"tenantguard-cli: downloading {archive_url}", file=sys.stderr)
260
+ archive_bytes = _fetch(archive_url)
261
+ checksums_bytes = _fetch(checksums_url)
262
+ checksums_sig_bytes = _fetch(checksums_sig_url)
263
+ checksums_cert_bytes = _fetch(checksums_cert_url)
264
+
265
+ _verify_checksums_signature(checksums_bytes, checksums_cert_bytes, checksums_sig_bytes)
266
+
267
+ checksums = _parse_checksums(checksums_bytes.decode("utf-8", errors="replace"))
268
+ expected_digest = checksums.get(asset_name)
269
+ if not expected_digest:
270
+ raise RuntimeError(
271
+ f"tenantguard-cli: no checksum entry for '{asset_name}' in {RELEASE_TAG}'s "
272
+ "checksums.txt -- refusing to proceed."
273
+ )
274
+
275
+ actual_digest = _sha256_hex(archive_bytes)
276
+ if actual_digest != expected_digest:
277
+ raise RuntimeError(
278
+ f"tenantguard-cli: checksum mismatch for {asset_name}: "
279
+ f"expected {expected_digest}, got {actual_digest}. Refusing to extract."
280
+ )
281
+ print(f"tenantguard-cli: checksum verified for {asset_name}", file=sys.stderr)
282
+
283
+ binary_data = _extract_binary(archive_bytes, ext=archive_ext(goos), target_basename=bin_name)
284
+ if not binary_data:
285
+ raise RuntimeError(f"tenantguard-cli: extracted an empty '{bin_name}' from {asset_name}.")
286
+
287
+ cache_dir.mkdir(parents=True, exist_ok=True)
288
+ tmp_path = cached_path.with_suffix(cached_path.suffix + ".tmp")
289
+ tmp_path.write_bytes(binary_data)
290
+ if sys.platform != "win32":
291
+ current_mode = tmp_path.stat().st_mode
292
+ tmp_path.chmod(current_mode | stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH)
293
+ tmp_path.replace(cached_path)
294
+
295
+ print(f"tenantguard-cli: cached verified binary at {cached_path}", file=sys.stderr)
296
+ return cached_path
297
+
298
+
299
+ def main(argv: list[str] | None = None) -> int:
300
+ argv = sys.argv[1:] if argv is None else argv
301
+ try:
302
+ binary_path = ensure_binary()
303
+ except UnsupportedPlatformError as exc:
304
+ print(str(exc), file=sys.stderr)
305
+ return 1
306
+ except RuntimeError as exc:
307
+ print(str(exc), file=sys.stderr)
308
+ return 1
309
+
310
+ result = subprocess.run([str(binary_path), *argv])
311
+ return result.returncode
312
+
313
+
314
+ if __name__ == "__main__":
315
+ sys.exit(main())
@@ -0,0 +1,70 @@
1
+ """Pure platform/arch resolution logic, kept separate from cli.py so it can
2
+ be unit tested without touching the network or the filesystem.
3
+
4
+ Mirrors the goreleaser build matrix in .goreleaser.yml (goos: linux, darwin,
5
+ windows / goarch: amd64, arm64) and the archive naming template
6
+ "{{ .ProjectName }}_{{ .Os }}_{{ .Arch }}" -- the same convention the npm
7
+ wrapper's optionalDependency package names / npm/scripts/fetch-binary.js
8
+ already rely on for this exact repo.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import platform
14
+ import sys
15
+
16
+ # sys.platform -> goreleaser GOOS
17
+ _GOOS_MAP = {
18
+ "linux": "linux",
19
+ "darwin": "darwin",
20
+ "win32": "windows",
21
+ "cygwin": "windows",
22
+ }
23
+
24
+ # platform.machine() (lowercased) -> goreleaser GOARCH
25
+ _GOARCH_MAP = {
26
+ "x86_64": "amd64",
27
+ "amd64": "amd64",
28
+ "arm64": "arm64",
29
+ "aarch64": "arm64",
30
+ }
31
+
32
+
33
+ class UnsupportedPlatformError(RuntimeError):
34
+ """Raised when the running machine has no matching TenantGuard release asset."""
35
+
36
+
37
+ def resolve_goos(sys_platform: str = sys.platform) -> str:
38
+ goos = _GOOS_MAP.get(sys_platform)
39
+ if goos is None:
40
+ raise UnsupportedPlatformError(
41
+ f"tenantguard-cli: unsupported platform '{sys_platform}'. "
42
+ f"Supported: {sorted(set(_GOOS_MAP.values()))}."
43
+ )
44
+ return goos
45
+
46
+
47
+ def resolve_goarch(machine: str | None = None) -> str:
48
+ machine = (machine if machine is not None else platform.machine()).lower()
49
+ goarch = _GOARCH_MAP.get(machine)
50
+ if goarch is None:
51
+ raise UnsupportedPlatformError(
52
+ f"tenantguard-cli: unsupported CPU architecture '{machine}'. "
53
+ f"Supported: {sorted(set(_GOARCH_MAP.values()))}."
54
+ )
55
+ return goarch
56
+
57
+
58
+ def archive_ext(goos: str) -> str:
59
+ return "zip" if goos == "windows" else "tar.gz"
60
+
61
+
62
+ def binary_name(goos: str, base_name: str = "tenantguard") -> str:
63
+ return f"{base_name}.exe" if goos == "windows" else base_name
64
+
65
+
66
+ def archive_name(project_name: str, goos: str, goarch: str) -> str:
67
+ """Matches the .goreleaser.yml archive name_template:
68
+ "{{ .ProjectName }}_{{ .Os }}_{{ .Arch }}" plus the format extension.
69
+ """
70
+ return f"{project_name}_{goos}_{goarch}.{archive_ext(goos)}"
File without changes
@@ -0,0 +1,177 @@
1
+ import hashlib
2
+
3
+ import pytest
4
+
5
+ from tenantguard_cli import cli
6
+ from tenantguard_cli.cli import _parse_checksums, _sha256_hex, _verify_checksums_signature
7
+
8
+
9
+ def test_parse_checksums_standard_format():
10
+ text = (
11
+ "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa "
12
+ "tenantguard_linux_amd64.tar.gz\n"
13
+ "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb "
14
+ "tenantguard_darwin_arm64.tar.gz\n"
15
+ )
16
+ checksums = _parse_checksums(text)
17
+ assert checksums["tenantguard_linux_amd64.tar.gz"] == "a" * 64
18
+ assert checksums["tenantguard_darwin_arm64.tar.gz"] == "b" * 64
19
+
20
+
21
+ def test_parse_checksums_tolerates_leading_star_and_blank_lines():
22
+ text = "\n" + "c" * 64 + " *tenantguard_windows_amd64.zip\n\n"
23
+ checksums = _parse_checksums(text)
24
+ assert checksums["tenantguard_windows_amd64.zip"] == "c" * 64
25
+
26
+
27
+ def test_parse_checksums_ignores_malformed_lines():
28
+ checksums = _parse_checksums("not-a-checksum-line\n")
29
+ assert checksums == {}
30
+
31
+
32
+ def test_sha256_hex_matches_hashlib():
33
+ data = b"tenantguard test payload"
34
+ assert _sha256_hex(data) == hashlib.sha256(data).hexdigest()
35
+
36
+
37
+ # --- checksums.txt Sigstore signature verification --------------------------
38
+ #
39
+ # These tests never touch the real Sigstore transparency log or Fulcio trust
40
+ # root: they monkeypatch the seams `_verify_checksums_signature` calls out to
41
+ # (certificate parsing, verifier construction, the Rekor log-entry lookup,
42
+ # and bundle assembly), so only the actual policy-check call --
43
+ # `Verifier.verify_artifact` -- is exercised, via a fake standing in for it.
44
+
45
+
46
+ class _FakeVerifier:
47
+ """Stand-in for sigstore.verify.Verifier. Records every call made to
48
+ verify_artifact (so tests can assert what identity/issuer policy was
49
+ checked against) and either succeeds or raises whatever exception the
50
+ test configures, exactly like the real Verifier would on a rejected
51
+ signature or an identity/issuer mismatch."""
52
+
53
+ def __init__(self, raises: Exception | None = None):
54
+ self.raises = raises
55
+ self.calls = []
56
+
57
+ def verify_artifact(self, input_, bundle, policy):
58
+ self.calls.append((input_, bundle, policy))
59
+ if self.raises is not None:
60
+ raise self.raises
61
+
62
+
63
+ def _patch_sigstore_plumbing(monkeypatch, verifier, *, log_entry=object(), bundle=object()):
64
+ """Bypasses everything upstream of the policy check -- PEM parsing, the
65
+ Rekor transparency-log lookup, and Sigstore bundle assembly -- with
66
+ lightweight stand-ins, since none of those are what this test suite is
67
+ verifying: they're sigstore-python's own responsibility, already covered
68
+ by that library's tests. What this module owns, and what these tests
69
+ verify, is that `ensure_binary()`'s digest never gets trusted until
70
+ `Verifier.verify_artifact` succeeds against the right identity/issuer.
71
+ """
72
+ monkeypatch.setattr(cli, "load_pem_x509_certificate", lambda pem: object())
73
+ monkeypatch.setattr(cli, "_build_sigstore_verifier", lambda: verifier)
74
+ monkeypatch.setattr(cli, "_retrieve_sigstore_log_entry", lambda *a, **k: log_entry)
75
+ monkeypatch.setattr(cli.Bundle, "from_parts", staticmethod(lambda *a, **k: bundle))
76
+
77
+
78
+ def _assert_policy_matches_pinned_identity(checked_policy) -> None:
79
+ """sigstore.verify.policy.Identity stores its fields as private
80
+ attributes (`_identity`, `_issuer._value`) rather than a public API --
81
+ reach into them here (test-only) to confirm _verify_checksums_signature
82
+ builds its policy from the pinned RELEASE_TAG-scoped identity and the
83
+ GitHub Actions OIDC issuer, not something looser."""
84
+ assert checked_policy._identity == cli._sigstore_certificate_identity()
85
+ assert checked_policy._issuer._value == cli.SIGSTORE_OIDC_ISSUER
86
+
87
+
88
+ def test_sigstore_certificate_identity_matches_release_workflow():
89
+ assert cli._sigstore_certificate_identity() == (
90
+ f"https://github.com/{cli.REPO}/.github/workflows/release.yml@refs/tags/{cli.RELEASE_TAG}"
91
+ )
92
+ assert cli.SIGSTORE_OIDC_ISSUER == "https://token.actions.githubusercontent.com"
93
+
94
+
95
+ def test_verify_checksums_signature_success_checks_correct_identity_and_issuer(monkeypatch):
96
+ verifier = _FakeVerifier(raises=None)
97
+ _patch_sigstore_plumbing(monkeypatch, verifier)
98
+
99
+ # Should not raise.
100
+ _verify_checksums_signature(b"checksums.txt contents", b"-----BEGIN CERTIFICATE-----", b"signature-bytes")
101
+
102
+ assert len(verifier.calls) == 1
103
+ checked_input, _checked_bundle, checked_policy = verifier.calls[0]
104
+ assert checked_input == b"checksums.txt contents"
105
+ _assert_policy_matches_pinned_identity(checked_policy)
106
+
107
+
108
+ def test_verify_checksums_signature_rejects_tampered_checksums(monkeypatch):
109
+ """A checksums.txt that was tampered with after signing no longer
110
+ matches the signature that was computed over the original bytes --
111
+ sigstore-python's verify_artifact raises VerificationError for this, and
112
+ that must surface as a RuntimeError, matching this module's error style,
113
+ before any digest inside checksums.txt is ever trusted."""
114
+ from sigstore.errors import VerificationError
115
+
116
+ verifier = _FakeVerifier(raises=VerificationError("Signature is invalid for input"))
117
+ _patch_sigstore_plumbing(monkeypatch, verifier)
118
+
119
+ with pytest.raises(RuntimeError, match="Sigstore signature verification failed"):
120
+ _verify_checksums_signature(b"tampered checksums.txt contents", b"-----BEGIN CERTIFICATE-----", b"sig")
121
+
122
+
123
+ def test_verify_checksums_signature_rejects_wrong_identity_or_issuer(monkeypatch):
124
+ """A certificate signed by a different workflow/repo/tag, or issued by a
125
+ different OIDC issuer than GitHub Actions, must be rejected even if the
126
+ signature itself is otherwise cryptographically valid -- this is what
127
+ the certificate-identity/issuer policy check exists for. sigstore-python
128
+ raises VerificationError for a policy mismatch too (from inside
129
+ verify_artifact's common-signing-cert checks); it must still surface as
130
+ a RuntimeError here."""
131
+ from sigstore.errors import VerificationError
132
+
133
+ verifier = _FakeVerifier(
134
+ raises=VerificationError(
135
+ "Certificate's SANs do not match the expected identity, or the "
136
+ "certificate's issuer extension does not match the expected issuer"
137
+ )
138
+ )
139
+ _patch_sigstore_plumbing(monkeypatch, verifier)
140
+
141
+ with pytest.raises(RuntimeError, match="Sigstore signature verification failed"):
142
+ _verify_checksums_signature(b"checksums.txt contents", b"-----BEGIN CERTIFICATE-----", b"sig")
143
+
144
+ # The policy actually checked was still the pinned identity/issuer, not
145
+ # something looser -- confirms the rejection came from that policy, not
146
+ # a coincidentally-broad one that would have let a wrong cert through.
147
+ assert len(verifier.calls) == 1
148
+ _, _, checked_policy = verifier.calls[0]
149
+ _assert_policy_matches_pinned_identity(checked_policy)
150
+
151
+
152
+ def test_verify_checksums_signature_rejects_missing_transparency_log_entry(monkeypatch):
153
+ """No matching Rekor entry (e.g. checksums.txt.sig/.pem weren't actually
154
+ produced by a real Sigstore signing operation) must fail loudly rather
155
+ than silently skipping straight to the SHA-256 check."""
156
+ verifier = _FakeVerifier(raises=None)
157
+ _patch_sigstore_plumbing(monkeypatch, verifier, log_entry=None)
158
+
159
+ with pytest.raises(RuntimeError, match="no matching Sigstore transparency log entry"):
160
+ _verify_checksums_signature(b"checksums.txt contents", b"-----BEGIN CERTIFICATE-----", b"sig")
161
+
162
+ # verify_artifact must never be reached without a log entry to build a bundle from.
163
+ assert verifier.calls == []
164
+
165
+
166
+ def test_verify_checksums_signature_rejects_unparseable_certificate(monkeypatch):
167
+ """A missing/corrupt checksums.txt.pem (e.g. the signing step never ran,
168
+ or the release asset wasn't published) must fail loudly with a clear
169
+ error rather than crash on an unhandled exception."""
170
+
171
+ def _raise_value_error(_pem):
172
+ raise ValueError("Unable to load PEM file")
173
+
174
+ monkeypatch.setattr(cli, "load_pem_x509_certificate", _raise_value_error)
175
+
176
+ with pytest.raises(RuntimeError, match="could not parse checksums.txt.pem"):
177
+ _verify_checksums_signature(b"checksums.txt contents", b"not a real certificate", b"sig")
@@ -0,0 +1,55 @@
1
+ import pytest
2
+
3
+ from tenantguard_cli.platforms import (
4
+ UnsupportedPlatformError,
5
+ archive_ext,
6
+ archive_name,
7
+ binary_name,
8
+ resolve_goarch,
9
+ resolve_goos,
10
+ )
11
+
12
+
13
+ def test_resolve_goos_known_platforms():
14
+ assert resolve_goos("linux") == "linux"
15
+ assert resolve_goos("darwin") == "darwin"
16
+ assert resolve_goos("win32") == "windows"
17
+ assert resolve_goos("cygwin") == "windows"
18
+
19
+
20
+ def test_resolve_goos_unsupported():
21
+ with pytest.raises(UnsupportedPlatformError):
22
+ resolve_goos("freebsd")
23
+
24
+
25
+ def test_resolve_goarch_known_machines():
26
+ assert resolve_goarch("x86_64") == "amd64"
27
+ assert resolve_goarch("amd64") == "amd64"
28
+ assert resolve_goarch("arm64") == "arm64"
29
+ assert resolve_goarch("aarch64") == "arm64"
30
+ # case-insensitive
31
+ assert resolve_goarch("X86_64") == "amd64"
32
+
33
+
34
+ def test_resolve_goarch_unsupported():
35
+ with pytest.raises(UnsupportedPlatformError):
36
+ resolve_goarch("riscv64")
37
+
38
+
39
+ def test_archive_ext():
40
+ assert archive_ext("windows") == "zip"
41
+ assert archive_ext("linux") == "tar.gz"
42
+ assert archive_ext("darwin") == "tar.gz"
43
+
44
+
45
+ def test_binary_name():
46
+ assert binary_name("windows") == "tenantguard.exe"
47
+ assert binary_name("linux") == "tenantguard"
48
+ assert binary_name("darwin") == "tenantguard"
49
+
50
+
51
+ def test_archive_name_matches_goreleaser_template():
52
+ # Matches .goreleaser.yml's name_template: "{{ .ProjectName }}_{{ .Os }}_{{ .Arch }}"
53
+ assert archive_name("tenantguard", "darwin", "arm64") == "tenantguard_darwin_arm64.tar.gz"
54
+ assert archive_name("tenantguard", "linux", "amd64") == "tenantguard_linux_amd64.tar.gz"
55
+ assert archive_name("tenantguard", "windows", "amd64") == "tenantguard_windows_amd64.zip"