gtsocial-umbx

Unnamed repository; edit this file 'description' to name the repository.
Log | Files | Refs | README | LICENSE

validate.go (2206B)


      1 // GoToSocial
      2 // Copyright (C) GoToSocial Authors admin@gotosocial.org
      3 // SPDX-License-Identifier: AGPL-3.0-or-later
      4 //
      5 // This program is free software: you can redistribute it and/or modify
      6 // it under the terms of the GNU Affero General Public License as published by
      7 // the Free Software Foundation, either version 3 of the License, or
      8 // (at your option) any later version.
      9 //
     10 // This program is distributed in the hope that it will be useful,
     11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
     12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
     13 // GNU Affero General Public License for more details.
     14 //
     15 // You should have received a copy of the GNU Affero General Public License
     16 // along with this program.  If not, see <http://www.gnu.org/licenses/>.
     17 
     18 package httpclient
     19 
     20 import (
     21 	"fmt"
     22 	"net/http"
     23 	"strings"
     24 
     25 	"golang.org/x/net/http/httpguts"
     26 )
     27 
     28 // ValidateRequest performs the same request validation logic found in the default
     29 // net/http.Transport{}.roundTrip() function, but pulls it out into this separate
     30 // function allowing validation errors to be wrapped under a single error type.
     31 func ValidateRequest(r *http.Request) error {
     32 	switch {
     33 	case r.URL == nil:
     34 		return fmt.Errorf("%w: nil url", ErrInvalidRequest)
     35 	case r.Header == nil:
     36 		return fmt.Errorf("%w: nil header", ErrInvalidRequest)
     37 	case r.URL.Host == "":
     38 		return fmt.Errorf("%w: empty url host", ErrInvalidRequest)
     39 	case r.URL.Scheme != "http" && r.URL.Scheme != "https":
     40 		return fmt.Errorf("%w: unsupported protocol %q", ErrInvalidRequest, r.URL.Scheme)
     41 	case strings.IndexFunc(r.Method, func(r rune) bool { return !httpguts.IsTokenRune(r) }) != -1:
     42 		return fmt.Errorf("%w: invalid method %q", ErrInvalidRequest, r.Method)
     43 	}
     44 
     45 	for key, values := range r.Header {
     46 		// Check field key name is valid
     47 		if !httpguts.ValidHeaderFieldName(key) {
     48 			return fmt.Errorf("%w: invalid header field name %q", ErrInvalidRequest, key)
     49 		}
     50 
     51 		// Check each field value is valid
     52 		for i := 0; i < len(values); i++ {
     53 			if !httpguts.ValidHeaderFieldValue(values[i]) {
     54 				return fmt.Errorf("%w: invalid header field value %q", ErrInvalidRequest, values[i])
     55 			}
     56 		}
     57 	}
     58 
     59 	// ps. kim wrote this
     60 
     61 	return nil
     62 }