swarmauri_signing_xmld 0.1.0.dev37__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.
- swarmauri_signing_xmld-0.1.0.dev37/PKG-INFO +78 -0
- swarmauri_signing_xmld-0.1.0.dev37/README.md +48 -0
- swarmauri_signing_xmld-0.1.0.dev37/pyproject.toml +86 -0
- swarmauri_signing_xmld-0.1.0.dev37/swarmauri_signing_xmld/__init__.py +5 -0
- swarmauri_signing_xmld-0.1.0.dev37/swarmauri_signing_xmld/xmld_signer.py +491 -0
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: swarmauri_signing_xmld
|
|
3
|
+
Version: 0.1.0.dev37
|
|
4
|
+
Summary: XML Digital Signature implementation for the Swarmauri SigningBase registry
|
|
5
|
+
License-Expression: Apache-2.0
|
|
6
|
+
Keywords: swarmauri,signing,xml,xml-dsig,digital-signature,sdk,standards,xmld,cryptography,xml-signature,canonicalization,enveloped-signature,signature-format,document-format
|
|
7
|
+
Author: Jacob Stewart
|
|
8
|
+
Author-email: jacob@swarmauri.com
|
|
9
|
+
Requires-Python: >=3.10,<3.13
|
|
10
|
+
Classifier: Development Status :: 1 - Planning
|
|
11
|
+
Classifier: License :: OSI Approved :: Apache Software License
|
|
12
|
+
Classifier: Natural Language :: English
|
|
13
|
+
Classifier: Programming Language :: Python
|
|
14
|
+
Classifier: Programming Language :: Python :: 3
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
18
|
+
Classifier: Topic :: Security :: Cryptography
|
|
19
|
+
Classifier: Intended Audience :: Developers
|
|
20
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
21
|
+
Requires-Dist: cryptography (>=42.0.0)
|
|
22
|
+
Requires-Dist: lxml (>=4.9)
|
|
23
|
+
Requires-Dist: swarmauri_base
|
|
24
|
+
Requires-Dist: swarmauri_core
|
|
25
|
+
Project-URL: Documentation, https://github.com/swarmauri/swarmauri-sdk/tree/main/pkgs/standards/swarmauri_signing_xmld#readme
|
|
26
|
+
Project-URL: Homepage, https://github.com/swarmauri/swarmauri-sdk
|
|
27
|
+
Project-URL: Source, https://github.com/swarmauri/swarmauri-sdk/tree/main/pkgs/standards/swarmauri_signing_xmld
|
|
28
|
+
Description-Content-Type: text/markdown
|
|
29
|
+
|
|
30
|
+
<p align="center">
|
|
31
|
+
<img src="../../../assets/swarmauri.brand.theme.svg" alt="Swarmauri logotype" width="420" />
|
|
32
|
+
</p>
|
|
33
|
+
|
|
34
|
+
<h1 align="center">swarmauri_signing_xmld</h1>
|
|
35
|
+
|
|
36
|
+
<p align="center">
|
|
37
|
+
<a href="https://img.shields.io/badge/status-experimental-ff6f61?style=for-the-badge"><img src="https://img.shields.io/badge/status-experimental-ff6f61?style=for-the-badge" alt="Status: experimental" /></a>
|
|
38
|
+
<a href="https://img.shields.io/badge/license-Apache--2.0-0a6ebd?style=for-the-badge"><img src="https://img.shields.io/badge/license-Apache--2.0-0a6ebd?style=for-the-badge" alt="License: Apache-2.0" /></a>
|
|
39
|
+
<a href="https://img.shields.io/badge/python-3.10%20|%203.11%20|%203.12-4b8bbe?style=for-the-badge"><img src="https://img.shields.io/badge/python-3.10%20|%203.11%20|%203.12-4b8bbe?style=for-the-badge" alt="Python versions" /></a>
|
|
40
|
+
</p>
|
|
41
|
+
|
|
42
|
+
`swarmauri_signing_xmld` packages an XML Digital Signature (`XMLDSig`) provider that registers
|
|
43
|
+
with the Swarmauri `SigningBase` registry. The signer focuses on canonicalized
|
|
44
|
+
XML payloads and produces detached signatures that can be embedded into
|
|
45
|
+
workflow-specific envelopes.
|
|
46
|
+
|
|
47
|
+
## Installation
|
|
48
|
+
|
|
49
|
+
### uv
|
|
50
|
+
|
|
51
|
+
```bash
|
|
52
|
+
uv pip install swarmauri_signing_xmld
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
### pip
|
|
56
|
+
|
|
57
|
+
```bash
|
|
58
|
+
pip install swarmauri_signing_xmld
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
## Usage
|
|
62
|
+
|
|
63
|
+
```python
|
|
64
|
+
from swarmauri_signing_xmld import XMLDSigner
|
|
65
|
+
|
|
66
|
+
signer = XMLDSigner()
|
|
67
|
+
xml_payload = """<note><to>Alice</to><from>Bob</from></note>""".encode()
|
|
68
|
+
|
|
69
|
+
signature = await signer.sign_bytes(
|
|
70
|
+
key={
|
|
71
|
+
"kind": "pem",
|
|
72
|
+
"private_key": "/path/to/private_key.pem",
|
|
73
|
+
"certificate": "/path/to/certificate.pem",
|
|
74
|
+
},
|
|
75
|
+
payload=xml_payload,
|
|
76
|
+
)
|
|
77
|
+
```
|
|
78
|
+
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
<p align="center">
|
|
2
|
+
<img src="../../../assets/swarmauri.brand.theme.svg" alt="Swarmauri logotype" width="420" />
|
|
3
|
+
</p>
|
|
4
|
+
|
|
5
|
+
<h1 align="center">swarmauri_signing_xmld</h1>
|
|
6
|
+
|
|
7
|
+
<p align="center">
|
|
8
|
+
<a href="https://img.shields.io/badge/status-experimental-ff6f61?style=for-the-badge"><img src="https://img.shields.io/badge/status-experimental-ff6f61?style=for-the-badge" alt="Status: experimental" /></a>
|
|
9
|
+
<a href="https://img.shields.io/badge/license-Apache--2.0-0a6ebd?style=for-the-badge"><img src="https://img.shields.io/badge/license-Apache--2.0-0a6ebd?style=for-the-badge" alt="License: Apache-2.0" /></a>
|
|
10
|
+
<a href="https://img.shields.io/badge/python-3.10%20|%203.11%20|%203.12-4b8bbe?style=for-the-badge"><img src="https://img.shields.io/badge/python-3.10%20|%203.11%20|%203.12-4b8bbe?style=for-the-badge" alt="Python versions" /></a>
|
|
11
|
+
</p>
|
|
12
|
+
|
|
13
|
+
`swarmauri_signing_xmld` packages an XML Digital Signature (`XMLDSig`) provider that registers
|
|
14
|
+
with the Swarmauri `SigningBase` registry. The signer focuses on canonicalized
|
|
15
|
+
XML payloads and produces detached signatures that can be embedded into
|
|
16
|
+
workflow-specific envelopes.
|
|
17
|
+
|
|
18
|
+
## Installation
|
|
19
|
+
|
|
20
|
+
### uv
|
|
21
|
+
|
|
22
|
+
```bash
|
|
23
|
+
uv pip install swarmauri_signing_xmld
|
|
24
|
+
```
|
|
25
|
+
|
|
26
|
+
### pip
|
|
27
|
+
|
|
28
|
+
```bash
|
|
29
|
+
pip install swarmauri_signing_xmld
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
## Usage
|
|
33
|
+
|
|
34
|
+
```python
|
|
35
|
+
from swarmauri_signing_xmld import XMLDSigner
|
|
36
|
+
|
|
37
|
+
signer = XMLDSigner()
|
|
38
|
+
xml_payload = """<note><to>Alice</to><from>Bob</from></note>""".encode()
|
|
39
|
+
|
|
40
|
+
signature = await signer.sign_bytes(
|
|
41
|
+
key={
|
|
42
|
+
"kind": "pem",
|
|
43
|
+
"private_key": "/path/to/private_key.pem",
|
|
44
|
+
"certificate": "/path/to/certificate.pem",
|
|
45
|
+
},
|
|
46
|
+
payload=xml_payload,
|
|
47
|
+
)
|
|
48
|
+
```
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "swarmauri_signing_xmld"
|
|
3
|
+
version = "0.1.0.dev37"
|
|
4
|
+
description = "XML Digital Signature implementation for the Swarmauri SigningBase registry"
|
|
5
|
+
license = "Apache-2.0"
|
|
6
|
+
readme = "README.md"
|
|
7
|
+
requires-python = ">=3.10,<3.13"
|
|
8
|
+
authors = [{ name = "Jacob Stewart", email = "jacob@swarmauri.com" }]
|
|
9
|
+
keywords = [
|
|
10
|
+
"swarmauri",
|
|
11
|
+
"signing",
|
|
12
|
+
"xml",
|
|
13
|
+
"xml-dsig",
|
|
14
|
+
"digital-signature",
|
|
15
|
+
"sdk",
|
|
16
|
+
"standards",
|
|
17
|
+
"xmld",
|
|
18
|
+
"cryptography",
|
|
19
|
+
"xml-signature",
|
|
20
|
+
"canonicalization",
|
|
21
|
+
"enveloped-signature",
|
|
22
|
+
"signature-format",
|
|
23
|
+
"document-format",
|
|
24
|
+
]
|
|
25
|
+
classifiers = [
|
|
26
|
+
"Development Status :: 1 - Planning",
|
|
27
|
+
"License :: OSI Approved :: Apache Software License",
|
|
28
|
+
"Natural Language :: English",
|
|
29
|
+
"Programming Language :: Python",
|
|
30
|
+
"Programming Language :: Python :: 3",
|
|
31
|
+
"Programming Language :: Python :: 3.10",
|
|
32
|
+
"Programming Language :: Python :: 3.11",
|
|
33
|
+
"Programming Language :: Python :: 3.12",
|
|
34
|
+
"Topic :: Security :: Cryptography",
|
|
35
|
+
"Intended Audience :: Developers",
|
|
36
|
+
"Programming Language :: Python :: 3 :: Only",
|
|
37
|
+
]
|
|
38
|
+
dependencies = [
|
|
39
|
+
"swarmauri_base",
|
|
40
|
+
"swarmauri_core",
|
|
41
|
+
"cryptography>=42.0.0",
|
|
42
|
+
"lxml>=4.9",
|
|
43
|
+
]
|
|
44
|
+
|
|
45
|
+
[project.urls]
|
|
46
|
+
Homepage = "https://github.com/swarmauri/swarmauri-sdk"
|
|
47
|
+
Source = "https://github.com/swarmauri/swarmauri-sdk/tree/main/pkgs/standards/swarmauri_signing_xmld"
|
|
48
|
+
Documentation = "https://github.com/swarmauri/swarmauri-sdk/tree/main/pkgs/standards/swarmauri_signing_xmld#readme"
|
|
49
|
+
|
|
50
|
+
[tool.uv.sources]
|
|
51
|
+
swarmauri_base = { workspace = true }
|
|
52
|
+
swarmauri_core = { workspace = true }
|
|
53
|
+
|
|
54
|
+
[tool.pytest.ini_options]
|
|
55
|
+
norecursedirs = ["combined", "scripts"]
|
|
56
|
+
markers = [
|
|
57
|
+
"test: standard test",
|
|
58
|
+
"unit: Unit tests",
|
|
59
|
+
"i9n: Integration tests",
|
|
60
|
+
"r8n: Regression tests",
|
|
61
|
+
"acceptance: Acceptance tests",
|
|
62
|
+
"perf: Performance tests",
|
|
63
|
+
"example: README-backed usage examples",
|
|
64
|
+
]
|
|
65
|
+
timeout = 300
|
|
66
|
+
log_cli = true
|
|
67
|
+
log_cli_level = "INFO"
|
|
68
|
+
log_cli_format = "%(asctime)s [%(levelname)s] %(message)s"
|
|
69
|
+
log_cli_date_format = "%Y-%m-%d %H:%M:%S"
|
|
70
|
+
asyncio_default_fixture_loop_scope = "function"
|
|
71
|
+
|
|
72
|
+
[dependency-groups]
|
|
73
|
+
dev = [
|
|
74
|
+
"pytest>=8.0",
|
|
75
|
+
"pytest-asyncio>=0.24.0",
|
|
76
|
+
"pytest-xdist>=3.6.1",
|
|
77
|
+
"pytest-json-report>=1.5.0",
|
|
78
|
+
"pytest-timeout>=2.3.1",
|
|
79
|
+
"pytest-benchmark>=4.0.0",
|
|
80
|
+
"flake8>=7.0",
|
|
81
|
+
"ruff>=0.9.9",
|
|
82
|
+
]
|
|
83
|
+
|
|
84
|
+
[build-system]
|
|
85
|
+
requires = ["poetry-core>=1.0.0"]
|
|
86
|
+
build-backend = "poetry.core.masonry.api"
|
|
@@ -0,0 +1,491 @@
|
|
|
1
|
+
"""XML Digital Signature provider."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import hashlib
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
from typing import Any, AsyncIterable, Iterable, Mapping, Optional, Sequence
|
|
8
|
+
|
|
9
|
+
from swarmauri_base import register_type
|
|
10
|
+
from swarmauri_base.signing.SigningBase import SigningBase
|
|
11
|
+
from swarmauri_core.crypto.types import Alg, KeyRef
|
|
12
|
+
from swarmauri_core.key_providers.IKeyProvider import IKeyProvider
|
|
13
|
+
from swarmauri_core.signing.ISigning import Canon, Envelope, StreamLike
|
|
14
|
+
from swarmauri_core.signing.types import Signature
|
|
15
|
+
|
|
16
|
+
try: # pragma: no cover - runtime guards
|
|
17
|
+
from lxml import etree
|
|
18
|
+
|
|
19
|
+
_LXML_OK = True
|
|
20
|
+
except Exception: # pragma: no cover
|
|
21
|
+
_LXML_OK = False
|
|
22
|
+
|
|
23
|
+
try: # pragma: no cover - runtime guards
|
|
24
|
+
from cryptography import x509
|
|
25
|
+
from cryptography.hazmat.primitives import hashes, serialization
|
|
26
|
+
from cryptography.hazmat.primitives.asymmetric import ec, ed25519, padding, rsa
|
|
27
|
+
|
|
28
|
+
_CRYPTO_OK = True
|
|
29
|
+
except Exception: # pragma: no cover
|
|
30
|
+
_CRYPTO_OK = False
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def _ensure_deps() -> None:
|
|
34
|
+
if not _LXML_OK:
|
|
35
|
+
raise RuntimeError("XMLDSigner requires 'lxml'. Install with: pip install lxml")
|
|
36
|
+
if not _CRYPTO_OK:
|
|
37
|
+
raise RuntimeError(
|
|
38
|
+
"XMLDSigner requires 'cryptography'. Install with: pip install cryptography"
|
|
39
|
+
)
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
async def _stream_to_bytes(stream: StreamLike) -> bytes:
|
|
43
|
+
if isinstance(stream, (bytes, bytearray)):
|
|
44
|
+
return bytes(stream)
|
|
45
|
+
if isinstance(stream, AsyncIterable):
|
|
46
|
+
parts = [bytes(chunk) async for chunk in stream]
|
|
47
|
+
return b"".join(parts)
|
|
48
|
+
if isinstance(stream, Iterable):
|
|
49
|
+
return b"".join(bytes(chunk) for chunk in stream)
|
|
50
|
+
raise TypeError("Unsupported stream payload for XMLDSigner")
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def _canon_xml(
|
|
54
|
+
data: Any, *, canon: str = "c14n", inclusive_ns: Optional[Sequence[str]] = None
|
|
55
|
+
) -> bytes:
|
|
56
|
+
_ensure_deps()
|
|
57
|
+
if isinstance(data, (bytes, bytearray)):
|
|
58
|
+
document = etree.fromstring(bytes(data))
|
|
59
|
+
elif isinstance(data, str):
|
|
60
|
+
document = etree.fromstring(data.encode("utf-8"))
|
|
61
|
+
else:
|
|
62
|
+
raise TypeError("XML canonicalization expects bytes or str input")
|
|
63
|
+
if canon in (None, "c14n"):
|
|
64
|
+
return etree.tostring(
|
|
65
|
+
document,
|
|
66
|
+
method="xml",
|
|
67
|
+
encoding="utf-8",
|
|
68
|
+
)
|
|
69
|
+
if canon == "c14n11":
|
|
70
|
+
try:
|
|
71
|
+
return etree.tostring(
|
|
72
|
+
document,
|
|
73
|
+
method="c14n",
|
|
74
|
+
exclusive=False,
|
|
75
|
+
with_comments=False,
|
|
76
|
+
c14n_version=1.1,
|
|
77
|
+
)
|
|
78
|
+
except TypeError:
|
|
79
|
+
return etree.tostring(
|
|
80
|
+
document,
|
|
81
|
+
method="c14n",
|
|
82
|
+
exclusive=False,
|
|
83
|
+
with_comments=False,
|
|
84
|
+
)
|
|
85
|
+
if canon == "exc-c14n":
|
|
86
|
+
return etree.tostring(
|
|
87
|
+
document,
|
|
88
|
+
method="c14n",
|
|
89
|
+
exclusive=True,
|
|
90
|
+
with_comments=False,
|
|
91
|
+
inclusive_ns_prefixes=inclusive_ns,
|
|
92
|
+
)
|
|
93
|
+
raise ValueError(f"Unsupported XML canon '{canon}'")
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def _load_pem(entry: Any) -> bytes:
|
|
97
|
+
if isinstance(entry, bytes):
|
|
98
|
+
return entry
|
|
99
|
+
if isinstance(entry, str):
|
|
100
|
+
path = Path(entry)
|
|
101
|
+
if path.exists():
|
|
102
|
+
return path.read_bytes()
|
|
103
|
+
return entry.encode("utf-8")
|
|
104
|
+
raise TypeError("PEM entries must be bytes or filesystem paths")
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def _load_private_key(key_ref: KeyRef):
|
|
108
|
+
_ensure_deps()
|
|
109
|
+
if isinstance(key_ref, Mapping):
|
|
110
|
+
kind = key_ref.get("kind")
|
|
111
|
+
password = key_ref.get("password")
|
|
112
|
+
password_bytes = None if password is None else str(password).encode("utf-8")
|
|
113
|
+
if kind == "pem":
|
|
114
|
+
pem = _load_pem(key_ref.get("private_key"))
|
|
115
|
+
return serialization.load_pem_private_key(pem, password=password_bytes)
|
|
116
|
+
if kind == "pkcs12":
|
|
117
|
+
data = _load_pem(key_ref.get("data"))
|
|
118
|
+
from cryptography.hazmat.primitives.serialization.pkcs12 import (
|
|
119
|
+
load_key_and_certificates,
|
|
120
|
+
)
|
|
121
|
+
|
|
122
|
+
private_key, cert, extras = load_key_and_certificates(data, password_bytes)
|
|
123
|
+
if private_key is None:
|
|
124
|
+
raise RuntimeError("PKCS#12 bundle did not include a private key")
|
|
125
|
+
return private_key
|
|
126
|
+
raise TypeError("XMLDSigner key_ref must describe 'pem' or 'pkcs12' material")
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def _load_certificate(key_ref: KeyRef) -> Optional[x509.Certificate]:
|
|
130
|
+
if isinstance(key_ref, Mapping):
|
|
131
|
+
cert_entry = key_ref.get("certificate")
|
|
132
|
+
if cert_entry is None:
|
|
133
|
+
return None
|
|
134
|
+
return x509.load_pem_x509_certificate(_load_pem(cert_entry))
|
|
135
|
+
return None
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def _fingerprint(public_bytes: bytes) -> str:
|
|
139
|
+
return hashlib.sha256(public_bytes).hexdigest()
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
def _resolve_alg(
|
|
143
|
+
key, alg: Optional[Alg]
|
|
144
|
+
) -> tuple[str, Any, hashes.HashAlgorithm | None]:
|
|
145
|
+
normalized = str(alg).upper() if alg else None
|
|
146
|
+
if isinstance(key, rsa.RSAPrivateKey):
|
|
147
|
+
hash_alg = hashes.SHA256()
|
|
148
|
+
mode = padding.PSS(
|
|
149
|
+
mgf=padding.MGF1(hash_alg), salt_length=padding.PSS.MAX_LENGTH
|
|
150
|
+
)
|
|
151
|
+
if not hasattr(mode, "salt_length"):
|
|
152
|
+
try:
|
|
153
|
+
mode.salt_length = mode._salt_length # type: ignore[attr-defined]
|
|
154
|
+
except Exception:
|
|
155
|
+
pass
|
|
156
|
+
name = "RSA-PSS-SHA256"
|
|
157
|
+
if normalized and "PKCS1" in normalized:
|
|
158
|
+
mode = padding.PKCS1v15()
|
|
159
|
+
name = "RSA-PKCS1-SHA256"
|
|
160
|
+
return name, mode, hash_alg
|
|
161
|
+
if isinstance(key, ec.EllipticCurvePrivateKey):
|
|
162
|
+
hash_alg = hashes.SHA256()
|
|
163
|
+
return "ECDSA-SHA256", ec.ECDSA(hash_alg), hash_alg
|
|
164
|
+
if isinstance(key, ed25519.Ed25519PrivateKey):
|
|
165
|
+
return "Ed25519", None, None
|
|
166
|
+
raise TypeError("Unsupported key type for XMLDSigner")
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
def _load_public_keys(entries: Optional[Iterable[Any]]) -> list[Any]:
|
|
170
|
+
_ensure_deps()
|
|
171
|
+
keys: list[Any] = []
|
|
172
|
+
for entry in entries or []:
|
|
173
|
+
if isinstance(
|
|
174
|
+
entry,
|
|
175
|
+
(rsa.RSAPublicKey, ec.EllipticCurvePublicKey, ed25519.Ed25519PublicKey),
|
|
176
|
+
):
|
|
177
|
+
keys.append(entry)
|
|
178
|
+
continue
|
|
179
|
+
pem = _load_pem(entry)
|
|
180
|
+
try:
|
|
181
|
+
keys.append(serialization.load_pem_public_key(pem))
|
|
182
|
+
continue
|
|
183
|
+
except ValueError:
|
|
184
|
+
cert = x509.load_pem_x509_certificate(pem)
|
|
185
|
+
keys.append(cert.public_key())
|
|
186
|
+
return keys
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
def _serialize_signature(
|
|
190
|
+
sig: bytes,
|
|
191
|
+
*,
|
|
192
|
+
payload_kind: str,
|
|
193
|
+
alg_name: str,
|
|
194
|
+
canon: str,
|
|
195
|
+
cert: Optional[x509.Certificate],
|
|
196
|
+
) -> Signature:
|
|
197
|
+
kid = None
|
|
198
|
+
if cert is not None:
|
|
199
|
+
kid = _fingerprint(cert.public_bytes(serialization.Encoding.DER))
|
|
200
|
+
meta = {"payload_kind": payload_kind, "canon": canon}
|
|
201
|
+
cert_chain = None
|
|
202
|
+
if cert is not None:
|
|
203
|
+
cert_chain = (cert.public_bytes(serialization.Encoding.DER),)
|
|
204
|
+
return Signature(
|
|
205
|
+
kid=kid,
|
|
206
|
+
version=None,
|
|
207
|
+
format="xml-dsig",
|
|
208
|
+
mode="detached",
|
|
209
|
+
alg=alg_name,
|
|
210
|
+
artifact=sig,
|
|
211
|
+
cert_chain_der=cert_chain,
|
|
212
|
+
meta=meta,
|
|
213
|
+
)
|
|
214
|
+
|
|
215
|
+
|
|
216
|
+
def _min_signers(require: Optional[Mapping[str, object]]) -> int:
|
|
217
|
+
if not require:
|
|
218
|
+
return 1
|
|
219
|
+
try:
|
|
220
|
+
return max(1, int(require.get("min_signers", 1)))
|
|
221
|
+
except (TypeError, ValueError):
|
|
222
|
+
return 1
|
|
223
|
+
|
|
224
|
+
|
|
225
|
+
@register_type(resource_type=SigningBase)
|
|
226
|
+
class XMLDSigner(SigningBase):
|
|
227
|
+
"""Produce detached XML Digital Signatures over canonicalized payloads."""
|
|
228
|
+
|
|
229
|
+
def __init__(self, key_provider: Optional[IKeyProvider] = None) -> None:
|
|
230
|
+
self._key_provider = key_provider
|
|
231
|
+
|
|
232
|
+
def set_key_provider(self, provider: IKeyProvider) -> None:
|
|
233
|
+
self._key_provider = provider
|
|
234
|
+
|
|
235
|
+
# ------------------------------------------------------------------
|
|
236
|
+
def supports(self, key_ref: Optional[str] = None) -> Mapping[str, Iterable[str]]:
|
|
237
|
+
base = {
|
|
238
|
+
"signs": ("bytes", "digest", "envelope", "stream"),
|
|
239
|
+
"verifies": ("bytes", "digest", "envelope", "stream"),
|
|
240
|
+
"envelopes": ("xml", "structured-json"),
|
|
241
|
+
"algs": ("RSA-PSS-SHA256", "RSA-PKCS1-SHA256", "ECDSA-SHA256", "Ed25519"),
|
|
242
|
+
"canons": ("c14n", "c14n11", "exc-c14n"),
|
|
243
|
+
"features": ("detached", "xml-dsig"),
|
|
244
|
+
"status": ("beta",),
|
|
245
|
+
}
|
|
246
|
+
if key_ref is None:
|
|
247
|
+
return base
|
|
248
|
+
return {**base, "key_refs": (key_ref,)}
|
|
249
|
+
|
|
250
|
+
# ------------------------------------------------------------------
|
|
251
|
+
async def sign_bytes(
|
|
252
|
+
self,
|
|
253
|
+
key: KeyRef,
|
|
254
|
+
payload: bytes,
|
|
255
|
+
*,
|
|
256
|
+
alg: Optional[Alg] = None,
|
|
257
|
+
opts: Optional[Mapping[str, object]] = None,
|
|
258
|
+
) -> Sequence[Signature]:
|
|
259
|
+
return await self._sign_payload(
|
|
260
|
+
key,
|
|
261
|
+
payload,
|
|
262
|
+
alg=alg,
|
|
263
|
+
opts=opts,
|
|
264
|
+
payload_kind="bytes",
|
|
265
|
+
canon="raw",
|
|
266
|
+
)
|
|
267
|
+
|
|
268
|
+
async def sign_digest(
|
|
269
|
+
self,
|
|
270
|
+
key: KeyRef,
|
|
271
|
+
digest: bytes,
|
|
272
|
+
*,
|
|
273
|
+
alg: Optional[Alg] = None,
|
|
274
|
+
opts: Optional[Mapping[str, object]] = None,
|
|
275
|
+
) -> Sequence[Signature]:
|
|
276
|
+
return await self._sign_payload(
|
|
277
|
+
key,
|
|
278
|
+
digest,
|
|
279
|
+
alg=alg,
|
|
280
|
+
opts=opts,
|
|
281
|
+
payload_kind="digest",
|
|
282
|
+
canon="raw",
|
|
283
|
+
)
|
|
284
|
+
|
|
285
|
+
async def sign_stream(
|
|
286
|
+
self,
|
|
287
|
+
key: KeyRef,
|
|
288
|
+
payload: StreamLike,
|
|
289
|
+
*,
|
|
290
|
+
alg: Optional[Alg] = None,
|
|
291
|
+
opts: Optional[Mapping[str, object]] = None,
|
|
292
|
+
) -> Sequence[Signature]:
|
|
293
|
+
data = await _stream_to_bytes(payload)
|
|
294
|
+
return await self.sign_bytes(key, data, alg=alg, opts=opts)
|
|
295
|
+
|
|
296
|
+
async def sign_envelope(
|
|
297
|
+
self,
|
|
298
|
+
key: KeyRef,
|
|
299
|
+
env: Envelope,
|
|
300
|
+
*,
|
|
301
|
+
alg: Optional[Alg] = None,
|
|
302
|
+
canon: Optional[Canon] = None,
|
|
303
|
+
opts: Optional[Mapping[str, object]] = None,
|
|
304
|
+
) -> Sequence[Signature]:
|
|
305
|
+
canonical = await self.canonicalize_envelope(env, canon=canon, opts=opts)
|
|
306
|
+
return await self._sign_payload(
|
|
307
|
+
key,
|
|
308
|
+
canonical,
|
|
309
|
+
alg=alg,
|
|
310
|
+
opts=opts,
|
|
311
|
+
payload_kind="envelope",
|
|
312
|
+
canon=str(canon or "c14n"),
|
|
313
|
+
)
|
|
314
|
+
|
|
315
|
+
# ------------------------------------------------------------------
|
|
316
|
+
async def verify_bytes(
|
|
317
|
+
self,
|
|
318
|
+
payload: bytes,
|
|
319
|
+
signatures: Sequence[Signature],
|
|
320
|
+
*,
|
|
321
|
+
require: Optional[Mapping[str, object]] = None,
|
|
322
|
+
opts: Optional[Mapping[str, object]] = None,
|
|
323
|
+
) -> bool:
|
|
324
|
+
return await self._verify_payload(
|
|
325
|
+
payload,
|
|
326
|
+
signatures,
|
|
327
|
+
require=require,
|
|
328
|
+
opts=opts,
|
|
329
|
+
payload_kind="bytes",
|
|
330
|
+
canon="raw",
|
|
331
|
+
)
|
|
332
|
+
|
|
333
|
+
async def verify_digest(
|
|
334
|
+
self,
|
|
335
|
+
digest: bytes,
|
|
336
|
+
signatures: Sequence[Signature],
|
|
337
|
+
*,
|
|
338
|
+
require: Optional[Mapping[str, object]] = None,
|
|
339
|
+
opts: Optional[Mapping[str, object]] = None,
|
|
340
|
+
) -> bool:
|
|
341
|
+
return await self._verify_payload(
|
|
342
|
+
digest,
|
|
343
|
+
signatures,
|
|
344
|
+
require=require,
|
|
345
|
+
opts=opts,
|
|
346
|
+
payload_kind="digest",
|
|
347
|
+
canon="raw",
|
|
348
|
+
)
|
|
349
|
+
|
|
350
|
+
async def verify_stream(
|
|
351
|
+
self,
|
|
352
|
+
payload: StreamLike,
|
|
353
|
+
signatures: Sequence[Signature],
|
|
354
|
+
*,
|
|
355
|
+
require: Optional[Mapping[str, object]] = None,
|
|
356
|
+
opts: Optional[Mapping[str, object]] = None,
|
|
357
|
+
) -> bool:
|
|
358
|
+
data = await _stream_to_bytes(payload)
|
|
359
|
+
return await self.verify_bytes(data, signatures, require=require, opts=opts)
|
|
360
|
+
|
|
361
|
+
async def verify_envelope(
|
|
362
|
+
self,
|
|
363
|
+
env: Envelope,
|
|
364
|
+
signatures: Sequence[Signature],
|
|
365
|
+
*,
|
|
366
|
+
canon: Optional[Canon] = None,
|
|
367
|
+
require: Optional[Mapping[str, object]] = None,
|
|
368
|
+
opts: Optional[Mapping[str, object]] = None,
|
|
369
|
+
) -> bool:
|
|
370
|
+
canonical = await self.canonicalize_envelope(env, canon=canon, opts=opts)
|
|
371
|
+
return await self._verify_payload(
|
|
372
|
+
canonical,
|
|
373
|
+
signatures,
|
|
374
|
+
require=require,
|
|
375
|
+
opts=opts,
|
|
376
|
+
payload_kind="envelope",
|
|
377
|
+
canon=str(canon or "c14n"),
|
|
378
|
+
)
|
|
379
|
+
|
|
380
|
+
# ------------------------------------------------------------------
|
|
381
|
+
async def canonicalize_envelope(
|
|
382
|
+
self,
|
|
383
|
+
env: Envelope,
|
|
384
|
+
*,
|
|
385
|
+
canon: Optional[Canon] = None,
|
|
386
|
+
opts: Optional[Mapping[str, object]] = None,
|
|
387
|
+
) -> bytes:
|
|
388
|
+
token = canon or "c14n"
|
|
389
|
+
if token == "raw":
|
|
390
|
+
if isinstance(env, (bytes, bytearray)):
|
|
391
|
+
return bytes(env)
|
|
392
|
+
if isinstance(env, str):
|
|
393
|
+
return env.encode("utf-8")
|
|
394
|
+
raise TypeError("raw canon expects bytes or str")
|
|
395
|
+
return _canon_xml(env, canon=str(token))
|
|
396
|
+
|
|
397
|
+
# ------------------------------------------------------------------
|
|
398
|
+
async def _sign_payload(
|
|
399
|
+
self,
|
|
400
|
+
key: KeyRef,
|
|
401
|
+
payload: bytes,
|
|
402
|
+
*,
|
|
403
|
+
alg: Optional[Alg],
|
|
404
|
+
opts: Optional[Mapping[str, object]],
|
|
405
|
+
payload_kind: str,
|
|
406
|
+
canon: str,
|
|
407
|
+
) -> Sequence[Signature]:
|
|
408
|
+
private_key = _load_private_key(key)
|
|
409
|
+
cert = _load_certificate(key)
|
|
410
|
+
alg_name, mode, hash_alg = _resolve_alg(private_key, alg)
|
|
411
|
+
data = payload
|
|
412
|
+
if payload_kind == "envelope" and canon != "raw":
|
|
413
|
+
data = payload # already canonicalized
|
|
414
|
+
if isinstance(private_key, ed25519.Ed25519PrivateKey):
|
|
415
|
+
sig = private_key.sign(data)
|
|
416
|
+
elif isinstance(private_key, ec.EllipticCurvePrivateKey):
|
|
417
|
+
sig = private_key.sign(data, mode) # type: ignore[arg-type]
|
|
418
|
+
else:
|
|
419
|
+
sig = private_key.sign(data, mode, hash_alg) # type: ignore[arg-type]
|
|
420
|
+
return [
|
|
421
|
+
_serialize_signature(
|
|
422
|
+
sig,
|
|
423
|
+
payload_kind=payload_kind,
|
|
424
|
+
alg_name=alg_name,
|
|
425
|
+
canon=canon,
|
|
426
|
+
cert=cert,
|
|
427
|
+
)
|
|
428
|
+
]
|
|
429
|
+
|
|
430
|
+
async def _verify_payload(
|
|
431
|
+
self,
|
|
432
|
+
payload: bytes,
|
|
433
|
+
signatures: Sequence[Signature],
|
|
434
|
+
*,
|
|
435
|
+
require: Optional[Mapping[str, object]],
|
|
436
|
+
opts: Optional[Mapping[str, object]],
|
|
437
|
+
payload_kind: str,
|
|
438
|
+
canon: str,
|
|
439
|
+
) -> bool:
|
|
440
|
+
if not signatures:
|
|
441
|
+
return False
|
|
442
|
+
keys = _load_public_keys((opts or {}).get("pubkeys"))
|
|
443
|
+
if not keys:
|
|
444
|
+
raise RuntimeError(
|
|
445
|
+
"XMLDSigner verification requires opts['pubkeys'] entries"
|
|
446
|
+
)
|
|
447
|
+
min_ok = _min_signers(require)
|
|
448
|
+
accepted = 0
|
|
449
|
+
for sig in signatures:
|
|
450
|
+
meta = sig.meta if isinstance(sig, Signature) else sig.get("meta")
|
|
451
|
+
kind = meta.get("payload_kind") if isinstance(meta, Mapping) else None
|
|
452
|
+
if kind not in (None, payload_kind):
|
|
453
|
+
continue
|
|
454
|
+
canon_token = meta.get("canon") if isinstance(meta, Mapping) else canon
|
|
455
|
+
if payload_kind == "envelope" and canon_token != canon:
|
|
456
|
+
continue
|
|
457
|
+
artifact = (
|
|
458
|
+
sig.artifact if isinstance(sig, Signature) else sig.get("artifact")
|
|
459
|
+
)
|
|
460
|
+
if isinstance(artifact, str):
|
|
461
|
+
signature_bytes = artifact.encode("latin1")
|
|
462
|
+
elif isinstance(artifact, (bytes, bytearray)):
|
|
463
|
+
signature_bytes = bytes(artifact)
|
|
464
|
+
else:
|
|
465
|
+
continue
|
|
466
|
+
alg_name = sig.alg if isinstance(sig, Signature) else sig.get("alg")
|
|
467
|
+
for key in keys:
|
|
468
|
+
try:
|
|
469
|
+
if isinstance(key, rsa.RSAPublicKey):
|
|
470
|
+
mode = padding.PSS(
|
|
471
|
+
mgf=padding.MGF1(hashes.SHA256()),
|
|
472
|
+
salt_length=padding.PSS.MAX_LENGTH,
|
|
473
|
+
)
|
|
474
|
+
if alg_name and "PKCS1" in str(alg_name).upper():
|
|
475
|
+
mode = padding.PKCS1v15()
|
|
476
|
+
key.verify(signature_bytes, payload, mode, hashes.SHA256())
|
|
477
|
+
accepted += 1
|
|
478
|
+
break
|
|
479
|
+
if isinstance(key, ec.EllipticCurvePublicKey):
|
|
480
|
+
key.verify(signature_bytes, payload, ec.ECDSA(hashes.SHA256()))
|
|
481
|
+
accepted += 1
|
|
482
|
+
break
|
|
483
|
+
if isinstance(key, ed25519.Ed25519PublicKey):
|
|
484
|
+
key.verify(signature_bytes, payload)
|
|
485
|
+
accepted += 1
|
|
486
|
+
break
|
|
487
|
+
except Exception:
|
|
488
|
+
continue
|
|
489
|
+
if accepted >= min_ok:
|
|
490
|
+
return True
|
|
491
|
+
return False
|