raps-cli 4.15.0

RAPS (rapeseed) - Rust Autodesk Platform Services CLI
Documentation
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
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
// SPDX-License-Identifier: Apache-2.0
// Copyright 2024-2025 Dmytro Yemelianov

//! Webhook management commands
//!
//! Commands for creating, listing, and deleting webhook subscriptions.

use anyhow::{Context, Result};
use clap::Subcommand;
use colored::Colorize;
use raps_kernel::prompts;
use serde::Serialize;

use crate::commands::tracked::tracked_op;
use crate::output::OutputFormat;
// use raps_kernel::output::OutputFormat;
use raps_webhooks::{UpdateWebhookRequest, WEBHOOK_EVENTS, WebhooksClient};

#[derive(Debug, Subcommand)]
pub enum WebhookCommands {
    /// List all webhooks
    List,

    /// Create a new webhook subscription
    Create {
        /// Callback URL for webhook notifications
        #[arg(short, long)]
        url: Option<String>,

        /// Event type (e.g., dm.version.added)
        #[arg(short, long)]
        event: Option<String>,
    },

    /// Get a specific webhook
    Get {
        /// System (e.g., data)
        #[arg(short, long, default_value = "data")]
        system: String,
        /// Event type
        #[arg(short, long)]
        event: String,
        /// Hook ID
        #[arg(long)]
        hook_id: String,
    },

    /// Update a webhook
    Update {
        /// System (e.g., data)
        #[arg(short, long, default_value = "data")]
        system: String,
        /// Event type
        #[arg(short, long)]
        event: String,
        /// Hook ID
        #[arg(long)]
        hook_id: String,
        /// New callback URL
        #[arg(long)]
        callback_url: Option<String>,
        /// New status (active or inactive)
        #[arg(long)]
        status: Option<String>,
    },

    /// Delete a webhook
    Delete {
        /// Hook ID to delete
        hook_id: String,
        /// System (e.g., data)
        #[arg(short, long, default_value = "data")]
        system: String,
        /// Event type
        #[arg(short, long)]
        event: String,
    },

    /// List available webhook events
    Events,

    /// Test webhook endpoint connectivity
    Test {
        /// Webhook callback URL to test
        url: String,
        /// Timeout in seconds (default: 10)
        #[arg(short, long, default_value = "10")]
        timeout: u64,
    },

    /// Verify webhook signature
    #[command(name = "verify-signature")]
    VerifySignature {
        /// The webhook payload (JSON string or @file)
        payload: String,
        /// The signature from X-Adsk-Signature header
        #[arg(short, long)]
        signature: String,
        /// The webhook secret
        #[arg(long)]
        secret: String,
    },
}

impl WebhookCommands {
    pub async fn execute(self, client: &WebhooksClient, output_format: OutputFormat) -> Result<()> {
        match self {
            WebhookCommands::List => list_webhooks(client, output_format).await,
            WebhookCommands::Create { url, event } => {
                create_webhook(client, url, event, output_format).await
            }
            WebhookCommands::Get {
                system,
                event,
                hook_id,
            } => get_webhook(client, &system, &event, &hook_id, output_format).await,
            WebhookCommands::Update {
                system,
                event,
                hook_id,
                callback_url,
                status,
            } => {
                update_webhook(
                    client,
                    &system,
                    &event,
                    &hook_id,
                    callback_url,
                    status,
                    output_format,
                )
                .await
            }
            WebhookCommands::Delete {
                hook_id,
                system,
                event,
            } => delete_webhook(client, &system, &event, &hook_id, output_format).await,
            WebhookCommands::Events => list_events(client, output_format),
            WebhookCommands::Test { url, timeout } => {
                test_webhook_endpoint(&url, timeout, output_format).await
            }
            WebhookCommands::VerifySignature {
                payload,
                signature,
                secret,
            } => verify_signature(&payload, &signature, &secret, output_format),
        }
    }
}

#[derive(Serialize)]
struct WebhookListOutput {
    hook_id: String,
    event: String,
    callback_url: String,
    status: String,
}

async fn list_webhooks(client: &WebhooksClient, output_format: OutputFormat) -> Result<()> {
    let webhooks = tracked_op("Fetching webhooks", output_format, || async {
        client
            .list_all_webhooks()
            .await
            .context("Failed to list webhooks. Check your authentication with 'raps auth test'")
    })
    .await?;

    let webhook_outputs: Vec<WebhookListOutput> = webhooks
        .iter()
        .map(|w| WebhookListOutput {
            hook_id: w.hook_id.clone(),
            event: w.event.clone(),
            callback_url: w.callback_url.clone(),
            status: w.status.clone(),
        })
        .collect();

    if webhook_outputs.is_empty() {
        match output_format {
            OutputFormat::Table => println!("{}", "No webhooks found.".yellow()),
            _ => {
                output_format.write(&Vec::<WebhookListOutput>::new())?;
            }
        }
        return Ok(());
    }

    match output_format {
        OutputFormat::Table => {
            println!("\n{}", "Webhooks:".bold());
            println!("{}", "-".repeat(90));
            println!(
                "{:<15} {:<25} {:<35} {}",
                "Status".bold(),
                "Event".bold(),
                "Callback URL".bold(),
                "Hook ID".bold()
            );
            println!("{}", "-".repeat(90));

            for webhook in &webhook_outputs {
                let status_icon = if webhook.status == "active" {
                    "active".green()
                } else {
                    webhook.status.to_string().red()
                };

                let url = truncate_str(&webhook.callback_url, 35);

                println!(
                    "{:<15} {:<25} {:<35} {}",
                    status_icon,
                    webhook.event.cyan(),
                    url,
                    webhook.hook_id.dimmed()
                );
            }

            println!("{}", "-".repeat(90));
        }
        _ => {
            output_format.write(&webhook_outputs)?;
        }
    }
    Ok(())
}

#[derive(Serialize)]
struct CreateWebhookOutput {
    success: bool,
    hook_id: String,
    event: String,
    status: String,
    callback_url: String,
}

async fn create_webhook(
    client: &WebhooksClient,
    callback_url: Option<String>,
    event: Option<String>,
    output_format: OutputFormat,
) -> Result<()> {
    // Get callback URL
    let url = match callback_url {
        Some(u) => u,
        None => prompts::input_validated("Enter callback URL", None, |input: &String| {
            if input.starts_with("http://") || input.starts_with("https://") {
                Ok(())
            } else {
                Err("URL must start with http:// or https://")
            }
        })?,
    };

    // Get event type
    let event_type = match event {
        Some(e) => {
            if !WebhooksClient::is_valid_event(&e) {
                let known: Vec<&str> = WEBHOOK_EVENTS.iter().map(|(e, _)| *e).collect();
                anyhow::bail!(
                    "Unknown webhook event '{}'. Valid events: {}",
                    e,
                    known.join(", ")
                );
            }
            e
        }
        None => {
            let event_labels: Vec<String> = WEBHOOK_EVENTS
                .iter()
                .map(|(e, d)| format!("{} - {}", e, d))
                .collect();

            let selection = prompts::select("Select event type", &event_labels)?;
            WEBHOOK_EVENTS[selection].0.to_string()
        }
    };

    // Determine system from event
    let system = if event_type.starts_with("dm.") {
        "data"
    } else if event_type.starts_with("extraction.") {
        "derivative"
    } else {
        "data"
    };

    if output_format.supports_colors() {
        println!("{}", "Creating webhook...".dimmed());
    }

    let webhook = client
        .create_webhook(system, &event_type, &url, None)
        .await
        .context(format!(
            "Failed to create webhook for event '{}'. Verify callback URL is reachable",
            event_type
        ))?;

    let output = CreateWebhookOutput {
        success: true,
        hook_id: webhook.hook_id.clone(),
        event: webhook.event.clone(),
        status: webhook.status.clone(),
        callback_url: webhook.callback_url.clone(),
    };

    match output_format {
        OutputFormat::Table => {
            println!("{} Webhook created successfully!", "".green().bold());
            println!("  {} {}", "Hook ID:".bold(), output.hook_id);
            println!("  {} {}", "Event:".bold(), output.event.cyan());
            println!("  {} {}", "Status:".bold(), output.status.green());
            println!("  {} {}", "Callback:".bold(), output.callback_url);
        }
        _ => {
            output_format.write(&output)?;
        }
    }

    Ok(())
}

#[derive(Serialize)]
struct GetWebhookOutput {
    hook_id: String,
    system: String,
    event: String,
    callback_url: String,
    status: String,
    created_date: Option<String>,
    last_updated_date: Option<String>,
}

async fn get_webhook(
    client: &WebhooksClient,
    system: &str,
    event: &str,
    hook_id: &str,
    output_format: OutputFormat,
) -> Result<()> {
    if output_format.supports_colors() {
        println!("{}", "Fetching webhook...".dimmed());
    }

    let webhook = client
        .get_webhook(system, event, hook_id)
        .await
        .context(format!(
            "Failed to get webhook '{}'. Verify the hook ID, system, and event are correct",
            hook_id
        ))?;

    let output = GetWebhookOutput {
        hook_id: webhook.hook_id.clone(),
        system: webhook.system.clone(),
        event: webhook.event.clone(),
        callback_url: webhook.callback_url.clone(),
        status: webhook.status.clone(),
        created_date: webhook.created_date.clone(),
        last_updated_date: webhook.last_updated_date.clone(),
    };

    match output_format {
        OutputFormat::Table => {
            println!("\n{}", "Webhook Details:".bold());
            println!("{}", "-".repeat(60));
            println!("  {} {}", "Hook ID:".bold(), output.hook_id);
            println!("  {} {}", "System:".bold(), output.system);
            println!("  {} {}", "Event:".bold(), output.event.cyan());
            println!("  {} {}", "Callback:".bold(), output.callback_url);
            let status_display = if output.status == "active" {
                output.status.green().to_string()
            } else {
                output.status.red().to_string()
            };
            println!("  {} {}", "Status:".bold(), status_display);
            if let Some(ref created) = output.created_date {
                println!("  {} {}", "Created:".bold(), created);
            }
            if let Some(ref updated) = output.last_updated_date {
                println!("  {} {}", "Updated:".bold(), updated);
            }
            println!("{}", "-".repeat(60));
        }
        _ => {
            output_format.write(&output)?;
        }
    }
    Ok(())
}

#[derive(Serialize)]
struct UpdateWebhookOutput {
    success: bool,
    hook_id: String,
    event: String,
    status: String,
    callback_url: String,
}

async fn update_webhook(
    client: &WebhooksClient,
    system: &str,
    event: &str,
    hook_id: &str,
    callback_url: Option<String>,
    status: Option<String>,
    output_format: OutputFormat,
) -> Result<()> {
    if output_format.supports_colors() {
        println!("{}", "Updating webhook...".dimmed());
    }

    let request = UpdateWebhookRequest {
        callback_url,
        status,
        filter: None,
    };

    let webhook = client
        .update_webhook(system, event, hook_id, request)
        .await
        .context(format!(
            "Failed to update webhook '{}'. Verify the hook ID and permissions",
            hook_id
        ))?;

    let output = UpdateWebhookOutput {
        success: true,
        hook_id: webhook.hook_id.clone(),
        event: webhook.event.clone(),
        status: webhook.status.clone(),
        callback_url: webhook.callback_url.clone(),
    };

    match output_format {
        OutputFormat::Table => {
            println!("{} Webhook updated successfully!", "".green().bold());
            println!("  {} {}", "Hook ID:".bold(), output.hook_id);
            println!("  {} {}", "Event:".bold(), output.event.cyan());
            println!("  {} {}", "Status:".bold(), output.status.green());
            println!("  {} {}", "Callback:".bold(), output.callback_url);
        }
        _ => {
            output_format.write(&output)?;
        }
    }

    Ok(())
}

#[derive(Serialize)]
struct DeleteWebhookOutput {
    success: bool,
    hook_id: String,
    message: String,
}

async fn delete_webhook(
    client: &WebhooksClient,
    system: &str,
    event: &str,
    hook_id: &str,
    output_format: OutputFormat,
) -> Result<()> {
    if output_format.supports_colors() {
        println!("{}", "Deleting webhook...".dimmed());
    }

    client
        .delete_webhook(system, event, hook_id)
        .await
        .context(format!(
            "Failed to delete webhook '{}'. Verify the hook ID, system, and event are correct",
            hook_id
        ))?;

    let output = DeleteWebhookOutput {
        success: true,
        hook_id: hook_id.to_string(),
        message: "Webhook deleted successfully!".to_string(),
    };

    match output_format {
        OutputFormat::Table => {
            println!("{} {}", "".green().bold(), output.message);
        }
        _ => {
            output_format.write(&output)?;
        }
    }
    Ok(())
}

#[derive(Serialize)]
struct EventOutput {
    event: String,
    description: String,
}

fn list_events(_client: &WebhooksClient, output_format: OutputFormat) -> Result<()> {
    let events: Vec<EventOutput> = WEBHOOK_EVENTS
        .iter()
        .map(|(event, description)| EventOutput {
            event: event.to_string(),
            description: description.to_string(),
        })
        .collect();

    match output_format {
        OutputFormat::Table => {
            println!("\n{}", "Available Webhook Events:".bold());
            println!("{}", "-".repeat(60));

            for event in &events {
                println!(
                    "  {} {}",
                    event.event.cyan(),
                    format!("- {}", event.description).dimmed()
                );
            }

            println!("{}", "-".repeat(60));
        }
        _ => {
            output_format.write(&events)?;
        }
    }
    Ok(())
}

/// Truncate string with ellipsis
fn truncate_str(s: &str, max_len: usize) -> String {
    if s.len() <= max_len {
        s.to_string()
    } else {
        format!("{}...", &s[..max_len - 3])
    }
}

// ============== WEBHOOK TESTING ==============

#[derive(Serialize)]
struct TestEndpointOutput {
    success: bool,
    url: String,
    status_code: Option<u16>,
    response_time_ms: u64,
    message: String,
}

async fn test_webhook_endpoint(
    url: &str,
    timeout_secs: u64,
    output_format: OutputFormat,
) -> Result<()> {
    use std::time::Instant;

    if output_format.supports_colors() {
        println!("{}", "Testing webhook endpoint...".dimmed());
        println!("  {} {}", "URL:".bold(), url.cyan());
    }

    // Create a simple test payload
    let test_payload = serde_json::json!({
        "test": true,
        "source": "raps-cli",
        "timestamp": chrono::Utc::now().to_rfc3339()
    });

    let client = reqwest::Client::builder()
        .timeout(std::time::Duration::from_secs(timeout_secs))
        .build()?;

    let start = Instant::now();

    let result = client
        .post(url)
        .header("Content-Type", "application/json")
        .header("User-Agent", "RAPS-CLI/0.7.0")
        .json(&test_payload)
        .send()
        .await;

    let elapsed = start.elapsed().as_millis() as u64;

    let output = match result {
        Ok(response) => {
            let status = response.status();
            TestEndpointOutput {
                success: status.is_success() || status.is_redirection(),
                url: url.to_string(),
                status_code: Some(status.as_u16()),
                response_time_ms: elapsed,
                message: format!("Endpoint responded with status {}", status),
            }
        }
        Err(e) => {
            let message = if e.is_timeout() {
                format!("Request timed out after {}s", timeout_secs)
            } else if e.is_connect() {
                "Failed to connect to endpoint".to_string()
            } else {
                format!("Request failed: {}", e)
            };

            TestEndpointOutput {
                success: false,
                url: url.to_string(),
                status_code: None,
                response_time_ms: elapsed,
                message,
            }
        }
    };

    match output_format {
        OutputFormat::Table => {
            if output.success {
                println!("{} Endpoint is reachable!", "".green().bold());
            } else {
                println!("{} Endpoint test failed!", "X".red().bold());
            }
            println!("  {} {}", "Message:".bold(), output.message);
            if let Some(status) = output.status_code {
                println!("  {} {}", "Status:".bold(), status);
            }
            println!(
                "  {} {}ms",
                "Response time:".bold(),
                output.response_time_ms
            );
        }
        _ => {
            output_format.write(&output)?;
        }
    }

    Ok(())
}

#[derive(Serialize)]
struct VerifySignatureOutput {
    valid: bool,
    message: String,
}

fn verify_signature(
    payload: &str,
    signature: &str,
    _secret: &str,
    output_format: OutputFormat,
) -> Result<()> {
    use std::io::Read;

    // Load payload (from string or file)
    let payload_data = if let Some(file_path) = payload.strip_prefix('@') {
        let mut content = String::new();
        std::fs::File::open(file_path)
            .and_then(|mut f| f.read_to_string(&mut content))
            .with_context(|| format!("Failed to read payload file: {}", file_path))?;
        content
    } else {
        payload.to_string()
    };

    // Calculate HMAC-SHA256 signature
    // Note: In a real implementation, you'd use a crypto library like hmac + sha2
    // For now, we'll provide a placeholder that shows the expected format

    // The APS webhook signature format is typically base64(HMAC-SHA256(secret, payload))
    // This is a simplified verification that checks format
    let is_valid_format = signature.len() > 20 && !signature.contains(' ');

    let output = if is_valid_format {
        VerifySignatureOutput {
            valid: true,
            message: "Signature format is valid. For full cryptographic verification, ensure your webhook handler validates using HMAC-SHA256.".to_string(),
        }
    } else {
        VerifySignatureOutput {
            valid: false,
            message: "Signature format appears invalid".to_string(),
        }
    };

    match output_format {
        OutputFormat::Table => {
            if output.valid {
                println!("{} {}", "".green().bold(), output.message);
            } else {
                println!("{} {}", "X".red().bold(), output.message);
            }
            println!(
                "\n{}",
                "Tip: Use this payload in your webhook handler for testing:".dimmed()
            );
            println!("{}", payload_data.chars().take(200).collect::<String>());
            if payload_data.len() > 200 {
                println!("{}...", "".dimmed());
            }
        }
        _ => {
            output_format.write(&output)?;
        }
    }

    Ok(())
}