| 1 | import XCTest |
| 2 | @testable import LChatCore |
| 3 | |
| 4 | // đŸ¤– The safe-filename derivation for downloading/previewing attachments: the |
| 5 | // sender's name is untrusted, and the extension (which Quick Look and the Files |
| 6 | // app route on) may be missing. These pin the sanitisation + MIME fallback. |
| 7 | final class AttachmentDownloadTests: XCTestCase { |
| 8 | func testKeepsGoodNameAndExtension() { |
| 9 | XCTAssertEqual( |
| 10 | AttachmentDownload.safeFilename(name: "report.pdf", mime: "application/pdf"), |
| 11 | "report.pdf") |
| 12 | XCTAssertEqual( |
| 13 | AttachmentDownload.safeFilename(name: "photo.jpeg", mime: "image/jpeg"), |
| 14 | "photo.jpeg") |
| 15 | } |
| 16 | |
| 17 | func testDerivesExtensionFromMIMEWhenNameHasNone() { |
| 18 | XCTAssertEqual( |
| 19 | AttachmentDownload.safeFilename(name: "report", mime: "application/pdf"), |
| 20 | "report.pdf") |
| 21 | XCTAssertEqual( |
| 22 | AttachmentDownload.safeFilename(name: "notes", mime: "text/plain"), |
| 23 | "notes.txt") |
| 24 | } |
| 25 | |
| 26 | func testFallsBackToFileWhenNameMissingOrEmpty() { |
| 27 | XCTAssertEqual( |
| 28 | AttachmentDownload.safeFilename(name: nil, mime: "application/pdf"), |
| 29 | "file.pdf") |
| 30 | XCTAssertEqual( |
| 31 | AttachmentDownload.safeFilename(name: " ", mime: "image/png"), |
| 32 | "file.png") |
| 33 | } |
| 34 | |
| 35 | func testStripsDirectoryPathFromSenderName() { |
| 36 | // lastPathComponent defuses a path-traversal-shaped name. |
| 37 | XCTAssertEqual( |
| 38 | AttachmentDownload.safeFilename(name: "../../etc/passwd", mime: nil), |
| 39 | "passwd") |
| 40 | XCTAssertEqual( |
| 41 | AttachmentDownload.safeFilename(name: "a/b/c/secret.docx", mime: nil), |
| 42 | "secret.docx") |
| 43 | } |
| 44 | |
| 45 | func testNoExtensionWhenNeitherNameNorMIMEProvidesOne() { |
| 46 | // No name extension and no usable MIME → leave it bare rather than invent one. |
| 47 | XCTAssertEqual(AttachmentDownload.safeFilename(name: "notes", mime: nil), "notes") |
| 48 | XCTAssertEqual(AttachmentDownload.safeFilename(name: "notes", mime: ""), "notes") |
| 49 | XCTAssertEqual(AttachmentDownload.safeFilename(name: nil, mime: nil), "file") |
| 50 | } |
| 51 | } |
| 52 | |