Skip to content

Host identity SCEP rate limit. - #31038

Merged
lucasmrod merged 3 commits into
mainfrom
victor/30989-scep-rate-limit
Jul 18, 2025
Merged

Host identity SCEP rate limit.#31038
lucasmrod merged 3 commits into
mainfrom
victor/30989-scep-rate-limit

Conversation

@getvictor

@getvictor getvictor commented Jul 18, 2025

Copy link
Copy Markdown
Member

Fixes #30989

Checklist for submitter

  • Added/updated automated tests
    • Where appropriate, automated tests simulate multiple hosts and test for host isolation (updates to one hosts's records do not affect another.)

Summary by CodeRabbit

  • New Features

    • Added rate limiting to SCEP certificate enrollment, returning a "Too Many Requests" (HTTP 429) response if hosts request certificates too frequently.
  • Bug Fixes

    • Improved error handling for rate-limited SCEP requests, providing clear feedback when rate limits are exceeded.
  • Tests

    • Introduced integration tests to verify SCEP rate limiting behavior.
  • Chores

    • Enhanced internal configuration handling for SCEP certificate management.

@coderabbitai

coderabbitai Bot commented Jul 18, 2025

Copy link
Copy Markdown
Contributor
📝 Walkthrough

Walkthrough

This change adds a rate limit to the SCEP certificate enrollment endpoint, ensuring hosts cannot request certificates too frequently. It introduces a cooldown period, stores certificate creation timestamps, updates error handling to return HTTP 429 on rate limiting, and includes integration tests to verify correct behavior.

Changes

File(s) Change Summary
ee/server/service/hostidentity/depot/depot.go Added cooldown-based rate limiting to certificate storage; depot struct and constructor updated for config usage.
ee/server/service/hostidentity/scep.go Introduced RateLimitError type; PKIOperation returns HTTP 429 on rate limiting.
ee/server/service/hostidentity/types/host_identity_certificates.go Added CreatedAt timestamp field to HostIdentityCertificate struct.
server/datastore/mysql/host_identity_scep.go Modified SQL to select created_at for certificates.
server/datastore/mysql/mysql.go NewHostIdentitySCEPDepot now takes FleetConfig pointer as argument.
cmd/fleet/serve.go Passes FleetConfig pointer to NewHostIdentitySCEPDepot.
ee/server/integrationtest/hostidentity/scep_rate_limit_test.go New integration test verifying SCEP rate limiting per host.
ee/server/integrationtest/hostidentity/suite.go Added SetUpSuiteWithConfig to allow test config mutation; passes config to depot constructor.

Sequence Diagram(s)

sequenceDiagram
    participant Host as Host
    participant SCEP as SCEP Endpoint
    participant Depot as HostIdentitySCEPDepot
    participant DB as Database

    Host->>SCEP: Request SCEP certificate (CSR)
    SCEP->>Depot: Store certificate for host
    Depot->>DB: Check for existing certificate by host
    DB-->>Depot: Return existing certificate (with CreatedAt)
    Depot-->>SCEP: Return error if within cooldown, else proceed
    alt Within cooldown
        SCEP-->>Host: HTTP 429 Too Many Requests
    else Not within cooldown
        Depot->>DB: Store new certificate
        SCEP-->>Host: Return issued certificate
    end
Loading

Possibly related PRs

  • fleetdm/fleet#30589: Implements the SCEP endpoint for host identity, including the creation of the SCEP service, depot, and related datastore methods. This work is directly related as it provides the foundation for the rate limiting feature.

📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 50f18ea and 9fae641.

📒 Files selected for processing (8)
  • cmd/fleet/serve.go (1 hunks)
  • ee/server/integrationtest/hostidentity/scep_rate_limit_test.go (1 hunks)
  • ee/server/integrationtest/hostidentity/suite.go (2 hunks)
  • ee/server/service/hostidentity/depot/depot.go (3 hunks)
  • ee/server/service/hostidentity/scep.go (3 hunks)
  • ee/server/service/hostidentity/types/host_identity_certificates.go (1 hunks)
  • server/datastore/mysql/host_identity_scep.go (1 hunks)
  • server/datastore/mysql/mysql.go (1 hunks)
🧰 Additional context used
🧠 Learnings (7)
server/datastore/mysql/host_identity_scep.go (2)
Learnt from: getvictor
PR: fleetdm/fleet#30589
File: server/datastore/mysql/schema.sql:501-517
Timestamp: 2025-07-07T22:21:15.748Z
Learning: In the host_identity_scep_certificates table schema, the VARBINARY(100) size for public_key_raw, the nullable host_id without a foreign key constraint, and the use of plain DATETIME instead of DATETIME(6) are intentional design decisions, not issues to be addressed.
Learnt from: getvictor
PR: fleetdm/fleet#30589
File: ee/server/service/hostidentity/depot/depot.go:104-119
Timestamp: 2025-07-08T16:06:54.576Z
Learning: In ee/server/service/hostidentity/depot/depot.go, the security concern where shared challenges allow certificate revocation (lines 104-119) is a known issue that will be addressed in a later feature, not an immediate concern to fix.
cmd/fleet/serve.go (4)
Learnt from: getvictor
PR: fleetdm/fleet#30589
File: ee/server/service/hostidentity/depot/depot.go:104-119
Timestamp: 2025-07-08T16:06:54.576Z
Learning: In ee/server/service/hostidentity/depot/depot.go, the security concern where shared challenges allow certificate revocation (lines 104-119) is a known issue that will be addressed in a later feature, not an immediate concern to fix.
Learnt from: getvictor
PR: fleetdm/fleet#30589
File: ee/server/service/hostidentity/depot/depot.go:108-111
Timestamp: 2025-07-08T16:12:48.797Z
Learning: In ee/server/service/hostidentity/depot/depot.go, the SCEP depot interface methods like Put() do not accept context parameters, and the common_mysql.WithRetryTxx callback function type TxFn only receives a transaction parameter, not a context. Therefore, using context.Background() in tx.ExecContext calls within the transaction callback is the correct approach.
Learnt from: getvictor
PR: fleetdm/fleet#30589
File: ee/server/service/hostidentity/depot/depot.go:115-115
Timestamp: 2025-07-08T16:11:49.555Z
Learning: In ee/server/service/hostidentity/depot/depot.go, the error from result.RowsAffected() is intentionally ignored because the information is only used for logging purposes, not for critical program logic.
Learnt from: getvictor
PR: fleetdm/fleet#30825
File: ee/server/service/hostidentity/httpsig/httpsig.go:86-88
Timestamp: 2025-07-15T07:26:38.930Z
Learning: In ee/server/service/hostidentity/httpsig/httpsig.go, the Fetch method stub returning "not implemented" is safe because the verification profile requires MetaKeyID in RequiredMetadata, ensuring the httpsig library always calls FetchByKeyID instead of Fetch for valid signatures.
server/datastore/mysql/mysql.go (3)
Learnt from: getvictor
PR: fleetdm/fleet#30589
File: ee/server/service/hostidentity/depot/depot.go:108-111
Timestamp: 2025-07-08T16:12:48.797Z
Learning: In ee/server/service/hostidentity/depot/depot.go, the SCEP depot interface methods like Put() do not accept context parameters, and the common_mysql.WithRetryTxx callback function type TxFn only receives a transaction parameter, not a context. Therefore, using context.Background() in tx.ExecContext calls within the transaction callback is the correct approach.
Learnt from: getvictor
PR: fleetdm/fleet#30589
File: ee/server/service/hostidentity/depot/depot.go:104-119
Timestamp: 2025-07-08T16:06:54.576Z
Learning: In ee/server/service/hostidentity/depot/depot.go, the security concern where shared challenges allow certificate revocation (lines 104-119) is a known issue that will be addressed in a later feature, not an immediate concern to fix.
Learnt from: getvictor
PR: fleetdm/fleet#30589
File: ee/server/service/hostidentity/depot/depot.go:115-115
Timestamp: 2025-07-08T16:11:49.555Z
Learning: In ee/server/service/hostidentity/depot/depot.go, the error from result.RowsAffected() is intentionally ignored because the information is only used for logging purposes, not for critical program logic.
ee/server/service/hostidentity/scep.go (3)
Learnt from: getvictor
PR: fleetdm/fleet#30589
File: ee/server/service/hostidentity/depot/depot.go:104-119
Timestamp: 2025-07-08T16:06:54.576Z
Learning: In ee/server/service/hostidentity/depot/depot.go, the security concern where shared challenges allow certificate revocation (lines 104-119) is a known issue that will be addressed in a later feature, not an immediate concern to fix.
Learnt from: getvictor
PR: fleetdm/fleet#30589
File: ee/server/service/hostidentity/depot/depot.go:108-111
Timestamp: 2025-07-08T16:12:48.797Z
Learning: In ee/server/service/hostidentity/depot/depot.go, the SCEP depot interface methods like Put() do not accept context parameters, and the common_mysql.WithRetryTxx callback function type TxFn only receives a transaction parameter, not a context. Therefore, using context.Background() in tx.ExecContext calls within the transaction callback is the correct approach.
Learnt from: getvictor
PR: fleetdm/fleet#30589
File: ee/server/service/hostidentity/depot/depot.go:115-115
Timestamp: 2025-07-08T16:11:49.555Z
Learning: In ee/server/service/hostidentity/depot/depot.go, the error from result.RowsAffected() is intentionally ignored because the information is only used for logging purposes, not for critical program logic.
ee/server/integrationtest/hostidentity/suite.go (2)
Learnt from: getvictor
PR: fleetdm/fleet#30589
File: ee/server/service/hostidentity/depot/depot.go:108-111
Timestamp: 2025-07-08T16:12:48.797Z
Learning: In ee/server/service/hostidentity/depot/depot.go, the SCEP depot interface methods like Put() do not accept context parameters, and the common_mysql.WithRetryTxx callback function type TxFn only receives a transaction parameter, not a context. Therefore, using context.Background() in tx.ExecContext calls within the transaction callback is the correct approach.
Learnt from: getvictor
PR: fleetdm/fleet#30589
File: server/fleet/datastore.go:13-14
Timestamp: 2025-07-08T16:12:48.182Z
Learning: The Fleet team is not currently testing or enforcing OSS build compatibility, so imports of enterprise-only packages (like ee/server/service/hostidentity/types) into OSS code are acceptable for now.
ee/server/service/hostidentity/depot/depot.go (3)
Learnt from: getvictor
PR: fleetdm/fleet#30589
File: ee/server/service/hostidentity/depot/depot.go:104-119
Timestamp: 2025-07-08T16:06:54.576Z
Learning: In ee/server/service/hostidentity/depot/depot.go, the security concern where shared challenges allow certificate revocation (lines 104-119) is a known issue that will be addressed in a later feature, not an immediate concern to fix.
Learnt from: getvictor
PR: fleetdm/fleet#30589
File: ee/server/service/hostidentity/depot/depot.go:108-111
Timestamp: 2025-07-08T16:12:48.797Z
Learning: In ee/server/service/hostidentity/depot/depot.go, the SCEP depot interface methods like Put() do not accept context parameters, and the common_mysql.WithRetryTxx callback function type TxFn only receives a transaction parameter, not a context. Therefore, using context.Background() in tx.ExecContext calls within the transaction callback is the correct approach.
Learnt from: getvictor
PR: fleetdm/fleet#30589
File: ee/server/service/hostidentity/depot/depot.go:115-115
Timestamp: 2025-07-08T16:11:49.555Z
Learning: In ee/server/service/hostidentity/depot/depot.go, the error from result.RowsAffected() is intentionally ignored because the information is only used for logging purposes, not for critical program logic.
ee/server/integrationtest/hostidentity/scep_rate_limit_test.go (1)
Learnt from: getvictor
PR: fleetdm/fleet#30589
File: ee/server/service/hostidentity/depot/depot.go:104-119
Timestamp: 2025-07-08T16:06:54.576Z
Learning: In ee/server/service/hostidentity/depot/depot.go, the security concern where shared challenges allow certificate revocation (lines 104-119) is a known issue that will be addressed in a later feature, not an immediate concern to fix.
🧬 Code Graph Analysis (1)
cmd/fleet/serve.go (1)
ee/server/service/hostidentity/depot/depot.go (1)
  • NewHostIdentitySCEPDepot (39-49)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (23)
  • GitHub Check: Analyze (go)
  • GitHub Check: Analyze (javascript)
  • GitHub Check: test-go (mysql, ubuntu-latest, mysql:8.0.36, false)
  • GitHub Check: test-go (vuln, ubuntu-latest, mysql:9.3.0, false)
  • GitHub Check: test-go (vuln, ubuntu-latest, mysql:8.0.36, false)
  • GitHub Check: test-go (service, ubuntu-latest, mysql:9.3.0, false)
  • GitHub Check: test-go (fleetctl, ubuntu-latest, mysql:9.3.0, false)
  • GitHub Check: test-go (fleetctl, ubuntu-latest, mysql:8.0.36, false)
  • GitHub Check: test-go (service, ubuntu-latest, mysql:8.0.36, false)
  • GitHub Check: test-go (main, ubuntu-latest, mysql:8.0.36, false)
  • GitHub Check: test-go (main, ubuntu-latest, mysql:9.3.0, false)
  • GitHub Check: test-go (integration-mdm, ubuntu-latest, mysql:9.3.0, false)
  • GitHub Check: test-go (integration-core, ubuntu-latest, mysql:8.0.36, false)
  • GitHub Check: test-go (integration-core, ubuntu-latest, mysql:9.3.0, false)
  • GitHub Check: test-go (mysql, ubuntu-latest, mysql:9.3.0, false)
  • GitHub Check: test-go (integration-enterprise, ubuntu-latest, mysql:9.3.0, false)
  • GitHub Check: test-go (integration-enterprise, ubuntu-latest, mysql:8.0.36, false)
  • GitHub Check: test-go (integration-mdm, ubuntu-latest, mysql:8.0.36, false)
  • GitHub Check: lint (macos-latest)
  • GitHub Check: lint (ubuntu-latest)
  • GitHub Check: lint (windows-latest)
  • GitHub Check: build-binaries
  • GitHub Check: publish
🔇 Additional comments (16)
ee/server/service/hostidentity/types/host_identity_certificates.go (1)

18-18: Clean addition to support rate limiting

The new CreatedAt field is properly structured with the correct database tag and will work well with the rate limiting feature. This is a simple, focused change that adds exactly what's needed.

server/datastore/mysql/host_identity_scep.go (1)

50-50: Good addition to retrieve the created_at timestamp

The SQL query now includes the created_at column which will properly populate the new field in the HostIdentityCertificate struct. This matches the database schema and supports the rate limiting functionality.

cmd/fleet/serve.go (1)

1209-1209: Configuration parameter properly passed for rate limiting

The call to NewHostIdentitySCEPDepot now includes the configuration parameter, which enables the depot to access rate limiting settings. This change aligns with the updated function signature and is necessary for the rate limiting feature to work.

server/datastore/mysql/mysql.go (1)

195-196: Function signature updated to support configuration

The method now accepts a *config.FleetConfig parameter and properly forwards it to the underlying depot constructor. This change enables the rate limiting feature by providing access to configuration settings.

ee/server/service/hostidentity/scep.go (3)

27-38: Well-implemented rate limit error type

The RateLimitError struct properly implements both the error interface and the StatusCoder interface needed for HTTP status code handling. The HTTP 429 status code is the correct choice for rate limiting scenarios.


12-12: Good addition of backoff library

The backoff library import is appropriate for handling retry logic and permanent errors in the rate limiting implementation.


175-181: Correct error handling for rate limiting

The logic properly detects permanent errors from the backoff library and converts them to HTTP 429 responses. This provides clear feedback to clients when they're being rate limited.

ee/server/integrationtest/hostidentity/suite.go (3)

36-38: Good backward compatibility approach

The original SetUpSuite function now calls the new SetUpSuiteWithConfig with nil as the modifier, maintaining backward compatibility while extending functionality.


40-52: Clean configuration modifier pattern

The configuration modifier pattern allows tests to customize the Fleet configuration before the depot is created. The conditional application ensures the modifier is only called when provided.


55-55: Proper configuration passing to depot

The updated depot creation correctly passes the address of the modified configuration, aligning with the new constructor signature.

ee/server/service/hostidentity/depot/depot.go (3)

33-33: Good configuration integration

The depot now properly stores and uses the Fleet configuration for rate limiting. The constructor signature change cleanly integrates the configuration parameter.

Also applies to: 39-39, 47-47


112-126: Solid rate limiting implementation

The rate limiting logic is well-implemented:

  • Checks if cooldown is configured before applying limits
  • Properly handles both "not found" and other database errors
  • Correctly compares elapsed time against cooldown period
  • Returns appropriate permanent backoff error for rate limiting
  • Continues processing when rate limit doesn't apply

The error message clearly identifies the problematic host for debugging purposes.


13-13: Appropriate library imports

The addition of the backoff library and ctxerr import supports the new rate limiting functionality and proper error handling.

Also applies to: 17-17

ee/server/integrationtest/hostidentity/scep_rate_limit_test.go (3)

25-34: Well-structured test setup

The test setup properly configures the cooldown period and ensures database cleanup. The 5-minute cooldown is appropriate for testing rate limiting behavior.


36-71: Comprehensive rate limiting test coverage

The test thoroughly validates the rate limiting functionality:

  • Initial request succeeds as expected
  • Immediate subsequent request is properly rate limited (HTTP 429)
  • Rate limiting persists over time within the cooldown period
  • Different hosts are not affected by rate limits for other hosts

This provides excellent coverage of the rate limiting behavior.


75-163: Robust SCEP certificate request helper

The helper function implements a realistic SCEP certificate request workflow:

  • Proper ECC key generation and CSR creation
  • Correct SCEP client setup and CA certificate retrieval
  • Appropriate HTTP request handling with status code checking
  • Proper handling of HTTP 429 responses
  • Complete SCEP message parsing and certificate extraction

The implementation follows SCEP protocol standards and provides good error handling.

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch victor/30989-scep-rate-limit

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
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai auto-generate unit tests to generate unit tests for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@codecov

codecov Bot commented Jul 18, 2025

Copy link
Copy Markdown

Codecov Report

Attention: Patch coverage is 91.66667% with 3 lines in your changes missing coverage. Please review.

Project coverage is 64.33%. Comparing base (8f2f805) to head (9fae641).
Report is 15 commits behind head on main.

Files with missing lines Patch % Lines
ee/server/service/hostidentity/depot/depot.go 85.71% 2 Missing ⚠️
cmd/fleet/serve.go 0.00% 1 Missing ⚠️
Additional details and impacted files
@@           Coverage Diff            @@
##             main   #31038    +/-   ##
========================================
  Coverage   64.32%   64.33%            
========================================
  Files        1892     1893     +1     
  Lines      185748   186082   +334     
  Branches     5354     5354            
========================================
+ Hits       119483   119714   +231     
- Misses      56892    56977    +85     
- Partials     9373     9391    +18     
Flag Coverage Δ
backend 65.24% <91.66%> (+<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.

@getvictor

Copy link
Copy Markdown
Member Author

@coderabbitai full review

@coderabbitai

coderabbitai Bot commented Jul 18, 2025

Copy link
Copy Markdown
Contributor
✅ Actions performed

Full review triggered.

@getvictor
getvictor marked this pull request as ready for review July 18, 2025 11:09
@getvictor
getvictor requested a review from a team as a code owner July 18, 2025 11:09
Comment thread ee/server/service/hostidentity/depot/depot.go
@lucasmrod
lucasmrod merged commit 909a48b into main Jul 18, 2025
39 checks passed
@lucasmrod
lucasmrod deleted the victor/30989-scep-rate-limit branch July 18, 2025 13:04
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.

TPM: Add rate limit on SCEP certificate request

2 participants