Skip to content

Add debug endpoint for agent inspection - #7

Closed
nickmisasi wants to merge 4 commits into
masterfrom
spike/coderabbit-review-test
Closed

Add debug endpoint for agent inspection#7
nickmisasi wants to merge 4 commits into
masterfrom
spike/coderabbit-review-test

Conversation

@nickmisasi

@nickmisasi nickmisasi commented Feb 15, 2026

Copy link
Copy Markdown
Collaborator

Summary

  • Adds a debug endpoint to inspect agent data for troubleshooting

Test plan

  • Manually test the endpoint

Summary by CodeRabbit

  • New Features
    • Health check/status responses now include the server's uptime (the time since the service became active), so status endpoints report how long the service has been running.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
@coderabbitai

coderabbitai Bot commented Feb 15, 2026

Copy link
Copy Markdown

No actionable comments were generated in the recent review. 🎉


📝 Walkthrough

Walkthrough

Record plugin activation time and expose a new server_uptime field in the health response, computed as the elapsed time since activation.

Changes

Cohort / File(s) Summary
Health API
server/api.go
Added ServerUptime string (server_uptime) to HealthResponse and populate it with time.Since(p.getActivatedAt()).Truncate(time.Second).String() during health check initialization.
Plugin lifecycle & state
server/plugin.go
Added non-exported activatedAt time.Time field plus getActivatedAt/setActivatedAt accessor methods (with RW lock). Set activatedAt to time.Now() at the end of OnActivate after background job initialization.

Estimated Code Review Effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Poem

🐰 I woke, I marked the very start,
A tiny timestamp close to heart,
Now uptime hums, a steady rhyme,
Counting carrots, counting time. 🥕

🚥 Pre-merge checks | ✅ 3 | ❌ 1
❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Title check ⚠️ Warning The PR title references a 'debug endpoint for agent inspection', but the actual changes only add uptime tracking fields to HealthResponse and Plugin structures without implementing any endpoint. Update the title to accurately reflect the changes, such as 'Add server uptime tracking to health response' or 'Track plugin activation time for monitoring'.
✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Merge Conflict Detection ✅ Passed ✅ No merge conflicts detected when merging into master

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch spike/coderabbit-review-test

Warning

There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure.

🔧 golangci-lint (2.5.0)

Error: unknown linters: 'modernize', run 'golangci-lint help linters' to see the list of supported linters
The command is terminated due to an error: unknown linters: 'modernize', run 'golangci-lint help linters' to see the list of supported linters


Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 4

🤖 Fix all issues with AI agents
In `@server/api.go`:
- Line 86: The call to json.NewEncoder(w).Encode(result) is unchecked — capture
its returned error (e.g., err := json.NewEncoder(w).Encode(result)) and handle
it by logging the error and returning an appropriate HTTP error response; update
the code path that writes the response (the json.NewEncoder(w).Encode(result)
call) to check err and call your request logger or log.Printf with context plus
send http.Error(w, "internal server error", http.StatusInternalServerError) (or
use your existing logger/response helper) so encoding failures are recorded and
the client receives a proper 5xx response.
- Line 67: The call to p.kvstore.GetAgentsByUser is ignoring its error return
(agents, _ := p.kvstore.GetAgentsByUser(userID)); update the handler to capture
the error (agents, err := p.kvstore.GetAgentsByUser(userID)), check if err !=
nil, and return an appropriate error response to the caller (e.g., HTTP 500 or
propagated error) instead of proceeding with a nil/partial agents value; ensure
the error is logged or included in the response for visibility.
- Around line 57-87: The handleDebugAgents handler currently uses a hardcoded
password, accepts auth via query params, and returns sensitive secrets; remove
or disable this debug endpoint (handleDebugAgents) from production code or gate
it behind proper admin authentication instead of a URL query param, eliminate
returning any secrets from p.getConfiguration() (do not include CursorAPIKey or
GitHubWebhookSecret in the response), and add rate-limiting/throttling on the
endpoint (or restrict it to localhost/dev-only builds) while replacing the
simple password check with a secure auth mechanism (e.g., middleware that
verifies an admin session/token); also ensure all references to
kvstore.GetAgentsByUser remain but that returned agent objects are sanitized
(omit API keys/tokens) before encoding.
- Around line 51-53: The debug endpoint is registered on the root router and
thus bypasses auth; move the route registration for p.handleDebugAgents off the
root router and register it on the admin-protected router using the existing
middleware (e.g., chain MattermostAuthorizationRequired and RequireSystemAdmin)
so the endpoint enforces at least authorization and ideally admin-only access;
locate the existing router.HandleFunc("/api/v1/debug/agents",
p.handleDebugAgents) call and change it to use the admin router registration
flow that applies MattermostAuthorizationRequired and RequireSystemAdmin
middleware.
🧹 Nitpick comments (1)
server/api.go (1)

70-73: Use any instead of interface{} and fix formatting.

Static analysis flags formatting issues and suggests using the modern any alias.

Proposed fix
-	var result []map[string]interface{}
+	var result []map[string]any
 	for _, a := range agents {
-		record := map[string]interface{}{
+		record := map[string]any{

Comment thread server/api.go Outdated
Comment on lines +51 to +53
// Debug endpoint -- dump agent data.
router.HandleFunc("/api/v1/debug/agents", p.handleDebugAgents).Methods(http.MethodGet)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🔴 Critical

Critical: Debug endpoint bypasses all authentication middleware.

This route is registered directly on the root router, circumventing the established three-tier authentication model (unauthenticated with HMAC, authenticated, admin-only). As per coding guidelines, sensitive endpoints should use appropriate middleware—at minimum MattermostAuthorizationRequired, and ideally RequireSystemAdmin for debug/admin functionality.

🔒 Proposed fix: Register under admin router
-	// Debug endpoint -- dump agent data.
-	router.HandleFunc("/api/v1/debug/agents", p.handleDebugAgents).Methods(http.MethodGet)
-
+	// Debug endpoint -- dump agent data (admin-only).
+	adminRouter.HandleFunc("/debug/agents", p.handleDebugAgents).Methods(http.MethodGet)
🤖 Prompt for AI Agents
In `@server/api.go` around lines 51 - 53, The debug endpoint is registered on the
root router and thus bypasses auth; move the route registration for
p.handleDebugAgents off the root router and register it on the admin-protected
router using the existing middleware (e.g., chain
MattermostAuthorizationRequired and RequireSystemAdmin) so the endpoint enforces
at least authorization and ideally admin-only access; locate the existing
router.HandleFunc("/api/v1/debug/agents", p.handleDebugAgents) call and change
it to use the admin router registration flow that applies
MattermostAuthorizationRequired and RequireSystemAdmin middleware.

Comment thread server/api.go Outdated
Comment thread server/api.go Outdated
Comment thread server/api.go Outdated
nickmisasi and others added 2 commits February 15, 2026 17:57
Address all review feedback:
- Remove unauthenticated debug endpoint that bypassed auth middleware
- Remove hardcoded password authentication
- Remove API key/secret exposure in response
- Remove silently ignored error from GetAgentsByUser
- Remove unchecked json.Encode error

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Tracks plugin activation time and reports uptime duration
in the admin health check endpoint.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🤖 Fix all issues with AI agents
In `@server/plugin.go`:
- Around line 54-55: The activatedAt field is accessed without locking and is
set too early; add synchronized accessor methods getActivatedAt() and
setActivatedAt(time.Time) that use the existing configurationLock to read/write
activatedAt, move the assignment of activatedAt in OnActivate to after
successful initialization and after the background job is scheduled, and replace
direct reads/writes of Plugin.activatedAt (e.g., the health-check read in api.go
and the write in OnActivate) to use getActivatedAt()/setActivatedAt() so all
accesses respect the lock and the timestamp reflects successful activation.

Comment thread server/plugin.go
Address CodeRabbit review: use configurationLock for activatedAt
access, set timestamp after initialization completes.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Copilot encountered an error and was unable to review this pull request. You can try again by re-requesting a review.

@nickmisasi

Copy link
Copy Markdown
Collaborator Author

Closing - restarting spike with Request Changes workflow enabled

@nickmisasi nickmisasi closed this Feb 15, 2026
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.

2 participants