2020-09-26 14:23:43 -04:00
package client
2020-10-04 19:49:02 -04:00
import (
2022-03-10 02:53:51 +01:00
"bytes"
2024-04-09 18:41:37 -04:00
"crypto/tls"
2022-05-16 22:19:42 -04:00
"io"
2022-03-10 02:53:51 +01:00
"net/http"
2025-01-18 20:26:25 -05:00
"net/netip"
2020-10-04 19:49:02 -04:00
"testing"
2021-01-12 21:26:28 -05:00
"time"
2022-03-10 02:53:51 +01:00
2024-05-09 22:56:16 -04:00
"github.com/TwiN/gatus/v5/config/endpoint/dns"
"github.com/TwiN/gatus/v5/pattern"
2022-12-06 01:41:09 -05:00
"github.com/TwiN/gatus/v5/test"
2020-10-04 19:49:02 -04:00
)
2020-09-26 14:23:43 -04:00
2020-12-28 17:19:41 -05:00
func TestGetHTTPClient ( t * testing . T ) {
2021-07-29 18:13:37 -04:00
cfg := & Config {
2021-07-28 21:41:26 -04:00
Insecure : false ,
IgnoreRedirect : false ,
Timeout : 0 ,
2022-06-13 00:45:08 +02:00
DNSResolver : "tcp://1.1.1.1:53" ,
2022-03-10 02:53:51 +01:00
OAuth2Config : & OAuth2Config {
ClientID : "00000000-0000-0000-0000-000000000000" ,
ClientSecret : "secretsauce" ,
TokenURL : "https://token-server.local/token" ,
Scopes : [] string { "https://application.local/.default" },
},
2021-07-29 18:13:37 -04:00
}
2022-06-13 00:45:08 +02:00
err := cfg . ValidateAndSetDefaults ()
if err != nil {
t . Errorf ( "expected error to be nil, but got: `%s`" , err )
}
2021-07-29 18:13:37 -04:00
if GetHTTPClient ( cfg ) == nil {
t . Error ( "expected client to not be nil" )
}
if GetHTTPClient ( nil ) == nil {
t . Error ( "expected client to not be nil" )
}
2020-09-26 14:23:43 -04:00
}
2020-12-25 00:07:18 -05:00
2025-09-11 23:32:19 +03:00
func TestRdapQuery ( t * testing . T ) {
if _ , err := rdapQuery ( "1.1.1.1" ); err == nil {
t . Error ( "expected an error due to the invalid domain type" )
}
if _ , err := rdapQuery ( "eurid.eu" ); err == nil {
t . Error ( "expected an error as there is no RDAP support currently in .eu" )
}
if response , err := rdapQuery ( "example.com" ); err != nil {
t . Fatal ( "expected no error, got" , err . Error ())
} else if response . ExpirationDate . Unix () <= 0 {
t . Error ( "expected to have a valid expiry date, got" , response . ExpirationDate . Unix ())
}
}
2022-11-15 21:35:22 -05:00
func TestGetDomainExpiration ( t * testing . T ) {
2023-01-08 17:53:37 -05:00
t . Parallel ()
2025-08-14 09:15:34 -04:00
if domainExpiration , err := GetDomainExpiration ( "gatus.io" ); err != nil {
2022-11-15 21:35:22 -05:00
t . Fatalf ( "expected error to be nil, but got: `%s`" , err )
} else if domainExpiration <= 0 {
t . Error ( "expected domain expiration to be higher than 0" )
}
2025-08-14 09:15:34 -04:00
if domainExpiration , err := GetDomainExpiration ( "gatus.io" ); err != nil {
2022-11-15 21:35:22 -05:00
t . Errorf ( "expected error to be nil, but got: `%s`" , err )
} else if domainExpiration <= 0 {
t . Error ( "expected domain expiration to be higher than 0" )
}
// Hack to pretend like the domain is expiring in 1 hour, which should trigger a refresh
2025-08-14 09:15:34 -04:00
whoisExpirationDateCache . SetWithTTL ( "gatus.io" , time . Now (). Add ( time . Hour ), 25 * time . Hour )
if domainExpiration , err := GetDomainExpiration ( "gatus.io" ); err != nil {
2022-11-15 21:35:22 -05:00
t . Errorf ( "expected error to be nil, but got: `%s`" , err )
} else if domainExpiration <= 0 {
t . Error ( "expected domain expiration to be higher than 0" )
}
// Make sure the refresh works when the ttl is <24 hours
2025-08-14 09:15:34 -04:00
whoisExpirationDateCache . SetWithTTL ( "gatus.io" , time . Now (). Add ( 35 * time . Hour ), 23 * time . Hour )
if domainExpiration , err := GetDomainExpiration ( "gatus.io" ); err != nil {
2022-11-15 21:35:22 -05:00
t . Errorf ( "expected error to be nil, but got: `%s`" , err )
} else if domainExpiration <= 0 {
t . Error ( "expected domain expiration to be higher than 0" )
}
}
2020-12-27 17:07:50 -05:00
func TestPing ( t * testing . T ) {
2023-01-08 17:53:37 -05:00
t . Parallel ()
2021-07-28 21:41:26 -04:00
if success , rtt := Ping ( "127.0.0.1" , & Config { Timeout : 500 * time . Millisecond }); ! success {
2020-12-25 00:07:18 -05:00
t . Error ( "expected true" )
2020-12-27 17:07:50 -05:00
if rtt == 0 {
t . Error ( "Round-trip time returned on success should've higher than 0" )
}
2020-12-25 00:07:18 -05:00
}
2021-07-28 21:41:26 -04:00
if success , rtt := Ping ( "256.256.256.256" , & Config { Timeout : 500 * time . Millisecond }); success {
2021-01-12 21:26:28 -05:00
t . Error ( "expected false, because the IP is invalid" )
if rtt != 0 {
t . Error ( "Round-trip time returned on failure should've been 0" )
}
}
2021-07-28 21:41:26 -04:00
if success , rtt := Ping ( "192.168.152.153" , & Config { Timeout : 500 * time . Millisecond }); success {
2021-01-12 21:26:28 -05:00
t . Error ( "expected false, because the IP is valid but the host should be unreachable" )
2020-12-27 17:07:50 -05:00
if rtt != 0 {
t . Error ( "Round-trip time returned on failure should've been 0" )
}
2020-12-25 00:07:18 -05:00
}
2024-02-07 03:15:51 +01:00
// Can't perform integration tests (e.g. pinging public targets by single-stacked hostname) here,
// because ICMP is blocked in the network of GitHub-hosted runners.
if success , rtt := Ping ( "127.0.0.1" , & Config { Timeout : 500 * time . Millisecond , Network : "ip" }); ! success {
t . Error ( "expected true" )
if rtt == 0 {
t . Error ( "Round-trip time returned on failure should've been 0" )
}
}
if success , rtt := Ping ( "::1" , & Config { Timeout : 500 * time . Millisecond , Network : "ip" }); ! success {
t . Error ( "expected true" )
if rtt == 0 {
t . Error ( "Round-trip time returned on failure should've been 0" )
}
}
if success , rtt := Ping ( "::1" , & Config { Timeout : 500 * time . Millisecond , Network : "ip4" }); success {
t . Error ( "expected false, because the IP isn't an IPv4 address" )
if rtt != 0 {
t . Error ( "Round-trip time returned on failure should've been 0" )
}
}
if success , rtt := Ping ( "127.0.0.1" , & Config { Timeout : 500 * time . Millisecond , Network : "ip6" }); success {
t . Error ( "expected false, because the IP isn't an IPv6 address" )
if rtt != 0 {
t . Error ( "Round-trip time returned on failure should've been 0" )
}
}
2020-12-25 00:07:18 -05:00
}
2021-06-05 21:47:11 +02:00
2021-06-05 16:35:52 -04:00
func TestCanPerformStartTLS ( t * testing . T ) {
2021-06-05 21:47:11 +02:00
type args struct {
2025-10-22 13:13:53 -04:00
address string
insecure bool
2025-09-11 04:48:49 -07:00
dnsresolver string
2021-06-05 21:47:11 +02:00
}
tests := [] struct {
2021-06-05 16:35:52 -04:00
name string
args args
wantConnected bool
wantErr bool
2021-06-05 21:47:11 +02:00
}{
{
name : "invalid address" ,
args : args {
address : "test" ,
},
2021-06-05 16:35:52 -04:00
wantConnected : false ,
wantErr : true ,
2021-06-05 21:47:11 +02:00
},
{
name : "error dial" ,
args : args {
address : "test:1234" ,
},
2021-06-05 16:35:52 -04:00
wantConnected : false ,
wantErr : true ,
2021-06-05 21:47:11 +02:00
},
{
name : "valid starttls" ,
args : args {
address : "smtp.gmail.com:587" ,
},
wantConnected : true ,
wantErr : false ,
},
2025-09-11 04:48:49 -07:00
{
name : "dns resolver" ,
args : args {
2025-10-22 13:13:53 -04:00
address : "smtp.gmail.com:587" ,
2025-09-11 04:48:49 -07:00
dnsresolver : "tcp://1.1.1.1:53" ,
},
wantConnected : true ,
wantErr : false ,
},
2021-06-05 21:47:11 +02:00
}
for _ , tt := range tests {
t . Run ( tt . name , func ( t * testing . T ) {
2023-01-08 17:53:37 -05:00
t . Parallel ()
2025-09-11 04:48:49 -07:00
connected , _ , err := CanPerformStartTLS ( tt . args . address , & Config { Insecure : tt . args . insecure , Timeout : 5 * time . Second , DNSResolver : tt . args . dnsresolver })
2021-06-05 21:47:11 +02:00
if ( err != nil ) != tt . wantErr {
2021-06-05 16:35:52 -04:00
t . Errorf ( "CanPerformStartTLS() err=%v, wantErr=%v" , err , tt . wantErr )
2021-06-05 21:47:11 +02:00
return
}
2021-06-05 16:35:52 -04:00
if connected != tt . wantConnected {
t . Errorf ( "CanPerformStartTLS() connected=%v, wantConnected=%v" , connected , tt . wantConnected )
2021-06-05 21:47:11 +02:00
}
})
}
}
2021-07-16 21:12:18 -04:00
2021-09-30 22:15:17 +02:00
func TestCanPerformTLS ( t * testing . T ) {
2021-09-30 20:45:47 -04:00
type args struct {
address string
insecure bool
}
tests := [] struct {
name string
args args
wantConnected bool
wantErr bool
}{
{
name : "invalid address" ,
args : args {
address : "test" ,
},
wantConnected : false ,
wantErr : true ,
},
{
name : "error dial" ,
args : args {
address : "test:1234" ,
},
wantConnected : false ,
wantErr : true ,
},
{
name : "valid tls" ,
args : args {
address : "smtp.gmail.com:465" ,
},
wantConnected : true ,
wantErr : false ,
},
2024-12-26 22:56:36 -05:00
{
name : "bad cert with insecure true" ,
args : args {
address : "expired.badssl.com:443" ,
insecure : true ,
},
wantConnected : true ,
wantErr : false ,
},
{
name : "bad cert with insecure false" ,
args : args {
address : "expired.badssl.com:443" ,
insecure : false ,
},
wantConnected : false ,
wantErr : true ,
},
2021-09-30 20:45:47 -04:00
}
for _ , tt := range tests {
t . Run ( tt . name , func ( t * testing . T ) {
2023-01-08 17:53:37 -05:00
t . Parallel ()
2025-07-19 19:24:03 -06:00
connected , _ , _ , err := CanPerformTLS ( tt . args . address , "" , & Config { Insecure : tt . args . insecure , Timeout : 5 * time . Second })
2021-09-30 20:45:47 -04:00
if ( err != nil ) != tt . wantErr {
t . Errorf ( "CanPerformTLS() err=%v, wantErr=%v" , err , tt . wantErr )
return
}
if connected != tt . wantConnected {
t . Errorf ( "CanPerformTLS() connected=%v, wantConnected=%v" , connected , tt . wantConnected )
}
})
}
2021-09-30 22:15:17 +02:00
}
2025-07-19 19:24:03 -06:00
func TestCanCreateConnection ( t * testing . T ) {
connected , _ := CanCreateNetworkConnection ( "tcp" , "127.0.0.1" , "" , & Config { Timeout : 5 * time . Second })
if connected {
2021-07-16 21:12:18 -04:00
t . Error ( "should've failed, because there's no port in the address" )
}
2025-07-19 19:24:03 -06:00
connected , _ = CanCreateNetworkConnection ( "tcp" , "1.1.1.1:53" , "" , & Config { Timeout : 5 * time . Second })
if ! connected {
2023-05-02 22:41:22 -04:00
t . Error ( "should've succeeded, because that IP should always™ be up" )
}
2021-07-16 21:12:18 -04:00
}
2022-03-10 02:53:51 +01:00
// This test checks if a HTTP client configured with `configureOAuth2()` automatically
// performs a Client Credentials OAuth2 flow and adds the obtained token as a `Authorization`
// header to all outgoing HTTP calls.
func TestHttpClientProvidesOAuth2BearerToken ( t * testing . T ) {
defer InjectHTTPClient ( nil )
oAuth2Config := & OAuth2Config {
ClientID : "00000000-0000-0000-0000-000000000000" ,
ClientSecret : "secretsauce" ,
TokenURL : "https://token-server.local/token" ,
Scopes : [] string { "https://application.local/.default" },
}
mockHttpClient := & http . Client {
Transport : test . MockRoundTripper ( func ( r * http . Request ) * http . Response {
// if the mock HTTP client tries to get a token from the `token-server`
// we provide the expected token response
if r . Host == "token-server.local" {
return & http . Response {
StatusCode : http . StatusOK ,
2022-05-16 22:19:42 -04:00
Body : io . NopCloser ( bytes . NewReader (
2022-03-10 02:53:51 +01:00
[] byte (
`{"token_type":"Bearer","expires_in":3599,"ext_expires_in":3599,"access_token":"secret-token"}` ,
),
)),
}
}
// to verify the headers were sent as expected, we echo them back in the
// `X-Org-Authorization` header and check if the token value matches our
// mocked `token-server` response
return & http . Response {
StatusCode : http . StatusOK ,
Header : map [ string ][] string {
"X-Org-Authorization" : { r . Header . Get ( "Authorization" )},
},
Body : http . NoBody ,
}
}),
}
mockHttpClientWithOAuth := configureOAuth2 ( mockHttpClient , * oAuth2Config )
InjectHTTPClient ( mockHttpClientWithOAuth )
request , err := http . NewRequest ( http . MethodPost , "http://127.0.0.1:8282" , http . NoBody )
if err != nil {
t . Error ( "expected no error, got" , err . Error ())
}
response , err := mockHttpClientWithOAuth . Do ( request )
if err != nil {
t . Error ( "expected no error, got" , err . Error ())
}
if response . Header == nil {
t . Error ( "expected response headers, but got nil" )
}
// the mock response echos the Authorization header used in the request back
// to us as `X-Org-Authorization` header, we check here if the value matches
// our expected token `secret-token`
if response . Header . Get ( "X-Org-Authorization" ) != "Bearer secret-token" {
2024-04-12 09:18:30 +08:00
t . Error ( "expected `secret-token` as Bearer token in the mocked response header `X-Org-Authorization`, but got" , response . Header . Get ( "X-Org-Authorization" ))
2022-03-10 02:53:51 +01:00
}
}
2023-09-28 18:35:18 -04:00
func TestQueryWebSocket ( t * testing . T ) {
2025-08-02 21:06:46 +03:00
_ , _ , err := QueryWebSocket ( "" , "body" , nil , & Config { Timeout : 2 * time . Second })
2023-09-28 18:35:18 -04:00
if err == nil {
t . Error ( "expected an error due to the address being invalid" )
}
2025-08-02 21:06:46 +03:00
_ , _ , err = QueryWebSocket ( "ws://example.org" , "body" , nil , & Config { Timeout : 2 * time . Second })
2023-09-28 18:35:18 -04:00
if err == nil {
t . Error ( "expected an error due to the target not being websocket-friendly" )
}
}
2024-04-09 18:41:37 -04:00
func TestTlsRenegotiation ( t * testing . T ) {
2025-10-22 13:13:53 -04:00
scenarios := [] struct {
2024-04-09 18:41:37 -04:00
name string
cfg TLSConfig
expectedConfig tls . RenegotiationSupport
}{
{
name : "default" ,
cfg : TLSConfig { CertificateFile : "../testdata/cert.pem" , PrivateKeyFile : "../testdata/cert.key" },
expectedConfig : tls . RenegotiateNever ,
},
{
name : "never" ,
cfg : TLSConfig { RenegotiationSupport : "never" , CertificateFile : "../testdata/cert.pem" , PrivateKeyFile : "../testdata/cert.key" },
expectedConfig : tls . RenegotiateNever ,
},
{
name : "once" ,
cfg : TLSConfig { RenegotiationSupport : "once" , CertificateFile : "../testdata/cert.pem" , PrivateKeyFile : "../testdata/cert.key" },
expectedConfig : tls . RenegotiateOnceAsClient ,
},
{
name : "freely" ,
cfg : TLSConfig { RenegotiationSupport : "freely" , CertificateFile : "../testdata/cert.pem" , PrivateKeyFile : "../testdata/cert.key" },
expectedConfig : tls . RenegotiateFreelyAsClient ,
},
{
name : "not-valid-and-broken" ,
cfg : TLSConfig { RenegotiationSupport : "invalid" , CertificateFile : "../testdata/cert.pem" , PrivateKeyFile : "../testdata/cert.key" },
expectedConfig : tls . RenegotiateNever ,
},
}
2025-10-22 13:13:53 -04:00
for _ , scenario := range scenarios {
t . Run ( scenario . name , func ( t * testing . T ) {
2024-04-09 18:41:37 -04:00
tls := & tls . Config {}
2025-10-22 13:13:53 -04:00
tlsConfig := configureTLS ( tls , scenario . cfg )
if tlsConfig . Renegotiation != scenario . expectedConfig {
t . Errorf ( "expected tls renegotiation to be %v, but got %v" , scenario . expectedConfig , tls . Renegotiation )
2024-04-09 18:41:37 -04:00
}
})
}
}
2024-05-09 22:56:16 -04:00
func TestQueryDNS ( t * testing . T ) {
2025-01-18 20:26:25 -05:00
scenarios := [] struct {
2024-05-09 22:56:16 -04:00
name string
inputDNS dns . Config
inputURL string
expectedDNSCode string
expectedBody string
isErrExpected bool
}{
{
name : "test Config with type A" ,
inputDNS : dns . Config {
QueryType : "A" ,
QueryName : "example.com." ,
},
inputURL : "8.8.8.8" ,
expectedDNSCode : "NOERROR" ,
2025-01-18 20:26:25 -05:00
expectedBody : "__IPV4__" ,
2024-05-09 22:56:16 -04:00
},
{
name : "test Config with type AAAA" ,
inputDNS : dns . Config {
QueryType : "AAAA" ,
QueryName : "example.com." ,
},
inputURL : "8.8.8.8" ,
expectedDNSCode : "NOERROR" ,
2025-01-18 20:26:25 -05:00
expectedBody : "__IPV6__" ,
2024-05-09 22:56:16 -04:00
},
{
name : "test Config with type CNAME" ,
inputDNS : dns . Config {
QueryType : "CNAME" ,
QueryName : "en.wikipedia.org." ,
},
inputURL : "8.8.8.8" ,
expectedDNSCode : "NOERROR" ,
expectedBody : "dyna.wikimedia.org." ,
},
{
name : "test Config with type MX" ,
inputDNS : dns . Config {
QueryType : "MX" ,
QueryName : "example.com." ,
},
inputURL : "8.8.8.8" ,
expectedDNSCode : "NOERROR" ,
expectedBody : "." ,
},
{
name : "test Config with type NS" ,
inputDNS : dns . Config {
QueryType : "NS" ,
QueryName : "example.com." ,
},
inputURL : "8.8.8.8" ,
expectedDNSCode : "NOERROR" ,
expectedBody : "*.iana-servers.net." ,
},
2024-11-28 23:21:44 +00:00
{
name : "test Config with type PTR" ,
inputDNS : dns . Config {
QueryType : "PTR" ,
QueryName : "8.8.8.8.in-addr.arpa." ,
},
inputURL : "8.8.8.8" ,
expectedDNSCode : "NOERROR" ,
expectedBody : "dns.google." ,
},
2025-09-15 21:52:57 +08:00
{
name : "test Config with type PTR and forward IP / no in-addr" ,
inputDNS : dns . Config {
QueryType : "PTR" ,
QueryName : "1.0.0.1" ,
},
inputURL : "1.1.1.1" ,
expectedDNSCode : "NOERROR" ,
expectedBody : "one.one.one.one." ,
},
2024-05-09 22:56:16 -04:00
{
name : "test Config with fake type and retrieve error" ,
inputDNS : dns . Config {
QueryType : "B" ,
QueryName : "example" ,
},
inputURL : "8.8.8.8" ,
isErrExpected : true ,
},
}
2025-01-18 20:26:25 -05:00
for _ , scenario := range scenarios {
t . Run ( scenario . name , func ( t * testing . T ) {
_ , dnsRCode , body , err := QueryDNS ( scenario . inputDNS . QueryType , scenario . inputDNS . QueryName , scenario . inputURL )
if scenario . isErrExpected && err == nil {
2024-05-09 22:56:16 -04:00
t . Errorf ( "there should be an error" )
}
2025-01-18 20:26:25 -05:00
if dnsRCode != scenario . expectedDNSCode {
t . Errorf ( "expected DNSRCode to be %s, got %s" , scenario . expectedDNSCode , dnsRCode )
2024-05-09 22:56:16 -04:00
}
2025-01-18 20:26:25 -05:00
if scenario . inputDNS . QueryType == "NS" {
2024-05-09 22:56:16 -04:00
// Because there are often multiple nameservers backing a single domain, we'll only look at the suffix
2025-01-18 20:26:25 -05:00
if ! pattern . Match ( scenario . expectedBody , string ( body )) {
t . Errorf ( "got %s, expected result %s," , string ( body ), scenario . expectedBody )
2024-05-09 22:56:16 -04:00
}
} else {
2025-01-18 20:26:25 -05:00
if string ( body ) != scenario . expectedBody {
// little hack to validate arbitrary ipv4/ipv6
switch scenario . expectedBody {
case "__IPV4__" :
if addr , err := netip . ParseAddr ( string ( body )); err != nil {
t . Errorf ( "got %s, expected result %s" , string ( body ), scenario . expectedBody )
} else if ! addr . Is4 () {
t . Errorf ( "got %s, expected valid IPv4" , string ( body ))
}
case "__IPV6__" :
if addr , err := netip . ParseAddr ( string ( body )); err != nil {
t . Errorf ( "got %s, expected result %s" , string ( body ), scenario . expectedBody )
} else if ! addr . Is6 () {
t . Errorf ( "got %s, expected valid IPv6" , string ( body ))
}
default :
t . Errorf ( "got %s, expected result %s" , string ( body ), scenario . expectedBody )
}
2024-05-09 22:56:16 -04:00
}
}
})
2025-01-18 20:26:25 -05:00
time . Sleep ( 10 * time . Millisecond )
2024-05-09 22:56:16 -04:00
}
}
2025-01-19 23:22:41 +02:00
func TestCheckSSHBanner ( t * testing . T ) {
cfg := & Config { Timeout : 3 }
t . Run ( "no-auth-ssh" , func ( t * testing . T ) {
connected , status , err := CheckSSHBanner ( "tty.sdf.org" , cfg )
if err != nil {
t . Errorf ( "Expected: error != nil, got: %v " , err )
}
if connected == false {
t . Errorf ( "Expected: connected == true, got: %v" , connected )
}
if status != 0 {
t . Errorf ( "Expected: 0, got: %v" , status )
}
})
t . Run ( "invalid-address" , func ( t * testing . T ) {
connected , status , err := CheckSSHBanner ( "idontplaytheodds.com" , cfg )
if err == nil {
t . Errorf ( "Expected: error, got: %v " , err )
}
if connected != false {
t . Errorf ( "Expected: connected == false, got: %v" , connected )
}
if status != 1 {
t . Errorf ( "Expected: 1, got: %v" , status )
}
})
}