tiny-ca-gateway 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.
@@ -0,0 +1,79 @@
1
+ """
2
+ models/settings.py — application settings via pydantic-settings.
3
+
4
+ All fields can be overridden with environment variables or a .env file.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ from datetime import datetime
10
+ from pathlib import Path
11
+ import warnings
12
+
13
+ from pydantic import Field
14
+ from pydantic_settings import BaseSettings, SettingsConfigDict
15
+
16
+
17
+ class ApiSettings(BaseSettings):
18
+ model_config = SettingsConfigDict(
19
+ env_file=".env",
20
+ env_file_encoding="utf-8",
21
+ case_sensitive=False,
22
+ extra="ignore",
23
+ )
24
+
25
+ debug: bool = False
26
+
27
+ # ------------------------------------------------------------------
28
+ # Storage paths
29
+ # ------------------------------------------------------------------
30
+ # Base folder for ALL certificates. CA cert lives in a sub-folder
31
+ # created by tiny_ca storage; its exact UUID path is tracked by the DB.
32
+ path_to_certificates_folder: str = "./certs"
33
+
34
+ # Resolved at runtime from the DB / scan — overridable via env for
35
+ # fixed-path deployments.
36
+ path_to_ca_cer: str = Field(default="certs/ca.pem", alias="CA_CER")
37
+ path_to_ca_key: str = Field(default="certs/ca.key", alias="CA_KEY")
38
+ path_to_crl: str = "./certs/crl.pem"
39
+
40
+ # ------------------------------------------------------------------
41
+ # Auth tokens
42
+ # ------------------------------------------------------------------
43
+ api_token: str = "changeme"
44
+ internal_temporary_token: str = "changeme2"
45
+
46
+ # ------------------------------------------------------------------
47
+ # Token TTL
48
+ # ------------------------------------------------------------------
49
+ internal_token_valid_until: str | datetime | None = None
50
+ ttl_token: int = 30 # minutes
51
+
52
+ # ------------------------------------------------------------------
53
+ # Database
54
+ # ------------------------------------------------------------------
55
+ db_url: str = Field("sqlite+aiosqlite:///ca_demo_repository.db", alias="DB_URL_CA")
56
+ db_url_sync: str = Field("sqlite:///ca_demo_repository.db", alias="DB_URL_CA_SYNC")
57
+
58
+ # ------------------------------------------------------------------
59
+ # Misc
60
+ # ------------------------------------------------------------------
61
+ datetime_fmt: str = "%Y-%m-%d %H:%M:%S"
62
+ cors_origins: list[str] = []
63
+
64
+ def model_post_init(self, __context: object) -> None: # noqa: D401
65
+ if self.api_token in ("changeme", "secret"):
66
+ warnings.warn(
67
+ "API_TOKEN is set to a default value — change it before deploying.",
68
+ UserWarning,
69
+ stacklevel=2,
70
+ )
71
+ if self.internal_temporary_token in ("changeme2", "secret2"):
72
+ warnings.warn(
73
+ "INTERNAL_TEMPORARY_TOKEN is set to a default value — change it before deploying.",
74
+ UserWarning,
75
+ stacklevel=2,
76
+ )
77
+
78
+
79
+ API_SETTINGS = ApiSettings()
@@ -0,0 +1,536 @@
1
+ from __future__ import annotations
2
+
3
+ from typing import Any
4
+
5
+
6
+ def build_openapi_schema(
7
+ title: str = "Tiny CA API", version: str = "1.0"
8
+ ) -> dict[str, Any]:
9
+ import json
10
+
11
+ from pydantic import TypeAdapter
12
+
13
+ from tiny_ca_gateway.core.schemas import (
14
+ CertListItem,
15
+ ChainResponse,
16
+ CosignRequest,
17
+ CosignResponse,
18
+ CreateRootCaResponse,
19
+ CRLRefreshResponse,
20
+ CRLVerifyRequest,
21
+ DeleteResponse,
22
+ ExpiringResponse,
23
+ ExportP12Request,
24
+ IntermediateCARequest,
25
+ IssueCertRequest,
26
+ IssueCertResponse,
27
+ MaintenanceResponse,
28
+ RenewRequest,
29
+ RenewResponse,
30
+ RevokeRequest,
31
+ RevokeResponse,
32
+ RotateResponse,
33
+ StatusResponse,
34
+ VerifyRequest,
35
+ VerifyResponse,
36
+ )
37
+
38
+ def schema(model: Any) -> dict[str, Any]:
39
+ return TypeAdapter(model).json_schema()
40
+
41
+ all_models = [
42
+ CertListItem,
43
+ ExpiringResponse,
44
+ CreateRootCaResponse,
45
+ IssueCertResponse,
46
+ MaintenanceResponse,
47
+ VerifyResponse,
48
+ CRLRefreshResponse,
49
+ RevokeResponse,
50
+ DeleteResponse,
51
+ StatusResponse,
52
+ RenewResponse,
53
+ CosignResponse,
54
+ ChainResponse,
55
+ RotateResponse,
56
+ IntermediateCARequest,
57
+ IssueCertRequest,
58
+ CRLVerifyRequest,
59
+ VerifyRequest,
60
+ CosignRequest,
61
+ ExportP12Request,
62
+ RevokeRequest,
63
+ RenewRequest,
64
+ ]
65
+
66
+ components: dict[str, Any] = {}
67
+ for m in all_models:
68
+ s = schema(m)
69
+ components[m.__name__] = s
70
+
71
+ def ref(name: str) -> dict[str, Any]:
72
+ return {"$ref": f"#/components/schemas/{name}"}
73
+
74
+ def body(name: str) -> dict[str, Any]:
75
+ return {
76
+ "requestBody": {
77
+ "required": True,
78
+ "content": {"application/json": {"schema": ref(name)}},
79
+ }
80
+ }
81
+
82
+ def resp(name: str, status: int = 200) -> dict[str, Any]:
83
+ return {
84
+ str(status): {
85
+ "description": "OK",
86
+ "content": {"application/json": {"schema": ref(name)}},
87
+ },
88
+ "4XX": {
89
+ "description": "Client error",
90
+ "content": {
91
+ "application/json": {
92
+ "schema": {"$ref": "#/components/schemas/ErrorDetail"}
93
+ }
94
+ },
95
+ },
96
+ }
97
+
98
+ def resp_raw(description: str = "Binary file") -> dict[str, Any]:
99
+ return {
100
+ "200": {
101
+ "description": description,
102
+ "content": {
103
+ "application/x-pem-file": {
104
+ "schema": {"type": "string", "format": "binary"}
105
+ }
106
+ },
107
+ }
108
+ }
109
+
110
+ bearer: list[dict[str, Any]] = [{"BearerAuth": []}]
111
+
112
+ paths: dict[str, Any] = {
113
+ # ------------------------------------------------------------------
114
+ # Public
115
+ # ------------------------------------------------------------------
116
+ "/api/v1/ca/cert": {
117
+ "get": {
118
+ "tags": ["Public"],
119
+ "summary": "Download CA public certificate",
120
+ "responses": resp_raw("PEM certificate"),
121
+ }
122
+ },
123
+ "/api/v1/ca/crl": {
124
+ "get": {
125
+ "tags": ["Public"],
126
+ "summary": "Download CRL",
127
+ "parameters": [
128
+ {
129
+ "name": "pem",
130
+ "in": "query",
131
+ "schema": {"type": "boolean", "default": False},
132
+ }
133
+ ],
134
+ "responses": resp_raw("CRL file"),
135
+ }
136
+ },
137
+ # ------------------------------------------------------------------
138
+ # List
139
+ # ------------------------------------------------------------------
140
+ "/api/v1/ca/": {
141
+ "get": {
142
+ "tags": ["Certificates"],
143
+ "summary": "List certificates",
144
+ "security": bearer,
145
+ "parameters": [
146
+ {
147
+ "name": "status",
148
+ "in": "query",
149
+ "schema": {
150
+ "type": "string",
151
+ "enum": ["valid", "revoked", "expired"],
152
+ },
153
+ },
154
+ {"name": "key_type", "in": "query", "schema": {"type": "string"}},
155
+ {
156
+ "name": "limit",
157
+ "in": "query",
158
+ "schema": {
159
+ "type": "integer",
160
+ "default": 100,
161
+ "minimum": 1,
162
+ "maximum": 1000,
163
+ },
164
+ },
165
+ {
166
+ "name": "offset",
167
+ "in": "query",
168
+ "schema": {"type": "integer", "default": 0, "minimum": 0},
169
+ },
170
+ ],
171
+ "responses": {
172
+ "200": {
173
+ "description": "OK",
174
+ "content": {
175
+ "application/json": {
176
+ "schema": {
177
+ "type": "array",
178
+ "items": ref("CertListItem"),
179
+ }
180
+ }
181
+ },
182
+ }
183
+ },
184
+ }
185
+ },
186
+ "/api/v1/ca/expiring": {
187
+ "get": {
188
+ "tags": ["Certificates"],
189
+ "summary": "Certificates expiring soon",
190
+ "security": bearer,
191
+ "parameters": [
192
+ {
193
+ "name": "within_days",
194
+ "in": "query",
195
+ "schema": {
196
+ "type": "integer",
197
+ "default": 30,
198
+ "minimum": 1,
199
+ "maximum": 365,
200
+ },
201
+ }
202
+ ],
203
+ "responses": resp("ExpiringResponse"),
204
+ }
205
+ },
206
+ # ------------------------------------------------------------------
207
+ # CA bootstrap
208
+ # ------------------------------------------------------------------
209
+ "/api/v1/ca/root": {
210
+ "post": {
211
+ "tags": ["CA Bootstrap"],
212
+ "summary": "Bootstrap self-signed root CA",
213
+ "security": bearer,
214
+ **body("CreateRootCaResponse"), # reuse — CAConfig not in schemas
215
+ "responses": resp("CreateRootCaResponse"),
216
+ }
217
+ },
218
+ "/api/v1/ca/intermediate": {
219
+ "post": {
220
+ "tags": ["CA Bootstrap"],
221
+ "summary": "Issue intermediate CA",
222
+ "security": bearer,
223
+ **body("IntermediateCARequest"),
224
+ "responses": resp("IssueCertResponse"),
225
+ }
226
+ },
227
+ # ------------------------------------------------------------------
228
+ # Issuance
229
+ # ------------------------------------------------------------------
230
+ "/api/v1/ca/issue": {
231
+ "post": {
232
+ "tags": ["Issuance"],
233
+ "summary": "Issue leaf certificate",
234
+ "security": bearer,
235
+ **body("IssueCertRequest"),
236
+ "responses": resp("IssueCertResponse", 201),
237
+ }
238
+ },
239
+ # ------------------------------------------------------------------
240
+ # Maintenance
241
+ # ------------------------------------------------------------------
242
+ "/api/v1/ca/maintenance/expire": {
243
+ "post": {
244
+ "tags": ["Maintenance"],
245
+ "summary": "Bulk-mark expired certificates",
246
+ "security": bearer,
247
+ "responses": resp("MaintenanceResponse"),
248
+ }
249
+ },
250
+ # ------------------------------------------------------------------
251
+ # CRL
252
+ # ------------------------------------------------------------------
253
+ "/api/v1/ca/crl/refresh": {
254
+ "post": {
255
+ "tags": ["CRL"],
256
+ "summary": "Force-regenerate CRL",
257
+ "security": bearer,
258
+ "responses": resp("CRLRefreshResponse"),
259
+ }
260
+ },
261
+ "/api/v1/ca/crl/verify": {
262
+ "post": {
263
+ "tags": ["CRL"],
264
+ "summary": "Verify CRL signature",
265
+ "security": bearer,
266
+ **body("CRLVerifyRequest"),
267
+ "responses": resp("VerifyResponse"),
268
+ }
269
+ },
270
+ # ------------------------------------------------------------------
271
+ # Verification
272
+ # ------------------------------------------------------------------
273
+ "/api/v1/ca/verify": {
274
+ "post": {
275
+ "tags": ["Verification"],
276
+ "summary": "Verify certificate (chain + revocation)",
277
+ "security": bearer,
278
+ **body("VerifyRequest"),
279
+ "responses": resp("VerifyResponse"),
280
+ }
281
+ },
282
+ "/api/v1/ca/cosign": {
283
+ "post": {
284
+ "tags": ["Verification"],
285
+ "summary": "Co-sign a third-party certificate",
286
+ "security": bearer,
287
+ **body("CosignRequest"),
288
+ "responses": resp("CosignResponse"),
289
+ }
290
+ },
291
+ # ------------------------------------------------------------------
292
+ # Export
293
+ # ------------------------------------------------------------------
294
+ "/api/v1/ca/export-p12/{serial}": {
295
+ "post": {
296
+ "tags": ["Export"],
297
+ "summary": "Export PKCS#12 (.p12) bundle",
298
+ "security": bearer,
299
+ "parameters": [
300
+ {
301
+ "name": "serial",
302
+ "in": "path",
303
+ "required": True,
304
+ "schema": {"type": "integer"},
305
+ }
306
+ ],
307
+ **body("ExportP12Request"),
308
+ "responses": {
309
+ "200": {
310
+ "description": "PKCS#12 binary",
311
+ "content": {
312
+ "application/x-pkcs12": {
313
+ "schema": {"type": "string", "format": "binary"}
314
+ }
315
+ },
316
+ }
317
+ },
318
+ }
319
+ },
320
+ # ------------------------------------------------------------------
321
+ # Mutations
322
+ # ------------------------------------------------------------------
323
+ "/api/v1/ca/revoke": {
324
+ "patch": {
325
+ "tags": ["Mutations"],
326
+ "summary": "Revoke a certificate",
327
+ "security": bearer,
328
+ **body("RevokeRequest"),
329
+ "responses": resp("RevokeResponse"),
330
+ }
331
+ },
332
+ "/api/v1/ca/rotate/{serial}": {
333
+ "post": {
334
+ "tags": ["Mutations"],
335
+ "summary": "Rotate certificate (revoke + re-issue)",
336
+ "security": bearer,
337
+ "parameters": [
338
+ {
339
+ "name": "serial",
340
+ "in": "path",
341
+ "required": True,
342
+ "schema": {"type": "integer"},
343
+ }
344
+ ],
345
+ **body("IssueCertRequest"),
346
+ "responses": resp("RotateResponse"),
347
+ }
348
+ },
349
+ "/api/v1/ca/renew/{serial}": {
350
+ "post": {
351
+ "tags": ["Mutations"],
352
+ "summary": "Renew certificate (same key, new validity)",
353
+ "security": bearer,
354
+ "parameters": [
355
+ {
356
+ "name": "serial",
357
+ "in": "path",
358
+ "required": True,
359
+ "schema": {"type": "integer"},
360
+ }
361
+ ],
362
+ **body("RenewRequest"),
363
+ "responses": resp("RenewResponse"),
364
+ }
365
+ },
366
+ "/api/v1/ca/{serial}": {
367
+ "delete": {
368
+ "tags": ["Mutations"],
369
+ "summary": "Hard-delete certificate",
370
+ "security": bearer,
371
+ "parameters": [
372
+ {
373
+ "name": "serial",
374
+ "in": "path",
375
+ "required": True,
376
+ "schema": {"type": "integer"},
377
+ }
378
+ ],
379
+ "responses": resp("DeleteResponse"),
380
+ }
381
+ },
382
+ # ------------------------------------------------------------------
383
+ # Inspection
384
+ # ------------------------------------------------------------------
385
+ "/api/v1/ca/status/{serial}": {
386
+ "get": {
387
+ "tags": ["Inspection"],
388
+ "summary": "Get lifecycle status",
389
+ "security": bearer,
390
+ "parameters": [
391
+ {
392
+ "name": "serial",
393
+ "in": "path",
394
+ "required": True,
395
+ "schema": {"type": "integer"},
396
+ }
397
+ ],
398
+ "responses": resp("StatusResponse"),
399
+ }
400
+ },
401
+ "/api/v1/ca/inspect/{serial}": {
402
+ "get": {
403
+ "tags": ["Inspection"],
404
+ "summary": "Structured certificate details",
405
+ "security": bearer,
406
+ "parameters": [
407
+ {
408
+ "name": "serial",
409
+ "in": "path",
410
+ "required": True,
411
+ "schema": {"type": "integer"},
412
+ }
413
+ ],
414
+ "responses": {
415
+ "200": {
416
+ "description": "Certificate details",
417
+ "content": {"application/json": {"schema": {"type": "object"}}},
418
+ }
419
+ },
420
+ }
421
+ },
422
+ "/api/v1/ca/chain/{serial}": {
423
+ "get": {
424
+ "tags": ["Inspection"],
425
+ "summary": "Full PEM certificate chain",
426
+ "security": bearer,
427
+ "parameters": [
428
+ {
429
+ "name": "serial",
430
+ "in": "path",
431
+ "required": True,
432
+ "schema": {"type": "integer"},
433
+ }
434
+ ],
435
+ "responses": resp("ChainResponse"),
436
+ }
437
+ },
438
+ # ------------------------------------------------------------------
439
+ # File downloads
440
+ # ------------------------------------------------------------------
441
+ "/api/v1/ca/stream/{uuid}": {
442
+ "get": {
443
+ "tags": ["Downloads"],
444
+ "summary": "Stream certificate artefact",
445
+ "security": bearer,
446
+ "parameters": [
447
+ {
448
+ "name": "uuid",
449
+ "in": "path",
450
+ "required": True,
451
+ "schema": {"type": "string"},
452
+ },
453
+ {
454
+ "name": "object_type",
455
+ "in": "query",
456
+ "required": True,
457
+ "schema": {"type": "string", "enum": ["pem", "key", "csr"]},
458
+ },
459
+ ],
460
+ "responses": resp_raw("Streamed artefact"),
461
+ }
462
+ },
463
+ "/api/v1/ca/{uuid}": {
464
+ "get": {
465
+ "tags": ["Downloads"],
466
+ "summary": "Download certificate artefact",
467
+ "security": bearer,
468
+ "parameters": [
469
+ {
470
+ "name": "uuid",
471
+ "in": "path",
472
+ "required": True,
473
+ "schema": {"type": "string"},
474
+ },
475
+ {
476
+ "name": "object_type",
477
+ "in": "query",
478
+ "required": True,
479
+ "schema": {"type": "string", "enum": ["pem", "key", "csr"]},
480
+ },
481
+ ],
482
+ "responses": resp_raw("Artefact file"),
483
+ }
484
+ },
485
+ }
486
+
487
+ return {
488
+ "openapi": "3.0.3",
489
+ "info": {
490
+ "title": title,
491
+ "version": version,
492
+ "description": "Certificate Authority REST API powered by tiny-ca.",
493
+ },
494
+ "components": {
495
+ "schemas": {
496
+ "ErrorDetail": {
497
+ "type": "object",
498
+ "properties": {"detail": {"type": "string"}},
499
+ },
500
+ **components,
501
+ },
502
+ "securitySchemes": {
503
+ "BearerAuth": {"type": "http", "scheme": "bearer"},
504
+ },
505
+ },
506
+ "paths": paths,
507
+ }
508
+
509
+
510
+ # ---------------------------------------------------------------------------
511
+ # Swagger UI HTML
512
+ # ---------------------------------------------------------------------------
513
+
514
+ SWAGGER_UI_HTML = """<!DOCTYPE html>
515
+ <html>
516
+ <head>
517
+ <title>{title}</title>
518
+ <meta charset="utf-8"/>
519
+ <meta name="viewport" content="width=device-width, initial-scale=1">
520
+ <link rel="stylesheet" href="https://unpkg.com/swagger-ui-dist@5/swagger-ui.css">
521
+ </head>
522
+ <body>
523
+ <div id="swagger-ui"></div>
524
+ <script src="https://unpkg.com/swagger-ui-dist@5/swagger-ui-bundle.js"></script>
525
+ <script>
526
+ SwaggerUIBundle({{
527
+ url: "{openapi_url}",
528
+ dom_id: "#swagger-ui",
529
+ presets: [SwaggerUIBundle.presets.apis, SwaggerUIBundle.SwaggerUIStandalonePreset],
530
+ layout: "BaseLayout",
531
+ deepLinking: true,
532
+ persistAuthorization: true,
533
+ }})
534
+ </script>
535
+ </body>
536
+ </html>"""
@@ -0,0 +1,27 @@
1
+ import abc
2
+ from typing import Any
3
+
4
+
5
+ class SingletonMeta(type):
6
+ _instances = {} # type: dict[Any, Any]
7
+
8
+ def __call__(cls, *args, **kwargs) -> Any: # type: ignore # pragma: no cover
9
+ if cls not in cls._instances:
10
+ instance = super().__call__(*args, **kwargs)
11
+ cls._instances[cls] = instance
12
+ return cls._instances[cls]
13
+
14
+ def reset_instance_force(cls) -> None: # pragma: no cover
15
+ if cls in cls._instances:
16
+ del cls._instances[cls]
17
+
18
+ def is_initialized(cls) -> bool: # pragma: no cover
19
+ return cls in cls._instances
20
+
21
+
22
+ class SingletonABCMeta(abc.ABCMeta, SingletonMeta):
23
+ pass
24
+
25
+
26
+ class SingletonABC(metaclass=SingletonABCMeta):
27
+ __slots__ = ()