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.
- tiny_ca_gateway/aiohttp/api/v1/ca_routes.py +546 -0
- tiny_ca_gateway/aiohttp/lifespan/manager.py +11 -0
- tiny_ca_gateway/core/__init__.py +71 -0
- tiny_ca_gateway/core/auth.py +26 -0
- tiny_ca_gateway/core/base_manager.py +162 -0
- tiny_ca_gateway/core/helpers.py +110 -0
- tiny_ca_gateway/core/routes.py +41 -0
- tiny_ca_gateway/core/schemas.py +179 -0
- tiny_ca_gateway/core/summary.py +26 -0
- tiny_ca_gateway/db.py +63 -0
- tiny_ca_gateway/django/api/v1/ca_router.py +594 -0
- tiny_ca_gateway/django/lifespan/manager.py +5 -0
- tiny_ca_gateway/fastapi/api/v1/__init__.py +1 -0
- tiny_ca_gateway/fastapi/api/v1/ca_routes.py +580 -0
- tiny_ca_gateway/fastapi/api/v1/utils.py +87 -0
- tiny_ca_gateway/fastapi/auth/__init__.py +0 -0
- tiny_ca_gateway/fastapi/auth/verify.py +61 -0
- tiny_ca_gateway/fastapi/lifespan/__init__.py +3 -0
- tiny_ca_gateway/fastapi/lifespan/manager.py +7 -0
- tiny_ca_gateway/flask/api/v1/ca_blueprint.py +629 -0
- tiny_ca_gateway/flask/lifespan/manager.py +5 -0
- tiny_ca_gateway/models.py +79 -0
- tiny_ca_gateway/openapi.py +536 -0
- tiny_ca_gateway/utils/singleton.py +27 -0
- tiny_ca_gateway-0.1.0.dist-info/METADATA +233 -0
- tiny_ca_gateway-0.1.0.dist-info/RECORD +29 -0
- tiny_ca_gateway-0.1.0.dist-info/WHEEL +5 -0
- tiny_ca_gateway-0.1.0.dist-info/licenses/LICENSE +54 -0
- tiny_ca_gateway-0.1.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
from datetime import datetime, timedelta
|
|
2
|
+
from enum import Enum
|
|
3
|
+
|
|
4
|
+
from fastapi import Depends, FastAPI, HTTPException, status
|
|
5
|
+
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
|
|
6
|
+
|
|
7
|
+
from tiny_ca_gateway.models import API_SETTINGS
|
|
8
|
+
|
|
9
|
+
security = HTTPBearer()
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class RolesAccess(Enum):
|
|
13
|
+
GLOBAL = "global"
|
|
14
|
+
TEMPORARY = "temporary"
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def verify_token(
|
|
18
|
+
credentials: HTTPAuthorizationCredentials = Depends(security),
|
|
19
|
+
) -> str:
|
|
20
|
+
token = credentials.credentials
|
|
21
|
+
|
|
22
|
+
if token != API_SETTINGS.api_token:
|
|
23
|
+
raise HTTPException(
|
|
24
|
+
status_code=status.HTTP_401_UNAUTHORIZED,
|
|
25
|
+
detail="Invalid token",
|
|
26
|
+
)
|
|
27
|
+
|
|
28
|
+
return token
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def verify_temporary_token(
|
|
32
|
+
credentials: HTTPAuthorizationCredentials = Depends(security),
|
|
33
|
+
) -> str | None:
|
|
34
|
+
token = credentials.credentials
|
|
35
|
+
if (
|
|
36
|
+
token != API_SETTINGS.internal_temporary_token
|
|
37
|
+
and token != API_SETTINGS.api_token
|
|
38
|
+
):
|
|
39
|
+
raise HTTPException(
|
|
40
|
+
status_code=status.HTTP_401_UNAUTHORIZED,
|
|
41
|
+
detail="Invalid token",
|
|
42
|
+
)
|
|
43
|
+
# check global token
|
|
44
|
+
if token == API_SETTINGS.api_token:
|
|
45
|
+
return None
|
|
46
|
+
if API_SETTINGS.internal_token_valid_until is None:
|
|
47
|
+
internal_token_valid_until = datetime.now() + timedelta(
|
|
48
|
+
minutes=API_SETTINGS.ttl_token
|
|
49
|
+
)
|
|
50
|
+
API_SETTINGS.internal_token_valid_until = internal_token_valid_until
|
|
51
|
+
else:
|
|
52
|
+
time_token: str | datetime = API_SETTINGS.internal_token_valid_until
|
|
53
|
+
if isinstance(time_token, str):
|
|
54
|
+
time_token = datetime.strptime(time_token, API_SETTINGS.datetime_fmt)
|
|
55
|
+
|
|
56
|
+
if time_token < datetime.now(): # type: ignore[operator]
|
|
57
|
+
raise HTTPException(
|
|
58
|
+
status_code=status.HTTP_401_UNAUTHORIZED,
|
|
59
|
+
detail="Expired ttl temporary token",
|
|
60
|
+
)
|
|
61
|
+
return token
|
|
@@ -0,0 +1,629 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import asyncio
|
|
4
|
+
from collections.abc import AsyncGenerator, Callable, Coroutine, Generator
|
|
5
|
+
import functools
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
from typing import Any, TypeVar
|
|
8
|
+
import uuid as _uuid_module
|
|
9
|
+
|
|
10
|
+
import aiofiles
|
|
11
|
+
from cryptography import x509
|
|
12
|
+
from cryptography.hazmat.primitives.serialization import Encoding, load_pem_private_key
|
|
13
|
+
from flask import (
|
|
14
|
+
Blueprint,
|
|
15
|
+
Response,
|
|
16
|
+
abort,
|
|
17
|
+
jsonify,
|
|
18
|
+
make_response,
|
|
19
|
+
request,
|
|
20
|
+
stream_with_context,
|
|
21
|
+
)
|
|
22
|
+
from tiny_ca.managers.async_lifecycle_manager import AsyncCertLifecycleManager
|
|
23
|
+
from tiny_ca.models.certificate import CAConfig
|
|
24
|
+
|
|
25
|
+
from tiny_ca_gateway.core import (
|
|
26
|
+
REASON_MAP,
|
|
27
|
+
CosignRequest,
|
|
28
|
+
CRLVerifyRequest,
|
|
29
|
+
ExportP12Request,
|
|
30
|
+
IntermediateCARequest,
|
|
31
|
+
IssueCertRequest,
|
|
32
|
+
RenewRequest,
|
|
33
|
+
RevokeRequest,
|
|
34
|
+
Routes,
|
|
35
|
+
VerifyRequest,
|
|
36
|
+
build_client_config,
|
|
37
|
+
get_artifact_path,
|
|
38
|
+
record_to_item,
|
|
39
|
+
)
|
|
40
|
+
from tiny_ca_gateway.core.helpers import load_pem_cert, load_pem_crl
|
|
41
|
+
from tiny_ca_gateway.flask.lifespan.manager import FlaskCAManager
|
|
42
|
+
from tiny_ca_gateway.models import API_SETTINGS
|
|
43
|
+
|
|
44
|
+
ca_bp = Blueprint("ca", __name__)
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
# ---------------------------------------------------------------------------
|
|
48
|
+
# Flask-specific wrappers
|
|
49
|
+
# ---------------------------------------------------------------------------
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def _require_factory() -> AsyncCertLifecycleManager:
|
|
53
|
+
mgr = FlaskCAManager().manager
|
|
54
|
+
if mgr.factory is None:
|
|
55
|
+
abort(
|
|
56
|
+
make_response(
|
|
57
|
+
jsonify(detail="CA not initialised — POST /ca/root first."), 503
|
|
58
|
+
)
|
|
59
|
+
)
|
|
60
|
+
return mgr
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def _verify_token() -> None:
|
|
64
|
+
expected = getattr(API_SETTINGS, "api_token", None)
|
|
65
|
+
if not expected:
|
|
66
|
+
return
|
|
67
|
+
auth = request.headers.get("Authorization", "")
|
|
68
|
+
if not auth.startswith("Bearer ") or auth[7:] != expected:
|
|
69
|
+
abort(make_response(jsonify(detail="Invalid or missing bearer token."), 401))
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def _load_pem_cert(pem: str) -> x509.Certificate:
|
|
73
|
+
try:
|
|
74
|
+
return load_pem_cert(pem)
|
|
75
|
+
except ValueError as exc:
|
|
76
|
+
abort(make_response(jsonify(detail=str(exc)), 422))
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def _load_pem_crl(pem: str) -> x509.CertificateRevocationList:
|
|
80
|
+
try:
|
|
81
|
+
return load_pem_crl(pem)
|
|
82
|
+
except ValueError as exc:
|
|
83
|
+
abort(make_response(jsonify(detail=str(exc)), 422))
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
T = TypeVar("T")
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def _run(coro: Coroutine[Any, Any, T]) -> T:
|
|
90
|
+
try:
|
|
91
|
+
loop = asyncio.get_event_loop()
|
|
92
|
+
if loop.is_closed():
|
|
93
|
+
raise RuntimeError
|
|
94
|
+
except RuntimeError:
|
|
95
|
+
loop = asyncio.new_event_loop()
|
|
96
|
+
asyncio.set_event_loop(loop)
|
|
97
|
+
return loop.run_until_complete(coro)
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def _async(f: Callable[..., Coroutine[Any, Any, T]]) -> Callable[..., T]:
|
|
101
|
+
@functools.wraps(f)
|
|
102
|
+
def wrapper(*args: Any, **kwargs: Any) -> T:
|
|
103
|
+
return _run(f(*args, **kwargs))
|
|
104
|
+
|
|
105
|
+
return wrapper
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def _json(data: dict[str, Any] | list[Any], status: int = 200) -> tuple[Response, int]:
|
|
109
|
+
if hasattr(data, "model_dump"):
|
|
110
|
+
return jsonify(data.model_dump(mode="json")), status
|
|
111
|
+
if isinstance(data, list):
|
|
112
|
+
return (
|
|
113
|
+
jsonify(
|
|
114
|
+
[
|
|
115
|
+
i.model_dump(mode="json") if hasattr(i, "model_dump") else i
|
|
116
|
+
for i in data
|
|
117
|
+
]
|
|
118
|
+
),
|
|
119
|
+
status,
|
|
120
|
+
)
|
|
121
|
+
return jsonify(data), status
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
# ===========================================================================
|
|
125
|
+
# Public
|
|
126
|
+
# ===========================================================================
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
@ca_bp.get(Routes.GET_PUBLIC_CERT)
|
|
130
|
+
def get_public_cert() -> Response | tuple[Response, int]:
|
|
131
|
+
cert_path = Path(API_SETTINGS.path_to_ca_cer)
|
|
132
|
+
if not cert_path.exists():
|
|
133
|
+
return jsonify(detail="CA not bootstrapped — POST /ca/root first."), 404
|
|
134
|
+
return Response(
|
|
135
|
+
cert_path.read_bytes(),
|
|
136
|
+
mimetype="application/x-pem-file",
|
|
137
|
+
headers={"Content-Disposition": 'attachment; filename="ca.pem"'},
|
|
138
|
+
)
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
@ca_bp.get(Routes.BASE_CRL)
|
|
142
|
+
@_async
|
|
143
|
+
async def crl_route() -> Response | tuple[Response, int]:
|
|
144
|
+
pem_fmt = request.args.get("pem", "false").lower() == "true"
|
|
145
|
+
crl_path = Path(API_SETTINGS.path_to_crl)
|
|
146
|
+
if not crl_path.exists():
|
|
147
|
+
mgr = _require_factory()
|
|
148
|
+
try:
|
|
149
|
+
await mgr.generate_crl()
|
|
150
|
+
except Exception as exc:
|
|
151
|
+
return jsonify(detail=str(exc)), 500
|
|
152
|
+
if not crl_path.exists():
|
|
153
|
+
return jsonify(detail="CRL not found after generation."), 500
|
|
154
|
+
async with aiofiles.open(crl_path, "rb") as fh:
|
|
155
|
+
content = await fh.read()
|
|
156
|
+
if pem_fmt:
|
|
157
|
+
if not content.startswith(b"-----"):
|
|
158
|
+
content = x509.load_der_x509_crl(content).public_bytes(Encoding.PEM)
|
|
159
|
+
return Response(
|
|
160
|
+
content,
|
|
161
|
+
mimetype="application/x-pem-file",
|
|
162
|
+
headers={"Content-Disposition": 'attachment; filename="ca.crl.pem"'},
|
|
163
|
+
)
|
|
164
|
+
return Response(
|
|
165
|
+
content,
|
|
166
|
+
mimetype="application/pkix-crl",
|
|
167
|
+
headers={
|
|
168
|
+
"Content-Disposition": 'attachment; filename="ca.crl"',
|
|
169
|
+
"Cache-Control": "max-age=3600",
|
|
170
|
+
},
|
|
171
|
+
)
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
# ===========================================================================
|
|
175
|
+
# List / search
|
|
176
|
+
# ===========================================================================
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
@ca_bp.get(Routes.GET_LIST_CERTS, strict_slashes=False)
|
|
180
|
+
@ca_bp.get("/", strict_slashes=False)
|
|
181
|
+
@_async
|
|
182
|
+
async def list_certificates() -> Response | tuple[Response, int]:
|
|
183
|
+
_verify_token()
|
|
184
|
+
mgr = _require_factory()
|
|
185
|
+
records = await mgr.list_certificates(
|
|
186
|
+
status=request.args.get("status"),
|
|
187
|
+
key_type=request.args.get("key_type"),
|
|
188
|
+
limit=min(int(request.args.get("limit", 100)), 1000),
|
|
189
|
+
offset=max(int(request.args.get("offset", 0)), 0),
|
|
190
|
+
)
|
|
191
|
+
return _json([record_to_item(r) for r in records])
|
|
192
|
+
|
|
193
|
+
|
|
194
|
+
@ca_bp.get(Routes.GET_LIST_EXPIRING_CERTS)
|
|
195
|
+
@_async
|
|
196
|
+
async def get_expiring() -> Response | tuple[Response, int]:
|
|
197
|
+
_verify_token()
|
|
198
|
+
mgr = _require_factory()
|
|
199
|
+
within_days = max(1, min(int(request.args.get("within_days", 30)), 365))
|
|
200
|
+
records = await mgr.get_expiring_soon(within_days=within_days)
|
|
201
|
+
return _json(
|
|
202
|
+
{
|
|
203
|
+
"within_days": within_days,
|
|
204
|
+
"count": len(records),
|
|
205
|
+
"certificates": [
|
|
206
|
+
record_to_item(r).model_dump(mode="json") for r in records
|
|
207
|
+
],
|
|
208
|
+
}
|
|
209
|
+
)
|
|
210
|
+
|
|
211
|
+
|
|
212
|
+
# ===========================================================================
|
|
213
|
+
# CA bootstrap / issuance
|
|
214
|
+
# ===========================================================================
|
|
215
|
+
|
|
216
|
+
|
|
217
|
+
@ca_bp.post(Routes.CA_ROOT)
|
|
218
|
+
@_async
|
|
219
|
+
async def create_root_ca() -> Response | tuple[Response, int]:
|
|
220
|
+
_verify_token()
|
|
221
|
+
lm = FlaskCAManager()
|
|
222
|
+
try:
|
|
223
|
+
payload = CAConfig.model_validate(request.get_json())
|
|
224
|
+
except Exception as exc:
|
|
225
|
+
return jsonify(detail=str(exc)), 422
|
|
226
|
+
try:
|
|
227
|
+
await lm.rebuild_root_ca_pair(ca_config=payload)
|
|
228
|
+
except Exception as exc:
|
|
229
|
+
return jsonify(detail=str(exc)), 409
|
|
230
|
+
try:
|
|
231
|
+
await lm.rebuild_manager()
|
|
232
|
+
except Exception as exc:
|
|
233
|
+
lm.logger.error("Factory reload failed: %s", exc)
|
|
234
|
+
cert_obj = x509.load_pem_x509_certificate(
|
|
235
|
+
Path(API_SETTINGS.path_to_ca_cer).read_bytes()
|
|
236
|
+
)
|
|
237
|
+
return _json(
|
|
238
|
+
{
|
|
239
|
+
"ca_id": "",
|
|
240
|
+
"expires_at": cert_obj.not_valid_after_utc.strftime(
|
|
241
|
+
API_SETTINGS.datetime_fmt
|
|
242
|
+
),
|
|
243
|
+
}
|
|
244
|
+
)
|
|
245
|
+
|
|
246
|
+
|
|
247
|
+
@ca_bp.post(Routes.CA_INTERMEDIATE)
|
|
248
|
+
@_async
|
|
249
|
+
async def issue_intermediate_ca() -> Response | tuple[Response, int]:
|
|
250
|
+
_verify_token()
|
|
251
|
+
mgr = _require_factory()
|
|
252
|
+
try:
|
|
253
|
+
payload = IntermediateCARequest.model_validate(request.get_json())
|
|
254
|
+
except Exception as exc:
|
|
255
|
+
return jsonify(detail=str(exc)), 422
|
|
256
|
+
_uuid = str(_uuid_module.uuid4())
|
|
257
|
+
try:
|
|
258
|
+
cert, _ = await mgr.issue_intermediate_ca(
|
|
259
|
+
common_name=payload.common_name,
|
|
260
|
+
key_size=payload.key_size,
|
|
261
|
+
days_valid=payload.days_valid,
|
|
262
|
+
path_length=payload.path_length,
|
|
263
|
+
organization=payload.organization,
|
|
264
|
+
country=payload.country,
|
|
265
|
+
uuid_str=_uuid,
|
|
266
|
+
)
|
|
267
|
+
except Exception as exc:
|
|
268
|
+
return jsonify(detail=str(exc)), 422
|
|
269
|
+
return _json(
|
|
270
|
+
{
|
|
271
|
+
"uuid": _uuid,
|
|
272
|
+
"serial_number": cert.serial_number,
|
|
273
|
+
"common_name": payload.common_name,
|
|
274
|
+
"not_valid_before": cert.not_valid_before_utc.isoformat(),
|
|
275
|
+
"not_valid_after": cert.not_valid_after_utc.isoformat(),
|
|
276
|
+
}
|
|
277
|
+
)
|
|
278
|
+
|
|
279
|
+
|
|
280
|
+
@ca_bp.post(Routes.ISSUE)
|
|
281
|
+
@_async
|
|
282
|
+
async def issue_certificate() -> Response | tuple[Response, int]:
|
|
283
|
+
_verify_token()
|
|
284
|
+
mgr = _require_factory()
|
|
285
|
+
try:
|
|
286
|
+
payload = IssueCertRequest.model_validate(request.get_json())
|
|
287
|
+
except Exception as exc:
|
|
288
|
+
return jsonify(detail=str(exc)), 422
|
|
289
|
+
_uuid = str(_uuid_module.uuid4())
|
|
290
|
+
try:
|
|
291
|
+
if payload.key_size and (payload.key_size < 2048 or payload.key_size > 4096):
|
|
292
|
+
return (
|
|
293
|
+
jsonify(
|
|
294
|
+
detail=f"Invalid key_size: {payload.key_size}. Must be 2048-4096."
|
|
295
|
+
),
|
|
296
|
+
400,
|
|
297
|
+
)
|
|
298
|
+
|
|
299
|
+
cert, _, _ = await mgr.issue_certificate(
|
|
300
|
+
config=build_client_config(payload),
|
|
301
|
+
uuid_str=_uuid,
|
|
302
|
+
is_overwrite=payload.is_overwrite,
|
|
303
|
+
)
|
|
304
|
+
except ValueError as exc:
|
|
305
|
+
if "key" in str(exc).lower():
|
|
306
|
+
return jsonify(detail=str(exc)), 400
|
|
307
|
+
return jsonify(detail=str(exc)), 409
|
|
308
|
+
except Exception as exc:
|
|
309
|
+
return jsonify(detail=str(exc)), 409
|
|
310
|
+
return _json(
|
|
311
|
+
{
|
|
312
|
+
"uuid": _uuid,
|
|
313
|
+
"serial_number": cert.serial_number,
|
|
314
|
+
"common_name": payload.common_name,
|
|
315
|
+
"not_valid_before": cert.not_valid_before_utc.isoformat(),
|
|
316
|
+
"not_valid_after": cert.not_valid_after_utc.isoformat(),
|
|
317
|
+
},
|
|
318
|
+
201,
|
|
319
|
+
)
|
|
320
|
+
|
|
321
|
+
|
|
322
|
+
@ca_bp.post(Routes.MAINTENANCE_EXPIRE)
|
|
323
|
+
@_async
|
|
324
|
+
async def mark_expired() -> Response | tuple[Response, int]:
|
|
325
|
+
_verify_token()
|
|
326
|
+
return _json({"updated": await _require_factory().refresh_expired_statuses()})
|
|
327
|
+
|
|
328
|
+
|
|
329
|
+
# ===========================================================================
|
|
330
|
+
# CRL
|
|
331
|
+
# ===========================================================================
|
|
332
|
+
|
|
333
|
+
|
|
334
|
+
@ca_bp.post(Routes.CRL_REFRESH)
|
|
335
|
+
@_async
|
|
336
|
+
async def refresh_crl() -> Response | tuple[Response, int]:
|
|
337
|
+
_verify_token()
|
|
338
|
+
try:
|
|
339
|
+
crl = await _require_factory().generate_crl()
|
|
340
|
+
except Exception as exc:
|
|
341
|
+
return jsonify(detail=str(exc)), 500
|
|
342
|
+
return _json({"next_update": crl.next_update_utc.isoformat()})
|
|
343
|
+
|
|
344
|
+
|
|
345
|
+
@ca_bp.post(Routes.CRL_VERIFY)
|
|
346
|
+
@_async
|
|
347
|
+
async def verify_crl() -> Response | tuple[Response, int]:
|
|
348
|
+
_verify_token()
|
|
349
|
+
try:
|
|
350
|
+
payload = CRLVerifyRequest.model_validate(request.get_json())
|
|
351
|
+
except Exception as exc:
|
|
352
|
+
return jsonify(detail=str(exc)), 422
|
|
353
|
+
crl = _load_pem_crl(payload.pem)
|
|
354
|
+
try:
|
|
355
|
+
await _require_factory().verify_crl(crl=crl)
|
|
356
|
+
return _json({"valid": True, "next_update": crl.next_update_utc.isoformat()})
|
|
357
|
+
except Exception as exc:
|
|
358
|
+
return _json({"valid": False, "detail": str(exc)})
|
|
359
|
+
|
|
360
|
+
|
|
361
|
+
# ===========================================================================
|
|
362
|
+
# Verification / cosign / export
|
|
363
|
+
# ===========================================================================
|
|
364
|
+
|
|
365
|
+
|
|
366
|
+
@ca_bp.post(Routes.VERIFY)
|
|
367
|
+
@_async
|
|
368
|
+
async def verify_certificate() -> Response | tuple[Response, int]:
|
|
369
|
+
_verify_token()
|
|
370
|
+
try:
|
|
371
|
+
payload = VerifyRequest.model_validate(request.get_json())
|
|
372
|
+
except Exception as exc:
|
|
373
|
+
return jsonify(detail=str(exc)), 422
|
|
374
|
+
cert = _load_pem_cert(payload.pem)
|
|
375
|
+
try:
|
|
376
|
+
result = await _require_factory().verify_certificate(cert=cert)
|
|
377
|
+
if isinstance(result, tuple):
|
|
378
|
+
valid, reason = result
|
|
379
|
+
if valid:
|
|
380
|
+
return _json({"valid": True})
|
|
381
|
+
else:
|
|
382
|
+
return _json(
|
|
383
|
+
{"valid": False, "detail": reason or "Verification failed"}
|
|
384
|
+
)
|
|
385
|
+
|
|
386
|
+
return _json({"valid": True})
|
|
387
|
+
except Exception as exc:
|
|
388
|
+
return _json({"valid": False, "detail": str(exc)})
|
|
389
|
+
|
|
390
|
+
|
|
391
|
+
@ca_bp.post(Routes.COSIGN)
|
|
392
|
+
@_async
|
|
393
|
+
async def cosign_certificate() -> Response | tuple[Response, int]:
|
|
394
|
+
_verify_token()
|
|
395
|
+
try:
|
|
396
|
+
payload = CosignRequest.model_validate(request.get_json())
|
|
397
|
+
except Exception as exc:
|
|
398
|
+
return jsonify(detail=str(exc)), 422
|
|
399
|
+
cert = _load_pem_cert(payload.pem)
|
|
400
|
+
try:
|
|
401
|
+
cosigned = await _require_factory().cosign_certificate(
|
|
402
|
+
cert=cert,
|
|
403
|
+
days_valid=payload.days_valid,
|
|
404
|
+
valid_from=payload.valid_from,
|
|
405
|
+
)
|
|
406
|
+
except Exception as exc:
|
|
407
|
+
return jsonify(detail=str(exc)), 422
|
|
408
|
+
return _json(
|
|
409
|
+
{
|
|
410
|
+
"serial_number": cosigned.serial_number,
|
|
411
|
+
"not_valid_before": cosigned.not_valid_before_utc.isoformat(),
|
|
412
|
+
"not_valid_after": cosigned.not_valid_after_utc.isoformat(),
|
|
413
|
+
"pem": cosigned.public_bytes(Encoding.PEM).decode(),
|
|
414
|
+
}
|
|
415
|
+
)
|
|
416
|
+
|
|
417
|
+
|
|
418
|
+
@ca_bp.post("/export-p12/<int:serial>")
|
|
419
|
+
@_async
|
|
420
|
+
async def export_pkcs12(serial: int) -> Response | tuple[Response, int]:
|
|
421
|
+
_verify_token()
|
|
422
|
+
mgr = _require_factory()
|
|
423
|
+
try:
|
|
424
|
+
payload = ExportP12Request.model_validate(request.get_json() or {})
|
|
425
|
+
except Exception as exc:
|
|
426
|
+
return jsonify(detail=str(exc)), 422
|
|
427
|
+
record = await mgr._db.get_by_serial(serial=serial)
|
|
428
|
+
if not record:
|
|
429
|
+
return jsonify(detail=f"Certificate serial={serial} not found"), 404
|
|
430
|
+
key_path = await get_artifact_path(record.uuid, "key")
|
|
431
|
+
if not key_path:
|
|
432
|
+
return jsonify(detail="Private key not found"), 404
|
|
433
|
+
async with aiofiles.open(key_path, "rb") as fh:
|
|
434
|
+
private_key = load_pem_private_key(await fh.read(), password=None)
|
|
435
|
+
p12 = await mgr.export_pkcs12(
|
|
436
|
+
cert=x509.load_pem_x509_certificate(record.certificate_pem.encode()),
|
|
437
|
+
private_key=private_key,
|
|
438
|
+
password=payload.password.encode() if payload.password else None,
|
|
439
|
+
)
|
|
440
|
+
fname = (record.common_name or str(serial)).replace(" ", "_")
|
|
441
|
+
return Response(
|
|
442
|
+
p12,
|
|
443
|
+
mimetype="application/x-pkcs12",
|
|
444
|
+
headers={"Content-Disposition": f'attachment; filename="{fname}.p12"'},
|
|
445
|
+
)
|
|
446
|
+
|
|
447
|
+
|
|
448
|
+
# ===========================================================================
|
|
449
|
+
# Mutations
|
|
450
|
+
# ===========================================================================
|
|
451
|
+
|
|
452
|
+
|
|
453
|
+
@ca_bp.patch(Routes.REVOKE)
|
|
454
|
+
@_async
|
|
455
|
+
async def revoke_certificate() -> Response | tuple[Response, int]:
|
|
456
|
+
_verify_token()
|
|
457
|
+
try:
|
|
458
|
+
payload = RevokeRequest.model_validate(request.get_json())
|
|
459
|
+
except Exception as exc:
|
|
460
|
+
return jsonify(detail=str(exc)), 422
|
|
461
|
+
reason = REASON_MAP.get(payload.reason, x509.ReasonFlags.unspecified)
|
|
462
|
+
ok = await _require_factory().revoke_certificate(
|
|
463
|
+
serial=payload.serial_number, reason=reason
|
|
464
|
+
)
|
|
465
|
+
if not ok:
|
|
466
|
+
return (
|
|
467
|
+
jsonify(detail=f"No valid certificate with serial={payload.serial_number}"),
|
|
468
|
+
404,
|
|
469
|
+
)
|
|
470
|
+
return _json({"revoked": True, "serial_number": payload.serial_number})
|
|
471
|
+
|
|
472
|
+
|
|
473
|
+
@ca_bp.post("/rotate/<int:serial>")
|
|
474
|
+
@_async
|
|
475
|
+
async def rotate_certificate(serial: int) -> Response | tuple[Response, int]:
|
|
476
|
+
_verify_token()
|
|
477
|
+
try:
|
|
478
|
+
payload = IssueCertRequest.model_validate(request.get_json())
|
|
479
|
+
except Exception as exc:
|
|
480
|
+
return jsonify(detail=str(exc)), 422
|
|
481
|
+
_uuid = str(_uuid_module.uuid4())
|
|
482
|
+
try:
|
|
483
|
+
new_cert, _, _ = await _require_factory().rotate_certificate(
|
|
484
|
+
serial=serial, config=build_client_config(payload)
|
|
485
|
+
)
|
|
486
|
+
except Exception as exc:
|
|
487
|
+
return jsonify(detail=str(exc)), 404
|
|
488
|
+
return _json(
|
|
489
|
+
{
|
|
490
|
+
"uuid": _uuid,
|
|
491
|
+
"serial_number": new_cert.serial_number,
|
|
492
|
+
"common_name": payload.common_name,
|
|
493
|
+
"not_valid_before": new_cert.not_valid_before_utc.isoformat(),
|
|
494
|
+
"not_valid_after": new_cert.not_valid_after_utc.isoformat(),
|
|
495
|
+
}
|
|
496
|
+
)
|
|
497
|
+
|
|
498
|
+
|
|
499
|
+
@ca_bp.post("/renew/<int:serial>")
|
|
500
|
+
@_async
|
|
501
|
+
async def renew_certificate(serial: int) -> Response | tuple[Response, int]:
|
|
502
|
+
_verify_token()
|
|
503
|
+
try:
|
|
504
|
+
payload = RenewRequest.model_validate(request.get_json())
|
|
505
|
+
except Exception as exc:
|
|
506
|
+
return jsonify(detail=str(exc)), 422
|
|
507
|
+
try:
|
|
508
|
+
renewed = await _require_factory().renew_certificate(
|
|
509
|
+
serial=serial, days_valid=payload.days_valid
|
|
510
|
+
)
|
|
511
|
+
except Exception as exc:
|
|
512
|
+
return jsonify(detail=str(exc)), 404
|
|
513
|
+
return _json(
|
|
514
|
+
{
|
|
515
|
+
"old_serial": serial,
|
|
516
|
+
"new_serial": renewed.serial_number,
|
|
517
|
+
"not_valid_after": renewed.not_valid_after_utc.isoformat(),
|
|
518
|
+
}
|
|
519
|
+
)
|
|
520
|
+
|
|
521
|
+
|
|
522
|
+
@ca_bp.delete("/<int:serial>")
|
|
523
|
+
@_async
|
|
524
|
+
async def delete_certificate(serial: int) -> Response | tuple[Response, int]:
|
|
525
|
+
_verify_token()
|
|
526
|
+
if not await _require_factory().delete_certificate(serial=serial):
|
|
527
|
+
return jsonify(detail=f"Certificate serial={serial} not found"), 404
|
|
528
|
+
return _json({"deleted": True, "serial": serial})
|
|
529
|
+
|
|
530
|
+
|
|
531
|
+
# ===========================================================================
|
|
532
|
+
# Inspection
|
|
533
|
+
# ===========================================================================
|
|
534
|
+
|
|
535
|
+
|
|
536
|
+
@ca_bp.get("/status/<int:serial>")
|
|
537
|
+
@_async
|
|
538
|
+
async def get_status(serial: int) -> Response | tuple[Response, int]:
|
|
539
|
+
_verify_token()
|
|
540
|
+
status = await _require_factory().get_certificate_status(serial=serial)
|
|
541
|
+
return _json({"serial": serial, "status": str(status)})
|
|
542
|
+
|
|
543
|
+
|
|
544
|
+
@ca_bp.get("/inspect/<int:serial>")
|
|
545
|
+
@_async
|
|
546
|
+
async def inspect_certificate(serial: int) -> Response | tuple[Response, int]:
|
|
547
|
+
_verify_token()
|
|
548
|
+
mgr = _require_factory()
|
|
549
|
+
record = await mgr._db.get_by_serial(serial=serial)
|
|
550
|
+
if not record:
|
|
551
|
+
return jsonify(detail=f"Certificate serial={serial} not found"), 404
|
|
552
|
+
cert = x509.load_pem_x509_certificate(record.certificate_pem.encode())
|
|
553
|
+
return _json((await mgr.inspect_certificate(cert=cert)).model_dump())
|
|
554
|
+
|
|
555
|
+
|
|
556
|
+
@ca_bp.get("/chain/<int:serial>")
|
|
557
|
+
@_async
|
|
558
|
+
async def get_cert_chain(serial: int) -> Response | tuple[Response, int]:
|
|
559
|
+
_verify_token()
|
|
560
|
+
mgr = _require_factory()
|
|
561
|
+
record = await mgr._db.get_by_serial(serial=serial)
|
|
562
|
+
if not record:
|
|
563
|
+
return jsonify(detail=f"Certificate serial={serial} not found"), 404
|
|
564
|
+
cert = x509.load_pem_x509_certificate(record.certificate_pem.encode())
|
|
565
|
+
chain = await mgr.get_cert_chain(cert=cert)
|
|
566
|
+
return _json( # type: ignore[no-untyped-call]
|
|
567
|
+
{
|
|
568
|
+
"serial": serial,
|
|
569
|
+
"chain_length": len(chain),
|
|
570
|
+
"chain": [c.public_bytes(Encoding.PEM).decode() for c in chain],
|
|
571
|
+
}
|
|
572
|
+
)
|
|
573
|
+
|
|
574
|
+
|
|
575
|
+
# ===========================================================================
|
|
576
|
+
# Downloads
|
|
577
|
+
# ===========================================================================
|
|
578
|
+
|
|
579
|
+
|
|
580
|
+
@ca_bp.get("/stream/<string:uuid_certificate>")
|
|
581
|
+
@_async
|
|
582
|
+
async def stream_artifact(uuid_certificate: str) -> Response | tuple[Response, int]:
|
|
583
|
+
_verify_token()
|
|
584
|
+
object_type = request.args.get("object_type", "pem")
|
|
585
|
+
path = await get_artifact_path(uuid_certificate, object_type) # type: ignore[arg-type]
|
|
586
|
+
if not path:
|
|
587
|
+
return jsonify(detail="Artefact not found"), 404
|
|
588
|
+
|
|
589
|
+
def _sync_iter() -> Generator[bytes, None, None]:
|
|
590
|
+
import asyncio as _asyncio
|
|
591
|
+
|
|
592
|
+
loop = _asyncio.new_event_loop()
|
|
593
|
+
gen = _iter(path)
|
|
594
|
+
try:
|
|
595
|
+
while True:
|
|
596
|
+
try:
|
|
597
|
+
yield loop.run_until_complete(gen.__anext__())
|
|
598
|
+
except StopAsyncIteration:
|
|
599
|
+
break
|
|
600
|
+
finally:
|
|
601
|
+
loop.close()
|
|
602
|
+
|
|
603
|
+
async def _iter(p: Path, chunk: int = 1024 * 1024) -> AsyncGenerator[bytes, None]:
|
|
604
|
+
async with aiofiles.open(p, "rb") as fh:
|
|
605
|
+
while data := await fh.read(chunk):
|
|
606
|
+
yield data
|
|
607
|
+
|
|
608
|
+
return Response(
|
|
609
|
+
stream_with_context(_sync_iter()),
|
|
610
|
+
mimetype="application/x-pem-file",
|
|
611
|
+
headers={"Content-Disposition": f'attachment; filename="{path.name}"'},
|
|
612
|
+
)
|
|
613
|
+
|
|
614
|
+
|
|
615
|
+
@ca_bp.get("/<string:uuid_certificate>")
|
|
616
|
+
@_async
|
|
617
|
+
async def download_artifact(uuid_certificate: str) -> Response | tuple[Response, int]:
|
|
618
|
+
_verify_token()
|
|
619
|
+
object_type = request.args.get("object_type", "pem")
|
|
620
|
+
path = await get_artifact_path(uuid_certificate, object_type) # type: ignore[arg-type]
|
|
621
|
+
if not path:
|
|
622
|
+
return jsonify(detail="Artefact not found"), 404
|
|
623
|
+
async with aiofiles.open(path, "rb") as fh:
|
|
624
|
+
content = await fh.read()
|
|
625
|
+
return Response(
|
|
626
|
+
content,
|
|
627
|
+
mimetype="application/x-pem-file",
|
|
628
|
+
headers={"Content-Disposition": f'attachment; filename="{path.name}"'},
|
|
629
|
+
)
|