crowdsecurity/crowdsec · error

failed to build alert request: %w

Error message

failed to build alert request: %w

What it means

AlertsCountPerScenario fails to build the ent query when applyAlertFilter rejects the provided filter (e.g. an invalid since/until date or malformed filter value). The error reports that the alert-count request could not be constructed.

Source

Thrown at pkg/database/alerts.go:777

		if err != nil {
			return nil, fmt.Errorf("machine '%s': %w", machineID, err)
		}
	}

	return alertIDs, nil
}

func (c *Client) AlertsCountPerScenario(ctx context.Context, filter map[string][]string) (map[string]int, error) {
	var res []struct {
		Scenario string
		Count    int
	}

	query := c.Ent.Alert.Query()

	query, err := applyAlertFilter(query, filter)
	if err != nil {
		return nil, fmt.Errorf("failed to build alert request: %w", err)
	}

	err = query.GroupBy(alert.FieldScenario).Aggregate(ent.Count()).Scan(ctx, &res)
	if err != nil {
		return nil, fmt.Errorf("failed to count alerts per scenario: %w", err)
	}

	counts := make(map[string]int)

	for _, r := range res {
		counts[r.Scenario] = r.Count
	}

	return counts, nil
}

func (c *Client) TotalAlerts(ctx context.Context) (int, error) {
	return c.Ent.Alert.Query().Count(ctx)

View on GitHub (pinned to 909b515798)

Solutions

  1. Fix the filter value that applyAlertFilter rejects (check the wrapped error for the field)
  2. Use RFC3339 for since/until date filters
  3. Check the wrapped error with errors.Is against time parsing sentinels
  4. Validate query parameters on the client before calling the LAPI

Example fix

// before
filter := models.AlertsFilter{"since": "yesterday"}
counts, err := db.AlertsCountPerScenario(ctx, filter)
// after
filter := models.AlertsFilter{"since": time.Now().Add(-24 * time.Hour).Format(time.RFC3339)}
counts, err := db.AlertsCountPerScenario(ctx, filter)
Defensive patterns

Strategy: validation

Validate before calling

if since, ok := filter["since"]; ok {
    if _, err := time.Parse(time.RFC3339, since); err != nil {
        return fmt.Errorf("invalid since: %w", err)
    }
}

Prevention

When it happens

Trigger: Calling AlertsCountPerScenario with a filter containing values applyAlertFilter cannot parse (bad time format, invalid field name passed through from a LAPI query string).

Common situations: API clients passing malformed `since`/`until` parameters; custom dashboards hitting LAPI /alerts with hand-built query strings; version drift where a filter key was renamed.

Understand the failure class

Background: "Invalid query parameter" / "Failed to parse value of ...": fixing bad query string parameters across APIs — this error's family across 36 libraries.

Related errors


AI-assisted analysis of crowdsecurity/crowdsec@909b515798 (2026-09-06). Data as JSON: /api/errors/643043ebc9ed21ce. Report an issue: GitHub.