railwayapp 4.37.4

Interact with Railway via CLI
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
use std::fmt;

use anyhow::{Result, bail};
use clap::Parser;
use is_terminal::IsTerminal;

use crate::client::GQLClient;
use crate::config::Configs;
use crate::controllers::ssh_keys::{
    LocalSshKey, compute_fingerprint_from_pubkey, delete_ssh_key, find_local_ssh_keys,
    get_github_ssh_keys, get_registered_ssh_keys, register_ssh_key,
};
use crate::gql::queries::git_hub_ssh_keys::GitHubSshKeysGitHubSshKeys;
use crate::gql::queries::ssh_public_keys::SshPublicKeysSshPublicKeysEdgesNode;
use crate::util::prompt::{prompt_options, prompt_text};

/// Wrapper for LocalSshKey to implement Display for prompts
struct LocalKeyOption(LocalSshKey);

impl fmt::Display for LocalKeyOption {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "{} ({})",
            self.0
                .path
                .file_name()
                .unwrap_or_default()
                .to_string_lossy(),
            self.0.fingerprint
        )
    }
}

/// Wrapper for registered SSH key to implement Display for prompts
struct RegisteredKeyOption(SshPublicKeysSshPublicKeysEdgesNode);

impl fmt::Display for RegisteredKeyOption {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{} ({})", self.0.name, self.0.fingerprint)
    }
}

/// Wrapper for GitHub SSH key to implement Display for prompts
struct GitHubKeyOption(GitHubSshKeysGitHubSshKeys);

impl fmt::Display for GitHubKeyOption {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let parts: Vec<&str> = self.0.key.split_whitespace().collect();
        let key_type = parts.first().unwrap_or(&"unknown");
        let fingerprint = compute_fingerprint_from_pubkey(&self.0.key).unwrap_or_default();
        if fingerprint.is_empty() {
            write!(f, "{} ({})", self.0.title, key_type)
        } else {
            write!(f, "{} ({}) {}", self.0.title, key_type, fingerprint)
        }
    }
}

/// Manage SSH keys registered with Railway
#[derive(Parser, Clone)]
pub struct Args {
    #[clap(subcommand)]
    command: Option<Commands>,
}

#[derive(Parser, Clone)]
enum Commands {
    /// List all registered SSH keys
    #[clap(alias = "ls")]
    List,

    /// Add/register a local SSH key with Railway
    Add {
        /// Path to the public key file (defaults to auto-detect)
        #[clap(long, short)]
        key: Option<String>,

        /// Name for the key (defaults to filename)
        #[clap(long, short)]
        name: Option<String>,
    },

    /// Remove a registered SSH key
    #[clap(alias = "rm", alias = "delete")]
    Remove {
        /// Key ID or fingerprint to remove
        key: Option<String>,

        /// 2FA code (required if 2FA is enabled)
        #[clap(long = "2fa-code")]
        two_factor_code: Option<String>,
    },

    /// Import SSH keys from your GitHub account
    #[clap(alias = "import")]
    Github,
}

pub async fn command(args: Args) -> Result<()> {
    match args.command {
        Some(Commands::List) | None => list_keys().await,
        Some(Commands::Add { key, name }) => add_key(key, name).await,
        Some(Commands::Remove {
            key,
            two_factor_code,
        }) => remove_key(key, two_factor_code).await,
        Some(Commands::Github) => import_github_keys().await,
    }
}

async fn list_keys() -> Result<()> {
    let configs = Configs::new()?;
    let client = GQLClient::new_authorized(&configs)?;

    let registered_keys = get_registered_ssh_keys(&client, &configs).await?;
    let local_keys = find_local_ssh_keys()?;
    let github_keys = get_github_ssh_keys(&client, &configs)
        .await
        .unwrap_or_default();

    // Show registered Railway keys
    if !registered_keys.is_empty() {
        println!("Registered SSH Keys:");

        for key in &registered_keys {
            let local_match = local_keys.iter().find(|l| l.fingerprint == key.fingerprint);

            // Extract comment/hostname from public key
            let parts: Vec<&str> = key.public_key.split_whitespace().collect();
            let key_type = parts.first().unwrap_or(&"");
            let hostname = parts.get(2).unwrap_or(&"");

            println!("  {}", key.name);
            println!("    Fingerprint: {}", key.fingerprint);
            if !key_type.is_empty() {
                println!("    Type:        {}", key_type);
            }
            if !hostname.is_empty() {
                println!("    Hostname:    {}", hostname);
            }
            if local_match.is_some() {
                println!("    Source:      local (~/.ssh/)");
            }
            println!();
        }
    }

    // Show GitHub keys
    if !github_keys.is_empty() {
        println!("GitHub SSH Keys:");
        for key in &github_keys {
            let parts: Vec<&str> = key.key.split_whitespace().collect();
            let key_type = parts.first().unwrap_or(&"unknown");
            let hostname = parts.get(2).unwrap_or(&"");
            let fingerprint = compute_fingerprint_from_pubkey(&key.key).unwrap_or_default();

            // Check if already registered
            let is_registered = registered_keys.iter().any(|r| r.fingerprint == fingerprint);

            println!("  {}", key.title);
            if !fingerprint.is_empty() {
                println!("    Fingerprint: {}", fingerprint);
            }
            println!("    Type:        {}", key_type);
            if !hostname.is_empty() {
                println!("    Hostname:    {}", hostname);
            }
            if is_registered {
                println!("    Status:      registered");
            }
            println!();
        }

        let has_unregistered = github_keys.iter().any(|gh| {
            let fp = compute_fingerprint_from_pubkey(&gh.key).unwrap_or_default();
            !registered_keys.iter().any(|r| r.fingerprint == fp)
        });
        if has_unregistered {
            println!("Import with:\n    railway ssh keys github");
            println!();
        }
    }

    // Show local keys that aren't registered
    let unregistered: Vec<_> = local_keys
        .iter()
        .filter(|l| {
            !registered_keys
                .iter()
                .any(|r| r.fingerprint == l.fingerprint)
        })
        .collect();

    if registered_keys.is_empty() && github_keys.is_empty() {
        println!("No SSH keys registered with Railway.");
        println!();
        println!("Add a key with: railway ssh keys add");
        println!("Or register at: https://railway.com/account/ssh-keys");
        return Ok(());
    }

    if !unregistered.is_empty() {
        println!("Local Keys (not registered):");
        for key in unregistered {
            // Extract hostname from public key
            let parts: Vec<&str> = key.public_key.split_whitespace().collect();
            let hostname = parts.get(2).unwrap_or(&"");

            println!(
                "  {}",
                key.path.file_name().unwrap_or_default().to_string_lossy()
            );
            println!("    Fingerprint: {}", key.fingerprint);
            println!("    Type:        {}", key.key_type);
            if !hostname.is_empty() {
                println!("    Hostname:    {}", hostname);
            }
            println!("    Path:        {}", key.path.display());
            println!();
        }
        println!("Add with:\n    railway ssh keys add");
    }

    Ok(())
}

async fn add_key(key_path: Option<String>, name: Option<String>) -> Result<()> {
    let configs = Configs::new()?;
    let client = GQLClient::new_authorized(&configs)?;

    let local_keys = find_local_ssh_keys()?;
    if local_keys.is_empty() {
        bail!(
            "No SSH keys found in ~/.ssh/\n\n\
            Generate one with:\n  ssh-keygen -t ed25519\n\n\
            Then run this command again."
        );
    }

    let registered_keys = get_registered_ssh_keys(&client, &configs).await?;

    // Filter to unregistered keys
    let unregistered: Vec<_> = local_keys
        .iter()
        .filter(|l| {
            !registered_keys
                .iter()
                .any(|r| r.fingerprint == l.fingerprint)
        })
        .collect();

    if unregistered.is_empty() {
        println!("All local SSH keys are already registered with Railway.");
        return Ok(());
    }

    // Select key to add
    let key_to_add = if let Some(path) = key_path {
        // Find by path
        local_keys
            .iter()
            .find(|k| k.path.to_string_lossy().contains(&path))
            .ok_or_else(|| anyhow::anyhow!("Key not found: {}", path))?
            .clone()
    } else if unregistered.len() == 1 {
        unregistered[0].clone()
    } else if std::io::stdin().is_terminal() {
        let options: Vec<LocalKeyOption> = unregistered
            .into_iter()
            .map(|k| LocalKeyOption(k.clone()))
            .collect();
        let selected = prompt_options("Select a key to register", options)?;
        selected.0
    } else {
        // Non-interactive: use first (preferred) key
        unregistered[0].clone()
    };

    // Determine name
    let key_name = name.unwrap_or_else(|| {
        key_to_add
            .path
            .file_stem()
            .and_then(|s| s.to_str())
            .unwrap_or("ssh-key")
            .to_string()
    });

    println!(
        "Registering key: {} ({})",
        key_to_add.path.display(),
        key_to_add.fingerprint
    );

    register_ssh_key(&client, &configs, &key_name, &key_to_add.public_key).await?;

    println!("SSH key '{}' registered successfully!", key_name);

    Ok(())
}

async fn remove_key(key: Option<String>, two_factor_code: Option<String>) -> Result<()> {
    let configs = Configs::new()?;
    let client = GQLClient::new_authorized(&configs)?;

    let registered_keys = get_registered_ssh_keys(&client, &configs).await?;

    if registered_keys.is_empty() {
        println!("No SSH keys registered with Railway.");
        return Ok(());
    }

    // Select key to remove
    let key_to_remove = if let Some(key_id) = key {
        // Find by ID or fingerprint
        registered_keys
            .into_iter()
            .find(|k| k.id == key_id || k.fingerprint == key_id || k.name == key_id)
            .ok_or_else(|| anyhow::anyhow!("Key not found: {}", key_id))?
    } else if std::io::stdin().is_terminal() {
        let options: Vec<RegisteredKeyOption> = registered_keys
            .into_iter()
            .map(RegisteredKeyOption)
            .collect();
        let selected = prompt_options("Select a key to remove", options)?;
        selected.0
    } else {
        bail!("Key ID or fingerprint required in non-interactive mode");
    };

    // Get 2FA code if needed and not provided
    let code = if two_factor_code.is_some() {
        two_factor_code
    } else {
        None
    };

    println!(
        "Removing key: {} ({})",
        key_to_remove.name, key_to_remove.fingerprint
    );

    match delete_ssh_key(&client, &configs, &key_to_remove.id, code).await {
        Ok(true) => {
            println!("SSH key '{}' removed successfully!", key_to_remove.name);
            Ok(())
        }
        Ok(false) => {
            bail!("Failed to remove SSH key");
        }
        Err(e) => {
            // Check if it's a 2FA error
            let err_str = e.to_string().to_lowercase();
            if err_str.contains("two factor")
                || err_str.contains("two-factor")
                || err_str.contains("2fa")
                || err_str.contains("verification")
            {
                if std::io::stdin().is_terminal() {
                    let code = prompt_text("Enter 2FA code")?;
                    delete_ssh_key(&client, &configs, &key_to_remove.id, Some(code)).await?;
                    println!("SSH key '{}' removed successfully!", key_to_remove.name);
                    Ok(())
                } else {
                    bail!("2FA code required. Use --2fa-code option.");
                }
            } else {
                Err(e)
            }
        }
    }
}

async fn import_github_keys() -> Result<()> {
    let configs = Configs::new()?;
    let client = GQLClient::new_authorized(&configs)?;

    println!("Fetching SSH keys from GitHub...");

    let github_keys = get_github_ssh_keys(&client, &configs).await?;

    if github_keys.is_empty() {
        println!("No SSH keys found in your GitHub account.");
        println!();
        println!("Add SSH keys to GitHub at: https://github.com/settings/keys");
        return Ok(());
    }

    let registered_keys = get_registered_ssh_keys(&client, &configs).await?;

    // Filter to keys not already registered (compare by fingerprint)
    let unregistered: Vec<_> = github_keys
        .iter()
        .filter(|gh| {
            let gh_fingerprint = compute_fingerprint_from_pubkey(&gh.key).unwrap_or_default();
            !registered_keys
                .iter()
                .any(|r| r.fingerprint == gh_fingerprint)
        })
        .collect();

    if unregistered.is_empty() {
        println!("All GitHub SSH keys are already registered with Railway.");
        return Ok(());
    }

    println!(
        "Found {} GitHub key(s) not yet registered:",
        unregistered.len()
    );
    for key in &unregistered {
        let parts: Vec<&str> = key.key.split_whitespace().collect();
        let key_type = parts.first().unwrap_or(&"unknown");
        let fingerprint = compute_fingerprint_from_pubkey(&key.key).unwrap_or_default();
        println!("  - {} ({}) {}", key.title, key_type, fingerprint);
    }
    println!();

    // Select key to import
    let key_to_import = if unregistered.len() == 1 {
        unregistered[0].clone()
    } else if std::io::stdin().is_terminal() {
        let options: Vec<GitHubKeyOption> = unregistered
            .into_iter()
            .map(|k| GitHubKeyOption(k.clone()))
            .collect();
        let selected = prompt_options("Select a key to import", options)?;
        selected.0
    } else {
        // Non-interactive: import first key
        unregistered[0].clone()
    };

    println!("Importing key: {}", key_to_import.title);

    register_ssh_key(&client, &configs, &key_to_import.title, &key_to_import.key).await?;

    println!("SSH key '{}' imported successfully!", key_to_import.title);

    Ok(())
}