dccff23cc0
* 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>
146 lines
4.1 KiB
Go
146 lines
4.1 KiB
Go
package lifecycle
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
"testing"
|
|
|
|
"github.com/kandev/kandev/internal/common/logger"
|
|
"github.com/kandev/kandev/internal/secrets"
|
|
)
|
|
|
|
// inMemorySecretStore implements secrets.SecretStore for testing.
|
|
type inMemorySecretStore struct {
|
|
store map[string]*secrets.SecretWithValue
|
|
err error
|
|
}
|
|
|
|
var _ secrets.SecretStore = (*inMemorySecretStore)(nil)
|
|
|
|
func newInMemorySecretStore() *inMemorySecretStore {
|
|
return &inMemorySecretStore{store: make(map[string]*secrets.SecretWithValue)}
|
|
}
|
|
|
|
func (s *inMemorySecretStore) Create(_ context.Context, secret *secrets.SecretWithValue) error {
|
|
if s.err != nil {
|
|
return s.err
|
|
}
|
|
if secret.ID == "" {
|
|
secret.ID = fmt.Sprintf("secret-%d", len(s.store)+1)
|
|
}
|
|
s.store[secret.ID] = secret
|
|
return nil
|
|
}
|
|
|
|
func (s *inMemorySecretStore) Get(_ context.Context, id string) (*secrets.Secret, error) {
|
|
if sw, ok := s.store[id]; ok {
|
|
return &sw.Secret, nil
|
|
}
|
|
return nil, fmt.Errorf("not found")
|
|
}
|
|
|
|
func (s *inMemorySecretStore) Reveal(_ context.Context, id string) (string, error) {
|
|
if sw, ok := s.store[id]; ok {
|
|
return sw.Value, nil
|
|
}
|
|
return "", fmt.Errorf("not found")
|
|
}
|
|
|
|
func (s *inMemorySecretStore) Update(_ context.Context, _ string, _ *secrets.UpdateSecretRequest) error {
|
|
return nil
|
|
}
|
|
func (s *inMemorySecretStore) Delete(_ context.Context, _ string) error { return nil }
|
|
func (s *inMemorySecretStore) List(_ context.Context) ([]*secrets.SecretListItem, error) {
|
|
return nil, nil
|
|
}
|
|
func (s *inMemorySecretStore) Close() error { return nil }
|
|
|
|
func TestPersistAuthToken(t *testing.T) {
|
|
log, _ := logger.NewLogger(logger.LoggingConfig{Level: "error", Format: "json"})
|
|
|
|
t.Run("stores token and sets metadata", func(t *testing.T) {
|
|
store := newInMemorySecretStore()
|
|
m := &Manager{logger: log, secretStore: store}
|
|
|
|
instance := &ExecutorInstance{
|
|
InstanceID: "exec-123456789012",
|
|
AuthToken: "handshake-token-abc",
|
|
}
|
|
execution := &AgentExecution{
|
|
Metadata: make(map[string]interface{}),
|
|
}
|
|
|
|
m.persistAuthToken(context.Background(), instance, execution)
|
|
|
|
// Verify secret was stored
|
|
if len(store.store) != 1 {
|
|
t.Fatalf("expected 1 secret, got %d", len(store.store))
|
|
}
|
|
|
|
// Verify metadata has the secret ID
|
|
secretID, ok := execution.Metadata[MetadataKeyAuthTokenSecret].(string)
|
|
if !ok || secretID == "" {
|
|
t.Fatalf("expected secret ID in metadata, got %v", execution.Metadata[MetadataKeyAuthTokenSecret])
|
|
}
|
|
|
|
// Verify we can retrieve the token
|
|
revealed, err := store.Reveal(context.Background(), secretID)
|
|
if err != nil {
|
|
t.Fatalf("failed to reveal: %v", err)
|
|
}
|
|
if revealed != "handshake-token-abc" {
|
|
t.Fatalf("expected handshake-token-abc, got %q", revealed)
|
|
}
|
|
})
|
|
|
|
t.Run("no-op when auth token is empty", func(t *testing.T) {
|
|
store := newInMemorySecretStore()
|
|
m := &Manager{logger: log, secretStore: store}
|
|
|
|
instance := &ExecutorInstance{InstanceID: "exec-123456789012"}
|
|
execution := &AgentExecution{Metadata: make(map[string]interface{})}
|
|
|
|
m.persistAuthToken(context.Background(), instance, execution)
|
|
|
|
if len(store.store) != 0 {
|
|
t.Fatal("expected no secrets stored")
|
|
}
|
|
if _, ok := execution.Metadata[MetadataKeyAuthTokenSecret]; ok {
|
|
t.Fatal("expected no metadata key")
|
|
}
|
|
})
|
|
|
|
t.Run("no-op when secret store is nil", func(t *testing.T) {
|
|
m := &Manager{logger: log}
|
|
|
|
instance := &ExecutorInstance{
|
|
InstanceID: "exec-123456789012",
|
|
AuthToken: "some-token",
|
|
}
|
|
execution := &AgentExecution{Metadata: make(map[string]interface{})}
|
|
|
|
// Should not panic
|
|
m.persistAuthToken(context.Background(), instance, execution)
|
|
})
|
|
|
|
t.Run("handles nil metadata in execution", func(t *testing.T) {
|
|
store := newInMemorySecretStore()
|
|
m := &Manager{logger: log, secretStore: store}
|
|
|
|
instance := &ExecutorInstance{
|
|
InstanceID: "exec-123456789012",
|
|
AuthToken: "token-xyz",
|
|
}
|
|
execution := &AgentExecution{}
|
|
|
|
m.persistAuthToken(context.Background(), instance, execution)
|
|
|
|
if execution.Metadata == nil {
|
|
t.Fatal("expected metadata to be initialized")
|
|
}
|
|
if _, ok := execution.Metadata[MetadataKeyAuthTokenSecret]; !ok {
|
|
t.Fatal("expected secret ID in metadata")
|
|
}
|
|
})
|
|
}
|