Same agent Smaller bill. The tools and infrastructure to get more work from your AI. Fewer tokens. Less compute. Lower cost.
TypeScript agent-harnessagent-harness-engineeringai-engineeringai-observabilityamd-gpuclaude-codeclickhousecodexcoding-agentcoding-agentscursorgenaigpu-monitoringllm-observabilityllmopsnvidia-smiobservabilityopen-sourceopenaiopentelemetry
fix: auth persistent login, fleet hub persistent agent instance with custom config (#941)
Aman Agarwaleee1e904b3a1
diff --git a/docker-compose.yml b/docker-compose.ymlindex ad7fdec4..239607dd 100644--- a/docker-compose.yml+++ b/docker-compose.yml@@ -54,7 +54,6 @@ services:volumes:- openlit-data:/app/client/data- ./assets/otel-collector-config.yaml:/etc/otel/otel-collector-config.yaml- - ./assets/supervisor-dynamic.yaml:/etc/otel/supervisor-dynamic.yamlrestart: alwaysvolumes:diff --git a/src/client/package-lock.json b/src/client/package-lock.jsonindex c9d31b3f..d463c7f3 100644--- a/src/client/package-lock.json+++ b/src/client/package-lock.json@@ -1,12 +1,12 @@{"name": "openlit",- "version": "1.15.0",+ "version": "1.15.1","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "openlit",- "version": "1.15.0",+ "version": "1.15.1","dependencies": {"@anthropic-ai/sdk": "^0.21.1","@clickhouse/client": "^1.1.0",diff --git a/src/client/package.json b/src/client/package.jsonindex b86adf02..1767f8a6 100644--- a/src/client/package.json+++ b/src/client/package.json@@ -1,6 +1,6 @@{"name": "openlit",- "version": "1.15.0",+ "version": "1.15.1","private": true,"scripts": {"dev": "next dev",diff --git a/src/client/scripts/entrypoint.sh b/src/client/scripts/entrypoint.shindex eff33688..b38e8b51 100644--- a/src/client/scripts/entrypoint.sh+++ b/src/client/scripts/entrypoint.sh@@ -1,11 +1,30 @@#!/bin/bashset -e-# Generate and set NextAuth.js secret as an environment variable-export NEXTAUTH_SECRET=$(openssl rand -base64 32)+# Generate and persist NextAuth.js secret to ensure session persistence across restarts+NEXTAUTH_SECRET_FILE="/app/client/data/.nextauth_secret"++if [ -f "$NEXTAUTH_SECRET_FILE" ]; then+ # Load existing secret from persistent volume+ export NEXTAUTH_SECRET=$(cat "$NEXTAUTH_SECRET_FILE")+ echo "✅ Loaded existing NextAuth secret from persistent storage"+else+ # Generate new secret and save it to persistent volume+ export NEXTAUTH_SECRET=$(openssl rand -base64 32)+ echo "$NEXTAUTH_SECRET" > "$NEXTAUTH_SECRET_FILE"+ chmod 600 "$NEXTAUTH_SECRET_FILE"+ echo "✅ Generated and saved new NextAuth secret to persistent storage"+fi# Set NextAuth.js environment variables-echo "NEXTAUTH_SECRET=$NEXTAUTH_SECRET" >> /etc/environment+# remove any existing NEXTAUTH_SECRET line, then append the current value+if [ -w /etc/environment ]; then+ sed -i '/^NEXTAUTH_SECRET=/d' /etc/environment+ echo "NEXTAUTH_SECRET=$NEXTAUTH_SECRET" >> /etc/environment+else+ echo "WARNING: /etc/environment is not writable; NEXTAUTH_SECRET will not be persisted there." >&2+fi+echo "NEXTAUTH_URL=http://localhost:${DOCKER_PORT:-3000}" >> /etc/environmentecho "SQLITE_DATABASE_URL=${SQLITE_DATABASE_URL:-file:../data/data.db}" >> /etc/environmentecho "PATH=./node_modules/.bin:$PATH" >> /etc/environment@@ -58,15 +77,18 @@ fiecho "Configuring OpAMP supervisor for $OPAMP_ENVIRONMENT environment..."cd /app/opamp+# Use a runtime config location to avoid overwriting mounted files+SUPERVISOR_CONFIG_PATH="/app/opamp/supervisor-runtime.yaml"+# Create supervisor configuration dynamically-cat > /etc/otel/supervisor-dynamic.yaml << EOF+cat > "$SUPERVISOR_CONFIG_PATH" << EOFserver:endpoint: wss://localhost:4320/v1/opamptls:EOFif [[ "$OPAMP_ENVIRONMENT" == "production" ]]; then- cat >> /etc/otel/supervisor-dynamic.yaml << EOF+ cat >> "$SUPERVISOR_CONFIG_PATH" << EOFinsecure_skip_verify: falseca_file: /app/opamp/certs/cert/ca.cert.pemcert_file: /app/opamp/certs/client/client.cert.pem@@ -74,17 +96,17 @@ if [[ "$OPAMP_ENVIRONMENT" == "production" ]]; thenEOFecho " Production mode: Using CA certificate verification with client certificates"else- cat >> /etc/otel/supervisor-dynamic.yaml << EOF+ cat >> "$SUPERVISOR_CONFIG_PATH" << EOFinsecure_skip_verify: trueEOFecho " Development mode: Skipping certificate verification"fi-cat >> /etc/otel/supervisor-dynamic.yaml << EOF+cat >> "$SUPERVISOR_CONFIG_PATH" << EOFagent:executable: /app/opamp/otelcontribcol- config_files:+ config_files:- /etc/otel/otel-collector-config.yamlcapabilities:@@ -97,10 +119,10 @@ capabilities:reports_remote_config: truestorage:- directory: ./storage+ directory: /app/client/data/supervisor-storageEOF-echo "✅ Supervisor configuration generated"+echo "✅ Supervisor configuration generated at $SUPERVISOR_CONFIG_PATH"# Starting OpAMP Serverecho "Starting OpAMP Server..."@@ -112,7 +134,7 @@ sleep 2# Starting Supervisor for the OTEL Collectorecho "Starting OpAMP Supervisor..."-/app/opamp/opampsupervisor --config=/etc/otel/supervisor-dynamic.yaml &+/app/opamp/opampsupervisor --config="$SUPERVISOR_CONFIG_PATH" &SUPERVISOR_PID=$!diff --git a/src/client/src/app/(playground)/fleet-hub/[id]/agent.tsx b/src/client/src/app/(playground)/fleet-hub/[id]/agent.tsxindex b2c8888c..f3d34071 100644--- a/src/client/src/app/(playground)/fleet-hub/[id]/agent.tsx+++ b/src/client/src/app/(playground)/fleet-hub/[id]/agent.tsx@@ -17,6 +17,7 @@ import { getAttributeValue } from "@/helpers/client/fleet-hub"import { usePageHeader } from "@/selectors/page"import { usePostHog } from "posthog-js/react"import { CLIENT_EVENTS } from "@/constants/events"+import { toast } from "sonner"interface AgentDetailProps {agent: Agent,@@ -105,7 +106,7 @@ export default function AgentDetail({ agent, fetchAgentInfo }: AgentDetailProps)))}</div>- <h4 className="font-semibold text-sm">Component Health Status</h4>+ {Object.keys(agent.Status.health.component_health_map || {}).length > 0 ? <h4 className="font-semibold text-sm">Component Health Status</h4> : null}<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">{Object.entries(agent.Status.health.component_health_map || {}).map(([component, health]) => (<div key={component} className={`p-4 rounded-lg border ${health.healthy ? "bg-green-500/10 border-green-500/20" : "bg-red-500/10 border-red-500/20"}`}>@@ -135,13 +136,24 @@ function ConfigDetails({ agent, fetchAgentInfo }: { agent: Agent, fetchAgentInfo};const onSave = useCallback(() => {+ const isClearing = yamlInput.trim() === "";+fireRequest({requestType: "POST",url: `/api/fleet-hub/${agent.InstanceIdStr}/config`,body: jsonStringify({config: yamlInput,}),- successCb: (resp) => {+ successCb: () => {+ if (isClearing) {+ toast.success("Configuration cleared successfully", {+ description: "The custom collector configuration has been removed. The collector will use its default configuration."+ });+ } else {+ toast.success("Configuration saved successfully", {+ description: "The collector configuration has been updated and applied."+ });+ }fetchAgentInfo();posthog?.capture(CLIENT_EVENTS.FLEET_HUB_AGENT_CONFIG_SAVED, {agentId: agent.InstanceIdStr,@@ -149,9 +161,23 @@ function ConfigDetails({ agent, fetchAgentInfo }: { agent: Agent, fetchAgentInfo},failureCb: (resp) => {consoleLog(resp);+ // Extract error message from response+ let errorMessage = "Failed to save configuration";+ try {+ const errorData = typeof resp === 'string' ? JSON.parse(resp) : resp;+ errorMessage = errorData.error || errorMessage;+ } catch (e) {+ // If parsing fails, use the raw response as error message+ errorMessage = typeof resp === 'string' ? resp : errorMessage;+ }++ toast.error("Configuration validation failed", {+ description: errorMessage,+ duration: 5000+ });}})- }, [yamlInput, agent.InstanceIdStr]);+ }, [yamlInput, agent.InstanceIdStr, fetchAgentInfo, posthog]);return (<div className="grid grid-cols-2 gap-3 grow text-stone-700 dark:text-stone-300">diff --git a/src/client/src/app/api/fleet-hub/[id]/config/route.ts b/src/client/src/app/api/fleet-hub/[id]/config/route.tsindex 18d0bede..5a45b551 100644--- a/src/client/src/app/api/fleet-hub/[id]/config/route.ts+++ b/src/client/src/app/api/fleet-hub/[id]/config/route.ts@@ -4,5 +4,13 @@ export async function POST(request: Request, context: any) {const { id } = context.params;const { config } = await request.json();const res = await updateAgentConfig(id, config);++ // Check if there was an error from the OpAMP server+ if (res.err) {+ return Response.json(res.err,+ { status: res.status || 500 }+ );+ }+return Response.json(res);}\ No newline at end of filediff --git a/src/client/src/lib/platform/fleet-hub/index.ts b/src/client/src/lib/platform/fleet-hub/index.tsindex 4d206534..8f6fe654 100644--- a/src/client/src/lib/platform/fleet-hub/index.ts+++ b/src/client/src/lib/platform/fleet-hub/index.ts@@ -61,7 +61,17 @@ export async function updateAgentConfig(id: string, config: string) {if (err) {consoleLog(err);return {- err+ err: err.message || "Failed to save configuration",+ status: 500+ };+ }++ // Check for HTTP error responses+ if (!res.ok) {+ const errorText = await res.text();+ return {+ err: errorText || `HTTP ${res.status}: ${res.statusText}`,+ status: res.status};}diff --git a/src/client/src/middleware.ts b/src/client/src/middleware.tsindex e00baf17..f2edab78 100644--- a/src/client/src/middleware.ts+++ b/src/client/src/middleware.ts@@ -25,5 +25,6 @@ export const config = {"/home","/dashboards/:path*","/d/:path*",+ "/fleet-hub"],};diff --git a/src/client/src/utils/hooks/useFetchWrapper.ts b/src/client/src/utils/hooks/useFetchWrapper.tsindex 4b95c4be..38676333 100644--- a/src/client/src/utils/hooks/useFetchWrapper.ts+++ b/src/client/src/utils/hooks/useFetchWrapper.ts@@ -49,8 +49,13 @@ export default function useFetchWrapper<T>() {setData(finalResponse);if (typeof successCb === "function") successCb(finalResponse);}- } catch (error) {- error = error;+ } catch (errorResp) {+ if (typeof errorResp === "string") {+ error = errorResp;+ } else if (typeof errorResp === "object" && errorResp !== null){+ error = (errorResp as any).message || (errorResp as any).error;+ }+const updatedError = (error as any).toString().replaceAll("Error:", "");setError(updatedError);setData(null);diff --git a/src/dev-docker-compose.yml b/src/dev-docker-compose.ymlindex 28d4cf59..68b2c67b 100644--- a/src/dev-docker-compose.yml+++ b/src/dev-docker-compose.yml@@ -60,7 +60,6 @@ services:- clickhousevolumes:- openlit-data:/app/client/data- - ../assets/supervisor-dynamic.yaml:/etc/otel/supervisor-dynamic.yaml- ../assets/otel-collector-config.yaml:/etc/otel/otel-collector-config.yamlrestart: alwaysdiff --git a/src/opamp-server/constants/certificatespath.go b/src/opamp-server/constants/certificatespath.goindex 4bac5a81..ce9154bf 100644--- a/src/opamp-server/constants/certificatespath.go+++ b/src/opamp-server/constants/certificatespath.go@@ -25,6 +25,9 @@ var (ClientCSRPath = filepath.Join(CertificatesDirectory, "client", "client.csr"))+// Agent configuration storage directory+const ConfigDirectory = "/app/client/data/configs"+// getEnvOrDefault returns environment variable value or default if not setfunc getEnvOrDefault(key, defaultValue string) string {if value := os.Getenv(key); value != "" {diff --git a/src/opamp-server/data/agents.go b/src/opamp-server/data/agents.goindex 8ee9139b..89d37c5c 100644--- a/src/opamp-server/data/agents.go+++ b/src/opamp-server/data/agents.go@@ -4,11 +4,17 @@ import ("crypto/sha256""io""log"+ "os"+ "path/filepath""sync"+ "github.com/google/uuid""github.com/open-telemetry/opamp-go/protobufs""github.com/open-telemetry/opamp-go/protobufshelpers""github.com/open-telemetry/opamp-go/server/types"+ "gopkg.in/yaml.v3"++ "opamp-server/constants")type Agents struct {@@ -82,6 +88,9 @@ func (agents *Agents) FindOrCreateAgent(agentId InstanceId, conn types.Connectioagent = NewAgent(agentId, conn)agents.agentsById[agentId] = agent+ // Load persisted configuration if available+ agents.loadPersistedConfig(agent)+// Ensure the Agent's instance id is associated with the connection.if agents.connections[conn] == nil {agents.connections[conn] = map[InstanceId]bool{}@@ -92,6 +101,55 @@ func (agents *Agents) FindOrCreateAgent(agentId InstanceId, conn types.Connectioreturn agent}+// loadPersistedConfig loads a persisted configuration for an agent if it exists+func (agents *Agents) loadPersistedConfig(agent *Agent) {+ agentIDStr := uuid.UUID(agent.InstanceId).String()+ configPath := filepath.Join(constants.ConfigDirectory, agentIDStr+".yaml")++ // Check if persisted config exists+ if _, err := os.Stat(configPath); os.IsNotExist(err) {+ return+ }++ // Read the persisted configuration+ configData, err := os.ReadFile(configPath)+ if err != nil {+ logger.Printf("Failed to read persisted config for agent %s: %v", agentIDStr, err)+ return+ }++ // Validate that the persisted config is valid YAML+ var yamlTest interface{}+ if err := yaml.Unmarshal(configData, &yamlTest); err != nil {+ logger.Printf("Persisted config for agent %s is invalid YAML, skipping: %v", agentIDStr, err)+ // Delete the corrupted config file+ if removeErr := os.Remove(configPath); removeErr != nil {+ logger.Printf("Failed to remove corrupted config file %s: %v", configPath, removeErr)+ } else {+ logger.Printf("Removed corrupted config file: %s", configPath)+ }+ return+ }++ // Additional validation: ensure it's a YAML map/object, not a scalar value+ if _, isMap := yamlTest.(map[string]interface{}); !isMap {+ logger.Printf("Persisted config for agent %s must be a YAML object, not a scalar value. Skipping.", agentIDStr)+ // Delete the invalid config file+ if removeErr := os.Remove(configPath); removeErr != nil {+ logger.Printf("Failed to remove invalid config file %s: %v", configPath, removeErr)+ } else {+ logger.Printf("Removed invalid config file: %s", configPath)+ }+ return+ }++ // Set the custom config on the agent+ agent.CustomInstanceConfig = string(configData)+ agent.calcRemoteConfig()++ logger.Printf("Loaded persisted configuration for agent %s from %s", agentIDStr, configPath)+}+func (agents *Agents) GetAgentReadonlyClone(agentId InstanceId) *Agent {agent := agents.FindAgent(agentId)if agent == nil {diff --git a/src/opamp-server/go.mod b/src/opamp-server/go.modindex b0983fb3..57ce81d6 100644--- a/src/opamp-server/go.mod+++ b/src/opamp-server/go.mod@@ -8,6 +8,7 @@ require (github.com/open-telemetry/opamp-go v0.21.0go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.62.0google.golang.org/protobuf v1.36.7+ gopkg.in/yaml.v3 v3.0.1)require (diff --git a/src/opamp-server/go.sum b/src/opamp-server/go.sumindex f8cbcb85..9076a0e7 100644--- a/src/opamp-server/go.sum+++ b/src/opamp-server/go.sum@@ -13,6 +13,10 @@ github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=github.com/gorilla/websocket v1.5.3 h1:saDtZ6Pbx/0u+bgYQ3q96pZgCzfhKXGPqt7kZ72aNNg=github.com/gorilla/websocket v1.5.3/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=+github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=+github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=+github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=+github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=github.com/oklog/ulid/v2 v2.1.1 h1:suPZ4ARWLOJLegGFiZZ1dFAkqzhMjL3J1TzI+5wHz8s=github.com/oklog/ulid/v2 v2.1.1/go.mod h1:rcEKHmBBKfef9DhnvX7y1HZBYxjXb0cP5ExxNsTT1QQ=github.com/open-telemetry/opamp-go v0.21.0 h1:G2e0G4bi2Il3Z4hHqbXUA05m5jajdhQLxq2dBARvT5U=@@ -20,6 +24,8 @@ github.com/open-telemetry/opamp-go v0.21.0/go.mod h1:d8/1ubFfy2QkTodIC9rd+9A3OCCgithub.com/pborman/getopt v0.0.0-20170112200414-7148bc3a4c30/go.mod h1:85jBQOZwpVEaDAr341tbn15RS4fCAsIst0qp7i8ex1o=github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=+github.com/rogpeppe/go-internal v1.13.1 h1:KvO1DLK/DRN07sQ1LQKScxyZJuNnedQ5/wKSR38lUII=+github.com/rogpeppe/go-internal v1.13.1/go.mod h1:uMEvuHeurkdAXX61udpOXGD/AzZDWNMNyH2VO9fmH0o=github.com/stretchr/testify v1.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOfJA=github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=go.opentelemetry.io/auto/sdk v1.1.0 h1:cH53jehLUN6UFLY71z+NDOiNJqDdPRaXzTel0sJySYA=@@ -40,5 +46,8 @@ golang.org/x/sys v0.33.0 h1:q3i8TbbEz+JRD9ywIRlyRAQbM0qF7hu24q3teo2hbuw=golang.org/x/sys v0.33.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k=google.golang.org/protobuf v1.36.7 h1:IgrO7UwFQGJdRNXH/sQux4R1Dj1WAKcLElzeeRaXV2A=google.golang.org/protobuf v1.36.7/go.mod h1:jduwjTPXsFjZGTmRluh+L6NjiWu7pchiJ2/5YcXBHnY=+gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=+gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=+gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=diff --git a/src/opamp-server/opamp-server b/src/opamp-server/opamp-serverindex 48e84ebd..dbadbea0 100755Binary files a/src/opamp-server/opamp-server and b/src/opamp-server/opamp-server differdiff --git a/src/opamp-server/server/ui.go b/src/opamp-server/server/ui.goindex 240db64f..63f2b7a2 100644--- a/src/opamp-server/server/ui.go+++ b/src/opamp-server/server/ui.go@@ -5,9 +5,13 @@ import ("encoding/json""net/http""os"+ "path/filepath"+ "regexp""sync""time"+ "gopkg.in/yaml.v3"+"opamp-server/certman""opamp-server/constants""opamp-server/data"@@ -26,6 +30,8 @@ var (}return string(p)})+ // uuidRegex validates UUID format (8-4-4-4-12 hexadecimal pattern)+ uuidRegex = regexp.MustCompile(`^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$`))func (srv *Server) setupRoutes(mux *http.ServeMux) {@@ -34,6 +40,7 @@ func (srv *Server) setupRoutes(mux *http.ServeMux) {mux.HandleFunc("/api/agent/config", srv.handleSaveConfig)mux.HandleFunc("/api/agent/connection", srv.handleConnectionSettings)mux.HandleFunc("/api/agent/certificate", srv.handleRotateCertificate)+ // TODO// mux.HandleFunc("/api/capabilities", srv.handleCapabilities)}@@ -70,6 +77,13 @@ func (srv *Server) handleGetAgent(w http.ResponseWriter, r *http.Request) {return}+ // Validate UUID format using regex to prevent path traversal+ if !uuidRegex.MatchString(instanceID) {+ srv.logger.Printf("Instance ID failed regex validation: %s", instanceID)+ http.Error(w, "Invalid instance ID format", http.StatusBadRequest)+ return+ }+uid, err := uuid.Parse(instanceID)if err != nil {http.Error(w, "Invalid instance ID", http.StatusBadRequest)@@ -102,6 +116,13 @@ func (srv *Server) handleSaveConfig(w http.ResponseWriter, r *http.Request) {return}+ // Validate UUID format using regex to prevent path traversal+ if !uuidRegex.MatchString(request.InstanceID) {+ srv.logger.Printf("Instance ID failed regex validation: %s", request.InstanceID)+ http.Error(w, "Invalid instance ID format", http.StatusBadRequest)+ return+ }+uid, err := uuid.Parse(request.InstanceID)if err != nil {http.Error(w, "Invalid instance ID", http.StatusBadRequest)@@ -116,12 +137,79 @@ func (srv *Server) handleSaveConfig(w http.ResponseWriter, r *http.Request) {}configStr := request.Config++ // Handle empty config - this clears the custom configuration+ if configStr == "" {+ // Delete the persisted config file if it exists+ configPath := filepath.Join(constants.ConfigDirectory, request.InstanceID+".yaml")+ if err := os.Remove(configPath); err != nil && !os.IsNotExist(err) {+ srv.logger.Printf("Failed to delete config for agent %s: %v", request.InstanceID, err)+ http.Error(w, "Failed to clear configuration", http.StatusInternalServerError)+ return+ }++ // Send empty config to agent to clear remote configuration+ config := &protobufs.AgentConfigMap{+ ConfigMap: map[string]*protobufs.AgentConfigFile{+ "": {Body: []byte("")},+ },+ }++ srv.logger.Printf("Cleared configuration for agent %s", request.InstanceID)++ notifyNextStatusUpdate := make(chan struct{}, 1)+ data.AllAgents.SetCustomConfigForAgent(instanceId, config, notifyNextStatusUpdate)++ // Wait for up to 5 seconds for a Status update+ timer := time.NewTicker(time.Second * 5)+ defer timer.Stop()++ select {+ case <-notifyNextStatusUpdate:+ w.WriteHeader(http.StatusOK)+ case <-timer.C:+ w.WriteHeader(http.StatusRequestTimeout)+ }+ return+ }++ // Validate that the config is valid YAML+ var yamlTest interface{}+ if err := yaml.Unmarshal([]byte(configStr), &yamlTest); err != nil {+ srv.logger.Printf("Invalid YAML configuration for agent %s: %v", request.InstanceID, err)+ http.Error(w, "Invalid YAML configuration: "+err.Error(), http.StatusBadRequest)+ return+ }++ // Additional validation: ensure it's a YAML map/object, not a scalar value+ if _, isMap := yamlTest.(map[string]interface{}); !isMap {+ srv.logger.Printf("Configuration must be a YAML object/map for agent %s", request.InstanceID)+ http.Error(w, "Configuration must be a valid YAML object with key-value pairs", http.StatusBadRequest)+ return+ }+config := &protobufs.AgentConfigMap{ConfigMap: map[string]*protobufs.AgentConfigFile{"": {Body: []byte(configStr)},},}+ // Persist configuration to disk+ if err := os.MkdirAll(constants.ConfigDirectory, 0755); err != nil {+ srv.logger.Printf("Failed to create config directory: %v", err)+ http.Error(w, "Failed to save configuration", http.StatusInternalServerError)+ return+ }++ configPath := filepath.Join(constants.ConfigDirectory, request.InstanceID+".yaml")+ if err := os.WriteFile(configPath, []byte(configStr), 0644); err != nil {+ srv.logger.Printf("Failed to persist config for agent %s: %v", request.InstanceID, err)+ http.Error(w, "Failed to save configuration", http.StatusInternalServerError)+ return+ }++ srv.logger.Printf("Persisted configuration for agent %s to %s", request.InstanceID, configPath)+notifyNextStatusUpdate := make(chan struct{}, 1)data.AllAgents.SetCustomConfigForAgent(instanceId, config, notifyNextStatusUpdate)@@ -153,6 +241,13 @@ func (srv *Server) handleRotateCertificate(w http.ResponseWriter, r *http.Requesreturn}+ // Validate UUID format using regex to prevent path traversal+ if !uuidRegex.MatchString(request.InstanceID) {+ srv.logger.Printf("Instance ID failed regex validation: %s", request.InstanceID)+ http.Error(w, "Invalid instance ID format", http.StatusBadRequest)+ return+ }+uid, err := uuid.Parse(request.InstanceID)if err != nil {http.Error(w, "Invalid instance ID", http.StatusBadRequest)@@ -217,6 +312,13 @@ func (srv *Server) handleConnectionSettings(w http.ResponseWriter, r *http.Requereturn}+ // Validate UUID format using regex to prevent path traversal+ if !uuidRegex.MatchString(request.InstanceID) {+ srv.logger.Printf("Instance ID failed regex validation: %s", request.InstanceID)+ http.Error(w, "Invalid instance ID format", http.StatusBadRequest)+ return+ }+uid, err := uuid.Parse(request.InstanceID)if err != nil {http.Error(w, "Invalid instance ID", http.StatusBadRequest)