//! The task modal (`docs/architecture.md` section 4, `docs/reference/old-inventory.md` 2.3): the card that //! `GET /?task=` opens over the board, and every write the modal makes. //! //! Reads: the modal loads one task of this board by its key. A key that is unknown, deleted or on another //! board answers the board with a "not found" notice and `404`. A viewer sees the same content with no //! write control. //! //! Writes: every write is a form that carries the CSRF token and a `next` path (the modal's own URL). The //! gate is the same as the board's (`pages/tasks.rs`): a member with the write level, the token, then the //! change. A refused change re-renders the board with the modal open, the message above the fields, and //! the typed values kept, at `422`. An accepted change redirects (Post/Redirect/Get) to the modal of its //! task, with a notice. Each write bumps the board topic and the task topic (`live.rs`). //! //! Comments are checked by their own id: the store loads the comment, checks that its task is live and on //! this board, and only then asks `authz` whether this member may edit or delete it. A comment of a deleted //! task is not found. use std::collections::{HashMap, HashSet}; use std::result::Result as StdResult; use iz_core::authz::{Action, authorize}; use iz_core::clock::{MeetingInput, resolve_meeting, timestamp_of}; use iz_core::limits::{COMMENT_MAX, DESCRIPTION_MAX, TITLE_MAX}; use iz_core::store::board::Tag; use iz_core::store::members::Member; use iz_core::store::tasks::{NewTask, Task, TaskDetail, TaskEdit}; use iz_core::zones::{parse_zone, utc_to_local}; use jiff::civil::Date; use jiff::tz::TimeZone; use serde::Deserialize; use topcoat::Result; use topcoat::context::{Cx, app_context}; use topcoat::router::content::Form; use topcoat::router::error::{forbidden, not_found, see_other}; use topcoat::router::response::Response; use topcoat::router::{StatusCode, path_param_segment, route}; use crate::auth::{CurrentMember, percent_encode, safe_next}; use crate::i18n::board::{K as BK, t as bt}; use crate::i18n::task::{K, activity_kind, t}; use crate::i18n::{Lang, lang}; use crate::live::Topic; use crate::pages::board::{BoardPage, board_url, load, pairs, query_of, render, the_board}; use crate::pages::tasks::{answer_stop, writer}; use crate::state::AppState; /// Rows of activity per page in the modal. Reason: the feed is a summary; older rows are one click away. const ACTIVITY_PAGE: usize = 20; /// The filters that the modal keeps in its own links, so the board behind it is the same one. const FILTER_KEYS: [&str; 4] = ["tag", "assignee", "sort", "q"]; /// The fields of the edit form as typed, or as stored. A refused edit shows the typed values again. #[derive(Clone, Debug, Default)] pub struct EditValues { /// The title. pub title: String, /// The description, as plain text. pub description: String, /// The project id. pub tag: String, /// The deadline day, `YYYY-MM-DD`, or empty. pub deadline: String, /// The meeting time in the viewer's zone, `HH:MM`, or empty. pub time: String, } /// One comment as the modal shows it, with the rights of the viewer over it. pub struct CommentRow { /// The comment id. pub id: String, /// The author's name. pub author: String, /// The body as stored (plain text). pub body: String, /// When it was written, in the viewer's zone, `YYYY-MM-DD HH:MM`. pub when: String, /// Whether it was edited after it was written. pub edited: bool, /// Whether the viewer may edit it (its author, while a member). pub can_edit: bool, /// Whether the viewer may delete it (its author, or an admin). pub can_delete: bool, } /// One row of the activity feed. pub struct ActivityRow { /// The sentence for the kind of event, in the viewer's language. pub sentence: &'static str, /// Who did it, by name (`-` for the system). pub actor: String, /// When, in the viewer's zone, `YYYY-MM-DD HH:MM`. pub when: String, } /// One attachment as the modal lists it, with the links and rights of the viewer over it. pub struct FileRow { /// The file name as uploaded. pub name: String, /// The size, as text. pub size: String, /// The uploader's name. pub uploader: String, /// When it was uploaded, in the viewer's zone. pub when: String, /// Whether the viewer can show it (has a preview). pub viewable: bool, /// The modal URL that opens its viewer. pub view_url: String, /// The URL that saves it. pub download_url: String, /// The form action that deletes it. pub delete_action: String, /// Whether the viewer may delete it. pub can_delete: bool, } /// The task modal, as the board page shows it. pub struct TaskModal { /// The attachments of the task, oldest first. pub files: Vec, /// The file open in the viewer (`?file=`), when there is one. pub viewer: Option, /// The task with its tag, assignees, subtasks and links. pub detail: TaskDetail, /// Whether the viewer may change the task. pub can_write: bool, /// This modal's own URL: the board filters and `task=`. Forms return here. pub base: String, /// The board with the same filters and no task: where the modal closes. pub close: String, /// The edit form's values: the stored ones, or the typed ones after a refusal. pub edit: EditValues, /// Enabled members who may be assigned and are not yet assigned here. pub assignable: Vec, /// Every other live task of the board, for the dependency and parent pickers. pub options: Vec, /// Whether the viewer watches the task. pub watching: bool, /// The live comments, oldest first. pub comments: Vec, /// The newest page of the activity feed. pub activity: Vec, /// The URL of the next, older page of activity, when there is one. pub older: Option, /// Whether the delete confirmation is open. pub confirm_delete: bool, /// The message of a refused write, shown above the fields. pub error: Option<&'static str>, /// The comment text typed in the composer, kept after a refusal. pub comment_draft: String, } /// What a re-rendered modal starts from: the message of a refusal, the typed values, and the view options. #[derive(Default)] pub struct Draft { /// The refusal to show. pub error: Option<&'static str>, /// The typed edit values, when the edit was refused. pub edit: Option, /// The typed comment, when the comment was refused. pub comment: Option, /// Whether the delete confirmation is open (`?confirm=delete`). pub confirm: bool, /// The cursor of the activity page to show (`?before=`). pub before: Option, } /// The form of every modal write. Each field is optional on the wire; a missing one is empty. #[derive(Deserialize, Default)] pub struct ModalForm { #[serde(default)] csrf: String, /// The modal URL the form was on. #[serde(default)] next: String, #[serde(default)] title: String, #[serde(default)] description: String, /// The project id. #[serde(default)] tag: String, #[serde(default)] deadline: String, /// The meeting time, `HH:MM`. #[serde(default)] time: String, /// A comment body. #[serde(default)] body: String, /// A member's id, for assign and unassign. #[serde(default)] sub: String, /// `1` to watch, `0` to stop. #[serde(default)] on: String, /// The parent task's id, or empty for none. #[serde(default)] parent: String, /// The other task of a dependency. #[serde(default)] other: String, /// `blocked_by` (this task waits for `other`) or `blocks` (`other` waits for this task). #[serde(default)] direction: String, } /// The modal's URL for `key`: the board filters of `query` and `task=`, plus `extra`. Filters that are /// not in [`FILTER_KEYS`] are dropped, so a stale `confirm` or `before` never comes back. pub fn modal_url(query: Option<&str>, key: &str, extra: &[(&str, &str)]) -> String { let mut parts: Vec = pairs(query.unwrap_or("")) .into_iter() .filter(|(name, _)| FILTER_KEYS.contains(&name.as_str())) .map(|(name, value)| format!("{name}={}", percent_encode(&value))) .collect(); parts.push(format!("task={}", percent_encode(key))); parts.extend( extra .iter() .map(|(name, value)| format!("{name}={}", percent_encode(value))), ); format!("/?{}", parts.join("&")) } /// The link to another task's modal from `close` (the board URL with the filters). pub fn task_link(close: &str, key: &str) -> String { let separator = if close.contains('?') { '&' } else { '?' }; format!("{close}{separator}task={}", percent_encode(key)) } /// The `task` value of a `next` path, when it names one. fn task_of(next: &str) -> Option { pairs(query_of(safe_next(Some(next))).unwrap_or("")) .into_iter() .find(|(name, _)| name == "task") .map(|(_, value)| value) .filter(|value| !value.is_empty()) } /// Maps a store error to the framework's answer: a missing or hidden thing is `404`, a refused right is /// `403`, and anything else is a logged `500`. pub fn core_err(error: iz_core::Error) -> topcoat::Error { match error { iz_core::Error::NotFound => not_found().into(), iz_core::Error::Forbidden(_) => forbidden().into(), other => other.into(), } } /// The zone of the signed-in member; UTC when the stored name does not parse. fn zone_of(me: &CurrentMember) -> TimeZone { parse_zone(&me.member.zoneinfo).unwrap_or(TimeZone::UTC) } /// A stored UTC stamp in `zone` as `YYYY-MM-DD HH:MM`. Empty when the stamp does not parse. pub(crate) fn local_text(stamp: &str, zone: &TimeZone) -> String { match timestamp_of(stamp) { Ok(at) => { let local = utc_to_local(zone, at); format!( "{:04}-{:02}-{:02} {:02}:{:02}", local.year(), local.month(), local.day(), local.hour(), local.minute() ) } Err(_) => String::new(), } } /// A stored UTC stamp in `zone` as `HH:MM`, for the time field. fn clock_text(stamp: &str, zone: &TimeZone) -> String { match timestamp_of(stamp) { Ok(at) => { let local = utc_to_local(zone, at); format!("{:02}:{:02}", local.hour(), local.minute()) } Err(_) => String::new(), } } /// Reads `HH:MM` (one or two digits per part). `None` for anything else, or an hour or minute out of range. fn parse_clock(text: &str) -> Option<(u8, u8)> { let (hour, minute) = text.trim().split_once(':')?; if hour.is_empty() || hour.len() > 2 || minute.len() != 2 { return None; } let hour: u8 = hour.parse().ok()?; let minute: u8 = minute.parse().ok()?; (hour < 24 && minute < 60).then_some((hour, minute)) } /// Checks the edit form and turns it into the store's input. The first problem found is the message. The /// deadline and the meeting time are resolved in the viewer's zone (`clock.rs`). fn edit_input( form: &ModalForm, tags: &[Tag], zone: &TimeZone, language: Lang, ) -> StdResult { let title = form.title.trim(); if title.is_empty() || title.chars().count() > TITLE_MAX { return Err(bt(language, BK::TitleInvalid)); } if form.description.chars().count() > DESCRIPTION_MAX { return Err(t(language, K::DescriptionTooLong)); } if !tags.iter().any(|tag| tag.id == form.tag) { return Err(t(language, K::ErrProject)); } let day = match form.deadline.trim() { "" => None, text => Some( text.parse::() .map_err(|_| t(language, K::ErrDeadline))?, ), }; let clock = match form.time.trim() { "" => None, text => Some(parse_clock(text).ok_or(t(language, K::ErrTime))?), }; let (hour, minute) = match clock { Some((hour, minute)) => (Some(hour), Some(minute)), None => (None, None), }; let (deadline, meeting_at) = resolve_meeting(MeetingInput { day, hour, minute }, zone) .map_err(|_| t(language, K::ErrMeeting))?; Ok(TaskEdit { title: title.to_owned(), description: form.description.clone(), tag_id: form.tag.clone(), deadline, meeting_at, }) } /// The direction of a dependency as the stored pair: `(blocked, blocking)`. `None` for an unknown word. fn link_pair<'a>(task: &'a str, other: &'a str, direction: &str) -> Option<(&'a str, &'a str)> { match direction { "blocked_by" => Some((task, other)), "blocks" => Some((other, task)), _ => None, } } /// Loads the modal of `key` into `page`. Returns `false` when the task does not exist on this board (or is /// deleted); the page is then left as it was. pub async fn open( state: &AppState, me: &CurrentMember, page: &mut BoardPage, key: &str, query: Option<&str>, draft: Draft, ) -> Result { let store = &state.store; let board = the_board(store).await?; let detail = match store.task_detail(&board.id, key).await { Ok(detail) => detail, Err(iz_core::Error::NotFound) => return Ok(false), Err(error) => return Err(core_err(error)), }; let task_id = detail.task.id.clone(); let zone = page.zone.clone(); let names: HashMap = store .list_members() .await .map_err(core_err)? .into_iter() .map(|member| (member.sub, member.name)) .collect(); let name_of = |sub: &str| names.get(sub).cloned().unwrap_or_else(|| "-".to_owned()); let comments = store .list_comments(&board.id, &task_id) .await .map_err(core_err)?; let before = draft.before.filter(|cursor| cursor.contains('~')); let feed = store .list_task_page(&board.id, &task_id, before.as_deref(), ACTIVITY_PAGE) .await .map_err(core_err)?; let watching = store .is_watching(&task_id, &me.member.sub) .await .map_err(core_err)?; let options: Vec = store .task_options(&board.id) .await .map_err(core_err)? .into_iter() .filter(|other| other.id != task_id) .collect(); let assigned: HashSet<&str> = detail.assignees.iter().map(|a| a.sub.as_str()).collect(); let assignable: Vec = page .members .iter() .filter(|member| !assigned.contains(member.sub.as_str())) .cloned() .collect(); let can_write = page.can_write; let comment_rows: Vec = comments .into_iter() .map(|comment| { let author = comment.author.clone(); CommentRow { can_edit: can_write && authorize( &me.actor(), &Action::EditComment { author: author.clone(), }, ) .is_ok(), can_delete: can_write && authorize( &me.actor(), &Action::DeleteComment { author: author.clone(), }, ) .is_ok(), author: name_of(&author), when: local_text(&comment.created_at, &zone), edited: comment.edited_at.is_some(), id: comment.id, body: comment.body, } }) .collect(); let activity: Vec = feed .items .iter() .map(|item| ActivityRow { sentence: activity_kind(page.lang, &item.kind), actor: item .actor .as_deref() .map_or_else(|| "-".to_owned(), name_of), when: local_text(&item.at, &zone), }) .collect(); let base = modal_url(query, key, &[]); let older = feed .next_cursor .map(|cursor| format!("{base}&before={}", percent_encode(&cursor))); let stored = EditValues { title: detail.task.title.clone(), description: detail.task.description.clone(), tag: detail.task.tag_id.clone(), deadline: detail .task .deadline .map(|day| day.to_string()) .unwrap_or_default(), time: detail .task .meeting_at .as_deref() .map(|stamp| clock_text(stamp, &zone)) .unwrap_or_default(), }; let attachments = store .list_attachments(&board.id, &task_id) .await .map_err(core_err)?; let files = crate::pages::files::file_rows(&attachments, key, query, me, can_write, &names, &zone); let modal = TaskModal { files, viewer: None, can_write, close: board_url(&page.filters, &[]), base, edit: draft.edit.unwrap_or(stored), assignable, options, watching, comments: comment_rows, activity, older, confirm_delete: draft.confirm && can_write, error: draft.error, comment_draft: draft.comment.unwrap_or_default(), detail, }; page.modal = Some(modal); Ok(true) } /// A write that passed the gate and found its task on this board. struct Begun { me: CurrentMember, lang: Lang, board_id: String, detail: TaskDetail, } /// The gate of a write: the member with the write level and the CSRF token, then the board. A refusal of /// the gate is answered as the board's writes answer theirs; the inner `Err` carries that answer. async fn gate( cx: &Cx, csrf: &str, next: &str, ) -> Result> { let state = app_context::(cx); let me = match writer(cx, csrf).await { Ok(me) => me, Err(stop) => { return Ok(Err( answer_stop(cx, stop, false, next, lang(cx, None)).await? )); } }; let language = lang(cx, me.member.locale_override.as_deref()); let board = the_board(&state.store).await?; Ok(Ok((me, language, board.id))) } /// The gate of a write that names its task in the path. async fn gate_task(cx: &Cx, form: &ModalForm, task_id: &str) -> Result> { let state = app_context::(cx); let (me, language, board_id) = match gate(cx, &form.csrf, &form.next).await? { Ok(found) => found, Err(response) => return Ok(Err(response)), }; let detail = state .store .task_detail(&board_id, task_id) .await .map_err(core_err)?; Ok(Ok(Begun { me, lang: language, board_id, detail, })) } /// Re-renders the board with the modal of `key` open, the refusal above its fields, and `422`. When the /// task is gone the board answers `404` with its "not found" notice. pub(crate) async fn refuse( cx: &Cx, me: &CurrentMember, language: Lang, next: &str, key: &str, draft: Draft, ) -> Result { let state = app_context::(cx); let query = query_of(safe_next(Some(next))); let mut page = load(&state.store, me, language, query).await?; let found = open(state, me, &mut page, key, query, draft).await?; let status = if found { StatusCode::UNPROCESSABLE_ENTITY } else { page.alert = Some(BK::TaskNotFound); StatusCode::NOT_FOUND }; render(cx, &page, Some(status)).await } /// A `Draft` that only shows a refusal. fn refusal(message: &'static str) -> Draft { Draft { error: Some(message), ..Draft::default() } } /// Tells every open view of the board and of the task that something changed. pub(crate) fn bump(state: &AppState, board_id: &str, task_id: &str) { state.live.bump(&Topic::Board(board_id.to_owned())); state.live.bump(&Topic::Task(task_id.to_owned())); } /// Answers a write that went through: the modal of `key` with the saved notice, or the board when there is /// no task to return to. pub(crate) fn back(next: &str, key: Option<&str>) -> Result { let target = match key { Some(key) => modal_url(query_of(safe_next(Some(next))), key, &[("notice", "saved")]), None => "/".to_owned(), }; Err(see_other(target).into()) } /// `POST /tasks/{id}/edit`: the title, description, project, deadline and meeting time. #[route(POST "/tasks/{id}/edit")] async fn edit_task(cx: &Cx, form: Option>) -> Result { let state = app_context::(cx); let form = form.map(|Form(form)| form).unwrap_or_default(); let task_id = path_param_segment(cx, "id").to_owned(); let begun = match gate_task(cx, &form, &task_id).await? { Ok(begun) => begun, Err(response) => return Ok(response), }; let key = begun.detail.task.key.clone(); let zone = zone_of(&begun.me); let tags = state.store.tags(&begun.board_id).await.map_err(core_err)?; let typed = EditValues { title: form.title.clone(), description: form.description.clone(), tag: form.tag.clone(), deadline: form.deadline.clone(), time: form.time.clone(), }; let edit = match edit_input(&form, &tags, &zone, begun.lang) { Ok(edit) => edit, Err(message) => { let draft = Draft { edit: Some(typed), ..refusal(message) }; return refuse(cx, &begun.me, begun.lang, &form.next, &key, draft).await; } }; match state .store .edit_task(&begun.board_id, &task_id, edit, &begun.me.member.sub) .await { Ok(_) => { bump(state, &begun.board_id, &task_id); back(&form.next, Some(key.as_str())) } Err(iz_core::Error::Invalid(_)) => { let draft = Draft { edit: Some(typed), ..refusal(bt(begun.lang, BK::InvalidForm)) }; refuse(cx, &begun.me, begun.lang, &form.next, &key, draft).await } Err(error) => Err(core_err(error)), } } /// `POST /tasks/{id}/assign`: adds one member. The store refuses anyone who is not an enabled admin or /// member. #[route(POST "/tasks/{id}/assign")] async fn assign(cx: &Cx, form: Option>) -> Result { let state = app_context::(cx); let form = form.map(|Form(form)| form).unwrap_or_default(); let task_id = path_param_segment(cx, "id").to_owned(); let begun = match gate_task(cx, &form, &task_id).await? { Ok(begun) => begun, Err(response) => return Ok(response), }; let key = begun.detail.task.key.clone(); let sub = form.sub.trim().to_owned(); if sub.is_empty() { return refuse( cx, &begun.me, begun.lang, &form.next, &key, refusal(t(begun.lang, K::ErrAssignee)), ) .await; } match state .store .assign( &begun.board_id, &task_id, std::slice::from_ref(&sub), &begun.me.member.sub, ) .await { Ok(()) => { bump(state, &begun.board_id, &task_id); state.live.bump(&Topic::Person(sub.clone())); back(&form.next, Some(key.as_str())) } Err(iz_core::Error::Invalid(_)) => { refuse( cx, &begun.me, begun.lang, &form.next, &key, refusal(t(begun.lang, K::ErrAssignee)), ) .await } Err(error) => Err(core_err(error)), } } /// `POST /tasks/{id}/unassign`: removes one member. Removing someone who is not assigned changes nothing. #[route(POST "/tasks/{id}/unassign")] async fn unassign(cx: &Cx, form: Option>) -> Result { let state = app_context::(cx); let form = form.map(|Form(form)| form).unwrap_or_default(); let task_id = path_param_segment(cx, "id").to_owned(); let begun = match gate_task(cx, &form, &task_id).await? { Ok(begun) => begun, Err(response) => return Ok(response), }; let key = begun.detail.task.key.clone(); state .store .unassign( &begun.board_id, &task_id, &[form.sub.trim().to_owned()], &begun.me.member.sub, ) .await .map_err(core_err)?; bump(state, &begun.board_id, &task_id); state.live.bump(&Topic::Person(form.sub.trim().to_owned())); back(&form.next, Some(key.as_str())) } /// `POST /tasks/{id}/watch`: starts (`on=1`) or stops (`on=0`) watching the task, for the viewer. #[route(POST "/tasks/{id}/watch")] async fn watch(cx: &Cx, form: Option>) -> Result { let state = app_context::(cx); let form = form.map(|Form(form)| form).unwrap_or_default(); let task_id = path_param_segment(cx, "id").to_owned(); let begun = match gate_task(cx, &form, &task_id).await? { Ok(begun) => begun, Err(response) => return Ok(response), }; let key = begun.detail.task.key.clone(); let on = match form.on.trim() { "1" => true, "0" => false, _ => { return refuse( cx, &begun.me, begun.lang, &form.next, &key, refusal(bt(begun.lang, BK::InvalidForm)), ) .await; } }; state .store .set_watch(&begun.board_id, &task_id, &begun.me.member.sub, on) .await .map_err(core_err)?; bump(state, &begun.board_id, &task_id); back(&form.next, Some(key.as_str())) } /// `POST /tasks/{id}/subtasks`: creates a subtask under this task, in its column and project. #[route(POST "/tasks/{id}/subtasks")] async fn add_subtask(cx: &Cx, form: Option>) -> Result { let state = app_context::(cx); let form = form.map(|Form(form)| form).unwrap_or_default(); let task_id = path_param_segment(cx, "id").to_owned(); let begun = match gate_task(cx, &form, &task_id).await? { Ok(begun) => begun, Err(response) => return Ok(response), }; let key = begun.detail.task.key.clone(); let title = form.title.trim().to_owned(); if title.is_empty() || title.chars().count() > TITLE_MAX { let message = t(begun.lang, K::ErrSubtaskTitle); return refuse( cx, &begun.me, begun.lang, &form.next, &key, refusal(message), ) .await; } if begun.detail.task.parent_id.is_some() { let message = t(begun.lang, K::ErrParent); return refuse( cx, &begun.me, begun.lang, &form.next, &key, refusal(message), ) .await; } let input = NewTask { title, description: String::new(), column_id: begun.detail.task.column_id.clone(), tag_id: begun.detail.task.tag_id.clone(), deadline: None, meeting_at: None, assignees: Vec::new(), parent_id: Some(task_id.clone()), link: None, }; match state .store .create_task(&begun.board_id, input, &begun.me.member.sub) .await { Ok(_) => { bump(state, &begun.board_id, &task_id); back(&form.next, Some(key.as_str())) } Err(iz_core::Error::Invalid(_)) => { let message = t(begun.lang, K::ErrParent); refuse( cx, &begun.me, begun.lang, &form.next, &key, refusal(message), ) .await } Err(error) => Err(core_err(error)), } } /// `POST /tasks/{id}/parent`: makes this task a subtask of `parent`, or a top-level task when `parent` is /// empty. One level only; the store refuses the rest. #[route(POST "/tasks/{id}/parent")] async fn set_parent(cx: &Cx, form: Option>) -> Result { let state = app_context::(cx); let form = form.map(|Form(form)| form).unwrap_or_default(); let task_id = path_param_segment(cx, "id").to_owned(); let begun = match gate_task(cx, &form, &task_id).await? { Ok(begun) => begun, Err(response) => return Ok(response), }; let key = begun.detail.task.key.clone(); let parent = form.parent.trim(); let parent = (!parent.is_empty()).then_some(parent); match state .store .set_parent(&begun.board_id, &task_id, parent, &begun.me.member.sub) .await { Ok(()) => { bump(state, &begun.board_id, &task_id); back(&form.next, Some(key.as_str())) } Err(iz_core::Error::Conflict(_)) => { let message = t(begun.lang, K::ErrParentHasChildren); refuse( cx, &begun.me, begun.lang, &form.next, &key, refusal(message), ) .await } Err(iz_core::Error::Invalid(_)) => { let message = t(begun.lang, K::ErrParent); refuse( cx, &begun.me, begun.lang, &form.next, &key, refusal(message), ) .await } Err(error) => Err(core_err(error)), } } /// `POST /tasks/{id}/links`: adds a dependency with `other`. A cycle is refused with its own message. #[route(POST "/tasks/{id}/links")] async fn add_link(cx: &Cx, form: Option>) -> Result { let state = app_context::(cx); let form = form.map(|Form(form)| form).unwrap_or_default(); let task_id = path_param_segment(cx, "id").to_owned(); let begun = match gate_task(cx, &form, &task_id).await? { Ok(begun) => begun, Err(response) => return Ok(response), }; let key = begun.detail.task.key.clone(); let other = form.other.trim().to_owned(); if other.is_empty() { let message = t(begun.lang, K::ErrOtherTask); return refuse( cx, &begun.me, begun.lang, &form.next, &key, refusal(message), ) .await; } let Some((blocked, blocking)) = link_pair(&task_id, &other, form.direction.trim()) else { let message = t(begun.lang, K::ErrDirection); return refuse( cx, &begun.me, begun.lang, &form.next, &key, refusal(message), ) .await; }; match state .store .add_dependency(&begun.board_id, blocked, blocking, &begun.me.member.sub) .await { Ok(()) => { bump(state, &begun.board_id, &task_id); state.live.bump(&Topic::Task(other.clone())); back(&form.next, Some(key.as_str())) } Err(iz_core::Error::Conflict(_)) => { let message = t(begun.lang, K::ErrCycle); refuse( cx, &begun.me, begun.lang, &form.next, &key, refusal(message), ) .await } Err(iz_core::Error::Invalid(_)) => { let message = t(begun.lang, K::ErrSelf); refuse( cx, &begun.me, begun.lang, &form.next, &key, refusal(message), ) .await } Err(iz_core::Error::NotFound) => { let message = t(begun.lang, K::ErrOtherTask); refuse( cx, &begun.me, begun.lang, &form.next, &key, refusal(message), ) .await } Err(error) => Err(core_err(error)), } } /// `POST /tasks/{id}/links/remove`: clears a dependency (a soft clear: the history stays). #[route(POST "/tasks/{id}/links/remove")] async fn remove_link(cx: &Cx, form: Option>) -> Result { let state = app_context::(cx); let form = form.map(|Form(form)| form).unwrap_or_default(); let task_id = path_param_segment(cx, "id").to_owned(); let begun = match gate_task(cx, &form, &task_id).await? { Ok(begun) => begun, Err(response) => return Ok(response), }; let key = begun.detail.task.key.clone(); let other = form.other.trim().to_owned(); let Some((blocked, blocking)) = link_pair(&task_id, &other, form.direction.trim()) else { let message = t(begun.lang, K::ErrDirection); return refuse( cx, &begun.me, begun.lang, &form.next, &key, refusal(message), ) .await; }; match state .store .clear_dependency(&begun.board_id, blocked, blocking, &begun.me.member.sub) .await { Ok(()) | Err(iz_core::Error::NotFound) => { bump(state, &begun.board_id, &task_id); state.live.bump(&Topic::Task(other.clone())); back(&form.next, Some(key.as_str())) } Err(error) => Err(core_err(error)), } } /// `POST /tasks/{id}/comments`: posts a comment on the task. #[route(POST "/tasks/{id}/comments")] async fn add_comment(cx: &Cx, form: Option>) -> Result { let state = app_context::(cx); let form = form.map(|Form(form)| form).unwrap_or_default(); let task_id = path_param_segment(cx, "id").to_owned(); let begun = match gate_task(cx, &form, &task_id).await? { Ok(begun) => begun, Err(response) => return Ok(response), }; let key = begun.detail.task.key.clone(); let body = form.body.trim().to_owned(); if body.is_empty() || body.chars().count() > COMMENT_MAX { let draft = Draft { comment: Some(form.body.clone()), ..refusal(t(begun.lang, K::ErrComment)) }; return refuse(cx, &begun.me, begun.lang, &form.next, &key, draft).await; } match state .store .add_comment(&begun.board_id, &task_id, &begun.me.member.sub, &body) .await { Ok(_) => { bump(state, &begun.board_id, &task_id); back(&form.next, Some(key.as_str())) } Err(error) => Err(core_err(error)), } } /// `POST /comments/{id}/edit`: edits a comment. Only its author may, and only while a member. The comment /// is checked by its own id (live, on this board, its task live), then by `authz`. #[route(POST "/comments/{id}/edit")] async fn edit_comment(cx: &Cx, form: Option>) -> Result { let state = app_context::(cx); let form = form.map(|Form(form)| form).unwrap_or_default(); let comment_id = path_param_segment(cx, "id").to_owned(); let (me, language, board_id) = match gate(cx, &form.csrf, &form.next).await? { Ok(found) => found, Err(response) => return Ok(response), }; let key = task_of(&form.next); let body = form.body.trim().to_owned(); if body.is_empty() || body.chars().count() > COMMENT_MAX { let Some(key) = key else { return Err(not_found().into()); }; let draft = Draft { comment: Some(form.body.clone()), ..refusal(t(language, K::ErrComment)) }; return refuse(cx, &me, language, &form.next, &key, draft).await; } match state .store .edit_comment(&board_id, &comment_id, &me.actor(), &body) .await { Ok(comment) => { bump(state, &board_id, &comment.task_id); back(&form.next, key.as_deref()) } Err(error) => Err(core_err(error)), } } /// `POST /comments/{id}/delete`: deletes a comment. Its author (while a member) or an admin may. #[route(POST "/comments/{id}/delete")] async fn delete_comment(cx: &Cx, form: Option>) -> Result { let state = app_context::(cx); let form = form.map(|Form(form)| form).unwrap_or_default(); let comment_id = path_param_segment(cx, "id").to_owned(); let (me, _language, board_id) = match gate(cx, &form.csrf, &form.next).await? { Ok(found) => found, Err(response) => return Ok(response), }; let key = task_of(&form.next); match state .store .delete_comment(&board_id, &comment_id, &me.actor()) .await { Ok(task_id) => { bump(state, &board_id, &task_id); back(&form.next, key.as_deref()) } Err(error) => Err(core_err(error)), } } #[cfg(test)] mod tests { use super::*; #[test] fn modal_url_keeps_filters_and_drops_the_rest() { assert_eq!( modal_url(Some("tag=a b&confirm=delete&sort=title&q=x"), "IZ-4", &[]), "/?tag=a%20b&sort=title&q=x&task=IZ-4" ); assert_eq!( modal_url(None, "IZ-4", &[("before", "2026~01")]), "/?task=IZ-4&before=2026~01" ); } #[test] fn clock_text_is_hours_and_minutes() { assert_eq!(parse_clock("09:30"), Some((9, 30))); assert_eq!(parse_clock("9:30"), Some((9, 30))); assert_eq!(parse_clock("24:00"), None); assert_eq!(parse_clock("09:60"), None); assert_eq!(parse_clock("0930"), None); } #[test] fn a_dependency_names_its_blocked_and_blocking_side() { assert_eq!(link_pair("a", "b", "blocked_by"), Some(("a", "b"))); assert_eq!(link_pair("a", "b", "blocks"), Some(("b", "a"))); assert_eq!(link_pair("a", "b", "other"), None); } #[test] fn a_return_path_names_its_task_only_when_local() { assert_eq!(task_of("/?task=IZ-4&tag=x").as_deref(), Some("IZ-4")); assert_eq!(task_of("//evil.example/?task=IZ-4"), None); } } #[cfg(test)] mod render_tests { use http::header::{CONTENT_TYPE, COOKIE}; use iz_core::authz::Role; use iz_core::store::tasks::{NewTask, TaskEdit}; use topcoat::router::{Body, to_bytes}; use super::*; use crate::boot::{router, test_state}; use crate::pages::board::{cookie_of, one_card, sign_in_as}; use crate::state::AppState; const AUTHOR: &str = "01ADAAAAAAAAAAAAAAAAAAAAAA"; const OTHER: &str = "01BOAAAAAAAAAAAAAAAAAAAAAA"; const VIEWER: &str = "01VIAAAAAAAAAAAAAAAAAAAAAA"; /// Sends one request and returns its status and body as text. async fn send(state: &AppState, request: http::Request) -> (u16, String) { let response = router(state.clone()).handle(request).await; let status = response.status().as_u16(); let bytes = to_bytes(response.into_body(), 1024 * 1024) .await .expect("body"); (status, String::from_utf8_lossy(&bytes).into_owned()) } /// A form POST with the session's cookie. fn post(path: &str, token: &str, body: String) -> http::Request { http::Request::post(path) .header(CONTENT_TYPE, "application/x-www-form-urlencoded") .header(COOKIE, cookie_of(token)) .body(Body::from(body)) .expect("request") } /// A GET with the session's cookie. fn get(path: &str, token: &str) -> http::Request { http::Request::get(path) .header(COOKIE, cookie_of(token)) .body(Body::empty()) .expect("request") } /// The key of a task, read through the store. async fn key_of(state: &AppState, task_id: &str) -> String { let board = state.store.board().await.expect("board").expect("some"); state .store .task_detail(&board.id, task_id) .await .expect("detail") .task .key } /// The modal URL of a task, as a form carries it. fn next_of(key: &str) -> String { percent_encode(&modal_url(None, key, &[])) } /// A viewer's comment is refused with `403`, and nothing is stored. #[tokio::test] async fn a_viewer_cannot_comment() { let (_dir, state) = test_state().await; sign_in_as(&state, AUTHOR, Role::Member).await; let (task_id, _) = one_card(&state, "Milk", AUTHOR).await; let (token, csrf) = sign_in_as(&state, VIEWER, Role::Viewer).await; let key = key_of(&state, &task_id).await; let body = format!("csrf={csrf}&next={}&body=hello", next_of(&key)); let (status, _) = send( &state, post(&format!("/tasks/{task_id}/comments"), &token, body), ) .await; assert_eq!(status, 403); let board = state.store.board().await.expect("board").expect("some"); let comments = state .store .list_comments(&board.id, &task_id) .await .expect("comments"); assert!(comments.is_empty()); } /// Another member cannot edit someone else's comment: `403`, and the body stays as it was. #[tokio::test] async fn another_member_cannot_edit_a_comment() { let (_dir, state) = test_state().await; sign_in_as(&state, AUTHOR, Role::Member).await; sign_in_as(&state, OTHER, Role::Member).await; let (task_id, _) = one_card(&state, "Milk", AUTHOR).await; let board = state.store.board().await.expect("board").expect("some"); let comment = state .store .add_comment(&board.id, &task_id, AUTHOR, "mine") .await .expect("comment"); let (token, csrf) = sign_in_as(&state, OTHER, Role::Member).await; let key = key_of(&state, &task_id).await; let body = format!("csrf={csrf}&next={}&body=changed", next_of(&key)); let (status, _) = send( &state, post(&format!("/comments/{}/edit", comment.id), &token, body), ) .await; assert_eq!(status, 403); let comments = state .store .list_comments(&board.id, &task_id) .await .expect("comments"); assert_eq!(comments[0].body, "mine"); } /// A comment of a deleted task is not found, for edit and for delete. #[tokio::test] async fn a_comment_of_a_deleted_task_is_not_found() { let (_dir, state) = test_state().await; sign_in_as(&state, AUTHOR, Role::Member).await; let (task_id, _) = one_card(&state, "Milk", AUTHOR).await; let board = state.store.board().await.expect("board").expect("some"); let comment = state .store .add_comment(&board.id, &task_id, AUTHOR, "old") .await .expect("comment"); state .store .delete_task(&board.id, &task_id, AUTHOR) .await .expect("delete"); let (token, csrf) = sign_in_as(&state, AUTHOR, Role::Member).await; let body = format!("csrf={csrf}&next=%2F&body=again"); let (status, _) = send( &state, post(&format!("/comments/{}/edit", comment.id), &token, body), ) .await; assert_eq!(status, 404); let body = format!("csrf={csrf}&next=%2F"); let (status, _) = send( &state, post(&format!("/comments/{}/delete", comment.id), &token, body), ) .await; assert_eq!(status, 404); } /// A description with markup and a `javascript:` address reaches the page as text. Only the https /// address becomes a link. #[tokio::test] async fn a_description_is_plain_text_with_safe_links() { let (_dir, state) = test_state().await; let (token, _) = sign_in_as(&state, AUTHOR, Role::Member).await; let (task_id, _) = one_card(&state, "Milk", AUTHOR).await; let board = state.store.board().await.expect("board").expect("some"); let tags = state.store.tags(&board.id).await.expect("tags"); let description = "\njavascript:alert(1) \ https://ok.example/a?b=1. bold"; state .store .edit_task( &board.id, &task_id, TaskEdit { title: "Milk".into(), description: description.into(), tag_id: tags[0].id.clone(), deadline: None, meeting_at: None, }, AUTHOR, ) .await .expect("edit"); let key = key_of(&state, &task_id).await; let (status, html) = send(&state, get(&format!("/?task={key}"), &token)).await; assert_eq!(status, 200); assert!( html.contains("<img src=x onerror=alert(1)>"), "not escaped" ); assert!(!html.contains("bold"), "markup reached the page"); assert!(!html.contains("href=\"javascript"), "javascript link"); assert!( html.contains("href=\"https://ok.example/a?b=1\""), "https address not linked" ); } /// A dependency that closes a cycle is refused with `422` and its translated message. #[tokio::test] async fn a_dependency_cycle_is_refused_with_a_message() { let (_dir, state) = test_state().await; let (token, csrf) = sign_in_as(&state, AUTHOR, Role::Member).await; let (first, column) = one_card(&state, "First", AUTHOR).await; let board = state.store.board().await.expect("board").expect("some"); let tags = state.store.tags(&board.id).await.expect("tags"); let second = state .store .create_task( &board.id, NewTask { title: "Second".into(), description: String::new(), column_id: column, tag_id: tags[0].id.clone(), deadline: None, meeting_at: None, assignees: Vec::new(), parent_id: None, link: None, }, AUTHOR, ) .await .expect("second task") .id; state .store .add_dependency(&board.id, &first, &second, AUTHOR) .await .expect("first link"); let key = key_of(&state, &second).await; let body = format!( "csrf={csrf}&next={}&other={first}&direction=blocked_by", next_of(&key) ); let (status, html) = send( &state, post(&format!("/tasks/{second}/links"), &token, body), ) .await; assert_eq!(status, 422); assert!( html.contains(t(Lang::En, K::ErrCycle)), "cycle message missing: {html}" ); } /// An unknown task key answers the board with its notice and `404`. #[tokio::test] async fn an_unknown_task_key_is_not_found() { let (_dir, state) = test_state().await; let (token, _) = sign_in_as(&state, AUTHOR, Role::Member).await; state.store.ensure_board("IZ").await.expect("board"); let (status, html) = send(&state, get("/?task=IZ-999", &token)).await; assert_eq!(status, 404); assert!(html.contains(crate::i18n::board::t( Lang::En, crate::i18n::board::K::TaskNotFound ))); } }