gnap-caep-risc 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (36) hide show
  1. gnap_caep_risc-0.1.0/LICENSE +21 -0
  2. gnap_caep_risc-0.1.0/PKG-INFO +100 -0
  3. gnap_caep_risc-0.1.0/README.md +83 -0
  4. gnap_caep_risc-0.1.0/pyproject.toml +31 -0
  5. gnap_caep_risc-0.1.0/setup.cfg +4 -0
  6. gnap_caep_risc-0.1.0/src/gnap_caep_risc/__init__.py +50 -0
  7. gnap_caep_risc-0.1.0/src/gnap_caep_risc/cli.py +101 -0
  8. gnap_caep_risc-0.1.0/src/gnap_caep_risc/client.py +535 -0
  9. gnap_caep_risc-0.1.0/src/gnap_caep_risc/codec.py +40 -0
  10. gnap_caep_risc-0.1.0/src/gnap_caep_risc/config.py +228 -0
  11. gnap_caep_risc-0.1.0/src/gnap_caep_risc/discovery.py +104 -0
  12. gnap_caep_risc-0.1.0/src/gnap_caep_risc/errors.py +24 -0
  13. gnap_caep_risc-0.1.0/src/gnap_caep_risc/hashes.py +16 -0
  14. gnap_caep_risc-0.1.0/src/gnap_caep_risc/http.py +91 -0
  15. gnap_caep_risc-0.1.0/src/gnap_caep_risc/httpsig.py +90 -0
  16. gnap_caep_risc-0.1.0/src/gnap_caep_risc/jwsd.py +31 -0
  17. gnap_caep_risc-0.1.0/src/gnap_caep_risc/keys.py +239 -0
  18. gnap_caep_risc-0.1.0/src/gnap_caep_risc/ssf/__init__.py +4 -0
  19. gnap_caep_risc-0.1.0/src/gnap_caep_risc/ssf/events.py +94 -0
  20. gnap_caep_risc-0.1.0/src/gnap_caep_risc/ssf/jws.py +72 -0
  21. gnap_caep_risc-0.1.0/src/gnap_caep_risc/ssf/receiver.py +314 -0
  22. gnap_caep_risc-0.1.0/src/gnap_caep_risc/ssf/session.py +81 -0
  23. gnap_caep_risc-0.1.0/src/gnap_caep_risc/subject.py +135 -0
  24. gnap_caep_risc-0.1.0/src/gnap_caep_risc/x509gen.py +67 -0
  25. gnap_caep_risc-0.1.0/src/gnap_caep_risc.egg-info/PKG-INFO +100 -0
  26. gnap_caep_risc-0.1.0/src/gnap_caep_risc.egg-info/SOURCES.txt +34 -0
  27. gnap_caep_risc-0.1.0/src/gnap_caep_risc.egg-info/dependency_links.txt +1 -0
  28. gnap_caep_risc-0.1.0/src/gnap_caep_risc.egg-info/entry_points.txt +2 -0
  29. gnap_caep_risc-0.1.0/src/gnap_caep_risc.egg-info/requires.txt +4 -0
  30. gnap_caep_risc-0.1.0/src/gnap_caep_risc.egg-info/top_level.txt +1 -0
  31. gnap_caep_risc-0.1.0/tests/test_client.py +500 -0
  32. gnap_caep_risc-0.1.0/tests/test_config.py +71 -0
  33. gnap_caep_risc-0.1.0/tests/test_password_file.py +63 -0
  34. gnap_caep_risc-0.1.0/tests/test_ssf.py +239 -0
  35. gnap_caep_risc-0.1.0/tests/test_subject.py +37 -0
  36. gnap_caep_risc-0.1.0/tests/test_trust_chain.py +188 -0
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Iya CyberSecurity Solutions, LLC
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,100 @@
1
+ Metadata-Version: 2.4
2
+ Name: gnap-caep-risc
3
+ Version: 0.1.0
4
+ Summary: Server-side GNAP client with a registered key, key-bound tokens, and a CAEP and RISC receiver
5
+ Author: Iya CyberSecurity Solutions, LLC
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/rcbj/gnap-caep-risc-python
8
+ Project-URL: Repository, https://github.com/rcbj/gnap-caep-risc-python
9
+ Project-URL: Issues, https://github.com/rcbj/gnap-caep-risc-python/issues
10
+ Requires-Python: >=3.11
11
+ Description-Content-Type: text/markdown
12
+ License-File: LICENSE
13
+ Requires-Dist: cryptography>=42
14
+ Provides-Extra: dev
15
+ Requires-Dist: pytest>=8; extra == "dev"
16
+ Dynamic: license-file
17
+
18
+ # gnap-caep-risc
19
+
20
+ A server-side [GNAP](https://www.rfc-editor.org/rfc/rfc9635) client. The key is registered by value and proved with mutual TLS, an HTTP message signature, or a detached JWS. Access tokens are key-bound; a bearer token is refused. One Shared Signals poll stream carries CAEP and RISC events.
21
+
22
+ The private key stays in this process. The same `gnap.json` shape as the Node library loads: the JSON keys are identical.
23
+
24
+ ## Build and tests
25
+
26
+ ```bash
27
+ docker build --target test .
28
+ ```
29
+
30
+ The `test` stage runs `pip install --no-cache-dir ".[dev]" && pytest` in `python:3.11-slim`. GitHub Actions on a push uses that command. Do not run pytest on the host. The demo image does not run the suite.
31
+
32
+ Those tests use an in-process stub. They do not start iya-sts.
33
+
34
+ `python3 scripts/live_iya_sts.py` is the live half. It copies this checkout to a scratch build context, generates the client key and runs the install script there (which writes the `tlsCa` chain), then builds this demo image from it, checks the image carries the chain and no key, starts the demo with no CA mount and `TLS_CA_REFRESH=0`, signs in, and requires a credential-change event and a session-revoked event on `GET /live-status`. The second event ends the local session. When `IYA_STS_URL` is unset it starts the latest main branch of iya-sts in memory mode, with persistence and clustering off. It uses the host's Python and Docker and does not import this library. It binds two high ports and never binds 3000 or 8081. The nightly workflow runs the unit suite and this script once every 24 hours.
35
+
36
+ A pull request merged into `main` publishes the package to PyPI after the test workflow succeeds on that commit. A direct push does not. There is no API token: PyPI Trusted Publishing trades the workflow's GitHub OIDC token for a short-lived upload token, from the `pypi` environment, and PyPI holds the publisher for this repository and `publish.yml`. A version already on PyPI stays there; the next release is a new `version` in `pyproject.toml` (and `VERSION`).
37
+
38
+ ## The iya-sts trust chain (`tlsCa`)
39
+
40
+ `tlsCa` in `demo/gnap.json` names the iya-sts TLS listener CA trust chain the library trusts. The default is `generated/idp-ca.pem`, relative to `demo/`. The value may also be `file:<path>`, `env:<NAME>`, or the PEM itself. The library adds every certificate in it to the default trust store.
41
+
42
+ `scripts/configure_iya_sts.py`, the install script, writes that file. It saves the whole chain iya-sts publishes at `GET /tls/server-certificate` (leaf, TLS Issuing CA, Intermediate, Root), or the chain from the TLS handshake when that path does not answer. It prints the path, the trust anchor's subject and its SHA-256 fingerprint. Compare the anchor with the Root CA on iya-sts's PKI page.
43
+
44
+ The demo image build copies that file into the image at `/app/demo/generated/idp-ca.pem`, so the image trusts that iya-sts with no bind mount and no fetch. Run the install script before you build the image. Rebuild the image after running the install script against a different iya-sts. `.dockerignore` admits only that file from `demo/generated`. The client key and certificate stay out of the image; compose mounts `demo/generated` for them. A build with no chain file yet (a fresh clone, CI) still succeeds; the image then has no `tlsCa` file.
45
+
46
+ The mechanism is `COPY demo demo` plus `.dockerignore`'s `demo/generated/*` and `!demo/generated/idp-ca.pem`. Do not replace it with a COPY that names the file or globs for it: when the file is absent, BuildKit fails on the missing `demo/generated` and the classic builder fails with "no source files were specified". A directory COPY of `demo/` (which always exists) succeeds in both.
47
+
48
+ The container entrypoint also refreshes the file from the authorization server at start, because a development iya-sts makes a new CA when it restarts. A failed refresh keeps the file from the build. `TLS_CA_REFRESH=0` turns the refresh off. `python scripts/trust_chain.py --config demo/gnap.json` refreshes it by hand.
49
+
50
+ ## Three calls
51
+
52
+ ```python
53
+ from gnap_caep_risc import GnapClient
54
+
55
+ gnap = GnapClient.from_file("gnap.json")
56
+ started = gnap.request_grant()
57
+ done = gnap.finish_redirect(query, [started.pending.id])
58
+ ```
59
+
60
+ `request_grant` returns a redirect and a pending grant. `finish_redirect` checks the interaction hash against grants this process started, then continues the grant with the key proof. Pass the pending ids this browser was given as `allowed_ids`.
61
+
62
+ `resolve_config` and `read_config_file` load the same document without starting a grant.
63
+
64
+ ## Signals
65
+
66
+ `signals` omitted or `true` keeps CAEP and RISC on. The resolved configuration omits the key, fills `ssf` from `ssf.transmitter` or `transmitterIssuer`, and asks for `ssf.read` and `ssf.manage` when `access` does not say otherwise.
67
+
68
+ `signals: false` does not start the Shared Signals receiver, does not require transmitter metadata, and drops `ssf.read` and `ssf.manage` from the GNAP access. The resolved configuration includes `signals: false`. If those two rights were the only ones, configuration fails and asks for another right the authorization server grants. Any other value fails with `signals must be true or false`.
69
+
70
+ `ssf.pollIntervalMs` is the poll interval in milliseconds.
71
+
72
+ ## Demo
73
+
74
+ ```bash
75
+ docker compose up --build
76
+ ```
77
+
78
+ `PORT` defaults to 3000 and is the bind port. Loopback finish and display URLs follow `PORT`. Any other host is left as written. `PUBLIC_URL` or `--public-url` replaces the origin and keeps the path. `GET /healthz` returns `ok`. The home page has a sign-in control; `/login` starts a grant, `/callback` finishes it, and `POST /logout` signs out. `GET /live-status` is JSON: `signedIn`, `subject`, the receiver state, and the Shared Signals events this process has accepted (`type` and `jti` only). It does not include tokens. Do not bind port 3000 or 8081 while something else is already using them.
79
+
80
+ The shipped `demo/gnap.json` leaves `signals` on by omitting the key. Key material is `file:` or `env:` and is not in the tree. Generate a key inside the demo image, then register the application:
81
+
82
+ ```bash
83
+ docker compose build
84
+ docker run --rm --user "$(id -u):$(id -g)" \
85
+ -v "$PWD/demo:/app/demo" \
86
+ gnap-caep-risc-python-demo \
87
+ gnap-caep-risc generate-key --config demo/gnap.json
88
+ ADMIN_API_CLIENT_SECRET=… python scripts/configure_iya_sts.py --config demo/gnap.json
89
+ docker compose build
90
+ ```
91
+
92
+ The second build bakes in the trust chain the install script saved.
93
+
94
+ The install script creates the test user `gnap-demo-user`. Its password is `$GNAP_DEMO_USER_PASSWORD`, or iya-sts generates one; the script writes a generated password to `demo/generated/gnap-demo-user.password` (mode 0600) and prints only that path, never the password.
95
+
96
+ `--dry-run` prints the admin API calls and sends nothing. When the `gnap-demo` container is running, its `PORT` wins over the shell `PORT`.
97
+
98
+ ## License
99
+
100
+ MIT. Copyright (c) 2026 Iya CyberSecurity Solutions, LLC.
@@ -0,0 +1,83 @@
1
+ # gnap-caep-risc
2
+
3
+ A server-side [GNAP](https://www.rfc-editor.org/rfc/rfc9635) client. The key is registered by value and proved with mutual TLS, an HTTP message signature, or a detached JWS. Access tokens are key-bound; a bearer token is refused. One Shared Signals poll stream carries CAEP and RISC events.
4
+
5
+ The private key stays in this process. The same `gnap.json` shape as the Node library loads: the JSON keys are identical.
6
+
7
+ ## Build and tests
8
+
9
+ ```bash
10
+ docker build --target test .
11
+ ```
12
+
13
+ The `test` stage runs `pip install --no-cache-dir ".[dev]" && pytest` in `python:3.11-slim`. GitHub Actions on a push uses that command. Do not run pytest on the host. The demo image does not run the suite.
14
+
15
+ Those tests use an in-process stub. They do not start iya-sts.
16
+
17
+ `python3 scripts/live_iya_sts.py` is the live half. It copies this checkout to a scratch build context, generates the client key and runs the install script there (which writes the `tlsCa` chain), then builds this demo image from it, checks the image carries the chain and no key, starts the demo with no CA mount and `TLS_CA_REFRESH=0`, signs in, and requires a credential-change event and a session-revoked event on `GET /live-status`. The second event ends the local session. When `IYA_STS_URL` is unset it starts the latest main branch of iya-sts in memory mode, with persistence and clustering off. It uses the host's Python and Docker and does not import this library. It binds two high ports and never binds 3000 or 8081. The nightly workflow runs the unit suite and this script once every 24 hours.
18
+
19
+ A pull request merged into `main` publishes the package to PyPI after the test workflow succeeds on that commit. A direct push does not. There is no API token: PyPI Trusted Publishing trades the workflow's GitHub OIDC token for a short-lived upload token, from the `pypi` environment, and PyPI holds the publisher for this repository and `publish.yml`. A version already on PyPI stays there; the next release is a new `version` in `pyproject.toml` (and `VERSION`).
20
+
21
+ ## The iya-sts trust chain (`tlsCa`)
22
+
23
+ `tlsCa` in `demo/gnap.json` names the iya-sts TLS listener CA trust chain the library trusts. The default is `generated/idp-ca.pem`, relative to `demo/`. The value may also be `file:<path>`, `env:<NAME>`, or the PEM itself. The library adds every certificate in it to the default trust store.
24
+
25
+ `scripts/configure_iya_sts.py`, the install script, writes that file. It saves the whole chain iya-sts publishes at `GET /tls/server-certificate` (leaf, TLS Issuing CA, Intermediate, Root), or the chain from the TLS handshake when that path does not answer. It prints the path, the trust anchor's subject and its SHA-256 fingerprint. Compare the anchor with the Root CA on iya-sts's PKI page.
26
+
27
+ The demo image build copies that file into the image at `/app/demo/generated/idp-ca.pem`, so the image trusts that iya-sts with no bind mount and no fetch. Run the install script before you build the image. Rebuild the image after running the install script against a different iya-sts. `.dockerignore` admits only that file from `demo/generated`. The client key and certificate stay out of the image; compose mounts `demo/generated` for them. A build with no chain file yet (a fresh clone, CI) still succeeds; the image then has no `tlsCa` file.
28
+
29
+ The mechanism is `COPY demo demo` plus `.dockerignore`'s `demo/generated/*` and `!demo/generated/idp-ca.pem`. Do not replace it with a COPY that names the file or globs for it: when the file is absent, BuildKit fails on the missing `demo/generated` and the classic builder fails with "no source files were specified". A directory COPY of `demo/` (which always exists) succeeds in both.
30
+
31
+ The container entrypoint also refreshes the file from the authorization server at start, because a development iya-sts makes a new CA when it restarts. A failed refresh keeps the file from the build. `TLS_CA_REFRESH=0` turns the refresh off. `python scripts/trust_chain.py --config demo/gnap.json` refreshes it by hand.
32
+
33
+ ## Three calls
34
+
35
+ ```python
36
+ from gnap_caep_risc import GnapClient
37
+
38
+ gnap = GnapClient.from_file("gnap.json")
39
+ started = gnap.request_grant()
40
+ done = gnap.finish_redirect(query, [started.pending.id])
41
+ ```
42
+
43
+ `request_grant` returns a redirect and a pending grant. `finish_redirect` checks the interaction hash against grants this process started, then continues the grant with the key proof. Pass the pending ids this browser was given as `allowed_ids`.
44
+
45
+ `resolve_config` and `read_config_file` load the same document without starting a grant.
46
+
47
+ ## Signals
48
+
49
+ `signals` omitted or `true` keeps CAEP and RISC on. The resolved configuration omits the key, fills `ssf` from `ssf.transmitter` or `transmitterIssuer`, and asks for `ssf.read` and `ssf.manage` when `access` does not say otherwise.
50
+
51
+ `signals: false` does not start the Shared Signals receiver, does not require transmitter metadata, and drops `ssf.read` and `ssf.manage` from the GNAP access. The resolved configuration includes `signals: false`. If those two rights were the only ones, configuration fails and asks for another right the authorization server grants. Any other value fails with `signals must be true or false`.
52
+
53
+ `ssf.pollIntervalMs` is the poll interval in milliseconds.
54
+
55
+ ## Demo
56
+
57
+ ```bash
58
+ docker compose up --build
59
+ ```
60
+
61
+ `PORT` defaults to 3000 and is the bind port. Loopback finish and display URLs follow `PORT`. Any other host is left as written. `PUBLIC_URL` or `--public-url` replaces the origin and keeps the path. `GET /healthz` returns `ok`. The home page has a sign-in control; `/login` starts a grant, `/callback` finishes it, and `POST /logout` signs out. `GET /live-status` is JSON: `signedIn`, `subject`, the receiver state, and the Shared Signals events this process has accepted (`type` and `jti` only). It does not include tokens. Do not bind port 3000 or 8081 while something else is already using them.
62
+
63
+ The shipped `demo/gnap.json` leaves `signals` on by omitting the key. Key material is `file:` or `env:` and is not in the tree. Generate a key inside the demo image, then register the application:
64
+
65
+ ```bash
66
+ docker compose build
67
+ docker run --rm --user "$(id -u):$(id -g)" \
68
+ -v "$PWD/demo:/app/demo" \
69
+ gnap-caep-risc-python-demo \
70
+ gnap-caep-risc generate-key --config demo/gnap.json
71
+ ADMIN_API_CLIENT_SECRET=… python scripts/configure_iya_sts.py --config demo/gnap.json
72
+ docker compose build
73
+ ```
74
+
75
+ The second build bakes in the trust chain the install script saved.
76
+
77
+ The install script creates the test user `gnap-demo-user`. Its password is `$GNAP_DEMO_USER_PASSWORD`, or iya-sts generates one; the script writes a generated password to `demo/generated/gnap-demo-user.password` (mode 0600) and prints only that path, never the password.
78
+
79
+ `--dry-run` prints the admin API calls and sends nothing. When the `gnap-demo` container is running, its `PORT` wins over the shell `PORT`.
80
+
81
+ ## License
82
+
83
+ MIT. Copyright (c) 2026 Iya CyberSecurity Solutions, LLC.
@@ -0,0 +1,31 @@
1
+ [build-system]
2
+ requires = ["setuptools>=77"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "gnap-caep-risc"
7
+ version = "0.1.0"
8
+ description = "Server-side GNAP client with a registered key, key-bound tokens, and a CAEP and RISC receiver"
9
+ readme = "README.md"
10
+ requires-python = ">=3.11"
11
+ license = "MIT"
12
+ license-files = ["LICENSE"]
13
+ authors = [{ name = "Iya CyberSecurity Solutions, LLC" }]
14
+ dependencies = ["cryptography>=42"]
15
+
16
+ [project.optional-dependencies]
17
+ dev = ["pytest>=8"]
18
+
19
+ [project.scripts]
20
+ gnap-caep-risc = "gnap_caep_risc.cli:main"
21
+
22
+ [tool.setuptools.packages.find]
23
+ where = ["src"]
24
+
25
+ [tool.pytest.ini_options]
26
+ testpaths = ["tests"]
27
+
28
+ [project.urls]
29
+ Homepage = "https://github.com/rcbj/gnap-caep-risc-python"
30
+ Repository = "https://github.com/rcbj/gnap-caep-risc-python"
31
+ Issues = "https://github.com/rcbj/gnap-caep-risc-python/issues"
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,50 @@
1
+ # SPDX-FileCopyrightText: 2026 Iya CyberSecurity Solutions, LLC
2
+ # SPDX-License-Identifier: MIT
3
+
4
+ """Server-side GNAP client. The private key stays in this process. Tokens are key-bound."""
5
+
6
+ from .client import FinishedGrant, GnapClient, Grant, GrantResult, PendingGrant, SecurityPosture
7
+ from .config import read_config_file, resolve_config
8
+ from .discovery import discover_grant_server, discover_open_id, validate_grant_server, well_known_urls
9
+ from .errors import GnapError
10
+ from .hashes import interaction_hash
11
+ from .keys import load_client_key, public_key_object
12
+ from .ssf.events import CAEP_EVENTS, DEFAULT_ENDING_EVENTS, DEFAULT_EVENTS_REQUESTED, EVENT, RISC_EVENTS, subject_of
13
+ from .ssf.jws import verify_compact_jws
14
+ from .ssf.receiver import SignalEvent, SignalsReceiver
15
+ from .ssf.session import MemorySessionIndex, TrackedSession, tracked_from_person
16
+ from .subject import person_from
17
+ from .x509gen import create_self_signed_key_pair
18
+
19
+ __all__ = [
20
+ "CAEP_EVENTS",
21
+ "DEFAULT_ENDING_EVENTS",
22
+ "DEFAULT_EVENTS_REQUESTED",
23
+ "EVENT",
24
+ "FinishedGrant",
25
+ "GnapClient",
26
+ "GnapError",
27
+ "Grant",
28
+ "GrantResult",
29
+ "MemorySessionIndex",
30
+ "PendingGrant",
31
+ "RISC_EVENTS",
32
+ "SecurityPosture",
33
+ "SignalEvent",
34
+ "SignalsReceiver",
35
+ "TrackedSession",
36
+ "create_self_signed_key_pair",
37
+ "discover_grant_server",
38
+ "discover_open_id",
39
+ "interaction_hash",
40
+ "load_client_key",
41
+ "person_from",
42
+ "public_key_object",
43
+ "read_config_file",
44
+ "resolve_config",
45
+ "subject_of",
46
+ "tracked_from_person",
47
+ "validate_grant_server",
48
+ "verify_compact_jws",
49
+ "well_known_urls",
50
+ ]
@@ -0,0 +1,101 @@
1
+ # SPDX-FileCopyrightText: 2026 Iya CyberSecurity Solutions, LLC
2
+ # SPDX-License-Identifier: MIT
3
+
4
+ """Write a P-256 private key and self-signed certificate at the file: paths in a configuration."""
5
+
6
+ import json
7
+ import os
8
+ import sys
9
+ from pathlib import Path
10
+
11
+ from .x509gen import create_self_signed_key_pair
12
+
13
+
14
+ def _usage() -> str:
15
+ return """Usage: gnap-caep-risc generate-key --config gnap.json [--cn name] [--days 1095] [--force]
16
+
17
+ Writes a P-256 private key and a self-signed certificate at the file: paths in the configuration
18
+ (privateKey and certificate). A path that already exists is left alone unless --force is given."""
19
+
20
+
21
+ def _destination(raw, base: Path, what: str):
22
+ if not raw:
23
+ return None
24
+ if str(raw).startswith("env:"):
25
+ raise SystemExit(f"{what} is {raw}; this command only writes file: paths")
26
+ if "-----BEGIN" in str(raw):
27
+ raise SystemExit(f"{what} is inline PEM; this command only writes file: paths")
28
+ path = str(raw)[5:] if str(raw).startswith("file:") else str(raw)
29
+ return Path(path) if Path(path).is_absolute() else base / path
30
+
31
+
32
+ def main(argv=None):
33
+ argv = list(sys.argv[1:] if argv is None else argv)
34
+ if not argv or argv[0] != "generate-key":
35
+ print(_usage())
36
+ if argv:
37
+ sys.exit(1)
38
+ return
39
+ config = ""
40
+ cn = ""
41
+ days = 1095
42
+ force = False
43
+ index = 1
44
+ while index < len(argv):
45
+ arg = argv[index]
46
+ def value():
47
+ nonlocal index
48
+ index += 1
49
+ if index >= len(argv):
50
+ raise SystemExit(f"{arg} needs a value")
51
+ return argv[index]
52
+ if arg == "--config":
53
+ config = value()
54
+ elif arg == "--cn":
55
+ cn = value()
56
+ elif arg == "--days":
57
+ days = float(value())
58
+ elif arg == "--force":
59
+ force = True
60
+ elif arg in ("--help", "-h"):
61
+ print(_usage())
62
+ return
63
+ else:
64
+ raise SystemExit(f"Unknown argument {arg}\n{_usage()}")
65
+ index += 1
66
+ if not config:
67
+ raise SystemExit(f"--config is required\n{_usage()}")
68
+ if days < 1:
69
+ raise SystemExit("--days must be a positive number")
70
+ full = Path(config).resolve()
71
+ raw = json.loads(full.read_text(encoding="utf-8"))
72
+ base = full.parent
73
+ key_path = _destination(raw.get("privateKey"), base, "privateKey")
74
+ cert_path = _destination(raw.get("certificate"), base, "certificate")
75
+ if key_path is None:
76
+ raise SystemExit("the configuration has no privateKey path to write")
77
+ if not force and key_path.exists() and (cert_path is None or cert_path.exists()):
78
+ print(f"Key already at {key_path}. Pass --force to replace it.")
79
+ return
80
+ name = cn or ((raw.get("display") or {}).get("name")) or raw.get("application") or "gnap-client"
81
+ pair = create_self_signed_key_pair(name, days=int(days))
82
+ key_path.parent.mkdir(parents=True, exist_ok=True)
83
+ key_path.write_text(pair.private_key_pem, encoding="utf-8")
84
+ os.chmod(key_path, 0o600)
85
+ if cert_path:
86
+ cert_path.parent.mkdir(parents=True, exist_ok=True)
87
+ cert_path.write_text(pair.certificate_pem, encoding="utf-8")
88
+ print(f"Wrote {key_path}")
89
+ if cert_path:
90
+ print(f"Wrote {cert_path}")
91
+ print(f"sha256 {pair.fingerprint256}")
92
+
93
+
94
+ if __name__ == "__main__":
95
+ try:
96
+ main()
97
+ except SystemExit:
98
+ raise
99
+ except Exception as err:
100
+ print(str(err), file=sys.stderr)
101
+ sys.exit(1)