-
Notifications
You must be signed in to change notification settings - Fork 169
feat: Add support for SSH agents in addition to raw keyfiles #901
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
KazWolfe
wants to merge
8
commits into
railwayapp:master
Choose a base branch
from
KazWolfe:ssh-agent-support
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+139
−71
Open
Changes from all commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
248c18d
feat: Add support for SSH agents as well as raw file scans
KazWolfe 6e02d25
chore: apply lint, fix some messaging
KazWolfe 1e46f4f
fix: handle ssh-add not returning any keys
KazWolfe 6a1ceec
feat: allow adding agent keys via fingerprint or comment
KazWolfe 5f142af
fix: handle empty comment case *correctly*, catch file stem problems
KazWolfe 6b703ea
fix: more pr comments.
KazWolfe 6f15d76
fix: restrict file browser to just using file keys for now
KazWolfe c19798d
fix: filter unsupported keys from the agent
KazWolfe File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,5 +1,6 @@ | ||
| use anyhow::{Context, Result, bail}; | ||
| use reqwest::Client; | ||
| use std::borrow::Cow; | ||
| use std::path::{Path, PathBuf}; | ||
| use std::process::Command; | ||
|
|
||
|
|
@@ -14,10 +15,31 @@ use crate::gql::queries::{GitHubSshKeys, SshPublicKeys, git_hub_ssh_keys, ssh_pu | |
| /// Local SSH key info | ||
| #[derive(Debug, Clone)] | ||
| pub struct LocalSshKey { | ||
| pub path: PathBuf, | ||
| pub path: Option<PathBuf>, | ||
| pub public_key: String, | ||
| pub fingerprint: String, | ||
| pub key_type: String, | ||
| pub key_comment: Option<String>, | ||
| } | ||
|
|
||
| impl LocalSshKey { | ||
| pub fn key_name(&self) -> Cow<'_, str> { | ||
| match (self.key_comment.as_ref(), self.path.as_ref()) { | ||
| (Some(comment), _) => comment.into(), | ||
| (_, Some(path)) => path | ||
| .file_stem() | ||
| .map(|stem| stem.to_string_lossy()) | ||
| .unwrap_or_else(|| (&self.fingerprint).into()), | ||
| (None, None) => (&self.fingerprint).into(), | ||
| } | ||
| } | ||
|
KazWolfe marked this conversation as resolved.
|
||
|
|
||
| pub fn key_source(&self) -> Cow<'_, str> { | ||
| self.path | ||
| .as_ref() | ||
| .map(|p| p.to_string_lossy()) | ||
| .unwrap_or_else(|| "SSH Agent".into()) | ||
| } | ||
| } | ||
|
|
||
| /// Supported SSH key types (in order of preference) | ||
|
|
@@ -30,8 +52,29 @@ const SUPPORTED_KEY_TYPES: &[&str] = &[ | |
| "ssh-dss", | ||
| ]; | ||
|
|
||
| /// Find local SSH keys by scanning ~/.ssh/ for .pub files | ||
| pub fn find_local_ssh_keys() -> Result<Vec<LocalSshKey>> { | ||
| let mut seen = std::collections::HashMap::new(); | ||
| for key in fetch_keys_from_ssh_agent()? { | ||
| seen.entry(key.fingerprint.clone()).or_insert(key); | ||
| } | ||
|
|
||
| for key in find_ssh_key_files()? { | ||
| seen.entry(key.fingerprint.clone()).or_insert(key); | ||
| } | ||
|
|
||
| let mut keys = seen.into_values().collect::<Vec<_>>(); | ||
| keys.sort_by_key(|k| { | ||
| SUPPORTED_KEY_TYPES | ||
| .iter() | ||
| .position(|t| k.key_type.starts_with(t)) | ||
| .unwrap_or(usize::MAX) | ||
| }); | ||
|
|
||
| Ok(keys) | ||
| } | ||
|
|
||
| /// Find local SSH keys by scanning ~/.ssh/ for .pub files | ||
| pub fn find_ssh_key_files() -> Result<Vec<LocalSshKey>> { | ||
| let home = dirs::home_dir().context("Could not find home directory")?; | ||
| let ssh_dir = home.join(".ssh"); | ||
|
|
||
|
|
@@ -59,17 +102,46 @@ pub fn find_local_ssh_keys() -> Result<Vec<LocalSshKey>> { | |
| } | ||
| } | ||
|
|
||
| // Sort by key type preference (ed25519 first, then ecdsa, then rsa, then dss) | ||
| keys.sort_by_key(|k| { | ||
| SUPPORTED_KEY_TYPES | ||
| .iter() | ||
| .position(|t| k.key_type.starts_with(t)) | ||
| .unwrap_or(usize::MAX) | ||
| }); | ||
|
|
||
| Ok(keys) | ||
| } | ||
|
|
||
| // Pull SSH keys from the agent directly. | ||
| pub fn fetch_keys_from_ssh_agent() -> Result<Vec<LocalSshKey>> { | ||
| let output = match Command::new("ssh-add").arg("-L").output() { | ||
| Ok(output) => output, | ||
| Err(_) => return Ok(vec![]), | ||
| }; | ||
|
|
||
| if !output.status.success() { | ||
| // If we successfully run but can't find keys, it's probably best to just pretend like the | ||
| // SSH agent doesn't exist at all. | ||
|
|
||
| return Ok(vec![]); | ||
| } | ||
|
|
||
| String::from_utf8_lossy(&output.stdout) | ||
| .split("\n") | ||
| .filter(|s| !s.is_empty()) | ||
| .filter(|s| SUPPORTED_KEY_TYPES.iter().any(|kt| s.starts_with(kt))) | ||
| .map(|s| { | ||
| let parts: Vec<_> = s.split_whitespace().collect(); | ||
| let fingerprint = compute_fingerprint_from_pubkey(s)?; | ||
| let key_comment = parts | ||
| .get(2..) | ||
| .map(|p| p.join(" ")) | ||
| .filter(|s| !s.is_empty()); | ||
|
|
||
| Ok(LocalSshKey { | ||
| path: None, | ||
| public_key: s.trim().to_string(), | ||
| fingerprint, | ||
| key_type: parts[0].to_string(), | ||
| key_comment, | ||
| }) | ||
| }) | ||
| .collect() | ||
|
Comment on lines
+122
to
+142
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This is pre-existing - any such explosion on file-based keys would do same. This is another good candidate for "rewrite the entire thing using russh." (which only became a thing after I opened this PR!)
KazWolfe marked this conversation as resolved.
|
||
| } | ||
|
KazWolfe marked this conversation as resolved.
|
||
|
|
||
| /// Read and parse an SSH public key file | ||
| fn read_ssh_key(path: &Path) -> Result<LocalSshKey> { | ||
| let content = std::fs::read_to_string(path)?; | ||
|
|
@@ -81,15 +153,20 @@ fn read_ssh_key(path: &Path) -> Result<LocalSshKey> { | |
|
|
||
| let key_type = parts[0].to_string(); | ||
| let public_key = content.trim().to_string(); | ||
| let key_comment = parts | ||
| .get(2..) | ||
| .map(|p| p.join(" ")) | ||
| .filter(|s| !s.is_empty()); | ||
|
|
||
| // Compute fingerprint using ssh-keygen | ||
| let fingerprint = compute_fingerprint(path)?; | ||
|
|
||
| Ok(LocalSshKey { | ||
| path: path.to_path_buf(), | ||
| path: Some(path.into()), | ||
| public_key, | ||
| fingerprint, | ||
| key_type, | ||
| key_comment, | ||
| }) | ||
| } | ||
|
|
||
|
|
||
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Semantics, I would prefer if we didn't change this- such that we can keep things consistent. I would prefer that we add a separate method so that we don't overwrite existing behavior.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Will fix the lint aside, however the semantics of
Hostnameare wrong (imo) here - SSH key comments are significantly more broad and cover things like card serial numbers, generating user/host (as probably implied), etc. I can revert if preferred, but the intent is to follow how SSH itself wants to work.