Skip to content

Commit 29b79a7

Browse files
authored
Merge pull request #1780 from Thorium/audit-critical-fixes
Fix stability, resource, and correctness bugs
2 parents 4e0964d + aed5716 commit 29b79a7

23 files changed

Lines changed: 404 additions & 124 deletions

File tree

‎RELEASE_NOTES.md‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,22 @@
11
# Release Notes
22

3+
## 8.2.0 - Jul 06 2026
4+
5+
- Fix: HTML hexadecimal character references (`A`) are now decoded correctly; previously digit-only hex refs were parsed as decimal and refs containing `a`–`f` were left as literal text.
6+
- Fix: HTML table parsing clamps `colspan`/`rowspan` to the HTML spec limits (1000/65534) and no longer materializes unbounded ranges — malicious/malformed span attributes previously caused `OverflowException`, out-of-memory, or hangs.
7+
- Fix: `HtmlNode.ToString()` uses an explicit work stack, so deeply nested documents (which already parsed fine) no longer crash serialization with an uncatchable `StackOverflowException`.
8+
- Fix: `Http` multipart uploads no longer truncate when a source stream returns a partial read (e.g. network/gzip streams), and multipart parts of 2GB or more no longer overflow. User-supplied body streams are now disposed even when the upload faults.
9+
- Fix: `Http` `Range` headers in the RFC 7233 open-ended (`bytes=N-`) and suffix (`bytes=-N`) forms no longer throw `FormatException`.
10+
- Fix: `CsvFile.Rows` with `skipRows` re-applies the skip on repeated enumerations; previously the second enumeration returned garbage rows or threw.
11+
- Fix: `CsvFile.Save` now quotes headers, fields containing a lone `\r`, and fields containing any of the document's separators, so saved CSV round-trips correctly. `Save(TextWriter)` no longer disposes the caller-owned writer (it flushes instead).
12+
- Fix: JsonProvider-generated constructors no longer throw `OverflowException` for `NaN`, infinite, or very large `float` values; such values serialize through `JsonValue.Float`.
13+
- Fix: the JSON parser no longer silently swallows a stray `/` as whitespace (e.g. `[1, /2]` previously parsed as `[1, 2]`).
14+
- Fix: the in-memory cache no longer overflows `Int32` for expirations over ~24.8 days (which could crash the host process via an unhandled thread-pool exception), and a concurrently re-set entry can no longer be evicted by a stale expiration check. The file cache writes via temp-file-and-rename so concurrent readers never observe half-written entries.
15+
- Fix: file-watcher subscriptions are synchronized; concurrent subscribe/change events could corrupt the subscription dictionary and crash the IDE host at design time. Provider instance ids are now allocated with `Interlocked.Increment` and the design-time dispose-action set is locked.
16+
- Fix: the design-time web cache key now includes the `Encoding` (and row-limit) parameters, so two providers reading the same URL with different encodings no longer share the first decode.
17+
- Fix: WorldBank no longer caches HTTP-200 error bodies (which poisoned the cache for 30 days); invalid responses now go through the retry logic. Topics whose indicators are all filtered out by `Sources` return an empty collection instead of throwing `KeyNotFoundException`. Country/indicator codes are escaped with `Uri.EscapeDataString`, preventing URL path/query injection.
18+
- Fix: `XmlProvider` record creation no longer corrupts the structure when an intermediate path segment has the same name as the leaf (e.g. nested elements named `item`).
19+
320
## 8.1.14 - May 09 2026
421

522
- Eng: Remove manual `AssemblyInfo*.fs` files; use SDK-generated assembly attributes instead.

‎src/FSharp.Data.Csv.Core/CsvRuntime.fs‎

Lines changed: 39 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -104,18 +104,29 @@ module private CsvHelpers =
104104
LineIterator: IEnumerator<string[] * int>
105105
ColumnCount: int
106106
HasHeaders: bool
107+
SkipRows: int
107108
Separators: string
108109
Quote: char }
109110

110111
/// An enumerable that will return elements from the 'firstSeq' first time it
111112
/// is accessed and then will call 'nextSeq' each time for all future GetEnumerator calls
112113
type private ReentrantEnumerable<'T>(firstSeq: seq<'T>, nextSeq: unit -> seq<'T>) =
113114
let mutable first = true
115+
let sync = obj ()
114116

115117
interface seq<'T> with
116118
member x.GetEnumerator() =
117-
if first then
118-
first <- false
119+
// synchronized so concurrent enumerations cannot both claim 'firstSeq'
120+
// and end up sharing one live reader
121+
let isFirst =
122+
lock sync (fun () ->
123+
if first then
124+
first <- false
125+
true
126+
else
127+
false)
128+
129+
if isFirst then
119130
firstSeq.GetEnumerator()
120131
else
121132
nextSeq().GetEnumerator()
@@ -165,6 +176,7 @@ module private CsvHelpers =
165176
LineIterator = linesIterator
166177
ColumnCount = numberOfColumns
167178
HasHeaders = hasHeaders
179+
SkipRows = skipRows
168180
Separators = separators
169181
Quote = quote }
170182

@@ -181,6 +193,7 @@ module private CsvHelpers =
181193
LineIterator = linesIterator
182194
ColumnCount = numberOfColumns
183195
HasHeaders = hasHeaders
196+
SkipRows = skipRows
184197
Separators = separators
185198
Quote = quote }
186199
=
@@ -205,6 +218,8 @@ module private CsvHelpers =
205218
let nextSeq () =
206219
let reader: TextReader = newReader ()
207220
let csv = CsvReader.readCsvFile reader separators quote
221+
// re-apply skipRows exactly like the first read did, then the header row
222+
let csv = if skipRows > 0 then Seq.skip skipRows csv else csv
208223
if hasHeaders then Seq.skip 1 csv else csv
209224

210225
let untypedRows = ReentrantEnumerable<_>(firstSeq, nextSeq)
@@ -459,8 +474,6 @@ type CsvFile<'RowType>
459474
let quote = (defaultArg quote x.Quote).ToString()
460475
let doubleQuote = quote + quote
461476

462-
use writer = writer
463-
464477
// RFC 4180 (https://www.rfc-editor.org/rfc/rfc4180)
465478
// 2. Definition of the CSV Format
466479
// Each record is located on a separated line, delimited by a line break CRLF
@@ -471,6 +484,22 @@ type CsvFile<'RowType>
471484
| null -> String.Empty
472485
| _ -> str
473486

487+
// quote fields containing any of the document's separators (not just the one
488+
// used for saving), the quote char, or a line break (a bare CR also terminates
489+
// a row when re-parsing, so it needs quoting like LF)
490+
let charsNeedingQuoting =
491+
(x.Separators + separator + quote + "\r\n").ToCharArray() |> Array.distinct
492+
493+
let writeEscaped (item: string) =
494+
let item = item |> nullSafeguard
495+
496+
if item.IndexOfAny(charsNeedingQuoting) >= 0 then
497+
writer.Write quote
498+
writer.Write(item.Replace(quote, doubleQuote))
499+
writer.Write quote
500+
else
501+
writer.Write item
502+
474503
let writeLine writeItem (items: string[]) =
475504
for i = 0 to items.Length - 2 do
476505
writeItem items.[i]
@@ -480,25 +509,15 @@ type CsvFile<'RowType>
480509
writer.WriteLine()
481510

482511
match x.Headers with
483-
| Some headers -> headers |> writeLine writer.Write
512+
| Some headers -> headers |> writeLine writeEscaped
484513
| None -> ()
485514

486515
for row in x.Rows do
487-
row
488-
|> rowToStringArray.Invoke
489-
|> writeLine (fun item ->
490-
let item = item |> nullSafeguard
491-
492-
if
493-
item.IndexOf(separator, StringComparison.Ordinal) >= 0
494-
|| item.IndexOf(quote, StringComparison.Ordinal) >= 0
495-
|| item.IndexOf('\n') >= 0
496-
then
497-
writer.Write quote
498-
writer.Write(item.Replace(quote, doubleQuote))
499-
writer.Write quote
500-
else
501-
writer.Write item)
516+
row |> rowToStringArray.Invoke |> writeLine writeEscaped
517+
518+
// the writer is owned by the caller and must not be disposed here,
519+
// but buffered output should be visible when Save returns
520+
writer.Flush()
502521

503522
/// Saves CSV to the specified stream
504523
member x.Save(stream: Stream, [<Optional>] ?separator, [<Optional>] ?quote) =

‎src/FSharp.Data.DesignTime/CommonProviderImplementation/Helpers.fs‎

Lines changed: 20 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -85,11 +85,12 @@ type DisposableTypeProviderForNamespaces(config, ?assemblyReplacementMap) as x =
8585

8686
static let mutable idCount = 0
8787

88-
let id = idCount
88+
// IDE hosts can construct provider instances concurrently; an unsynchronized
89+
// read-then-increment could hand two instances the same id, breaking the
90+
// (fullTypeName, id) keys used for dispose actions and file watchers
91+
let id = System.Threading.Interlocked.Increment(&idCount)
8992
let filesToWatch = Dictionary()
9093

91-
do idCount <- idCount + 1
92-
9394
let dispose typeNameOpt =
9495
lock lockObj (fun () ->
9596
for i = disposeActions.Count - 1 downto 0 do
@@ -317,12 +318,23 @@ module internal ProviderHelpers =
317318

318319
let sample =
319320
if isWeb uri then
321+
// the cached value is the decoded (and possibly row-limited) text,
322+
// so the key must include everything that affects it, not just the URL
323+
let cacheKey =
324+
sprintf
325+
"%s|encoding=%s|maxRows=%s"
326+
uri.OriginalString
327+
encodingStr
328+
(match maxNumberOfRows with
329+
| Some n -> string n
330+
| None -> "")
331+
320332
let text =
321-
match webUrisCache.TryRetrieve(uri.OriginalString) with
333+
match webUrisCache.TryRetrieve(cacheKey) with
322334
| Some text -> text
323335
| None ->
324336
let text = readText ()
325-
webUrisCache.Set(uri.OriginalString, text)
337+
webUrisCache.Set(cacheKey, text)
326338
text
327339

328340
text
@@ -375,7 +387,9 @@ module internal ProviderHelpers =
375387

376388
let setupDisposeAction providedType fileToWatch =
377389

378-
if activeDisposeActions.Add(fullTypeName, tp.Id) then
390+
// synchronized: getOrCreateProvidedType can run concurrently on IDE threads
391+
// and HashSet mutation is not thread-safe
392+
if lock activeDisposeActions (fun () -> activeDisposeActions.Add(fullTypeName, tp.Id)) then
379393

380394
log "Setting up dispose action"
381395

‎src/FSharp.Data.Html.Core/HtmlCharRefs.fs‎

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2260,15 +2260,16 @@ module internal HtmlCharRefs =
22602260

22612261
match delimeters with
22622262
| ("&#", _) ->
2263-
let num =
2263+
let styles, num =
22642264
if discriminator <> 'x' then
2265-
s.Substring(2, s.Length - 2)
2265+
NumberStyles.Integer, s.Substring(2, s.Length - 2)
22662266
else
2267-
s.Substring(3, s.Length - 3)
2267+
NumberStyles.AllowHexSpecifier, s.Substring(3, s.Length - 3)
22682268

2269-
match UInt32.TryParse(num, NumberStyles.Integer, CultureInfo.InvariantCulture) with
2269+
match UInt32.TryParse(num, styles, CultureInfo.InvariantCulture) with
22702270
| true, i -> Number(i)
22712271
| false, _ -> Lookup(orig)
2272+
// legacy hex form without the '#', e.g. &x41;
22722273
| ("&x", _) ->
22732274
let num = s.Substring(2, s.Length - 2)
22742275

‎src/FSharp.Data.Html.Core/HtmlNode.fs‎

Lines changed: 34 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -119,18 +119,24 @@ type HtmlNode =
119119
static member NewCData content = HtmlCData(content)
120120

121121
override x.ToString() =
122-
let rec serialize (sb: StringBuilder) indentation canAddNewLine insidePre html =
123-
let append (str: string) = sb.Append str |> ignore
122+
let sb = StringBuilder()
123+
let append (str: string) = sb.Append str |> ignore
124124

125-
let appendEndTag name =
126-
append "</"
127-
append name
128-
append ">"
125+
let appendEndTag name =
126+
append "</"
127+
append name
128+
append ">"
129129

130-
let newLine plus =
131-
sb.AppendLine() |> ignore
132-
sb.Append(' ', indentation + plus) |> ignore
130+
let newLine indentation plus =
131+
sb.AppendLine() |> ignore
132+
sb.Append(' ', indentation + plus) |> ignore
133133

134+
// serialization uses an explicit work stack instead of call-stack recursion:
135+
// the parser accepts arbitrarily deep documents (it uses its own stack), so
136+
// ToString must not StackOverflow on them either
137+
let work = System.Collections.Generic.Stack<unit -> unit>()
138+
139+
let rec serialize indentation canAddNewLine insidePre html =
134140
match html with
135141
| HtmlElement(name, attributes, elements) ->
136142
let onlyText =
@@ -143,7 +149,7 @@ type HtmlNode =
143149
let nowInsidePre = insidePre || isPreTag
144150

145151
if canAddNewLine && not insidePre && not (onlyText || isPreTag) then
146-
newLine 0
152+
newLine indentation 0
147153

148154
append "<"
149155
append name
@@ -164,18 +170,23 @@ type HtmlNode =
164170
append ">"
165171

166172
if not insidePre && not (onlyText || isPreTag) then
167-
newLine 2
173+
newLine indentation 2
168174

169-
let mutable canAddNewLine = false
175+
// pushed first so it runs after all children are processed
176+
work.Push(fun () ->
177+
if not insidePre && not (onlyText || isPreTag) then
178+
newLine indentation 0
170179

171-
for element in elements do
172-
serialize sb (indentation + 2) canAddNewLine nowInsidePre element
173-
canAddNewLine <- true
180+
appendEndTag name)
174181

175-
if not insidePre && not (onlyText || isPreTag) then
176-
newLine 0
182+
// push children in reverse so they pop in document order;
183+
// only the first child is serialized with canAddNewLine = false
184+
let elements = List.toArray elements
177185

178-
appendEndTag name
186+
for i in elements.Length - 1 .. -1 .. 0 do
187+
let element = elements.[i]
188+
let canAddNewLine = i > 0
189+
work.Push(fun () -> serialize (indentation + 2) canAddNewLine nowInsidePre element)
179190
| HtmlText str -> append str
180191
| HtmlComment str ->
181192
append "<!--"
@@ -186,8 +197,11 @@ type HtmlNode =
186197
append str
187198
append "]]>"
188199

189-
let sb = StringBuilder()
190-
serialize sb 0 false false x |> ignore
200+
serialize 0 false false x
201+
202+
while work.Count > 0 do
203+
work.Pop () ()
204+
191205
sb.ToString()
192206

193207
/// <exclude />

‎src/FSharp.Data.Html.Core/HtmlRuntime.fs‎

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -288,11 +288,13 @@ module HtmlRuntime =
288288
index
289289
(table: HtmlNode, parents: HtmlNode list)
290290
=
291+
// the HTML spec caps rowspan at 65534 and colspan at 1000; without the cap a
292+
// malicious/malformed attribute overflows the column-count sum or allocates huge arrays
291293
let rowSpan cell =
292-
max 1 (defaultArg (TextConversions.AsInteger CultureInfo.InvariantCulture cell?rowspan) 0)
294+
min 65534 (max 1 (defaultArg (TextConversions.AsInteger CultureInfo.InvariantCulture cell?rowspan) 0))
293295

294296
let colSpan cell =
295-
max 1 (defaultArg (TextConversions.AsInteger CultureInfo.InvariantCulture cell?colspan) 0)
297+
min 1000 (max 1 (defaultArg (TextConversions.AsInteger CultureInfo.InvariantCulture cell?colspan) 0))
296298

297299
let rows =
298300
let header =
@@ -347,10 +349,9 @@ module HtmlRuntime =
347349
while col_i < res.[rowindex].Length && res.[rowindex].[col_i] <> Empty do
348350
col_i <- col_i + 1
349351

350-
for j in [ col_i .. (col_i + colSpan cell - 1) ] do
351-
for i in [ rowindex .. (rowindex + rowSpan cell - 1) ] do
352-
if i < rows.Length && j < numberOfColumns then
353-
res.[i].[j] <- data
352+
for j in col_i .. min (col_i + colSpan cell - 1) (numberOfColumns - 1) do
353+
for i in rowindex .. min (rowindex + rowSpan cell - 1) (rows.Length - 1) do
354+
res.[i].[j] <- data
354355

355356
let numberOfHeaderRows =
356357
res |> Array.countWhile (Array.forall (fun cell -> cell.IsHeader))

‎src/FSharp.Data.Http/Http.fs‎

Lines changed: 18 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1471,19 +1471,15 @@ module internal HttpHelpers =
14711471
match streams |> Seq.tryHead with
14721472
| None -> 0
14731473
| Some stream ->
1474-
let qty =
1475-
if stream.CanSeek then
1476-
min count (int stream.Length)
1477-
else
1478-
count
1479-
1480-
let read = stream.Read(buffer, offset, qty)
1474+
let read = stream.Read(buffer, offset, count)
14811475

1482-
if read < count then
1476+
if read = 0 then
1477+
// only a zero-byte read signals the end of the current stream: Read may
1478+
// legally return fewer bytes than requested while data is still pending
1479+
// (network/gzip/pipe streams), so a partial read must not skip the stream
14831480
stream.Dispose()
14841481
streams <- streams |> Seq.skip 1
1485-
let readFromRest = readFromStream buffer (offset + read) (count - read)
1486-
read + readFromRest
1482+
readFromStream buffer offset count
14871483
else
14881484
read
14891485

@@ -1615,9 +1611,12 @@ module internal HttpHelpers =
16151611

16161612
let asyncCopy (source: Stream) (dest: Stream) =
16171613
async {
1618-
do! source.CopyToAsync(dest) |> Async.AwaitIAsyncResult |> Async.Ignore
1619-
1620-
source.Dispose()
1614+
try
1615+
do! source.CopyToAsync(dest) |> Async.AwaitIAsyncResult |> Async.Ignore
1616+
finally
1617+
// dispose user-supplied body streams even when the copy faults
1618+
// (e.g. connection reset mid-upload)
1619+
source.Dispose()
16211620
}
16221621

16231622
let writeBody (req: HttpWebRequest) (data: Stream) =
@@ -1747,7 +1746,12 @@ module internal HttpHelpers =
17471746
if bytes.Length <> 2 then
17481747
failwithf "Invalid value for the Range header (%s)" value
17491748

1750-
req.AddRange(int64 bytes.[0], int64 bytes.[1])
1749+
// RFC 7233 also allows open-ended (bytes=N-) and suffix (bytes=-N) ranges
1750+
match bytes.[0], bytes.[1] with
1751+
| "", "" -> failwithf "Invalid value for the Range header (%s)" value
1752+
| rangeStart, "" -> req.AddRange(int64 rangeStart)
1753+
| "", suffixLength -> req.AddRange(-(int64 suffixLength))
1754+
| rangeStart, rangeEnd -> req.AddRange(int64 rangeStart, int64 rangeEnd)
17511755
| "proxy-authorization" -> req.Headers.[HeaderEnum.ProxyAuthorization] <- value
17521756
| "referer" -> req.Referer <- value
17531757
| "te" -> req.Headers.[HeaderEnum.Te] <- value

0 commit comments

Comments
 (0)