devices
runner nix smoke / nix label and flake smoke (push) Canceled after 0s

This commit is contained in:
2026-10-15 01:05:01 +00:00
parent 60d2e5d80f
commit 06925e9af8
10 changed files with 495 additions and 44 deletions
+20 -1
View File
@@ -1,7 +1,10 @@
use serde::de::DeserializeOwned;
use serde::Serialize;
use crate::model::{CreateRoutine, CreateTask, RescheduleTask, Routine, Task};
use crate::model::{
CreateEncryptionDevice, CreateRoutine, CreateTask, EncryptionDevice, EncryptionRecipient,
RescheduleTask, Routine, Task,
};
pub struct ApiClient {
base_url: String,
@@ -28,6 +31,22 @@ impl ApiClient {
self.get("/v1/tasks/archived")
}
pub fn list_encryption_devices(&self) -> Result<Vec<EncryptionDevice>, String> {
self.get("/v1/encryption/devices")
}
pub fn list_encryption_recipients(&self) -> Result<Vec<EncryptionRecipient>, String> {
self.get("/v1/encryption/recipients")
}
pub fn create_encryption_device(&self, device: &CreateEncryptionDevice) -> Result<(), String> {
self.send_json("/v1/encryption/devices", device)
}
pub fn revoke_encryption_device(&self, id: i64) -> Result<(), String> {
self.send_empty("POST", &format!("/v1/encryption/devices/{id}/revoke"))
}
pub fn create_task(&self, task: &CreateTask) -> Result<(), String> {
self.send_json("/v1/tasks", task)
}
+112 -16
View File
@@ -3,13 +3,16 @@ use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
use crate::api::ApiClient;
use crate::crypto::Crypto;
use crate::model::{CreateRoutine, CreateTask, Routine, Schedule, Task};
use crate::model::{
CreateEncryptionDevice, CreateRoutine, CreateTask, EncryptionDevice, Routine, Schedule, Task,
};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum View {
Tasks,
Routines,
Archive,
Devices,
}
#[derive(Debug, Clone, Copy)]
@@ -17,6 +20,7 @@ pub enum FormKind {
Task,
Routine,
Reschedule { task_id: i64 },
Device,
}
#[derive(Debug, Clone)]
@@ -55,11 +59,12 @@ pub struct Form {
pub enum PendingActionKind {
Archive,
Delete,
RevokeDevice,
}
#[derive(Debug, Clone)]
pub struct PendingAction {
pub task_id: i64,
pub item_id: i64,
pub title: String,
pub kind: PendingActionKind,
}
@@ -72,6 +77,7 @@ pub struct App {
pub tasks: Vec<Task>,
pub archived_tasks: Vec<Task>,
pub routines: Vec<Routine>,
pub devices: Vec<EncryptionDevice>,
pub selected: usize,
pub status: String,
pub form: Option<Form>,
@@ -89,6 +95,7 @@ impl App {
tasks: Vec::new(),
archived_tasks: Vec::new(),
routines: Vec::new(),
devices: Vec::new(),
selected: 0,
status: "connecting…".to_owned(),
form: None,
@@ -120,6 +127,9 @@ impl App {
.for_each(|task| self.crypto.decrypt_task(task));
self.archived_tasks = tasks;
}),
View::Devices => self.api.list_encryption_devices().map(|devices| {
self.devices = devices;
}),
};
self.selected = self.selected.min(self.item_count().saturating_sub(1));
self.status = match result {
@@ -143,6 +153,7 @@ impl App {
View::Tasks => self.tasks.len(),
View::Routines => self.routines.len(),
View::Archive => self.archived_tasks.len(),
View::Devices => self.devices.len(),
}
}
@@ -155,7 +166,8 @@ impl App {
self.view = match self.view {
View::Tasks => View::Routines,
View::Routines => View::Archive,
View::Archive => View::Tasks,
View::Archive => View::Devices,
View::Devices => View::Tasks,
};
self.selected = 0;
self.refresh();
@@ -172,6 +184,7 @@ impl App {
KeyCode::Char('x') if self.view == View::Tasks => self.ask_archive_selected(),
KeyCode::Char('x') if self.view == View::Archive => self.ask_delete_selected(),
KeyCode::Char('u') if self.view == View::Archive => self.restore_selected(),
KeyCode::Char('x') if self.view == View::Devices => self.ask_revoke_device(),
KeyCode::Char('s') if self.view == View::Tasks => self.open_reschedule_form(),
_ => {}
}
@@ -183,11 +196,15 @@ impl App {
let pending = self.pending_action.take().expect("task action is pending");
let (result, success) = match pending.kind {
PendingActionKind::Archive => {
(self.api.archive_task(pending.task_id), "archived")
(self.api.archive_task(pending.item_id), "archived")
}
PendingActionKind::Delete => {
(self.api.delete_task(pending.task_id), "deleted permanently")
(self.api.delete_task(pending.item_id), "deleted permanently")
}
PendingActionKind::RevokeDevice => (
self.api.revoke_encryption_device(pending.item_id),
"device revoked for future encryption",
),
};
self.finish_action(result, success);
}
@@ -243,6 +260,7 @@ impl App {
FormKind::Reschedule { task_id } => {
self.api.reschedule_task(task_id, form.fields[0].display())
}
FormKind::Device => self.submit_device(&form),
};
match result {
Ok(()) => {
@@ -257,10 +275,12 @@ impl App {
}
fn submit_task(&self, form: &Form) -> Result<(), String> {
let encrypted = self.crypto.encrypt_optional(
optional(form.fields[1].display()),
optional(form.fields[2].display()),
)?;
let private_title = optional(form.fields[1].display());
let notes = optional(form.fields[2].display());
let recipients = self.recipients_for(&private_title, &notes)?;
let encrypted = self
.crypto
.encrypt_optional(private_title, notes, &recipients)?;
self.api.create_task(&CreateTask {
public_title: required(form.fields[0].display(), "public title")?,
encrypted_payload: encrypted.encrypted_payload,
@@ -274,10 +294,12 @@ impl App {
}
fn submit_routine(&self, form: &Form) -> Result<(), String> {
let encrypted = self.crypto.encrypt_optional(
optional(form.fields[1].display()),
optional(form.fields[2].display()),
)?;
let private_title = optional(form.fields[1].display());
let notes = optional(form.fields[2].display());
let recipients = self.recipients_for(&private_title, &notes)?;
let encrypted = self
.crypto
.encrypt_optional(private_title, notes, &recipients)?;
let schedule = parse_schedule(form.fields[5].display(), form.fields[6].display())?;
self.api.create_routine(&CreateRoutine {
public_title: required(form.fields[0].display(), "public title")?,
@@ -291,11 +313,35 @@ impl App {
})
}
fn submit_device(&self, form: &Form) -> Result<(), String> {
self.api.create_encryption_device(&CreateEncryptionDevice {
name: required(form.fields[0].display(), "device name")?,
age_recipient: required(form.fields[1].display(), "age recipient")?,
})
}
fn recipients_for(
&self,
private_title: &Option<String>,
notes: &Option<String>,
) -> Result<Vec<String>, String> {
if private_title.is_none() && notes.is_none() {
return Ok(Vec::new());
}
self.api.list_encryption_recipients().map(|recipients| {
recipients
.into_iter()
.map(|recipient| recipient.age_recipient)
.collect()
})
}
fn open_create_form(&mut self) {
self.form = Some(match self.view {
View::Tasks => task_form(),
View::Routines => routine_form(),
View::Archive => return,
View::Devices => device_form(self.crypto.local_recipient().to_owned()),
});
}
@@ -326,7 +372,7 @@ impl App {
return;
};
self.pending_action = Some(PendingAction {
task_id: task.id,
item_id: task.id,
title: task.visible_title().to_owned(),
kind: PendingActionKind::Archive,
});
@@ -338,12 +384,28 @@ impl App {
return;
};
self.pending_action = Some(PendingAction {
task_id: task.id,
item_id: task.id,
title: task.visible_title().to_owned(),
kind: PendingActionKind::Delete,
});
}
fn ask_revoke_device(&mut self) {
let Some(device) = self.devices.get(self.selected) else {
self.status = "no device selected".to_owned();
return;
};
if device.status != "active" {
self.status = "device is already revoked".to_owned();
return;
}
self.pending_action = Some(PendingAction {
item_id: device.id,
title: device.name.clone(),
kind: PendingActionKind::RevokeDevice,
});
}
fn restore_selected(&mut self) {
let Some(task) = self.archived_tasks.get(self.selected) else {
self.status = "no archived task selected".to_owned();
@@ -427,6 +489,17 @@ fn routine_form() -> Form {
}
}
fn device_form(recipient: String) -> Form {
Form {
kind: FormKind::Device,
fields: vec![
text_field("Device name", "required", String::new()),
text_field("AGE recipient", "public key", recipient),
],
active: 0,
}
}
fn text_field(label: &'static str, hint: &'static str, value: String) -> Field {
Field {
label,
@@ -553,7 +626,7 @@ mod tests {
app.handle_key(KeyEvent::new(KeyCode::Char('x'), KeyModifiers::NONE));
let pending = app.pending_action.as_ref().unwrap();
assert_eq!(pending.task_id, 42);
assert_eq!(pending.item_id, 42);
assert_eq!(pending.title, "Keep me");
assert_eq!(pending.kind, PendingActionKind::Archive);
@@ -577,4 +650,27 @@ mod tests {
PendingActionKind::Delete
);
}
#[test]
fn active_device_requires_confirmation_before_revocation() {
let mut app = App::new(
ApiClient::new("http://127.0.0.1:1".to_owned(), None),
Crypto::disabled(),
);
app.view = View::Devices;
app.devices.push(EncryptionDevice {
id: 7,
name: "Laptop".to_owned(),
age_recipient: "age1example".to_owned(),
status: "active".to_owned(),
created_at: 0,
revoked_at: None,
});
app.handle_key(KeyEvent::new(KeyCode::Char('x'), KeyModifiers::NONE));
let pending = app.pending_action.as_ref().unwrap();
assert_eq!(pending.item_id, 7);
assert_eq!(pending.title, "Laptop");
assert_eq!(pending.kind, PendingActionKind::RevokeDevice);
}
}
+80 -14
View File
@@ -11,14 +11,14 @@ const ENCRYPTION_VERSION: i16 = 1;
static CONTENT_COUNTER: AtomicU64 = AtomicU64::new(0);
pub struct Crypto {
recipient: Option<String>,
local_recipient: Option<String>,
identity_file: Option<PathBuf>,
}
impl Crypto {
pub fn from_env() -> Self {
Self {
recipient: env::var("ROUTINE_AGE_RECIPIENT").ok(),
local_recipient: env::var("ROUTINE_AGE_RECIPIENT").ok(),
identity_file: env::var_os("ROUTINE_AGE_IDENTITY_FILE").map(PathBuf::from),
}
}
@@ -26,7 +26,7 @@ impl Crypto {
#[cfg(test)]
pub fn disabled() -> Self {
Self {
recipient: None,
local_recipient: None,
identity_file: None,
}
}
@@ -35,14 +35,16 @@ impl Crypto {
&self,
private_title: Option<String>,
notes: Option<String>,
recipients: &[String],
) -> Result<EncryptedFields, String> {
if private_title.is_none() && notes.is_none() {
return Ok(EncryptedFields::default());
}
let recipient = self
.recipient
.as_deref()
.ok_or_else(|| "ROUTINE_AGE_RECIPIENT is required for private fields".to_owned())?;
if recipients.is_empty() {
return Err(
"register at least one active encryption device for private fields".to_owned(),
);
}
let content_id = new_content_id()?;
let plaintext = serde_json::to_vec(&PrivatePayload {
version: ENCRYPTION_VERSION as u8,
@@ -51,10 +53,12 @@ impl Crypto {
notes,
})
.map_err(|error| format!("cannot encode private fields: {error}"))?;
let encrypted_payload = run_age(
&["--encrypt", "--armor", "--recipient", recipient],
&plaintext,
)?;
let mut arguments = vec!["--encrypt".to_owned(), "--armor".to_owned()];
for recipient in recipients {
arguments.push("--recipient".to_owned());
arguments.push(recipient.clone());
}
let encrypted_payload = run_age(&arguments, &plaintext)?;
let encrypted_payload = String::from_utf8(encrypted_payload)
.map_err(|_| "age returned non-UTF-8 armored output".to_owned())?;
Ok(EncryptedFields {
@@ -64,6 +68,10 @@ impl Crypto {
})
}
pub fn local_recipient(&self) -> &str {
self.local_recipient.as_deref().unwrap_or("")
}
pub fn decrypt_task(&self, task: &mut Task) {
match self.decrypt_fields(
task.encrypted_payload.as_deref(),
@@ -113,7 +121,11 @@ impl Crypto {
let identity_file = self.identity_file.as_ref().ok_or(())?;
let identity = identity_file.to_str().ok_or(())?;
let plaintext = run_age(
&["--decrypt", "--identity", identity],
&[
"--decrypt".to_owned(),
"--identity".to_owned(),
identity.to_owned(),
],
encrypted_payload.as_bytes(),
)
.map_err(|_| ())?;
@@ -127,7 +139,7 @@ impl Crypto {
}
}
fn run_age(arguments: &[&str], input: &[u8]) -> Result<Vec<u8>, String> {
fn run_age(arguments: &[String], input: &[u8]) -> Result<Vec<u8>, String> {
let mut child = Command::new("age")
.args(arguments)
.stdin(Stdio::piped())
@@ -184,7 +196,7 @@ mod tests {
assert!(recipient.status.success());
let crypto = Crypto {
recipient: Some(
local_recipient: Some(
String::from_utf8(recipient.stdout)
.unwrap()
.trim()
@@ -196,6 +208,7 @@ mod tests {
.encrypt_optional(
Some("Private appointment".to_owned()),
Some("Private notes".to_owned()),
&[crypto.local_recipient().to_owned()],
)
.unwrap();
let decrypted = crypto
@@ -215,4 +228,57 @@ mod tests {
assert_eq!(decrypted.notes.as_deref(), Some("Private notes"));
std::fs::remove_dir_all(test_dir).unwrap();
}
#[test]
fn one_payload_decrypts_with_each_registered_identity() {
let test_dir = env::temp_dir().join(format!(
"routine-age-multi-test-{}",
new_content_id().unwrap()
));
std::fs::create_dir(&test_dir).unwrap();
let mut identities = Vec::new();
let mut recipients = Vec::new();
for index in 0..2 {
let identity = test_dir.join(format!("identity-{index}.txt"));
assert!(Command::new("age-keygen")
.args(["-o", identity.to_str().unwrap()])
.status()
.unwrap()
.success());
let recipient = Command::new("age-keygen")
.args(["-y", identity.to_str().unwrap()])
.output()
.unwrap();
recipients.push(
String::from_utf8(recipient.stdout)
.unwrap()
.trim()
.to_owned(),
);
identities.push(identity);
}
let encryptor = Crypto {
local_recipient: None,
identity_file: None,
};
let encrypted = encryptor
.encrypt_optional(Some("shared".to_owned()), None, &recipients)
.unwrap();
for identity_file in identities {
let decryptor = Crypto {
local_recipient: None,
identity_file: Some(identity_file),
};
let decrypted = decryptor
.decrypt_fields(
encrypted.encrypted_payload.as_deref(),
encrypted.encryption_version,
encrypted.content_id.as_deref(),
)
.unwrap()
.unwrap();
assert_eq!(decrypted.private_title.as_deref(), Some("shared"));
}
std::fs::remove_dir_all(test_dir).unwrap();
}
}
+21
View File
@@ -83,6 +83,27 @@ pub struct RescheduleTask {
pub scheduled_date: String,
}
#[derive(Debug, Clone, Deserialize)]
pub struct EncryptionDevice {
pub id: i64,
pub name: String,
pub age_recipient: String,
pub status: String,
pub created_at: i64,
pub revoked_at: Option<i64>,
}
#[derive(Debug, Clone, Deserialize)]
pub struct EncryptionRecipient {
pub age_recipient: String,
}
#[derive(Debug, Serialize)]
pub struct CreateEncryptionDevice {
pub name: String,
pub age_recipient: String,
}
#[derive(Debug, Deserialize, Serialize)]
pub struct PrivatePayload {
pub version: u8,
+57 -5
View File
@@ -34,6 +34,11 @@ pub fn render(frame: &mut Frame, app: &App) {
} else {
Style::default()
};
let devices_style = if app.view == View::Devices {
active
} else {
Style::default()
};
let date = if app.view == View::Tasks {
format!(" {} ", app.date)
} else {
@@ -45,6 +50,8 @@ pub fn render(frame: &mut Frame, app: &App) {
Span::styled(" Routines ", routines_style),
Span::raw(" "),
Span::styled(" Archive ", archive_style),
Span::raw(" "),
Span::styled(" Devices ", devices_style),
Span::raw(date),
]))
.block(Block::default().borders(Borders::ALL).title("Routine"));
@@ -141,11 +148,34 @@ pub fn render(frame: &mut Frame, app: &App) {
ListItem::new(lines)
})
.collect::<Vec<_>>(),
View::Devices => app
.devices
.iter()
.map(|device| {
let mark = if device.status == "active" {
"●"
} else {
"○"
};
let revoked = device
.revoked_at
.map(|timestamp| format!(" revoked:{timestamp}"))
.unwrap_or_default();
ListItem::new(Line::from(format!(
"{mark} {:<10} {} {} created:{}{revoked}",
device.status,
device.name,
short_recipient(&device.age_recipient),
device.created_at,
)))
})
.collect::<Vec<_>>(),
};
let title = match app.view {
View::Tasks => "Tasks for selected day",
View::Routines => "Daily, weekly, and monthly routines",
View::Archive => "Archived tasks",
View::Devices => "Encryption devices (public recipients only)",
};
let list = List::new(items)
.block(Block::default().borders(Borders::ALL).title(title))
@@ -157,10 +187,11 @@ pub fn render(frame: &mut Frame, app: &App) {
let help = match app.view {
View::Tasks => {
"q quit Tab routines h/l day t today j/k move a add Space complete s move x delete r refresh"
"q quit Tab routines h/l day t today j/k move a add Space complete s move x archive r refresh"
}
View::Routines => "q quit Tab tasks j/k move a add routine r refresh",
View::Archive => "q quit Tab tasks j/k move u restore x delete permanently r refresh",
View::Devices => "q quit Tab tasks j/k move a register device x revoke r refresh",
};
let footer = Paragraph::new(vec![
Line::from(help),
@@ -178,6 +209,7 @@ pub fn render(frame: &mut Frame, app: &App) {
FormKind::Task => format!("New task for {}", app.date),
FormKind::Routine => "New routine".to_owned(),
FormKind::Reschedule { .. } => "Reschedule task".to_owned(),
FormKind::Device => "Register encryption device".to_owned(),
};
let lines = form
.fields
@@ -210,12 +242,15 @@ pub fn render(frame: &mut Frame, app: &App) {
if let Some(pending) = &app.pending_action {
let area = centered_rect(60, 7, frame.area());
frame.render_widget(Clear, area);
let (verb, title) = match pending.kind {
PendingActionKind::Archive => ("Archive", "Confirm archive"),
PendingActionKind::Delete => ("Permanently delete", "Confirm permanent deletion"),
let (subject, verb, title) = match pending.kind {
PendingActionKind::Archive => ("task", "Archive", "Confirm archive"),
PendingActionKind::Delete => {
("task", "Permanently delete", "Confirm permanent deletion")
}
PendingActionKind::RevokeDevice => ("device", "Revoke", "Confirm device revocation"),
};
let dialog = Paragraph::new(vec![
Line::from(format!("{verb} task “{}”?", pending.title)),
Line::from(format!("{verb} {subject} “{}”?", pending.title)),
Line::from(""),
Line::styled(
"y: confirm • n/Esc: cancel",
@@ -229,6 +264,23 @@ pub fn render(frame: &mut Frame, app: &App) {
}
}
fn short_recipient(recipient: &str) -> String {
const EDGE: usize = 10;
if recipient.chars().count() <= EDGE * 2 + 1 {
return recipient.to_owned();
}
let start: String = recipient.chars().take(EDGE).collect();
let end: String = recipient
.chars()
.rev()
.take(EDGE)
.collect::<String>()
.chars()
.rev()
.collect();
format!("{start}…{end}")
}
fn centered_rect(width_percent: u16, height: u16, area: Rect) -> Rect {
let vertical_margin = area.height.saturating_sub(height) / 2;
let vertical = Layout::vertical([