swarmauri_tool_signimage 0.1.0__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.
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [2025] [Jacob Stewart @ Swarmauri]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,4 @@
1
+ Swarmauri SDK
2
+
3
+ This package is part of the Swarmauri SDK and is distributed under the
4
+ Apache License, Version 2.0. See LICENSE for the license terms.
@@ -0,0 +1,353 @@
1
+ Metadata-Version: 2.4
2
+ Name: swarmauri_tool_signimage
3
+ Version: 0.1.0
4
+ Summary: Sign generated images and configured metadata through MediaSigner.
5
+ License-Expression: Apache-2.0
6
+ License-File: LICENSE
7
+ License-File: NOTICE
8
+ Keywords: swarmauri,tools,MediaSigner,JWS signatures,signed image metadata
9
+ Author: Jacob Stewart
10
+ Author-email: jacob@swarmauri.com
11
+ Requires-Python: >=3.10,<3.15
12
+ Classifier: Development Status :: 1 - Planning
13
+ Classifier: Programming Language :: Python :: 3.10
14
+ Classifier: Programming Language :: Python :: 3.11
15
+ Classifier: Programming Language :: Python :: 3.12
16
+ Classifier: Programming Language :: Python :: 3.13
17
+ Classifier: Programming Language :: Python :: 3.14
18
+ Requires-Dist: MediaSigner (>=0.11.1,<0.12)
19
+ Requires-Dist: cryptography (>=42)
20
+ Requires-Dist: pydantic (>=2.9,<3)
21
+ Requires-Dist: swarmauri_base (>=0.11.0,<0.12)
22
+ Requires-Dist: swarmauri_core (>=0.11.1,<0.12)
23
+ Project-URL: Repository, https://github.com/swarmauri/swarmauri-sdk
24
+ Description-Content-Type: text/markdown
25
+
26
+ # swarmauri_tool_signimage
27
+
28
+ <!-- readme-standards:begin branding -->
29
+ <p align="center"><a href="https://github.com/swarmauri/swarmauri-sdk"><img src="https://raw.githubusercontent.com/swarmauri/swarmauri-sdk/master/assets/swarmauri.brand.theme.svg" alt="Swarmauri SDK" width="300"></a></p>
30
+ <p align="center"><strong>swarmauri_tool_signimage</strong></p>
31
+ <p align="center">Sign generated images and configured metadata through MediaSigner.</p>
32
+ <p align="center">
33
+ <a href="https://pypi.org/project/swarmauri_tool_signimage/"><img alt="pypi: swarmauri_tool_signimage unpublished" src="https://img.shields.io/static/v1?label=pypi&amp;message=swarmauri_tool_signimage%20unpublished&amp;labelColor=292421&amp;color=805500"></a>
34
+ <a href="https://github.com/swarmauri/swarmauri-sdk/blob/master/pkgs/60-plugins/swarmauri_tool_signimage/pyproject.toml"><img alt="Source version: 0.1.0" src="https://img.shields.io/static/v1?label=Source%20version&amp;message=0.1.0&amp;labelColor=292421&amp;color=994525"></a>
35
+ <a href="https://github.com/swarmauri/swarmauri-sdk/blob/master/pkgs/60-plugins/swarmauri_tool_signimage/pyproject.toml"><img alt="Python: &gt;=3.10,&lt;3.15" src="https://img.shields.io/static/v1?label=Python&amp;message=%3E%3D3.10%2C%3C3.15&amp;labelColor=292421&amp;color=994525"></a>
36
+ <a href="https://github.com/swarmauri/swarmauri-sdk/blob/master/pkgs/60-plugins/swarmauri_tool_signimage/pyproject.toml"><img alt="Layer: plugins" src="https://img.shields.io/static/v1?label=Layer&amp;message=plugins&amp;labelColor=292421&amp;color=994525"></a>
37
+ <a href="https://github.com/swarmauri/swarmauri-sdk/blob/master/pkgs/60-plugins/swarmauri_tool_signimage/README.md#lifecycle-and-migration"><img alt="Lifecycle: active" src="https://img.shields.io/static/v1?label=Lifecycle&amp;message=active&amp;labelColor=292421&amp;color=24654A"></a>
38
+ <a href="https://github.com/swarmauri/swarmauri-sdk/blob/master/pkgs/60-plugins/swarmauri_tool_signimage/LICENSE"><img alt="License: Apache-2.0" src="https://img.shields.io/static/v1?label=License&amp;message=Apache-2.0&amp;labelColor=292421&amp;color=994525"></a>
39
+ <a href="https://github.com/swarmauri/swarmauri-sdk/blob/master/pkgs/60-plugins/swarmauri_tool_signimage/NOTICE"><img alt="Notice: attribution" src="https://img.shields.io/static/v1?label=Notice&amp;message=attribution&amp;labelColor=292421&amp;color=994525"></a>
40
+ </p>
41
+ <p align="center">
42
+ <a href="https://pypi.org/project/swarmauri_tool_signimage/"><img alt="pypi downloads: swarmauri_tool_signimage: unpublished" src="https://img.shields.io/static/v1?label=pypi%20downloads&amp;message=swarmauri_tool_signimage%3A%20unpublished&amp;labelColor=292421&amp;color=805500"></a>
43
+ <a href="https://github.com/swarmauri/swarmauri-sdk/blob/master/pkgs/60-plugins/swarmauri_tool_signimage/README.md"><img alt="README hits: swarmauri_tool_signimage" src="https://hits.sh/github.com/swarmauri/swarmauri-sdk/pkgs/60-plugins/swarmauri_tool_signimage/README.md.svg?label=README%20hits&amp;labelColor=292421&amp;color=08704E"></a>
44
+ </p>
45
+ <p align="center">
46
+ <a href="https://github.com/swarmauri/swarmauri-sdk/actions/workflows/readme-standards.yml"><img alt="README standards: CI gate" src="https://img.shields.io/static/v1?label=README%20standards&amp;message=CI%20gate&amp;labelColor=292421&amp;color=67437E"></a>
47
+ <a href="https://github.com/swarmauri/swarmauri-sdk/blob/master/pkgs/60-plugins/swarmauri_tool_signimage/tests/unit/test_readme_sources.py"><img alt="Tests: example source" src="https://img.shields.io/static/v1?label=Tests&amp;message=example%20source&amp;labelColor=292421&amp;color=67437E"></a>
48
+ <a href="https://github.com/swarmauri/swarmauri-sdk/blob/master/pkgs/60-plugins/swarmauri_tool_signimage/README.md#certification-status"><img alt="Certification: not certified" src="https://img.shields.io/static/v1?label=Certification&amp;message=not%20certified&amp;labelColor=292421&amp;color=805500"></a>
49
+ <a href="https://github.com/swarmauri/swarmauri-sdk/blob/master/tools/readme/POLICY.md"><img alt="Governance: repository policy" src="https://img.shields.io/static/v1?label=Governance&amp;message=repository%20policy&amp;labelColor=292421&amp;color=67437E"></a>
50
+ <a href="https://github.com/swarmauri/swarmauri-sdk/actions/workflows/readme-standards.yml"><img alt="Evidence: source and CI" src="https://img.shields.io/static/v1?label=Evidence&amp;message=source%20and%20CI&amp;labelColor=292421&amp;color=67437E"></a>
51
+ </p>
52
+ <p align="center"><a href="#overview">Overview</a> · <a href="#installation">Installation</a> · <a href="#quick-start">Quick Start</a> · <a href="#usage">Usage</a> · <a href="#public-api-and-import-surfaces">API</a> · <a href="#contributing">Contributing</a> · <a href="#governance">Governance</a> · <a href="#license">License</a></p>
53
+ <!-- readme-standards:end branding -->
54
+
55
+ ---
56
+
57
+ ## Overview
58
+
59
+ ### Summary
60
+
61
+ Sign generated images and configured metadata through MediaSigner.
62
+
63
+ ### Why This Package
64
+
65
+ This package provides MediaSigner, JWS signatures, signed image metadata for applications using the Swarmauri SDK.
66
+
67
+ ### When to Use
68
+
69
+ Use this component when an application needs the image workflow described in the usage examples.
70
+
71
+ ### Features
72
+
73
+ - MediaSigner.
74
+ - JWS signatures.
75
+ - Signed image metadata.
76
+
77
+ ### Non-Goals
78
+
79
+ Provider accounts, storage credentials, and signing identities are configured by the application.
80
+
81
+ ---
82
+
83
+ ## Getting Started
84
+
85
+ ### Prerequisites
86
+
87
+ The package supports Python 3.10 through 3.14. Install any application-specific provider or adapter used in your workflow.
88
+
89
+ ### Installation
90
+
91
+ #### Install with uv
92
+
93
+ <!-- readme-standards:begin installation.uv -->
94
+ `swarmauri_tool_signimage` is not declared published. From the source checkout:
95
+
96
+ ```bash
97
+ uv pip install .
98
+ ```
99
+ <!-- readme-standards:end installation.uv -->
100
+
101
+ From a Swarmauri SDK checkout, run `uv sync --directory pkgs --package swarmauri_tool_signimage`.
102
+
103
+ #### Install with pip
104
+
105
+ <!-- readme-standards:begin installation.pip -->
106
+ `swarmauri_tool_signimage` is not declared published. From the source checkout:
107
+
108
+ ```bash
109
+ python -m pip install .
110
+ ```
111
+ <!-- readme-standards:end installation.pip -->
112
+
113
+ From the wheelhouse containing the SDK dependency builds, run `python -m pip install --find-links dist swarmauri_tool_signimage`.
114
+
115
+ #### Install with Poetry
116
+
117
+ <!-- readme-standards:begin installation.poetry -->
118
+ `swarmauri_tool_signimage` is not declared published. From a separate Poetry project, replace the path with your checkout:
119
+
120
+ ```bash
121
+ poetry add /path/to/swarmauri_tool_signimage
122
+ ```
123
+ <!-- readme-standards:end installation.poetry -->
124
+
125
+ ### Quick Start
126
+
127
+ #### Example
128
+
129
+ <!-- readme-standards:begin example.quick-start -->
130
+ Source: [docs/readme/quick_start.py](https://github.com/swarmauri/swarmauri-sdk/blob/master/pkgs/60-plugins/swarmauri_tool_signimage/docs/readme/quick_start.py).
131
+
132
+ ```python
133
+ from swarmauri_tool_signimage import ImageSigningConfig
134
+
135
+
136
+ config = ImageSigningConfig(
137
+ key_ref="image-key",
138
+ algorithm="EdDSA",
139
+ metadata={"issuer": "Studio", "purpose": "image generation"},
140
+ )
141
+ print(config.algorithm)
142
+ ```
143
+ <!-- readme-standards:end example.quick-start -->
144
+
145
+ #### Expected Result
146
+
147
+ The example shows the package’s configuration and workflow entry point.
148
+
149
+ ---
150
+
151
+ ## Usage
152
+
153
+ ### Common Workflows
154
+
155
+ The signing configuration example uses EdDSA. Inject an existing key provider and scope when creating SignImageTool. The verification script takes an image, its signature JSON, and a trusted raw Ed25519 public key as file arguments. The JWS backend requires a key provider that can supply signing material for the configured key. Its exit status reports verification success.
156
+
157
+ <!-- readme-standards:begin example.usage -->
158
+ Source: [docs/readme/usage.py](https://github.com/swarmauri/swarmauri-sdk/blob/master/pkgs/60-plugins/swarmauri_tool_signimage/docs/readme/usage.py).
159
+
160
+ ```python
161
+ import asyncio
162
+ from pathlib import Path
163
+ from sys import argv
164
+
165
+ from swarmauri_tool_signimage import verify_image_signature
166
+
167
+
168
+ if __name__ == "__main__":
169
+ image, signature, trusted_public_key = map(Path, argv[1:])
170
+ valid = asyncio.run(
171
+ verify_image_signature(
172
+ image.read_bytes(),
173
+ signature.read_bytes(),
174
+ algorithm="EdDSA",
175
+ verify_options={"ed_pubkeys": [trusted_public_key.read_bytes()]},
176
+ )
177
+ )
178
+ print(valid)
179
+ raise SystemExit(0 if valid else 1)
180
+ ```
181
+ <!-- readme-standards:end example.usage -->
182
+
183
+ The image helper uses `MediaVerifier` by default. Applications can import
184
+ `MediaVerifier` from `MediaSigner` and pass an existing verifier through the
185
+ `verifier` argument. Image verification uses the trusted public key.
186
+
187
+ **Expected output.** For an intact image and signature file with the matching trusted key, the script prints the following and exits with status `0`. An invalid signature or changed image prints `False` and exits with status `1`.
188
+
189
+ ```text
190
+ True
191
+ ```
192
+
193
+ ### Configuration
194
+
195
+ Use the public constructor or loader shown above. The caller supplies application-specific collaborators when constructing a component.
196
+
197
+ ### Error Handling
198
+
199
+ Check the structured tool or agent outcome before using image references or reporting that signing succeeded.
200
+
201
+ ### Best Practices
202
+
203
+ Use a distinct storage scope per authorized session and retrieve images through the toolkit after publication.
204
+
205
+ ---
206
+
207
+ ## Package Boundary
208
+
209
+ ### What It Owns
210
+
211
+ Sign generated images and configured metadata through MediaSigner.
212
+
213
+ ### Public API and Import Surfaces
214
+
215
+ Import `SignImageTool` from `swarmauri_tool_signimage`.
216
+
217
+ ### Entry Points
218
+
219
+ <!-- readme-standards:begin entry-points -->
220
+ - `swarmauri.tools` → `SignImageTool` → `swarmauri_tool_signimage:SignImageTool`
221
+ <!-- readme-standards:end entry-points -->
222
+
223
+ ### Injected Dependencies
224
+
225
+ Inject the collaborators required by your application through the public constructor.
226
+
227
+ ### Protocol Consumers
228
+
229
+ Swarmauri applications can use this component through the corresponding SDK resource family.
230
+
231
+ ### Extensions
232
+
233
+ Supply compatible SDK components through the inputs shown in the examples.
234
+
235
+ ---
236
+
237
+ ## Operations and Readiness
238
+
239
+ ### Operational Requirements
240
+
241
+ Set up the application collaborators listed above before running the workflow. Use a test provider and isolated scope for local verification.
242
+
243
+ ### Health and Observability
244
+
245
+ Check tool outcomes, provider health, and storage availability in the application.
246
+
247
+ ### Security and Resource Limits
248
+
249
+ Set provider and storage limits at the application boundary. Keep signing keys in the configured key provider.
250
+
251
+ ### Compatibility
252
+
253
+ Python 3.10 through 3.14. Check the Python support of any provider adapter installed alongside this package.
254
+
255
+ ---
256
+
257
+ ## Verification
258
+
259
+ ### Tests
260
+
261
+ Run the package’s pytest suite from the SDK workspace.
262
+
263
+ ### Certification Status
264
+
265
+ The package is in planning status. Its tests are available in the repository.
266
+
267
+ ### Evidence
268
+
269
+ The package tests and maintained example sources are available alongside its manifest.
270
+
271
+ ---
272
+
273
+ ## FAQ
274
+
275
+ ### Why
276
+
277
+ Sign generated images and configured metadata through MediaSigner.
278
+
279
+ ### How
280
+
281
+ Use the installation instructions and the workflow examples in this guide.
282
+
283
+ ### When
284
+
285
+ Use it when your image workflow needs MediaSigner, JWS signatures, signed image metadata.
286
+
287
+ ---
288
+
289
+ ## Documentation and Related Packages
290
+
291
+ ### More Documentation
292
+
293
+ See the maintained example sources under `docs/readme`.
294
+
295
+ ### Related Packages
296
+
297
+ See the SDK package index for the image tools, toolkit, agents, and packaged skills.
298
+
299
+ ### Project Links
300
+
301
+ <!-- readme-standards:begin project-links -->
302
+ - [Repository](https://github.com/swarmauri/swarmauri-sdk)
303
+ - [pypi: swarmauri_tool_signimage](https://pypi.org/project/swarmauri_tool_signimage/)
304
+ <!-- readme-standards:end project-links -->
305
+
306
+ ---
307
+
308
+ ## Contributing
309
+
310
+ ### How to Contribute
311
+
312
+ Follow the SDK contribution guide and keep workflow examples in sync with the public API.
313
+
314
+ ### Development Setup
315
+
316
+ Use the SDK uv workspace and run the package’s lint and test commands.
317
+
318
+ ### Notes for Maintainers
319
+
320
+ Keep the package import path and registered component name aligned with the manifest.
321
+
322
+ ---
323
+
324
+ ## Governance
325
+
326
+ ### Ownership and Decision Making
327
+
328
+ The Swarmauri SDK maintainers review changes to this package.
329
+
330
+ ### Standards and Policies
331
+
332
+ Follow the SDK contribution and package README policies.
333
+
334
+ ### Lifecycle and Migration
335
+
336
+ This is a new package in planning status.
337
+
338
+ ---
339
+
340
+ ## License and Attribution
341
+
342
+ ### License
343
+
344
+ <!-- readme-standards:begin license -->
345
+ Licensed under `Apache-2.0`. See [LICENSE](https://github.com/swarmauri/swarmauri-sdk/blob/master/pkgs/60-plugins/swarmauri_tool_signimage/LICENSE).
346
+ <!-- readme-standards:end license -->
347
+
348
+ ### Notices
349
+
350
+ <!-- readme-standards:begin notices -->
351
+ See [NOTICE](https://github.com/swarmauri/swarmauri-sdk/blob/master/pkgs/60-plugins/swarmauri_tool_signimage/NOTICE) for attribution.
352
+ <!-- readme-standards:end notices -->
353
+
@@ -0,0 +1,327 @@
1
+ # swarmauri_tool_signimage
2
+
3
+ <!-- readme-standards:begin branding -->
4
+ <p align="center"><a href="https://github.com/swarmauri/swarmauri-sdk"><img src="https://raw.githubusercontent.com/swarmauri/swarmauri-sdk/master/assets/swarmauri.brand.theme.svg" alt="Swarmauri SDK" width="300"></a></p>
5
+ <p align="center"><strong>swarmauri_tool_signimage</strong></p>
6
+ <p align="center">Sign generated images and configured metadata through MediaSigner.</p>
7
+ <p align="center">
8
+ <a href="https://pypi.org/project/swarmauri_tool_signimage/"><img alt="pypi: swarmauri_tool_signimage unpublished" src="https://img.shields.io/static/v1?label=pypi&amp;message=swarmauri_tool_signimage%20unpublished&amp;labelColor=292421&amp;color=805500"></a>
9
+ <a href="https://github.com/swarmauri/swarmauri-sdk/blob/master/pkgs/60-plugins/swarmauri_tool_signimage/pyproject.toml"><img alt="Source version: 0.1.0" src="https://img.shields.io/static/v1?label=Source%20version&amp;message=0.1.0&amp;labelColor=292421&amp;color=994525"></a>
10
+ <a href="https://github.com/swarmauri/swarmauri-sdk/blob/master/pkgs/60-plugins/swarmauri_tool_signimage/pyproject.toml"><img alt="Python: &gt;=3.10,&lt;3.15" src="https://img.shields.io/static/v1?label=Python&amp;message=%3E%3D3.10%2C%3C3.15&amp;labelColor=292421&amp;color=994525"></a>
11
+ <a href="https://github.com/swarmauri/swarmauri-sdk/blob/master/pkgs/60-plugins/swarmauri_tool_signimage/pyproject.toml"><img alt="Layer: plugins" src="https://img.shields.io/static/v1?label=Layer&amp;message=plugins&amp;labelColor=292421&amp;color=994525"></a>
12
+ <a href="https://github.com/swarmauri/swarmauri-sdk/blob/master/pkgs/60-plugins/swarmauri_tool_signimage/README.md#lifecycle-and-migration"><img alt="Lifecycle: active" src="https://img.shields.io/static/v1?label=Lifecycle&amp;message=active&amp;labelColor=292421&amp;color=24654A"></a>
13
+ <a href="https://github.com/swarmauri/swarmauri-sdk/blob/master/pkgs/60-plugins/swarmauri_tool_signimage/LICENSE"><img alt="License: Apache-2.0" src="https://img.shields.io/static/v1?label=License&amp;message=Apache-2.0&amp;labelColor=292421&amp;color=994525"></a>
14
+ <a href="https://github.com/swarmauri/swarmauri-sdk/blob/master/pkgs/60-plugins/swarmauri_tool_signimage/NOTICE"><img alt="Notice: attribution" src="https://img.shields.io/static/v1?label=Notice&amp;message=attribution&amp;labelColor=292421&amp;color=994525"></a>
15
+ </p>
16
+ <p align="center">
17
+ <a href="https://pypi.org/project/swarmauri_tool_signimage/"><img alt="pypi downloads: swarmauri_tool_signimage: unpublished" src="https://img.shields.io/static/v1?label=pypi%20downloads&amp;message=swarmauri_tool_signimage%3A%20unpublished&amp;labelColor=292421&amp;color=805500"></a>
18
+ <a href="https://github.com/swarmauri/swarmauri-sdk/blob/master/pkgs/60-plugins/swarmauri_tool_signimage/README.md"><img alt="README hits: swarmauri_tool_signimage" src="https://hits.sh/github.com/swarmauri/swarmauri-sdk/pkgs/60-plugins/swarmauri_tool_signimage/README.md.svg?label=README%20hits&amp;labelColor=292421&amp;color=08704E"></a>
19
+ </p>
20
+ <p align="center">
21
+ <a href="https://github.com/swarmauri/swarmauri-sdk/actions/workflows/readme-standards.yml"><img alt="README standards: CI gate" src="https://img.shields.io/static/v1?label=README%20standards&amp;message=CI%20gate&amp;labelColor=292421&amp;color=67437E"></a>
22
+ <a href="https://github.com/swarmauri/swarmauri-sdk/blob/master/pkgs/60-plugins/swarmauri_tool_signimage/tests/unit/test_readme_sources.py"><img alt="Tests: example source" src="https://img.shields.io/static/v1?label=Tests&amp;message=example%20source&amp;labelColor=292421&amp;color=67437E"></a>
23
+ <a href="https://github.com/swarmauri/swarmauri-sdk/blob/master/pkgs/60-plugins/swarmauri_tool_signimage/README.md#certification-status"><img alt="Certification: not certified" src="https://img.shields.io/static/v1?label=Certification&amp;message=not%20certified&amp;labelColor=292421&amp;color=805500"></a>
24
+ <a href="https://github.com/swarmauri/swarmauri-sdk/blob/master/tools/readme/POLICY.md"><img alt="Governance: repository policy" src="https://img.shields.io/static/v1?label=Governance&amp;message=repository%20policy&amp;labelColor=292421&amp;color=67437E"></a>
25
+ <a href="https://github.com/swarmauri/swarmauri-sdk/actions/workflows/readme-standards.yml"><img alt="Evidence: source and CI" src="https://img.shields.io/static/v1?label=Evidence&amp;message=source%20and%20CI&amp;labelColor=292421&amp;color=67437E"></a>
26
+ </p>
27
+ <p align="center"><a href="#overview">Overview</a> · <a href="#installation">Installation</a> · <a href="#quick-start">Quick Start</a> · <a href="#usage">Usage</a> · <a href="#public-api-and-import-surfaces">API</a> · <a href="#contributing">Contributing</a> · <a href="#governance">Governance</a> · <a href="#license">License</a></p>
28
+ <!-- readme-standards:end branding -->
29
+
30
+ ---
31
+
32
+ ## Overview
33
+
34
+ ### Summary
35
+
36
+ Sign generated images and configured metadata through MediaSigner.
37
+
38
+ ### Why This Package
39
+
40
+ This package provides MediaSigner, JWS signatures, signed image metadata for applications using the Swarmauri SDK.
41
+
42
+ ### When to Use
43
+
44
+ Use this component when an application needs the image workflow described in the usage examples.
45
+
46
+ ### Features
47
+
48
+ - MediaSigner.
49
+ - JWS signatures.
50
+ - Signed image metadata.
51
+
52
+ ### Non-Goals
53
+
54
+ Provider accounts, storage credentials, and signing identities are configured by the application.
55
+
56
+ ---
57
+
58
+ ## Getting Started
59
+
60
+ ### Prerequisites
61
+
62
+ The package supports Python 3.10 through 3.14. Install any application-specific provider or adapter used in your workflow.
63
+
64
+ ### Installation
65
+
66
+ #### Install with uv
67
+
68
+ <!-- readme-standards:begin installation.uv -->
69
+ `swarmauri_tool_signimage` is not declared published. From the source checkout:
70
+
71
+ ```bash
72
+ uv pip install .
73
+ ```
74
+ <!-- readme-standards:end installation.uv -->
75
+
76
+ From a Swarmauri SDK checkout, run `uv sync --directory pkgs --package swarmauri_tool_signimage`.
77
+
78
+ #### Install with pip
79
+
80
+ <!-- readme-standards:begin installation.pip -->
81
+ `swarmauri_tool_signimage` is not declared published. From the source checkout:
82
+
83
+ ```bash
84
+ python -m pip install .
85
+ ```
86
+ <!-- readme-standards:end installation.pip -->
87
+
88
+ From the wheelhouse containing the SDK dependency builds, run `python -m pip install --find-links dist swarmauri_tool_signimage`.
89
+
90
+ #### Install with Poetry
91
+
92
+ <!-- readme-standards:begin installation.poetry -->
93
+ `swarmauri_tool_signimage` is not declared published. From a separate Poetry project, replace the path with your checkout:
94
+
95
+ ```bash
96
+ poetry add /path/to/swarmauri_tool_signimage
97
+ ```
98
+ <!-- readme-standards:end installation.poetry -->
99
+
100
+ ### Quick Start
101
+
102
+ #### Example
103
+
104
+ <!-- readme-standards:begin example.quick-start -->
105
+ Source: [docs/readme/quick_start.py](https://github.com/swarmauri/swarmauri-sdk/blob/master/pkgs/60-plugins/swarmauri_tool_signimage/docs/readme/quick_start.py).
106
+
107
+ ```python
108
+ from swarmauri_tool_signimage import ImageSigningConfig
109
+
110
+
111
+ config = ImageSigningConfig(
112
+ key_ref="image-key",
113
+ algorithm="EdDSA",
114
+ metadata={"issuer": "Studio", "purpose": "image generation"},
115
+ )
116
+ print(config.algorithm)
117
+ ```
118
+ <!-- readme-standards:end example.quick-start -->
119
+
120
+ #### Expected Result
121
+
122
+ The example shows the package’s configuration and workflow entry point.
123
+
124
+ ---
125
+
126
+ ## Usage
127
+
128
+ ### Common Workflows
129
+
130
+ The signing configuration example uses EdDSA. Inject an existing key provider and scope when creating SignImageTool. The verification script takes an image, its signature JSON, and a trusted raw Ed25519 public key as file arguments. The JWS backend requires a key provider that can supply signing material for the configured key. Its exit status reports verification success.
131
+
132
+ <!-- readme-standards:begin example.usage -->
133
+ Source: [docs/readme/usage.py](https://github.com/swarmauri/swarmauri-sdk/blob/master/pkgs/60-plugins/swarmauri_tool_signimage/docs/readme/usage.py).
134
+
135
+ ```python
136
+ import asyncio
137
+ from pathlib import Path
138
+ from sys import argv
139
+
140
+ from swarmauri_tool_signimage import verify_image_signature
141
+
142
+
143
+ if __name__ == "__main__":
144
+ image, signature, trusted_public_key = map(Path, argv[1:])
145
+ valid = asyncio.run(
146
+ verify_image_signature(
147
+ image.read_bytes(),
148
+ signature.read_bytes(),
149
+ algorithm="EdDSA",
150
+ verify_options={"ed_pubkeys": [trusted_public_key.read_bytes()]},
151
+ )
152
+ )
153
+ print(valid)
154
+ raise SystemExit(0 if valid else 1)
155
+ ```
156
+ <!-- readme-standards:end example.usage -->
157
+
158
+ The image helper uses `MediaVerifier` by default. Applications can import
159
+ `MediaVerifier` from `MediaSigner` and pass an existing verifier through the
160
+ `verifier` argument. Image verification uses the trusted public key.
161
+
162
+ **Expected output.** For an intact image and signature file with the matching trusted key, the script prints the following and exits with status `0`. An invalid signature or changed image prints `False` and exits with status `1`.
163
+
164
+ ```text
165
+ True
166
+ ```
167
+
168
+ ### Configuration
169
+
170
+ Use the public constructor or loader shown above. The caller supplies application-specific collaborators when constructing a component.
171
+
172
+ ### Error Handling
173
+
174
+ Check the structured tool or agent outcome before using image references or reporting that signing succeeded.
175
+
176
+ ### Best Practices
177
+
178
+ Use a distinct storage scope per authorized session and retrieve images through the toolkit after publication.
179
+
180
+ ---
181
+
182
+ ## Package Boundary
183
+
184
+ ### What It Owns
185
+
186
+ Sign generated images and configured metadata through MediaSigner.
187
+
188
+ ### Public API and Import Surfaces
189
+
190
+ Import `SignImageTool` from `swarmauri_tool_signimage`.
191
+
192
+ ### Entry Points
193
+
194
+ <!-- readme-standards:begin entry-points -->
195
+ - `swarmauri.tools` → `SignImageTool` → `swarmauri_tool_signimage:SignImageTool`
196
+ <!-- readme-standards:end entry-points -->
197
+
198
+ ### Injected Dependencies
199
+
200
+ Inject the collaborators required by your application through the public constructor.
201
+
202
+ ### Protocol Consumers
203
+
204
+ Swarmauri applications can use this component through the corresponding SDK resource family.
205
+
206
+ ### Extensions
207
+
208
+ Supply compatible SDK components through the inputs shown in the examples.
209
+
210
+ ---
211
+
212
+ ## Operations and Readiness
213
+
214
+ ### Operational Requirements
215
+
216
+ Set up the application collaborators listed above before running the workflow. Use a test provider and isolated scope for local verification.
217
+
218
+ ### Health and Observability
219
+
220
+ Check tool outcomes, provider health, and storage availability in the application.
221
+
222
+ ### Security and Resource Limits
223
+
224
+ Set provider and storage limits at the application boundary. Keep signing keys in the configured key provider.
225
+
226
+ ### Compatibility
227
+
228
+ Python 3.10 through 3.14. Check the Python support of any provider adapter installed alongside this package.
229
+
230
+ ---
231
+
232
+ ## Verification
233
+
234
+ ### Tests
235
+
236
+ Run the package’s pytest suite from the SDK workspace.
237
+
238
+ ### Certification Status
239
+
240
+ The package is in planning status. Its tests are available in the repository.
241
+
242
+ ### Evidence
243
+
244
+ The package tests and maintained example sources are available alongside its manifest.
245
+
246
+ ---
247
+
248
+ ## FAQ
249
+
250
+ ### Why
251
+
252
+ Sign generated images and configured metadata through MediaSigner.
253
+
254
+ ### How
255
+
256
+ Use the installation instructions and the workflow examples in this guide.
257
+
258
+ ### When
259
+
260
+ Use it when your image workflow needs MediaSigner, JWS signatures, signed image metadata.
261
+
262
+ ---
263
+
264
+ ## Documentation and Related Packages
265
+
266
+ ### More Documentation
267
+
268
+ See the maintained example sources under `docs/readme`.
269
+
270
+ ### Related Packages
271
+
272
+ See the SDK package index for the image tools, toolkit, agents, and packaged skills.
273
+
274
+ ### Project Links
275
+
276
+ <!-- readme-standards:begin project-links -->
277
+ - [Repository](https://github.com/swarmauri/swarmauri-sdk)
278
+ - [pypi: swarmauri_tool_signimage](https://pypi.org/project/swarmauri_tool_signimage/)
279
+ <!-- readme-standards:end project-links -->
280
+
281
+ ---
282
+
283
+ ## Contributing
284
+
285
+ ### How to Contribute
286
+
287
+ Follow the SDK contribution guide and keep workflow examples in sync with the public API.
288
+
289
+ ### Development Setup
290
+
291
+ Use the SDK uv workspace and run the package’s lint and test commands.
292
+
293
+ ### Notes for Maintainers
294
+
295
+ Keep the package import path and registered component name aligned with the manifest.
296
+
297
+ ---
298
+
299
+ ## Governance
300
+
301
+ ### Ownership and Decision Making
302
+
303
+ The Swarmauri SDK maintainers review changes to this package.
304
+
305
+ ### Standards and Policies
306
+
307
+ Follow the SDK contribution and package README policies.
308
+
309
+ ### Lifecycle and Migration
310
+
311
+ This is a new package in planning status.
312
+
313
+ ---
314
+
315
+ ## License and Attribution
316
+
317
+ ### License
318
+
319
+ <!-- readme-standards:begin license -->
320
+ Licensed under `Apache-2.0`. See [LICENSE](https://github.com/swarmauri/swarmauri-sdk/blob/master/pkgs/60-plugins/swarmauri_tool_signimage/LICENSE).
321
+ <!-- readme-standards:end license -->
322
+
323
+ ### Notices
324
+
325
+ <!-- readme-standards:begin notices -->
326
+ See [NOTICE](https://github.com/swarmauri/swarmauri-sdk/blob/master/pkgs/60-plugins/swarmauri_tool_signimage/NOTICE) for attribution.
327
+ <!-- readme-standards:end notices -->
@@ -0,0 +1,97 @@
1
+ [project]
2
+ name = "swarmauri_tool_signimage"
3
+ version = "0.1.0"
4
+ description = "Sign generated images and configured metadata through MediaSigner."
5
+ readme = "README.md"
6
+ license = "Apache-2.0"
7
+ license-files = ["LICENSE", "NOTICE"]
8
+ requires-python = ">=3.10,<3.15"
9
+ authors = [{ name = "Jacob Stewart", email = "jacob@swarmauri.com" }]
10
+ keywords = ["swarmauri","tools","MediaSigner","JWS signatures","signed image metadata"]
11
+ classifiers = [
12
+ "Development Status :: 1 - Planning",
13
+ "Programming Language :: Python :: 3.10",
14
+ "Programming Language :: Python :: 3.11",
15
+ "Programming Language :: Python :: 3.12",
16
+ "Programming Language :: Python :: 3.13",
17
+ "Programming Language :: Python :: 3.14",
18
+ ]
19
+ dependencies = [
20
+ "swarmauri_base>=0.11.0,<0.12",
21
+ "swarmauri_core>=0.11.1,<0.12",
22
+ "MediaSigner>=0.11.1,<0.12",
23
+ "cryptography>=42",
24
+ "pydantic>=2.9,<3",
25
+ ]
26
+
27
+ [project.urls]
28
+ Repository = "https://github.com/swarmauri/swarmauri-sdk"
29
+
30
+ [project.entry-points."swarmauri.tools"]
31
+ SignImageTool = "swarmauri_tool_signimage:SignImageTool"
32
+
33
+ [tool.uv.sources]
34
+ MediaSigner = { workspace = true }
35
+ swarmauri_base = { workspace = true }
36
+ swarmauri_core = { workspace = true }
37
+ swarmauri_keyprovider_inmemory = { workspace = true }
38
+ swarmauri_storage_memory = { workspace = true }
39
+
40
+ [tool.pytest.ini_options]
41
+ markers = ["unit: Unit tests", "i9n: Integration tests"]
42
+
43
+ [build-system]
44
+ requires = ["poetry-core>=2.2"]
45
+ build-backend = "poetry.core.masonry.api"
46
+
47
+ [dependency-groups]
48
+ dev = ["pytest>=8", "ruff>=0.9.9", "readme-standards==0.1.6; python_version >= '3.11'", "swarmauri_keyprovider_inmemory", "swarmauri_storage_memory"]
49
+
50
+ [tool.readme_standards]
51
+ policy = "package-guide-v1"
52
+ readme = "README.md"
53
+ brand = "swarmauri"
54
+ brand_catalog = "../../../tools/readme/brands.toml"
55
+ repository = "https://github.com/swarmauri/swarmauri-sdk"
56
+ ref = "master"
57
+ package_path = "pkgs/60-plugins/swarmauri_tool_signimage"
58
+ layer = "plugins"
59
+ lifecycle = "active"
60
+ license_file = "LICENSE"
61
+ notice_file = "NOTICE"
62
+
63
+ [tool.readme_standards.distributions.pypi]
64
+ name = "swarmauri_tool_signimage"
65
+ published = false
66
+
67
+ [tool.readme_standards.examples.quick_start]
68
+ source = "docs/readme/quick_start.py"
69
+ test = "tests/unit/test_readme_sources.py"
70
+ language = "python"
71
+ expected_exit_code = 0
72
+
73
+ [tool.readme_standards.examples.usage]
74
+ source = "docs/readme/usage.py"
75
+ test = "tests/unit/test_readme_sources.py"
76
+ language = "python"
77
+ expected_exit_code = 0
78
+
79
+ [tool.readme_standards.statuses.readme]
80
+ label = "CI gate"
81
+ url = "https://github.com/swarmauri/swarmauri-sdk/actions/workflows/readme-standards.yml"
82
+
83
+ [tool.readme_standards.statuses.tests]
84
+ label = "example source"
85
+ url = "https://github.com/swarmauri/swarmauri-sdk/blob/master/pkgs/60-plugins/swarmauri_tool_signimage/tests/unit/test_readme_sources.py"
86
+
87
+ [tool.readme_standards.statuses.certification]
88
+ label = "not certified"
89
+ url = "https://github.com/swarmauri/swarmauri-sdk/blob/master/pkgs/60-plugins/swarmauri_tool_signimage/README.md#certification-status"
90
+
91
+ [tool.readme_standards.statuses.governance]
92
+ label = "repository policy"
93
+ url = "https://github.com/swarmauri/swarmauri-sdk/blob/master/tools/readme/POLICY.md"
94
+
95
+ [tool.readme_standards.statuses.evidence]
96
+ label = "source and CI"
97
+ url = "https://github.com/swarmauri/swarmauri-sdk/actions/workflows/readme-standards.yml"
@@ -0,0 +1,269 @@
1
+ """Sign the bytes and configured metadata of a generated image."""
2
+
3
+ import asyncio
4
+ import json
5
+ from dataclasses import asdict
6
+ from hashlib import sha256
7
+ from threading import Lock
8
+ from typing import Any, Literal
9
+
10
+ from cryptography.hazmat.primitives.serialization import load_pem_private_key
11
+ from MediaSigner import MediaSigner, MediaVerifier
12
+ from pydantic import (
13
+ BaseModel,
14
+ ConfigDict,
15
+ Field,
16
+ JsonValue,
17
+ PrivateAttr,
18
+ field_validator,
19
+ )
20
+ from swarmauri_base.ComponentBase import ComponentBase
21
+ from swarmauri_base.tools.ParameterBase import ParameterBase
22
+ from swarmauri_base.tools.ToolBase import ToolBase
23
+ from swarmauri_core.crypto.types import KeyUse
24
+ from swarmauri_core.image_gens.types import ImageArtifact, image_artifact_key
25
+ from swarmauri_core.key_providers.IKeyProvider import IKeyProvider
26
+ from swarmauri_core.signing.types import Signature
27
+ from swarmauri_core.storage.IStorageAdapter import IStorageAdapter
28
+
29
+ _FORMAT = "JWSSigner"
30
+ _RESERVED = {
31
+ "schema_version",
32
+ "sha256",
33
+ "artifact_id",
34
+ "media_type",
35
+ "byte_count",
36
+ "provider",
37
+ "model",
38
+ "metadata",
39
+ }
40
+
41
+
42
+ def _json(value: Any) -> bytes:
43
+ return json.dumps(
44
+ value,
45
+ ensure_ascii=True,
46
+ sort_keys=True,
47
+ separators=(",", ":"),
48
+ allow_nan=False,
49
+ ).encode()
50
+
51
+
52
+ class ImageSigningConfig(BaseModel):
53
+ """Configure the key reference and metadata as an application operator."""
54
+
55
+ model_config = ConfigDict(frozen=True, extra="forbid")
56
+ key_ref: str = Field(min_length=1, repr=False, exclude=True)
57
+ algorithm: str = Field(min_length=1)
58
+ metadata: dict[str, JsonValue] = Field(default_factory=dict)
59
+
60
+ @field_validator("metadata")
61
+ @classmethod
62
+ def validate_metadata(
63
+ cls, value: dict[str, JsonValue]
64
+ ) -> dict[str, JsonValue]:
65
+ """Check that the metadata can fit inside a versioned manifest."""
66
+ if _RESERVED.intersection(value):
67
+ raise ValueError("Signature metadata includes reserved fields")
68
+ if len(_json(value)) > 8192:
69
+ raise ValueError("Signature metadata exceeds 8 KiB")
70
+ return value
71
+
72
+
73
+ async def verify_image_signature(
74
+ image: bytes,
75
+ signature_file: bytes,
76
+ *,
77
+ algorithm: str,
78
+ verify_options: dict[str, Any],
79
+ verifier: MediaVerifier | None = None,
80
+ ) -> bool:
81
+ """Verify the image and manifest with a trusted key and algorithm."""
82
+ try:
83
+ sidecar = json.loads(signature_file)
84
+ manifest = sidecar["manifest"]
85
+ if (
86
+ manifest["schema_version"] != 1
87
+ or manifest["sha256"] != sha256(image).hexdigest()
88
+ or manifest["byte_count"] != len(image)
89
+ ):
90
+ return False
91
+ signature = Signature(
92
+ kid=None,
93
+ version=None,
94
+ format="jws-compact",
95
+ mode="attached",
96
+ alg=algorithm,
97
+ artifact=sidecar["jws"].encode("ascii"),
98
+ meta={"payload_kind": "envelope"},
99
+ )
100
+ except (ValueError, TypeError, KeyError, AttributeError):
101
+ return False
102
+
103
+ verifier = verifier if verifier is not None else MediaVerifier()
104
+ return await verifier.verify_envelope(
105
+ _FORMAT,
106
+ manifest,
107
+ [signature],
108
+ canon="json",
109
+ opts={**verify_options, "alg_allowlist": [algorithm]},
110
+ )
111
+
112
+
113
+ @ComponentBase.register_type(ToolBase, "SignImageTool")
114
+ class SignImageTool(ToolBase):
115
+ """Sign a published artifact in the application's storage scope."""
116
+
117
+ type: Literal["SignImageTool"] = "SignImageTool"
118
+ name: Literal["SignImageTool"] = "SignImageTool"
119
+ description: str = "Sign a generated image by its artifact ID."
120
+ storage: IStorageAdapter = Field(exclude=True)
121
+ scope: str = Field(min_length=1, exclude=True)
122
+ key_provider: IKeyProvider = Field(exclude=True)
123
+ config: ImageSigningConfig = Field(exclude=True)
124
+ parameters: list[ParameterBase] = Field(
125
+ default_factory=lambda: [
126
+ ParameterBase(
127
+ name="artifact_id",
128
+ description="ID returned by GenerateImageTool.",
129
+ input_type="string",
130
+ required=True,
131
+ )
132
+ ]
133
+ )
134
+ _lock: Lock = PrivateAttr(default_factory=Lock)
135
+ _signer: MediaSigner = PrivateAttr()
136
+
137
+ def model_post_init(self, context: Any) -> None:
138
+ self._signer = MediaSigner(key_provider=self.key_provider)
139
+ if self.config.algorithm not in self._signer.supports(_FORMAT).get(
140
+ "algs", ()
141
+ ):
142
+ raise ValueError("Unsupported JWS signing algorithm")
143
+
144
+ def __call__(self, artifact_id: str) -> dict[str, str]:
145
+ """Sign a visible image and return the signature reference."""
146
+ try:
147
+ self.require_published(artifact_id)
148
+ except (ValueError, FileNotFoundError):
149
+ return {"status": "artifact_unavailable"}
150
+ try:
151
+ return self.sign_staged(artifact_id)
152
+ except Exception:
153
+ return {"status": "signing_failed", "artifact_id": artifact_id}
154
+
155
+ def require_published(self, artifact_id: str) -> str:
156
+ """Resolve the storage key of a visible image in this scope."""
157
+ key = image_artifact_key(self.scope, artifact_id)
158
+ batch, _, _ = key.rpartition("/")
159
+ if self.storage.get_blob(f"{batch}/published") != b"1":
160
+ raise FileNotFoundError("Image batch is unpublished")
161
+ return key
162
+
163
+ def sign_staged(self, artifact_id: str) -> dict[str, str]:
164
+ """Sign a stored image for an application-controlled publication."""
165
+ with self._lock:
166
+ return asyncio.run(self._sign(artifact_id))
167
+
168
+ async def _sign(self, artifact_id: str) -> dict[str, str]:
169
+ key = image_artifact_key(self.scope, artifact_id)
170
+ artifact = ImageArtifact(
171
+ **json.loads(self.storage.get_blob(f"{key}/artifact.json"))
172
+ )
173
+ if artifact.artifact_id != artifact_id:
174
+ raise ValueError(
175
+ "The stored record does not match the requested artifact"
176
+ )
177
+ image = self.storage.get_blob(f"{key}/image")
178
+ if len(image) != artifact.byte_count:
179
+ raise ValueError("The stored image does not match its record")
180
+
181
+ if "://" in self.config.key_ref:
182
+ ref = await self.key_provider.get_key_by_ref(
183
+ self.config.key_ref, include_secret=True
184
+ )
185
+ else:
186
+ ref = await self.key_provider.get_key(
187
+ self.config.key_ref, include_secret=True
188
+ )
189
+ if KeyUse.SIGN not in ref.uses:
190
+ raise ValueError("The key is not authorized for signing")
191
+ metadata = ImageSigningConfig.validate_metadata(self.config.metadata)
192
+ manifest = {
193
+ "schema_version": 1,
194
+ **asdict(artifact),
195
+ "sha256": sha256(image).hexdigest(),
196
+ "metadata": metadata,
197
+ }
198
+ signature_id = sha256(
199
+ _json(
200
+ {
201
+ "manifest": manifest,
202
+ "algorithm": self.config.algorithm,
203
+ "key_ref": self.config.key_ref,
204
+ "key_id": ref.kid,
205
+ "key_version": ref.version,
206
+ }
207
+ )
208
+ ).hexdigest()
209
+ signature_key = self._signature_key(key, signature_id)
210
+
211
+ try:
212
+ self.storage.get_blob(signature_key)
213
+ except FileNotFoundError:
214
+ material = ref.material
215
+ if material is None:
216
+ raise ValueError(
217
+ "The JWS backend requires local signing material"
218
+ )
219
+
220
+ signatures = await self._signer.sign_envelope(
221
+ _FORMAT,
222
+ self._jws_key(material),
223
+ manifest,
224
+ alg=self.config.algorithm,
225
+ canon="json",
226
+ opts={"kid": ref.kid},
227
+ )
228
+ if not signatures:
229
+ raise ValueError("MediaSigner returned no signature")
230
+ sidecar = {
231
+ "manifest": manifest,
232
+ "jws": signatures[0].artifact.decode("ascii"),
233
+ }
234
+ self.storage.put_blob(signature_key, _json(sidecar))
235
+ return {
236
+ "status": "signed",
237
+ "artifact_id": artifact_id,
238
+ "signature_id": signature_id,
239
+ }
240
+
241
+ def _jws_key(self, material: bytes | str) -> dict[str, Any]:
242
+ # The JWS implementations use backend-specific key mappings.
243
+ algorithm = self.config.algorithm
244
+ if algorithm.startswith("HS"):
245
+ return {"kind": "raw", "key": material}
246
+ payload = material.encode() if isinstance(material, str) else material
247
+ if algorithm == "EdDSA":
248
+ if payload.startswith(b"-----BEGIN "):
249
+ return {
250
+ "kind": "cryptography_obj",
251
+ "obj": load_pem_private_key(payload, password=None),
252
+ }
253
+ return {"kind": "raw_ed25519_sk", "bytes": payload}
254
+ if algorithm.startswith(("RS", "PS")):
255
+ return {"kind": "pem_priv", "data": payload}
256
+ return {"kind": "pem", "data": payload}
257
+
258
+ def read_signature(self, artifact_id: str, signature_id: str) -> bytes:
259
+ """Read a signature file for a published image in this scope."""
260
+ key = self.require_published(artifact_id)
261
+ return self.storage.get_blob(self._signature_key(key, signature_id))
262
+
263
+ @staticmethod
264
+ def _signature_key(key: str, signature_id: str) -> str:
265
+ if len(signature_id) != 64 or any(
266
+ char not in "0123456789abcdef" for char in signature_id
267
+ ):
268
+ raise ValueError("Invalid image signature ID")
269
+ return f"{key}/signatures/{signature_id}.json"
@@ -0,0 +1,9 @@
1
+ """Sign generated images and configured metadata through MediaSigner."""
2
+
3
+ from .SignImageTool import (
4
+ ImageSigningConfig,
5
+ SignImageTool,
6
+ verify_image_signature,
7
+ )
8
+
9
+ __all__ = ["ImageSigningConfig", "SignImageTool", "verify_image_signature"]