`--filter` silently ignores unknown keys: `images -f dangling=true` returns every image
mocker version: 0.9.7 (Homebrew) — macOS 27, container 1.5.0, arm64; reproduced on 0.9.6 and again on 0.9.7. Code references are against main @ 4402015.
Summary
images, ps, volume ls and network ls drop a --filter key they do not know in a default: break and return the unfiltered list. Docker rejects it (invalid filter 'foo'). The difference is destructive in the most common cleanup idiom:
docker rmi $(docker images -qf dangling=true) # mocker: removes every image
reference= also never matches a pulled image, because the repository column holds docker.io/library/alpine and the comparison is exact.
Reproduction
$ mocker images -q | wc -l
4
$ mocker images -q -f dangling=true | wc -l
4 # Docker: 0 (there are no dangling images)
$ mocker images -q -f foo=bar | wc -l
4 # Docker: Error response from daemon: invalid filter 'foo'
$ mocker images -q -f reference=alpine | wc -l
0 # Docker: 1
Same pattern: Sources/Mocker/Commands/ImageListOptions.swift:93, ContainerListOptions.swift:107, Volume.swift:80, Network.swift:120.
Proposed behaviour (what the branch does)
Kept deliberately small:
- A 20-line
ListFilter.parseshared by the four list commands: a key the command does not evaluate isinvalid filter 'x', a filter without=is a format error. The fourswitches stay as they are, minus the silentdefault. images -f dangling=trueis empty: the store names every image (an untagged build gets a UUID), and empty is what the cleanup idiom needs.images -f reference=also matches the familiar name (alpinefordocker.io/library/alpine), bare or with:tag.
After:
$ mocker images -q -f dangling=true | wc -l
0
$ mocker images -q -f reference=alpine | wc -l
1
$ mocker images -f foo=bar
Error: Error response from daemon: invalid filter 'foo'
$ mocker ps -f volume=data
Error: Error response from daemon: invalid filter 'volume'
Left out on purpose, to keep this one small (happy to follow up on any of them): reference globs, label on volume ls/network ls, ps -f status=exited not matching containers stored as stopped, same-key filters combining with AND (Docker ORs), and network prune --filter, which is parsed and ignored (Network.swift:242) and therefore prunes everything — the same class of bug.
A tested fix is on my fork, branch fix/list-filters (compare); the diff is below. I'm not fluent in Swift and don't want to pile work on you, so I'd rather agree first: say the word and I'll open it as a PR, or take it from here yourself if you prefer — either is fine with me. I'm filing the related reports (cp, exec, compose platform, short image IDs) the same way.
Proposed fix: git diff main...fix/list-filters
diff --git a/Sources/Mocker/Commands/ContainerListOptions.swift b/Sources/Mocker/Commands/ContainerListOptions.swift
index 9105a00..82c792a 100644
--- a/Sources/Mocker/Commands/ContainerListOptions.swift
+++ b/Sources/Mocker/Commands/ContainerListOptions.swift
@@ -33,7 +33,7 @@ struct ContainerListOptions: ParsableArguments {
let engine = try ContainerEngine(config: config)
// --latest / --last include all states regardless of --all (matches Docker).
let includeAll = all || latest || last != nil
- var containers = filtered(try await engine.list(all: includeAll))
+ var containers = try filtered(try await engine.list(all: includeAll))
if latest {
containers = Array(containers.prefix(1))
@@ -81,14 +81,11 @@ struct ContainerListOptions: ParsableArguments {
}
/// Apply Docker-style `--filter` predicates. Pure; safe to unit-test.
- func filtered(_ containers: [ContainerInfo]) -> [ContainerInfo] {
+ func filtered(_ containers: [ContainerInfo]) throws -> [ContainerInfo] {
var containers = containers
- for f in filter {
- let parts = f.split(separator: "=", maxSplits: 1)
- guard parts.count == 2 else { continue }
- let key = String(parts[0])
- let value = String(parts[1])
- switch key {
+ for f in try ListFilter.parse(filter, supported: ["name", "status", "id", "label", "ancestor"]) {
+ let value = f.value
+ switch f.key {
case "name":
containers = containers.filter { $0.name.contains(value) }
case "status":
@@ -105,7 +102,7 @@ struct ContainerListOptions: ParsableArguments {
case "ancestor":
containers = containers.filter { $0.image == value || $0.image.hasPrefix(value) }
default:
- break
+ break // unreachable: `parse` rejected every other key
}
}
return containers
diff --git a/Sources/Mocker/Commands/ImageListOptions.swift b/Sources/Mocker/Commands/ImageListOptions.swift
index 7f7beda..fa6361e 100644
--- a/Sources/Mocker/Commands/ImageListOptions.swift
+++ b/Sources/Mocker/Commands/ImageListOptions.swift
@@ -29,7 +29,7 @@ struct ImageListOptions: ParsableArguments {
// up when ImageManager surfaces that data.
let config = MockerConfig()
let manager = try ImageManager(config: config)
- let images = filtered(try await manager.list())
+ let images = try filtered(try await manager.list())
if quiet {
for image in images {
@@ -72,28 +72,42 @@ struct ImageListOptions: ParsableArguments {
}
/// Apply Docker-style `--filter` predicates. Pure; safe to unit-test.
- func filtered(_ images: [ImageInfo]) -> [ImageInfo] {
+ func filtered(_ images: [ImageInfo]) throws -> [ImageInfo] {
var images = images
- for f in filter {
- let parts = f.split(separator: "=", maxSplits: 1)
- guard parts.count == 2 else { continue }
- let key = String(parts[0])
- let value = String(parts[1])
- switch key {
+ for f in try ListFilter.parse(filter, supported: ["dangling", "reference", "label"]) {
+ switch f.key {
+ case "dangling":
+ // The store names every image (an untagged build gets a UUID), so nothing
+ // is dangling — which is what `rmi $(images -qf dangling=true)` needs.
+ if f.value == "true" { images = [] }
case "reference":
- // Docker matches a bare repo (any tag) or an exact repo:tag. Glob (`*`) is not supported.
- images = images.filter { $0.repository == value || $0.reference == value }
+ // Docker matches a bare repo (any tag) or an exact repo:tag, by the name
+ // it shows: a pulled `alpine` is stored as `docker.io/library/alpine`.
+ // Glob (`*`) is not supported.
+ images = images.filter { image in
+ [image.repository, Self.familiar(image.repository)].contains {
+ $0 == f.value || "\($0):\(image.tag)" == f.value
+ }
+ }
case "label":
- let labelParts = value.split(separator: "=", maxSplits: 1)
+ let labelParts = f.value.split(separator: "=", maxSplits: 1)
if labelParts.count == 2 {
images = images.filter { $0.labels[String(labelParts[0])] == String(labelParts[1]) }
} else {
- images = images.filter { $0.labels[value] != nil }
+ images = images.filter { $0.labels[f.value] != nil }
}
default:
- break
+ break // unreachable: `parse` rejected every other key
}
}
return images
}
+
+ /// `alpine` for `docker.io/library/alpine`, `acme/app` for `docker.io/acme/app`.
+ private static func familiar(_ repository: String) -> String {
+ for prefix in ["docker.io/library/", "docker.io/"] where repository.hasPrefix(prefix) {
+ return String(repository.dropFirst(prefix.count))
+ }
+ return repository
+ }
}
diff --git a/Sources/Mocker/Commands/ListFilter.swift b/Sources/Mocker/Commands/ListFilter.swift
new file mode 100644
index 0000000..6504d81
--- /dev/null
+++ b/Sources/Mocker/Commands/ListFilter.swift
@@ -0,0 +1,24 @@
+import MockerKit
+
+/// A `--filter key=value` whose key the command knows how to evaluate.
+///
+/// Docker rejects a key it does not know (`invalid filter 'foo'`). Ignoring it instead
+/// returned the unfiltered list, which turned `images -f dangling=true` into "every
+/// image" and the usual cleanup `rmi $(images -qf dangling=true)` into "delete everything".
+struct ListFilter {
+ let key: String
+ let value: String
+
+ static func parse(_ raw: [String], supported: Set<String>) throws -> [ListFilter] {
+ try raw.map { filter in
+ let parts = filter.split(separator: "=", maxSplits: 1)
+ guard parts.count == 2 else {
+ throw MockerError.operationFailed("bad format of filter (expected name=value): \(filter)")
+ }
+ guard supported.contains(String(parts[0])) else {
+ throw MockerError.operationFailed("invalid filter '\(parts[0])'")
+ }
+ return ListFilter(key: String(parts[0]), value: String(parts[1]))
+ }
+ }
+}
diff --git a/Sources/Mocker/Commands/Network.swift b/Sources/Mocker/Commands/Network.swift
index bced543..8eee84e 100644
--- a/Sources/Mocker/Commands/Network.swift
+++ b/Sources/Mocker/Commands/Network.swift
@@ -109,15 +109,12 @@ struct NetworkList: AsyncParsableCommand {
let manager = try NetworkManager(config: config)
var networks = try await manager.list()
- for f in filter {
- let parts = f.split(separator: "=", maxSplits: 1)
- guard parts.count == 2 else { continue }
- let key = String(parts[0]), value = String(parts[1])
- switch key {
- case "name": networks = networks.filter { $0.name.contains(value) }
- case "driver": networks = networks.filter { $0.driver == value }
- case "id": networks = networks.filter { $0.id.hasPrefix(value) }
- default: break
+ for f in try ListFilter.parse(filter, supported: ["name", "driver", "id"]) {
+ switch f.key {
+ case "name": networks = networks.filter { $0.name.contains(f.value) }
+ case "driver": networks = networks.filter { $0.driver == f.value }
+ case "id": networks = networks.filter { $0.id.hasPrefix(f.value) }
+ default: break // unreachable: `parse` rejected every other key
}
}
diff --git a/Sources/Mocker/Commands/Volume.swift b/Sources/Mocker/Commands/Volume.swift
index 7ba882d..57f3b35 100644
--- a/Sources/Mocker/Commands/Volume.swift
+++ b/Sources/Mocker/Commands/Volume.swift
@@ -70,14 +70,11 @@ struct VolumeList: AsyncParsableCommand {
let manager = try VolumeManager(config: config)
var volumes = try await manager.list()
- for f in filter {
- let parts = f.split(separator: "=", maxSplits: 1)
- guard parts.count == 2 else { continue }
- let key = String(parts[0]), value = String(parts[1])
- switch key {
- case "name": volumes = volumes.filter { $0.name.contains(value) }
- case "driver": volumes = volumes.filter { $0.driver == value }
- default: break
+ for f in try ListFilter.parse(filter, supported: ["name", "driver"]) {
+ switch f.key {
+ case "name": volumes = volumes.filter { $0.name.contains(f.value) }
+ case "driver": volumes = volumes.filter { $0.driver == f.value }
+ default: break // unreachable: `parse` rejected every other key
}
}
diff --git a/Tests/MockerTests/CLITests.swift b/Tests/MockerTests/CLITests.swift
index 6752278..f74739a 100644
--- a/Tests/MockerTests/CLITests.swift
+++ b/Tests/MockerTests/CLITests.swift
@@ -282,10 +282,10 @@ struct CLITests {
ImageInfo(id: "b", repository: "redis", tag: "7", labels: ["env": "dev"]),
]
let byRef = try ImageLs.parse(["--filter", "reference=nginx"]).options
- #expect(byRef.filtered(images).map(\.id) == ["a"])
+ #expect(try byRef.filtered(images).map(\.id) == ["a"])
let byLabel = try ImageLs.parse(["--filter", "label=env=dev"]).options
- #expect(byLabel.filtered(images).map(\.id) == ["b"])
+ #expect(try byLabel.filtered(images).map(\.id) == ["b"])
}
@Test("image ls --format substitutes repository, tag and labels")
@@ -318,10 +318,10 @@ struct CLITests {
ContainerInfo(id: "b", name: "db", image: "redis", state: .exited, status: "Exited", created: .distantPast),
]
let byStatus = try ContainerLs.parse(["--filter", "status=running"]).options
- #expect(byStatus.filtered(containers).map(\.id) == ["a"])
+ #expect(try byStatus.filtered(containers).map(\.id) == ["a"])
let byName = try ContainerLs.parse(["--filter", "name=db"]).options
- #expect(byName.filtered(containers).map(\.id) == ["b"])
+ #expect(try byName.filtered(containers).map(\.id) == ["b"])
}
@Test("Build -f flag parses to the provided path")
diff --git a/Tests/MockerTests/ListFilterTests.swift b/Tests/MockerTests/ListFilterTests.swift
new file mode 100644
index 0000000..4892346
--- /dev/null
+++ b/Tests/MockerTests/ListFilterTests.swift
@@ -0,0 +1,40 @@
+import Testing
+import MockerKit
+@testable import Mocker
+
+/// `--filter` must behave like Docker's: an unknown key is an error, not a no-op.
+/// Ignoring `dangling=true` made `rmi $(images -qf dangling=true)` delete every image.
+@Suite("List filters")
+struct ListFilterTests {
+
+ private let images = [
+ ImageInfo(id: "a", repository: "docker.io/library/alpine", tag: "3.20"),
+ ImageInfo(id: "b", repository: "docker.io/library/alpine", tag: "latest"),
+ ImageInfo(id: "c", repository: "mybuild", tag: "latest"),
+ ]
+
+ private func imageIDs(_ filter: String) throws -> [String] {
+ try ImageLs.parse(["--filter", filter]).options.filtered(images).map(\.id)
+ }
+
+ @Test("an unknown key or a filter without `=` is rejected")
+ func unknownKeyRejected() {
+ #expect(throws: MockerError.self) { try imageIDs("foo=bar") }
+ #expect(throws: MockerError.self) { try imageIDs("dangling") }
+ #expect(throws: MockerError.self) { try ContainerLs.parse(["--filter", "foo=bar"]).options.filtered([]) }
+ }
+
+ @Test("images: dangling=true is empty, since the store names every image")
+ func danglingTrueIsEmpty() throws {
+ #expect(try imageIDs("dangling=true").isEmpty)
+ #expect(try imageIDs("dangling=false").count == 3)
+ }
+
+ @Test("images: reference matches a pulled image by its familiar name")
+ func referenceMatchesFamiliarName() throws {
+ #expect(try imageIDs("reference=alpine") == ["a", "b"])
+ #expect(try imageIDs("reference=alpine:3.20") == ["a"])
+ #expect(try imageIDs("reference=docker.io/library/alpine:latest") == ["b"])
+ #expect(try imageIDs("reference=mybuild") == ["c"])
+ }
+}
Thanks @BluPix, these were excellent reports, and the fork branches made it easy. I took all six commits unchanged (your authorship) into #109 and ran each repro on container 1.5.0, before and after.
A few follow-ups on top, mostly where two of the fixes met:
images -f dangling=truenow selects exactly whatimage pruneremoves (the UUID-named untagged builds), and a value other thantrue/1/false/0is an error:dangling=1used to fall through to every image.- prune keeps any image an existing container uses in both modes. The dangling path skipped that check, so an untagged build a stopped container was created from got deleted. In-use also reads
container ls --all, since the runtime happily deletes an image a stoppedcontainer runcontainer still needs. exec -it shprinted a prompt but never read input:Processputs the child in its own process group.execnow uses the sameposix_spawnpath as attachedrun.- a
build:service withplatform:is built for that platform too. compose cprefuses service to service (also under--dry-run),compose attachkeeps the exit status,network prune --filteris rejected.
Left as you described: reference globs, until=, ps -f status=exited vs stopped, and run -v /path not creating an anonymous volume. Also still open: mocker run <12-hex id> does not resolve an image ID (rmi, tag, inspect and history do).
Shipped in 0.9.8 (ref #109), checked with the Homebrew build on container 1.5.0. Thanks @BluPix!
Thanks — upgraded to 0.9.8 and re-ran the reproduction steps from all six issues: all good.