{"id":"56786654b9639783","repo":"gofiber/fiber","slug":"csrf-failed-to-store-key-q-w","errorCode":null,"errorMessage":"csrf: failed to store key %q: %w","messagePattern":"csrf: failed to store key %q: %w","errorType":"http","errorClass":null,"httpStatus":null,"severity":"error","filePath":"middleware/csrf/storage_manager.go","lineNumber":60,"sourceCode":"\t\treturn raw, nil\n\t}\n\n\tif value := m.memory.Get(key); value != nil {\n\t\traw, ok := value.([]byte)\n\t\tif !ok {\n\t\t\treturn nil, fmt.Errorf(\"csrf: unexpected value type %T in storage\", value)\n\t\t}\n\t\treturn raw, nil\n\t}\n\n\treturn nil, nil\n}\n\n// set data to storage or memory\nfunc (m *storageManager) setRaw(ctx context.Context, key string, raw []byte, exp time.Duration) error {\n\tif m.storage != nil {\n\t\tif err := m.storage.SetWithContext(ctx, key, raw, exp); err != nil {\n\t\t\treturn fmt.Errorf(\"csrf: failed to store key %q: %w\", m.logKey(key), err)\n\t\t}\n\t\treturn nil\n\t}\n\n\tm.memory.Set(key, raw, exp)\n\treturn nil\n}\n\n// delete data from storage or memory\nfunc (m *storageManager) delRaw(ctx context.Context, key string) error {\n\tif m.storage != nil {\n\t\tif err := m.storage.DeleteWithContext(ctx, key); err != nil {\n\t\t\treturn fmt.Errorf(\"csrf: failed to delete key %q: %w\", m.logKey(key), err)\n\t\t}\n\t\treturn nil\n\t}\n\n\tm.memory.Delete(key)","sourceCodeStart":42,"sourceCodeEnd":78,"githubUrl":"https://github.com/gofiber/fiber/blob/9a4c7e57fe0b080a04235d28a4b0d2b4b353d58c/middleware/csrf/storage_manager.go#L42-L78","documentation":"Thrown at middleware/csrf/storage_manager.go:60 by storageManager.setRaw when m.storage.SetWithContext fails. This is the inner layer wrapped by error 151 (csrf: failed to store token in storage); the wrapped %w is the raw driver write error.","triggerScenarios":"CSRF token create/extend calls Storage.SetWithContext and the backend rejects the write: OOM, disk full, connection lost, ctx cancelled, auth expired.","commonSituations":"Redis maxmemory-policy returning errors; persistent backend out of disk; storage AUTH expired mid-run; client disconnect causing ctx cancellation during SET; network blip.","solutions":["Resolve the backend write refusal identified in the wrapped error (capacity, auth, timeout).","Ensure storage capacity matches the IdleTimeout-bounded working set of CSRF tokens.","Tune the storage write timeout below the per-request deadline to avoid ctx-cancellation errors.","Provide cfg.ErrorHandler that returns 503 + Retry-After so clients retry cleanly.","Run with cfg.Session to leverage the session store's resilience for token persistence."],"exampleFix":"// before\napp.Use(csrf.New(csrf.Config{ Storage: redis.New() }))\n\n// after: explicit timeout + clear failure mode\nstore := redis.New(redis.Config{\n    URL:          os.Getenv(\"CSRF_REDIS_URL\"),\n    WriteTimeout: 500 * time.Millisecond,\n})\napp.Use(csrf.New(csrf.Config{\n    Storage: store,\n    ErrorHandler: func(c fiber.Ctx, err error) error {\n        if strings.Contains(err.Error(), \"failed to store key\") {\n            c.Set(fiber.HeaderRetryAfter, \"5\")\n            return c.Status(fiber.StatusServiceUnavailable).\n                SendString(\"token store busy; retry shortly\")\n        }\n        return c.Status(fiber.StatusForbidden).SendString(err.Error())\n    },\n}))","handlingStrategy":"try-catch","validationCode":"// At boot, confirm the CSRF store accepts writes with the dummy payload size.\nctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)\ndefer cancel()\nif err := store.SetWithContext(ctx, \"__csrf_probe__\", []byte(\"+\"), time.Minute); err != nil {\n    log.Fatalf(\"csrf storage write probe failed: %v\", err)\n}","typeGuard":null,"tryCatchPattern":"if err := m.storage.SetWithContext(ctx, key, raw, exp); err != nil {\n    return fmt.Errorf(\"csrf: failed to store key %q: %w\", m.logKey(key), err)\n}\n// Caller (csrf.New) wraps via cfg.ErrorHandler into a 503 + Retry-After.","preventionTips":["Probe write capability at startup.","Size storage for the IdleTimeout-bounded token set; monitor capacity.","Set the storage write timeout below the request deadline.","Return 503 + Retry-After to clients on transient write failures."],"tags":["csrf","storage","network","security","fiber"],"analyzedSha":"9a4c7e57fe0b080a04235d28a4b0d2b4b353d58c","analyzedAt":"2026-08-04T21:44:03.395Z","schemaVersion":2}