mockforge-registry-core 0.3.137

Shared domain models, storage abstractions, and OSS-safe handlers for MockForge's registry backends (SaaS Postgres + OSS SQLite admin UI).
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
//! Plugin model

use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use sqlx::FromRow;
use uuid::Uuid;

#[derive(Debug, Clone, FromRow, Serialize, Deserialize)]
pub struct Plugin {
    pub id: Uuid,
    pub name: String,
    pub description: String,
    pub current_version: String,
    pub category: String,
    pub license: String,
    pub repository: Option<String>,
    pub homepage: Option<String>,
    pub downloads_total: i64,
    pub rating_avg: rust_decimal::Decimal,
    pub rating_count: i32,
    pub author_id: Uuid,
    pub verified_at: Option<DateTime<Utc>>,
    pub created_at: DateTime<Utc>,
    pub updated_at: DateTime<Utc>,
    #[sqlx(default)]
    pub language: String,
    #[sqlx(default)]
    pub taken_down_at: Option<DateTime<Utc>>,
    #[sqlx(default)]
    pub taken_down_reason: Option<String>,
}

#[derive(Debug, Clone, FromRow, Serialize, Deserialize)]
pub struct PluginVersion {
    pub id: Uuid,
    pub plugin_id: Uuid,
    pub version: String,
    pub download_url: String,
    pub checksum: String,
    pub file_size: i64,
    pub min_mockforge_version: Option<String>,
    pub yanked: bool,
    pub downloads: i32,
    pub published_at: DateTime<Utc>,
    /// Optional Software Bill of Materials (typically CycloneDX JSON)
    /// submitted at publish time. Used by the vulnerability-scan step of
    /// the plugin security worker. Absent on versions published before
    /// SBOM support shipped.
    #[sqlx(default)]
    pub sbom_json: Option<serde_json::Value>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PluginWithVersions {
    #[serde(flatten)]
    pub plugin: Plugin,
    pub versions: Vec<PluginVersion>,
    pub tags: Vec<String>,
}

#[derive(Debug, Clone, FromRow, Serialize, Deserialize)]
pub struct PluginSecurityScan {
    pub id: Uuid,
    pub plugin_version_id: Uuid,
    pub status: String,
    pub score: i16,
    pub findings: serde_json::Value,
    pub scanner_version: Option<String>,
    pub scanned_at: DateTime<Utc>,
}

/// Context needed by the background scanner worker to re-download a plugin
/// artifact and rewrite its scan row. `plugin_version_id` is the PK the worker
/// upserts against; `plugin_name` + `version` reconstruct the storage key.
#[derive(Debug, Clone, FromRow, Serialize, Deserialize)]
pub struct PendingScanJob {
    pub plugin_version_id: Uuid,
    pub plugin_name: String,
    pub version: String,
    pub file_size: i64,
    pub checksum: String,
}

#[cfg(feature = "postgres")]
impl Plugin {
    /// Search plugins
    #[allow(clippy::too_many_arguments)]
    pub async fn search(
        pool: &sqlx::PgPool,
        query: Option<&str>,
        category: Option<&str>,
        language: Option<&str>,
        tags: &[String],
        sort_by: &str,
        limit: i64,
        offset: i64,
    ) -> sqlx::Result<Vec<Self>> {
        let mut sql = String::from(
            r#"
            SELECT DISTINCT p.*
            FROM plugins p
            "#,
        );

        let mut conditions = Vec::new();
        let mut params_count = 0;

        // Add tag filtering if needed
        if !tags.is_empty() {
            sql.push_str(
                r#"
                INNER JOIN plugin_tags pt ON p.id = pt.plugin_id
                INNER JOIN tags t ON pt.tag_id = t.id
                "#,
            );
            params_count += 1;
            conditions.push(format!("t.name = ANY(${})", params_count));
        }

        // Hide taken-down plugins from public search. The admin UI loads
        // them through a separate query path (`Plugin::find_by_name` does
        // not filter on this) so moderation stays reversible.
        sql.push_str(" WHERE p.taken_down_at IS NULL ");

        // Add search query
        if let Some(_q) = query {
            params_count += 1;
            conditions
                .push(format!("p.search_vector @@ plainto_tsquery('english', ${})", params_count));
        }

        // Add category filter
        if let Some(_cat) = category {
            params_count += 1;
            conditions.push(format!("p.category = ${}", params_count));
        }

        // Add language filter
        if let Some(_lang) = language {
            params_count += 1;
            conditions.push(format!("p.language = ${}", params_count));
        }

        if !conditions.is_empty() {
            sql.push_str(" AND ");
            sql.push_str(&conditions.join(" AND "));
        }

        // Add sorting. "popular" weights ratings into the ranking so
        // well-loved-but-less-downloaded plugins surface above silently
        // popular ones; "security" floats verified plugins to the top
        // (matching how `derive_security_score` boosts verified entries
        // by 35 points).
        match sort_by {
            "downloads" => sql.push_str(" ORDER BY p.downloads_total DESC"),
            "rating" => sql.push_str(" ORDER BY p.rating_avg DESC, p.rating_count DESC"),
            "recent" => sql.push_str(" ORDER BY p.updated_at DESC"),
            "name" => sql.push_str(" ORDER BY p.name ASC"),
            "popular" => sql.push_str(
                " ORDER BY (p.downloads_total + (p.rating_avg * p.rating_count * 100)::bigint) DESC",
            ),
            "security" => sql.push_str(
                " ORDER BY (p.verified_at IS NOT NULL) DESC, p.rating_avg DESC, p.downloads_total DESC",
            ),
            _ => sql.push_str(" ORDER BY p.downloads_total DESC"),
        }

        params_count += 2;
        sql.push_str(&format!(" LIMIT ${} OFFSET ${}", params_count - 1, params_count));

        let mut query_builder = sqlx::query_as::<_, Self>(&sql);

        // Bind parameters in order
        if !tags.is_empty() {
            query_builder = query_builder.bind(tags);
        }
        if let Some(q) = query {
            query_builder = query_builder.bind(q);
        }
        if let Some(cat) = category {
            query_builder = query_builder.bind(cat);
        }
        if let Some(lang) = language {
            query_builder = query_builder.bind(lang);
        }
        query_builder = query_builder.bind(limit).bind(offset);

        query_builder.fetch_all(pool).await
    }

    /// Count total matching plugins for a search (used for pagination)
    pub async fn count_search(
        pool: &sqlx::PgPool,
        query: Option<&str>,
        category: Option<&str>,
        language: Option<&str>,
        tags: &[String],
    ) -> sqlx::Result<i64> {
        let mut sql = String::from(
            r#"
            SELECT COUNT(DISTINCT p.id)
            FROM plugins p
            "#,
        );

        let mut conditions = Vec::new();
        let mut params_count = 0;

        if !tags.is_empty() {
            sql.push_str(
                r#"
                INNER JOIN plugin_tags pt ON p.id = pt.plugin_id
                INNER JOIN tags t ON pt.tag_id = t.id
                "#,
            );
            params_count += 1;
            conditions.push(format!("t.name = ANY(${})", params_count));
        }

        // Same taken-down filter as `search` so the count matches the
        // page rendered to anonymous / non-admin users.
        sql.push_str(" WHERE p.taken_down_at IS NULL ");

        if let Some(_q) = query {
            params_count += 1;
            conditions
                .push(format!("p.search_vector @@ plainto_tsquery('english', ${})", params_count));
        }

        if let Some(_cat) = category {
            params_count += 1;
            conditions.push(format!("p.category = ${}", params_count));
        }

        if let Some(_lang) = language {
            params_count += 1;
            conditions.push(format!("p.language = ${}", params_count));
        }

        if !conditions.is_empty() {
            sql.push_str(" AND ");
            sql.push_str(&conditions.join(" AND "));
        }

        let mut query_builder = sqlx::query_scalar::<_, i64>(&sql);

        if !tags.is_empty() {
            query_builder = query_builder.bind(tags);
        }
        if let Some(q) = query {
            query_builder = query_builder.bind(q);
        }
        if let Some(cat) = category {
            query_builder = query_builder.bind(cat);
        }
        if let Some(lang) = language {
            query_builder = query_builder.bind(lang);
        }

        query_builder.fetch_one(pool).await
    }

    /// Find plugin by name
    pub async fn find_by_name(pool: &sqlx::PgPool, name: &str) -> sqlx::Result<Option<Self>> {
        sqlx::query_as::<_, Self>("SELECT * FROM plugins WHERE name = $1")
            .bind(name)
            .fetch_optional(pool)
            .await
    }

    /// Get plugin tags
    pub async fn get_tags(pool: &sqlx::PgPool, plugin_id: Uuid) -> sqlx::Result<Vec<String>> {
        let tags: Vec<(String,)> = sqlx::query_as(
            r#"
            SELECT t.name
            FROM tags t
            INNER JOIN plugin_tags pt ON t.id = pt.tag_id
            WHERE pt.plugin_id = $1
            "#,
        )
        .bind(plugin_id)
        .fetch_all(pool)
        .await?;

        Ok(tags.into_iter().map(|(name,)| name).collect())
    }

    /// Create new plugin
    #[allow(clippy::too_many_arguments)]
    pub async fn create(
        pool: &sqlx::PgPool,
        name: &str,
        description: &str,
        version: &str,
        category: &str,
        license: &str,
        repository: Option<&str>,
        homepage: Option<&str>,
        author_id: Uuid,
        language: &str,
    ) -> sqlx::Result<Self> {
        sqlx::query_as::<_, Self>(
            r#"
            INSERT INTO plugins (
                name, description, current_version, category, license,
                repository, homepage, author_id, language
            )
            VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)
            RETURNING *
            "#,
        )
        .bind(name)
        .bind(description)
        .bind(version)
        .bind(category)
        .bind(license)
        .bind(repository)
        .bind(homepage)
        .bind(author_id)
        .bind(language)
        .fetch_one(pool)
        .await
    }

    /// Increment download count
    pub async fn increment_downloads(pool: &sqlx::PgPool, plugin_id: Uuid) -> sqlx::Result<()> {
        sqlx::query("UPDATE plugins SET downloads_total = downloads_total + 1 WHERE id = $1")
            .bind(plugin_id)
            .execute(pool)
            .await?;
        Ok(())
    }

    /// Mark a plugin as taken-down. The reason is surfaced to admins on the
    /// detail view so they remember why moderation acted.
    pub async fn take_down(
        pool: &sqlx::PgPool,
        plugin_id: Uuid,
        reason: Option<&str>,
    ) -> sqlx::Result<()> {
        sqlx::query(
            "UPDATE plugins SET taken_down_at = NOW(), taken_down_reason = $2 WHERE id = $1",
        )
        .bind(plugin_id)
        .bind(reason)
        .execute(pool)
        .await?;
        Ok(())
    }

    /// Reverse a takedown — clears both the timestamp and the reason so the
    /// plugin reappears in search.
    pub async fn restore(pool: &sqlx::PgPool, plugin_id: Uuid) -> sqlx::Result<()> {
        sqlx::query(
            "UPDATE plugins SET taken_down_at = NULL, taken_down_reason = NULL WHERE id = $1",
        )
        .bind(plugin_id)
        .execute(pool)
        .await?;
        Ok(())
    }

    /// Returns every plugin currently flagged as taken-down, newest first.
    /// Powers the admin moderation page; the public search filters these
    /// out, so this is the only path to find them once a takedown has
    /// happened (apart from the per-action audit row).
    pub async fn list_taken_down(pool: &sqlx::PgPool) -> sqlx::Result<Vec<Self>> {
        sqlx::query_as::<_, Self>(
            "SELECT * FROM plugins WHERE taken_down_at IS NOT NULL ORDER BY taken_down_at DESC",
        )
        .fetch_all(pool)
        .await
    }
}

#[cfg(feature = "postgres")]
impl PluginVersion {
    /// Get all versions for a plugin
    pub async fn get_by_plugin(pool: &sqlx::PgPool, plugin_id: Uuid) -> sqlx::Result<Vec<Self>> {
        sqlx::query_as::<_, Self>(
            "SELECT * FROM plugin_versions WHERE plugin_id = $1 ORDER BY published_at DESC",
        )
        .bind(plugin_id)
        .fetch_all(pool)
        .await
    }

    /// Find specific version
    pub async fn find(
        pool: &sqlx::PgPool,
        plugin_id: Uuid,
        version: &str,
    ) -> sqlx::Result<Option<Self>> {
        sqlx::query_as::<_, Self>(
            "SELECT * FROM plugin_versions WHERE plugin_id = $1 AND version = $2",
        )
        .bind(plugin_id)
        .bind(version)
        .fetch_optional(pool)
        .await
    }

    /// Create new version
    #[allow(clippy::too_many_arguments)]
    pub async fn create(
        pool: &sqlx::PgPool,
        plugin_id: Uuid,
        version: &str,
        download_url: &str,
        checksum: &str,
        file_size: i64,
        min_mockforge_version: Option<&str>,
        sbom_json: Option<&serde_json::Value>,
    ) -> sqlx::Result<Self> {
        sqlx::query_as::<_, Self>(
            r#"
            INSERT INTO plugin_versions (
                plugin_id, version, download_url, checksum, file_size,
                min_mockforge_version, sbom_json
            )
            VALUES ($1, $2, $3, $4, $5, $6, $7)
            RETURNING *
            "#,
        )
        .bind(plugin_id)
        .bind(version)
        .bind(download_url)
        .bind(checksum)
        .bind(file_size)
        .bind(min_mockforge_version)
        .bind(sbom_json)
        .fetch_one(pool)
        .await
    }

    /// Yank a version
    pub async fn yank(pool: &sqlx::PgPool, version_id: Uuid) -> sqlx::Result<()> {
        sqlx::query("UPDATE plugin_versions SET yanked = true WHERE id = $1")
            .bind(version_id)
            .execute(pool)
            .await?;
        Ok(())
    }

    /// Increment download count
    pub async fn increment_downloads(pool: &sqlx::PgPool, version_id: Uuid) -> sqlx::Result<()> {
        sqlx::query("UPDATE plugin_versions SET downloads = downloads + 1 WHERE id = $1")
            .bind(version_id)
            .execute(pool)
            .await?;
        Ok(())
    }

    /// Get dependencies for a version
    pub async fn get_dependencies(
        pool: &sqlx::PgPool,
        version_id: Uuid,
    ) -> sqlx::Result<std::collections::HashMap<String, String>> {
        let deps = sqlx::query_as::<_, (String, String)>(
            "SELECT depends_on_plugin, version_requirement FROM plugin_dependencies WHERE version_id = $1"
        )
        .bind(version_id)
        .fetch_all(pool)
        .await?;

        Ok(deps.into_iter().collect())
    }

    /// Add dependency
    pub async fn add_dependency(
        pool: &sqlx::PgPool,
        version_id: Uuid,
        plugin_name: &str,
        version_req: &str,
    ) -> sqlx::Result<()> {
        sqlx::query(
            "INSERT INTO plugin_dependencies (version_id, depends_on_plugin, version_requirement) VALUES ($1, $2, $3)"
        )
        .bind(version_id)
        .bind(plugin_name)
        .bind(version_req)
        .execute(pool)
        .await?;
        Ok(())
    }
}