mockforge-registry-server 0.3.127

Plugin registry server for MockForge
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
//! Admin handlers

use axum::{
    extract::{Path, State},
    Extension, Json,
};
use chrono::Utc;
use serde::{Deserialize, Serialize};
use uuid::Uuid;

use crate::{
    error::{ApiError, ApiResult},
    models::{AuditEventType, Plugin},
    AppState,
};

#[derive(Debug, Deserialize)]
pub struct VerifyPluginRequest {
    pub verified: bool,
}

#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct TakedownPluginRequest {
    /// Optional reason shown on the admin detail view. Stored on the
    /// plugin row so admins reviewing past moderation see why.
    #[serde(default)]
    pub reason: Option<String>,
}

#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct TakedownPluginResponse {
    pub success: bool,
    pub plugin_name: String,
    pub taken_down: bool,
    pub taken_down_at: Option<String>,
    pub reason: Option<String>,
    pub message: String,
}

#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct VerifyPluginResponse {
    pub success: bool,
    pub plugin_name: String,
    pub verified: bool,
    pub verified_at: Option<String>,
    pub message: String,
}

pub async fn verify_plugin(
    State(state): State<AppState>,
    Path(name): Path<String>,
    Extension(user_id): Extension<String>,
    Json(request): Json<VerifyPluginRequest>,
) -> ApiResult<Json<VerifyPluginResponse>> {
    let pool = state.db.pool();

    // Parse user_id
    let user_uuid = Uuid::parse_str(&user_id)
        .map_err(|_| ApiError::InvalidRequest("Invalid user ID".to_string()))?;

    // Check if user is admin
    let user = sqlx::query_as::<_, (bool,)>("SELECT is_admin FROM users WHERE id = $1")
        .bind(user_uuid)
        .fetch_one(pool)
        .await
        .map_err(ApiError::Database)?;

    if !user.0 {
        return Err(ApiError::PermissionDenied);
    }

    // Get plugin
    let plugin = Plugin::find_by_name(pool, &name)
        .await
        .map_err(ApiError::Database)?
        .ok_or_else(|| ApiError::PluginNotFound(name.clone()))?;

    // Update verification status
    let verified_at = if request.verified {
        Some(Utc::now())
    } else {
        None
    };

    sqlx::query("UPDATE plugins SET verified_at = $1 WHERE id = $2")
        .bind(verified_at)
        .bind(plugin.id)
        .execute(pool)
        .await
        .map_err(ApiError::Database)?;

    let message = if request.verified {
        format!("Plugin '{}' has been verified", name)
    } else {
        format!("Plugin '{}' verification has been removed", name)
    };

    // Record audit event for admin verification action
    state
        .store
        .record_audit_event(
            Uuid::nil(),
            Some(user_uuid),
            AuditEventType::AdminImpersonation, // Reusing admin action type for verification
            message.clone(),
            Some(serde_json::json!({
                "plugin_name": name,
                "verified": request.verified,
                "action": "verify_plugin",
            })),
            None,
            None,
        )
        .await;

    Ok(Json(VerifyPluginResponse {
        success: true,
        plugin_name: name,
        verified: request.verified,
        verified_at: verified_at.map(|dt| dt.to_rfc3339()),
        message,
    }))
}

/// Soft-delete a plugin from the public catalog. Reversible via
/// `restore_plugin` — installed copies keep working because we only flip
/// flags; we don't drop rows.
pub async fn takedown_plugin(
    State(state): State<AppState>,
    Path(name): Path<String>,
    Extension(user_id): Extension<String>,
    Json(request): Json<TakedownPluginRequest>,
) -> ApiResult<Json<TakedownPluginResponse>> {
    let pool = state.db.pool();

    let user_uuid = Uuid::parse_str(&user_id)
        .map_err(|_| ApiError::InvalidRequest("Invalid user ID".to_string()))?;

    let user = sqlx::query_as::<_, (bool,)>("SELECT is_admin FROM users WHERE id = $1")
        .bind(user_uuid)
        .fetch_one(pool)
        .await
        .map_err(ApiError::Database)?;
    if !user.0 {
        return Err(ApiError::PermissionDenied);
    }

    let plugin = Plugin::find_by_name(pool, &name)
        .await
        .map_err(ApiError::Database)?
        .ok_or_else(|| ApiError::PluginNotFound(name.clone()))?;

    let reason = request.reason.as_deref().map(str::trim).filter(|s| !s.is_empty());
    state.store.take_down_plugin(plugin.id, reason).await?;

    let message = format!("Plugin '{}' has been taken down", name);
    state
        .store
        .record_audit_event(
            Uuid::nil(),
            Some(user_uuid),
            AuditEventType::PluginTakenDown,
            message.clone(),
            Some(serde_json::json!({
                "plugin_name": name,
                "reason": reason,
            })),
            None,
            None,
        )
        .await;

    Ok(Json(TakedownPluginResponse {
        success: true,
        plugin_name: name,
        taken_down: true,
        taken_down_at: Some(Utc::now().to_rfc3339()),
        reason: reason.map(str::to_string),
        message,
    }))
}

/// Reverse a takedown — clears both the timestamp and the stored reason.
pub async fn restore_plugin(
    State(state): State<AppState>,
    Path(name): Path<String>,
    Extension(user_id): Extension<String>,
) -> ApiResult<Json<TakedownPluginResponse>> {
    let pool = state.db.pool();

    let user_uuid = Uuid::parse_str(&user_id)
        .map_err(|_| ApiError::InvalidRequest("Invalid user ID".to_string()))?;

    let user = sqlx::query_as::<_, (bool,)>("SELECT is_admin FROM users WHERE id = $1")
        .bind(user_uuid)
        .fetch_one(pool)
        .await
        .map_err(ApiError::Database)?;
    if !user.0 {
        return Err(ApiError::PermissionDenied);
    }

    let plugin = Plugin::find_by_name(pool, &name)
        .await
        .map_err(ApiError::Database)?
        .ok_or_else(|| ApiError::PluginNotFound(name.clone()))?;

    state.store.restore_plugin(plugin.id).await?;

    let message = format!("Plugin '{}' has been restored", name);
    state
        .store
        .record_audit_event(
            Uuid::nil(),
            Some(user_uuid),
            AuditEventType::PluginRestored,
            message.clone(),
            Some(serde_json::json!({ "plugin_name": name })),
            None,
            None,
        )
        .await;

    Ok(Json(TakedownPluginResponse {
        success: true,
        plugin_name: name,
        taken_down: false,
        taken_down_at: None,
        reason: None,
        message,
    }))
}

#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct TakenDownPluginEntry {
    pub name: String,
    pub description: String,
    pub category: String,
    pub current_version: String,
    pub author: TakenDownAuthorInfo,
    pub taken_down_at: String,
    pub reason: Option<String>,
}

#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct TakenDownAuthorInfo {
    pub id: String,
    pub username: String,
    pub email: Option<String>,
}

#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ListTakenDownResponse {
    pub plugins: Vec<TakenDownPluginEntry>,
    pub total: usize,
}

/// Admin moderation: list every plugin that's currently taken-down.
/// `Plugin::search` filters these out, so this is the only programmatic
/// path for the moderation UI to find them after the post-takedown
/// snackbar window closes.
pub async fn list_taken_down_plugins(
    State(state): State<AppState>,
    Extension(user_id): Extension<String>,
) -> ApiResult<Json<ListTakenDownResponse>> {
    let pool = state.db.pool();

    let user_uuid = Uuid::parse_str(&user_id)
        .map_err(|_| ApiError::InvalidRequest("Invalid user ID".to_string()))?;

    let user = sqlx::query_as::<_, (bool,)>("SELECT is_admin FROM users WHERE id = $1")
        .bind(user_uuid)
        .fetch_one(pool)
        .await
        .map_err(ApiError::Database)?;
    if !user.0 {
        return Err(ApiError::PermissionDenied);
    }

    let plugins = state.store.list_taken_down_plugins().await?;
    let mut entries = Vec::with_capacity(plugins.len());
    for plugin in plugins {
        let author = state
            .store
            .find_user_by_id(plugin.author_id)
            .await?
            .unwrap_or_else(|| crate::models::User::placeholder(plugin.author_id));
        entries.push(TakenDownPluginEntry {
            name: plugin.name,
            description: plugin.description,
            category: plugin.category,
            current_version: plugin.current_version,
            author: TakenDownAuthorInfo {
                id: author.id.to_string(),
                username: author.username,
                email: Some(author.email),
            },
            // taken_down_at is guaranteed Some by the SQL filter, but
            // keep a defensive fallback so a clock-skew or column
            // regression can't crash the page.
            taken_down_at: plugin.taken_down_at.map(|dt| dt.to_rfc3339()).unwrap_or_default(),
            reason: plugin.taken_down_reason,
        });
    }

    let total = entries.len();
    Ok(Json(ListTakenDownResponse {
        plugins: entries,
        total,
    }))
}

#[derive(Debug, Serialize)]
pub struct PluginWithBadges {
    pub name: String,
    pub version: String,
    pub badges: Vec<String>,
}

pub async fn get_plugin_badges(
    State(state): State<AppState>,
    Path(name): Path<String>,
) -> ApiResult<Json<PluginWithBadges>> {
    let pool = state.db.pool();

    // Get plugin
    let plugin = Plugin::find_by_name(pool, &name)
        .await
        .map_err(ApiError::Database)?
        .ok_or_else(|| ApiError::PluginNotFound(name.clone()))?;

    let mut badges = Vec::new();

    // Check for "Official" badge (created by admin user)
    // ADMIN_USER_ID: UUID of the admin user for official plugins
    // Default: "00000000-0000-0000-0000-000000000001"
    let admin_id = std::env::var("ADMIN_USER_ID")
        .ok()
        .and_then(|s| Uuid::parse_str(&s).ok())
        .unwrap_or_else(|| {
            Uuid::parse_str("00000000-0000-0000-0000-000000000001")
                .expect("default admin UUID is valid")
        });
    if plugin.author_id == admin_id {
        badges.push("official".to_string());
    }

    // Check for "Verified" badge
    if plugin.verified_at.is_some() {
        badges.push("verified".to_string());
    }

    // Check for "Popular" badge (1000+ downloads)
    if plugin.downloads_total >= 1000 {
        badges.push("popular".to_string());
    }

    // Check for "Highly Rated" badge (4.5+ stars with 10+ reviews)
    if plugin.rating_avg >= rust_decimal::Decimal::new(45, 1) && plugin.rating_count >= 10 {
        badges.push("highly-rated".to_string());
    }

    // Check for "Maintained" badge (updated within last 90 days)
    let ninety_days_ago = Utc::now() - chrono::Duration::days(90);
    if plugin.updated_at > ninety_days_ago {
        badges.push("maintained".to_string());
    }

    // Check for "Trending" badge (check downloads in last week)
    // For MVP, we'll use a simple heuristic
    if plugin.downloads_total > 100 {
        badges.push("trending".to_string());
    }

    // "Signed" badge — set when the plugin's current version was
    // published with a verified Ed25519 SBOM attestation. The scanner
    // also surfaces this inside security findings, but the badge here
    // makes it visible at the marketplace card level so users can spot
    // signed plugins without opening the security tab.
    let signed: Option<bool> = sqlx::query_scalar(
        r#"
        SELECT (sbom_signed_key_id IS NOT NULL) AS signed
        FROM plugin_versions
        WHERE plugin_id = $1 AND version = $2
        LIMIT 1
        "#,
    )
    .bind(plugin.id)
    .bind(&plugin.current_version)
    .fetch_optional(pool)
    .await
    .map_err(ApiError::Database)?;
    if matches!(signed, Some(true)) {
        badges.push("signed".to_string());
    }

    Ok(Json(PluginWithBadges {
        name: plugin.name,
        version: plugin.current_version,
        badges,
    }))
}

#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct StatsResponse {
    pub total_plugins: i64,
    pub total_downloads: i64,
    pub total_users: i64,
    pub verified_plugins: i64,
    pub total_reviews: i64,
    pub average_rating: f64,
}

pub async fn get_admin_stats(
    State(state): State<AppState>,
    Extension(user_id): Extension<String>,
) -> ApiResult<Json<StatsResponse>> {
    let pool = state.db.pool();

    // Parse user_id
    let user_uuid = Uuid::parse_str(&user_id)
        .map_err(|_| ApiError::InvalidRequest("Invalid user ID".to_string()))?;

    // Check if user is admin
    let user = sqlx::query_as::<_, (bool,)>("SELECT is_admin FROM users WHERE id = $1")
        .bind(user_uuid)
        .fetch_one(pool)
        .await
        .map_err(ApiError::Database)?;

    if !user.0 {
        return Err(ApiError::PermissionDenied);
    }

    // Get stats
    let plugin_stats = sqlx::query_as::<_, (i64, i64, i64)>(
        "SELECT COUNT(*), SUM(downloads_total), COUNT(*) FILTER (WHERE verified_at IS NOT NULL) FROM plugins"
    )
    .fetch_one(pool)
    .await
    .map_err(ApiError::Database)?;

    let user_count = sqlx::query_as::<_, (i64,)>("SELECT COUNT(*) FROM users")
        .fetch_one(pool)
        .await
        .map_err(ApiError::Database)?;

    let review_stats = sqlx::query_as::<_, (i64, f64)>(
        "SELECT COUNT(*), COALESCE(AVG(rating), 0.0)::float8 FROM reviews",
    )
    .fetch_one(pool)
    .await
    .map_err(ApiError::Database)?;

    Ok(Json(StatsResponse {
        total_plugins: plugin_stats.0,
        total_downloads: plugin_stats.1,
        verified_plugins: plugin_stats.2,
        total_users: user_count.0,
        total_reviews: review_stats.0,
        average_rating: review_stats.1,
    }))
}