Skip to content

Added license checks when targeting queries by label (33045)#41255

Merged
juan-fdz-hawa merged 2 commits intomainfrom
33045-fleet-free---targeting-queries-by-label-not-blocked-rest-api
Mar 9, 2026
Merged

Added license checks when targeting queries by label (33045)#41255
juan-fdz-hawa merged 2 commits intomainfrom
33045-fleet-free---targeting-queries-by-label-not-blocked-rest-api

Conversation

@juan-fdz-hawa
Copy link
Copy Markdown
Contributor

@juan-fdz-hawa juan-fdz-hawa commented Mar 9, 2026

Related issue: Resolves #33045

When creating or updating queries either via the API or Gitops, make sure that the license is premium if the query is targeting a label.

Checklist for submitter

If some of the following don't apply, delete the relevant line.

  • Changes file added for user-visible changes in changes/, orbit/changes/ or ee/fleetd-chrome/changes.
    See Changes files for more information.

Testing

  • Added/updated automated tests
  • QA'd all new/changed functionality manually

Summary by CodeRabbit

Release Notes

  • Premium Features
    • Label-based query targeting now requires Fleet Premium license
    • GitOps configuration processing enforces premium licensing for label-based query filters
    • Free tier users receive a payment required response when attempting label-based query operations

When creating or updating queries either via the API or Gitops,
make sure that the license is premium if the query is targeting
a label.
@codecov
Copy link
Copy Markdown

codecov Bot commented Mar 9, 2026

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 66.35%. Comparing base (1bf6df1) to head (4c96d9d).
⚠️ Report is 14 commits behind head on main.

Additional details and impacted files
@@           Coverage Diff           @@
##             main   #41255   +/-   ##
=======================================
  Coverage   66.34%   66.35%           
=======================================
  Files        2477     2477           
  Lines      198439   198470   +31     
  Branches     8890     8890           
=======================================
+ Hits       131660   131700   +40     
+ Misses      54876    54865   -11     
- Partials    11903    11905    +2     
Flag Coverage Δ
backend 68.14% <100.00%> (+0.01%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@juan-fdz-hawa
Copy link
Copy Markdown
Contributor Author

@coderabbitai full review

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented Mar 9, 2026

✅ Actions performed

Full review triggered.

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented Mar 9, 2026

Walkthrough

This PR adds license enforcement for label-based query targeting across the Fleet REST API and CLI. It introduces premium license checks in the query creation (NewQuery), modification (ModifyQuery), and spec application (ApplyQuerySpecs) endpoints to prevent queries using the LabelsIncludeAny field from being created or modified without a premium license. The GitOps gitops.go file is updated to validate that queries in GitOps configurations do not use label targeting on non-premium instances. Comprehensive tests are added to verify the license gating behavior across REST API integration tests, unit tests, and CLI test scenarios.

Possibly related PRs

  • PR #37246: Modifies server/service/queries.go with additional pre-condition checks around LabelsIncludeAny for team-assignment and label verification validation.
  • PR #37801: Updates GitOps label handling in gitops.go and related tests to implement team-labels and label-move logic alongside premium license guards.
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 8.33% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and concisely summarizes the main change: adding license checks for targeting queries by label, with the issue reference (33045).
Description check ✅ Passed The description includes the related issue reference, explains the purpose of the change, and checks all critical boxes (changes file, automated tests, manual QA).
Linked Issues check ✅ Passed The code changes comprehensively implement the requirement to enforce license checks when targeting queries by label across API, GitOps, and all code paths.
Out of Scope Changes check ✅ Passed All changes are directly related to enforcing premium license checks for label-based query targeting, with no unrelated modifications detected.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
  • 📝 Generate docstrings (stacked PR)
  • 📝 Generate docstrings (commit on current branch)
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch 33045-fleet-free---targeting-queries-by-label-not-blocked-rest-api

Tip

Try Coding Plans. Let us write the prompt for your AI agent so you can ship faster (with fewer bugs).
Share your feedback on Discord.


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (2)
cmd/fleetctl/fleetctl/gitops_test.go (2)

1162-1164: Tighten this label-ID mock so it can't hide partial resolution bugs.

Right now the stub returns both IDs no matter what names contains. That means this test would still pass if GitOps only asked the datastore for one label, or the wrong set entirely.

Suggested tightening
 ds.LabelIDsByNameFunc = func(ctx context.Context, names []string, filter fleet.TeamFilter) (map[string]uint, error) {
-	return map[string]uint{"a": 1, "b": 2}, nil
+	require.ElementsMatch(t, []string{"a", "b"}, names)
+	ids := make(map[string]uint, len(names))
+	for _, name := range names {
+		switch name {
+		case "a":
+			ids[name] = 1
+		case "b":
+			ids[name] = 2
+		}
+	}
+	return ids, nil
 }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@cmd/fleetctl/fleetctl/gitops_test.go` around lines 1162 - 1164, The mock for
LabelIDsByNameFunc is too permissive and returns both IDs regardless of the
input, which can hide bugs where the code requests the wrong labels or a subset;
update the LabelIDsByNameFunc stub to inspect the incoming names slice and
return a map containing only the requested label names (or an error for unknown
names) so tests fail when the code queries the wrong set—change the
implementation of LabelIDsByNameFunc to validate the names argument and produce
a result keyed only by those names (or return an error) instead of always
returning {"a":1,"b":2}.

1247-1249: Avoid keying this assertion off appliedQueries[0].

These checks are order-dependent. If ApplyQueries changes ordering, this test will fail even though label resolution is still correct. Resolve the query by name first, then assert its labels.

Suggested rewrite
-	assert.Len(t, appliedQueries[0].LabelsIncludeAny, 2)
-	assert.Contains(t, []string{appliedQueries[0].LabelsIncludeAny[0].LabelName, appliedQueries[0].LabelsIncludeAny[1].LabelName}, "a")
-	assert.Contains(t, []string{appliedQueries[0].LabelsIncludeAny[0].LabelName, appliedQueries[0].LabelsIncludeAny[1].LabelName}, "b")
+	var labeledQuery *fleet.Query
+	for _, q := range appliedQueries {
+		if q.Name == "test_query" || q.Name == "test-query" {
+			labeledQuery = q
+			break
+		}
+	}
+	require.NotNil(t, labeledQuery)
+	require.Len(t, labeledQuery.LabelsIncludeAny, 2)
+	assert.ElementsMatch(t, []string{"a", "b"}, []string{
+		labeledQuery.LabelsIncludeAny[0].LabelName,
+		labeledQuery.LabelsIncludeAny[1].LabelName,
+	})
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@cmd/fleetctl/fleetctl/gitops_test.go` around lines 1247 - 1249, Test
currently asserts labels using appliedQueries[0], which is order-dependent;
instead locate the specific query by its name within the appliedQueries slice
(e.g., find the element whose Name or QueryName equals the expected value) and
then assert against that query's LabelsIncludeAny values in an order-independent
way (verify the set contains "a" and "b" by checking the LabelName values of
LabelsIncludeAny). Use the foundQuery variable (or similar) rather than
appliedQueries[0] and assert membership of both labels without relying on
element order.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@cmd/fleetctl/fleetctl/gitops.go`:
- Around line 315-322: Fix the typo in the inline comment: change "Targeting
queries agaisnt labels is a Premium feature only" to "Targeting queries against
labels is a Premium feature only" near the block that checks
appConfig.License.IsPremium() and iterates over config.Queries to inspect
query.LabelsIncludeAny; do not modify the conditional logic checking
len(query.LabelsIncludeAny) > 0 or the error message returned.

---

Nitpick comments:
In `@cmd/fleetctl/fleetctl/gitops_test.go`:
- Around line 1162-1164: The mock for LabelIDsByNameFunc is too permissive and
returns both IDs regardless of the input, which can hide bugs where the code
requests the wrong labels or a subset; update the LabelIDsByNameFunc stub to
inspect the incoming names slice and return a map containing only the requested
label names (or an error for unknown names) so tests fail when the code queries
the wrong set—change the implementation of LabelIDsByNameFunc to validate the
names argument and produce a result keyed only by those names (or return an
error) instead of always returning {"a":1,"b":2}.
- Around line 1247-1249: Test currently asserts labels using appliedQueries[0],
which is order-dependent; instead locate the specific query by its name within
the appliedQueries slice (e.g., find the element whose Name or QueryName equals
the expected value) and then assert against that query's LabelsIncludeAny values
in an order-independent way (verify the set contains "a" and "b" by checking the
LabelName values of LabelsIncludeAny). Use the foundQuery variable (or similar)
rather than appliedQueries[0] and assert membership of both labels without
relying on element order.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 4784d944-8847-45cd-9ead-512c37ec5337

📥 Commits

Reviewing files that changed from the base of the PR and between 8b435c5 and 8fb9596.

📒 Files selected for processing (6)
  • changes/33045-fleet-free-targetting-queries-by-label
  • cmd/fleetctl/fleetctl/gitops.go
  • cmd/fleetctl/fleetctl/gitops_test.go
  • server/service/integration_core_test.go
  • server/service/queries.go
  • server/service/queries_test.go

Comment thread cmd/fleetctl/fleetctl/gitops.go Outdated
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
Copy link
Copy Markdown
Contributor

@sgress454 sgress454 left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

tested 👍

return document, nil, nil
}

// Premium mocks
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

only the freshest, hottest mocks

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@juan-fdz-hawa juan-fdz-hawa merged commit baa413a into main Mar 9, 2026
43 checks passed
@juan-fdz-hawa juan-fdz-hawa deleted the 33045-fleet-free---targeting-queries-by-label-not-blocked-rest-api branch March 9, 2026 20:54
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Fleet Free - Targeting queries by label is blocked in the UI, but not in the REST API

2 participants