qualia_core_db/semantic_instruments/attestation/
open_badge.rs1use serde_json::{json, Value};
8
9use super::kinds::{AttestationKind, InstrumentAttestation};
10use crate::semantic_instruments::errors::InstrumentError;
11
12pub const VC_V1_CONTEXT: &str = "https://www.w3.org/2018/credentials/v1";
14pub const OB_V3_CONTEXT: &str = "https://purl.imsglobal.org/spec/ob/v3p0/context-3.0.3.json";
16
17#[derive(Debug, Clone, PartialEq, Eq)]
19pub struct BadgeImage {
20 pub locator: String,
21 pub media_type: String,
22 pub digest: String,
23 pub accessible_text: String,
24}
25
26#[derive(Debug, Clone, PartialEq, Eq)]
28pub struct InstrumentBadgeExport {
29 pub context: Vec<String>,
30 pub types: Vec<String>,
31 pub id: String,
32 pub issuer: String,
33 pub credential_subject_id: String,
34 pub achievement_id: String,
35 pub achievement_name: String,
36 pub assessment_instrument: String,
37 pub image: BadgeImage,
38 pub origin_is_not_truth: bool,
39 pub content_digest: String,
40}
41
42fn require_text(value: &str, field: &'static str) -> Result<(), InstrumentError> {
43 if value.trim().is_empty() {
44 Err(InstrumentError::MissingField(field))
45 } else {
46 Ok(())
47 }
48}
49
50fn require_sha256(value: &str, field: &'static str) -> Result<(), InstrumentError> {
51 if value.starts_with("sha256:") && value.len() > "sha256:".len() {
52 Ok(())
53 } else {
54 Err(InstrumentError::MissingField(field))
55 }
56}
57
58fn person_is_instrument(person: &str, instrument: &str) -> bool {
59 person == instrument
60}
61
62pub fn badge_export(
64 attestation: &InstrumentAttestation,
65 image: BadgeImage,
66 achievement_name: &str,
67) -> Result<InstrumentBadgeExport, InstrumentError> {
68 attestation.validate()?;
69 require_sha256(&image.digest, "digest")?;
70 require_text(&image.accessible_text, "accessible_text")?;
71 require_text(&image.locator, "locator")?;
72 require_text(achievement_name, "achievement_name")?;
73
74 let (credential_subject_id, assessment_instrument) = match attestation.kind {
75 AttestationKind::CapabilityAward => (
76 attestation.award_subject.clone(),
77 attestation.assessment_release_id.clone(),
78 ),
79 _ => (attestation.actor.clone(), attestation.release_id.clone()),
80 };
81
82 if person_is_instrument(&credential_subject_id, &assessment_instrument)
83 || person_is_instrument(&credential_subject_id, &attestation.release_id)
84 {
85 return Err(match attestation.kind {
86 AttestationKind::CapabilityAward => InstrumentError::AwardIsInstrument,
87 _ => InstrumentError::RoleCollision,
88 });
89 }
90
91 Ok(InstrumentBadgeExport {
92 context: vec![VC_V1_CONTEXT.to_string(), OB_V3_CONTEXT.to_string()],
93 types: vec![
94 "VerifiableCredential".into(),
95 "OpenBadgeCredential".into(),
96 "InstrumentAttestation".into(),
97 ],
98 id: format!(
99 "{}#si-open-badge/{}",
100 attestation.release_id, attestation.issued_at
101 ),
102 issuer: attestation.actor.clone(),
103 credential_subject_id,
104 achievement_id: attestation.release_id.clone(),
105 achievement_name: achievement_name.to_string(),
106 assessment_instrument,
107 image,
108 origin_is_not_truth: true,
109 content_digest: attestation.content_digest.clone(),
110 })
111}
112
113impl InstrumentBadgeExport {
114 fn nested_value(&self) -> Result<Value, InstrumentError> {
115 if !self.origin_is_not_truth {
116 return Err(InstrumentError::SignatureAsTruth);
117 }
118 if person_is_instrument(&self.credential_subject_id, &self.assessment_instrument) {
119 return Err(InstrumentError::AwardIsInstrument);
120 }
121 Ok(json!({
122 "@context": self.context,
123 "type": self.types,
124 "id": self.id,
125 "issuer": self.issuer,
126 "credentialSubject": {
127 "id": self.credential_subject_id,
128 "achievement": {
129 "id": self.achievement_id,
130 "name": self.achievement_name,
131 "image": {
132 "id": self.image.locator,
133 "digest": self.image.digest,
134 "mediaType": self.image.media_type,
135 "accessibleText": self.image.accessible_text,
136 }
137 },
138 "assessmentInstrument": self.assessment_instrument,
139 },
140 "originIsNotTruth": true,
141 "contentDigest": self.content_digest,
142 }))
143 }
144
145 pub fn to_json(&self) -> Result<Vec<u8>, InstrumentError> {
147 serde_json::to_vec(&self.nested_value()?)
148 .map_err(|e| InstrumentError::Canonical(e.to_string()))
149 }
150}
151
152#[cfg(test)]
153mod tests {
154 use super::*;
155 use crate::semantic_instruments::demo::demo_catalog;
156 use crate::semantic_instruments::visual::VISUAL_MEDIA_TYPE;
157
158 const DIGEST: &str = "sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
159 const ACTOR: &str = "did:webizen:agent:demo-reviewer";
160 const LEARNER: &str = "did:webizen:agent:learner";
161
162 fn unit_release() -> &'static str {
163 demo_catalog()
164 .iter()
165 .find(|s| s.slug == "unit-convert")
166 .expect("unit-convert demo seed")
167 .release_id
168 }
169
170 fn image() -> BadgeImage {
171 BadgeImage {
172 locator: "https://ns.webizen.org/demo/unit-convert/badge.10d".into(),
173 media_type: VISUAL_MEDIA_TYPE.into(),
174 digest: DIGEST.into(),
175 accessible_text: "Unit conversion demo badge".into(),
176 }
177 }
178
179 fn authorship() -> InstrumentAttestation {
180 InstrumentAttestation {
181 kind: AttestationKind::Authorship,
182 release_id: unit_release().into(),
183 content_digest: DIGEST.into(),
184 actor: ACTOR.into(),
185 issued_at: 1_726_358_400,
186 valid_until: 0,
187 origin_is_not_truth: true,
188 award_subject: String::new(),
189 assessment_release_id: String::new(),
190 }
191 }
192
193 fn award() -> InstrumentAttestation {
194 InstrumentAttestation {
195 kind: AttestationKind::CapabilityAward,
196 release_id: unit_release().into(),
197 content_digest: DIGEST.into(),
198 actor: ACTOR.into(),
199 issued_at: 1_726_358_400,
200 valid_until: 0,
201 origin_is_not_truth: true,
202 award_subject: LEARNER.into(),
203 assessment_release_id: unit_release().into(),
204 }
205 }
206
207 #[test]
208 fn nested_json_contains_achievement_and_image_digest() {
209 let export = badge_export(&authorship(), image(), "Unit conversion (demo)").unwrap();
210 let bytes = export.to_json().unwrap();
211 let text = String::from_utf8(bytes.clone()).unwrap();
212 assert!(text.contains("\"achievement\""));
213 assert!(text.contains("\"digest\""));
214 assert!(text.contains(DIGEST));
215 let v: Value = serde_json::from_slice(&bytes).unwrap();
216 assert_eq!(
217 v["credentialSubject"]["achievement"]["image"]["digest"].as_str(),
218 Some(DIGEST)
219 );
220 assert_eq!(
221 v["credentialSubject"]["achievement"]["id"].as_str(),
222 Some(unit_release())
223 );
224 assert_eq!(v["originIsNotTruth"].as_bool(), Some(true));
225 assert!(export.origin_is_not_truth);
226 assert!(v["@context"]
227 .as_array()
228 .unwrap()
229 .iter()
230 .any(|c| c.as_str() == Some(VC_V1_CONTEXT)));
231 assert!(v["@context"]
232 .as_array()
233 .unwrap()
234 .iter()
235 .any(|c| c.as_str() == Some(OB_V3_CONTEXT)));
236 let types = v["type"].as_array().unwrap();
237 for required in [
238 "VerifiableCredential",
239 "OpenBadgeCredential",
240 "InstrumentAttestation",
241 ] {
242 assert!(types.iter().any(|t| t.as_str() == Some(required)));
243 }
244 }
245
246 #[test]
247 fn capability_award_subject_differs_from_assessment_instrument() {
248 let export = badge_export(&award(), image(), "Unit conversion (demo)").unwrap();
249 assert_eq!(export.credential_subject_id, LEARNER);
250 assert_eq!(export.assessment_instrument, unit_release());
251 assert_ne!(export.credential_subject_id, export.assessment_instrument);
252 let v: Value = serde_json::from_slice(&export.to_json().unwrap()).unwrap();
253 let subject = v["credentialSubject"]["id"].as_str().unwrap();
254 let instrument = v["credentialSubject"]["assessmentInstrument"]
255 .as_str()
256 .unwrap();
257 assert_eq!(subject, LEARNER);
258 assert_eq!(instrument, unit_release());
259 assert_ne!(subject, instrument);
260 }
261
262 #[test]
263 fn missing_accessible_text_fails() {
264 let mut img = image();
265 img.accessible_text.clear();
266 assert_eq!(
267 badge_export(&authorship(), img, "Unit conversion (demo)").unwrap_err(),
268 InstrumentError::MissingField("accessible_text")
269 );
270 }
271
272 #[test]
273 fn actor_equal_to_release_is_role_collision() {
274 let mut claim = authorship();
275 claim.actor = unit_release().into();
276 assert_eq!(
277 badge_export(&claim, image(), "Unit conversion (demo)").unwrap_err(),
278 InstrumentError::RoleCollision
279 );
280 }
281
282 #[test]
283 fn award_subject_equal_to_assessment_is_rejected() {
284 let mut claim = award();
285 claim.award_subject = unit_release().into();
286 assert_eq!(
287 badge_export(&claim, image(), "Unit conversion (demo)").unwrap_err(),
288 InstrumentError::AwardIsInstrument
289 );
290 }
291
292 #[test]
293 fn missing_image_digest_prefix_fails() {
294 let mut img = image();
295 img.digest = "md5:not-sha256".into();
296 assert_eq!(
297 badge_export(&authorship(), img, "Unit conversion (demo)").unwrap_err(),
298 InstrumentError::MissingField("digest")
299 );
300 }
301}