ezcerts 1.0.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.
ezcerts/__init__.py ADDED
@@ -0,0 +1,16 @@
1
+ """A small two-tier certificate authority for mutual TLS: certificates, CRLs, the CA service
2
+ (enrollment, renewal, admin API) and nginx/compose/systemd generation. Clients use ezmtls."""
3
+
4
+ from importlib.metadata import version
5
+
6
+ from ezcerts.ca import CertificateAuthority, IssuedCertificate, Profile, RevocationReason
7
+
8
+ __version__ = version("ezcerts")
9
+
10
+ __all__ = [
11
+ "CertificateAuthority",
12
+ "IssuedCertificate",
13
+ "Profile",
14
+ "RevocationReason",
15
+ "__version__",
16
+ ]
ezcerts/_inventory.py ADDED
@@ -0,0 +1,466 @@
1
+ """SQLite record of every certificate the intermediate CA issued, and which are revoked."""
2
+
3
+ import contextlib
4
+ import datetime as dt
5
+ import json
6
+ import logging
7
+ import sqlite3
8
+ from collections.abc import Generator
9
+ from contextlib import AbstractContextManager, closing
10
+ from dataclasses import dataclass
11
+ from pathlib import Path
12
+
13
+ from ezcerts.errors import CABusyError, CAStorageError, EzcertsError
14
+ from ezmtls.errors import EzmtlsError
15
+
16
+ log = logging.getLogger(__name__)
17
+
18
+ # 1: certificates. 2: + enrollment tokens (created on open; older files are upgraded in place).
19
+ SCHEMA_VERSION = 2
20
+
21
+ _META = """
22
+ CREATE TABLE IF NOT EXISTS meta (
23
+ key TEXT PRIMARY KEY,
24
+ value TEXT NOT NULL
25
+ );
26
+ """
27
+
28
+ _SCHEMA = """
29
+ CREATE TABLE IF NOT EXISTS certificates (
30
+ serial TEXT PRIMARY KEY, -- lower-case hex
31
+ name TEXT NOT NULL,
32
+ profile TEXT NOT NULL, -- server | client
33
+ subject TEXT NOT NULL,
34
+ sans TEXT NOT NULL, -- JSON list of strings
35
+ not_before TEXT NOT NULL, -- ISO 8601, UTC
36
+ not_after TEXT NOT NULL,
37
+ current INTEGER NOT NULL, -- 1 for the certificate in issued/<name>/cert.pem
38
+ from_csr INTEGER NOT NULL, -- 1 when the requester holds the key
39
+ revoked_at TEXT,
40
+ reason TEXT
41
+ );
42
+ CREATE INDEX IF NOT EXISTS certificates_name ON certificates (name);
43
+ CREATE TABLE IF NOT EXISTS tokens (
44
+ token_hash TEXT PRIMARY KEY, -- SHA-256 of the token; the token itself is never stored
45
+ name TEXT NOT NULL,
46
+ profile TEXT NOT NULL,
47
+ sans TEXT NOT NULL, -- JSON list: the names the certificate will carry
48
+ days INTEGER NOT NULL,
49
+ created_at TEXT NOT NULL,
50
+ expires_at TEXT NOT NULL,
51
+ used_at TEXT
52
+ );
53
+ """
54
+
55
+
56
+ @dataclass(frozen=True)
57
+ class Record:
58
+ serial: int
59
+ name: str
60
+ profile: str
61
+ subject: str
62
+ sans: tuple[str, ...]
63
+ not_before: dt.datetime
64
+ not_after: dt.datetime
65
+ current: bool
66
+ from_csr: bool
67
+ revoked_at: dt.datetime | None
68
+ reason: str | None
69
+
70
+ @property
71
+ def revoked(self) -> bool:
72
+ return self.revoked_at is not None
73
+
74
+
75
+ def _ts(value: dt.datetime) -> str:
76
+ return value.astimezone(dt.UTC).isoformat()
77
+
78
+
79
+ def _from_ts(value: str) -> dt.datetime:
80
+ return dt.datetime.fromisoformat(value)
81
+
82
+
83
+ def _record(row: sqlite3.Row) -> Record:
84
+ return Record(
85
+ serial=int(row["serial"], 16),
86
+ name=row["name"],
87
+ profile=row["profile"],
88
+ subject=row["subject"],
89
+ sans=tuple(json.loads(row["sans"])),
90
+ not_before=_from_ts(row["not_before"]),
91
+ not_after=_from_ts(row["not_after"]),
92
+ current=bool(row["current"]),
93
+ from_csr=bool(row["from_csr"]),
94
+ revoked_at=_from_ts(row["revoked_at"]) if row["revoked_at"] else None,
95
+ reason=row["reason"],
96
+ )
97
+
98
+
99
+ @dataclass(frozen=True)
100
+ class TokenRecord:
101
+ name: str
102
+ profile: str
103
+ sans: tuple[str, ...]
104
+ days: int
105
+ expires_at: dt.datetime
106
+
107
+
108
+ #: Seconds a write waits for another process holding the database before giving up.
109
+ BUSY_TIMEOUT = 30.0
110
+
111
+
112
+ class Inventory:
113
+ """One connection to the inventory database. Each public method is one transaction."""
114
+
115
+ def __init__(self, conn: sqlite3.Connection, path: Path) -> None:
116
+ self._conn = conn
117
+ self.path = path
118
+ self._bulk = False
119
+
120
+ @classmethod
121
+ def open(cls, path: Path) -> tuple["Inventory", Path | None]:
122
+ """Open (creating if needed) the inventory.
123
+
124
+ A file that is not a readable inventory is renamed aside and a fresh one is created; the
125
+ second value is then the path it was moved to, so the caller can rebuild the records.
126
+ """
127
+ try:
128
+ return cls._connect(path), None
129
+ except sqlite3.DatabaseError as exc:
130
+ if not _is_damage(exc):
131
+ # Locked by another process, read-only, disk full: not corruption. Moving the file
132
+ # aside would lose its records (or, under a running service, split them in two).
133
+ raise _usable_error(exc, path) from exc
134
+ stamp = dt.datetime.now(dt.UTC).strftime("%Y%m%dT%H%M%S%fZ")
135
+ aside = path.with_name(f"{path.name}.corrupt-{stamp}")
136
+ path.replace(aside)
137
+ log.warning("inventory %s was unreadable (%s); moved to %s", path, exc, aside)
138
+ return cls._connect(path), aside
139
+
140
+ @classmethod
141
+ def _connect(cls, path: Path) -> "Inventory":
142
+ conn = sqlite3.connect(path, timeout=BUSY_TIMEOUT, isolation_level=None)
143
+ try:
144
+ conn.row_factory = sqlite3.Row
145
+ if conn.execute("PRAGMA quick_check").fetchone()[0] != "ok":
146
+ raise _Damaged("integrity check failed")
147
+ conn.executescript(_META)
148
+ with closing(conn.execute("SELECT value FROM meta WHERE key = 'schema'")) as cur:
149
+ row = cur.fetchone()
150
+ if row is not None and int(row[0]) > SCHEMA_VERSION:
151
+ # Not corruption: written by a newer version. Never move it aside or change it.
152
+ raise EzcertsError(
153
+ f"{path} uses inventory format {row[0]}; this version of ezcerts"
154
+ f" understands format {SCHEMA_VERSION}: upgrade ezcerts"
155
+ )
156
+ conn.executescript(_SCHEMA)
157
+ conn.execute(
158
+ "INSERT INTO meta (key, value) VALUES ('schema', ?)"
159
+ " ON CONFLICT(key) DO UPDATE SET value = excluded.value",
160
+ (str(SCHEMA_VERSION),),
161
+ )
162
+ except BaseException:
163
+ conn.close()
164
+ raise
165
+ return cls(conn, path)
166
+
167
+ def close(self) -> None:
168
+ self._conn.close()
169
+
170
+ def reopen(self) -> None:
171
+ """Replace the connection with a fresh one to the same file, between transactions.
172
+
173
+ File sharing that caches open files (Docker Desktop for Mac, seen 2026-12-02) can keep
174
+ showing a long-lived connection the file as it was, hiding what other processes wrote. A
175
+ fresh open reads it anew. The file must exist (`mode=rw`): a deleted inventory is an error
176
+ here, never silently recreated empty; on any failure the current connection stays.
177
+ """
178
+ uri = self.path.absolute().as_uri()
179
+ if not uri.startswith("file:///"):
180
+ # A Windows network share, file://server/share: SQLite takes the server only as path.
181
+ uri = "file://" + uri.removeprefix("file:")
182
+ conn = sqlite3.connect(
183
+ uri + "?mode=rw",
184
+ uri=True,
185
+ timeout=BUSY_TIMEOUT,
186
+ isolation_level=None,
187
+ )
188
+ conn.row_factory = sqlite3.Row
189
+ old, self._conn = self._conn, conn
190
+ old.close()
191
+
192
+ def _tx(self) -> AbstractContextManager[None]:
193
+ # Inside `rebuilding()` every write joins the one rebuild transaction.
194
+ return contextlib.nullcontext() if self._bulk else _Transaction(self._conn)
195
+
196
+ def is_complete(self) -> bool:
197
+ """Whether this inventory was fully written by `init` or a rebuild (see `mark_complete`).
198
+
199
+ A zero-byte or schema-less file, or a rebuild that never finished, lacks the mark.
200
+ """
201
+ row = self._conn.execute("SELECT value FROM meta WHERE key = 'complete'").fetchone()
202
+ return row is not None and row[0] == "1"
203
+
204
+ def mark_complete(self) -> None:
205
+ with self._tx():
206
+ self._conn.execute(
207
+ "INSERT INTO meta (key, value) VALUES ('complete', '1')"
208
+ " ON CONFLICT(key) DO UPDATE SET value = excluded.value"
209
+ )
210
+
211
+ @contextlib.contextmanager
212
+ def rebuilding(self) -> Generator[None]:
213
+ """One transaction for a whole rebuild, marked complete at the end: a rebuild that fails
214
+ halfway leaves nothing behind, so the next open starts it again."""
215
+ with _Transaction(self._conn):
216
+ self._bulk = True
217
+ try:
218
+ yield
219
+ self.mark_complete()
220
+ finally:
221
+ self._bulk = False
222
+
223
+ def add(
224
+ self,
225
+ *,
226
+ serial: int,
227
+ name: str,
228
+ profile: str,
229
+ subject: str,
230
+ sans: list[str],
231
+ not_before: dt.datetime,
232
+ not_after: dt.datetime,
233
+ from_csr: bool,
234
+ current: bool = True,
235
+ revoked_at: dt.datetime | None = None,
236
+ reason: str | None = None,
237
+ ) -> None:
238
+ """Record a new certificate. A current one replaces the name's previous current one."""
239
+ with self._tx():
240
+ if current:
241
+ self._conn.execute("UPDATE certificates SET current = 0 WHERE name = ?", (name,))
242
+ self._conn.execute(
243
+ "INSERT INTO certificates (serial, name, profile, subject, sans, not_before,"
244
+ " not_after, current, from_csr, revoked_at, reason)"
245
+ " VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
246
+ (
247
+ format(serial, "x"),
248
+ name,
249
+ profile,
250
+ subject,
251
+ json.dumps(sans),
252
+ _ts(not_before),
253
+ _ts(not_after),
254
+ int(current),
255
+ int(from_csr),
256
+ _ts(revoked_at) if revoked_at else None,
257
+ reason,
258
+ ),
259
+ )
260
+
261
+ def current(self, name: str) -> Record | None:
262
+ row = self._conn.execute(
263
+ "SELECT * FROM certificates WHERE name = ? AND current = 1", (name,)
264
+ ).fetchone()
265
+ return _record(row) if row else None
266
+
267
+ def by_serial(self, serial: int) -> Record | None:
268
+ row = self._conn.execute(
269
+ "SELECT * FROM certificates WHERE serial = ?", (format(serial, "x"),)
270
+ ).fetchone()
271
+ return _record(row) if row else None
272
+
273
+ def require(self, serial: int) -> Record:
274
+ record = self.by_serial(serial)
275
+ if record is None:
276
+ raise LookupError(f"serial {serial:x} is not in the inventory")
277
+ return record
278
+
279
+ def name_ignoring_case(self, name: str) -> str | None:
280
+ """Another stored name equal to `name` when case is ignored (folders on Windows and
281
+ macOS ignore case), or None."""
282
+ row = self._conn.execute(
283
+ "SELECT name FROM certificates WHERE lower(name) = lower(?) AND name != ? LIMIT 1",
284
+ (name, name),
285
+ ).fetchone()
286
+ return str(row[0]) if row else None
287
+
288
+ def name_exists(self, name: str) -> bool:
289
+ row = self._conn.execute("SELECT 1 FROM certificates WHERE name = ?", (name,)).fetchone()
290
+ return row is not None
291
+
292
+ def all(self) -> list[Record]:
293
+ rows = self._conn.execute("SELECT * FROM certificates ORDER BY name, not_before").fetchall()
294
+ return [_record(r) for r in rows]
295
+
296
+ def revoked(self) -> list[Record]:
297
+ rows = self._conn.execute(
298
+ "SELECT * FROM certificates WHERE revoked_at IS NOT NULL ORDER BY revoked_at"
299
+ ).fetchall()
300
+ return [_record(r) for r in rows]
301
+
302
+ def revoke(self, serial: int, at: dt.datetime, reason: str) -> bool:
303
+ """Mark a certificate revoked. Returns False if it already was."""
304
+ with self._tx():
305
+ cur = self._conn.execute(
306
+ "UPDATE certificates SET revoked_at = ?, reason = ?"
307
+ " WHERE serial = ? AND revoked_at IS NULL",
308
+ (_ts(at), reason, format(serial, "x")),
309
+ )
310
+ return cur.rowcount == 1
311
+
312
+ def add_token(
313
+ self,
314
+ *,
315
+ token_hash: str,
316
+ name: str,
317
+ profile: str,
318
+ sans: list[str],
319
+ days: int,
320
+ created_at: dt.datetime,
321
+ expires_at: dt.datetime,
322
+ ) -> None:
323
+ with self._tx():
324
+ self._conn.execute(
325
+ "INSERT INTO tokens (token_hash, name, profile, sans, days, created_at, expires_at)"
326
+ " VALUES (?, ?, ?, ?, ?, ?, ?)",
327
+ (
328
+ token_hash,
329
+ name,
330
+ profile,
331
+ json.dumps(sans),
332
+ days,
333
+ _ts(created_at),
334
+ _ts(expires_at),
335
+ ),
336
+ )
337
+
338
+ def release_token(self, token_hash: str) -> None:
339
+ """Make a taken token usable again (its enrollment failed)."""
340
+ with self._tx():
341
+ self._conn.execute(
342
+ "UPDATE tokens SET used_at = NULL WHERE token_hash = ?", (token_hash,)
343
+ )
344
+
345
+ def take_token(self, token_hash: str, at: dt.datetime) -> TokenRecord | None:
346
+ """Mark an unused, unexpired token used and return it, in one transaction (single use)."""
347
+ with self._tx():
348
+ row = self._conn.execute(
349
+ "SELECT * FROM tokens WHERE token_hash = ? AND used_at IS NULL AND expires_at > ?",
350
+ (token_hash, _ts(at)),
351
+ ).fetchone()
352
+ if row is None:
353
+ return None
354
+ self._conn.execute(
355
+ "UPDATE tokens SET used_at = ? WHERE token_hash = ?", (_ts(at), token_hash)
356
+ )
357
+ return TokenRecord(
358
+ name=row["name"],
359
+ profile=row["profile"],
360
+ sans=tuple(json.loads(row["sans"])),
361
+ days=int(row["days"]),
362
+ expires_at=_from_ts(row["expires_at"]),
363
+ )
364
+
365
+ def used_token(self, token_hash: str, at: dt.datetime) -> TokenRecord | None:
366
+ """A token already used but not yet expired (an enrollment asked for again)."""
367
+ row = self._conn.execute(
368
+ "SELECT * FROM tokens WHERE token_hash = ? AND used_at IS NOT NULL AND expires_at > ?",
369
+ (token_hash, _ts(at)),
370
+ ).fetchone()
371
+ if row is None:
372
+ return None
373
+ return TokenRecord(
374
+ name=row["name"],
375
+ profile=row["profile"],
376
+ sans=tuple(json.loads(row["sans"])),
377
+ days=int(row["days"]),
378
+ expires_at=_from_ts(row["expires_at"]),
379
+ )
380
+
381
+ def open_token_for(self, name: str, at: dt.datetime) -> bool:
382
+ row = self._conn.execute(
383
+ "SELECT 1 FROM tokens WHERE name = ? AND used_at IS NULL AND expires_at > ?",
384
+ (name, _ts(at)),
385
+ ).fetchone()
386
+ return row is not None
387
+
388
+ def next_crl_number(self) -> int:
389
+ """Increment and return the CRL number (RFC 5280 requires it to grow with each CRL)."""
390
+ with self._tx():
391
+ row = self._conn.execute("SELECT value FROM meta WHERE key = 'crl_number'").fetchone()
392
+ number = int(row[0]) + 1 if row else 1
393
+ self._conn.execute(
394
+ "INSERT INTO meta (key, value) VALUES ('crl_number', ?)"
395
+ " ON CONFLICT(key) DO UPDATE SET value = excluded.value",
396
+ (str(number),),
397
+ )
398
+ return number
399
+
400
+ def set_crl_number_at_least(self, number: int) -> None:
401
+ with self._tx():
402
+ row = self._conn.execute("SELECT value FROM meta WHERE key = 'crl_number'").fetchone()
403
+ if row is None or int(row[0]) < number:
404
+ self._conn.execute(
405
+ "INSERT INTO meta (key, value) VALUES ('crl_number', ?)"
406
+ " ON CONFLICT(key) DO UPDATE SET value = excluded.value",
407
+ (str(number),),
408
+ )
409
+
410
+
411
+ class _Transaction:
412
+ """BEGIN IMMEDIATE ... COMMIT/ROLLBACK, so concurrent writers queue instead of racing."""
413
+
414
+ def __init__(self, conn: sqlite3.Connection) -> None:
415
+ self._conn = conn
416
+
417
+ def __enter__(self) -> None:
418
+ try:
419
+ self._conn.execute("BEGIN IMMEDIATE")
420
+ except sqlite3.OperationalError as exc:
421
+ raise _usable_error(exc, None) from exc
422
+
423
+ def __exit__(self, exc_type: type[BaseException] | None, *_: object) -> None:
424
+ if exc_type is not None:
425
+ if self._conn.in_transaction:
426
+ self._conn.execute("ROLLBACK")
427
+ return
428
+ try:
429
+ self._conn.execute("COMMIT")
430
+ except sqlite3.Error as exc:
431
+ # A failed COMMIT leaves the transaction open: every later write would fail with
432
+ # "cannot start a transaction within a transaction". Roll back, then report it.
433
+ if self._conn.in_transaction:
434
+ with contextlib.suppress(sqlite3.Error):
435
+ self._conn.execute("ROLLBACK")
436
+ raise _usable_error(exc, None) from exc
437
+
438
+
439
+ class _Damaged(sqlite3.DatabaseError):
440
+ """The file is not a sound SQLite database (as opposed to busy or read-only)."""
441
+
442
+
443
+ def _is_damage(exc: sqlite3.DatabaseError) -> bool:
444
+ if isinstance(exc, _Damaged):
445
+ return True
446
+ code = getattr(exc, "sqlite_errorcode", None)
447
+ if code is None:
448
+ return not isinstance(exc, sqlite3.OperationalError)
449
+ return code & 0xFF in (sqlite3.SQLITE_CORRUPT, sqlite3.SQLITE_NOTADB)
450
+
451
+
452
+ def _usable_error(exc: sqlite3.Error, path: Path | None) -> EzmtlsError:
453
+ """A message for an inventory that works but cannot be used right now: busy (try again) or a
454
+ storage problem on this host, never the requester's fault."""
455
+ where = f"the inventory {path}" if path is not None else "the inventory"
456
+ code = getattr(exc, "sqlite_errorcode", 0) & 0xFF
457
+ if code in (sqlite3.SQLITE_BUSY, sqlite3.SQLITE_LOCKED):
458
+ return CABusyError(
459
+ f"{where} is locked by another process (another ezcerts command, the CA service, or a"
460
+ " backup); try again"
461
+ )
462
+ if code == sqlite3.SQLITE_READONLY:
463
+ return CAStorageError(f"{where} is read-only: give the CA's owner write permission")
464
+ if code == sqlite3.SQLITE_FULL:
465
+ return CAStorageError(f"{where} could not be written: the disk is full")
466
+ return CAStorageError(f"{where} could not be used: {exc}")
ezcerts/_lock.py ADDED
@@ -0,0 +1,104 @@
1
+ """An exclusive lock on a CA folder, shared by every ezcerts process using it.
2
+
3
+ The CLI and the CA service (or two CLIs) can work on one CA at once. Each operation that changes the
4
+ CA (issue, renew, revoke, publish a CRL, tokens, rebuilding the inventory) holds this lock, so the
5
+ "does the name exist" check, the files and the inventory row of one operation cannot interleave
6
+ with another's, and a CRL cannot be overwritten by an older one.
7
+
8
+ It is an OS file lock on `.ezcerts.lock` in the CA folder (`fcntl.flock` on POSIX, `msvcrt.locking`
9
+ on Windows): released by the OS if the process dies. Within one CA object it is reentrant, because
10
+ operations call each other (revoke publishes a CRL). Locks may not work across Docker Desktop's
11
+ shared folders (a VM in between).
12
+ """
13
+
14
+ import os
15
+ import time
16
+ from pathlib import Path
17
+ from types import TracebackType
18
+ from typing import IO
19
+
20
+ from ezcerts.errors import CABusyError
21
+
22
+ #: Seconds an operation waits for another process to finish with the CA before giving up.
23
+ LOCK_TIMEOUT = 30.0
24
+ _POLL = 0.05
25
+
26
+ LOCK_FILE = ".ezcerts.lock"
27
+
28
+
29
+ class CALock:
30
+ def __init__(self, home: Path) -> None:
31
+ self.path = home / LOCK_FILE
32
+ self._file: IO[bytes] | None = None
33
+ self._depth = 0
34
+
35
+ def __enter__(self) -> None:
36
+ if self._depth == 0:
37
+ self._acquire()
38
+ self._depth += 1
39
+
40
+ def __exit__(
41
+ self,
42
+ exc_type: type[BaseException] | None,
43
+ exc: BaseException | None,
44
+ tb: TracebackType | None,
45
+ ) -> None:
46
+ self._depth -= 1
47
+ if self._depth == 0:
48
+ self._release()
49
+
50
+ def _acquire(self) -> None:
51
+ handle = self.path.open("a+b")
52
+ try:
53
+ if handle.seek(0, os.SEEK_END) == 0:
54
+ handle.write(b"\0") # Windows locks a byte range: make sure there is a byte
55
+ handle.flush()
56
+ deadline = time.monotonic() + LOCK_TIMEOUT
57
+ while not _try_lock(handle):
58
+ if time.monotonic() >= deadline:
59
+ raise CABusyError(
60
+ f"the CA folder is in use by another ezcerts process (the CA service or"
61
+ f" another command) for over {LOCK_TIMEOUT:g} s; try again"
62
+ )
63
+ time.sleep(_POLL)
64
+ except BaseException:
65
+ handle.close()
66
+ raise
67
+ self._file = handle
68
+
69
+ def _release(self) -> None:
70
+ handle, self._file = self._file, None
71
+ if handle is not None:
72
+ try:
73
+ _unlock(handle)
74
+ finally:
75
+ handle.close()
76
+
77
+
78
+ if os.name == "nt":
79
+ import msvcrt
80
+
81
+ def _try_lock(handle: IO[bytes]) -> bool:
82
+ handle.seek(0)
83
+ try:
84
+ msvcrt.locking(handle.fileno(), msvcrt.LK_NBLCK, 1)
85
+ except OSError:
86
+ return False
87
+ return True
88
+
89
+ def _unlock(handle: IO[bytes]) -> None:
90
+ handle.seek(0)
91
+ msvcrt.locking(handle.fileno(), msvcrt.LK_UNLCK, 1)
92
+
93
+ else:
94
+ import fcntl
95
+
96
+ def _try_lock(handle: IO[bytes]) -> bool:
97
+ try:
98
+ fcntl.flock(handle.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)
99
+ except BlockingIOError:
100
+ return False
101
+ return True
102
+
103
+ def _unlock(handle: IO[bytes]) -> None:
104
+ fcntl.flock(handle.fileno(), fcntl.LOCK_UN)