Skip to main content
coreydaley.dev

Unit tests that guard security settings in vendored C code

Purrchiver vendors its C libraries: libarchive, liblzma, and a few others are compiled from source inside Swift packages rather than linked from the system. That means I can patch them, and I have. It also means every one of those patches is one careless update away from disappearing. Copy a new upstream release over the old directory, build, run the tests, everything passes, and a security fix you made a month ago is gone. Nothing fails, because the change was about what the code doesn’t do.

So I added tests that read the vendored source directly and fail if a specific setting goes missing. They’re crude. They’re also the only thing that would catch this kind of regression.

The pattern

Swift Testing (or XCTest) can find files relative to the test’s own source file with #filePath, which works the same in Xcode, from xcodebuild, and in CI:

private func vendoredSource(_ relative: String,
                            file: String = #filePath) throws -> String {
    let root = URL(fileURLWithPath: file)
        .deletingLastPathComponent()   // MyKitTests/
        .deletingLastPathComponent()   // Tests/
        .deletingLastPathComponent()   // package root
    return try String(contentsOf: root.appending(path: relative),
                      encoding: .utf8)
}

Each test then checks for, or against, one specific string, with a failure message that explains why it matters. The message is the most important part: the person who sees it is usually updating the library a long time later and has never heard of the patch.

1. XAR: keep libxml2 off the network

XAR is the container format inside .pkg installers, and Purrchiver reads it through libarchive. A XAR archive’s table of contents is XML, and libarchive parses it with libxml2. The vendored reader passed 0 for the parser options, which leaves network behavior up to libxml2’s defaults. XML can declare external entities that point at URLs, which is how XXE attacks work, and a XAR’s table of contents comes from whoever made the archive. I didn’t want whether the parser might try a fetch to depend on a library default.

In May I patched the call to pass XML_PARSE_NONET, which tells libxml2 never to fetch anything over the network:

reader = xmlReaderForIO(xml2_read_cb, xml2_close_cb, a, NULL, NULL,
    XML_PARSE_NONET);

Purrchiver has no network entitlement, so the sandbox would refuse the request anyway. I still don’t want a parser in my app that tries.

The test is one assertion:

@Test func xarSetsNoNet() throws {
    let src = try vendoredSource(
        "Sources/Clibarchive/archive_read_support_format_xar.c")
    #expect(src.contains("XML_PARSE_NONET"),
            "The XAR reader must keep XML_PARSE_NONET on the libxml2 parse to block external-entity fetches. A libarchive update may have dropped it.")
}

2. The .crypto engine must not log paths with NSLog

Purrchiver opens .crypto files from MacPaw’s Encrypto using MacPaw’s Objective-C engine, vendored. That engine reported errors with NSLog, and some messages included the path of the file being extracted and its attribute dictionary.

NSLog writes to the unified log with the arguments visible, so those paths were recorded in the clear, where they could also be picked up when a user exports logs from inside the app.

I switched the 13 call sites to os_log_error and marked the path and attribute arguments %{private}@, so the unified log stores <private> instead. Error codes stay public, since they’re useful and identify nothing:

os_log_error(OS_LOG_DEFAULT,
    "setAttributes failed for item %{private}@. Attributes %{private}@.",
    item.path, item.attributes);

There’s no reasonable way for a unit test to ask the unified log “did a clear path get stored?” So the test pins the one thing that guarantees it: no NSLog( anywhere in the engine’s .m and .mm files.

let files = try FileManager.default
    .contentsOfDirectory(at: engineDir, includingPropertiesForKeys: nil)
    .filter { ["m", "mm"].contains($0.pathExtension) }
#expect(!files.isEmpty, "Expected engine sources at \(engineDir.path)")
for url in files {
    let source = try String(contentsOf: url, encoding: .utf8)
    #expect(!source.contains("NSLog("),
            "\(url.lastPathComponent) reintroduced NSLog(. Use os_log_error with %{private}@ for paths.")
}

The !files.isEmpty line matters. If the directory moves, a loop over zero files passes, and the test would go on reporting green while checking nothing.

The third guard isn’t about an attack. It’s about App Review, which rejected Purrchiver 1.0 under Guideline 2.5.1 because the package linked the liblzma macOS ships, a library with no public headers. The fix compiles liblzma from source, and putting the system link back would be a one-line Package.swift change, so the test reads Package.swift:

let codeOnly = manifest
    .split(separator: "\n", omittingEmptySubsequences: false)
    .filter { !$0.trimmingCharacters(in: .whitespaces).hasPrefix("//") }
    .joined(separator: "\n")
    .replacingOccurrences(of: " ", with: "")
#expect(!codeOnly.contains(".linkedLibrary(\"lzma\")"))

The interesting part is the comment strip. The manifest has a comment explaining why the system link was removed, and that comment names the call. Without the strip, the test would fail on its own documentation.

What these tests can’t do

A source-text check is a proxy. XML_PARSE_NONET could appear in a comment while the call passes 0. A future engine could log through something other than NSLog. These tests don’t prove the behavior. They make the one likeliest regression, an update that silently reverts a patch, fail loudly with an explanation attached.

That’s worth a lot for code I didn’t write and update rarely. Next time I update one of these libraries, I’ll have forgotten these patches exist, and the tests won’t have.

What to take away

  • Every local patch to vendored code deserves a test, even a one-line one.
  • Write the failure message for whoever updates the library next.
  • Guard against the test passing vacuously: check that the files exist and aren’t empty.
  • Strip comments before matching, or your own documentation will trip the test.

Related posts