puerto 0.34.0

Puerto: la CLI de un framework full-stack DDD en Rust. Genera proyectos con Clean Architecture, la inyección de dependencias cableada sola y soporte de SQLx, sin cablear nada a mano. Antes, puerto-framework.
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
// Phase 16.8 end to end: a generated auth project's API as a real process. OIDC (`make test/auth`):
// the project's own realm imported into a throwaway Keycloak, tokens from `task auth:token` (its
// `dev-cli` client), `admin@` the caller with the role and `user@` the one without; the first call
// provisions one `users` row, later ones (a restart included) add none. Local (`make test/db`):
// register → login → `/me` → the account cycle (Fase 39: the links read from Mailpit) → logout, and
// the revoked token is refused.
use super::*;

use std::process::Command;

use super::compile_matrix::{AUTH_LOCAL, AUTH_OIDC_DB};
use super::mail_e2e::{address, mailpit, mailpit_messages};
use super::worker_e2e::{Project, build_scenario_project, free_port, http, http_as, wait_until};

const PRODUCT: &str = r#"{"name":"Desk lamp","sku":"LAMP-1","price":2500,"status":"Draft"}"#;

/// Whether `body` is the error `code` (`RespuestaError { codigo, mensaje }`).
fn is_error(body: &str, code: &str) -> bool {
    body.contains(&format!("\"codigo\":\"{code}\""))
}

fn database_url(project: &Project) -> String {
    project
        .env
        .iter()
        .find(|(k, _)| k == "DATABASE_URL")
        .map(|(_, v)| v.clone())
        .expect("no DATABASE_URL")
}

/// How many `users` rows the project's database holds.
fn users(project: &Project) -> i64 {
    let url = database_url(project);
    tokio::runtime::Builder::new_current_thread()
        .enable_all()
        .build()
        .unwrap()
        .block_on(async {
            let pool = sqlx::PgPool::connect(&url).await.unwrap();
            let count: i64 = sqlx::query_scalar("SELECT count(*) FROM usuarios")
                .fetch_one(&pool)
                .await
                .unwrap();
            pool.close().await;
            count
        })
}

/// Starts the project's API on a free port and waits until it is ready.
fn start_api(
    project: &Project,
    binary: &str,
    log: &str,
    env: &[(&str, String)],
) -> (super::worker_e2e::Running, u16) {
    let port = free_port();
    let mut env = env.to_vec();
    env.push(("SERVICE_PORT", port.to_string()));
    let api = project.spawn(binary, &project.dir.join(log), &env);
    wait_until("the API to be ready", || {
        http(port, "GET", "/health/ready", "").is_some_and(|(s, _)| s == 200)
    });
    (api, port)
}

// ── OIDC ──────────────────────────────────────────────────────────────────

const OIDC_PROJECT: &str = "e2e-auth-oidc";

/// `curl` with `args`; its stdout.
fn curl(args: &[&str]) -> String {
    let out = Command::new("curl")
        .args(["-sS", "--fail-with-body"])
        .args(args)
        .output()
        .expect("curl not found");
    let body = String::from_utf8_lossy(&out.stdout).to_string();
    assert!(
        out.status.success(),
        "curl {args:?}: {body}{}",
        String::from_utf8_lossy(&out.stderr)
    );
    body
}

/// Imports the generated `keycloak/realm.json` into the test Keycloak, as the
/// project's `docker-compose.yml` does on its first start — replacing one an earlier run left.
fn import_realm(keycloak: &str, output: &Path) {
    let token = curl(&[
        &format!("{keycloak}/realms/master/protocol/openid-connect/token"),
        "-d",
        "grant_type=password",
        "-d",
        "client_id=admin-cli",
        "-d",
        "username=admin",
        "-d",
        "password=admin",
    ]);
    let token: serde_json::Value = serde_json::from_str(&token).unwrap();
    let bearer = format!(
        "Authorization: Bearer {}",
        token["access_token"].as_str().unwrap()
    );
    let _ = Command::new("curl")
        .args(["-s", "-X", "DELETE", "-H", &bearer])
        .arg(format!("{keycloak}/admin/realms/{OIDC_PROJECT}"))
        .output();
    let realm = output.join("keycloak/realm.json");
    curl(&[
        "-X",
        "POST",
        "-H",
        &bearer,
        "-H",
        "Content-Type: application/json",
        "--data-binary",
        &format!("@{}", realm.display()),
        &format!("{keycloak}/admin/realms"),
    ]);
}

/// `task auth:token -- <email>@…` in the project: what a developer runs. The shell's
/// `AUTH_ISSUER` wins over `.env`'s.
fn token(project: &Project, issuer: &str, email: &str) -> String {
    let out = task_command(&project.output)
        .args(["auth:token", "--"])
        .arg(format!("{email}@{OIDC_PROJECT}.localhost"))
        .env("AUTH_ISSUER", issuer)
        .output()
        .expect("task not found");
    assert!(
        out.status.success(),
        "task auth:token -- {email}@…: {}",
        String::from_utf8_lossy(&out.stderr)
    );
    let token = String::from_utf8_lossy(&out.stdout).trim().to_string();
    assert_eq!(token.split('.').count(), 3, "not a JWT: {token}");
    token
}

#[test]
#[ignore = "slow: needs Keycloak and Postgres — run via `make test/auth`"]
fn keycloak_oidc_project_refuses_without_token_or_role_and_provisions_each_caller_once() {
    let Some(keycloak) = std::env::var("PUERTO_TEST_KEYCLOAK_URL").ok() else {
        eprintln!("PUERTO_TEST_KEYCLOAK_URL not set — skipping (run `make test/auth`)");
        return;
    };
    let keycloak = keycloak.trim_end_matches('/').to_string();
    let issuer = format!("{keycloak}/realms/{OIDC_PROJECT}");
    let env = [
        ("AUTH_ISSUER", issuer.clone()),
        ("AUTH_AUDIENCE", "api".to_string()),
        ("AUTH_ROLES_CLAIM", "realm_access.roles".to_string()),
    ];
    let Some(project) = build_scenario_project(
        &AUTH_OIDC_DB,
        OIDC_PROJECT,
        "puerto_matrix_auth_oidc_e2e",
        &env,
        |_| {},
    ) else {
        eprintln!("PUERTO_TEST_DATABASE_URL not set — skipping (run `make test/auth`)");
        return;
    };
    import_realm(&keycloak, &project.output);
    let admin = token(&project, &issuer, "admin");
    let user = token(&project, &issuer, "user");

    let (api, port) = start_api(&project, OIDC_PROJECT, "api.log", &[]);

    // No token: a public route answers, a protected one is 401.
    let (status, _) = http(port, "GET", "/api/productos", "").unwrap();
    assert_eq!(status, 200, "a public route needs no token");
    let (status, body) = http(port, "GET", "/api/pedidos", "").unwrap();
    assert_eq!(status, 401, "{body}");
    assert!(is_error(&body, "auth.no_autenticado"), "{body}");
    let (status, body) = http_as(port, "GET", "/api/pedidos", "", Some("not.a.token")).unwrap();
    assert_eq!(status, 401, "{body}");
    assert_eq!(users(&project), 0, "nobody signed in yet");

    // The first call provisions the caller; a second one does not add another row.
    let (status, body) = http_as(port, "GET", "/api/me", "", Some(&admin)).unwrap();
    assert_eq!(status, 200, "{body}");
    assert!(
        body.contains(&format!("admin@{OIDC_PROJECT}.localhost")),
        "{body}"
    );
    assert!(
        body.contains("\"admin\""),
        "the role from the token: {body}"
    );
    assert_eq!(users(&project), 1);
    let (status, body) = http_as(port, "POST", "/api/productos", PRODUCT, Some(&admin)).unwrap();
    assert_eq!(status, 201, "admin holds `admin`: {body}");
    assert_eq!(users(&project), 1);

    // The role: `user@` holds none — 403 on a role-guarded route, 200 on a public one and on a
    // protected one that asks no role.
    let (status, body) = http_as(port, "POST", "/api/productos", PRODUCT, Some(&user)).unwrap();
    assert_eq!(status, 403, "{body}");
    assert!(is_error(&body, "auth.prohibido"), "{body}");
    let (status, _) = http_as(port, "GET", "/api/productos", "", Some(&user)).unwrap();
    assert_eq!(status, 200);
    assert_own_orders(port, &user);
    assert_eq!(users(&project), 2, "user@ provisioned on its first call");

    // A restarted API has no cache: it finds the rows instead of adding them.
    drop(api);
    let (api, port) = start_api(&project, OIDC_PROJECT, "api-restarted.log", &[]);
    let (status, body) = http_as(port, "GET", "/api/me", "", Some(&admin)).unwrap();
    assert_eq!(status, 200, "{body}");
    assert_eq!(users(&project), 2);

    drop(api);
    cleanup(&project.dir);
}

// ── Local ─────────────────────────────────────────────────────────────────

const LOCAL_PROJECT: &str = "e2e-auth-local";

/// The `"<field>":"<value>"` of a JSON body.
/// Pedido's list and detail are `admin`'s (27.8), and each Pedido is its buyer's (27.18): a caller
/// without the role is refused the list, creates one — owned by its own `id_usuario`, which the
/// OIDC provisioning sets too — and finds it in `/mis_pedidos`.
fn assert_own_orders(port: u16, token: &str) {
    let (status, body) = http_as(port, "GET", "/api/pedidos", "", Some(token)).unwrap();
    assert_eq!(status, 403, "the list asks for `admin`: {body}");
    let (status, body) = http_as(
        port,
        "POST",
        "/api/pedidos",
        r#"{"total":1200}"#,
        Some(token),
    )
    .unwrap();
    assert_eq!(status, 201, "{body}");
    let id = field(&body, "id");
    let (status, body) = http_as(port, "GET", "/api/mis_pedidos", "", Some(token)).unwrap();
    assert_eq!(status, 200, "{body}");
    assert!(body.contains(&id), "the caller's own order: {body}");
    let (status, body) =
        http_as(port, "GET", &format!("/api/pedidos/{id}"), "", Some(token)).unwrap();
    assert_eq!(status, 200, "its owner reads it without the role: {body}");
}

fn field(body: &str, name: &str) -> String {
    let json: serde_json::Value =
        serde_json::from_str(body).unwrap_or_else(|_| panic!("not JSON: {body}"));
    json[name]
        .as_str()
        .unwrap_or_else(|| panic!("no {name}: {body}"))
        .to_string()
}

/// The text of the message `id` Mailpit holds, over HTTP/1.0 so the body is never chunked.
fn mailpit_text(api_port: u16, id: &str) -> String {
    use std::io::{Read, Write};
    let mut stream =
        std::net::TcpStream::connect(("127.0.0.1", api_port)).expect("Mailpit is not up");
    write!(
        stream,
        "GET /api/v1/message/{id} HTTP/1.0\r\nHost: localhost\r\n\r\n"
    )
    .unwrap();
    let mut response = String::new();
    stream.read_to_string(&mut response).unwrap();
    let body = response.split_once("\r\n\r\n").map_or("", |(_, b)| b);
    let json: serde_json::Value = serde_json::from_str(body).unwrap_or_default();
    json["Text"].as_str().unwrap_or_default().to_string()
}

/// The token of the newest link to `path` (`/verificar`, `/contrasena/nueva`) mailed to `to`.
fn mailed_token(api_port: u16, to: &str, path: &str) -> String {
    let marker = format!("{path}?token=");
    let mut token = String::new();
    wait_until(&format!("a link to {path} for {to}"), || {
        // Newest first: the first one that carries the link is the last one sent.
        let found = mailpit_messages(api_port)
            .iter()
            .filter(|m| {
                m["To"]
                    .as_array()
                    .is_some_and(|tos| tos.iter().any(|t| t["Address"] == to))
            })
            .map(|m| mailpit_text(api_port, m["ID"].as_str().unwrap_or_default()))
            .find_map(|text| {
                let (_, rest) = text.split_once(&marker)?;
                Some(rest.split_whitespace().next()?.to_string())
            });
        found.map(|t| token = t).is_some()
    });
    token
}

#[test]
#[ignore = "slow: needs Postgres — run via `make test/db`"]
fn postgres_local_auth_project_registers_signs_in_and_revokes_on_logout() {
    let (Some(smtp_url), Some((_, mailpit_api))) =
        (std::env::var("PUERTO_TEST_SMTP_URL").ok(), mailpit())
    else {
        eprintln!(
            "PUERTO_TEST_SMTP_URL / PUERTO_TEST_MAILPIT_API not set — skipping (run `make test/db`)"
        );
        return;
    };
    let Some(project) = build_scenario_project(
        &AUTH_LOCAL,
        LOCAL_PROJECT,
        "puerto_matrix_auth_local_e2e",
        &[],
        |_| {},
    ) else {
        eprintln!("PUERTO_TEST_DATABASE_URL not set — skipping (run `make test/db`)");
        return;
    };
    let (api, port) = start_api(
        &project,
        LOCAL_PROJECT,
        "api.log",
        &[("SMTP_URL", smtp_url)],
    );
    // Mailpit keeps what earlier runs sent: an address of this run's own.
    let email = address("ada");

    // No token: a public route answers, a protected one is 401.
    let (status, _) = http(port, "GET", "/api/productos", "").unwrap();
    assert_eq!(status, 200);
    let (status, body) = http(port, "GET", "/api/pedidos", "").unwrap();
    assert_eq!(status, 401, "{body}");
    assert!(is_error(&body, "auth.no_autenticado"), "{body}");

    // Register, then sign in.
    let account = format!(
        r#"{{"email":"{}","contrasena":"correct horse battery","nombre":"Ada"}}"#,
        email.to_uppercase()
    );
    let (status, body) = http(port, "POST", "/api/auth/registro", &account).unwrap();
    assert_eq!(status, 201, "{body}");
    let (status, body) = http(port, "POST", "/api/auth/registro", &account).unwrap();
    assert_eq!(status, 409, "the email is taken: {body}");
    let login = |password: &str| {
        let body = format!(r#"{{"email":"{email}","contrasena":"{password}"}}"#);
        http(port, "POST", "/api/auth/login", &body).unwrap()
    };
    let (status, body) = login("not the password");
    assert_eq!(status, 401, "{body}");
    assert!(is_error(&body, "auth.credenciales_invalidas"), "{body}");
    let (status, body) = login("correct horse battery");
    assert_eq!(status, 200, "{body}");
    let token = field(&body, "token");

    // The session: `/me`, a protected route, and no role for a role-guarded one.
    let (status, body) = http_as(port, "GET", "/api/me", "", Some(&token)).unwrap();
    assert_eq!(status, 200, "{body}");
    assert_eq!(field(&body, "email"), email);
    assert!(body.contains(r#""emailVerificado":false"#), "{body}");
    assert_own_orders(port, &token);
    let (status, body) = http_as(port, "POST", "/api/productos", PRODUCT, Some(&token)).unwrap();
    assert_eq!(status, 403, "{body}");
    assert!(is_error(&body, "auth.prohibido"), "{body}");
    assert_eq!(users(&project), 1);

    // Fase 39. Registering mailed the link that verifies the email; it works once.
    let verify = format!(
        r#"{{"token":"{}"}}"#,
        mailed_token(mailpit_api, &email, "/verificar")
    );
    let (status, body) = http(port, "POST", "/api/auth/verificacion/confirmar", &verify).unwrap();
    assert_eq!(status, 204, "{body}");
    let (status, body) = http(port, "POST", "/api/auth/verificacion/confirmar", &verify).unwrap();
    assert_eq!(status, 422, "a spent link: {body}");
    assert!(
        is_error(&body, "usuario.validacion.token_invalido"),
        "{body}"
    );
    let (_, body) = http_as(port, "GET", "/api/me", "", Some(&token)).unwrap();
    assert!(body.contains(r#""emailVerificado":true"#), "{body}");

    // A forgotten password: the same 204 with or without an account; the link resets it and
    // closes every session.
    for who in [email.as_str(), "nobody@e2e.test"] {
        let request = format!(r#"{{"email":"{who}"}}"#);
        let (status, body) = http(port, "POST", "/api/auth/restablecimiento", &request).unwrap();
        assert_eq!(status, 204, "{who}: {body}");
    }
    let reset = format!(
        r#"{{"token":"{}","contrasena":"a brand new secret"}}"#,
        mailed_token(mailpit_api, &email, "/contrasena/nueva")
    );
    let (status, body) =
        http(port, "POST", "/api/auth/restablecimiento/confirmar", &reset).unwrap();
    assert_eq!(status, 204, "{body}");
    let (status, body) = http_as(port, "GET", "/api/me", "", Some(&token)).unwrap();
    assert_eq!(status, 401, "reset closes every session: {body}");
    assert_eq!(login("correct horse battery").0, 401);
    let (status, body) = login("a brand new secret");
    assert_eq!(status, 200, "{body}");
    let token = field(&body, "token");

    // Changing it knowing the current one answers a new session, and the old one is gone.
    let change = r#"{"actual":"a brand new secret","nueva":"another new secret"}"#;
    let (status, body) =
        http_as(port, "PUT", "/api/auth/contrasena", change, Some(&token)).unwrap();
    assert_eq!(status, 200, "{body}");
    let old = token;
    let token = field(&body, "token");
    assert_eq!(
        http_as(port, "GET", "/api/me", "", Some(&old)).unwrap().0,
        401
    );
    let wrong = r#"{"actual":"not the password","nueva":"another new secret"}"#;
    let (status, body) = http_as(port, "PUT", "/api/auth/contrasena", wrong, Some(&token)).unwrap();
    assert_eq!(status, 422, "{body}");
    assert!(
        is_error(&body, "usuario.validacion.contrasena_incorrecta"),
        "{body}"
    );

    // The profile: the name.
    let profile = r#"{"nombre":"  Ada Lovelace "}"#;
    let (status, body) = http_as(port, "PUT", "/api/auth/perfil", profile, Some(&token)).unwrap();
    assert_eq!(status, 200, "{body}");
    assert_eq!(field(&body, "nombre"), "Ada Lovelace");

    // Logout revokes the token it was called with.
    let (status, body) = http_as(port, "POST", "/api/auth/logout", "", Some(&token)).unwrap();
    assert_eq!(status, 204, "{body}");
    let (status, body) = http_as(port, "GET", "/api/me", "", Some(&token)).unwrap();
    assert_eq!(status, 401, "a revoked session: {body}");
    assert!(is_error(&body, "auth.no_autenticado"), "{body}");

    drop(api);
    cleanup(&project.dir);
}