use serde::{Deserialize, Serialize};
use super::{ActionAddress, CatalogueRow, RemoteActionTarget, model_providers, person_accounts};
pub const PROVIDER: &str = "tilo.vault";
pub const RESOURCE: &str = "vault";
pub const LIST: &str = "list";
pub const ADD: &str = "add";
pub const REMOVE: &str = "remove";
pub const USES: &str = "uses";
pub const TAKE_BACK: &str = "take-back";
pub const COPY: &str = "copy";
pub const REVEAL: &str = "reveal";
pub const FILL_PAGE: &str = "fill-page";
pub const ASK: &str = "ask";
pub const VAULT_KIND: &str = tilo_action_policy::roles::WORKSPACE_VAULT_KIND;
pub const KEEP_SEALED: &str = "keep-sealed";
pub const REMOVE_SEALED: &str = "remove-sealed";
pub const KEEP_USES: &str = "keep-uses";
#[must_use]
pub fn effects(action: &str) -> Vec<crate::ActionEffect> {
match action {
ADD | ASK | KEEP => vec![vault_step(KEEP_SEALED)],
REMOVE => vec![vault_step(REMOVE_SEALED)],
COPY | REVEAL | FILL_PAGE | WEB_CALL | SIGN | RELEASE => vec![vault_step(KEEP_USES)],
_ => Vec::new(),
}
}
#[must_use]
pub fn vault_step(verb: &str) -> crate::ActionEffect {
crate::ActionEffect::new(tilo_app_id::apps::PASSWORDS, VAULT_KIND, verb)
}
#[must_use]
pub fn declared_effects(target: &RemoteActionTarget) -> Vec<crate::ActionEffect> {
let in_workspace_tree = target.provider == super::WORKSPACE_GOVERNANCE_PROVIDER
&& target
.address
.resource
.strip_prefix(super::WORKSPACE_GOVERNANCE_KIND)
.and_then(|rest| rest.strip_prefix(':'))
.and_then(|rest| rest.strip_suffix(super::WORKSPACE_VAULT))
.and_then(|workspace| workspace.strip_suffix('/'))
.is_some_and(|workspace| !workspace.contains('/'));
if target.provider == PROVIDER || in_workspace_tree {
return effects(&target.address.action);
}
described_use(target).map_or_else(Vec::new, |action| action.contract.effects)
}
pub const ITEM_KIND: &str = "vault.item";
pub const CODE: &str = "code";
pub const FIND: &str = "find";
#[must_use]
pub fn item_resource(item: &ItemRef) -> String {
format!("{ITEM_KIND}:{}", item.id())
}
#[must_use]
pub fn code_target(item: &ItemRef) -> RemoteActionTarget {
RemoteActionTarget {
provider: PROVIDER.to_owned(),
address: ActionAddress::new(item_resource(item), CODE),
}
}
pub const SIGN: &str = "sign";
#[must_use]
pub fn sign_target(item: &ItemRef) -> RemoteActionTarget {
RemoteActionTarget {
provider: PROVIDER.to_owned(),
address: ActionAddress::new(item_resource(item), SIGN),
}
}
#[must_use]
pub fn signing_item(target: &RemoteActionTarget) -> Option<ItemRef> {
(target.provider == PROVIDER && target.address.action == SIGN)
.then(|| ItemRef::parse(&target.address.resource))
.flatten()
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct Sign {
pub place: String,
pub data: String,
#[serde(default, skip_serializing_if = "String::is_empty")]
pub namespace: String,
#[serde(default, skip_serializing_if = "String::is_empty")]
pub reason: String,
}
#[must_use]
pub fn looks_like_place(text: &str) -> bool {
let Some((scheme, rest)) = text.split_once("://") else {
return false;
};
matches!(
scheme.to_ascii_lowercase().as_str(),
"https" | "http" | "imap" | "smtp" | "ssh"
) && !rest.is_empty()
&& text.len() <= 2_048
&& !text
.chars()
.any(|character| character.is_control() || character.is_whitespace())
}
#[must_use]
pub fn target(action: &str) -> RemoteActionTarget {
RemoteActionTarget {
provider: PROVIDER.to_owned(),
address: ActionAddress::new(RESOURCE, action),
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum ItemKind {
Login,
Key,
CodeGenerator,
SshKey,
Value,
Note,
Wifi,
}
impl ItemKind {
#[must_use]
pub const fn word(self) -> &'static str {
match self {
Self::Login => "login",
Self::Key => "key",
Self::CodeGenerator => "code-generator",
Self::SshKey => "ssh-key",
Self::Value => "value",
Self::Note => "note",
Self::Wifi => "wifi",
}
}
}
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(try_from = "String", into = "String")]
pub struct ItemRef {
id: String,
}
impl ItemRef {
#[must_use]
pub fn from_id(id: &str) -> Option<Self> {
let hex = |part: &str| {
part.bytes()
.all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
};
let entry = match id.len() {
32 => hex(id),
36 => {
let parts: Vec<&str> = id.split('-').collect();
parts.iter().map(|part| part.len()).eq([8, 4, 4, 4, 12])
&& parts.iter().all(|part| hex(part))
}
_ => false,
};
entry.then(|| Self { id: id.to_owned() })
}
#[must_use]
pub fn parse(address: &str) -> Option<Self> {
let id = address.strip_prefix(ITEM_KIND)?.strip_prefix(':')?;
Self::from_id(id)
}
#[must_use]
pub fn id(&self) -> &str {
&self.id
}
}
impl std::fmt::Display for ItemRef {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(formatter, "{ITEM_KIND}:{}", self.id)
}
}
impl TryFrom<String> for ItemRef {
type Error = &'static str;
fn try_from(address: String) -> Result<Self, Self::Error> {
Self::parse(&address).ok_or("a reference to a vault item reads vault.item:<id>")
}
}
impl From<ItemRef> for String {
fn from(reference: ItemRef) -> Self {
reference.to_string()
}
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct ItemView {
pub reference: ItemRef,
pub kind: ItemKind,
pub belongs_to: Vec<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub title: Option<String>,
pub added_at: u64,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub last_used_at: Option<u64>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub algorithm: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub digits: Option<u8>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub period: Option<u64>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub tags: Vec<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub fields: Vec<String>,
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub has_notes: bool,
#[serde(default)]
pub changed_at: u64,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub concerns: Vec<Concern>,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum Concern {
Weak,
Reused,
Stale,
}
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct KeptItems {
pub items: Vec<ItemView>,
}
#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct AddItem {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub item: Option<ItemRef>,
pub kind: ItemKind,
#[serde(default)]
pub belongs_to: Vec<String>,
#[serde(default, skip_serializing_if = "String::is_empty")]
pub username: String,
#[serde(default, skip_serializing_if = "String::is_empty")]
pub sent_in: String,
#[serde(default, skip_serializing_if = "String::is_empty")]
pub algorithm: String,
#[serde(default)]
pub digits: Option<u8>,
#[serde(default)]
pub period: Option<u64>,
#[serde(default, skip_serializing_if = "String::is_empty")]
pub title: String,
#[serde(default, skip_serializing_if = "String::is_empty")]
pub notes: String,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub fields: Vec<ItemField>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub tags: Vec<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub generate: Option<Generate>,
#[serde(default)]
pub secret: String,
}
impl std::fmt::Debug for AddItem {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
formatter
.debug_struct("AddItem")
.field("kind", &self.kind)
.field("belongs_to", &self.belongs_to)
.field("tags", &self.tags)
.finish_non_exhaustive()
}
}
#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct ItemField {
pub label: String,
pub value: String,
}
impl std::fmt::Debug for ItemField {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
formatter
.debug_struct("ItemField")
.field("label", &self.label)
.finish_non_exhaustive()
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct Generate {
#[serde(default = "Generate::twenty")]
pub length: u16,
#[serde(default = "Generate::yes")]
pub capitals: bool,
#[serde(default = "Generate::yes")]
pub digits: bool,
#[serde(default = "Generate::yes")]
pub symbols: bool,
}
impl Generate {
pub const SHORTEST: u16 = 12;
pub const LONGEST: u16 = 128;
const fn twenty() -> u16 {
20
}
const fn yes() -> bool {
true
}
}
impl Default for Generate {
fn default() -> Self {
Self {
length: Self::twenty(),
capitals: true,
digits: true,
symbols: true,
}
}
}
#[must_use]
pub fn item_param(name: &'static str, description: &'static str) -> crate::ActionParam {
crate::ActionParam::required(name, crate::ParamType::Resource, description)
.of_resource_kind(ITEM_KIND)
}
#[must_use]
pub fn takes_item(param: &crate::ActionParam) -> bool {
param.ty == crate::ParamType::Resource && param.resource_kind() == Some(ITEM_KIND)
}
impl ItemRef {
#[must_use]
pub fn bound(args: &crate::ActionArgs, name: &str) -> Option<Self> {
match args.get(name)? {
crate::ArgValue::Resource(address) | crate::ArgValue::Text(address) => {
Self::parse(address)
}
_ => None,
}
}
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct UsesOf {
pub item: ItemRef,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct ItemUse {
pub at: u64,
pub places: Vec<String>,
#[serde(default, skip_serializing_if = "String::is_empty")]
pub by: String,
#[serde(default, skip_serializing_if = "String::is_empty")]
pub using: String,
#[serde(default, skip_serializing_if = "String::is_empty")]
pub what: String,
#[serde(default, skip_serializing_if = "String::is_empty")]
pub allowed: String,
}
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct ItemUses {
pub uses: Vec<ItemUse>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub always: Vec<AlwaysUse>,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct AlwaysUse {
#[serde(default, skip_serializing_if = "String::is_empty")]
pub agent: String,
#[serde(default, skip_serializing_if = "String::is_empty")]
pub app: String,
#[serde(default, skip_serializing_if = "String::is_empty")]
pub by: String,
pub using: String,
pub places: Vec<String>,
pub since: u64,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct RemoveItem {
pub item: ItemRef,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct ShowItem {
pub item: ItemRef,
#[serde(default = "ShowItem::secret_part")]
pub part: String,
}
impl ShowItem {
pub const SECRET: &str = "secret";
pub const NOTES: &str = "notes";
pub const USERNAME: &str = "username";
pub const FIELD: &str = "field:";
fn secret_part() -> String {
Self::SECRET.to_owned()
}
}
#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct Revealed {
pub value: String,
}
impl std::fmt::Debug for Revealed {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
formatter.debug_struct("Revealed").finish_non_exhaustive()
}
}
#[must_use]
pub fn answers_secret(request: &super::InvokeRequest) -> bool {
let target = &request.target;
super::answers_a_secret(&target.address.action) || calls_answering_a_secret(request)
}
#[must_use]
pub fn calls_answering_a_secret(request: &super::InvokeRequest) -> bool {
let target = &request.target;
target.address.action == "call"
&& target.provider == super::ACTIONS_PROVIDER
&& match &request.argument {
super::InvokeArgument::Json(arguments) => arguments
.get("address")
.and_then(serde_json::Value::as_str)
.and_then(|address| address.rsplit_once('#'))
.is_some_and(|(_, action)| super::answers_a_secret(action)),
super::InvokeArgument::None | super::InvokeArgument::Text(_) => false,
}
}
#[must_use]
pub fn calls_by_address(request: &super::InvokeRequest, action: &str) -> bool {
let target = &request.target;
target.address.action == "call"
&& target.provider == super::ACTIONS_PROVIDER
&& match &request.argument {
super::InvokeArgument::Json(arguments) => arguments
.get("address")
.and_then(serde_json::Value::as_str)
.and_then(|address| address.strip_suffix(action))
.and_then(|rest| rest.strip_suffix('#'))
.is_some_and(|rest| rest.ends_with(super::WORKSPACE_VAULT)),
super::InvokeArgument::None | super::InvokeArgument::Text(_) => false,
}
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct TakeBack {
pub item: ItemRef,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub agent: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub app: Option<String>,
}
const REFERENCE: &str = "The `reference` the vault's `ask` answered with (`vault.item:…`). It \
names the vault item and is never the secret itself.";
const REASON: &str = "Why you need it, in one sentence your person reads when they are asked \
whether you may.";
const ASKED_FIRST: &str = "When you work with nobody watching, your person is asked first in the \
conversation whether you may use the item there: tell them it waits for their answer and \
do not make the call again. The item is used when they allow it, and after their Always \
without asking.";
fn use_row(
(provider, resource, label): (&str, &str, &str),
(action, action_label): (&str, &str),
description: String,
params: Vec<crate::ActionParam>,
) -> CatalogueRow {
let mut contract = crate::ActionContract {
kind: crate::ActionKind::Outside,
effects: if provider == PROVIDER {
effects(action)
} else {
vec![vault_step(KEEP_USES)]
},
..crate::ActionContract::default()
};
contract.set_audience(crate::contract::Audience::Agents);
CatalogueRow::for_action(
provider,
provider,
crate::ActionDescriptor {
did: None,
state: crate::ActionState::default(),
semantic_identity: None,
address: ActionAddress::new(resource, action),
resource_kind: resource.to_owned(),
resource_label: label.to_owned(),
action_label: action_label.to_owned(),
keywords: Vec::new(),
icon: None,
description: Some(description),
locus: crate::ExecutionLocus::ServerPreferred,
kind: crate::OperationKind::Effect,
contract,
input: crate::InputSpec::None,
params,
view: None,
},
)
}
#[must_use]
pub fn use_rows() -> Vec<CatalogueRow> {
use crate::{ActionParam, ParamType};
vec![
use_row(
(
person_accounts::PROVIDER,
person_accounts::RESOURCE,
"Mail accounts",
),
(
person_accounts::ADD_MAIL_WITH_ITEM,
"Add mail account from vault",
),
format!(
"Add a mail account for your person, signing in with a password their vault \
keeps. You never hold the password. To get it, call the vault's `ask` with \
kind `login`, belongsTo `[\"imap://<incomingHost>:<incomingPort>\", \
\"smtp://<outgoingHost>:<outgoingPort>\"]` and the username: your person \
types it into a protected field, and you are told the `reference` their \
vault keeps it under. Pass that reference as `password`. The item must be a \
login that belongs to both servers, and it is sent nowhere else. \
{ASKED_FIRST}"
),
vec![
ActionParam::required("address", ParamType::Text, "The account's mail address."),
ActionParam::optional(
"displayName",
ParamType::Text,
"The name mail from it carries.",
),
ActionParam::optional(
"username",
ParamType::Text,
"The name it signs in with, when that is neither the item's own nor the \
address.",
),
ActionParam::required(
"incomingHost",
ParamType::Text,
"The server mail is read from (IMAP).",
),
ActionParam::optional(
"incomingPort",
ParamType::Integer,
"Its port; 993 when left out.",
),
ActionParam::required(
"outgoingHost",
ParamType::Text,
"The server mail is sent through (SMTP).",
),
ActionParam::optional(
"outgoingPort",
ParamType::Integer,
"Its port; 465 when left out.",
),
item_param("password", REFERENCE),
ActionParam::optional("reason", ParamType::Text, REASON),
],
),
use_row(
(
model_providers::PROVIDER,
model_providers::RESOURCE,
"Model providers",
),
(
model_providers::SET_KEY_FROM_ITEM,
"Keep provider key from vault",
),
format!(
"Keep the API key of one of your person's model providers from a key their \
vault keeps. You never hold the key. To get it, call the vault's `ask` with \
kind `key` and belongsTo `[\"<the web address of the provider's endpoint, \
such as https://api.example.com>\"]`: your person types it into a protected \
field, and you are told the `reference` the workspace's vault keeps it under. Pass that \
reference as `key`. The item must be a key that belongs to the provider's \
endpoint, and it is kept for no other. {ASKED_FIRST}"
),
vec![
ActionParam::required(
"provider",
ParamType::Text,
"The provider's id, as your person's model providers list it.",
),
item_param("key", REFERENCE),
ActionParam::optional("reason", ParamType::Text, REASON),
],
),
]
}
#[must_use]
pub fn use_of(target: &RemoteActionTarget) -> Option<crate::ActionDescriptor> {
if *target == page_target() {
return page_use();
}
use_rows().into_iter().find_map(|row| {
let action = row.action?;
(row.provider == target.provider && action.address == target.address).then_some(action)
})
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct FillPage {
pub site: String,
pub item: ItemRef,
#[serde(default, skip_serializing_if = "String::is_empty")]
pub reason: String,
}
#[must_use]
pub fn page_target() -> RemoteActionTarget {
RemoteActionTarget {
provider: PROVIDER.to_owned(),
address: ActionAddress::new(RESOURCE, FILL_PAGE),
}
}
#[must_use]
pub fn page_use() -> Option<crate::ActionDescriptor> {
use crate::{ActionParam, ParamType};
use_row(
(PROVIDER, RESOURCE, "Vault"),
(FILL_PAGE, "Fill page field from vault"),
format!(
"Fill a field of a web page from an item your person's vault keeps for that page's \
site: a login's password, a code generator's code of this moment, or a kept \
value. You never hold what the item keeps. {ASKED_FIRST}"
),
vec![
ActionParam::required(
"site",
ParamType::Text,
"The site the page is at, as its window's engine names it.",
),
item_param("item", REFERENCE),
ActionParam::optional("reason", ParamType::Text, REASON),
],
)
.action
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct FillField {
pub element: String,
pub item: ItemRef,
#[serde(default, skip_serializing_if = "String::is_empty")]
pub reason: String,
}
#[must_use]
pub fn fill_row() -> CatalogueRow {
use crate::{ActionParam, ParamType};
use_row(
(PROVIDER, RESOURCE, "Vault"),
(FILL_PAGE, "Fill page field from vault"),
format!(
"Fill a field of the page in this workspace's Browser window from an item your \
person's vault keeps for that page's site: a login's password, a code generator's \
code of this moment, or a kept value. You name the field as the page's outline \
names it and the item by its reference, and you never hold what the item keeps. \
{ASKED_FIRST}"
),
vec![
ActionParam::required(
"element",
ParamType::Text,
"The field, by its reference in the page's outline.",
),
item_param("item", REFERENCE),
ActionParam::optional("reason", ParamType::Text, REASON),
],
)
}
#[must_use]
pub fn use_word(target: &RemoteActionTarget) -> String {
format!("{}/{}", target.provider, target.address.action)
}
pub const WEB_CALL: &str = "web-call";
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct ContentRef {
#[serde(default, skip_serializing_if = "String::is_empty")]
pub app: String,
pub hash: String,
#[serde(default, skip_serializing_if = "String::is_empty")]
pub filename: String,
#[serde(default, skip_serializing_if = "String::is_empty")]
pub content_type: String,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct WebCallPart {
pub name: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub text: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub json: Option<serde_json::Value>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub content: Option<ContentRef>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct WebCall {
pub url: String,
#[serde(default, skip_serializing_if = "String::is_empty")]
pub method: String,
#[serde(default, skip_serializing_if = "std::collections::BTreeMap::is_empty")]
pub headers: std::collections::BTreeMap<String, String>,
#[serde(default, skip_serializing_if = "String::is_empty")]
pub body: String,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub body_parts: Vec<WebCallPart>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub body_content: Option<ContentRef>,
pub key: ItemRef,
#[serde(default, skip_serializing_if = "String::is_empty")]
pub reason: String,
}
#[must_use]
pub fn call_target() -> RemoteActionTarget {
target(WEB_CALL)
}
#[must_use]
pub fn is_web_call(target: &RemoteActionTarget) -> bool {
*target == call_target()
}
#[must_use]
pub fn call_rows() -> Vec<CatalogueRow> {
use crate::{ActionParam, ParamType};
vec![use_row(
(PROVIDER, RESOURCE, "Vault"),
(WEB_CALL, "Call a service with a key from the vault"),
format!(
"Make a web request to a service that takes a key, with a key your person's vault \
keeps: for a service that has no connection of its own. The server adds the key \
on the way out, where the item says its service takes it (as a bearer token \
unless it says otherwise), and only to the service the item belongs to: `url` \
must be at that service's web address, over https. You never hold the key, and \
it is struck from what you are answered: the status, the headers and the body. \
What it sends is `body` text, `bodyParts` (an inline `text` or `json` part, or a \
`content` part naming content your workspace keeps by its BLAKE3 hex address, with \
its filename and content type), or `bodyContent`, one content reference sent as the \
whole body. The server reads that content from the workspace's store: its bytes \
never pass through you, and you may name only content the workspace keeps. \
To get the key, call the vault's `ask` with kind `key`, belongsTo `[\"<the \
service's web address, such as https://api.example.com>\"]` and `sentIn`, which \
says how the service takes its key when not as a bearer token: `basic`, \
`header:<name>` such as `header:X-Api-Key`, or `query:<name>`. Your person types \
it into a protected field, and you are told the `reference` the workspace's vault keeps it \
under. Pass that reference as `key`. {CALL_ASKED_FIRST}"
),
vec![
ActionParam::required("url", ParamType::Text, "The address to call."),
ActionParam::optional(
"method",
ParamType::Text,
"GET, HEAD, POST, PUT, PATCH or DELETE; when left out, POST if it sends a body and GET if not.",
),
ActionParam::optional(
"headers",
ParamType::Object,
"Headers to send besides the key, by name. Not the one the key rides in, and \
none that signs the request in.",
),
ActionParam::optional(
"body",
ParamType::Text,
"What to send, as text. Not beside `bodyParts` or `bodyContent`.",
),
ActionParam::optional(
"bodyParts",
ParamType::Array,
"What to send, as the parts of a multipart body: each names its field and holds \
`text`, `json`, or `content`, content the workspace keeps by its BLAKE3 hex \
address with a `filename` and `contentType`. The vault reads the bytes from the \
workspace's store, so they never pass through you.",
),
ActionParam::optional(
"bodyContent",
ParamType::Object,
"Content the workspace keeps, by its BLAKE3 hex address with a `filename` and \
`contentType`, sent as the whole body.",
),
item_param("key", REFERENCE),
ActionParam::optional("reason", ParamType::Text, REASON),
],
)]
}
pub const RELEASE: &str = "release";
#[must_use]
pub fn release_target(item: &ItemRef) -> RemoteActionTarget {
RemoteActionTarget {
provider: PROVIDER.to_owned(),
address: ActionAddress::new(item.to_string(), RELEASE),
}
}
#[must_use]
pub fn is_release(target: &RemoteActionTarget) -> bool {
target.provider == PROVIDER && target.address.action == RELEASE
}
#[must_use]
pub fn released_item(target: &RemoteActionTarget) -> Option<ItemRef> {
is_release(target)
.then(|| ItemRef::parse(&target.address.resource))
.flatten()
}
#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct Released {
pub secret: String,
}
impl std::fmt::Debug for Released {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
formatter.debug_struct("Released").finish_non_exhaustive()
}
}
#[must_use]
pub fn app_tag(app: &str) -> String {
format!("app:{app}")
}
#[must_use]
pub fn purpose_tag(purpose: &str) -> String {
format!("purpose:{purpose}")
}
#[must_use]
pub fn item_tag(item: &str) -> String {
format!("item:{item}")
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct FindItem {
pub app: String,
pub purpose: String,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct Found {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub reference: Option<ItemRef>,
}
#[must_use]
pub fn is_find(target: &RemoteActionTarget) -> bool {
target.provider == PROVIDER && target.address.action == FIND
}
pub const KEEP: &str = "keep";
#[must_use]
pub fn keep_target() -> RemoteActionTarget {
target(KEEP)
}
#[must_use]
pub fn is_keep(target: &RemoteActionTarget) -> bool {
*target == keep_target()
}
#[must_use]
pub fn keep_params() -> Vec<crate::ActionParam> {
use crate::{ActionParam, ParamType};
vec![
ActionParam::required(
"purpose",
ParamType::Text,
"What the app keeps it for, such as `oauth-token`: the app finds it again by this.",
),
ActionParam::required(
"value",
ParamType::Secret,
"The secret: sealed in the workspace's vault, released back only to the app's own \
process.",
),
ActionParam::optional(
"replacing",
ParamType::Resource,
"The app's own item whose secret this renews, by its reference; left out, the item \
the app keeps for the purpose is renewed, or a new one kept.",
)
.of_resource_kind(ITEM_KIND),
]
}
#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct KeepValue {
pub purpose: String,
pub value: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub replacing: Option<ItemRef>,
}
impl std::fmt::Debug for KeepValue {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
formatter
.debug_struct("KeepValue")
.field("purpose", &self.purpose)
.field("replacing", &self.replacing)
.finish_non_exhaustive()
}
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct Kept {
pub reference: ItemRef,
}
pub const DEVICE_KEY: &str = "device-key";
#[must_use]
pub fn device_key_target() -> RemoteActionTarget {
target(DEVICE_KEY)
}
#[must_use]
pub fn is_device_key(target: &RemoteActionTarget) -> bool {
*target == device_key_target()
}
#[must_use]
pub fn device_key_params() -> Vec<crate::ActionParam> {
use crate::{ActionParam, ParamType};
vec![ActionParam::required(
"purpose",
ParamType::Text,
"What the app uses the key for, such as `grayjay-noise`: the same purpose answers the \
same key on this device.",
)]
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct DeviceKeyFor {
pub purpose: String,
}
#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct DeviceKey {
pub key: String,
}
impl std::fmt::Debug for DeviceKey {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
formatter.debug_struct("DeviceKey").finish_non_exhaustive()
}
}
pub const PAGE_LOGINS: &str = "page-logins";
pub const KEEP_PAGE_LOGIN: &str = "keep-page-login";
pub const FORGET_PAGE_LOGIN: &str = "forget-page-login";
pub const PAGE_FILL: &str = "page-fill";
pub const SIGN_IN: &str = "sign-in";
#[must_use]
pub fn page_fill_target(item: &ItemRef) -> RemoteActionTarget {
RemoteActionTarget {
provider: PROVIDER.to_owned(),
address: ActionAddress::new(item.to_string(), PAGE_FILL),
}
}
#[must_use]
pub fn is_page_login(target: &RemoteActionTarget) -> bool {
target.provider == PROVIDER
&& match target.address.action.as_str() {
PAGE_LOGINS | KEEP_PAGE_LOGIN | FORGET_PAGE_LOGIN => {
target.address.resource == RESOURCE
}
PAGE_FILL => true,
_ => false,
}
}
#[must_use]
pub fn page_filled_item(target: &RemoteActionTarget) -> Option<ItemRef> {
(target.provider == PROVIDER && target.address.action == PAGE_FILL)
.then(|| ItemRef::parse(&target.address.resource))
.flatten()
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct PageLoginsAt {
pub site: String,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct PageLogin {
pub reference: ItemRef,
pub title: String,
pub username: String,
pub belongs_to: Vec<String>,
pub own: bool,
}
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct PageLogins {
pub logins: Vec<PageLogin>,
}
#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct KeepPageLogin {
pub site: String,
pub username: String,
pub secret: String,
pub replacing: Option<ItemRef>,
}
impl std::fmt::Debug for KeepPageLogin {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
formatter
.debug_struct("KeepPageLogin")
.field("site", &self.site)
.field("replacing", &self.replacing)
.finish_non_exhaustive()
}
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct ForgetPageLogin {
pub site: String,
pub item: ItemRef,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct PageFillAt {
pub site: String,
}
#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct PageFilled {
pub username: String,
pub secret: String,
}
impl std::fmt::Debug for PageFilled {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
formatter.debug_struct("PageFilled").finish_non_exhaustive()
}
}
pub const MAX_ASKED_PLACES: usize = 4;
const MAX_ASKED_NAME_BYTES: usize = 320;
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct AskForItem {
pub kind: ItemKind,
pub belongs_to: Vec<String>,
#[serde(default, skip_serializing_if = "String::is_empty")]
pub username: String,
#[serde(default, skip_serializing_if = "String::is_empty")]
pub sent_in: String,
}
impl AskForItem {
pub fn checked(mut self) -> Result<Self, String> {
if self.belongs_to.is_empty() || self.belongs_to.len() > MAX_ASKED_PLACES {
return Err(format!(
"belongsTo: 1 to {MAX_ASKED_PLACES} places, each a web address such as \
https://example.com or a server such as imap://mail.example.com:993"
));
}
for place in &mut self.belongs_to {
*place = place.trim().to_owned();
if !looks_like_place(place) {
return Err(
"belongsTo: each place is a web address such as https://example.com or a \
server such as imap://mail.example.com:993 or ssh://git.example.com"
.to_owned(),
);
}
}
self.username = self.username.trim().to_owned();
self.sent_in = self.sent_in.trim().to_owned();
for (name, said) in [("username", &self.username), ("sentIn", &self.sent_in)] {
if said.len() > MAX_ASKED_NAME_BYTES || said.chars().any(char::is_control) {
return Err(format!("{name}: a few words on one line"));
}
}
if !self.sent_in.is_empty() && self.kind != ItemKind::Key {
return Err("sentIn: only a key says how it is sent".to_owned());
}
Ok(self)
}
#[must_use]
pub fn words(&self, agent: &str) -> String {
let what = match self.kind {
ItemKind::Login => "the password",
ItemKind::Key => "the key",
ItemKind::CodeGenerator => "the setup key of the code generator",
ItemKind::SshKey => "the ssh key",
ItemKind::Value => "the value",
ItemKind::Note => "the note",
ItemKind::Wifi => "the Wi-Fi password",
};
let places = self.belongs_to.join(" and ");
let of = if self.username.is_empty() {
String::new()
} else {
format!(" of {}", self.username)
};
let alone = if self.belongs_to.len() == 1 {
"that place alone"
} else {
"those places alone"
};
format!(
"{agent} asks for {what}{of} at {places}. {agent} never sees what you type: your \
vault keeps it for {alone}."
)
}
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct Asked {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub reference: Option<ItemRef>,
}
#[must_use]
pub fn ask_target() -> RemoteActionTarget {
target(ASK)
}
#[must_use]
pub fn ask_row() -> CatalogueRow {
use crate::{ActionParam, ParamType};
use_row(
(PROVIDER, RESOURCE, "Vault"),
(ASK, "Ask your person for a secret"),
"Ask your person for a password, a key or another secret. This is the one way to get \
one: never ask for one in the conversation, where everyone in it and you read what \
they write. Your person types it into the system's protected field on their own device, \
in words the system writes; you never see it. The workspace's vault keeps it for the places in \
`belongsTo` alone: a site as `https://example.com`, a server as \
`imap://mail.example.com:993` or `ssh://git.example.com`. You are told the \
`reference` it is kept under (`vault.item:…`), or that they declined: pass the \
reference where an action takes the secret. Where nobody watches, the call ends at \
once and you are told in your conversation with them; do not make it again."
.to_owned(),
vec![
ActionParam::required(
"kind",
ParamType::Text,
"What it is: `login` (a password), `key`, `code-generator`, `ssh-key` or `value`.",
),
ActionParam::required(
"belongsTo",
ParamType::Array,
"Where it belongs: each a web address or a server, at most four.",
),
ActionParam::optional(
"username",
ParamType::Text,
"The name it signs in with, when you know it.",
),
ActionParam::optional(
"sentIn",
ParamType::Text,
"For a key: how its service takes it when not as a bearer token: `basic`, \
`header:<name>` or `query:<name>`.",
),
],
)
}
const CALL_ASKED_FIRST: &str = "When you work with nobody watching, your person is asked first \
in the conversation whether you may make this call, and nothing is sent: tell them it \
waits for their answer. Once they allowed it, make the same call again with the same \
arguments: it is sent once. Each call is asked about anew.";
#[must_use]
pub fn described_use(target: &RemoteActionTarget) -> Option<crate::ActionDescriptor> {
use_of(target).or_else(|| {
call_rows().into_iter().find_map(|row| {
let action = row.action?;
(row.provider == target.provider && action.address == target.address).then_some(action)
})
})
}
#[cfg(test)]
mod call_tests {
use super::*;
#[test]
fn a_web_call_takes_its_key_by_reference_and_is_listed_apart() {
let rows = call_rows();
assert_eq!(rows.len(), 1);
let target = call_target();
assert_eq!(use_word(&target), "tilo.vault/web-call");
let action = rows[0].action.clone().expect("the row is an action");
assert_eq!(rows[0].provider, PROVIDER);
assert_eq!(action.address, target.address);
assert_eq!(action.contract.kind, crate::ActionKind::Outside);
assert_eq!(
action
.params
.iter()
.filter(|param| takes_item(param))
.count(),
1
);
assert!(
action
.params
.iter()
.all(|param| param.ty != crate::ParamType::Secret),
"no parameter takes a secret's text"
);
let described = action.description.unwrap_or_default();
for said in [
"vault's `ask`",
"sentIn",
"`reference`",
"asked first",
"struck",
] {
assert!(described.contains(said), "{said}: {described}");
}
assert_eq!(
described_use(&target).map(|found| found.address),
Some(target.address.clone())
);
assert!(use_of(&target).is_none(), "no Always stands for a call");
assert!(
use_rows()
.iter()
.all(|row| described_use(&RemoteActionTarget {
provider: row.provider.clone(),
address: row.action.as_ref().unwrap().address.clone(),
})
.is_some()),
"the uses are described as before"
);
assert!(described_use(&super::target(LIST)).is_none());
}
#[test]
fn a_calls_arguments_are_typed() {
let reference = format!("vault.item:{}", "0".repeat(32));
let call: WebCall = serde_json::from_value(serde_json::json!({
"url": "https://api.example.test/v1/balance",
"key": reference,
}))
.unwrap();
assert!(call.method.is_empty() && call.headers.is_empty() && call.body.is_empty());
let whole: WebCall = serde_json::from_value(serde_json::json!({
"url": "https://api.example.test/v1/notes",
"method": "POST",
"headers": {"Content-Type": "application/json"},
"body": "{}",
"key": reference,
"reason": "To file the note.",
}))
.unwrap();
assert_eq!(whole.headers["Content-Type"], "application/json");
let parts: WebCall = serde_json::from_value(serde_json::json!({
"url": "https://api.example.test/v1/upload",
"method": "POST",
"bodyParts": [
{"name": "payload_json", "json": {"content": "hi"}},
{"name": "files[0]", "content": {
"app": "so.tilo.chat",
"hash": "ab".repeat(32),
"filename": "a.png",
"contentType": "image/png",
}},
{"name": "note", "text": "one line"},
],
"key": reference,
}))
.unwrap();
assert_eq!(parts.body_parts.len(), 3);
assert_eq!(
parts.body_parts[0].json,
Some(serde_json::json!({"content": "hi"}))
);
let content = parts.body_parts[1].content.clone().unwrap();
assert_eq!(content.app, "so.tilo.chat");
assert_eq!(content.filename, "a.png");
assert_eq!(content.content_type, "image/png");
let raw: WebCall = serde_json::from_value(serde_json::json!({
"url": "https://api.example.test/v1/upload",
"method": "PUT",
"bodyContent": {"hash": "ab".repeat(32), "contentType": "image/png"},
"key": reference,
}))
.unwrap();
assert_eq!(raw.body_content.unwrap().hash, "ab".repeat(32));
for wrong in [
serde_json::json!({"url": "https://api.example.test", "key": "a key typed out"}),
serde_json::json!({"url": "https://api.example.test", "key": reference, "secret": "x"}),
serde_json::json!({"key": reference}),
serde_json::json!({"url": "https://api.example.test", "key": reference,
"bodyParts": [{"name": "x", "text": "t", "other": 1}]}),
] {
assert!(serde_json::from_value::<WebCall>(wrong).is_err());
}
let adding: AddItem = serde_json::from_value(serde_json::json!({
"kind": "key",
"belongsTo": ["https://api.example.test"],
"sentIn": "header:X-Api-Key",
"secret": "made-up-key-0123456789",
}))
.unwrap();
assert_eq!(adding.sent_in, "header:X-Api-Key");
assert!(!format!("{adding:?}").contains("made-up-key"));
}
}
#[cfg(test)]
mod tests {
#![allow(
clippy::unwrap_used,
clippy::panic,
reason = "in a test these are the assertion, not a hazard"
)]
use super::*;
const ID: &str = "0123456789abcdef0123456789abcdef";
#[test]
fn an_ask_for_a_secret_is_checked_and_worded_by_the_system() {
let ask: AskForItem = serde_json::from_value(serde_json::json!({
"kind": "login",
"belongsTo": [" https://example.com "],
"username": "ada",
}))
.unwrap();
let ask = ask.checked().unwrap();
assert_eq!(
ask.words("Scout"),
"Scout asks for the password of ada at https://example.com. Scout never sees what \
you type: your vault keeps it for that place alone."
);
for wrong in [
serde_json::json!({"kind": "login", "belongsTo": []}),
serde_json::json!({"kind": "login", "belongsTo": ["my bank"]}),
serde_json::json!({"kind": "login", "belongsTo": ["https://a.example"], "sentIn": "basic"}),
] {
let ask: AskForItem = serde_json::from_value(wrong).unwrap();
assert!(ask.checked().is_err());
}
assert!(
serde_json::from_value::<AskForItem>(serde_json::json!({
"kind": "login",
"belongsTo": ["https://example.com"],
"secret": "hunter2",
}))
.is_err(),
"an ask carries no secret"
);
let row = ask_row();
let action = row.action.unwrap();
assert_eq!(action.address.action, ASK);
assert!(
action
.params
.iter()
.all(|param| param.ty != crate::ParamType::Secret && !takes_item(param)),
"an ask takes no secret and no reference"
);
}
#[test]
fn a_place_is_checked_before_a_person_is_asked() {
for place in [
"https://example.com/login",
"HTTP://example.com",
"imap://mail.example.com:993",
"smtp://mail.example.com:465",
"ssh://git.example.com",
] {
assert!(looks_like_place(place), "{place}");
}
for other in [
"",
"example.com",
"my bank",
"ftp://example.com",
"https://",
"https://exa mple.com",
] {
assert!(!looks_like_place(other), "{other:?}");
}
}
#[test]
fn a_use_by_reference_takes_no_secret_and_says_how_to_ask() {
let rows = use_rows();
assert_eq!(rows.len(), 2);
for row in &rows {
let action = row.action.as_ref().unwrap();
assert_eq!(
action
.params
.iter()
.filter(|param| takes_item(param))
.count(),
1,
"{}",
action.address.action
);
assert!(
!action
.params
.iter()
.any(|param| param.ty == crate::ParamType::Secret)
);
assert_eq!(action.contract.kind, crate::ActionKind::Outside);
let description = action.description.as_deref().unwrap();
for said in ["vault's `ask`", "`reference`", "asked first", "Always"] {
assert!(description.contains(said), "{said}: {description}");
}
let target = RemoteActionTarget {
provider: row.provider.clone(),
address: action.address.clone(),
};
assert_eq!(
use_of(&target).map(|found| found.address),
Some(action.address.clone())
);
assert_eq!(
use_word(&target),
format!("{}/{}", row.provider, action.address.action)
);
}
assert!(use_of(&target(LIST)).is_none());
assert!(use_of(&person_accounts::target(person_accounts::ADD_MAIL)).is_none());
assert!(use_of(&model_providers::target(model_providers::SET_KEY)).is_none());
let mail = use_of(&person_accounts::target(
person_accounts::ADD_MAIL_WITH_ITEM,
))
.unwrap();
let arguments = serde_json::json!({
"address": "ada@example.test",
"incomingHost": "imap.example.test",
"outgoingHost": "smtp.example.test",
"password": format!("vault.item:{ID}"),
});
let draft = crate::Draft::render(&mail, arguments.as_object().unwrap());
let shown = serde_json::to_string(&draft).unwrap();
assert!(!shown.contains(ID), "{shown}");
assert!(shown.contains("ada@example.test"), "{shown}");
}
#[test]
fn leaves_are_listed_beside_the_uses() {
let none: ItemUses = serde_json::from_value(serde_json::json!({"uses": []})).unwrap();
assert!(none.always.is_empty());
assert_eq!(
serde_json::to_value(&none).unwrap(),
serde_json::json!({"uses": []})
);
let leave = AlwaysUse {
agent: "scout".into(),
app: String::new(),
by: "Scout".into(),
using: "tilo.accounts/add-mail-with-item".into(),
places: vec!["imap://mail.example.test:993".into()],
since: 7,
};
let some = ItemUses {
uses: Vec::new(),
always: vec![leave],
};
let said = serde_json::to_value(&some).unwrap();
assert_eq!(said["always"][0]["agent"], "scout");
assert_eq!(said["always"][0]["since"], 7);
assert!(
said["always"][0].get("app").is_none(),
"an agent's leave names no app"
);
assert_eq!(serde_json::from_value::<ItemUses>(said).unwrap(), some);
let back: TakeBack =
serde_json::from_value(serde_json::json!({"item": format!("vault.item:{ID}")}))
.unwrap();
assert_eq!(back.agent, None);
}
#[test]
fn a_use_says_what_it_was_for_where_that_is_known() {
let plain: ItemUse = serde_json::from_value(serde_json::json!({
"at": 7,
"places": ["https://api.example.test"],
}))
.unwrap();
assert!(plain.using.is_empty() && plain.what.is_empty() && plain.allowed.is_empty());
assert_eq!(
serde_json::to_value(&plain).unwrap(),
serde_json::json!({"at": 7, "places": ["https://api.example.test"]})
);
let call = ItemUse {
at: 8,
places: vec!["https://api.example.test".into()],
by: "Scout".into(),
using: "tilo.vault/web-call".into(),
what: "GET /v1/balance".into(),
allowed: "once".into(),
};
let said = serde_json::to_value(&call).unwrap();
assert_eq!(said["using"], "tilo.vault/web-call");
assert_eq!(said["what"], "GET /v1/balance");
assert_eq!(said["allowed"], "once");
assert_eq!(serde_json::from_value::<ItemUse>(said).unwrap(), call);
}
#[test]
fn a_reference_is_an_items_address() {
let reference = ItemRef::from_id(ID).unwrap();
assert_eq!(reference.to_string(), format!("vault.item:{ID}"));
assert_eq!(
ItemRef::parse(&reference.to_string()),
Some(reference.clone())
);
assert_eq!(reference.id(), ID);
let json = serde_json::to_value(&reference).unwrap();
assert_eq!(json, serde_json::json!(format!("vault.item:{ID}")));
assert_eq!(serde_json::from_value::<ItemRef>(json).unwrap(), reference);
for other in [
String::new(),
ID.to_owned(),
format!("vault.item:{}", ID.to_uppercase()),
format!("vault.item:{ID}0"),
format!("vault.item:{}", ID.get(1..).unwrap()),
format!("vault.items:{ID}"),
format!("vault.item:{ID}/secret"),
"vault.item:../../people".to_owned(),
] {
assert_eq!(ItemRef::parse(&other), None, "{other}");
assert!(
serde_json::from_value::<ItemRef>(serde_json::json!(other)).is_err(),
"{other}"
);
}
}
#[test]
fn a_parameter_takes_a_secret_by_reference() {
let param = item_param("password", "The account's password, by reference");
assert!(takes_item(¶m));
assert_eq!(param.ty, crate::ParamType::Resource);
let typed = crate::ActionParam::required("password", crate::ParamType::Secret, "typed");
assert!(!takes_item(&typed));
let other = crate::ActionParam::required("folder", crate::ParamType::Resource, "a folder")
.of_resource_kind("files.entry");
assert!(!takes_item(&other));
let params = [param];
let named = serde_json::json!({"password": format!("vault.item:{ID}")});
let bound = crate::ActionArgs::bind_json(¶ms, named.as_object().unwrap()).unwrap();
assert_eq!(ItemRef::bound(&bound, "password"), ItemRef::from_id(ID));
assert_eq!(ItemRef::bound(&bound, "username"), None);
let typed = serde_json::json!({"password": "hunter2"});
let bound = crate::ActionArgs::bind_json(¶ms, typed.as_object().unwrap());
assert!(!bound.is_ok_and(|bound| ItemRef::bound(&bound, "password").is_some()));
}
#[test]
fn nothing_read_back_carries_a_secret() {
let adding: AddItem = serde_json::from_value(serde_json::json!({
"kind": "login",
"belongsTo": ["https://example.com"],
"username": "ada@example.test",
"secret": "hunter2",
}))
.unwrap();
let printed = format!("{adding:?}");
assert!(
!printed.contains("hunter2") && !printed.contains("ada@"),
"{printed}"
);
let view = ItemView {
reference: ItemRef::from_id(ID).unwrap(),
kind: ItemKind::CodeGenerator,
belongs_to: vec!["https://example.com".into()],
title: Some("Example".into()),
added_at: 1_800_000_000,
last_used_at: Some(1_800_000_100),
algorithm: None,
digits: None,
period: None,
tags: Vec::new(),
fields: Vec::new(),
has_notes: false,
changed_at: 1_800_000_000,
concerns: Vec::new(),
};
let json = serde_json::to_value(KeptItems { items: vec![view] }).unwrap();
let mut fields: Vec<&str> = json["items"][0]
.as_object()
.unwrap()
.keys()
.map(String::as_str)
.collect();
fields.sort_unstable();
assert_eq!(
fields,
[
"addedAt",
"belongsTo",
"changedAt",
"kind",
"lastUsedAt",
"reference",
"title"
]
);
assert_eq!(json["items"][0]["kind"], "code-generator");
assert!(
serde_json::from_value::<ItemView>(serde_json::json!({
"reference": format!("vault.item:{ID}"),
"kind": "login",
"belongsTo": [],
"addedAt": 0,
"secret": "hunter2",
}))
.is_err()
);
}
#[test]
fn filling_a_page_is_a_use_no_catalogue_offers() {
let target = page_target();
assert_eq!(use_word(&target), "tilo.vault/fill-page");
let shown = use_of(&target).expect("a person is shown what it is");
assert_eq!(shown.address, target.address);
assert!(shown.params.iter().any(takes_item));
assert!(
use_rows()
.iter()
.all(|row| row.action.as_ref().map(|action| &action.address)
!= Some(&target.address)),
"no turn is offered it by a listing"
);
let fill: FillPage = serde_json::from_value(serde_json::json!({
"site": "https://example.test",
"item": format!("vault.item:{}", "0".repeat(32)),
}))
.unwrap();
assert_eq!(fill.site, "https://example.test");
assert!(fill.reason.is_empty());
}
#[test]
fn a_turn_names_the_field_and_the_item_and_never_the_site() {
let row = fill_row();
assert_eq!(row.provider, PROVIDER);
let offered = row.action.expect("the row offers the fill");
assert_eq!(offered.address, page_target().address);
assert_eq!(offered.params.len(), 3);
assert!(offered.params.iter().any(takes_item));
let item = format!("vault.item:{}", "0".repeat(32));
let named: FillField =
serde_json::from_value(serde_json::json!({"element": "d1e5", "item": item})).unwrap();
assert_eq!(named.element, "d1e5");
assert!(named.reason.is_empty());
assert!(
serde_json::from_value::<FillField>(serde_json::json!({
"element": "d1e5",
"item": item,
"site": "https://example.test",
}))
.is_err(),
"a turn that names a site is not read"
);
}
}