rustango 0.51.1

Django-shaped batteries-included web framework for Rust: ORM + migrations + auto-admin + multi-tenancy + audit log + auth (sessions, JWT, OAuth2/OIDC, HMAC) + APIs (ViewSet, OpenAPI auto-derive, JSON:API) + jobs (in-mem + Postgres) + email + media (S3 / R2 / B2 / MinIO + presigned uploads + collections + tags) + production middleware (CSRF, CSP, rate-limiting, compression, idempotency, etc.).
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
//! `manage` verbs for MCP agents (epic #1013, Slice 2 / #1015):
//! `create-agent`, `rotate-agent-secret`, `list-agents`. Tenant-scoped —
//! each takes a `<slug>` and operates on that tenant's pool, mirroring the
//! `create-user` verb. The generated secret is printed exactly once.

use std::io::Write;

use sqlx::Database;

use crate::sql::Pool;
use crate::tenancy::error::TenancyError;
use crate::tenancy::manage::args::{next_value, reject_leading_flag};
use crate::tenancy::pools::TenantPools;

use super::users::scoped_tenant_pool;

const CREATE_HELP: &str = "create-agent <slug> <name>";
const ROTATE_HELP: &str = "rotate-agent-secret <slug> <name>";
const LIST_HELP: &str = "list-agents <slug>";
const CREATE_SKILL_HELP: &str =
    "create-skill <slug> <codename> [--name <s>] [--description <s>] [--tools t1,t2] [--instructions <s>]";
const GRANT_HELP: &str = "grant-skill <slug> <agent> <skill>";
const REVOKE_HELP: &str = "revoke-skill <slug> <agent> <skill>";
const LIST_SKILLS_HELP: &str = "list-skills <slug>";
const CREATE_USER_KEY_HELP: &str =
    "create-user-key <slug> <username> [--label <l>] [--skill <codename>]…  \
     (repeat --skill to scope the key to a skillset; omit for a full key)";
const LIST_USER_KEYS_HELP: &str = "list-user-keys <slug> <username>";
const REVOKE_USER_KEY_HELP: &str = "revoke-user-key <slug> <username> <key_id>";
const MAP_SKILL_PERM_HELP: &str = "map-skill-permission <slug> <skill> <permission>";
const UNMAP_SKILL_PERM_HELP: &str = "unmap-skill-permission <slug> <skill> <permission>";

/// `create-agent <slug> <name>` — provision a new MCP agent in the tenant
/// and print its one-time `prefix.secret` credential.
pub(super) async fn create_agent_cmd<W: Write + Send, DB: Database>(
    pools: &TenantPools<DB>,
    registry_url: &str,
    args: &[String],
    w: &mut W,
) -> Result<(), TenancyError>
where
    crate::sql::Pool: From<sqlx::Pool<DB>>,
{
    reject_leading_flag(args, "create-agent", "slug", CREATE_HELP)?;
    let mut iter = args.iter();
    let slug = iter
        .next()
        .cloned()
        .ok_or_else(|| TenancyError::Validation(CREATE_HELP.into()))?;
    let name = iter
        .next()
        .cloned()
        .ok_or_else(|| TenancyError::Validation(CREATE_HELP.into()))?;
    if let Some(extra) = iter.next() {
        return Err(TenancyError::Validation(format!(
            "create-agent: unexpected argument `{extra}`"
        )));
    }

    let scoped = scoped_tenant_pool(pools, registry_url, &slug).await?;
    let issued = crate::tenancy::create_agent_pool(&scoped, &name)
        .await
        .map_err(|e| TenancyError::Validation(e.to_string()))?;
    let id = issued.agent.id.get().copied().unwrap_or_default();
    writeln!(w, "created agent `{name}` (id {id}) in tenant `{slug}`")?;
    writeln!(w, "  secret: {}", issued.token)?;
    writeln!(w, "  store this safely — it won't be shown again")?;
    Ok(())
}

/// `rotate-agent-secret <slug> <name>` — issue a fresh secret for an
/// existing agent, invalidating the old one. Prints the new credential.
pub(super) async fn rotate_agent_secret_cmd<W: Write + Send, DB: Database>(
    pools: &TenantPools<DB>,
    registry_url: &str,
    args: &[String],
    w: &mut W,
) -> Result<(), TenancyError>
where
    crate::sql::Pool: From<sqlx::Pool<DB>>,
{
    reject_leading_flag(args, "rotate-agent-secret", "slug", ROTATE_HELP)?;
    let mut iter = args.iter();
    let slug = iter
        .next()
        .cloned()
        .ok_or_else(|| TenancyError::Validation(ROTATE_HELP.into()))?;
    let name = iter
        .next()
        .cloned()
        .ok_or_else(|| TenancyError::Validation(ROTATE_HELP.into()))?;

    let scoped = scoped_tenant_pool(pools, registry_url, &slug).await?;
    let issued = crate::tenancy::rotate_agent_secret_pool(&scoped, &name)
        .await
        .map_err(|e| TenancyError::Validation(e.to_string()))?;
    writeln!(w, "rotated secret for agent `{name}` in tenant `{slug}`")?;
    writeln!(w, "  new secret: {}", issued.token)?;
    writeln!(w, "  the previous secret no longer authenticates")?;
    Ok(())
}

/// `list-agents <slug>` — print every agent in the tenant.
pub(super) async fn list_agents_cmd<W: Write + Send, DB: Database>(
    pools: &TenantPools<DB>,
    registry_url: &str,
    args: &[String],
    w: &mut W,
) -> Result<(), TenancyError>
where
    crate::sql::Pool: From<sqlx::Pool<DB>>,
{
    reject_leading_flag(args, "list-agents", "slug", LIST_HELP)?;
    let slug = args
        .first()
        .cloned()
        .ok_or_else(|| TenancyError::Validation(LIST_HELP.into()))?;

    let scoped = scoped_tenant_pool(pools, registry_url, &slug).await?;
    let agents = crate::tenancy::list_agents_pool(&scoped)
        .await
        .map_err(|e| TenancyError::Validation(e.to_string()))?;
    if agents.is_empty() {
        writeln!(w, "no agents in tenant `{slug}`")?;
        return Ok(());
    }
    writeln!(w, "agents in tenant `{slug}`:")?;
    for a in &agents {
        let id = a.id.get().copied().unwrap_or_default();
        let status = if a.active { "active" } else { "disabled" };
        writeln!(
            w,
            "  {id:>4}  {}  ({status}, prefix {})",
            a.name, a.secret_prefix
        )?;
    }
    Ok(())
}

/// `create-skill <slug> <codename> [--name ..] [--description ..] [--tools a,b] [--instructions ..]`
pub(super) async fn create_skill_cmd<W: Write + Send, DB: Database>(
    pools: &TenantPools<DB>,
    registry_url: &str,
    args: &[String],
    w: &mut W,
) -> Result<(), TenancyError>
where
    crate::sql::Pool: From<sqlx::Pool<DB>>,
{
    reject_leading_flag(args, "create-skill", "slug", CREATE_SKILL_HELP)?;
    let mut iter = args.iter();
    let slug = iter
        .next()
        .cloned()
        .ok_or_else(|| TenancyError::Validation(CREATE_SKILL_HELP.into()))?;
    let codename = iter
        .next()
        .cloned()
        .ok_or_else(|| TenancyError::Validation(CREATE_SKILL_HELP.into()))?;
    let mut name = String::new();
    let mut description = String::new();
    let mut instructions = String::new();
    let mut tools: Vec<String> = Vec::new();
    while let Some(flag) = iter.next() {
        match flag.as_str() {
            "--name" => name = next_value(&mut iter, "--name")?,
            "--description" => description = next_value(&mut iter, "--description")?,
            "--instructions" => instructions = next_value(&mut iter, "--instructions")?,
            "--tools" => {
                tools = next_value(&mut iter, "--tools")?
                    .split(',')
                    .map(|s| s.trim().to_owned())
                    .filter(|s| !s.is_empty())
                    .collect();
            }
            other => {
                return Err(TenancyError::Validation(format!(
                    "create-skill: unknown argument `{other}`"
                )));
            }
        }
    }

    let scoped = scoped_tenant_pool(pools, registry_url, &slug).await?;
    let skill = crate::tenancy::create_skill_pool(
        &scoped,
        &codename,
        &name,
        &description,
        &instructions,
        &tools,
    )
    .await
    .map_err(|e| TenancyError::Validation(e.to_string()))?;
    let id = skill.id.get().copied().unwrap_or_default();
    writeln!(
        w,
        "created skill `{codename}` (id {id}) in tenant `{slug}` with {} tool(s)",
        tools.len()
    )?;
    Ok(())
}

/// `grant-skill <slug> <agent> <skill>`
pub(super) async fn grant_skill_cmd<W: Write + Send, DB: Database>(
    pools: &TenantPools<DB>,
    registry_url: &str,
    args: &[String],
    w: &mut W,
) -> Result<(), TenancyError>
where
    crate::sql::Pool: From<sqlx::Pool<DB>>,
{
    let (slug, agent, skill) = three_positionals(args, "grant-skill", GRANT_HELP)?;
    let scoped = scoped_tenant_pool(pools, registry_url, &slug).await?;
    crate::tenancy::grant_skill_pool(&scoped, &slug, &agent, &skill)
        .await
        .map_err(|e| TenancyError::Validation(e.to_string()))?;
    writeln!(
        w,
        "granted skill `{skill}` to agent `{agent}` in tenant `{slug}`"
    )?;
    Ok(())
}

/// `revoke-skill <slug> <agent> <skill>`
pub(super) async fn revoke_skill_cmd<W: Write + Send, DB: Database>(
    pools: &TenantPools<DB>,
    registry_url: &str,
    args: &[String],
    w: &mut W,
) -> Result<(), TenancyError>
where
    crate::sql::Pool: From<sqlx::Pool<DB>>,
{
    let (slug, agent, skill) = three_positionals(args, "revoke-skill", REVOKE_HELP)?;
    let scoped = scoped_tenant_pool(pools, registry_url, &slug).await?;
    crate::tenancy::revoke_skill_pool(&scoped, &slug, &agent, &skill)
        .await
        .map_err(|e| TenancyError::Validation(e.to_string()))?;
    writeln!(
        w,
        "revoked skill `{skill}` from agent `{agent}` in tenant `{slug}`"
    )?;
    Ok(())
}

/// `list-skills <slug>`
pub(super) async fn list_skills_cmd<W: Write + Send, DB: Database>(
    pools: &TenantPools<DB>,
    registry_url: &str,
    args: &[String],
    w: &mut W,
) -> Result<(), TenancyError>
where
    crate::sql::Pool: From<sqlx::Pool<DB>>,
{
    reject_leading_flag(args, "list-skills", "slug", LIST_SKILLS_HELP)?;
    let slug = args
        .first()
        .cloned()
        .ok_or_else(|| TenancyError::Validation(LIST_SKILLS_HELP.into()))?;
    let scoped = scoped_tenant_pool(pools, registry_url, &slug).await?;
    let skills = crate::tenancy::list_skills_pool(&scoped)
        .await
        .map_err(|e| TenancyError::Validation(e.to_string()))?;
    if skills.is_empty() {
        writeln!(w, "no skills in tenant `{slug}`")?;
        return Ok(());
    }
    writeln!(w, "skills in tenant `{slug}`:")?;
    for s in &skills {
        writeln!(w, "  {}  {}", s.codename, s.name)?;
    }
    Ok(())
}

/// `create-user-key <slug> <username> [label]` — provision a personal,
/// user-owned MCP key for `<username>` and print its one-time credential.
/// The default label is the username.
pub(super) async fn create_user_key_cmd<W: Write + Send, DB: Database>(
    pools: &TenantPools<DB>,
    registry_url: &str,
    args: &[String],
    w: &mut W,
) -> Result<(), TenancyError>
where
    crate::sql::Pool: From<sqlx::Pool<DB>>,
{
    reject_leading_flag(args, "create-user-key", "slug", CREATE_USER_KEY_HELP)?;
    let slug = args
        .first()
        .cloned()
        .ok_or_else(|| TenancyError::Validation(CREATE_USER_KEY_HELP.into()))?;
    let username = args
        .get(1)
        .cloned()
        .ok_or_else(|| TenancyError::Validation(CREATE_USER_KEY_HELP.into()))?;

    // Flags after the two positionals: --label <l>, --skill <codename> (repeat
    // --skill for a skillset; none = a full-permission key).
    let mut label: Option<String> = None;
    let mut skills: Vec<String> = Vec::new();
    let mut i = 2;
    while i < args.len() {
        match args[i].as_str() {
            "--label" => {
                i += 1;
                label = Some(args.get(i).cloned().ok_or_else(|| {
                    TenancyError::Validation("create-user-key: --label needs a value".into())
                })?);
            }
            "--skill" => {
                i += 1;
                skills.push(args.get(i).cloned().ok_or_else(|| {
                    TenancyError::Validation("create-user-key: --skill needs a codename".into())
                })?);
            }
            other => {
                return Err(TenancyError::Validation(format!(
                    "create-user-key: unexpected argument `{other}` ({CREATE_USER_KEY_HELP})"
                )));
            }
        }
        i += 1;
    }
    let label = label.unwrap_or_else(|| username.clone());

    let scoped = scoped_tenant_pool(pools, registry_url, &slug).await?;
    let uid = resolve_user_id(&scoped, &username).await?;
    let issued = crate::tenancy::create_user_key_pool(&scoped, uid, &label, &skills)
        .await
        .map_err(|e| TenancyError::Validation(e.to_string()))?;
    let id = issued.agent.id.get().copied().unwrap_or_default();
    let scope = if skills.is_empty() {
        "full (owner's permissions)".to_owned()
    } else {
        format!("skills: {}", skills.join(", "))
    };
    writeln!(
        w,
        "created key #{id} for user `{username}` in tenant `{slug}` (label `{label}`, scope {scope})"
    )?;
    writeln!(w, "  token: {}", issued.token)?;
    writeln!(w, "  store this safely — it won't be shown again")?;
    Ok(())
}

/// `list-user-keys <slug> <username>` — print every personal key owned by
/// `<username>`, newest first.
pub(super) async fn list_user_keys_cmd<W: Write + Send, DB: Database>(
    pools: &TenantPools<DB>,
    registry_url: &str,
    args: &[String],
    w: &mut W,
) -> Result<(), TenancyError>
where
    crate::sql::Pool: From<sqlx::Pool<DB>>,
{
    reject_leading_flag(args, "list-user-keys", "slug", LIST_USER_KEYS_HELP)?;
    let mut iter = args.iter();
    let slug = iter
        .next()
        .cloned()
        .ok_or_else(|| TenancyError::Validation(LIST_USER_KEYS_HELP.into()))?;
    let username = iter
        .next()
        .cloned()
        .ok_or_else(|| TenancyError::Validation(LIST_USER_KEYS_HELP.into()))?;

    let scoped = scoped_tenant_pool(pools, registry_url, &slug).await?;
    let uid = resolve_user_id(&scoped, &username).await?;
    let keys = crate::tenancy::list_user_keys_pool(&scoped, uid)
        .await
        .map_err(|e| TenancyError::Validation(e.to_string()))?;
    if keys.is_empty() {
        writeln!(w, "no keys for user `{username}`")?;
        return Ok(());
    }
    writeln!(w, "keys for user `{username}` in tenant `{slug}`:")?;
    for k in &keys {
        let id = k.id.get().copied().unwrap_or_default();
        let label = k
            .data
            .get("label")
            .and_then(serde_json::Value::as_str)
            .unwrap_or("");
        let created = k
            .created_at
            .get()
            .map(chrono::DateTime::to_rfc3339)
            .unwrap_or_default();
        writeln!(w, "  #{id}  {label}  {created}")?;
    }
    Ok(())
}

/// `revoke-user-key <slug> <username> <key_id>` — delete one of
/// `<username>`'s personal keys by its id (ownership-verified).
pub(super) async fn revoke_user_key_cmd<W: Write + Send, DB: Database>(
    pools: &TenantPools<DB>,
    registry_url: &str,
    args: &[String],
    w: &mut W,
) -> Result<(), TenancyError>
where
    crate::sql::Pool: From<sqlx::Pool<DB>>,
{
    reject_leading_flag(args, "revoke-user-key", "slug", REVOKE_USER_KEY_HELP)?;
    let mut iter = args.iter();
    let slug = iter
        .next()
        .cloned()
        .ok_or_else(|| TenancyError::Validation(REVOKE_USER_KEY_HELP.into()))?;
    let username = iter
        .next()
        .cloned()
        .ok_or_else(|| TenancyError::Validation(REVOKE_USER_KEY_HELP.into()))?;
    let key_id: i64 = iter
        .next()
        .ok_or_else(|| TenancyError::Validation(REVOKE_USER_KEY_HELP.into()))?
        .parse()
        .map_err(|_| {
            TenancyError::Validation("revoke-user-key: <key_id> must be an integer".into())
        })?;

    let scoped = scoped_tenant_pool(pools, registry_url, &slug).await?;
    let uid = resolve_user_id(&scoped, &username).await?;
    crate::tenancy::revoke_user_key_pool(&scoped, uid, key_id)
        .await
        .map_err(|e| TenancyError::Validation(e.to_string()))?;
    writeln!(w, "revoked key #{key_id} for user `{username}`")?;
    Ok(())
}

/// `map-skill-permission <slug> <skill> <permission>` — grant everyone
/// holding `<permission>` the `<skill>`'s tools on their user-owned keys.
/// Idempotent.
pub(super) async fn map_skill_permission_cmd<W: Write + Send, DB: Database>(
    pools: &TenantPools<DB>,
    registry_url: &str,
    args: &[String],
    w: &mut W,
) -> Result<(), TenancyError>
where
    crate::sql::Pool: From<sqlx::Pool<DB>>,
{
    let (slug, skill, permission) =
        three_positionals(args, "map-skill-permission", MAP_SKILL_PERM_HELP)?;
    let scoped = scoped_tenant_pool(pools, registry_url, &slug).await?;
    crate::tenancy::map_skill_to_permission_pool(&scoped, &skill, &permission)
        .await
        .map_err(|e| TenancyError::Validation(e.to_string()))?;
    writeln!(
        w,
        "mapped skill `{skill}` → permission `{permission}` in tenant `{slug}`"
    )?;
    Ok(())
}

/// `unmap-skill-permission <slug> <skill> <permission>` — remove a
/// skill↔permission mapping. No-op if absent.
pub(super) async fn unmap_skill_permission_cmd<W: Write + Send, DB: Database>(
    pools: &TenantPools<DB>,
    registry_url: &str,
    args: &[String],
    w: &mut W,
) -> Result<(), TenancyError>
where
    crate::sql::Pool: From<sqlx::Pool<DB>>,
{
    let (slug, skill, permission) =
        three_positionals(args, "unmap-skill-permission", UNMAP_SKILL_PERM_HELP)?;
    let scoped = scoped_tenant_pool(pools, registry_url, &slug).await?;
    crate::tenancy::unmap_skill_from_permission_pool(&scoped, &skill, &permission)
        .await
        .map_err(|e| TenancyError::Validation(e.to_string()))?;
    writeln!(w, "unmapped skill `{skill}` ✗ permission `{permission}`")?;
    Ok(())
}

/// Resolve `username` to a `rustango_users.id` on the scoped tenant pool.
/// Returns a `Validation` error naming the unknown user.
async fn resolve_user_id(pool: &Pool, username: &str) -> Result<i64, TenancyError> {
    use crate::sql::FetcherPool as _;
    let user = crate::tenancy::User::objects()
        .filter("username", username.to_owned())
        .limit(1)
        .fetch(pool)
        .await
        .map_err(|e| TenancyError::Validation(e.to_string()))?
        .into_iter()
        .next()
        .ok_or_else(|| TenancyError::Validation(format!("unknown user `{username}`")))?;
    Ok(user.id.get().copied().unwrap_or_default())
}

/// Parse exactly three positional args (`<slug> <a> <b>`) for the grant verbs.
fn three_positionals(
    args: &[String],
    verb: &str,
    help: &str,
) -> Result<(String, String, String), TenancyError> {
    reject_leading_flag(args, verb, "slug", help)?;
    match args {
        [slug, a, b] => Ok((slug.clone(), a.clone(), b.clone())),
        _ => Err(TenancyError::Validation(help.into())),
    }
}