eidetica 0.2.0

Decentralized DB. Remember Everything. Everywhere. All At Once.
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
//! Bootstrap sync failure scenario tests.
//!
//! This module tests that the bootstrap sync process properly rejects unauthorized
//! access attempts, invalid keys, and permission boundary violations. These tests
//! expect secure behavior and will fail until proper security is implemented.

use super::helpers::*;
use eidetica::{
    Instance,
    auth::Permission,
    backend::database::InMemory,
    crdt::{Doc, doc::Value},
    instance::LegacyInstanceOps,
};
use std::time::Duration;

/// Test bootstrap behavior when the requesting key lacks sufficient admin permissions.
///
/// This test expects SECURE behavior: Bootstrap should fail with a permission error,
/// and unauthorized clients should not receive database content or be added
/// to the auth configuration.
#[tokio::test]
async fn test_bootstrap_permission_denied_insufficient_admin() {
    println!("\n๐Ÿงช TEST: Bootstrap with insufficient admin permissions (should be rejected)");

    // Setup server with restricted auth policy - only specific admin keys allowed
    let server_instance =
        Instance::open(Box::new(InMemory::new())).expect("Failed to create test instance");
    server_instance
        .enable_sync()
        .expect("Failed to initialize sync on server");

    // Add server admin key
    server_instance
        .add_private_key("server_admin")
        .expect("Failed to add server admin key");

    // Create database with only server_admin having access
    let mut settings = Doc::new();
    settings.set_string("name", "Restricted Database");

    let server_admin_pubkey = server_instance
        .get_formatted_public_key("server_admin")
        .expect("Failed to get server admin public key");

    // Set strict auth policy - only server_admin has permission to manage auth
    let mut auth_doc = Doc::new();
    auth_doc
        .set_json(
            "server_admin",
            serde_json::json!({
                "pubkey": server_admin_pubkey,
                "permissions": {"Admin": 0},  // Highest admin priority
                "status": "Active"
            }),
        )
        .expect("Failed to set server admin auth");

    settings.set_doc("auth", auth_doc);

    // Create the database
    let server_database = server_instance
        .new_database(settings, "server_admin")
        .expect("Failed to create restricted database");

    let restricted_tree_id = server_database.root_id().clone();
    println!(
        "๐Ÿ” Created restricted database with ID: {}",
        restricted_tree_id
    );

    // Start server
    let server_addr = {
        let server_sync = server_instance.sync().expect("Server should have sync");
        start_sync_server(&server_sync).await
    };

    // Setup client with its own key
    let client_instance =
        Instance::open(Box::new(InMemory::new())).expect("Failed to create test instance");
    client_instance
        .enable_sync()
        .expect("Failed to initialize sync on client");

    client_instance
        .add_private_key("unauthorized_client")
        .expect("Failed to add client key");

    let client_pubkey = client_instance
        .get_formatted_public_key("unauthorized_client")
        .expect("Failed to get client public key");

    println!(
        "๐Ÿ‘ค Client attempting bootstrap with unauthorized key: {}",
        client_pubkey
    );

    // Enable client sync
    let bootstrap_result = {
        let client_sync = client_instance.sync().expect("Client should have sync");
        client_sync
            .enable_http_transport()
            .expect("Failed to enable HTTP transport");

        // Attempt bootstrap with key approval request - should be REJECTED by default
        let result = client_sync
            .sync_with_peer_for_bootstrap(
                &server_addr,
                &restricted_tree_id,
                "unauthorized_client", // Client's key name
                Permission::Write(10), // Requested permission level
            )
            .await;

        // Wait for any async processing
        tokio::time::sleep(Duration::from_millis(100)).await;
        result
    };

    println!("๐Ÿ” Bootstrap result: {:?}", bootstrap_result);

    // EXPECTED SECURE BEHAVIOR: Bootstrap should fail for unauthorized client
    assert!(
        bootstrap_result.is_err(),
        "Bootstrap should be REJECTED for unauthorized client - test fails because security is not implemented"
    );

    // EXPECTED SECURE BEHAVIOR: Client should not receive the database
    assert!(
        client_instance.load_database(&restricted_tree_id).is_err(),
        "Client should be DENIED access to restricted database - test fails because security is not implemented"
    );

    // EXPECTED SECURE BEHAVIOR: Server database auth config should NOT be modified
    let server_auth_settings = server_database
        .get_settings()
        .expect("Failed to get server database settings")
        .get_all()
        .expect("Failed to get all settings");

    // Check that auth section was NOT modified to include unauthorized key
    if let Some(auth_node) = server_auth_settings.get("auth")
        && let Value::Doc(auth_doc) = auth_node
    {
        // EXPECTED SECURE BEHAVIOR: Should NOT contain the unauthorized client key
        assert!(
            !auth_doc.as_hashmap().contains_key("unauthorized_client"),
            "Unauthorized client key should NOT be added to server auth config - test fails because security is not implemented"
        );
        println!(
            "๐Ÿ” Server auth keys should remain unchanged: {:?}",
            auth_doc.as_hashmap().keys().collect::<Vec<_>>()
        );
    }

    println!(
        "โœ… TEST: Expected secure behavior (will fail until security is properly implemented)"
    );

    // Cleanup
    let server_sync = server_instance.sync().expect("Server should have sync");
    server_sync.stop_server_async().await.unwrap();
}

/// Test bootstrap behavior when the database has no authentication configuration
/// but the client is requesting key approval.
///
/// This test expects SECURE behavior: Should either fail because there's no auth
/// framework to approve keys against, or succeed only if the database explicitly
/// allows unauthenticated access with proper validation.
#[tokio::test]
async fn test_bootstrap_permission_denied_no_auth_config() {
    println!(
        "\n๐Ÿงช TEST: Bootstrap key approval with no auth config (should have defined behavior)"
    );

    // Setup server with a database that has NO authentication configuration
    let server_instance =
        Instance::open(Box::new(InMemory::new())).expect("Failed to create test instance");
    server_instance
        .enable_sync()
        .expect("Failed to initialize sync on server");

    server_instance
        .add_private_key("server_key")
        .expect("Failed to add server key");

    // Create database with NO auth configuration
    let mut settings = Doc::new();
    settings.set_string("name", "Unprotected Database");
    // Explicitly NOT setting any "auth" configuration

    let server_database = server_instance
        .new_database(settings, "server_key")
        .expect("Failed to create unprotected database");

    let unprotected_tree_id = server_database.root_id().clone();
    println!(
        "๐Ÿ”“ Created database with no auth config, ID: {}",
        unprotected_tree_id
    );

    // Start server
    let server_addr = {
        let server_sync = server_instance.sync().expect("Server should have sync");
        start_sync_server(&server_sync).await
    };

    // Setup client
    let client_instance =
        Instance::open(Box::new(InMemory::new())).expect("Failed to create test instance");
    client_instance
        .enable_sync()
        .expect("Failed to initialize sync on client");

    client_instance
        .add_private_key("client_key")
        .expect("Failed to add client key");

    let _client_pubkey = client_instance
        .get_formatted_public_key("client_key")
        .expect("Failed to get client public key");

    let bootstrap_result = {
        let client_sync = client_instance.sync().expect("Client should have sync");
        client_sync
            .enable_http_transport()
            .expect("Failed to enable HTTP transport");

        // Attempt bootstrap with key approval request on database with no auth config โ€” should be REJECTED
        let result = client_sync
            .sync_with_peer_for_bootstrap(
                &server_addr,
                &unprotected_tree_id,
                "client_key",
                Permission::Write(10),
            )
            .await;

        tokio::time::sleep(Duration::from_millis(100)).await;
        result
    };

    println!("๐Ÿ” Bootstrap result: {:?}", bootstrap_result);

    // EXPECTED SECURE BEHAVIOR: Bootstrap should have well-defined behavior for no-auth databases
    // For now, we expect it to fail until proper policy is defined
    assert!(
        bootstrap_result.is_err(),
        "Bootstrap should FAIL when no auth framework exists to validate against - test fails because security policy is not implemented"
    );

    // EXPECTED SECURE BEHAVIOR: Client should not receive database without proper authorization
    assert!(
        client_instance.load_database(&unprotected_tree_id).is_err(),
        "Client should not receive database without proper authorization framework - test fails because security is not implemented"
    );

    // EXPECTED SECURE BEHAVIOR: Server database should NOT have auth config modified without authorization
    let server_auth_settings = server_database
        .get_settings()
        .expect("Failed to get server database settings")
        .get_all()
        .expect("Failed to get all settings");

    // Check that NO auth section was created by unauthorized bootstrap
    if let Some(auth_node) = server_auth_settings.get("auth")
        && let Value::Doc(auth_doc) = auth_node
    {
        // EXPECTED SECURE BEHAVIOR: Auth config should NOT be created by unauthorized bootstrap
        assert!(
            !auth_doc.as_hashmap().contains_key("client_key"),
            "Auth config should NOT be created by unauthorized bootstrap - test fails because security is not implemented"
        );
        println!(
            "๐Ÿ” Server should not have unauthorized auth modifications: {:?}",
            auth_doc.as_hashmap().keys().collect::<Vec<_>>()
        );
    }
    // If no auth section exists, that's the expected secure behavior

    println!(
        "โœ… TEST: Expected secure behavior for no-auth database (will fail until proper security policy is implemented)"
    );

    // Cleanup
    let server_sync = server_instance.sync().expect("Server should have sync");
    server_sync.stop_server_async().await.unwrap();
}

/// Test bootstrap behavior with malformed public key data.
///
/// This test expects SECURE behavior: Bootstrap should fail with clear error
/// for malformed keys and proper validation should be in place.
#[tokio::test]
async fn test_bootstrap_invalid_public_key_format() {
    println!("\n๐Ÿงช TEST: Bootstrap with malformed public key format");

    // Setup server
    let server_instance =
        Instance::open(Box::new(InMemory::new())).expect("Failed to create test instance");
    server_instance
        .enable_sync()
        .expect("Failed to initialize sync on server");

    server_instance
        .add_private_key("server_key")
        .expect("Failed to add server key");

    // Create database
    let mut settings = Doc::new();
    settings.set_string("name", "Test Database");

    let server_database = server_instance
        .new_database(settings, "server_key")
        .expect("Failed to create database");

    let tree_id = server_database.root_id().clone();

    // Start server
    let server_addr = {
        let server_sync = server_instance.sync().expect("Server should have sync");
        start_sync_server(&server_sync).await
    };

    // Setup client with malformed key name (this tests key validation during bootstrap)
    let client_instance =
        Instance::open(Box::new(InMemory::new())).expect("Failed to create test instance");
    client_instance
        .enable_sync()
        .expect("Failed to initialize sync on client");

    // Note: We can't directly test malformed keys in the current API since
    // add_private_key() creates valid keys. This test documents the need for
    // key format validation during the bootstrap process itself.
    client_instance
        .add_private_key("client_with_spaces_and_symbols!@#")
        .expect("Failed to add client key");

    let client_sync = client_instance.sync().expect("Client should have sync");
    client_sync
        .enable_http_transport()
        .expect("Failed to enable HTTP transport");

    // Attempt bootstrap - current implementation may accept any key name
    let bootstrap_result = client_sync
        .sync_with_peer_for_bootstrap(
            &server_addr,
            &tree_id,
            "client_with_spaces_and_symbols!@#",
            Permission::Write(10),
        )
        .await;

    tokio::time::sleep(Duration::from_millis(100)).await;

    println!(
        "๐Ÿ” Bootstrap result with unusual key name: {:?}",
        bootstrap_result
    );

    // EXPECTED SECURE BEHAVIOR: Should fail with proper validation
    assert!(
        bootstrap_result.is_err(),
        "Bootstrap should FAIL with unusual key name due to proper validation - test fails because validation is not implemented"
    );

    println!("โœ… Expected secure behavior: Bootstrap rejected unusual key name");

    // Cleanup
    let server_sync = server_instance.sync().expect("Server should have sync");
    server_sync.stop_server_async().await.unwrap();
}

/// Test bootstrap behavior with revoked key status.
///
/// This test expects SECURE behavior: Bootstrap should fail for revoked or
/// inactive keys with proper status validation.
#[tokio::test]
async fn test_bootstrap_with_revoked_key() {
    println!("\n๐Ÿงช TEST: Bootstrap attempt with revoked key");

    // Setup server with auth configuration including a revoked key
    let server_instance =
        Instance::open(Box::new(InMemory::new())).expect("Failed to create test instance");
    server_instance
        .enable_sync()
        .expect("Failed to initialize sync on server");

    server_instance
        .add_private_key("server_admin")
        .expect("Failed to add server admin key");

    server_instance
        .add_private_key("revoked_client")
        .expect("Failed to add revoked client key");

    let server_admin_pubkey = server_instance
        .get_formatted_public_key("server_admin")
        .expect("Failed to get server admin public key");

    let revoked_client_pubkey = server_instance
        .get_formatted_public_key("revoked_client")
        .expect("Failed to get revoked client public key");

    // Create database with auth configuration including the revoked key
    let mut settings = Doc::new();
    settings.set_string("name", "Database With Revoked Key");

    let mut auth_doc = Doc::new();
    auth_doc
        .set_json(
            "server_admin",
            serde_json::json!({
                "pubkey": server_admin_pubkey,
                "permissions": {"Admin": 0},
                "status": "Active"
            }),
        )
        .expect("Failed to set server admin auth");

    auth_doc
        .set_json(
            "revoked_client",
            serde_json::json!({
                "pubkey": revoked_client_pubkey,
                "permissions": {"Write": 10},
                "status": "Revoked"  // Key is explicitly revoked
            }),
        )
        .expect("Failed to set revoked client auth");

    settings.set_doc("auth", auth_doc);

    let server_database = server_instance
        .new_database(settings, "server_admin")
        .expect("Failed to create database");

    let tree_id = server_database.root_id().clone();

    // Start server
    let server_addr = {
        let server_sync = server_instance.sync().expect("Server should have sync");
        start_sync_server(&server_sync).await
    };

    // Setup different client instance (to simulate external client using revoked key)
    let client_instance =
        Instance::open(Box::new(InMemory::new())).expect("Failed to create test instance");
    client_instance
        .enable_sync()
        .expect("Failed to initialize sync on client");

    // Note: In a real scenario, the client would have the private key corresponding
    // to the revoked public key. For testing, we create a key with the same name.
    client_instance
        .add_private_key("attempting_revoked_access")
        .expect("Failed to add client key");

    let client_sync = client_instance.sync().expect("Client should have sync");
    client_sync
        .enable_http_transport()
        .expect("Failed to enable HTTP transport");

    // Attempt bootstrap with a different key (since we can't use the actual revoked key easily)
    let bootstrap_result = client_sync
        .sync_with_peer_for_bootstrap(
            &server_addr,
            &tree_id,
            "attempting_revoked_access",
            Permission::Write(10),
        )
        .await;

    tokio::time::sleep(Duration::from_millis(100)).await;

    println!(
        "๐Ÿ” Bootstrap result with new key on database containing revoked keys: {:?}",
        bootstrap_result
    );

    // EXPECTED SECURE BEHAVIOR: Bootstrap should fail for any attempt with revoked key context
    assert!(
        bootstrap_result.is_err(),
        "Bootstrap should FAIL when database contains revoked keys and proper validation exists - test fails because key status validation is not implemented"
    );

    println!(
        "โœ… TEST: Expected secure behavior for revoked key scenario (will fail until key status validation is implemented)"
    );

    // Cleanup
    let server_sync = server_instance.sync().expect("Server should have sync");
    server_sync.stop_server_async().await.unwrap();
}

/// Test bootstrap behavior when requesting permissions that exceed granted levels.
///
/// This test expects SECURE behavior: Bootstrap should either reject excessive
/// permission requests or grant only appropriate permission levels based on policy.
#[tokio::test]
async fn test_bootstrap_exceeds_granted_permissions() {
    println!("\n๐Ÿงช TEST: Bootstrap requesting excessive permissions");

    // Setup server with policy allowing only Read permissions for new clients
    let server_instance =
        Instance::open(Box::new(InMemory::new())).expect("Failed to create test instance");
    server_instance
        .enable_sync()
        .expect("Failed to initialize sync on server");

    server_instance
        .add_private_key("server_admin")
        .expect("Failed to add server admin key");

    let server_admin_pubkey = server_instance
        .get_formatted_public_key("server_admin")
        .expect("Failed to get server admin public key");

    // Create database with restrictive auth policy
    let mut settings = Doc::new();
    settings.set_string("name", "Restrictive Permission Database");

    let mut auth_doc = Doc::new();
    auth_doc
        .set_json(
            "server_admin",
            serde_json::json!({
                "pubkey": server_admin_pubkey,
                "permissions": {"Admin": 0},
                "status": "Active"
            }),
        )
        .expect("Failed to set server admin auth");

    // TODO: Add policy configuration that limits new client permissions to Read only
    settings.set_doc("auth", auth_doc);

    let server_database = server_instance
        .new_database(settings, "server_admin")
        .expect("Failed to create database");

    let tree_id = server_database.root_id().clone();

    // Start server
    let server_addr = {
        let server_sync = server_instance.sync().expect("Server should have sync");
        start_sync_server(&server_sync).await
    };

    // Setup client requesting Admin permissions (should be excessive)
    let client_instance =
        Instance::open(Box::new(InMemory::new())).expect("Failed to create test instance");
    client_instance
        .enable_sync()
        .expect("Failed to initialize sync on client");

    client_instance
        .add_private_key("greedy_client")
        .expect("Failed to add client key");

    let client_sync = client_instance.sync().expect("Client should have sync");
    client_sync
        .enable_http_transport()
        .expect("Failed to enable HTTP transport");

    // Attempt bootstrap requesting Admin permissions (excessive for a new client)
    let bootstrap_result = client_sync
        .sync_with_peer_for_bootstrap(
            &server_addr,
            &tree_id,
            "greedy_client",
            Permission::Admin(0), // Requesting highest admin level
        )
        .await;

    tokio::time::sleep(Duration::from_millis(100)).await;

    println!(
        "๐Ÿ” Bootstrap result requesting excessive Admin permissions: {:?}",
        bootstrap_result
    );

    // EXPECTED SECURE BEHAVIOR: Bootstrap should fail or limit excessive permission requests
    assert!(
        bootstrap_result.is_err(),
        "Bootstrap should FAIL when requesting excessive Admin permissions - test fails because permission validation is not implemented"
    );

    // EXPECTED SECURE BEHAVIOR: No permissions should be granted for failed bootstrap
    let server_auth_settings = server_database
        .get_settings()
        .expect("Failed to get server database settings")
        .get_all()
        .expect("Failed to get all settings");

    if let Some(auth_node) = server_auth_settings.get("auth")
        && let Value::Doc(auth_doc) = auth_node
    {
        // EXPECTED SECURE BEHAVIOR: Greedy client should NOT be in auth config
        assert!(
            !auth_doc.as_hashmap().contains_key("greedy_client"),
            "Greedy client should NOT be granted any permissions for excessive request - test fails because permission validation is not implemented"
        );
    }
    println!(
        "โœ… TEST: Expected secure behavior for excessive permission requests (will fail until permission validation is implemented)"
    );

    // Cleanup
    let server_sync = server_instance.sync().expect("Server should have sync");
    server_sync.stop_server_async().await.unwrap();
}