Skip to content

Commit ca4884f

Browse files
authored
Build context fix, bump to containerization 0.52.1. (#2415)
- `BuildFSSync.read()` and `info()` resolved a requested path, checked that the result was inside the build context, and then opened the original path. A symlink replaced between the check and the open was followed to its new target, which could be outside the context. -This change opens each requested file by walking its path one component at a time from a directory descriptor pinned on the context root, using `FileDescriptorOps` from `containerization`. Symlinks are followed only when the target is relative and stays beneath the context root. The metadata and the content returned to the builder both come from the same open descriptor. - Behavior change: a symlink with an absolute target is now rejected by `read()` and `info()`, even when the target is inside the context. Relative symlinks that stay inside the context still work. `walk()`-based transfers are unchanged. - Dependency: Requires `containerization` 0.50.0 for its `FileDescriptorOps` API enhancements. This change updates the library from 0.52.0 to 0.52.1.
1 parent 31e3a98 commit ca4884f

4 files changed

Lines changed: 236 additions & 97 deletions

File tree

‎Package.resolved‎

Lines changed: 3 additions & 3 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎Package.swift‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@ import PackageDescription
2323
let releaseVersion = ProcessInfo.processInfo.environment["RELEASE_VERSION"] ?? "0.0.0"
2424
let gitCommit = ProcessInfo.processInfo.environment["GIT_COMMIT"] ?? "unspecified"
2525
let builderShimVersion = "0.13.2"
26-
let scVersion = "0.52.0"
26+
let scVersion = "0.52.1"
2727

2828
let package = Package(
2929
name: "container",

‎Sources/ContainerBuild/BuildFSSync.swift‎

Lines changed: 113 additions & 93 deletions
Original file line numberDiff line numberDiff line change
@@ -18,9 +18,11 @@ import Collections
1818
import ContainerAPIClient
1919
import ContainerizationArchive
2020
import ContainerizationOCI
21+
import ContainerizationOS
2122
import CryptoKit
2223
import Foundation
2324
import GRPCCore
25+
import SystemPackage
2426

2527
/// Handles the `fssync` stage of the build protocol.
2628
///
@@ -50,10 +52,19 @@ import GRPCCore
5052
/// The host enforces that no file served to the builder resolves to a path
5153
/// outside the context root. If any component of a requested path is a symlink
5254
/// whose target lies outside the context root the request is rejected.
55+
///
56+
/// ``read(_:_:_:)`` and ``info(_:_:_:)`` enforce this by walking the path
57+
/// component by component from a directory descriptor pinned on the context
58+
/// root (``FileDescriptorOps``), so there is no window between checking a path
59+
/// and using it in which a symlink can be swapped in. Symlinks are followed
60+
/// only to relative targets that stay beneath the context root.
5361
/// Dockerignore filtering is **not** applied here; the shim applies it after
5462
/// unpacking the tar.
5563
actor BuildFSSync: BuildPipelineHandler {
5664
let contextDir: URL
65+
/// Descriptor for `contextDir`, opened once so every request is resolved
66+
/// relative to the same directory regardless of later changes to its path.
67+
private let contextFD: FileDescriptor
5768

5869
init(_ contextDir: URL) throws {
5970
let resolved = contextDir.resolvingSymlinksInPath()
@@ -65,6 +76,12 @@ actor BuildFSSync: BuildPipelineHandler {
6576
}
6677

6778
self.contextDir = resolved
79+
self.contextFD = try FileDescriptor.open(
80+
FilePath(resolved.cleanPath), .readOnly, options: [.directory, .closeOnExec])
81+
}
82+
83+
deinit {
84+
try? contextFD.close()
6885
}
6986

7087
nonisolated func accept(_ packet: ServerStream) throws -> Bool {
@@ -97,37 +114,31 @@ actor BuildFSSync: BuildPipelineHandler {
97114
/// Serves the content of a single context file to the shim.
98115
///
99116
/// Called only via the shim's `FS.Open()` fallback path, not during a
100-
/// normal `Walk`-based build. Rejects any path whose symlink chain resolves
101-
/// outside the context root.
117+
/// normal `Walk`-based build. The file is opened by walking its path from
118+
/// the pinned context descriptor, following only symlinks that stay beneath
119+
/// the context root; anything else is rejected with ``Error/pathIsNotChild``.
102120
func read(_ sender: AsyncStream<ClientStream>.Continuation, _ packet: BuildTransfer, _ buildID: String) async throws {
103121
let offset: UInt64 = packet.offset() ?? 0
104122
let size: Int = packet.len() ?? 0
105-
var path: URL
106-
if packet.source.hasPrefix("/") {
107-
path = URL(fileURLWithPath: packet.source).standardizedFileURL
108-
} else {
109-
path =
110-
contextDir
111-
.appendingPathComponent(packet.source)
112-
.standardizedFileURL
113-
}
114-
if !FileManager.default.fileExists(atPath: path.cleanPath) {
115-
path = URL(filePath: self.contextDir.cleanPath)
116-
path.append(components: packet.source.cleanPathComponent)
117-
}
118-
let resolved = path.resolvingSymlinksInPath()
119-
guard self.contextDir.parentOf(resolved) else {
120-
throw Error.pathIsNotChild(resolved.cleanPath, self.contextDir.cleanPath)
121-
}
122-
let data = try {
123-
if try path.isDir() {
124-
return Data()
123+
let relative = try self.relativePath(for: packet.source)
124+
125+
let (data, status) = try self.confined(packet.source) { () -> (Data, FileDescriptorOps.FileStatus) in
126+
do {
127+
let fd = try FileDescriptorOps.openFile(self.contextFD, relativePath: relative, symlinks: .followBeneath)
128+
defer { try? fd.close() }
129+
// Metadata and content both come from the descriptor, so they
130+
// describe the same inode.
131+
let status = try FileDescriptorOps.status(of: fd)
132+
let handle = FileHandle(fileDescriptor: fd.rawValue, closeOnDealloc: false)
133+
try handle.seek(toOffset: offset)
134+
let data = size == 0 ? try handle.readToEnd() : try handle.read(upToCount: size)
135+
return (data ?? Data(), status)
136+
} catch FileDescriptorOps.Error.conflict(.directory) {
137+
return (Data(), try self.entryStatus(relative))
125138
}
126-
let file = try LocalContent(path: path.standardizedFileURL)
127-
return try file.data(offset: offset, length: size) ?? Data()
128-
}()
139+
}
129140

130-
let transfer = try path.buildTransfer(id: packet.id, contextDir: self.contextDir, complete: true, data: data)
141+
let transfer = BuildTransfer(id: packet.id, source: relative.string, status: status, complete: true, data: data)
131142
var response = ClientStream()
132143
response.buildID = buildID
133144
response.buildTransfer = transfer
@@ -139,30 +150,70 @@ actor BuildFSSync: BuildPipelineHandler {
139150
/// context path.
140151
///
141152
/// Called only via the shim's `FS.Open()` fallback path, not during a
142-
/// normal `Walk`-based build. Must reject paths that escape the context root
143-
/// via symlinks for the same reasons as ``read(_:_:_:)``.
153+
/// normal `Walk`-based build. Applies the same descriptor-relative
154+
/// confinement as ``read(_:_:_:)``. The metadata is that of the entry
155+
/// itself (a symlink is not dereferenced), but a symlink is rejected unless
156+
/// it also resolves beneath the context root.
144157
func info(_ sender: AsyncStream<ClientStream>.Continuation, _ packet: BuildTransfer, _ buildID: String) async throws {
145-
let path: URL
146-
if packet.source.hasPrefix("/") {
147-
path = URL(fileURLWithPath: packet.source).standardizedFileURL
148-
} else {
149-
path =
150-
contextDir
151-
.appendingPathComponent(packet.source)
152-
.standardizedFileURL
153-
}
154-
let resolved = path.resolvingSymlinksInPath()
155-
guard self.contextDir.parentOf(resolved) else {
156-
throw Error.pathIsNotChild(resolved.cleanPath, self.contextDir.cleanPath)
158+
let relative = try self.relativePath(for: packet.source)
159+
160+
let status = try self.confined(packet.source) { () -> FileDescriptorOps.FileStatus in
161+
let status = try self.entryStatus(relative)
162+
if status.type == .symlink {
163+
do {
164+
try FileDescriptorOps.openFile(self.contextFD, relativePath: relative, symlinks: .followBeneath).close()
165+
} catch FileDescriptorOps.Error.conflict, FileDescriptorOps.Error.notFound {
166+
// The link stays beneath the context; its target is just not a regular file.
167+
}
168+
}
169+
return status
157170
}
158-
let transfer = try path.buildTransfer(id: packet.id, contextDir: self.contextDir, complete: true)
171+
172+
let transfer = BuildTransfer(id: packet.id, source: relative.string, status: status, complete: true)
159173
var response = ClientStream()
160174
response.buildID = buildID
161175
response.buildTransfer = transfer
162176
response.packetType = .buildTransfer(transfer)
163177
sender.yield(response)
164178
}
165179

180+
/// Converts a request `source` into a path relative to the context root.
181+
///
182+
/// Absolute sources inside the context are made relative to it; other
183+
/// absolute sources are taken to be relative to the context root, as the
184+
/// shim sometimes sends them. `..` is collapsed lexically and a result
185+
/// that leaves the context is rejected. This is only normalisation: the
186+
/// real confinement is done by the descriptor walk.
187+
private func relativePath(for source: String) throws -> FilePath {
188+
if source.hasPrefix("/") {
189+
let url = URL(fileURLWithPath: source).standardizedFileURL
190+
if let relative = try? url.relativeChildPath(to: self.contextDir) {
191+
return FilePath(relative)
192+
}
193+
let fallback = self.contextDir.appending(components: source.cleanPathComponent).standardizedFileURL
194+
return FilePath(try fallback.relativeChildPath(to: self.contextDir))
195+
}
196+
let url = self.contextDir.appendingPathComponent(source).standardizedFileURL
197+
return FilePath(try url.relativeChildPath(to: self.contextDir))
198+
}
199+
200+
/// Metadata of the entry at `relative` without dereferencing it.
201+
private func entryStatus(_ relative: FilePath) throws -> FileDescriptorOps.FileStatus {
202+
guard let status = try FileDescriptorOps.status(self.contextFD, relativePath: relative, symlinks: .followBeneath) else {
203+
throw FileDescriptorOps.Error.notFound
204+
}
205+
return status
206+
}
207+
208+
/// Runs `body`, reporting a refused symlink or path as ``Error/pathIsNotChild``.
209+
private func confined<T>(_ source: String, _ body: () throws -> T) throws -> T {
210+
do {
211+
return try body()
212+
} catch FileDescriptorOps.Error.cannotFollowSymlink, FileDescriptorOps.Error.invalidRelativePath {
213+
throw Error.pathIsNotChild(source, self.contextDir.cleanPath)
214+
}
215+
}
216+
166217
private struct DirEntry: Hashable {
167218
let url: URL
168219
let isDirectory: Bool
@@ -497,6 +548,27 @@ extension BuildTransfer {
497548
}
498549
}
499550

551+
extension BuildTransfer {
552+
fileprivate init(id: String, source: String, status: FileDescriptorOps.FileStatus, complete: Bool, data: Data = Data()) {
553+
self.init(
554+
id: id,
555+
source: source,
556+
complete: complete,
557+
isDir: status.type == .directory,
558+
metadata: [
559+
"os": "linux",
560+
"stage": "fssync",
561+
"mode": String(status.permissions.rawValue),
562+
"size": String(status.size),
563+
"modified_at": Date(timeIntervalSince1970: TimeInterval(status.modificationSeconds)).rfc3339(),
564+
"uid": String(status.userID),
565+
"gid": String(status.groupID),
566+
],
567+
data: data
568+
)
569+
}
570+
}
571+
500572
extension URL {
501573
fileprivate func size() throws -> UInt64 {
502574
let attrs = try FileManager.default.attributesOfItem(atPath: self.cleanPath)
@@ -514,65 +586,13 @@ extension URL {
514586
throw BuildFSSync.Error.couldNotDetermineModTime(self.cleanPath)
515587
}
516588

517-
fileprivate func isDir() throws -> Bool {
518-
let attrs = try FileManager.default.attributesOfItem(atPath: self.cleanPath)
519-
guard let t = attrs[.type] as? FileAttributeType, t == .typeDirectory else {
520-
return false
521-
}
522-
return true
523-
}
524-
525589
fileprivate func mode() throws -> UInt32 {
526590
let attrs = try FileManager.default.attributesOfItem(atPath: self.cleanPath)
527591
if let mode = attrs[FileAttributeKey.posixPermissions] as? NSNumber {
528592
return mode.uint32Value
529593
}
530594
throw BuildFSSync.Error.couldNotDetermineFileMode(self.cleanPath)
531595
}
532-
533-
fileprivate func uid() throws -> UInt32 {
534-
let attrs = try FileManager.default.attributesOfItem(atPath: self.cleanPath)
535-
if let uid = attrs[.ownerAccountID] as? UInt32 {
536-
return uid
537-
}
538-
throw BuildFSSync.Error.couldNotDetermineUID(self.cleanPath)
539-
}
540-
541-
fileprivate func gid() throws -> UInt32 {
542-
let attrs = try FileManager.default.attributesOfItem(atPath: self.cleanPath)
543-
if let gid = attrs[.groupOwnerAccountID] as? UInt32 {
544-
return gid
545-
}
546-
throw BuildFSSync.Error.couldNotDetermineGID(self.cleanPath)
547-
}
548-
549-
fileprivate func buildTransfer(
550-
id: String,
551-
contextDir: URL? = nil,
552-
complete: Bool = false,
553-
data: Data = Data()
554-
) throws -> BuildTransfer {
555-
let p = try {
556-
if let contextDir { return try self.relativeChildPath(to: contextDir) }
557-
return self.cleanPath
558-
}()
559-
return BuildTransfer(
560-
id: id,
561-
source: String(p),
562-
complete: complete,
563-
isDir: try self.isDir(),
564-
metadata: [
565-
"os": "linux",
566-
"stage": "fssync",
567-
"mode": String(try self.mode()),
568-
"size": String(try self.size()),
569-
"modified_at": try self.modTime(),
570-
"uid": String(try self.uid()),
571-
"gid": String(try self.gid()),
572-
],
573-
data: data
574-
)
575-
}
576596
}
577597

578598
extension Date {

0 commit comments

Comments
 (0)