This commit is contained in:
@@ -4,9 +4,9 @@ Small PostgreSQL-backed HTTP service for one-off tasks and daily, weekly, or
|
||||
monthly routine tasks. The server generates future task occurrences and can
|
||||
send due reminders through the Telegram Bot API.
|
||||
|
||||
The server stores an obligatory public title and an optional client-encrypted
|
||||
payload. It never receives an age identity and Telegram always uses the public
|
||||
title.
|
||||
The server stores an obligatory public title, an optional client-encrypted
|
||||
payload, and the public age recipients of registered devices. It never receives
|
||||
an age identity and Telegram always uses the public title.
|
||||
|
||||
## Configuration
|
||||
|
||||
@@ -68,6 +68,10 @@ POST /v1/tasks/{id}/reschedule
|
||||
DELETE /v1/tasks/{id} (archived tasks only)
|
||||
GET /v1/routines
|
||||
POST /v1/routines
|
||||
GET /v1/encryption/devices
|
||||
GET /v1/encryption/recipients
|
||||
POST /v1/encryption/devices
|
||||
POST /v1/encryption/devices/{id}/revoke
|
||||
```
|
||||
|
||||
Weekly days use ISO numbers: Monday is `1`, Sunday is `7`.
|
||||
@@ -75,3 +79,7 @@ Weekly days use ISO numbers: Monday is `1`, Sunday is `7`.
|
||||
When private data is present, `encrypted_payload`, `encryption_version`, and
|
||||
`content_id` must all be set. `encrypted_payload` is an ASCII-armored age file
|
||||
containing the client's versioned JSON document.
|
||||
|
||||
Only active device recipients are returned for encryption. Revocation affects
|
||||
new payloads; it cannot make ciphertext that a device already received
|
||||
unreadable.
|
||||
|
||||
@@ -130,6 +130,29 @@ pub struct DueNotification {
|
||||
pub priority: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
pub struct CreateEncryptionDevice {
|
||||
pub name: String,
|
||||
pub age_recipient: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
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, Serialize)]
|
||||
pub struct EncryptionRecipient {
|
||||
pub id: i64,
|
||||
pub name: String,
|
||||
pub age_recipient: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
pub struct IdResponse {
|
||||
pub id: i64,
|
||||
|
||||
@@ -4,7 +4,8 @@ use serde::Serialize;
|
||||
use tiny_http::{Header, Method, Request, Response, Server, StatusCode};
|
||||
|
||||
use crate::model::{
|
||||
CreateRoutine, CreateTask, ErrorResponse, IdResponse, RescheduleTask, StatusResponse,
|
||||
CreateEncryptionDevice, CreateRoutine, CreateTask, ErrorResponse, IdResponse, RescheduleTask,
|
||||
StatusResponse,
|
||||
};
|
||||
use crate::store::Store;
|
||||
|
||||
@@ -61,10 +62,52 @@ fn handle(mut request: Request, store: &Store, api_token: Option<&str>) {
|
||||
});
|
||||
respond_created(request, result);
|
||||
}
|
||||
(&Method::Get, "/v1/encryption/devices") => match store.list_encryption_devices() {
|
||||
Ok(devices) => respond_json(request, 200, &devices),
|
||||
Err(error) => respond_failure(request, &error),
|
||||
},
|
||||
(&Method::Get, "/v1/encryption/recipients") => match store.list_encryption_recipients() {
|
||||
Ok(recipients) => respond_json(request, 200, &recipients),
|
||||
Err(error) => respond_failure(request, &error),
|
||||
},
|
||||
(&Method::Post, "/v1/encryption/devices") => {
|
||||
let result = parse_json::<CreateEncryptionDevice>(&mut request)
|
||||
.and_then(|input| store.create_encryption_device(input));
|
||||
respond_created(request, result);
|
||||
}
|
||||
_ if path.starts_with("/v1/encryption/devices/") => {
|
||||
handle_device_action(request, store, &path)
|
||||
}
|
||||
_ => handle_task_action(request, store, &path),
|
||||
}
|
||||
}
|
||||
|
||||
fn handle_device_action(request: Request, store: &Store, path: &str) {
|
||||
let segments: Vec<_> = path.trim_matches('/').split('/').collect();
|
||||
if segments.len() != 5
|
||||
|| segments[0] != "v1"
|
||||
|| segments[1] != "encryption"
|
||||
|| segments[2] != "devices"
|
||||
|| segments[4] != "revoke"
|
||||
|| request.method() != &Method::Post
|
||||
{
|
||||
respond_error(request, 404, "route not found");
|
||||
return;
|
||||
}
|
||||
let id = match segments[3].parse::<i64>() {
|
||||
Ok(id) => id,
|
||||
Err(_) => {
|
||||
respond_error(request, 400, "device id must be an integer");
|
||||
return;
|
||||
}
|
||||
};
|
||||
match store.revoke_encryption_device(id) {
|
||||
Ok(true) => respond_json(request, 200, &StatusResponse { status: "ok" }),
|
||||
Ok(false) => respond_error(request, 404, "active device not found"),
|
||||
Err(error) => respond_failure(request, &error),
|
||||
}
|
||||
}
|
||||
|
||||
fn handle_task_action(mut request: Request, store: &Store, path: &str) {
|
||||
let segments: Vec<_> = path.trim_matches('/').split('/').collect();
|
||||
if segments.len() < 3 || segments[0] != "v1" || segments[1] != "tasks" {
|
||||
|
||||
@@ -1,7 +1,10 @@
|
||||
use chrono::{Datelike, Days, NaiveDate, NaiveTime};
|
||||
use postgres::{Client, NoTls};
|
||||
|
||||
use crate::model::{CreateRoutine, CreateTask, DueNotification, Routine, Schedule, Task};
|
||||
use crate::model::{
|
||||
CreateEncryptionDevice, CreateRoutine, CreateTask, DueNotification, EncryptionDevice,
|
||||
EncryptionRecipient, Routine, Schedule, Task,
|
||||
};
|
||||
|
||||
pub type Result<T> = std::result::Result<T, String>;
|
||||
|
||||
@@ -68,11 +71,97 @@ impl Store {
|
||||
ALTER TABLE tasks
|
||||
ADD COLUMN IF NOT EXISTS status_before_archive TEXT;
|
||||
ALTER TABLE tasks
|
||||
ADD COLUMN IF NOT EXISTS archived_at TIMESTAMPTZ;",
|
||||
ADD COLUMN IF NOT EXISTS archived_at TIMESTAMPTZ;
|
||||
CREATE TABLE IF NOT EXISTS encryption_devices (
|
||||
id BIGSERIAL PRIMARY KEY,
|
||||
name TEXT NOT NULL,
|
||||
age_recipient TEXT NOT NULL UNIQUE,
|
||||
status TEXT NOT NULL DEFAULT 'active',
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
revoked_at TIMESTAMPTZ,
|
||||
CHECK (status IN ('active', 'revoked')),
|
||||
CHECK ((status = 'active' AND revoked_at IS NULL)
|
||||
OR (status = 'revoked' AND revoked_at IS NOT NULL))
|
||||
);",
|
||||
)
|
||||
.map_err(db_error)
|
||||
}
|
||||
|
||||
pub fn list_encryption_devices(&self) -> Result<Vec<EncryptionDevice>> {
|
||||
let mut client = self.connect()?;
|
||||
let rows = client
|
||||
.query(
|
||||
"SELECT id, name, age_recipient, status,
|
||||
EXTRACT(EPOCH FROM created_at)::BIGINT,
|
||||
EXTRACT(EPOCH FROM revoked_at)::BIGINT
|
||||
FROM encryption_devices
|
||||
ORDER BY status, id",
|
||||
&[],
|
||||
)
|
||||
.map_err(db_error)?;
|
||||
Ok(rows
|
||||
.into_iter()
|
||||
.map(|row| EncryptionDevice {
|
||||
id: row.get(0),
|
||||
name: row.get(1),
|
||||
age_recipient: row.get(2),
|
||||
status: row.get(3),
|
||||
created_at: row.get(4),
|
||||
revoked_at: row.get(5),
|
||||
})
|
||||
.collect())
|
||||
}
|
||||
|
||||
pub fn list_encryption_recipients(&self) -> Result<Vec<EncryptionRecipient>> {
|
||||
let mut client = self.connect()?;
|
||||
let rows = client
|
||||
.query(
|
||||
"SELECT id, name, age_recipient
|
||||
FROM encryption_devices
|
||||
WHERE status = 'active'
|
||||
ORDER BY id",
|
||||
&[],
|
||||
)
|
||||
.map_err(db_error)?;
|
||||
Ok(rows
|
||||
.into_iter()
|
||||
.map(|row| EncryptionRecipient {
|
||||
id: row.get(0),
|
||||
name: row.get(1),
|
||||
age_recipient: row.get(2),
|
||||
})
|
||||
.collect())
|
||||
}
|
||||
|
||||
pub fn create_encryption_device(&self, device: CreateEncryptionDevice) -> Result<i64> {
|
||||
let name = device.name.trim();
|
||||
let recipient = device.age_recipient.trim();
|
||||
validate_device(name, recipient)?;
|
||||
let mut client = self.connect()?;
|
||||
let row = client
|
||||
.query_one(
|
||||
"INSERT INTO encryption_devices (name, age_recipient)
|
||||
VALUES ($1, $2)
|
||||
RETURNING id",
|
||||
&[&name, &recipient],
|
||||
)
|
||||
.map_err(db_error)?;
|
||||
Ok(row.get(0))
|
||||
}
|
||||
|
||||
pub fn revoke_encryption_device(&self, id: i64) -> Result<bool> {
|
||||
let mut client = self.connect()?;
|
||||
client
|
||||
.execute(
|
||||
"UPDATE encryption_devices
|
||||
SET status = 'revoked', revoked_at = now()
|
||||
WHERE id = $1 AND status = 'active'",
|
||||
&[&id],
|
||||
)
|
||||
.map(|changed| changed == 1)
|
||||
.map_err(db_error)
|
||||
}
|
||||
|
||||
pub fn create_task(&self, task: CreateTask) -> Result<i64> {
|
||||
validate_public_title(&task.public_title)?;
|
||||
validate_encrypted_fields(
|
||||
@@ -394,6 +483,22 @@ fn validate_public_title(title: &str) -> Result<()> {
|
||||
}
|
||||
}
|
||||
|
||||
fn validate_device(name: &str, recipient: &str) -> Result<()> {
|
||||
if name.is_empty() {
|
||||
return Err("device name must not be empty".to_owned());
|
||||
}
|
||||
if name.len() > 100 {
|
||||
return Err("device name must be at most 100 bytes".to_owned());
|
||||
}
|
||||
if recipient.is_empty() {
|
||||
return Err("age recipient must not be empty".to_owned());
|
||||
}
|
||||
if recipient.len() > 4096 || recipient.contains('\n') || recipient.contains('\r') {
|
||||
return Err("age recipient must be a single line of at most 4096 bytes".to_owned());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn validate_encrypted_fields(
|
||||
payload: Option<&str>,
|
||||
version: Option<i16>,
|
||||
@@ -527,4 +632,14 @@ mod tests {
|
||||
)
|
||||
.unwrap());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn validates_encryption_device_fields() {
|
||||
assert!(validate_device("Laptop", "age1example").is_ok());
|
||||
assert_eq!(
|
||||
validate_device("", "age1example").unwrap_err(),
|
||||
"device name must not be empty"
|
||||
);
|
||||
assert!(validate_device("Laptop", "age1example\nother").is_err());
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user