Skip to content

Improve fleet scope validation for software title lookups#48034

Merged
sharon-fdm merged 4 commits into
mainfrom
fix-software-title-scope-validation
Jun 23, 2026
Merged

Improve fleet scope validation for software title lookups#48034
sharon-fdm merged 4 commits into
mainfrom
fix-software-title-scope-validation

Conversation

@sharon-fdm

@sharon-fdm sharon-fdm commented Jun 22, 2026

Copy link
Copy Markdown
Collaborator

Summary

Ensures that SoftwareTitleByID validates fleet scope for all non-nil team_id values, including zero. Previously the scope check was only applied when team_id > 0.

Reproduction

Added a unit test (TestSoftwareTitleByIDTeamIDZero) that sets up a fleet-scoped user on fleet 1, then calls SoftwareTitleByID with team_id=0. Before this change, the call succeeded. After, it correctly returns 403.

Also confirmed that a global admin calling with team_id=0 still succeeds, and that all existing TestServiceSoftwareTitlesAuth subtests continue to pass.

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.

  • Input data is properly validated, SELECT * is avoided, SQL injection is prevented (using placeholders for values in statements), JS inline code is prevented especially for url redirects, and untrusted data interpolated into shell scripts/commands is validated against shell metacharacters.

Testing

  • Added/updated automated tests

  • QA'd all new/changed functionality manually

Summary by CodeRabbit

  • Improvements

    • Enhanced fleet scope validation for software title lookups, including correct handling when a team scope value is set to 0.
  • Tests

    • Added unit test coverage for software title retrieval authorization behavior when the team scope value is 0.

@sharon-fdm sharon-fdm force-pushed the fix-software-title-scope-validation branch from d0ee47e to 193e553 Compare June 22, 2026 17:47
@sharon-fdm sharon-fdm marked this pull request as ready for review June 22, 2026 17:50
@sharon-fdm sharon-fdm requested a review from a team as a code owner June 22, 2026 17:50
Copilot AI review requested due to automatic review settings June 22, 2026 17:50

@claude claude Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Claude Code Review

This repository is configured for manual code reviews. Comment @claude review to trigger a review and subscribe this PR to future pushes, or @claude review once for a one-time review.

Tip: disable this comment in your organization's Code Review settings.

@coderabbitai

coderabbitai Bot commented Jun 22, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: e67fb293-bb9e-4e04-9f9e-b404289e1846

📥 Commits

Reviewing files that changed from the base of the PR and between 9421806 and 1daa696.

📒 Files selected for processing (2)
  • server/service/software_titles.go
  • server/service/software_titles_test.go
🚧 Files skipped from review as they are similar to previous changes (2)
  • server/service/software_titles_test.go
  • server/service/software_titles.go

Walkthrough

In SoftwareTitleByID, the authorization call for AuthzSoftwareInventory is moved to execute whenever teamID is non-nil, regardless of whether the pointed-to value is zero. The TeamExists datastore lookup and the fleet.NewInvalidArgumentError not-found path remain gated on *teamID != 0. A new unit test TestSoftwareTitleByIDTeamIDZero verifies that a team-scoped admin is forbidden when passing team_id=0 while a global admin succeeds. A changelog entry notes the fix.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% 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 accurately summarizes the main change: improving fleet scope validation for software title lookups.
Description check ✅ Passed The description covers the key aspects including summary, reproduction steps, and test results. However, some optional checklist items were not addressed.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

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

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix-software-title-scope-validation

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.

Copilot AI left a comment

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.

Warning

  • Copilot's review of this pull request may be incomplete because some of the changed files are excluded by your Copilot content exclusion settings. See Excluding content from Copilot for details.

Pull request overview

This PR tightens authorization behavior for SoftwareTitleByID so that providing a non-nil team_id/fleet_id pointer always triggers software-inventory scope authorization, including the previously-unchecked team_id=0 case.

Changes:

  • Apply AuthzSoftwareInventory authorization whenever teamID != nil (not only when *teamID != 0).
  • Keep team existence validation only for non-zero team IDs.
  • Add a unit test covering the team_id=0 authorization behavior.

Reviewed changes

Copilot reviewed 2 out of 3 changed files in this pull request and generated 3 comments.

File Description
server/service/software_titles.go Adjusts scope authorization to run for all non-nil team IDs, including 0, and retains existence checks for non-zero IDs.
server/service/software_titles_test.go Adds a focused unit test for SoftwareTitleByID with team_id=0 behavior across team-scoped vs global admin users.
changes/software-title-scope-validation User-visible changes entry (diff content excluded by policy).
Files excluded by content exclusion policy (1)
  • changes/software-title-scope-validation

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment thread server/service/software_titles.go Outdated
Comment thread server/service/software_titles.go Outdated
Comment on lines 147 to 149
// This auth check ensures we return 403 if the user doesn't have access to the team
if err := svc.authz.Authorize(ctx, &fleet.AuthzSoftwareInventory{TeamID: teamID}, fleet.ActionRead); err != nil {
return nil, err
Comment thread server/service/software_titles_test.go Outdated
Comment on lines +298 to +300
require.Error(t, err)
require.Contains(t, err.Error(), "forbidden")

@coderabbitai coderabbitai Bot left a comment

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.

🧹 Nitpick comments (1)
server/service/software_titles_test.go (1)

281-309: 🧹 Nitpick | 🔵 Trivial | ⚡ Quick win

Assert TeamExists is never called for team_id=0.

This test verifies auth outcomes, but Line 281’s always-true mock won’t catch regressions where SoftwareTitleByID starts calling TeamExists(0) again.

Suggested test hardening
 func TestSoftwareTitleByIDTeamIDZero(t *testing.T) {
 	ds := new(mock.Store)
+	teamExistsCalled := false
 	ds.SoftwareTitleByIDFunc = func(ctx context.Context, id uint, teamID *uint, tmFilter fleet.TeamFilter) (*fleet.SoftwareTitle, error) {
 		return &fleet.SoftwareTitle{BundleIdentifier: ptr.String("com.example.app")}, nil
 	}
-	ds.TeamExistsFunc = func(ctx context.Context, teamID uint) (bool, error) { return true, nil }
+	ds.TeamExistsFunc = func(ctx context.Context, teamID uint) (bool, error) {
+		teamExistsCalled = true
+		return true, nil
+	}
@@
 	_, err = svc.SoftwareTitleByID(adminCtx, 1, teamIDZero)
 	require.NoError(t, err)
+	require.False(t, teamExistsCalled, "TeamExists should not be called when team_id=0")
 }
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@server/service/software_titles_test.go` around lines 281 - 309, The test
mocks TeamExistsFunc to always return true but does not verify that it is never
called with team_id=0. Modify the ds.TeamExistsFunc mock to track invocations
with their parameters, then add assertions after both SoftwareTitleByID calls to
verify that TeamExistsFunc was either not called at all or never called with a
team_id argument of 0. This will prevent regressions where SoftwareTitleByID
might incorrectly start calling TeamExists(0) when handling the zero team_id
case.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Nitpick comments:
In `@server/service/software_titles_test.go`:
- Around line 281-309: The test mocks TeamExistsFunc to always return true but
does not verify that it is never called with team_id=0. Modify the
ds.TeamExistsFunc mock to track invocations with their parameters, then add
assertions after both SoftwareTitleByID calls to verify that TeamExistsFunc was
either not called at all or never called with a team_id argument of 0. This will
prevent regressions where SoftwareTitleByID might incorrectly start calling
TeamExists(0) when handling the zero team_id case.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 2ba9f3a9-761b-4e5a-b56f-48189a5ad28e

📥 Commits

Reviewing files that changed from the base of the PR and between bad2a48 and 9421806.

📒 Files selected for processing (3)
  • changes/software-title-scope-validation
  • server/service/software_titles.go
  • server/service/software_titles_test.go

@codecov

codecov Bot commented Jun 22, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 62.50000% with 3 lines in your changes missing coverage. Please review.
✅ Project coverage is 67.31%. Comparing base (59f33dc) to head (5def89a).
⚠️ Report is 1 commits behind head on main.

Files with missing lines Patch % Lines
server/service/software_titles.go 62.50% 1 Missing and 2 partials ⚠️
Additional details and impacted files
@@           Coverage Diff            @@
##             main   #48034    +/-   ##
========================================
  Coverage   67.31%   67.31%            
========================================
  Files        3655     3655            
  Lines      231242   231244     +2     
  Branches    12224    12076   -148     
========================================
+ Hits       155658   155660     +2     
- Misses      61618    61620     +2     
+ Partials    13966    13964     -2     
Flag Coverage Δ
backend 68.94% <62.50%> (+<0.01%) ⬆️

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

☔ View full report in Codecov by Harness.
📢 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.

@sharon-fdm sharon-fdm merged commit 81f2ede into main Jun 23, 2026
44 checks passed
@sharon-fdm sharon-fdm deleted the fix-software-title-scope-validation branch June 23, 2026 18:28
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.

3 participants