File size: 8,714 Bytes
7ce9fc3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
# Utility functions for LLM Code Deployment API

import os
import json
import base64
import logging
import tempfile
from datetime import datetime
from typing import List, Dict, Any

logger = logging.getLogger(__name__)

def save_request_log(request_data: Dict[str, Any]) -> str:
    """
    Save request data to a log file for debugging and audit purposes
    
    Args:
        request_data: The complete request data
        
    Returns:
        Path to the saved log file
    """
    try:
        # Create logs directory if it doesn't exist
        logs_dir = os.path.join(os.getcwd(), 'logs')
        os.makedirs(logs_dir, exist_ok=True)
        
        # Generate filename with timestamp
        timestamp = datetime.utcnow().strftime("%Y%m%d_%H%M%S")
        email_safe = request_data.get('email', 'unknown').replace('@', '_at_').replace('.', '_')
        task_id = request_data.get('task', 'unknown')
        round_num = request_data.get('round', 0)
        
        filename = f"{timestamp}_{email_safe}_{task_id}_round{round_num}.json"
        log_path = os.path.join(logs_dir, filename)
        
        # Create a copy without sensitive data for logging
        log_data = dict(request_data)
        if 'secret' in log_data:
            log_data['secret'] = '[REDACTED]'
        
        # Add metadata
        log_data['_metadata'] = {
            'logged_at': datetime.utcnow().isoformat(),
            'log_file': filename
        }
        
        # Save to file
        with open(log_path, 'w', encoding='utf-8') as f:
            json.dump(log_data, f, indent=2, ensure_ascii=False)
        
        logger.info(f"Request logged to {log_path}")
        return log_path
        
    except Exception as e:
        logger.error(f"Failed to save request log: {str(e)}")
        return ""

def decode_attachments(attachments: List[Dict[str, Any]], task_id: str) -> List[str]:
    """
    Decode base64 attachments and save to temporary files
    
    Args:
        attachments: List of attachment objects with 'filename' and 'content' (base64)
        task_id: Task identifier for unique naming
        
    Returns:
        List of file paths to decoded attachments
    """
    attachment_files = []
    
    try:
        # Create temp directory for this task
        temp_dir = os.path.join(tempfile.gettempdir(), f"task_{task_id}")
        os.makedirs(temp_dir, exist_ok=True)
        
        for i, attachment in enumerate(attachments):
            try:
                # Get filename and content
                filename = attachment.get('filename', f'attachment_{i}')
                content_b64 = attachment.get('content', '')
                
                if not content_b64:
                    logger.warning(f"Empty content for attachment {filename}")
                    continue
                
                # Decode base64 content
                try:
                    content_bytes = base64.b64decode(content_b64)
                except Exception as e:
                    logger.error(f"Failed to decode base64 for {filename}: {str(e)}")
                    continue
                
                # Save to temporary file
                file_path = os.path.join(temp_dir, filename)
                
                # Determine if content is text or binary
                try:
                    # Try to decode as text first
                    content_text = content_bytes.decode('utf-8')
                    with open(file_path, 'w', encoding='utf-8') as f:
                        f.write(content_text)
                except UnicodeDecodeError:
                    # Save as binary
                    with open(file_path, 'wb') as f:
                        f.write(content_bytes)
                
                attachment_files.append(file_path)
                logger.info(f"Decoded attachment: {filename} -> {file_path}")
                
            except Exception as e:
                logger.error(f"Failed to process attachment {i}: {str(e)}")
                continue
        
        return attachment_files
        
    except Exception as e:
        logger.error(f"Failed to decode attachments: {str(e)}")
        return []

def create_license_file() -> str:
    """
    Create MIT license content
    
    Returns:
        MIT license text
    """
    current_year = datetime.utcnow().year
    
    return f"""MIT License
Copyright (c) {current_year} Student Project
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""

def validate_json_structure(data: Dict[str, Any]) -> List[str]:
    """
    Validate the structure of incoming JSON requests
    
    Args:
        data: Request data to validate
        
    Returns:
        List of validation errors (empty if valid)
    """
    errors = []
    
    # Required fields
    required_fields = {
        'email': str,
        'secret': str,
        'task': str,
        'round': int,
        'nonce': str,
        'brief': str,
        'evaluation_url': str
    }
    
    for field, expected_type in required_fields.items():
        if field not in data:
            errors.append(f"Missing required field: {field}")
        elif not isinstance(data[field], expected_type):
            errors.append(f"Field {field} must be of type {expected_type.__name__}")
    
    # Validate round number
    if 'round' in data and data['round'] not in [1, 2]:
        errors.append("Round must be 1 or 2")
    
    # Validate email format (basic)
    if 'email' in data:
        email = data['email']
        if '@' not in email or '.' not in email.split('@')[-1]:
            errors.append("Invalid email format")
    
    # Validate URL format (basic)
    if 'evaluation_url' in data:
        url = data['evaluation_url']
        if not url.startswith(('http://', 'https://')):
            errors.append("Evaluation URL must start with http:// or https://")
    
    # Validate attachments structure if present
    if 'attachments' in data:
        attachments = data['attachments']
        if not isinstance(attachments, list):
            errors.append("Attachments must be a list")
        else:
            for i, attachment in enumerate(attachments):
                if not isinstance(attachment, dict):
                    errors.append(f"Attachment {i} must be an object")
                elif 'filename' not in attachment or 'content' not in attachment:
                    errors.append(f"Attachment {i} must have filename and content fields")
    
    return errors

def cleanup_temp_files(task_id: str):
    """
    Clean up temporary files for a task
    
    Args:
        task_id: Task identifier
    """
    try:
        temp_dir = os.path.join(tempfile.gettempdir(), f"task_{task_id}")
        if os.path.exists(temp_dir):
            import shutil
            shutil.rmtree(temp_dir)
            logger.info(f"Cleaned up temp directory: {temp_dir}")
    except Exception as e:
        logger.warning(f"Failed to cleanup temp files for {task_id}: {str(e)}")

def sanitize_filename(filename: str) -> str:
    """
    Sanitize a filename to be safe for filesystem use
    
    Args:
        filename: Original filename
        
    Returns:
        Sanitized filename
    """
    import re
    
    # Replace unsafe characters with underscores
    safe_filename = re.sub(r'[<>:"/\\|?*]', '_', filename)
    
    # Remove or replace other problematic characters
    safe_filename = safe_filename.replace(' ', '_')
    safe_filename = re.sub(r'_{2,}', '_', safe_filename)  # Multiple underscores to single
    safe_filename = safe_filename.strip('_')  # Remove leading/trailing underscores
    
    # Ensure it's not empty
    if not safe_filename:
        safe_filename = 'unnamed_file'
    
    return safe_filename