1use std::time::Duration;
21
22use axum::http::StatusCode;
23use axum::response::{IntoResponse, Response};
24use axum::Json;
25use serde_json::json;
26use zeroize::Zeroizing;
27
28use crate::backend::vault::signins::Space;
29use crate::backend::vault::uses::{Ended, UseRequest};
30use crate::backend::vault::{changes, Line};
31
32use super::browser_actions::{note, How, Kind};
33use super::browser_signup::Field;
34use super::ui_handlers::err_response;
35use super::AppState;
36
37const ANSWER_WAIT: Duration = Duration::from_secs(10 * 60);
38#[cfg(not(test))]
39const NOTICE: Duration = Duration::from_secs(10);
40#[cfg(test)]
41const NOTICE: Duration = Duration::from_millis(150);
42const HOST_WAIT: Duration = Duration::from_secs(20);
43const ASKED: &str = "asked to change the password";
45const FILLED: &str = "filled on password change";
46const DETAIL: &str = "a changed password";
48const BUSY: &str = "another notice is showing on this pane: no password was made; try again when it is done";
49
50pub(crate) struct Asked<'a> {
52 pub block_id: &'a str,
53 pub agent: &'a str,
54 pub agent_id: &'a str,
55 pub pane: Option<&'a str>,
56 pub agent_pane: String,
57 pub reason: &'a str,
58 pub profile: String,
59 pub incognito: bool,
60 pub field: Field,
62}
63
64fn use_request(a: &Asked<'_>, origin: &str) -> UseRequest {
65 UseRequest {
66 agent_reason: a.reason.to_string(),
67 id: uuid::Uuid::new_v4().to_string(),
68 agent: a.agent.to_string(),
69 block_id: a.agent_pane.clone(),
70 entry_label: format!("your password on {origin}"),
71 what: "password change".to_string(),
72 origin: origin.to_string(),
73 offer_always: false,
75 reason: "a changed password stops the old one working on the site; the Vault keeps the old one for 7 days".to_string(),
76 kind: "login".to_string(),
77 account: true,
79 change: true,
80 requested_ms: agentmux_common::time::now_ms_u64(),
81 ..Default::default()
82 }
83}
84
85fn line(state: &AppState, entry: &str, label: &str, a: &Asked<'_>, action: &str, outcome: &str) {
87 let l = Line { entry_id: entry, label, actor: a.agent, action, target: &a.field.origin, outcome, reason: a.reason };
88 crate::backend::vault::record_line(&state.identity_store, l);
89 super::vault_handlers::publish(state);
90}
91
92fn refuse(state: &AppState, a: &Asked<'_>, why: String) -> Response {
93 note(a.block_id, a.agent, Kind::Fill).detail(DETAIL).how(How::Refused(why.clone())).record(state);
94 err_response(StatusCode::BAD_REQUEST, why)
95}
96
97pub(crate) async fn handle(state: &AppState, a: Asked<'_>) -> Response {
99 let origin = a.field.origin.clone();
100 if a.incognito {
101 return refuse(state, &a, format!("this is an Incognito tab, which keeps no sign-ins, so there is no saved password for {origin} to change: ask the person"));
102 }
103 if !super::browser_signin_fill::fillable(&origin) {
104 return refuse(state, &a, format!("{origin} isn't https, so no password was made for it"));
105 }
106 if let Err(e) = super::browser_signup::new_password(&a.field) {
108 return refuse(state, &a, e);
109 }
110 let space = Space { profile: a.profile.clone(), origin: origin.clone(), realm: String::new(), proxy: false };
111 let (store, who, user) = (state.identity_store.clone(), a.agent.to_string(), a.field.username.clone());
112 let sp = space.clone();
113 let saved = match tokio::task::spawn_blocking(move || changes::saved_login(&store, &sp, &user, &who)).await {
114 Ok(Ok(row)) => row,
115 Ok(Err(e)) => return refuse(state, &a, e),
116 Err(e) => return refuse(state, &a, e.to_string()),
117 };
118 tracing::info!(agent = %a.agent, block_id = %a.block_id, origin = %origin, "[change] an agent asked to change a saved password");
119 if let Err((ended, code, how, why)) = approve(state, &a, &origin).await {
120 line(state, &saved.id, &saved.label, &a, ASKED, ended.outcome());
121 note(a.block_id, a.agent, Kind::Fill).detail(DETAIL).how(how).record(state);
122 return err_response(code, why);
123 }
124 match super::browser_signin::notice(state, a.block_id, a.agent, &origin, &a.field.username, "change", NOTICE).await {
125 Some(true) => {}
126 Some(false) => {
127 line(state, &saved.id, &saved.label, &a, ASKED, "stopped");
128 note(a.block_id, a.agent, Kind::Fill).detail(DETAIL).how(How::Declined).record(state);
129 return err_response(StatusCode::FORBIDDEN, "the person stopped it: no password was made".to_string());
130 }
131 None => return refuse(state, &a, BUSY.to_string()),
132 }
133 if let Err((code, e)) = super::browser_signin::still_allowed(state, a.agent_id, a.pane, a.block_id) {
134 note(a.block_id, a.agent, Kind::Fill).detail(DETAIL).how(How::Refused(e.clone())).record(state);
135 return err_response(code, e);
136 }
137 match make(state, &a, &saved).await {
138 Ok(()) => {
139 note(a.block_id, a.agent, Kind::Fill).detail(DETAIL).how(How::Allowed).record(state);
140 let out = json!({
141 "entry": saved.id,
142 "site": origin,
143 "profile": a.profile,
144 "password": "[secret: hidden]",
145 "kept": "the saved password stays the one that works until the form is sent with the new one; the old one is then kept 7 days",
146 });
147 (StatusCode::OK, Json(json!({ "ok": true, "data": out }))).into_response()
148 }
149 Err(e) => {
150 note(a.block_id, a.agent, Kind::Fill).detail(DETAIL).how(How::Refused(e.clone())).record(state);
151 err_response(StatusCode::BAD_GATEWAY, e)
152 }
153 }
154}
155
156async fn approve(state: &AppState, a: &Asked<'_>, origin: &str) -> Result<(), (Ended, StatusCode, How, String)> {
158 let headline = format!("{} wants to change your password on {origin}", a.agent);
159 let (ended, _) = super::vault_ask::ask(state, a.block_id, use_request(a, origin), ANSWER_WAIT, &headline).await;
160 match ended {
161 Ended::Once => Ok(()),
162 other => Err(super::browser_account::not_allowed(other, "an agent changes a password")),
163 }
164}
165
166async fn make(state: &AppState, a: &Asked<'_>, saved: &crate::backend::storage::vault::VaultRow) -> Result<(), String> {
168 let password = super::browser_signup::new_password(&a.field)?;
169 let (store, row, value, who) = (state.identity_store.clone(), saved.clone(), password.clone(), a.agent.to_string());
170 let change = tokio::task::spawn_blocking(move || changes::start(&store, &row, &value, &who)).await.map_err(|e| e.to_string())??;
171 let body = json!({ "block_id": a.block_id, "origin": a.field.origin, "field": a.field.field, "password": password.as_str() });
172 let filled = super::ui_handlers::proxy_value(state, "signup_fill", body, HOST_WAIT).await;
173 drop(password);
174 match filled {
175 Ok(_) => {
176 line(state, &saved.id, &saved.label, a, FILLED, "done");
177 Ok(())
178 }
179 Err((_, e)) => {
180 let store = state.identity_store.clone();
182 if let Err(e) = tokio::task::spawn_blocking(move || changes::abandon(&store, &change)).await.map_err(|e| e.to_string()).and_then(|r| r) {
183 tracing::warn!(error = %e, "[change] couldn't drop a password change that was never typed");
184 }
185 line(state, &saved.id, &saved.label, a, FILLED, "failed");
186 Err(format!("the password wasn't typed, so none was kept: {e}"))
187 }
188 }
189}
190
191pub(crate) fn sent(state: &AppState, block_id: &str, origin: &str, username: Zeroizing<String>, password: Zeroizing<String>) {
195 if let Some(profile) = super::browser_signin_offer::profile_of(state, block_id) {
196 let space = Space { profile, origin: origin.to_string(), realm: String::new(), proxy: false };
197 match changes::confirm_sent(&state.identity_store, &space, &password) {
198 Ok(Some(_)) => {
199 super::vault_handlers::publish(state);
200 return;
201 }
202 Ok(None) => {}
203 Err(e) => tracing::warn!(error = %e, "[change] couldn't confirm the changed password"),
204 }
205 }
206 super::browser_signin_offer::offer(state, block_id, origin, username, Some(password));
207}