From 1782c29b952f64b429a77194d752ae9c0dba12a0 Mon Sep 17 00:00:00 2001 From: Mark Eaton Date: Wed, 11 Nov 2026 14:32:53 -0500 Subject: [PATCH] move skills out of this repo --- skills/FLASK-SECURITY.md | 206 ------------------- skills/PYTEST-ADVANCED.md | 276 ------------------------- skills/PYTEST.md | 177 ---------------- skills/VUE.md | 412 -------------------------------------- 4 files changed, 1071 deletions(-) delete mode 100644 skills/FLASK-SECURITY.md delete mode 100644 skills/PYTEST-ADVANCED.md delete mode 100644 skills/PYTEST.md delete mode 100644 skills/VUE.md diff --git a/skills/FLASK-SECURITY.md b/skills/FLASK-SECURITY.md deleted file mode 100644 index 03488a0..0000000 --- a/skills/FLASK-SECURITY.md +++ /dev/null @@ -1,206 +0,0 @@ -# Flask Security Audit - -Perform a security audit of this Flask (or Quart) application. Work through each section below, report findings, and fix issues. At the end, provide a summary with a letter grade for each area. - -## Instructions - -- Audit the project against every section below. -- For each section, report: what is already correct, what needs fixing, and what is not applicable. -- Fix all issues you find. If a fix would be disruptive or ambiguous, describe the fix and ask before applying it. -- At the end, produce a **Security Audit Summary** table with a letter grade (A-F) for each section. - ---- - -## 1. Resource Limits (DoS Prevention) - -Verify these Flask config values are set explicitly (not left at defaults): - -```python -app.config['MAX_CONTENT_LENGTH'] = # e.g. 16 * 1024 * 1024 for 16MB -app.config['MAX_FORM_MEMORY_SIZE'] = # default 500kB -app.config['MAX_FORM_PARTS'] = # default 1000 -``` - -- `MAX_CONTENT_LENGTH` has no default — it **must** be set. -- Consider the app's actual needs when choosing values. - ---- - -## 2. Cross-Site Scripting (XSS) - -Check for these common XSS pitfalls: - -- **Unquoted HTML attributes** — all template attributes must be quoted: ``, never ``. -- **`Markup()` on user input** — never call `Markup()` or `|safe` on user-submitted data. -- **HTML generated outside Jinja** — any HTML built in Python code must be escaped. -- **Uploaded files served as HTML** — uploaded files should be served with `Content-Disposition: attachment` or stored with validated content types. -- **`javascript:` URIs** — if any `href` or `src` attribute uses a user-controlled value, validate that it starts with `http://`, `https://`, or `/`. Enforce via CSP as well. - ---- - -## 3. Cross-Site Request Forgery (CSRF) - -Flask has no built-in CSRF protection. Verify that: - -- A CSRF library is in use (e.g. Flask-WTF's `CSRFProtect`, or equivalent). -- All state-changing forms include CSRF tokens. -- AJAX state-changing requests include CSRF tokens in headers. -- If no CSRF protection exists, add it using Flask-WTF: - -```python -from flask_wtf.csrf import CSRFProtect -csrf = CSRFProtect(app) -``` - -```html -
- - ... -
-``` - ---- - -## 4. Security Headers - -Check that the following response headers are set. Recommend Flask-Talisman if headers are missing or manually managed: - -| Header | Required Value | -|--------|---------------| -| `Strict-Transport-Security` | `max-age=31536000; includeSubDomains` | -| `Content-Security-Policy` | See Section 5 below | -| `X-Content-Type-Options` | `nosniff` | -| `X-Frame-Options` | `DENY` or `SAMEORIGIN` | - -If Flask-Talisman is not in use, suggest adding it: - -```python -from flask_talisman import Talisman -Talisman(app, content_security_policy=csp) -``` - ---- - -## 5. Content Security Policy (CSP) - -Audit the CSP and make it as restrictive as possible. Apply these principles: - -- Start from `default-src 'self'` and only open directives that the app actually needs. -- **Never allow** `unsafe-inline` for `script-src` unless absolutely unavoidable. Prefer nonces or hashes. -- **Never allow** `unsafe-eval` for `script-src`. -- Avoid wildcard (`*`) origins — list specific domains. -- Set `form-action 'self'` to prevent form hijacking. -- Set `frame-ancestors 'none'` (or `'self'`) to prevent clickjacking (replaces X-Frame-Options). -- Set `base-uri 'self'` to prevent base tag hijacking. -- Set `object-src 'none'` to block plugins. - -Provide: -1. The current CSP (or note its absence). -2. A recommended CSP with explanations for each directive. -3. A letter grade (A-F) assessing how restrictive the CSP is. - ---- - -## 6. Cookie and Session Security - -Verify these session/cookie configuration values: - -```python -app.config.update( - SESSION_COOKIE_SECURE=True, # cookies sent over HTTPS only - SESSION_COOKIE_HTTPONLY=True, # no JavaScript access to session cookie - SESSION_COOKIE_SAMESITE='Lax', # CSRF protection for cookies - PERMANENT_SESSION_LIFETIME=600, # session timeout in seconds -) -``` - -Also check: -- Any manually set cookies (`response.set_cookie(...)`) should use `secure=True`, `httponly=True`, and `samesite='Lax'`. -- Sessions are cleared on login (`session.clear()` before setting new session data). -- `SECRET_KEY` is cryptographically random and not hardcoded (see Section 7). - ---- - -## 7. Secrets Management - -Verify that: - -- **No secrets are hardcoded** in source files. Search for: `SECRET_KEY`, `PASSWORD`, `API_KEY`, `TOKEN`, database URIs with credentials, and similar patterns. -- All secrets are loaded from environment variables. -- A `.env` file exists for local development, and `.env` is listed in `.gitignore`. -- Use `python-dotenv` to load the `.env` file: - -```python -from dotenv import load_dotenv -load_dotenv() - -app.config['SECRET_KEY'] = os.environ['SECRET_KEY'] -``` - -- Create `.gitignore` if it does not exist. Ensure `.env` is in it. -- If a `.env.example` file does not exist, create one with placeholder values (never real secrets). - ---- - -## 8. CORS Configuration - -If CORS is configured (e.g. via Flask-CORS), review and explain: - -- Which origins are allowed. Flag `*` (allow-all) as a problem unless this is a fully public API. -- Which methods and headers are allowed. -- Whether `supports_credentials=True` is set — this is dangerous with broad origins. -- If CORS is not needed, confirm it is not enabled. - ---- - -## 9. Host Header Validation - -Check that trusted hosts are configured to prevent host header poisoning: - -```python -app.config['TRUSTED_HOSTS'] = ['example.com', 'www.example.com'] -``` - -If the app runs behind a reverse proxy, verify `ProxyFix` is configured correctly: - -```python -from werkzeug.middleware.proxy_fix import ProxyFix -app.wsgi_app = ProxyFix(app.wsgi_app, x_for=1, x_proto=1, x_host=1) -``` - ---- - -## 10. Additional Checks - -- **Debug mode**: Verify `app.debug` is `False` and `FLASK_DEBUG` is not set to `1` in production config. -- **JSON security**: If the app returns JSON arrays at top level, confirm this is intentional. -- **File uploads**: If file uploads exist, verify filenames are sanitized with `werkzeug.utils.secure_filename()`. -- **SQL injection**: If raw SQL is used, verify parameterized queries. Flag any string concatenation/formatting in SQL. -- **Dependency vulnerabilities**: Run `pip audit` or `safety check` if available and report results. - ---- - -## Security Audit Summary - -After completing all sections, produce a summary in this format: - -| Section | Grade | Notes | -|---------|-------|-------| -| 1. Resource Limits | ? | | -| 2. XSS Prevention | ? | | -| 3. CSRF Protection | ? | | -| 4. Security Headers | ? | | -| 5. Content Security Policy | ? | | -| 6. Cookie/Session Security | ? | | -| 7. Secrets Management | ? | | -| 8. CORS Configuration | ? | | -| 9. Host Header Validation | ? | | -| 10. Additional Checks | ? | | -| **Overall** | **?** | | - -Grading scale: -- **A**: Best practices fully implemented -- **B**: Mostly good, minor improvements possible -- **C**: Functional but missing important protections -- **D**: Significant security gaps -- **F**: Critical vulnerabilities present diff --git a/skills/PYTEST-ADVANCED.md b/skills/PYTEST-ADVANCED.md deleted file mode 100644 index 147678e..0000000 --- a/skills/PYTEST-ADVANCED.md +++ /dev/null @@ -1,276 +0,0 @@ -# Pytest TDD Workflow — Advanced - -This skill extends the core PYTEST skill with advanced testing techniques. Use when the basic red-green-refactor cycle is comfortable and you need fixtures, parametrize, mocking, or Flask/Quart test patterns. - -**All rules from the core PYTEST skill still apply** — always follow red-green-refactor, always write the test first. - -## Instructions - -- Follow the red-green-refactor cycle for every piece of functionality. -- Use the techniques below when they genuinely simplify or improve tests. -- Run tests after every change. - ---- - -## 1. Fixtures - -Use fixtures for setup code that multiple tests share. - -### Basic fixture - -```python -# tests/conftest.py -import pytest - -@pytest.fixture -def sample_user(): - return User(name="alice", email="alice@example.com") -``` - -```python -# tests/test_models.py -def test_user_display_name(sample_user): - assert sample_user.display_name == "alice" -``` - -### Yield fixtures for setup/teardown - -```python -@pytest.fixture -def db_session(): - session = create_session() - yield session - session.rollback() - session.close() -``` - -### Fixture scope - -| Scope | Lifetime | Use when | -|-------|----------|----------| -| `"function"` (default) | Each test | Most cases — tests stay isolated | -| `"class"` | Each test class | Grouping related tests with shared setup | -| `"module"` | Each test file | Expensive setup shared across a file | -| `"session"` | Entire test run | Very expensive one-time setup (e.g. database creation) | - -Prefer `function` scope. Only widen scope when setup is genuinely expensive and tests do not mutate shared state. - -### conftest.py organization - -- `tests/conftest.py` — fixtures used across the entire test suite -- `tests/api/conftest.py` — fixtures specific to API tests -- Fixtures in a `conftest.py` are available to all tests in that directory and below - ---- - -## 2. Flask/Quart Test Patterns - -### App factory fixture - -```python -# tests/conftest.py -import pytest -from myapp import create_app - -@pytest.fixture -def app(): - app = create_app({ - "TESTING": True, - "SECRET_KEY": "test-secret-key", - }) - yield app - -@pytest.fixture -def client(app): - return app.test_client() - -@pytest.fixture -def runner(app): - return app.test_cli_runner() -``` - -### Testing routes - -```python -def test_homepage_returns_200(client): - response = client.get("/") - assert response.status_code == 200 - -def test_homepage_contains_title(client): - response = client.get("/") - assert b"Welcome" in response.data -``` - -### Testing POST requests and forms - -```python -def test_login_with_valid_credentials(client): - response = client.post("/login", data={ - "username": "alice", - "password": "correct-password", - }, follow_redirects=True) - assert response.status_code == 200 -``` - -### Testing JSON APIs - -```python -def test_api_returns_user_list(client): - response = client.get("/api/users") - assert response.status_code == 200 - data = response.get_json() - assert isinstance(data, list) -``` - -### Testing with application context - -```python -def test_db_query_within_app_context(app): - with app.app_context(): - users = User.query.all() - assert len(users) >= 0 -``` - -### Testing with request context - -```python -def test_url_generation(app): - with app.test_request_context(): - assert url_for("index") == "/" -``` - -### Quart async tests - -For Quart applications, use `pytest-asyncio`: - -```python -import pytest - -@pytest.fixture -def app(): - app = create_app({"TESTING": True}) - return app - -@pytest.fixture -def client(app): - return app.test_client() - -@pytest.mark.asyncio -async def test_homepage(client): - response = await client.get("/") - assert response.status_code == 200 -``` - ---- - -## 3. Parametrize - -Use `@pytest.mark.parametrize` to test multiple inputs without duplicating test functions. - -### Basic parametrize - -```python -@pytest.mark.parametrize("input_val, expected", [ - ("alice", True), - ("", False), - ("a" * 256, False), - ("bob@", False), -]) -def test_is_valid_username(input_val, expected): - assert is_valid_username(input_val) == expected -``` - -### Testing edge cases systematically - -Think about these categories for each function: - -- **Valid inputs** — normal cases that should succeed -- **Boundary values** — empty strings, zero, max length, off-by-one -- **Invalid inputs** — wrong types, malformed data, None -- **Error cases** — inputs that should raise specific exceptions - -```python -@pytest.mark.parametrize("amount, expected", [ - (100, "$1.00"), # normal - (0, "$0.00"), # zero - (1, "$0.01"), # minimum - (99999, "$999.99"), # large value -]) -def test_format_currency(amount, expected): - assert format_currency(amount) == expected - -@pytest.mark.parametrize("amount", [-1, -100]) -def test_format_currency_rejects_negative(amount): - with pytest.raises(ValueError): - format_currency(amount) -``` - ---- - -## 4. Mocking - -### When to mock - -- **Mock**: external services (APIs, email, payment), system clock, file system operations, slow or nondeterministic operations. -- **Don't mock**: your own code under test, data structures, pure functions. Prefer real objects when practical. - -### monkeypatch (preferred for simple cases) - -```python -def test_get_api_data(monkeypatch): - def mock_get(url): - return MockResponse(json_data={"result": "ok"}) - - monkeypatch.setattr("myapp.services.requests.get", mock_get) - data = get_api_data() - assert data["result"] == "ok" -``` - -### monkeypatch for environment variables - -```python -def test_config_reads_env(monkeypatch): - monkeypatch.setenv("SECRET_KEY", "test-key") - config = load_config() - assert config.secret_key == "test-key" -``` - -### unittest.mock for complex cases - -```python -from unittest.mock import patch, MagicMock - -@patch("myapp.services.send_email") -def test_registration_sends_welcome_email(mock_send): - register_user("alice@example.com") - mock_send.assert_called_once_with( - to="alice@example.com", - subject="Welcome", - ) -``` - ---- - -## 5. Test Quality Checklist - -After completing a set of tests, review against this checklist: - -- [ ] **Every public function/route has at least one test.** -- [ ] **Tests are isolated** — no test depends on another test's state or execution order. -- [ ] **No hardcoded paths or ports** — use fixtures and configuration. -- [ ] **Assertions are specific** — test exact values, not just truthiness (`assert x == 5`, not `assert x`). -- [ ] **Error paths are tested** — not just the happy path. -- [ ] **Test names describe behavior** — someone reading only test names understands what the code does. -- [ ] **Fixtures are minimal** — each fixture sets up only what is needed, no "god fixtures" with everything. -- [ ] **No logic in tests** — tests should not contain `if`, `for`, or `try/except`. Each test is a straight line. -- [ ] **Mocks are focused** — only mock what is necessary. Over-mocking makes tests brittle. -- [ ] **Tests run fast** — the full suite completes in seconds. Slow tests indicate missing mocks or unnecessary I/O. - -### Running with coverage - -```bash -uv add --dev pytest-cov -pytest --cov=src --cov-report=term-missing -v -``` - -Report untested lines and suggest tests for them. diff --git a/skills/PYTEST.md b/skills/PYTEST.md deleted file mode 100644 index f9e5e82..0000000 --- a/skills/PYTEST.md +++ /dev/null @@ -1,177 +0,0 @@ -# Pytest TDD Workflow - -Guide development using test-driven development (TDD) with pytest. Always write the test first, watch it fail, then write the minimal code to make it pass. - -**Keep things simple.** Use plain `assert` statements, simple test functions, and avoid advanced patterns unless the user asks for them. When more advanced techniques (fixtures, parametrize, mocking) would help, briefly explain what they are and suggest the PYTEST-ADVANCED skill. - -## Instructions - -- **Never write implementation code before its test exists and fails.** -- Follow the red-green-refactor cycle below for each unit of functionality. -- Run tests after every change. -- If the project lacks pytest configuration, set it up first (Section 2). -- Explain each step as you go — the user is learning TDD. - ---- - -## 1. The Red-Green-Refactor Cycle - -Repeat this cycle for every piece of functionality: - -### Red — Write a failing test -1. Write a test that describes the desired behavior. -2. Run the test. **Confirm it fails.** -3. Check that it fails for the *right reason* (e.g. `AssertionError`, not `SyntaxError`). - -### Green — Make it pass -4. Write the **minimum** code needed to make the test pass. No more. -5. Run the test. **Confirm it passes.** - -### Refactor — Clean up -6. Improve the code (remove duplication, clarify names) while keeping all tests green. -7. Run tests after each change. - -**Label each phase** (Red/Green/Refactor) when presenting work so the workflow is visible. - ---- - -## 2. Project Setup - -### Directory layout - -``` -project/ -├── src/ -│ └── myapp/ -│ └── __init__.py -├── tests/ -│ └── test_myapp.py -└── pyproject.toml -``` - -### pyproject.toml - -If pytest config does not exist, add it: - -```toml -[tool.pytest.ini_options] -testpaths = ["tests"] -addopts = "-v --tb=short" -``` - -### Install pytest - -```bash -uv add --dev pytest -``` - ---- - -## 3. Writing the Failing Test (Red) - -### Naming - -- Test files: `test_.py` -- Test functions: `test_` — describe *what* is being tested - -```python -# Good — describes behavior -def test_new_user_has_default_role(): - ... - -def test_login_rejects_invalid_password(): - ... - -# Bad — describes implementation -def test_user_init(): - ... -``` - -### One test at a time - -Write a single test, run it, see it fail, then implement. Do not write a batch of tests upfront. - -### Assert clearly - -Use plain `assert` — pytest provides detailed failure messages automatically. - -```python -def test_new_user_has_default_role(): - user = User(name="alice") - assert user.role == "viewer" -``` - -### Run and confirm failure - -```bash -pytest tests/test_myapp.py::test_new_user_has_default_role -v -``` - -Read the error. Make sure it's the failure you expect before moving on. - ---- - -## 4. Making the Test Pass (Green) - -Write the **minimal** implementation to make the test pass. - -- Don't add features the test doesn't require. -- Don't handle edge cases that aren't tested yet. -- It's fine to hard-code a return value if only one test exists — the next test will force a real implementation. - -Run the full test suite: - -```bash -pytest -v -``` - -All tests must pass before moving on. - ---- - -## 5. Refactor - -With all tests green, clean up: - -- Remove duplication. -- Rename for clarity. -- Simplify logic. - -**Run tests after every change.** If something breaks, undo and try a smaller step. - -Don't add new behavior during refactoring. If you spot missing behavior, go back to Red. - ---- - -## 6. Testing Exceptions - -When a function should raise an error, test for it: - -```python -import pytest - -def test_divide_by_zero_raises(): - with pytest.raises(ZeroDivisionError): - divide(1, 0) -``` - ---- - -## 7. Test Quality Checklist - -After completing a set of tests, review: - -- [ ] **Every public function has at least one test.** -- [ ] **Tests are isolated** — no test depends on another test running first. -- [ ] **Assertions are specific** — test exact values (`assert x == 5`, not `assert x`). -- [ ] **Error paths are tested** — not just the happy path. -- [ ] **Test names describe behavior** — reading only test names tells you what the code does. -- [ ] **No logic in tests** — no `if`, `for`, or `try/except` in test functions. -- [ ] **Tests run fast.** - -### Running with coverage - -```bash -uv add --dev pytest-cov -pytest --cov=src --cov-report=term-missing -v -``` diff --git a/skills/VUE.md b/skills/VUE.md deleted file mode 100644 index 5d19406..0000000 --- a/skills/VUE.md +++ /dev/null @@ -1,412 +0,0 @@ -# Vue.js Basics - -Guide Vue.js development using Vue 3 loaded via CDN. **No build process.** No Vite, no npm, no .vue single-file components. Import Vue and any other libraries via ` - - - -``` - -Key points: -- Vue script tag goes before `app.js` so Vue is available when your code runs. -- The `
` is where Vue mounts — everything inside it becomes a Vue template. -- Use `vue.global.js` (not `vue.esm-browser.js`) for script-tag usage. - ---- - -## 2. Creating an App - -### Minimal app - -```js -// js/app.js -const app = Vue.createApp({ - data() { - return { - message: "Hello, Vue!", - }; - }, -}); - -app.mount("#app"); -``` - -```html - -

{{ message }}

-``` - -### Options explained - -| Option | Purpose | -|--------|---------| -| `data()` | Returns an object of reactive state. Must be a function. | -| `methods` | Object of functions the template can call. | -| `computed` | Object of derived values that update automatically. | -| `watch` | Object of functions that run when a data property changes. | -| `mounted()` | Lifecycle hook — runs after the app is inserted into the page. | - ---- - -## 3. Template Basics - -### Text interpolation - -```html -

{{ message }}

-

{{ count + 1 }}

-

{{ items.length > 0 ? "Has items" : "Empty" }}

-``` - -Double curly braces `{{ }}` output the value of a JavaScript expression. The expression is reactive — the page updates automatically when the data changes. - -### Attribute binding — `v-bind` (shorthand `:`) - -```html - -Link - - -Link - - -``` - -Use `:` to bind any HTML attribute to a data property. - -### Conditional rendering — `v-if` / `v-else-if` / `v-else` - -```html -

No items yet.

-

One item.

-

{{ items.length }} items.

-``` - -`v-if` removes or adds elements from the DOM. Use `v-show` instead if you need to toggle visibility frequently (it uses CSS `display: none`). - -### List rendering — `v-for` - -```html -
    -
  • - {{ item.name }} -
  • -
-``` - -**Always provide a `:key`** — Vue uses it to track which items changed. Use a unique identifier, not the array index. - -### Two-way binding — `v-model` - -```html - -

You typed: {{ searchQuery }}

-``` - -`v-model` syncs an input's value with a data property. Works on ``, `