Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion Sources/CLI/client/AppleSupportClient+Error.swift
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ enum AppleSupportClientError: Error, Equatable, LocalizedError {
var errorDescription: String? {
switch self {
case .invalidPath:
return "Expected a developer-site-relative path under help/ or support/ without a query or fragment."
return "Expected a supported developer-site-relative path without a query or fragment."
case .invalidResponse:
return "Apple support returned an invalid response or redirected outside supported developer pages."
case .httpStatus(let status):
Expand Down
18 changes: 16 additions & 2 deletions Sources/CLI/client/AppleSupportClient.swift
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import Logging
#if DEBUG
protocol AppleSupportClient: Sendable {
func fetchHTML(at destination: SupportDestination) async throws -> SupportHTMLDocument
func fetchDocument(at destination: SupportDestination) async throws -> SupportDocumentResponse
}
extension DefaultAppleSupportClient: AppleSupportClient {}
typealias DefaultAppleSupportClientDependencies = HTTPDataTransport
Expand All @@ -16,6 +17,11 @@ import Logging
typealias DefaultAppleSupportClientDependencies = URLSession
#endif

enum SupportDocumentResponse: Equatable, Sendable {
case html(SupportHTMLDocument)
case pdf(URL)
}

struct SupportHTMLDocument: Equatable, Sendable {
let destination: SupportDestination
let html: String
Expand All @@ -32,7 +38,14 @@ final class DefaultAppleSupportClient<Dependencies: DefaultAppleSupportClientDep
}

func fetchHTML(at destination: SupportDestination) async throws -> SupportHTMLDocument {
logger.debug("Requesting support HTML", metadata: ["path": .string(destination.path)])
switch try await fetchDocument(at: destination) {
case .html(let document): return document
case .pdf: throw AppleSupportClientError.unsupportedContentType("application/pdf")
}
}

func fetchDocument(at destination: SupportDestination) async throws -> SupportDocumentResponse {
logger.debug("Requesting support document", metadata: ["path": .string(destination.path)])
let (data, response) = try await dependencies.data(from: destination.url)
guard let response = response as? HTTPURLResponse, let responseURL = response.url else {
throw AppleSupportClientError.invalidResponse
Expand All @@ -42,6 +55,7 @@ final class DefaultAppleSupportClient<Dependencies: DefaultAppleSupportClientDep
}
let resolved = try SupportDestination(responseURL: responseURL)
let contentType = response.mimeType?.lowercased()
if contentType == "application/pdf" { return .pdf(resolved.url) }
guard contentType == "text/html" || contentType == "application/xhtml+xml" else {
throw AppleSupportClientError.unsupportedContentType(contentType)
}
Expand All @@ -51,6 +65,6 @@ final class DefaultAppleSupportClient<Dependencies: DefaultAppleSupportClientDep
logger.debug(
"Received support HTML",
metadata: ["path": .string(resolved.path), "bytes": .stringConvertible(data.count)])
return SupportHTMLDocument(destination: resolved, html: html, responseByteCount: data.count)
return .html(SupportHTMLDocument(destination: resolved, html: html, responseByteCount: data.count))
}
}
6 changes: 4 additions & 2 deletions Sources/CLI/client/SupportDestination.swift
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,9 @@ struct SupportDestination: Equatable, Hashable, Sendable {
value = decoded
}
let path = value.trimmingCharacters(in: CharacterSet(charactersIn: "/"))
guard let root = path.split(separator: "/").first, root == "help" || root == "support" else {
guard let root = path.split(separator: "/").first,
root == "help" || root == "support" || path == "xcode/system-requirements"
else {
throw AppleSupportClientError.invalidPath
}
self.path = path
Expand All @@ -28,7 +30,7 @@ struct SupportDestination: Equatable, Hashable, Sendable {
var components = URLComponents()
components.scheme = "https"
components.host = "developer.apple.com"
components.path = "/" + path + "/"
components.path = "/" + path + (path.lowercased().hasSuffix(".pdf") ? "" : "/")
return components.url!
}

Expand Down
4 changes: 2 additions & 2 deletions Sources/CLI/cmd/support/SupportCommand.swift
Original file line number Diff line number Diff line change
Expand Up @@ -35,11 +35,11 @@ extension SupportExecutableCommand {
struct SupportViewCommand: SupportExecutableCommand {
@OptionGroup var global: GlobalOptions
@OptionGroup var output: OutputOptions
@Option(help: "A supported path relative to developer.apple.com, including help/ or support/.")
@Option(help: "A supported developer-site path, such as support/fee-waiver or xcode/system-requirements.")
var path: String

static let configuration = CommandConfiguration(
commandName: "view", abstract: "Read a supported HTML document. PDFs and unknown layouts are not parsed.")
commandName: "view", abstract: "Read a supported HTML document or show a PDF download link.")

var request: SupportRequest { .article(path: path) }
}
6 changes: 5 additions & 1 deletion Sources/CLI/cmd/support/SupportCommandRunner.swift
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,11 @@ struct SupportCommandRunner: Sendable {
case .glossaryEntry(let term): payload = .glossaryEntry(try await service.fetchGlossaryEntry(term: term))
case .terms(let category): payload = .terms(try await service.fetchTerms(category: category))
case .termsEntry(let name): payload = .termsEntry(try await service.fetchTermsEntry(named: name))
case .article(let path): payload = .article(try await service.fetchArticle(path: path))
case .article(let path):
switch try await service.fetchDocument(path: path) {
case .article(let article): payload = .article(article)
case .pdf(let pdf): payload = .pdf(pdf)
}
}
return try renderer.render(payload)
}
Expand Down
7 changes: 5 additions & 2 deletions Sources/CLI/renderer/SupportPresentation.swift
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ enum SupportPayload: Sendable {
case terms(SupportTermsCatalog)
case termsEntry(SupportTermsEntry)
case article(SupportArticle)
case pdf(SupportPDF)

var kind: String {
switch self {
Expand All @@ -20,6 +21,7 @@ enum SupportPayload: Sendable {
case .terms: return "termsCatalog"
case .termsEntry: return "termsEntry"
case .article: return "article"
case .pdf: return "pdf"
}
}

Expand All @@ -33,6 +35,7 @@ enum SupportPayload: Sendable {
case .terms(let value): try value.encode(to: encoder)
case .termsEntry(let value): try value.encode(to: encoder)
case .article(let value): try value.encode(to: encoder)
case .pdf(let value): try value.encode(to: encoder)
}
}
}
Expand Down Expand Up @@ -133,8 +136,8 @@ struct SupportPresenter {
return
(parts.count > 2 && parts[0] == "help"
&& ["account", "app-store-connect", "app-review"].contains(parts[1]))
|| path == "support/fee-waiver"
|| path == "support/terms/apple-developer-program-license-agreement"
|| path.hasPrefix("support/")
|| path == "xcode/system-requirements"
}

private func quote(_ text: String) -> String {
Expand Down
2 changes: 2 additions & 0 deletions Sources/CLI/renderer/SupportTextRenderer.swift
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,8 @@ struct SupportTextRenderer {
}
case .termsEntry(let value):
return termsEntry(value, level: 1)
case .pdf(let value):
return [value.message + " " + value.url.absoluteString]
case .article(let value):
return [
heading(value.title, level: 1), value.url.absoluteString,
Expand Down
10 changes: 7 additions & 3 deletions Sources/CLI/support/AppleSupportService.swift
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ import Foundation
func fetchGlossaryEntry(term: String) async throws -> SupportGlossaryEntry
func fetchTerms(category: String?) async throws -> SupportTermsCatalog
func fetchTermsEntry(named name: String) async throws -> SupportTermsEntry
func fetchArticle(path: String) async throws -> SupportArticle
func fetchDocument(path: String) async throws -> SupportDocument
}
extension DefaultAppleSupportService: AppleSupportService {}
typealias DefaultAppleSupportServiceDependencies = AppleSupportClient
Expand Down Expand Up @@ -88,8 +88,12 @@ final class DefaultAppleSupportService<Dependencies: DefaultAppleSupportServiceD
return entry
}

func fetchArticle(path: String) async throws -> SupportArticle {
try await parser(path: path).article()
func fetchDocument(path: String) async throws -> SupportDocument {
let destination = try SupportDestination(path: path)
switch try await dependencies.fetchDocument(at: destination) {
case .html(let document): return try .article(SupportHTMLParser(document: document).article())
case .pdf(let url): return .pdf(SupportPDF(url: url))
}
}

private func parser(path: String) async throws -> SupportHTMLParser {
Expand Down
10 changes: 10 additions & 0 deletions Sources/CLI/support/SupportContent.swift
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,16 @@ struct SupportBreadcrumb: Encodable, Equatable, Sendable {
let url: URL?
}

enum SupportDocument: Equatable, Sendable {
case article(SupportArticle)
case pdf(SupportPDF)
}

struct SupportPDF: Encodable, Equatable, Sendable {
let url: URL
let message = "Page is PDF which cannot be displayed. You can download from:"
}

struct SupportArticle: Encodable, Equatable, Sendable {
let url: URL
let title: String
Expand Down
2 changes: 1 addition & 1 deletion Sources/CLI/support/SupportHTMLParser+Content.swift
Original file line number Diff line number Diff line change
Expand Up @@ -118,7 +118,7 @@ extension SupportHTMLParser {
}

private func isInline(_ element: Element) -> Bool {
if !element.isBlock() { return true }
if !element.isBlock() { return element.children().allSatisfy(isInline) }
return ["ins", "del", "s"].contains(element.tagName()) && element.children().allSatisfy(isInline)
}

Expand Down
12 changes: 9 additions & 3 deletions Sources/CLI/support/SupportHTMLParser.swift
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ struct SupportHTMLParser {
let url = URL(string: raw, relativeTo: source.destination.url)?.absoluteURL,
let components = URLComponents(url: url, resolvingAgainstBaseURL: true),
let scheme = components.scheme?.lowercased(),
["https", "http", "mailto"].contains(scheme),
["https", "http", "mailto", "applefeedback"].contains(scheme),
components.user == nil, components.password == nil
else { throw SupportParsingError.invalidLink }
return url
Expand Down Expand Up @@ -108,8 +108,14 @@ struct SupportHTMLParser {
}

func article() throws -> SupportArticle {
let article = try required("main .main-content article")
let heading = try required("main h1")
let article: Element
if source.destination.path == "xcode/system-requirements" {
_ = try required("main .section-requirements")
article = try required("main")
} else {
article = try required("main .main-content article, main > article, body > article")
}
let heading = try document.select("main h1").first() ?? required("h1", in: article)
let content = try blocks(in: article)
guard !content.isEmpty else { throw layoutError }
return SupportArticle(
Expand Down
45 changes: 45 additions & 0 deletions Tests/CLIIntegrationTests/SupportCommandIntegrationTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,31 @@ struct SupportCommandIntegrationTests {
"help/app-store-connect/reference/app-information/screenshot-specifications",
"support/fee-waiver",
"support/terms/apple-developer-program-license-agreement",
"support/bimi",
"support/install-beta",
"support/technical",
"support/kernel-extensions",
"support/forums",
"support/expiration",
"support/ipv6",
"support/sca",
"support/xcode",
"support/app-store",
"support/volume-purchase-and-custom-apps",
"support/protecting-users-from-suspicious-software",
"support/required-device-capabilities",
"support/unlisted-app-distribution",
"support/dma-and-apps-in-the-eu",
"support/third-party-SDK-requirements",
"support/interoperability-requests",
"support/reader-apps",
"support/age-assurance",
"support/app-distribution-in-brazil",
"support/app-distribution-in-japan",
"support/apps-in-the-eu",
"support/storekit-external-entitlement-kr",
"support/hce-transactions-in-apps",
"support/nfc-se-platform",
])
func liveDocument(path: String) throws {
// -- Arrange --
Expand All @@ -62,6 +87,26 @@ struct SupportCommandIntegrationTests {
}
}

@Test("returns a download notice for a live PDF without failing")
func livePDF() throws {
// -- Arrange --
let path = "support/macos-server/macOS-Server-Service-Migration-Guide.pdf"

// -- Act --
let output = try runAppleDocs(["support", "view", "--path", path])
let json = try runAppleDocs(["support", "view", "--path", path, "--agent", "--json"])
let value = try #require(JSONSerialization.jsonObject(with: Data(json.utf8)) as? [String: Any])

// -- Assert --
#expect(output.contains("Page is PDF which cannot be displayed. You can download from:"))
#expect(
output.contains("https://developer.apple.com/support/downloads/macOS-Server-Service-Migration-Guide.pdf"))
#expect(value["kind"] as? String == "pdf")
#expect(
value["url"] as? String
== "https://developer.apple.com/support/downloads/macOS-Server-Service-Migration-Guide.pdf")
}

@Test("renders live agent text with follow-up navigation")
func liveAgentText() throws {
// -- Arrange --
Expand Down
28 changes: 28 additions & 0 deletions Tests/CLITests/client/AppleSupportClientTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,32 @@ struct AppleSupportClientTests {
await #expect(throws: AppleSupportClientError.unsupportedContentType(contentType)) { try await fetch() }
}

@Test("reports a linked PDF as non-HTML after its file redirect")
func rejectsLinkedPDF() async throws {
// -- Arrange --
let url = try #require(
URL(string: "https://developer.apple.com/support/macos-server/macOS-Server-Service-Migration-Guide.pdf"))
let finalURL = try #require(
URL(string: "https://developer.apple.com/support/downloads/macOS-Server-Service-Migration-Guide.pdf"))
let response = try #require(
HTTPURLResponse(
url: finalURL, statusCode: 200, httpVersion: nil, headerFields: ["Content-Type": "application/pdf"]))
let client = DefaultAppleSupportClient(
logger: Logger(label: "test") { _ in SwiftLogNoOpLogHandler() },
dependencies: HTTPTestTransport(responses: [
url: .response(data: Data("%PDF-1.3".utf8), response: response)
]))
let destination = try SupportDestination(path: "support/macos-server/macOS-Server-Service-Migration-Guide.pdf")

// -- Act --
let fetch = { try await client.fetchHTML(at: destination) }

// -- Assert --
await #expect(throws: AppleSupportClientError.unsupportedContentType("application/pdf")) {
try await fetch()
}
}

@Test("keeps a validated redirect destination")
func followsDeveloperRedirect() async throws {
// -- Arrange --
Expand All @@ -95,6 +121,8 @@ struct AppleSupportClientTests {
arguments: [
"https://example.com/help/glossary/", "http://developer.apple.com/help/glossary/",
"https://developer.apple.com/account/", "https://developer.apple.com:444/help/glossary/",
"https://example.com/xcode/system-requirements/", "https://developer.apple.com/xcode/download/",
"https://developer.apple.com/xcode/system-requirements?query=secret",
])
func rejectsRedirect(raw: String) async throws {
// -- Arrange --
Expand Down
28 changes: 28 additions & 0 deletions Tests/CLITests/client/SupportDestinationTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -18,13 +18,41 @@ struct SupportDestinationTests {
#expect(destination.url.absoluteString == "https://developer.apple.com/support/D-U-N-S/")
}

@Test("preserves PDF file URLs without adding a directory slash")
func preservesPDFURL() throws {
// -- Arrange --
let path = "support/macos-server/macOS-Server-Service-Migration-Guide.pdf"

// -- Act --
let destination = try SupportDestination(path: path)

// -- Assert --
#expect(
destination.url.absoluteString
== "https://developer.apple.com/support/macos-server/macOS-Server-Service-Migration-Guide.pdf")
}

@Test("accepts the Xcode support redirect destination")
func xcodeRequirements() throws {
// -- Arrange --
let url = try #require(URL(string: "https://developer.apple.com/xcode/system-requirements"))

// -- Act --
let destination = try SupportDestination(responseURL: url)

// -- Assert --
#expect(destination.path == "xcode/system-requirements")
#expect(destination.url.absoluteString == "https://developer.apple.com/xcode/system-requirements/")
}

@Test(
"rejects unsafe or unsupported input before transport",
arguments: [
"", "https://developer.apple.com/help/glossary/", "//example.com/help/glossary", "account/login",
"help/../account", "help/./glossary", "help/%2e%2e/account", "help/%252e%252e/account",
"help/foo%2f..%2faccount", "help/glossary?query=secret", "help/glossary#term", "help/foo\\bar",
"help/foo%5cbar", "help/foo\u{001B}[2J", "help/foo%0a", "help//glossary", "help/foo%3fquery=secret",
"xcode", "xcode/download", "xcode/system-requirements/other", "xcode/system-requirements/../download",
])
func rejectsPath(raw: String) {
// -- Arrange --
Expand Down
Loading
Loading