1#[allow(
23 unused_imports,
24 clippy::wildcard_imports,
25 reason = "Standard workspace module prelude"
26)]
27use crate::utilities::*;
28use ctb_storage::global_graph_layout::get_block_name_for_id;
29use ctb_storage::node::{Node, NodeType};
30
31use std::io::Read;
32use std::str::FromStr;
33
34use axum::body::Bytes;
35use axum::extract::{Query, State};
36use axum::response::Response;
37use axum_typed_multipart::{TryFromMultipart, TypedMultipart};
38use serde::Deserialize;
39
40use crate::flexible_form::FlexibleForm;
41
42use crate::controllers::base::redirect_temporary;
43use crate::extractors::pagination::PageQuery;
44use crate::get_user_and_graph;
45use crate::{
46 AppState, AuthenticatedUser, RequestState, error_400, error_403,
47 respond_page,
48};
49
50pub async fn get_nodes_index(
51 State(state): State<AppState>,
52 req: RequestState,
53 sess: AuthenticatedUser,
54 _q: Query<PageQuery>,
55) -> Response {
56 let token = {
57 let u = sess.user.lock().await;
58 u.session_token().map(String::from)
59 };
60 let Some(token) = token else {
61 return error_400(&state, &req, "No active session token");
62 };
63 let nodes: Vec<Node> = match Node::list_nodes(&token) {
64 Ok(nodes) => nodes,
65 Err(e) => {
66 return error_400(
67 &state,
68 &req,
69 format!("Failed to list nodes: {e}"),
70 );
71 }
72 };
73
74 let nodes_list: Vec<_> = nodes
75 .into_iter()
76 .map(|node| {
77 let preview = ctb_formats_dcstring::dctext::format_blob_preview(
78 &node.data,
79 node.node_type == NodeType::Statements
80 || node.node_type == NodeType::System,
81 );
82
83 json_value!({
84 "id" => node.id,
85 "graph_id" => node.graph_id,
86 "node_type" => node.node_type.as_str(),
87 "data_len" => node.data.len(),
88 "preview" => preview,
89 })
90 })
91 .collect();
92
93 respond_page(
94 &state,
95 req,
96 "nodes.index",
97 &json_value!({
98 "nodes" => nodes_list,
99 }),
100 )
101}
102
103#[derive(serde::Deserialize)]
104pub struct NodeViewQuery {
105 #[serde(alias = "node_id")]
106 pub id: Option<String>,
107 #[serde(alias = "graph_id")]
108 pub graph: Option<String>,
109}
110
111pub async fn get_nodes_view(
112 State(state): State<AppState>,
113 req: RequestState,
114 sess: AuthenticatedUser,
115 Query(q): Query<NodeViewQuery>,
116) -> Response {
117 let Some(ref id_str) = q.id else {
118 return error_400(&state, &req, "Missing node ID");
119 };
120 let node_id = match string::to_u128(id_str) {
121 Ok(val) => val,
122 Err(e) => {
123 return error_400(&state, &req, format!("Invalid node ID: {e}"));
124 }
125 };
126
127 let token = {
128 let u = sess.user.lock().await;
129 u.session_token().map(String::from)
130 };
131 let Some(token) = token else {
132 return error_400(&state, &req, "No active session token");
133 };
134
135 let graph_id = if let Some(ref g_str) = q.graph {
136 match string::to_u128(g_str) {
137 Ok(val) => val,
138 Err(e) => {
139 return error_400(
140 &state,
141 &req,
142 format!("Invalid graph ID: {e}"),
143 );
144 }
145 }
146 } else {
147 let list = Node::list_nodes(&token).unwrap_or_default();
149 if let Some(n) = list.into_iter().find(|n| n.id == node_id) {
150 n.graph_id
151 } else {
152 return error_400(&state, &req, "Node not found");
153 }
154 };
155
156 let node = match Node::get(&token, graph_id, node_id) {
157 Ok(Some(n)) => n,
158 Ok(None) => return error_400(&state, &req, "Node not found"),
159 Err(e) => {
160 return error_400(
161 &state,
162 &req,
163 format!("Failed to fetch node: {e}"),
164 );
165 }
166 };
167
168 let is_admin = sess.user.lock().await.is_admin();
169
170 let is_data = node.node_type == NodeType::Data;
171 let is_statements = node.node_type == NodeType::Statements
172 || node.node_type == NodeType::System;
173
174 let display_content = if is_statements {
175 let dctext_bytes =
176 ctb_formats_dcstring::dctext::dctf_to_dctext(node.data.clone());
177 String::from_utf8_lossy(&dctext_bytes).into_owned()
178 } else {
179 String::from_utf8_lossy(&node.data).into_owned()
180 };
181
182 let hex_dump = if is_data {
183 ctb_formats_hexdump::to_fancy_hex_dump(&node.data)
184 } else {
185 String::new()
186 };
187
188 respond_page(
189 &state,
190 req,
191 "nodes.view",
192 &json_value!({
193 "node" => json_value!({
194 "id" => node.id,
195 "graph_id" => node.graph_id,
196 "node_type" => node.node_type.as_str(),
197 "data_len" => node.data.len(),
198 "is_data" => is_data,
199 "display_content" => display_content,
200 "hex_dump" => hex_dump,
201 "checksum" => node.checksum.as_ref().map(bin2hex),
202 }),
203 "is_admin" => is_admin,
204 }),
205 )
206}
207
208pub async fn get_nodes_create(
209 State(state): State<AppState>,
210 req: RequestState,
211 _user: AuthenticatedUser,
212) -> Response {
213 respond_page(&state, req, "nodes.create", &json_value!({}))
214}
215
216#[derive(TryFromMultipart, Deserialize)]
217#[try_from_multipart(strict)]
218pub struct CreateNodeForm {
219 #[form_data(default)]
220 graph: Option<String>,
221 node_type: String,
222 node_content: String,
223}
224
225pub async fn post_nodes_create(
226 State(state): State<AppState>,
227 req: RequestState,
228 sess: AuthenticatedUser,
229 FlexibleForm(input): FlexibleForm<CreateNodeForm>,
230) -> Response {
231 let graph_id = if let Some(ref g_str) = input.graph {
232 match string::to_u128(g_str) {
233 Ok(val) => val,
234 Err(e) => {
235 return error_400(
236 &state,
237 &req,
238 format!("Invalid graph ID: {e}"),
239 );
240 }
241 }
242 } else {
243 1
244 };
245 get_user_and_graph!(&state, &req, sess, graph_id, user, graph);
246
247 let node_type = match NodeType::from_str(&input.node_type) {
248 Ok(t) => t,
249 Err(e) => {
250 return error_400(&state, &req, format!("Invalid node type: {e}"));
251 }
252 };
253
254 if let Err(e) = graph.create_node(
255 &user,
256 node_type,
257 strtovec(input.node_content.as_str()).as_slice(),
258 ) {
259 return error_400(&state, &req, e);
260 }
261
262 redirect_temporary(req.is_js_request, "/nodes")
263}
264
265pub async fn get_nodes_upload(
266 State(state): State<AppState>,
267 req: RequestState,
268 _user: AuthenticatedUser,
269) -> Response {
270 respond_page(&state, req, "nodes.upload", &json_value!({}))
271}
272
273#[derive(TryFromMultipart)]
274#[try_from_multipart(strict)]
275pub struct UploadNodeForm {
276 #[form_data(default)]
277 graph: Option<String>,
278 node_type: String,
279 #[form_data(limit = "unlimited")]
280 node_content: Bytes,
281}
282
283struct ReadableBytes {
285 inner: Bytes,
286}
287
288impl Read for ReadableBytes {
290 fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
291 let len = std::cmp::min(buf.len(), self.inner.len());
292 if let (Some(dest), Some(src)) =
293 (buf.get_mut(..len), self.inner.get(..len))
294 {
295 dest.copy_from_slice(src);
296 }
297 self.inner = self.inner.slice(len..);
298 Ok(len)
299 }
300}
301
302impl ReadableBytes {
303 fn new(bytes: Bytes) -> Self {
304 Self { inner: bytes }
305 }
306}
307
308pub async fn post_nodes_upload(
309 State(state): State<AppState>,
310 req: RequestState,
311 sess: AuthenticatedUser,
312 TypedMultipart(form): TypedMultipart<UploadNodeForm>,
313) -> Response {
314 let graph_id = if let Some(ref g_str) = form.graph {
315 match string::to_u128(g_str) {
316 Ok(val) => val,
317 Err(e) => {
318 return error_400(
319 &state,
320 &req,
321 format!("Invalid graph ID: {e}"),
322 );
323 }
324 }
325 } else {
326 1
327 };
328 get_user_and_graph!(&state, &req, sess, graph_id, user, graph);
329 let readable_bytes = ReadableBytes::new(form.node_content);
330
331 let node_type = match NodeType::from_str(&form.node_type) {
332 Ok(t) => t,
333 Err(e) => {
334 return error_400(&state, &req, format!("Invalid node type: {e}"));
335 }
336 };
337
338 if let Err(e) = graph.create_node(&user, node_type, readable_bytes) {
339 return error_400(&state, &req, e);
340 }
341
342 redirect_temporary(req.is_js_request, "/nodes")
343}
344
345#[derive(serde::Deserialize)]
346pub struct PublishNodeRequest {
347 pub target_id: Option<u128>,
348}
349
350#[derive(serde::Deserialize)]
351pub struct PublishQuery {
352 pub target_id: Option<String>,
353}
354
355#[derive(serde::Deserialize)]
356pub struct PublishPageQuery {
357 pub target_id: Option<String>,
358}
359
360#[derive(TryFromMultipart, serde::Deserialize)]
361#[try_from_multipart(strict)]
362pub struct PublishForm {
363 pub target_id: Option<String>,
364}
365
366pub async fn get_nodes_publish(
367 State(state): State<AppState>,
368 req: RequestState,
369 sess: AuthenticatedUser,
370 axum::extract::Path((graph_id, node_id)): axum::extract::Path<(u128, u128)>,
371 axum::extract::Query(q): axum::extract::Query<PublishPageQuery>,
372) -> Response {
373 let is_admin = sess.user.lock().await.is_admin();
374 if !is_admin {
375 return error_403(
376 &state,
377 &req,
378 "Admin privileges are required to publish nodes.",
379 );
380 }
381
382 let _token = {
383 let u = sess.user.lock().await;
384 u.session_token().map(String::from)
385 };
386 let Some(_token) = _token else {
387 return error_400(&state, &req, "No active session token");
388 };
389
390 let mut err_msg = None;
392 let target_id = if let Some(ref t) = q.target_id {
393 let trimmed = t.trim();
394 if trimmed.is_empty() {
395 None
396 } else if let Ok(val) = trimmed.parse::<u128>() {
397 Some(val)
398 } else {
399 err_msg = Some("Invalid target ID".to_string());
400 None
401 }
402 } else {
403 None
404 };
405
406 let mut block_name = String::new();
407 if let Some(tid) = target_id {
408 let unicode_block =
410 ctb_storage::global_graph_layout::get_block("Unicode");
411 if let Some(ref block) = unicode_block {
412 if block.contains_id(tid) {
413 err_msg = Some(
414 "Publishing nodes to the Unicode range is disallowed."
415 .to_string(),
416 );
417 }
418 }
419
420 if err_msg.is_none() {
421 block_name = match get_block_name_for_id(tid) {
422 Ok(name) => {
423 if name == "Unicode" {
424 err_msg = Some("Publishing nodes to the Unicode range is disallowed.".to_string());
425 }
426 name
427 }
428 Err(e) => {
429 err_msg = Some(format!("Invalid ID: {e}"));
430 String::new()
431 }
432 };
433 }
434 }
435
436 respond_page(
437 &state,
438 req,
439 "nodes.publish",
440 &json_value!({
441 "node_id" => node_id.to_string(),
442 "graph_id" => graph_id.to_string(),
443 "target_id" => target_id.map(|t| t.to_string()),
444 "block_name" => block_name,
445 "error" => err_msg,
446 }),
447 )
448}
449
450pub async fn get_nodes_publish_as(
451 State(state): State<AppState>,
452 req: RequestState,
453 sess: AuthenticatedUser,
454 axum::extract::Path((graph_id, node_id)): axum::extract::Path<(u128, u128)>,
455) -> Response {
456 let is_admin = sess.user.lock().await.is_admin();
457 if !is_admin {
458 return error_403(
459 &state,
460 &req,
461 "Admin privileges are required to publish nodes.",
462 );
463 }
464
465 respond_page(
466 &state,
467 req,
468 "nodes.publish_as",
469 &json_value!({
470 "node_id" => node_id.to_string(),
471 "graph_id" => graph_id.to_string(),
472 }),
473 )
474}
475
476pub async fn post_nodes_publish(
477 State(state): State<AppState>,
478 req: RequestState,
479 sess: AuthenticatedUser,
480 axum::extract::Path((graph_id, node_id)): axum::extract::Path<(u128, u128)>,
481 FlexibleForm(form): FlexibleForm<PublishForm>,
482) -> Response {
483 let is_admin = sess.user.lock().await.is_admin();
484 if !is_admin {
485 return error_403(
486 &state,
487 &req,
488 "Admin privileges are required to publish nodes.",
489 );
490 }
491
492 let token = {
493 let u = sess.user.lock().await;
494 u.session_token().map(String::from)
495 };
496 let Some(token) = token else {
497 return error_400(&state, &req, "No active session token");
498 };
499
500 let target_id = if let Some(ref t) = form.target_id {
501 let trimmed = t.trim();
502 if trimmed.is_empty() {
503 None
504 } else {
505 match trimmed.parse::<u128>() {
506 Ok(val) => Some(val),
507 Err(_) => return error_400(&state, &req, "Invalid target ID"),
508 }
509 }
510 } else {
511 None
512 };
513
514 let mut local_node = match Node::get(&token, graph_id, node_id) {
515 Ok(Some(n)) => n,
516 Ok(None) => return error_400(&state, &req, "Local node not found"),
517 Err(e) => {
518 return error_400(
519 &state,
520 &req,
521 format!("Failed to fetch local node: {e}"),
522 );
523 }
524 };
525
526 let global_token = {
527 let guard = state.global_session_token.lock().await;
528 guard.clone()
529 };
530
531 if let Err(e) = local_node
532 .publish(&token, global_token.as_deref(), target_id)
533 .await
534 {
535 return error_400(&state, &req, e.to_string());
536 }
537
538 let view_url = format!("/nodes/view?id={node_id}&graph={graph_id}");
540 crate::controllers::base::redirect_temporary(req.is_js_request, &view_url)
541}
542
543pub async fn post_publish_node(
544 State(state): State<AppState>,
545 req: RequestState,
546 sess: AuthenticatedUser,
547 axum::extract::Path((_graph_id, _node_id)): axum::extract::Path<(
548 u128,
549 u128,
550 )>,
551 axum::extract::Query(query): axum::extract::Query<PublishQuery>,
552 body_bytes: Bytes,
553) -> Response {
554 if ctb_utilities::environment::is_public_website() {
555 let token = {
557 let u = sess.user.lock().await;
558 u.session_token().map(String::from)
559 };
560 let Some(token) = token else {
561 return error_400(&state, &req, "No active session token");
562 };
563
564 let target_id = if let Some(ref tid_str) = query.target_id {
565 match string::to_u128(tid_str) {
566 Ok(val) => Some(val),
567 Err(e) => {
568 return error_400(
569 &state,
570 &req,
571 format!("Invalid target ID: {e}"),
572 );
573 }
574 }
575 } else {
576 None
577 };
578
579 match ctb_storage::get_global_graph().import_node(
580 &token,
581 &body_bytes,
582 target_id,
583 ) {
584 Ok(allocated_id) => {
585 let response_body = json_value!({
586 "success" => true,
587 "allocated_id" => allocated_id.to_string(),
588 });
589 axum::response::IntoResponse::into_response(axum::Json(
590 response_body,
591 ))
592 }
593 Err(e) => error_400(
594 &state,
595 &req,
596 format!("Failed to publish packaged node: {e}"),
597 ),
598 }
599 } else {
600 error_400(&state, &req, "Client publish API is disabled.")
601 }
602}
603
604pub async fn get_node_checksum(
605 State(state): State<AppState>,
606 req: RequestState,
607 sess: AuthenticatedUser,
608 axum::extract::Path((graph_id, node_id)): axum::extract::Path<(u128, u128)>,
609) -> Response {
610 let token = {
611 let u = sess.user.lock().await;
612 u.session_token().map(String::from)
613 };
614 let Some(token) = token else {
615 return error_400(&state, &req, "No active session token");
616 };
617
618 if graph_id != 0 {
619 let user = sess.user.lock().await;
621 if user.get_graph_by_id(graph_id).is_none() {
622 return error_400(&state, &req, "Graph not found");
623 }
624 }
625
626 match Node::get(&token, graph_id, node_id) {
627 Ok(Some(node)) => {
628 let response = json_value!({
629 "checksum" => node.checksum.as_ref().map(bin2hex),
630 });
631 axum::response::IntoResponse::into_response(axum::Json(response))
632 }
633 Ok(None) => error_400(&state, &req, "Node not found"),
634 Err(e) => error_400(&state, &req, format!("Failed to fetch node: {e}")),
635 }
636}
637
638#[derive(serde::Deserialize)]
639pub struct NodeDownloadQuery {
640 #[serde(alias = "node_id")]
641 pub id: Option<String>,
642 #[serde(alias = "graph_id")]
643 pub graph: Option<String>,
644 pub format: Option<String>,
645}
646
647pub async fn get_nodes_download(
648 State(state): State<AppState>,
649 req: RequestState,
650 sess: AuthenticatedUser,
651 Query(q): Query<NodeDownloadQuery>,
652) -> Response {
653 let Some(ref id_str) = q.id else {
654 return error_400(&state, &req, "Missing node ID");
655 };
656 let node_id = match string::to_u128(id_str) {
657 Ok(val) => val,
658 Err(e) => {
659 return error_400(&state, &req, format!("Invalid node ID: {e}"));
660 }
661 };
662
663 let token = {
664 let u = sess.user.lock().await;
665 u.session_token().map(String::from)
666 };
667 let Some(token) = token else {
668 return error_400(&state, &req, "No active session token");
669 };
670
671 let graph_id = if let Some(ref g_str) = q.graph {
672 match string::to_u128(g_str) {
673 Ok(val) => val,
674 Err(e) => {
675 return error_400(
676 &state,
677 &req,
678 format!("Invalid graph ID: {e}"),
679 );
680 }
681 }
682 } else {
683 let list = Node::list_nodes(&token).unwrap_or_default();
685 if let Some(n) = list.into_iter().find(|n| n.id == node_id) {
686 n.graph_id
687 } else {
688 return error_400(&state, &req, "Node not found");
689 }
690 };
691
692 download_node_response(
693 &state,
694 &req,
695 &token,
696 graph_id,
697 node_id,
698 q.format.as_deref(),
699 )
700 .await
701}
702
703pub async fn get_nodes_download_path(
704 State(state): State<AppState>,
705 req: RequestState,
706 sess: AuthenticatedUser,
707 axum::extract::Path((graph_id, node_id)): axum::extract::Path<(u128, u128)>,
708 Query(q): Query<NodeDownloadQuery>,
709) -> Response {
710 let token = {
711 let u = sess.user.lock().await;
712 u.session_token().map(String::from)
713 };
714 let Some(token) = token else {
715 return error_400(&state, &req, "No active session token");
716 };
717
718 download_node_response(
719 &state,
720 &req,
721 &token,
722 graph_id,
723 node_id,
724 q.format.as_deref(),
725 )
726 .await
727}
728
729async fn download_node_response(
730 state: &AppState,
731 req: &RequestState,
732 token: &str,
733 graph_id: u128,
734 node_id: u128,
735 format: Option<&str>,
736) -> Response {
737 let node = match Node::get(token, graph_id, node_id) {
738 Ok(Some(n)) => n,
739 Ok(None) => return error_400(state, req, "Node not found"),
740 Err(e) => {
741 return error_400(state, req, format!("Failed to fetch node: {e}"));
742 }
743 };
744
745 let (bytes, filename) = match format {
746 Some("packaged" | "ctbn") => {
747 let pkg_bytes = match node.to_packaged_node() {
748 Ok(b) => b,
749 Err(e) => {
750 return error_400(
751 state,
752 req,
753 format!("Failed to serialize packaged node: {e}"),
754 );
755 }
756 };
757 (pkg_bytes, format!("node_{node_id}.ctbn"))
758 }
759 _ => (node.data, format!("node_{node_id}.bin")),
760 };
761
762 let mut headers = axum::http::HeaderMap::new();
763 headers.insert(
764 axum::http::header::CONTENT_TYPE,
765 axum::http::HeaderValue::from_static("application/octet-stream"),
766 );
767 if let Ok(disposition) = axum::http::HeaderValue::from_str(&format!(
768 "attachment; filename=\"{filename}\""
769 )) {
770 headers.insert(axum::http::header::CONTENT_DISPOSITION, disposition);
771 }
772 if let Ok(len_val) =
773 axum::http::HeaderValue::from_str(&bytes.len().to_string())
774 {
775 headers.insert(axum::http::header::CONTENT_LENGTH, len_val);
776 }
777
778 use axum::response::IntoResponse;
779 (headers, bytes).into_response()
780}
781
782#[cfg(test)]
783#[allow(
784 clippy::panic,
785 clippy::expect_used,
786 clippy::unwrap_used,
787 clippy::unwrap_in_result,
788 clippy::panic_in_result_fn,
789 clippy::indexing_slicing,
790 clippy::arithmetic_side_effects,
791 reason = "Standard repository test boilerplate"
792)]
793mod tests {
794 use crate::test_helpers::{TestApp, assert_eq_or_print_body, test_request};
795 use crate::utilities::*;
796 use axum::http::Method;
797 use ctb_storage::node::{Node, NodeType};
798
799 #[crate::ctb_test("tokio")]
800 async fn test_graph_endpoints() {
801 let test_app = TestApp::new();
802 let (cookie_val, _lock) =
803 test_app.register_and_login("graph_user").await.unwrap();
804
805 let (status, body) = test_request::<()>(
807 &test_app.app,
808 Method::GET,
809 "/nodes",
810 None,
811 Some(&cookie_val),
812 None,
813 None,
814 None,
815 )
816 .await;
817 assert_eq_or_print_body(status, 200, &body);
818 assert!(body.contains("No nodes found"));
819
820 let (status, body) = test_request::<()>(
822 &test_app.app,
823 Method::GET,
824 "/nodes/view",
825 None,
826 Some(&cookie_val),
827 None,
828 None,
829 None,
830 )
831 .await;
832 assert_eq_or_print_body(status, 400, &body);
833
834 let (status, body) = test_request::<()>(
836 &test_app.app,
837 Method::GET,
838 "/nodes/create",
839 None,
840 Some(&cookie_val),
841 None,
842 None,
843 None,
844 )
845 .await;
846 assert_eq_or_print_body(status, 200, &body);
847
848 #[derive(serde::Serialize)]
850 struct CreateForm {
851 graph: Option<u32>,
852 node_type: String,
853 node_content: String,
854 }
855 let form = CreateForm {
856 graph: Some(1),
857 node_type: "data".to_string(),
858 node_content: "hello world".to_string(),
859 };
860 let (status, body) = test_request(
861 &test_app.app,
862 Method::POST,
863 "/nodes/create",
864 None,
865 Some(&cookie_val),
866 None,
867 Some(&form),
868 None,
869 )
870 .await;
871 assert_eq_or_print_body(status, 303, &body); let (status, body) = test_request::<()>(
875 &test_app.app,
876 Method::GET,
877 "/nodes/upload",
878 None,
879 Some(&cookie_val),
880 None,
881 None,
882 None,
883 )
884 .await;
885 assert_eq_or_print_body(status, 200, &body);
886
887 #[derive(serde::Serialize)]
889 struct UploadForm {
890 graph: Option<u32>,
891 node_type: String,
892 node_content: Vec<u8>,
893 }
894 let upload_form = UploadForm {
895 graph: Some(1),
896 node_type: "data".to_string(),
897 node_content: b"uploaded content data".to_vec(),
898 };
899 let (status, body) = test_request(
900 &test_app.app,
901 Method::POST,
902 "/nodes/upload",
903 None,
904 Some(&cookie_val),
905 None,
906 None,
907 Some(&upload_form),
908 )
909 .await;
910 assert_eq_or_print_body(status, 303, &body); let token = cookie_val
914 .split(';')
915 .next()
916 .unwrap()
917 .strip_prefix("session=")
918 .unwrap()
919 .to_string();
920
921 let node1_opt: Option<Vec<u8>> =
922 Node::get(&token, 1, 1).unwrap().map(|n| n.data);
923 let node1 =
924 node1_opt.expect("Node 1 was not persisted to the database");
925 assert_eq!(node1, b"hello world".to_vec());
926
927 let node2_opt: Option<Vec<u8>> =
928 Node::get(&token, 1, 2).unwrap().map(|n| n.data);
929 let node2 =
930 node2_opt.expect("Node 2 was not persisted to the database");
931 assert_eq!(node2, b"uploaded content data".to_vec());
932
933 let (status, body) = test_request::<()>(
935 &test_app.app,
936 Method::GET,
937 "/nodes",
938 None,
939 Some(&cookie_val),
940 None,
941 None,
942 None,
943 )
944 .await;
945 assert_eq_or_print_body(status, 200, &body);
946 assert!(body.contains("hello world"));
947 assert!(body.contains("uploaded content data"));
948
949 let (status, body) = test_request::<()>(
951 &test_app.app,
952 Method::GET,
953 "/nodes/view?id=1",
954 None,
955 Some(&cookie_val),
956 None,
957 None,
958 None,
959 )
960 .await;
961 assert_eq_or_print_body(status, 200, &body);
962 assert!(body.contains("Node ID:"));
963 assert!(body.contains("68 65 6c 6c 6f 20 77 6f 72 6c 64")); let (status, body) = test_request::<()>(
967 &test_app.app,
968 Method::GET,
969 "/nodes/view?id=999",
970 None,
971 Some(&cookie_val),
972 None,
973 None,
974 None,
975 )
976 .await;
977 assert_eq_or_print_body(status, 400, &body);
978
979 let (status, body) = test_request::<()>(
981 &test_app.app,
982 Method::GET,
983 "/nodes/1/1/download?format=packaged",
984 None,
985 Some(&cookie_val),
986 None,
987 None,
988 None,
989 )
990 .await;
991 assert_eq_or_print_body(status, 200, &body);
992 assert!(body.starts_with("CTBNODE\0"));
993
994 let (status, body) = test_request::<()>(
996 &test_app.app,
997 Method::GET,
998 "/nodes/1/1/download?format=raw",
999 None,
1000 Some(&cookie_val),
1001 None,
1002 None,
1003 None,
1004 )
1005 .await;
1006 assert_eq_or_print_body(status, 200, &body);
1007 assert_eq!(body, "hello world");
1008 }
1009
1010 #[crate::ctb_test("tokio")]
1011 async fn test_publish_and_redirect_flow() {
1012 let test_app = TestApp::new();
1013 let (cookie_val, _lock) =
1014 test_app.register_and_login("admin_user").await.unwrap();
1015 let user_id = ipcb!(storage)
1016 .get_user_by_name_b("admin_user")
1017 .unwrap()
1018 .expect("User not found")
1019 .id;
1020
1021 {
1023 let mut settings =
1024 pc_settings::PcSettings::load().unwrap_or_default();
1025 settings.admin_users =
1026 ctb_utilities::json::maybe_value::MaybeOption::Value(vec![
1027 user_id,
1028 ]);
1029 settings.save().unwrap();
1030 }
1031
1032 let token_str = cookie_val
1033 .split('=')
1034 .nth(1)
1035 .unwrap()
1036 .split(';')
1037 .next()
1038 .unwrap()
1039 .to_string();
1040
1041 let local_node_id = Node::new(
1042 &token_str,
1043 1,
1044 NodeType::Data,
1045 b"hello world publish test",
1046 )
1047 .unwrap();
1048
1049 let _ = ctb_storage::user::User::create(
1051 "global",
1052 &ctb_utilities::password::Password {
1053 password: b"secure_global_pass".to_vec(),
1054 },
1055 );
1056 let target_id = 8589934595u128;
1057
1058 let (status, body) = test_request::<()>(
1060 &test_app.app,
1061 Method::GET,
1062 &format!("/nodes/1/{local_node_id}/publish?target_id={target_id}"),
1063 None,
1064 Some(&cookie_val),
1065 None,
1066 None,
1067 None,
1068 )
1069 .await;
1070 assert_eq_or_print_body(status, 200, &body);
1071 assert!(
1072 body.contains("Confirm Publishing"),
1073 "Expected 'Confirm Publishing' in body, got: {body}"
1074 );
1075 assert!(
1076 body.contains("System"),
1077 "Expected block name 'System' in body, got: {body}"
1078 );
1079
1080 let (status, body) = test_request::<()>(
1082 &test_app.app,
1083 Method::GET,
1084 &format!("/nodes/1/{local_node_id}/publish?target_id=1000"),
1085 None,
1086 Some(&cookie_val),
1087 None,
1088 None,
1089 None,
1090 )
1091 .await;
1092 assert_eq_or_print_body(status, 200, &body);
1093 assert!(
1094 body.contains(
1095 "Publishing nodes to the Unicode range is disallowed."
1096 )
1097 );
1098
1099 let mut headers = axum::http::HeaderMap::new();
1100 headers.insert(
1101 axum::http::header::CONTENT_TYPE,
1102 axum::http::HeaderValue::from_static(
1103 "application/x-www-form-urlencoded",
1104 ),
1105 );
1106
1107 let local_node =
1109 Node::get(&token_str, 1, local_node_id).unwrap().unwrap();
1110 let local_checksum = bin2hex(local_node.checksum.unwrap());
1111
1112 let (status, body) = test_request(
1114 &test_app.app,
1115 Method::POST,
1116 &format!("/nodes/1/{local_node_id}/publish"),
1117 Some(headers),
1118 Some(&cookie_val),
1119 Some(format!("target_id={target_id}").into_bytes()),
1120 None::<&()>,
1121 None::<&()>,
1122 )
1123 .await;
1124 assert!(
1125 status == 303 || status == 302 || status == 307,
1126 "Expected redirect status, got {status} and body: {body}"
1127 );
1128
1129 let updated_node =
1131 Node::get(&token_str, 1, local_node_id).unwrap().unwrap();
1132 assert_eq!(updated_node.node_type, NodeType::System);
1133
1134 let dctext_bytes =
1135 ctb_formats_dcstring::dctext::dctf_to_dctext(updated_node.data);
1136 let redirect_dctext = String::from_utf8(dctext_bytes).unwrap();
1137 assert_eq!(redirect_dctext, format!("@1114409@@{target_id}@"));
1138
1139 assert_eq!(bin2hex(updated_node.checksum.unwrap()), local_checksum);
1140
1141 let (view_status, view_body) = test_request::<()>(
1143 &test_app.app,
1144 Method::GET,
1145 &format!("/nodes/view?graph_id=1&node_id={local_node_id}"),
1146 None,
1147 Some(&cookie_val),
1148 None,
1149 None,
1150 None,
1151 )
1152 .await;
1153 assert_eq_or_print_body(view_status, 200, &view_body);
1154 assert!(view_body.contains(&target_id.to_string()));
1155 }
1156}