raisfast 0.2.21

The last backend you'll ever need. Rust-powered headless CMS with built-in blog, ecommerce, wallet, payment and 4 plugin engines.
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
use super::*;
use raisfast::DbDriver;

async fn has_tenant_id_column(pool: &raisfast::db::Pool) -> bool {
    #[cfg(feature = "db-sqlite")]
    {
        let result: Result<(i64,), sqlx::Error> = sqlx::query_as(
            "SELECT COUNT(*) FROM pragma_table_info('users') WHERE name = 'tenant_id'",
        )
        .fetch_one(pool)
        .await;
        result.is_ok_and(|(c,)| c > 0)
    }
    #[cfg(not(feature = "db-sqlite"))]
    {
        let _ = pool;
        false
    }
}

macro_rules! skip_without_tenant {
    ($pool:expr) => {
        if !has_tenant_id_column($pool).await {
            return;
        }
    };
}

async fn create_tenant_in_db(pool: &raisfast::db::Pool, name: &str) {
    let now = chrono::Utc::now().to_rfc3339();
    sqlx::query(
        "INSERT OR IGNORE INTO tenants (name, config, status, created_at, updated_at) VALUES (?, '{}', 'active', ?, ?)"
    )
    .bind(name).bind(&now).bind(&now)
    .execute(pool).await.unwrap();
}

async fn create_user_in_tenant(
    pool: &raisfast::db::Pool,
    email: &str,
    username: &str,
    role: &str,
    tenant_id: &str,
) -> i64 {
    let hash = raisfast::services::auth::hash_password("TestPass123!").unwrap();
    let sql = format!(
        "INSERT INTO users (tenant_id, username, role, status, registered_via) VALUES ({}, {}, {}, 'active', 'email') RETURNING id",
        raisfast::db::Driver::ph(1),
        raisfast::db::Driver::ph(2),
        raisfast::db::Driver::ph(3)
    );
    let int_id: i64 = sqlx::query_scalar(&sql)
        .bind(tenant_id)
        .bind(username)
        .bind(role)
        .fetch_one(pool)
        .await
        .unwrap();
    let cred_data = serde_json::json!({"password_hash": hash}).to_string();
    let cred_id = raisfast::utils::id::new_id();
    let cred_now = raisfast::utils::tz::now_utc();
    let cred_sql = format!(
        "INSERT INTO user_credentials (id, user_id, auth_type, identifier, credential_data, verified, created_at, updated_at) VALUES ({}, {}, 'email', {}, {}, 1, {}, {})",
        raisfast::db::Driver::ph(1),
        raisfast::db::Driver::ph(2),
        raisfast::db::Driver::ph(3),
        raisfast::db::Driver::ph(4),
        raisfast::db::Driver::ph(5),
        raisfast::db::Driver::ph(6)
    );
    sqlx::query(&cred_sql)
        .bind(cred_id)
        .bind(int_id)
        .bind(email)
        .bind(&cred_data)
        .bind(cred_now)
        .bind(cred_now)
        .execute(pool)
        .await
        .unwrap();
    int_id
}

async fn create_published_post_in_tenant(
    pool: &raisfast::db::Pool,
    slug: &str,
    title: &str,
    author_int_id: i64,
    tenant_id: &str,
) {
    let now = chrono::Utc::now().to_rfc3339();
    let sql = format!(
        "INSERT INTO posts (tenant_id, title, slug, content, excerpt, status, created_by, updated_by, created_at, updated_at) VALUES ({}, {}, {}, 'content', 'excerpt', 'published', {}, NULL, {}, {})",
        raisfast::db::Driver::ph(1),
        raisfast::db::Driver::ph(2),
        raisfast::db::Driver::ph(3),
        raisfast::db::Driver::ph(4),
        raisfast::db::Driver::ph(5),
        raisfast::db::Driver::ph(6)
    );
    sqlx::query(&sql)
        .bind(tenant_id)
        .bind(title)
        .bind(slug)
        .bind(author_int_id)
        .bind(&now)
        .bind(&now)
        .execute(pool)
        .await
        .unwrap();
}

fn login_with_tenant(email: &str, password: &str, tenant_id: &str) -> Request<Body> {
    Request::builder()
        .method("POST")
        .uri("/api/v1/auth/login")
        .header(header::CONTENT_TYPE, "application/json")
        .header("X-Tenant-ID", tenant_id)
        .body(Body::from(
            serde_json::to_string(&json!({"email": email, "password": password})).unwrap(),
        ))
        .unwrap()
}

fn get_with_tenant(path: &str, tenant_id: &str) -> Request<Body> {
    Request::builder()
        .method("GET")
        .uri(path)
        .header("X-Tenant-ID", tenant_id)
        .body(Body::empty())
        .unwrap()
}

fn get_auth_tenant(path: &str, token: &str, tenant_id: &str) -> Request<Body> {
    Request::builder()
        .method("GET")
        .uri(path)
        .header(header::AUTHORIZATION, format!("Bearer {token}"))
        .header("X-Tenant-ID", tenant_id)
        .body(Body::empty())
        .unwrap()
}

async fn do_login(app: &mut axum::Router, email: &str, password: &str, tenant_id: &str) -> String {
    let (status, body) = send(app, login_with_tenant(email, password, tenant_id)).await;
    assert!(
        status.is_success(),
        "login failed for {email} tenant={tenant_id}: {status} {body:?}"
    );
    body["data"]["access_token"].as_str().unwrap().to_string()
}

#[tokio::test]
async fn tenant_user_sees_own_data_only() {
    let (mut app, state) = test_app().await;
    let pool = &state.pool;
    skip_without_tenant!(pool);

    create_tenant_in_db(pool, "Tenant A").await;
    create_tenant_in_db(pool, "Tenant B").await;

    create_user_in_tenant(
        pool,
        "author_a@tenant.test",
        "author_a",
        "author",
        "tenant_a",
    )
    .await;

    create_user_in_tenant(
        pool,
        "author_b@tenant.test",
        "author_b",
        "author",
        "tenant_b",
    )
    .await;

    let token_a = do_login(&mut app, "author_a@tenant.test", "TestPass123!", "tenant_a").await;
    let token_b = do_login(&mut app, "author_b@tenant.test", "TestPass123!", "tenant_b").await;

    let (status, body) = send(
        &mut app,
        post_json_auth(
            "/api/v1/posts",
            json!({"title": "Post from A", "content": "content a", "status": "published"}),
            &token_a,
        ),
    )
    .await;
    assert!(status.is_success(), "create post a: {status} {body:?}");

    let (status, body) = send(
        &mut app,
        post_json_auth(
            "/api/v1/posts",
            json!({"title": "Post from B", "content": "content b", "status": "published"}),
            &token_b,
        ),
    )
    .await;
    assert!(status.is_success(), "create post b: {status} {body:?}");

    let (status, body) = send(&mut app, get_auth("/api/v1/posts", &token_a)).await;
    assert!(status.is_success(), "author_a list: {status} {body:?}");
    let items = body["data"]["items"].as_array().unwrap();
    assert_eq!(
        items.len(),
        1,
        "author_a should see 1 post, got {}",
        items.len()
    );
    assert_eq!(items[0]["title"], "Post from A");

    let (status, body) = send(&mut app, get_auth("/api/v1/posts", &token_b)).await;
    assert!(status.is_success(), "author_b list: {status} {body:?}");
    let items = body["data"]["items"].as_array().unwrap();
    assert_eq!(
        items.len(),
        1,
        "author_b should see 1 post, got {}",
        items.len()
    );
    assert_eq!(items[0]["title"], "Post from B");
}

#[tokio::test]
async fn admin_without_header_sees_all() {
    let (mut app, state) = test_app().await;
    let pool = &state.pool;
    skip_without_tenant!(pool);

    create_tenant_in_db(pool, "Tenant A").await;
    create_tenant_in_db(pool, "Tenant B").await;

    create_user_in_tenant(
        pool,
        "admin_all@tenant.test",
        "admin_all",
        "admin",
        "tenant_a",
    )
    .await;

    let author_a_int_id = create_user_in_tenant(
        pool,
        "author_ta@tenant.test",
        "author_ta",
        "author",
        "tenant_a",
    )
    .await;

    let author_b_int_id = create_user_in_tenant(
        pool,
        "author_tb@tenant.test",
        "author_tb",
        "author",
        "tenant_b",
    )
    .await;

    create_published_post_in_tenant(
        pool,
        "post-tenant-a",
        "Post in Tenant A",
        author_a_int_id,
        "tenant_a",
    )
    .await;

    create_published_post_in_tenant(
        pool,
        "post-tenant-b",
        "Post in Tenant B",
        author_b_int_id,
        "tenant_b",
    )
    .await;

    let token = do_login(
        &mut app,
        "admin_all@tenant.test",
        "TestPass123!",
        "tenant_a",
    )
    .await;

    let (status, body) = send(&mut app, get_auth("/api/v1/posts", &token)).await;
    assert!(status.is_success(), "admin list: {status} {body:?}");
    let total = body["data"]["total"].as_i64().unwrap();
    assert_eq!(
        total, 2,
        "admin without header should see 2 posts, got {total}"
    );
}

#[tokio::test]
async fn admin_switches_tenant_with_header() {
    let (mut app, state) = test_app().await;
    let pool = &state.pool;
    skip_without_tenant!(pool);

    create_tenant_in_db(pool, "Tenant A").await;
    create_tenant_in_db(pool, "Tenant B").await;

    create_user_in_tenant(
        pool,
        "admin_switch@tenant.test",
        "admin_switch",
        "admin",
        "default",
    )
    .await;

    let author_a_int_id = create_user_in_tenant(
        pool,
        "author_sw@tenant.test",
        "author_sw",
        "author",
        "tenant_a",
    )
    .await;

    create_published_post_in_tenant(
        pool,
        "post-switch-a",
        "Post in Tenant A for Switch",
        author_a_int_id,
        "tenant_a",
    )
    .await;

    let token = do_login(
        &mut app,
        "admin_switch@tenant.test",
        "TestPass123!",
        "default",
    )
    .await;

    let (status, body) = send(
        &mut app,
        get_auth_tenant("/api/v1/posts", &token, "tenant_a"),
    )
    .await;
    assert!(status.is_success(), "admin tenant_a: {status} {body:?}");
    let total = body["data"]["total"].as_i64().unwrap();
    assert_eq!(
        total, 1,
        "admin with tenant_a header should see 1 post, got {total}"
    );

    let (status, body) = send(
        &mut app,
        get_auth_tenant("/api/v1/posts", &token, "tenant_b"),
    )
    .await;
    assert!(status.is_success(), "admin tenant_b: {status} {body:?}");
    let total = body["data"]["total"].as_i64().unwrap();
    assert_eq!(
        total, 0,
        "admin with tenant_b header should see 0 posts, got {total}"
    );
}

#[tokio::test]
async fn public_api_scoped_by_tenant_header() {
    let (mut app, state) = test_app().await;
    let pool = &state.pool;
    skip_without_tenant!(pool);

    create_tenant_in_db(pool, "Tenant A").await;
    create_tenant_in_db(pool, "Tenant B").await;

    let author_a_int_id = create_user_in_tenant(
        pool,
        "author_pub_a@tenant.test",
        "author_pub_a",
        "author",
        "tenant_a",
    )
    .await;

    let author_b_int_id = create_user_in_tenant(
        pool,
        "author_pub_b@tenant.test",
        "author_pub_b",
        "author",
        "tenant_b",
    )
    .await;

    create_published_post_in_tenant(
        pool,
        "public-post-a",
        "Public Post A",
        author_a_int_id,
        "tenant_a",
    )
    .await;

    create_published_post_in_tenant(
        pool,
        "public-post-b",
        "Public Post B",
        author_b_int_id,
        "tenant_b",
    )
    .await;

    let (status, body) = send(&mut app, get_with_tenant("/api/v1/posts", "tenant_a")).await;
    assert!(status.is_success(), "public tenant_a: {status} {body:?}");
    let total = body["data"]["total"].as_i64().unwrap();
    assert_eq!(
        total, 1,
        "public with tenant_a should see 1 post, got {total}"
    );

    let (status, body) = send(&mut app, get_with_tenant("/api/v1/posts", "tenant_b")).await;
    assert!(status.is_success(), "public tenant_b: {status} {body:?}");
    let total = body["data"]["total"].as_i64().unwrap();
    assert_eq!(
        total, 1,
        "public with tenant_b should see 1 post, got {total}"
    );

    let (status, body) = send(&mut app, get_req("/api/v1/posts")).await;
    assert!(status.is_success(), "public no header: {status} {body:?}");
    let total = body["data"]["total"].as_i64().unwrap();
    assert_eq!(
        total, 0,
        "public without header should see default tenant (0 posts), got {total}"
    );
}

#[tokio::test]
async fn cross_tenant_post_not_accessible() {
    let (mut app, state) = test_app().await;
    let pool = &state.pool;
    skip_without_tenant!(pool);

    create_tenant_in_db(pool, "Tenant A").await;
    create_tenant_in_db(pool, "Tenant B").await;

    let author_a_int_id = create_user_in_tenant(
        pool,
        "author_cross@tenant.test",
        "author_cross",
        "author",
        "tenant_a",
    )
    .await;

    let post_slug = "cross-tenant-post";
    create_published_post_in_tenant(
        pool,
        post_slug,
        "Cross Tenant Post",
        author_a_int_id,
        "tenant_a",
    )
    .await;

    let (status, body) = send(
        &mut app,
        get_with_tenant(&format!("/api/v1/posts/{post_slug}"), "tenant_a"),
    )
    .await;
    assert!(
        status.is_success(),
        "same tenant should succeed: {status} {body:?}"
    );

    let (status, _body) = send(
        &mut app,
        get_with_tenant(&format!("/api/v1/posts/{post_slug}"), "tenant_b"),
    )
    .await;
    assert_eq!(
        status,
        StatusCode::NOT_FOUND,
        "cross-tenant access should return 404"
    );
}