function load_custom_instructions
Flask API endpoint that loads and returns the content of custom instruction files from a designated instructions directory with security validation.
/tf/active/vicechatdev/docchat/app.py
1716 - 1736
moderate
Purpose
This function serves as a secure file loader for custom instruction files in a Flask web application. It reads text files from a specific 'instructions' directory, validates that the requested file path doesn't escape the directory (preventing directory traversal attacks), and returns the file content as JSON. It's designed to provide custom instructions or templates to the frontend application while maintaining security boundaries.
Source Code
def load_custom_instructions(filename):
"""Load custom instructions from a file"""
try:
instructions_dir = os.path.join(os.path.dirname(__file__), 'instructions')
filepath = os.path.join(instructions_dir, filename)
# Security check - ensure file is within instructions directory
if not os.path.abspath(filepath).startswith(os.path.abspath(instructions_dir)):
return jsonify({'error': 'Invalid filename'}), 400
if not os.path.exists(filepath):
return jsonify({'error': 'File not found'}), 404
with open(filepath, 'r', encoding='utf-8') as f:
content = f.read()
return jsonify({'content': content})
except Exception as e:
logger.error(f"Error loading instructions: {e}")
return jsonify({'error': str(e)}), 500
Parameters
| Name | Type | Default | Kind |
|---|---|---|---|
filename |
- | - | positional_or_keyword |
Parameter Details
filename: The name of the instruction file to load from the instructions directory. Should be a simple filename (e.g., 'template.txt') without path traversal characters. The function validates this parameter to prevent directory traversal attacks by ensuring the resolved path stays within the instructions directory.
Return Value
Returns a Flask JSON response tuple. On success: (jsonify({'content': <file_content_string>}), 200). On error: (jsonify({'error': <error_message>}), status_code) where status_code is 400 for invalid filenames, 404 for files not found, or 500 for other exceptions. The response is a Flask Response object with JSON content type.
Dependencies
flaskoslogging
Required Imports
from flask import jsonify
import os
import logging
Usage Example
# Assuming Flask app setup and logger configured
from flask import Flask, jsonify
import os
import logging
app = Flask(__name__)
logger = logging.getLogger(__name__)
@app.route('/api/instructions/load/<filename>', methods=['GET'])
def load_custom_instructions(filename):
try:
instructions_dir = os.path.join(os.path.dirname(__file__), 'instructions')
filepath = os.path.join(instructions_dir, filename)
if not os.path.abspath(filepath).startswith(os.path.abspath(instructions_dir)):
return jsonify({'error': 'Invalid filename'}), 400
if not os.path.exists(filepath):
return jsonify({'error': 'File not found'}), 404
with open(filepath, 'r', encoding='utf-8') as f:
content = f.read()
return jsonify({'content': content})
except Exception as e:
logger.error(f"Error loading instructions: {e}")
return jsonify({'error': str(e)}), 500
# Client usage (HTTP request):
# GET /api/instructions/load/my_template.txt
# Response: {"content": "<file contents>"} or {"error": "<error message>"}
Best Practices
- Always validate file paths to prevent directory traversal attacks using os.path.abspath() comparison
- Use UTF-8 encoding when reading text files to handle international characters
- Implement proper error handling with appropriate HTTP status codes (400 for client errors, 404 for not found, 500 for server errors)
- Log errors for debugging and monitoring purposes
- Use context managers (with statement) for file operations to ensure proper resource cleanup
- Consider implementing additional security measures like file extension validation or content sanitization
- Ensure the instructions directory exists before deploying the application
- Consider implementing rate limiting to prevent abuse of the endpoint
- Use secure_filename() from werkzeug.utils if accepting user-provided filenames to sanitize input
- Consider caching frequently accessed instruction files to improve performance
Tags
Similar Components
AI-powered semantic similarity - components with related functionality:
-
function save_custom_instructions 78.4% similar
-
function list_custom_instructions 76.5% similar
-
function api_load_template 71.6% similar
-
function api_load_template_v2 68.7% similar
-
function get_instruction_templates 61.3% similar