Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
65 changes: 60 additions & 5 deletions src/app/form.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,46 @@
use crate::config::{AuthMethod, JumpHop, Profile, profile_name_is_path_safe, profile_names_equal};
use crate::config::{
AuthMethod, JumpHop, Profile, ProfileHop, profile_name_is_path_safe, profile_names_equal,
};

use super::{
AuthDraft, DEFAULT_PORT, FormField, KeySource, ProfileDraft, SaveMode,
AuthDraft, DEFAULT_PORT, FormField, JumpChoice, KeySource, ProfileDraft, SaveMode,
helpers::{parse_endpoint_shorthand, parse_jump_chain, path_to_string},
};

impl JumpChoice {
/// Read the selector back from a saved chain.
fn from_chain(chain: &[JumpHop]) -> Self {
match chain {
[] => Self::Direct,
[JumpHop::Profile(reference)] => Self::Profile(reference.profile_id.clone()),
_ => Self::Custom,
}
}

/// Every choice the selector offers for the given saved profiles.
pub(super) fn options(profiles: &[Profile]) -> Vec<Self> {
let mut options = vec![Self::Direct];
options.extend(
profiles
.iter()
.map(|profile| Self::Profile(profile.id.clone())),
);
options.push(Self::Custom);
options
}

/// Move `delta` steps through `options`, wrapping at both ends.
pub(super) fn cycle(&mut self, profiles: &[Profile], delta: i32) {
let options = Self::options(profiles);
let index = options
.iter()
.position(|option| option == self)
.unwrap_or(0);
let next = (index as i32 + delta).rem_euclid(options.len() as i32) as usize;
*self = options[next].clone();
}
}

impl AuthDraft {
fn from_auth(auth: &AuthMethod) -> Self {
match auth {
Expand Down Expand Up @@ -33,6 +69,7 @@ pub struct FormState {
pub port: String,
pub username: String,
pub jump_chain: Vec<JumpHop>,
pub jump: JumpChoice,
pub auth: AuthDraft,
pub field: FormField,
pub cursor: usize,
Expand All @@ -54,6 +91,7 @@ impl std::fmt::Debug for FormState {
.field("port", &self.port)
.field("username", &self.username)
.field("jump_chain", &self.jump_chain)
.field("jump", &self.jump)
.field("auth", &self.auth)
.field("field", &self.field)
.field("cursor", &self.cursor)
Expand All @@ -74,6 +112,7 @@ impl FormState {
port: DEFAULT_PORT.to_string(),
username: "root".to_owned(),
jump_chain: Vec::new(),
jump: JumpChoice::Direct,
auth: AuthDraft::Password {
password: String::new(),
},
Expand Down Expand Up @@ -103,6 +142,7 @@ impl FormState {
port: profile.port.to_string(),
username: profile.username.clone(),
jump_chain: profile.jump_chain.clone(),
jump: JumpChoice::from_chain(&profile.jump_chain),
auth,
field: FormField::Name,
cursor: profile.name.chars().count(),
Expand All @@ -118,6 +158,7 @@ impl FormState {
FormField::Username,
FormField::Host,
FormField::Port,
FormField::Jump,
FormField::Authentication,
];
match &self.auth {
Expand Down Expand Up @@ -164,7 +205,10 @@ impl FormState {
AuthDraft::Key { public_key, .. } => public_key.as_deref(),
_ => None,
},
FormField::Authentication | FormField::ShowPassword | FormField::KeySource => None,
FormField::Jump
| FormField::Authentication
| FormField::ShowPassword
| FormField::KeySource => None,
}
}

Expand All @@ -191,7 +235,10 @@ impl FormState {
}
_ => None,
},
FormField::Authentication | FormField::ShowPassword | FormField::KeySource => None,
FormField::Jump
| FormField::Authentication
| FormField::ShowPassword
| FormField::KeySource => None,
}
}

Expand Down Expand Up @@ -289,9 +336,17 @@ impl FormState {
return Err("Port must be a number between 1 and 65535".into());
}

// A chain pasted into the Host field is explicit input, so it wins
// over whatever the jump selector happens to show.
let jump_chain = match jump_from_host {
Some(spec) => parse_jump_chain(&spec)?,
None => self.jump_chain.clone(),
None => match &self.jump {
JumpChoice::Direct => Vec::new(),
JumpChoice::Profile(profile_id) => vec![JumpHop::Profile(ProfileHop {
profile_id: profile_id.clone(),
})],
JumpChoice::Custom => self.jump_chain.clone(),
},
};

let auth = match &self.auth {
Expand Down
11 changes: 11 additions & 0 deletions src/app/input/form.rs
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,17 @@ impl App {
}
_ => {}
},
Some(FormField::Jump) => match key.code {
KeyCode::Left => {
self.cycle_jump(-1);
return AppAction::None;
}
KeyCode::Right | KeyCode::Char(' ') => {
self.cycle_jump(1);
return AppAction::None;
}
_ => {}
},
Some(FormField::KeySource) => match key.code {
KeyCode::Left => {
self.cycle_key_source(-1);
Expand Down
7 changes: 7 additions & 0 deletions src/app/input/keys.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,13 @@ impl App {
}
}

pub(super) fn cycle_jump(&mut self, delta: i32) {
let profiles = self.profiles.clone();
if let Some(form) = self.form.as_mut() {
form.jump.cycle(&profiles, delta);
}
}

pub(crate) fn ensure_existing_key_selected(&mut self) {
let first = self.available_keys.first().cloned();
let Some(form) = self.form.as_mut() else {
Expand Down
4 changes: 2 additions & 2 deletions src/app/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,8 @@ pub use form::FormState;
pub use mouse::{MouseRegions, MouseTarget};
pub use state::App;
pub use types::{
AppAction, AuthDraft, DEFAULT_PORT, FormField, KeyChoice, KeySource, ProfileDraft, SaveMode,
Screen,
AppAction, AuthDraft, DEFAULT_PORT, FormField, JumpChoice, KeyChoice, KeySource, ProfileDraft,
SaveMode, Screen,
};

#[cfg(test)]
Expand Down
141 changes: 140 additions & 1 deletion src/app/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ use crossterm::event::{
Event, KeyCode, KeyEvent, KeyModifiers, MouseButton, MouseEvent, MouseEventKind,
};

use crate::config::{AuthMethod, JumpHop, Profile};
use crate::config::{AuthMethod, JumpHop, Profile, ProfileHop};

use super::*;

Expand Down Expand Up @@ -773,6 +773,145 @@ fn multi_hop_paste_rejects_an_empty_hop() {
);
}

#[test]
fn jump_selector_cycles_through_direct_saved_profiles_and_custom() {
let mut app = App::new(vec![profile("1", "Bastion"), profile("2", "Edge")]);
app.begin_add();
let form = app.form_mut().unwrap();
form.field = FormField::Jump;

let mut seen = vec![format!("{:?}", form.jump.clone())];
for _ in 0..3 {
app.handle_key(key(KeyCode::Right, KeyModifiers::NONE));
seen.push(format!("{:?}", app.form().unwrap().jump.clone()));
}

assert_eq!(
seen,
vec![
"Direct".to_owned(),
r#"Profile("1")"#.to_owned(),
r#"Profile("2")"#.to_owned(),
"Custom".to_owned(),
]
);

app.handle_key(key(KeyCode::Left, KeyModifiers::NONE));
assert_eq!(app.form().unwrap().jump, JumpChoice::Profile("2".into()));
}

#[test]
fn choosing_a_saved_profile_saves_it_as_the_only_hop() {
let mut app = App::new(vec![profile("1", "Bastion")]);
app.begin_add();
{
let form = app.form_mut().unwrap();
form.name = "Target".into();
form.host = "10.77.0.2".into();
form.jump = JumpChoice::Profile("1".into());
form.auth = AuthDraft::Password {
password: "secret".into(),
};
}

let action = app.handle_key(key(KeyCode::Enter, KeyModifiers::NONE));

assert!(matches!(
action,
AppAction::Save(ProfileDraft { jump_chain, .. })
if jump_chain == vec![JumpHop::Profile(ProfileHop { profile_id: "1".into() })]
));
}

#[test]
fn choosing_direct_clears_a_saved_chain() {
let mut existing = profile("1", "Target");
existing.jump_chain = vec![JumpHop::endpoint(
Some("root".into()),
"124.222.134.112",
22,
)];
let mut app = App::new(vec![existing]);
app.begin_edit();
app.form_mut().unwrap().jump = JumpChoice::Direct;

let draft = app.form().unwrap().draft(app.profiles()).unwrap();

assert!(draft.jump_chain.is_empty());
}

#[test]
fn pasted_jump_chain_still_wins_over_the_selector() {
let mut app = App::new(vec![profile("1", "Bastion")]);
app.begin_add();
{
let form = app.form_mut().unwrap();
form.name = "Target".into();
form.host = "ssh -J root@jump-a,root@jump-b root@10.77.0.2".into();
form.jump = JumpChoice::Direct;
form.auth = AuthDraft::Password {
password: "secret".into(),
};
}

let action = app.handle_key(key(KeyCode::Enter, KeyModifiers::NONE));

assert!(matches!(
action,
AppAction::Save(ProfileDraft { jump_chain, .. }) if jump_chain.len() == 2
));
}

#[test]
fn editing_a_profile_backed_hop_selects_that_profile() {
let target = {
let mut target = profile("2", "Target");
target.jump_chain = vec![JumpHop::Profile(ProfileHop {
profile_id: "1".into(),
})];
target
};
let mut app = App::new(vec![profile("1", "Bastion"), target]);
app.select(1);
app.begin_edit();

assert_eq!(app.form().unwrap().jump, JumpChoice::Profile("1".into()));
assert_eq!(
app.form()
.unwrap()
.draft(app.profiles())
.unwrap()
.jump_chain,
vec![JumpHop::Profile(ProfileHop {
profile_id: "1".into()
})]
);
}

#[test]
fn editing_a_pasted_chain_keeps_the_custom_choice() {
let mut existing = profile("1", "Target");
existing.jump_chain = vec![
JumpHop::endpoint(Some("root".into()), "jump-a", 22),
JumpHop::endpoint(Some("root".into()), "jump-b", 2222),
];
let mut app = App::new(vec![existing]);
app.begin_edit();

assert_eq!(app.form().unwrap().jump, JumpChoice::Custom);
assert_eq!(
app.form()
.unwrap()
.draft(app.profiles())
.unwrap()
.jump_chain,
vec![
JumpHop::endpoint(Some("root".into()), "jump-a", 22),
JumpHop::endpoint(Some("root".into()), "jump-b", 2222),
]
);
}

#[test]
fn editing_profile_keeps_the_whole_multi_hop_chain() {
let mut existing = profile("1", "one");
Expand Down
12 changes: 12 additions & 0 deletions src/app/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -134,6 +134,7 @@ pub enum FormField {
Host,
Port,
Username,
Jump,
Authentication,
Password,
ShowPassword,
Expand All @@ -142,6 +143,17 @@ pub enum FormField {
PublicKey,
}

/// What the form's jump field selects.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum JumpChoice {
/// No jump host.
Direct,
/// Use another saved profile as the only hop.
Profile(String),
/// Keep the chain pasted into the Host field, or the one already saved.
Custom,
}

impl FormField {
pub(super) fn is_text(self) -> bool {
matches!(
Expand Down
Loading
Loading