Skip to main content

adk_vision/manifest/
licence.rs

1//! Licence acceptance and the [`LicenceGate`].
2
3use std::collections::BTreeSet;
4use std::path::{Path, PathBuf};
5use std::sync::Mutex;
6
7use chrono::{DateTime, Utc};
8use serde::{Deserialize, Serialize};
9
10use super::{LicenceClass, ModelManifest};
11use crate::digest::Digest;
12use crate::error::{Result, VisionError};
13
14/// A person's recorded acceptance of a use-restricted model's licence.
15///
16/// Recorded by `adk-rust vision models accept <id>`, which shows the licence URL first. No
17/// agent tool records one (V-I11).
18#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
19#[serde(rename_all = "camelCase")]
20pub struct LicenceAcceptance {
21    /// The model manifest id.
22    pub model: String,
23    /// The licence's SPDX id or `LicenseRef-` name.
24    pub licence_id: String,
25    /// The licence URL the person was shown.
26    pub licence_url: String,
27    /// The digest of the licence text the person read, when it was fetched.
28    #[serde(default, skip_serializing_if = "Option::is_none")]
29    pub licence_text_digest: Option<Digest>,
30    /// Who accepted.
31    pub principal: String,
32    /// When.
33    pub accepted_at: DateTime<Utc>,
34}
35
36impl LicenceAcceptance {
37    /// An acceptance of `manifest`'s licence by `principal`, now.
38    pub fn of(manifest: &ModelManifest, principal: impl Into<String>) -> Self {
39        Self {
40            model: manifest.id.clone(),
41            licence_id: manifest.licence.id.clone(),
42            licence_url: manifest.licence.url.clone(),
43            licence_text_digest: None,
44            principal: principal.into(),
45            accepted_at: Utc::now(),
46        }
47    }
48
49    fn covers(&self, manifest: &ModelManifest) -> bool {
50        self.model == manifest.id
51            && self.licence_id == manifest.licence.id
52            && self.licence_url == manifest.licence.url
53    }
54}
55
56/// Where licence acceptances are kept.
57pub trait AcceptanceStore: Send + Sync {
58    /// Every recorded acceptance.
59    ///
60    /// # Errors
61    ///
62    /// The store's read error.
63    fn acceptances(&self) -> Result<Vec<LicenceAcceptance>>;
64
65    /// Records an acceptance.
66    ///
67    /// # Errors
68    ///
69    /// The store's write error.
70    fn record(&self, acceptance: LicenceAcceptance) -> Result<()>;
71}
72
73/// Acceptances in memory.
74#[derive(Debug, Default)]
75pub struct InMemoryAcceptanceStore {
76    acceptances: Mutex<Vec<LicenceAcceptance>>,
77}
78
79impl InMemoryAcceptanceStore {
80    /// An empty store.
81    pub fn new() -> Self {
82        Self::default()
83    }
84}
85
86impl AcceptanceStore for InMemoryAcceptanceStore {
87    fn acceptances(&self) -> Result<Vec<LicenceAcceptance>> {
88        Ok(self.acceptances.lock().unwrap_or_else(|e| e.into_inner()).clone())
89    }
90
91    fn record(&self, acceptance: LicenceAcceptance) -> Result<()> {
92        self.acceptances.lock().unwrap_or_else(|e| e.into_inner()).push(acceptance);
93        Ok(())
94    }
95}
96
97/// Acceptances in a JSON file, by default `.adk/vision/licences.json` in the project.
98///
99/// # Example
100///
101/// ```
102/// use adk_vision::{AcceptanceStore, FileAcceptanceStore};
103///
104/// let dir = std::env::temp_dir().join(format!("adk-vision-doc-{}", std::process::id()));
105/// let store = FileAcceptanceStore::new(dir.join("licences.json"));
106/// assert!(store.acceptances().unwrap().is_empty());
107/// ```
108#[derive(Debug)]
109pub struct FileAcceptanceStore {
110    path: PathBuf,
111    lock: Mutex<()>,
112}
113
114impl FileAcceptanceStore {
115    /// A store in the file at `path`; the file is created on the first acceptance.
116    pub fn new(path: impl Into<PathBuf>) -> Self {
117        Self { path: path.into(), lock: Mutex::new(()) }
118    }
119
120    /// The project's store, `<project>/.adk/vision/licences.json`.
121    pub fn in_project(project: &Path) -> Self {
122        Self::new(project.join(".adk").join("vision").join("licences.json"))
123    }
124
125    fn read(&self) -> Result<Vec<LicenceAcceptance>> {
126        match std::fs::read_to_string(&self.path) {
127            Ok(text) => serde_json::from_str(&text).map_err(|e| {
128                VisionError::InvalidInput(format!("{} is not valid: {e}", self.path.display()))
129            }),
130            Err(err) if err.kind() == std::io::ErrorKind::NotFound => Ok(Vec::new()),
131            Err(err) => Err(VisionError::io("could not read", &self.path, err)),
132        }
133    }
134}
135
136impl AcceptanceStore for FileAcceptanceStore {
137    fn acceptances(&self) -> Result<Vec<LicenceAcceptance>> {
138        let _guard = self.lock.lock().unwrap_or_else(|e| e.into_inner());
139        self.read()
140    }
141
142    fn record(&self, acceptance: LicenceAcceptance) -> Result<()> {
143        let _guard = self.lock.lock().unwrap_or_else(|e| e.into_inner());
144        let mut all = self.read()?;
145        all.push(acceptance);
146        if let Some(parent) = self.path.parent() {
147            std::fs::create_dir_all(parent)
148                .map_err(|e| VisionError::io("could not create", parent, e))?;
149        }
150        let text = serde_json::to_string_pretty(&all)
151            .map_err(|e| VisionError::InvalidInput(e.to_string()))?;
152        let tmp = self.path.with_extension("json.tmp");
153        std::fs::write(&tmp, text).map_err(|e| VisionError::io("could not write", &tmp, e))?;
154        std::fs::rename(&tmp, &self.path)
155            .map_err(|e| VisionError::io("could not replace", &self.path, e))
156    }
157}
158
159/// The non-commercial and copyleft models a user's configuration allows, by id.
160#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
161#[serde(rename_all = "camelCase")]
162pub struct LicencePolicy {
163    /// Model ids allowed despite a non-commercial or copyleft licence.
164    #[serde(default)]
165    pub allow: BTreeSet<String>,
166}
167
168impl LicencePolicy {
169    /// Allows nothing beyond permissive and accepted use-restricted models.
170    pub fn new() -> Self {
171        Self::default()
172    }
173
174    /// Allows a non-commercial or copyleft model by id.
175    pub fn allowing(mut self, model: impl Into<String>) -> Self {
176        self.allow.insert(model.into());
177        self
178    }
179}
180
181/// Decides whether a model may be fetched or loaded under its licence.
182///
183/// # Example
184///
185/// ```
186/// use adk_vision::{
187///     InMemoryAcceptanceStore, LicenceAcceptance, LicenceGate, LicencePolicy, ModelManifest,
188/// };
189///
190/// let sam = ModelManifest::from_json(r#"{
191///     "id": "sam3-local", "task": "segment",
192///     "source": {"kind": "local", "dir": "/models/sam3"},
193///     "files": [{"path": "sam3.onnx", "size": 1,
194///       "sha256": "sha256:0000000000000000000000000000000000000000000000000000000000000000"}],
195///     "licence": {"id": "LicenseRef-SAM", "url": "https://example.org/sam-license",
196///       "class": "useRestricted"},
197///     "runtime": {"kind": "ort", "opset": 17}
198/// }"#).unwrap();
199/// let store = InMemoryAcceptanceStore::new();
200/// let policy = LicencePolicy::new();
201/// let gate = LicenceGate::new(&policy, &store);
202/// let refused = gate.check(&sam).unwrap_err().to_string();
203/// assert!(refused.contains("licence acceptance required"));
204/// assert!(refused.contains("https://example.org/sam-license"));
205///
206/// use adk_vision::AcceptanceStore;
207/// store.record(LicenceAcceptance::of(&sam, "alice@example.com")).unwrap();
208/// assert!(gate.check(&sam).is_ok());
209/// ```
210pub struct LicenceGate<'a> {
211    policy: &'a LicencePolicy,
212    acceptances: &'a dyn AcceptanceStore,
213}
214
215impl<'a> LicenceGate<'a> {
216    /// A gate over a policy and an acceptance store.
217    pub fn new(policy: &'a LicencePolicy, acceptances: &'a dyn AcceptanceStore) -> Self {
218        Self { policy, acceptances }
219    }
220
221    /// Allows a permissive model; a use-restricted one with a recorded acceptance of the
222    /// same licence; a non-commercial or copyleft one the policy names.
223    ///
224    /// # Errors
225    ///
226    /// [`VisionError::LicenceAcceptanceRequired`] with the licence URL,
227    /// [`VisionError::LicenceNotAllowed`], or the store's error.
228    pub fn check(&self, manifest: &ModelManifest) -> Result<()> {
229        match manifest.licence.class {
230            LicenceClass::Permissive => Ok(()),
231            LicenceClass::UseRestricted => {
232                if self.acceptances.acceptances()?.iter().any(|a| a.covers(manifest)) {
233                    Ok(())
234                } else {
235                    Err(VisionError::LicenceAcceptanceRequired {
236                        model: manifest.id.clone(),
237                        licence_url: manifest.licence.url.clone(),
238                    })
239                }
240            }
241            class @ (LicenceClass::NonCommercial | LicenceClass::Copyleft) => {
242                if self.policy.allow.contains(&manifest.id) {
243                    Ok(())
244                } else {
245                    Err(VisionError::LicenceNotAllowed {
246                        model: manifest.id.clone(),
247                        class: class.to_string(),
248                        licence_url: manifest.licence.url.clone(),
249                    })
250                }
251            }
252        }
253    }
254}