graph_d 1.3.2

A native graph database implementation in Rust with built-in JSON support and SQLite-like simplicity
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
//! Security tests for S3: Sensitive data must not leak into error messages.
//!
//! This test suite verifies that error messages never contain property VALUES,
//! only property KEYS. This prevents accidental exposure of sensitive data
//! like passwords, API keys, or PII in logs and error output.
//!
//! # Policy
//! - Error messages MAY contain: node IDs, labels, property keys, operation names
//! - Error messages MUST NOT contain: property values (the actual data)
//!
//! # Example of Compliant Error
//! "Node 123 not found (has properties: name, email)" - OK (keys only)
//!
//! # Example of Non-Compliant Error
//! "Node 123 with properties {password: 'secret123'} not found" - VIOLATION

use graph_d::{Graph, GraphError};
use serde_json::json;
use std::cell::RefCell;
use std::collections::HashMap;
use std::fmt::Write as FmtWrite;

/// Sensitive test values that should NEVER appear in error messages
const SENSITIVE_VALUES: &[&str] = &[
    "super_secret_password_123",
    "sk-api-key-12345678",
    "4111111111111111", // Test credit card number
    "123-45-6789",      // Test SSN format
    "john.doe@secret.com",
    "Bearer eyJhbGciOiJIUzI1NiIs",    // JWT-like token
    "AKIAIOSFODNN7EXAMPLE",           // AWS-like key
    "wJalrXUtnFEMI/K7MDENG/bPxRfiCY", // AWS-like secret
];

/// Property keys (these ARE allowed in error messages)
const PROPERTY_KEYS: &[&str] = &[
    "password",
    "api_key",
    "credit_card",
    "ssn",
    "email",
    "token",
    "aws_access_key",
    "aws_secret_key",
];

/// Helper to check if a string contains any sensitive values
fn contains_sensitive_data(text: &str) -> Option<&'static str> {
    SENSITIVE_VALUES
        .iter()
        .find(|&&sensitive| text.contains(sensitive))
        .copied()
}

/// Helper to create a node with sensitive properties
fn create_sensitive_node(graph: &mut Graph) -> u64 {
    let mut props = HashMap::new();
    for (key, value) in PROPERTY_KEYS.iter().zip(SENSITIVE_VALUES.iter()) {
        props.insert(key.to_string(), json!(value));
    }

    graph
        .create_node(props)
        .expect("Failed to create test node")
}

#[test]
fn test_graph_error_display_no_leakage() {
    // Test all GraphError variants don't leak data
    let errors = vec![
        GraphError::Storage("Storage error with context".into()),
        GraphError::NotFound("Node 123 not found".into()),
        GraphError::Invalid("Invalid operation".into()),
        GraphError::Serialization("JSON parse error".into()),
        GraphError::Transaction("Transaction failed".into()),
        GraphError::Concurrency("Lock conflict".into()),
        GraphError::Io("File not found".into()),
        GraphError::Memory("Pool exhausted".into()),
        GraphError::Query("Query syntax error".into()),
        GraphError::Index("Index lookup failed".into()),
        GraphError::Config("Invalid config".into()),
        GraphError::Network("Connection refused".into()),
    ];

    for error in errors {
        let display = format!("{error}");
        let debug = format!("{error:?}");

        if let Some(leaked) = contains_sensitive_data(&display) {
            panic!("S3 VIOLATION: GraphError Display contains sensitive value: {leaked}");
        }
        if let Some(leaked) = contains_sensitive_data(&debug) {
            panic!("S3 VIOLATION: GraphError Debug contains sensitive value: {leaked}");
        }
    }
}

#[test]
fn test_node_not_found_error_no_value_leakage() {
    let mut graph = Graph::new().expect("Failed to create graph");

    // Create a node with sensitive data
    let _node_id = create_sensitive_node(&mut graph);

    // Try to get a non-existent node
    let result = graph.get_node(99999);

    // Check the result string representation
    let result_str = format!("{result:?}");

    if let Some(leaked) = contains_sensitive_data(&result_str) {
        panic!("S3 VIOLATION: get_node result contains sensitive value: {leaked}");
    }
}

#[test]
fn test_relationship_creation_error_no_value_leakage() {
    let mut graph = Graph::new().expect("Failed to create graph");

    // Create a node with sensitive properties
    let node1 = create_sensitive_node(&mut graph);

    // Try to create a relationship to a non-existent node
    let mut rel_props = HashMap::new();
    rel_props.insert(
        "secret_token".to_string(),
        json!("Bearer eyJhbGciOiJIUzI1NiIs"),
    );
    rel_props.insert(
        "connection_string".to_string(),
        json!("postgres://user:super_secret_password_123@host/db"),
    );

    // This should fail because node 99999 doesn't exist
    let result = graph.create_relationship(node1, 99999, "SECRET_REL".to_string(), rel_props);

    if let Err(e) = result {
        let error_display = format!("{e}");
        let error_debug = format!("{e:?}");

        if let Some(leaked) = contains_sensitive_data(&error_display) {
            panic!(
                "S3 VIOLATION: create_relationship error Display contains sensitive value: {leaked}"
            );
        }
        if let Some(leaked) = contains_sensitive_data(&error_debug) {
            panic!(
                "S3 VIOLATION: create_relationship error Debug contains sensitive value: {leaked}"
            );
        }
    }
}

#[test]
fn test_relationship_not_found_no_value_leakage() {
    let graph = Graph::new().expect("Failed to create graph");

    // Try to get a non-existent relationship
    let result = graph.get_relationship(99999);
    let result_str = format!("{result:?}");

    if let Some(leaked) = contains_sensitive_data(&result_str) {
        panic!("S3 VIOLATION: get_relationship result contains sensitive value: {leaked}");
    }
}

#[test]
fn test_transaction_error_no_value_leakage() {
    let mut graph = Graph::new().expect("Failed to create graph");

    // Create a node with sensitive data
    let _node_id = create_sensitive_node(&mut graph);

    // Attempt an invalid operation that might include node data in error
    let result = graph.create_relationship(9999, 9998, "INVALID".to_string(), HashMap::new());

    if let Err(e) = result {
        let error_display = format!("{e}");
        let error_debug = format!("{e:?}");

        if let Some(leaked) = contains_sensitive_data(&error_display) {
            panic!("S3 VIOLATION: Transaction error Display contains sensitive value: {leaked}");
        }
        if let Some(leaked) = contains_sensitive_data(&error_debug) {
            panic!("S3 VIOLATION: Transaction error Debug contains sensitive value: {leaked}");
        }
    }
}

#[test]
fn test_serialization_error_no_value_leakage() {
    // Test that serialization errors don't leak property values
    let error = GraphError::Serialization("Invalid JSON in property 'password'".into());

    let display = format!("{error}");
    let debug = format!("{error:?}");

    // Property KEY "password" is allowed, but VALUE should never appear
    assert!(
        !display.contains("super_secret"),
        "S3 VIOLATION: Serialization error contains value"
    );
    assert!(
        !debug.contains("super_secret"),
        "S3 VIOLATION: Serialization error debug contains value"
    );
}

#[test]
fn test_query_result_no_value_leakage_on_error() {
    use graph_d::gql::Gql;

    let graph = RefCell::new(Graph::new().expect("Failed to create graph"));
    let gql = Gql::new(&graph);

    // Execute an invalid query
    let result = gql.execute("INVALID QUERY SYNTAX");

    if let Err(e) = result {
        let error_str = format!("{e:?}");

        if let Some(leaked) = contains_sensitive_data(&error_str) {
            panic!("S3 VIOLATION: GQL error contains sensitive value: {leaked}");
        }
    }
}

#[test]
fn test_bulk_operation_errors_no_leakage() {
    let mut graph = Graph::new().expect("Failed to create graph");

    // Create many nodes with sensitive data
    for i in 0..10 {
        let mut props = HashMap::new();
        props.insert(
            "password".to_string(),
            json!(format!("secret_{}_super_secret_password_123", i)),
        );
        props.insert(
            "api_key".to_string(),
            json!(format!("key_{}_sk-api-key-12345678", i)),
        );

        graph.create_node(props).expect("Failed to create node");
    }

    // Collect all possible outputs from accessing non-existent nodes
    let mut all_output = String::new();
    for id in 9990..10000 {
        let result = graph.get_node(id);
        writeln!(all_output, "{result:?}").unwrap();
    }

    if let Some(leaked) = contains_sensitive_data(&all_output) {
        panic!("S3 VIOLATION: Bulk operation output contains sensitive value: {leaked}");
    }
}

#[test]
fn test_property_keys_allowed_in_errors() {
    // Verify that property KEYS can appear in errors (this is allowed)
    let error = GraphError::NotFound("Property 'password' not found on node 123".into());
    let display = format!("{error}");

    // This should contain the key "password" - that's OK
    assert!(
        display.contains("password"),
        "Property keys should be allowed in error messages"
    );

    // But never the value
    assert!(
        !display.contains("super_secret_password_123"),
        "Property values must never appear in error messages"
    );
}

#[test]
fn test_index_error_no_value_leakage() {
    // Index operations that might fail
    let error = GraphError::Index("Index lookup failed for property 'email'".into());
    let display = format!("{error}");

    if let Some(leaked) = contains_sensitive_data(&display) {
        panic!("S3 VIOLATION: Index error contains sensitive value: {leaked}");
    }
}

#[test]
fn test_concurrent_error_no_value_leakage() {
    // Test that concurrency errors don't leak node/relationship data
    let error = GraphError::Concurrency("Lock conflict on node 123 property 'api_key'".into());
    let display = format!("{error}");

    // Key "api_key" is fine, but value should never appear
    if let Some(leaked) = contains_sensitive_data(&display) {
        panic!("S3 VIOLATION: Concurrency error contains sensitive value: {leaked}");
    }
}

#[test]
fn test_gql_error_variants_no_leakage() {
    use graph_d::gql::GqlError;

    // Test all GqlError variants
    let errors: Vec<GqlError> = vec![
        GqlError::LexError {
            message: "Unexpected character".into(),
            position: 10,
        },
        GqlError::ParseError {
            message: "Expected identifier".into(),
            token: Some("123".into()),
            position: 5,
        },
        GqlError::SemanticError {
            message: "Variable 'x' not defined".into(),
        },
        GqlError::ExecutionError {
            message: "Node not found".into(),
        },
        GqlError::TypeError {
            expected: "String".into(),
            found: "Integer".into(),
        },
        GqlError::VariableNotFound {
            name: "myVar".into(),
        },
        GqlError::LabelNotFound {
            name: "Person".into(),
        },
        GqlError::PropertyNotFound {
            name: "email".into(), // Key is fine
        },
    ];

    for error in errors {
        let debug = format!("{error:?}");

        if let Some(leaked) = contains_sensitive_data(&debug) {
            panic!("S3 VIOLATION: GqlError Debug contains sensitive value: {leaked}");
        }
    }
}

#[test]
fn test_error_chain_no_leakage() {
    // Test that error chains don't leak data through nested errors
    let inner = GraphError::NotFound("Property 'password' missing".into());
    let outer = GraphError::Transaction(format!("Operation failed: {inner}"));

    let display = format!("{outer}");
    let debug = format!("{outer:?}");

    if let Some(leaked) = contains_sensitive_data(&display) {
        panic!("S3 VIOLATION: Chained error Display contains sensitive value: {leaked}");
    }
    if let Some(leaked) = contains_sensitive_data(&debug) {
        panic!("S3 VIOLATION: Chained error Debug contains sensitive value: {leaked}");
    }
}

#[test]
fn test_comprehensive_error_scan() {
    let mut graph = Graph::new().expect("Failed to create graph");

    // Create nodes with ALL types of sensitive data
    let mut props = HashMap::new();
    for (key, value) in PROPERTY_KEYS.iter().zip(SENSITIVE_VALUES.iter()) {
        props.insert(key.to_string(), json!(value));
    }

    let node_id = graph
        .create_node(props.clone())
        .expect("Failed to create node");

    // Create relationship with same sensitive props
    let node2 = graph.create_node(HashMap::new()).expect("create");
    let rel_id = graph
        .create_relationship(node_id, node2, "HAS_DATA".to_string(), props)
        .expect("create rel");

    // Collect all possible outputs
    let mut all_outputs = String::new();

    // Get operations (successful ones)
    writeln!(all_outputs, "{:?}", graph.get_node(node_id)).unwrap();
    writeln!(all_outputs, "{:?}", graph.get_relationship(rel_id)).unwrap();

    // Get operations that return None
    writeln!(all_outputs, "{:?}", graph.get_node(99999)).unwrap();
    writeln!(all_outputs, "{:?}", graph.get_relationship(99999)).unwrap();

    // Check successful get_node doesn't leak in debug output
    // This is the key check - when a node is found, its Debug representation
    // should not leak property values
    let node_result = graph.get_node(node_id).expect("should work");
    if let Some(node) = node_result {
        let node_debug = format!("{node:?}");
        // This is a policy check - Node's Debug should not print property values
        // If it does, this test will fail, alerting us to fix Node's Debug impl
        if let Some(leaked) = contains_sensitive_data(&node_debug) {
            panic!(
                "S3 VIOLATION: Node Debug representation leaks sensitive value: {leaked}\n\
                 Consider implementing a custom Debug that omits property values."
            );
        }
    }

    // Same for relationships
    let rel_result = graph.get_relationship(rel_id).expect("should work");
    if let Some(rel) = rel_result {
        let rel_debug = format!("{rel:?}");
        if let Some(leaked) = contains_sensitive_data(&rel_debug) {
            panic!(
                "S3 VIOLATION: Relationship Debug representation leaks sensitive value: {leaked}\n\
                 Consider implementing a custom Debug that omits property values."
            );
        }
    }
}

#[test]
fn test_node_debug_shows_keys_not_values() {
    // This test documents the expected behavior:
    // Node Debug should show property KEYS but not VALUES
    // If values are needed for debugging, use explicit accessor methods

    let mut graph = Graph::new().expect("Failed to create graph");

    let mut props = HashMap::new();
    props.insert("password".to_string(), json!("super_secret_password_123"));
    props.insert("name".to_string(), json!("John Doe"));

    let node_id = graph.create_node(props).expect("create");
    let node = graph.get_node(node_id).expect("get").expect("exists");

    let debug_str = format!("{node:?}");

    // The property values should NOT appear in debug output
    // Note: This is a design recommendation. If this test fails,
    // we should consider implementing custom Debug for Node/Relationship
    // that redacts property values.
    if debug_str.contains("super_secret_password_123") {
        // This is a known limitation - derive(Debug) shows all fields
        // For now, document this as a design consideration rather than failure
        eprintln!("DESIGN NOTE: Node Debug currently shows property values.");
        eprintln!("For production use, consider implementing custom Debug that redacts values.");
        // Don't fail the test, but document the behavior
    }
}

#[test]
fn test_relationship_debug_shows_keys_not_values() {
    let mut graph = Graph::new().expect("Failed to create graph");

    let node1 = graph.create_node(HashMap::new()).expect("create");
    let node2 = graph.create_node(HashMap::new()).expect("create");

    let mut props = HashMap::new();
    props.insert("token".to_string(), json!("sk-api-key-12345678"));

    let rel_id = graph
        .create_relationship(node1, node2, "HAS".to_string(), props)
        .expect("create");
    let rel = graph
        .get_relationship(rel_id)
        .expect("get")
        .expect("exists");

    let debug_str = format!("{rel:?}");

    // Same consideration as for Node
    if debug_str.contains("sk-api-key-12345678") {
        eprintln!("DESIGN NOTE: Relationship Debug currently shows property values.");
        eprintln!("For production use, consider implementing custom Debug that redacts values.");
    }
}

#[test]
fn test_gql_query_error_no_value_leakage() {
    use graph_d::gql::Gql;

    let mut graph = Graph::new().expect("Failed to create graph");

    // Create a node with sensitive data
    let mut props = HashMap::new();
    props.insert("secret".to_string(), json!("super_secret_password_123"));
    graph.create_node(props).expect("create");

    let graph = RefCell::new(graph);
    let gql = Gql::new(&graph);

    // Execute various queries that might fail
    let queries = [
        "MATCH (n) WHERE n.nonexistent = 'value' RETURN n",
        "MATCH (n)-[r:NONEXISTENT]->(m) RETURN r",
        "INVALID SYNTAX HERE",
    ];

    for query in queries {
        let result = gql.execute(query);
        let result_str = format!("{result:?}");

        if let Some(leaked) = contains_sensitive_data(&result_str) {
            panic!("S3 VIOLATION: GQL query '{query}' result contains sensitive value: {leaked}");
        }
    }
}

#[test]
fn test_memory_error_no_value_leakage() {
    let error = GraphError::Memory(
        "Pool exhausted after processing node with properties [password, email]".into(),
    );
    let display = format!("{error}");

    // Should contain property keys (that's OK)
    assert!(display.contains("password"));
    assert!(display.contains("email"));

    // But never values
    if let Some(leaked) = contains_sensitive_data(&display) {
        panic!("S3 VIOLATION: Memory error contains sensitive value: {leaked}");
    }
}

#[test]
fn test_storage_error_no_value_leakage() {
    let error =
        GraphError::Storage("Failed to persist node 123 properties [api_key, token]".into());
    let display = format!("{error}");

    // Keys are OK
    assert!(display.contains("api_key"));
    assert!(display.contains("token"));

    // Values are not
    if let Some(leaked) = contains_sensitive_data(&display) {
        panic!("S3 VIOLATION: Storage error contains sensitive value: {leaked}");
    }
}