riley-cms-api 0.1.0

HTTP API server for riley_cms - Axum-based REST endpoints
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
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
//! Integration tests for riley-cms-api HTTP endpoints

use axum::{
    body::Body,
    http::{Request, StatusCode, header},
};
use http_body_util::BodyExt;
use riley_cms_api::{AppState, build_router};
use riley_cms_core::{RileyCms, RileyCmsConfig};
use serde_json::Value;
use std::fs;
use std::sync::Arc;
use tempfile::TempDir;
use tower::ServiceExt;

/// Create a minimal test config
fn create_test_config(temp_dir: &TempDir) -> RileyCmsConfig {
    let toml_content = format!(
        r#"
[content]
repo_path = "{}"
content_dir = "content"

[storage]
bucket = "test-bucket"
public_url_base = "https://test.example.com"

[auth]
api_token = "test-secret-token"
"#,
        temp_dir.path().display()
    );
    toml::from_str(&toml_content).unwrap()
}

/// Create test post files
fn create_test_post(dir: &std::path::Path, slug: &str, title: &str, goes_live_at: Option<&str>) {
    let post_dir = dir.join(slug);
    fs::create_dir_all(&post_dir).unwrap();

    let date_line = goes_live_at
        .map(|d| format!("goes_live_at = \"{}\"", d))
        .unwrap_or_default();

    fs::write(
        post_dir.join("config.toml"),
        format!(
            r#"title = "{}"
preview_text = "Preview for {}"
{}
"#,
            title, title, date_line
        ),
    )
    .unwrap();

    fs::write(
        post_dir.join("content.mdx"),
        format!("# {}\n\nContent here.", title),
    )
    .unwrap();
}

/// Helper to setup test environment and build router
async fn setup_test_app(temp_dir: &TempDir) -> axum::Router {
    let config = create_test_config(temp_dir);
    let riley_cms = RileyCms::from_config(config.clone()).await.unwrap();
    let state = Arc::new(AppState { riley_cms, config });
    build_router(state)
}

/// Helper to read response body as JSON
async fn body_json(body: Body) -> Value {
    let bytes = body.collect().await.unwrap().to_bytes();
    serde_json::from_slice(&bytes).unwrap()
}

// === Health Check Tests ===

#[tokio::test]
async fn test_health_endpoint() {
    let temp_dir = TempDir::new().unwrap();
    let app = setup_test_app(&temp_dir).await;

    let response = app
        .oneshot(
            Request::builder()
                .uri("/health")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();

    assert_eq!(response.status(), StatusCode::OK);

    let body = body_json(response.into_body()).await;
    assert_eq!(body["status"], "ok");
}

// === Public Posts Tests ===

#[tokio::test]
async fn test_list_posts_empty() {
    let temp_dir = TempDir::new().unwrap();
    let app = setup_test_app(&temp_dir).await;

    let response = app
        .oneshot(
            Request::builder()
                .uri("/api/v1/posts")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();

    assert_eq!(response.status(), StatusCode::OK);

    let body = body_json(response.into_body()).await;
    assert_eq!(body["posts"].as_array().unwrap().len(), 0);
    assert_eq!(body["total"], 0);
}

#[tokio::test]
async fn test_list_posts_with_live_content() {
    let temp_dir = TempDir::new().unwrap();
    let content_dir = temp_dir.path().join("content");
    fs::create_dir_all(&content_dir).unwrap();

    // Create a live post (past date)
    create_test_post(
        &content_dir,
        "live-post",
        "Live Post",
        Some("2020-01-01T00:00:00Z"),
    );

    let app = setup_test_app(&temp_dir).await;

    let response = app
        .oneshot(
            Request::builder()
                .uri("/api/v1/posts")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();

    assert_eq!(response.status(), StatusCode::OK);

    let body = body_json(response.into_body()).await;
    assert_eq!(body["posts"].as_array().unwrap().len(), 1);
    assert_eq!(body["posts"][0]["title"], "Live Post");
}

#[tokio::test]
async fn test_list_posts_excludes_drafts_by_default() {
    let temp_dir = TempDir::new().unwrap();
    let content_dir = temp_dir.path().join("content");
    fs::create_dir_all(&content_dir).unwrap();

    // Create a draft post (no date)
    create_test_post(&content_dir, "draft-post", "Draft Post", None);
    // Create a live post
    create_test_post(
        &content_dir,
        "live-post",
        "Live Post",
        Some("2020-01-01T00:00:00Z"),
    );

    let app = setup_test_app(&temp_dir).await;

    let response = app
        .oneshot(
            Request::builder()
                .uri("/api/v1/posts")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();

    assert_eq!(response.status(), StatusCode::OK);

    let body = body_json(response.into_body()).await;
    // Should only see the live post
    assert_eq!(body["posts"].as_array().unwrap().len(), 1);
    assert_eq!(body["posts"][0]["title"], "Live Post");
}

// === Authentication Tests ===

#[tokio::test]
async fn test_drafts_require_auth_returns_401() {
    let temp_dir = TempDir::new().unwrap();
    let content_dir = temp_dir.path().join("content");
    fs::create_dir_all(&content_dir).unwrap();

    create_test_post(&content_dir, "draft-post", "Draft Post", None);

    let app = setup_test_app(&temp_dir).await;

    // Request drafts without authentication
    let response = app
        .oneshot(
            Request::builder()
                .uri("/api/v1/posts?include_drafts=true")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();

    assert_eq!(response.status(), StatusCode::UNAUTHORIZED);

    let body = body_json(response.into_body()).await;
    assert!(body["error"].as_str().unwrap().contains("Authentication"));
}

#[tokio::test]
async fn test_scheduled_require_auth_returns_401() {
    let temp_dir = TempDir::new().unwrap();
    let content_dir = temp_dir.path().join("content");
    fs::create_dir_all(&content_dir).unwrap();

    create_test_post(
        &content_dir,
        "scheduled-post",
        "Scheduled Post",
        Some("2099-01-01T00:00:00Z"),
    );

    let app = setup_test_app(&temp_dir).await;

    // Request scheduled without authentication
    let response = app
        .oneshot(
            Request::builder()
                .uri("/api/v1/posts?include_scheduled=true")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();

    assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
}

#[tokio::test]
async fn test_drafts_with_valid_auth_returns_200() {
    let temp_dir = TempDir::new().unwrap();
    let content_dir = temp_dir.path().join("content");
    fs::create_dir_all(&content_dir).unwrap();

    create_test_post(&content_dir, "draft-post", "Draft Post", None);
    create_test_post(
        &content_dir,
        "live-post",
        "Live Post",
        Some("2020-01-01T00:00:00Z"),
    );

    let app = setup_test_app(&temp_dir).await;

    // Request drafts WITH valid authentication
    let response = app
        .oneshot(
            Request::builder()
                .uri("/api/v1/posts?include_drafts=true")
                .header(header::AUTHORIZATION, "Bearer test-secret-token")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();

    assert_eq!(response.status(), StatusCode::OK);

    let body = body_json(response.into_body()).await;
    // Should see both posts (live + draft)
    assert_eq!(body["posts"].as_array().unwrap().len(), 2);
}

#[tokio::test]
async fn test_invalid_token_returns_401() {
    let temp_dir = TempDir::new().unwrap();
    let content_dir = temp_dir.path().join("content");
    fs::create_dir_all(&content_dir).unwrap();

    create_test_post(&content_dir, "draft-post", "Draft Post", None);

    let app = setup_test_app(&temp_dir).await;

    // Request drafts with INVALID token
    let response = app
        .oneshot(
            Request::builder()
                .uri("/api/v1/posts?include_drafts=true")
                .header(header::AUTHORIZATION, "Bearer wrong-token")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();

    assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
}

// === Series Authentication Tests ===

#[tokio::test]
async fn test_series_drafts_require_auth() {
    let temp_dir = TempDir::new().unwrap();
    let app = setup_test_app(&temp_dir).await;

    // Request series drafts without authentication
    let response = app
        .oneshot(
            Request::builder()
                .uri("/api/v1/series?include_drafts=true")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();

    assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
}

#[tokio::test]
async fn test_series_drafts_with_valid_auth() {
    let temp_dir = TempDir::new().unwrap();
    let app = setup_test_app(&temp_dir).await;

    // Request series drafts WITH authentication
    let response = app
        .oneshot(
            Request::builder()
                .uri("/api/v1/series?include_drafts=true")
                .header(header::AUTHORIZATION, "Bearer test-secret-token")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();

    assert_eq!(response.status(), StatusCode::OK);
}

// === Cache Header Tests ===

#[tokio::test]
async fn test_public_response_has_cache_headers() {
    let temp_dir = TempDir::new().unwrap();
    let content_dir = temp_dir.path().join("content");
    fs::create_dir_all(&content_dir).unwrap();

    create_test_post(&content_dir, "post", "Post", Some("2020-01-01T00:00:00Z"));

    let app = setup_test_app(&temp_dir).await;

    let response = app
        .oneshot(
            Request::builder()
                .uri("/api/v1/posts")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();

    assert_eq!(response.status(), StatusCode::OK);

    // Should have Cache-Control header with public directive
    let cache_control = response.headers().get(header::CACHE_CONTROL).unwrap();
    assert!(cache_control.to_str().unwrap().contains("public"));

    // Should have ETag header
    assert!(response.headers().contains_key(header::ETAG));
}

#[tokio::test]
async fn test_authenticated_response_no_public_cache() {
    let temp_dir = TempDir::new().unwrap();
    let content_dir = temp_dir.path().join("content");
    fs::create_dir_all(&content_dir).unwrap();

    create_test_post(&content_dir, "draft", "Draft", None);

    let app = setup_test_app(&temp_dir).await;

    let response = app
        .oneshot(
            Request::builder()
                .uri("/api/v1/posts?include_drafts=true")
                .header(header::AUTHORIZATION, "Bearer test-secret-token")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();

    assert_eq!(response.status(), StatusCode::OK);

    // Should have Cache-Control with private/no-store
    let cache_control = response.headers().get(header::CACHE_CONTROL).unwrap();
    let cc_str = cache_control.to_str().unwrap();
    assert!(cc_str.contains("private") || cc_str.contains("no-store"));
}

// === Single Post Tests ===

#[tokio::test]
async fn test_get_single_post() {
    let temp_dir = TempDir::new().unwrap();
    let content_dir = temp_dir.path().join("content");
    fs::create_dir_all(&content_dir).unwrap();

    create_test_post(
        &content_dir,
        "my-post",
        "My Post",
        Some("2020-01-01T00:00:00Z"),
    );

    let app = setup_test_app(&temp_dir).await;

    let response = app
        .oneshot(
            Request::builder()
                .uri("/api/v1/posts/my-post")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();

    assert_eq!(response.status(), StatusCode::OK);

    let body = body_json(response.into_body()).await;
    assert_eq!(body["slug"], "my-post");
    assert_eq!(body["title"], "My Post");
    assert!(body["content"].as_str().unwrap().contains("# My Post"));
}

#[tokio::test]
async fn test_get_nonexistent_post_returns_404() {
    let temp_dir = TempDir::new().unwrap();
    let app = setup_test_app(&temp_dir).await;

    let response = app
        .oneshot(
            Request::builder()
                .uri("/api/v1/posts/nonexistent")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();

    assert_eq!(response.status(), StatusCode::NOT_FOUND);
}

// === Visibility Bypass Tests (get_post) ===

#[tokio::test]
async fn test_draft_post_returns_404_without_auth() {
    let temp_dir = TempDir::new().unwrap();
    let content_dir = temp_dir.path().join("content");
    fs::create_dir_all(&content_dir).unwrap();

    // Create a draft post (no goes_live_at)
    create_test_post(&content_dir, "secret-draft", "Secret Draft", None);

    let app = setup_test_app(&temp_dir).await;

    // Accessing draft directly by slug without auth should return 404
    let response = app
        .oneshot(
            Request::builder()
                .uri("/api/v1/posts/secret-draft")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();

    assert_eq!(response.status(), StatusCode::NOT_FOUND);
}

#[tokio::test]
async fn test_scheduled_post_returns_404_without_auth() {
    let temp_dir = TempDir::new().unwrap();
    let content_dir = temp_dir.path().join("content");
    fs::create_dir_all(&content_dir).unwrap();

    // Create a scheduled post (future date)
    create_test_post(
        &content_dir,
        "future-post",
        "Future Post",
        Some("2099-01-01T00:00:00Z"),
    );

    let app = setup_test_app(&temp_dir).await;

    // Accessing scheduled post directly by slug without auth should return 404
    let response = app
        .oneshot(
            Request::builder()
                .uri("/api/v1/posts/future-post")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();

    assert_eq!(response.status(), StatusCode::NOT_FOUND);
}

#[tokio::test]
async fn test_draft_post_visible_with_admin_auth() {
    let temp_dir = TempDir::new().unwrap();
    let content_dir = temp_dir.path().join("content");
    fs::create_dir_all(&content_dir).unwrap();

    create_test_post(&content_dir, "secret-draft", "Secret Draft", None);

    let app = setup_test_app(&temp_dir).await;

    // Accessing draft with valid admin token should succeed
    let response = app
        .oneshot(
            Request::builder()
                .uri("/api/v1/posts/secret-draft")
                .header(header::AUTHORIZATION, "Bearer test-secret-token")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();

    assert_eq!(response.status(), StatusCode::OK);

    let body = body_json(response.into_body()).await;
    assert_eq!(body["title"], "Secret Draft");
}

#[tokio::test]
async fn test_draft_post_raw_returns_404_without_auth() {
    let temp_dir = TempDir::new().unwrap();
    let content_dir = temp_dir.path().join("content");
    fs::create_dir_all(&content_dir).unwrap();

    create_test_post(&content_dir, "secret-draft", "Secret Draft", None);

    let app = setup_test_app(&temp_dir).await;

    // Accessing draft raw content without auth should return 404
    let response = app
        .oneshot(
            Request::builder()
                .uri("/api/v1/posts/secret-draft/raw")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();

    assert_eq!(response.status(), StatusCode::NOT_FOUND);
}

// === Series Visibility Tests ===

#[tokio::test]
async fn test_draft_series_returns_404_without_auth() {
    let temp_dir = TempDir::new().unwrap();
    let content_dir = temp_dir.path().join("content");
    let series_dir = content_dir.join("draft-series");

    fs::create_dir_all(&series_dir).unwrap();
    fs::write(
        series_dir.join("series.toml"),
        r#"title = "Draft Series"
description = "A draft series"
"#,
    )
    .unwrap();

    let app = setup_test_app(&temp_dir).await;

    // Accessing draft series directly by slug without auth should return 404
    let response = app
        .oneshot(
            Request::builder()
                .uri("/api/v1/series/draft-series")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();

    assert_eq!(response.status(), StatusCode::NOT_FOUND);
}

#[tokio::test]
async fn test_draft_series_visible_with_admin_auth() {
    let temp_dir = TempDir::new().unwrap();
    let content_dir = temp_dir.path().join("content");
    let series_dir = content_dir.join("draft-series");

    fs::create_dir_all(&series_dir).unwrap();
    fs::write(
        series_dir.join("series.toml"),
        r#"title = "Draft Series"
description = "A draft series"
"#,
    )
    .unwrap();

    let app = setup_test_app(&temp_dir).await;

    // Accessing draft series with admin token should succeed
    let response = app
        .oneshot(
            Request::builder()
                .uri("/api/v1/series/draft-series")
                .header(header::AUTHORIZATION, "Bearer test-secret-token")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();

    assert_eq!(response.status(), StatusCode::OK);

    let body = body_json(response.into_body()).await;
    assert_eq!(body["title"], "Draft Series");
}

// === Git Path Validation Tests ===

#[tokio::test]
async fn test_git_path_traversal_rejected() {
    let temp_dir = TempDir::new().unwrap();
    let app = setup_test_app(&temp_dir).await;

    let response = app
        .oneshot(
            Request::builder()
                .uri("/git/../../etc/passwd")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();

    // Should be rejected (either 400 Bad Request or auth failure)
    assert!(
        response.status() == StatusCode::BAD_REQUEST
            || response.status() == StatusCode::UNAUTHORIZED
    );
}

#[tokio::test]
async fn test_git_path_special_chars_rejected() {
    let temp_dir = TempDir::new().unwrap();
    let app = setup_test_app(&temp_dir).await;

    let response = app
        .oneshot(
            Request::builder()
                .uri("/git/;rm%20-rf%20/")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();

    // Should be rejected
    assert!(
        response.status() == StatusCode::BAD_REQUEST
            || response.status() == StatusCode::UNAUTHORIZED
    );
}

// === ETag Tests ===

#[tokio::test]
async fn test_etag_is_full_sha256() {
    let temp_dir = TempDir::new().unwrap();
    let content_dir = temp_dir.path().join("content");
    fs::create_dir_all(&content_dir).unwrap();

    create_test_post(&content_dir, "post", "Post", Some("2020-01-01T00:00:00Z"));

    let app = setup_test_app(&temp_dir).await;

    let response = app
        .oneshot(
            Request::builder()
                .uri("/api/v1/posts")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();

    assert_eq!(response.status(), StatusCode::OK);

    let etag = response
        .headers()
        .get(header::ETAG)
        .unwrap()
        .to_str()
        .unwrap();
    // Full SHA256 = 64 hex chars + 2 quotes = 66 chars
    assert_eq!(
        etag.len(),
        66,
        "ETag should be full SHA256 (64 hex chars + quotes), got: {}",
        etag
    );
    assert!(etag.starts_with('"') && etag.ends_with('"'));
}