package s3notification import ( "bytes" "context" "errors" "fmt" "io" "net/http" "net/url" "time" "github.com/seaweedfs/seaweedfs/weed/pb/schema_pb" "github.com/seaweedfs/seaweedfs/weed/util/netguard" ) const ( webhookTimeout = 30 * time.Second // webhookErrorBodyLimit is how much of a refusal's body is kept for the log. webhookErrorBodyLimit = 256 maxWebhookRedirects = 10 ) // destination delivers a batch of records in order; nil means the // destination took all of them, and an *unrenderableError names records it // never will. type destination interface { Send(ctx context.Context, records []*schema_pb.RecordValue) error } // webhook POSTs a batch as one {"Records":[...]} body, a test event in its // own body, and takes any 2xx as delivered. type webhook struct { endpoint string token string render func(records ...*schema_pb.RecordValue) ([]byte, error) client *http.Client } func newWebhook(t *Target) *webhook { return &webhook{ endpoint: t.Endpoint, token: t.BearerToken, render: Render, client: &http.Client{ Timeout: webhookTimeout, Transport: &http.Transport{ // no proxy, so the dialer checks the address actually connected to Proxy: nil, DialContext: netguard.DialContext(redactedEndpoint(t.Endpoint), netguard.Local), ForceAttemptHTTP2: true, MaxIdleConnsPerHost: 4, IdleConnTimeout: 90 * time.Second, TLSHandshakeTimeout: 10 * time.Second, }, CheckRedirect: sameHostRedirect, }, } } // sameHostRedirect follows a redirect only to the endpoint's own host and // never from https to http, so the token and records stay with the endpoint // the operator configured. Only 307 and 308 are followed: on 301, 302 and 303 // Go resends the POST as a bodiless GET, whose 2xx would pass for delivery. func sameHostRedirect(req *http.Request, via []*http.Request) error { if len(via) >= maxWebhookRedirects { return fmt.Errorf("stopped after %d redirects", len(via)) } if code := req.Response.StatusCode; code != http.StatusTemporaryRedirect && code != http.StatusPermanentRedirect { return fmt.Errorf("refusing redirect %d, which would drop the posted records", code) } from := via[0].URL if req.URL.Host != from.Host || (from.Scheme == "https" && req.URL.Scheme != "https") { return fmt.Errorf("refusing redirect from %s://%s to %s://%s", from.Scheme, from.Host, req.URL.Scheme, req.URL.Host) } return nil } // redactedEndpoint names an endpoint in errors and logs without what it may // carry in its userinfo, query or fragment. func redactedEndpoint(endpoint string) string { u, err := url.Parse(endpoint) if err != nil { return "unparsable endpoint" } return (&url.URL{Scheme: u.Scheme, Host: u.Host, Path: u.Path}).String() } func (w *webhook) Send(ctx context.Context, records []*schema_pb.RecordValue) error { if u, err := url.Parse(w.endpoint); err != nil { return errors.New("unparsable endpoint") } else if netguard.IsMetadataHost(u.Hostname()) { return fmt.Errorf("endpoint %s targets the instance metadata service", u.Hostname()) } // render everything before posting anything, so dropping an unrenderable // record and sending the rest again does not repeat a body var bodies [][]byte unrenderable := &unrenderableError{} renderRun := func(start, end int) { if start == end { return } if body, err := w.render(records[start:end]...); err == nil { bodies = append(bodies, body) return } for i := start; i < end; i++ { body, err := w.render(records[i]) if err != nil { unrenderable.indexes = append(unrenderable.indexes, i) unrenderable.err = err continue } bodies = append(bodies, body) } } start := 0 for i, r := range records { if IsTestEvent(r) { renderRun(start, i) renderRun(i, i+1) start = i + 1 } } renderRun(start, len(records)) if len(unrenderable.indexes) > 0 { return unrenderable } for _, body := range bodies { if err := w.post(ctx, body); err != nil { return err } } return nil } // unrenderableError names the records of a batch that cannot be rendered, so // sending them again cannot succeed. type unrenderableError struct { indexes []int // into the batch given to Send err error } func (e *unrenderableError) Error() string { return fmt.Sprintf("%d records cannot be rendered: %v", len(e.indexes), e.err) } func (e *unrenderableError) Unwrap() error { return e.err } func (w *webhook) post(ctx context.Context, body []byte) error { req, err := http.NewRequestWithContext(ctx, http.MethodPost, w.endpoint, bytes.NewReader(body)) if err != nil { return fmt.Errorf("post to %s: invalid request", redactedEndpoint(w.endpoint)) } req.Header.Set("Content-Type", "application/json") if w.token != "" { req.Header.Set("Authorization", "Bearer "+w.token) } resp, err := w.client.Do(req) if err != nil { var urlErr *url.Error if errors.As(err, &urlErr) { // the URL may carry credentials in its query; the cause is enough return fmt.Errorf("post: %w", urlErr.Err) } return err } defer resp.Body.Close() if resp.StatusCode/100 == 2 { _, _ = io.Copy(io.Discard, io.LimitReader(resp.Body, 64*1024)) return nil } detail, _ := io.ReadAll(io.LimitReader(resp.Body, webhookErrorBodyLimit)) return fmt.Errorf("endpoint answered %s: %s", resp.Status, bytes.TrimSpace(detail)) }