pythonbeid 0.3.0__py3-none-any.whl → 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.
pythonbeid/models.py ADDED
@@ -0,0 +1,593 @@
1
+ """Typed data models describing the content of a Belgian eID card.
2
+
3
+ All models are immutable (frozen dataclasses). Field names follow the official
4
+ specification *ID and Address file contents* (applet 1.8, v5.0) published by
5
+ BOSA in the ``Fedict/eid-mw`` repository.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import base64
11
+ import enum
12
+ from dataclasses import dataclass, field, fields
13
+ from datetime import date
14
+ from types import MappingProxyType
15
+ from typing import TYPE_CHECKING, Any
16
+
17
+ if TYPE_CHECKING:
18
+ from collections.abc import Mapping
19
+
20
+ __all__ = [
21
+ "Address",
22
+ "CardFile",
23
+ "CardInfo",
24
+ "DocumentType",
25
+ "EidData",
26
+ "Identity",
27
+ "PartialDate",
28
+ "Sex",
29
+ "SpecialStatus",
30
+ "VerificationReport",
31
+ ]
32
+
33
+ _DF00 = (0x3F, 0x00, 0xDF, 0x00)
34
+ _DF01 = (0x3F, 0x00, 0xDF, 0x01)
35
+
36
+
37
+ class CardFile(enum.Enum):
38
+ """Elementary files of the Belgian eID card, identified by absolute path."""
39
+
40
+ IDENTITY = (*_DF01, 0x40, 0x31)
41
+ IDENTITY_SIGNATURE = (*_DF01, 0x40, 0x32)
42
+ ADDRESS = (*_DF01, 0x40, 0x33)
43
+ ADDRESS_SIGNATURE = (*_DF01, 0x40, 0x34)
44
+ PHOTO = (*_DF01, 0x40, 0x35)
45
+ BASIC_PUBLIC_KEY = (*_DF01, 0x40, 0x40)
46
+ """Basic public key (SubjectPublicKeyInfo DER), applet 1.8 only."""
47
+ AUTHENTICATION_CERTIFICATE = (*_DF00, 0x50, 0x38)
48
+ SIGNING_CERTIFICATE = (*_DF00, 0x50, 0x39)
49
+ CA_CERTIFICATE = (*_DF00, 0x50, 0x3A)
50
+ ROOT_CERTIFICATE = (*_DF00, 0x50, 0x3B)
51
+ RRN_CERTIFICATE = (*_DF00, 0x50, 0x3C)
52
+ """Certificate of the National Register, which signs identity and address."""
53
+
54
+ @property
55
+ def path(self) -> bytes:
56
+ """Absolute path of the file, as used in a SELECT command."""
57
+ return bytes(self.value)
58
+
59
+ @property
60
+ def is_certificate(self) -> bool:
61
+ """Whether the file holds a DER certificate padded with zero bytes."""
62
+ return self.value[:4] == _DF00
63
+
64
+
65
+ class Sex(enum.StrEnum):
66
+ """Sex of the card holder.
67
+
68
+ Cards use ``M`` for men and ``F`` (French), ``V`` (Dutch) or ``W``
69
+ (German) for women; all three are normalised to :attr:`FEMALE`.
70
+ """
71
+
72
+ MALE = "M"
73
+ FEMALE = "F"
74
+
75
+
76
+ class DocumentType(enum.IntEnum):
77
+ """Type of document (tag ``0x0F`` of the identity file).
78
+
79
+ Unknown codes do not raise: they are mapped to a pseudo-member named
80
+ ``UNKNOWN_<code>`` so new card types never break reading.
81
+ """
82
+
83
+ IDENTITY_CARD = 1
84
+ KIDS_CARD = 6
85
+ BOOTSTRAP_CARD = 7
86
+ HABILITATION_CARD = 8
87
+ FOREIGNER_A = 11
88
+ FOREIGNER_B = 12
89
+ FOREIGNER_C = 13
90
+ FOREIGNER_D = 14
91
+ FOREIGNER_E = 15
92
+ FOREIGNER_E_PLUS = 16
93
+ FOREIGNER_F = 17
94
+ FOREIGNER_F_PLUS = 18
95
+ FOREIGNER_H = 19
96
+ FOREIGNER_I = 20
97
+ FOREIGNER_J = 21
98
+ FOREIGNER_M = 22
99
+ FOREIGNER_N = 23
100
+ FOREIGNER_K = 27
101
+ FOREIGNER_L = 28
102
+ FOREIGNER_EU = 31
103
+ FOREIGNER_EU_PLUS = 32
104
+ FOREIGNER_A_2021 = 33
105
+ FOREIGNER_B_2021 = 34
106
+ FOREIGNER_F_2021 = 35
107
+ FOREIGNER_F_PLUS_2021 = 36
108
+ KIDS_FOREIGNER_EU = 61
109
+ KIDS_FOREIGNER_EU_PLUS = 62
110
+ KIDS_FOREIGNER_A = 63
111
+ KIDS_FOREIGNER_B = 64
112
+ KIDS_FOREIGNER_K = 65
113
+ KIDS_FOREIGNER_L = 66
114
+ KIDS_FOREIGNER_F = 67
115
+ KIDS_FOREIGNER_F_PLUS = 68
116
+ KIDS_FOREIGNER_M = 69
117
+
118
+ @classmethod
119
+ def _missing_(cls, value: object) -> DocumentType | None:
120
+ if not isinstance(value, int):
121
+ return None
122
+ member = int.__new__(cls, value)
123
+ member._name_ = f"UNKNOWN_{value}"
124
+ member._value_ = value
125
+ return member
126
+
127
+ @property
128
+ def description(self) -> str:
129
+ """English label, as displayed by the official eID Viewer."""
130
+ return _DOCUMENT_TYPE_LABELS.get(self.value, f"Unknown document type {self}")
131
+
132
+ @property
133
+ def is_kids_card(self) -> bool:
134
+ """Whether the document is a card for children under 12."""
135
+ return self.value == 6 or 61 <= self.value <= 69
136
+
137
+ @property
138
+ def is_foreigner_card(self) -> bool:
139
+ """Whether the document is a residence card for foreign nationals."""
140
+ return self.value >= 11
141
+
142
+
143
+ _DOCUMENT_TYPE_LABELS: dict[int, str] = {
144
+ 1: "Identity card",
145
+ 6: "Kids card",
146
+ 7: "Bootstrap card",
147
+ 8: "Habilitation card",
148
+ 11: "A. Proof of registration in the Aliens' Register - Temporary residence",
149
+ 12: "B. Proof of registration in the Aliens' Register",
150
+ 13: "C. Identity card for aliens",
151
+ 14: "D. Long-term EU resident",
152
+ 15: "E. Registration certificate",
153
+ 16: "E+. Document certifying permanent residence",
154
+ 17: "F. Residence card of a family member of a Union citizen",
155
+ 18: "F+. Permanent residence card of a family member of a Union citizen",
156
+ 19: "H. EU Blue Card",
157
+ 20: "I. ICT",
158
+ 21: "J. Mobile ICT",
159
+ 22: "M. Article 50 TEU",
160
+ 23: "N. Article 50 TEU - Local border traffic",
161
+ 27: "K. Establishment",
162
+ 28: "L. EU long-term resident",
163
+ 31: "EU. Registration - Art 8 Directive 2004/38/EC",
164
+ 32: "EU+. Permanent residence - Art 19 Directive 2004/38/EC",
165
+ 33: "A. Limited stay",
166
+ 34: "B. Unlimited stay",
167
+ 35: "F. Family member EU - Art 10 Directive 2004/38/EC",
168
+ 36: "F+. Family member EU - Art 20 Directive 2004/38/EC",
169
+ 61: "EU. Registration - Art 8 Directive 2004/38/EC (kids)",
170
+ 62: "EU+. Permanent residence - Art 19 Directive 2004/38/EC (kids)",
171
+ 63: "A. Limited stay (kids)",
172
+ 64: "B. Unlimited stay (kids)",
173
+ 65: "K. Establishment (kids)",
174
+ 66: "L. EU long-term resident (kids)",
175
+ 67: "F. Family member EU - Art 10 Directive 2004/38/EC (kids)",
176
+ 68: "F+. Family member EU - Art 20 Directive 2004/38/EC (kids)",
177
+ 69: "M. Article 50 TEU (kids)",
178
+ }
179
+
180
+
181
+ class SpecialStatus(enum.IntEnum):
182
+ """Special status of the card holder (tag ``0x10``).
183
+
184
+ The codes are an enumeration, not bit flags: 5 means yellow cane *and*
185
+ extended minority. Unknown codes map to a pseudo-member named
186
+ ``UNKNOWN_<code>``.
187
+ """
188
+
189
+ NONE = 0
190
+ WHITE_CANE = 1
191
+ EXTENDED_MINORITY = 2
192
+ WHITE_CANE_AND_EXTENDED_MINORITY = 3
193
+ YELLOW_CANE = 4
194
+ YELLOW_CANE_AND_EXTENDED_MINORITY = 5
195
+
196
+ @classmethod
197
+ def _missing_(cls, value: object) -> SpecialStatus | None:
198
+ if not isinstance(value, int):
199
+ return None
200
+ member = int.__new__(cls, value)
201
+ member._name_ = f"UNKNOWN_{value}"
202
+ member._value_ = value
203
+ return member
204
+
205
+ @property
206
+ def white_cane(self) -> bool:
207
+ """The holder is blind (white cane)."""
208
+ return self.value in (1, 3)
209
+
210
+ @property
211
+ def yellow_cane(self) -> bool:
212
+ """The holder is partially sighted (yellow cane)."""
213
+ return self.value in (4, 5)
214
+
215
+ @property
216
+ def extended_minority(self) -> bool:
217
+ """The holder is under extended minority."""
218
+ return self.value in (2, 3, 5)
219
+
220
+
221
+ @dataclass(frozen=True, slots=True)
222
+ class PartialDate:
223
+ """A date that may lack its day or month.
224
+
225
+ Belgian eID cards of some foreign nationals carry a birth date where only
226
+ the year (or the year and month) is known.
227
+ """
228
+
229
+ year: int
230
+ month: int | None = None
231
+ day: int | None = None
232
+
233
+ def __post_init__(self) -> None:
234
+ if self.month is None and self.day is not None:
235
+ msg = "a day cannot be given without a month"
236
+ raise ValueError(msg)
237
+ if self.month is not None and not 1 <= self.month <= 12:
238
+ msg = f"invalid month: {self.month}"
239
+ raise ValueError(msg)
240
+ if self.month is not None and self.day is not None:
241
+ date(self.year, self.month, self.day) # validates the day
242
+
243
+ @property
244
+ def is_complete(self) -> bool:
245
+ """Whether year, month and day are all known."""
246
+ return self.day is not None
247
+
248
+ def to_date(self) -> date:
249
+ """Return the equivalent :class:`datetime.date`.
250
+
251
+ Raises:
252
+ ValueError: If the day or the month is unknown.
253
+ """
254
+ if self.month is None or self.day is None:
255
+ msg = f"incomplete date: {self}"
256
+ raise ValueError(msg)
257
+ return date(self.year, self.month, self.day)
258
+
259
+ def __str__(self) -> str:
260
+ """ISO 8601 representation with reduced precision when incomplete."""
261
+ text = f"{self.year:04d}"
262
+ if self.month is not None:
263
+ text += f"-{self.month:02d}"
264
+ if self.day is not None:
265
+ text += f"-{self.day:02d}"
266
+ return text
267
+
268
+
269
+ def _readonly(mapping: Mapping[Any, bytes] | None = None) -> Mapping[Any, bytes]:
270
+ return MappingProxyType(dict(mapping or {}))
271
+
272
+
273
+ @dataclass(frozen=True, slots=True)
274
+ class Identity:
275
+ """Content of the identity file (``DF01/4031``).
276
+
277
+ Attributes:
278
+ card_number: Number printed on the card.
279
+ chip_number: Serial number of the chip, as uppercase hexadecimal.
280
+ validity_start: First day of validity.
281
+ validity_end: Last day of validity.
282
+ issuing_municipality: Municipality that delivered the card.
283
+ national_number: National register number (11 digits).
284
+ last_name: Last name.
285
+ first_names: The first two given names.
286
+ third_given_name_initial: First letter of the third given name.
287
+ nationality: Nationality, in the language of the card.
288
+ birth_place: Place of birth.
289
+ birth_date: Date of birth, possibly incomplete; ``None`` when the
290
+ card holds a format this library does not know (the raw value
291
+ stays in ``raw[0x0C]``).
292
+ sex: Sex, or ``None`` when the card holds an unexpected value.
293
+ noble_condition: Noble title, if any.
294
+ document_type: Type of document.
295
+ special_status: Special status flags.
296
+ photo_hash: Digest of the photo file (SHA-1, SHA-256 or SHA-384).
297
+ duplicate: Duplicate number of the card, if present.
298
+ special_organization: Code of the special organisation (foreigners).
299
+ member_of_family: Whether the holder is a family member (foreigners).
300
+ date_and_country_of_protection: Protection date and country
301
+ (``dd.mm.yyyy-CC``), if present.
302
+ work_permit: Work permit code, if present.
303
+ employer_vat_1: First employer VAT number, if present.
304
+ employer_vat_2: Second employer VAT number, if present.
305
+ regional_file_number: Regional file number, if present.
306
+ basic_key_hash: SHA-384 digest of the basic public key (applet 1.8).
307
+ brexit_mention_1: First Brexit mention code, if present.
308
+ brexit_mention_2: Second Brexit mention code, if present.
309
+ card_a_mention_1: First mention code of an A card, if present.
310
+ card_a_mention_2: Second mention code of an A card, if present.
311
+ eu_registration_date: Registration date of EU/EU+ cards, if present.
312
+ file_structure_version: Version of the file layout (tag ``0x00``), if
313
+ present.
314
+ raw: Every TLV record of the file, keyed by tag.
315
+ """
316
+
317
+ card_number: str
318
+ chip_number: str
319
+ validity_start: date
320
+ validity_end: date
321
+ issuing_municipality: str
322
+ national_number: str
323
+ last_name: str
324
+ first_names: str
325
+ third_given_name_initial: str
326
+ nationality: str
327
+ birth_place: str
328
+ birth_date: PartialDate | None
329
+ sex: Sex | None
330
+ noble_condition: str = ""
331
+ document_type: DocumentType | None = None
332
+ special_status: SpecialStatus = SpecialStatus.NONE
333
+ photo_hash: bytes = field(default=b"", repr=False)
334
+ duplicate: int | None = None
335
+ special_organization: str | None = None
336
+ member_of_family: bool = False
337
+ date_and_country_of_protection: str | None = None
338
+ work_permit: str | None = None
339
+ employer_vat_1: str | None = None
340
+ employer_vat_2: str | None = None
341
+ regional_file_number: str | None = None
342
+ basic_key_hash: bytes | None = field(default=None, repr=False)
343
+ brexit_mention_1: str | None = None
344
+ brexit_mention_2: str | None = None
345
+ card_a_mention_1: str | None = None
346
+ card_a_mention_2: str | None = None
347
+ eu_registration_date: date | None = None
348
+ file_structure_version: int | None = None
349
+ raw: Mapping[int, bytes] = field(
350
+ default_factory=_readonly, repr=False, compare=False
351
+ )
352
+
353
+ @property
354
+ def given_names(self) -> str:
355
+ """First two given names followed by the initial of the third one."""
356
+ return " ".join(
357
+ part for part in (self.first_names, self.third_given_name_initial) if part
358
+ )
359
+
360
+ @property
361
+ def national_number_valid(self) -> bool:
362
+ """Whether the national number passes the modulo-97 checksum."""
363
+ from .parser import is_valid_national_number # noqa: PLC0415 - cycle
364
+
365
+ return is_valid_national_number(self.national_number)
366
+
367
+ def is_valid_on(self, day: date) -> bool:
368
+ """Whether the card is within its validity period on *day*."""
369
+ return self.validity_start <= day <= self.validity_end
370
+
371
+ def to_dict(self) -> dict[str, Any]:
372
+ """Return a JSON-serialisable representation (``raw`` excluded)."""
373
+ return {
374
+ f.name: _jsonable(getattr(self, f.name))
375
+ for f in fields(self)
376
+ if f.name != "raw"
377
+ }
378
+
379
+
380
+ @dataclass(frozen=True, slots=True)
381
+ class Address:
382
+ """Content of the address file (``DF01/4033``).
383
+
384
+ Attributes:
385
+ street: Street name and house number.
386
+ postal_code: Postal code.
387
+ municipality: Municipality.
388
+ file_structure_version: Version of the file layout, if present.
389
+ raw: Every TLV record of the file, keyed by tag.
390
+ """
391
+
392
+ street: str
393
+ postal_code: str
394
+ municipality: str
395
+ file_structure_version: int | None = None
396
+ raw: Mapping[int, bytes] = field(
397
+ default_factory=_readonly, repr=False, compare=False
398
+ )
399
+
400
+ def to_dict(self) -> dict[str, Any]:
401
+ """Return a JSON-serialisable representation (``raw`` excluded)."""
402
+ return {
403
+ f.name: _jsonable(getattr(self, f.name))
404
+ for f in fields(self)
405
+ if f.name != "raw"
406
+ }
407
+
408
+
409
+ @dataclass(frozen=True, slots=True)
410
+ class CardInfo:
411
+ """Chip information returned by the GET CARD DATA command.
412
+
413
+ Attributes:
414
+ serial_number: Chip serial number, as uppercase hexadecimal.
415
+ component_code: Component code.
416
+ os_number: Operating system number.
417
+ os_version: Operating system version.
418
+ softmask_number: Softmask number.
419
+ softmask_version: Softmask version.
420
+ applet_version: Applet version byte (``0x17`` for 1.7, ``0x18`` for
421
+ 1.8).
422
+ global_os_version: Global OS version.
423
+ applet_interface_version: Applet interface version.
424
+ pkcs1_support: PKCS#1 support byte.
425
+ key_exchange_version: Key exchange version.
426
+ lifecycle: Applet life cycle state.
427
+ pin_attempts_left: Remaining PIN attempts, applet 1.8 only.
428
+ """
429
+
430
+ serial_number: str
431
+ component_code: int
432
+ os_number: int
433
+ os_version: int
434
+ softmask_number: int
435
+ softmask_version: int
436
+ applet_version: int
437
+ global_os_version: int
438
+ applet_interface_version: int
439
+ pkcs1_support: int
440
+ key_exchange_version: int
441
+ lifecycle: int
442
+ pin_attempts_left: int | None = None
443
+
444
+ @property
445
+ def applet_version_string(self) -> str:
446
+ """Applet version in dotted form, e.g. ``"1.8"``."""
447
+ return f"{self.applet_version >> 4}.{self.applet_version & 0x0F}"
448
+
449
+ @property
450
+ def has_basic_key(self) -> bool:
451
+ """Whether the applet supports the basic key (applet 1.8 and later)."""
452
+ return self.applet_version >= 0x18
453
+
454
+ def to_dict(self) -> dict[str, Any]:
455
+ """Return a JSON-serialisable representation."""
456
+ data = {f.name: _jsonable(getattr(self, f.name)) for f in fields(self)}
457
+ data["applet_version_string"] = self.applet_version_string
458
+ return data
459
+
460
+
461
+ @dataclass(frozen=True, slots=True)
462
+ class EidData:
463
+ """Everything read from a card in one go.
464
+
465
+ Attributes:
466
+ identity: Identity file content.
467
+ address: Address file content.
468
+ card: Chip information (GET CARD DATA). It is not signed by the
469
+ card issuer, so it is informative only; ``None`` when the data
470
+ was not read from a live card.
471
+ photo: JPEG photo, or ``None`` when it was not read.
472
+ files: Raw content of every file that was read, keyed by file. It is
473
+ what :func:`pythonbeid.verify_eid` checks.
474
+ """
475
+
476
+ identity: Identity
477
+ address: Address
478
+ card: CardInfo | None = None
479
+ photo: bytes | None = field(default=None, repr=False)
480
+ files: Mapping[CardFile, bytes] = field(
481
+ default_factory=_readonly, repr=False, compare=False
482
+ )
483
+
484
+ @classmethod
485
+ def from_files(
486
+ cls, files: Mapping[CardFile, bytes], card: CardInfo | None = None
487
+ ) -> EidData:
488
+ """Decode raw card files, e.g. received by a server from a client.
489
+
490
+ Args:
491
+ files: Raw files; the identity and address files are required.
492
+ card: Chip information, if known.
493
+
494
+ Raises:
495
+ KeyError: If the identity or address file is missing.
496
+ CardDataError: If a file cannot be decoded.
497
+ """
498
+ from .parser import parse_address, parse_identity # noqa: PLC0415 - cycle
499
+
500
+ return cls(
501
+ identity=parse_identity(files[CardFile.IDENTITY]),
502
+ address=parse_address(files[CardFile.ADDRESS]),
503
+ card=card,
504
+ photo=files.get(CardFile.PHOTO),
505
+ files=_readonly(files),
506
+ )
507
+
508
+ def to_dict(self, *, include_photo: bool = True) -> dict[str, Any]:
509
+ """Return a JSON-serialisable representation.
510
+
511
+ Args:
512
+ include_photo: Include the photo as a base-64 string.
513
+ """
514
+ data: dict[str, Any] = {
515
+ "card": None if self.card is None else self.card.to_dict(),
516
+ "identity": self.identity.to_dict(),
517
+ "address": self.address.to_dict(),
518
+ }
519
+ if include_photo and self.photo is not None:
520
+ data["photo"] = base64.b64encode(self.photo).decode("ascii")
521
+ return data
522
+
523
+
524
+ @dataclass(frozen=True, slots=True)
525
+ class VerificationReport:
526
+ """Outcome of the integrity checks of a card.
527
+
528
+ A ``None`` value means the check does not apply or could not be run (for
529
+ example the photo was not read, or the card has no basic key).
530
+
531
+ Attributes:
532
+ photo_hash_valid: The photo matches the digest in the identity file.
533
+ identity_signature_valid: The identity file is signed by the RRN.
534
+ address_signature_valid: The address file is signed by the RRN.
535
+ rrn_certificate_trusted: The RRN certificate chains up to a trusted
536
+ Belgian root certificate.
537
+ rrn_certificate_period_valid: The validity period of the RRN
538
+ certificate overlaps the validity period of the card. (Cards
539
+ re-signed after issuance carry a newer certificate, and the
540
+ certificate of a valid card may have expired since.)
541
+ content_matches_files: The decoded identity, address and photo are
542
+ exactly those of the signed raw files.
543
+ basic_key_valid: The basic public key matches its signed digest
544
+ (applet 1.8).
545
+ chip_authenticated: The chip proved it holds the basic private key
546
+ (applet 1.8, live card only).
547
+ errors: Human-readable reasons for every failed check.
548
+ """
549
+
550
+ photo_hash_valid: bool | None
551
+ identity_signature_valid: bool
552
+ address_signature_valid: bool
553
+ rrn_certificate_trusted: bool
554
+ rrn_certificate_period_valid: bool
555
+ content_matches_files: bool = True
556
+ basic_key_valid: bool | None = None
557
+ chip_authenticated: bool | None = None
558
+ errors: tuple[str, ...] = ()
559
+
560
+ @property
561
+ def is_valid(self) -> bool:
562
+ """Whether no applicable check failed."""
563
+ checks = (
564
+ self.photo_hash_valid,
565
+ self.identity_signature_valid,
566
+ self.address_signature_valid,
567
+ self.rrn_certificate_trusted,
568
+ self.rrn_certificate_period_valid,
569
+ self.content_matches_files,
570
+ self.basic_key_valid,
571
+ self.chip_authenticated,
572
+ )
573
+ return all(check is not False for check in checks)
574
+
575
+ def to_dict(self) -> dict[str, Any]:
576
+ """Return a JSON-serialisable representation."""
577
+ data = {f.name: _jsonable(getattr(self, f.name)) for f in fields(self)}
578
+ data["is_valid"] = self.is_valid
579
+ return data
580
+
581
+
582
+ def _jsonable(value: Any) -> Any:
583
+ if isinstance(value, enum.Enum):
584
+ return value.value
585
+ if isinstance(value, PartialDate):
586
+ return str(value)
587
+ if isinstance(value, date):
588
+ return value.isoformat()
589
+ if isinstance(value, bytes):
590
+ return value.hex()
591
+ if isinstance(value, tuple):
592
+ return list(value)
593
+ return value