Merge branch 'main' into fastapi-port
Brings the Flask-era commits (incl. PR #43 video demo) into the port branch so the PR can merge cleanly. Conflicts resolved in favor of the FastAPI port: Dockerfile, README.md, requirements.txt, .gitignore (superset). .dockerignore is a union of both apps' exclusions. The old Flask app (app.py, templates/, static/, docker-compose.yml, demo.mp4, pyproject.toml) is kept in the tree for reference.
This commit is contained in:
commit
6b51dbe2ff
@ -1,5 +1,20 @@
|
||||
.git
|
||||
.gitignore
|
||||
__pycache__
|
||||
*.pyc
|
||||
.pytest_cache
|
||||
.venv
|
||||
venv
|
||||
*.md
|
||||
Dockerfile
|
||||
docker-compose.yml
|
||||
docker-compose.override.yml
|
||||
.env
|
||||
.dockerignore
|
||||
.archllm-progress.json
|
||||
*.meta.json
|
||||
demo/
|
||||
data/
|
||||
store/
|
||||
uploads/
|
||||
tests/
|
||||
ui/
|
||||
|
||||
5
.env.example
Normal file
5
.env.example
Normal file
@ -0,0 +1,5 @@
|
||||
# Server port exposed on host (maps to container port 8080)
|
||||
PORT=9780
|
||||
|
||||
# Secret key for Flask sessions - generate with: python3 -c "import secrets; print(secrets.token_hex(32))"
|
||||
SECRET_KEY=change-me-to-a-random-secret
|
||||
143
.gitea/workflows/ci.yml
Normal file
143
.gitea/workflows/ci.yml
Normal file
@ -0,0 +1,143 @@
|
||||
name: CI
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main, master]
|
||||
pull_request:
|
||||
branches: [main, master]
|
||||
|
||||
env:
|
||||
GITEA_URL: https://git.example.com
|
||||
|
||||
jobs:
|
||||
lint:
|
||||
runs-on: ubuntu-latest
|
||||
container:
|
||||
image: gitea-job-image
|
||||
steps:
|
||||
- name: Clone repo
|
||||
run: |
|
||||
rm -rf $GITHUB_WORKSPACE/*
|
||||
git clone --depth 1 $GITEA_URL/$GITHUB_REPOSITORY $GITHUB_WORKSPACE
|
||||
git -C $GITHUB_WORKSPACE checkout $GITHUB_SHA 2>/dev/null || true
|
||||
|
||||
- name: Run ruff (Python lint)
|
||||
if: always()
|
||||
run: |
|
||||
if [[ -f pyproject.toml ]]; then
|
||||
pip3 install ruff
|
||||
ruff check .
|
||||
else
|
||||
echo "No Python project detected, skipping ruff"
|
||||
fi
|
||||
|
||||
- name: Run npm lint (JS/TS)
|
||||
if: always()
|
||||
run: |
|
||||
if [[ -f package.json ]]; then
|
||||
npm ci
|
||||
npm run lint --if-present || true
|
||||
else
|
||||
echo "No Node.js project detected, skipping npm lint"
|
||||
fi
|
||||
|
||||
test:
|
||||
runs-on: ubuntu-latest
|
||||
container:
|
||||
image: gitea-job-image
|
||||
steps:
|
||||
- name: Clone repo
|
||||
run: |
|
||||
rm -rf $GITHUB_WORKSPACE/*
|
||||
git clone --depth 1 $GITEA_URL/$GITHUB_REPOSITORY $GITHUB_WORKSPACE
|
||||
git -C $GITHUB_WORKSPACE checkout $GITHUB_SHA 2>/dev/null || true
|
||||
|
||||
- name: Run pytest (Python)
|
||||
if: always()
|
||||
run: |
|
||||
if [[ -f pyproject.toml ]]; then
|
||||
python3 -m pip install --upgrade pip
|
||||
pip3 install -e ".[dev]" 2>/dev/null || pip3 install -e . 2>/dev/null || true
|
||||
pip3 install pytest
|
||||
pytest tests/ -v --tb=short 2>/dev/null || true
|
||||
else
|
||||
echo "No Python project detected, skipping pytest"
|
||||
fi
|
||||
|
||||
- name: Run npm test (JS/TS)
|
||||
if: always()
|
||||
run: |
|
||||
if [[ -f package.json ]]; then
|
||||
npm ci
|
||||
npm run test --if-present || true
|
||||
else
|
||||
echo "No Node.js project detected, skipping npm test"
|
||||
fi
|
||||
|
||||
- name: Run Go tests
|
||||
if: always()
|
||||
run: |
|
||||
if [[ -f go.mod ]]; then
|
||||
go test ./...
|
||||
else
|
||||
echo "No Go project detected, skipping go test"
|
||||
fi
|
||||
|
||||
docker-build:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Clone repo
|
||||
run: |
|
||||
rm -rf $GITHUB_WORKSPACE/*
|
||||
git clone --depth 1 $GITEA_URL/$GITHUB_REPOSITORY $GITHUB_WORKSPACE
|
||||
git -C $GITHUB_WORKSPACE checkout $GITHUB_SHA 2>/dev/null || true
|
||||
|
||||
- name: Build Docker image
|
||||
if: always()
|
||||
run: |
|
||||
if [[ -f Dockerfile ]]; then
|
||||
docker build -t $GITHUB_REPOSITORY:test .
|
||||
else
|
||||
echo "No Dockerfile found, skipping docker build"
|
||||
fi
|
||||
|
||||
security:
|
||||
runs-on: ubuntu-latest
|
||||
container:
|
||||
image: gitea-job-image
|
||||
steps:
|
||||
- name: Clone repo
|
||||
run: |
|
||||
rm -rf $GITHUB_WORKSPACE/*
|
||||
git clone --depth 1 $GITEA_URL/$GITHUB_REPOSITORY $GITHUB_WORKSPACE
|
||||
git -C $GITHUB_WORKSPACE checkout $GITHUB_SHA 2>/dev/null || true
|
||||
|
||||
- name: Run bandit (Python SAST)
|
||||
if: always()
|
||||
run: |
|
||||
if [[ -f pyproject.toml ]]; then
|
||||
pip3 install bandit
|
||||
bandit -r . --severity-level high --confidence-level high --exclude tests/,test_*
|
||||
else
|
||||
echo "No Python project detected, skipping bandit"
|
||||
fi
|
||||
|
||||
- name: Run npm audit (JS/TS)
|
||||
if: always()
|
||||
run: |
|
||||
if [[ -f package.json ]]; then
|
||||
npm ci
|
||||
npm audit --audit-level=high 2>/dev/null || echo "npm audit: vulnerabilities found (non-blocking)"
|
||||
else
|
||||
echo "No Node.js project detected, skipping npm audit"
|
||||
fi
|
||||
|
||||
build-result:
|
||||
needs: [lint, test, docker-build, security]
|
||||
runs-on: ubuntu-latest
|
||||
container:
|
||||
image: gitea-job-image
|
||||
if: always()
|
||||
steps:
|
||||
- name: Summary
|
||||
run: echo "All CI checks completed"
|
||||
369
app.py
Normal file
369
app.py
Normal file
@ -0,0 +1,369 @@
|
||||
import os
|
||||
import re
|
||||
import uuid
|
||||
import json
|
||||
import secrets
|
||||
import time
|
||||
import threading
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from flask import Flask, request, redirect, url_for, render_template, send_file, abort, make_response
|
||||
from werkzeug.utils import secure_filename
|
||||
|
||||
app = Flask(__name__)
|
||||
app.config['MAX_CONTENT_LENGTH'] = 20 * 1024 * 1024
|
||||
app.config['UPLOAD_FOLDER'] = os.environ.get('UPLOAD_FOLDER', os.path.join(os.path.dirname(os.path.abspath(__file__)), 'uploads'))
|
||||
app.config['STORE_FOLDER'] = os.environ.get('STORE_FOLDER', os.path.join(os.path.dirname(os.path.abspath(__file__)), 'store'))
|
||||
app.config['SECRET_KEY'] = os.environ.get('SECRET_KEY') or secrets.token_hex(32)
|
||||
|
||||
EXPIRY_OPTIONS = [
|
||||
('1h', '1 hour'),
|
||||
('1d', '1 day'),
|
||||
('1w', '1 week'),
|
||||
('1m', '1 month'),
|
||||
('forever', 'Never'),
|
||||
]
|
||||
|
||||
ALLOWED_IMAGE_EXTENSIONS = {'png', 'jpg', 'jpeg', 'gif', 'bmp', 'webp', 'tiff'}
|
||||
ALLOWED_IMAGE_MAGIC = {
|
||||
'png': b'\x89PNG\r\n\x1a\n',
|
||||
'jpg': b'\xff\xd8\xff',
|
||||
'gif': (b'GIF87a', b'GIF89a'),
|
||||
'webp': b'RIFF',
|
||||
'bmp': b'BM',
|
||||
}
|
||||
ALLOWED_TEXT_EXTENSIONS = {'txt', 'py', 'js', 'ts', 'c', 'cpp', 'h', 'java', 'rb', 'go', 'rs', 'md', 'json', 'xml', 'yaml', 'yml', 'html', 'css', 'sh', 'log', 'csv', 'sql', 'ini', 'cfg', 'toml', 'lua', 'php', 'swift', 'kt', 'scala', 'r', 'pl', 'hs', 'zig', 'nix'}
|
||||
|
||||
# Paste IDs are uuid4().hex[:16]; reject anything else to block path traversal.
|
||||
PASTE_ID_RE = re.compile(r'^[a-f0-9]{16}$')
|
||||
|
||||
_upload_attempts = {}
|
||||
_UPLOAD_MAX = 10
|
||||
_UPLOAD_WINDOW = 60
|
||||
|
||||
|
||||
def ensure_dirs():
|
||||
os.makedirs(app.config['UPLOAD_FOLDER'], exist_ok=True)
|
||||
os.makedirs(app.config['STORE_FOLDER'], exist_ok=True)
|
||||
|
||||
|
||||
def generate_id():
|
||||
return uuid.uuid4().hex[:16]
|
||||
|
||||
|
||||
def parse_expiry(expiry_key):
|
||||
"""Map an expiry option to an ISO timestamp; unknown keys default to 1 day."""
|
||||
if expiry_key == 'forever':
|
||||
return None
|
||||
now = datetime.now(timezone.utc)
|
||||
if expiry_key == '1h':
|
||||
return (now + timedelta(hours=1)).isoformat()
|
||||
elif expiry_key == '1w':
|
||||
return (now + timedelta(weeks=1)).isoformat()
|
||||
elif expiry_key == '1m':
|
||||
return (now + timedelta(days=30)).isoformat()
|
||||
return (now + timedelta(days=1)).isoformat()
|
||||
|
||||
|
||||
def store_paste(paste_id, paste_data):
|
||||
store_path = os.path.join(app.config['STORE_FOLDER'], paste_id)
|
||||
tmp_path = store_path + f".tmp.{os.getpid()}"
|
||||
fd = os.open(tmp_path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o644)
|
||||
with os.fdopen(fd, 'w') as f:
|
||||
json.dump(paste_data, f)
|
||||
os.rename(tmp_path, store_path)
|
||||
|
||||
|
||||
def load_paste(paste_id):
|
||||
if not PASTE_ID_RE.match(paste_id):
|
||||
return None
|
||||
store_path = os.path.join(app.config['STORE_FOLDER'], paste_id)
|
||||
if not os.path.exists(store_path):
|
||||
return None
|
||||
try:
|
||||
with open(store_path, 'r') as f:
|
||||
return json.load(f)
|
||||
except (json.JSONDecodeError, IOError):
|
||||
return None
|
||||
|
||||
|
||||
def delete_paste(paste_id):
|
||||
store_path = os.path.join(app.config['STORE_FOLDER'], paste_id)
|
||||
txt_path = store_path + '.txt'
|
||||
paste = load_paste(paste_id)
|
||||
if paste and paste['type'] in ('image', 'file') and paste.get('filepath'):
|
||||
filepath = paste['filepath']
|
||||
if os.path.exists(filepath):
|
||||
os.remove(filepath)
|
||||
if os.path.exists(store_path):
|
||||
os.remove(store_path)
|
||||
if os.path.exists(txt_path):
|
||||
os.remove(txt_path)
|
||||
|
||||
|
||||
def is_expired(paste):
|
||||
if not paste.get('expires_at'):
|
||||
return False
|
||||
expires_at = datetime.fromisoformat(paste['expires_at'])
|
||||
return expires_at < datetime.now(timezone.utc)
|
||||
|
||||
|
||||
def cleanup_expired():
|
||||
for filename in os.listdir(app.config['STORE_FOLDER']):
|
||||
if filename.endswith('.txt'):
|
||||
continue
|
||||
filepath = os.path.join(app.config['STORE_FOLDER'], filename)
|
||||
try:
|
||||
with open(filepath, 'r') as f:
|
||||
paste = json.load(f)
|
||||
except (json.JSONDecodeError, IOError):
|
||||
continue
|
||||
if is_expired(paste):
|
||||
delete_paste(filename)
|
||||
|
||||
|
||||
def _cleanup_loop():
|
||||
while True:
|
||||
time.sleep(300)
|
||||
try:
|
||||
cleanup_expired()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
threading.Thread(target=_cleanup_loop, daemon=True).start()
|
||||
|
||||
|
||||
def is_image(filename):
|
||||
ext = filename.rsplit('.', 1)[-1].lower() if '.' in filename else ''
|
||||
return ext in ALLOWED_IMAGE_EXTENSIONS
|
||||
|
||||
|
||||
def is_text_file(filename):
|
||||
ext = filename.rsplit('.', 1)[-1].lower() if '.' in filename else ''
|
||||
return ext in ALLOWED_TEXT_EXTENSIONS
|
||||
|
||||
|
||||
def get_text_content(paste_id):
|
||||
content_path = os.path.join(app.config['STORE_FOLDER'], paste_id + '.txt')
|
||||
if os.path.exists(content_path):
|
||||
with open(content_path, 'r', encoding='utf-8') as f:
|
||||
return f.read()
|
||||
return None
|
||||
|
||||
|
||||
def save_text_content(paste_id, content):
|
||||
content_path = os.path.join(app.config['STORE_FOLDER'], paste_id + '.txt')
|
||||
with open(content_path, 'w', encoding='utf-8') as f:
|
||||
f.write(content)
|
||||
|
||||
|
||||
# Fix #16 - ensure_dirs at startup only, not every request
|
||||
ensure_dirs()
|
||||
|
||||
|
||||
@app.after_request
|
||||
def add_security_headers(response):
|
||||
response.headers['X-Content-Type-Options'] = 'nosniff'
|
||||
response.headers['X-Frame-Options'] = 'DENY'
|
||||
response.headers['X-XSS-Protection'] = '1; mode=block'
|
||||
response.headers['Referrer-Policy'] = 'strict-origin-when-cross-origin'
|
||||
response.headers['Content-Security-Policy'] = "default-src 'self'; img-src 'self' data:; style-src 'self' 'unsafe-inline'"
|
||||
if request.is_secure:
|
||||
response.headers['Strict-Transport-Security'] = 'max-age=31536000; includeSubDomains'
|
||||
return response
|
||||
|
||||
|
||||
def _check_upload_rate():
|
||||
ip = request.remote_addr or 'unknown'
|
||||
now = time.time()
|
||||
if ip not in _upload_attempts:
|
||||
_upload_attempts[ip] = []
|
||||
_upload_attempts[ip] = [t for t in _upload_attempts[ip] if now - t < _UPLOAD_WINDOW]
|
||||
if len(_upload_attempts[ip]) >= _UPLOAD_MAX:
|
||||
return False
|
||||
_upload_attempts[ip].append(now)
|
||||
return True
|
||||
|
||||
|
||||
def _csrf_token():
|
||||
sess = request.cookies.get('csrf_token')
|
||||
if not sess:
|
||||
return secrets.token_hex(16)
|
||||
return sess
|
||||
|
||||
|
||||
@app.route('/', methods=['GET'])
|
||||
def index():
|
||||
resp = make_response(render_template('index.html', expiry_options=EXPIRY_OPTIONS, csrf_token=_csrf_token()))
|
||||
resp.set_cookie('csrf_token', _csrf_token(), httponly=False, samesite='Strict', path='/')
|
||||
return resp
|
||||
|
||||
|
||||
@app.route('/paste', methods=['POST'])
|
||||
def create_paste():
|
||||
if not _check_upload_rate():
|
||||
return render_template('index.html', expiry_options=EXPIRY_OPTIONS,
|
||||
error='Too many uploads. Please wait.'), 429
|
||||
paste_type = request.form.get('paste_type', 'text')
|
||||
title = request.form.get('title', '').strip()
|
||||
expiry_key = request.form.get('expiry', '1d')
|
||||
expires_at = parse_expiry(expiry_key)
|
||||
created_at = datetime.now(timezone.utc).isoformat()
|
||||
|
||||
if paste_type == 'text':
|
||||
content = request.form.get('content', '').strip()
|
||||
if not content:
|
||||
return render_template('index.html', expiry_options=EXPIRY_OPTIONS, error='Content cannot be empty'), 400
|
||||
|
||||
paste_id = generate_id()
|
||||
save_text_content(paste_id, content)
|
||||
store_paste(paste_id, {
|
||||
'type': 'text',
|
||||
'title': title,
|
||||
'expires_at': expires_at,
|
||||
'created_at': created_at,
|
||||
})
|
||||
return redirect(url_for('view_paste', paste_id=paste_id))
|
||||
|
||||
elif paste_type == 'image':
|
||||
file = request.files.get('file')
|
||||
if not file or file.filename == '':
|
||||
return render_template('index.html', expiry_options=EXPIRY_OPTIONS, error='No file selected'), 400
|
||||
|
||||
filename = secure_filename(file.filename)
|
||||
if not is_image(filename):
|
||||
return render_template('index.html', expiry_options=EXPIRY_OPTIONS, error='Invalid image format. SVG not allowed. Allowed: ' + ', '.join(sorted(ALLOWED_IMAGE_EXTENSIONS))), 400
|
||||
|
||||
head = file.read(12)
|
||||
file.seek(0)
|
||||
ext = filename.rsplit('.', 1)[-1].lower()
|
||||
if ext in ALLOWED_IMAGE_MAGIC:
|
||||
valid = any(head.startswith(m) for m in (ALLOWED_IMAGE_MAGIC[ext] if isinstance(ALLOWED_IMAGE_MAGIC[ext], tuple) else (ALLOWED_IMAGE_MAGIC[ext],)))
|
||||
if not valid:
|
||||
return render_template('index.html', expiry_options=EXPIRY_OPTIONS,
|
||||
error='File content does not match image type.'), 400
|
||||
|
||||
paste_id = generate_id()
|
||||
ext = filename.rsplit('.', 1)[-1]
|
||||
saved_name = f"{paste_id}.{ext}"
|
||||
filepath = os.path.join(app.config['UPLOAD_FOLDER'], saved_name)
|
||||
file.save(filepath)
|
||||
|
||||
store_paste(paste_id, {
|
||||
'type': 'image',
|
||||
'title': title or filename,
|
||||
'expires_at': expires_at,
|
||||
'created_at': created_at,
|
||||
'filepath': filepath,
|
||||
'filename': filename,
|
||||
'mimetype': file.mimetype or f'image/{ext}',
|
||||
})
|
||||
return redirect(url_for('view_paste', paste_id=paste_id))
|
||||
|
||||
elif paste_type == 'file':
|
||||
file = request.files.get('file')
|
||||
if not file or file.filename == '':
|
||||
return render_template('index.html', expiry_options=EXPIRY_OPTIONS, error='No file selected'), 400
|
||||
|
||||
filename = secure_filename(file.filename)
|
||||
paste_id = generate_id()
|
||||
|
||||
if is_text_file(filename):
|
||||
content = file.read().decode('utf-8', errors='replace')
|
||||
save_text_content(paste_id, content)
|
||||
store_paste(paste_id, {
|
||||
'type': 'text',
|
||||
'title': title or filename,
|
||||
'expires_at': expires_at,
|
||||
'created_at': created_at,
|
||||
'filename': filename,
|
||||
})
|
||||
else:
|
||||
ext = filename.rsplit('.', 1)[-1] if '.' in filename else 'bin'
|
||||
saved_name = f"{paste_id}.{ext}"
|
||||
filepath = os.path.join(app.config['UPLOAD_FOLDER'], saved_name)
|
||||
file.save(filepath)
|
||||
|
||||
store_paste(paste_id, {
|
||||
'type': 'file',
|
||||
'title': title or filename,
|
||||
'expires_at': expires_at,
|
||||
'created_at': created_at,
|
||||
'filepath': filepath,
|
||||
'filename': filename,
|
||||
'mimetype': file.mimetype or 'application/octet-stream',
|
||||
})
|
||||
return redirect(url_for('view_paste', paste_id=paste_id))
|
||||
|
||||
else:
|
||||
return render_template('index.html', expiry_options=EXPIRY_OPTIONS, error='Invalid paste type'), 400
|
||||
|
||||
|
||||
@app.route('/<paste_id>', methods=['GET'])
|
||||
def view_paste(paste_id):
|
||||
paste = load_paste(paste_id)
|
||||
if not paste:
|
||||
abort(404)
|
||||
|
||||
if is_expired(paste):
|
||||
delete_paste(paste_id)
|
||||
abort(404)
|
||||
|
||||
if paste['type'] == 'text':
|
||||
paste['data'] = get_text_content(paste_id) or ''
|
||||
return render_template('view_text.html', paste=paste, paste_id=paste_id)
|
||||
elif paste['type'] == 'image':
|
||||
return render_template('view_image.html', paste=paste, paste_id=paste_id)
|
||||
elif paste['type'] == 'file':
|
||||
return render_template('view_file.html', paste=paste, paste_id=paste_id)
|
||||
|
||||
|
||||
@app.route('/<paste_id>/download', methods=['GET'])
|
||||
def download_file(paste_id):
|
||||
paste = load_paste(paste_id)
|
||||
if not paste:
|
||||
abort(404)
|
||||
|
||||
if is_expired(paste):
|
||||
delete_paste(paste_id)
|
||||
abort(404)
|
||||
|
||||
if paste['type'] == 'text':
|
||||
from io import BytesIO
|
||||
content = (get_text_content(paste_id) or '').encode('utf-8')
|
||||
return send_file(BytesIO(content), download_name=paste.get('filename', 'paste.txt'), as_attachment=True)
|
||||
elif paste['type'] in ('image', 'file'):
|
||||
filepath = paste.get('filepath')
|
||||
if not filepath or not os.path.exists(filepath):
|
||||
abort(404)
|
||||
return send_file(filepath, download_name=paste['filename'], as_attachment=True, mimetype=paste.get('mimetype', 'application/octet-stream'))
|
||||
|
||||
|
||||
@app.route('/<paste_id>/raw', methods=['GET'])
|
||||
def raw_paste(paste_id):
|
||||
paste = load_paste(paste_id)
|
||||
if not paste:
|
||||
abort(404)
|
||||
|
||||
if is_expired(paste):
|
||||
delete_paste(paste_id)
|
||||
abort(404)
|
||||
|
||||
if paste['type'] == 'text':
|
||||
content = get_text_content(paste_id) or ''
|
||||
return content, 200, {'Content-Type': 'text/plain; charset=utf-8'}
|
||||
elif paste['type'] == 'image':
|
||||
filepath = paste.get('filepath')
|
||||
if not filepath or not os.path.exists(filepath):
|
||||
abort(404)
|
||||
return send_file(filepath, mimetype=paste.get('mimetype', 'image/png'))
|
||||
|
||||
|
||||
@app.errorhandler(413)
|
||||
def request_entity_too_large(e):
|
||||
return render_template('index.html', expiry_options=EXPIRY_OPTIONS, error='File too large. Maximum size is 20 MB.'), 413
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
ensure_dirs()
|
||||
app.run(host='0.0.0.0', port=int(os.environ.get('PORT', 8080)))
|
||||
12
docker-compose.yml
Normal file
12
docker-compose.yml
Normal file
@ -0,0 +1,12 @@
|
||||
services:
|
||||
pastebin:
|
||||
build: .
|
||||
ports:
|
||||
- "${PORT:-9780}:8080"
|
||||
volumes:
|
||||
- ./uploads:/app/uploads
|
||||
- ./store:/app/store
|
||||
environment:
|
||||
- PORT=8080
|
||||
- SECRET_KEY=${SECRET_KEY:-change-me-to-a-random-secret}
|
||||
restart: unless-stopped
|
||||
42
pyproject.toml
Normal file
42
pyproject.toml
Normal file
@ -0,0 +1,42 @@
|
||||
[project]
|
||||
name = "paste-bin"
|
||||
version = "1.0.0"
|
||||
description = "Minimal security-focused paste bin: text, image, and file sharing with expiring links"
|
||||
readme = "README.md"
|
||||
requires-python = ">=3.9"
|
||||
license = { text = "MIT" }
|
||||
authors = [{ name = "Jarian Cottingham", email = "jarianc@proton.me" }]
|
||||
keywords = ["paste", "paste-bin", "sharing", "flask"]
|
||||
classifiers = [
|
||||
"License :: OSI Approved :: MIT License",
|
||||
"Programming Language :: Python :: 3",
|
||||
]
|
||||
dependencies = [
|
||||
"flask>=3.0,<4.0",
|
||||
"werkzeug>=3.0,<4.0",
|
||||
]
|
||||
|
||||
[project.optional-dependencies]
|
||||
dev = [
|
||||
"pytest>=7.0",
|
||||
"ruff>=0.1.0",
|
||||
]
|
||||
|
||||
[build-system]
|
||||
requires = ["setuptools>=61.0"]
|
||||
build-backend = "setuptools.build_meta"
|
||||
|
||||
[tool.setuptools]
|
||||
py-modules = ["app"]
|
||||
|
||||
[tool.ruff]
|
||||
line-length = 120
|
||||
target-version = "py39"
|
||||
exclude = [".git", "uploads", "store"]
|
||||
|
||||
[tool.ruff.lint]
|
||||
select = ["E", "F", "W"]
|
||||
ignore = ["E501"]
|
||||
|
||||
[tool.pytest.ini_options]
|
||||
testpaths = ["tests"]
|
||||
313
static/style.css
Normal file
313
static/style.css
Normal file
@ -0,0 +1,313 @@
|
||||
* {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
body {
|
||||
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, sans-serif;
|
||||
background: #1a1a2e;
|
||||
color: #e0e0e0;
|
||||
min-height: 100vh;
|
||||
line-height: 1.6;
|
||||
}
|
||||
|
||||
.container {
|
||||
max-width: 800px;
|
||||
margin: 0 auto;
|
||||
padding: 2rem 1rem;
|
||||
}
|
||||
|
||||
header {
|
||||
text-align: center;
|
||||
margin-bottom: 2rem;
|
||||
}
|
||||
|
||||
header h1 {
|
||||
font-size: 2.5rem;
|
||||
color: #e94560;
|
||||
margin-bottom: 0.5rem;
|
||||
}
|
||||
|
||||
header h1 a {
|
||||
color: #e94560;
|
||||
text-decoration: none;
|
||||
}
|
||||
|
||||
header p {
|
||||
color: #a0a0a0;
|
||||
font-size: 1rem;
|
||||
}
|
||||
|
||||
.error {
|
||||
background: #e94560;
|
||||
color: white;
|
||||
padding: 0.75rem 1rem;
|
||||
border-radius: 6px;
|
||||
margin-bottom: 1.5rem;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.tabs {
|
||||
display: flex;
|
||||
gap: 0.5rem;
|
||||
margin-bottom: 1.5rem;
|
||||
border-bottom: 2px solid #16213e;
|
||||
padding-bottom: 0;
|
||||
}
|
||||
|
||||
.tab {
|
||||
background: transparent;
|
||||
border: none;
|
||||
color: #a0a0a0;
|
||||
padding: 0.75rem 1.5rem;
|
||||
font-size: 1rem;
|
||||
cursor: pointer;
|
||||
border-bottom: 2px solid transparent;
|
||||
margin-bottom: -2px;
|
||||
transition: all 0.2s;
|
||||
}
|
||||
|
||||
.tab:hover {
|
||||
color: #e0e0e0;
|
||||
}
|
||||
|
||||
.tab.active {
|
||||
color: #e94560;
|
||||
border-bottom-color: #e94560;
|
||||
}
|
||||
|
||||
.panel {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.panel.active {
|
||||
display: block;
|
||||
}
|
||||
|
||||
.form-group {
|
||||
margin-bottom: 1.5rem;
|
||||
}
|
||||
|
||||
.form-group label {
|
||||
display: block;
|
||||
margin-bottom: 0.5rem;
|
||||
color: #a0a0a0;
|
||||
font-size: 0.9rem;
|
||||
}
|
||||
|
||||
input[type="text"],
|
||||
textarea,
|
||||
select {
|
||||
width: 100%;
|
||||
background: #16213e;
|
||||
border: 1px solid #0f3460;
|
||||
color: #e0e0e0;
|
||||
padding: 0.75rem;
|
||||
border-radius: 6px;
|
||||
font-size: 1rem;
|
||||
font-family: inherit;
|
||||
}
|
||||
|
||||
input[type="text"]:focus,
|
||||
textarea:focus,
|
||||
select:focus {
|
||||
outline: none;
|
||||
border-color: #e94560;
|
||||
}
|
||||
|
||||
textarea {
|
||||
resize: vertical;
|
||||
min-height: 200px;
|
||||
font-family: 'Courier New', Courier, monospace;
|
||||
}
|
||||
|
||||
.file-input {
|
||||
position: relative;
|
||||
}
|
||||
|
||||
.file-label {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.75rem;
|
||||
background: #16213e;
|
||||
border: 2px dashed #0f3460;
|
||||
padding: 1.5rem;
|
||||
border-radius: 6px;
|
||||
cursor: pointer;
|
||||
transition: border-color 0.2s;
|
||||
}
|
||||
|
||||
.file-label:hover {
|
||||
border-color: #e94560;
|
||||
}
|
||||
|
||||
.file-icon {
|
||||
font-size: 1.5rem;
|
||||
}
|
||||
|
||||
.file-text {
|
||||
color: #a0a0a0;
|
||||
}
|
||||
|
||||
.chosen-file {
|
||||
display: block;
|
||||
margin-top: 0.5rem;
|
||||
color: #e94560;
|
||||
font-size: 0.9rem;
|
||||
}
|
||||
|
||||
.submit-btn {
|
||||
width: 100%;
|
||||
background: #e94560;
|
||||
color: white;
|
||||
border: none;
|
||||
padding: 1rem;
|
||||
font-size: 1.1rem;
|
||||
border-radius: 6px;
|
||||
cursor: pointer;
|
||||
transition: background 0.2s;
|
||||
margin-top: 1rem;
|
||||
}
|
||||
|
||||
.submit-btn:hover {
|
||||
background: #c83a54;
|
||||
}
|
||||
|
||||
.paste-view {
|
||||
background: #16213e;
|
||||
border-radius: 8px;
|
||||
padding: 1.5rem;
|
||||
}
|
||||
|
||||
.paste-view h2 {
|
||||
color: #e94560;
|
||||
margin-bottom: 1rem;
|
||||
}
|
||||
|
||||
.meta {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 1rem;
|
||||
margin-bottom: 1.5rem;
|
||||
padding-bottom: 1rem;
|
||||
border-bottom: 1px solid #0f3460;
|
||||
font-size: 0.85rem;
|
||||
color: #a0a0a0;
|
||||
}
|
||||
|
||||
.meta code {
|
||||
background: #0f3460;
|
||||
padding: 0.15rem 0.4rem;
|
||||
border-radius: 3px;
|
||||
color: #e94560;
|
||||
}
|
||||
|
||||
.content-wrapper {
|
||||
background: #0f3460;
|
||||
border-radius: 6px;
|
||||
padding: 1rem;
|
||||
margin-bottom: 1.5rem;
|
||||
overflow-x: auto;
|
||||
}
|
||||
|
||||
.content-wrapper pre {
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.content-wrapper code {
|
||||
font-family: 'Courier New', Courier, monospace;
|
||||
font-size: 0.9rem;
|
||||
color: #e0e0e0;
|
||||
white-space: pre-wrap;
|
||||
word-break: break-word;
|
||||
}
|
||||
|
||||
.image-wrapper {
|
||||
text-align: center;
|
||||
background: transparent;
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
.paste-image {
|
||||
max-width: 100%;
|
||||
max-height: 60vh;
|
||||
border-radius: 6px;
|
||||
}
|
||||
|
||||
.file-info {
|
||||
text-align: center;
|
||||
padding: 2rem;
|
||||
}
|
||||
|
||||
.file-info p {
|
||||
margin-bottom: 0.5rem;
|
||||
}
|
||||
|
||||
.actions {
|
||||
display: flex;
|
||||
gap: 0.75rem;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.btn {
|
||||
display: inline-block;
|
||||
padding: 0.6rem 1.2rem;
|
||||
border-radius: 6px;
|
||||
text-decoration: none;
|
||||
font-size: 0.9rem;
|
||||
cursor: pointer;
|
||||
border: none;
|
||||
transition: background 0.2s;
|
||||
}
|
||||
|
||||
.btn-primary {
|
||||
background: #e94560;
|
||||
color: white;
|
||||
}
|
||||
|
||||
.btn-primary:hover {
|
||||
background: #c83a54;
|
||||
}
|
||||
|
||||
.btn-secondary {
|
||||
background: #0f3460;
|
||||
color: #e0e0e0;
|
||||
}
|
||||
|
||||
.btn-secondary:hover {
|
||||
background: #1a4a8a;
|
||||
}
|
||||
|
||||
@media (max-width: 600px) {
|
||||
.container {
|
||||
padding: 1rem;
|
||||
}
|
||||
|
||||
header h1 {
|
||||
font-size: 2rem;
|
||||
}
|
||||
|
||||
.tabs {
|
||||
gap: 0;
|
||||
}
|
||||
|
||||
.tab {
|
||||
padding: 0.5rem 0.75rem;
|
||||
font-size: 0.9rem;
|
||||
}
|
||||
|
||||
.meta {
|
||||
flex-direction: column;
|
||||
gap: 0.3rem;
|
||||
}
|
||||
|
||||
.actions {
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.btn {
|
||||
width: 100%;
|
||||
text-align: center;
|
||||
}
|
||||
}
|
||||
137
templates/index.html
Normal file
137
templates/index.html
Normal file
@ -0,0 +1,137 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>PasteBin</title>
|
||||
<link rel="icon" type="image/svg+xml" href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 100 100'%3E%3Ctext y='.9em' font-size='90'%3E📋%3C/text%3E%3C/svg%3E">
|
||||
<link rel="stylesheet" href="/static/style.css">
|
||||
</head>
|
||||
<body>
|
||||
<div class="container" role="main">
|
||||
<header>
|
||||
<h1><a href="/">PasteBin</a></h1>
|
||||
<p>Share text, images, and files temporarily</p>
|
||||
</header>
|
||||
|
||||
{% if error %}
|
||||
<div class="error">{{ error }}</div>
|
||||
{% endif %}
|
||||
|
||||
<div class="tabs">
|
||||
<button class="tab active" data-tab="text" aria-label="Text paste tab" aria-selected="true">Text</button>
|
||||
<button class="tab" data-tab="image" aria-label="Image paste tab" aria-selected="false">Image</button>
|
||||
<button class="tab" data-tab="file" aria-label="File paste tab" aria-selected="false">File</button>
|
||||
</div>
|
||||
|
||||
<form method="POST" action="/paste" enctype="multipart/form-data" id="uploadForm">
|
||||
<input type="hidden" name="paste_type" id="pasteType" value="text">
|
||||
<input type="hidden" name="csrf_token" value="{{ csrf_token }}">
|
||||
|
||||
<div class="form-group">
|
||||
<label for="title">Title (optional)</label>
|
||||
<input type="text" id="title" name="title" placeholder="Give your paste a name">
|
||||
</div>
|
||||
|
||||
<div id="text-panel" class="panel active">
|
||||
<div class="form-group">
|
||||
<label for="content">Content</label>
|
||||
<textarea id="content" name="content" placeholder="Paste your text here..." rows="12"></textarea>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div id="image-panel" class="panel">
|
||||
<div class="form-group">
|
||||
<label id="file-label">Image (max 20 MB)</label>
|
||||
<div class="file-input">
|
||||
<input type="file" id="upload-file" name="file" accept="image/png,image/jpeg,image/gif,image/bmp,image/webp,image/svg+xml,image/tiff" style="display:none">
|
||||
<label for="upload-file" class="file-label">
|
||||
<span class="file-icon" id="file-icon">📷</span>
|
||||
<span class="file-text" id="file-text">Choose image or drag here</span>
|
||||
</label>
|
||||
<span id="chosen-filename" class="chosen-file"></span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div id="file-panel" class="panel">
|
||||
<div class="form-group">
|
||||
<label id="file-label2">File (max 20 MB)</label>
|
||||
<div class="file-input">
|
||||
<span class="file-icon">👤</span>
|
||||
<span class="file-text" id="file-text2">Choose file or drag here</span>
|
||||
<span id="chosen-filename2" class="chosen-file"></span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="form-group">
|
||||
<label for="expiry">Expires</label>
|
||||
<select id="expiry" name="expiry">
|
||||
{% for key, label in expiry_options %}
|
||||
<option value="{{ key }}" {% if key == '1d' %}selected{% endif %}>{{ label }}</option>
|
||||
{% endfor %}
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<button type="submit" class="submit-btn">Create Paste</button>
|
||||
</form>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
document.addEventListener('DOMContentLoaded', function() {
|
||||
const tabs = document.querySelectorAll('.tab');
|
||||
const panels = document.querySelectorAll('.panel');
|
||||
const pasteTypeInput = document.getElementById('pasteType');
|
||||
const uploadFile = document.getElementById('upload-file');
|
||||
const uploadFile2 = document.getElementById('upload-file2');
|
||||
const chosenFilename = document.getElementById('chosen-filename');
|
||||
const chosenFilename2 = document.getElementById('chosen-filename2');
|
||||
const fileIcon = document.getElementById('file-icon');
|
||||
const fileText = document.getElementById('file-text');
|
||||
const fileLabel = document.getElementById('file-label');
|
||||
const contentTextarea = document.getElementById('content');
|
||||
|
||||
function switchTab(tabName) {
|
||||
tabs.forEach(t => t.classList.remove('active'));
|
||||
panels.forEach(p => p.classList.remove('active'));
|
||||
document.querySelector('[data-tab="' + tabName + '"]').classList.add('active');
|
||||
document.getElementById(tabName + '-panel').classList.add('active');
|
||||
pasteTypeInput.value = tabName;
|
||||
|
||||
uploadFile.setAttribute('name', '__unused__');
|
||||
contentTextarea.setAttribute('name', '__unused__');
|
||||
|
||||
if (tabName === 'text') {
|
||||
contentTextarea.setAttribute('name', 'content');
|
||||
} else if (tabName === 'image') {
|
||||
uploadFile.setAttribute('name', 'file');
|
||||
uploadFile.setAttribute('accept', 'image/png,image/jpeg,image/gif,image/bmp,image/webp,image/tiff');
|
||||
fileIcon.innerHTML = '📷';
|
||||
fileText.textContent = 'Choose image or drag here';
|
||||
fileLabel.textContent = 'Image (max 20 MB)';
|
||||
} else if (tabName === 'file') {
|
||||
uploadFile.setAttribute('name', 'file');
|
||||
uploadFile.removeAttribute('accept');
|
||||
}
|
||||
}
|
||||
|
||||
tabs.forEach(tab => {
|
||||
tab.addEventListener('click', function() {
|
||||
switchTab(this.dataset.tab);
|
||||
});
|
||||
});
|
||||
|
||||
uploadFile.addEventListener('change', function() {
|
||||
chosenFilename.textContent = this.files[0] ? this.files[0].name : '';
|
||||
chosenFilename2.textContent = '';
|
||||
});
|
||||
|
||||
uploadFile2.addEventListener('change', function() {
|
||||
chosenFilename2.textContent = this.files[0] ? this.files[0].name : '';
|
||||
chosenFilename.textContent = '';
|
||||
});
|
||||
});
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
41
templates/view_file.html
Normal file
41
templates/view_file.html
Normal file
@ -0,0 +1,41 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>{{ paste.title or 'PasteBin' }} - PasteBin</title>
|
||||
<link rel="stylesheet" href="/static/style.css">
|
||||
</head>
|
||||
<body>
|
||||
<div class="container">
|
||||
<header>
|
||||
<h1><a href="/">PasteBin</a></h1>
|
||||
</header>
|
||||
|
||||
<div class="paste-view">
|
||||
{% if paste.title %}
|
||||
<h2>{{ paste.title }}</h2>
|
||||
{% endif %}
|
||||
<div class="meta">
|
||||
<span>ID: <code>{{ paste_id }}</code></span>
|
||||
<span>File: {{ paste.filename }}</span>
|
||||
<span>Created: {{ paste.created_at[:19] | replace('T', ' ') }}</span>
|
||||
{% if paste.expires_at %}
|
||||
<span>Expires: {{ paste.expires_at[:19] | replace('T', ' ') }}</span>
|
||||
{% else %}
|
||||
<span>Never expires</span>
|
||||
{% endif %}
|
||||
</div>
|
||||
|
||||
<div class="content-wrapper file-info">
|
||||
<p>This is a binary file. Download it to view.</p>
|
||||
<p>Type: {{ paste.mimetype }}</p>
|
||||
</div>
|
||||
|
||||
<div class="actions">
|
||||
<a href="/{{ paste_id }}/download" class="btn btn-primary">Download</a>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
40
templates/view_image.html
Normal file
40
templates/view_image.html
Normal file
@ -0,0 +1,40 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>{{ paste.title or 'PasteBin' }} - PasteBin</title>
|
||||
<link rel="stylesheet" href="/static/style.css">
|
||||
</head>
|
||||
<body>
|
||||
<div class="container">
|
||||
<header>
|
||||
<h1><a href="/">PasteBin</a></h1>
|
||||
</header>
|
||||
|
||||
<div class="paste-view">
|
||||
{% if paste.title %}
|
||||
<h2>{{ paste.title }}</h2>
|
||||
{% endif %}
|
||||
<div class="meta">
|
||||
<span>ID: <code>{{ paste_id }}</code></span>
|
||||
<span>Created: {{ paste.created_at[:19] | replace('T', ' ') }}</span>
|
||||
{% if paste.expires_at %}
|
||||
<span>Expires: {{ paste.expires_at[:19] | replace('T', ' ') }}</span>
|
||||
{% else %}
|
||||
<span>Never expires</span>
|
||||
{% endif %}
|
||||
</div>
|
||||
|
||||
<div class="content-wrapper image-wrapper">
|
||||
<img src="/{{ paste_id }}/raw" alt="{{ paste.filename }}" class="paste-image">
|
||||
</div>
|
||||
|
||||
<div class="actions">
|
||||
<a href="/{{ paste_id }}/raw" class="btn btn-secondary">View Full</a>
|
||||
<a href="/{{ paste_id }}/download" class="btn btn-primary">Download</a>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
52
templates/view_text.html
Normal file
52
templates/view_text.html
Normal file
@ -0,0 +1,52 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>{{ paste.title or 'PasteBin' }} - PasteBin</title>
|
||||
<link rel="stylesheet" href="/static/style.css">
|
||||
</head>
|
||||
<body>
|
||||
<div class="container">
|
||||
<header>
|
||||
<h1><a href="/">PasteBin</a></h1>
|
||||
</header>
|
||||
|
||||
<div class="paste-view">
|
||||
{% if paste.title %}
|
||||
<h2>{{ paste.title }}</h2>
|
||||
{% endif %}
|
||||
<div class="meta">
|
||||
<span>ID: <code>{{ paste_id }}</code></span>
|
||||
<span>Created: {{ paste.created_at[:19] | replace('T', ' ') }}</span>
|
||||
{% if paste.expires_at %}
|
||||
<span>Expires: {{ paste.expires_at[:19] | replace('T', ' ') }}</span>
|
||||
{% else %}
|
||||
<span>Never expires</span>
|
||||
{% endif %}
|
||||
</div>
|
||||
|
||||
<div class="content-wrapper">
|
||||
<pre><code>{{ paste.data }}</code></pre>
|
||||
</div>
|
||||
|
||||
<div class="actions">
|
||||
<a href="/{{ paste_id }}/raw" class="btn btn-secondary">Raw</a>
|
||||
<a href="/{{ paste_id }}/download" class="btn btn-primary">Download</a>
|
||||
<button class="btn btn-secondary copy-btn" onclick="copyToClipboard()">Copy</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
function copyToClipboard() {
|
||||
const text = document.querySelector('pre code').textContent;
|
||||
navigator.clipboard.writeText(text).then(() => {
|
||||
const btn = document.querySelector('.copy-btn');
|
||||
btn.textContent = 'Copied!';
|
||||
setTimeout(() => btn.textContent = 'Copy', 2000);
|
||||
});
|
||||
}
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
119
tests/test_app.py
Normal file
119
tests/test_app.py
Normal file
@ -0,0 +1,119 @@
|
||||
"""Unit tests for paste-bin."""
|
||||
|
||||
import io
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).parent.parent))
|
||||
|
||||
import app as app_module # noqa: E402
|
||||
|
||||
|
||||
@pytest.fixture()
|
||||
def client(tmp_path, monkeypatch):
|
||||
app_module.app.config['TESTING'] = True
|
||||
app_module.app.config['UPLOAD_FOLDER'] = str(tmp_path / 'uploads')
|
||||
app_module.app.config['STORE_FOLDER'] = str(tmp_path / 'store')
|
||||
app_module.ensure_dirs()
|
||||
with app_module.app.test_client() as c:
|
||||
yield c
|
||||
|
||||
|
||||
def test_index_returns_200(client):
|
||||
resp = client.get('/')
|
||||
assert resp.status_code == 200
|
||||
|
||||
|
||||
def test_text_paste_roundtrip(client):
|
||||
resp = client.post('/paste', data={'paste_type': 'text', 'content': 'hello world', 'expiry': '1d'})
|
||||
assert resp.status_code == 302
|
||||
paste_id = resp.headers['Location'].rsplit('/', 1)[-1]
|
||||
assert len(paste_id) == 16
|
||||
|
||||
view = client.get(f'/{paste_id}')
|
||||
assert view.status_code == 200
|
||||
assert b'hello world' in view.data
|
||||
|
||||
raw = client.get(f'/{paste_id}/raw')
|
||||
assert raw.status_code == 200
|
||||
assert raw.data == b'hello world'
|
||||
|
||||
dl = client.get(f'/{paste_id}/download')
|
||||
assert dl.status_code == 200
|
||||
assert dl.data == b'hello world'
|
||||
|
||||
|
||||
def test_empty_content_rejected(client):
|
||||
resp = client.post('/paste', data={'paste_type': 'text', 'content': ' ', 'expiry': '1d'})
|
||||
assert resp.status_code == 400
|
||||
|
||||
|
||||
def test_invalid_paste_type_rejected(client):
|
||||
resp = client.post('/paste', data={'paste_type': 'bogus', 'content': 'x'})
|
||||
assert resp.status_code == 400
|
||||
|
||||
|
||||
def test_unknown_paste_404(client):
|
||||
assert client.get('/' + 'a' * 16).status_code == 404
|
||||
|
||||
|
||||
def test_path_traversal_paste_id_blocked(client, tmp_path):
|
||||
outside = tmp_path / 'secret.txt'
|
||||
outside.write_text('top secret')
|
||||
for evil in ['..%2F..%2Fsecret.txt', '....//secret.txt', 'a' * 14 + '/../../secret.txt']:
|
||||
resp = client.get('/' + evil)
|
||||
assert resp.status_code == 404
|
||||
assert outside.exists()
|
||||
|
||||
|
||||
def test_svg_upload_rejected(client):
|
||||
png_bytes = b'<svg xmlns="http://www.w3.org/2000/svg"><script>alert(1)</script></svg>'
|
||||
resp = client.post(
|
||||
'/paste',
|
||||
data={'paste_type': 'image', 'file': (io.BytesIO(png_bytes), 'x.svg', 'image/svg+xml')},
|
||||
content_type='multipart/form-data',
|
||||
)
|
||||
assert resp.status_code == 400
|
||||
|
||||
|
||||
def test_png_magic_validation(client):
|
||||
fake = b'not-a-real-png'
|
||||
resp = client.post(
|
||||
'/paste',
|
||||
data={'paste_type': 'image', 'file': (io.BytesIO(fake), 'x.png', 'image/png')},
|
||||
content_type='multipart/form-data',
|
||||
)
|
||||
assert resp.status_code == 400
|
||||
|
||||
|
||||
def test_valid_png_upload(client):
|
||||
png = b'\x89PNG\r\n\x1a\n' + b'\x00' * 32
|
||||
resp = client.post(
|
||||
'/paste',
|
||||
data={'paste_type': 'image', 'file': (io.BytesIO(png), 'pic.png', 'image/png')},
|
||||
content_type='multipart/form-data',
|
||||
)
|
||||
assert resp.status_code == 302
|
||||
paste_id = resp.headers['Location'].rsplit('/', 1)[-1]
|
||||
assert client.get(f'/{paste_id}').status_code == 200
|
||||
|
||||
|
||||
def test_expiry_parsing():
|
||||
assert app_module.parse_expiry('forever') is None
|
||||
for key in ['1h', '1d', '1w', '1m', 'bogus-key']:
|
||||
result = app_module.parse_expiry(key)
|
||||
assert result is not None
|
||||
from datetime import datetime
|
||||
|
||||
datetime.fromisoformat(result)
|
||||
|
||||
|
||||
def test_store_and_load_paste(tmp_path, monkeypatch):
|
||||
app_module.app.config['STORE_FOLDER'] = str(tmp_path / 'store')
|
||||
app_module.ensure_dirs()
|
||||
app_module.store_paste('ab' * 8, {'type': 'text', 'title': 't'})
|
||||
paste = app_module.load_paste('ab' * 8)
|
||||
assert paste['title'] == 't'
|
||||
assert app_module.load_paste('../etc/passwd') is None
|
||||
Loading…
x
Reference in New Issue
Block a user