1
use server::command::ssh_key::AddSshKey;
2
use server::command::{CmdError, CmdResult};
3
use server::ssh_keys::parse_authorized_keys_line;
4

            
5
use super::{AuthMethod, Session_};
6

            
7
/// More than any real `authorized_keys` payload from `ssh-copy-id`.
8
pub(super) const MAX_UPLOAD_BYTES: usize = 64 * 1024;
9

            
10
/// Appends `data` unless the upload would pass [`MAX_UPLOAD_BYTES`].
11
13
pub(super) fn append_upload(buf: &mut Vec<u8>, data: &[u8]) -> bool {
12
13
    let fits = buf.len().saturating_add(data.len()) <= MAX_UPLOAD_BYTES;
13
13
    if fits {
14
10
        buf.extend_from_slice(data);
15
3
    }
16
13
    fits
17
13
}
18

            
19
/// What the client may read about a failed store: the caller's own mistakes as
20
/// they are, any other fault only as a fixed text.
21
3
pub(super) fn client_reason(user_id: sqlx::types::Uuid, error: &CmdError) -> String {
22
3
    match error {
23
        CmdError::Args(_) | CmdError::Disabled | CmdError::NotFound(_) | CmdError::Refused(_) => {
24
2
            error.to_string()
25
        }
26
        _ => {
27
1
            tracing::warn!("ssh-copy-id key store failed user_id={user_id}: {error}");
28
1
            "the key could not be stored".to_string()
29
        }
30
    }
31
3
}
32

            
33
impl Session_ {
34
    /// True only for the ssh-copy-id bootstrap window: the session
35
    /// authenticated with a password AND the user does not yet have
36
    /// any registered key.
37
2
    pub(super) async fn is_bootstrap_upload_allowed(&self) -> bool {
38
2
        if self.auth_method != Some(AuthMethod::Password) {
39
            return false;
40
2
        }
41
2
        let Some(uid) = self.user_id else {
42
            return false;
43
        };
44
2
        matches!(
45
2
            server::command::ssh_key::UserHasSshKey::new()
46
2
                .user_id(uid)
47
2
                .run()
48
2
                .await,
49
            Ok(Some(CmdResult::Bool(false)))
50
        )
51
2
    }
52

            
53
    /// Parse the bytes ssh-copy-id wrote to stdin (one or more
54
    /// `authorized_keys` lines) and register each line via
55
    /// [`AddSshKey`]. Returns the operator-facing banner that the
56
    /// channel writes back before closing.
57
2
    pub(super) async fn process_pubkey_upload(&self, buf: &[u8]) -> String {
58
2
        let Some(uid) = self.user_id else {
59
            return "ssh-copy-id: no authenticated user; aborting.\n".to_string();
60
        };
61
2
        let raw = match std::str::from_utf8(buf) {
62
2
            Ok(s) => s,
63
            Err(_) => {
64
                return "ssh-copy-id: pubkey payload is not UTF-8.\n".to_string();
65
            }
66
        };
67

            
68
2
        let mut accepted = 0usize;
69
2
        let mut errors: Vec<String> = Vec::new();
70
2
        for line in raw.lines() {
71
2
            let trimmed = line.trim();
72
2
            if trimmed.is_empty() || trimmed.starts_with('#') {
73
                continue;
74
2
            }
75
2
            let parsed = match parse_authorized_keys_line(trimmed) {
76
2
                Ok(p) => p,
77
                Err(e) => {
78
                    errors.push(format!("parse: {e}"));
79
                    continue;
80
                }
81
            };
82
2
            let annotation = if parsed.comment.is_empty() {
83
2
                "ssh-copy-id".to_string()
84
            } else {
85
                format!("ssh-copy-id ({})", parsed.comment)
86
            };
87
2
            match AddSshKey::new()
88
2
                .user_id(uid)
89
2
                .key_type(parsed.key_type)
90
2
                .key_blob(parsed.key_blob)
91
2
                .fingerprint(parsed.fingerprint)
92
2
                .annotation(annotation)
93
2
                .run()
94
2
                .await
95
            {
96
1
                Ok(Some(CmdResult::Uuid(_))) => accepted += 1,
97
                Ok(_) => errors.push("server returned no key id".to_string()),
98
1
                Err(e) => errors.push(client_reason(uid, &e)),
99
            }
100
        }
101

            
102
2
        if accepted == 0 {
103
1
            let detail = if errors.is_empty() {
104
                "no usable pubkey lines".to_string()
105
            } else {
106
1
                errors.join("; ")
107
            };
108
1
            return format!("ssh-copy-id: no key accepted ({detail}).\n");
109
1
        }
110

            
111
1
        let user_label = self.user_name.as_deref().unwrap_or("YOUR_LOGIN");
112
1
        format!(
113
            "Identity added; password auth disabled.\r\n\
114
             \r\n\
115
             Suggested ~/.ssh/config entry:\r\n\
116
             \r\n\
117
             Host nomisync\r\n\
118
             \x20   HostName       {hostname}\r\n\
119
             \x20   Port           {port}\r\n\
120
             \x20   User           {user}\r\n\
121
             \x20   IdentitiesOnly yes\r\n\
122
             \x20   # IdentityAgent ${{SSH_AUTH_SOCK}}    # uncomment if using gpg-agent\r\n\
123
             \x20   # IdentityFile  ~/.ssh/id_ed25519     # or point at your private key\r\n\
124
             \r\n\
125
             Host key fingerprint (verify on first connect):\r\n\
126
             \x20   {fp}\r\n",
127
1
            hostname = self.connect_info.hostname,
128
1
            port = self.connect_info.port,
129
1
            user = user_label,
130
1
            fp = self.connect_info.host_fingerprint,
131
        )
132
2
    }
133
}