marktacular/vs-python-secure icon
public
Published on 6/4/2025
Secure Python Coding Style

Builds on the standard style but adds a strong focus on minimizing security risks. Emphasizes input validation, safe file handling, privilege boundaries, and avoiding unsafe patterns (e.g., eval, insecure subprocess usage). Designed for systems exposed to untrusted data or users.

Rules

You are writing production-grade Python code for network monitoring and diagnostics.

Development Principles

  • Prioritize clarity, modularity, and security
  • Minimize privilege: never assume admin/root rights
  • Always validate external input (filenames, IPs, arguments)
  • Handle system calls with care — prefer libraries over subprocess when possible
  • Treat all file, socket, and network access as untrusted

Secure Coding Guidelines

  • Use pathlib.Path for secure and cross-platform file paths
  • Avoid eval(), exec(), or pickle unless absolutely necessary
  • Validate all arguments passed to shell/system calls
  • Use subprocess.run(..., check=True, text=True) with explicit argument lists
  • Log errors and unexpected states using the logging module, never print()
  • Use secrets instead of random for token generation or sensitive data
  • Prefer with blocks for all file/network/socket operations
  • Use try/except blocks with specific exception classes (avoid bare except:)

Type Safety and Structure

  • Use type hints (def foo(x: int) -> str:) and enforce with mypy
  • Include a docstring for every function/class/module (Google or NumPy format)
  • Use constants and enums to eliminate magic values
  • Ensure all script logic is guarded with if __name__ == "__main__":
  • External configurations should be loaded via .env or structured YAML, not hardcoded

Tooling & Linting

  • Use black for formatting
  • Use ruff or flake8 for linting
  • Use mypy for static typing
  • Use bandit to scan for security issues
  • Use pylint for stricter structural feedback

Testing and CI

  • All testable logic must be in importable modules, not embedded in scripts
  • Use pytest with mocker, monkeypatch, or unittest.mock for isolating side effects
  • Tests must cover both expected and invalid inputs
  • Add a Makefile or noxfile for test/lint/type-check automation

Response Format

  • Explain the rationale behind non-obvious changes
  • Include input validation and error handling where appropriate
  • Avoid adding new dependencies without justifying their security implications