lific 2.5.0

Local-first, lightweight issue tracker. Single binary, SQLite-backed, MCP-native.
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
use axum::{
    Extension,
    extract::{Json, Path, Query, State},
};

use crate::authz;
use crate::db::{DbPool, models::*};
use crate::error::LificError;
use crate::realtime::{RealtimeEvent, RealtimeHub};

use super::{require_structure_role, with_read, with_write};

// ── Module endpoints ─────────────────────────────────────────

#[derive(serde::Deserialize)]
pub(super) struct ModuleQuery {
    project_id: i64,
}

pub(super) async fn list_modules(
    State(db): State<DbPool>,
    Extension(auth_user): Extension<Option<AuthUser>>,
    Query(q): Query<ModuleQuery>,
) -> Result<Json<Vec<Module>>, LificError> {
    authz::require_role(&db, &auth_user, q.project_id, Role::Viewer)?;
    with_read(&db, |conn| {
        crate::db::queries::list_modules(conn, q.project_id)
    })
    .map(Json)
}

pub(super) async fn get_module(
    State(db): State<DbPool>,
    Extension(auth_user): Extension<Option<AuthUser>>,
    Path(id): Path<i64>,
) -> Result<Json<Module>, LificError> {
    let module = with_read(&db, |conn| crate::db::queries::get_module(conn, id))?;
    authz::require_role(&db, &auth_user, module.project_id, Role::Viewer)?;
    Ok(Json(module))
}

pub(super) async fn create_module(
    State(db): State<DbPool>,
    Extension(realtime): Extension<RealtimeHub>,
    Extension(auth_user): Extension<Option<AuthUser>>,
    Json(input): Json<CreateModule>,
) -> Result<Json<Module>, LificError> {
    require_structure_role(&db, &auth_user, input.project_id)?;
    let module = with_write(&db, |conn| crate::db::queries::create_module(conn, &input))?;
    realtime.send(RealtimeEvent::ProjectUpdated { project_id: module.project_id });
    Ok(Json(module))
}

pub(super) async fn update_module(
    State(db): State<DbPool>,
    Extension(realtime): Extension<RealtimeHub>,
    Path(id): Path<i64>,
    Extension(auth_user): Extension<Option<AuthUser>>,
    Json(input): Json<UpdateModule>,
) -> Result<Json<Module>, LificError> {
    let project_id = with_read(&db, |conn| {
        crate::db::queries::get_resource_project_id(conn, "modules", id)
    })?;
    require_structure_role(&db, &auth_user, project_id)?;
    let module = with_write(&db, |conn| {
        crate::db::queries::update_module(conn, id, &input)
    })?;
    realtime.send(RealtimeEvent::ProjectUpdated { project_id });
    Ok(Json(module))
}

pub(super) async fn delete_module_handler(
    State(db): State<DbPool>,
    Extension(realtime): Extension<RealtimeHub>,
    Path(id): Path<i64>,
    Extension(auth_user): Extension<Option<AuthUser>>,
) -> Result<Json<serde_json::Value>, LificError> {
    let project_id = with_read(&db, |conn| {
        crate::db::queries::get_resource_project_id(conn, "modules", id)
    })?;
    require_structure_role(&db, &auth_user, project_id)?;
    with_write(&db, |conn| crate::db::queries::delete_module(conn, id))?;
    realtime.send(RealtimeEvent::ProjectUpdated { project_id });
    Ok(Json(serde_json::json!({"deleted": true})))
}

// ── Label endpoints ──────────────────────────────────────────

#[derive(serde::Deserialize)]
pub(super) struct LabelQuery {
    project_id: i64,
}

pub(super) async fn list_labels(
    State(db): State<DbPool>,
    Extension(auth_user): Extension<Option<AuthUser>>,
    Query(q): Query<LabelQuery>,
) -> Result<Json<Vec<Label>>, LificError> {
    authz::require_role(&db, &auth_user, q.project_id, Role::Viewer)?;
    with_read(&db, |conn| {
        crate::db::queries::list_labels(conn, q.project_id)
    })
    .map(Json)
}

pub(super) async fn create_label(
    State(db): State<DbPool>,
    Extension(realtime): Extension<RealtimeHub>,
    Extension(auth_user): Extension<Option<AuthUser>>,
    Json(input): Json<CreateLabel>,
) -> Result<Json<Label>, LificError> {
    require_structure_role(&db, &auth_user, input.project_id)?;
    let label = with_write(&db, |conn| crate::db::queries::create_label(conn, &input))?;
    realtime.send(RealtimeEvent::ProjectUpdated { project_id: input.project_id });
    Ok(Json(label))
}

pub(super) async fn update_label_handler(
    State(db): State<DbPool>,
    Extension(realtime): Extension<RealtimeHub>,
    Path(id): Path<i64>,
    Extension(auth_user): Extension<Option<AuthUser>>,
    Json(input): Json<UpdateLabel>,
) -> Result<Json<Label>, LificError> {
    let project_id = with_read(&db, |conn| {
        crate::db::queries::get_resource_project_id(conn, "labels", id)
    })?;
    require_structure_role(&db, &auth_user, project_id)?;
    let label = with_write(&db, |conn| {
        crate::db::queries::update_label(conn, id, &input)
    })?;
    realtime.send(RealtimeEvent::ProjectUpdated { project_id });
    Ok(Json(label))
}

pub(super) async fn delete_label_handler(
    State(db): State<DbPool>,
    Extension(realtime): Extension<RealtimeHub>,
    Path(id): Path<i64>,
    Extension(auth_user): Extension<Option<AuthUser>>,
) -> Result<Json<serde_json::Value>, LificError> {
    let project_id = with_read(&db, |conn| {
        crate::db::queries::get_resource_project_id(conn, "labels", id)
    })?;
    require_structure_role(&db, &auth_user, project_id)?;
    with_write(&db, |conn| crate::db::queries::delete_label(conn, id))?;
    realtime.send(RealtimeEvent::ProjectUpdated { project_id });
    Ok(Json(serde_json::json!({"deleted": true})))
}

#[derive(serde::Deserialize)]
pub(super) struct MergeLabel {
    /// Target label id the source is folded into.
    into: i64,
}

pub(super) async fn merge_label_handler(
    State(db): State<DbPool>,
    Extension(realtime): Extension<RealtimeHub>,
    Path(id): Path<i64>,
    Extension(auth_user): Extension<Option<AuthUser>>,
    Json(input): Json<MergeLabel>,
) -> Result<Json<Label>, LificError> {
    // Both labels must live in the same project, and the caller must lead it.
    let source_project = with_read(&db, |conn| {
        crate::db::queries::get_resource_project_id(conn, "labels", id)
    })?;
    let target_project = with_read(&db, |conn| {
        crate::db::queries::get_resource_project_id(conn, "labels", input.into)
    })?;
    if source_project != target_project {
        return Err(LificError::BadRequest(
            "cannot merge labels across projects".into(),
        ));
    }
    require_structure_role(&db, &auth_user, source_project)?;
    let label = with_write(&db, |conn| {
        crate::db::queries::merge_label(conn, id, input.into)
    })?;
    realtime.send(RealtimeEvent::ProjectUpdated { project_id: source_project });
    Ok(Json(label))
}

// ── Folder endpoints ─────────────────────────────────────────

#[derive(serde::Deserialize)]
pub(super) struct FolderQuery {
    project_id: i64,
}

pub(super) async fn list_folders_handler(
    State(db): State<DbPool>,
    Extension(auth_user): Extension<Option<AuthUser>>,
    Query(q): Query<FolderQuery>,
) -> Result<Json<Vec<Folder>>, LificError> {
    authz::require_role(&db, &auth_user, q.project_id, Role::Viewer)?;
    with_read(&db, |conn| {
        crate::db::queries::list_folders(conn, q.project_id)
    })
    .map(Json)
}

pub(super) async fn create_folder(
    State(db): State<DbPool>,
    Extension(realtime): Extension<RealtimeHub>,
    Extension(auth_user): Extension<Option<AuthUser>>,
    Json(input): Json<CreateFolder>,
) -> Result<Json<Folder>, LificError> {
    require_structure_role(&db, &auth_user, input.project_id)?;
    let folder = with_write(&db, |conn| crate::db::queries::create_folder(conn, &input))?;
    realtime.send(RealtimeEvent::ProjectUpdated { project_id: input.project_id });
    Ok(Json(folder))
}

pub(super) async fn delete_folder_handler(
    State(db): State<DbPool>,
    Extension(realtime): Extension<RealtimeHub>,
    Path(id): Path<i64>,
    Extension(auth_user): Extension<Option<AuthUser>>,
) -> Result<Json<serde_json::Value>, LificError> {
    let project_id = with_read(&db, |conn| {
        crate::db::queries::get_resource_project_id(conn, "folders", id)
    })?;
    require_structure_role(&db, &auth_user, project_id)?;
    with_write(&db, |conn| crate::db::queries::delete_folder(conn, id))?;
    realtime.send(RealtimeEvent::ProjectUpdated { project_id });
    Ok(Json(serde_json::json!({"deleted": true})))
}

pub(super) async fn update_folder(
    State(db): State<DbPool>,
    Extension(realtime): Extension<RealtimeHub>,
    Path(id): Path<i64>,
    Extension(auth_user): Extension<Option<AuthUser>>,
    Json(input): Json<UpdateFolder>,
) -> Result<Json<Folder>, LificError> {
    let project_id = with_read(&db, |conn| {
        crate::db::queries::get_resource_project_id(conn, "folders", id)
    })?;
    require_structure_role(&db, &auth_user, project_id)?;
    let folder = with_write(&db, |conn| {
        crate::db::queries::update_folder(conn, id, &input)
    })?;
    realtime.send(RealtimeEvent::ProjectUpdated { project_id });
    Ok(Json(folder))
}

#[cfg(test)]
mod tests {
    use crate::api::test_helpers::*;
    use axum::http::StatusCode;

    #[tokio::test]
    async fn lead_can_manage_modules() {
        let (db, _, lead, regular, project_id) = setup_lead_test();

        // Lead can create a module
        let lead_app = app_as_user(db.clone(), &lead);
        let body = serde_json::json!({
            "project_id": project_id,
            "name": "Backend",
            "status": "active"
        });
        let resp = json_post(&lead_app, "/api/modules", body).await;
        assert_eq!(resp.status(), StatusCode::OK);

        // Regular user cannot create a module
        let reg_app = app_as_user(db, &regular);
        let body = serde_json::json!({
            "project_id": project_id,
            "name": "Forbidden Module",
            "status": "active"
        });
        let resp = json_post(&reg_app, "/api/modules", body).await;
        assert_eq!(resp.status(), StatusCode::FORBIDDEN);
    }

    #[tokio::test]
    async fn lead_can_manage_labels() {
        let (db, _, lead, regular, project_id) = setup_lead_test();

        // Lead can create a label
        let lead_app = app_as_user(db.clone(), &lead);
        let body = serde_json::json!({
            "project_id": project_id,
            "name": "bug",
            "color": "#FF0000"
        });
        let resp = json_post(&lead_app, "/api/labels", body).await;
        assert_eq!(resp.status(), StatusCode::OK);

        // Regular user cannot
        let reg_app = app_as_user(db, &regular);
        let body = serde_json::json!({
            "project_id": project_id,
            "name": "forbidden-label",
            "color": "#FF0000"
        });
        let resp = json_post(&reg_app, "/api/labels", body).await;
        assert_eq!(resp.status(), StatusCode::FORBIDDEN);
    }

    #[tokio::test]
    async fn lead_can_update_label_and_regular_cannot() {
        let (db, _, lead, regular, project_id) = setup_lead_test();
        let lead_app = app_as_user(db.clone(), &lead);

        // Create a label to mutate.
        let resp = json_post(
            &lead_app,
            "/api/labels",
            serde_json::json!({ "project_id": project_id, "name": "bug", "color": "#FF0000" }),
        )
        .await;
        assert_eq!(resp.status(), StatusCode::OK);
        let created = parse_json(resp).await;
        let label_id = created["id"].as_i64().unwrap();

        // Lead can rename + recolor it.
        let resp = json_put(
            &lead_app,
            &format!("/api/labels/{label_id}"),
            serde_json::json!({ "name": "defect", "color": "#00FF00" }),
        )
        .await;
        assert_eq!(resp.status(), StatusCode::OK);
        let updated = parse_json(resp).await;
        assert_eq!(updated["name"], "defect");
        assert_eq!(updated["color"], "#00FF00");

        // Regular user cannot update it.
        let reg_app = app_as_user(db, &regular);
        let resp = json_put(
            &reg_app,
            &format!("/api/labels/{label_id}"),
            serde_json::json!({ "name": "nope" }),
        )
        .await;
        assert_eq!(resp.status(), StatusCode::FORBIDDEN);
    }

    #[tokio::test]
    async fn lead_can_update_folder_and_regular_cannot() {
        let (db, _, lead, regular, project_id) = setup_lead_test();
        let lead_app = app_as_user(db.clone(), &lead);
        let created = parse_json(
            json_post(
                &lead_app,
                "/api/folders",
                serde_json::json!({ "project_id": project_id, "name": "Docs" }),
            )
            .await,
        )
        .await;
        let folder_id = created["id"].as_i64().unwrap();

        let updated = parse_json(
            json_put(
                &lead_app,
                &format!("/api/folders/{folder_id}"),
                serde_json::json!({ "name": "Documentation" }),
            )
            .await,
        )
        .await;
        assert_eq!(updated["name"], "Documentation");

        let regular_app = app_as_user(db, &regular);
        let response = json_put(
            &regular_app,
            &format!("/api/folders/{folder_id}"),
            serde_json::json!({ "name": "Nope" }),
        )
        .await;
        assert_eq!(response.status(), StatusCode::FORBIDDEN);
    }

    #[tokio::test]
    async fn folder_update_allows_maintainer_and_denies_viewer_and_non_member_when_enforced() {
        let (db, _admin, _lead, maintainer, viewer, non_member, project_id) =
            setup_membership_test();
        let maintainer_app = app_as_user(db.clone(), &maintainer);
        let folder = parse_json(
            json_post(
                &maintainer_app,
                "/api/folders",
                serde_json::json!({ "project_id": project_id, "name": "Docs" }),
            )
            .await,
        )
        .await;
        let folder_id = folder["id"].as_i64().unwrap();

        let response = json_put(
            &maintainer_app,
            &format!("/api/folders/{folder_id}"),
            serde_json::json!({ "name": "Documentation" }),
        )
        .await;
        assert_eq!(response.status(), StatusCode::OK);
        assert_eq!(parse_json(response).await["name"], "Documentation");

        let viewer_app = app_as_user(db.clone(), &viewer);
        let response = json_put(
            &viewer_app,
            &format!("/api/folders/{folder_id}"),
            serde_json::json!({ "name": "Nope" }),
        )
        .await;
        assert_eq!(response.status(), StatusCode::FORBIDDEN);

        let non_member_app = app_as_user(db, &non_member);
        let response = json_put(
            &non_member_app,
            &format!("/api/folders/{folder_id}"),
            serde_json::json!({ "name": "Still nope" }),
        )
        .await;
        assert_eq!(response.status(), StatusCode::FORBIDDEN);
    }

    #[tokio::test]
    async fn regular_cannot_create_folder() {
        let (db, _, _lead, regular, project_id) = setup_lead_test();
        let regular_app = app_as_user(db, &regular);
        let response = json_post(
            &regular_app,
            "/api/folders",
            serde_json::json!({ "project_id": project_id, "name": "Docs" }),
        )
        .await;

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

    #[tokio::test]
    async fn lead_can_merge_labels_and_regular_cannot() {
        let (db, _, lead, regular, project_id) = setup_lead_test();
        let lead_app = app_as_user(db.clone(), &lead);

        let mk = |name: &str| serde_json::json!({ "project_id": project_id, "name": name, "color": "#FF0000" });
        let a = parse_json(json_post(&lead_app, "/api/labels", mk("bug")).await).await;
        let b = parse_json(json_post(&lead_app, "/api/labels", mk("defect")).await).await;
        let a_id = a["id"].as_i64().unwrap();
        let b_id = b["id"].as_i64().unwrap();

        // Regular user cannot merge.
        let reg_app = app_as_user(db, &regular);
        let resp = json_post(
            &reg_app,
            &format!("/api/labels/{a_id}/merge"),
            serde_json::json!({ "into": b_id }),
        )
        .await;
        assert_eq!(resp.status(), StatusCode::FORBIDDEN);

        // Lead merges A into B: response is the survivor, and A is gone.
        let resp = json_post(
            &lead_app,
            &format!("/api/labels/{a_id}/merge"),
            serde_json::json!({ "into": b_id }),
        )
        .await;
        assert_eq!(resp.status(), StatusCode::OK);
        assert_eq!(parse_json(resp).await["id"].as_i64().unwrap(), b_id);

        let list =
            parse_json(json_get(&lead_app, &format!("/api/labels?project_id={project_id}")).await)
                .await;
        let names: Vec<&str> = list
            .as_array()
            .unwrap()
            .iter()
            .map(|l| l["name"].as_str().unwrap())
            .collect();
        assert_eq!(names, vec!["defect"]);
    }
}