link-cli 3.5.1

A CLI tool and reusable library for links manipulation backed by a LiNo-notation doublet storage engine.
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
//! `clink --permissions`, `--subject` and the token table end to end (issue
//! #149). The C# counterpart is `CliPermissionsTests`.

#[path = "common/stop_server.rs"]
mod stop_server;
#[path = "common/permissions_world.rs"]
mod world;

use std::io::{BufRead, BufReader};
use std::path::{Path, PathBuf};
use std::process::{Child, Command, Output, Stdio};

use link_cli::cli::{Cli, CliCommand};
use link_cli::{NamedTypeLinks, NamedTypesDecorator, PermissionPolicy, PermissionsDecorator};
use tempfile::TempDir;
use world::{make_world, Names};

struct Fixture {
    directory: TempDir,
}

struct Made {
    t: Names,
    v: Names,
    alice_sees: Vec<String>,
    all: Vec<String>,
}

impl Fixture {
    fn new() -> Self {
        Self {
            directory: TempDir::new().unwrap(),
        }
    }

    fn data(&self) -> PathBuf {
        self.directory.path().join("data.links")
    }

    fn rules(&self) -> PathBuf {
        self.directory.path().join("rules.links")
    }

    fn path(&self, name: &str) -> String {
        self.directory.path().join(name).display().to_string()
    }

    /// Writes the world of the permission tests into the data, its rules
    /// there or in a file of their own.
    fn make_world(&self, separate_rules: bool) -> Made {
        let mut data = NamedTypesDecorator::new(self.data(), false).unwrap();
        let mut rules = NamedTypesDecorator::new(self.rules(), false).unwrap();
        let (t, v, _, _) = make_world(
            &mut data,
            if separate_rules {
                Some(&mut rules)
            } else {
                None
            },
        )
        .unwrap();
        rules.save().unwrap();
        let policy = if separate_rules {
            PermissionPolicy::with_rules(&mut data, Box::new(rules)).unwrap()
        } else {
            PermissionPolicy::in_data(&mut data).unwrap()
        };
        let alice_sees = PermissionsDecorator::new(&mut data, policy, v["alice"])
            .lino_lines()
            .unwrap();
        let all = data.lino_lines().unwrap();
        data.save().unwrap();
        Made {
            t,
            v,
            alice_sees,
            all,
        }
    }

    fn clink(&self, args: &[&str]) -> Output {
        Command::new(env!("CARGO_BIN_EXE_clink"))
            .args(args)
            .output()
            .unwrap()
    }

    fn on_data(&self, args: &[&str]) -> Output {
        let data = self.data().display().to_string();
        let mut all = vec!["--db", data.as_str()];
        all.extend_from_slice(args);
        self.clink(&all)
    }

    fn permitted(&self, separate_rules: bool, args: &[&str]) -> Output {
        let rules = if separate_rules {
            self.rules().display().to_string()
        } else {
            "self".to_string()
        };
        let mut all = vec!["--permissions", rules.as_str()];
        all.extend_from_slice(args);
        self.on_data(&all)
    }

    fn after(&self) -> Vec<String> {
        lines(&succeeded(self.on_data(&["--after"])))
    }

    fn serve(&self, extra: &[&str]) -> Server {
        Server::start(&self.data(), extra)
    }
}

fn stdout(output: &Output) -> String {
    String::from_utf8_lossy(&output.stdout).into_owned()
}

fn stderr(output: &Output) -> String {
    String::from_utf8_lossy(&output.stderr).into_owned()
}

fn succeeded(output: Output) -> String {
    assert!(output.status.success(), "clink failed: {}", stderr(&output));
    stdout(&output)
}

fn lines(stdout: &str) -> Vec<String> {
    stdout.lines().map(str::to_string).collect()
}

fn failed_with(output: &Output, message: &str) {
    assert_eq!(output.status.code(), Some(1), "{}", stdout(output));
    assert!(
        stderr(output).contains(message),
        "{message:?} not in {:?}",
        stderr(output)
    );
}

fn a_subject_sees_what_its_rules_allow_and_writes_nothing_else(separate_rules: bool) {
    let fixture = Fixture::new();
    let Made {
        t,
        v,
        alice_sees,
        all,
    } = fixture.make_world(separate_rules);
    // Without --permissions nothing changes: every link is there.
    assert_eq!(fixture.after(), all);

    let seen = succeeded(fixture.permitted(separate_rules, &["--subject", "alice", "--after"]));
    assert_eq!(lines(&seen), alice_sees);
    assert!(alice_sees.contains(&"(note: Note note)".to_string()));
    assert!(alice_sees.contains(&"(shared: Shared shared)".to_string()));
    assert!(!alice_sees.iter().any(|line| line.contains("secret")));

    // A note of alice's may become another note, not a secret.
    let refused = fixture.permitted(
        separate_rules,
        &[
            "--subject",
            "alice",
            "--changes",
            "((note: Note note)) ((note: Public note))",
        ],
    );
    failed_with(&refused, &format!("Forbidden: update {}", v["note"]));
    assert_eq!(fixture.after(), all);

    // A secret is as missing to alice as a deleted link.
    let alice = v["alice"].to_string();
    failed_with(
        &fixture.permitted(
            separate_rules,
            &["--subject", &alice, "--changes", "((secret: * *)) ()"],
        ),
        "Invalid reference to non-existent link 'secret'",
    );
    assert_eq!(fixture.after(), all);

    // The boss writes anything.
    let boss = succeeded(fixture.permitted(
        separate_rules,
        &[
            "--subject",
            "boss",
            "--changes",
            "((note: Note note)) ((note: Secret note))",
        ],
    ));
    assert!(
        boss.contains("((note: Note note)) ((note: Secret note))"),
        "{boss}"
    );
    assert_ne!(t["Secret"], 0);
}

#[test]
fn a_subject_sees_what_its_rules_allow_and_writes_nothing_else_with_rules_in_the_data() {
    a_subject_sees_what_its_rules_allow_and_writes_nothing_else(false);
}

#[test]
fn a_subject_sees_what_its_rules_allow_and_writes_nothing_else_with_rules_apart() {
    a_subject_sees_what_its_rules_allow_and_writes_nothing_else(true);
}

#[test]
fn a_guest_reads_nothing_and_creates_nothing() {
    let fixture = Fixture::new();
    fixture.make_world(false);
    let seen = succeeded(fixture.permitted(false, &["--after"]));
    assert_eq!(seen, "");
    // Whether 1 exists is hidden from a guest, as for any other reference.
    failed_with(
        &fixture.permitted(false, &["() ((1 2))"]),
        "Invalid reference to non-existent link '1'",
    );
    failed_with(
        &fixture.permitted(false, &["--auto-create-missing-references", "() ((1 2))"]),
        "Forbidden: create",
    );
    failed_with(
        &fixture.permitted(false, &["--subject", "nobody", "--after"]),
        "Unknown subject 'nobody'",
    );
}

#[test]
fn token_commands_need_a_token_table_and_a_subject() {
    let fixture = Fixture::new();
    fixture.make_world(false);
    failed_with(
        &fixture.on_data(&["--subject", "alice", "--grant-token", "x"]),
        "--grant-token and --revoke-token need --tokens.",
    );
    failed_with(
        &fixture.on_data(&["--tokens", "self", "--grant-token", "x"]),
        "--grant-token needs a --subject.",
    );
    assert_eq!(
        succeeded(fixture.on_data(&["--tokens", "self", "--revoke-token", "x"])),
        "Unknown token.\n"
    );
    failed_with(
        &fixture.permitted(false, &["--always", "() ((1 1))"]),
        "--always, --once and --never cannot be used with --permissions.",
    );
}

fn served_connections_authenticate_with_tokens_stored_as_links(separate_tokens: bool) {
    let fixture = Fixture::new();
    let Made {
        v,
        alice_sees,
        mut all,
        ..
    } = fixture.make_world(false);
    let tokens = if separate_tokens {
        fixture.path("tokens.links")
    } else {
        "self".to_string()
    };
    let granted = succeeded(fixture.on_data(&[
        "--tokens",
        &tokens,
        "--subject",
        "alice",
        "--grant-token",
        "alice-secret",
    ]));
    assert!(
        granted.starts_with(&format!("Token granted to subject {}", v["alice"])),
        "{granted}"
    );
    if !separate_tokens {
        // The token links are links of the data, which alice cannot see.
        all = fixture.after();
    }

    {
        let server = fixture.serve(&["--permissions", "self", "--tokens", &tokens]);
        assert_eq!(succeeded(server.connect(&["(count: ())"])), "(count: 0)\n");
        assert_eq!(
            succeeded(server.connect(&["--token", "alice-secret", "(count: ())"])),
            format!("(count: {})\n", alice_sees.len())
        );
        let update = format!("(update: ({} {} {}))", v["note"], v["secret"], v["note"]);
        let refused = server.connect(&["--token", "alice-secret", &update]);
        assert!(!refused.status.success(), "{}", stdout(&refused));
        let wrong = server.connect(&["--token", "wrong", "(count: ())"]);
        assert!(!wrong.status.success());
        assert!(
            stderr(&wrong).contains("Forbidden: authentication failed"),
            "{}",
            stderr(&wrong)
        );
    }

    assert_eq!(fixture.after(), all);
    let revoked =
        succeeded(fixture.on_data(&["--tokens", &tokens, "--revoke-token", "alice-secret"]));
    assert_eq!(revoked, "Token revoked.\n");
}

#[test]
fn served_connections_authenticate_with_tokens_stored_as_links_in_the_data() {
    served_connections_authenticate_with_tokens_stored_as_links(false);
}

#[test]
fn served_connections_authenticate_with_tokens_stored_as_links_apart() {
    served_connections_authenticate_with_tokens_stored_as_links(true);
}

#[test]
fn parses_permission_options() {
    let cli = match Cli::parse_from([
        "clink",
        "--permissions",
        "rules.links",
        "--subject=alice",
        "--tokens",
        "self",
        "--grant-token=a",
        "--revoke-token",
        "b",
        "--token=c",
    ])
    .unwrap()
    {
        CliCommand::Run(cli) => *cli,
        other => panic!("expected run command, got {other:?}"),
    };
    assert_eq!(cli.permissions.as_deref(), Some("rules.links"));
    assert_eq!(cli.subject.as_deref(), Some("alice"));
    assert_eq!(cli.tokens.as_deref(), Some("self"));
    assert_eq!(cli.grant_token.as_deref(), Some("a"));
    assert_eq!(cli.revoke_token.as_deref(), Some("b"));
    assert_eq!(cli.token.as_deref(), Some("c"));
    for option in [
        "--permissions <RULES>",
        "--subject <LINK>",
        "--tokens <TOKENS>",
        "--grant-token <TOKEN>",
        "--revoke-token <TOKEN>",
        "--token <TOKEN>",
    ] {
        assert!(Cli::help_text().contains(option), "{option}");
    }
}

struct Server {
    child: Child,
    address: String,
}

impl Server {
    fn start(database: &Path, extra: &[&str]) -> Self {
        let mut child = Command::new(env!("CARGO_BIN_EXE_clink"))
            .arg("--db")
            .arg(database)
            .args(["--serve", "127.0.0.1:0"])
            .args(extra)
            .stdout(Stdio::piped())
            .stderr(Stdio::null())
            .spawn()
            .unwrap();
        let mut line = String::new();
        BufReader::new(child.stdout.take().unwrap())
            .read_line(&mut line)
            .unwrap();
        let address = line
            .trim()
            .strip_prefix("clink server listening on ")
            .unwrap_or_else(|| panic!("unexpected banner {line:?}"))
            .to_string();
        Self { child, address }
    }

    fn connect(&self, args: &[&str]) -> Output {
        Command::new(env!("CARGO_BIN_EXE_clink"))
            .args(["--connect", &self.address])
            .args(args)
            .output()
            .unwrap()
    }
}

impl Drop for Server {
    fn drop(&mut self) {
        stop_server::terminate(&mut self.child);
    }
}

/// What `clink --subject alice` answers for `query`, with the address it holds
/// written as `<address>`, so two addresses can be compared.
fn answer_of(fixture: &Fixture, query: &str, address: u32) -> (Option<i32>, String) {
    let output = fixture.permitted(false, &["--subject", "alice", "--changes", query]);
    let answer = format!("{}{}", stdout(&output), stderr(&output));
    (
        output.status.code(),
        answer.replace(&address.to_string(), "<address>"),
    )
}

/// Issue #161: a subject without the right gets the same answer for an
/// unreadable address and a missing one, and the store does not change.
#[test]
fn an_unreadable_address_answers_as_a_missing_one() {
    const MISSING: u32 = 9999;
    let fixture = Fixture::new();
    let Made { v, .. } = fixture.make_world(false);
    // The first permitted run may add a marker; the store is compared from here.
    succeeded(fixture.permitted(false, &["--subject", "alice", "--after"]));
    let before = fixture.after();
    for query in [
        "() ((Note <address>))",
        "() ((<address>: Note Note))",
        "((<address>: * *)) ()",
        "((<address>: * *)) ((<address>: Note Note))",
    ] {
        let at = |address: u32| query.replace("<address>", &address.to_string());
        let hidden = answer_of(&fixture, &at(v["secret"]), v["secret"]);
        let missing = answer_of(&fixture, &at(MISSING), MISSING);
        assert_eq!(hidden, missing, "{query}");
        assert_eq!(fixture.after(), before, "{query}");
    }
    // The same through a name: the name of a hidden link is an unknown name.
    let hidden = fixture.permitted(false, &["--subject", "alice", "() ((Note secret))"]);
    let missing = fixture.permitted(false, &["--subject", "alice", "() ((Note nothing))"]);
    assert_eq!(hidden.status.code(), missing.status.code());
    assert_eq!(
        stderr(&hidden).replace("secret", "<name>"),
        stderr(&missing).replace("nothing", "<name>")
    );
    assert_eq!(fixture.after(), before);
}