nxthdr 0.6.0

Command line interface for the nxthdr platform
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
mod api;
mod auth;
mod config;
mod output;
mod peering;
mod probing;
mod ris;

use clap::{CommandFactory, Parser, Subcommand};
use clap_verbosity_flag::{InfoLevel, Verbosity};
use std::time::{SystemTime, UNIX_EPOCH};

#[derive(Parser)]
#[command(name = "nxthdr")]
#[command(version)]
#[command(about = "CLI tool to interact with nxthdr platform", long_about = None)]
struct Cli {
    #[command(subcommand)]
    command: Commands,

    #[command(flatten)]
    verbose: Verbosity<InfoLevel>,

    #[arg(
        long,
        short = 'o',
        global = true,
        value_enum,
        default_value = "text",
        help = "Output format"
    )]
    output: output::OutputFormat,
}

#[derive(Subcommand)]
enum Commands {
    #[command(about = "Authenticate with the nxthdr platform")]
    Auth {
        #[command(subcommand)]
        command: AuthCommands,
    },
    #[command(about = "Interact with peering platform")]
    Peering {
        #[command(subcommand)]
        command: PeeringCommands,
    },
    #[command(about = "Interact with probing platform")]
    Probing {
        #[command(subcommand)]
        command: ProbingCommands,
    },
    #[command(about = "Generate shell completion scripts")]
    Completions {
        #[arg(value_enum, help = "Shell to generate completions for")]
        shell: clap_complete::Shell,
    },
}

#[derive(Subcommand)]
enum AuthCommands {
    #[command(about = "Login to nxthdr platform")]
    Login,
    #[command(about = "Logout from nxthdr platform")]
    Logout,
    #[command(about = "Show authentication status")]
    Status,
}

#[derive(Subcommand)]
enum ProbingCommands {
    #[command(about = "Manage probing agents")]
    Agent {
        #[command(subcommand)]
        command: AgentCommands,
    },
    #[command(about = "Show your probing credits usage")]
    Credits {
        #[command(subcommand)]
        command: CreditsCommands,
    },
    #[command(about = "Send, list, and manage measurements")]
    Measurement {
        #[command(subcommand)]
        command: MeasurementCommands,
    },
    #[command(about = "Query probe replies")]
    Reply {
        #[command(subcommand)]
        command: ReplyCommands,
    },
}

#[derive(Subcommand)]
enum AgentCommands {
    #[command(about = "List available probing agents")]
    List,
}

#[derive(Subcommand)]
enum CreditsCommands {
    #[command(about = "Show your probing credits usage")]
    Get,
}

#[derive(Subcommand)]
enum MeasurementCommands {
    #[command(
        about = "Send probes from one or more agents",
        long_about = "Send probes read from a file or stdin.\n\nEach line must be: dst_addr,src_port,dst_port,ttl,protocol\nProtocol is 'icmpv6' or 'udp' (case-insensitive).\n\nExamples:\n  nxthdr probing measurement send --agent vltcdg01 probes.csv\n  prowl | nxthdr probing measurement send --agent vltcdg01"
    )]
    Send {
        #[arg(help = "Input file with probes (reads from stdin if omitted)")]
        file: Option<std::path::PathBuf>,
        #[arg(short, long, help = "Agent ID(s) to use", required = true)]
        agent: Vec<String>,
        #[arg(
            long,
            help = "Override source IPv6 address (auto-detected per agent if not set)"
        )]
        src_ip: Option<String>,
    },
    #[command(about = "List your recent measurements")]
    List {
        #[arg(
            long,
            default_value_t = 20,
            help = "Maximum number of measurements to list (1-100)"
        )]
        limit: u32,
        #[arg(
            long,
            value_delimiter = ',',
            help = "Filter by status (comma-separated): complete, in-progress, cancelled"
        )]
        status: Vec<probing::StatusFilter>,
        #[arg(
            long,
            help = "Only measurements started at/after this time (e.g. '2026-03-22' or '2026-03-22 10:00:00')"
        )]
        since: Option<String>,
        #[arg(long, help = "Only measurements started at/before this time")]
        until: Option<String>,
        #[arg(long, help = "Only measurements involving this agent ID")]
        agent: Option<String>,
        #[arg(
            long,
            value_enum,
            default_value = "updated",
            help = "Sort by 'started' or 'updated' time"
        )]
        sort: probing::SortField,
        #[arg(long, help = "Reverse the order (oldest first)")]
        reverse: bool,
    },
    #[command(about = "Get status of a measurement by ID")]
    Get {
        #[arg(help = "Measurement ID returned by 'send'")]
        id: String,
    },
    #[command(about = "Cancel a stuck/in-progress measurement by ID")]
    Cancel {
        #[arg(help = "Measurement ID to cancel")]
        id: String,
    },
}

#[derive(Subcommand)]
enum ReplyCommands {
    #[command(about = "Query replies from ClickHouse")]
    List {
        #[arg(long, help = "Source IP(s) to filter by", required = true, num_args = 1..)]
        src_ip: Vec<String>,
        #[arg(long, help = "Start of time window (e.g. '2026-03-19 21:00:00')")]
        since: Option<String>,
        #[arg(long, help = "End of time window (e.g. '2026-03-19 22:00:00')")]
        until: Option<String>,
    },
}

#[derive(Subcommand)]
enum PeeringCommands {
    #[command(about = "Manage your ASN")]
    Asn {
        #[command(subcommand)]
        command: AsnCommands,
    },
    #[command(about = "Manage prefix leases")]
    Prefix {
        #[command(subcommand)]
        command: PrefixCommands,
    },
    #[command(about = "Inspect prefix visibility in public BGP collectors (RIPE RIS)")]
    Route {
        #[command(subcommand)]
        command: RouteCommands,
    },
    #[command(about = "PeerLab utilities")]
    Peerlab {
        #[command(subcommand)]
        command: PeerlabCommands,
    },
}

#[derive(Subcommand)]
enum RouteCommands {
    #[command(about = "Show your leased prefixes as seen by public BGP collectors (RIPE RIS)")]
    List,
    #[command(about = "Looking glass: how a prefix is seen by public BGP collectors (RIPE RIS)")]
    Lookup {
        #[arg(help = "Prefix or IP to look up (e.g., 2001:db8::/48)")]
        prefix: String,
    },
}

#[derive(Subcommand)]
enum AsnCommands {
    #[command(about = "Get your ASN")]
    Get,
}

#[derive(Subcommand)]
enum PeerlabCommands {
    #[command(about = "Generate .env file for PeerLab")]
    Env,
}

#[derive(Subcommand)]
enum PrefixCommands {
    #[command(about = "List your active prefix leases")]
    List,
    #[command(about = "Request a new prefix lease")]
    Request {
        #[arg(value_name = "HOURS", help = "Lease duration in hours (1-24)")]
        duration: u32,
    },
    #[command(about = "Revoke a prefix lease")]
    Revoke {
        #[arg(help = "Prefix to revoke (e.g., 2001:db8::/48)")]
        prefix: String,
    },
    #[command(about = "Manage RPKI ROA for a leased prefix")]
    Rpki {
        #[command(subcommand)]
        command: RpkiCommands,
    },
}

#[derive(Subcommand)]
enum RpkiCommands {
    #[command(about = "Enable RPKI ROA for a leased prefix")]
    Enable {
        #[arg(help = "Prefix (e.g., 2001:db8::/48)")]
        prefix: String,
    },
    #[command(about = "Disable RPKI ROA for a leased prefix")]
    Disable {
        #[arg(help = "Prefix (e.g., 2001:db8::/48)")]
        prefix: String,
    },
}

fn now_secs() -> i64 {
    SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .unwrap()
        .as_secs() as i64
}

#[tokio::main]
async fn main() -> anyhow::Result<()> {
    let cli = Cli::parse();

    output::set_format(cli.output);
    tracing_subscriber::fmt().with_max_level(cli.verbose).init();

    match cli.command {
        Commands::Auth { command } => match command {
            AuthCommands::Login => handle_login().await?,
            AuthCommands::Logout => handle_logout()?,
            AuthCommands::Status => handle_status()?,
        },
        Commands::Peering { command } => handle_peering(command).await?,
        Commands::Probing { command } => handle_probing(command).await?,
        Commands::Completions { shell } => {
            let mut cmd = Cli::command();
            let bin = cmd.get_name().to_string();
            clap_complete::generate(shell, &mut cmd, bin, &mut std::io::stdout());
        }
    }

    Ok(())
}

async fn handle_probing(command: ProbingCommands) -> anyhow::Result<()> {
    match command {
        ProbingCommands::Agent { command } => match command {
            AgentCommands::List => probing::agents().await,
        },
        ProbingCommands::Credits { command } => match command {
            CreditsCommands::Get => probing::credits().await,
        },
        ProbingCommands::Measurement { command } => match command {
            MeasurementCommands::Send {
                file,
                agent,
                src_ip,
            } => probing::send(file, agent, src_ip).await,
            MeasurementCommands::List {
                limit,
                status,
                since,
                until,
                agent,
                sort,
                reverse,
            } => probing::measurements(limit, status, since, until, agent, sort, reverse).await,
            MeasurementCommands::Get { id } => probing::measurement_status(&id).await,
            MeasurementCommands::Cancel { id } => probing::cancel(&id).await,
        },
        ProbingCommands::Reply { command } => match command {
            ReplyCommands::List {
                src_ip,
                since,
                until,
            } => probing::results(src_ip, since, until).await,
        },
    }
}

async fn handle_peering(command: PeeringCommands) -> anyhow::Result<()> {
    match command {
        PeeringCommands::Asn { command } => match command {
            AsnCommands::Get => peering::asn().await,
        },
        PeeringCommands::Prefix { command } => match command {
            PrefixCommands::List => peering::prefix_list().await,
            PrefixCommands::Request { duration } => peering::prefix_request(duration).await,
            PrefixCommands::Revoke { prefix } => peering::prefix_revoke(&prefix).await,
            PrefixCommands::Rpki { command } => match command {
                RpkiCommands::Enable { prefix } => peering::prefix_rpki(&prefix, true).await,
                RpkiCommands::Disable { prefix } => peering::prefix_rpki(&prefix, false).await,
            },
        },
        PeeringCommands::Route { command } => match command {
            RouteCommands::List => peering::routes().await,
            RouteCommands::Lookup { prefix } => peering::lookup(&prefix).await,
        },
        PeeringCommands::Peerlab { command } => match command {
            PeerlabCommands::Env => peering::peerlab_env().await,
        },
    }
}

async fn handle_login() -> anyhow::Result<()> {
    if config::tokens_exist() {
        let tokens = config::load_tokens()?;

        if tokens.expires_at >= now_secs() {
            output::kv(&[("auth", "already logged in")]);
            output::hint("nxthdr auth logout  # to switch accounts");
            return Ok(());
        }

        if tokens.refresh_token.is_empty() {
            anyhow::bail!("access token expired and no refresh token available — run 'nxthdr auth logout' then 'nxthdr auth login'");
        }

        output::info("refreshing token...");
        let (access_token, refresh_token, expires_at) =
            auth::refresh_access_token(&tokens.refresh_token)
                .await
                .map_err(|e| {
                    anyhow::anyhow!(
                "failed to refresh token: {e} — run 'nxthdr auth logout' then 'nxthdr auth login'"
            )
                })?;
        config::save_tokens(&config::TokenStorage {
            access_token,
            refresh_token,
            expires_at,
        })?;
        output::success("token refreshed");
        return Ok(());
    }

    let device_code = auth::start_device_flow().await?;

    output::info("open the following URL to authenticate:");
    output::info(&format!("\n  {}\n", device_code.verification_uri_complete));
    output::info(&format!(
        "or go to {} and enter code: {}\n",
        device_code.verification_uri, device_code.user_code
    ));
    output::info("waiting...");

    let (access_token, refresh_token, expires_at) =
        auth::poll_for_token(&device_code.device_code, device_code.interval).await?;

    config::save_tokens(&config::TokenStorage {
        access_token,
        refresh_token,
        expires_at,
    })?;
    output::success("authenticated");

    Ok(())
}

fn handle_logout() -> anyhow::Result<()> {
    if !config::tokens_exist() {
        output::info("not logged in");
        return Ok(());
    }
    config::delete_tokens()?;
    output::success("logged out");
    Ok(())
}

fn handle_status() -> anyhow::Result<()> {
    output::section("status");

    if !config::tokens_exist() {
        output::kv(&[("auth", "not logged in")]);
        output::hint("nxthdr auth login");
        return Ok(());
    }

    let tokens = config::load_tokens()?;
    let now = now_secs();

    if tokens.expires_at < now {
        output::kv(&[("auth", "logged in"), ("token", "expired")]);
        output::hint("nxthdr auth login  # to refresh");
    } else {
        let secs = tokens.expires_at - now;
        let expiry = format!("valid {}h {}m", secs / 3600, (secs % 3600) / 60);
        output::kv(&[("auth", "logged in"), ("token", &expiry)]);
    }

    Ok(())
}