usp-mp 1.3.20261124__tar.gz

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.
Files changed (42) hide show
  1. usp_mp-1.3.20261124/LICENSE +28 -0
  2. usp_mp-1.3.20261124/MANIFEST.in +4 -0
  3. usp_mp-1.3.20261124/PKG-INFO +133 -0
  4. usp_mp-1.3.20261124/README.md +98 -0
  5. usp_mp-1.3.20261124/pyproject.toml +71 -0
  6. usp_mp-1.3.20261124/setup.cfg +4 -0
  7. usp_mp-1.3.20261124/src/usp_mp/__init__.py +18 -0
  8. usp_mp-1.3.20261124/src/usp_mp/adapter.py +254 -0
  9. usp_mp-1.3.20261124/src/usp_mp/certs/brz_ca.cer +33 -0
  10. usp_mp-1.3.20261124/src/usp_mp/cli.py +179 -0
  11. usp_mp-1.3.20261124/src/usp_mp/errors.py +37 -0
  12. usp_mp-1.3.20261124/src/usp_mp/mail.py +393 -0
  13. usp_mp-1.3.20261124/src/usp_mp/py.typed +0 -0
  14. usp_mp-1.3.20261124/src/usp_mp/util.py +85 -0
  15. usp_mp-1.3.20261124/src/usp_mp/wsdl/PATCHES.md +36 -0
  16. usp_mp-1.3.20261124/src/usp_mp/wsdl/W3C-XMLDSig.xsd +265 -0
  17. usp_mp-1.3.20261124/src/usp_mp/wsdl/zuse_mypersondata_en_p2.xsd +348 -0
  18. usp_mp-1.3.20261124/src/usp_mp/wsdl/zuse_p2.xsd +1118 -0
  19. usp_mp-1.3.20261124/src/usp_mp/wsdl/zuseaa_p2.wsdl +104 -0
  20. usp_mp-1.3.20261124/src/usp_mp/wsdl/zuseaa_p2.xsd +452 -0
  21. usp_mp-1.3.20261124/src/usp_mp/wsdl/zusetypes_p2.xsd +175 -0
  22. usp_mp-1.3.20261124/src/usp_mp.egg-info/PKG-INFO +133 -0
  23. usp_mp-1.3.20261124/src/usp_mp.egg-info/SOURCES.txt +40 -0
  24. usp_mp-1.3.20261124/src/usp_mp.egg-info/dependency_links.txt +1 -0
  25. usp_mp-1.3.20261124/src/usp_mp.egg-info/entry_points.txt +2 -0
  26. usp_mp-1.3.20261124/src/usp_mp.egg-info/requires.txt +8 -0
  27. usp_mp-1.3.20261124/src/usp_mp.egg-info/top_level.txt +1 -0
  28. usp_mp-1.3.20261124/tests/conftest.py +150 -0
  29. usp_mp-1.3.20261124/tests/data/demo_snapshot.json +397 -0
  30. usp_mp-1.3.20261124/tests/data/get_delivery_response.xml +1 -0
  31. usp_mp-1.3.20261124/tests/fakes.py +292 -0
  32. usp_mp-1.3.20261124/tests/snapshot.py +24 -0
  33. usp_mp-1.3.20261124/tests/test_adapter_tls.py +416 -0
  34. usp_mp-1.3.20261124/tests/test_ca.py +49 -0
  35. usp_mp-1.3.20261124/tests/test_cli.py +388 -0
  36. usp_mp-1.3.20261124/tests/test_demo.py +508 -0
  37. usp_mp-1.3.20261124/tests/test_errors.py +53 -0
  38. usp_mp-1.3.20261124/tests/test_import.py +39 -0
  39. usp_mp-1.3.20261124/tests/test_mail.py +651 -0
  40. usp_mp-1.3.20261124/tests/test_snapshot.py +34 -0
  41. usp_mp-1.3.20261124/tests/test_util.py +115 -0
  42. usp_mp-1.3.20261124/tests/test_wsdl.py +153 -0
@@ -0,0 +1,28 @@
1
+ BSD 3-Clause License
2
+
3
+ Copyright (c) 2026, Martin J. Laubach
4
+
5
+ Redistribution and use in source and binary forms, with or without
6
+ modification, are permitted provided that the following conditions are met:
7
+
8
+ 1. Redistributions of source code must retain the above copyright notice, this
9
+ list of conditions and the following disclaimer.
10
+
11
+ 2. Redistributions in binary form must reproduce the above copyright notice,
12
+ this list of conditions and the following disclaimer in the documentation
13
+ and/or other materials provided with the distribution.
14
+
15
+ 3. Neither the name of the copyright holder nor the names of its
16
+ contributors may be used to endorse or promote products derived from
17
+ this software without specific prior written permission.
18
+
19
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
20
+ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21
+ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
22
+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
23
+ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24
+ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
25
+ SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
26
+ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
27
+ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28
+ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
@@ -0,0 +1,4 @@
1
+ # Ship the complete test suite in the sdist (setuptools only picks up tests/test_*.py by default,
2
+ # which leaves out conftest.py, fakes.py, snapshot.py and tests/data/).
3
+ graft tests
4
+ global-exclude __pycache__ *.py[cod]
@@ -0,0 +1,133 @@
1
+ Metadata-Version: 2.4
2
+ Name: usp-mp
3
+ Version: 1.3.20261124
4
+ Summary: Client for the Mein Postkorb automatic retrieval (Automatische Abholung) service of the Austrian Unternehmensserviceportal (USP)
5
+ Author-email: "Martin J. Laubach" <mjl@laubach.at>
6
+ License-Expression: BSD-3-Clause
7
+ Project-URL: Homepage, https://github.com/mjl/usp-mp
8
+ Project-URL: Documentation, https://github.com/mjl/usp-mp/blob/master/docs/howto.md
9
+ Project-URL: Changelog, https://github.com/mjl/usp-mp/blob/master/docs/CHANGELOG.md
10
+ Project-URL: Issues, https://github.com/mjl/usp-mp/issues
11
+ Keywords: USP,Unternehmensserviceportal,Mein Postkorb,Automatische Abholung,e-Zustellung,Austria,SOAP
12
+ Classifier: Development Status :: 4 - Beta
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: Operating System :: OS Independent
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Programming Language :: Python :: 3 :: Only
17
+ Classifier: Programming Language :: Python :: 3.11
18
+ Classifier: Programming Language :: Python :: 3.12
19
+ Classifier: Programming Language :: Python :: 3.13
20
+ Classifier: Programming Language :: Python :: 3.14
21
+ Classifier: Topic :: Communications
22
+ Classifier: Topic :: Office/Business
23
+ Classifier: Typing :: Typed
24
+ Requires-Python: >=3.11
25
+ Description-Content-Type: text/markdown
26
+ License-File: LICENSE
27
+ Requires-Dist: zeep>=4.3.3
28
+ Requires-Dist: requests>=2.32.4
29
+ Requires-Dist: urllib3>=2.8.0
30
+ Requires-Dist: lxml>=6.1.1
31
+ Requires-Dist: cryptography>=48.0.1
32
+ Provides-Extra: dev
33
+ Requires-Dist: pytest>=7; extra == "dev"
34
+ Dynamic: license-file
35
+
36
+
37
+
38
+
39
+ # USP Mein Postkorb
40
+
41
+ This package provides access to the *Mein Postkorb* service of the Austrian Government's *Unternehmensserviceportal* (see references below).
42
+ You can retrieve new or all deliveries (Nachrichten), mark them as read or delete them, and download attachments.
43
+
44
+ # Installation
45
+
46
+ Requires Python 3.11 or newer. Install from PyPI:
47
+
48
+ ```bash
49
+ pip install usp-mp
50
+ ```
51
+
52
+ This installs the `usp_mp` library and the `uspmp` command line tool:
53
+
54
+ ```bash
55
+ uspmp --help
56
+ ```
57
+
58
+ To install only the command line tool, in its own environment, use `pipx install usp-mp` or `uv tool install usp-mp` instead.
59
+
60
+ To install from source, for example for development:
61
+
62
+ ```bash
63
+ git clone https://github.com/mjl/usp-mp.git
64
+ cd usp-mp
65
+ python -m venv .venv && . .venv/bin/activate
66
+ pip install -e '.[dev]'
67
+ ```
68
+
69
+ You also need a client certificate (`.p12`) for the *Automatische Abholung*; see [docs/howto.md](https://github.com/mjl/usp-mp/blob/master/docs/howto.md) for how to obtain one and for usage.
70
+
71
+ # Development
72
+
73
+ Run the tests (no certificate or network needed; a fake service stands in for Mein Postkorb):
74
+
75
+ ```bash
76
+ pip install -e '.[dev]'
77
+ pytest
78
+ ```
79
+
80
+ Or, with [uv](https://docs.astral.sh/uv/), on a specific Python version. Run at least the oldest (3.11) and the newest supported version:
81
+
82
+ ```bash
83
+ uv run --no-project --python 3.11 --with-editable '.[dev]' pytest
84
+ uv run --no-project --python 3.14 --with-editable '.[dev]' pytest
85
+ ```
86
+
87
+ ## Tests against the demo service
88
+
89
+ `tests/test_demo.py` runs against the Mein Postkorb **demo (TEST) endpoint**. It covers TLS with the client certificate, querying and paging, metadata, downloads with checksum verification, the documented error responses, close/delete, and the `uspmp` CLI.
90
+
91
+ The demo always returns the same mock data, and the tests check it against expected results in three layers:
92
+
93
+ 1. **Invariants** that hold for any data: `HitCount` matches, paging reassembles the full list, checksums verify, and so on.
94
+ 2. **Values documented in the vendor HowTo:** the 10 delivery IDs in order, the 3 new ones, and the attachment-download example.
95
+ 3. **A golden snapshot** of everything else in [tests/data/demo_snapshot.json](https://github.com/mjl/usp-mp/blob/master/tests/data/demo_snapshot.json): subjects, timestamps, and attachment IDs, names, MIME types, sizes and checksums. A mismatch lists each difference by path. If BRZ refreshes the demo data, re-record it with `--update-demo-snapshot` (plus the certificate options) and review the diff before committing.
96
+
97
+ **You must bring your own client certificate and password.** Neither is part of this repository, and no test contains or defaults to one. Each person running these tests uses a `.p12` issued for their own USP account (see the certificate setup checklist in [docs/howto.md](https://github.com/mjl/usp-mp/blob/master/docs/howto.md)). Without a certificate, the demo tests are skipped and everything else runs normally.
98
+
99
+ Provide the certificate and password with pytest options or environment variables (options win):
100
+
101
+ | What | Option | Environment variable |
102
+ |---|---|---|
103
+ | Certificate | `--p12=PATH` | `USP_MP_P12` |
104
+ | Password, from a file (first line) | `--p12-password-file=PATH` | `USP_MP_P12_PASS_FILE` |
105
+ | Password, as a value (empty means none) | `--p12-password=VALUE` | `USP_MP_P12_PASS` |
106
+ | Re-record the snapshot instead of comparing | `--update-demo-snapshot` | |
107
+
108
+ ```bash
109
+ # only the demo tests
110
+ pytest -m demo --p12=$HOME/secrets/usp.p12 --p12-password-file=$HOME/secrets/usp.pw
111
+
112
+ # everything, configured through the environment
113
+ export USP_MP_P12=$HOME/secrets/usp.p12 USP_MP_P12_PASS_FILE=$HOME/secrets/usp.pw
114
+ pytest
115
+ ```
116
+
117
+ Notes:
118
+
119
+ - Write the options with `=`, as above. With `--p12 PATH`, pytest mistakes the path for a test location before it reads the project configuration, and then reports the option as unknown.
120
+ - Prefer a password file (mode `0600`) over `--p12-password` or `USP_MP_P12_PASS`, since a value on the command line is visible to other users in the process list.
121
+ - Keep the certificate and password file outside the repository. `*.p12` is in `.gitignore` as a safety net, but a password file is not.
122
+ - If a certificate is given without any password source, or the file doesn't exist, pytest stops with a usage error instead of silently skipping. A wrong password makes the demo tests fail, not skip.
123
+ - The tests only ever use the demo endpoint and refuse to run against production. They call close and delete, which per the vendor HowTo succeed on the demo without changing its mock data.
124
+ - `pytest --help` lists the options under "Mein Postkorb demo-service tests".
125
+
126
+ # License
127
+
128
+ BSD 3-Clause; see [LICENSE](https://github.com/mjl/usp-mp/blob/master/LICENSE). BRZ's documents are not redistributed here (see [docs/api_docs/README.md](https://github.com/mjl/usp-mp/blob/master/docs/api_docs/README.md)). The bundled WSDL/XSDs are BRZ's service definition, with local changes listed in `src/usp_mp/wsdl/PATCHES.md`.
129
+
130
+ # References
131
+
132
+ * Austrian [Unternehmensserviceportal](https://www.usp.gv.at/)
133
+ * [Mein Postkorb Automatische Abholung HowTo](https://www.usp.gv.at/at.gv.mpk-p/aadocs/Mein_Postkorb_AutomatischeAbholung_HowTo.pdf)
@@ -0,0 +1,98 @@
1
+
2
+
3
+
4
+ # USP Mein Postkorb
5
+
6
+ This package provides access to the *Mein Postkorb* service of the Austrian Government's *Unternehmensserviceportal* (see references below).
7
+ You can retrieve new or all deliveries (Nachrichten), mark them as read or delete them, and download attachments.
8
+
9
+ # Installation
10
+
11
+ Requires Python 3.11 or newer. Install from PyPI:
12
+
13
+ ```bash
14
+ pip install usp-mp
15
+ ```
16
+
17
+ This installs the `usp_mp` library and the `uspmp` command line tool:
18
+
19
+ ```bash
20
+ uspmp --help
21
+ ```
22
+
23
+ To install only the command line tool, in its own environment, use `pipx install usp-mp` or `uv tool install usp-mp` instead.
24
+
25
+ To install from source, for example for development:
26
+
27
+ ```bash
28
+ git clone https://github.com/mjl/usp-mp.git
29
+ cd usp-mp
30
+ python -m venv .venv && . .venv/bin/activate
31
+ pip install -e '.[dev]'
32
+ ```
33
+
34
+ You also need a client certificate (`.p12`) for the *Automatische Abholung*; see [docs/howto.md](https://github.com/mjl/usp-mp/blob/master/docs/howto.md) for how to obtain one and for usage.
35
+
36
+ # Development
37
+
38
+ Run the tests (no certificate or network needed; a fake service stands in for Mein Postkorb):
39
+
40
+ ```bash
41
+ pip install -e '.[dev]'
42
+ pytest
43
+ ```
44
+
45
+ Or, with [uv](https://docs.astral.sh/uv/), on a specific Python version. Run at least the oldest (3.11) and the newest supported version:
46
+
47
+ ```bash
48
+ uv run --no-project --python 3.11 --with-editable '.[dev]' pytest
49
+ uv run --no-project --python 3.14 --with-editable '.[dev]' pytest
50
+ ```
51
+
52
+ ## Tests against the demo service
53
+
54
+ `tests/test_demo.py` runs against the Mein Postkorb **demo (TEST) endpoint**. It covers TLS with the client certificate, querying and paging, metadata, downloads with checksum verification, the documented error responses, close/delete, and the `uspmp` CLI.
55
+
56
+ The demo always returns the same mock data, and the tests check it against expected results in three layers:
57
+
58
+ 1. **Invariants** that hold for any data: `HitCount` matches, paging reassembles the full list, checksums verify, and so on.
59
+ 2. **Values documented in the vendor HowTo:** the 10 delivery IDs in order, the 3 new ones, and the attachment-download example.
60
+ 3. **A golden snapshot** of everything else in [tests/data/demo_snapshot.json](https://github.com/mjl/usp-mp/blob/master/tests/data/demo_snapshot.json): subjects, timestamps, and attachment IDs, names, MIME types, sizes and checksums. A mismatch lists each difference by path. If BRZ refreshes the demo data, re-record it with `--update-demo-snapshot` (plus the certificate options) and review the diff before committing.
61
+
62
+ **You must bring your own client certificate and password.** Neither is part of this repository, and no test contains or defaults to one. Each person running these tests uses a `.p12` issued for their own USP account (see the certificate setup checklist in [docs/howto.md](https://github.com/mjl/usp-mp/blob/master/docs/howto.md)). Without a certificate, the demo tests are skipped and everything else runs normally.
63
+
64
+ Provide the certificate and password with pytest options or environment variables (options win):
65
+
66
+ | What | Option | Environment variable |
67
+ |---|---|---|
68
+ | Certificate | `--p12=PATH` | `USP_MP_P12` |
69
+ | Password, from a file (first line) | `--p12-password-file=PATH` | `USP_MP_P12_PASS_FILE` |
70
+ | Password, as a value (empty means none) | `--p12-password=VALUE` | `USP_MP_P12_PASS` |
71
+ | Re-record the snapshot instead of comparing | `--update-demo-snapshot` | |
72
+
73
+ ```bash
74
+ # only the demo tests
75
+ pytest -m demo --p12=$HOME/secrets/usp.p12 --p12-password-file=$HOME/secrets/usp.pw
76
+
77
+ # everything, configured through the environment
78
+ export USP_MP_P12=$HOME/secrets/usp.p12 USP_MP_P12_PASS_FILE=$HOME/secrets/usp.pw
79
+ pytest
80
+ ```
81
+
82
+ Notes:
83
+
84
+ - Write the options with `=`, as above. With `--p12 PATH`, pytest mistakes the path for a test location before it reads the project configuration, and then reports the option as unknown.
85
+ - Prefer a password file (mode `0600`) over `--p12-password` or `USP_MP_P12_PASS`, since a value on the command line is visible to other users in the process list.
86
+ - Keep the certificate and password file outside the repository. `*.p12` is in `.gitignore` as a safety net, but a password file is not.
87
+ - If a certificate is given without any password source, or the file doesn't exist, pytest stops with a usage error instead of silently skipping. A wrong password makes the demo tests fail, not skip.
88
+ - The tests only ever use the demo endpoint and refuse to run against production. They call close and delete, which per the vendor HowTo succeed on the demo without changing its mock data.
89
+ - `pytest --help` lists the options under "Mein Postkorb demo-service tests".
90
+
91
+ # License
92
+
93
+ BSD 3-Clause; see [LICENSE](https://github.com/mjl/usp-mp/blob/master/LICENSE). BRZ's documents are not redistributed here (see [docs/api_docs/README.md](https://github.com/mjl/usp-mp/blob/master/docs/api_docs/README.md)). The bundled WSDL/XSDs are BRZ's service definition, with local changes listed in `src/usp_mp/wsdl/PATCHES.md`.
94
+
95
+ # References
96
+
97
+ * Austrian [Unternehmensserviceportal](https://www.usp.gv.at/)
98
+ * [Mein Postkorb Automatische Abholung HowTo](https://www.usp.gv.at/at.gv.mpk-p/aadocs/Mein_Postkorb_AutomatischeAbholung_HowTo.pdf)
@@ -0,0 +1,71 @@
1
+ [project]
2
+ name = "usp-mp"
3
+ dynamic = ["version"]
4
+ description = "Client for the Mein Postkorb automatic retrieval (Automatische Abholung) service of the Austrian Unternehmensserviceportal (USP)"
5
+ keywords = ["USP", "Unternehmensserviceportal", "Mein Postkorb", "Automatische Abholung", "e-Zustellung", "Austria", "SOAP"]
6
+ classifiers = [
7
+ "Development Status :: 4 - Beta",
8
+ "Intended Audience :: Developers",
9
+ "Operating System :: OS Independent",
10
+ "Programming Language :: Python :: 3",
11
+ "Programming Language :: Python :: 3 :: Only",
12
+ "Programming Language :: Python :: 3.11",
13
+ "Programming Language :: Python :: 3.12",
14
+ "Programming Language :: Python :: 3.13",
15
+ "Programming Language :: Python :: 3.14",
16
+ "Topic :: Communications",
17
+ "Topic :: Office/Business",
18
+ "Typing :: Typed",
19
+ ]
20
+ readme = "README.md"
21
+ license = "BSD-3-Clause"
22
+ license-files = ["LICENSE"]
23
+ authors = [
24
+ { name = "Martin J. Laubach", email = "mjl@laubach.at" }
25
+ ]
26
+ requires-python = ">=3.11"
27
+ dependencies = [
28
+ # Floors pick up security fixes; see docs/CHANGELOG.md. Older versions that still pass the
29
+ # tests: requests 2.28, urllib3 1.26, cryptography 42.0.8, lxml 6.0 (5.x has no 3.14 wheels).
30
+ "zeep>=4.3.3", # GHSA-4cc2-g9w2-fhf6; zeep < 4.3 fails on Python 3.13+ (imports cgi)
31
+ "requests>=2.32.4", # CVE-2024-47081 (.netrc credentials leak); also CVE-2024-35195
32
+ "urllib3>=2.8.0", # imported directly (adapter.py); GHSA-8988-9cw3-xx77, decompression-bomb fixes
33
+ "lxml>=6.1.1", # imported directly (mail.py); CVE-2026-41066 (XXE by default), patched libxslt
34
+ "cryptography>=48.0.1", # GHSA-537c-gmf6-5ccf (vulnerable OpenSSL in wheels)
35
+ ]
36
+
37
+ [project.urls]
38
+ Homepage = "https://github.com/mjl/usp-mp"
39
+ Documentation = "https://github.com/mjl/usp-mp/blob/master/docs/howto.md"
40
+ Changelog = "https://github.com/mjl/usp-mp/blob/master/docs/CHANGELOG.md"
41
+ Issues = "https://github.com/mjl/usp-mp/issues"
42
+
43
+ [project.scripts]
44
+ uspmp = "usp_mp.cli:main"
45
+
46
+ [project.optional-dependencies]
47
+ dev = [
48
+ "pytest>=7",
49
+ ]
50
+
51
+ [tool.pytest.ini_options]
52
+ testpaths = ["tests"]
53
+ markers = [
54
+ "demo: integration tests against the demo service (need USP_MP_P12 and USP_MP_P12_PASS)",
55
+ ]
56
+
57
+ [build-system]
58
+ requires = ["setuptools>=77.0"] # PEP 639 license expression
59
+ build-backend = "setuptools.build_meta"
60
+
61
+ [tool.setuptools.package-data]
62
+ "usp_mp" = [
63
+ "certs/*",
64
+ "wsdl/*",
65
+ ]
66
+
67
+ [tool.setuptools.packages.find]
68
+ where = ["src"]
69
+
70
+ [tool.setuptools.dynamic]
71
+ version = {attr = "usp_mp.__version__"}
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,18 @@
1
+ # Copyright (c) 2026, Martin J. Laubach
2
+ # SPDX-License-Identifier: BSD-3-Clause
3
+
4
+ from .adapter import USP_MP_Adapter
5
+ from .errors import ApiError, CertificateError, ChecksumError, MailboxStateError, UspMpError
6
+ from .mail import Mailbox
7
+
8
+ __all__ = [
9
+ 'ApiError',
10
+ 'CertificateError',
11
+ 'ChecksumError',
12
+ 'Mailbox',
13
+ 'MailboxStateError',
14
+ 'USP_MP_Adapter',
15
+ 'UspMpError',
16
+ ]
17
+
18
+ __version__ = '1.3.20261124'
@@ -0,0 +1,254 @@
1
+ # Copyright (c) 2026, Martin J. Laubach
2
+ # SPDX-License-Identifier: BSD-3-Clause
3
+
4
+ import datetime
5
+ import logging
6
+ import os
7
+ import secrets
8
+ from dataclasses import dataclass
9
+ from typing import Any
10
+ import ssl
11
+ import tempfile
12
+ from urllib.parse import urljoin
13
+
14
+ import requests
15
+ from requests.adapters import HTTPAdapter
16
+ from urllib3.util.ssl_ import create_urllib3_context
17
+
18
+ from cryptography.hazmat.primitives import serialization
19
+ from cryptography.hazmat.primitives.serialization import pkcs12
20
+ from cryptography.hazmat.backends import default_backend
21
+
22
+ from zeep import Client, Settings
23
+
24
+ from .errors import CertificateError, MailboxStateError
25
+
26
+ logger = logging.getLogger(__name__)
27
+
28
+ # Warn this long before the client certificate expires
29
+ CERTIFICATE_EXPIRY_WARNING = datetime.timedelta(days=30)
30
+ from zeep.transports import Transport
31
+ from zeep.wsdl import Document
32
+
33
+
34
+ class SSLContextAdapter(HTTPAdapter):
35
+ """requests transport adapter that uses a preconfigured SSLContext.
36
+
37
+ The context already carries the client certificate and the trusted CA,
38
+ so no certificate or key files are needed while the session is in use.
39
+ """
40
+
41
+ def __init__(self, ssl_context: ssl.SSLContext, **kwargs) -> None:
42
+ self._ssl_context = ssl_context
43
+ super().__init__(**kwargs)
44
+
45
+ def init_poolmanager(self, *args, **kwargs):
46
+ kwargs["ssl_context"] = self._ssl_context
47
+ return super().init_poolmanager(*args, **kwargs)
48
+
49
+ def proxy_manager_for(self, proxy, **proxy_kwargs):
50
+ # Without this, an HTTPS_PROXY setting would bypass the client certificate.
51
+ proxy_kwargs["ssl_context"] = self._ssl_context
52
+ return super().proxy_manager_for(proxy, **proxy_kwargs)
53
+
54
+
55
+ def _write_private_file(path: str, data: bytes) -> None:
56
+ fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
57
+ with os.fdopen(fd, "wb") as f:
58
+ f.write(data)
59
+
60
+
61
+ @dataclass(frozen=True)
62
+ class QueryTypes:
63
+ """zeep types for building QueryDeliveries selectors, resolved from the bundled WSDL."""
64
+
65
+ AllDeliveriesType: Any
66
+ PagingType: Any
67
+ NewDeliveriesOnlyType: Any
68
+
69
+
70
+ class USP_MP_Adapter:
71
+ """Certificate, TLS context and parsed WSDL for one Mein Postkorb endpoint.
72
+
73
+ Not thread-safe: a connection's requests.Session and zeep client must not be
74
+ shared between threads. Use one Mailbox (and so one adapter) per thread.
75
+ """
76
+
77
+ DEMO_ENDPOINT_URL = "https://demo-autoabholung.meinpostkorb.brz.gv.at"
78
+ PROD_ENDPOINT_URL = "https://autoabholung.meinpostkorb.brz.gv.at"
79
+
80
+ VERSION = "2.4.0-004"
81
+ WSDL_PATH = os.path.join(os.path.dirname(__file__), 'wsdl', 'zuseaa_p2.wsdl')
82
+ CA_PATH = os.path.join(os.path.dirname(__file__), 'certs', 'brz_ca.cer')
83
+ TIMEOUT = 10
84
+
85
+ def __init__(self, p12_path: str, p12_pass: str|None=None, *, prod: bool=False) -> None:
86
+ self.endpoint = self.PROD_ENDPOINT_URL if prod else self.DEMO_ENDPOINT_URL
87
+ self.soap_endpoint = urljoin(self.endpoint, 'soap')
88
+ self.attachment_endpoint = urljoin(self.endpoint, 'attachment')
89
+
90
+ from . import __version__
91
+ self.headers = {'User-Agent': f'USP_MP/{__version__}'}
92
+
93
+ logger.debug("Using %s endpoint %s", "production" if prod else "demo", self.endpoint)
94
+
95
+ private_key, cert = self.load_p12_cert(p12_path, p12_pass)
96
+ self.certificate_expires = self.check_expiry(cert)
97
+ self.ssl_context = self.build_ssl_context(private_key, cert)
98
+ del private_key # only the SSLContext keeps the key from here on
99
+
100
+ # Parsed once per adapter; every connection's zeep client reuses it
101
+ self.settings = self.zeep_settings(self.headers)
102
+ self.wsdl, self.types = self.load_wsdl(self.settings)
103
+
104
+ @staticmethod
105
+ def zeep_settings(headers: dict[str, str]) -> Settings:
106
+ # The bundled schema is patched so that zeep can parse the p:Person substitution
107
+ # (PhysicalPerson/CorporateBody) in Sender/Receiver; see wsdl/PATCHES.md. With the
108
+ # patch, all demo responses also parse with strict=True (tests/test_demo.py checks
109
+ # that). strict=False is kept deliberately: if the service ever sends an element the
110
+ # bundled schema doesn't know, retrieval keeps working, the element ends up in
111
+ # _raw_elements, and Delivery logs a warning instead of failing.
112
+ # zeep reads `strict` from the settings the WSDL Document was parsed with.
113
+ return Settings(strict=False, extra_http_headers=headers) # pyright: ignore[reportCallIssue]
114
+
115
+ @classmethod
116
+ def load_wsdl(cls, settings: Settings | None = None) -> tuple[Document, QueryTypes]:
117
+ """Parse the bundled WSDL (the service doesn't serve ?wsdl) and resolve the query types."""
118
+ client = Client(wsdl=cls.WSDL_PATH, settings=settings) # local files only, no network
119
+ if not client.wsdl.services:
120
+ raise ValueError("No services found in WSDL")
121
+ types = QueryTypes(**{
122
+ name: client.get_type(f'ns0:{name}')
123
+ for name in ('AllDeliveriesType', 'PagingType', 'NewDeliveriesOnlyType')
124
+ })
125
+ return client.wsdl, types
126
+
127
+ def load_p12_cert(self, p12_path: str, p12_pass: str|None = None):
128
+ """Load PKCS12 and extract certificate and private key; raises CertificateError"""
129
+
130
+ try:
131
+ with open(p12_path, "rb") as f:
132
+ p12_data = f.read()
133
+ except OSError as e:
134
+ raise CertificateError(f"Cannot read client certificate {p12_path}: {e.strerror}") from e
135
+ password = p12_pass.encode() if p12_pass else None
136
+ try:
137
+ private_key, certificate, additional_certs = pkcs12.load_key_and_certificates(
138
+ p12_data, password, default_backend()
139
+ )
140
+ except ValueError as e:
141
+ raise CertificateError(
142
+ f"Cannot load client certificate {p12_path}: wrong password or not a PKCS#12 file"
143
+ ) from e
144
+ if private_key is None or certificate is None:
145
+ raise CertificateError(f"Client certificate {p12_path} contains no private key and certificate")
146
+ return private_key, certificate
147
+
148
+ @staticmethod
149
+ def check_expiry(certificate) -> datetime.datetime:
150
+ """Log when the client certificate expires; warn shortly before (or after) it does."""
151
+ expires = getattr(certificate, "not_valid_after_utc", None) # cryptography >= 42
152
+ if expires is None:
153
+ expires = certificate.not_valid_after.replace(tzinfo=datetime.timezone.utc)
154
+ remaining = expires - datetime.datetime.now(datetime.timezone.utc)
155
+ if remaining <= datetime.timedelta(0):
156
+ logger.warning("Client certificate expired on %s; the service will reject it", expires.date())
157
+ elif remaining <= CERTIFICATE_EXPIRY_WARNING:
158
+ logger.warning("Client certificate expires on %s (in %d days); create a new one in USP",
159
+ expires.date(), remaining.days)
160
+ else:
161
+ logger.debug("Client certificate valid until %s", expires.date())
162
+ return expires
163
+
164
+ def build_ssl_context(self, private_key, certificate) -> ssl.SSLContext:
165
+ """Build a client SSLContext carrying the client certificate and the BRZ CA.
166
+
167
+ Python's ssl module can only load keys from files, so the key is written
168
+ to a private temporary directory -- but only in encrypted form, with a
169
+ random one-time password that never leaves this process. The directory
170
+ is removed as soon as the key is loaded, even if loading fails.
171
+ """
172
+ # Same defaults requests/urllib3 would use (incl. VERIFY_X509_STRICT on 3.13+)
173
+ ctx = create_urllib3_context()
174
+ ctx.load_verify_locations(cafile=self.CA_PATH)
175
+
176
+ one_time_password = secrets.token_urlsafe(32).encode()
177
+ cert_pem = certificate.public_bytes(encoding=serialization.Encoding.PEM)
178
+ encrypted_key_pem = private_key.private_bytes(
179
+ encoding=serialization.Encoding.PEM,
180
+ format=serialization.PrivateFormat.PKCS8,
181
+ encryption_algorithm=serialization.BestAvailableEncryption(one_time_password),
182
+ )
183
+
184
+ with tempfile.TemporaryDirectory(prefix="usp_mp-") as tmpdir: # created with mode 0700
185
+ cert_path = os.path.join(tmpdir, "cert.pem")
186
+ key_path = os.path.join(tmpdir, "key.pem")
187
+ _write_private_file(cert_path, cert_pem)
188
+ _write_private_file(key_path, encrypted_key_pem)
189
+ try:
190
+ ctx.load_cert_chain(cert_path, key_path, password=one_time_password)
191
+ except ssl.SSLError as e:
192
+ raise CertificateError(f"Cannot use client certificate: {e}") from e
193
+
194
+ return ctx
195
+
196
+ class ConnectionContext:
197
+ """One HTTP session and zeep client. Usable until it is exited/closed."""
198
+
199
+ def __init__(self, uspmp):
200
+ self.uspmp = uspmp
201
+ self.closed = False
202
+ self.session = requests.Session()
203
+ # The mounted context does the actual verification; keeping `verify`
204
+ # pinned to the BRZ CA ensures nothing falls back to the system store.
205
+ self.session.verify = uspmp.CA_PATH
206
+ self.session.mount("https://", SSLContextAdapter(uspmp.ssl_context))
207
+
208
+ transport = Transport(session=self.session, timeout=uspmp.TIMEOUT, operation_timeout=uspmp.TIMEOUT)
209
+ # After Transport(): zeep overwrites the session's User-Agent with its own
210
+ self.session.headers.update(uspmp.headers)
211
+
212
+ # Reuses the adapter's parsed WSDL; SOAP calls go through this connection's transport
213
+ self.client = Client(wsdl=uspmp.wsdl, transport=transport, settings=uspmp.settings)
214
+ binding = next(iter(self.client.wsdl.bindings)) # load_wsdl checked there is one
215
+ self._service = self.client.create_service(binding, uspmp.soap_endpoint)
216
+ logger.debug("Opened connection to %s", uspmp.endpoint)
217
+
218
+ def _ensure_open(self) -> None:
219
+ if self.closed:
220
+ raise MailboxStateError("Mailbox connection is closed")
221
+
222
+ @property
223
+ def service(self):
224
+ """The zeep service proxy for SOAP calls."""
225
+ self._ensure_open()
226
+ return self._service
227
+
228
+ def __enter__(self):
229
+ self._ensure_open()
230
+ return self
231
+
232
+ def __exit__(self, exc_type, exc_val, exc_tb):
233
+ self.close()
234
+
235
+ def close(self) -> None:
236
+ if not self.closed:
237
+ self.closed = True
238
+ self.session.close()
239
+ logger.debug("Closed connection to %s", self.uspmp.endpoint)
240
+
241
+ def download_attachment(self, delivery_id: str, attachment_id: str) -> bytes:
242
+ self._ensure_open()
243
+ # Must go through the session: the client certificate lives in its SSLContext
244
+ r = self.session.get(self.uspmp.attachment_endpoint,
245
+ params={'delivery_id': delivery_id, 'attachment_id': attachment_id},
246
+ timeout=self.uspmp.TIMEOUT,
247
+ )
248
+ r.raise_for_status()
249
+ logger.debug("Downloaded attachment %s of delivery %s: %d bytes", attachment_id, delivery_id, len(r.content))
250
+ return r.content
251
+
252
+ def connection(self):
253
+ """Open a new connection; use as a context manager. Mailbox does this for you."""
254
+ return self.ConnectionContext(self)
@@ -0,0 +1,33 @@
1
+ -----BEGIN CERTIFICATE-----
2
+ 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
32
+ 0C49VYd80kzqdlvpGbsM7oHfoEXEgMshnhYl
33
+ -----END CERTIFICATE-----