capy-framework 0.10.0

An opinionated full-stack Rust web framework with strong conventions and sensible defaults.
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
//! The public application harness uses the same builder, routes and migrations as serving.
#![cfg(feature = "testing")]
use capy_framework::{
    self as capy,
    migration::{MigrationTrait, MigratorTrait, SchemaManager},
    prelude::*,
    sea_orm::{ConnectionTrait, Statement, TransactionTrait},
    testing::{Factory, FactoryBuilder, TestApp, TestDatabase},
};

struct Migrator;
#[capy::migration::async_trait::async_trait]
impl MigratorTrait for Migrator {
    fn migrations() -> Vec<Box<dyn MigrationTrait>> {
        vec![Box::new(Records)]
    }
}
struct Records;
impl capy::migration::MigrationName for Records {
    fn name(&self) -> &str {
        "test_records"
    }
}
#[capy::migration::async_trait::async_trait]
impl MigrationTrait for Records {
    async fn up(&self, manager: &SchemaManager) -> std::result::Result<(), capy::sea_orm::DbErr> {
        manager
            .get_connection()
            .execute_unprepared("CREATE TABLE records (id BIGINT PRIMARY KEY, title TEXT NOT NULL)")
            .await?;
        Ok(())
    }
    async fn down(&self, manager: &SchemaManager) -> std::result::Result<(), capy::sea_orm::DbErr> {
        manager
            .get_connection()
            .execute_unprepared("DROP TABLE records")
            .await?;
        Ok(())
    }
}

#[derive(Default)]
struct RecordFactory {
    id: i64,
    title: String,
}
impl Factory for RecordFactory {
    type Model = i64;
    async fn create<C: ConnectionTrait>(self, db: &C) -> Result<i64> {
        db.execute(Statement::from_sql_and_values(
            db.get_database_backend(),
            "INSERT INTO records (id,title) VALUES ($1,$2)",
            [self.id.into(), self.title.into()],
        ))
        .await?;
        Ok(self.id)
    }
}

async fn count(Context(ctx): Context) -> Result<Json<Value>> {
    let row = ctx
        .db
        .query_one(Statement::from_string(
            ctx.db.get_database_backend(),
            "SELECT COUNT(*) AS n FROM records",
        ))
        .await?
        .unwrap();
    Ok(Json(json!({"count":row.try_get::<i64>("", "n")?})))
}

fn application() -> App<Migrator> {
    App::new()
        .config(AppConfig::default())
        .api_routes(Routes::new().get("/records", count))
        .migrations(Migrator)
}

#[tokio::test]
async fn boot_migrates_real_factory_and_isolates_concurrent_apps() -> Result<()> {
    let (a, b) = tokio::try_join!(TestApp::boot(application()), TestApp::boot(application()))?;
    a.factory::<RecordFactory>()
        .with(|record| {
            record.id = 1;
            record.title = "First".into();
        })
        .create()
        .await?;
    a.get("/api/records")
        .send()
        .await
        .assert_json(json!({"count":1}));
    b.get("/api/records")
        .send()
        .await
        .assert_json(json!({"count":0}));
    assert_eq!(a.context().config.app.environment, "test");
    let tx = a.db().begin().await?;
    FactoryBuilder::new(
        RecordFactory {
            id: 2,
            title: "Rolled back".into(),
        },
        &tx,
    )
    .create()
    .await?;
    tx.rollback().await?;
    a.get("/api/records")
        .send()
        .await
        .assert_json(json!({"count":1}));
    let closed = a.db().clone();
    a.cleanup().await?;
    assert!(closed.ping().await.is_err());
    b.cleanup().await?;
    Ok(())
}

#[tokio::test]
async fn missing_migrations_remain_observable() -> Result<()> {
    let app = TestApp::builder(application())
        .without_migrations()
        .boot()
        .await?;
    app.get("/api/records")
        .send()
        .await
        .assert_status(axum::http::StatusCode::INTERNAL_SERVER_ERROR)
        .assert_json(json!({"message":"Internal server error"}));
    app.cleanup().await
}

#[tokio::test]
async fn seeds_are_explicit_atomic_and_reusable_in_application_tests() -> Result<()> {
    let app = TestApp::boot(application().seeds(|ctx| {
        Box::pin(async move {
            ctx.transaction
                .execute(Statement::from_sql_and_values(
                    ctx.transaction.get_database_backend(),
                    "INSERT INTO records (id,title) VALUES ($1,$2) ON CONFLICT (id) DO NOTHING",
                    [1_i64.into(), "Seeded".into()],
                ))
                .await?;
            Ok(())
        })
    }))
    .await?;
    app.get("/api/records")
        .send()
        .await
        .assert_json(json!({"count":0}));
    app.seed().await?;
    app.seed().await?;
    app.get("/api/records")
        .send()
        .await
        .assert_json(json!({"count":1}));
    app.cleanup().await?;
    let app = TestApp::boot(application().seeds(|ctx| {
        Box::pin(async move {
            FactoryBuilder::new(RecordFactory::default(), ctx.transaction)
                .create()
                .await?;
            Err(AppError::Conflict("deliberate seed failure".into()))
        })
    }))
    .await?;
    assert!(app.seed().await.is_err());
    app.get("/api/records")
        .send()
        .await
        .assert_json(json!({"count":0}));
    app.cleanup().await
}

#[tokio::test]
async fn production_seed_command_rejects_before_connecting_or_running_callback() {
    let mut config = AppConfig::default();
    config.app.environment = "production".into();
    config.database.url = "postgres://never-connect@127.0.0.1:1/production".into();
    let error = App::new()
        .config(config)
        .seeds(|_| Box::pin(async { panic!("production seeds must not execute") }))
        .run_command("db:seed")
        .await
        .unwrap_err();
    assert!(error
        .to_string()
        .contains("disabled outside development/test"));
}

#[tokio::test]
async fn session_uses_configured_peer_and_rejects_cross_origin_paths() -> Result<()> {
    async fn peer(
        axum::extract::ConnectInfo(peer): axum::extract::ConnectInfo<std::net::SocketAddr>,
    ) -> Json<String> {
        Json(peer.ip().to_string())
    }
    let app = TestApp::builder(
        App::new()
            .config(AppConfig::default())
            .api_routes(Routes::new().get("/peer", peer)),
    )
    .peer_addr(([192, 0, 2, 10], 12345).into())
    .boot()
    .await?;
    let mut session = app.session();
    session
        .get("/api/peer")
        .send()
        .await?
        .assert_json(json!("192.0.2.10"));
    assert!(session
        .get("https://elsewhere.example/api/peer")
        .send()
        .await
        .is_err());
    assert!(session
        .get("//elsewhere.example/api/peer")
        .send()
        .await
        .is_err());
    app.cleanup().await
}

#[tokio::test]
#[ignore = "requires CAPY_TEST_ADMIN_POSTGRES_URL with CREATEDB permission"]
async fn postgres_harness_provisions_and_removes_only_its_unique_database() -> Result<()> {
    let url =
        std::env::var("CAPY_TEST_ADMIN_POSTGRES_URL").expect("disposable PostgreSQL admin URL");
    let mut config = AppConfig::default();
    config.database.url = url.clone();
    let admin = capy::db::connect(&config.database).await?;
    let admin_name: String = admin
        .query_one(Statement::from_string(
            admin.get_database_backend(),
            "SELECT current_database() AS name",
        ))
        .await?
        .unwrap()
        .try_get("", "name")?;
    // A supported SQLx query parameter must never override the isolated path.
    // PostgreSQL database names here come from the disposable admin connection.
    let separator = if url.contains('?') { '&' } else { '?' };
    let override_url =
        format!("{url}{separator}dbname={admin_name}&application_name=capy-isolation-test");
    let (a, b) = tokio::try_join!(
        TestApp::builder(application())
            .database(TestDatabase::Postgres(override_url))
            .boot(),
        TestApp::builder(application())
            .database(TestDatabase::Postgres(url.clone()))
            .boot()
    )?;
    let db_a: String = a
        .db()
        .query_one(Statement::from_string(
            a.db().get_database_backend(),
            "SELECT current_database() AS name",
        ))
        .await?
        .unwrap()
        .try_get("", "name")?;
    assert_ne!(db_a, admin_name);
    assert!(db_a.starts_with("capy_test_"));
    assert!(a
        .context()
        .config
        .database
        .url
        .contains("application_name=capy-isolation-test"));
    assert_ne!(
        a.context().config.database.url,
        b.context().config.database.url
    );
    a.factory::<RecordFactory>().create().await?;
    b.get("/api/records")
        .send()
        .await
        .assert_json(json!({"count":0}));
    a.cleanup().await?;
    b.cleanup().await?;
    let row = admin
        .query_one(Statement::from_sql_and_values(
            admin.get_database_backend(),
            "SELECT datname FROM pg_database WHERE datname=$1",
            [db_a.into()],
        ))
        .await?;
    assert!(row.is_none(), "cleanup must drop its disposable database");
    admin.close().await?;
    Ok(())
}

#[cfg(all(feature = "auth", feature = "jobs", feature = "mail"))]
mod authenticated {
    use super::*;
    use capy::{
        auth::{AuthUser, MemoryResetDelivery},
        mail::{Mail, MailContext, MailResult, Mailable, QueueableMail},
    };

    struct AuthMigrator;
    #[capy::migration::async_trait::async_trait]
    impl MigratorTrait for AuthMigrator {
        fn migrations() -> Vec<Box<dyn MigrationTrait>> {
            vec![
                Box::new(capy::auth::migration::IdentityMigration),
                Box::new(capy::jobs::migration::JobsMigration),
            ]
        }
    }
    struct Welcome;
    impl Mailable for Welcome {
        const NAME: &'static str = "test.welcome";
        fn render(&self) -> MailResult<Mail> {
            Ok(Mail::new("Welcome").text("Ready to read"))
        }
    }
    impl QueueableMail for Welcome {}
    async fn protected(AuthUser(user): AuthUser) -> Result<Json<Value>> {
        if user.email.starts_with("blocked") {
            return Err(AppError::Forbidden);
        }
        Ok(Json(json!({"email": user.email})))
    }
    async fn send_mail(
        AuthUser(user): AuthUser,
        Context(ctx): Context,
        MailContext(mail): MailContext,
    ) -> Result<NoContent> {
        mail.queue(&ctx, Welcome.to(&user.email)?).await?;
        Ok(NoContent)
    }
    fn factory(reset: MemoryResetDelivery) -> App<AuthMigrator> {
        App::new()
            .config(AppConfig::default())
            .auth(reset)
            .mail()
            .api_routes(
                Routes::new()
                    .post("/protected", protected)
                    .post("/welcome", send_mail),
            )
            .migrations(AuthMigrator)
    }

    #[tokio::test]
    async fn sessions_rotate_csrf_login_logout_and_preserve_authorization() -> Result<()> {
        let app = TestApp::boot(factory(MemoryResetDelivery::default())).await?;
        let mut guest = app.session();
        guest
            .post("/api/protected")
            .send()
            .await?
            .assert_status(axum::http::StatusCode::UNAUTHORIZED);
        guest.post("/api/auth/register").without_csrf().json(json!({"name":"Reader", "email":"reader@example.test", "password":"correct horse battery staple"})).send().await?.assert_status(axum::http::StatusCode::FORBIDDEN);
        guest.post("/api/auth/register").json(json!({"name":"Reader", "email":"reader@example.test", "password":"correct horse battery staple"})).send().await?.assert_created();
        guest
            .post("/api/protected")
            .send()
            .await?
            .assert_ok()
            .assert_json(json!({"email":"reader@example.test"}));
        guest.logout().await?.assert_no_content();
        guest
            .get("/api/auth/me")
            .send()
            .await?
            .assert_status(axum::http::StatusCode::UNAUTHORIZED);
        guest
            .login("reader@example.test", "wrong password")
            .await?
            .assert_status(axum::http::StatusCode::UNAUTHORIZED);
        guest
            .login("reader@example.test", "correct horse battery staple")
            .await?
            .assert_ok();
        guest.post("/api/protected").send().await?.assert_ok();
        let mut other = app.session();
        other.post("/api/auth/register").json(json!({"name":"Blocked", "email":"blocked@example.test", "password":"correct horse battery staple"})).send().await?.assert_created();
        other
            .post("/api/protected")
            .send()
            .await?
            .assert_status(axum::http::StatusCode::FORBIDDEN);
        app.cleanup().await
    }

    #[tokio::test]
    async fn reset_revokes_sessions_and_helpers_never_bypass_password_verification() -> Result<()> {
        let reset = MemoryResetDelivery::default();
        let app = TestApp::boot(factory(reset.clone())).await?;
        let mut user = app.session();
        user.post("/api/auth/register").json(json!({"name":"Reader", "email":"reader@example.test", "password":"correct horse battery staple"})).send().await?.assert_created();
        let mut second = app
            .login("reader@example.test", "correct horse battery staple")
            .await?;
        assert!(app
            .login("reader@example.test", "wrong password")
            .await
            .is_err());
        let mut anonymous = app.session();
        anonymous
            .post("/api/auth/forgot-password")
            .json(json!({"email":"reader@example.test"}))
            .send()
            .await?
            .assert_ok();
        let token = reset.take().remove(0).token;
        anonymous
            .post("/api/auth/reset-password")
            .json(json!({"token":token.expose(), "password":"a different long password"}))
            .send()
            .await?
            .assert_no_content();
        user.get("/api/auth/me")
            .send()
            .await?
            .assert_status(axum::http::StatusCode::UNAUTHORIZED);
        second
            .get("/api/auth/me")
            .send()
            .await?
            .assert_status(axum::http::StatusCode::UNAUTHORIZED);
        app.login("reader@example.test", "a different long password")
            .await?
            .get("/api/auth/me")
            .send()
            .await?
            .assert_ok();
        app.cleanup().await
    }

    #[tokio::test]
    async fn jobs_use_the_real_mail_handler_and_explicit_capture() -> Result<()> {
        let app = TestApp::builder(factory(MemoryResetDelivery::default()))
            .capture_mail()
            .boot()
            .await?;
        let mut user = app.session();
        user.post("/api/auth/register").json(json!({"name":"Reader", "email":"reader@example.test", "password":"correct horse battery staple"})).send().await?.assert_created();
        user.post("/api/welcome").send().await?.assert_no_content();
        assert!(app.mail().sent().is_empty());
        assert_eq!(app.jobs().clone().on_queue("mail")?.drain(10).await?, 1);
        app.mail().assert_sent_to("reader@example.test");
        app.mail().assert_subject("Welcome");
        assert_eq!(app.mail().sent().len(), 1);
        app.cleanup().await
    }
}