-
Notifications
You must be signed in to change notification settings - Fork 149
Expand file tree
/
Copy pathFileOperationsTestWindows.swift
More file actions
375 lines (321 loc) · 11.9 KB
/
Copy pathFileOperationsTestWindows.swift
File metadata and controls
375 lines (321 loc) · 11.9 KB
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
/*
This source file is part of the Swift System open source project
Copyright (c) 2024 Apple Inc. and the Swift System project authors
Licensed under Apache License v2.0 with Runtime Library Exception
See https://swift.org/LICENSE.txt for license information
*/
import XCTest
#if os(Windows)
#if SYSTEM_PACKAGE
@testable import SystemPackage
#else
@testable import System
#endif
import WinSDK
import ucrt
private let FILE_APPEND_DATA = DWORD(WinSDK.FILE_APPEND_DATA)
private let FILE_EXECUTE = DWORD(WinSDK.FILE_EXECUTE)
private let FILE_READ_ATTRIBUTES = DWORD(WinSDK.FILE_READ_ATTRIBUTES)
@available(iOS 8, *)
final class FileOperationsTestWindows: XCTestCase {
private let r = ACCESS_MASK(
FILE_READ_ATTRIBUTES
| FILE_READ_DATA
| FILE_READ_EA
| STANDARD_RIGHTS_READ
| SYNCHRONIZE
)
private let w = ACCESS_MASK(
FILE_APPEND_DATA
| FILE_WRITE_ATTRIBUTES
| FILE_WRITE_DATA
| FILE_WRITE_EA
| STANDARD_RIGHTS_WRITE
| SYNCHRONIZE
)
private let x = ACCESS_MASK(
FILE_EXECUTE
| FILE_READ_ATTRIBUTES
| STANDARD_RIGHTS_EXECUTE
| SYNCHRONIZE
)
private let none = ACCESS_MASK(0)
private struct Test {
var permissions: CModeT
var ownerAccess: ACCESS_MASK
var groupAccess: ACCESS_MASK
var otherAccess: ACCESS_MASK
init(_ permissions: CModeT,
_ ownerAccess: ACCESS_MASK,
_ groupAccess: ACCESS_MASK,
_ otherAccess: ACCESS_MASK) {
self.permissions = permissions
self.ownerAccess = ownerAccess
self.groupAccess = groupAccess
self.otherAccess = otherAccess
}
}
/// Retrieve the owner, group and other access masks for a given file.
///
/// - Parameters:
/// - path: The path to the file to inspect
/// - Returns: A tuple of ACCESS_MASK values.
func getAccessMasks(
path: FilePath
) -> (ACCESS_MASK, ACCESS_MASK, ACCESS_MASK) {
var SIDAuthWorld = SID_IDENTIFIER_AUTHORITY(Value: (0, 0, 0, 0, 0, 1))
var psidEveryone: PSID? = nil
XCTAssert(AllocateAndInitializeSid(&SIDAuthWorld, 1,
SECURITY_WORLD_RID,
0, 0, 0, 0, 0, 0, 0,
&psidEveryone))
defer {
FreeSid(psidEveryone)
}
var everyone = TRUSTEE_W(
pMultipleTrustee: nil,
MultipleTrusteeOperation: NO_MULTIPLE_TRUSTEE,
TrusteeForm: TRUSTEE_IS_SID,
TrusteeType: TRUSTEE_IS_GROUP,
ptstrName:
psidEveryone!.assumingMemoryBound(to: CInterop.PlatformChar.self)
)
return path.withPlatformString { objectName in
var psidOwner: PSID? = nil
var psidGroup: PSID? = nil
var pDacl: PACL? = nil
var pSD: PSECURITY_DESCRIPTOR? = nil
XCTAssertEqual(GetNamedSecurityInfoW(
objectName,
SE_FILE_OBJECT,
SECURITY_INFORMATION(
DACL_SECURITY_INFORMATION
| GROUP_SECURITY_INFORMATION
| OWNER_SECURITY_INFORMATION
),
&psidOwner,
&psidGroup,
&pDacl,
nil,
&pSD), ERROR_SUCCESS)
defer {
LocalFree(pSD)
}
var owner = TRUSTEE_W(
pMultipleTrustee: nil,
MultipleTrusteeOperation: NO_MULTIPLE_TRUSTEE,
TrusteeForm: TRUSTEE_IS_SID,
TrusteeType: TRUSTEE_IS_USER,
ptstrName:
psidOwner!.assumingMemoryBound(to: CInterop.PlatformChar.self)
)
var group = TRUSTEE_W(
pMultipleTrustee: nil,
MultipleTrusteeOperation: NO_MULTIPLE_TRUSTEE,
TrusteeForm: TRUSTEE_IS_SID,
TrusteeType: TRUSTEE_IS_GROUP,
ptstrName:
psidGroup!.assumingMemoryBound(to: CInterop.PlatformChar.self)
)
var ownerAccess = ACCESS_MASK(0)
var groupAccess = ACCESS_MASK(0)
var otherAccess = ACCESS_MASK(0)
XCTAssertEqual(GetEffectiveRightsFromAclW(
pDacl,
&owner,
&ownerAccess), ERROR_SUCCESS)
XCTAssertEqual(GetEffectiveRightsFromAclW(
pDacl,
&group,
&groupAccess), ERROR_SUCCESS)
XCTAssertEqual(GetEffectiveRightsFromAclW(
pDacl,
&everyone,
&otherAccess), ERROR_SUCCESS)
return (ownerAccess, groupAccess, otherAccess)
}
}
private func runTests(_ tests: [Test], at path: FilePath) throws {
for test in tests {
let octal = String(test.permissions, radix: 8)
let testPath = path.appending("test-\(octal).txt")
let fd = try FileDescriptor.open(
testPath,
.readWrite,
options: [.create, .truncate],
permissions: FilePermissions(rawValue: test.permissions)
)
_ = try fd.closeAfter {
try fd.writeAll("Hello World".utf8)
}
let (ownerAccess, groupAccess, otherAccess)
= getAccessMasks(path: testPath)
XCTAssertEqual(ownerAccess, test.ownerAccess)
XCTAssertEqual(groupAccess, test.groupAccess)
XCTAssertEqual(otherAccess, test.otherAccess)
}
}
/// Test that the umask works properly
func testUmask() throws {
// See https://learn.microsoft.com/en-us/virtualization/windowscontainers/manage-containers/persistent-storage#permissions
try XCTSkipIf(NSUserName() == "ContainerAdministrator", "containers use a different permission model")
// Default mask should be 0o022
XCTAssertEqual(FilePermissions.creationMask, [.groupWrite, .otherWrite])
try withTemporaryFilePath(basename: "testUmask") { path in
let tests = [
Test(0o000, none, none, none),
Test(0o700, r|w|x, none, none),
Test(0o770, r|w|x, r|x, none),
Test(0o777, r|w|x, r|x, r|x)
]
try runTests(tests, at: path)
}
try FilePermissions.withCreationMask([.groupWrite, .groupExecute,
.otherWrite, .otherExecute]) {
try withTemporaryFilePath(basename: "testUmask") { path in
let tests = [
Test(0o000, none, none, none),
Test(0o700, r|w|x, none, none),
Test(0o770, r|w|x, r, none),
Test(0o777, r|w|x, r, r)
]
try runTests(tests, at: path)
}
}
}
/// Test that setting permissions on a file works as expected
func testPermissions() throws {
// See https://learn.microsoft.com/en-us/virtualization/windowscontainers/manage-containers/persistent-storage#permissions
try XCTSkipIf(NSUserName() == "ContainerAdministrator", "containers use a different permission model")
try FilePermissions.withCreationMask([]) {
try withTemporaryFilePath(basename: "testPermissions") { path in
let tests = [
Test(0o000, none, none, none),
Test(0o400, r, none, none),
Test(0o200, w, none, none),
Test(0o100, x, none, none),
Test(0o040, none, r, none),
Test(0o020, none, w, none),
Test(0o010, none, x, none),
Test(0o004, none, none, r),
Test(0o002, none, none, w),
Test(0o001, none, none, x),
Test(0o700, r|w|x, none, none),
Test(0o770, r|w|x, r|w|x, none),
Test(0o777, r|w|x, r|w|x, r|w|x),
Test(0o755, r|w|x, r|x, r|x),
Test(0o644, r|w, r, r),
Test(0o007, none, none, r|w|x),
Test(0o070, none, r|w|x, none),
Test(0o077, none, r|w|x, r|w|x),
]
try runTests(tests, at: path)
}
}
}
/// Test that buffer sizes exceeding DWORD.max (4GB) are properly rejected
func testBufferSizeLimit() throws {
try withTemporaryFilePath(basename: "testBufferSizeLimit") { path in
let fd = try FileDescriptor.open(
path.appending("test.txt"),
.readWrite,
options: [.create, .truncate],
permissions: .ownerReadWrite
)
defer { try? fd.close() }
// Write some data first
try fd.writeAll("test data".utf8)
// Allocate a small buffer for testing
let buffer = UnsafeMutableRawBufferPointer.allocate(byteCount: 1024, alignment: 1)
defer { buffer.deallocate() }
// Test that a count exceeding DWORD.max (UInt32.max = 4,294,967,295) returns EINVAL
// We use a buffer pointer but pass a count > DWORD.max
let oversizedCount = Int(DWORD.max) + 1
let oversizedBuffer = UnsafeMutableRawBufferPointer(
start: buffer.baseAddress,
count: oversizedCount
)
// pread should fail with EINVAL
do {
_ = try fd.read(fromAbsoluteOffset: 0, into: oversizedBuffer)
XCTFail("Expected EINVAL for buffer size exceeding DWORD.max")
} catch let err as Errno {
XCTAssertEqual(err, .invalidArgument, "Expected EINVAL, got \(err)")
}
// pwrite should also fail with EINVAL
do {
_ = try fd.write(toAbsoluteOffset: 0, UnsafeRawBufferPointer(oversizedBuffer))
XCTFail("Expected EINVAL for buffer size exceeding DWORD.max")
} catch let err as Errno {
XCTAssertEqual(err, .invalidArgument, "Expected EINVAL, got \(err)")
}
// Verify that exactly DWORD.max works (if we had a buffer that large)
// We can't easily test this without allocating 4GB, but the boundary is correct
}
}
/// The sequential read/write adapters must reject a byte count exceeding
/// DWORD.max with EINVAL, matching the positioned pread/pwrite guard.
/// Without the guard, `numericCast(count)` into the CRT's unsigned int would
/// trap. We pass an oversized *count* over a small allocation; the guard
/// rejects it before any bytes are touched.
func testSequentialBufferSizeLimit() throws {
try withTemporaryFilePath(basename: "testSequentialBufferSizeLimit") { path in
let fd = try FileDescriptor.open(
path.appending("test.txt"),
.readWrite,
options: [.create, .truncate],
permissions: .ownerReadWrite
)
defer { try? fd.close() }
try fd.writeAll("test data".utf8)
let buffer = UnsafeMutableRawBufferPointer.allocate(byteCount: 1024, alignment: 1)
defer { buffer.deallocate() }
let oversizedCount = Int(DWORD.max) + 1
let oversizedBuffer = UnsafeMutableRawBufferPointer(
start: buffer.baseAddress,
count: oversizedCount
)
do {
_ = try fd.read(into: oversizedBuffer)
XCTFail("Expected EINVAL for buffer size exceeding DWORD.max")
} catch let err as Errno {
XCTAssertEqual(err, .invalidArgument, "Expected EINVAL, got \(err)")
}
do {
_ = try fd.write(UnsafeRawBufferPointer(oversizedBuffer))
XCTFail("Expected EINVAL for buffer size exceeding DWORD.max")
} catch let err as Errno {
XCTAssertEqual(err, .invalidArgument, "Expected EINVAL, got \(err)")
}
}
}
func testCloseOnExecOpenOption() throws {
try withTemporaryFilePath(basename: "testCloseOnExec") { path in
func hasInheritFlag(of fd: FileDescriptor) throws -> Bool {
let osfHandle = _get_osfhandle(fd.rawValue)
let handle = try XCTUnwrap(HANDLE(bitPattern: osfHandle))
var flags: DWORD = 0
XCTAssertTrue(GetHandleInformation(handle, &flags))
return flags & DWORD(HANDLE_FLAG_INHERIT) == DWORD(HANDLE_FLAG_INHERIT)
}
var fd: FileDescriptor
fd = try FileDescriptor.open(
path.appending("wontinherit.txt"), .readWrite,
options: [.create, .truncate, .closeOnExec],
permissions: .ownerReadWrite
)
try fd.closeAfter {
XCTAssertEqual(try hasInheritFlag(of: fd), false)
}
fd = try FileDescriptor.open(
path.appending("inheritable.txt"), .readWrite,
options: [.create, .truncate],
permissions: .ownerReadWrite
)
try fd.closeAfter {
XCTAssertEqual(try hasInheritFlag(of: fd), true)
}
}
}
}
#endif // os(Windows)