Skip to main content

tilo_actions/remote/
vault.rs

1//! What every vocabulary knows of the workspace's vault, whose provider declares its actions
2//! (`tilo_workspace_records::vault`): its provider, the reference that names one of
3//! its items without its secret ([`ItemRef`]) and the parameter that takes one
4//! ([`item_param`]), and the steps its actions take in the record the vault is kept in. Which of
5//! its actions take which step, and which answer a secret, its declaration says
6//! (`tilo_workspace_records::vault`).
7
8use serde::{Deserialize, Serialize};
9
10use super::{ActionAddress, InvokeArgument, InvokeRequest, RemoteActionTarget};
11
12/// The provider the workspace's vault answers under.
13pub const VAULT_PROVIDER: &str = "tilo.vault";
14/// The resource the vault's own actions are of.
15pub const VAULT_RESOURCE: &str = "vault";
16/// The kind of resource a reference is the address of ([`ItemRef`]): what a parameter that
17/// takes a secret by reference names as its resource kind.
18pub const VAULT_ITEM_KIND: &str = "vault.item";
19/// The vault's action that hands one item's secret to a process of an app's own, addressed at
20/// the item ([`ItemRef::target`]).
21pub const VAULT_RELEASE: &str = "release";
22// The vault's actions crates published apart from their provider call by name; the provider's
23// registry test checks each against its declaration.
24/// The items Passwords lists.
25pub const VAULT_LIST: &str = "list";
26/// The item an app's own process kept for a purpose.
27pub const VAULT_FIND: &str = "find";
28/// A secret an app's own process keeps for a purpose.
29pub const VAULT_KEEP: &str = "keep";
30/// A key derived for this device and an app's purpose.
31pub const VAULT_DEVICE_KEY: &str = "device-key";
32/// The logins a page's app kept for a site.
33pub const VAULT_PAGE_LOGINS: &str = "page-logins";
34/// A login a page's app keeps for a site.
35pub const VAULT_KEEP_PAGE_LOGIN: &str = "keep-page-login";
36/// A login a page's app forgets for a site.
37pub const VAULT_FORGET_PAGE_LOGIN: &str = "forget-page-login";
38/// A login written into a page, addressed at the item ([`ItemRef::target`]).
39pub const VAULT_PAGE_FILL: &str = "page-fill";
40
41// The record kind the workspace keeps its vault in, in Passwords, where every action of the vault
42// that writes takes its step, and the id its declaration binds to it.
43pub use tilo_app_id::passwords::{VAULT_KIND, VAULT_RECORD};
44/// The vault record's step that keeps an item, a new one or an edit of one.
45pub const KEEP_SEALED: &str = "keep-sealed";
46/// The vault record's step that forgets an item.
47pub const REMOVE_SEALED: &str = "remove-sealed";
48/// The vault record's step that writes down an item's uses.
49pub const KEEP_USES: &str = "keep-uses";
50
51/// The target of the vault's action `action` of [`VAULT_RESOURCE`].
52#[must_use]
53pub fn vault_target(action: &str) -> RemoteActionTarget {
54    RemoteActionTarget {
55        provider: VAULT_PROVIDER.to_owned(),
56        address: ActionAddress::new(VAULT_RESOURCE, action),
57    }
58}
59
60/// A reference to one item of the workspace's vault: its address (`vault.item:<id>`), which
61/// names it and is not its secret.
62///
63/// An agent may have one, pass it as an argument and keep it in a document. It opens nothing
64/// by itself: the host resolves it only for whoever the workspace's vault lets reach the item,
65/// and only at a place the item belongs to. The id is random, so a reference cannot be guessed
66/// from another.
67#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
68#[serde(try_from = "String", into = "String")]
69pub struct ItemRef {
70    id: String,
71}
72
73impl ItemRef {
74    /// The reference to the entry of the workspace's vault `id` names, when `id` is an
75    /// entry's id: 32 lowercase hexadecimal digits, or an older entry's, the same spelled as a
76    /// UUID with its four hyphens.
77    #[must_use]
78    pub fn from_id(id: &str) -> Option<Self> {
79        let hex = |part: &str| {
80            part.bytes()
81                .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
82        };
83        let entry = match id.len() {
84            32 => hex(id),
85            36 => {
86                let parts: Vec<&str> = id.split('-').collect();
87                parts.iter().map(|part| part.len()).eq([8, 4, 4, 4, 12])
88                    && parts.iter().all(|part| hex(part))
89            }
90            _ => false,
91        };
92        entry.then(|| Self { id: id.to_owned() })
93    }
94
95    /// The reference `address` spells, when it is one.
96    #[must_use]
97    pub fn parse(address: &str) -> Option<Self> {
98        let id = address.strip_prefix(VAULT_ITEM_KIND)?.strip_prefix(':')?;
99        Self::from_id(id)
100    }
101
102    /// The id of the item it names.
103    #[must_use]
104    pub fn id(&self) -> &str {
105        &self.id
106    }
107
108    /// The vault's action `action` addressed at this item (`vault.item:<id>#<action>`), so a
109    /// grant on it is a grant on this one item alone.
110    #[must_use]
111    pub fn target(&self, action: &str) -> RemoteActionTarget {
112        RemoteActionTarget {
113            provider: VAULT_PROVIDER.to_owned(),
114            address: ActionAddress::new(self.to_string(), action),
115        }
116    }
117
118    /// The item an action at `target` of the vault is addressed at, when it is one of `action`
119    /// and addressed at an item.
120    #[must_use]
121    pub fn addressed(target: &RemoteActionTarget, action: &str) -> Option<Self> {
122        (target.provider == VAULT_PROVIDER && target.address.action == action)
123            .then(|| Self::parse(&target.address.resource))
124            .flatten()
125    }
126}
127
128impl std::fmt::Display for ItemRef {
129    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
130        write!(formatter, "{VAULT_ITEM_KIND}:{}", self.id)
131    }
132}
133
134impl TryFrom<String> for ItemRef {
135    type Error = &'static str;
136
137    fn try_from(address: String) -> Result<Self, Self::Error> {
138        Self::parse(&address).ok_or("a reference to a vault item reads vault.item:<id>")
139    }
140}
141
142impl From<ItemRef> for String {
143    fn from(reference: ItemRef) -> Self {
144        reference.to_string()
145    }
146}
147
148/// A parameter that takes a secret by reference: the address of an item of the workspace's
149/// vault ([`ItemRef`]), never the secret's text.
150///
151/// It is a resource parameter of kind [`VAULT_ITEM_KIND`], so every surface that lists, checks
152/// or records arguments carries it as it carries any record's address, and a draft shows it
153/// withheld, as it shows a secret.
154#[must_use]
155pub fn item_param(name: &'static str, description: &'static str) -> crate::ActionParam {
156    crate::ActionParam::required(name, crate::ParamType::Resource, description)
157        .of_resource_kind(VAULT_ITEM_KIND)
158}
159
160/// The vault's actions whose answer is a secret ([`crate::SECRET_ANSWER_TAG`]): a secret shown
161/// to its person, and the code of this moment.
162pub const VAULT_SECRET_ANSWERS: [&str; 2] = ["reveal", "code"];
163
164/// Whether `param` takes a secret by reference ([`item_param`]).
165#[must_use]
166pub fn takes_item(param: &crate::ActionParam) -> bool {
167    param.ty == crate::ParamType::Resource && param.resource_kind() == Some(VAULT_ITEM_KIND)
168}
169
170/// Whether `request` answers a secret, so that whatever records it keeps neither its answer nor
171/// its arguments: an action whose declaration carries
172/// [`SECRET_ANSWER_TAG`](crate::SECRET_ANSWER_TAG), or a call of the action registry that names
173/// one by address.
174#[must_use]
175pub fn answers_secret(request: &InvokeRequest) -> bool {
176    super::answers_a_secret(&request.target.address.action) || calls_answering_a_secret(request)
177}
178
179/// The address a call of the action registry (`tilo.actions#call`) names, when `request` is one.
180fn called_address(request: &InvokeRequest) -> Option<&str> {
181    let target = &request.target;
182    if target.address.action != "call" || target.provider != super::ACTIONS_PROVIDER {
183        return None;
184    }
185    match &request.argument {
186        InvokeArgument::Json(arguments) => {
187            arguments.get("address").and_then(serde_json::Value::as_str)
188        }
189        InvokeArgument::None | InvokeArgument::Text(_) => None,
190    }
191}
192
193/// Whether `request` is a call of the action registry (`tilo.actions#call`) that names, by its
194/// address, an action whose answer is a secret.
195#[must_use]
196pub fn calls_answering_a_secret(request: &InvokeRequest) -> bool {
197    called_address(request)
198        .and_then(|address| address.rsplit_once('#'))
199        .is_some_and(|(_, action)| super::answers_a_secret(action))
200}
201
202/// Whether `request` is a call of the action registry (`tilo.actions#call`) that names the
203/// vault's `action` by its address (`tilo.vault/vault#<action>`, or the vault in a workspace's
204/// tree): what Passwords' code makes of the vault, whose record follows the vault's own.
205#[must_use]
206pub fn calls_by_address(request: &InvokeRequest, action: &str) -> bool {
207    called_address(request)
208        .and_then(|address| address.strip_suffix(action))
209        .and_then(|rest| rest.strip_suffix('#'))
210        .is_some_and(|rest| rest.ends_with(super::WORKSPACE_VAULT))
211}
212
213#[cfg(test)]
214mod tests {
215    #![allow(
216        clippy::unwrap_used,
217        reason = "in a test these are the assertion, not a hazard"
218    )]
219
220    use super::*;
221
222    const ID: &str = "0123456789abcdef0123456789abcdef";
223
224    /// A reference is an item's address and nothing else reads as one.
225    #[test]
226    fn a_reference_is_an_items_address() {
227        let reference = ItemRef::from_id(ID).unwrap();
228        assert_eq!(reference.to_string(), format!("vault.item:{ID}"));
229        assert_eq!(
230            ItemRef::parse(&reference.to_string()),
231            Some(reference.clone())
232        );
233        assert_eq!(reference.id(), ID);
234        let json = serde_json::to_value(&reference).unwrap();
235        assert_eq!(json, serde_json::json!(format!("vault.item:{ID}")));
236        assert_eq!(serde_json::from_value::<ItemRef>(json).unwrap(), reference);
237        let release = reference.target(VAULT_RELEASE);
238        assert_eq!(release.address.resource, format!("vault.item:{ID}"));
239        assert_eq!(ItemRef::addressed(&release, VAULT_RELEASE), Some(reference));
240        assert_eq!(ItemRef::addressed(&release, "code"), None);
241
242        for other in [
243            String::new(),
244            ID.to_owned(),
245            format!("vault.item:{}", ID.to_uppercase()),
246            format!("vault.item:{ID}0"),
247            format!("vault.item:{}", ID.get(1..).unwrap()),
248            format!("vault.items:{ID}"),
249            format!("vault.item:{ID}/secret"),
250            "vault.item:../../people".to_owned(),
251        ] {
252            assert_eq!(ItemRef::parse(&other), None, "{other}");
253            assert!(
254                serde_json::from_value::<ItemRef>(serde_json::json!(other)).is_err(),
255                "{other}"
256            );
257        }
258    }
259
260    /// A parameter that takes a secret by reference is a resource parameter of the vault
261    /// item's kind, and what binds as a reference there is an item's address, never typed
262    /// text.
263    #[test]
264    fn a_parameter_takes_a_secret_by_reference() {
265        let param = item_param("password", "The account's password, by reference");
266        assert!(takes_item(&param));
267        assert_eq!(param.ty, crate::ParamType::Resource);
268        let typed = crate::ActionParam::required("password", crate::ParamType::Secret, "typed");
269        assert!(!takes_item(&typed));
270        let other = crate::ActionParam::required("folder", crate::ParamType::Resource, "a folder")
271            .of_resource_kind("files.entry");
272        assert!(!takes_item(&other));
273
274        let params = [param];
275        let named = serde_json::json!({"password": format!("vault.item:{ID}")});
276        let reference = |args: crate::ActionArgs| match args.get("password") {
277            Some(crate::ArgValue::Resource(address) | crate::ArgValue::Text(address)) => {
278                ItemRef::parse(address)
279            }
280            _ => None,
281        };
282        let bound = crate::ActionArgs::bind_json(&params, named.as_object().unwrap()).unwrap();
283        assert_eq!(reference(bound), ItemRef::from_id(ID));
284        let typed = serde_json::json!({"password": "hunter2"});
285        let bound = crate::ActionArgs::bind_json(&params, typed.as_object().unwrap());
286        // Text that is no address either does not bind or binds as no reference.
287        assert!(!bound.is_ok_and(|bound| reference(bound).is_some()));
288    }
289}