Skip to content

Enforce API-only endpoint restrictions on chart routes - #49477

Merged
sharon-fdm merged 4 commits into
mainfrom
fix-pt46-chart-api-only-bypass
Jul 23, 2026
Merged

Enforce API-only endpoint restrictions on chart routes#49477
sharon-fdm merged 4 commits into
mainfrom
fix-pt46-chart-api-only-bypass

Conversation

@sharon-fdm

@sharon-fdm sharon-fdm commented Jul 17, 2026

Copy link
Copy Markdown
Collaborator

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.

  • Timeouts are implemented and retries are limited to avoid infinite loops

  • If paths of existing endpoints are modified without backwards compatibility, checked the frontend/CLI for any necessary changes

Summary

Enforced API-only endpoint restrictions on chart endpoints, matching the pattern already used by the activity bounded context. Also added RouteTemplateRequestFunc to chart route server options so the middleware can read the matched mux route template from context.

Testing

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

Reproduction

Created an API-only user with a restrictive endpoint allow-list (only GET /api/v1/fleet/hosts). Confirmed that:

  • Allowed endpoint (/api/latest/fleet/hosts) returns 200
  • Non-allowed cataloged endpoint (/api/latest/fleet/users) returns 403
  • Chart endpoint (/api/latest/fleet/charts/uptime) returned 200 before the fix (the bug)
  • After the fix, chart endpoint correctly returns 403

Unit test

Added a test case in server/service/middleware/auth/api_only_test.go that verifies an API-only user with endpoint restrictions is denied access to chart endpoints not in their allow-list. The chart endpoint is included in the test catalog (matching production), so the test exercises the allow-list rejection path.

All 17 tests in the auth middleware package pass.

Local verification

  1. Confirmed the chart middleware in cmd/fleet/serve.go previously called auth.AuthenticatedUser(svc, next) without APIOnlyEndpointCheck wrapping
  2. Verified the activity bounded context (same file) already uses auth.APIOnlyEndpointCheck(next) as the correct pattern
  3. Applied the same wrapping to the chart middleware
  4. Added RouteTemplateRequestFunc to server/chart/internal/service/endpoint_utils.go so the route template is available in context (required by APIOnlyEndpointCheck)
  5. Ran go test ./server/service/middleware/auth/ -v with all 17 tests passing
  6. Ran make lint-go-incremental with 0 issues

@codecov

codecov Bot commented Jul 17, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 67.82%. Comparing base (60d8f51) to head (521b130).
⚠️ Report is 303 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff             @@
##             main   #49477      +/-   ##
==========================================
- Coverage   67.99%   67.82%   -0.17%     
==========================================
  Files        3768     3815      +47     
  Lines      239077   247093    +8016     
  Branches    12613    12613              
==========================================
+ Hits       162570   167601    +5031     
- Misses      61744    64253    +2509     
- Partials    14763    15239     +476     
Flag Coverage Δ
backend 69.30% <100.00%> (-0.27%) ⬇️

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.

… file

Adds a test case verifying that API-only users with endpoint restrictions
are denied access to chart endpoints not in the API catalog. Also updates
the changes file to use past tense.
@sharon-fdm
sharon-fdm marked this pull request as ready for review July 17, 2026 15:20
Copilot AI review requested due to automatic review settings July 17, 2026 15:20
@sharon-fdm
sharon-fdm requested a review from a team as a code owner July 17, 2026 15:20
@coderabbitai

coderabbitai Bot commented Jul 17, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

Walkthrough

Chart endpoint construction now attaches matched route templates to request context. Chart authentication wraps requests with an API-only endpoint check, and tests verify that restricted chart requests return a fleet.PermissionError without reaching the downstream handler.

🚥 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
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.
Title check ✅ Passed The title clearly and concisely summarizes the main change to chart route authorization.
Description check ✅ Passed The description covers the required summary and testing details, with only minor template omissions like the related issue line.
✨ 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-pt46-chart-api-only-bypass

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.

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 applies the existing API-only endpoint restriction middleware (APIOnlyEndpointCheck) to the chart bounded-context routes so that API-only users with endpoint allow-lists are restricted consistently (matching the activity bounded context).

Changes:

  • Wrap chart bounded-context authentication middleware with auth.APIOnlyEndpointCheck.
  • Add an auth middleware unit test case covering a chart route template under API-only restrictions.
  • Add a changes entry (content excluded from this review).

Reviewed changes

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

File Description
server/service/middleware/auth/api_only_test.go Adds a new test case for API-only restrictions against a chart route template.
cmd/fleet/serve.go Wraps chart bounded-context auth middleware with APIOnlyEndpointCheck.
changes/fix-chart-api-only-enforcement Changes entry for user-visible behavior (diff content excluded by policy).
Files excluded by content exclusion policy (1)
  • changes/fix-chart-api-only-enforcement

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

Comment thread server/service/middleware/auth/api_only_test.go Outdated
Comment thread cmd/fleet/serve.go
@sharon-fdm
sharon-fdm marked this pull request as draft July 17, 2026 15:50
@sharon-fdm
sharon-fdm marked this pull request as ready for review July 17, 2026 15:50
- Add RouteTemplateRequestFunc as a ServerBefore option in chart
  endpoint_utils.go so APIOnlyEndpointCheck can read the matched
  mux route template from context (matching the activity pattern).
- Update test to include charts in the catalog so it exercises the
  allow-list rejection path rather than the catalog-check path.

@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/middleware/auth/api_only_test.go (1)

298-312: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Consider using a full-slice expression to prevent potential test pollution.

While testCatalogEndpoints is currently a slice literal (meaning its len equals its cap) and append will safely allocate a new backing array without mutating the global state, you might consider using a full-slice expression here for consistency with endpoint_utils.go. This defensively guarantees that the global slice won't be mutated if it is ever modified to have spare capacity in the future.

♻️ Proposed refactor
-		catalogWithCharts := append(testCatalogEndpoints,
+		catalogWithCharts := append(testCatalogEndpoints[:len(testCatalogEndpoints):len(testCatalogEndpoints)],
 			fleet.NewAPIEndpointFromTpl("GET", "/api/v1/fleet/charts/:metric"),
 		)
🤖 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/middleware/auth/api_only_test.go` around lines 298 - 312,
Update the catalog construction in the “api-only user with restrictions, chart
endpoint not in allow-list is rejected” test to append to a full-slice view of
testCatalogEndpoints with capacity limited to its length, preventing accidental
mutation if the shared slice later has spare capacity. Keep the existing
endpoint set and apiOnlyEndpointCheck behavior unchanged.
🤖 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/middleware/auth/api_only_test.go`:
- Around line 298-312: Update the catalog construction in the “api-only user
with restrictions, chart endpoint not in allow-list is rejected” test to append
to a full-slice view of testCatalogEndpoints with capacity limited to its
length, preventing accidental mutation if the shared slice later has spare
capacity. Keep the existing endpoint set and apiOnlyEndpointCheck behavior
unchanged.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 6f34ad6d-811b-4a37-9caa-961ed68ec4ea

📥 Commits

Reviewing files that changed from the base of the PR and between d8d3106 and 0b18b46.

📒 Files selected for processing (2)
  • server/chart/internal/service/endpoint_utils.go
  • server/service/middleware/auth/api_only_test.go

@nulmete nulmete self-assigned this Jul 22, 2026

@nulmete nulmete left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

LGTM, some minor comments below.

Comment thread server/service/middleware/auth/api_only_test.go Outdated
Comment thread server/service/middleware/auth/api_only_test.go Outdated
Move chart endpoint into testCatalogEndpoints and use the standard
newEndpoint helper instead of building a custom catalog inline.
Copilot AI review requested due to automatic review settings July 23, 2026 14:25

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

Copilot reviewed 3 out of 4 changed files in this pull request and generated no new comments.

Files excluded by content exclusion policy (1)
  • changes/fix-chart-api-only-enforcement

@sharon-fdm
sharon-fdm merged commit f492a6a into main Jul 23, 2026
35 of 38 checks passed
@sharon-fdm
sharon-fdm deleted the fix-pt46-chart-api-only-bypass branch July 23, 2026 14:44
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