Skip to content

Commit

Permalink
Merge pull request #2 from gh123man/fix-overflow
Browse files Browse the repository at this point in the history
Fix arithmetic overflow on untrusted input
  • Loading branch information
macmoonshine authored Nov 26, 2023
2 parents aa2b5c7 + bbf6097 commit 3c24dbd
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 4 deletions.
15 changes: 11 additions & 4 deletions Sources/sqids/Sqids.swift
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ public struct Sqids {
case invalidMinLength(Int)
case valueError(Id)
case maximumAttemptsReached
case overflow
}
public static let defaultAlphabet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
public static let minAlphabetLength = 3
Expand Down Expand Up @@ -160,7 +161,7 @@ public struct Sqids {
break
}
else {
let number = toNumber(
let number = try toNumber(
id: chunks[0],
alphabet: Array(alphabet.suffix(from: 1))
)
Expand Down Expand Up @@ -213,11 +214,17 @@ public struct Sqids {
return characters
}

func toNumber(id: String, alphabet: [Character]) -> Id {
func toNumber(id: String, alphabet: [Character]) throws -> Id {
let count = Id(alphabet.count)

return id.reduce(0) {
$0 * count + Id(alphabet.firstIndex(of: $1) ?? -1)
return try id.reduce(0) {
let (product, productOverflow) = $0.multipliedReportingOverflow(by: count)
guard !productOverflow else { throw Error.overflow }

let (sum, sumOverflow) = product.addingReportingOverflow(Id(alphabet.firstIndex(of: $1) ?? -1))
guard !sumOverflow else { throw Error.overflow }

return sum
}
}

Expand Down
9 changes: 9 additions & 0 deletions Tests/sqidsTests/EncodeTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -145,4 +145,13 @@ final class EncodeTests: XCTestCase {
XCTAssertEqual(-1, id)
}
}

func testDecodeOfUntrustedInput() throws {
let sqids = Sqids()
let badInput = try sqids.encode([Int64.max]) + "a"
do {
_ = try sqids.decode(badInput) // Should not crash
}
catch Sqids.Error.overflow { }
}
}

0 comments on commit 3c24dbd

Please sign in to comment.