knative.dev/pkg@v0.0.0-20260602142205-ac97e43f6622/test/spoof/error_checks.go (about)

     1  /*
     2  Copyright 2019 The Knative Authors
     3  
     4  Licensed under the Apache License, Version 2.0 (the "License");
     5  you may not use this file except in compliance with the License.
     6  You may obtain a copy of the License at
     7  
     8      http://www.apache.org/licenses/LICENSE-2.0
     9  
    10  Unless required by applicable law or agreed to in writing, software
    11  distributed under the License is distributed on an "AS IS" BASIS,
    12  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13  See the License for the specific language governing permissions and
    14  limitations under the License.
    15  */
    16  
    17  // spoof contains logic to make polling HTTP requests against an endpoint with optional host spoofing.
    18  
    19  package spoof
    20  
    21  import (
    22  	"errors"
    23  	"net"
    24  	"net/http"
    25  	"strings"
    26  )
    27  
    28  func isTCPTimeout(err error) bool {
    29  	if err == nil {
    30  		return false
    31  	}
    32  	var errNet net.Error
    33  	if !errors.As(err, &errNet) {
    34  		return false
    35  	}
    36  	return errNet.Timeout()
    37  }
    38  
    39  func isDNSError(err error) bool {
    40  	if err == nil {
    41  		return false
    42  	}
    43  	// Checking by casting to url.Error and casting the nested error
    44  	// seems to be not as robust as string check.
    45  	msg := strings.ToLower(err.Error())
    46  	// Example error message:
    47  	//   > Get http://this.url.does.not.exist: dial tcp: lookup this.url.does.not.exist on 127.0.0.1:53: no such host
    48  	return strings.Contains(msg, "no such host") || strings.Contains(msg, ":53")
    49  }
    50  
    51  func isConnectionRefused(err error) bool {
    52  	// The alternative for the string check is:
    53  	// 	errNo := (((err.(*url.Error)).Err.(*net.OpError)).Err.(*os.SyscallError).Err).(syscall.Errno)
    54  	// if errNo == syscall.Errno(0x6f) {...}
    55  	// But with assertions, of course.
    56  	return err != nil && strings.Contains(err.Error(), "connect: connection refused")
    57  }
    58  
    59  func isConnectionReset(err error) bool {
    60  	return err != nil && strings.Contains(err.Error(), "connection reset by peer")
    61  }
    62  
    63  func isNoRouteToHostError(err error) bool {
    64  	return err != nil && strings.Contains(err.Error(), "connect: no route to host")
    65  }
    66  
    67  func isResponseDNSError(resp *Response) bool {
    68  	// no such host with 502 is sent back from istio-ingressgateway when it fails to resolve domain.
    69  	return resp.StatusCode == http.StatusBadGateway && strings.Contains(string(resp.Body), "no such host")
    70  }