Files
kandev/apps/backend/internal/agentctl/server/api/auth_test.go
T
João Salavisa dccff23cc0 feat(backend): per-launch authentication for agentctl (#666)
* feat(backend): per-launch authentication for agentctl

Add nonce-based handshake protocol to secure all agentctl HTTP/WS
endpoints. On launch, the parent (backend) passes a one-time bootstrap
nonce via AGENTCTL_BOOTSTRAP_NONCE env var. agentctl generates its own
auth token, enables Bearer auth immediately, and returns the token to
the parent via POST /auth/handshake (validated by nonce).

Standalone, Docker, and Sprites executors all use the same handshake
flow. Removes the old AGENTCTL_AUTH_TOKEN env var approach. For
Docker/Sprites, the retrieved token is persisted encrypted in
SecretStore (AES-256-GCM) for crash recovery.

Security properties:
- Auth enabled from boot (no unprotected window)
- Token never in env vars (only the burned nonce)
- Nonce is one-shot (replay impossible)
- Constant-time token comparison (timing-safe)

* fix: check fmt.Sscanf return value in integration test

* fix: address review feedback - constant-time nonce comparison, safe ID truncation

* fix(backend): exempt MCP routes from agentctl auth middleware

The agent subprocess connects to agentctl's MCP endpoints (/sse, /message,
/mcp) to use kandev tools (create_task, ask_user_question, etc.). These
endpoints run on the same HTTP server as the authenticated API, but the
agent process doesn't possess the auth token — it was only exchanged
between the backend and agentctl during the handshake.

Exempt /sse, /message, and /mcp from the Bearer auth middleware since the
agent process runs in the same trust boundary as agentctl.

* refactor(backend): remove query param token fallback and document SetAuthToken constraint

Remove the ?token= query parameter fallback from extractBearerToken —
tokens in URLs leak via access logs, referer headers, and browser history.
All WS callers already use Authorization headers via wsAuthHeaders().

Document SetAuthToken's concurrency constraint: it must not be called
concurrently with HTTP requests on the same client.

* fix(backend): enforce mutex in ControlClient/Launcher auth, fix Start() lock scope

- Add sync.Mutex to ControlClient; protect SetAuthToken and AuthToken() reads
- Guard Launcher.AuthToken() with l.mu (written under lock in Start, read unprotected)
- Extract buildAndStartProcess and performHandshake from Start() (was 106 lines, over 80-line limit)
- Release l.mu before blocking health/handshake calls so monitorExit() can close
  l.exited — previously the fast-fail path in waitForHealthy was unreachable
- Update stale executor_backend.go comment (standalone no longer uses env var auth)

Co-authored-by: João Salavisa <undefined@users.noreply.github.com>

---------

Co-authored-by: Kandev Agent <agent@kandev.dev>
Co-authored-by: claude[bot] <41898282+claude[bot]@users.noreply.github.com>
Co-authored-by: João Salavisa <undefined@users.noreply.github.com>
2026-04-21 14:00:49 +01:00

126 lines
3.4 KiB
Go

package api
import (
"net/http"
"net/http/httptest"
"testing"
"github.com/gin-gonic/gin"
)
func init() {
gin.SetMode(gin.TestMode)
}
func setupRouter(token string, exemptPaths ...string) *gin.Engine {
r := gin.New()
r.Use(bearerTokenAuth(token, exemptPaths...))
r.GET("/health", func(c *gin.Context) { c.JSON(200, gin.H{"status": "ok"}) })
r.GET("/api/v1/status", func(c *gin.Context) { c.JSON(200, gin.H{"status": "running"}) })
r.GET("/api/v1/data", func(c *gin.Context) { c.JSON(200, gin.H{"data": "secret"}) })
return r
}
func TestBearerTokenAuth_EmptyToken_DisablesAuth(t *testing.T) {
r := setupRouter("")
w := httptest.NewRecorder()
req := httptest.NewRequest("GET", "/api/v1/status", nil)
r.ServeHTTP(w, req)
if w.Code != http.StatusOK {
t.Fatalf("expected 200, got %d", w.Code)
}
}
func TestBearerTokenAuth_ValidToken(t *testing.T) {
r := setupRouter("test-secret-token")
w := httptest.NewRecorder()
req := httptest.NewRequest("GET", "/api/v1/status", nil)
req.Header.Set("Authorization", "Bearer test-secret-token")
r.ServeHTTP(w, req)
if w.Code != http.StatusOK {
t.Fatalf("expected 200, got %d", w.Code)
}
}
func TestBearerTokenAuth_MissingToken(t *testing.T) {
r := setupRouter("test-secret-token")
w := httptest.NewRecorder()
req := httptest.NewRequest("GET", "/api/v1/status", nil)
r.ServeHTTP(w, req)
if w.Code != http.StatusUnauthorized {
t.Fatalf("expected 401, got %d", w.Code)
}
}
func TestBearerTokenAuth_InvalidToken(t *testing.T) {
r := setupRouter("test-secret-token")
w := httptest.NewRecorder()
req := httptest.NewRequest("GET", "/api/v1/status", nil)
req.Header.Set("Authorization", "Bearer wrong-token")
r.ServeHTTP(w, req)
if w.Code != http.StatusUnauthorized {
t.Fatalf("expected 401, got %d", w.Code)
}
}
func TestBearerTokenAuth_ExemptPath(t *testing.T) {
r := setupRouter("test-secret-token", "/health")
w := httptest.NewRecorder()
req := httptest.NewRequest("GET", "/health", nil)
r.ServeHTTP(w, req)
if w.Code != http.StatusOK {
t.Fatalf("expected 200, got %d (health should be exempt)", w.Code)
}
}
func TestBearerTokenAuth_NonExemptPathRequiresAuth(t *testing.T) {
r := setupRouter("test-secret-token", "/health")
w := httptest.NewRecorder()
req := httptest.NewRequest("GET", "/api/v1/data", nil)
r.ServeHTTP(w, req)
if w.Code != http.StatusUnauthorized {
t.Fatalf("expected 401, got %d", w.Code)
}
}
func TestBearerTokenAuth_QueryParamIgnored(t *testing.T) {
r := setupRouter("test-secret-token")
w := httptest.NewRecorder()
req := httptest.NewRequest("GET", "/api/v1/status?token=test-secret-token", nil)
r.ServeHTTP(w, req)
if w.Code != http.StatusUnauthorized {
t.Fatalf("expected 401 — query param tokens must be ignored, got %d", w.Code)
}
}
func TestBearerTokenAuth_MalformedAuthHeader(t *testing.T) {
r := setupRouter("test-secret-token")
w := httptest.NewRecorder()
req := httptest.NewRequest("GET", "/api/v1/status", nil)
req.Header.Set("Authorization", "Basic dXNlcjpwYXNz")
r.ServeHTTP(w, req)
if w.Code != http.StatusUnauthorized {
t.Fatalf("expected 401 for non-Bearer auth, got %d", w.Code)
}
}
func TestTokenEqual_ConstantTime(t *testing.T) {
if !tokenEqual("abc", "abc") {
t.Error("expected equal tokens to match")
}
if tokenEqual("abc", "xyz") {
t.Error("expected different tokens to not match")
}
if tokenEqual("abc", "ab") {
t.Error("expected different length tokens to not match")
}
}