ctb_io_webui/controllers/
debug.rs

1// SPDX-License-Identifier: AGPL-3.0-or-later
2/*
3This file is part of Collective Toolbox, a database and document workspace and utilities.
4Copyright (C) 2026 Collective Toolbox Developers
5Contact: info@collectivetoolbox.com
6
7This program is free software: you can redistribute it and/or modify it under
8the terms of the GNU Affero General Public License as published by the Free
9Software Foundation, either version 3 of the License, or (at your option) any
10later version.
11
12This program is distributed in the hope that it will be useful, but WITHOUT ANY
13WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
14A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more details.
15
16You should have received a copy of the GNU Affero General Public License along
17with this program.  If not, see <https://www.gnu.org/licenses/>.
18*/
19
20//! Controller for viewing database tables and raw data.
21#[allow(
22    unused_imports,
23    clippy::wildcard_imports,
24    reason = "Standard workspace module prelude"
25)]
26use crate::utilities::*;
27
28use axum::{
29    extract::{Path, Query, State},
30    response::Response,
31};
32use serde::{Deserialize, Serialize};
33
34use crate::session_auth::AuthenticatedUser;
35use crate::{AppState, RequestState, error_400, respond_page};
36
37#[derive(Deserialize)]
38pub struct DbQuery {
39    pub db_name: Option<String>,
40    pub page: Option<u32>,
41}
42
43#[derive(Serialize)]
44pub struct DatabaseItem {
45    pub name: String,
46    pub is_active: bool,
47}
48
49/// GET /debug/db-tables
50pub async fn get_db_tables(
51    State(state): State<AppState>,
52    req: RequestState,
53    user: AuthenticatedUser,
54    Query(query): Query<DbQuery>,
55) -> Response {
56    // Reason for fallback: query param db_name absent defaults to "users" database
57    let db_name = query.db_name.clone().unwrap_or_else(|| "users".to_string());
58    let token = {
59        let u = user.user.lock().await;
60        u.session_token().map(String::from)
61    };
62    let Some(token) = token else {
63        return error_400(&state, &req, "No active session token");
64    };
65
66    let databases = match ipc!(storage).list_databases(&token).await {
67        Ok(d) => d,
68        Err(e) => {
69            return error_400(
70                &state,
71                &req,
72                format!("Failed to list databases: {e}"),
73            );
74        }
75    };
76
77    let database_items: Vec<DatabaseItem> = databases
78        .into_iter()
79        .map(|name| {
80            let is_active = name == db_name;
81            DatabaseItem { name, is_active }
82        })
83        .collect();
84
85    let tables = match ipc!(storage).list_tables(&token, &db_name).await {
86        Ok(t) => t,
87        Err(e) => {
88            return error_400(
89                &state,
90                &req,
91                format!("Failed to list tables: {e}"),
92            );
93        }
94    };
95
96    respond_page(
97        &state,
98        req,
99        "admin.db-tables",
100        &json_value!({
101            "databases" => database_items,
102            "current_db" => db_name,
103            "tables" => tables,
104        }),
105    )
106}
107
108/// GET /debug/db-tables/{table_name}
109pub async fn get_db_table_data(
110    State(state): State<AppState>,
111    req: RequestState,
112    user: AuthenticatedUser,
113    Path(table_name): Path<String>,
114    Query(query): Query<DbQuery>,
115) -> Response {
116    // Reason for fallback: query param db_name absent defaults to "users" database
117    let db_name = query.db_name.clone().unwrap_or_else(|| "users".to_string());
118    // Reason for fallback: query param page absent defaults to page 1
119    let page = query.page.unwrap_or(1);
120
121    let token = {
122        let u = user.user.lock().await;
123        u.session_token().map(String::from)
124    };
125    let Some(token) = token else {
126        return error_400(&state, &req, "No active session token");
127    };
128
129    let data = match ipc!(storage)
130        .get_formatted_table_data(&token, &db_name, &table_name, page)
131        .await
132    {
133        Ok(d) => d,
134        Err(e) => {
135            return error_400(
136                &state,
137                &req,
138                format!("Failed to get table data: {e}"),
139            );
140        }
141    };
142
143    let id_col_idx = data.columns.iter().position(|c| c == "id");
144    let graph_id_col_idx = data.columns.iter().position(|c| c == "graph_id");
145
146    let formatted_values: Vec<Vec<serde_json::Value>> = data
147        .values
148        .iter()
149        .map(|row| {
150            row.iter()
151                .enumerate()
152                .map(|(i, val)| {
153                    let mut link_url = None;
154                    if table_name == "nodes" {
155                        if Some(i) == id_col_idx {
156                            if let Some(g_idx) = graph_id_col_idx {
157                                if let Some(graph_id) = row.get(g_idx) {
158                                    link_url = Some(format!(
159                                        "/nodes/view?id={val}&graph={graph_id}"
160                                    ));
161                                }
162                            }
163                        }
164                    }
165                    serde_json::json!({
166                        "value": val,
167                        "link_url": link_url,
168                    })
169                })
170                .collect()
171        })
172        .collect();
173
174    respond_page(
175        &state,
176        req,
177        "admin.db-table-data",
178        &json_value!({
179            "table_name" => table_name,
180            "current_db" => db_name,
181            "columns" => data.columns,
182            "values" => formatted_values,
183            "page" => data.page,
184            "total_pages" => data.total_pages,
185            "total_rows" => data.total_rows,
186            "has_prev" => data.page > 1,
187            "prev_page" => data.page.saturating_sub(1),
188            "has_next" => data.page < data.total_pages,
189            "next_page" => data.page.saturating_add(1),
190        }),
191    )
192}
193
194#[cfg(test)]
195#[allow(
196    clippy::panic,
197    clippy::expect_used,
198    clippy::unwrap_used,
199    clippy::unwrap_in_result,
200    clippy::panic_in_result_fn,
201    clippy::indexing_slicing,
202    clippy::arithmetic_side_effects,
203    reason = "Standard repository test boilerplate"
204)]
205mod tests {
206    use crate::test_helpers::{
207        TestApp, assert_eq_or_print_body, assert_or_print_body, test_request,
208    };
209    use axum::http::Method;
210
211    #[crate::ctb_test("tokio")]
212    async fn test_db_tables_endpoints() {
213        let test_app = TestApp::new();
214        let (cookie_val, _lock) =
215            test_app.register_and_login("admin_user").await.unwrap();
216
217        // Test listing tables
218        let (status, body) = test_request::<()>(
219            &test_app.app,
220            Method::GET,
221            "/debug/db-tables?db_name=users",
222            None,
223            Some(&cookie_val),
224            None,
225            None,
226            None,
227        )
228        .await;
229        assert_eq_or_print_body(status, 200, &body);
230        assert_or_print_body(body.contains("Database Tables"), &body);
231        assert_or_print_body(body.contains("users"), &body);
232
233        // Test getting table data (using sqlite_master which always exists)
234        let (status_data, body_data) = test_request::<()>(
235            &test_app.app,
236            Method::GET,
237            "/debug/db-tables/sqlite_master?db_name=users",
238            None,
239            Some(&cookie_val),
240            None,
241            None,
242            None,
243        )
244        .await;
245        assert_eq_or_print_body(status_data, 200, &body_data);
246        assert_or_print_body(body_data.contains("Table:"), &body_data);
247        assert_or_print_body(body_data.contains("sqlite_master"), &body_data);
248
249        // Ensure that columns from sqlite_master are correctly queried and displayed
250        assert_or_print_body(body_data.contains("type"), &body_data);
251        assert_or_print_body(body_data.contains("name"), &body_data);
252        assert_or_print_body(body_data.contains("tbl_name"), &body_data);
253        assert_or_print_body(body_data.contains("rootpage"), &body_data);
254        assert_or_print_body(body_data.contains("sql"), &body_data);
255        // Ensure we don't have asterisk columns
256        assert_or_print_body(
257            !body_data.contains("<th class=\"py-2 px-4\"><code>*</code></th>"),
258            &body_data,
259        );
260
261        // Test getting table data for schema_migrations
262        let (status_migrations, body_migrations) = test_request::<()>(
263            &test_app.app,
264            Method::GET,
265            "/debug/db-tables/schema_migrations?db_name=users",
266            None,
267            Some(&cookie_val),
268            None,
269            None,
270            None,
271        )
272        .await;
273        assert_eq_or_print_body(status_migrations, 200, &body_migrations);
274        assert_or_print_body(
275            body_migrations.contains("Table:"),
276            &body_migrations,
277        );
278        assert_or_print_body(
279            body_migrations.contains("schema_migrations"),
280            &body_migrations,
281        );
282        assert_or_print_body(
283            body_migrations.contains("name"),
284            &body_migrations,
285        );
286        assert_or_print_body(
287            body_migrations.contains("applied_at"),
288            &body_migrations,
289        );
290        assert_or_print_body(
291            !body_migrations
292                .contains("<th class=\"py-2 px-4\"><code>*</code></th>"),
293            &body_migrations,
294        );
295
296        // Create a test node first
297        let mut headers = axum::http::HeaderMap::new();
298        headers.insert(
299            axum::http::header::CONTENT_TYPE,
300            axum::http::HeaderValue::from_static(
301                "application/x-www-form-urlencoded",
302            ),
303        );
304        let mut form = std::collections::HashMap::new();
305        form.insert("graph", "1");
306        form.insert("node_type", "data");
307        form.insert("node_content", "hello world");
308
309        let (status_create, body_create) = test_request(
310            &test_app.app,
311            Method::POST,
312            "/nodes/create",
313            Some(headers.clone()),
314            Some(&cookie_val),
315            None,
316            Some(&form),
317            None,
318        )
319        .await;
320        assert_eq_or_print_body(status_create, 303, &body_create);
321
322        // Parse user database name from the databases list in body
323        let user_db_name = if let Some(idx) = body.find("graphs/") {
324            let rest = body.get(idx..).unwrap_or("");
325            if let Some(end_idx) = rest.find("/user_data") {
326                rest.get(..end_idx.saturating_add("/user_data".len()))
327                    .unwrap_or("")
328                    .to_string()
329            } else {
330                "graphs/1/user_data".to_string()
331            }
332        } else {
333            "graphs/1/user_data".to_string()
334        };
335
336        // Query the nodes table
337        let (status_nodes, body_nodes) = test_request::<()>(
338            &test_app.app,
339            Method::GET,
340            &format!("/debug/db-tables/nodes?db_name={user_db_name}"),
341            None,
342            Some(&cookie_val),
343            None,
344            None,
345            None,
346        )
347        .await;
348        assert_eq_or_print_body(status_nodes, 200, &body_nodes);
349        assert_or_print_body(
350            body_nodes.contains("sticky-table-container"),
351            &body_nodes,
352        );
353        assert_or_print_body(body_nodes.contains("Table:"), &body_nodes);
354        assert_or_print_body(body_nodes.contains("nodes"), &body_nodes);
355        // Verify decimal IDs are used (not raw hex blobs) and they are linked
356        assert_or_print_body(
357            body_nodes.contains("/nodes/view?id&#x3D;1&amp;graph&#x3D;1"),
358            &body_nodes,
359        );
360        // Verify the data column text preview is correctly formatted
361        assert_or_print_body(body_nodes.contains("hello world"), &body_nodes);
362        // Verify checksum displays as 64-character hex without 0x prefix and not binary data stub
363        assert_or_print_body(
364            !body_nodes.contains("&lt;binary data: 32 bytes&gt;"),
365            &body_nodes,
366        );
367        let has_checksum_hex = body_nodes
368            .chars()
369            .collect::<Vec<_>>()
370            .windows(64)
371            .any(|window| window.iter().all(char::is_ascii_hexdigit));
372        assert_or_print_body(has_checksum_hex, &body_nodes);
373    }
374}