ruby-c2pa 0.2.0

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.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: abf1a09586e233e0bbd47b8917ef9ff2e5f45af8d440575b55a4281f7cbbce8b
4
+ data.tar.gz: bdfee13cb10722e6d4265c5a0a302efd262f1bf313868638c27c0720125db1a9
5
+ SHA512:
6
+ metadata.gz: d0c2c0ca8d3b98b5b668adf0acd4cc37116a5bb7bc6ffa59b08e7b9b84195c09aba15b2440602f655ffca721461a59b9f468a45246c9ebb093e802421b90f19c
7
+ data.tar.gz: 7059e66ff87f11eef2a44715bf0052b23fe2db6056c097eae666ba55ec74b2ccdb5cedfb9cabdd49d56c62700b4914fa32771a9cb79e31201b089674bcc19f62
data/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Carlos Rodriguez
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,296 @@
1
+ # ruby-c2pa
2
+
3
+ A Ruby gem for signing and reading [C2PA](https://c2pa.org) content credentials in media files. Built on top of the official [c2pa-rs](https://github.com/contentauth/c2pa-rs) Rust library via a native extension.
4
+
5
+ ## What is C2PA?
6
+
7
+ C2PA (Coalition for Content Provenance and Authenticity) is an open technical standard for attaching cryptographically signed provenance metadata to media files. It lets you prove:
8
+
9
+ - Who created or edited a file
10
+ - What tools were used
11
+ - When and where it was created
12
+ - Whether the content has been tampered with since signing
13
+
14
+ It is backed by Adobe, Microsoft, Google, the BBC, and others, and is increasingly required by platforms and publishers to establish trust in digital media — particularly in an era of AI-generated content.
15
+
16
+ ## Why Rust bindings?
17
+
18
+ The C2PA specification is complex and security-sensitive. The reference implementation is [c2pa-rs](https://github.com/contentauth/c2pa-rs), an official Rust library maintained by the Content Authenticity Initiative. Rather than re-implementing the specification in Ruby (which would risk diverging from the spec or introducing security bugs), this gem wraps c2pa-rs directly.
19
+
20
+ The binding layer is a native Ruby extension written in Rust using [magnus](https://github.com/matsadler/magnus), which compiles directly into a `.bundle`/`.so` that Ruby loads like any other native extension. This means:
21
+
22
+ - **Correctness** — you get the reference implementation, not a reimplementation
23
+ - **Security** — cryptographic signing and manifest validation are handled by audited Rust code
24
+ - **Performance** — signing large video files happens in native code with no Ruby overhead
25
+ - **Spec compliance** — as c2pa-rs is updated to track the spec, you get those updates by bumping the Rust dependency
26
+
27
+ ## Requirements
28
+
29
+ - Ruby >= 3.0
30
+ - Rust and Cargo (to compile the native library)
31
+ - OpenSSL (usually already present on macOS and Linux)
32
+
33
+ ### Installing Rust
34
+
35
+ The compilation happens automatically during `gem install`, but Rust must be present on your system first.
36
+
37
+ The recommended way is via [mise](https://mise.jdx.dev), which can manage both Ruby and Rust in one place:
38
+
39
+ ```bash
40
+ mise use --global rust@latest
41
+ ```
42
+
43
+ Or via the official [rustup](https://rustup.rs) installer:
44
+
45
+ ```bash
46
+ curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
47
+ ```
48
+
49
+ ## Installation
50
+
51
+ Add to your Gemfile:
52
+
53
+ ```ruby
54
+ gem "ruby-c2pa"
55
+ ```
56
+
57
+ Then run:
58
+
59
+ ```bash
60
+ bundle install
61
+ ```
62
+
63
+ The native Rust library is compiled automatically during installation. This takes a few minutes the first time as it downloads and compiles the c2pa-rs dependency tree.
64
+
65
+ ## Preparing your certificate and key
66
+
67
+ C2PA signing requires an X.509 certificate chain and private key in PEM format. The certificate must chain to a CA that is trusted by the C2PA ecosystem — **self-signed certificates are rejected by c2pa-rs**.
68
+
69
+ ### Development and testing
70
+
71
+ The c2pa-rs project publishes test certificates that work for local development:
72
+
73
+ ```bash
74
+ curl -sL -o test_cert.pem https://raw.githubusercontent.com/contentauth/c2pa-rs/main/sdk/tests/fixtures/certs/es256.pub
75
+ curl -sL -o test_key.pem https://raw.githubusercontent.com/contentauth/c2pa-rs/main/sdk/tests/fixtures/certs/es256.pem
76
+ ```
77
+
78
+ Files signed with these test certificates will include a `signingCredential.untrusted` validation warning since the test CA is not in the public trust list, but are otherwise valid for development purposes.
79
+
80
+ ### Production
81
+
82
+ Obtain a certificate from a CA trusted by the C2PA ecosystem. The certificate file must contain the full chain (end-entity certificate first, then any intermediates), but must **not** include the root CA.
83
+
84
+ The supported signing algorithms are: `es256`, `es384`, `es512`, `ps256`, `ps384`, `ps512`, `ed25519`.
85
+
86
+ ## Usage
87
+
88
+ ### Building a manifest
89
+
90
+ Every signed file requires a `C2PA::Manifest` with at least one action. Actions describe what happened to the asset and are drawn from the `C2PA::Actions` constants, which cover the full vocabulary defined in the C2PA specification.
91
+
92
+ ```ruby
93
+ require "c2pa"
94
+
95
+ manifest = C2PA::Manifest.new(title: "Sunset over the bay")
96
+ manifest.add_action(C2PA::Actions::CREATED)
97
+ ```
98
+
99
+ Actions can be chained:
100
+
101
+ ```ruby
102
+ manifest = C2PA::Manifest.new(title: "Edited photo")
103
+ .add_action(C2PA::Actions::OPENED)
104
+ .add_action(C2PA::Actions::EDITED)
105
+ .add_action(C2PA::Actions::PUBLISHED)
106
+ ```
107
+
108
+ Each action accepts optional fields from the C2PA specification:
109
+
110
+ ```ruby
111
+ manifest.add_action(
112
+ C2PA::Actions::CREATED,
113
+ when_time: "2026-03-17T10:00:00Z", # ISO 8601 timestamp
114
+ software_agent: "Acme Editor/2.0", # defaults to "ruby-c2pa/<version>"
115
+ digital_source_type: "https://cv.iptc.org/newscodes/digitalsourcetype/trainedAlgorithmicMedia",
116
+ changed: ["region_of_interest"],
117
+ parameters: { "description" => "Generated by AI" }
118
+ )
119
+ ```
120
+
121
+ ### Available actions
122
+
123
+ All actions defined in the C2PA specification are available as constants on `C2PA::Actions`:
124
+
125
+ | Constant | Value |
126
+ |----------|-------|
127
+ | `C2PA::Actions::CREATED` | `c2pa.created` |
128
+ | `C2PA::Actions::OPENED` | `c2pa.opened` |
129
+ | `C2PA::Actions::EDITED` | `c2pa.edited` |
130
+ | `C2PA::Actions::EDITED_METADATA` | `c2pa.edited.metadata` |
131
+ | `C2PA::Actions::ADJUSTED_COLOR` | `c2pa.adjustedColor` |
132
+ | `C2PA::Actions::CHANGED_SPEED` | `c2pa.changedSpeed` |
133
+ | `C2PA::Actions::CONVERTED` | `c2pa.converted` |
134
+ | `C2PA::Actions::CROPPED` | `c2pa.cropped` |
135
+ | `C2PA::Actions::DELETED` | `c2pa.deleted` |
136
+ | `C2PA::Actions::DRAWING` | `c2pa.drawing` |
137
+ | `C2PA::Actions::DUBBED` | `c2pa.dubbed` |
138
+ | `C2PA::Actions::ENHANCED` | `c2pa.enhanced` |
139
+ | `C2PA::Actions::FILTERED` | `c2pa.filtered` |
140
+ | `C2PA::Actions::ORIENTATION` | `c2pa.orientation` |
141
+ | `C2PA::Actions::PLACED` | `c2pa.placed` |
142
+ | `C2PA::Actions::PUBLISHED` | `c2pa.published` |
143
+ | `C2PA::Actions::REDACTED` | `c2pa.redacted` |
144
+ | `C2PA::Actions::REMOVED` | `c2pa.removed` |
145
+ | `C2PA::Actions::REPACKAGED` | `c2pa.repackaged` |
146
+ | `C2PA::Actions::RESIZED` | `c2pa.resized` |
147
+ | `C2PA::Actions::TRANSLATED` | `c2pa.translated` |
148
+ | `C2PA::Actions::TRANSCODED` | `c2pa.transcoded` |
149
+ | `C2PA::Actions::TRIMMED` | `c2pa.trimmed` |
150
+ | `C2PA::Actions::UNKNOWN` | `c2pa.unknown` |
151
+ | `C2PA::Actions::WATERMARKED` | `c2pa.watermarked` |
152
+
153
+ ### Adding other assertions
154
+
155
+ Use `add_assertion` for any assertion type beyond actions, such as schema.org metadata or AI training preferences:
156
+
157
+ ```ruby
158
+ manifest.add_assertion(
159
+ label: "stds.schema-org.CreativeWork",
160
+ data: {
161
+ "@context" => "https://schema.org",
162
+ "@type" => "CreativeWork",
163
+ "author" => [{ "@type" => "Person", "name" => "Jane Smith" }]
164
+ }
165
+ )
166
+ ```
167
+
168
+ ### Adding ingredients
169
+
170
+ Ingredients record the source assets a file was derived from:
171
+
172
+ ```ruby
173
+ manifest.add_ingredient(
174
+ title: "Original photo",
175
+ format: "image/jpeg",
176
+ instance_id: "xmp:iid:original-uuid-here"
177
+ )
178
+ ```
179
+
180
+ ### Signing a file
181
+
182
+ The `output` path must not already exist — c2pa-rs will raise an error rather than overwrite an existing file.
183
+
184
+ ```ruby
185
+ manifest = C2PA::Manifest.new(title: "Sunset over the bay")
186
+ .add_action(C2PA::Actions::CREATED)
187
+
188
+ C2PA.sign(
189
+ file: "photo.jpg",
190
+ output: "photo_signed.jpg",
191
+ certificate: "test_cert.pem",
192
+ key: "test_key.pem",
193
+ manifest: manifest
194
+ )
195
+ ```
196
+
197
+ Specify a different signing algorithm with `algorithm:` (default is `"es256"`):
198
+
199
+ ```ruby
200
+ C2PA.sign(
201
+ file: "photo.jpg",
202
+ output: "photo_signed.jpg",
203
+ certificate: "cert.pem",
204
+ key: "key.pem",
205
+ algorithm: "ps256",
206
+ manifest: manifest
207
+ )
208
+ ```
209
+
210
+ ### Reading a manifest
211
+
212
+ ```ruby
213
+ result = C2PA.read(file: "photo_signed.jpg")
214
+
215
+ active = result["manifests"][result["active_manifest"]]
216
+ puts active["title"]
217
+ puts active["claim_generator_info"].first["name"]
218
+ ```
219
+
220
+ ### Checking the SDK version
221
+
222
+ ```ruby
223
+ puts C2PA.sdk_version # => "0.78.3" (depends on the c2pa-rs version bundled with the gem)
224
+ ```
225
+
226
+ ### Error handling
227
+
228
+ All errors inherit from `C2PA::Error`, so you can rescue broadly or narrowly:
229
+
230
+ ```ruby
231
+ begin
232
+ C2PA.sign(file: "photo.jpg", output: "photo_signed.jpg", certificate: "cert.pem", key: "key.pem", manifest: manifest)
233
+ rescue C2PA::InvalidManifestError => e
234
+ puts "Manifest is invalid: #{e.message}"
235
+ rescue C2PA::SigningError => e
236
+ puts "Signing failed: #{e.message}"
237
+ end
238
+
239
+ begin
240
+ C2PA.read(file: "photo_signed.jpg")
241
+ rescue C2PA::ReadError => e
242
+ puts "Could not read manifest: #{e.message}"
243
+ end
244
+
245
+ # Or rescue any C2PA error broadly
246
+ rescue C2PA::Error => e
247
+ puts "C2PA error: #{e.message}"
248
+ end
249
+ ```
250
+
251
+ ## Supported file formats
252
+
253
+ Signing and reading are supported for any format supported by c2pa-rs, including:
254
+
255
+ | Format | MIME type |
256
+ |--------|-----------|
257
+ | JPEG | `image/jpeg` |
258
+ | PNG | `image/png` |
259
+ | WebP | `image/webp` |
260
+ | TIFF | `image/tiff` |
261
+ | AVIF | `image/avif` |
262
+ | MP4 / M4V | `video/mp4` |
263
+ | MOV | `video/quicktime` |
264
+ | MP3 | `audio/mpeg` |
265
+ | WAV | `audio/wav` |
266
+ | PDF | `application/pdf` |
267
+
268
+ The format is detected automatically from the file extension.
269
+
270
+ ## How it works
271
+
272
+ ```
273
+ Ruby (C2PA.sign)
274
+
275
+ │ native extension (magnus)
276
+
277
+ Rust (C2PA::Native.sign_file)
278
+
279
+ │ calls c2pa-rs Builder API
280
+
281
+ c2pa-rs — embeds signed manifest into the file
282
+ ```
283
+
284
+ The Rust extension (`ext/c2pa_native/src/lib.rs`) defines `C2PA::Native` with three methods:
285
+
286
+ | Method | Description |
287
+ |--------|-------------|
288
+ | `C2PA::Native.sign_file` | Sign a file and write the result |
289
+ | `C2PA::Native.read_file` | Read and return the manifest JSON |
290
+ | `C2PA::Native.sdk_version` | Return the c2pa-rs version string |
291
+
292
+ Errors are raised as Ruby exceptions directly from Rust and surfaced as typed `C2PA::Error` subclasses.
293
+
294
+ ## License
295
+
296
+ MIT
data/Rakefile ADDED
@@ -0,0 +1,18 @@
1
+ require "rake/extensiontask"
2
+ require "rake/testtask"
3
+
4
+ GEMSPEC = Gem::Specification.load("ruby-c2pa.gemspec")
5
+
6
+ Rake::ExtensionTask.new("c2pa_native", GEMSPEC) do |ext|
7
+ ext.lib_dir = "lib/c2pa"
8
+ ext.source_pattern = "**/*.{rs,toml,rb}"
9
+ end
10
+
11
+ Rake::TestTask.new(:test) do |t|
12
+ t.libs << "lib" << "test"
13
+ t.test_files = FileList["test/**/*_test.rb"]
14
+ t.verbose = true
15
+ end
16
+
17
+ task test: :compile
18
+ task default: :test
@@ -0,0 +1,19 @@
1
+ [package]
2
+ name = "c2pa_native"
3
+ version = "0.1.0"
4
+ edition = "2021"
5
+
6
+ [lib]
7
+ name = "c2pa_native"
8
+ crate-type = ["cdylib"]
9
+
10
+ [dependencies]
11
+ magnus = { version = "0.8", features = [] }
12
+ c2pa = { version = "0.78", features = ["file_io"] }
13
+ serde_json = "1"
14
+
15
+ [profile.release]
16
+ opt-level = 3
17
+ lto = true
18
+ codegen-units = 1
19
+ strip = true
@@ -0,0 +1,4 @@
1
+ require "mkmf"
2
+ require "rb_sys/mkmf"
3
+
4
+ create_rust_makefile("c2pa/c2pa_native")
@@ -0,0 +1,104 @@
1
+ use std::path::Path;
2
+ use c2pa::{create_signer, Builder, Reader, SigningAlg};
3
+ use magnus::{function, prelude::*, Error, Ruby};
4
+
5
+ // ─── Helpers ─────────────────────────────────────────────────────────────────
6
+
7
+ fn alg_from_str(alg: &str) -> Result<SigningAlg, String> {
8
+ match alg.to_lowercase().as_str() {
9
+ "ps256" => Ok(SigningAlg::Ps256),
10
+ "ps384" => Ok(SigningAlg::Ps384),
11
+ "ps512" => Ok(SigningAlg::Ps512),
12
+ "es256" => Ok(SigningAlg::Es256),
13
+ "es384" => Ok(SigningAlg::Es384),
14
+ "es512" => Ok(SigningAlg::Es512),
15
+ "ed25519" => Ok(SigningAlg::Ed25519),
16
+ _ => Err(format!(
17
+ "Unknown signing algorithm: '{}'. Valid options: ps256, ps384, ps512, es256, es384, es512, ed25519",
18
+ alg
19
+ )),
20
+ }
21
+ }
22
+
23
+ // ─── Core logic ──────────────────────────────────────────────────────────────
24
+
25
+ fn do_sign_file(
26
+ source_path: &str,
27
+ dest_path: &str,
28
+ cert_path: &str,
29
+ key_path: &str,
30
+ alg_str: &str,
31
+ manifest_json: Option<&str>,
32
+ ) -> Result<(), Box<dyn std::error::Error>> {
33
+ let cert = std::fs::read(cert_path)
34
+ .map_err(|e| format!("Cannot read certificate '{}': {}", cert_path, e))?;
35
+ let key = std::fs::read(key_path)
36
+ .map_err(|e| format!("Cannot read key '{}': {}", key_path, e))?;
37
+
38
+ let alg = alg_from_str(alg_str)?;
39
+ let signer = create_signer::from_keys(&cert, &key, alg, None)
40
+ .map_err(|e| format!("Failed to create signer: {}", e))?;
41
+
42
+ let title = Path::new(source_path)
43
+ .file_name()
44
+ .and_then(|n| n.to_str())
45
+ .unwrap_or("unknown")
46
+ .replace('"', "\\\"");
47
+ let default_json = format!(r#"{{"title": "{}"}}"#, title);
48
+ let json = manifest_json.unwrap_or(&default_json);
49
+
50
+ let mut builder = Builder::from_json(json)
51
+ .map_err(|e| format!("Invalid manifest JSON: {}", e))?;
52
+
53
+ builder.sign_file(&*signer, source_path, dest_path)
54
+ .map_err(|e| format!("Signing failed: {}", e))?;
55
+
56
+ Ok(())
57
+ }
58
+
59
+ fn do_read_file(path: &str) -> Result<String, Box<dyn std::error::Error>> {
60
+ let reader = Reader::from_file(path)
61
+ .map_err(|e| format!("Failed to read manifest from '{}': {}", path, e))?;
62
+ Ok(reader.json())
63
+ }
64
+
65
+ // ─── Ruby-facing functions ────────────────────────────────────────────────────
66
+
67
+ fn sign_file(
68
+ source: String,
69
+ dest: String,
70
+ cert: String,
71
+ key: String,
72
+ alg: Option<String>,
73
+ manifest_json: Option<String>,
74
+ ) -> Result<String, Error> {
75
+ let alg_str = alg.as_deref().unwrap_or("es256");
76
+
77
+ do_sign_file(&source, &dest, &cert, &key, alg_str, manifest_json.as_deref())
78
+ .map_err(|e| Error::new(Ruby::get().expect("called from Ruby thread").exception_runtime_error(), e.to_string()))?;
79
+
80
+ Ok(dest)
81
+ }
82
+
83
+ fn read_file(path: String) -> Result<String, Error> {
84
+ do_read_file(&path)
85
+ .map_err(|e| Error::new(Ruby::get().expect("called from Ruby thread").exception_runtime_error(), e.to_string()))
86
+ }
87
+
88
+ fn sdk_version() -> String {
89
+ c2pa::VERSION.to_string()
90
+ }
91
+
92
+ // ─── Extension entry point ────────────────────────────────────────────────────
93
+
94
+ #[magnus::init]
95
+ fn init(ruby: &Ruby) -> Result<(), Error> {
96
+ let c2pa = ruby.define_module("C2PA")?;
97
+ let native = c2pa.define_module("Native")?;
98
+
99
+ native.define_singleton_method("sign_file", function!(sign_file, 6))?;
100
+ native.define_singleton_method("read_file", function!(read_file, 1))?;
101
+ native.define_singleton_method("sdk_version", function!(sdk_version, 0))?;
102
+
103
+ Ok(())
104
+ }