fix: inject service user context in API key authentication #2556
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!2556
Loading…
Add table
Add a link
Reference in a new issue
No description provided.
Delete branch "refs/pull/2556/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: #2117
Original author: @mfreeman451
Original URL: https://github.com/carverauto/serviceradar/pull/2117
Original created: 2025-12-13T17:05:34Z
Original updated: 2025-12-13T20:40:58Z
Original head: carverauto/serviceradar:bug/icmp_metrics_stoppage
Original base: main
Original merged: 2025-12-13T20:40:53Z by @mfreeman451
User description
API key authentication was not setting a user in the request context, causing RouteProtectionMiddleware and RBAC checks to fail with HTTP 401. This broke the /api/devices/{id}/metrics endpoint when called with API key auth (e.g., from the web frontend), preventing ICMP metrics from being displayed in the UI.
The fix injects a service user with admin/operator/viewer roles when API key authentication succeeds, matching the behavior of edge-download authentication and bearer token authentication.
🤖 Generated with Claude Code
IMPORTANT: Please sign the Developer Certificate of Origin
Thank you for your contribution to ServiceRadar. Please note, when contributing, the developer must include
a DCO sign-off statement indicating the DCO acceptance in one commit message. Here
is an example DCO Signed-off-by line in a commit message:
Describe your changes
Issue ticket number and link
Code checklist before requesting a review
PR Type
Bug fix
Description
Inject service user context in API key authentication to fix RBAC failures
Allows
/api/devices/{id}/metricsendpoint to work with API key authRestores ICMP metrics display in UI that was showing stale data
Matches behavior of edge-download and bearer token authentication
Diagram Walkthrough
File Walkthrough
server.go
Inject service user context in API key authpkg/core/api/server.go
handleAPIKeyAuthfunction to inject a service user intorequest context after successful API key validation
api-key@systemand rolesadmin,operator,viewercontext.WithValueto set user in context before calling nexthandler
proposal.md
Change proposal for ICMP metrics display fixopenspec/changes/fix-icmp-metrics-display-stoppage/proposal.md
context from API key auth
returns HTTP 401
investigation
spec.md
API key authentication context propagation specificationopenspec/changes/fix-icmp-metrics-display-stoppage/specs/api-authentication/spec.md
API key validation
endpoints
authentication
tasks.md
Implementation and verification tasks for metrics fixopenspec/changes/fix-icmp-metrics-display-stoppage/tasks.md
endpoint HTTP 401 error
handleAPIKeyAuthandinjecting user context
investigation
Imported GitHub PR comment.
Original author: @qodo-code-review[bot]
Original URL: https://github.com/carverauto/serviceradar/pull/2117#issuecomment-3649626756
Original created: 2025-12-13T17:06:08Z
You are nearing your monthly Qodo Merge usage quota. For more information, please visit here.
PR Compliance Guide 🔍
Below is a summary of compliance checks for this PR:
Privilege escalation
Description: Broad privilege escalation via API key: a successful API key match injects a service user
with high-privilege roles (
admin,operator,viewer) into the request context, grantingfull RBAC access to any holder of the single shared API key without scoping, rotation, or
audit linkage to a real principal.
server.go [545-550]
Referred Code
Insecure context handling
Description: Insecure context key usage risk: uses
context.WithValue(r.Context(), auth.UserKey,&models.User{...})which can be overwritten or spoofed by other middleware ifauth.UserKeyis not an unexported unique type, potentially allowing user impersonation or confusion of
auth state.
server.go [546-550]
Referred Code
Weak API key auth
Description: Static shared API key from environment with header comparison only (
X-API-Key==API_KEY)lacks rate limiting, replay protection, or IP throttling and now unlocks admin access,
increasing brute-force and credential stuffing impact if the key leaks.
server.go [539-551]
Referred Code
🎫 No ticket provided
Codebase context is not defined
Follow the guide to enable codebase context checks.
Generic: Meaningful Naming and Self-Documenting Code
Objective: Ensure all identifiers clearly express their purpose and intent, making code
self-documenting
Status: Passed
Generic: Secure Error Handling
Objective: To prevent the leakage of sensitive system information through error messages while
providing sufficient detail for internal debugging.
Status: Passed
Generic: Secure Logging Practices
Objective: To ensure logs are useful for debugging and auditing without exposing sensitive
information like PII, PHI, or cardholder data.
Status: Passed
Generic: Comprehensive Audit Trails
Objective: To create a detailed and reliable record of critical system actions for security analysis
and compliance.
Status:
Missing audit log: The new API key success path injects a service user and proceeds without logging the
authentication event or user context, leaving no audit trail for this critical action.
Referred Code
Generic: Robust Error Handling and Edge Case Management
Objective: Ensure comprehensive error handling that provides meaningful context and graceful
degradation
Status:
Context error handling: The code creates a context with user data but does not handle potential issues (e.g., nil
keys/types or downstream failures) or add diagnostic logs for the invalid API key branch.
Referred Code
Generic: Security-First Input Validation and Data Handling
Objective: Ensure all data inputs are validated, sanitized, and handled securely to prevent
vulnerabilities
Status:
Broad role grant: Injecting a service user with admin/operator/viewer roles for any valid API key may exceed
least privilege; consider restricting roles or scoping access for API key usage.
Referred Code
Compliance status legend
🟢 - Fully Compliant🟡 - Partial Compliant
🔴 - Not Compliant
⚪ - Requires Further Human Verification
🏷️ - Compliance label
Imported GitHub PR comment.
Original author: @qodo-code-review[bot]
Original URL: https://github.com/carverauto/serviceradar/pull/2117#issuecomment-3649627557
Original created: 2025-12-13T17:07:07Z
You are nearing your monthly Qodo Merge usage quota. For more information, please visit here.
PR Code Suggestions ✨
Explore these optional code suggestions:
Re-evaluate hardcoded admin permissions for API keys
The current fix grants excessive admin permissions to any user authenticating
with an API key, creating a security risk. A better approach would be to
associate API keys with specific, limited roles instead of a static,
all-powerful user.
Examples:
pkg/core/api/server.go [546-549]
Solution Walkthrough:
Before:
After:
Suggestion importance[1-10]: 9
__
Why: The suggestion correctly identifies a significant security risk by hardcoding full admin privileges for the API key, which violates the principle of least privilege and has system-wide implications.
Avoid hardcoding permissive admin roles
Make the API key roles configurable via an environment variable and default to a
least-privilege role like
viewerinstead of hardcoding full admin access.pkg/core/api/server.go [545-550]
Suggestion importance[1-10]: 9
__
Why: The suggestion correctly identifies a significant security risk by hardcoding admin-level permissions for the API key, and proposes a more secure, configurable approach that adheres to the principle of least privilege.
Cache API key on startup
To improve performance, read the
API_KEYfrom environment variables once atserver startup and cache it in the
APIServerstruct, instead of reading it onevery request.
pkg/core/api/server.go [537-559]
[To ensure code accuracy, apply this suggestion manually]Suggestion importance[1-10]: 5
__
Why: The suggestion proposes a valid performance optimization by caching the
API_KEYon startup, which is a good practice, although the performance impact ofos.Getenvis likely minor in this context.