Fixed issue with shelly self signed certificate.
This commit is contained in:
+13
-1
@@ -3,6 +3,7 @@ package shelly
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/tls"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
@@ -39,11 +40,22 @@ func NewClient(rawURL, username, password string, timeout time.Duration) (*Clien
|
||||
username: username,
|
||||
password: password,
|
||||
httpClient: &http.Client{
|
||||
Timeout: timeout,
|
||||
Timeout: timeout,
|
||||
Transport: insecureTLSTransport(),
|
||||
},
|
||||
}, nil
|
||||
}
|
||||
|
||||
// insecureTLSTransport retains the standard HTTP transport behavior but accepts
|
||||
// certificates that are expired, self-signed, or issued for another hostname.
|
||||
func insecureTLSTransport() *http.Transport {
|
||||
transport := http.DefaultTransport.(*http.Transport).Clone()
|
||||
transport.TLSClientConfig = &tls.Config{
|
||||
InsecureSkipVerify: true, // #nosec G402 -- Shelly device certificates are intentionally not verified.
|
||||
}
|
||||
return transport
|
||||
}
|
||||
|
||||
// GetStatus decodes the /status response into destination.
|
||||
func (c *Client) GetStatus(ctx context.Context, destination any) error {
|
||||
statusURL := *c.baseURL
|
||||
|
||||
@@ -38,6 +38,28 @@ func TestClientGetStatusUsesStatusEndpointAndBasicAuth(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestClientGetStatusAcceptsUntrustedTLSCertificate(t *testing.T) {
|
||||
server := httptest.NewTLSServer(http.HandlerFunc(func(response http.ResponseWriter, _ *http.Request) {
|
||||
response.Header().Set("Content-Type", "application/json")
|
||||
_, _ = response.Write([]byte(`{"serial":42}`))
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
client, err := NewClient(server.URL, "", "", time.Second)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var status struct {
|
||||
Serial int `json:"serial"`
|
||||
}
|
||||
if err := client.GetStatus(context.Background(), &status); err != nil {
|
||||
t.Fatalf("GetStatus() returned an unexpected TLS certificate error: %v", err)
|
||||
}
|
||||
if status.Serial != 42 {
|
||||
t.Fatalf("Serial = %d, want 42", status.Serial)
|
||||
}
|
||||
}
|
||||
|
||||
func TestClientGetStatusReportsHTTPError(t *testing.T) {
|
||||
server := httptest.NewServer(http.HandlerFunc(func(response http.ResponseWriter, _ *http.Request) {
|
||||
http.Error(response, "not authorized", http.StatusUnauthorized)
|
||||
|
||||
Reference in New Issue
Block a user