Repository: caddyserver/caddy
File: modules/caddyhttp/requestbody/requestbody.go (Go)

Code before:
	// This field permit to replace body on the fly
	// EXPERIMENTAL. Subject to change/removal.
	Set string `json:"set,omitempty"`

	logger *zap.Logger
}

// CaddyModule returns the Caddy module information.
func (RequestBody) CaddyModule() caddy.ModuleInfo {
	return caddy.ModuleInfo{
		ID:  "http.handlers.request_body",
		New: func() caddy.Module { return new(RequestBody) },
	}
}

func (rb *RequestBody) Provision(ctx caddy.Context) error {
	rb.logger = ctx.Logger()
	return nil
}

func (rb RequestBody) ServeHTTP(w http.ResponseWriter, r *http.Request, next caddyhttp.Handler) error {
	if rb.Set != "" {
		err := r.Body.Close()
		if err != nil {
			return err
		}
		repl := r.Context().Value(caddy.ReplacerCtxKey).(*caddy.Replacer)
		replacedBody := repl.ReplaceAll(rb.Set, "")
		r.Body = io.NopCloser(strings.NewReader(replacedBody))
		r.ContentLength = int64(len(rb.Set))
	}
	if r.Body == nil {
		return next.ServeHTTP(w, r)
	}
	if rb.MaxSize > 0 {
		r.Body = errorWrapper{http.MaxBytesReader(w, r.Body, rb.MaxSize)}
	}
	if rb.ReadTimeout > 0 || rb.WriteTimeout > 0 {
		//nolint:bodyclose
		rc := http.NewResponseController(w)
		if rb.ReadTimeout > 0 {
			if err := rc.SetReadDeadline(time.Now().Add(rb.ReadTimeout)); err != nil {
				if c := rb.logger.Check(zapcore.ErrorLevel, "could not set read deadline"); c != nil {
					c.Write(zap.Error(err))
				}
			}
		}
		if rb.WriteTimeout > 0 {
			if err := rc.SetWriteDeadline(time.Now().Add(rb.WriteTimeout)); err != nil {
				if c := rb.logger.Check(zapcore.ErrorLevel, "could not set write deadline"); c != nil {
					c.Write(zap.Error(err))

Review comment (suggestion):
Potential panic risk: `r.Body.Close()` may cause a nil pointer dereference  

Currently, `r.Body.Close()` is called without checking if `r.Body` is `nil`. While `r.Body` is typically not `nil` in standard HTTP requests (defaulting to `http.NoBody`), some middleware or handlers may explicitly set it to `nil`. This can lead to a runtime panic if `r.Body.Close()` is called on a `nil` reference.  

From [`net/http` docs](https://pkg.go.dev/net/http#NoBody):  
> "An alternative, however, is to simply set [Request.Body] to nil."  


Code after:
	// This field permit to replace body on the fly
	// EXPERIMENTAL. Subject to change/removal.
	Set string `json:"set,omitempty"`

	logger *zap.Logger
}

// CaddyModule returns the Caddy module information.
func (RequestBody) CaddyModule() caddy.ModuleInfo {
	return caddy.ModuleInfo{
		ID:  "http.handlers.request_body",
		New: func() caddy.Module { return new(RequestBody) },
	}
}

func (rb *RequestBody) Provision(ctx caddy.Context) error {
	rb.logger = ctx.Logger()
	return nil
}

func (rb RequestBody) ServeHTTP(w http.ResponseWriter, r *http.Request, next caddyhttp.Handler) error {
	if rb.Set != "" {
		if r.Body != nil {
			err := r.Body.Close()
			if err != nil {
				return err
			}
		}
		repl := r.Context().Value(caddy.ReplacerCtxKey).(*caddy.Replacer)
		replacedBody := repl.ReplaceAll(rb.Set, "")
		r.Body = io.NopCloser(strings.NewReader(replacedBody))
		r.ContentLength = int64(len(rb.Set))
	}
	if r.Body == nil {
		return next.ServeHTTP(w, r)
	}
	if rb.MaxSize > 0 {
		r.Body = errorWrapper{http.MaxBytesReader(w, r.Body, rb.MaxSize)}
	}
	if rb.ReadTimeout > 0 || rb.WriteTimeout > 0 {
		//nolint:bodyclose
		rc := http.NewResponseController(w)
		if rb.ReadTimeout > 0 {
			if err := rc.SetReadDeadline(time.Now().Add(rb.ReadTimeout)); err != nil {
				if c := rb.logger.Check(zapcore.ErrorLevel, "could not set read deadline"); c != nil {
					c.Write(zap.Error(err))
				}
			}
		}
		if rb.WriteTimeout > 0 {
			if err := rc.SetWriteDeadline(time.Now().Add(rb.WriteTimeout)); err != nil {