Feature/pre commit ci (#37)

* feat: add comprehensive pre-commit CI hooks

- Add safety for dependency vulnerability scanning
- Add bandit for Python security linting with appropriate skips
- Add interrogate for docstring coverage checking (60% threshold)
- Add mypy for type checking with permissive CI configuration
- Update requirements.txt with safety and bandit dependencies
- Configure all tools for CI compatibility (non-blocking for initial setup)

* security: add hardening measures based on upstream issues

- Add .gitattributes rules to force LF line endings for critical files (fixes CRLF security issues)
- Enhance document validator with MIME type validation and stricter PDF size limits
- Fix subprocess security issues by adding shell=False to prevent command injection
- Add resource exhaustion protection with separate PDF size limits (50MB vs 100MB general limit)

Addresses upstream issues:
- #97: Cross-platform deployment failures due to CRLF line endings
- #31: Large PDF processing failures and resource exhaustion
- Security hardening for subprocess calls to prevent injection attacks

* docs: streamline contribution process and pre-commit checks

- Update and format CONTRIBUTING.md for clarity

- Simplify pull request template

- Adjust pre-commit config to be more lenient locally

* chore: update .gitignore, .secrets.baseline, pyproject.toml, and requirements.txt for improved configuration and dependency management
This commit is contained in:
Scarlet Moore
2026-01-14 13:57:18 +11:00
committed by GitHub
parent 1447a5987b
commit a0433d784e
10 changed files with 477 additions and 154 deletions

17
.gitattributes vendored
View File

@@ -1 +1,18 @@
*.mp4 filter=lfs diff=lfs merge=lfs -text
# Force critical build and script files to use LF line endings for cross-platform compatibility
# This prevents CRLF-related security issues in Docker containers and shell scripts
Dockerfile text eol=lf
docker-compose.yml text eol=lf
docker-compose.*.yml text eol=lf
*.sh text eol=lf
*.py text eol=lf
*.yaml text eol=lf
*.yml text eol=lf
*.md text eol=lf
*.txt text eol=lf
*.env text eol=lf
*.json text eol=lf
*.toml text eol=lf
*.cfg text eol=lf
*.ini text eol=lf

View File

@@ -1,55 +1,35 @@
<!--
Thank you for contributing to AI-Tutor!
Please make sure your pull request is ready for review before submitting.
About this template
This template assists contributors in providing a clear and concise description of their changes. Feel free to adjust it as needed.
Thank you for contributing to DeepTutor! 🚀
Please ensure your PR is ready for review and follows our contribution guidelines.
For more details, see our [CONTRIBUTING.md](https://github.com/HKUDS/DeepTutor/blob/dev/CONTRIBUTING.md).
-->
## Description
### Description
*A clear and concise description of the changes.*
[Briefly describe the changes made in this pull request.]
### Related Issues
- Closes #...
- Related to #...
## Related Issues
### Module(s) Affected
- [ ] `agents`
- [ ] `api`
- [ ] `cli`
- [ ] `config`
- [ ] `core`
- [ ] `knowledge`
- [ ] `services`
- [ ] `web` (Frontend)
- [ ] `docs` (Documentation)
- [ ] Other: `...`
[Reference any related issues or tasks addressed by this pull request.]
- Closes #
- Related to #
### Checklist
- [ ] I have read and followed the [contribution guidelines](https://github.com/HKUDS/DeepTutor/blob/dev/CONTRIBUTING.md).
- [ ] My code follows the project's coding standards.
- [ ] I have run `pre-commit run --all-files` and fixed any issues.
- [ ] I have added relevant tests for my changes.
- [ ] I have updated the documentation (if necessary).
- [ ] My changes do not introduce any new security vulnerabilities.
## Changes Made
[List the specific changes made in this pull request.]
## Module(s) Affected
- [ ] Dashboard
- [ ] Knowledge Base Management
- [ ] Smart Solver
- [ ] Question Generator
- [ ] Deep Research
- [ ] Co-Writer
- [ ] Notebook
- [ ] Guided Learning
- [ ] Idea Generation
- [ ] API/Backend
- [ ] Frontend/Web
- [ ] Configuration
- [ ] Documentation
- [ ] Other: ___________
## Checklist
- [ ] ✅ Ran `pre-commit run --all-files` (required — CI will fail otherwise)
- [ ] Changes tested locally
- [ ] Code follows project style guidelines
- [ ] Self-review completed
- [ ] Code reviewed
- [ ] Documentation updated (if necessary)
- [ ] No new warnings generated
- [ ] Tests added/updated (if applicable)
## Additional Notes
[Add any additional notes or context for the reviewer(s).]
### Additional Notes
*Add any other context or screenshots about the pull request here.*

2
.gitignore vendored
View File

@@ -10,7 +10,6 @@ data/user/
data/knowledge_bases/
run_code_workspace/
src/agents/question/reference_papers/
tests/
# ============================================
# Python Related
@@ -86,6 +85,7 @@ outputs/
cache/
**/cache/
.cache/
.ruff_cache
# Log files
*.log

View File

@@ -16,34 +16,24 @@ repos:
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v6.0.0
hooks:
# Remove trailing whitespace
- id: trailing-whitespace
args: [--markdown-linebreak-ext=md]
exclude: ^(assets/roster/.*\.svg|.*\.min\.(js|css)|.*\.lock|.*\.log|.*\.pdf|.*\.zip|.*\.tar\.gz)
# Ensure files end with a newline
- id: end-of-file-fixer
exclude: ^(assets/roster/.*\.svg|.*\.min\.(js|css)|.*\.lock|.*\.log|.*\.pdf|.*\.zip|.*\.tar\.gz)
# Check YAML files for syntax errors
- id: check-yaml
args: [--unsafe] # Allow custom tags in YAML
# Check JSON files for syntax errors
args: [--unsafe]
- id: check-json
exclude: ^(.*\.lock|.*\.log)
# Prevent committing large files
- id: check-added-large-files
args: [--maxkb=6144]
# Detect merge conflict markers
- id: check-merge-conflict
# Detect case conflicts in file names
- id: check-case-conflict
# Check for files that would conflict in case-insensitive filesystems
- id: check-toml
# ============================================
@@ -52,33 +42,21 @@ repos:
- repo: https://github.com/astral-sh/ruff-pre-commit
rev: v0.14.7
hooks:
# Ruff linting - removing --exit-zero to ensure we catch issues before they land
- id: ruff
args: [--fix]
# Added --quiet to suppress logs; --exit-zero makes it a "soft fail" if desired
args: [--fix, --quiet, --exit-zero]
# Ruff import sorting
- id: ruff-format
args: [--quiet]
# ============================================
# Frontend code formatting and linting
# ============================================
# Note: ESLint is disabled for now due to missing config file in /web
# - repo: https://github.com/pre-commit/mirrors-eslint
# rev: v9.17.0
# hooks:
# - id: eslint
# files: ^web/.*\.(js|jsx|ts|tsx)$
# exclude: ^web/(node_modules|\.next|out|dist|build)/
# additional_dependencies:
# - eslint@^9.0.0
# - eslint-config-next@^15.0.0
# - "@eslint/eslintrc"
# args: [--fix]
- repo: https://github.com/pre-commit/mirrors-prettier
rev: v4.0.0-alpha.8
hooks:
- id: prettier
args: [--loglevel, warn]
files: ^web/.*\.(css|scss|json|jsonc|yaml|yml|md|graphql|html|ts|tsx|js|jsx)$
exclude: ^web/(node_modules|\.next|out|dist|build)/
@@ -92,3 +70,37 @@ repos:
args: ['--baseline', '.secrets.baseline']
exclude: package-lock.json
pass_filenames: false
# Replaced Safety with pip-audit due to version 3.x breakdown
- repo: https://github.com/pypa/pip-audit
rev: v2.7.3
hooks:
- id: pip-audit
args: ["--desc", "on"]
- repo: https://github.com/PyCQA/bandit
rev: 1.8.0
hooks:
- id: bandit
args: [-c, pyproject.toml, -q]
exclude: ^tests/
# ============================================
# Docstring coverage checking
# ============================================
- repo: https://github.com/econchick/interrogate
rev: 1.7.0
hooks:
- id: interrogate
args: [-v, -q, --exclude=tests/, --exclude=scripts/, --ignore-init-method, --ignore-private]
pass_filenames: false
# ============================================
# Type checking
# ============================================
- repo: https://github.com/pre-commit/mirrors-mypy
rev: v1.13.0
hooks:
- id: mypy
args: [--max-errors, "10"]
exclude: ^(tests/|scripts/)

View File

@@ -1,5 +1,5 @@
{
"version": "1.4.0",
"version": "1.5.0",
"plugins_used": [
{
"name": "ArtifactoryDetector"
@@ -26,6 +26,9 @@
{
"name": "GitHubTokenDetector"
},
{
"name": "GitLabTokenDetector"
},
{
"name": "HexHighEntropyString",
"limit": 3.0
@@ -36,6 +39,9 @@
{
"name": "IbmCosHmacDetector"
},
{
"name": "IPPublicDetector"
},
{
"name": "JwtTokenDetector"
},
@@ -49,9 +55,15 @@
{
"name": "NpmDetector"
},
{
"name": "OpenAIDetector"
},
{
"name": "PrivateKeyDetector"
},
{
"name": "PypiTokenDetector"
},
{
"name": "SendGridDetector"
},
@@ -67,6 +79,9 @@
{
"name": "StripeDetector"
},
{
"name": "TelegramBotTokenDetector"
},
{
"name": "TwilioKeyDetector"
}
@@ -76,7 +91,8 @@
"path": "detect_secrets.filters.allowlist.is_line_allowlisted"
},
{
"path": "detect_secrets.filters.common.is_baseline_file"
"path": "detect_secrets.filters.common.is_baseline_file",
"filename": ".secrets.baseline"
},
{
"path": "detect_secrets.filters.common.is_ignored_due_to_verification_policies",
@@ -110,6 +126,196 @@
"path": "detect_secrets.filters.heuristic.is_templated_secret"
}
],
"results": {},
"generated_at": "2024-01-01T00:00:00Z"
"results": {
".github/workflows/docker-publish.yml": [
{
"type": "Secret Keyword",
"filename": ".github/workflows/docker-publish.yml",
"hashed_secret": "a7c6f2bf2a1f9d8b6cd1b1c8d550b25cf6c1f970",
"is_verified": false,
"line_number": 175
}
],
"src/agents/guide/agents/interactive_agent.py": [
{
"type": "Base64 High Entropy String",
"filename": "src/agents/guide/agents/interactive_agent.py",
"hashed_secret": "559f33e318ea8360e316ec7409de63272a7daea0",
"is_verified": false,
"line_number": 74,
"is_secret": false
},
{
"type": "Base64 High Entropy String",
"filename": "src/agents/guide/agents/interactive_agent.py",
"hashed_secret": "fe9ae166dc80168f37e50564be9e45c016a48cd0",
"is_verified": false,
"line_number": 75,
"is_secret": false
},
{
"type": "Base64 High Entropy String",
"filename": "src/agents/guide/agents/interactive_agent.py",
"hashed_secret": "482f1d4d250823ce0ff5fad9dfaf0d471835aedb",
"is_verified": false,
"line_number": 76,
"is_secret": false
}
],
"src/agents/solve/main_solver.py": [
{
"type": "Secret Keyword",
"filename": "src/agents/solve/main_solver.py",
"hashed_secret": "985b05576c57bdeccfcaf33261ea1c43ce7e3155",
"is_verified": false,
"line_number": 208,
"is_secret": false
}
],
"src/api/routers/embedding_provider.py": [
{
"type": "Secret Keyword",
"filename": "src/api/routers/embedding_provider.py",
"hashed_secret": "6a7087481b65a934d9f1986d6313216eb1565b87",
"is_verified": false,
"line_number": 118,
"is_secret": false
}
],
"src/api/routers/llm_provider.py": [
{
"type": "Secret Keyword",
"filename": "src/api/routers/llm_provider.py",
"hashed_secret": "985b05576c57bdeccfcaf33261ea1c43ce7e3155",
"is_verified": false,
"line_number": 98,
"is_secret": false
}
],
"src/api/routers/system.py": [
{
"type": "Secret Keyword",
"filename": "src/api/routers/system.py",
"hashed_secret": "985b05576c57bdeccfcaf33261ea1c43ce7e3155",
"is_verified": false,
"line_number": 108,
"is_secret": false
}
],
"src/knowledge/README.md": [
{
"type": "Secret Keyword",
"filename": "src/knowledge/README.md",
"hashed_secret": "9ad19750930e5cf133e024641c00daf5fc90c700",
"is_verified": false,
"line_number": 323,
"is_secret": false
}
],
"src/tools/web_search/README.md": [
{
"type": "Secret Keyword",
"filename": "src/tools/web_search/README.md",
"hashed_secret": "b2bc1f908a5df61aee3c6badf1ab9e6bec390592",
"is_verified": false,
"line_number": 333,
"is_secret": false
},
{
"type": "Secret Keyword",
"filename": "src/tools/web_search/README.md",
"hashed_secret": "46125dd7214670fbb5f5c6b57126ae3440d207f4",
"is_verified": false,
"line_number": 690,
"is_secret": false
}
],
"src/tools/web_search/providers/baidu.py": [
{
"type": "Secret Keyword",
"filename": "src/tools/web_search/providers/baidu.py",
"hashed_secret": "46a00de6537088c80b8db3165380fcf31d441b95",
"is_verified": false,
"line_number": 30,
"is_secret": false
}
],
"src/tools/web_search/providers/exa.py": [
{
"type": "Secret Keyword",
"filename": "src/tools/web_search/providers/exa.py",
"hashed_secret": "3dae1eb41288aa0483187ef2264b4b3b27d7a5cd",
"is_verified": false,
"line_number": 38,
"is_secret": false
}
],
"src/tools/web_search/providers/jina.py": [
{
"type": "Secret Keyword",
"filename": "src/tools/web_search/providers/jina.py",
"hashed_secret": "2272f6d4bdf0da9db19a683d47cedce691a1a076",
"is_verified": false,
"line_number": 35,
"is_secret": false
}
],
"src/tools/web_search/providers/perplexity.py": [
{
"type": "Secret Keyword",
"filename": "src/tools/web_search/providers/perplexity.py",
"hashed_secret": "05e4bcd7b031cd6255f628df4f8a976559d44f06",
"is_verified": false,
"line_number": 27,
"is_secret": false
}
],
"src/tools/web_search/providers/serper.py": [
{
"type": "Secret Keyword",
"filename": "src/tools/web_search/providers/serper.py",
"hashed_secret": "41dbe0a0d71248b123de33a9faa472809514c464",
"is_verified": false,
"line_number": 39,
"is_secret": false
}
],
"src/tools/web_search/providers/tavily.py": [
{
"type": "Secret Keyword",
"filename": "src/tools/web_search/providers/tavily.py",
"hashed_secret": "46125dd7214670fbb5f5c6b57126ae3440d207f4",
"is_verified": false,
"line_number": 33,
"is_secret": false
}
],
"web/app/guide/page.tsx": [
{
"type": "Base64 High Entropy String",
"filename": "web/app/guide/page.tsx",
"hashed_secret": "559f33e318ea8360e316ec7409de63272a7daea0",
"is_verified": false,
"line_number": 159,
"is_secret": false
},
{
"type": "Base64 High Entropy String",
"filename": "web/app/guide/page.tsx",
"hashed_secret": "fe9ae166dc80168f37e50564be9e45c016a48cd0",
"is_verified": false,
"line_number": 161,
"is_secret": false
},
{
"type": "Base64 High Entropy String",
"filename": "web/app/guide/page.tsx",
"hashed_secret": "482f1d4d250823ce0ff5fad9dfaf0d471835aedb",
"is_verified": false,
"line_number": 163,
"is_secret": false
}
]
},
"generated_at": "2026-01-14T02:31:46Z"
}

View File

@@ -1,38 +1,94 @@
# Contributing to DeepTutor
Thank you for your interest in contributing to DeepTutor! We are trying to make DeepTutor smooth and robust, for every developers to develop and conribute.
Join our community for discussion and support:
Contributing to DeepTutor 🚀
Thank you for your interest in contributing to DeepTutor! We are committed to building a smooth and robust intelligent learning companion, and we welcome developers of all skill levels to join us.
Join our community for discussion, support, and collaboration:
<p align="center">
<a href="https://discord.gg/zpP9cssj"><img src="https://img.shields.io/badge/Discord-Join_Community-5865F2?style=for-the-badge&logo=discord&logoColor=white" alt="Discord"></a>&nbsp;
<a href="https://github.com/HKUDS/DeepTutor/issues/78"><img src="https://img.shields.io/badge/WeChat-Join_Group-07C160?style=for-the-badge&logo=wechat&logoColor=white" alt="WeChat"></a>&nbsp;
<a href="./Communication.md"><img src="https://img.shields.io/badge/Feishu-Join_Group-00D4AA?style=for-the-badge&logo=feishu&logoColor=white" alt="Feishu"></a>
<a href="https://discord.gg/zpP9cssj"><img src="https://img.shields.io/badge/Discord-Join_Community-5865F2?style=for-the-badge&logo=discord&logoColor=white" alt="Discord"></a>&nbsp;
<a href="https://github.com/HKUDS/DeepTutor/issues/78"><img src="https://img.shields.io/badge/WeChat-Join_Group-07C160?style=for-the-badge&logo=wechat&logoColor=white" alt="WeChat"></a>&nbsp;
<a href="./Communication.md"><img src="https://img.shields.io/badge/Feishu-Join_Group-00D4AA?style=for-the-badge&logo=feishu&logoColor=white" alt="Feishu"></a>
</p>
## Table of Contents
- [Contribution Requirements](#️-contribution-requirements)
- [Code Quality & Security](#-code-quality--security)
- [Security Best Practices](#-security-best-practices)
- [Coding Standards](#-coding-standards)
- [Development Setup](#-development-setup)
- [Commit Message Format](#-commit-message-format)
- [How to Get Started](#-how-to-get-started)
## ⚠️ Contribution Requirements
[!IMPORTANT]
All contributions must be based on the `dev` branch!
1. Fork the repository and clone it locally.
2. **Synchronize**: Always pull from the `dev` branch before starting:
```bash
git checkout dev && git pull origin dev
```
3. **Branch**: Create your feature branch from `dev`:
```bash
git checkout -b feature/your-feature-name
```
4. **PR Target**: Submit your Pull Request to the `dev` branch (not `main`).
5. **Validation**: Ensure all pre-commit checks pass before submitting.
> [!IMPORTANT]
> **All contributions must be based on the `dev` branch!**
>
> 1. Fork the repository and clone it locally
> 2. **Always pull from the `dev` branch**: `git checkout dev && git pull origin dev`
> 3. Create your feature branch from `dev`: `git checkout -b feature/your-feature`
> 4. Submit your PR to the `dev` branch (NOT `main`)
> 5. Ensure all pre-commit checks pass before submitting
## 🛠️ Code Quality & Security
We use a suite of automated tools to maintain high standards of code quality and security. These are configured via `pyproject.toml` and `.pre-commit-config.yaml`.
## 🛠️ Code Quality
### Our Toolstack
- **Ruff**: High-performance Python linting and formatting.
- **Prettier**: Consistent formatting for frontend and configuration files.
- **detect-secrets**: Scans for high-entropy strings and hardcoded secrets.
- **pip-audit**: Scans dependencies for known vulnerabilities (V3.x compatible).
- **Bandit**: Analyzes code for common security issues.
- **MyPy**: Static type checking to ensure code reliability.
- **Interrogate**: Reports docstring coverage. While it won't block your commit, please aim for high coverage.
We use automated tools to maintain code quality:
[!TIP]
Before submitting a PR, you MUST run:
```bash
pre-commit run --all-files
```
While local pre-commit hooks are configured to be lenient and may only show warnings, the CI will perform strict checks and will automatically reject PRs that fail.
- **Ruff** — Python linting & formatting (`pyproject.toml`)
- **Prettier** — Frontend formatting (`web/.prettierrc.json`)
- **detect-secrets** — Security scanning
## 🔒 Security Best Practices
### File Uploads
- **Size Limits**: General files are capped at 100MB; PDFs are capped at 50MB to prevent resource exhaustion.
- **Validation**: We enforce multi-layer validation (Extension + MIME type + Content sanitization).
- **Sanitization**: All filenames are sanitized to prevent path traversal attacks.
> [!IMPORTANT]
> **Before submitting a PR, you MUST run:** `pre-commit run --all-files`
>
> CI will automatically check this and **reject PRs** that fail pre-commit checks.
### Development Standards
- **Subprocesses**: Always use `shell=False` when calling subprocesses to prevent command injection.
- **Pathing**: Use `pathlib.Path` for all operations to ensure cross-platform (Windows/Linux/macOS) compatibility.
- **Line Endings**: LF (Unix) line endings are enforced for critical scripts via `.gitattributes`.
## 💻 Coding Standards
To keep the codebase maintainable, please follow these guidelines:
### Python Guidelines
- Use Type Hints for all function signatures.
- Prefer f-strings for string formatting.
- Follow PEP 8 (mostly enforced by Ruff/Black).
- Keep functions small and focused on a single responsibility.
### Documentation
- Every new module, class, and public function should have a docstring.
- Use the Google Python Style Guide for docstring formatting.
- Update `README.md` if your change introduces new features or configuration variables.
## ⚙️ Development Setup
<details>
<summary><b>Setting Up Your Environment (Recommended)</b></summary>
**Step 1: Create a virtual environment**
```bash
python -m venv venv
source venv/bin/activate # On Windows: venv\Scripts\activate
```
**Step 2: Install dependencies**
```bash
pip install -e ".[all]"
```
</details>
<details>
<summary><b>Setting Up Pre-commit (First Time Only)</b></summary>
@@ -46,64 +102,46 @@ pip install pre-commit
conda install -c conda-forge pre-commit
```
**Step 2: Install Git hooks (recommended)**
**Step 2: Install Git hooks**
```bash
cd DeepTutor
pre-commit install
```
> After this, hooks will run **automatically** on every commit — no need to remember!
Hooks will now run automatically on every commit.
**Step 3: Run checks on all files**
**Step 3: Initialize the Secrets Baseline**
If you encounter new "false positive" secrets (like API hash placeholders), update the baseline:
```bash
pre-commit run --all-files
detect-secrets scan > .secrets.baseline
```
</details>
### Common Commands
```bash
# Normal commit (hooks run automatically if installed)
git commit -m "Your commit message"
# Manually check all files (do this before pushing!)
pre-commit run --all-files
# Update hooks to latest versions
pre-commit autoupdate
# Skip hooks (not recommended, only for emergencies)
git commit --no-verify -m "Emergency fix"
```
| Task | Command |
|-------------------|------------------------------------------------|
| Check all files | `pre-commit run --all-files` |
| Check quietly | `pre-commit run --all-files -q` |
| Update tools | `pre-commit autoupdate` |
| Emergency skip | `git commit --no-verify -m "message"` (Not recommended) |
## 📋 Commit Message Format
We follow a structured commit format to maintain a clean history:
```
<type>: <short description>
[optional body]
[optional footer(s)]
```
**Types**: `feat`, `fix`, `docs`, `style`, `refactor`, `test`, `chore`
- `feat`: A new feature (corresponds to a MINOR version bump).
- `fix`: A bug fix (corresponds to a PATCH version bump).
- `docs`: Documentation only changes.
- `style`: Changes that do not affect the meaning of the code (formatting, missing semi-colons, etc).
- `refactor`: A code change that neither fixes a bug nor adds a feature.
- `test`: Adding missing tests or correcting existing tests.
- `chore`: Routine tasks (updating build processes, etc).
**Examples**:
- `feat: for a new feature. This typically corresponds to a MINOR version bump in Semantic Versioning.`
- `fix: for a bug fix. This typically corresponds to a PATCH version bump.`
- `chore: for routine tasks that do not modify source code or tests (e.g., updating build processes).`
- `docs: for documentation-only changes.`
- `style: for changes that do not affect the meaning of the code (e.g., whitespace, semicolons).`
- `refactor: for code changes that neither fix a bug nor add a feature.`
- `test: for adding missing tests or correcting existing tests.`
---
## 💡 How to Get Started
1. Browse our [Issues](https://github.com/HKUDS/DeepTutor/issues) for tasks labeled `good first issue`.
2. Comment on the issue to let others know you're working on it.
3. Follow the process above and submit your PR!
### 💡 How to Get Started
1. Check our [Issues](https://github.com/HKUDS/DeepTutor/issues) for tasks labeled `good first issue` or `help wanted`
2. Comment on the issue you'd like to work on
3. Follow the contribution process above
4. Join our [Discord](https://discord.gg/aka9p9EW) if you have questions!
---
### Let's build DeepTutor TOGETHER! 🚀
Questions? Reach out on Discord.
Let's build the future of AI tutoring together! 🚀

View File

@@ -180,3 +180,35 @@ addopts = [
"--disable-warnings",
"--tb=short"
]
# ============================================
# MyPy type checking configuration
# ============================================
[tool.mypy]
python_version = "3.10"
# Only show the summary line if there are errors
pretty = false
show_error_context = false
# Limit the number of errors shown
max_errors = 10
warn_return_any = true
warn_no_return = true
show_error_codes = true
ignore_missing_imports = true
follow_imports = "silent"
# Module-specific overrides
[[tool.mypy.overrides]]
module = "tests.*"
ignore_errors = true
[[tool.mypy.overrides]]
module = "src.tools.*"
ignore_errors = true # Some tools may have dynamic imports
# ============================================
# Bandit security linting configuration
# ============================================
[tool.bandit]
exclude_dirs = ["tests", "scripts"]
skips = ["B101", "B311", "B403", "B404"] # B101=assert, B311=random, B403/B404=pickle/subprocess imports

View File

@@ -67,6 +67,8 @@ PyMuPDF>=1.26.0 # For PDF text extraction (fast and reliable)
# Development tools
# ============================================
pre-commit>=3.0.0
safety>=2.4.0,<3.0.0 # Pin to stable 2.x version, 3.0.0 is broken
bandit>=1.8.0
llama-cloud==0.1.35
llama-cloud-services==0.6.54
llama-index==0.14.12

View File

@@ -16,7 +16,7 @@ def check_mineru_installed():
"""Check if MinerU is installed"""
try:
result = subprocess.run(
["magic-pdf", "--version"], check=False, capture_output=True, text=True
["magic-pdf", "--version"], check=False, capture_output=True, text=True, shell=False
)
if result.returncode == 0:
return "magic-pdf"
@@ -25,7 +25,7 @@ def check_mineru_installed():
try:
result = subprocess.run(
["mineru", "--version"], check=False, capture_output=True, text=True
["mineru", "--version"], check=False, capture_output=True, text=True, shell=False
)
if result.returncode == 0:
return "mineru"
@@ -96,7 +96,7 @@ def parse_pdf_with_mineru(pdf_path: str, output_base_dir: str = None):
print(f"🔧 Executing command: {' '.join(cmd)}")
result = subprocess.run(cmd, capture_output=True, text=True, check=False)
result = subprocess.run(cmd, capture_output=True, text=True, check=False, shell=False)
if result.returncode != 0:
print("✗ MinerU parsing failed:")

View File

@@ -4,6 +4,7 @@
Document Validator - Validation utilities for document uploads
"""
import mimetypes
import os
import re
from typing import ClassVar
@@ -15,6 +16,9 @@ class DocumentValidator:
# Maximum file size in bytes (100MB)
MAX_FILE_SIZE: ClassVar[int] = 100 * 1024 * 1024
# Maximum file size for PDF processing (50MB to prevent resource exhaustion)
MAX_PDF_SIZE: ClassVar[int] = 50 * 1024 * 1024
# Allowed file extensions
ALLOWED_EXTENSIONS: ClassVar[set[str]] = {
".pdf",
@@ -34,6 +38,25 @@ class DocumentValidator:
".ppt",
}
# MIME type mapping for additional validation
ALLOWED_MIME_TYPES: ClassVar[set[str]] = {
"application/pdf",
"text/plain",
"text/markdown",
"application/msword",
"application/vnd.openxmlformats-officedocument.wordprocessingml.document",
"application/rtf",
"text/html",
"application/xml",
"text/xml",
"application/json",
"text/csv",
"application/vnd.ms-excel",
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
"application/vnd.ms-powerpoint",
"application/vnd.openxmlformats-officedocument.presentationml.presentation",
}
@staticmethod
def validate_upload_safety(
filename: str, file_size: int | None, allowed_extensions: set[str] | None = None
@@ -58,6 +81,13 @@ class DocumentValidator:
f"File too large: {file_size} bytes. Maximum allowed: {DocumentValidator.MAX_FILE_SIZE} bytes"
)
# Additional size check for PDFs to prevent resource exhaustion
_, ext = os.path.splitext(filename.lower())
if ext == ".pdf" and file_size is not None and file_size > DocumentValidator.MAX_PDF_SIZE:
raise ValueError(
f"PDF file too large: {file_size} bytes. Maximum allowed for PDFs: {DocumentValidator.MAX_PDF_SIZE} bytes"
)
# Sanitize filename - remove path components and dangerous characters
# Extract just the filename, removing any path components
safe_name = os.path.basename(filename)
@@ -70,13 +100,19 @@ class DocumentValidator:
raise ValueError("Invalid filename")
# Check file extension
_, ext = os.path.splitext(safe_name.lower())
exts_to_check = allowed_extensions or DocumentValidator.ALLOWED_EXTENSIONS
if ext not in exts_to_check:
raise ValueError(
f"Unsupported file type: {ext}. Allowed types: {', '.join(exts_to_check)}"
)
# Additional MIME type validation for security
guessed_mime, _ = mimetypes.guess_type(filename)
if guessed_mime and guessed_mime not in DocumentValidator.ALLOWED_MIME_TYPES:
raise ValueError(
f"MIME type validation failed: {guessed_mime}. File may be malicious or corrupted."
)
return safe_name
@staticmethod