mockforge-registry-server 0.3.128

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
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
//! Template marketplace handlers
//!
//! Provides endpoints for the template marketplace (orchestration templates for chaos testing)

use axum::{
    extract::{Path, State},
    http::HeaderMap,
    Json,
};
use base64::Engine;
use serde::{Deserialize, Serialize};

use crate::{
    error::{ApiError, ApiResult},
    middleware::{resolve_org_context, AuthUser, OptionalAuthUser},
    models::{AuditEventType, FeatureType, TemplateCategory, TemplateVersion, UsageCounter, User},
    AppState,
};

/// Search templates
/// Supports org filtering: if user is authenticated, includes their org's private templates
pub async fn search_templates(
    State(state): State<AppState>,
    OptionalAuthUser(maybe_user_id): OptionalAuthUser,
    headers: HeaderMap,
    Json(query): Json<TemplateSearchQuery>,
) -> ApiResult<Json<TemplateSearchResults>> {
    let metrics = crate::metrics::MarketplaceMetrics::start(state.metrics.clone(), "template");
    let pool = state.db.pool();

    // Try to resolve org context for filtering (optional)
    // If user is authenticated, include their org's private templates
    let org_id = if let Some(user_id) = maybe_user_id {
        if let Ok(org_ctx) = resolve_org_context(&state, user_id, &headers, None).await {
            Some(org_ctx.org_id)
        } else {
            None
        }
    } else {
        None
    };

    // Validate and limit pagination parameters
    let per_page = query.per_page.clamp(1, 100); // Max 100 items per page
    let page = query.page;
    let limit = per_page as i64;
    let offset = (page * per_page) as i64;

    // Search templates
    let templates = state
        .store
        .search_templates(
            query.query.as_deref(),
            query.category.as_deref(),
            &query.tags,
            org_id,
            limit,
            offset,
        )
        .await?;

    // Get total count for pagination (before converting entries)
    let total = state
        .store
        .count_search_templates(
            query.query.as_deref(),
            query.category.as_deref(),
            &query.tags,
            org_id,
        )
        .await? as usize;

    // Live star counts for this page (stats_json.stars is not the source of
    // truth — see `template_stars` table and models::TemplateStar docs).
    let page_ids: Vec<uuid::Uuid> = templates.iter().map(|t| t.id).collect();
    let star_counts = state.store.count_template_stars_batch(&page_ids).await?;

    // Convert to response format
    let mut entries = Vec::new();
    for template in templates {
        let _versions = TemplateVersion::get_by_template(pool, template.id)
            .await
            .map_err(ApiError::Database)?;

        let author = state
            .store
            .find_user_by_id(template.author_id)
            .await?
            .unwrap_or_else(|| User::placeholder(template.author_id));

        let stats = template.stats_json.clone();
        let compatibility = template.compatibility_json.clone();
        let category = template.category();
        let template_name = template.name.clone();
        let live_stars = star_counts.get(&template.id).copied().unwrap_or(0);

        let mut stats_out =
            serde_json::from_value::<TemplateStats>(stats).unwrap_or(TemplateStats {
                downloads: 0,
                stars: 0,
                forks: 0,
                rating: 0.0,
                rating_count: 0,
            });
        stats_out.stars = live_stars as u64;

        entries.push(TemplateRegistryEntry {
            id: template.id.to_string(),
            name: template.name,
            description: template.description,
            author: author.username,
            author_email: Some(author.email),
            version: template.version,
            category,
            tags: template.tags,
            content: template.content_json,
            readme: template.readme,
            example_usage: template.example_usage,
            requirements: template.requirements,
            compatibility: serde_json::from_value(compatibility).unwrap_or_else(|e| {
                tracing::warn!(
                    "Failed to parse compatibility JSON for template '{}': {}",
                    template_name,
                    e
                );
                CompatibilityInfo {
                    min_version: "0.1.0".to_string(),
                    max_version: None,
                    required_features: vec![],
                    protocols: vec![],
                }
            }),
            stats: stats_out,
            created_at: template.created_at.to_rfc3339(),
            updated_at: template.updated_at.to_rfc3339(),
            published: template.published,
        });
    }

    // Record metrics
    metrics.record_search_success();

    Ok(Json(TemplateSearchResults {
        templates: entries,
        total,
        page,
        per_page,
    }))
}

/// Get template by name and version
pub async fn get_template(
    State(state): State<AppState>,
    Path((name, version)): Path<(String, String)>,
) -> ApiResult<Json<TemplateRegistryEntry>> {
    let metrics = crate::metrics::MarketplaceMetrics::start(state.metrics.clone(), "template");

    let template = state
        .store
        .find_template_by_name_version(&name, &version)
        .await?
        .ok_or_else(|| ApiError::TemplateNotFound(format!("{}@{}", name, version)))?;

    let author = state
        .store
        .find_user_by_id(template.author_id)
        .await?
        .unwrap_or_else(|| User::placeholder(template.author_id));

    let stats = template.stats_json.clone();
    let compatibility = template.compatibility_json.clone();
    let category = template.category();
    let template_name = template.name.clone();
    let live_stars = state.store.count_template_stars(template.id).await?;

    let mut stats_out = serde_json::from_value::<TemplateStats>(stats).unwrap_or(TemplateStats {
        downloads: 0,
        stars: 0,
        forks: 0,
        rating: 0.0,
        rating_count: 0,
    });
    stats_out.stars = live_stars as u64;

    // Record metrics
    metrics.record_download_success();

    Ok(Json(TemplateRegistryEntry {
        id: template.id.to_string(),
        name: template.name,
        description: template.description,
        author: author.username,
        author_email: Some(author.email),
        version: template.version,
        category,
        tags: template.tags,
        content: template.content_json,
        readme: template.readme,
        example_usage: template.example_usage,
        requirements: template.requirements,
        compatibility: serde_json::from_value(compatibility).unwrap_or_else(|e| {
            tracing::warn!(
                "Failed to parse compatibility JSON for template '{}': {}",
                template_name,
                e
            );
            CompatibilityInfo {
                min_version: "0.1.0".to_string(),
                max_version: None,
                required_features: vec![],
                protocols: vec![],
            }
        }),
        stats: stats_out,
        created_at: template.created_at.to_rfc3339(),
        updated_at: template.updated_at.to_rfc3339(),
        published: template.published,
    }))
}

/// Publish a template
pub async fn publish_template(
    State(state): State<AppState>,
    AuthUser(author_id): AuthUser,
    headers: HeaderMap,
    Json(request): Json<PublishTemplateRequest>,
) -> ApiResult<Json<PublishTemplateResponse>> {
    let metrics = crate::metrics::MarketplaceMetrics::start(state.metrics.clone(), "template");
    let pool = state.db.pool();

    // Resolve org context
    let org_ctx = resolve_org_context(&state, author_id, &headers, None)
        .await
        .map_err(|_| ApiError::OrganizationNotFound)?;

    // Check publishing limits
    let limits = &org_ctx.org.limits_json;
    let max_templates = limits.get("max_templates_published").and_then(|v| v.as_i64()).unwrap_or(3);

    if max_templates >= 0 {
        let existing = state.store.list_templates_by_org(org_ctx.org_id).await?;

        if existing.len() as i64 >= max_templates {
            return Err(ApiError::InvalidRequest(format!(
                "Template limit exceeded. Your plan allows {} templates. Upgrade to publish more.",
                max_templates
            )));
        }
    }

    // Check storage limit
    let storage_limit_gb = limits.get("storage_gb").and_then(|v| v.as_i64()).unwrap_or(1);
    let storage_limit_bytes = storage_limit_gb * 1_000_000_000;

    let usage = UsageCounter::get_or_create_current(pool, org_ctx.org_id)
        .await
        .map_err(ApiError::Database)?;

    let new_storage = usage.storage_bytes + request.file_size;
    if new_storage > storage_limit_bytes {
        return Err(ApiError::InvalidRequest(format!(
            "Storage limit exceeded. Your plan allows {} GB.",
            storage_limit_gb
        )));
    }

    // Validate input fields
    crate::validation::validate_name(&request.name)?;
    crate::validation::validate_name(&request.slug)?;
    crate::validation::validate_version(&request.version)?;
    crate::validation::validate_checksum(&request.checksum)?;

    // Validate base64 encoding
    crate::validation::validate_base64(&request.package)?;

    // Decode package data
    let package_data = base64::engine::general_purpose::STANDARD
        .decode(&request.package)
        .map_err(|e| ApiError::InvalidRequest(format!("Invalid base64: {}", e)))?;

    // Validate package file
    crate::validation::validate_package_file(
        &package_data,
        request.file_size as u64,
        crate::validation::MAX_TEMPLATE_SIZE,
    )?;

    // Verify checksum
    use sha2::{Digest, Sha256};
    let mut hasher = Sha256::new();
    hasher.update(&package_data);
    let calculated_checksum = hex::encode(hasher.finalize());

    if calculated_checksum != request.checksum {
        return Err(ApiError::InvalidRequest("Checksum mismatch".to_string()));
    }

    // Upload to storage
    let download_url = state
        .storage
        .upload_template(&request.name, &request.version, package_data)
        .await
        .map_err(|e| ApiError::Storage(e.to_string()))?;

    // Create or update template
    let template = if let Some(existing) = state
        .store
        .find_template_by_name_version(&request.name, &request.version)
        .await?
    {
        existing
    } else {
        state
            .store
            .create_template(
                Some(org_ctx.org_id),
                &request.name,
                &request.slug,
                &request.description,
                author_id,
                &request.version,
                request.category,
                request.content_json.clone(),
            )
            .await?
    };

    // Create version entry
    TemplateVersion::create(
        pool,
        template.id,
        &request.version,
        request.content_json,
        Some(&download_url),
        Some(&request.checksum),
        request.file_size,
    )
    .await
    .map_err(ApiError::Database)?;

    // Update storage usage
    UsageCounter::update_storage(pool, org_ctx.org_id, new_storage)
        .await
        .map_err(ApiError::Database)?;

    // Track feature usage
    state
        .store
        .record_feature_usage(
            org_ctx.org_id,
            Some(author_id),
            FeatureType::TemplatePublish,
            Some(serde_json::json!({
                "template_name": request.name,
                "version": request.version,
            })),
        )
        .await;

    // Record audit event
    let ip_address = headers
        .get("X-Forwarded-For")
        .or_else(|| headers.get("X-Real-IP"))
        .and_then(|h| h.to_str().ok())
        .map(|s| s.split(',').next().unwrap_or(s).trim());
    let user_agent = headers.get("User-Agent").and_then(|h| h.to_str().ok());

    state
        .store
        .record_audit_event(
            org_ctx.org_id,
            Some(author_id),
            AuditEventType::TemplatePublished,
            format!("Template {} version {} published", request.name, request.version),
            Some(serde_json::json!({
                "template_name": request.name,
                "version": request.version,
            })),
            ip_address,
            user_agent,
        )
        .await;

    // Record metrics
    metrics.record_publish_success();

    Ok(Json(PublishTemplateResponse {
        name: request.name,
        version: request.version,
        download_url,
        published_at: chrono::Utc::now().to_rfc3339(),
    }))
}

/// Toggle a star for (current user, template@version).
/// Returns the new star state and updated count.
pub async fn toggle_template_star(
    State(state): State<AppState>,
    AuthUser(user_id): AuthUser,
    Path((name, version)): Path<(String, String)>,
) -> ApiResult<Json<StarToggleResponse>> {
    let template = state
        .store
        .find_template_by_name_version(&name, &version)
        .await?
        .ok_or_else(|| ApiError::TemplateNotFound(format!("{}@{}", name, version)))?;

    let (starred, stars) = state.store.toggle_template_star(template.id, user_id).await?;

    Ok(Json(StarToggleResponse { starred, stars }))
}

/// Whether the current user has starred (name@version).
pub async fn get_template_star_state(
    State(state): State<AppState>,
    AuthUser(user_id): AuthUser,
    Path((name, version)): Path<(String, String)>,
) -> ApiResult<Json<StarStateResponse>> {
    let template = state
        .store
        .find_template_by_name_version(&name, &version)
        .await?
        .ok_or_else(|| ApiError::TemplateNotFound(format!("{}@{}", name, version)))?;

    let starred = state.store.is_template_starred_by(template.id, user_id).await?;
    let stars = state.store.count_template_stars(template.id).await?;

    Ok(Json(StarStateResponse { starred, stars }))
}

// Request/Response types

#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct StarToggleResponse {
    pub starred: bool,
    pub stars: i64,
}

#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct StarStateResponse {
    pub starred: bool,
    pub stars: i64,
}

#[derive(Debug, Deserialize)]
pub struct TemplateSearchQuery {
    pub query: Option<String>,
    pub category: Option<String>,
    pub tags: Vec<String>,
    #[serde(default = "default_page")]
    pub page: usize,
    #[serde(default = "default_per_page")]
    pub per_page: usize,
}

fn default_page() -> usize {
    0
}

fn default_per_page() -> usize {
    20
}

#[derive(Debug, Serialize)]
pub struct TemplateSearchResults {
    pub templates: Vec<TemplateRegistryEntry>,
    pub total: usize,
    pub page: usize,
    pub per_page: usize,
}

#[derive(Debug, Serialize)]
pub struct TemplateRegistryEntry {
    pub id: String,
    pub name: String,
    pub description: String,
    pub author: String,
    pub author_email: Option<String>,
    pub version: String,
    #[serde(rename = "category")]
    pub category: TemplateCategory,
    pub tags: Vec<String>,
    pub content: serde_json::Value,
    pub readme: Option<String>,
    pub example_usage: Option<String>,
    pub requirements: Vec<String>,
    pub compatibility: CompatibilityInfo,
    pub stats: TemplateStats,
    pub created_at: String,
    pub updated_at: String,
    pub published: bool,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct CompatibilityInfo {
    pub min_version: String,
    pub max_version: Option<String>,
    pub required_features: Vec<String>,
    pub protocols: Vec<String>,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct TemplateStats {
    pub downloads: u64,
    pub stars: u64,
    pub forks: u64,
    pub rating: f64,
    pub rating_count: u64,
}

#[derive(Debug, Deserialize)]
pub struct PublishTemplateRequest {
    pub name: String,
    pub slug: String,
    pub description: String,
    pub version: String,
    pub category: TemplateCategory,
    pub content_json: serde_json::Value,
    pub package: String, // Base64 encoded
    pub checksum: String,
    pub file_size: i64,
}

#[derive(Debug, Serialize)]
pub struct PublishTemplateResponse {
    pub name: String,
    pub version: String,
    pub download_url: String,
    pub published_at: String,
}