未验证 提交 d84770ed 编写于 作者: J Jon Shier 提交者: GitHub

Ensure encoded multipart body stream has appropriate length. (#3420)

* Ensure that the encoded body stream data has expected length (#3380)

* Ensure that the encoded body stream data has expected length

* Using a custom error for unexpected stream length instead of extending MultipartEncodingFailureReason

* Making `bytesExpected` and `bytesRead` of `UnexpectedInputStreamLengthError` public

* Slight cleanup.
Co-authored-by: NYu Ao <YuAo@users.noreply.github.com>
上级 b359efe6
......@@ -57,6 +57,15 @@ public enum AFError: Error {
case inputStreamReadFailed(error: Error)
}
/// Represents unexpected input stream length that occur when encoding the `MultipartFormData`. Instances will be
/// embedded within an `AFError.multipartEncodingFailed` `.inputStreamReadFailed` case.
public struct UnexpectedInputStreamLength: Error {
/// The expected byte count to read.
public var bytesExpected: UInt64
/// The actual byte count read.
public var bytesRead: UInt64
}
/// The underlying reason the `.parameterEncodingFailed` error occurred.
public enum ParameterEncodingFailureReason {
/// The `URLRequest` did not have a `URL` to encode.
......
......@@ -419,6 +419,12 @@ open class MultipartFormData {
}
}
guard UInt64(encoded.count) == bodyPart.bodyContentLength else {
let error = AFError.UnexpectedInputStreamLength(bytesExpected: bodyPart.bodyContentLength,
bytesRead: UInt64(encoded.count))
throw AFError.multipartEncodingFailed(reason: .inputStreamReadFailed(error: error))
}
return encoded
}
......
......@@ -918,4 +918,31 @@ class MultipartFormDataFailureTestCase: BaseTestCase {
XCTAssertNotNil(encodingError, "encoding error should not be nil")
XCTAssertEqual(encodingError?.asAFError?.isOutputStreamURLInvalid, true)
}
func testThatStreamBodyPartHasUnexpectedLength() {
// Given
let multipartFormData = MultipartFormData()
let data = Data("Lorem ipsum dolor sit amet.".utf8)
multipartFormData.append(data, withName: "data")
var firstError: Error?
var secondError: Error?
// When
do {
_ = try multipartFormData.encode()
} catch {
firstError = error
}
do {
_ = try multipartFormData.encode()
} catch {
secondError = error
}
XCTAssertNil(firstError, "firstError should be nil")
XCTAssertNotNil(secondError, "secondError should not be nil")
XCTAssertEqual(secondError?.asAFError?.isInputStreamReadFailed, true)
XCTAssert(secondError?.asAFError?.underlyingError is AFError.UnexpectedInputStreamLength)
}
}
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册