mirror of
https://github.com/apple/swift-nio-http2
synced 2026-11-24 04:38:00 +00:00
Add a `GlitchesMonitor` that will terminate a connection if too many glitches are triggered. See https://github.com/HTTPWorkshop/workshop2024/blob/main/talks/1.%20Security/glitches.pdf for details.
72 lines
2.1 KiB
Swift
72 lines
2.1 KiB
Swift
//===----------------------------------------------------------------------===//
|
|
//
|
|
// This source file is part of the SwiftNIO open source project
|
|
//
|
|
// Copyright (c) 2025 Apple Inc. and the SwiftNIO project authors
|
|
// Licensed under Apache License v2.0
|
|
//
|
|
// See LICENSE.txt for license information
|
|
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
|
|
//
|
|
// SPDX-License-Identifier: Apache-2.0
|
|
//
|
|
//===----------------------------------------------------------------------===//
|
|
|
|
struct GlitchesMonitor {
|
|
static var defaultMaximumGlitches: Int { 200 }
|
|
private var stateMachine: GlitchesMonitorStateMachine
|
|
|
|
init(maximumGlitches: Int = GlitchesMonitor.defaultMaximumGlitches) {
|
|
self.stateMachine = GlitchesMonitorStateMachine(maxGlitches: maximumGlitches)
|
|
}
|
|
|
|
mutating func processStreamError() throws {
|
|
switch self.stateMachine.recordEvent() {
|
|
case .belowLimit:
|
|
()
|
|
|
|
case .exceededLimit:
|
|
throw NIOHTTP2Errors.excessiveNumberOfGlitches()
|
|
}
|
|
}
|
|
}
|
|
|
|
extension GlitchesMonitor {
|
|
private struct GlitchesMonitorStateMachine {
|
|
enum State {
|
|
case monitoring(numberOfGlitches: Int)
|
|
case glitchesExceeded
|
|
}
|
|
|
|
private var state: State
|
|
private let maxGlitches: Int
|
|
|
|
init(maxGlitches: Int) {
|
|
precondition(maxGlitches >= 0)
|
|
self.state = .monitoring(numberOfGlitches: 0)
|
|
self.maxGlitches = maxGlitches
|
|
}
|
|
|
|
enum RecordEventAction {
|
|
case belowLimit
|
|
case exceededLimit
|
|
}
|
|
|
|
mutating func recordEvent() -> RecordEventAction {
|
|
switch self.state {
|
|
case .monitoring(let numberOfGlitches):
|
|
if numberOfGlitches < self.maxGlitches {
|
|
self.state = .monitoring(numberOfGlitches: numberOfGlitches &+ 1)
|
|
return .belowLimit
|
|
} else {
|
|
self.state = .glitchesExceeded
|
|
return .exceededLimit
|
|
}
|
|
|
|
case .glitchesExceeded:
|
|
return .exceededLimit
|
|
}
|
|
}
|
|
}
|
|
}
|