Skip to content
Myr

ci(sec): improve type safety and server organization in HTTP middleware (#4437)

Before adoption: this commit came in with the history the project adopted, so no landing records it.

- Update linting configuration to exclude G115 gosec check instead of including specific checks - Add the safeInt8 helper for safer type conversions and use it to prevent int8 overflow in middleware handler execution - Group related constants and variables together for better organization in gin.go - Refactor HTTP server instantiation to use a dedicated http.Server object for all Run methods - Add the safeUint16 helper and use it to safely handle conversions in tree node functions to prevent uint16 overflow

authored by Bo-Yi Wu · committed by GitHub · parent 58135f0 · Browse files · 4 files+50 added−22 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Trailers

  • Signed-off-by: appleboy <appleboy.tw@gmail.com>

Diff stats

4 files+50 added−22 removed

  • other:+50 added−22 removed

4 files+50 added−22 removed

modified:.golangci.yml+2 added-9 removed
modified:context.go+9 added-1 removed
53 unmodified lines
5455// abortIndex represents a typical value used in abort functions.56const abortIndex int8 = math.MaxInt8 >> 15758// safeInt8 converts int to int8 safely, capping at math.MaxInt859func safeInt8(n int) int8 {60 if n > math.MaxInt8 {61 return math.MaxInt862 }63 return int8(n)64}6566// Context is the most important part of gin. It allows us to pass variables between middleware,67// manage the flow, validate the JSON of a request and render a JSON response for example.68type Context struct {69 writermem responseWriter
123 unmodified lines
193// It executes the pending handlers in the chain inside the calling handler.194// See example in GitHub.195func (c *Context) Next() {196 c.index++189 for c.index < int8(len(c.handlers)) {197 for c.index < safeInt8(len(c.handlers)) {198 if c.handlers[c.index] != nil {199 c.handlers[c.index](c)200 }201 c.index++
1254 unmodified lines
modified:gin.go+28 added-10 removed
21 unmodified lines
22 "golang.org/x/net/http2"23 "golang.org/x/net/http2/h2c"24)2526const (26const defaultMultipartMemory = 32 << 20 // 32 MB27const escapedColon = "\\:"28const colon = ":"29const backslash = "\\"27 defaultMultipartMemory = 32 << 20 // 32 MB28 escapedColon = "\\:"29 colon = ":"30 backslash = "\\"31)3233var (34 default404Body = []byte("404 page not found")35 default405Body = []byte("405 method not allowed")
11 unmodified lines
47 Mask: net.IPMask{0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0},48 },49}5051var (49var regSafePrefix = regexp.MustCompile("[^a-zA-Z0-9/-]+")50var regRemoveRepeatedChar = regexp.MustCompile("/{2,}")52 regSafePrefix = regexp.MustCompile("[^a-zA-Z0-9/-]+")53 regRemoveRepeatedChar = regexp.MustCompile("/{2,}")54)5556// HandlerFunc defines the handler used by gin middleware as return value.57type HandlerFunc func(*Context)58
481 unmodified lines
540 }541 engine.updateRouteTrees()542 address := resolveAddress(addr)543 debugPrint("Listening and serving HTTP on %s\n", address)540 err = http.ListenAndServe(address, engine.Handler())544 server := &http.Server{ // #nosec G112545 Addr: address,546 Handler: engine.Handler(),547 }548 err = server.ListenAndServe()549 return550}551552// RunTLS attaches the router to a http.Server and starts listening and serving HTTPS (secure) requests.
7 unmodified lines
560 debugPrint("[WARNING] You trusted all proxies, this is NOT safe. We recommend you to set a value.\n" +561 "Please check https://github.com/gin-gonic/gin/blob/master/docs/doc.md#dont-trust-all-proxies for details.")562 }563556 err = http.ListenAndServeTLS(addr, certFile, keyFile, engine.Handler())564 server := &http.Server{ // #nosec G112565 Addr: addr,566 Handler: engine.Handler(),567 }568 err = server.ListenAndServeTLS(certFile, keyFile)569 return570}571572// RunUnix attaches the router to a http.Server and starts listening and serving HTTP requests
14 unmodified lines
587 }588 defer listener.Close()589 defer os.Remove(file)590579 err = http.Serve(listener, engine.Handler())591 server := &http.Server{ // #nosec G112592 Handler: engine.Handler(),593 }594 err = server.Serve(listener)595 return596}597598// RunFd attaches the router to a http.Server and starts listening and serving HTTP requests
45 unmodified lines
644 debugPrint("[WARNING] You trusted all proxies, this is NOT safe. We recommend you to set a value.\n" +645 "Please check https://github.com/gin-gonic/gin/blob/master/docs/doc.md#dont-trust-all-proxies for details.")646 }647633 err = http.Serve(listener, engine.Handler())648 server := &http.Server{ // #nosec G112649 Handler: engine.Handler(),650 }651 err = server.Serve(listener)652 return653}654655// ServeHTTP conforms to the http.Handler interface.
152 unmodified lines
modified:tree.go+11 added-2 removed
3 unmodified lines
45package gin67import (8 "math"9 "net/url"10 "strings"11 "unicode"12 "unicode/utf8"
64 unmodified lines
77 n.children = append(n.children, child)78 }79}8081// safeUint16 converts int to uint16 safely, capping at math.MaxUint1682func safeUint16(n int) uint16 {83 if n > math.MaxUint16 {84 return math.MaxUint1685 }86 return uint16(n)87}8889func countParams(path string) uint16 {90 colons := strings.Count(path, ":")91 stars := strings.Count(path, "*")83 return uint16(colons + stars)92 return safeUint16(colons + stars)93}9495func countSections(path string) uint16 {87 return uint16(strings.Count(path, "/"))96 return safeUint16(strings.Count(path, "/"))97}9899type nodeType uint8100
799 unmodified lines