ommx 3.0.0-beta.4

Open Mathematical prograMming eXchange (OMMX)
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
//! End-to-end authentication tests for the v3 native OCI transport.
//!
//! These tests start ephemeral OCI registries (anonymous or
//! htpasswd-protected) via `testcontainers`, materialise the
//! credentials the SDK is supposed to discover (env vars or a fake
//! `~/.docker/config.json`), and then exercise the full push / pull
//! pipeline against the registry. They cover every tier of the
//! three-tier credential resolver in
//! `artifact::remote_transport::resolve_auth` plus the auth
//! negotiation that `oci_client::Client::auth` performs.
//!
//! Every push / pull path in the SDK shares the same `RemoteTransport`
//! plumbing: `LocalArtifact::push` reads from SQLite, archive push
//! goes through `ommx load <file>` then `LocalArtifact::push`, and
//! `pull_image` writes straight into SQLite. The suite mirrors that
//! split so any future divergence between "push from SQLite",
//! "load-then-push from archive", and "pull into SQLite" surfaces
//! here rather than only in production.
//!
//! All tests are `#[ignore]` so a plain `cargo test` does not require
//! Docker. CI re-runs the suite with `--include-ignored auth_e2e`.
//! `#[serial]` is necessary because the tests mutate process env
//! (`DOCKER_CONFIG`, `OMMX_BASIC_AUTH_*`), which is shared global
//! state under cargo's default parallel test runner.

#![cfg(feature = "remote-artifact")]

use anyhow::Result;
use ommx::artifact::{
    local_registry::LocalRegistry, media_types, ArtifactDraft, ImageRef, LocalArtifact,
};
use serial_test::serial;
use std::collections::HashMap;
use std::path::Path;
use std::sync::Arc;
use testcontainers::{
    core::{ContainerPort, Mount, WaitFor},
    runners::SyncRunner,
    Container, GenericImage, ImageExt,
};
use testcontainers_modules::cncf_distribution::CncfDistribution;

const ALICE_PASSWORD: &str = "secret";
const ALICE_USER: &str = "alice";

/// Path to the committed bcrypt htpasswd file (`alice:secret`). The
/// hash is generated by `htpasswd -nbB alice secret` and committed so
/// no bcrypt runtime dependency is needed; see `tests/fixtures/README.md`.
fn htpasswd_path() -> std::path::PathBuf {
    Path::new(env!("CARGO_MANIFEST_DIR"))
        .join("tests")
        .join("fixtures")
        .join("htpasswd")
}

/// Start an anonymous OCI registry. Tagged with the cncf-distribution
/// module's wait-for-ready check so we don't race the listener.
fn start_anonymous_registry() -> Container<CncfDistribution> {
    CncfDistribution::default()
        .start()
        .expect("failed to start anonymous test registry")
}

/// Start an htpasswd-protected registry. The bcrypt entries from
/// `tests/fixtures/htpasswd` are bind-mounted into the container.
/// Bind mount (not `with_copy_to`) so the container can re-read on
/// restart and so we don't have to maintain a digest-pinned content
/// hash.
fn start_htpasswd_registry() -> Container<GenericImage> {
    let mount = Mount::bind_mount(htpasswd_path().to_string_lossy(), "/auth/htpasswd");
    GenericImage::new("registry", "2")
        .with_wait_for(WaitFor::message_on_stderr("listening on [::]:5000"))
        .with_exposed_port(ContainerPort::Tcp(5000))
        .with_env_var("REGISTRY_AUTH", "htpasswd")
        .with_env_var("REGISTRY_AUTH_HTPASSWD_REALM", "Registry Realm")
        .with_env_var("REGISTRY_AUTH_HTPASSWD_PATH", "/auth/htpasswd")
        .with_mount(mount)
        .start()
        .expect("failed to start htpasswd test registry")
}

/// Build a tiny LocalArtifact in a fresh tempdir-backed SQLite Local
/// Registry and run `f` while that registry is still alive.
fn with_test_artifact<T>(
    image_name: ImageRef,
    f: impl FnOnce(LocalArtifact<'_>) -> Result<T>,
) -> Result<T> {
    ArtifactDraft::with_temp_local_registry(image_name, |mut draft| {
        draft.add_layer_bytes(
            oci_spec::image::MediaType::Other(media_types::V1_INSTANCE_MEDIA_TYPE.to_string()),
            b"auth-e2e-test".to_vec(),
            HashMap::from([(
                "org.ommx.v1.instance.title".to_string(),
                "auth-e2e".to_string(),
            )]),
        )?;
        let artifact = draft.commit()?;
        f(artifact)
    })
}

/// Materialise a fake `~/.docker/config.json` in a tempdir and point
/// `$DOCKER_CONFIG` at it. Returns the tempdir; dropping it before
/// `LocalArtifact::push` runs would race-clean the file, so the caller
/// must keep it bound.
fn write_docker_config(host: &str, user: &str, password: &str) -> Result<tempfile::TempDir> {
    use base64::{engine::general_purpose, Engine as _};
    let auth = general_purpose::STANDARD.encode(format!("{user}:{password}"));
    let body = format!(r#"{{ "auths": {{ "{host}": {{ "auth": "{auth}" }} }} }}"#,);
    let dir = tempfile::tempdir()?;
    std::fs::write(dir.path().join("config.json"), body)?;
    // Safety: parallel-unsafe; the `#[serial]` attribute on every test
    // that calls this serialises env mutation.
    unsafe {
        std::env::set_var("DOCKER_CONFIG", dir.path());
    }
    Ok(dir)
}

/// Test fixture guard: when dropped, every env var the auth resolver
/// reads is removed. Centralised here so individual tests can't forget
/// to clean up — a leaked `OMMX_BASIC_AUTH_DOMAIN` would cascade into
/// the next test as a partial-override error.
struct EnvGuard;

impl EnvGuard {
    fn new() -> Self {
        Self::clear();
        Self
    }

    fn clear() {
        for k in [
            "OMMX_BASIC_AUTH_DOMAIN",
            "OMMX_BASIC_AUTH_USERNAME",
            "OMMX_BASIC_AUTH_PASSWORD",
            "DOCKER_CONFIG",
        ] {
            // Safety: parallel-unsafe; tests are `#[serial]`.
            unsafe {
                std::env::remove_var(k);
            }
        }
    }
}

impl Drop for EnvGuard {
    fn drop(&mut self) {
        Self::clear();
    }
}

fn set_env(key: &str, value: &str) {
    // Safety: parallel-unsafe; tests are `#[serial]`.
    unsafe {
        std::env::set_var(key, value);
    }
}

// ──────────────────────────────────────────────────────────────────
// Tier 1: anonymous (baseline)
// ──────────────────────────────────────────────────────────────────

/// Anonymous push to an open registry: the registry accepts everything,
/// no credentials needed. Supersedes the previous one-shot smoke test
/// that lived in `artifact/push.rs::tests`.
#[test]
#[ignore = "requires docker"]
#[serial]
fn push_anonymous_against_open_registry() -> Result<()> {
    let _env = EnvGuard::new();
    let registry = start_anonymous_registry();
    let port = registry.get_host_port_ipv4(5000)?;
    let image_name = ImageRef::parse(&format!("localhost:{port}/ommx-test/anon:tag1"))?;
    with_test_artifact(image_name, |artifact| artifact.push())
}

// ──────────────────────────────────────────────────────────────────
// Tier 2: docker config (the "docker login だけ" pattern)
// ──────────────────────────────────────────────────────────────────

/// The user ran `docker login` and nothing else. The SDK should
/// discover the credentials in `~/.docker/config.json` and push
/// successfully. This is the headline UX of the credential resolver.
#[test]
#[ignore = "requires docker"]
#[serial]
fn push_with_docker_config_only() -> Result<()> {
    let _env = EnvGuard::new();
    let registry = start_htpasswd_registry();
    let port = registry.get_host_port_ipv4(5000)?;
    let host = format!("localhost:{port}");
    let _docker_dir = write_docker_config(&host, ALICE_USER, ALICE_PASSWORD)?;

    let image_name = ImageRef::parse(&format!("{host}/ommx-test/docker-only:tag1"))?;
    with_test_artifact(image_name, |artifact| artifact.push())
}

/// Sanity check: the htpasswd registry actually enforces auth. If
/// anonymous succeeded against an htpasswd registry the rest of the
/// suite would be testing nothing.
#[test]
#[ignore = "requires docker"]
#[serial]
fn push_anonymous_against_htpasswd_registry_fails() -> Result<()> {
    let _env = EnvGuard::new();
    let registry = start_htpasswd_registry();
    let port = registry.get_host_port_ipv4(5000)?;
    let image_name = ImageRef::parse(&format!("localhost:{port}/ommx-test/anon-fail:tag1"))?;
    with_test_artifact(image_name, |artifact| {
        let err = artifact
            .push()
            .expect_err("anonymous push must be rejected");
        let msg = format!("{err:#}");
        assert!(
            msg.contains("auth") || msg.contains("401") || msg.contains("unauthorized"),
            "expected an auth-related error, got: {msg}"
        );
        Ok(())
    })
}

// ──────────────────────────────────────────────────────────────────
// Tier 0: explicit env-var override
// ──────────────────────────────────────────────────────────────────

/// `OMMX_BASIC_AUTH_*` fully populated (CI's intended shape).
/// The env override should authenticate even when no docker config is
/// present.
#[test]
#[ignore = "requires docker"]
#[serial]
fn push_with_env_basic_auth() -> Result<()> {
    let _env = EnvGuard::new();
    let registry = start_htpasswd_registry();
    let port = registry.get_host_port_ipv4(5000)?;
    let host = format!("localhost:{port}");

    set_env("OMMX_BASIC_AUTH_DOMAIN", &host);
    set_env("OMMX_BASIC_AUTH_USERNAME", ALICE_USER);
    set_env("OMMX_BASIC_AUTH_PASSWORD", ALICE_PASSWORD);

    let image_name = ImageRef::parse(&format!("{host}/ommx-test/env-auth:tag1"))?;
    with_test_artifact(image_name, |artifact| artifact.push())
}

/// Env override with wrong password must fail against the registry —
/// proves the env-var path actually carries the credentials through
/// the negotiation instead of being silently dropped.
#[test]
#[ignore = "requires docker"]
#[serial]
fn push_with_wrong_env_password_fails() -> Result<()> {
    let _env = EnvGuard::new();
    let registry = start_htpasswd_registry();
    let port = registry.get_host_port_ipv4(5000)?;
    let host = format!("localhost:{port}");

    set_env("OMMX_BASIC_AUTH_DOMAIN", &host);
    set_env("OMMX_BASIC_AUTH_USERNAME", ALICE_USER);
    set_env("OMMX_BASIC_AUTH_PASSWORD", "wrong-password");

    let image_name = ImageRef::parse(&format!("{host}/ommx-test/wrong-pw:tag1"))?;
    with_test_artifact(image_name, |artifact| {
        assert!(artifact.push().is_err());
        Ok(())
    })
}

/// Env override beats docker config when both are present: the env
/// credentials must be the ones that hit the wire. We point docker
/// config at the *wrong* password and the env at the *right* one;
/// success proves env wins.
#[test]
#[ignore = "requires docker"]
#[serial]
fn env_override_beats_docker_config() -> Result<()> {
    let _env = EnvGuard::new();
    let registry = start_htpasswd_registry();
    let port = registry.get_host_port_ipv4(5000)?;
    let host = format!("localhost:{port}");

    let _docker_dir = write_docker_config(&host, ALICE_USER, "wrong-password")?;
    set_env("OMMX_BASIC_AUTH_DOMAIN", &host);
    set_env("OMMX_BASIC_AUTH_USERNAME", ALICE_USER);
    set_env("OMMX_BASIC_AUTH_PASSWORD", ALICE_PASSWORD);

    let image_name = ImageRef::parse(&format!("{host}/ommx-test/env-wins:tag1"))?;
    with_test_artifact(image_name, |artifact| artifact.push())
}

/// The `ommx` CLI's push subcommand must route through
/// `LocalArtifact::push()` for any image resident in the SQLite Local
/// Registry — not the legacy `Artifact::from_oci_dir` + ocipkg path.
/// Seed an artifact only in SQLite (no legacy disk dir, achieved by
/// using a tempdir-scoped registry root that nothing else writes to),
/// invoke the CLI, and assert the push succeeds. A regression that
/// took the legacy fallback would fail because there is no disk dir
/// for it to read.
#[cfg(feature = "cli")]
#[test]
#[ignore = "requires docker and the ommx binary"]
#[serial]
fn cli_push_routes_through_native_path() -> Result<()> {
    let _env = EnvGuard::new();
    let registry = start_anonymous_registry();
    let port = registry.get_host_port_ipv4(5000)?;
    let image_name = format!("localhost:{port}/ommx-test/cli-dispatch:tag1");

    // Seed the artifact in a fresh SQLite Local Registry root via the
    // Rust API. This deliberately does NOT call `ommx pull` (which
    // would also create a legacy disk dir), so the resulting registry
    // has the image in SQLite only.
    let dir = tempfile::tempdir()?;
    {
        let local = Arc::new(LocalRegistry::open(dir.path())?);
        let mut builder =
            ArtifactDraft::with_registry(local.as_ref(), ImageRef::parse(&image_name)?);
        builder.add_layer_bytes(
            oci_spec::image::MediaType::Other(media_types::V1_INSTANCE_MEDIA_TYPE.to_string()),
            b"cli-dispatch".to_vec(),
            HashMap::new(),
        )?;
        builder.commit()?;
    }

    // CARGO_BIN_EXE_ommx is set by Cargo whenever the `ommx` binary
    // is built alongside the integration test. The test is gated on
    // `feature = "cli"`, which is one of the binary's required
    // features, so by the time this code runs the binary is on disk.
    let bin = env!("CARGO_BIN_EXE_ommx");
    let output = std::process::Command::new(bin)
        .env("OMMX_LOCAL_REGISTRY_ROOT", dir.path())
        .args(["push", &image_name])
        .output()?;
    assert!(
        output.status.success(),
        "ommx push failed:\nstdout: {}\nstderr: {}",
        String::from_utf8_lossy(&output.stdout),
        String::from_utf8_lossy(&output.stderr),
    );
    Ok(())
}

// ──────────────────────────────────────────────────────────────────
// Archive push path
// ──────────────────────────────────────────────────────────────────

/// v3 treats `.ommx` archives as an exchange format: pushing an
/// archive means "load it into the SQLite Local Registry, then push
/// the resulting registry entry". This test exercises that two-step
/// pipeline against an anonymous registry: build, save, drop the
/// sender registry, then import into a fresh receiver registry and
/// push from there. A regression that re-introduced ocipkg's
/// `RemoteBuilder` / `auth_from_env` on the push side would fail
/// because `LocalArtifact::push` routes through the v3
/// `RemoteTransport`.
#[test]
#[ignore = "requires docker"]
#[serial]
fn push_oci_archive_via_load_then_push() -> Result<()> {
    let _env = EnvGuard::new();
    let registry = start_anonymous_registry();
    let port = registry.get_host_port_ipv4(5000)?;
    let image_name = ImageRef::parse(&format!("localhost:{port}/ommx-test/archive-push:tag1"))?;

    // Sender side: build in SQLite, save to archive on disk.
    let archive_dir = tempfile::tempdir()?;
    let archive_path = archive_dir.path().join("artifact.ommx");
    with_test_artifact(image_name.clone(), |sender_local| {
        sender_local.save(&archive_path)
    })?;

    // Receiver side: import the archive into a fresh SQLite registry,
    // then push from that registry. Matches the v3 "archive is
    // exchange format" model exactly.
    let receiver_dir = tempfile::tempdir()?;
    let receiver = Arc::new(LocalRegistry::open(receiver_dir.path())?);
    receiver.import_oci_archive(&archive_path)?;
    let receiver_local = LocalArtifact::open_in_registry(receiver.as_ref(), image_name)?;
    receiver_local.push()
}

// ──────────────────────────────────────────────────────────────────
// Pull path
// ──────────────────────────────────────────────────────────────────

/// `pull_image` against an anonymous registry: push an artifact, then
/// pull it back into a *fresh* SQLite Local Registry tempdir and
/// verify the same instance layer round-trips. End-to-end integration
/// test for the native pull pipeline. The unit test
/// `pull_image_short_circuits_when_ref_is_present_with_blob` in
/// `local_registry/tests.rs` covers the SQLite-resident fast path;
/// this one covers the network-fetch slow path that the unit test
/// stubs out.
#[test]
#[ignore = "requires docker"]
#[serial]
fn pull_image_round_trips_through_anonymous_registry() -> Result<()> {
    let _env = EnvGuard::new();
    let registry = start_anonymous_registry();
    let port = registry.get_host_port_ipv4(5000)?;
    let image_name = ImageRef::parse(&format!("localhost:{port}/ommx-test/pull-rt:tag1"))?;

    // Push from a sender-side SQLite registry.
    let expected_layer_bytes = with_test_artifact(image_name.clone(), |sender_local| {
        let layers = sender_local.layers()?;
        assert_eq!(layers.len(), 1);
        let expected_layer_bytes = sender_local.get_blob(&layers[0])?;
        sender_local.push()?;
        Ok(expected_layer_bytes)
    })?;

    // Pull into a fresh receiver-side SQLite registry tempdir.
    let receiver_dir = tempfile::tempdir()?;
    let receiver = Arc::new(LocalRegistry::open(receiver_dir.path())?);
    let outcome = receiver.pull_image(&image_name)?;
    assert_eq!(&outcome.image_name, &image_name);

    // The pulled artifact must be the same artifact: same manifest
    // digest, same single layer, same layer bytes. Failure on any of
    // these assertions means the native pull lost data on the way
    // through `RemoteTransport` + `publish_artifact_atomic`.
    let pulled = LocalArtifact::open_in_registry(receiver.as_ref(), image_name)?;
    assert_eq!(pulled.manifest_digest(), &outcome.manifest_digest);
    let layers = pulled.layers()?;
    assert_eq!(layers.len(), 1);
    let pulled_bytes = pulled.get_blob(&layers[0])?;
    assert_eq!(pulled_bytes, expected_layer_bytes);
    Ok(())
}

/// Partial env override (DOMAIN set, USERNAME/PASSWORD missing) must
/// bail at credential resolution time *before* any network request,
/// with a message naming the missing variable. This is the CI
/// misconfig case Codex flagged in the second-pass review.
#[test]
#[ignore = "requires docker"]
#[serial]
fn partial_env_override_bails_before_registry_call() -> Result<()> {
    let _env = EnvGuard::new();
    let registry = start_htpasswd_registry();
    let port = registry.get_host_port_ipv4(5000)?;
    let host = format!("localhost:{port}");

    set_env("OMMX_BASIC_AUTH_DOMAIN", &host);
    set_env("OMMX_BASIC_AUTH_USERNAME", ALICE_USER);
    // PASSWORD deliberately unset.

    let image_name = ImageRef::parse(&format!("{host}/ommx-test/partial:tag1"))?;
    with_test_artifact(image_name, |artifact| {
        let err = artifact
            .push()
            .expect_err("partial OMMX_BASIC_AUTH_* must bail");
        let msg = format!("{err:#}");
        assert!(
            msg.contains("OMMX_BASIC_AUTH_PASSWORD") && msg.contains("unset"),
            "error should name the missing var: {msg}"
        );
        Ok(())
    })
}