Code Quality Help

Security

Security is every developer’s responsibility. The rules in this section apply to all codebases and must be verified during code review and automated scans. When automating these checks is not yet possible, the reviewer must explicitly confirm compliance.

11.1 General Principles

  • Least privilege: Every service, user, and API key must have the minimal permissions required to function.

  • Defense in depth: Apply multiple layers of protection; do not rely on a single check (e.g., validate on both client and server).

  • Fail securely: If a security check fails, deny access and log the attempt. Never default to an insecure state.

  • Never trust user input: Treat all data from outside the service boundary (HTTP requests, message queues, file uploads) as malicious until validated.

11.2 Secret Management

  • No secrets in code or config files: Connection strings, API keys, passwords, tokens, and certificates must never be stored in source code, appsettings.json, environment.ts, or Kubernetes YAML files.

  • Accepted storage: .NET secrets manager (development only), environment variables, Azure Key Vault, HashiCorp Vault, or Kubernetes Secrets with proper RBAC.

  • Logging: Never log secrets. Review every log statement that prints a request body or dynamic value.

  • Accidental commits: If a secret is committed, consider it compromised and rotate it immediately. Rebase/rewrite history to remove it if possible, but rotation is mandatory.

11.3 C# Backend Security

  • Input validation:

    • Use data annotations ([Required], [StringLength], [Range], [EmailAddress]) or FluentValidation on all API input models.

    • Validate parameters at the start of every public method.

      [HttpPost] public async Task<IActionResult> CreateOrder([FromBody] CreateOrderRequest request) { if (!ModelState.IsValid) return BadRequest(ModelState); // ... }
  • Authentication & authorization:

    • Use OAuth2/OIDC with JWT tokens. Validate tokens properly (issuer, audience, expiry).

    • Decorate controllers/endpoints with [Authorize(Roles = "...")] or custom policies.

    • Do not implement custom authentication or hashing; rely on ASP.NET Core Identity and well-vetted libraries.

  • Cross‑Site Scripting (XSS) prevention:

    • Razor views (if any) auto-encode output. For API responses, the client is responsible for safe rendering, but the API must sanitize stored user content that could be rendered.

    • Encode output when building HTML dynamically (but prefer not to at all).

  • SQL Injection: Use Entity Framework Core or parameterized queries exclusively. Never concatenate user input into raw SQL.

  • CORS: Configure CORS to allow only known origins. Do not use AllowAnyOrigin with AllowCredentials.

  • Dependency scanning: Run dotnet list package --vulnerable or CI steps (e.g., dotnet-retire) to detect vulnerable NuGet packages.

11.4 Angular / TypeScript Frontend Security

  • Cross‑Site Scripting (XSS):

    • Angular’s built-in sanitization escapes values in interpolation ({{ }}) automatically. Do not bypass it.

    • Never use bypassSecurityTrustHtml, bypassSecurityTrustScript, bypassSecurityTrustUrl, etc. without an explicit security review and a comment explaining why it’s unavoidable and safe.

    • When rendering user‑generated content that contains HTML, sanitize it server‑side before storage, or use Angular’s DomSanitizer with extreme caution.

  • DOM manipulation: Avoid document.getElementById and innerHTML. Use Angular’s Renderer2 and template bindings. If you must set raw HTML, use [innerHTML] only with sanitized content.

  • CORS / CSRF: Angular’s HttpClient supports CSRF token mechanisms. Our backend issues a CSRF token cookie when browser‑based authentication is used; the Angular app must send it via the X-XSRF-TOKEN header. Do not disable CSRF protection on the backend for production.

  • Authentication tokens: Access tokens must be stored in HttpOnly cookies (managed by the backend) or in memory. Never store tokens in localStorage or sessionStorage unless there is no alternative (document the exception).

  • Environment‑specific rules: Production builds must disable console.log and enable CSP (Content Security Policy) headers. The index.html should not contain any secrets or feature flags that reveal internal information.

11.5 APIs and Communication

  • HTTPS only: All external endpoints must use HTTPS. Internal service‑to‑service communication should use HTTPS or mTLS where possible.

  • Rate limiting and throttling: Expose APIs only behind a gateway that enforces rate limits per client (or per user) to prevent abuse and DoS.

  • Expose minimal data: API responses must contain only the fields required by the frontend. DTOs must not leak internal fields like database IDs, internal status codes, or technical stack details.

  • Web security headers: All web applications (back-end or front-end serving) must include Content-Security-Policy, X-Content-Type-Options: nosniff, X-Frame-Options: DENY, and Strict-Transport-Security headers. These are typically configured at the ingress or reverse proxy level, but each service must verify them.

11.6 Dependency Management

  • Keep dependencies up to date: Use automated tooling (e.g., Dependabot, Renovate, or CI pipelines) to detect outdated and vulnerable packages for NuGet, npm, and Docker base images.

  • No untrusted sources: All third-party libraries must come from official registries (nuget.org, npmjs.com). Adding private registries requires approval.

  • Vulnerability scanning: All repositories must have a CI step that fails the build if a known critical/high vulnerability is detected in dependencies.

11.7 Code Review Checklist for Security

During code review, verify the following:

  • Are any secrets or sensitive values hardcoded or logged?

  • Is user input validated?

  • Are authentication and authorization checks present on all protected endpoints?

  • Are bypassSecurityTrust* calls justified and safe?

  • Are third‑party packages up to date and free of known vulnerabilities?

  • Does error handling leak internal information?

04 мая 2026