1use ed25519_dalek::{Signature, Signer, SigningKey, Verifier, VerifyingKey};
7
8use super::codec::{amendment_canonical_bytes, canonical_bytes, canonical_digest, LICENCE_FORMAT};
9use super::model::{
10 AgentKind, Delegation, DomainLicence, LicenceAmendment, LicenceClass, PaymentEvidence,
11 RepresentedPrincipalContext, MAX_AMENDMENT_DELTA, MAX_ANCHORS, MAX_DOMAINS, MAX_MEMBERS,
12 MAX_SCOPES,
13};
14
15#[derive(Debug, Clone, PartialEq, Eq)]
16pub enum LicenceError {
17 Malformed(&'static str),
18 UnknownFormat,
19 UnknownClass,
20 UnknownAgentKind,
21 MissingField(&'static str),
22 Oversize(&'static str),
23 InvalidIssuerKey,
24 UntrustedIssuer,
25 BadSignature,
26 NotYetValid,
27 Expired,
28 DomainNotCovered,
29 ScopeNotCovered,
30 DelegationNotPermitted,
31 LicenceIdMismatch,
32 PaymentEvidenceMissing,
33 CommercialPrincipalRequiresCommercialLicence,
34}
35
36impl std::fmt::Display for LicenceError {
37 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
38 let msg = match self {
39 Self::Malformed(w) => return write!(f, "malformed licence: {w}"),
40 Self::UnknownFormat => "unknown licence format",
41 Self::UnknownClass => "unknown licence class",
42 Self::UnknownAgentKind => "unknown licensee agent type",
43 Self::MissingField(n) => return write!(f, "missing field: {n}"),
44 Self::Oversize(w) => return write!(f, "oversize: {w}"),
45 Self::InvalidIssuerKey => "invalid issuer key",
46 Self::UntrustedIssuer => "issuer key is not the pinned issuer",
47 Self::BadSignature => "signature verification failed",
48 Self::NotYetValid => "licence is not yet valid",
49 Self::Expired => "licence has expired",
50 Self::DomainNotCovered => "domain is not covered by this licence",
51 Self::ScopeNotCovered => "capability scope is not covered by this licence",
52 Self::DelegationNotPermitted => "licence class does not permit delegation",
53 Self::LicenceIdMismatch => "amendment targets a different licence",
54 Self::PaymentEvidenceMissing => "licence class requires payment evidence",
55 Self::CommercialPrincipalRequiresCommercialLicence => {
56 "commercial principal or beneficiary cannot claim gratis community/personal tier"
57 }
58 };
59 f.write_str(msg)
60 }
61}
62
63impl std::error::Error for LicenceError {}
64
65pub fn verify_represented_principal(
70 lic: &DomainLicence,
71 principal_ctx: &RepresentedPrincipalContext,
72) -> Result<(), LicenceError> {
73 let class = validate_shape(lic)?;
74 if principal_ctx.requires_commercial_licence() && class.is_gratis_non_commercial() {
75 return Err(LicenceError::CommercialPrincipalRequiresCommercialLicence);
76 }
77 if class.expects_payment() && lic.payment_evidence.is_none() {
78 return Err(LicenceError::PaymentEvidenceMissing);
79 }
80 Ok(())
81}
82
83#[derive(Debug, Clone, Default)]
86pub struct IssueParams {
87 pub issuer_did: String,
88 pub subject_domains: Vec<String>,
89 pub domain_did: String,
90 pub delegation: Option<Delegation>,
91 pub licensee_did: String,
92 pub licensee_agent_type: String,
93 pub licensee_label: String,
94 pub licence_class: LicenceClass,
95 pub capability_scope: Vec<String>,
96 pub not_before_unix: u64,
97 pub expires_unix: u64,
99 pub payment_evidence: Option<PaymentEvidence>,
100 pub revocation_uri: String,
101 pub terms_uri: String,
102}
103
104pub fn normalize_domain(name: &str) -> String {
107 let trimmed = name.trim().trim_end_matches('.').to_ascii_lowercase();
108 match trimmed.rsplit_once(':') {
109 Some((host, port)) if !port.is_empty() && port.chars().all(|c| c.is_ascii_digit()) => {
110 host.to_string()
111 }
112 _ => trimmed,
113 }
114}
115
116fn is_subdomain(domain: &str, parent: &str) -> bool {
118 domain.len() > parent.len()
119 && domain.ends_with(parent)
120 && domain.as_bytes()[domain.len() - parent.len() - 1] == b'.'
121}
122
123fn decode_pubkey(hex_str: &str) -> Result<VerifyingKey, LicenceError> {
124 let bytes: [u8; 32] = hex::decode(hex_str)
125 .ok()
126 .and_then(|b| b.try_into().ok())
127 .ok_or(LicenceError::InvalidIssuerKey)?;
128 VerifyingKey::from_bytes(&bytes).map_err(|_| LicenceError::InvalidIssuerKey)
129}
130
131fn decode_signature(hex_str: &str) -> Result<Signature, LicenceError> {
132 let bytes = hex::decode(hex_str).map_err(|_| LicenceError::Malformed("signature hex"))?;
133 Signature::from_slice(&bytes).map_err(|_| LicenceError::Malformed("signature bytes"))
134}
135
136fn validate_shape(lic: &DomainLicence) -> Result<LicenceClass, LicenceError> {
138 if lic.format != LICENCE_FORMAT {
139 return Err(LicenceError::UnknownFormat);
140 }
141 let class = LicenceClass::parse(&lic.licence_class);
142 if class == LicenceClass::Unknown {
143 return Err(LicenceError::UnknownClass);
144 }
145 if lic.licence_id.trim().is_empty() {
146 return Err(LicenceError::MissingField("licence_id"));
147 }
148 if lic.subject_domains.is_empty() {
149 return Err(LicenceError::MissingField("subject_domains"));
150 }
151 if lic.subject_domains.len() > MAX_DOMAINS {
152 return Err(LicenceError::Oversize("subject_domains"));
153 }
154 if lic.capability_scope.len() > MAX_SCOPES {
155 return Err(LicenceError::Oversize("capability_scope"));
156 }
157 if lic.chain_anchors.len() > MAX_ANCHORS {
158 return Err(LicenceError::Oversize("chain_anchors"));
159 }
160 if !lic.licensee_agent_type.is_empty()
161 && AgentKind::parse(&lic.licensee_agent_type) == AgentKind::Unknown
162 {
163 return Err(LicenceError::UnknownAgentKind);
164 }
165 for name in lic.subject_domains.iter() {
166 if name.contains('*') || normalize_domain(name).is_empty() {
167 return Err(LicenceError::Malformed("subject_domains"));
168 }
169 }
170 if let Some(d) = &lic.delegation {
171 if !class.permits_delegation() {
172 return Err(LicenceError::DelegationNotPermitted);
173 }
174 if d.members.len() > MAX_MEMBERS {
175 return Err(LicenceError::Oversize("delegation.members"));
176 }
177 for m in d.members.iter() {
178 if m.contains('*') || normalize_domain(m).is_empty() {
179 return Err(LicenceError::Malformed("delegation.members"));
180 }
181 }
182 }
183 Ok(class)
184}
185
186fn domain_covered(
187 lic: &DomainLicence,
188 class: LicenceClass,
189 domain: &str,
190 effective_members: Option<&[String]>,
191) -> bool {
192 let d = normalize_domain(domain);
193 if lic.subject_domains.iter().any(|s| normalize_domain(s) == d) {
194 return true;
195 }
196 if !class.permits_delegation() {
197 return false;
198 }
199 let Some(del) = &lic.delegation else {
200 return false;
201 };
202 let roster: &[String] = effective_members.unwrap_or(&del.members);
203 if roster.iter().any(|m| normalize_domain(m) == d) {
204 return true;
205 }
206 del.covers_subdomains
207 && lic
208 .subject_domains
209 .iter()
210 .any(|s| is_subdomain(&d, &normalize_domain(s)))
211}
212
213pub fn issue(params: IssueParams, signing_key: &SigningKey) -> Result<DomainLicence, LicenceError> {
215 if params.licence_class == LicenceClass::Unknown {
216 return Err(LicenceError::UnknownClass);
217 }
218 if params.licence_class.expects_payment() && params.payment_evidence.is_none() {
219 return Err(LicenceError::PaymentEvidenceMissing);
220 }
221 if params.delegation.is_some() && !params.licence_class.permits_delegation() {
222 return Err(LicenceError::DelegationNotPermitted);
223 }
224 let issuer_pubkey_hex = hex::encode(signing_key.verifying_key().to_bytes());
225 let mut lic = DomainLicence {
226 format: LICENCE_FORMAT.to_string(),
227 licence_id: String::new(),
228 issuer_did: params.issuer_did,
229 issuer_pubkey_hex,
230 subject_domains: params
231 .subject_domains
232 .iter()
233 .map(|d| normalize_domain(d))
234 .collect(),
235 domain_did: params.domain_did,
236 delegation: params.delegation.map(|d| Delegation {
237 covers_subdomains: d.covers_subdomains,
238 members: d.members.iter().map(|m| normalize_domain(m)).collect(),
239 steward_agreement: d.steward_agreement,
240 }),
241 licensee_did: params.licensee_did,
242 licensee_agent_type: params.licensee_agent_type,
243 licensee_label: params.licensee_label,
244 licence_class: params.licence_class.token().to_string(),
245 capability_scope: params.capability_scope,
246 not_before_unix: params.not_before_unix,
247 expires_unix: params.expires_unix,
248 payment_evidence: params.payment_evidence,
249 chain_anchors: Vec::new(),
250 revocation_uri: params.revocation_uri,
251 terms_uri: params.terms_uri,
252 signature_hex: String::new(),
253 };
254 let provisional = canonical_digest(&lic);
255 lic.licence_id = format!("did:q42:licence:{}", &hex::encode(provisional)[..32]);
256 let sig = signing_key.sign(&canonical_bytes(&lic));
257 lic.signature_hex = hex::encode(sig.to_bytes());
258 validate_shape(&lic)?;
259 Ok(lic)
260}
261
262pub fn issue_amendment(
264 licence_id: &str,
265 seq: u32,
266 add_members: Vec<String>,
267 remove_members: Vec<String>,
268 issued_unix: u64,
269 signing_key: &SigningKey,
270) -> Result<LicenceAmendment, LicenceError> {
271 if add_members.len() + remove_members.len() > MAX_AMENDMENT_DELTA {
272 return Err(LicenceError::Oversize("amendment delta"));
273 }
274 let mut amend = LicenceAmendment {
275 licence_id: licence_id.to_string(),
276 seq,
277 add_members: add_members.iter().map(|m| normalize_domain(m)).collect(),
278 remove_members: remove_members.iter().map(|m| normalize_domain(m)).collect(),
279 issued_unix,
280 signature_hex: String::new(),
281 };
282 let sig = signing_key.sign(&amendment_canonical_bytes(&amend));
283 amend.signature_hex = hex::encode(sig.to_bytes());
284 Ok(amend)
285}
286
287pub fn verify_amendment(amend: &LicenceAmendment, lic: &DomainLicence) -> Result<(), LicenceError> {
289 if amend.licence_id != lic.licence_id {
290 return Err(LicenceError::LicenceIdMismatch);
291 }
292 let key = decode_pubkey(&lic.issuer_pubkey_hex)?;
293 let sig = decode_signature(&amend.signature_hex)?;
294 key.verify(&amendment_canonical_bytes(amend), &sig)
295 .map_err(|_| LicenceError::BadSignature)
296}
297
298pub fn delegated_members(
300 lic: &DomainLicence,
301 amendments: &[LicenceAmendment],
302) -> Result<Vec<String>, LicenceError> {
303 let mut roster: Vec<String> = lic
304 .delegation
305 .as_ref()
306 .map(|d| d.members.clone())
307 .unwrap_or_default();
308 let mut sorted: Vec<&LicenceAmendment> = amendments.iter().collect();
309 sorted.sort_by_key(|a| a.seq);
310 for amend in sorted {
311 verify_amendment(amend, lic)?;
312 for m in &amend.add_members {
313 let n = normalize_domain(m);
314 if !roster.contains(&n) {
315 roster.push(n);
316 }
317 }
318 for m in &amend.remove_members {
319 let n = normalize_domain(m);
320 roster.retain(|r| r != &n);
321 }
322 }
323 if roster.len() > MAX_MEMBERS {
324 return Err(LicenceError::Oversize("delegation.members"));
325 }
326 Ok(roster)
327}
328
329pub fn verify(
331 lic: &DomainLicence,
332 now_unix: u64,
333 serving_domain: &str,
334 required_scope: &str,
335 pinned_issuer_pubkey_hex: Option<&str>,
336 amendments: &[LicenceAmendment],
337) -> Result<(), LicenceError> {
338 let class = validate_shape(lic)?;
339 let key = decode_pubkey(&lic.issuer_pubkey_hex)?;
340 if let Some(pinned) = pinned_issuer_pubkey_hex {
341 if !lic.issuer_pubkey_hex.eq_ignore_ascii_case(pinned.trim()) {
342 return Err(LicenceError::UntrustedIssuer);
343 }
344 }
345 let sig = decode_signature(&lic.signature_hex)?;
346 key.verify(&canonical_bytes(lic), &sig)
347 .map_err(|_| LicenceError::BadSignature)?;
348 if now_unix < lic.not_before_unix {
349 return Err(LicenceError::NotYetValid);
350 }
351 if lic.expires_unix != 0 && now_unix >= lic.expires_unix {
352 return Err(LicenceError::Expired);
353 }
354 let members = delegated_members(lic, amendments)?;
355 if !domain_covered(lic, class, serving_domain, Some(&members)) {
356 return Err(LicenceError::DomainNotCovered);
357 }
358 if !required_scope.is_empty() && !lic.capability_scope.iter().any(|s| s == required_scope) {
359 return Err(LicenceError::ScopeNotCovered);
360 }
361 Ok(())
362}
363
364#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
366pub struct LicenceStatus {
367 pub licensed: bool,
368 pub licence_id: String,
369 pub class: String,
370 pub subject_domains: Vec<String>,
371 pub expires_unix: u64,
372 pub reason: String,
373}
374
375pub fn licence_status(
377 lic: Option<&DomainLicence>,
378 now_unix: u64,
379 serving_domain: &str,
380 required_scope: &str,
381 pinned_issuer_pubkey_hex: Option<&str>,
382 amendments: &[LicenceAmendment],
383) -> LicenceStatus {
384 let Some(lic) = lic else {
385 return LicenceStatus {
386 licensed: false,
387 licence_id: String::new(),
388 class: String::new(),
389 subject_domains: Vec::new(),
390 expires_unix: 0,
391 reason: "no licence".into(),
392 };
393 };
394 let status = LicenceStatus {
395 licensed: false,
396 licence_id: lic.licence_id.clone(),
397 class: lic.licence_class.clone(),
398 subject_domains: lic.subject_domains.clone(),
399 expires_unix: lic.expires_unix,
400 reason: String::new(),
401 };
402 match verify(
403 lic,
404 now_unix,
405 serving_domain,
406 required_scope,
407 pinned_issuer_pubkey_hex,
408 amendments,
409 ) {
410 Ok(()) => LicenceStatus {
411 licensed: true,
412 reason: "ok".into(),
413 ..status
414 },
415 Err(e) => LicenceStatus {
416 reason: e.to_string(),
417 ..status
418 },
419 }
420}