artifactize 0.22.0

The AI-native collaboration layer for one-of-a-kind teammates and their agents: split a project into Artifacts with their own evals, and reuse every review while it still holds.
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
#[path = "support/run.rs"]
mod owned_run;
use owned_run::Watcher;

use std::{
    fs,
    io::Write,
    net::TcpListener,
    path::Path,
    process::{Command, Stdio},
    time::Duration,
};

use serde_json::{Value, json};

#[path = "../../artifactize-core/tests/support/mod.rs"]
mod support;

fn test_token() -> String {
    let mut bytes = [0u8; 16];
    getrandom::fill(&mut bytes).unwrap();
    let hex: String = bytes.iter().map(|byte| format!("{byte:02x}")).collect();
    format!("azt_test{hex}")
}

fn artifactize(state: &Path) -> Command {
    let mut command = Command::new(support::os::cli());
    command
        .arg("--state-dir")
        .arg(state)
        .env_remove("ARTIFACTIZE_REMOTE")
        .env_remove("ARTIFACTIZE_REMOTE_TOKEN")
        .env_remove("ARTIFACTIZE_REMOTE_SHARE");
    command
}

/// Run with `--json`; the output never contains `secret`.
fn run(command: &mut Command, stdin: &str, secret: &str, code: i32) -> Value {
    command.arg("--json").stdin(Stdio::piped());
    let child = support::os::start(command);
    let mut child = Watcher::new(child);
    child
        .stdin
        .take()
        .unwrap()
        .write_all(stdin.as_bytes())
        .unwrap();
    let output = child.wait_with_output().unwrap();
    let (stdout, stderr) = (
        String::from_utf8_lossy(&output.stdout),
        String::from_utf8_lossy(&output.stderr),
    );
    assert_eq!(output.status.code(), Some(code), "{stdout}{stderr}");
    assert!(!stdout.contains(secret) && !stderr.contains(secret));
    // Nor a piece of it: the random part after `azt_test`, and its end.
    if secret.len() >= 24 {
        for piece in [&secret[8..20], &secret[secret.len() - 12..]] {
            assert!(
                !stdout.contains(piece) && !stderr.contains(piece),
                "{stdout}{stderr}"
            );
        }
    }
    serde_json::from_slice(&output.stdout).unwrap()
}

struct Whoami {
    url: String,
    _provider: support::FakeProvider,
}

impl Whoami {
    fn start(token: &str) -> Self {
        let expected = format!("Bearer {token}");
        let provider = support::FakeProvider::start(move |request| {
            assert_eq!(request.method, "GET");
            assert_eq!(request.path, "/v1/whoami");
            if request.headers.get("authorization") == Some(&expected) {
                support::Reply::Json(
                    200,
                    json!({"principal":"alice-laptop","scopes":["read","publish"]}),
                )
            } else {
                support::Reply::Json(401, json!({"error":"Invalid or revoked token."}))
            }
        });
        Self {
            url: format!("{}/", provider.url),
            _provider: provider,
        }
    }
}

#[test]
fn login_status_overrides_and_logout_against_a_test_server() {
    let root = support::os::tempdir();
    let state = root.path().join("state");
    let token = test_token();
    let server = Whoami::start(&token);

    let refused = run(
        artifactize(&state).args(["remote", "login", "http://reviews.example/"]),
        &token,
        &token,
        2,
    );
    assert!(refused["error"].as_str().unwrap().contains("https://"));
    let rejected_token = test_token();
    let rejected = run(
        artifactize(&state).args(["remote", "login", &server.url]),
        &format!("{rejected_token}\n"),
        &rejected_token,
        2,
    );
    assert!(rejected["error"].as_str().unwrap().contains("rejected"));
    assert!(!state.join("remote.json").exists());

    assert_eq!(
        run(
            artifactize(&state).args(["remote", "login", &server.url]),
            &format!("{token}\n"),
            &token,
            0
        ),
        json!({
            "url":server.url,
            "share":"summary",
            "principal":"alice-laptop",
            "scopes":["read","publish"],
        })
    );
    let saved = state.join("auth/remote-token.json");
    assert!(support::os::private_file(&saved));
    assert_eq!(
        serde_json::from_slice::<Value>(&fs::read(state.join("remote.json")).unwrap()).unwrap(),
        json!({"url":server.url,"share":"summary"})
    );

    assert_eq!(
        run(
            artifactize(&state).args(["remote", "status"]),
            "",
            &token,
            0
        ),
        json!({"configured":true,"url":server.url,"share":"summary","tokenSource":"file",
            "reachable":true,"principal":"alice-laptop","scopes":["read","publish"],"error":null})
    );
    let other = test_token();
    let overridden = run(
        artifactize(&state)
            .args(["remote", "status"])
            .env("ARTIFACTIZE_REMOTE_TOKEN", &other)
            .env("ARTIFACTIZE_REMOTE_SHARE", "full"),
        "",
        &other,
        1,
    );
    assert_eq!(
        (
            &overridden["tokenSource"],
            &overridden["share"],
            &overridden["reachable"],
            &overridden["principal"]
        ),
        (&json!("env"), &json!("full"), &json!(true), &Value::Null)
    );
    assert!(overridden["error"].as_str().unwrap().contains("rejected"));
    assert_eq!(
        run(
            artifactize(&state)
                .args(["remote", "status"])
                .env("ARTIFACTIZE_REMOTE", "off"),
            "",
            &token,
            1
        ),
        json!({"configured":false})
    );
    let closed = TcpListener::bind("127.0.0.1:0").unwrap();
    let closed_url = format!("http://{}/", closed.local_addr().unwrap());
    drop(closed);
    let elsewhere = run(
        artifactize(&state)
            .args(["remote", "status"])
            .env("ARTIFACTIZE_REMOTE", &closed_url),
        "",
        &token,
        2,
    );
    assert!(
        elsewhere["error"]
            .as_str()
            .unwrap()
            .contains("another store")
    );
    let unreachable = run(
        artifactize(&state)
            .args(["remote", "status"])
            .env("ARTIFACTIZE_REMOTE", &closed_url)
            .env("ARTIFACTIZE_REMOTE_TOKEN", &token),
        "",
        &token,
        1,
    );
    assert_eq!(unreachable["reachable"], false);
    assert!(
        unreachable["error"]
            .as_str()
            .unwrap()
            .contains("unreachable")
    );

    assert_eq!(
        run(
            artifactize(&state).args(["remote", "logout"]),
            "",
            &token,
            0
        ),
        json!({"signedIn":false})
    );
    assert!(!saved.exists() && !state.join("remote.json").exists());
}

#[test]
fn doctor_checks_remote_configuration_without_opening_a_socket() {
    let root = support::os::tempdir();
    let state = root.path().join("state");
    let bin = root.path().join("bin");
    support::os::create_private_dir_all(&state.join("auth"));
    fs::create_dir(&bin).unwrap();
    let listener = TcpListener::bind("127.0.0.1:0").unwrap();
    listener.set_nonblocking(true).unwrap();
    let url = format!("http://{}/", listener.local_addr().unwrap());
    let token = test_token();
    let doctor = |code| {
        let report = run(
            artifactize(&state)
                .arg("doctor")
                .env("PATH", &bin)
                .env_remove("OPENAI_API_KEY")
                .env_remove("ANTHROPIC_API_KEY"),
            "",
            &token,
            code,
        );
        report["checks"]
            .as_array()
            .unwrap()
            .iter()
            .find(|check| check["name"] == "remote")
            .unwrap()
            .clone()
    };
    assert_eq!(doctor(0)["status"], "PASS");

    fs::write(state.join("remote.json"), json!({"url":url}).to_string()).unwrap();
    let missing = doctor(0);
    assert_eq!(missing["status"], "WARN");
    assert_eq!(missing["details"]["tokenSource"], "none");

    let saved = state.join("auth/remote-token.json");
    let contents = json!({"url":url,"token":token}).to_string();
    support::os::write_private_file(&saved, &contents);
    support::os::grant_everyone_read(&saved);
    let unsafe_file = doctor(1);
    assert_eq!(unsafe_file["status"], "FAIL");
    assert!(
        unsafe_file["message"]
            .as_str()
            .unwrap()
            .contains("readable by their owner only")
    );
    // Owner-only again: mode 0600, or on Windows a new file with the folder's DACL.
    fs::remove_file(&saved).unwrap();
    support::os::write_private_file(&saved, &contents);
    let ready = doctor(0);
    assert_eq!(
        (&ready["status"], &ready["details"]["tokenSource"]),
        (&json!("PASS"), &json!("file"))
    );
    assert_eq!(
        listener.accept().unwrap_err().kind(),
        std::io::ErrorKind::WouldBlock
    );

    fs::write(
        state.join("remote.json"),
        json!({"url":"http://reviews.example/"}).to_string(),
    )
    .unwrap();
    assert!(doctor(1)["message"].as_str().unwrap().contains("https://"));
}

#[test]
fn login_on_a_terminal_does_not_echo_the_token() {
    let root = support::os::tempdir();
    let token = test_token();
    let server = Whoami::start(&token);
    let state = root.path().join("state");
    let (mut terminal, receiver) = support::os::PseudoTerminal::start(
        support::os::cli().as_path(),
        &[
            "--state-dir",
            state.to_str().unwrap(),
            "remote",
            "login",
            &server.url,
        ],
        &[
            "ARTIFACTIZE_REMOTE",
            "ARTIFACTIZE_REMOTE_TOKEN",
            "ARTIFACTIZE_REMOTE_SHARE",
        ],
        100,
        30,
    );
    let wait = support::os::patience(Duration::from_secs(10));
    let mut output = Vec::new();
    while !String::from_utf8_lossy(&output).contains("Paste the remote token") {
        output.extend(
            receiver
                .recv_timeout(wait)
                .expect("login did not ask for the token"),
        );
    }
    // A terminal's Enter key sends a carriage return.
    terminal.type_text(format!("{token}\r").as_bytes());
    assert!(terminal.finish());
    // The output ends once the terminal has closed.
    while let Ok(chunk) = receiver.recv_timeout(wait) {
        output.extend(chunk);
    }
    let output = String::from_utf8_lossy(&output);
    assert!(!output.contains(&token));
    assert!(output.contains("as alice-laptop"), "{output}");
}

// Git Bash's mintty hands a program a pipe named like a pty: a terminal to `is_terminal`, but
// no console whose echo can be turned off. Login then reads the token visibly and says so.
#[cfg(windows)]
#[test]
fn login_on_a_mintty_pipe_reads_the_token_visibly_with_a_warning() {
    let root = support::os::tempdir();
    let token = test_token();
    let server = Whoami::start(&token);
    let (mut writer, reader) = support::os::mintty_pipe();
    assert!(
        support::os::is_terminal(&reader),
        "the pipe passes for a mintty terminal"
    );
    let child = support::os::start(
        artifactize(&root.path().join("state"))
            .args(["remote", "login", &server.url])
            .stdin(reader),
    );
    let child = Watcher::new(child);
    // The pipe stays open meanwhile: a pty whose master closed is no longer a terminal.
    writer.write_all(format!("{token}\n").as_bytes()).unwrap();
    let output = child.wait_with_output().unwrap();
    drop(writer);
    let (stdout, stderr) = (
        String::from_utf8_lossy(&output.stdout),
        String::from_utf8_lossy(&output.stderr),
    );
    assert!(output.status.success(), "{stdout}{stderr}");
    assert!(stderr.contains("cannot hide input"), "{stdout}{stderr}");
    assert!(stderr.contains("Paste the remote token"), "{stderr}");
    assert!(stdout.contains("as alice-laptop"), "{stdout}");
    assert!(!stdout.contains(&token) && !stderr.contains(&token));
}

/// How a store or proxy may echo the Authorization header it was sent.
#[derive(Clone, Copy)]
enum Echo {
    Whole,
    /// Split by a newline: dropping control characters would rejoin it.
    Split,
    /// Where the 300-character clip falls inside it.
    AtTheClip,
}

/// A store that answers whoami with a client error echoing the Authorization header.
fn echoing(echo: Echo) -> support::FakeProvider {
    support::FakeProvider::start(move |request| {
        let header = request
            .headers
            .get("authorization")
            .cloned()
            .unwrap_or_default();
        let error = match echo {
            Echo::Whole => format!("Bad request; Authorization: {header}"),
            Echo::Split => {
                let (head, tail) = header.split_at("Bearer ".len() + 12);
                format!("Bad request; Authorization: {head}\n{tail}")
            }
            Echo::AtTheClip => format!("{}{header}", "x".repeat(290)),
        };
        support::Reply::Json(400, json!({ "error": error }))
    })
}

#[test]
fn a_store_that_echoes_the_token_never_gets_it_printed() {
    let withheld =
        "The remote store answered HTTP 400: [withheld: it contained part of the credential sent]";
    for echo in [Echo::Whole, Echo::Split, Echo::AtTheClip] {
        let root = support::os::tempdir();
        let state = root.path().join("state");
        let token = test_token();
        let server = echoing(echo);
        let url = format!("{}/", server.url);
        // run() checks that no output holds the token or a piece of it.
        let check =
            |command: &mut Command, stdin: &str, code: i32| run(command, stdin, &token, code);
        let refused = check(
            artifactize(&state).args(["remote", "login", &url]),
            &format!("{token}\n"),
            2,
        );
        assert_eq!(refused["error"], withheld);
        // A saved token the store later echoes: status and push say so without it.
        let status = check(
            artifactize(&state)
                .args(["remote", "status"])
                .env("ARTIFACTIZE_REMOTE", &url)
                .env("ARTIFACTIZE_REMOTE_TOKEN", &token),
            "",
            1,
        );
        assert_eq!(status["error"], withheld);
        let push = check(
            artifactize(&state)
                .args(["remote", "push"])
                .env("ARTIFACTIZE_REMOTE", &url)
                .env("ARTIFACTIZE_REMOTE_TOKEN", &token),
            "",
            2,
        );
        assert_eq!(push["error"], withheld);
    }
}