certgen-core 0.1.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.
- certgen_core/__init__.py +8 -0
- certgen_core/cli.py +87 -0
- certgen_core/generator.py +135 -0
- certgen_core/py.typed +0 -0
- certgen_core-0.1.0.dist-info/METADATA +68 -0
- certgen_core-0.1.0.dist-info/RECORD +9 -0
- certgen_core-0.1.0.dist-info/WHEEL +5 -0
- certgen_core-0.1.0.dist-info/entry_points.txt +2 -0
- certgen_core-0.1.0.dist-info/top_level.txt +1 -0
certgen_core/__init__.py
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
"""Generate self-signed TLS certificates from YAML configuration."""
|
|
2
|
+
|
|
3
|
+
from importlib.metadata import version
|
|
4
|
+
|
|
5
|
+
from .generator import GeneratedCertificate, generate_from_yaml
|
|
6
|
+
|
|
7
|
+
__version__ = version("certgen-core")
|
|
8
|
+
__all__ = ["GeneratedCertificate", "generate_from_yaml"]
|
certgen_core/cli.py
ADDED
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
"""Command-line entry point for cert-gen."""
|
|
2
|
+
|
|
3
|
+
import os
|
|
4
|
+
import sys
|
|
5
|
+
from argparse import ArgumentParser
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
from shutil import get_terminal_size
|
|
8
|
+
from time import sleep
|
|
9
|
+
|
|
10
|
+
from . import __version__, generate_from_yaml
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
_LOCK = (
|
|
14
|
+
" ⣀⣤⣶⣶⣤⣀",
|
|
15
|
+
" ⣼⣿⠟⠉⠉⠻⣿⣧",
|
|
16
|
+
" ⣿⣿ ⣿⣿",
|
|
17
|
+
" ⣿⣿ ⣿⣿",
|
|
18
|
+
" ⣠⣶⣿⣿⣶⣶⣶⣶⣶⣿⣿⣶⣄",
|
|
19
|
+
" ⢸⣿⣿⣿⠁⢹⣿⣿⠁⢹⣿⣿⣿⡇",
|
|
20
|
+
" ⢸⣿⣿⣿⣄⣼⣿⣿⣄⣼⣿⣿⣿⡇",
|
|
21
|
+
" ⢸⣿⣿⣿⣿⣿⡿⢿⣿⣿⣿⣿⣿⡇",
|
|
22
|
+
" ⠘⢿⣿⣿⣿⣿⣧⣼⣿⣿⣿⣿⡿⠃",
|
|
23
|
+
" ⠉⠛⠛⠛⠛⠛⠛⠛⠛⠉",
|
|
24
|
+
)
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def _show_lock_sprite() -> None:
|
|
28
|
+
message = "Wrong door! I make keys, but If you are here you have messed up!"
|
|
29
|
+
hint = "Try: cert-gen certs.yml (or cert-gen --help)"
|
|
30
|
+
if not sys.stdout.isatty() or os.environ.get("TERM") == "dumb":
|
|
31
|
+
print("\n".join((*_LOCK, "", message, hint)))
|
|
32
|
+
return
|
|
33
|
+
|
|
34
|
+
blink = (*_LOCK[:5], " ⢸⣿⣿⣿⠉⠉⣿⣿⠉⠉⣿⣿⣿⡇", " ⢸⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡇", *_LOCK[7:])
|
|
35
|
+
wink = (*_LOCK[:5], " ⢸⣿⣿⣿⠉⠉⣿⣿⠁⢹⣿⣿⣿⡇", " ⢸⣿⣿⣿⣿⣿⣿⣿⣄⣼⣿⣿⣿⡇", *_LOCK[7:])
|
|
36
|
+
width = max(map(len, _LOCK)) + 5
|
|
37
|
+
columns = get_terminal_size().columns
|
|
38
|
+
side_by_side = columns > width + len(hint)
|
|
39
|
+
caption = ("Wrong door! I make keys, but", "If you are here you have messed up!", "", hint)
|
|
40
|
+
frames = (
|
|
41
|
+
(0.00, ("", *_LOCK)),
|
|
42
|
+
(0.12, (*_LOCK, " ⠈⠁ ⠈⠁")),
|
|
43
|
+
(0.13, ("", *blink)),
|
|
44
|
+
(0.10, (" ⠈⠁ ⠈⠁", *wink)),
|
|
45
|
+
(0.18, ("", *_LOCK)),
|
|
46
|
+
)
|
|
47
|
+
for index, (pause, frame) in enumerate(frames):
|
|
48
|
+
sleep(pause)
|
|
49
|
+
if index:
|
|
50
|
+
print(f"\x1b[{len(frame)}F", end="")
|
|
51
|
+
lines = list(frame)
|
|
52
|
+
if side_by_side:
|
|
53
|
+
for row, line in enumerate(caption, start=4):
|
|
54
|
+
lines[row] = f"{lines[row]:<{width}}{line}".rstrip()
|
|
55
|
+
print("\n".join(f"\x1b[2K{line}" for line in lines), flush=True)
|
|
56
|
+
if not side_by_side:
|
|
57
|
+
print(f"\n{message}\n{hint}")
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def run(argv: list[str] | None = None) -> int:
|
|
61
|
+
"""Run the CLI and return its exit status."""
|
|
62
|
+
if argv is None:
|
|
63
|
+
argv = sys.argv[1:]
|
|
64
|
+
if not argv:
|
|
65
|
+
_show_lock_sprite()
|
|
66
|
+
return 2
|
|
67
|
+
|
|
68
|
+
parser = ArgumentParser(description="Generate self-signed TLS certificates from YAML.")
|
|
69
|
+
parser.add_argument("--version", action="version", version=__version__)
|
|
70
|
+
parser.add_argument("config", type=Path)
|
|
71
|
+
parser.add_argument("-o", "--output-dir", type=Path, default=Path("certs"))
|
|
72
|
+
args = parser.parse_args(argv)
|
|
73
|
+
try:
|
|
74
|
+
results = generate_from_yaml(args.config, args.output_dir)
|
|
75
|
+
except (OSError, ValueError) as exc:
|
|
76
|
+
parser.exit(1, f"cert-gen: {exc}\n")
|
|
77
|
+
for result in results:
|
|
78
|
+
print(f"{result.certificate_path}\n{result.private_key_path}")
|
|
79
|
+
return 0
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def main() -> int:
|
|
83
|
+
return run()
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
if __name__ == "__main__":
|
|
87
|
+
raise SystemExit(main())
|
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
"""Read certificate specifications and write PEM certificate/key pairs."""
|
|
2
|
+
|
|
3
|
+
import ipaddress
|
|
4
|
+
import os
|
|
5
|
+
import re
|
|
6
|
+
from dataclasses import dataclass
|
|
7
|
+
from datetime import UTC, datetime, timedelta
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
|
|
10
|
+
import yaml
|
|
11
|
+
from cryptography import x509
|
|
12
|
+
from cryptography.hazmat.primitives import hashes, serialization
|
|
13
|
+
from cryptography.hazmat.primitives.asymmetric import rsa
|
|
14
|
+
from cryptography.x509.oid import ExtendedKeyUsageOID, NameOID
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
@dataclass(frozen=True)
|
|
18
|
+
class GeneratedCertificate:
|
|
19
|
+
certificate_path: Path
|
|
20
|
+
private_key_path: Path
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
@dataclass(frozen=True)
|
|
24
|
+
class _CertificateSpec:
|
|
25
|
+
name: str
|
|
26
|
+
common_name: str
|
|
27
|
+
names: list[x509.GeneralName]
|
|
28
|
+
days: int
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def _parse_spec(item: object) -> _CertificateSpec:
|
|
32
|
+
fields = {"name", "common_name", "dns_names", "ip_addresses", "days"}
|
|
33
|
+
if not isinstance(item, dict) or item.keys() - fields:
|
|
34
|
+
raise ValueError("Each certificate must be a mapping with known fields")
|
|
35
|
+
|
|
36
|
+
name = item.get("name")
|
|
37
|
+
if not isinstance(name, str) or not re.fullmatch(r"[a-z0-9][a-z0-9_-]*", name):
|
|
38
|
+
raise ValueError("name must start with a lowercase letter or digit and contain only a-z, 0-9, _ or -")
|
|
39
|
+
|
|
40
|
+
common_name = item.get("common_name")
|
|
41
|
+
if not isinstance(common_name, str) or not common_name.strip():
|
|
42
|
+
raise ValueError(f"{name}: common_name must be a nonempty string")
|
|
43
|
+
|
|
44
|
+
days = item.get("days", 30)
|
|
45
|
+
if type(days) is not int or not 1 <= days <= 365:
|
|
46
|
+
raise ValueError(f"{name}: days must be an integer between 1 and 365")
|
|
47
|
+
|
|
48
|
+
names: list[x509.GeneralName] = []
|
|
49
|
+
for field in ("dns_names", "ip_addresses"):
|
|
50
|
+
values = item.get(field, [])
|
|
51
|
+
if not isinstance(values, list) or any(
|
|
52
|
+
not isinstance(value, str) or not value or value.strip() != value
|
|
53
|
+
for value in values
|
|
54
|
+
):
|
|
55
|
+
raise ValueError(f"{name}: {field} must be a list of nonempty strings")
|
|
56
|
+
for value in values:
|
|
57
|
+
if field == "dns_names":
|
|
58
|
+
labels = value.removesuffix(".").removeprefix("*.").split(".")
|
|
59
|
+
if len(value) > 253 or any(
|
|
60
|
+
not re.fullmatch(r"[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?", label)
|
|
61
|
+
for label in labels
|
|
62
|
+
):
|
|
63
|
+
raise ValueError(f"{name}: invalid DNS name {value!r}")
|
|
64
|
+
names.append(x509.DNSName(value))
|
|
65
|
+
else:
|
|
66
|
+
names.append(x509.IPAddress(ipaddress.ip_address(value)))
|
|
67
|
+
if not names:
|
|
68
|
+
raise ValueError(f"{name}: provide at least one DNS name or IP address")
|
|
69
|
+
return _CertificateSpec(name, common_name, names, days)
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def _generate(spec: _CertificateSpec) -> tuple[bytes, bytes]:
|
|
73
|
+
key = rsa.generate_private_key(public_exponent=65537, key_size=2048)
|
|
74
|
+
subject = x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, spec.common_name)])
|
|
75
|
+
now = datetime.now(UTC)
|
|
76
|
+
certificate = (
|
|
77
|
+
x509.CertificateBuilder()
|
|
78
|
+
.subject_name(subject)
|
|
79
|
+
.issuer_name(subject)
|
|
80
|
+
.public_key(key.public_key())
|
|
81
|
+
.serial_number(x509.random_serial_number())
|
|
82
|
+
.not_valid_before(now - timedelta(minutes=5))
|
|
83
|
+
.not_valid_after(now + timedelta(days=spec.days))
|
|
84
|
+
.add_extension(x509.BasicConstraints(ca=False, path_length=None), critical=True)
|
|
85
|
+
.add_extension(x509.SubjectAlternativeName(spec.names), critical=False)
|
|
86
|
+
.add_extension(x509.ExtendedKeyUsage([ExtendedKeyUsageOID.SERVER_AUTH]), critical=False)
|
|
87
|
+
.sign(key, hashes.SHA256())
|
|
88
|
+
)
|
|
89
|
+
return certificate.public_bytes(serialization.Encoding.PEM), key.private_bytes(
|
|
90
|
+
serialization.Encoding.PEM,
|
|
91
|
+
serialization.PrivateFormat.PKCS8,
|
|
92
|
+
serialization.NoEncryption(),
|
|
93
|
+
)
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def generate_from_yaml(
|
|
97
|
+
config_path: str | Path, output_dir: str | Path
|
|
98
|
+
) -> list[GeneratedCertificate]:
|
|
99
|
+
"""Generate the YAML certificates and return the paths in configuration order."""
|
|
100
|
+
try:
|
|
101
|
+
config = yaml.safe_load(Path(config_path).read_text(encoding="utf-8"))
|
|
102
|
+
except yaml.YAMLError as exc:
|
|
103
|
+
raise ValueError(f"Invalid YAML: {exc}") from exc
|
|
104
|
+
if not isinstance(config, dict) or config.keys() != {"certificates"}:
|
|
105
|
+
raise ValueError("Expected a YAML mapping with a certificates list")
|
|
106
|
+
items = config["certificates"]
|
|
107
|
+
if not isinstance(items, list) or not items:
|
|
108
|
+
raise ValueError("certificates must be a nonempty list")
|
|
109
|
+
specs = [_parse_spec(item) for item in items]
|
|
110
|
+
if len({spec.name for spec in specs}) != len(specs):
|
|
111
|
+
raise ValueError("Certificate names must be unique")
|
|
112
|
+
|
|
113
|
+
directory = Path(output_dir)
|
|
114
|
+
directory.mkdir(parents=True, exist_ok=True)
|
|
115
|
+
created: list[Path] = []
|
|
116
|
+
results: list[GeneratedCertificate] = []
|
|
117
|
+
try:
|
|
118
|
+
for spec in specs:
|
|
119
|
+
certificate, key = _generate(spec)
|
|
120
|
+
cert_path = directory / f"{spec.name}.cert.pem"
|
|
121
|
+
key_path = directory / f"{spec.name}.key.pem"
|
|
122
|
+
for path, data, mode in (
|
|
123
|
+
(key_path, key, 0o600),
|
|
124
|
+
(cert_path, certificate, 0o644),
|
|
125
|
+
):
|
|
126
|
+
fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, mode)
|
|
127
|
+
created.append(path)
|
|
128
|
+
with os.fdopen(fd, "wb") as stream:
|
|
129
|
+
stream.write(data)
|
|
130
|
+
results.append(GeneratedCertificate(cert_path, key_path))
|
|
131
|
+
except Exception:
|
|
132
|
+
for path in reversed(created):
|
|
133
|
+
path.unlink(missing_ok=True)
|
|
134
|
+
raise
|
|
135
|
+
return results
|
certgen_core/py.typed
ADDED
|
File without changes
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: certgen-core
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Generate self-signed TLS certificates from a YAML file.
|
|
5
|
+
Requires-Python: >=3.11
|
|
6
|
+
Description-Content-Type: text/markdown
|
|
7
|
+
Requires-Dist: cryptography>=42
|
|
8
|
+
Requires-Dist: PyYAML>=6
|
|
9
|
+
Provides-Extra: test
|
|
10
|
+
Requires-Dist: pytest>=8; extra == "test"
|
|
11
|
+
Provides-Extra: release
|
|
12
|
+
Requires-Dist: build>=1; extra == "release"
|
|
13
|
+
Requires-Dist: twine>=6; extra == "release"
|
|
14
|
+
|
|
15
|
+
# certgen-core
|
|
16
|
+
|
|
17
|
+
Generate self-signed X.509 TLS server certificates and matching RSA private keys from YAML. Use these certificates for local development and testing. Clients must explicitly trust them.
|
|
18
|
+
|
|
19
|
+
## Installation
|
|
20
|
+
|
|
21
|
+
With Python 3.11 or later, install from PyPI once the first release is available.
|
|
22
|
+
|
|
23
|
+
```sh
|
|
24
|
+
pip install certgen-core
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
## Generate certificates
|
|
28
|
+
|
|
29
|
+
Save this as `certs.yml`, or use [examples/localhost.yml](examples/localhost.yml).
|
|
30
|
+
|
|
31
|
+
```yaml
|
|
32
|
+
certificates:
|
|
33
|
+
- name: localhost
|
|
34
|
+
common_name: localhost
|
|
35
|
+
dns_names: [localhost]
|
|
36
|
+
ip_addresses: ["127.0.0.1", "::1"]
|
|
37
|
+
days: 30
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
```sh
|
|
41
|
+
cert-gen certs.yml --output-dir certs
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
Each entry produces `<name>.cert.pem` and `<name>.key.pem`. Use a unique lowercase filename stem and provide at least one DNS name or IP address per entry. Validity defaults to 30 days and accepts 1 through 365. The generator refuses to overwrite existing files. Private keys are unencrypted and are created with owner-only permissions on POSIX systems. Keep them out of source control.
|
|
45
|
+
|
|
46
|
+
```python
|
|
47
|
+
from certgen_core import generate_from_yaml
|
|
48
|
+
|
|
49
|
+
for result in generate_from_yaml("certs.yml", "certs"):
|
|
50
|
+
print(result.certificate_path, result.private_key_path)
|
|
51
|
+
```
|
|
52
|
+
|
|
53
|
+
## Development
|
|
54
|
+
|
|
55
|
+
```sh
|
|
56
|
+
python3.11 -m venv .venv
|
|
57
|
+
source .venv/bin/activate
|
|
58
|
+
python -m pip install -e '.[test,release]'
|
|
59
|
+
python -m pytest
|
|
60
|
+
python -m build
|
|
61
|
+
python -m twine check --strict dist/*
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
Build from a clean checkout so `dist/` contains only the intended release files.
|
|
65
|
+
|
|
66
|
+
## Releases
|
|
67
|
+
|
|
68
|
+
Set the version in `pyproject.toml`, run CI on the release commit, and publish a GitHub Release with the matching `vX.Y.Z` tag. See the [PyPI publishing guide](docs/PYPI_PUBLISHING.md) for Trusted Publisher setup and release steps.
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
certgen_core/__init__.py,sha256=dBMTvgQ1PGn9HJp5L4BS-MHczOpjzFY1m2diYTRcXTo,270
|
|
2
|
+
certgen_core/cli.py,sha256=VM_l2ZO-c5pnY8dIWd8uw7YdT-T0HAS8cwninRpRWHQ,3044
|
|
3
|
+
certgen_core/generator.py,sha256=1UYg5Y0prEmbQyorhL1db01aZdCJGs-b1lPIrE-2Hj0,5467
|
|
4
|
+
certgen_core/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
5
|
+
certgen_core-0.1.0.dist-info/METADATA,sha256=-VGIgqlMK3yLADh5lq012PSfFnv2mCHsWKJ0gtIS4eE,2152
|
|
6
|
+
certgen_core-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
7
|
+
certgen_core-0.1.0.dist-info/entry_points.txt,sha256=hxvhRLWGFadpECWzIXK6Li1LvXOTwLNaILwWi9KKceM,51
|
|
8
|
+
certgen_core-0.1.0.dist-info/top_level.txt,sha256=5C-9YfqC9jXZgQXN8U3XTzGjCNKhmkB80zx5StL9Bhw,13
|
|
9
|
+
certgen_core-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
certgen_core
|