use zeroize::Zeroize;
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum ItemKind {
Note,
Login,
Card,
SshKey,
Wifi,
ApiToken,
Bank,
File,
Unknown(String),
}
impl ItemKind {
pub fn as_str(&self) -> &str {
match self {
Self::Note => "note",
Self::Login => "login",
Self::Card => "card",
Self::SshKey => "ssh-key",
Self::Wifi => "wifi",
Self::ApiToken => "api-token",
Self::Bank => "bank",
Self::File => "file",
Self::Unknown(name) => name,
}
}
pub fn parse(value: &str) -> Self {
match value {
"note" => Self::Note,
"login" | LEGACY_LOGIN_NAME => Self::Login,
"card" => Self::Card,
"ssh-key" => Self::SshKey,
"wifi" => Self::Wifi,
"api-token" => Self::ApiToken,
"bank" => Self::Bank,
"file" => Self::File,
other => Self::Unknown(other.to_owned()),
}
}
pub fn is_known(&self) -> bool {
!matches!(self, Self::Unknown(_))
}
pub fn template(&self) -> Option<&'static Template> {
TEMPLATES.iter().find(|template| &template.kind == self)
}
pub fn is_record(&self) -> bool {
self.template().is_some()
}
pub fn known() -> [Self; 8] {
[
Self::Note,
Self::Login,
Self::Card,
Self::SshKey,
Self::Wifi,
Self::ApiToken,
Self::Bank,
Self::File,
]
}
}
pub const LEGACY_LOGIN_NAME: &str = "credential";
impl std::fmt::Display for ItemKind {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(self.as_str())
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Template {
pub kind: ItemKind,
pub fields: &'static [FieldSpec],
}
impl Template {
pub fn field(&self, name: &str) -> Option<&FieldSpec> {
self.fields.iter().find(|field| field.name == name)
}
pub fn default_field(&self) -> Option<&FieldSpec> {
self.fields.iter().find(|field| field.secret)
}
pub fn fill_order(&self) -> impl Iterator<Item = &FieldSpec> {
self.fields.iter().filter(|field| field.fill)
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FieldSpec {
pub name: &'static str,
pub description: &'static str,
pub secret: bool,
pub fill: bool,
pub audit: AuditAs,
}
impl FieldSpec {
const fn new(
name: &'static str,
description: &'static str,
secret: bool,
fill: bool,
audit: AuditAs,
) -> Self {
Self {
name,
description,
secret,
fill,
audit,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AuditAs {
Password,
Unique,
Nothing,
}
impl AuditAs {
pub fn of(kind: &ItemKind, field: &Field) -> Self {
if let Some(spec) = kind
.template()
.and_then(|template| template.field(&field.name))
{
return spec.audit;
}
if !field.secret {
return Self::Nothing;
}
TEMPLATES
.iter()
.find_map(|template| template.field(&field.name))
.map_or(Self::Nothing, |spec| spec.audit)
}
}
pub fn normalize_value(name: &str, value: &str) -> crate::Result<String> {
match name {
crate::otp::FIELD => crate::otp::normalize(value),
crate::expiry::FIELD => crate::expiry::normalize(value),
_ => Ok(value.to_owned()),
}
}
const PUBLIC: bool = false;
const SECRET: bool = true;
const FILL: bool = true;
const KEEP: bool = false;
const CHOSEN: AuditAs = AuditAs::Password;
const ISSUED: AuditAs = AuditAs::Unique;
const UNCHECKED: AuditAs = AuditAs::Nothing;
static TEMPLATES: &[Template] = &[
Template {
kind: ItemKind::Login,
fields: &[
FieldSpec::new(
"login",
"username, email, or whatever the service calls it",
PUBLIC,
FILL,
UNCHECKED,
),
FieldSpec::new("password", "the secret itself", SECRET, FILL, CHOSEN),
FieldSpec::new("url", "where the account lives", PUBLIC, KEEP, UNCHECKED),
FieldSpec::new(
crate::otp::FIELD,
"key for one-time passwords",
SECRET,
FILL,
ISSUED,
),
FieldSpec::new(
"notes",
"anything else worth remembering",
PUBLIC,
KEEP,
UNCHECKED,
),
],
},
Template {
kind: ItemKind::Card,
fields: &[
FieldSpec::new("number", "the card number", SECRET, FILL, ISSUED),
FieldSpec::new(
"holder",
"name embossed on the card",
PUBLIC,
FILL,
UNCHECKED,
),
FieldSpec::new(
crate::expiry::FIELD,
"the month it runs out, as printed: 03/29",
PUBLIC,
FILL,
UNCHECKED,
),
FieldSpec::new(
"cvv",
"verification code on the back",
SECRET,
FILL,
UNCHECKED,
),
FieldSpec::new("pin", "the PIN", SECRET, KEEP, UNCHECKED),
FieldSpec::new(
"notes",
"bank, account, anything else",
PUBLIC,
KEEP,
UNCHECKED,
),
],
},
Template {
kind: ItemKind::SshKey,
fields: &[
FieldSpec::new(
"private-key",
"the private key, as it appears in the file",
SECRET,
KEEP,
ISSUED,
),
FieldSpec::new(
"passphrase",
"passphrase protecting the private key",
SECRET,
FILL,
CHOSEN,
),
FieldSpec::new("public-key", "the public key", PUBLIC, KEEP, UNCHECKED),
FieldSpec::new("host", "where the key is used", PUBLIC, KEEP, UNCHECKED),
FieldSpec::new(
"notes",
"anything else worth remembering",
PUBLIC,
KEEP,
UNCHECKED,
),
],
},
Template {
kind: ItemKind::Wifi,
fields: &[
FieldSpec::new("ssid", "the network's name", PUBLIC, FILL, UNCHECKED),
FieldSpec::new("password", "the network key", SECRET, FILL, CHOSEN),
FieldSpec::new("security", "WPA2, WPA3, open", PUBLIC, KEEP, UNCHECKED),
FieldSpec::new("notes", "where it is, whose it is", PUBLIC, KEEP, UNCHECKED),
],
},
Template {
kind: ItemKind::ApiToken,
fields: &[
FieldSpec::new("token", "the token itself", SECRET, FILL, ISSUED),
FieldSpec::new(
"url",
"where it is issued and revoked",
PUBLIC,
KEEP,
UNCHECKED,
),
FieldSpec::new(
"scopes",
"what it is allowed to do",
PUBLIC,
KEEP,
UNCHECKED,
),
FieldSpec::new(
crate::expiry::FIELD,
"the last day it works: 2027-01-31",
PUBLIC,
KEEP,
UNCHECKED,
),
FieldSpec::new("notes", "what uses it", PUBLIC, KEEP, UNCHECKED),
],
},
Template {
kind: ItemKind::Bank,
fields: &[
FieldSpec::new("account", "account number or IBAN", SECRET, FILL, ISSUED),
FieldSpec::new(
"holder",
"whose name the account is in",
PUBLIC,
FILL,
UNCHECKED,
),
FieldSpec::new("bank", "the bank", PUBLIC, FILL, UNCHECKED),
FieldSpec::new(
"routing",
"SWIFT/BIC, routing or sort code",
PUBLIC,
FILL,
UNCHECKED,
),
FieldSpec::new(
"notes",
"branch, contact, anything else",
PUBLIC,
KEEP,
UNCHECKED,
),
],
},
];
#[derive(Debug, Clone, PartialEq, Eq, Zeroize)]
pub struct Field {
pub name: String,
pub value: String,
#[zeroize(skip)]
pub secret: bool,
}
impl Field {
pub fn public(name: impl Into<String>, value: impl Into<String>) -> Self {
Self {
name: name.into(),
value: value.into(),
secret: false,
}
}
pub fn secret(name: impl Into<String>, value: impl Into<String>) -> Self {
Self {
name: name.into(),
value: value.into(),
secret: true,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Payload {
Note {
text: String,
},
Fields {
kind: ItemKind,
fields: Vec<Field>,
},
File {
filename: String,
bytes: Vec<u8>,
},
Unknown {
kind: String,
},
}
impl Payload {
pub fn fields(kind: ItemKind, fields: impl IntoIterator<Item = Field>) -> Self {
Self::Fields {
kind,
fields: fields.into_iter().collect(),
}
}
pub fn kind(&self) -> ItemKind {
match self {
Self::Note { .. } => ItemKind::Note,
Self::Fields { kind, .. } => kind.clone(),
Self::File { .. } => ItemKind::File,
Self::Unknown { kind } => ItemKind::Unknown(kind.clone()),
}
}
pub fn field(&self, name: &str) -> Option<&Field> {
match self {
Self::Fields { fields, .. } => fields.iter().find(|field| field.name == name),
_ => None,
}
}
}
impl Zeroize for Payload {
fn zeroize(&mut self) {
match self {
Self::Note { text } => text.zeroize(),
Self::Fields { fields, .. } => fields.zeroize(),
Self::File { filename, bytes } => {
filename.zeroize();
bytes.zeroize();
}
Self::Unknown { .. } => {}
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ItemSummary {
pub id: i64,
pub uuid: String,
pub title: String,
pub kind: ItemKind,
pub tags: Vec<String>,
pub created_at: i64,
pub updated_at: i64,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Item {
pub summary: ItemSummary,
pub payload: Payload,
}
#[derive(Debug, Clone)]
pub struct NewItem {
pub title: String,
pub payload: Payload,
pub tags: Vec<String>,
}
impl NewItem {
pub fn new(title: impl Into<String>, payload: Payload) -> Self {
Self {
title: title.into(),
payload,
tags: Vec::new(),
}
}
pub fn with_tags<I, S>(mut self, tags: I) -> Self
where
I: IntoIterator<Item = S>,
S: Into<String>,
{
self.tags = tags.into_iter().map(Into::into).collect();
self
}
}
#[derive(Debug, Clone, Default)]
pub struct Query {
pub text: Option<String>,
pub kind: Option<ItemKind>,
pub tags: Vec<String>,
}
impl Query {
pub fn all() -> Self {
Self::default()
}
pub fn text(mut self, text: impl Into<String>) -> Self {
self.text = Some(text.into());
self
}
pub fn kind(mut self, kind: ItemKind) -> Self {
self.kind = Some(kind);
self
}
pub fn tags<I, S>(mut self, tags: I) -> Self
where
I: IntoIterator<Item = S>,
S: Into<String>,
{
self.tags = tags.into_iter().map(Into::into).collect();
self
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn kind_names_round_trip() {
for kind in ItemKind::known() {
assert_eq!(ItemKind::parse(kind.as_str()), kind);
}
}
#[test]
fn an_unheard_of_kind_keeps_its_name_instead_of_failing() {
let kind = ItemKind::parse("passport");
assert_eq!(kind, ItemKind::Unknown("passport".to_owned()));
assert_eq!(kind.as_str(), "passport");
assert!(!kind.is_known());
assert_eq!(ItemKind::parse(kind.as_str()), kind);
}
#[test]
fn the_old_name_for_a_login_still_reads() {
assert_eq!(ItemKind::parse(LEGACY_LOGIN_NAME), ItemKind::Login);
assert_eq!(ItemKind::Login.as_str(), "login");
}
#[test]
fn only_field_backed_kinds_have_a_template() {
assert!(ItemKind::Login.template().is_some());
assert!(ItemKind::Card.template().is_some());
assert!(ItemKind::SshKey.template().is_some());
assert!(ItemKind::Wifi.template().is_some());
assert!(ItemKind::ApiToken.template().is_some());
assert!(ItemKind::Bank.template().is_some());
assert!(ItemKind::Note.template().is_none());
assert!(ItemKind::File.template().is_none());
assert!(
ItemKind::Unknown("passport".to_owned())
.template()
.is_none()
);
}
#[test]
fn every_template_names_its_fields_uniquely() {
for template in TEMPLATES {
let mut seen: Vec<&str> = Vec::new();
for field in template.fields {
assert!(
!seen.contains(&field.name),
"{} names {} twice",
template.kind,
field.name
);
seen.push(field.name);
}
}
}
#[test]
fn the_default_field_is_the_first_secret_one() {
assert_eq!(
ItemKind::Login
.template()
.unwrap()
.default_field()
.unwrap()
.name,
"password"
);
assert_eq!(
ItemKind::Card
.template()
.unwrap()
.default_field()
.unwrap()
.name,
"number"
);
assert_eq!(
ItemKind::SshKey
.template()
.unwrap()
.default_field()
.unwrap()
.name,
"private-key"
);
}
#[test]
fn every_kind_but_a_note_and_a_file_is_a_record_with_a_template_row() {
for kind in ItemKind::known() {
let expected = !matches!(kind, ItemKind::Note | ItemKind::File);
assert_eq!(kind.is_record(), expected, "{kind}");
}
for template in TEMPLATES {
assert!(
ItemKind::known().contains(&template.kind),
"{}",
template.kind
);
}
}
#[test]
fn a_one_time_password_key_is_secret_wherever_a_template_has_one() {
for template in TEMPLATES {
if let Some(field) = template.field(crate::otp::FIELD) {
assert!(field.secret, "{} keeps its key in the open", template.kind);
}
}
}
#[test]
fn a_field_name_is_audited_the_same_way_in_every_template() {
for template in TEMPLATES {
for field in template.fields {
for other in TEMPLATES {
if let Some(same) = other.field(field.name) {
assert_eq!(
same.audit, field.audit,
"{} in {} and {}",
field.name, template.kind, other.kind
);
}
}
}
}
}
#[test]
fn only_a_secret_is_ever_audited() {
for template in TEMPLATES {
for field in template.fields {
if !field.secret {
assert_eq!(field.audit, AuditAs::Nothing, "{}", field.name);
}
}
}
}
#[test]
fn a_field_outside_the_template_is_audited_as_its_name_is_elsewhere() {
let bank = ItemKind::Bank;
assert_eq!(
AuditAs::of(&bank, &Field::secret("password", "p")),
AuditAs::Password
);
assert_eq!(
AuditAs::of(&bank, &Field::secret("token", "t")),
AuditAs::Unique
);
assert_eq!(
AuditAs::of(&bank, &Field::public("password", "p")),
AuditAs::Nothing
);
assert_eq!(
AuditAs::of(&bank, &Field::secret("recovery", "r")),
AuditAs::Nothing
);
assert_eq!(
AuditAs::of(&ItemKind::Card, &Field::secret("pin", "1234")),
AuditAs::Nothing
);
}
#[test]
fn a_value_with_a_shape_is_checked_and_stored_in_it() {
assert_eq!(normalize_value("expires", "03/29").unwrap(), "2029-03");
assert!(normalize_value("expires", "soon").is_err());
assert_eq!(normalize_value("notes", " as is ").unwrap(), " as is ");
assert!(normalize_value(crate::otp::FIELD, "not a key!").is_err());
}
#[test]
fn a_login_fills_in_the_order_a_sign_in_form_asks() {
let order: Vec<&str> = ItemKind::Login
.template()
.unwrap()
.fill_order()
.map(|field| field.name)
.collect();
assert_eq!(order, ["login", "password", crate::otp::FIELD]);
}
#[test]
fn a_field_is_looked_up_by_name() {
let payload = Payload::fields(
ItemKind::Login,
[
Field::public("login", "ada"),
Field::secret("password", "s"),
],
);
assert_eq!(payload.field("login").unwrap().value, "ada");
assert!(payload.field("password").unwrap().secret);
assert!(payload.field("url").is_none());
}
}