Ver Fonte

provisioner: redact webhook URL details from all webhook call errors

Webhook transport errors (*url.Error from http.Client.Do or
NewRequestWithContext) embed the full expanded URL, and a
customer-configured webhook URL can carry credentials in userinfo,
path, or query. Redact at every error return of Webhook.DoWithContext:
logs keep the webhook name, scheme, host, and cause, while userinfo,
path, query, and fragment render as <redacted> markers when present.
A root path renders as-is. If the URL cannot be parsed, fail closed to
<redacted>. The body-close log line also redacts the configured URL.
Covers the SCEP challenge, authorizing, and enriching webhook paths.
Christian Mejlak há 1 mês atrás
pai
commit
0cab6d272f

+ 49 - 4
authority/provisioner/webhook.go

@@ -188,6 +188,51 @@ func (w *Webhook) Validate() error {
 // [http.RoundTripper].
 type TransportWrapper = httptransport.Wrapper
 
+// redactWebhookURLError rewrites a transport error from a webhook call so logs
+// keep the webhook name, scheme, host, and underlying cause, while userinfo,
+// path, query, and fragment are replaced with "<redacted>" markers. If the URL
+// cannot be parsed, it fails closed and the URL renders as "<redacted>".
+func redactWebhookURLError(err error, name string) error {
+	var urlErr *url.Error
+	if errors.As(err, &urlErr) {
+		redacted := *urlErr
+		redacted.URL = redactURLString(urlErr.URL)
+		return fmt.Errorf("webhook %q: %w", name, &redacted)
+	}
+	return err
+}
+
+// redactURLString renders a raw URL string with every sensitive part replaced
+// by a "<redacted>" marker, failing closed to "<redacted>" when unparseable.
+func redactURLString(raw string) string {
+	u, err := url.Parse(raw)
+	if err != nil {
+		return "<redacted>"
+	}
+	return redactURL(u)
+}
+
+// redactURL renders a URL as scheme://[userinfo@]host with every sensitive
+// part replaced by a "<redacted>" marker when present. A root path "/" carries
+// nothing sensitive and is kept as-is.
+func redactURL(u *url.URL) string {
+	s := u.Scheme + "://"
+	if u.User != nil {
+		s += "<redacted>@"
+	}
+	s += u.Host
+	if u.Path != "" && u.Path != "/" {
+		s += "/<redacted>"
+	}
+	if u.RawQuery != "" {
+		s += "?<redacted>"
+	}
+	if u.Fragment != "" {
+		s += "#<redacted>"
+	}
+	return s
+}
+
 func (w *Webhook) DoWithContext(ctx context.Context, client HTTPClient, tw TransportWrapper, reqBody *webhook.RequestBody, data any) (*webhook.ResponseBody, error) {
 	tmpl, err := template.New("url").Funcs(templates.StepFuncMap()).Parse(w.URL)
 	if err != nil {
@@ -224,7 +269,7 @@ retry:
 
 	req, err := http.NewRequestWithContext(ctx, "POST", webhookURL, bytes.NewReader(reqBytes))
 	if err != nil {
-		return nil, err
+		return nil, redactWebhookURLError(err, w.Name)
 	}
 
 	req.Header.Set("Content-Type", "application/json")
@@ -269,17 +314,17 @@ retry:
 	resp, err := client.Do(req)
 	if err != nil {
 		if errors.Is(err, context.DeadlineExceeded) {
-			return nil, err
+			return nil, redactWebhookURLError(err, w.Name)
 		} else if retries > 0 {
 			retries--
 			time.Sleep(time.Second)
 			goto retry
 		}
-		return nil, err
+		return nil, redactWebhookURLError(err, w.Name)
 	}
 	defer func() {
 		if err := resp.Body.Close(); err != nil {
-			log.Printf("Failed to close body of response from %s", w.URL)
+			log.Printf("Failed to close body of response from webhook %q URL %s", w.Name, redactURLString(w.URL))
 		}
 	}()
 	if resp.StatusCode >= 500 && retries > 0 {

+ 89 - 0
authority/provisioner/webhook_redact_test.go

@@ -0,0 +1,89 @@
+package provisioner
+
+import (
+	"context"
+	"encoding/base64"
+	"errors"
+	"net/http"
+	"net/url"
+	"testing"
+
+	"github.com/smallstep/certificates/webhook"
+	"github.com/stretchr/testify/require"
+)
+
+func TestRedactWebhookURLError(t *testing.T) {
+	const name = "test-webhook"
+
+	// path and query are marked, not shown; the webhook name is included
+	err := &url.Error{Op: "Post", URL: "https://hooks.example.com/validate?token=secret", Err: errors.New("connection refused")}
+	got := redactWebhookURLError(err, name)
+	require.Equal(t, `webhook "test-webhook": Post "https://hooks.example.com/<redacted>?<redacted>": connection refused`, got.Error())
+	require.NotContains(t, got.Error(), "token=secret")
+	require.NotContains(t, got.Error(), "/validate")
+
+	// userinfo is marked too
+	withUser := &url.Error{Op: "Post", URL: "https://user:token@hooks.example.com/validate", Err: errors.New("connection refused")}
+	got = redactWebhookURLError(withUser, name)
+	require.Equal(t, `webhook "test-webhook": Post "https://<redacted>@hooks.example.com/<redacted>": connection refused`, got.Error())
+	require.NotContains(t, got.Error(), "user:token")
+
+	// a bare host with a root path renders without markers
+	bare := &url.Error{Op: "Post", URL: "https://hooks.example.com/", Err: errors.New("connection refused")}
+	require.Equal(t, `webhook "test-webhook": Post "https://hooks.example.com": connection refused`, redactWebhookURLError(bare, name).Error())
+
+	// deadline errors keep working through the wrapper
+	deadline := &url.Error{Op: "Post", URL: "https://hooks.example.com/x?token=secret", Err: context.DeadlineExceeded}
+	require.ErrorIs(t, redactWebhookURLError(deadline, name), context.DeadlineExceeded)
+
+	// fail closed when the URL cannot be parsed: no raw URL, name and cause kept
+	bad := &url.Error{Op: "Post", URL: "https://hooks.example.com/val%zz?token=secret", Err: errors.New("connection refused")}
+	got = redactWebhookURLError(bad, name)
+	require.Equal(t, `webhook "test-webhook": Post "<redacted>": connection refused`, got.Error())
+	require.NotContains(t, got.Error(), "token=secret")
+	require.ErrorIs(t, got, bad.Err)
+
+	// non-URL errors pass through unchanged, without a name prefix
+	plain := errors.New("boom")
+	require.Equal(t, plain, redactWebhookURLError(plain, name))
+}
+
+func TestRedactURLString(t *testing.T) {
+	// a URL template with actions still parses and redacts
+	require.Equal(t,
+		`https://hooks.example.com/<redacted>?<redacted>`,
+		redactURLString(`https://hooks.example.com/{{ .Webhooks.ScepChallenge.ID }}/validate?token=x`))
+	// unparseable input fails closed
+	require.Equal(t, "<redacted>", redactURLString("https://hooks.example.com/val%zz?token=x\n"))
+}
+
+func TestWebhookDoWithContextRedactsURL(t *testing.T) {
+	w := &Webhook{
+		Name:   "test-webhook",
+		URL:    "http://127.0.0.1:1/validate?token=secret",
+		Secret: base64.StdEncoding.EncodeToString([]byte("secret")),
+	}
+
+	_, err := w.DoWithContext(context.Background(), &http.Client{}, nil, &webhook.RequestBody{}, nil)
+	require.Error(t, err)
+	require.NotContains(t, err.Error(), "token=secret")
+	require.NotContains(t, err.Error(), "/validate")
+	require.Contains(t, err.Error(), `webhook "test-webhook": Post "http://127.0.0.1:1/<redacted>?<redacted>"`)
+	require.Contains(t, err.Error(), "connection refused")
+}
+
+func TestWebhookDoWithContextRedactsNewRequestError(t *testing.T) {
+	// A control character in the templated URL makes NewRequestWithContext
+	// fail; its error carries the raw expanded URL and must be redacted too.
+	w := &Webhook{
+		Name:   "test-webhook",
+		URL:    "http://127.0.0.1:1/validate?token=secret\n",
+		Secret: base64.StdEncoding.EncodeToString([]byte("secret")),
+	}
+
+	_, err := w.DoWithContext(context.Background(), &http.Client{}, nil, &webhook.RequestBody{}, nil)
+	require.Error(t, err)
+	require.NotContains(t, err.Error(), "token=secret")
+	require.Contains(t, err.Error(), `webhook "test-webhook"`)
+	require.Contains(t, err.Error(), "<redacted>")
+}