thirdpass 0.3.3

A multi-ecosystem package code review system.
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
use crate::common;
use crate::extension;
use crate::package;
use crate::peer;
use crate::registry;
use crate::review;
use crate::review::comment::{Comment, Selection};
use crate::review::common::{Priority, ReviewConfidence, ReviewerDetails, SecuritySummary};
use anyhow::{format_err, Result};
use reqwest::StatusCode;
use thirdpass_core::schema as api;

pub type ReviewCandidate = api::ReviewCandidate;
pub type ReviewQuery = api::ReviewQuery;

#[derive(Debug, serde::Deserialize)]
struct ReviewSubmitResponse {
    id: String,
    public_user_id: String,
}

/// Server response metadata for an accepted review submission.
#[derive(Debug, Clone, Eq, PartialEq)]
pub struct ReviewSubmitResult {
    /// Server-assigned review id.
    pub id: String,
    /// Server-derived public user ID.
    pub public_user_id: String,
}

const API_KEY_CONFIG_COMMAND: &str = "thirdpass config set core.api-key <key>";

#[derive(Debug)]
struct AuthenticationRequiredError {
    status: StatusCode,
    body: String,
}

impl AuthenticationRequiredError {
    fn new(status: StatusCode, body: String) -> Self {
        Self { status, body }
    }
}

impl std::fmt::Display for AuthenticationRequiredError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "Login required by Thirdpass API ({}). Set your API key with: {}",
            self.status, API_KEY_CONFIG_COMMAND
        )?;
        let body = self.body.trim();
        if !body.is_empty() {
            write!(f, ". Server response: {}", body)?;
        }
        Ok(())
    }
}

impl std::error::Error for AuthenticationRequiredError {}

/// Return true when an API error means the user needs to authenticate.
pub(crate) fn is_authentication_required_error(err: &anyhow::Error) -> bool {
    err.downcast_ref::<AuthenticationRequiredError>().is_some()
}

pub fn submit(
    review: &review::Review,
    package_manifest: &api::PackageManifest,
    config: &common::config::Config,
) -> Result<ReviewSubmitResult> {
    let registry = get_primary_registry(&review.package)?;
    let target = api::ReviewTarget {
        registry_host: registry.host_name.clone(),
        package_name: review.package.name.clone(),
        package_version: review.package.version.clone(),
        package_hash: review.package.package_hash.clone(),
    };
    let files = to_api_review_files(&review.targets);

    let payload = api::ReviewSubmission {
        target,
        files,
        package_manifest: Some(package_manifest.clone()),
        reviewer_details: to_api_reviewer_details(&review.reviewer_details),
        agent_summary: if review.agent_summary.trim().is_empty() {
            None
        } else {
            Some(review.agent_summary.clone())
        },
        overall_security_summary: None,
        overall_security_confidence: None,
    };

    let client = reqwest::blocking::Client::new();
    let base = crate::common::api::normalize_base(&config.core.api_base)?;
    let url = crate::common::api::join(&base, "v1/reviews")?;
    let request = common::api::with_client_headers(client.post(url), config);
    let response = request.json(&payload).send()?;
    let response = require_success(response, "Failed to submit review")?;
    let response = response.json::<ReviewSubmitResponse>()?;
    Ok(ReviewSubmitResult {
        id: response.id,
        public_user_id: response.public_user_id.trim().to_string(),
    })
}

pub fn fetch(
    query: &api::ReviewQuery,
    config: &common::config::Config,
) -> Result<Vec<api::ReviewRecord>> {
    let client = reqwest::blocking::Client::new();
    let base = crate::common::api::normalize_base(&config.core.api_base)?;
    let url = crate::common::api::join(&base, "v1/reviews")?;
    let request = common::api::with_client_headers(client.get(url), config);
    let response = request.query(&query).send()?;
    let response = require_success(response, "Failed to fetch reviews")?;
    let reviews = response.json::<Vec<api::ReviewRecord>>()?;
    Ok(reviews)
}

pub fn request_target(
    candidates: Vec<api::ReviewCandidate>,
    config: &common::config::Config,
) -> Result<Option<api::ReviewCandidate>> {
    if candidates.is_empty() {
        return Ok(None);
    }
    let payload = api::ReviewRequest {
        candidates,
        supported_registry_hosts: supported_registry_hosts(config),
        review_target_policies: review_target_policies(config)?,
    };
    let assignment = match post_review_request(&payload, config) {
        Ok(assignment) => assignment,
        Err(err) => {
            if is_authentication_required_error(&err) {
                return Err(err);
            }
            log::warn!("Failed to request target from API: {}", err);
            return Ok(None);
        }
    };
    Ok(assignment.target)
}

pub fn request_global_target(
    config: &common::config::Config,
) -> Result<Option<api::ReviewCandidate>> {
    let payload = api::ReviewRequest {
        candidates: Vec::new(),
        supported_registry_hosts: supported_registry_hosts(config),
        review_target_policies: review_target_policies(config)?,
    };
    Ok(post_review_request(&payload, config)?.target)
}

fn supported_registry_hosts(config: &common::config::Config) -> Vec<String> {
    config
        .extensions
        .registries
        .iter()
        .filter_map(|(registry_host, extension_name)| {
            config
                .extensions
                .enabled
                .get(extension_name)
                .copied()
                .unwrap_or(false)
                .then(|| registry_host.clone())
        })
        .collect()
}

pub(crate) fn review_target_policies(
    config: &common::config::Config,
) -> Result<std::collections::BTreeMap<String, thirdpass_core::extension::ReviewTargetPolicy>> {
    let extension_names = enabled_extension_names_for_registries(config);
    if extension_names.is_empty() {
        return Ok(std::collections::BTreeMap::new());
    }

    let mut policies = std::collections::BTreeMap::new();
    for extension in extension::manage::get_enabled(&extension_names, config)? {
        let extension_name = extension.name();
        let policy = extension.review_target_policy();
        for registry_host in extension.registries() {
            if config.extensions.registries.get(&registry_host) == Some(&extension_name)
                && config
                    .extensions
                    .enabled
                    .get(&extension_name)
                    .copied()
                    .unwrap_or(false)
            {
                policies.insert(registry_host, policy.clone());
            }
        }
    }
    Ok(policies)
}

fn enabled_extension_names_for_registries(
    config: &common::config::Config,
) -> std::collections::BTreeSet<String> {
    config
        .extensions
        .registries
        .values()
        .filter(|extension_name| {
            config
                .extensions
                .enabled
                .get(*extension_name)
                .copied()
                .unwrap_or(false)
        })
        .cloned()
        .collect()
}

fn post_review_request(
    payload: &api::ReviewRequest,
    config: &common::config::Config,
) -> Result<api::ReviewAssignment> {
    let client = reqwest::blocking::Client::new();
    let base = crate::common::api::normalize_base(&config.core.api_base)?;
    let url = crate::common::api::join(&base, "v1/review-requests")?;
    let request = common::api::with_client_headers(client.post(url), config);
    let response = request.json(&payload).send()?;
    let response = require_success(response, "Review request failed")?;
    Ok(response.json::<api::ReviewAssignment>()?)
}

fn require_success(
    response: reqwest::blocking::Response,
    failure_message: &'static str,
) -> Result<reqwest::blocking::Response> {
    if response.status().is_success() {
        return Ok(response);
    }

    let status = response.status();
    let body = response.text().unwrap_or_default();
    if is_authentication_required_status(status) {
        return Err(AuthenticationRequiredError::new(status, body).into());
    }

    Err(format_err!("{} ({}): {}", failure_message, status, body))
}

fn is_authentication_required_status(status: StatusCode) -> bool {
    matches!(status, StatusCode::UNAUTHORIZED | StatusCode::FORBIDDEN)
}

pub fn store_records(
    records: Vec<api::ReviewRecord>,
    config: &common::config::Config,
) -> Result<usize> {
    let mut stored = 0;
    for record in records {
        if record.reviewer_details.public_user_id == config.core.public_user_id {
            continue;
        }
        store_record(record, config)?;
        stored += 1;
    }
    Ok(stored)
}

fn store_record(record: api::ReviewRecord, config: &common::config::Config) -> Result<()> {
    let api::ReviewRecord {
        target,
        reviewer_details,
        files,
        overall_security_summary,
        overall_security_confidence,
        agent_summary,
        ..
    } = record;
    let registry = build_registry(&target)?;
    let package = build_package(&target, &registry);
    let peer = peer::public_user_peer(&reviewer_details.public_user_id, &config.core.api_base)?;
    let targets = files
        .into_iter()
        .map(|file| {
            let api::ReviewFile {
                file_path,
                file_hash,
                summary,
                security_summary,
                confidence,
                comments,
            } = file;
            let comments = comments
                .into_iter()
                .map(|comment| from_remote_comment(comment, &file_path))
                .collect::<std::collections::BTreeSet<_>>();
            review::ReviewTarget {
                file_path: std::path::PathBuf::from(file_path),
                file_hash,
                agent_summary: summary,
                security_summary: security_summary.as_ref().map(from_api_security_summary),
                confidence: confidence.as_ref().map(from_api_confidence),
                comments,
            }
        })
        .collect::<Vec<_>>();

    let review = review::Review {
        id: 0,
        peer,
        package,
        targets,
        reviewer_details: from_api_reviewer_details(&reviewer_details),
        agent_summary: agent_summary.unwrap_or_default(),
        overall_security_summary: from_api_security_summary(&overall_security_summary),
        overall_security_confidence: overall_security_confidence
            .as_ref()
            .map(from_api_confidence),
    };

    review::store_submitted(&review)?;
    Ok(())
}

fn to_api_review_files(targets: &[review::ReviewTarget]) -> Vec<api::ReviewFile> {
    targets
        .iter()
        .map(|target| api::ReviewFile {
            file_path: target.file_path.display().to_string(),
            file_hash: target.file_hash.clone(),
            summary: target.agent_summary.clone(),
            security_summary: target
                .security_summary
                .as_ref()
                .map(to_api_security_summary),
            confidence: target.confidence.as_ref().map(to_api_confidence),
            comments: target
                .comments
                .iter()
                .cloned()
                .map(to_remote_comment)
                .collect(),
        })
        .collect()
}

fn to_remote_comment(comment: Comment) -> api::ReviewComment {
    api::ReviewComment {
        comment: comment.message,
        security: to_api_priority(&comment.security),
        complexity: to_api_priority(&comment.complexity),
        selection: comment.selection.as_ref().map(to_api_selection),
    }
}

fn from_remote_comment(comment: api::ReviewComment, file_path: &str) -> Comment {
    Comment {
        id: 0,
        security: from_api_priority(&comment.security),
        complexity: from_api_priority(&comment.complexity),
        summary: None,
        path: std::path::PathBuf::from(file_path),
        message: comment.comment,
        selection: comment.selection.as_ref().map(from_api_selection),
    }
}

fn to_api_selection(selection: &Selection) -> api::Selection {
    api::Selection {
        start: api::Position {
            line: selection.start.line,
            character: selection.start.character,
        },
        end: api::Position {
            line: selection.end.line,
            character: selection.end.character,
        },
    }
}

fn from_api_selection(selection: &api::Selection) -> Selection {
    Selection {
        start: crate::review::comment::common::Position {
            line: selection.start.line,
            character: selection.start.character,
        },
        end: crate::review::comment::common::Position {
            line: selection.end.line,
            character: selection.end.character,
        },
    }
}

fn to_api_priority(priority: &Priority) -> api::Priority {
    match priority {
        Priority::Critical => api::Priority::Critical,
        Priority::Medium => api::Priority::Medium,
        Priority::Low => api::Priority::Low,
    }
}

fn from_api_priority(priority: &api::Priority) -> Priority {
    match priority {
        api::Priority::Critical => Priority::Critical,
        api::Priority::Medium => Priority::Medium,
        api::Priority::Low => Priority::Low,
    }
}

fn to_api_security_summary(summary: &SecuritySummary) -> api::SecuritySummary {
    match summary {
        SecuritySummary::Critical => api::SecuritySummary::Critical,
        SecuritySummary::Medium => api::SecuritySummary::Medium,
        SecuritySummary::Low => api::SecuritySummary::Low,
        SecuritySummary::None => api::SecuritySummary::None,
    }
}

fn from_api_security_summary(summary: &api::SecuritySummary) -> SecuritySummary {
    match summary {
        api::SecuritySummary::Critical => SecuritySummary::Critical,
        api::SecuritySummary::Medium => SecuritySummary::Medium,
        api::SecuritySummary::Low => SecuritySummary::Low,
        api::SecuritySummary::None => SecuritySummary::None,
    }
}

fn to_api_confidence(confidence: &ReviewConfidence) -> api::ReviewConfidence {
    match confidence {
        ReviewConfidence::High => api::ReviewConfidence::High,
        ReviewConfidence::Medium => api::ReviewConfidence::Medium,
        ReviewConfidence::Low => api::ReviewConfidence::Low,
    }
}

fn from_api_confidence(confidence: &api::ReviewConfidence) -> ReviewConfidence {
    match confidence {
        api::ReviewConfidence::High => ReviewConfidence::High,
        api::ReviewConfidence::Medium => ReviewConfidence::Medium,
        api::ReviewConfidence::Low => ReviewConfidence::Low,
    }
}

fn to_api_reviewer_details(details: &ReviewerDetails) -> api::ReviewerDetails {
    api::ReviewerDetails {
        public_user_id: details.public_user_id.clone(),
        agent_name: details.agent_name.clone(),
        agent_model: details.agent_model.clone(),
        agent_reasoning_effort: details.agent_reasoning_effort.clone(),
        review_strategy: details.review_strategy.clone(),
        review_scope: to_api_review_scope(&details.review_scope),
        created_at: details.created_at.clone(),
        thirdpass_version: details.thirdpass_version.clone(),
    }
}

fn from_api_reviewer_details(details: &api::ReviewerDetails) -> ReviewerDetails {
    ReviewerDetails {
        public_user_id: details.public_user_id.clone(),
        agent_name: details.agent_name.clone(),
        agent_model: details.agent_model.clone(),
        agent_reasoning_effort: details.agent_reasoning_effort.clone(),
        review_strategy: details.review_strategy.clone(),
        review_scope: from_api_review_scope(&details.review_scope),
        created_at: details.created_at.clone(),
        thirdpass_version: details.thirdpass_version.clone(),
    }
}

fn to_api_review_scope(scope: &review::ReviewScope) -> api::ReviewScope {
    match scope {
        review::ReviewScope::TargetFileFull => api::ReviewScope::TargetFileFull,
        review::ReviewScope::TargetFilePartial => api::ReviewScope::TargetFilePartial,
    }
}

fn from_api_review_scope(scope: &api::ReviewScope) -> review::ReviewScope {
    match scope {
        api::ReviewScope::TargetFileFull => review::ReviewScope::TargetFileFull,
        api::ReviewScope::TargetFilePartial => review::ReviewScope::TargetFilePartial,
    }
}

fn get_primary_registry<'a>(package: &'a package::Package) -> Result<&'a registry::Registry> {
    let registry = package
        .registries
        .iter()
        .next()
        .ok_or(format_err!("Package does not have associated registries."))?;
    Ok(registry)
}

fn build_registry(target: &api::ReviewTarget) -> Result<registry::Registry> {
    let host = target.registry_host.as_str();
    let human_url = url::Url::parse(&format!("https://{}/", host))?;
    let artifact_url = url::Url::parse(&format!("https://{}/artifact", host))?;
    Ok(registry::Registry {
        id: 0,
        host_name: target.registry_host.clone(),
        human_url,
        artifact_url,
    })
}

fn build_package(target: &api::ReviewTarget, registry: &registry::Registry) -> package::Package {
    package::Package {
        id: 0,
        name: target.package_name.clone(),
        version: target.package_version.clone(),
        registries: maplit::btreeset! { registry.clone() },
        package_hash: target.package_hash.clone(),
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn to_api_review_files_preserves_file_hash() {
        let file_hash = api::FileHash::blake3("abc123");
        let targets = vec![review::ReviewTarget {
            file_path: std::path::PathBuf::from("index.js"),
            file_hash: Some(file_hash.clone()),
            agent_summary: Some("Reviewed the file.".to_string()),
            security_summary: Some(SecuritySummary::Low),
            confidence: Some(ReviewConfidence::High),
            comments: std::collections::BTreeSet::new(),
        }];

        let files = to_api_review_files(&targets);

        assert_eq!(files.len(), 1);
        assert_eq!(files[0].file_path, "index.js");
        assert_eq!(files[0].file_hash, Some(file_hash));
        assert_eq!(files[0].summary.as_deref(), Some("Reviewed the file."));
        assert_eq!(files[0].security_summary, Some(api::SecuritySummary::Low));
        assert_eq!(files[0].confidence, Some(api::ReviewConfidence::High));
    }

    #[test]
    fn review_submit_response_reads_public_user_id() {
        let response: ReviewSubmitResponse =
            serde_json::from_str(r#"{"id":"rev_1","public_user_id":"user-1"}"#)
                .expect("failed to parse response");

        assert_eq!(response.id, "rev_1");
        assert_eq!(response.public_user_id, "user-1");
    }

    #[test]
    fn authentication_required_error_tells_user_how_to_configure_api_key() {
        let err: anyhow::Error = AuthenticationRequiredError::new(
            StatusCode::UNAUTHORIZED,
            "missing bearer token".to_string(),
        )
        .into();

        assert!(is_authentication_required_error(&err));
        assert!(err
            .to_string()
            .contains("thirdpass config set core.api-key <key>"));
        assert!(err.to_string().contains("missing bearer token"));
    }

    #[test]
    fn forbidden_status_is_treated_as_authentication_required() {
        assert!(is_authentication_required_status(StatusCode::FORBIDDEN));
    }

    #[test]
    fn supported_registry_hosts_uses_enabled_extensions() {
        let mut config = common::config::Config::default();
        config.extensions.enabled.insert("js".to_string(), true);
        config.extensions.enabled.insert("rs".to_string(), false);
        config
            .extensions
            .registries
            .insert("npmjs.com".to_string(), "js".to_string());
        config
            .extensions
            .registries
            .insert("crates.io".to_string(), "rs".to_string());

        assert_eq!(supported_registry_hosts(&config), vec!["npmjs.com"]);
    }
}