### Fetch Agent Usage Guide Source: https://securitycards.rewarelabs.com/integration Command to retrieve the agent usage guide directly from the command line. ```bash curl https://securitycards.rewarelabs.com/agent-usage.md ``` -------------------------------- ### Start vLLM API Server with Authentication Source: https://securitycards.rewarelabs.com/libraries/python/vllm/v0-26-0 Configure the VLLM_API_KEY environment variable to enforce authentication on the OpenAI-compatible API server. ```bash export VLLM_API_KEY="secret-api-key-token" python -m vllm.entrypoints.openai.api_server --model facebook/opt-125m ``` -------------------------------- ### Register Custom HTTP Methods Source: https://securitycards.rewarelabs.com/libraries/go/chi/v5-3-1 Invoke chi.RegisterMethod during application initialization before router setup to prevent data races. ```go func main() { chi.RegisterMethod("PURGE") r := chi.NewRouter() r.MethodFunc("PURGE", "/cache", handlePurge) } ``` -------------------------------- ### Install python-multipart dependency Source: https://securitycards.rewarelabs.com/libraries/python/fastapi/0-139-2 Required command to enable multipart form and file data parsing in FastAPI. ```bash pip install python-multipart ``` -------------------------------- ### Install Security Cards skill Source: https://securitycards.rewarelabs.com/agent-usage.md Installs the securitycards skill globally to enable agent-assisted security workflows. ```bash npx skills add Reware-Labs/securitycards --skill securitycards -g ``` -------------------------------- ### Define GenerateRequest with parameters Source: https://securitycards.rewarelabs.com/libraries/go/ollama/v0-32-5 Example of initializing a GenerateRequest struct with specific model parameters. ```go req := api.GenerateRequest{ Model: "llama3", Prompt: "Write a summary", TopLogprobs: 5, } ``` -------------------------------- ### Configure fetchRequestHandler with GET and POST methods Source: https://securitycards.rewarelabs.com/libraries/typescript/trpc/v11-18-0 Align the endpoint configuration with the route path and export both GET and POST handlers to ensure proper request handling. ```typescript import { fetchRequestHandler } from '@trpc/server/adapters/fetch'; import { appRouter } from '@/server/routers/_app'; const handler = (req: Request) => fetchRequestHandler({ endpoint: '/api/trpc', req, router: appRouter, createContext: () => ({}), }); export { handler as GET, handler as POST }; ``` -------------------------------- ### Secure Configuration and Authentication Setup Source: https://securitycards.rewarelabs.com/libraries/csharp/asp-net/v10-0-10 Enforces HTTPS metadata requirements for JWT tokens and prevents insecure environment-based overrides for forwarded headers. ```csharp var builder = WebApplication.CreateBuilder(args); // 1. Identity tokens – always fetch metadata over HTTPS. builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) .AddJwtBearer(o => { o.Authority = builder.Configuration["Auth:Authority"]; o.RequireHttpsMetadata = true; // don’t allow dev-only overrides in prod }); // 2. Edge server – refuse permissive proxy settings from env/config. if (builder.Environment.IsProduction() && string.Equals(Environment.GetEnvironmentVariable("ASPNETCORE_FORWARDEDHEADERS_ENABLED"), "true", StringComparison.OrdinalIgnoreCase)) { throw new InvalidOperationException( "ForwardedHeaders must be enabled explicitly in code with KnownProxies; " + "the ASPNETCORE_FORWARDEDHEADERS_ENABLED environment variable is not allowed."); } var app = builder.Build(); app.Run(); ``` -------------------------------- ### Initialize HTTPX Client with TLS Settings Source: https://securitycards.rewarelabs.com/libraries/python/httpx/0-28-1 Demonstrates configuring TLS verification during client instantiation, including the use of default settings and custom SSL contexts. ```python import httpx import ssl client = httpx.Client(verify=True) response = client.get('https://example.com') custom_ctx = ssl.create_default_context() custom_client = httpx.Client(verify=custom_ctx) ``` -------------------------------- ### Configure API Key Authentication for SGLang Server Source: https://securitycards.rewarelabs.com/libraries/python/sglang/v0-5-16 Demonstrates launching a server with an API key and initializing an OpenAI client with the corresponding credentials. ```python process = popen_launch_server(model_name, base_url, api_key="sk-secure-key-123") client = openai.Client(api_key="sk-secure-key-123", base_url="http://localhost:30000/v1") ``` -------------------------------- ### Load Configuration from Trusted OS Directories Source: https://securitycards.rewarelabs.com/libraries/python/click/8-4-2 Use click.get_app_dir to locate standard per-user configuration directories instead of relative paths. ```python import os import click import configparser APP_NAME = 'my_app' def load_config(): config_dir = click.get_app_dir(APP_NAME) config_path = os.path.join(config_dir, 'config.ini') parser = configparser.ConfigParser() if os.path.exists(config_path): parser.read(config_path) return parser ``` -------------------------------- ### Enforce Plugin Hash Verification Source: https://securitycards.rewarelabs.com/libraries/go/traefik/v3-7-10 Validates external plugins against expected SHA-256 hashes during installation. ```go plugin := Descriptor{ ModuleName: "github.com/example/plugin", Version: "v1.0.0", Hash: "expected-sha256-hash", } err := manager.InstallPlugin(ctx, plugin) ``` -------------------------------- ### Initialize SodiumVault with Environment-Provided Key Source: https://securitycards.rewarelabs.com/libraries/php/symfony/v8-1-1 Load decryption keys dynamically from environment variables rather than hardcoding them or storing them in version control. ```php use Symfony\Bundle\FrameworkBundle\Secrets\SodiumVault; $vault = new SodiumVault( secretsDir: $kernel->getProjectDir().'/config/secrets/prod', decryptionKey: $_ENV['SYMFONY_DECRYPTION_SECRET'] ?? null ); ``` -------------------------------- ### WebSocket Protocol Scheme Source: https://securitycards.rewarelabs.com/libraries/java/quarkus/3-38-0 Example of a secure WebSocket URL using the wss:// scheme. ```text wss://example.com/chat/username ``` -------------------------------- ### Isolate request state using Context set and get methods Source: https://securitycards.rewarelabs.com/libraries/typescript/hono/v4-12-32 Use c.set() to attach request-scoped state during middleware execution and retrieve it via c.get() within route handlers to prevent state bleeding. ```typescript app.use('*', async (c, next) => { const user = await verifyAuthToken(c.req.header('Authorization')) c.set('user', user) await next() }) app.get('/profile', (c) => { const user = c.get('user') return c.json({ userId: user.id }) }) ``` -------------------------------- ### Initialize Cryptographic Resources Before Sandboxing Source: https://securitycards.rewarelabs.com/libraries/swift/swift-crypto/4-5-1 Call CRYPTO_pre_sandbox_init() before applying process sandbox policies to ensure necessary system resources are acquired. ```C // Call before setting up sandbox restrictions CRYPTO_pre_sandbox_init(); // Proceed with enabling sandbox policies apply_process_sandbox_policy(); ``` -------------------------------- ### Configure PASSWORD_HASHERS Source: https://securitycards.rewarelabs.com/libraries/python/django/6-1rc1 Prioritize robust hashing algorithms like Argon2 at the start of the PASSWORD_HASHERS list. ```python PASSWORD_HASHERS = [ 'django.contrib.auth.hashers.Argon2PasswordHasher', 'django.contrib.auth.hashers.PBKDF2PasswordHasher', 'django.contrib.auth.hashers.PBKDF2SHA1PasswordHasher', ] ``` -------------------------------- ### Build Gateway Router Configuration Source: https://securitycards.rewarelabs.com/libraries/python/sglang/v0-5-16 Use the RouterConfigBuilder to initialize gateway settings with validation enabled to ensure security constraints are verified. ```rust let config = RouterConfigBuilder::new() .host("127.0.0.1") .port(8080) .api_key("secure-api-key-string") .build()?; ``` -------------------------------- ### Initialize Jinja Environment with Trusted Configuration Source: https://securitycards.rewarelabs.com/libraries/python/jinja/3-1-6 Configure the environment during application startup with explicit loaders and autoescaping settings. ```python from jinja2 import Environment, FileSystemLoader, select_autoescape env = Environment( loader=FileSystemLoader("templates"), autoescape=select_autoescape(["html", "htm", "xml"]), ) ``` -------------------------------- ### Redirect with 303 See Other Source: https://securitycards.rewarelabs.com/libraries/ruby/rails/v8-1-3 Ensures a redirect is followed by a GET request, preventing unintended method repetition. ```ruby redirect_to posts_url, status: :see_other ``` -------------------------------- ### Configure Production Static Storage Source: https://securitycards.rewarelabs.com/libraries/python/django/6-1rc1 Set up static file storage and root paths for production environments. ```python from pathlib import Path from django.conf import STATICFILES_STORAGE_ALIAS BASE_DIR = Path(__file__).resolve().parent.parent STATIC_ROOT = BASE_DIR / 'staticfiles' STATIC_URL = '/static/' STORAGES = { 'default': { 'BACKEND': 'django.core.files.storage.FileSystemStorage', }, STATICFILES_STORAGE_ALIAS: { 'BACKEND': 'django.contrib.staticfiles.storage.ManifestStaticFilesStorage', }, } ``` -------------------------------- ### Enforce Bounded Decompression Source: https://securitycards.rewarelabs.com/libraries/python/urllib3/2-7-0 Requires specific versions of Brotli for bounded-output decompression and provides a configuration example. ```text # requirements.txt # urllib3 == 2.7.0 # brotli >= 1.2.0 # # Alternatively: # brotlicffi >= 1.2.0.0 for chunk in response.stream(amt=65536, decode_content=True): process_chunk(chunk) ``` -------------------------------- ### Update Ollama Deployments Source: https://securitycards.rewarelabs.com/libraries/go/ollama/v0-32-5 Commands to update Ollama installations on Linux or via Docker to ensure runtime security. ```bash # Update Ollama using the official installer on Linux: curl -fsSL https://ollama.com/install.sh | sh # Or update a Docker-based deployment: docker pull ollama/ollama:latest ``` -------------------------------- ### Configure production settings and server Source: https://securitycards.rewarelabs.com/libraries/python/django/6-1rc1 Disable DEBUG mode and utilize a production-grade server like Gunicorn for deployment. ```python # settings.py DEBUG = False # Run via production WSGI server gunicorn myproject.wsgi:application --bind 127.0.0.1:8000 ``` -------------------------------- ### Configuring Dotfile Access Source: https://securitycards.rewarelabs.com/libraries/javascript/express/v5-2-1 Demonstrates how to ignore, allow, or deny dotfiles when serving static content or individual files. ```javascript // Ignore dotfiles in general static content app.use(express.static('public', { dotfiles: 'ignore' })); // Allow only the required public dot-directory app.use( '/.well-known', express.static('public/.well-known', { dotfiles: 'allow' }) ); // Deny dotfiles when serving request-selected files app.get('/files/:name', (req, res) => { res.sendFile(req.params.name, { root: '/uploads', dotfiles: 'deny' }); }); ``` -------------------------------- ### Validate subscription arguments with validateSubscriptionArgs Source: https://securitycards.rewarelabs.com/libraries/javascript/graphql-js/v17-0-2 Use validateSubscriptionArgs before invoking createSourceEventStream to prevent runtime exceptions during subscription setup. ```javascript const validatedArgs = validateSubscriptionArgs(executionArgs); if ('schema' in validatedArgs) { const sourceStream = await createSourceEventStream(validatedArgs); } else { // Handle schema validation errors } ``` -------------------------------- ### Configure TLS with AutoCertManager Source: https://securitycards.rewarelabs.com/libraries/go/fiber/v3-4-0 Use a single, unambiguous source for TLS credentials in ListenConfig to avoid initialization conflicts. ```go err := app.Listen(":443", fiber.ListenConfig{ AutoCertManager: &autocert.Manager{ Prompt: autocert.AcceptTOS, HostPolicy: autocert.HostWhitelist("example.com"), }, }) ``` -------------------------------- ### Configure CSRF Protection in Ktor Source: https://securitycards.rewarelabs.com/libraries/kotlin/ktor/3-5-1 Install the CSRF plugin within a route to validate origins and headers for state-changing requests. ```kotlin route("/api") { install(CSRF) { allowOrigin("https://app.example.com") originMatchesHost() checkHeader("X-CSRF-Token") { token -> token == "expected-valid-token" } } } ``` -------------------------------- ### Configure Logging Interceptor in Factory Source: https://securitycards.rewarelabs.com/libraries/kotlin/okhttp/parent-5-4-0 Demonstrates a factory pattern for creating an OkHttpClient with a pre-configured, redacted logging interceptor. ```java import okhttp3.OkHttpClient; import okhttp3.logging.HttpLoggingInterceptor; import okhttp3.logging.HttpLoggingInterceptor.Level; public final class HttpClientFactory { public static OkHttpClient create() { HttpLoggingInterceptor logging = new HttpLoggingInterceptor(); logging.setLevel(Level.HEADERS); logging.redactHeader("Authorization"); logging.redactHeader("Cookie"); return new OkHttpClient.Builder() .addInterceptor(logging) .build(); } } ``` -------------------------------- ### Disable Hidden File Serving Source: https://securitycards.rewarelabs.com/libraries/rust/actix-web/web-v4-14-0 Avoid calling use_hidden_files() to ensure that files and directories starting with a dot remain inaccessible. ```rust use actix_files::Files; use actix_web::App; let app = App::new() .service( Files::new("/static", "./static") ); ``` -------------------------------- ### Initialize Router with PD Disaggregation Source: https://securitycards.rewarelabs.com/libraries/python/sglang/v0-5-16 Configure the router to manage prefill and decode endpoints, ensuring client-supplied bootstrap parameters are overwritten. ```python from sglang_router import Router, RouterArgs args = RouterArgs( pd_disaggregation=True, prefill_urls=[("http://prefill:30000", 8998)], decode_urls=["http://decode:30000"], ) router = Router.from_args(args) ``` -------------------------------- ### Load Database Credentials via URL.create Source: https://securitycards.rewarelabs.com/libraries/python/sqlalchemy/rel-2-0-51 Pass passphrases directly to URL.create to avoid URL encoding issues with special characters. ```python import os from sqlalchemy import URL, create_engine db_url = URL.create( drivername="sqlite+pysqlcipher", password=os.environ["DB_PASSPHRASE"], database="encrypted.db", ) engine = create_engine(db_url) ``` -------------------------------- ### Load Configuration from Trusted Files Source: https://securitycards.rewarelabs.com/libraries/go/beego/v2-3-10 Use config.NewConfig to load configuration files from verified local paths to prevent environment variable injection. ```go cnf, err := config.NewConfig("yaml", "/etc/myapp/config.yaml") if err != nil { log.Fatalf("failed to load config: %v", err) } dbHost := cnf.DefaultString("database.host", "127.0.0.1") ``` -------------------------------- ### Anchor URL patterns in re_path Source: https://securitycards.rewarelabs.com/libraries/python/django/6-1rc1 Use start and end anchors in regular expressions to prevent partial matching vulnerabilities. ```python from django.urls import re_path from views import bio urlpatterns = [ re_path(r'^bio/(?P\w+)/$', bio, name='bio'), ] ``` -------------------------------- ### Disable Development Mode for Production Source: https://securitycards.rewarelabs.com/libraries/python/vllm/v0-26-0 Ensure developer mode is unset before starting the vLLM server to prevent exposure of administrative endpoints. ```bash unset VLLM_SERVER_DEV_MODE vllm serve facebook/opt-125m ``` -------------------------------- ### Generate and Initialize Encrypter Source: https://securitycards.rewarelabs.com/libraries/php/laravel/v13-22-0 Use this to generate a secure key and initialize the encrypter with an AEAD cipher. ```php $key = \Illuminate\Encryption\Encrypter::generateKey('aes-256-gcm'); $encrypter = new \Illuminate\Encryption\Encrypter($key, 'aes-256-gcm'); ``` -------------------------------- ### Launch Server with Private Interface Binding Source: https://securitycards.rewarelabs.com/libraries/python/sglang/v0-5-16 Bind the server to a private interface to isolate management and scheduler ports from external access. ```bash python3 -m sglang.launch_server \ --host 127.0.0.1 \ --port 30000 \ --model-path meta-llama/Llama-2-7b-chat-hf ``` -------------------------------- ### Configure Tensorizer with Encryption Source: https://securitycards.rewarelabs.com/libraries/python/vllm/v0-26-0 Use TensorizerConfig with an encryption keyfile to secure model weights and LoRA adapters. Requires libsodium to be installed in the environment. ```python from vllm.model_executor.model_loader.tensorizer import TensorizerConfig tensorizer_config = TensorizerConfig( tensorizer_uri="s3://my-bucket/vllm/model.tensors", encryption_keyfile="/etc/secrets/tensorizer_encryption.key", ) ``` -------------------------------- ### Configure Environment Proxies Source: https://securitycards.rewarelabs.com/libraries/python/aiohttp/v3-14-3 Use http:// schemes for environment proxy variables, as aiohttp ignores https:// and wss:// proxy configurations. ```python import os import aiohttp os.environ['HTTP_PROXY'] = 'http://proxy.example.com:8080' os.environ['HTTPS_PROXY'] = 'http://proxy.example.com:8080' async with aiohttp.ClientSession() as session: async with session.get('https://example.com') as resp: pass ``` -------------------------------- ### Configure Upstream Reverse Proxy Authentication Source: https://securitycards.rewarelabs.com/libraries/python/sglang/v0-5-16 Example Nginx configuration for enforcing authentication at the network boundary when running multi-tokenizer worker mode. ```nginx # When deploying SGLang with multiple tokenizer workers, do not set server_args.api_key. Place the HTTP server behind an authenticated reverse proxy (e.g., Nginx, Envoy, or an API gateway) to perform token verification before forwarding requests. # Example Nginx reverse proxy auth configuration location /v1/ { auth_request /auth; proxy_pass http://127.0.0.1:30000; } ``` -------------------------------- ### Enforce JSON schema constraints Source: https://securitycards.rewarelabs.com/libraries/go/ollama/v0-32-5 Example of a JSON payload using the format field to enforce strict data types for structured outputs. ```json { "model": "llama3.1:8b", "prompt": "Provide user metadata. Respond using JSON", "stream": false, "format": { "type": "object", "properties": { "age": { "type": "integer" }, "available": { "type": "boolean" } }, "required": ["age", "available"] } } ``` -------------------------------- ### Implement Basic Authentication middleware Source: https://securitycards.rewarelabs.com/libraries/go/gin/v1-12-0 Protect routes using gin.BasicAuth and retrieve the authenticated user identity from the context using gin.AuthUserKey. ```go router := gin.Default() authorized := router.Group("/admin", gin.BasicAuth(gin.Accounts{ "admin": "SecretPassword123!", })) authorized.GET("/dashboard", func(c *gin.Context) { user := c.MustGet(gin.AuthUserKey).(string) c.String(http.StatusOK, "Hello %s", user) }) ``` -------------------------------- ### Hash and Verify Passwords with Bcrypt Source: https://securitycards.rewarelabs.com/libraries/swift/vapor/4-122-0 Demonstrates hashing passwords before database persistence and verifying them during the authentication process using Bcrypt. ```swift // Hash before saving let user = try User( name: create.name, email: create.email, passwordHash: Bcrypt.hash(create.password) ) try await user.save(on: req.db) // Verify during login extension User: ModelAuthenticatable { static let usernameKey = \User.$email static let passwordHashKey = \User.$passwordHash func verify(password: String) throws -> Bool { try Bcrypt.verify(password, created: self.passwordHash) } } ``` -------------------------------- ### Specify transaction isolation levels Source: https://securitycards.rewarelabs.com/libraries/typescript/type-orm/1-1-0 Explicitly define isolation levels when starting transactions to ensure database consistency and prevent concurrency issues. ```typescript await dataSource.manager.transaction("SERIALIZABLE", async (transactionalEntityManager) => { const post = new Post(); post.title = "Secure Transaction Post"; await transactionalEntityManager.save(post); }); ``` -------------------------------- ### Paginate Queue Getter Queries Source: https://securitycards.rewarelabs.com/libraries/typescript/bullmq/v5-81-3 Use start and end offsets when fetching jobs or logs to avoid loading excessive data into memory. ```typescript const pageSize = 50; const start = 0; const end = start + pageSize - 1; const completedJobs = await queue.getCompleted(start, end); const jobLogs = await queue.getJobLogs(jobId, start, end); ``` -------------------------------- ### Serve static assets with Echo middleware Source: https://securitycards.rewarelabs.com/libraries/go/echo/v5-3-1 Use StaticWithConfig to serve files from a specific directory while relying on Echo's built-in path sanitization. ```go e := echo.New() e.Use(middleware.StaticWithConfig(middleware.StaticConfig{ Root: "public", Filesystem: os.DirFS("dist"), })) ``` -------------------------------- ### Validate redirect URLs for security Source: https://securitycards.rewarelabs.com/libraries/javascript/express/v5-2-1 Restrict redirect targets to relative paths starting with a single slash to prevent open redirect vulnerabilities. ```javascript app.get('/login-redirect', (req, res) => { const target = req.query.url; if (target && target.startsWith('/') && !target.startsWith('//')) { res.redirect(302, target); } else { res.redirect(302, '/dashboard'); } }); ``` -------------------------------- ### Verify Model Configuration Files Source: https://securitycards.rewarelabs.com/libraries/go/ollama/v0-32-5 Validate file hashes before parsing model configuration files to mitigate prompt injection risks. ```go func convertModelSafely(modelDir string) (*Tokenizer, error) { if err := verifyFileHashes(modelDir); err != nil { return nil, fmt.Errorf("untrusted model files: %w", err) } return parseTokenizer(os.DirFS(modelDir), []string{"bos", "eos"}) } ``` -------------------------------- ### Initialize Cache Token Repository Source: https://securitycards.rewarelabs.com/libraries/php/laravel/v13-22-0 Configure token expiration and throttling limits to mitigate brute-force and enumeration attacks. ```php use Illuminate\Auth\Passwords\CacheTokenRepository; use Illuminate\Contracts\Cache\Repository as CacheRepository; use Illuminate\Contracts\Hashing\Hasher; $repository = new CacheTokenRepository( cache: $app[CacheRepository::class], hasher: $app[Hasher::class], hashKey: config('app.key'), expires: 3600, throttle: 60 ); ``` -------------------------------- ### Handle missing cryptography dependency Source: https://securitycards.rewarelabs.com/libraries/python/pyjwt/2-13-0 Ensure the pyjwt[crypto] extra is installed for asymmetric key operations and handle MissingCryptographyError to prevent runtime crashes. ```python # Install dependency via: pip install 'pyjwt[crypto]' from jwt import PyJWKSet from jwt.exceptions import MissingCryptographyError try: jwk_set = PyJWKSet.from_dict(jwk_data) except MissingCryptographyError as e: raise SystemExit("cryptography package is required for JWK verification") from e ``` -------------------------------- ### Configure link preloading attributes Source: https://securitycards.rewarelabs.com/libraries/javascript/svelte-kit/sveltejs-kit-2-70-1 Use these attributes on anchor tags to prevent hover-triggered execution of load functions or GET endpoints that contain side-effects. ```html View Metrics View Live Feed ``` -------------------------------- ### Run Fastify Application Source: https://securitycards.rewarelabs.com/libraries/javascript/fastify/v5-9-0 Execute the application using the default secure HTTP parser settings. ```bash node app.js ``` -------------------------------- ### Initialize Fiber without Prefork Source: https://securitycards.rewarelabs.com/libraries/go/fiber/v3-4-0 Use this configuration for production environments requiring strict single-owner socket semantics to avoid shared network namespace risks. ```go package main import ( "log" "github.com/gofiber/fiber/v3" ) func main() { app := fiber.New() app.Get("/api/health", func(c fiber.Ctx) error { return c.SendString("OK") }) // Standard single-process server start log.Fatal(app.Listen(":8080")) } ``` -------------------------------- ### Define RBAC destination port range Source: https://securitycards.rewarelabs.com/libraries/cpp/envoy/v1-39-0 Set valid port boundaries for RBAC permissions, ensuring the start port is strictly less than the end port. ```cpp envoy::config::rbac::v3::Permission permission; auto* range = permission.mutable_destination_port_range(); range->set_start(80); range->set_end(443); ``` -------------------------------- ### Initialize PlanetScale driver adapter Source: https://securitycards.rewarelabs.com/libraries/typescript/prisma/7-8-0 Pass the connection URL explicitly when initializing the PrismaPlanetScale adapter. ```typescript const adapter = new PrismaPlanetScale({ url: process.env.JS_PLANETSCALE_DATABASE_URL }) ``` -------------------------------- ### Define routes with attribute macros Source: https://securitycards.rewarelabs.com/libraries/rust/rocket/v0-5-1 Prefer Rocket's attribute macros like #[get] or #[post] over manual routing to maintain automatic parameter validation and type-checking. ```rust #[get("/item/")] fn get_item(id: u64) -> String { format!("Item {}", id) } ``` -------------------------------- ### Validate Request Payloads with RequestValidation and StatusPages Source: https://securitycards.rewarelabs.com/libraries/kotlin/ktor/3-5-1 Install the RequestValidation plugin to enforce input constraints and use StatusPages to handle RequestValidationException by returning a 400 Bad Request response. ```kotlin install(RequestValidation) { validate { body -> if (!body.startsWith("+")) { ValidationResult.Invalid("String must start with '+'") } else { ValidationResult.Valid } } } install(StatusPages) { exception { call, cause -> call.respond(HttpStatusCode.BadRequest, cause.reasons.joinToString(", ")) } } ``` -------------------------------- ### initStoreFromUrlOrLocalStorage() Source: https://securitycards.rewarelabs.com/libraries/javascript/react/v19-2-7 Retrieves and validates the application state from the URL hash or localStorage, falling back to default values if necessary. ```APIDOC ## initStoreFromUrlOrLocalStorage() ### Description Initializes the application state by checking the URL hash first, then `localStorage`. It validates the retrieved data and returns a `Store` object. ### Returns - **Store** - The validated application state object. ``` -------------------------------- ### Sanitize Configuration Environment Variables Source: https://securitycards.rewarelabs.com/libraries/go/ollama/v0-32-5 Explicitly set configuration directories to prevent path hijacking and unauthorized file access. ```go t.Setenv("PI_CODING_AGENT_DIR", filepath.Join(trustedDir, "agent")) t.Setenv("PI_CONFIG_DIR", "") o := &OMP{} if err := o.ConfigureWithModels("new-model", models); err != nil { log.Fatalf("Configuration failed: %v", err) } ``` -------------------------------- ### Restrict HTTP Verbs in Routes Source: https://securitycards.rewarelabs.com/libraries/ruby/rails/v8-1-3 Use the via option in match routes to explicitly define allowed HTTP methods and prevent unintended state changes via GET. ```ruby Always restrict HTTP methods using the via option when defining match routes: Rails.application.routes.draw do match 'openid/login', via: [:get, :post], to: 'openid#login' end ``` -------------------------------- ### Restrict HTTP Verbs in Routes Source: https://securitycards.rewarelabs.com/libraries/ruby/rails/v8-1-3 Use the via option in match routes to explicitly define allowed HTTP methods and prevent unintended state changes via GET requests. ```ruby Rails.application.routes.draw do match 'openid/login', via: [:get, :post], to: 'openid#login' end ``` -------------------------------- ### Configure HTTP/3 QUIC Protocol Options Source: https://securitycards.rewarelabs.com/libraries/cpp/envoy/v1-39-0 Disable QPACK and configure HTTP/3 options for QUIC client connections to enhance security. ```cpp envoy::config::core::v3::Http3ProtocolOptions http3_options; http3_options.set_disable_qpack(true); session->setHttp3Options(http3_options); ``` -------------------------------- ### Initialize SQLite with Foreign Key Enforcement Source: https://securitycards.rewarelabs.com/libraries/go/ollama/v0-32-5 Configure SQLite connections with foreign key support and WAL mode enabled to ensure data integrity. ```go conn, err := sql.Open("sqlite3", dbPath+"?_foreign_keys=on&_journal_mode=WAL&_busy_timeout=5000&_txlock=immediate") if err != nil { return nil, err } _, err = conn.Exec("PRAGMA foreign_keys = ON") ``` -------------------------------- ### Configure Trusted X.509 Certificate Store Source: https://securitycards.rewarelabs.com/libraries/swift/swift-crypto/4-5-1 Avoid environment variable fallbacks by explicitly defining the certificate directory and file type. ```c /* Build a store that trusts only certificates in /etc/ssl/certs. */ X509_STORE *store = X509_STORE_new(); if (!store) { /* handle error */ } X509_LOOKUP *lookup = X509_STORE_add_lookup(store, X509_LOOKUP_hash_dir()); if (!lookup || !X509_LOOKUP_add_dir(lookup, "/etc/ssl/certs", X509_FILETYPE_PEM)) { /* Abort: explicit trust store failed to load. */ } ``` -------------------------------- ### Constructing Database URLs with URL.create Source: https://securitycards.rewarelabs.com/libraries/python/sqlalchemy/rel-2-0-51 Use URL.create to build connection strings from components, ensuring special characters in credentials are handled safely without manual escaping. ```python from sqlalchemy import URL, create_engine url_object = URL.create( "postgresql+pg8000", username="dbuser", password="kx@jj5/g", host="pghost10", database="appdb", ) engine = create_engine(url_object) ``` -------------------------------- ### Implement Dynamic Token Retrieval Source: https://securitycards.rewarelabs.com/libraries/go/ollama/v0-32-5 Use a GetToken callback to handle WWW-Authenticate challenges securely during registry transfers. ```go err := transfer.Download(ctx, transfer.DownloadOptions{ Blobs: blobs, BaseURL: registryURL, DestDir: destDir, GetToken: func(ctx context.Context, challenge transfer.AuthChallenge) (string, error) { return tokenClient.FetchToken(ctx, challenge.Realm, challenge.Service, challenge.Scope) }, }) ``` -------------------------------- ### Configure Secure Basic Authentication Source: https://securitycards.rewarelabs.com/libraries/go/fiber/v3-4-0 Use bcrypt hashes for stored credentials in basicauth.Config to protect against brute-force attacks. ```go app.Use(basicauth.New(basicauth.Config{ Users: map[string]string{ "admin": "$2a$10$vI8aWBnW3fID.ZQ4/07.e.e1cTfE2wG8Pz6A0ZqYh123456789012", }, })) ``` -------------------------------- ### Enable PKCE for OpenID Connect Source: https://securitycards.rewarelabs.com/libraries/csharp/asp-net/v10-0-10 Set UsePkce to true to prevent code interception during authorization code flows. ```csharp builder.Services.AddAuthentication().AddOpenIdConnect(options => { options.ResponseType = OpenIdConnectResponseType.Code; options.UsePkce = true; }); ``` -------------------------------- ### Configure Static Directory Serving Source: https://securitycards.rewarelabs.com/libraries/rust/salvo/v0-94-0 Use StaticDir to serve files from a dedicated, absolute path. Ensure the directory has restrictive permissions. ```rust use salvo_core::prelude::*; use salvo_serve_static::StaticDir; let router = Router::new().push( Router::with_path("static/{**}").get( StaticDir::new("/var/www/my-app/static-assets") .defaults("index.html") ), ); ``` -------------------------------- ### Instantiate Prisma Client with Driver Adapter Source: https://securitycards.rewarelabs.com/libraries/typescript/prisma/7-8-0 Requires a compatible driver adapter for database communication in Prisma 7.8.0. ```typescript import { PrismaBetterSqlite3 } from '@prisma/adapter-better-sqlite3' import { PrismaClient } from './generated/prisma/client' const adapter = new PrismaBetterSqlite3({ url: 'file:prisma/dev.db' }) const prisma = new PrismaClient({ adapter }) // For D1 specific adapter: // import { PrismaD1 } from '@prisma/adapter-d1' // const adapter = new PrismaD1(env.MY_DATABASE); // const prisma = new PrismaClient({ adapter }); ``` -------------------------------- ### Initialize SecretKey with Cryptographic Entropy Source: https://securitycards.rewarelabs.com/libraries/rust/rocket/v0-5-1 Manually instantiate a SecretKey using a 64-byte array to ensure sufficient cryptographic entropy. ```rust use rocket::config::SecretKey; let mut master = [0u8; 64]; let key = SecretKey::from(&master); ``` -------------------------------- ### Configure X509 Verification Parameters Source: https://securitycards.rewarelabs.com/libraries/swift/swift-crypto/4-5-1 Sets up X509 verification parameters using standard CRL checking flags to avoid unsupported flag failures. ```c X509_VERIFY_PARAM *param = X509_VERIFY_PARAM_new(); X509_VERIFY_PARAM_set_flags(param, X509_V_FLAG_CRL_CHECK); X509_STORE_CTX_set0_param(ctx, param); ``` -------------------------------- ### Configure runtime initialization for native images Source: https://securitycards.rewarelabs.com/libraries/java/quarkus/3-38-0 Specify classes that must be initialized at runtime to avoid static build-time caching of sensitive security states. ```properties quarkus.native.additional-build-args=--initialize-at-run-time=com.example.CryptoService\,sun.security.provider.NativePRNG ``` -------------------------------- ### Build Envoy with BoringSSL Source: https://securitycards.rewarelabs.com/libraries/cpp/envoy/v1-39-0 Use these Bazel commands to build Envoy with secure BoringSSL configurations instead of OpenSSL. ```bash bazel build //source/exe:envoy-static # Or for FIPS compliance: bazel build --config=boringssl-fips //source/exe:envoy-static ``` -------------------------------- ### Configure Session Manager Source: https://securitycards.rewarelabs.com/libraries/go/beego/v2-3-10 Initializes a session manager with secure cookie attributes and Redis provider configuration. ```go sessionConfig := session.NewManagerConfig( session.CfgCookieName("gosessionid"), session.CfgSetCookie(true), session.CfgSecure(true), session.CfgGcLifeTime(3600), session.CfgMaxLifeTime(3600), session.CfgProviderConfig("127.0.0.1:6379,100,,0,30"), ) globalSessions, err := session.NewManager("redis", sessionConfig) ``` -------------------------------- ### Handle file uploads with UploadFile Source: https://securitycards.rewarelabs.com/libraries/python/fastapi/0-139-2 Demonstrates using UploadFile to read file contents and return metadata, ensuring proper resource management. ```python from fastapi import FastAPI, File, UploadFile app = FastAPI() @app.post("/upload/") async def handle_upload(file: UploadFile = File(...)): contents = await file.read() return {"filename": file.filename, "size": len(contents)} ``` -------------------------------- ### Merge environment settings for manual requests Source: https://securitycards.rewarelabs.com/libraries/python/requests/v2-34-2 Ensures environment configurations and custom CA bundles are applied when using Session.send() with a PreparedRequest. ```python from requests import Request, Session s = Session() req = Request('GET', 'https://example.com') prepped = s.prepare_request(req) settings = s.merge_environment_settings(prepped.url, {}, None, None, None) resp = s.send(prepped, **settings) ``` -------------------------------- ### Configure Identity and Find User Source: https://securitycards.rewarelabs.com/libraries/csharp/asp-net/v10-0-10 Registers Identity services and demonstrates a standard user lookup using the UserManager. ```csharp builder.Services.AddIdentity() .AddEntityFrameworkStores(); public async Task FindUserAsync(UserManager userManager, string userInput) { return await userManager.FindByNameAsync(userInput); } ``` -------------------------------- ### Apply Request Size and Concurrency Limits Source: https://securitycards.rewarelabs.com/libraries/go/chi/v5-3-1 Use RequestSize and ThrottleWithOpts middleware to protect resource-heavy endpoints from exhaustion. ```go r := chi.NewRouter() r.With(middleware.RequestSize(1048576)).With(middleware.ThrottleWithOpts(middleware.ThrottleOpts{ Limit: 50, BacklogLimit: 100, BacklogTimeout: 5 * time.Second, StatusCode: http.StatusTooManyRequests, RetryAfterFn: func(ctxDone bool) time.Duration { return 10 * time.Second }, })).Post("/api/heavy-process", heavyHandler) ``` -------------------------------- ### Initialize Session Guard with Timebox Source: https://securitycards.rewarelabs.com/libraries/php/laravel/v13-22-0 Use a Timebox instance to maintain consistent execution time and prevent timing side-channel attacks. ```php use Illuminate\Auth\SessionGuard; use Illuminate\Support\Timebox; $guard = new SessionGuard( 'web', $userProvider, $session, $request, new Timebox, rehashOnLogin: true, timeboxDuration: 200000 ); ``` -------------------------------- ### Integrate net/http Handlers Safely Source: https://securitycards.rewarelabs.com/libraries/go/fiber/v3-4-0 Use context-aware adaptors to propagate request context without relying on unsafe reflection or memory manipulation. ```go app.Get("/hello", adaptor.HTTPHandlerWithContext(http.HandlerFunc(handleRequest))) func handleRequest(w http.ResponseWriter, r *http.Request) { ctx, ok := adaptor.LocalContextFromHTTPRequest(r) if !ok || ctx == nil { http.Error(w, "missing context", http.StatusInternalServerError) return } } ``` -------------------------------- ### Handle Connection Lifecycle Source: https://securitycards.rewarelabs.com/libraries/typescript/mongoose/9-8-0 Always instantiate a new connection after destroying an existing one rather than attempting to reuse closed instances. ```javascript await conn.destroy(); const newConn = mongoose.createConnection(uri); await newConn.asPromise(); ``` -------------------------------- ### Secure Remote Configuration Loading Source: https://securitycards.rewarelabs.com/libraries/go/caddy/v2-11-4 Use HTTPS and explicit TLS credentials when fetching dynamic configurations to prevent tampering and unauthorized access. ```go loader := caddyconfig.HTTPLoader{ Method: "GET", URL: "https://config-server.internal.domain/v1/caddy-config", Timeout: caddy.Duration(10 * time.Second), TLS: &struct { UseServerIdentity bool `json:"use_server_identity,omitempty"` ClientCertificateFile string `json:"client_certificate_file,omitempty"` ClientCertificateKeyFile string `json:"client_certificate_key_file,omitempty"` RootCAPEMFiles []string `json:"root_ca_pem_files,omitempty"` }{ RootCAPEMFiles: []string{"/etc/ssl/certs/internal-ca.pem"}, ClientCertificateFile: "/etc/ssl/certs/config-client.crt", ClientCertificateKeyFile: "/etc/ssl/certs/config-client.key", }, } ``` -------------------------------- ### Serve Static Files Securely in Ktor Source: https://securitycards.rewarelabs.com/libraries/kotlin/ktor/3-5-1 Use the staticFiles DSL to serve files from a defined root directory while automatically preventing directory traversal. ```kotlin routing { staticFiles("static", File("/app/public")) } ``` -------------------------------- ### Load Database Credentials from Environment Variables Source: https://securitycards.rewarelabs.com/libraries/go/beego/v2-3-10 Retrieve sensitive database connection strings from environment variables to avoid hardcoding credentials in source files. ```go dbDSN := os.Getenv("DATABASE_DSN") orm.RegisterDataBase("default", "mysql", dbDSN, 30) ``` -------------------------------- ### Resolve Symbolic Links for Secure Access Source: https://securitycards.rewarelabs.com/libraries/go/ollama/v0-32-5 Use filepath.EvalSymlinks to resolve paths before opening files to ensure they remain within expected boundaries. ```go realPath, err := filepath.EvalSymlinks(path) if err != nil { return "", err } bin, err := os.Open(realPath) if err != nil { return "", err } defer bin.Close() ``` -------------------------------- ### Configure Fastify Instance Options Source: https://securitycards.rewarelabs.com/libraries/javascript/fastify/v5-9-0 Pass security-sensitive options like bodyLimit and trustProxy directly to the Fastify constructor to ensure configuration integrity. ```javascript const fastify = require('fastify')({ bodyLimit: 1048576, trustProxy: true }); ``` -------------------------------- ### Registering Routes and Static Files in Order Source: https://securitycards.rewarelabs.com/libraries/rust/actix-web/web-v4-14-0 Register specific routes before broad catch-all services to prevent request shadowing. ```rust use actix_web::{web, App, HttpResponse, Responder}; use actix_files::Files; async fn api_handler() -> impl Responder { HttpResponse::Ok().body("OK") } let app = App::new() .route("/api/health", web::get().to(api_handler)) .service(Files::new("/", "./static").index_file("index.html")); ``` -------------------------------- ### Configure Agent Session Authorization Source: https://securitycards.rewarelabs.com/libraries/go/ollama/v0-32-5 Initialize an agent session with explicit approval mechanisms to gate model-initiated tool execution. ```go session := &agent.Session{ Client: chatClient, ApprovalPrompter: customPrompter, ApprovalState: &agent.ApprovalState{}, } ``` -------------------------------- ### Configure Prisma migrations with environment variables Source: https://securitycards.rewarelabs.com/libraries/typescript/prisma/7-8-0 Use environment variables for database URLs and define migration paths explicitly in prisma.config.ts. ```bash # Configure this separately in each environment: DATABASE_URL="postgres://user:pass@host/db" # Then specify in prisma.config.ts: import { defineConfig, env } from 'prisma/config' export default defineConfig({ schema: 'prisma/schema.prisma', migrations: { path: 'prisma/migrations', }, datasource: { url: env('DATABASE_URL'), }, }) ``` ```typescript import { defineConfig, env } from 'prisma/config' export default defineConfig({ schema: 'prisma/schema.prisma', migrations: { path: 'prisma/migrations', }, datasource: { url: env('DATABASE_URL'), }, }) ``` -------------------------------- ### Configure JSON-RPC Stream Source: https://securitycards.rewarelabs.com/libraries/go/goa/v3-28-0 Initialize stream configuration for JSON-RPC WebSocket connections. ```go cfg := jsonrpc.NewStreamConfig( jsonrpc.WithRequestTimeout(30*time.Second), ) ``` -------------------------------- ### Configure CookieStore with Stable Secret Key Source: https://securitycards.rewarelabs.com/libraries/rust/salvo/v0-94-0 Initializes a CookieStore using a stable secret key from environment variables to ensure session persistence across restarts. ```rust use salvo_core::http::cookie::Key; use salvo_flash::CookieStore; let secret_key_bytes = std::env::var("SESSION_SECRET_KEY") .expect("SESSION_SECRET_KEY must be set"); let key = Key::from(secret_key_bytes.as_bytes()); let store = CookieStore::new().key(key); ``` -------------------------------- ### Configure Chi Compressor Middleware Source: https://securitycards.rewarelabs.com/libraries/go/chi/v5-3-1 Pass exact MIME types or trailing wildcards like 'text/*' to the compressor constructor to avoid runtime panics. ```go compressor := middleware.NewCompressor(5, "text/*", "application/json", "image/*") r.Use(compressor.Handler) ``` -------------------------------- ### Configure shared storage for rate limiting Source: https://securitycards.rewarelabs.com/libraries/go/fiber/v3-4-0 Use a centralized storage backend like Redis for rate limiting in multi-process deployments. ```go app.Use(limiter.New(limiter.Config{ Max: 20, Expiration: 30 * time.Second, Storage: customRedisStorage, })) ``` -------------------------------- ### Configure TrustedProxyIssuer for Rate Limiting Source: https://securitycards.rewarelabs.com/libraries/rust/salvo/v0-94-0 Initialize RateLimiter with a verified list of proxy IP addresses to prevent header-spoofing attacks. ```rust use std::net::IpAddr; use salvo_rate_limiter::{RateLimiter, TrustedProxyIssuer, BasicQuota, FixedGuard, MokaStore}; let trusted_proxies = [ "10.0.0.5".parse::().unwrap(), "10.0.0.6".parse::().unwrap(), ]; let limiter = RateLimiter::new( FixedGuard::default(), MokaStore::default(), TrustedProxyIssuer::new(trusted_proxies), BasicQuota::per_minute(100), ); ``` -------------------------------- ### Load and Validate PKI Key Pairs Source: https://securitycards.rewarelabs.com/libraries/go/caddy/v2-11-4 Load certificate and private key pairs for PKI operations, ensuring consistency and proper chain handling. ```go kp := caddypki.KeyPair{ Certificate: "/etc/ssl/pki/ca.crt", PrivateKey: "/etc/ssl/pki/ca.key", Format: "pem_file", } chain, signer, err := kp.Load() if err != nil { // Handle file access error or key mismatch error } ``` -------------------------------- ### Configure CertificatePinner for OkHttpClient Source: https://securitycards.rewarelabs.com/libraries/kotlin/okhttp/parent-5-4-0 Enforce SHA-256 public key pinning for specific hostnames to mitigate man-in-the-middle attacks. ```kotlin val certificatePinner = CertificatePinner.Builder() .add("api.example.com", "sha256/AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=") .build() val client = okHttpClient.newBuilder() .certificatePinner(certificatePinner) .build() ``` -------------------------------- ### Configure secure Kubernetes deployment settings Source: https://securitycards.rewarelabs.com/libraries/java/quarkus/3-38-0 Define security contexts, service accounts, and resource limits in application properties to harden container deployments. ```properties quarkus.kubernetes.security-context.run-as-non-root=true quarkus.kubernetes.security-context.read-only-root-filesystem=true quarkus.kubernetes.service-account=my-app-sa quarkus.kubernetes.resources.limits.memory=512Mi quarkus.kubernetes.app-secret=my-app-secret ``` -------------------------------- ### Verify OkHttp dependency artifacts Source: https://securitycards.rewarelabs.com/libraries/kotlin/okhttp/parent-5-4-0 Use this command to generate dependency verification metadata for OkHttp artifacts using PGP and SHA-256. ```bash ./gradlew --write-verification-metadata pgp,sha256 help ``` -------------------------------- ### Configure HTTP Response Security Headers Source: https://securitycards.rewarelabs.com/libraries/go/echo/v5-3-1 Use SecureWithConfig to define essential security headers like CSP, HSTS, and X-Frame-Options to protect against common web vulnerabilities. ```go e := echo.New() e.Use(middleware.SecureWithConfig(middleware.SecureConfig{ XSSProtection: "1; mode=block", ContentTypeNosniff: "nosniff", XFrameOptions: "SAMEORIGIN", HSTSMaxAge: 31536000, HSTSPreloadEnabled: true, HSTSExcludeSubdomains: false, ContentSecurityPolicy: "default-src 'self'", ReferrerPolicy: "strict-origin-when-cross-origin", })) ``` -------------------------------- ### Configure Hugging Face Token via Environment Variable Source: https://securitycards.rewarelabs.com/libraries/python/vllm/v0-26-0 Use environment variables to provide access tokens for private models instead of hardcoding them. ```bash export HF_TOKEN="hf_your_access_token_here" ``` -------------------------------- ### Configure UI Server Authentication Source: https://securitycards.rewarelabs.com/libraries/go/ollama/v0-32-5 Set Dev to false in production to enforce token validation for UI server instances. ```go s := &ui.Server{ Logger: logger, Token: requiredAuthToken, Dev: false, } ``` -------------------------------- ### Initialize Environment with Autoescaping Source: https://securitycards.rewarelabs.com/libraries/python/jinja/3-1-6 Configure the Jinja2 environment to automatically sanitize HTML and XML content. ```python from jinja2 import Environment, FileSystemLoader, select_autoescape env = Environment( loader=FileSystemLoader("templates"), autoescape=select_autoescape(["html", "xml"]) ) ``` ```python from jinja2 import Environment, select_autoescape env = Environment( autoescape=select_autoescape(["html", "xml"]) ) ``` -------------------------------- ### Configure JDBC Principal Queries Source: https://securitycards.rewarelabs.com/libraries/java/quarkus/3-38-0 Set up secure JDBC authentication with bcrypt password mapping and attribute index configuration. ```properties quarkus.security.jdbc.enabled=true quarkus.security.jdbc.principal-query.sql=SELECT u.password, u.role FROM test_user u WHERE u.username=? quarkus.security.jdbc.principal-query.bcrypt-password-mapper.enabled=true quarkus.security.jdbc.principal-query.bcrypt-password-mapper.password-index=1 quarkus.security.jdbc.principal-query.attribute-mappings.0.index=2 quarkus.security.jdbc.principal-query.attribute-mappings.0.to=groups ``` -------------------------------- ### Control File Overwriting Source: https://securitycards.rewarelabs.com/libraries/python/django/6-1rc1 Initialize FileSystemStorage with allow_overwrite set to False to prevent accidental file replacement. ```python from django.core.files.storage import FileSystemStorage # Prevent overwriting existing files on save storage = FileSystemStorage(allow_overwrite=False) ``` -------------------------------- ### Configure Security Options on Database Views Source: https://securitycards.rewarelabs.com/libraries/typescript/drizzle-orm/0-45-2 Use .with() to set securityInvoker and securityBarrier to ensure views execute with the calling user's permissions. ```typescript import { pgTable, integer, pgView } from 'drizzle-orm/pg-core'; export const users = pgTable('users', { id: integer('id').primaryKey().notNull(), }); export const secureUsersView = pgView('secure_users_view').with({ securityInvoker: true, securityBarrier: true, checkOption: 'cascaded', }).as((qb) => qb.select().from(users)); ``` -------------------------------- ### Configure SSL Context with Environment Variables Source: https://securitycards.rewarelabs.com/libraries/python/httpx/0-28-1 Manually retrieves SSL environment variables to populate a custom SSLContext, as HTTPX does not automatically read these when a custom context is provided. ```python import os import ssl import certifi import httpx ctx = ssl.create_default_context( cafile=os.environ.get("SSL_CERT_FILE", certifi.where()), capath=os.environ.get("SSL_CERT_DIR"), ) client = httpx.Client(verify=ctx) ``` -------------------------------- ### Secure Custom File Serving Source: https://securitycards.rewarelabs.com/libraries/go/gin/v1-12-0 Sanitize user-provided paths and verify files are regular before serving them from a designated root directory. ```go r.GET("/assets/*filepath", func(c *gin.Context) { name := strings.TrimPrefix(c.Param("filepath"), "/") file, err := os.OpenInRoot("/var/www/static", name) if err != nil { c.String(http.StatusNotFound, "File not found") return } defer file.Close() info, err := file.Stat() if err != nil || !info.Mode().IsRegular() { c.String(http.StatusNotFound, "File not found") return } http.ServeContent(c.Writer, c.Request, info.Name(), info.ModTime(), file) }) ``` -------------------------------- ### Configure Prisma with Environment Variables Source: https://securitycards.rewarelabs.com/libraries/typescript/prisma/7-8-0 Explicitly load environment variables using dotenv and the Prisma config helper to securely manage database connection strings. ```typescript import 'dotenv/config' import { defineConfig, env } from '@prisma/config' export default defineConfig({ datasource: { url: env('DATABASE_URL'), }, }) ``` -------------------------------- ### Configure allowed local media paths Source: https://securitycards.rewarelabs.com/libraries/python/vllm/v0-26-0 Set the allowed_local_media_path in EngineArgs to restrict filesystem access for multimodal inputs. ```python from vllm.engine.arg_utils import EngineArgs engine_args = EngineArgs( model="organization/multimodal-model", allowed_local_media_path="/var/app/safe_media_uploads" ) ``` -------------------------------- ### Serve files securely with StaticFiles Source: https://securitycards.rewarelabs.com/libraries/python/starlette/1-3-1 Mount StaticFiles to a specific directory to ensure that only files within that directory are accessible and to prevent directory traversal attacks. ```python from starlette.applications import Starlette from starlette.routing import Mount from starlette.staticfiles import StaticFiles routes = [ Mount( "/downloads", app=StaticFiles(directory="/app/storage/uploads"), name="downloads", ) ] app = Starlette(routes=routes) ``` -------------------------------- ### Instantiate ML-DSA keys from seeds Source: https://securitycards.rewarelabs.com/libraries/swift/swift-crypto/4-5-1 Supply the expected public key or use integrity-checked initializers when reconstructing post-quantum keys. ```swift let privateKey = try MLDSA65.PrivateKey( seedRepresentation: seedBytes, publicKey: expectedPublicKey ) ``` -------------------------------- ### Configure Client Session Header Limits Source: https://securitycards.rewarelabs.com/libraries/python/aiohttp/v3-14-3 Specify bounded limits for max_line_size, max_field_size, and max_headers during session initialization to prevent memory exhaustion from malicious headers. ```python import aiohttp async with aiohttp.ClientSession( max_line_size=8190, max_field_size=8190, max_headers=128 ) as session: async with session.get("https://example.com") as resp: text = await resp.text() ``` -------------------------------- ### Configure Referrer Policy Source: https://securitycards.rewarelabs.com/libraries/typescript/helmet/v8-3-0 Supply unique, recognized policy tokens in an array to prevent startup exceptions when configuring referrer policy. ```typescript import helmet from "helmet"; app.use( helmet.referrerPolicy({ policy: ["same-origin", "strict-origin"] }) ); ``` -------------------------------- ### Implement a Goa server interceptor Source: https://securitycards.rewarelabs.com/libraries/go/goa/v3-28-0 Demonstrates the correct pattern for invoking the next endpoint function and handling errors within a custom interceptor. ```go func (i *Interceptors) RequestAudit(ctx context.Context, info *RequestAuditInfo, next goa.Endpoint) (any, error) { res, err := next(ctx, info.RawPayload()) if err != nil { return nil, err } return res, nil } ``` -------------------------------- ### Configure environment file paths Source: https://securitycards.rewarelabs.com/libraries/php/laravel/v13-22-0 Use these methods to define the location of environment files, ensuring they are stored outside the public web root for security. ```php $app->useEnvironmentPath($app->basePath()); $app->loadEnvironmentFrom('.env'); ```