Repository navigation
Expand file tree
/
Copy pathdiff.rs
More file actions
1339 lines (1215 loc) · 46.8 KB
/
Copy pathdiff.rs
File metadata and controls
1339 lines (1215 loc) · 46.8 KB
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
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! Turns "this is what the tree looks like now" into "this is what to do".
//!
//! The rest of the app only knows `workspaces_save` and sends the whole tree
//! every time. For a file that is right; for a backend someone else is also
//! working on, it would be an overwrite. So this compares what comes in with
//! what was last known — and turns that into the individual calls.
//!
//! This module has a say in two things, and both have to do with data loss:
//!
//! - **An empty secret is not a secret.** Whoever opens a locked workspace and
//! changes something about a name would otherwise have replaced every
//! ciphertext on the server with an empty string. See
//! [`model::secret_of`] versus [`model::has_secret_source`].
//! - **Encryption happens when enqueuing, not when sending.** There is never
//! plaintext in the queue — it is stored on disk.
use std::collections::HashSet;
use base64::engine::general_purpose::STANDARD as BASE64;
use base64::Engine;
use rust_i18n::t;
use super::account::Unlocked;
use super::cache::{Cached, Grant, Pending};
use super::crypto;
use super::model::{
self, ApiConnection, ApiProject, ApiProjectKey, ApiSecret, ApiSnippet, ApiVaultAccount,
};
use crate::storage::{Connection, ConnectionSettings, Project, Workspace};
use crate::vault::VaultProvider;
/// Compares and enters the result into the copy right away.
///
/// So the copy is treated as if everything were already up — otherwise the
/// next load would show the old state again while the queue is still working.
/// What the server makes of it comes back with the next sync and then has the
/// last word.
pub fn plan(
cached: &mut Cached,
incoming: &Workspace,
user_id: &str,
unlocked: Option<&Unlocked>,
) -> Result<Vec<Pending>, String> {
let mut ops = Vec::new();
if cached.name != incoming.name {
cached.name = incoming.name.clone();
ops.push(Pending::RenameWorkspace {
name: incoming.name.clone(),
});
}
vault_accounts(cached, incoming, &mut ops);
let private = unlocked.map(|open| &*open.private);
let (current, _) = cached.tree(private);
// After the projects: a new snippet needs its project and connection on
// the server, and a deleted one should go only after the connections that
// started with it have let go of it — otherwise the server takes it out
// of them first, and their change would meet a newer revision.
//
// A startup command the server would not take yet — its snippet is new,
// or becomes locked or this connection's only in this same go — waits for
// a second pass after the snippets.
let later = startups_for_later(cached, ¤t, incoming);
projects(
cached,
¤t,
later.as_ref().unwrap_or(incoming),
user_id,
private,
&mut ops,
)?;
snippets(cached, incoming, &mut ops);
if later.is_some() {
let (current, _) = cached.tree(private);
projects(cached, ¤t, incoming, user_id, private, &mut ops)?;
}
Ok(ops)
}
/// The tree with the startup commands the server would refuse right now put
/// back to what they were — `None` if there are none. The server only takes
/// a locked snippet of the connection's project that is for all of its
/// connections or for this one; what the copy knows is what it has (or will
/// have, from the queue).
fn startups_for_later(
cached: &Cached,
current: &[Project],
incoming: &Workspace,
) -> Option<Workspace> {
let startup = |connection: &Connection| match &connection.settings {
ConnectionSettings::Ssh(ssh) => ssh.startup_snippet.clone(),
_ => None,
};
let before = |id: &str| {
current
.iter()
.flat_map(|project| project.connections.iter())
.find(|connection| connection.id == id)
.and_then(startup)
};
let fits = |project_id: &str, connection_id: &str, snippet_id: &str| {
cached.snippets.iter().any(|row| {
row.id == snippet_id
&& row.deleted_at.is_none()
&& row.locked
&& match &row.connection_id {
Some(id) => id == connection_id,
None => row.project_id == project_id,
}
})
};
let mut later = incoming.clone();
let mut any = false;
for project in &mut later.projects {
for connection in &mut project.connections {
let was = before(&connection.id);
if let ConnectionSettings::Ssh(ssh) = &mut connection.settings {
if let Some(id) = &ssh.startup_snippet {
if was.as_deref() != Some(id.as_str()) && !fits(&project.id, &connection.id, id)
{
ssh.startup_snippet = was;
any = true;
}
}
}
}
}
any.then_some(later)
}
// ---- Snippets ----------------------------------------------------------------
/// The order in the tree is the position. A snippet that is no longer in it is
/// deleted.
///
/// The project is not compared: a snippet does not change projects on its
/// own, only along with its connection — and that the server does itself.
fn snippets(cached: &mut Cached, incoming: &Workspace, ops: &mut Vec<Pending>) {
let wanted: HashSet<&str> = incoming.snippets.iter().map(|s| s.id.as_str()).collect();
let gone: Vec<String> = cached
.snippets
.iter()
.filter(|row| !wanted.contains(row.id.as_str()))
.map(|row| row.id.clone())
.collect();
for id in gone {
cached.snippets.retain(|row| row.id != id);
ops.push(Pending::DeleteSnippet { id });
}
for (position, snippet) in incoming.snippets.iter().enumerate() {
let row = ApiSnippet {
id: snippet.id.clone(),
project_id: snippet.project_id.clone(),
connection_id: snippet.connection_id.clone(),
locked: snippet.locked,
name: snippet.name.clone(),
folder: snippet.folder.clone(),
command: snippet.command.clone(),
position: position as i64,
revision: String::new(),
deleted_at: None,
};
let existing = cached.snippets.iter().position(|r| r.id == snippet.id);
match existing {
None => {
cached.snippets.push(row.clone());
ops.push(Pending::CreateSnippet { snippet: row });
}
Some(at) => {
let known = &cached.snippets[at];
let changed = known.name != row.name
|| known.connection_id != row.connection_id
|| known.locked != row.locked
|| known.folder != row.folder
|| known.command != row.command
|| known.position != row.position;
if !changed {
continue;
}
let expected_revision = expected(cached, &row.id, &known.revision);
let revision = known.revision.clone();
cached.snippets[at] = ApiSnippet {
revision,
project_id: known.project_id.clone(),
..row.clone()
};
ops.push(Pending::UpdateSnippet {
snippet: row,
expected_revision,
});
}
}
}
}
// ---- Vault accounts ----------------------------------------------------------
fn vault_accounts(cached: &mut Cached, incoming: &Workspace, ops: &mut Vec<Pending>) {
let one_password = incoming.one_password_account.trim().to_string();
if cached.one_password_account() != one_password {
set_vault_account(
cached,
ops,
VaultProvider::OnePassword,
&one_password,
"",
false,
);
}
let bitwarden = incoming
.bitwarden
.clone()
.filter(|account| !account.is_empty());
let current = cached.bitwarden_account();
let same = match (¤t, &bitwarden) {
(Some(a), Some(b)) => {
a.email == b.email
&& a.server == b.server
&& a.accept_invalid_cert == b.accept_invalid_cert
}
(None, None) => true,
_ => false,
};
if !same {
let account = bitwarden.unwrap_or_default();
set_vault_account(
cached,
ops,
VaultProvider::Bitwarden,
&account.email,
&account.server,
account.accept_invalid_cert,
);
}
}
fn set_vault_account(
cached: &mut Cached,
ops: &mut Vec<Pending>,
provider: VaultProvider,
account: &str,
server: &str,
accept_invalid_cert: bool,
) {
cached.vault_accounts.retain(|row| row.provider != provider);
// "No account" and "an account without a name" are the same, and only one
// of them belongs in the database.
if account.trim().is_empty() {
ops.push(Pending::DeleteVaultAccount { provider });
return;
}
cached.vault_accounts.push(ApiVaultAccount {
id: String::new(),
provider,
account: account.to_string(),
server: server.to_string(),
accept_invalid_cert,
revision: cached.revision.clone(),
deleted_at: None,
});
ops.push(Pending::PutVaultAccount {
provider,
account: account.to_string(),
server: server.to_string(),
accept_invalid_cert,
});
}
// ---- Projects ----------------------------------------------------------------
fn projects(
cached: &mut Cached,
current: &[Project],
incoming: &Workspace,
user_id: &str,
private: Option<&[u8; 32]>,
ops: &mut Vec<Pending>,
) -> Result<(), String> {
// Where each connection is now, and where it was before: one that
// disappears from one project and shows up in another has been moved —
// not deleted and created anew.
let incoming_ids: HashSet<&str> = incoming
.projects
.iter()
.flat_map(|project| project.connections.iter())
.map(|connection| connection.id.as_str())
.collect();
let everywhere: Vec<&Connection> = current
.iter()
.flat_map(|project| project.connections.iter())
.collect();
// A deleted project takes its connections with it. The deletion therefore
// goes up **last**: a connection that was pulled out beforehand has to
// have moved first.
let mut deleted = Vec::new();
for project in current {
if !incoming.projects.iter().any(|row| row.id == project.id) {
cached.projects.retain(|row| row.id != project.id);
cached
.connections
.retain(|row| row.project_id != project.id);
cached.secrets.retain(|row| {
project
.connections
.iter()
.all(|c| c.id != row.connection_id)
});
deleted.push(Pending::DeleteProject {
id: project.id.clone(),
});
}
}
for (position, project) in incoming.projects.iter().enumerate() {
let position = position as i64;
let known = current.iter().find(|row| row.id == project.id);
match known {
None => {
cached.projects.push(ApiProject {
id: project.id.clone(),
name: project.name.clone(),
position,
created_by_id: Some(user_id.to_string()),
revision: cached.revision.clone(),
deleted_at: None,
});
ops.push(Pending::CreateProject {
id: project.id.clone(),
name: project.name.clone(),
position,
});
// A new project needs a project key before the first secret can
// be stored under it — and that key is created here, not on the
// server.
new_project_key(cached, &project.id, user_id, private, ops)?;
}
Some(_) => {
let row = cached
.project(&project.id)
.cloned()
.ok_or_else(|| t!("cloud_sync.project_missing_from_cache").into_owned())?;
if row.name != project.name || row.position != position {
if let Some(entry) = cached.projects.iter_mut().find(|p| p.id == project.id) {
entry.name = project.name.clone();
entry.position = position;
}
ops.push(Pending::UpdateProject {
id: project.id.clone(),
name: project.name.clone(),
position,
expected_revision: expected(cached, &project.id, &row.revision),
});
}
}
}
let empty = Vec::new();
let was = known.map(|row| &row.connections).unwrap_or(&empty);
connections(
cached,
was,
&everywhere,
&incoming_ids,
project,
private,
ops,
)?;
}
ops.extend(deleted);
Ok(())
}
/// Generates a project key and wraps it for oneself.
///
/// For oneself first and for others later: whoever has a share but no key yet
/// is listed in `…/key-requests` — and that list is caught up on every sync.
/// Waiting for all members here would mean not being able to create any
/// project at all while offline.
fn new_project_key(
cached: &mut Cached,
project_id: &str,
user_id: &str,
private: Option<&[u8; 32]>,
ops: &mut Vec<Pending>,
) -> Result<(), String> {
let Some(private) = private else {
return Err(locked());
};
let public = crypto::public_key_of(private);
let key_id = uuid::Uuid::new_v4().to_string();
let key = crypto::new_project_key()?;
let wrapped = crypto::wrap_project_key(&key, &public)?;
let grant = Grant {
user_id: user_id.to_string(),
ephemeral_public_key: BASE64.encode(wrapped.ephemeral_public_key),
nonce: BASE64.encode(&wrapped.nonce),
wrapped_key: BASE64.encode(&wrapped.wrapped_key),
};
// Into the copy as well, not only into the queue: otherwise the secrets
// enqueued right behind it would be unreadable after a restart before the
// upload.
cached.project_keys.push(ApiProjectKey {
project_id: project_id.to_string(),
user_id: user_id.to_string(),
key_id: key_id.clone(),
algorithm: crypto::GRANT_ALGORITHM.to_string(),
ephemeral_public_key: grant.ephemeral_public_key.clone(),
nonce: grant.nonce.clone(),
wrapped_key: grant.wrapped_key.clone(),
});
ops.push(Pending::GrantKeys {
project_id: project_id.to_string(),
key_id,
grants: vec![grant],
});
Ok(())
}
// ---- Connections -------------------------------------------------------------
fn connections(
cached: &mut Cached,
was: &[Connection],
everywhere: &[&Connection],
incoming_ids: &HashSet<&str>,
project: &Project,
private: Option<&[u8; 32]>,
ops: &mut Vec<Pending>,
) -> Result<(), String> {
for connection in was {
// If it is in another project, it has moved — the project it is in now
// takes care of that.
if !incoming_ids.contains(connection.id.as_str()) {
cached.connections.retain(|row| row.id != connection.id);
cached
.secrets
.retain(|row| row.connection_id != connection.id);
ops.push(Pending::DeleteConnection {
id: connection.id.clone(),
});
}
}
for (position, connection) in project.connections.iter().enumerate() {
let position = position as i64;
let here = was.iter().find(|row| row.id == connection.id);
// Moved here from another project.
let moved_from = match here {
Some(_) => None,
None => everywhere
.iter()
.copied()
.find(|row| row.id == connection.id),
};
let known = here.or(moved_from);
let moved = moved_from.is_some();
let row = api_connection(connection, &project.id, position)?;
match known {
None => {
cached.connections.push(row.clone());
ops.push(Pending::CreateConnection {
project_id: project.id.clone(),
connection: row.clone(),
});
}
Some(known) => {
let before = cached
.connection(&connection.id)
.map(|entry| entry.position)
.unwrap_or(position);
// The tree is compared, not the server row: the secret is in
// the settings, and that is exactly what matters.
let same = !moved && same_connection(known, connection) && before == position;
if !same {
let mut revision = String::new();
match cached
.connections
.iter_mut()
.find(|c| c.id == connection.id)
{
Some(entry) => {
revision = entry.revision.clone();
*entry = row.clone();
entry.revision = revision.clone();
}
// Its old project was deleted in the same go and took
// it out of the copy along with it.
None => cached.connections.push(row.clone()),
}
ops.push(Pending::UpdateConnection {
id: connection.id.clone(),
connection: row.clone(),
expected_revision: expected(cached, &connection.id, &revision),
});
}
}
}
secret(cached, known, connection, &project.id, private, ops, moved)?;
}
Ok(())
}
/// The revision a change builds on — provided the copy has one from the
/// server. A row whose creation is still waiting carries only a placeholder;
/// the server would not know it and would report a conflict that does not
/// exist.
fn expected(cached: &Cached, id: &str, revision: &str) -> Option<String> {
if revision.is_empty() || cached.creation_pending(id) {
return None;
}
Some(revision.to_string())
}
/// Whether two connections are the same.
///
/// Via the serialized form instead of field by field: the settings are a
/// tagged enum with three variants, each with its own authentication, and a
/// new connection type should not require any change here.
fn same_connection(a: &Connection, b: &Connection) -> bool {
serde_json::to_value(a).ok() == serde_json::to_value(b).ok()
}
fn api_connection(
connection: &Connection,
project_id: &str,
position: i64,
) -> Result<ApiConnection, String> {
let (ssh, ftp, s3) = model::bodies_of(&connection.settings);
Ok(ApiConnection {
id: connection.id.clone(),
project_id: project_id.to_string(),
name: connection.name.clone(),
kind: model::type_of(&connection.settings).to_string(),
bookmarked: connection.bookmarked,
position,
system: connection.system.clone(),
revision: String::new(),
deleted_at: None,
ssh,
ftp,
s3,
})
}
// ---- Secrets -----------------------------------------------------------------
/// Decides whether the ciphertext on the server is to be renewed, deleted or
/// left alone.
///
/// The third case is the most important one and the only one that is not
/// obvious: a field that is empty *because the vault was closed* looks exactly
/// like one that someone has cleared. That is why the source decides, not the
/// value — an `inlineKey` without content leaves it in place, a switch to
/// `keyFile` clears it away.
fn secret(
cached: &mut Cached,
known: Option<&Connection>,
connection: &Connection,
project_id: &str,
private: Option<&[u8; 32]>,
ops: &mut Vec<Pending>,
moved: bool,
) -> Result<(), String> {
let has_source = model::has_secret_source(&connection.settings);
let stored = cached
.secret(&connection.id)
.filter(|row| row.deleted_at.is_none())
.is_some();
if !has_source {
if stored {
cached
.secrets
.retain(|row| row.connection_id != connection.id);
ops.push(Pending::DeleteSecret {
connection_id: connection.id.clone(),
});
}
return Ok(());
}
let Some(plaintext) = model::secret_of(&connection.settings) else {
// Moved, but locked: the ciphertext is under the old project's key,
// and nobody in the new one can open it. Better not to move at all
// than like that.
if moved && stored {
return Err(locked());
}
// A source with a secret, but none at hand: loaded locked. The
// ciphertext stays where it is.
return Ok(());
};
let before = known.and_then(|row| model::secret_of(&row.settings));
// Unchanged and already up — only the rest of the connection has changed.
// Uploading again would be a new nonce for the same bytes and good for
// nothing. Except after a move: then it belongs under the new project's
// key.
if before == Some(plaintext) && stored && !moved {
return Ok(());
}
let Some(private) = private else {
return Err(locked());
};
let key_id = cached
.current_key_id(project_id)
.ok_or_else(|| t!("cloud_sync.no_project_key").into_owned())?;
let key = cached
.unwrap_key(private, project_id, &key_id)
.ok_or_else(|| t!("cloud_sync.project_key_unwrap_failed").into_owned())?;
let nonce = crypto::new_nonce()?;
// The `aad` is the `connectionId`. It has to be fixed from the start —
// introducing it later would mean re-encrypting everything.
let ciphertext = crypto::seal(&key, &nonce, plaintext.as_bytes(), connection.id.as_bytes())?;
let nonce = BASE64.encode(&nonce);
let ciphertext = BASE64.encode(&ciphertext);
cached
.secrets
.retain(|row| row.connection_id != connection.id);
cached.secrets.push(ApiSecret {
connection_id: connection.id.clone(),
algorithm: crypto::SECRET_ALGORITHM.to_string(),
key_id: key_id.clone(),
nonce: nonce.clone(),
ciphertext: ciphertext.clone(),
revision: cached.revision.clone(),
deleted_at: None,
});
ops.push(Pending::PutSecret {
connection_id: connection.id.clone(),
key_id,
nonce,
ciphertext,
});
Ok(())
}
fn locked() -> String {
t!("cloud_sync.vault_locked").into_owned()
}
#[cfg(test)]
mod tests {
use super::*;
use crate::cloud::model::{ShareRole, WorkspaceKind};
use crate::storage::{ConnectionSettings, SshAuth, SshSettings, StorageKind};
fn vault() -> (Unlocked, [u8; 32]) {
let pair = crypto::new_key_pair().expect("creates a pair");
let public = pair.public;
(Unlocked::new(pair.private, public), public)
}
fn copy() -> Cached {
Cached::new("org-1".into(), "acc-1".into(), "Company".into())
}
fn ssh(key: &str) -> ConnectionSettings {
ConnectionSettings::Ssh(SshSettings {
host: "web01.example".into(),
port: 22,
user: "root".into(),
auth: SshAuth::InlineKey { key: key.into() },
start_path: String::new(),
jump: None,
agent_forwarding: false,
via: Vec::new(),
forwards: Vec::new(),
proxy: None,
startup_snippet: None,
})
}
fn tree_of(projects: Vec<Project>) -> Workspace {
Workspace {
id: "org-1".into(),
name: "Company".into(),
storage: StorageKind::Cloud,
one_password_account: String::new(),
bitwarden: None,
remote: None,
projects,
snippets: Vec::new(),
}
}
fn connection(id: &str, name: &str, settings: ConnectionSettings) -> Connection {
Connection {
id: id.into(),
name: name.into(),
settings,
system: None,
bookmarked: false,
secret_unreadable: false,
}
}
/// A new project brings its key along — and that key comes **before** the
/// secret in the queue, because the server rejects a `secret` with an
/// unknown `keyId`.
#[test]
fn a_new_project_brings_its_key_along() {
let (open, _) = vault();
let mut cached = copy();
let tree = tree_of(vec![Project {
id: "p1".into(),
name: "Production".into(),
connections: vec![connection("c1", "web01", ssh("PRIVATE KEY"))],
}]);
let ops = plan(&mut cached, &tree, "u1", Some(&open)).expect("plans");
let names: Vec<&str> = ops
.iter()
.map(|op| match op {
Pending::CreateProject { .. } => "project",
Pending::GrantKeys { .. } => "key",
Pending::CreateConnection { .. } => "connection",
Pending::PutSecret { .. } => "secret",
_ => "other",
})
.collect();
assert_eq!(names, vec!["project", "key", "connection", "secret"]);
}
fn snippet(id: &str, command: &str) -> crate::storage::Snippet {
crate::storage::Snippet {
id: id.into(),
project_id: "p1".into(),
connection_id: None,
locked: true,
name: id.into(),
folder: String::new(),
command: command.into(),
}
}
/// Only the snippet operations, in their order.
fn snippet_ops(ops: &[Pending]) -> Vec<&Pending> {
ops.iter()
.filter(|op| {
matches!(
op,
Pending::CreateSnippet { .. }
| Pending::UpdateSnippet { .. }
| Pending::DeleteSnippet { .. }
)
})
.collect()
}
/// Create, update with the revision the change builds on, and delete — and
/// a mere reordering is a change.
#[test]
fn snippets_are_created_updated_and_deleted() {
let (open, _) = vault();
let mut cached = copy();
let mut tree = tree_of(vec![Project {
id: "p1".into(),
name: "Production".into(),
connections: Vec::new(),
}]);
tree.snippets = vec![snippet("s1", "uptime"), snippet("s2", "df -h")];
let ops = plan(&mut cached, &tree, "u1", Some(&open)).expect("plans");
assert!(matches!(
snippet_ops(&ops).as_slice(),
[Pending::CreateSnippet { .. }, Pending::CreateSnippet { .. }]
));
// As after the sync: the server has assigned revisions.
cached.pending.clear();
for row in &mut cached.snippets {
row.revision = "7".into();
}
for row in &mut cached.projects {
row.revision = "7".into();
}
tree.snippets = vec![snippet("s2", "df -h"), snippet("s1", "uptime -p")];
let ops = plan(&mut cached, &tree, "u1", Some(&open)).expect("plans");
let seen: Vec<_> = snippet_ops(&ops)
.into_iter()
.map(|op| match op {
Pending::UpdateSnippet {
snippet,
expected_revision,
} => (
snippet.id.as_str(),
snippet.position,
expected_revision.as_deref(),
),
_ => ("other", -1, None),
})
.collect();
assert_eq!(seen, [("s2", 0, Some("7")), ("s1", 1, Some("7"))]);
tree.snippets = vec![snippet("s1", "uptime -p")];
let ops = plan(&mut cached, &tree, "u1", Some(&open)).expect("plans");
assert!(matches!(
snippet_ops(&ops).as_slice(),
[Pending::DeleteSnippet { id }, Pending::UpdateSnippet { .. }] if id == "s2"
));
assert_eq!(cached.snippet_list().len(), 1);
}
/// Locking and binding to a connection are changes; the project is not —
/// it only changes along with the connection, on the server.
#[test]
fn a_snippet_is_changed_by_lock_and_connection_but_not_by_project() {
let (open, _) = vault();
let mut cached = copy();
let mut tree = tree_of(vec![Project {
id: "p1".into(),
name: "Production".into(),
connections: vec![connection("c1", "web01", ssh("KEY"))],
}]);
tree.snippets = vec![snippet("s1", "uptime")];
plan(&mut cached, &tree, "u1", Some(&open)).expect("plans");
cached.pending.clear();
tree.snippets[0].project_id = "p2".into();
let ops = plan(&mut cached, &tree, "u1", Some(&open)).expect("plans");
assert!(snippet_ops(&ops).is_empty());
tree.snippets[0].locked = false;
tree.snippets[0].connection_id = Some("c1".into());
let ops = plan(&mut cached, &tree, "u1", Some(&open)).expect("plans");
assert!(matches!(
snippet_ops(&ops).as_slice(),
[Pending::UpdateSnippet { snippet, .. }]
if !snippet.locked && snippet.connection_id.as_deref() == Some("c1")
));
}
fn startup_of(connection: &model::ApiConnection) -> Option<String> {
serde_json::to_value(connection).ok()?["ssh"]["startupSnippetId"]
.as_str()
.map(str::to_string)
}
/// The snippets come after the connections: a new one needs its
/// connection on the server. A startup command that points at it waits
/// for it — the connection goes up without, and gets it afterwards.
#[test]
fn snippets_follow_the_connections_and_a_startup_command_follows_its_snippet() {
let (open, _) = vault();
let mut cached = copy();
let mut settings = ssh("KEY");
if let ConnectionSettings::Ssh(ssh) = &mut settings {
ssh.startup_snippet = Some("s1".into());
}
let mut tree = tree_of(vec![Project {
id: "p1".into(),
name: "Production".into(),
connections: vec![connection("c1", "web01", settings)],
}]);
tree.snippets = vec![crate::storage::Snippet {
connection_id: Some("c1".into()),
..snippet("s1", "uptime")
}];
let ops = plan(&mut cached, &tree, "u1", Some(&open)).expect("plans");
let order: Vec<_> = ops
.iter()
.filter_map(|op| match op {
Pending::CreateConnection { connection, .. } => {
Some(("create connection", startup_of(connection)))
}
Pending::CreateSnippet { .. } => Some(("create snippet", None)),
Pending::UpdateConnection { connection, .. } => {
Some(("update connection", startup_of(connection)))
}
_ => None,
})
.collect();
assert_eq!(
order,
[
("create connection", None),
("create snippet", None),
("update connection", Some("s1".to_string())),
]
);
}
/// Deleting a startup snippet: the connection lets go of it first.
#[test]
fn a_deleted_startup_snippet_goes_after_the_connection_let_go() {
let (open, _) = vault();
let mut cached = copy();
let mut settings = ssh("KEY");
if let ConnectionSettings::Ssh(ssh) = &mut settings {
ssh.startup_snippet = Some("s1".into());
}
let mut tree = tree_of(vec![Project {
id: "p1".into(),
name: "Production".into(),
connections: vec![connection("c1", "web01", settings)],
}]);
tree.snippets = vec![snippet("s1", "uptime")];
plan(&mut cached, &tree, "u1", Some(&open)).expect("plans");
cached.pending.clear();
if let ConnectionSettings::Ssh(ssh) = &mut tree.projects[0].connections[0].settings {
ssh.startup_snippet = None;
}
tree.snippets.clear();
let ops = plan(&mut cached, &tree, "u1", Some(&open)).expect("plans");
let update = ops
.iter()
.position(|op| matches!(op, Pending::UpdateConnection { .. }))
.expect("updates the connection");
let delete = ops
.iter()
.position(|op| matches!(op, Pending::DeleteSnippet { .. }))
.expect("deletes the snippet");
assert!(update < delete);
}
/// And afterwards it comes back out when loading — the copy has been kept
/// as if everything were already up.
#[test]
fn after_planning_everything_is_already_in_the_copy() {
let (open, _) = vault();
let mut cached = copy();
let tree = tree_of(vec![Project {
id: "p1".into(),
name: "Production".into(),
connections: vec![connection("c1", "web01", ssh("PRIVATE KEY"))],
}]);
plan(&mut cached, &tree, "u1", Some(&open)).expect("plans");
let (projects, missing) = cached.tree(Some(&open.private));
assert!(!missing);
assert_eq!(
model::secret_of(&projects[0].connections[0].settings),
Some("PRIVATE KEY")
);
}
/// The case that would have deleted every ciphertext on the server without
/// this distinction: loaded locked, something changed in a name, saved.
#[test]
fn a_tree_loaded_locked_deletes_no_secret() {
let (open, _) = vault();
let mut cached = copy();
let tree = tree_of(vec![Project {
id: "p1".into(),
name: "Production".into(),
connections: vec![connection("c1", "web01", ssh("PRIVATE KEY"))],
}]);
plan(&mut cached, &tree, "u1", Some(&open)).expect("plans");
cached.pending.clear();
// This is what the tree looks like when it was loaded locked: the row
// is there, the field empty.
let (locked, missing) = cached.tree(None);
assert!(missing);
let mut changed = tree_of(locked);
changed.projects[0].connections[0].name = "web02".into();
let ops = plan(&mut cached, &changed, "u1", None).expect("plans even when locked");
assert!(ops
.iter()
.any(|op| matches!(op, Pending::UpdateConnection { .. })));
assert!(!ops
.iter()
.any(|op| matches!(op, Pending::DeleteSecret { .. } | Pending::PutSecret { .. })));
assert!(cached.secret("c1").is_some());
}
/// A change names the revision it builds on. If someone else has changed