sync #2298
No reviewers
Labels
No labels
1week
2weeks
Failed compliance check
IP cameras
NATS
Possible security concern
Review effort 1/5
Review effort 2/5
Review effort 3/5
Review effort 4/5
Review effort 5/5
UI
aardvark
accessibility
amd64
api
arm64
auth
back-end
bgp
blog
bug
build
checkers
ci-cd
cleanup
cnpg
codex
core
dependencies
device-management
documentation
duplicate
dusk
ebpf
enhancement
eta 1d
eta 1hr
eta 3d
eta 3hr
feature
fieldsurvey
github_actions
go
good first issue
help wanted
invalid
javascript
k8s
log-collector
mapper
mtr
needs-triage
netflow
network-sweep
observability
oracle
otel
plug-in
proton
python
question
reddit
redhat
research
rperf
rperf-checker
rust
sdk
security
serviceradar-agent
serviceradar-agent-gateway
serviceradar-web
serviceradar-web-ng
siem
snmp
sysmon
topology
ubiquiti
wasm
wontfix
zen-engine
No milestone
No project
No assignees
1 participant
Notifications
Due date
No due date set.
Dependencies
No dependencies set.
Reference
carverauto/serviceradar!2298
Loading…
Add table
Add a link
Reference in a new issue
No description provided.
Delete branch "refs/pull/2298/head"
Deleting a branch is permanent. Although the deleted branch may continue to exist for a short time before it actually gets removed, it CANNOT be undone in most cases. Continue?
Imported from GitHub pull request.
Original GitHub pull request: #1727
Original author: @mfreeman451
Original URL: https://github.com/carverauto/serviceradar/pull/1727
Original created: 2025-10-07T00:22:54Z
Original updated: 2025-10-07T02:09:52Z
Original head: carverauto/serviceradar:main
Original base: updates/device_registry
Original merged: 2025-10-07T02:09:52Z by @mfreeman451
PR Type
Enhancement, Tests, Documentation
Description
• Major performance and scalability improvements: Enhanced SYN scanner with sharded token bucket rate limiter, implemented sharded memory store for concurrent operations, and added TCP connect scanner support
• KV store infrastructure overhaul: Added multi-domain NATS KV support, atomic operations (
PutIfAbsent), configuration management endpoints, and comprehensive KV metadata handling• API server refactoring: Removed SRQL dependency, integrated RBAC middleware, added JWKS/OIDC discovery endpoints, and implemented services tree visualization
• Agent and poller enhancements: Added KV bootstrapping, runtime configuration updates, and improved service management capabilities
• Network sweeper improvements: Integrated TCP connect scanner, implemented parallel chunk processing with worker pools, and added adaptive configuration scaling
• Device deduplication: Added backfill functionality for identity management and IP alias tombstone processing
• Release automation: New GitHub release tool for automated package publishing with CI/CD integration
• Test improvements: Refactored test structures with helper functions and added comprehensive KV metadata test coverage
• Code cleanup: Import formatting, type renaming for cleaner APIs, and enhanced error handling throughout
Diagram Walkthrough
File Walkthrough
12 files
syn_scanner.go
Major SYN scanner performance and reliability enhancementspkg/scan/syn_scanner.go
• Added comprehensive constants for timing, network packet sizes,
buffer management, and performance tuning
• Implemented sharded token
bucket rate limiter to reduce lock contention at high concurrency
•
Added eventfd-based ring reader wakeup mechanism for improved
cancellation handling
• Enhanced error handling with predefined error
variables and improved resource cleanup
• Integrated fastsum library
for optimized checksum calculations in packet processing
sweeper.go
Network sweeper scalability and TCP connect scanner integrationpkg/sweeper/sweeper.go
• Added TCP connect scanner support alongside existing SYN scanner for
firewall-safe scanning
• Implemented parallel chunk processing with
worker pools for improved configuration loading performance
• Added
adaptive configuration scaling based on deployment size
(small/medium/large/extra-large scale)
• Enhanced result processing
with batching and stream processing for better memory efficiency
•
Added comprehensive error handling with predefined error variables
server.go
Major API server refactoring with KV store and auth enhancementspkg/core/api/server.go
• Removed SRQL-related imports and functionality, replacing with
direct database service calls
• Added comprehensive KV store
management with multiple endpoint support and domain routing
•
Implemented JWKS and OIDC discovery endpoints for authentication
•
Added RBAC middleware integration and admin route protection
•
Introduced services tree endpoint for hierarchical
poller/agent/service visualization
kv.pb.go
KV service protocol extension with Info endpointproto/kv.pb.go
• Added
InfoRequestandInfoResponsemessage types for KV serverconfiguration queries
• Extended KV service with
Infomethod to exposedomain and bucket information
• Updated protobuf definitions to
include new RPC method signatures
publish_packages.go
GitHub release automation tool for package publishingrelease/publish_packages.go
• Complete GitHub release automation tool for publishing package
artifacts
• Supports creating/updating releases with proper asset
management and versioning
• Handles Debian and RPM package naming
conventions with metadata extraction
• Includes dry-run mode and
comprehensive error handling for CI/CD integration
kv_grpc.pb.go
KV gRPC service extension with conditional put and info methodsproto/kv_grpc.pb.go
• Added
PutIfAbsentmethod for atomic conditional key storage•
Implemented
InfoRPC method for KV server configuration retrieval•
Updated client and server interfaces with new method signatures
•
Extended service descriptor with additional RPC endpoints
monitoring.pb.go
Add KV store identifier field to monitoring protobuf messagesproto/monitoring.pb.go
• Added
KvStoreIdfield toPollerStatusRequest,ServiceStatus, andPollerStatusChunkstructs• Added corresponding getter methods
GetKvStoreId()for the new field• Updated protobuf field numbers and
serialization descriptors to accommodate the new field
server.go
Enhance agent server with KV bootstrapping and runtime config updatespkg/agent/server.go
• Added bootstrap functionality to create default KV configurations
for common services
• Introduced new error variables for better error
handling (
ErrAgentIDRequired,ErrInvalidChunkCount, etc.)• Added
UpdateConfig()andRestartServices()methods for runtime configurationupdates
• Enhanced service creation to accept context parameter and
improved error handling
memory_store.go
Implement sharded memory store for improved concurrent performancepkg/sweeper/memory_store.go
• Implemented sharded storage architecture to reduce lock contention
under high write loads
• Added per-shard locking and hash-based shard
selection using FNV-1a algorithm
• Enhanced cleanup and metrics
logging with shard-aware operations
• Increased default capacity from
100k to 1M results to handle larger networks
backfill.go
Add device deduplication backfill functionality for identitymanagementpkg/core/backfill.go
• Added
BackfillIdentityTombstones()function to handle duplicatedevice cleanup based on identity keys
• Added
BackfillIPAliasTombstones()function to merge IP-based duplicates intocanonical devices
• Implemented helper functions for identity row
processing and device ID partitioning
auth.go
Add configuration management endpoints with KV store supportpkg/core/api/auth.go
• Added
handleGetConfig()andhandleUpdateConfig()methods forconfiguration management
• Implemented support for both JSON and TOML
configuration formats
• Added KV domain resolution and multi-store
support with fallback mechanisms
• Enhanced configuration routing with
service-specific key generation
nats.go
Add multi-domain support and atomic operations to NATS KV storepkg/kv/nats.go
• Refactored to support multi-domain JetStream operations with
domain-aware key routing
• Added
PutIfAbsent()method for atomic keycreation
• Implemented domain extraction from keys with
domains//pattern
• Enhanced connection management with per-domain JetStream and
KV instances
3 files
server.go
MCP server code cleanup and interface improvementspkg/mcp/server.go
• Reorganized imports and added proper formatting with consistent
spacing
• Renamed types from
MCPServer,MCPConfig,MCPTooletc. toServer,Config,Toolfor cleaner API• Added predefined error
variables for common validation errors
• Updated interface references
to use local
QueryExecutorinstead of external API packagesnmp_checker.go
Minor formatting improvement in SNMP checkerpkg/agent/snmp_checker.go
• Added blank line for improved code formatting and readability
icmp_scanner_priv_test.go
Fix import order formatting in ICMP scanner testpkg/scan/icmp_scanner_priv_test.go
• Reordered import statements to follow Go conventions (standard
library, third-party, local packages)
1 files
vim.css
Added vim theme CSS file for documentationthird_party/cwalk/docs/assets/css/vim.css
• Added new CSS file with single line content indicating unknown vim
theme
3 files
aggregation_test.go
Test refactoring for device aggregation functionalitypkg/sweeper/aggregation_test.go
• Refactored test structure with helper function for better test
organization
• Split monolithic test into focused individual test
functions
• Improved test readability and maintainability with proper
setup/teardown
• Enhanced test coverage for device result aggregation
functionality
end_to_end_flow_test.go
Refactor end-to-end test structure with helper functionspkg/integration_test/end_to_end_flow_test.go
• Refactored test structure by extracting helper functions for better
organization
• Added
createTestData()function to separate test datacreation
• Split main test logic into smaller, focused functions like
executeEndToEndFlow(),setupKVMock(), etc.• Improved code readability
and maintainability through better separation of concerns
kv_metadata_test.go
Add comprehensive tests for KV metadata functionalitypkg/core/kv_metadata_test.go
• Added comprehensive test suite for KV metadata extraction and
service record creation
• Tests cover services with and without KV
store IDs, metadata validation, and integration scenarios
• Includes
tests for
extractSafeKVMetadata(),createServiceRecords(), andReportStatus()methods101 files
Imported GitHub PR comment.
Original author: @qodo-code-review[bot]
Original URL: https://github.com/carverauto/serviceradar/pull/1727#issuecomment-3374738566
Original created: 2025-10-07T00:35:31Z
PR Compliance Guide 🔍
Below is a summary of compliance checks for this PR:
Environment-based toggle
Description: Use of environment variable 'SR_SYN_USE_EVENTFD' conditionally enables eventfd-based
wakeups without authentication or privilege checks, which could allow unbounded wakeups if
an attacker can set the environment for the running process; ensure the runtime
environment is controlled and consider a safer default.
syn_scanner.go [2056-2071]
Referred Code
Rate limit disable risk
Description: Conservative caps and defaults in rate limiting are implemented, but SetRateLimit allows
disabling limits (pps<=0) resulting in allow-all behavior; if exposed to untrusted input,
this could enable packet flood—validate caller and guard external configuration paths.
syn_scanner.go [1599-1660]
Referred Code
Hash-based shard skew
Description: FNV-1a based shard selection over user-controlled host string could be skewed by crafted
inputs causing shard hotspotting; consider stronger hashing or salting to reduce targeted
contention.
memory_store.go [592-633]
Referred Code
... (clipped 21 lines)
Imported GitHub PR comment.
Original author: @qodo-code-review[bot]
Original URL: https://github.com/carverauto/serviceradar/pull/1727#issuecomment-3374743135
Original created: 2025-10-07T00:38:09Z
PR Code Suggestions ✨
Explore these optional code suggestions:
Fix race condition during cleanup
Fix a race condition in the scan cleanup logic by moving the port release loop
to execute before the main scanner mutex is unlocked, preventing resource
contention with a subsequent scan.
pkg/scan/syn_scanner.go [2301-2325]
[To ensure code accuracy, apply this suggestion manually]Suggestion importance[1-10]: 8
__
Why: The suggestion correctly identifies a race condition where a new scan could start before the previous scan's ports are released, potentially causing port exhaustion. Moving the release logic inside the lock is a critical fix for correctness.
Ensure consistent hashing across platforms
In the
selectShardfunction, use thebinarypackage with a fixed byte order(e.g.,
binary.LittleEndian) to convert the port number to bytes. This ensuresconsistent hashing results across different machine architectures.
pkg/sweeper/memory_store.go [606-633]
[To ensure code accuracy, apply this suggestion manually]Suggestion importance[1-10]: 8
__
Why: The suggestion correctly identifies a potential cross-platform inconsistency issue due to not specifying byte order when hashing the port number. This could lead to hard-to-debug data inconsistency issues, making it a critical fix for correctness and reliability.
Prevent zeroing out critical configurations
Prevent critical configuration parameters in
applySmallScaleConfigfrom beingset to zero when
totalTargetsis zero by enforcing a minimum value of 1.pkg/sweeper/sweeper.go [1314-1330]
[To ensure code accuracy, apply this suggestion manually]Suggestion importance[1-10]: 7
__
Why: The suggestion correctly identifies that critical configuration values like
Concurrencycould be set to zero iftotalTargetsis zero, which would stall the scanner. Enforcing a minimum value of 1 is a good defensive measure.Parallelize network calls to improve performance
Refactor
filterConfiguredServicesto performisServiceConfiguredchecks inparallel using goroutines and a
sync.WaitGroupto improve performance byavoiding sequential network requests.
pkg/core/api/server.go [939-953]
[To ensure code accuracy, apply this suggestion manually]Suggestion importance[1-10]: 7
__
Why: The suggestion correctly identifies a performance bottleneck from sequential network calls in a loop and proposes a valid parallel implementation, which will significantly improve API responsiveness.
Use a struct for safe JSON generation
In
handleOIDCDiscovery, replace manual JSON string concatenation with a structand
json.NewEncoderto safely generate the OIDC discovery response and preventpotential injection vulnerabilities.
pkg/core/api/server.go [662-682]
[To ensure code accuracy, apply this suggestion manually]Suggestion importance[1-10]: 8
__
Why: The suggestion correctly identifies a security risk and bad practice of building JSON via string concatenation with user-controllable input (
r.Host) and provides a robust solution usingjson.NewEncoder.Improve test assertion for map values
In
TestEdgeCases, replaceassert.Equal(t, "",deviceUpdate.Metadata["scan_available_ips"])withassert.Empty()for a moreidiomatic and readable test assertion.
pkg/sweeper/aggregation_test.go [682]
[To ensure code accuracy, apply this suggestion manually]Suggestion importance[1-10]: 4
__
Why: The suggestion correctly points out a potential ambiguity in the test assertion but the proposed
assert.Emptyhas the same flaw; however, the change is already implemented in the PR, making the suggestion valid but redundant.