cmem-plugin-graphsigning 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.
- cmem_plugin_graphsigning/__init__.py +1 -0
- cmem_plugin_graphsigning/canonicalization.py +173 -0
- cmem_plugin_graphsigning/create_graph_signature.py +835 -0
- cmem_plugin_graphsigning/create_graph_signature.svg +1 -0
- cmem_plugin_graphsigning/graph_proof_utils.py +341 -0
- cmem_plugin_graphsigning/graph_store.py +95 -0
- cmem_plugin_graphsigning/remove_graph_signature.py +147 -0
- cmem_plugin_graphsigning/remove_graph_signature.svg +1 -0
- cmem_plugin_graphsigning/signing.py +259 -0
- cmem_plugin_graphsigning/verify_graph_signature.py +875 -0
- cmem_plugin_graphsigning/verify_graph_signature.svg +1 -0
- cmem_plugin_graphsigning/vocabulary.py +48 -0
- cmem_plugin_graphsigning-0.5.0.dist-info/METADATA +50 -0
- cmem_plugin_graphsigning-0.5.0.dist-info/RECORD +16 -0
- cmem_plugin_graphsigning-0.5.0.dist-info/WHEEL +4 -0
- cmem_plugin_graphsigning-0.5.0.dist-info/licenses/LICENSE +201 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""cmem-plugin-graphsigning"""
|
|
@@ -0,0 +1,173 @@
|
|
|
1
|
+
"""RDFC-1.0 canonicalization, delegated to pyoxigraph rather than hand-rolled.
|
|
2
|
+
|
|
3
|
+
Canonicalizing a blank-node-heavy graph correctly - assigning the one blank node
|
|
4
|
+
labelling the algorithm defines as canonical, not merely *a* consistent one - is
|
|
5
|
+
notoriously easy to get subtly wrong, and worst-case exponential in the number of
|
|
6
|
+
blank nodes by the algorithm's own design. pyoxigraph implements RDFC-1.0 against
|
|
7
|
+
the official W3C test suite, so this module leans on it rather than maintaining a
|
|
8
|
+
from-scratch canonicalizer.
|
|
9
|
+
|
|
10
|
+
Canonicalization runs in a throwaway subprocess so a graph shaped to blow up the
|
|
11
|
+
algorithm's worst case can be killed outright once it exceeds the time budget - a
|
|
12
|
+
plain thread or signal-based timeout cannot interrupt a blocking native call like
|
|
13
|
+
this one.
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
import hashlib
|
|
17
|
+
import multiprocessing as mp
|
|
18
|
+
import multiprocessing.connection
|
|
19
|
+
from dataclasses import dataclass
|
|
20
|
+
|
|
21
|
+
import pyoxigraph as ox
|
|
22
|
+
import rdflib
|
|
23
|
+
|
|
24
|
+
DEFAULT_TIMEOUT_SECONDS = 5.0
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
class CanonicalizationTimeoutError(TimeoutError):
|
|
28
|
+
"""Raised when canonicalizing a graph exceeds its time budget.
|
|
29
|
+
|
|
30
|
+
RDFC-1.0's blank node labelling algorithm is worst-case exponential in the
|
|
31
|
+
number of blank nodes by design, so a graph shaped adversarially - or just
|
|
32
|
+
unusually blank-node-heavy - can be made to run arbitrarily long; this is a
|
|
33
|
+
property of the algorithm itself; not a bug either here or in pyoxigraph.
|
|
34
|
+
"""
|
|
35
|
+
|
|
36
|
+
def __init__(self, timeout: float) -> None:
|
|
37
|
+
super().__init__(
|
|
38
|
+
f"Canonicalization exceeded {timeout}s. A graph with many blank nodes "
|
|
39
|
+
f"that hash alike can make RDFC-1.0's worst case exponential; this is "
|
|
40
|
+
f"inherent to the algorithm, not a bug."
|
|
41
|
+
)
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
class CanonicalizationError(ValueError):
|
|
45
|
+
"""Raised when *nquads* could not be parsed and canonicalized."""
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
@dataclass(frozen=True)
|
|
49
|
+
class _WorkerFailure:
|
|
50
|
+
"""A worker-side exception, carried back to the parent as data.
|
|
51
|
+
|
|
52
|
+
The original exception's class may not exist in the parent's import path in
|
|
53
|
+
every case (pyoxigraph's own exception types, for instance), so only its
|
|
54
|
+
message crosses the process boundary - re-raised here as a plain ValueError
|
|
55
|
+
rather than something that could fail to unpickle.
|
|
56
|
+
"""
|
|
57
|
+
|
|
58
|
+
message: str
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def _canonicalize_worker(
|
|
62
|
+
nquads: bytes, connection: "mp.connection.Connection[bytes | _WorkerFailure, object]"
|
|
63
|
+
) -> None:
|
|
64
|
+
"""Parse, canonicalize and serialize *nquads* in a worker process.
|
|
65
|
+
|
|
66
|
+
Runs entirely inside the subprocess so the only thing crossing back to the
|
|
67
|
+
parent is the finished result - never a live pyoxigraph object, which would
|
|
68
|
+
not survive the process boundary regardless. Only the failures input can cause
|
|
69
|
+
are sent back with their reason; anything else ends the worker, and the parent
|
|
70
|
+
reports a worker that exits without a result.
|
|
71
|
+
"""
|
|
72
|
+
try:
|
|
73
|
+
dataset = ox.Dataset()
|
|
74
|
+
for quad in ox.parse(input=nquads, format=ox.RdfFormat.N_QUADS):
|
|
75
|
+
dataset.add(quad)
|
|
76
|
+
dataset.canonicalize(ox.CanonicalizationAlgorithm.RDFC_1_0)
|
|
77
|
+
serialized = ox.serialize(list(dataset), format=ox.RdfFormat.N_QUADS) or b""
|
|
78
|
+
lines = sorted(serialized.decode("utf-8").splitlines())
|
|
79
|
+
result: bytes | _WorkerFailure = ("\n".join(lines) + "\n").encode("utf-8") if lines else b""
|
|
80
|
+
except (SyntaxError, ValueError) as error:
|
|
81
|
+
result = _WorkerFailure(f"{type(error).__name__}: {error}")
|
|
82
|
+
connection.send(result)
|
|
83
|
+
connection.close()
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def canonicalize_nquads(nquads: bytes, *, timeout: float = DEFAULT_TIMEOUT_SECONDS) -> bytes:
|
|
87
|
+
"""Return *nquads* in RDFC-1.0 canonical form: sorted, newline-terminated N-Quads.
|
|
88
|
+
|
|
89
|
+
Runs in a fresh ``spawn``-started subprocess, killed outright if it does not
|
|
90
|
+
finish within *timeout* seconds - the only way to bound a blocking native call
|
|
91
|
+
that does not check back in with Python for a cooperative cancellation.
|
|
92
|
+
|
|
93
|
+
The parent waits for the result and for the worker's exit together. Waiting for
|
|
94
|
+
the exit alone would never end for a result larger than the pipe holds, since the
|
|
95
|
+
worker cannot finish sending it until the parent starts reading; waiting for the
|
|
96
|
+
result alone would never end for a worker that died without sending one.
|
|
97
|
+
"""
|
|
98
|
+
ctx = mp.get_context("spawn")
|
|
99
|
+
receiver, sender = ctx.Pipe(duplex=False)
|
|
100
|
+
process = ctx.Process(target=_canonicalize_worker, args=(nquads, sender))
|
|
101
|
+
process.start()
|
|
102
|
+
sender.close()
|
|
103
|
+
try:
|
|
104
|
+
ready = mp.connection.wait([receiver, process.sentinel], timeout)
|
|
105
|
+
if not ready:
|
|
106
|
+
raise CanonicalizationTimeoutError(timeout)
|
|
107
|
+
try:
|
|
108
|
+
result = receiver.recv()
|
|
109
|
+
except EOFError:
|
|
110
|
+
process.join()
|
|
111
|
+
raise CanonicalizationError(
|
|
112
|
+
f"Canonicalization ended without a result (exit code {process.exitcode})"
|
|
113
|
+
) from None
|
|
114
|
+
finally:
|
|
115
|
+
receiver.close()
|
|
116
|
+
if process.is_alive():
|
|
117
|
+
process.kill()
|
|
118
|
+
process.join()
|
|
119
|
+
if isinstance(result, _WorkerFailure):
|
|
120
|
+
raise CanonicalizationError(f"Failed to canonicalize RDF: {result.message}")
|
|
121
|
+
return bytes(result)
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def canonical_digest_bytes(nquads: bytes, *, timeout: float = DEFAULT_TIMEOUT_SECONDS) -> bytes:
|
|
125
|
+
"""Return the SHA-256 digest of *nquads* in its RDFC-1.0 canonical form.
|
|
126
|
+
|
|
127
|
+
**This hash is a security use**: every digest a signature is made over goes
|
|
128
|
+
through here.
|
|
129
|
+
"""
|
|
130
|
+
return hashlib.sha256(canonicalize_nquads(nquads, timeout=timeout)).digest()
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
def _as_rdflib_term(term: ox.NamedNode | ox.BlankNode | ox.Literal) -> rdflib.term.Node:
|
|
134
|
+
"""Translate one pyoxigraph term into the equivalent rdflib term, without normalizing it."""
|
|
135
|
+
if isinstance(term, ox.Literal):
|
|
136
|
+
language = term.language
|
|
137
|
+
return rdflib.Literal(
|
|
138
|
+
term.value,
|
|
139
|
+
lang=language,
|
|
140
|
+
datatype=None if language else rdflib.URIRef(term.datatype.value),
|
|
141
|
+
normalize=False,
|
|
142
|
+
)
|
|
143
|
+
if isinstance(term, ox.BlankNode):
|
|
144
|
+
return rdflib.BNode(term.value)
|
|
145
|
+
return rdflib.URIRef(term.value)
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
def parse_without_normalizing(
|
|
149
|
+
data: bytes, rdf_format: ox.RdfFormat = ox.RdfFormat.N_QUADS
|
|
150
|
+
) -> rdflib.Graph:
|
|
151
|
+
"""Parse *data* into an rdflib.Graph without rewriting any literal's lexical form.
|
|
152
|
+
|
|
153
|
+
rdflib's own parser rewrites a recognized datatype's lexical form the moment it
|
|
154
|
+
constructs a Literal - an ``xsd:dateTime`` written ``...Z`` comes back ``...+00:00`` -
|
|
155
|
+
governed by a process-global flag (``rdflib.NORMALIZE_LITERALS``) this plugin must
|
|
156
|
+
never touch: Corporate Memory's DataIntegration runs every installed plugin in one
|
|
157
|
+
shared, concurrently-executing Python interpreter, so a global flip here would leak
|
|
158
|
+
into every other plugin sharing that process, or race against one running at the
|
|
159
|
+
same time. Parsing through pyoxigraph instead - which never rewrites a literal - and
|
|
160
|
+
translating its terms into rdflib's own term types (each ``Literal`` built with
|
|
161
|
+
``normalize=False``, a per-instance argument rather than shared state) reads the same
|
|
162
|
+
bytes into the same graph structure without that side effect.
|
|
163
|
+
"""
|
|
164
|
+
graph = rdflib.Graph()
|
|
165
|
+
for quad in ox.parse(input=data, format=rdf_format):
|
|
166
|
+
graph.add(
|
|
167
|
+
(
|
|
168
|
+
_as_rdflib_term(quad.subject),
|
|
169
|
+
_as_rdflib_term(quad.predicate),
|
|
170
|
+
_as_rdflib_term(quad.object),
|
|
171
|
+
)
|
|
172
|
+
)
|
|
173
|
+
return graph
|