Skip to content

Refactor EnrollOrbit/EnrollHost - #30872

Merged
lucasmrod merged 4 commits into
mainfrom
victor/30473-refactor-enroll-methods
Jul 15, 2025
Merged

Refactor EnrollOrbit/EnrollHost#30872
lucasmrod merged 4 commits into
mainfrom
victor/30473-refactor-enroll-methods

Conversation

@getvictor

@getvictor getvictor commented Jul 15, 2025

Copy link
Copy Markdown
Member

Fixes #30473

Refactore Datastore.EnrollHost and Datastore.EnrollOrbit methods to use functional options. Doing this refactor before adding new options to those methods. This should make the code more maintainable and easier to understand.

No functional changes here. Just refactoring.

Checklist for submitter

  • Added/updated automated tests

Summary by CodeRabbit

  • Refactor

    • Streamlined host and Orbit enrollment methods to use a flexible options-based pattern instead of fixed parameter lists.
    • Updated related tests and service logic to use the new options approach, improving clarity and extensibility for enrollment operations.
  • New Features

    • Introduced configuration options for host and Orbit enrollment, allowing more explicit and customizable parameter setting during enrollment.

@getvictor
getvictor requested a review from a team as a code owner July 15, 2025 10:16
@coderabbitai

coderabbitai Bot commented Jul 15, 2025

Copy link
Copy Markdown
Contributor

Important

Review skipped

Auto reviews are disabled on this repository.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

📝 Walkthrough

Walkthrough

This change refactors host enrollment methods and their usages to use a functional options pattern instead of positional parameters. It updates method signatures, internal logic, and all relevant call sites in the codebase and tests. No new features or control flow changes are introduced; only the enrollment API usage is modernized.

Changes

File(s) Change Summary
server/fleet/osquery.go, server/fleet/orbit.go Add config structs and functional option types/functions for enrollment options.
server/fleet/datastore.go Update datastore interface: EnrollHost and EnrollOrbit now use variadic options.
server/datastore/mysql/hosts.go, server/datastore/mysqlredis/hosts.go Refactor EnrollHost/EnrollOrbit implementations to use options pattern.
server/mock/datastore.go, server/mock/datastore_mock.go Update mock datastore methods and function types to use variadic options.
server/datastore/mysql/*.go, server/datastore/mysqlredis/hosts_test.go Refactor all test calls to enrollment functions to use new options pattern.
server/service/osquery.go, server/service/orbit.go Update service layer enrollment calls to use options.
server/service/integration_core_test.go, server/service/integration_mdm_test.go, server/test/enrollment.go Refactor test helpers and integration tests to use enrollment options.

Sequence Diagram(s)

sequenceDiagram
    participant Caller
    participant Datastore
    Note over Caller,Datastore: Host enrollment using functional options
    Caller->>Datastore: EnrollHost(ctx, WithEnrollHostOsqueryHostID(...), ...)
    Datastore->>Datastore: Apply options to config struct
    Datastore->>Datastore: Perform enrollment logic using config fields
    Datastore-->>Caller: Return Host or error
Loading
sequenceDiagram
    participant Caller
    participant Datastore
    Note over Caller,Datastore: Orbit enrollment using functional options
    Caller->>Datastore: EnrollOrbit(ctx, WithEnrollOrbitHostInfo(...), ...)
    Datastore->>Datastore: Apply options to config struct
    Datastore->>Datastore: Perform enrollment logic using config fields
    Datastore-->>Caller: Return Host or error
Loading

Assessment against linked issues

Objective Addressed Explanation
Check host tied to identity cert at enrollment (#30473) No logic for identity cert verification or tying certs to hosts is introduced.
Verify cert not expired and signature using public key at HTTP signature request (#30473) No HTTP signature verification or cert expiration checks are implemented.
Tie cert to host by node key if not already tied (#30473) No mechanism to tie certificates to hosts by node key is added.
Verify node key host matches certificate host (#30473) No check for node key and certificate host matching is present.
Efficiently check if host needs HTTP signature when request lacks signature (#30473) No new checks or optimizations for HTTP signature requirements are included.

Assessment against linked issues: Out-of-scope changes

Code Change Explanation
Refactoring enrollment methods to use functional options (multiple files, e.g., server/fleet/osquery.go) The linked issue is about HTTP signature and certificate verification, not enrollment API refactoring.
Updating all test and service code to use new enrollment options pattern (various test and service files) These changes are unrelated to the objectives of certificate or HTTP signature verification.
✨ Finishing Touches
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch victor/30473-refactor-enroll-methods

🪧 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 15, 2025

Copy link
Copy Markdown

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 64.20%. Comparing base (ab33557) to head (9d34732).
Report is 20 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff             @@
##             main   #30872      +/-   ##
==========================================
+ Coverage   64.17%   64.20%   +0.02%     
==========================================
  Files        1889     1890       +1     
  Lines      185003   185085      +82     
  Branches     5361     5361              
==========================================
+ Hits       118729   118825      +96     
+ Misses      56935    56923      -12     
+ Partials     9339     9337       -2     
Flag Coverage Δ
backend 65.19% <100.00%> (+0.02%) ⬆️

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 getvictor changed the title Refactor EnrollOrbit Refactor EnrollOrbit/EnrollHost Jul 15, 2025
@getvictor

Copy link
Copy Markdown
Member Author

@coderabbitai full review

@coderabbitai

coderabbitai Bot commented Jul 15, 2025

Copy link
Copy Markdown
Contributor
✅ Actions performed

Full review triggered.

@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.

Actionable comments posted: 0

🧹 Nitpick comments (2)
server/datastore/mysql/apple_mdm_test.go (1)

4751-4755: fix the “maunual-host” typo

tiny spelling slip in the hostname string—may trip up future greps.

- fleet.WithEnrollOrbitHostInfo(fleet.OrbitHostInfo{HardwareSerial: manualSerial, Platform: "darwin", HardwareUUID: manualUUID, Hostname: "maunual-host"}),
+ fleet.WithEnrollOrbitHostInfo(fleet.OrbitHostInfo{HardwareSerial: manualSerial, Platform: "darwin", HardwareUUID: manualUUID, Hostname: "manual-host"}),
server/fleet/datastore.go (1)

1049-1052: Excellent consistency with the functional options pattern!

This method signature change matches the EnrollHost refactoring above, which provides nice consistency across the enrollment methods. The functional options pattern will make it much easier to add new enrollment parameters in the future.

Consider updating the comment to reflect the new approach:

-// EnrollOrbit will enroll a new orbit instance.
+// EnrollOrbit will enroll a new orbit instance using the provided functional options.
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between ab33557 and 6a5b1e6.

📒 Files selected for processing (18)
  • server/datastore/mysql/apple_mdm_test.go (3 hunks)
  • server/datastore/mysql/hosts.go (2 hunks)
  • server/datastore/mysql/hosts_test.go (19 hunks)
  • server/datastore/mysql/labels_test.go (2 hunks)
  • server/datastore/mysql/policies_test.go (4 hunks)
  • server/datastore/mysql/targets_test.go (1 hunks)
  • server/datastore/mysqlredis/hosts.go (1 hunks)
  • server/datastore/mysqlredis/hosts_test.go (5 hunks)
  • server/fleet/datastore.go (1 hunks)
  • server/fleet/orbit.go (1 hunks)
  • server/fleet/osquery.go (2 hunks)
  • server/mock/datastore.go (1 hunks)
  • server/mock/datastore_mock.go (2 hunks)
  • server/service/integration_core_test.go (1 hunks)
  • server/service/integration_mdm_test.go (1 hunks)
  • server/service/orbit.go (1 hunks)
  • server/service/osquery.go (1 hunks)
  • server/test/enrollment.go (1 hunks)
🧰 Additional context used
🧠 Learnings (2)
server/datastore/mysql/apple_mdm_test.go (2)

undefined

<retrieved_learning>
Learnt from: getvictor
PR: #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.
</retrieved_learning>

<retrieved_learning>
Learnt from: getvictor
PR: #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.
</retrieved_learning>

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

undefined

<retrieved_learning>
Learnt from: getvictor
PR: #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.
</retrieved_learning>

🧬 Code Graph Analysis (11)
server/datastore/mysql/targets_test.go (1)
server/fleet/osquery.go (2)
  • WithEnrollHostOsqueryHostID (98-102)
  • WithEnrollHostNodeKey (119-123)
server/mock/datastore.go (1)
server/fleet/orbit.go (1)
  • DatastoreEnrollOrbitOption (120-120)
server/test/enrollment.go (1)
server/fleet/orbit.go (4)
  • WithEnrollOrbitHostInfo (130-134)
  • OrbitHostInfo (89-109)
  • WithEnrollOrbitNodeKey (137-141)
  • WithEnrollOrbitTeamID (144-148)
server/datastore/mysql/policies_test.go (1)
server/fleet/osquery.go (3)
  • WithEnrollHostOsqueryHostID (98-102)
  • WithEnrollHostNodeKey (119-123)
  • WithEnrollHostTeamID (126-130)
server/service/integration_core_test.go (1)
server/fleet/orbit.go (4)
  • WithEnrollOrbitHostInfo (130-134)
  • OrbitHostInfo (89-109)
  • WithEnrollOrbitNodeKey (137-141)
  • WithEnrollOrbitTeamID (144-148)
server/datastore/mysql/apple_mdm_test.go (1)
server/fleet/orbit.go (4)
  • WithEnrollOrbitMDMEnabled (123-127)
  • WithEnrollOrbitHostInfo (130-134)
  • OrbitHostInfo (89-109)
  • WithEnrollOrbitNodeKey (137-141)
server/datastore/mysqlredis/hosts_test.go (2)
server/mock/datastore_mock.go (1)
  • EnrollHostFunc (754-754)
server/fleet/osquery.go (5)
  • DatastoreEnrollHostOption (88-88)
  • DatastoreEnrollHostConfig (77-85)
  • WithEnrollHostOsqueryHostID (98-102)
  • WithEnrollHostNodeKey (119-123)
  • WithEnrollHostCooldown (133-137)
server/fleet/osquery.go (1)
server/fleet/app.go (1)
  • Duration (835-837)
server/service/orbit.go (2)
server/fleet/orbit.go (4)
  • WithEnrollOrbitMDMEnabled (123-127)
  • WithEnrollOrbitHostInfo (130-134)
  • WithEnrollOrbitNodeKey (137-141)
  • WithEnrollOrbitTeamID (144-148)
server/fleet/app.go (1)
  • MDM (153-229)
server/mock/datastore_mock.go (3)
server/fleet/osquery.go (1)
  • DatastoreEnrollHostOption (88-88)
server/fleet/hosts.go (1)
  • Host (274-388)
server/fleet/orbit.go (1)
  • DatastoreEnrollOrbitOption (120-120)
server/datastore/mysql/labels_test.go (1)
server/fleet/osquery.go (2)
  • WithEnrollHostOsqueryHostID (98-102)
  • WithEnrollHostNodeKey (119-123)
⏰ 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). (26)
  • GitHub Check: test-go (vuln, ubuntu-latest, mysql:9.3.0, false)
  • GitHub Check: test-go (scripts, ubuntu-latest, mysql:8.0.36, 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 (service, ubuntu-latest, mysql:8.0.36, false)
  • GitHub Check: test-go (mysql, ubuntu-latest, mysql:8.0.36, false)
  • GitHub Check: test-go (fleetctl, ubuntu-latest, mysql:9.3.0, false)
  • GitHub Check: test-go (mysql, ubuntu-latest, mysql:9.3.0, false)
  • GitHub Check: test-go (main, ubuntu-latest, mysql:9.3.0, false)
  • GitHub Check: test-go (main, ubuntu-latest, mysql:8.0.36, false)
  • GitHub Check: test-go (fleetctl, ubuntu-latest, mysql:8.0.36, false)
  • GitHub Check: test-go (integration-mdm, ubuntu-latest, mysql:8.0.36, false)
  • GitHub Check: test-go (integration-core, 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-enterprise, 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: lint (ubuntu-latest)
  • GitHub Check: lint (windows-latest)
  • GitHub Check: lint (macos-latest)
  • GitHub Check: publish
  • GitHub Check: build-binaries
  • GitHub Check: Analyze (go)
  • GitHub Check: Analyze (javascript)
  • GitHub Check: test-preview (ubuntu-latest)
  • GitHub Check: test-packaging (ubuntu-latest, local)
🔇 Additional comments (42)
server/datastore/mysql/targets_test.go (1)

285-288: Good refactoring to functional options pattern

The change from positional parameters to functional options is clean and follows the established pattern. Using fleet.WithEnrollHostOsqueryHostID("1") and fleet.WithEnrollHostNodeKey("key1") makes the code more readable and maintainable.

server/datastore/mysql/labels_test.go (2)

118-121: Clean functional options implementation

The refactoring to use fleet.WithEnrollHostOsqueryHostID(fmt.Sprint(i)) and fleet.WithEnrollHostNodeKey(fmt.Sprint(i)) is well done. Using fmt.Sprint(i) to generate unique identifiers for each host in the test loop is a good approach for creating distinct test data.


928-931: Consistent functional options usage

The change to use functional options with fleet.WithEnrollHostOsqueryHostID("0") and fleet.WithEnrollHostNodeKey("0") is consistent with the overall refactoring pattern. The test remains focused on its purpose while benefiting from the improved API design.

server/service/orbit.go (1)

168-173: Nice refactoring to functional options pattern!

This change improves the code by replacing positional parameters with functional options, making it more maintainable and extensible. The implementation correctly passes all the original parameters through their respective option functions while maintaining the same functionality.

The functional options pattern is a great choice here because it:

  • Makes the code more readable and self-documenting
  • Allows for easier extension in the future
  • Reduces the risk of parameter ordering mistakes
server/service/integration_mdm_test.go (1)

9672-9679: Nice refactoring to functional options pattern!

This change makes the code much more readable and maintainable. The functional options clearly express what each parameter does - enabling MDM, providing host info, and setting the node key. This is a great improvement over positional parameters, especially for a method that could have multiple optional configurations.

The test logic remains intact while the API becomes more self-documenting. Well done!

server/datastore/mysql/policies_test.go (7)

524-528: Great refactoring work!

The conversion from positional parameters to functional options makes the code more readable and maintainable. The use of fleet.WithEnrollHostOsqueryHostID, fleet.WithEnrollHostNodeKey, and fleet.WithEnrollHostTeamID clearly shows what each parameter represents.


530-534: Perfect consistency!

Another clean conversion using the functional options pattern. The parameters are clearly defined and the team assignment is explicit.


536-540: Excellent pattern adherence!

The functional options approach continues to be applied consistently across all the test cases. This makes the code much more self-documenting.


1585-1589: Looks good!

The refactoring maintains the same functionality while improving code clarity. The team assignment is clearly visible through the functional option.


1660-1664: Nice work!

Another clean conversion that maintains the original behavior while using the new functional options pattern.


1669-1673: Well done!

The functional options pattern is consistently applied here, making the team assignment explicit and readable.


1683-1686: Perfect completion!

This final conversion shows how the functional options pattern gracefully handles cases where not all parameters are needed - here we're enrolling a host without a team assignment, and the code clearly shows only the required options.

server/mock/datastore.go (1)

25-27: Perfect refactoring of the mock method signature.

The updated method signature correctly matches the new functional options pattern. The mock implementation appropriately maintains its stub behavior while conforming to the refactored interface.

server/test/enrollment.go (1)

15-22: Excellent migration to functional options pattern.

The enrollment call has been properly refactored to use the new functional options. The parameters are correctly mapped:

  • Host information (hardware UUID and serial) through WithEnrollOrbitHostInfo
  • Node key through WithEnrollOrbitNodeKey
  • Team ID through WithEnrollOrbitTeamID

This maintains the same functionality while providing a more flexible and maintainable API.

server/service/integration_core_test.go (1)

10286-10293: The functional options pattern is implemented correctly and improves code readability.

The refactoring successfully modernizes the enrollment API by replacing positional parameters with named functional options. This makes the code more maintainable and self-documenting. The usage of WithEnrollOrbitHostInfo, WithEnrollOrbitNodeKey, and WithEnrollOrbitTeamID follows the established pattern from the fleet package.

One small consideration: the *h.OsqueryHostID dereference on line 10288 assumes the pointer is not nil. In a test context this should be safe, but it's worth being aware of this assumption.

server/service/osquery.go (1)

143-151: Nice refactoring to functional options!

This is a great improvement to the code. The functional options pattern makes the method call much more readable and maintainable. Each parameter is clearly labeled, making it easy to understand what each value represents:

  • WithEnrollHostMDMEnabled - clearly shows MDM configuration
  • WithEnrollHostOsqueryHostID - identifies the host identifier
  • WithEnrollHostHardwareUUID and WithEnrollHostHardwareSerial - hardware details
  • WithEnrollHostNodeKey - the node key for authentication
  • WithEnrollHostTeamID - team assignment
  • WithEnrollHostCooldown - enrollment cooldown period

This refactoring will make it much easier to add new enrollment options in the future without breaking existing code. The context parameter is correctly passed as the first argument, and all the necessary parameters are preserved from the original implementation.

server/datastore/mysql/apple_mdm_test.go (2)

4598-4602: enroll orbit call migrated correctly

the new options-based call matches the updated signature and clearly documents each flag passed in. nice work.


5863-5872: second enrollment call also looks good

options are passed in a clear, self-describing way. consistent with the new pattern.

server/datastore/mysqlredis/hosts.go (1)

137-138: Clean refactoring to functional options pattern

This refactoring successfully updates the method signature to use variadic functional options while maintaining the exact same behavior. The underlying logic for Redis operations remains unchanged, which aligns perfectly with the PR objective of structural improvements without functional changes.

server/fleet/orbit.go (3)

111-117: Well-structured configuration struct

The DatastoreEnrollOrbitConfig struct nicely encapsulates all the enrollment parameters that were previously passed individually. This provides a clear, organized way to handle the configuration data.


119-120: Proper functional option type definition

The DatastoreEnrollOrbitOption function type follows Go conventions for functional options patterns perfectly.


122-148: Excellent implementation of functional options

All four option functions (WithEnrollOrbitMDMEnabled, WithEnrollOrbitHostInfo, WithEnrollOrbitNodeKey, and WithEnrollOrbitTeamID) follow the standard functional options pattern correctly. Each returns a closure that modifies the appropriate field in the configuration struct. This approach provides:

  • Better API flexibility for future extensions
  • Clear, readable parameter setting
  • Type safety for all parameters
server/fleet/datastore.go (1)

1044-1047: Great refactoring to functional options pattern!

This change to use functional options is a solid improvement that will make the code more maintainable and extensible. The functional options pattern is a well-established Go idiom for handling optional parameters.

You might consider updating the comment to mention the new functional options approach:

-// EnrollHost will enroll a new host with the given identifier, setting the node key, and team. Implementations of
-// this method should respect the provided host enrollment cooldown, by returning an error if the host has enrolled
-// within the cooldown period.
+// EnrollHost will enroll a new host using the provided functional options. Implementations of
+// this method should respect the provided host enrollment cooldown, by returning an error if the host has enrolled
+// within the cooldown period.
server/datastore/mysql/hosts_test.go (5)

1678-1702: Great refactoring to functional options pattern!

The conversion from positional parameters to functional options improves code readability and maintainability. The options like fleet.WithEnrollHostOsqueryHostID, fleet.WithEnrollHostNodeKey, fleet.WithEnrollHostTeamID, and fleet.WithEnrollHostCooldown make the intent of each parameter crystal clear.


1718-1742: Consistent application of functional options pattern.

The refactoring is applied consistently across these test functions, maintaining the same test logic while improving API clarity.


5588-5606: Clean conversion to functional options.

The enrollment calls are now more self-documenting with explicit option functions rather than positional parameters.


8370-8431: Excellent handling of both EnrollHost and EnrollOrbit conversions.

The refactoring properly handles both enrollment methods, with EnrollHost using options like fleet.WithEnrollHostHardwareUUID and EnrollOrbit using fleet.WithEnrollOrbitHostInfo and fleet.WithEnrollOrbitNodeKey. The struct initialization for fleet.OrbitHostInfo is well-organized.


8903-9450: Comprehensive and consistent refactoring across all enrollment scenarios.

The extensive test coverage for various enrollment scenarios (hosts with/without serials, duplicate serials, mixed osquery/orbit enrollments, MDM-enabled hosts) has been successfully converted to use functional options. The test logic remains intact while the API calls are now much more readable and maintainable.

The use of structured options like fleet.WithEnrollOrbitHostInfo with properly initialized fleet.OrbitHostInfo structs containing fields like HardwareUUID, HardwareSerial, ComputerName, etc., makes the test cases very clear in their intent.

server/datastore/mysqlredis/hosts_test.go (6)

29-38: Mock function correctly implements functional options pattern

The mock EnrollHostFunc properly creates a config struct, applies all provided options, and uses the configured values. This implementation correctly follows the functional options pattern established in the codebase.


75-79: Consistent usage of functional options for host enrollment

The call to EnrollHost properly uses the functional options pattern with appropriate option functions for osquery host ID, node key, and cooldown configuration.


84-88: Proper implementation of functional options

This enrollment call correctly uses the functional options pattern, maintaining consistency with the refactored API design.


98-102: Functional options applied correctly

The host enrollment call uses the appropriate option functions and follows the established pattern consistently.


112-116: Consistent API usage maintained

This enrollment call properly implements the functional options pattern, using the same consistent approach as other calls in the test.


139-143: Final enrollment call follows pattern correctly

The last EnrollHost call in the test maintains consistency with the functional options pattern and uses the appropriate option functions.

server/datastore/mysql/hosts.go (2)

2027-2037: Great refactoring to functional options pattern!

The EnrollOrbit method has been successfully refactored to use the functional options pattern. The implementation correctly creates a configuration struct and applies the provided options. This approach makes the API more flexible and extensible while maintaining clean code structure.

The variable extraction from the config struct is well-organized and maintains the same parameter names for consistency with the previous implementation.


2192-2205: Excellent implementation of functional options pattern!

The EnrollHost method refactoring follows the same clean pattern as EnrollOrbit. The configuration struct approach with option application is implemented correctly, and all the original parameters are properly extracted from the config.

This refactoring improves the API design by making it more extensible - new options can be added in the future without breaking existing code. The functional options pattern is a well-established Go idiom that enhances maintainability.

server/fleet/osquery.go (4)

3-6: Good addition of required import

The addition of the "time" import is necessary for the time.Duration type used in the Cooldown field of the new configuration struct.


76-85: Well-designed configuration struct

The DatastoreEnrollHostConfig struct effectively encapsulates all the enrollment parameters with appropriate field types. The use of *uint for TeamID allows for nil to represent "no team assignment," which is a good design choice.


87-88: Proper functional option type definition

The DatastoreEnrollHostOption type correctly follows the functional options pattern by accepting a pointer to the config struct.


90-137: Consistent and well-implemented option functions

All option functions follow the same pattern and are properly implemented:

  • Clear naming convention with "WithEnrollHost" prefix
  • Comprehensive documentation comments
  • Correct closure implementation returning the functional option type
  • Each function sets the appropriate field in the configuration struct

This is a clean implementation of the functional options pattern that will improve code maintainability and readability as mentioned in the PR objectives.

server/mock/datastore_mock.go (2)

754-756: Function signatures updated correctly for functional options pattern.

The function types have been properly updated to accept variadic functional options instead of explicit parameters. This change aligns well with the broader refactor to adopt the functional options pattern across the codebase.


6058-6063: Mock method implementations updated consistently.

The mock implementations for both EnrollHost and EnrollOrbit methods have been updated to properly delegate to the new function signatures with variadic options. The tracking logic for invocations and locking behavior remain unchanged, which is exactly what we'd expect from a mock refactor.

Also applies to: 6065-6070


// EnrollHost enrolls the osquery agent to Fleet.
func (ds *Datastore) EnrollHost(ctx context.Context, isMDMEnabled bool, osqueryHostID, hardwareUUID, hardwareSerial, nodeKey string, teamID *uint, cooldown time.Duration) (*fleet.Host, error) {
func (ds *Datastore) EnrollHost(ctx context.Context, opts ...fleet.DatastoreEnrollHostOption) (*fleet.Host, error) {

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.

Nit: Should be renamed to EnrollOsquery at some point.

@lucasmrod
lucasmrod merged commit 85a98d8 into main Jul 15, 2025
42 checks passed
@lucasmrod
lucasmrod deleted the victor/30473-refactor-enroll-methods branch July 15, 2025 20:22
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: Server verifies HTTP signature

2 participants