epgu-api 0.5.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,975 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ # Copyright (c) 2025 yellow444 <yellow444@gmail.com>
3
+ """Typed contracts for the four Goskey services published in API EPGU.
4
+
5
+ The module deliberately separates *documented* contracts from contracts that
6
+ are safe to generate. Official specifications sometimes disagree with their
7
+ embedded XSD. Such variants remain discoverable through :data:`CAPABILITIES`,
8
+ but :meth:`to_xml` fails closed until an unambiguous schema is published.
9
+
10
+ XML is built with ``lxml`` qualified names; values are never interpolated into
11
+ markup. Install the ``xml`` extra to use XML and manifest helpers::
12
+
13
+ pip install "epgu-api[xml]"
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ import io
19
+ import posixpath
20
+ import re
21
+ import zipfile
22
+ from dataclasses import dataclass, field
23
+ from datetime import datetime, timedelta
24
+ from enum import Enum
25
+ from types import MappingProxyType
26
+ from typing import Any, Dict, Iterable, Mapping, Optional, Sequence, Tuple, Union
27
+
28
+ from ..archive import OrderArchive
29
+ from ..errors import ConfigError, ValidationError
30
+ from ..signature.base import Signer
31
+
32
+ MAX_DIRECT_ARCHIVE_BYTES = 50_000_000
33
+ MAX_DOCUMENT_BYTES = 100_000_000
34
+ REQUEST_FILENAME = "req.xml"
35
+ SIGNATURE_SUFFIX = ".sig"
36
+
37
+ _SNILS_RE = re.compile(r"^[0-9]{3}-[0-9]{3}-[0-9]{3} [0-9]{2}$")
38
+ _OID_RE = re.compile(r"^[^\x00-\x1f]{1,20}$")
39
+ _OGRN_RE = re.compile(r"^(?:[0-9]{11}|[0-9]{13}|[0-9]{15})$")
40
+ _RAFP_RE = re.compile(r"^[0-9]{11}$")
41
+ _INN_USER_RE = re.compile(r"^[0-9]{12}$")
42
+ _USER_ID_RE = re.compile(r"^[0-9]{1,20}$")
43
+ _DOCUMENT_NAME_RE = re.compile(r"^[A-Za-zА-Яа-яЁё0-9_ .,\u2019']+$")
44
+ _MOSCOW_OFFSET = timedelta(hours=3)
45
+
46
+
47
+ class GoskeyOperation(str, Enum):
48
+ """Business operation exposed by a Goskey EPGU service."""
49
+
50
+ SIGN_INDIVIDUAL = "sign-individual"
51
+ SIGN_LEGAL_ENTITY = "sign-legal-entity"
52
+ DECIPHER = "decipher"
53
+ SIGN_TREASURY = "sign-treasury"
54
+
55
+
56
+ class SigningVariant(str, Enum):
57
+ """Recipient signature type for service ``10000000374``."""
58
+
59
+ UNEP = "unep"
60
+ UKEP = "ukep"
61
+
62
+
63
+ class DecipherSignOption(str, Enum):
64
+ """Allowed ``signOption`` value from service ``60079416`` XSD."""
65
+
66
+ GOSKEY_CHIEF = "DECIPHER_GOSKEY_CHIEF"
67
+
68
+
69
+ class CapabilityState(str, Enum):
70
+ """Confidence level of a locally implemented official contract."""
71
+
72
+ VERIFIED = "verified"
73
+ REFERENCE = "reference"
74
+ UNSUPPORTED = "unsupported"
75
+
76
+
77
+ class TransportMode(str, Enum):
78
+ """Submission sequence selected for a prepared ZIP archive."""
79
+
80
+ PUSH = "push"
81
+ ORDER_CHUNKED = "order+chunked"
82
+
83
+
84
+ class GoskeyContractError(ValidationError):
85
+ """Base error for invalid or contradictory Goskey contracts."""
86
+
87
+
88
+ class UnsupportedGoskeyContractError(GoskeyContractError):
89
+ """Raised before generation when official sources are contradictory."""
90
+
91
+
92
+ @dataclass(frozen=True)
93
+ class GoskeyCapability:
94
+ """Machine-readable status of one service/variant contract."""
95
+
96
+ operation: GoskeyOperation
97
+ service_code: str
98
+ target_code: str
99
+ root_name: str
100
+ namespace: str
101
+ state: CapabilityState
102
+ spec_version: str
103
+ spec_date: str
104
+ source_sha256: str
105
+ schema_sha256: Optional[str]
106
+ max_documents: int
107
+ allowed_extensions: Tuple[str, ...]
108
+ variant: Optional[SigningVariant] = None
109
+ contradictions: Tuple[str, ...] = ()
110
+
111
+ def require_verified(self) -> None:
112
+ """Fail closed unless this exact contract has verified schema coverage."""
113
+
114
+ if self.state is CapabilityState.VERIFIED:
115
+ return
116
+ detail = "; ".join(self.contradictions) or "contract is not verified"
117
+ raise UnsupportedGoskeyContractError(
118
+ "Goskey contract {0}/{1} is {2}: {3}".format(
119
+ self.service_code,
120
+ self.variant.value if self.variant else self.operation.value,
121
+ self.state.value,
122
+ detail,
123
+ )
124
+ )
125
+
126
+
127
+ _SIGN_EXTENSIONS = (".pdf", ".tif", ".tiff", ".jpg", ".jpeg", ".xml", ".txt")
128
+
129
+ _CAPABILITY_ITEMS = (
130
+ GoskeyCapability(
131
+ operation=GoskeyOperation.SIGN_INDIVIDUAL,
132
+ variant=SigningVariant.UNEP,
133
+ service_code="10000000374",
134
+ target_code="-10000000374",
135
+ root_name="SignRequest",
136
+ namespace="urn://mpkey.gosuslugi.ru/sign_document/1.0.0",
137
+ state=CapabilityState.VERIFIED,
138
+ spec_version="1.9",
139
+ spec_date="2025-08-28",
140
+ source_sha256="ad78aacb591ef37989e6fdd1dd715bfb1b8ec486b13e16e4bca5a9b00a9eab1d",
141
+ schema_sha256="f46480dbe996a62bb7a1fd9201fc47115bd3616befb27eff03377351523a206b",
142
+ max_documents=20,
143
+ allowed_extensions=_SIGN_EXTENSIONS,
144
+ contradictions=(
145
+ "The copied DOCX XML example contains non-breaking spaces in markup; "
146
+ "the embedded XSD is used as the normative source.",
147
+ ),
148
+ ),
149
+ GoskeyCapability(
150
+ operation=GoskeyOperation.SIGN_INDIVIDUAL,
151
+ variant=SigningVariant.UKEP,
152
+ service_code="10000000374",
153
+ target_code="-10000000374",
154
+ root_name="SignRequest",
155
+ namespace="urn://mpkey.gosuslugi.ru/sign_document_ukep/1.0.0",
156
+ state=CapabilityState.REFERENCE,
157
+ spec_version="1.9",
158
+ spec_date="2025-08-28",
159
+ source_sha256="ad78aacb591ef37989e6fdd1dd715bfb1b8ec486b13e16e4bca5a9b00a9eab1d",
160
+ schema_sha256=None,
161
+ max_documents=20,
162
+ allowed_extensions=_SIGN_EXTENSIONS,
163
+ contradictions=(
164
+ "The specification names the UKEP namespace and says both variants have the same "
165
+ "structure, but publishes only the UNEP targetNamespace XSD.",
166
+ ),
167
+ ),
168
+ GoskeyCapability(
169
+ operation=GoskeyOperation.SIGN_LEGAL_ENTITY,
170
+ service_code="60025907",
171
+ target_code="-60025907",
172
+ root_name="SignRequest",
173
+ namespace="urn://mpkey.gosuslugi.ru/sign_document_ukep_legalperson/1.0.0",
174
+ state=CapabilityState.VERIFIED,
175
+ spec_version="1.1",
176
+ spec_date="2025-08-28",
177
+ source_sha256="383ecf11f75bcee0221c57990b0a4be6943e0e56d1e76effebfa815f44dc3343",
178
+ schema_sha256="3b3fa3ca3e0cecb384dbb0169f421e62ea953a66080208d7f00fb1d1e13cd4ef",
179
+ max_documents=20,
180
+ allowed_extensions=_SIGN_EXTENSIONS,
181
+ contradictions=(
182
+ "Table 4 marks Description as 0..1 while the embedded XSD requires it; generation "
183
+ "follows the XSD.",
184
+ ),
185
+ ),
186
+ GoskeyCapability(
187
+ operation=GoskeyOperation.DECIPHER,
188
+ service_code="60079416",
189
+ target_code="-60079416",
190
+ root_name="DecipheringRequest",
191
+ namespace="urn://mpkey.gosuslugi.ru/deciphering_document/1.0.0",
192
+ state=CapabilityState.REFERENCE,
193
+ spec_version="1.0",
194
+ spec_date="2025-11-01",
195
+ source_sha256="91348129c8cd19557d40600c8c6c647fe0458a564d8869978c9746a2d85aa826",
196
+ schema_sha256="84310f7f2a753790f4f1427ba9c00e3ae1ad1f698a4d355fcdc062495714bd0f",
197
+ max_documents=50,
198
+ allowed_extensions=(".enc",),
199
+ contradictions=(
200
+ "Table 4 calls the Document child FileName, but the embedded XSD calls it Description.",
201
+ "The archive table allows 50 documents, while the XSD allows at most 20 "
202
+ "Document nodes.",
203
+ "The only request example omits Document, so it does not resolve either conflict.",
204
+ ),
205
+ ),
206
+ GoskeyCapability(
207
+ operation=GoskeyOperation.SIGN_TREASURY,
208
+ service_code="60080470",
209
+ target_code="-60080470",
210
+ root_name="SignRequest",
211
+ namespace="urn://mpkey.gosuslugi.ru/sign_document_ukep_roskazna/1.0.0",
212
+ state=CapabilityState.VERIFIED,
213
+ spec_version="1.0",
214
+ spec_date="2026-02-25",
215
+ source_sha256="a153bc7f383d5ed1774b405829626686f2704634c03ba2cd2153d57bf2e95a02",
216
+ schema_sha256="af4831fac4ad63e47da96c020833ba730022903d1bbd4dd4c39029860ee8715a",
217
+ max_documents=50,
218
+ allowed_extensions=_SIGN_EXTENSIONS,
219
+ contradictions=(
220
+ "The result-download prose mistakenly names eServiceCode 60025907; its request meta "
221
+ "and download example use 60080470.",
222
+ ),
223
+ ),
224
+ )
225
+
226
+ CAPABILITIES = MappingProxyType(
227
+ {(item.operation, item.variant): item for item in _CAPABILITY_ITEMS}
228
+ )
229
+ """Immutable registry of all currently documented Goskey contracts."""
230
+
231
+
232
+ def capability_for(
233
+ operation: GoskeyOperation,
234
+ variant: Optional[SigningVariant] = None,
235
+ ) -> GoskeyCapability:
236
+ """Return the exact capability, rejecting invalid operation/variant pairs."""
237
+
238
+ try:
239
+ operation = GoskeyOperation(operation)
240
+ except (TypeError, ValueError) as exc:
241
+ raise GoskeyContractError("Unknown Goskey operation: {0!r}".format(operation)) from exc
242
+ if variant is not None:
243
+ try:
244
+ variant = SigningVariant(variant)
245
+ except (TypeError, ValueError) as exc:
246
+ raise GoskeyContractError("Unknown signing variant: {0!r}".format(variant)) from exc
247
+ try:
248
+ return CAPABILITIES[(operation, variant)]
249
+ except KeyError as exc:
250
+ if operation is GoskeyOperation.SIGN_INDIVIDUAL:
251
+ message = "SIGN_INDIVIDUAL requires variant UNEP or UKEP"
252
+ else:
253
+ message = "{0} does not accept a signing variant".format(operation.value)
254
+ raise GoskeyContractError(message) from exc
255
+
256
+
257
+ def capability_for_service(
258
+ service_code: str,
259
+ variant: Optional[SigningVariant] = None,
260
+ ) -> GoskeyCapability:
261
+ """Look up a capability by EPGU service code."""
262
+
263
+ candidates = [item for item in _CAPABILITY_ITEMS if item.service_code == str(service_code)]
264
+ if not candidates:
265
+ raise GoskeyContractError("Unknown Goskey serviceCode: {0!r}".format(service_code))
266
+ if len(candidates) == 1:
267
+ if variant is not None:
268
+ raise GoskeyContractError(
269
+ "serviceCode {0} does not accept a signing variant".format(service_code)
270
+ )
271
+ return candidates[0]
272
+ if variant is None:
273
+ raise GoskeyContractError(
274
+ "serviceCode {0} requires variant UNEP or UKEP".format(service_code)
275
+ )
276
+ try:
277
+ normalized = SigningVariant(variant)
278
+ except (TypeError, ValueError) as exc:
279
+ raise GoskeyContractError("Unknown signing variant: {0!r}".format(variant)) from exc
280
+ for candidate in candidates:
281
+ if candidate.variant is normalized:
282
+ return candidate
283
+ raise GoskeyContractError("Unsupported service/variant pair")
284
+
285
+
286
+ @dataclass(frozen=True)
287
+ class GoskeyAttribute:
288
+ """One official ``AttributeName``/``AttributeValue`` pair."""
289
+
290
+ name: str
291
+ value: str
292
+
293
+ def __post_init__(self) -> None:
294
+ _validate_text(self.name, "AttributeName", 50)
295
+ _validate_text(self.value, "AttributeValue", 250)
296
+
297
+
298
+ @dataclass(frozen=True)
299
+ class IndividualRecipient:
300
+ """Exactly one physical-person identifier: SNILS or ESIA OID."""
301
+
302
+ snils: Optional[str] = None
303
+ oid: Optional[str] = None
304
+
305
+ def __post_init__(self) -> None:
306
+ _validate_exactly_one(self.snils, self.oid, "snils", "oid")
307
+ if self.snils is not None and not _SNILS_RE.fullmatch(self.snils):
308
+ raise GoskeyContractError("snils must match XXX-XXX-XXX XX")
309
+ if self.oid is not None and not _OID_RE.fullmatch(self.oid):
310
+ raise GoskeyContractError("oid must contain 1..20 characters without controls")
311
+
312
+
313
+ @dataclass(frozen=True)
314
+ class RussianLegalRecipient:
315
+ """Russian company or sole proprietor recipient for service ``60025907``."""
316
+
317
+ ogrn: str
318
+ snils: Optional[str] = None
319
+ oid: Optional[str] = None
320
+
321
+ def __post_init__(self) -> None:
322
+ _validate_exactly_one(self.snils, self.oid, "snils", "oid")
323
+ _validate_ogrn(self.ogrn)
324
+ if self.snils is not None and not _SNILS_RE.fullmatch(self.snils):
325
+ raise GoskeyContractError("snils must match XXX-XXX-XXX XX")
326
+ if self.oid is not None and not _OID_RE.fullmatch(self.oid):
327
+ raise GoskeyContractError("oid must contain 1..20 characters without controls")
328
+
329
+
330
+ @dataclass(frozen=True)
331
+ class ForeignLegalRecipient:
332
+ """Foreign company/accredited branch recipient for service ``60025907``."""
333
+
334
+ rafp: str
335
+ inn_user: str
336
+
337
+ def __post_init__(self) -> None:
338
+ if not _RAFP_RE.fullmatch(self.rafp):
339
+ raise GoskeyContractError("rafp must contain exactly 11 digits")
340
+ if not _INN_USER_RE.fullmatch(self.inn_user):
341
+ raise GoskeyContractError("inn_user must contain exactly 12 digits")
342
+
343
+
344
+ @dataclass(frozen=True)
345
+ class RussianDecipherRecipient:
346
+ """Russian recipient shape from the ``60079416`` XSD."""
347
+
348
+ ogrn: str
349
+ user_id: Optional[str] = None
350
+ snils: Optional[str] = None
351
+
352
+ def __post_init__(self) -> None:
353
+ if self.user_id is not None and self.snils is not None:
354
+ raise GoskeyContractError("Only one of user_id and snils may be supplied")
355
+ _validate_ogrn(self.ogrn)
356
+ if self.user_id is not None and not _USER_ID_RE.fullmatch(self.user_id):
357
+ raise GoskeyContractError("user_id must contain 1..20 digits")
358
+ if self.snils is not None and not _SNILS_RE.fullmatch(self.snils):
359
+ raise GoskeyContractError("snils must match XXX-XXX-XXX XX")
360
+
361
+
362
+ @dataclass(frozen=True)
363
+ class ForeignDecipherRecipient:
364
+ """Foreign recipient shape from the ``60079416`` XSD."""
365
+
366
+ rafp: str
367
+ inn_user: str
368
+
369
+ def __post_init__(self) -> None:
370
+ if not _RAFP_RE.fullmatch(self.rafp):
371
+ raise GoskeyContractError("rafp must contain exactly 11 digits")
372
+ if not _INN_USER_RE.fullmatch(self.inn_user):
373
+ raise GoskeyContractError("inn_user must contain exactly 12 digits")
374
+
375
+
376
+ @dataclass(frozen=True)
377
+ class IndividualSignRequest:
378
+ """Request for physical-person signing (service ``10000000374``)."""
379
+
380
+ variant: SigningVariant
381
+ recipient: IndividualRecipient
382
+ sign_expiration: datetime
383
+ description: str
384
+ attributes: Tuple[GoskeyAttribute, ...]
385
+ backlink: Optional[str] = None
386
+
387
+ def __post_init__(self) -> None:
388
+ _validate_request_common(
389
+ self.sign_expiration, self.description, self.backlink, self.attributes
390
+ )
391
+
392
+ @property
393
+ def capability(self) -> GoskeyCapability:
394
+ return capability_for(GoskeyOperation.SIGN_INDIVIDUAL, self.variant)
395
+
396
+ def to_xml(self) -> bytes:
397
+ """Build XSD-oriented ``req.xml`` or fail for the reference-only UKEP variant."""
398
+
399
+ capability = self.capability
400
+ capability.require_verified()
401
+ root = _root(capability)
402
+ _append_individual(root, capability.namespace, self.recipient)
403
+ _append_common_sign_fields(root, capability.namespace, self)
404
+ return _serialize(root)
405
+
406
+
407
+ @dataclass(frozen=True)
408
+ class LegalEntitySignRequest:
409
+ """UKEP signing request for a legal entity/IP (service ``60025907``)."""
410
+
411
+ recipient: Union[RussianLegalRecipient, ForeignLegalRecipient]
412
+ sign_expiration: datetime
413
+ description: str
414
+ attributes: Tuple[GoskeyAttribute, ...]
415
+ backlink: Optional[str] = None
416
+
417
+ def __post_init__(self) -> None:
418
+ if not isinstance(self.recipient, (RussianLegalRecipient, ForeignLegalRecipient)):
419
+ raise GoskeyContractError("recipient has an invalid type for service 60025907")
420
+ _validate_request_common(
421
+ self.sign_expiration, self.description, self.backlink, self.attributes
422
+ )
423
+
424
+ @property
425
+ def capability(self) -> GoskeyCapability:
426
+ return capability_for(GoskeyOperation.SIGN_LEGAL_ENTITY)
427
+
428
+ def to_xml(self) -> bytes:
429
+ """Build a deterministic ``SignRequest`` matching the embedded official XSD."""
430
+
431
+ capability = self.capability
432
+ capability.require_verified()
433
+ root = _root(capability)
434
+ namespace = capability.namespace
435
+ if isinstance(self.recipient, RussianLegalRecipient):
436
+ section = _subelement(root, namespace, "RFOrg")
437
+ _append_identifier(section, namespace, self.recipient.snils, self.recipient.oid)
438
+ _text_element(section, namespace, "OGRN", self.recipient.ogrn)
439
+ else:
440
+ section = _subelement(root, namespace, "ForeignOrg")
441
+ _text_element(section, namespace, "RAFP", self.recipient.rafp)
442
+ _text_element(section, namespace, "INN_user", self.recipient.inn_user)
443
+ _append_common_sign_fields(root, namespace, self)
444
+ return _serialize(root)
445
+
446
+
447
+ @dataclass(frozen=True)
448
+ class TreasurySignRequest:
449
+ """Treasury-certificate UKEP signing request (service ``60080470``)."""
450
+
451
+ recipient: IndividualRecipient
452
+ sign_expiration: datetime
453
+ description: str
454
+ attributes: Tuple[GoskeyAttribute, ...]
455
+ backlink: Optional[str] = None
456
+
457
+ def __post_init__(self) -> None:
458
+ _validate_request_common(
459
+ self.sign_expiration, self.description, self.backlink, self.attributes
460
+ )
461
+
462
+ @property
463
+ def capability(self) -> GoskeyCapability:
464
+ return capability_for(GoskeyOperation.SIGN_TREASURY)
465
+
466
+ def to_xml(self) -> bytes:
467
+ """Build a deterministic ``SignRequest`` matching the embedded official XSD."""
468
+
469
+ capability = self.capability
470
+ capability.require_verified()
471
+ root = _root(capability)
472
+ _append_individual(root, capability.namespace, self.recipient)
473
+ _append_common_sign_fields(root, capability.namespace, self)
474
+ return _serialize(root)
475
+
476
+
477
+ @dataclass(frozen=True)
478
+ class DecipherDocument:
479
+ """Document metadata recorded by the contradictory ``60079416`` sources."""
480
+
481
+ file_name: str
482
+ full_path_elements: Tuple[str, ...]
483
+
484
+ def __post_init__(self) -> None:
485
+ _validate_text(self.file_name, "file_name", 250)
486
+ paths = tuple(self.full_path_elements)
487
+ if not 1 <= len(paths) <= 10:
488
+ raise GoskeyContractError("full_path_elements must contain 1..10 values")
489
+ for path in paths:
490
+ _validate_text(path, "FullPathElement", 10_000)
491
+ object.__setattr__(self, "full_path_elements", paths)
492
+
493
+
494
+ @dataclass(frozen=True)
495
+ class DecipherRequest:
496
+ """Reference-only request for service ``60079416``.
497
+
498
+ The type exposes the published fields, but XML generation is blocked because
499
+ the field name and multiplicity for ``Document`` disagree between Table 4
500
+ and the embedded XSD.
501
+ """
502
+
503
+ recipient: Union[RussianDecipherRecipient, ForeignDecipherRecipient]
504
+ expiration: datetime
505
+ description: str
506
+ attributes: Tuple[GoskeyAttribute, ...]
507
+ documents: Tuple[DecipherDocument, ...] = ()
508
+ backlink: Optional[str] = None
509
+ sign_option: DecipherSignOption = DecipherSignOption.GOSKEY_CHIEF
510
+
511
+ def __post_init__(self) -> None:
512
+ if not isinstance(self.recipient, (RussianDecipherRecipient, ForeignDecipherRecipient)):
513
+ raise GoskeyContractError("recipient has an invalid type for service 60079416")
514
+ _validate_request_common(self.expiration, self.description, self.backlink, self.attributes)
515
+ documents = tuple(self.documents)
516
+ if len(documents) > 50:
517
+ raise GoskeyContractError("documents exceeds the archive-table limit of 50")
518
+ if any(not isinstance(item, DecipherDocument) for item in documents):
519
+ raise GoskeyContractError("documents must contain DecipherDocument values")
520
+ object.__setattr__(self, "documents", documents)
521
+ try:
522
+ object.__setattr__(self, "sign_option", DecipherSignOption(self.sign_option))
523
+ except (TypeError, ValueError) as exc:
524
+ raise GoskeyContractError("Unknown decipher sign_option") from exc
525
+
526
+ @property
527
+ def capability(self) -> GoskeyCapability:
528
+ return capability_for(GoskeyOperation.DECIPHER)
529
+
530
+ def to_xml(self) -> bytes:
531
+ """Always fail closed until the official ``Document`` conflict is resolved."""
532
+
533
+ self.capability.require_verified()
534
+ raise AssertionError( # pragma: no cover
535
+ "reference capability unexpectedly became verified"
536
+ )
537
+
538
+
539
+ @dataclass(frozen=True)
540
+ class ManifestReport:
541
+ """Result of structural detached-signature manifest validation."""
542
+
543
+ service_code: str
544
+ payload_names: Tuple[str, ...]
545
+ signature_names: Tuple[str, ...]
546
+ document_count: int
547
+ document_bytes: int
548
+ cryptographic_signatures_verified: bool = field(default=False, init=False)
549
+
550
+
551
+ @dataclass(frozen=True)
552
+ class TransportDecision:
553
+ """Selected API sequence for an already built archive."""
554
+
555
+ mode: TransportMode
556
+ endpoint: str
557
+ reserve_order: bool
558
+ order_id: Optional[int]
559
+
560
+
561
+ def select_transport(archive_size: int, order_id: Optional[int] = None) -> TransportDecision:
562
+ """Apply the Goskey threshold exactly.
563
+
564
+ ``push`` is selected only when the ZIP is at most 50,000,000 bytes and no
565
+ order has been reserved. Every other case uses ``order`` + ``push/chunked``.
566
+ """
567
+
568
+ if isinstance(archive_size, bool) or not isinstance(archive_size, int) or archive_size <= 0:
569
+ raise GoskeyContractError("archive_size must be a positive integer")
570
+ if order_id is not None and (
571
+ isinstance(order_id, bool) or not isinstance(order_id, int) or order_id <= 0
572
+ ):
573
+ raise GoskeyContractError("order_id must be a positive integer")
574
+ if archive_size <= MAX_DIRECT_ARCHIVE_BYTES and order_id is None:
575
+ return TransportDecision(TransportMode.PUSH, "/api/gusmev/push", False, None)
576
+ return TransportDecision(
577
+ TransportMode.ORDER_CHUNKED,
578
+ "/api/gusmev/push/chunked",
579
+ order_id is None,
580
+ order_id,
581
+ )
582
+
583
+
584
+ def validate_submission_window(
585
+ expiration: datetime,
586
+ *,
587
+ now: Optional[datetime] = None,
588
+ ) -> None:
589
+ """Validate the official Goskey signing window at submission time.
590
+
591
+ Request objects validate the wire format only, so they remain deterministic
592
+ and may be prepared in advance. Call this immediately before submission:
593
+ the deadline must be in the future, use Moscow UTC+03:00 and be no more
594
+ than 24 hours from ``now``.
595
+ """
596
+
597
+ if not isinstance(expiration, datetime) or expiration.tzinfo is None:
598
+ raise GoskeyContractError("expiration must be a timezone-aware datetime")
599
+ if expiration.utcoffset() != _MOSCOW_OFFSET:
600
+ raise GoskeyContractError("expiration must use Moscow UTC+03:00")
601
+ current = now or datetime.now(expiration.tzinfo)
602
+ if not isinstance(current, datetime) or current.tzinfo is None:
603
+ raise GoskeyContractError("now must be a timezone-aware datetime")
604
+ current_moscow = current.astimezone(expiration.tzinfo)
605
+ remaining = expiration - current_moscow
606
+ if remaining <= timedelta(0):
607
+ raise GoskeyContractError("expiration must be in the future")
608
+ if remaining > timedelta(hours=24):
609
+ raise GoskeyContractError("expiration must be no more than 24 hours from submission")
610
+
611
+
612
+ BytesValue = Union[bytes, bytearray, memoryview]
613
+
614
+
615
+ def validate_detached_signature_manifest(
616
+ members: Mapping[str, BytesValue],
617
+ *,
618
+ service_code: str,
619
+ variant: Optional[SigningVariant] = None,
620
+ ) -> ManifestReport:
621
+ """Validate archive members without pretending to verify CAdES cryptography.
622
+
623
+ Every payload, including ``req.xml``, must have a non-empty adjacent
624
+ ``<payload>.sig`` member. Names must be flat and unambiguous. The request
625
+ root/namespace, document extension/count and documented 100 MB payload limit
626
+ are also checked. Actual certificate-chain and signature verification is a
627
+ separate cryptographic responsibility, reflected by the report flag.
628
+ """
629
+
630
+ capability = capability_for_service(service_code, variant)
631
+ if not isinstance(members, Mapping) or not members:
632
+ raise GoskeyContractError("manifest must be a non-empty mapping")
633
+ normalized: Dict[str, bytes] = {}
634
+ casefold_names: Dict[str, str] = {}
635
+ for name, content in members.items():
636
+ _validate_archive_name(name)
637
+ folded = name.casefold()
638
+ if folded in casefold_names:
639
+ raise GoskeyContractError(
640
+ "archive names differ only by case: {0!r} and {1!r}".format(
641
+ casefold_names[folded], name
642
+ )
643
+ )
644
+ casefold_names[folded] = name
645
+ if not isinstance(content, (bytes, bytearray, memoryview)):
646
+ raise GoskeyContractError("archive member content must be bytes")
647
+ value = bytes(content)
648
+ if not value:
649
+ raise GoskeyContractError("archive member {0!r} is empty".format(name))
650
+ normalized[name] = value
651
+
652
+ payload_names = tuple(name for name in normalized if not name.endswith(SIGNATURE_SUFFIX))
653
+ signature_names = tuple(name for name in normalized if name.endswith(SIGNATURE_SUFFIX))
654
+ if REQUEST_FILENAME not in payload_names:
655
+ raise GoskeyContractError("manifest must contain req.xml")
656
+ for payload_name in payload_names:
657
+ signature_name = payload_name + SIGNATURE_SUFFIX
658
+ if signature_name not in normalized:
659
+ raise GoskeyContractError("missing detached signature {0!r}".format(signature_name))
660
+ for signature_name in signature_names:
661
+ payload_name = signature_name[: -len(SIGNATURE_SUFFIX)]
662
+ if payload_name not in payload_names:
663
+ raise GoskeyContractError("orphan detached signature {0!r}".format(signature_name))
664
+
665
+ _validate_request_root(normalized[REQUEST_FILENAME], capability)
666
+ document_names = tuple(name for name in payload_names if name != REQUEST_FILENAME)
667
+ if not document_names:
668
+ raise GoskeyContractError("manifest must contain at least one business document")
669
+ if len(document_names) > capability.max_documents:
670
+ raise GoskeyContractError(
671
+ "document count exceeds the official limit of {0}".format(capability.max_documents)
672
+ )
673
+ for name in document_names:
674
+ _validate_document_name(name, capability.allowed_extensions)
675
+ document_bytes = sum(len(normalized[name]) for name in document_names)
676
+ if document_bytes > MAX_DOCUMENT_BYTES:
677
+ raise GoskeyContractError("business documents exceed the 100,000,000-byte limit")
678
+ return ManifestReport(
679
+ service_code=capability.service_code,
680
+ payload_names=payload_names,
681
+ signature_names=signature_names,
682
+ document_count=len(document_names),
683
+ document_bytes=document_bytes,
684
+ )
685
+
686
+
687
+ RequestType = Union[
688
+ IndividualSignRequest,
689
+ LegalEntitySignRequest,
690
+ TreasurySignRequest,
691
+ DecipherRequest,
692
+ ]
693
+
694
+
695
+ def build_signed_archive(
696
+ request: RequestType,
697
+ documents: Mapping[str, BytesValue],
698
+ signer: Signer,
699
+ ) -> bytes:
700
+ """Generate ``req.xml`` and reuse :class:`OrderArchive` to sign every payload."""
701
+
702
+ if not isinstance(
703
+ request,
704
+ (IndividualSignRequest, LegalEntitySignRequest, TreasurySignRequest, DecipherRequest),
705
+ ):
706
+ raise GoskeyContractError("request has an unsupported Goskey type")
707
+ if not isinstance(documents, Mapping):
708
+ raise GoskeyContractError("documents must be a mapping")
709
+ request_xml = request.to_xml()
710
+ capability = request.capability
711
+ preflight: Dict[str, bytes] = {
712
+ REQUEST_FILENAME: request_xml,
713
+ REQUEST_FILENAME + SIGNATURE_SUFFIX: b"preflight",
714
+ }
715
+ for name, content in documents.items():
716
+ if name in {REQUEST_FILENAME, REQUEST_FILENAME + SIGNATURE_SUFFIX} or name.endswith(
717
+ SIGNATURE_SUFFIX
718
+ ):
719
+ raise GoskeyContractError("documents must contain unsigned business payloads only")
720
+ if not isinstance(content, (bytes, bytearray, memoryview)):
721
+ raise GoskeyContractError("document content must be bytes")
722
+ preflight[name] = bytes(content)
723
+ preflight[name + SIGNATURE_SUFFIX] = b"preflight"
724
+ validate_detached_signature_manifest(
725
+ preflight,
726
+ service_code=capability.service_code,
727
+ variant=capability.variant,
728
+ )
729
+
730
+ archive = OrderArchive(signer=signer)
731
+ archive.add_signed_file(REQUEST_FILENAME, request_xml)
732
+ for name, content in documents.items():
733
+ archive.add_signed_file(name, bytes(content))
734
+ result = archive.to_bytes()
735
+ validate_detached_signature_manifest(
736
+ _read_zip_members(result),
737
+ service_code=capability.service_code,
738
+ variant=capability.variant,
739
+ )
740
+ return result
741
+
742
+
743
+ def _validate_text(value: str, field_name: str, maximum: int) -> None:
744
+ if not isinstance(value, str) or not value or len(value) > maximum:
745
+ raise GoskeyContractError(
746
+ "{0} must be a non-empty string up to {1} characters".format(field_name, maximum)
747
+ )
748
+ if any(ord(char) < 32 and char not in "\t\r\n" for char in value):
749
+ raise GoskeyContractError("{0} contains control characters".format(field_name))
750
+
751
+
752
+ def _validate_exactly_one(
753
+ first: Optional[str],
754
+ second: Optional[str],
755
+ first_name: str,
756
+ second_name: str,
757
+ ) -> None:
758
+ if (first is None) == (second is None):
759
+ raise GoskeyContractError(
760
+ "Exactly one of {0} and {1} must be supplied".format(first_name, second_name)
761
+ )
762
+
763
+
764
+ def _validate_ogrn(value: str) -> None:
765
+ if not _OGRN_RE.fullmatch(value):
766
+ raise GoskeyContractError("ogrn must contain 11, 13 or 15 digits")
767
+
768
+
769
+ def _normalize_attributes(
770
+ attributes: Iterable[GoskeyAttribute],
771
+ ) -> Tuple[GoskeyAttribute, ...]:
772
+ items = tuple(attributes)
773
+ if len(items) > 10:
774
+ raise GoskeyContractError("attributes must contain at most 10 values")
775
+ if any(not isinstance(item, GoskeyAttribute) for item in items):
776
+ raise GoskeyContractError("attributes must contain GoskeyAttribute values")
777
+ names = [item.name for item in items]
778
+ if len(names) != len(set(names)):
779
+ raise GoskeyContractError("AttributeName values must be unique")
780
+ missing = {"orgName", "orgINN"}.difference(names)
781
+ if missing:
782
+ raise GoskeyContractError(
783
+ "required Goskey attributes are missing: {0}".format(", ".join(sorted(missing)))
784
+ )
785
+ return items
786
+
787
+
788
+ def _validate_request_common(
789
+ expiration: datetime,
790
+ description: str,
791
+ backlink: Optional[str],
792
+ attributes: Sequence[GoskeyAttribute],
793
+ ) -> None:
794
+ if not isinstance(expiration, datetime) or expiration.tzinfo is None:
795
+ raise GoskeyContractError("expiration must be a timezone-aware datetime")
796
+ if expiration.utcoffset() != _MOSCOW_OFFSET:
797
+ raise GoskeyContractError("expiration must use Moscow UTC+03:00")
798
+ _validate_text(description, "Description", 250)
799
+ if backlink is not None:
800
+ _validate_text(backlink, "Backlink", 250)
801
+ normalized = _normalize_attributes(attributes)
802
+ if isinstance(attributes, tuple) and attributes == normalized:
803
+ return
804
+ # Frozen request dataclasses call this helper only for validation. Keeping
805
+ # coercion out avoids mutating caller-provided list objects unexpectedly.
806
+
807
+
808
+ def _lxml_etree() -> Any:
809
+ try:
810
+ from lxml import etree # type: ignore[import-untyped]
811
+ except ImportError as exc: # pragma: no cover - exercised without the xml extra
812
+ raise ConfigError("Goskey XML support requires: pip install 'epgu-api[xml]'") from exc
813
+ return etree
814
+
815
+
816
+ def _root(capability: GoskeyCapability) -> Any:
817
+ etree = _lxml_etree()
818
+ return etree.Element(
819
+ etree.QName(capability.namespace, capability.root_name),
820
+ nsmap={None: capability.namespace},
821
+ )
822
+
823
+
824
+ def _subelement(parent: Any, namespace: str, name: str) -> Any:
825
+ etree = _lxml_etree()
826
+ return etree.SubElement(parent, etree.QName(namespace, name))
827
+
828
+
829
+ def _text_element(parent: Any, namespace: str, name: str, value: str) -> Any:
830
+ node = _subelement(parent, namespace, name)
831
+ node.text = value
832
+ return node
833
+
834
+
835
+ def _append_identifier(
836
+ parent: Any,
837
+ namespace: str,
838
+ snils: Optional[str],
839
+ oid: Optional[str],
840
+ ) -> None:
841
+ if snils is not None:
842
+ _text_element(parent, namespace, "Snils", snils)
843
+ else:
844
+ assert oid is not None
845
+ _text_element(parent, namespace, "OID", oid)
846
+
847
+
848
+ def _append_individual(
849
+ parent: Any,
850
+ namespace: str,
851
+ recipient: IndividualRecipient,
852
+ ) -> None:
853
+ _append_identifier(parent, namespace, recipient.snils, recipient.oid)
854
+
855
+
856
+ def _format_datetime(value: datetime) -> str:
857
+ if value.microsecond == 0:
858
+ timespec = "seconds"
859
+ elif value.microsecond % 1000 == 0:
860
+ timespec = "milliseconds"
861
+ else:
862
+ timespec = "microseconds"
863
+ return value.isoformat(timespec=timespec)
864
+
865
+
866
+ def _append_common_sign_fields(parent: Any, namespace: str, request: Any) -> None:
867
+ if request.backlink is not None:
868
+ _text_element(parent, namespace, "Backlink", request.backlink)
869
+ _text_element(parent, namespace, "SignExpiration", _format_datetime(request.sign_expiration))
870
+ _text_element(parent, namespace, "Description", request.description)
871
+ _append_attributes(parent, namespace, request.attributes)
872
+
873
+
874
+ def _append_attributes(
875
+ parent: Any,
876
+ namespace: str,
877
+ attributes: Iterable[GoskeyAttribute],
878
+ ) -> None:
879
+ for attribute in attributes:
880
+ node = _subelement(parent, namespace, "Attribute")
881
+ _text_element(node, namespace, "AttributeName", attribute.name)
882
+ _text_element(node, namespace, "AttributeValue", attribute.value)
883
+
884
+
885
+ def _serialize(root: Any) -> bytes:
886
+ etree = _lxml_etree()
887
+ return etree.tostring(root, encoding="UTF-8", xml_declaration=True, pretty_print=False)
888
+
889
+
890
+ def _validate_archive_name(name: str) -> None:
891
+ if not isinstance(name, str) or not name or "\x00" in name or "\\" in name:
892
+ raise GoskeyContractError("archive member has an invalid name")
893
+ if "/" in name or posixpath.isabs(name) or name in {".", ".."}:
894
+ raise GoskeyContractError("Goskey archives must be flat and cannot contain paths")
895
+ if len(name) >= 2 and name[1] == ":":
896
+ raise GoskeyContractError("archive member has an absolute Windows path")
897
+
898
+
899
+ def _validate_document_name(name: str, extensions: Tuple[str, ...]) -> None:
900
+ if len(name) > 50:
901
+ raise GoskeyContractError("business document name exceeds 50 characters")
902
+ if not _DOCUMENT_NAME_RE.fullmatch(name):
903
+ raise GoskeyContractError("business document name contains undocumented characters")
904
+ if not any(name.lower().endswith(extension) for extension in extensions):
905
+ raise GoskeyContractError(
906
+ "business document extension must be one of: {0}".format(", ".join(extensions))
907
+ )
908
+
909
+
910
+ def _validate_request_root(xml_content: bytes, capability: GoskeyCapability) -> None:
911
+ etree = _lxml_etree()
912
+ parser = etree.XMLParser(
913
+ resolve_entities=False,
914
+ load_dtd=False,
915
+ no_network=True,
916
+ huge_tree=False,
917
+ remove_comments=False,
918
+ )
919
+ try:
920
+ root = etree.fromstring(xml_content, parser)
921
+ except etree.XMLSyntaxError as exc:
922
+ raise GoskeyContractError("req.xml is not well-formed XML: {0}".format(exc)) from exc
923
+ if root.getroottree().docinfo.doctype:
924
+ raise GoskeyContractError("req.xml must not contain a DTD")
925
+ qname = etree.QName(root)
926
+ if qname.localname != capability.root_name or qname.namespace != capability.namespace:
927
+ raise GoskeyContractError(
928
+ "req.xml root must be {{{0}}}{1}".format(capability.namespace, capability.root_name)
929
+ )
930
+
931
+
932
+ def _read_zip_members(content: bytes) -> Mapping[str, bytes]:
933
+ members: Dict[str, bytes] = {}
934
+ with zipfile.ZipFile(io.BytesIO(content), "r") as archive:
935
+ for info in archive.infolist():
936
+ if info.is_dir() or info.filename in members:
937
+ raise GoskeyContractError("generated archive contains invalid or duplicate members")
938
+ members[info.filename] = archive.read(info)
939
+ return members
940
+
941
+
942
+ __all__ = [
943
+ "CAPABILITIES",
944
+ "MAX_DIRECT_ARCHIVE_BYTES",
945
+ "MAX_DOCUMENT_BYTES",
946
+ "REQUEST_FILENAME",
947
+ "SIGNATURE_SUFFIX",
948
+ "CapabilityState",
949
+ "DecipherDocument",
950
+ "DecipherRequest",
951
+ "DecipherSignOption",
952
+ "ForeignDecipherRecipient",
953
+ "ForeignLegalRecipient",
954
+ "GoskeyAttribute",
955
+ "GoskeyCapability",
956
+ "GoskeyContractError",
957
+ "GoskeyOperation",
958
+ "IndividualRecipient",
959
+ "IndividualSignRequest",
960
+ "LegalEntitySignRequest",
961
+ "ManifestReport",
962
+ "RussianDecipherRecipient",
963
+ "RussianLegalRecipient",
964
+ "SigningVariant",
965
+ "TransportDecision",
966
+ "TransportMode",
967
+ "TreasurySignRequest",
968
+ "UnsupportedGoskeyContractError",
969
+ "build_signed_archive",
970
+ "capability_for",
971
+ "capability_for_service",
972
+ "select_transport",
973
+ "validate_detached_signature_manifest",
974
+ "validate_submission_window",
975
+ ]