🔍 Code Extractor

function load_custom_instructions

Maturity: 50

Flask API endpoint that loads and returns the content of custom instruction files from a designated instructions directory with security validation.

File:
/tf/active/vicechatdev/docchat/app.py
Lines:
1716 - 1736
Complexity:
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

  • flask
  • os
  • logging

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

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function save_custom_instructions 78.4% similar

    Flask API endpoint that saves custom instructions to a markdown file in a designated instructions directory with filename sanitization.

    From: /tf/active/vicechatdev/docchat/app.py
  • function list_custom_instructions 76.5% similar

    Flask API endpoint that retrieves and returns a list of all custom instruction markdown files stored in the 'instructions' directory.

    From: /tf/active/vicechatdev/docchat/app.py
  • function api_load_template 71.6% similar

    Flask API endpoint that loads and returns instruction template content by template name, with authentication required.

    From: /tf/active/vicechatdev/vice_ai/app.py
  • function api_load_template_v2 68.7% similar

    Flask API endpoint that retrieves and returns an instruction template by name from the chat engine.

    From: /tf/active/vicechatdev/vice_ai/complex_app.py
  • function get_instruction_templates 61.3% similar

    Flask API endpoint that returns a dictionary of predefined instruction templates for different document types including SOPs, work instructions, quality forms, and document comparison guidelines.

    From: /tf/active/vicechatdev/docchat/app.py
← Back to Browse