Spaces:
Running
Running
milwright
commited on
Commit
Β·
f8cd41a
1
Parent(s):
a2232be
Add configuration templates and faculty documentation
Browse files- config_editor_template.py: Basic configuration interface
- enhanced_space_template.py: Advanced space configuration with dynamic fields
- secure_config_editor.py: Secure handling of sensitive configuration data
- faculty_config_guide.md: Step-by-step setup instructions for faculty
- test_faculty_password.py: Password validation test suite
- config_editor_template.py +112 -0
- enhanced_space_template.py +113 -0
- faculty_config_guide.md +181 -0
- secure_config_editor.py +247 -0
- test_faculty_password.py +374 -0
config_editor_template.py
ADDED
|
@@ -0,0 +1,112 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Config Editor Component for Deployed Spaces
|
| 2 |
+
# This can be integrated into the deployed app.py
|
| 3 |
+
|
| 4 |
+
import json
|
| 5 |
+
import gradio as gr
|
| 6 |
+
import os
|
| 7 |
+
|
| 8 |
+
def load_config():
|
| 9 |
+
"""Load configuration from config.json"""
|
| 10 |
+
try:
|
| 11 |
+
with open('config.json', 'r') as f:
|
| 12 |
+
return json.load(f)
|
| 13 |
+
except Exception as e:
|
| 14 |
+
return {"error": f"Failed to load config: {str(e)}"}
|
| 15 |
+
|
| 16 |
+
def save_config(system_prompt, temperature, max_tokens, examples_text, grounding_urls_text):
|
| 17 |
+
"""Save configuration back to config.json"""
|
| 18 |
+
try:
|
| 19 |
+
# Load existing config
|
| 20 |
+
config = load_config()
|
| 21 |
+
|
| 22 |
+
# Update modifiable fields
|
| 23 |
+
config['system_prompt'] = system_prompt
|
| 24 |
+
config['temperature'] = temperature
|
| 25 |
+
config['max_tokens'] = int(max_tokens)
|
| 26 |
+
|
| 27 |
+
# Parse examples (one per line)
|
| 28 |
+
if examples_text:
|
| 29 |
+
examples = [ex.strip() for ex in examples_text.split('\n') if ex.strip()]
|
| 30 |
+
config['examples'] = str(examples)
|
| 31 |
+
|
| 32 |
+
# Parse grounding URLs
|
| 33 |
+
if grounding_urls_text:
|
| 34 |
+
urls = [url.strip() for url in grounding_urls_text.split('\n') if url.strip()]
|
| 35 |
+
config['grounding_urls'] = json.dumps(urls)
|
| 36 |
+
|
| 37 |
+
# Save config
|
| 38 |
+
with open('config.json', 'w') as f:
|
| 39 |
+
json.dump(config, f, indent=2)
|
| 40 |
+
|
| 41 |
+
return "β
Configuration saved successfully! Refresh the page to apply changes."
|
| 42 |
+
except Exception as e:
|
| 43 |
+
return f"β Error saving config: {str(e)}"
|
| 44 |
+
|
| 45 |
+
def create_config_editor():
|
| 46 |
+
"""Create the configuration editor interface"""
|
| 47 |
+
config = load_config()
|
| 48 |
+
|
| 49 |
+
with gr.Group():
|
| 50 |
+
gr.Markdown("### Configuration Editor")
|
| 51 |
+
gr.Markdown("Edit your assistant's configuration below. Changes require a page refresh to take effect.")
|
| 52 |
+
|
| 53 |
+
with gr.Row():
|
| 54 |
+
with gr.Column(scale=2):
|
| 55 |
+
system_prompt = gr.TextArea(
|
| 56 |
+
label="System Prompt",
|
| 57 |
+
value=config.get('system_prompt', ''),
|
| 58 |
+
lines=10,
|
| 59 |
+
placeholder="Define your assistant's role and behavior..."
|
| 60 |
+
)
|
| 61 |
+
|
| 62 |
+
with gr.Column(scale=1):
|
| 63 |
+
temperature = gr.Slider(
|
| 64 |
+
label="Temperature",
|
| 65 |
+
minimum=0.0,
|
| 66 |
+
maximum=2.0,
|
| 67 |
+
step=0.1,
|
| 68 |
+
value=config.get('temperature', 0.7)
|
| 69 |
+
)
|
| 70 |
+
|
| 71 |
+
max_tokens = gr.Number(
|
| 72 |
+
label="Max Response Tokens",
|
| 73 |
+
value=config.get('max_tokens', 500),
|
| 74 |
+
minimum=50,
|
| 75 |
+
maximum=8000
|
| 76 |
+
)
|
| 77 |
+
|
| 78 |
+
examples_text = gr.TextArea(
|
| 79 |
+
label="Example Prompts (one per line)",
|
| 80 |
+
value='\n'.join(eval(config.get('examples', '[]'))),
|
| 81 |
+
lines=5,
|
| 82 |
+
placeholder="What is machine learning?\nExplain quantum computing\nHow do neural networks work?"
|
| 83 |
+
)
|
| 84 |
+
|
| 85 |
+
grounding_urls_text = gr.TextArea(
|
| 86 |
+
label="Grounding URLs (one per line)",
|
| 87 |
+
value='\n'.join(json.loads(config.get('grounding_urls', '[]'))),
|
| 88 |
+
lines=5,
|
| 89 |
+
placeholder="https://example.com/docs\nhttps://wiki.example.com"
|
| 90 |
+
)
|
| 91 |
+
|
| 92 |
+
save_btn = gr.Button("πΎ Save Configuration", variant="primary")
|
| 93 |
+
status = gr.Markdown("")
|
| 94 |
+
|
| 95 |
+
save_btn.click(
|
| 96 |
+
save_config,
|
| 97 |
+
inputs=[system_prompt, temperature, max_tokens, examples_text, grounding_urls_text],
|
| 98 |
+
outputs=status
|
| 99 |
+
)
|
| 100 |
+
|
| 101 |
+
gr.Markdown("""
|
| 102 |
+
### Configuration Tips:
|
| 103 |
+
- **System Prompt**: Define your assistant's personality, knowledge, and behavior
|
| 104 |
+
- **Temperature**: Lower values (0.0-0.5) for focused responses, higher (0.7-1.5) for creativity
|
| 105 |
+
- **Max Tokens**: Limit response length (1 token β 0.75 words)
|
| 106 |
+
- **Examples**: Provide sample questions to guide users
|
| 107 |
+
- **Grounding URLs**: Add reference websites for context
|
| 108 |
+
|
| 109 |
+
β οΈ **Note**: Model selection and API key cannot be changed here for security reasons.
|
| 110 |
+
""")
|
| 111 |
+
|
| 112 |
+
return config
|
enhanced_space_template.py
ADDED
|
@@ -0,0 +1,113 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Enhanced Space Template that loads from config.json
|
| 2 |
+
# This shows how the deployed app.py should be modified
|
| 3 |
+
|
| 4 |
+
import json
|
| 5 |
+
import os
|
| 6 |
+
|
| 7 |
+
# Load configuration from config.json at startup
|
| 8 |
+
def load_configuration():
|
| 9 |
+
"""Load configuration from config.json with fallbacks"""
|
| 10 |
+
try:
|
| 11 |
+
with open('config.json', 'r') as f:
|
| 12 |
+
config = json.load(f)
|
| 13 |
+
print("β
Configuration loaded from config.json")
|
| 14 |
+
return config
|
| 15 |
+
except FileNotFoundError:
|
| 16 |
+
print("β οΈ config.json not found, using embedded defaults")
|
| 17 |
+
# Fallback to embedded configuration
|
| 18 |
+
return {
|
| 19 |
+
'name': 'AI Assistant',
|
| 20 |
+
'description': 'A customizable AI assistant',
|
| 21 |
+
'system_prompt': 'You are a helpful AI assistant.',
|
| 22 |
+
'model': 'gemini/gemini-2.0-flash-thinking-exp-1219',
|
| 23 |
+
'temperature': 0.7,
|
| 24 |
+
'max_tokens': 500,
|
| 25 |
+
'examples': '[]',
|
| 26 |
+
'grounding_urls': '[]',
|
| 27 |
+
'enable_dynamic_urls': False,
|
| 28 |
+
'api_key_var': 'OPENROUTER_API_KEY'
|
| 29 |
+
}
|
| 30 |
+
except Exception as e:
|
| 31 |
+
print(f"β Error loading config.json: {str(e)}")
|
| 32 |
+
return None
|
| 33 |
+
|
| 34 |
+
# Initialize configuration
|
| 35 |
+
CONFIG = load_configuration()
|
| 36 |
+
|
| 37 |
+
# Extract configuration values
|
| 38 |
+
SPACE_NAME = CONFIG.get('name', 'AI Assistant')
|
| 39 |
+
SPACE_DESCRIPTION = CONFIG.get('description', 'A customizable AI assistant')
|
| 40 |
+
SYSTEM_PROMPT = CONFIG.get('system_prompt', 'You are a helpful AI assistant.')
|
| 41 |
+
MODEL = CONFIG.get('model', 'gemini/gemini-2.0-flash-thinking-exp-1219')
|
| 42 |
+
TEMPERATURE = CONFIG.get('temperature', 0.7)
|
| 43 |
+
MAX_TOKENS = CONFIG.get('max_tokens', 500)
|
| 44 |
+
GROUNDING_URLS = json.loads(CONFIG.get('grounding_urls', '[]'))
|
| 45 |
+
ENABLE_DYNAMIC_URLS = CONFIG.get('enable_dynamic_urls', False)
|
| 46 |
+
API_KEY_VAR = CONFIG.get('api_key_var', 'OPENROUTER_API_KEY')
|
| 47 |
+
|
| 48 |
+
# Get API key from environment
|
| 49 |
+
API_KEY = os.environ.get(API_KEY_VAR)
|
| 50 |
+
|
| 51 |
+
# Example of how to integrate config editor into the main interface
|
| 52 |
+
def create_interface_with_config():
|
| 53 |
+
"""Create the main interface with configuration tab"""
|
| 54 |
+
import gradio as gr
|
| 55 |
+
|
| 56 |
+
with gr.Blocks(title=SPACE_NAME) as demo:
|
| 57 |
+
gr.Markdown(f"# {SPACE_NAME}")
|
| 58 |
+
gr.Markdown(f"{SPACE_DESCRIPTION}")
|
| 59 |
+
|
| 60 |
+
with gr.Tabs():
|
| 61 |
+
# Main chat tab
|
| 62 |
+
with gr.Tab("π¬ Chat"):
|
| 63 |
+
# ... existing chat interface code ...
|
| 64 |
+
pass
|
| 65 |
+
|
| 66 |
+
# Configuration tab (only show if no access code or user is authenticated)
|
| 67 |
+
with gr.Tab("βοΈ Configuration"):
|
| 68 |
+
# Import and use the config editor
|
| 69 |
+
from config_editor_template import create_config_editor
|
| 70 |
+
create_config_editor()
|
| 71 |
+
|
| 72 |
+
# Help tab
|
| 73 |
+
with gr.Tab("β Help"):
|
| 74 |
+
gr.Markdown("""
|
| 75 |
+
### How to Customize Your Assistant
|
| 76 |
+
|
| 77 |
+
1. **Configuration Tab**: Edit settings directly in the browser
|
| 78 |
+
2. **Files Tab**: For advanced users - edit config.json directly
|
| 79 |
+
3. **Changes**: Refresh the page after saving to apply changes
|
| 80 |
+
|
| 81 |
+
### Configuration File Structure
|
| 82 |
+
|
| 83 |
+
The `config.json` file contains:
|
| 84 |
+
- `system_prompt`: Your assistant's instructions
|
| 85 |
+
- `temperature`: Response randomness (0-2)
|
| 86 |
+
- `max_tokens`: Maximum response length
|
| 87 |
+
- `examples`: Sample prompts for users
|
| 88 |
+
- `grounding_urls`: Reference websites
|
| 89 |
+
|
| 90 |
+
### Best Practices
|
| 91 |
+
|
| 92 |
+
1. **Test Changes**: Try different prompts after each change
|
| 93 |
+
2. **Iterative Refinement**: Make small changes and test
|
| 94 |
+
3. **Backup**: Download config.json before major changes
|
| 95 |
+
4. **Share**: Export your config to share with colleagues
|
| 96 |
+
""")
|
| 97 |
+
|
| 98 |
+
return demo
|
| 99 |
+
|
| 100 |
+
# Reload configuration endpoint for dynamic updates
|
| 101 |
+
def reload_configuration():
|
| 102 |
+
"""Reload configuration without restart - for advanced usage"""
|
| 103 |
+
global CONFIG, SYSTEM_PROMPT, TEMPERATURE, MAX_TOKENS, GROUNDING_URLS
|
| 104 |
+
|
| 105 |
+
new_config = load_configuration()
|
| 106 |
+
if new_config:
|
| 107 |
+
CONFIG = new_config
|
| 108 |
+
SYSTEM_PROMPT = CONFIG.get('system_prompt', SYSTEM_PROMPT)
|
| 109 |
+
TEMPERATURE = CONFIG.get('temperature', TEMPERATURE)
|
| 110 |
+
MAX_TOKENS = CONFIG.get('max_tokens', MAX_TOKENS)
|
| 111 |
+
GROUNDING_URLS = json.loads(CONFIG.get('grounding_urls', '[]'))
|
| 112 |
+
return "β
Configuration reloaded successfully"
|
| 113 |
+
return "β Failed to reload configuration"
|
faculty_config_guide.md
ADDED
|
@@ -0,0 +1,181 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Faculty Configuration Guide
|
| 2 |
+
|
| 3 |
+
## Overview
|
| 4 |
+
|
| 5 |
+
The config.json file serves as a stable reference point for customizing your deployed AI assistant on Hugging Face Spaces. This guide explains how to securely manage and iterate on your assistant's configuration.
|
| 6 |
+
|
| 7 |
+
## Security Model
|
| 8 |
+
|
| 9 |
+
### Faculty-Only Access
|
| 10 |
+
- Configuration editing is restricted to faculty members only
|
| 11 |
+
- Students can use the chatbot but cannot modify settings
|
| 12 |
+
- Access is controlled via a faculty password set in environment variables
|
| 13 |
+
|
| 14 |
+
### Setting Up Faculty Access
|
| 15 |
+
|
| 16 |
+
1. **In your Hugging Face Space Settings:**
|
| 17 |
+
```
|
| 18 |
+
Settings β Variables and secrets β New secret
|
| 19 |
+
|
| 20 |
+
Name: FACULTY_CONFIG_PASSWORD
|
| 21 |
+
Value: [your-secure-password]
|
| 22 |
+
```
|
| 23 |
+
|
| 24 |
+
2. **Alternative Token-Based Access:**
|
| 25 |
+
```
|
| 26 |
+
Name: CONFIG_EDIT_TOKEN
|
| 27 |
+
Value: [generated-secure-token]
|
| 28 |
+
```
|
| 29 |
+
|
| 30 |
+
## Configuration Workflow
|
| 31 |
+
|
| 32 |
+
### Initial Deployment
|
| 33 |
+
|
| 34 |
+
1. **Generate deployment package** using ChatUI Helper
|
| 35 |
+
2. **Upload to Hugging Face:**
|
| 36 |
+
- app.py
|
| 37 |
+
- config.json
|
| 38 |
+
- requirements.txt
|
| 39 |
+
|
| 40 |
+
3. **Set environment variables:**
|
| 41 |
+
- `OPENROUTER_API_KEY`: Your API key
|
| 42 |
+
- `FACULTY_CONFIG_PASSWORD`: Faculty access code
|
| 43 |
+
- `SPACE_ACCESS_CODE`: (Optional) General access control
|
| 44 |
+
|
| 45 |
+
### Iterative Customization
|
| 46 |
+
|
| 47 |
+
1. **Access Configuration Tab:**
|
| 48 |
+
- Navigate to your deployed space
|
| 49 |
+
- Click "βοΈ Configuration" tab
|
| 50 |
+
- Enter faculty access code
|
| 51 |
+
|
| 52 |
+
2. **Edit Settings:**
|
| 53 |
+
- **System Prompt**: Refine assistant behavior
|
| 54 |
+
- **Temperature**: Adjust response creativity
|
| 55 |
+
- **Max Tokens**: Control response length
|
| 56 |
+
- **Examples**: Update sample prompts
|
| 57 |
+
- **Grounding URLs**: Add/remove reference sites
|
| 58 |
+
|
| 59 |
+
3. **Save and Test:**
|
| 60 |
+
- Click "πΎ Save Configuration"
|
| 61 |
+
- Refresh page to apply changes
|
| 62 |
+
- Test with students before finalizing
|
| 63 |
+
|
| 64 |
+
## config.json Structure
|
| 65 |
+
|
| 66 |
+
```json
|
| 67 |
+
{
|
| 68 |
+
"name": "AI Assistant",
|
| 69 |
+
"description": "A customizable AI assistant",
|
| 70 |
+
"system_prompt": "You are a helpful teaching assistant...",
|
| 71 |
+
"model": "gemini/gemini-2.0-flash-thinking-exp-1219",
|
| 72 |
+
"temperature": 0.7,
|
| 73 |
+
"max_tokens": 500,
|
| 74 |
+
"examples": "['What is machine learning?', 'Explain neural networks']",
|
| 75 |
+
"grounding_urls": "[\"https://course-website.edu\"]",
|
| 76 |
+
"api_key_var": "OPENROUTER_API_KEY",
|
| 77 |
+
"enable_dynamic_urls": false,
|
| 78 |
+
"locked": false,
|
| 79 |
+
"lock_reason": "",
|
| 80 |
+
"last_modified_by": "faculty",
|
| 81 |
+
"last_modified_at": "2024-01-15 10:30:00"
|
| 82 |
+
}
|
| 83 |
+
```
|
| 84 |
+
|
| 85 |
+
## Best Practices
|
| 86 |
+
|
| 87 |
+
### 1. Iterative Refinement
|
| 88 |
+
- Start with a basic configuration
|
| 89 |
+
- Test with sample student queries
|
| 90 |
+
- Refine based on actual usage
|
| 91 |
+
- Document changes for other faculty
|
| 92 |
+
|
| 93 |
+
### 2. System Prompt Engineering
|
| 94 |
+
```
|
| 95 |
+
You are a teaching assistant for [Course Name].
|
| 96 |
+
Your role is to:
|
| 97 |
+
- Answer questions about course material
|
| 98 |
+
- Guide students without giving direct answers
|
| 99 |
+
- Encourage critical thinking
|
| 100 |
+
- Reference course materials when relevant
|
| 101 |
+
|
| 102 |
+
Important guidelines:
|
| 103 |
+
- Do not provide solutions to assignments
|
| 104 |
+
- Redirect homework questions to office hours
|
| 105 |
+
- Maintain academic integrity
|
| 106 |
+
```
|
| 107 |
+
|
| 108 |
+
### 3. Configuration Locking
|
| 109 |
+
- Lock configuration during exams
|
| 110 |
+
- Prevents accidental changes
|
| 111 |
+
- Clear communication with lock reason
|
| 112 |
+
|
| 113 |
+
### 4. Backup Strategy
|
| 114 |
+
- Export configuration before major changes
|
| 115 |
+
- Share configurations between courses
|
| 116 |
+
- Version control for semester changes
|
| 117 |
+
|
| 118 |
+
## Advanced Features
|
| 119 |
+
|
| 120 |
+
### Configuration Import/Export
|
| 121 |
+
1. **Export current config:**
|
| 122 |
+
- Click "π₯ Export Config"
|
| 123 |
+
- Save for backup or sharing
|
| 124 |
+
|
| 125 |
+
2. **Import configuration:**
|
| 126 |
+
- Click "π€ Import Config"
|
| 127 |
+
- Select JSON file
|
| 128 |
+
- Review changes before saving
|
| 129 |
+
|
| 130 |
+
### Grounding URLs
|
| 131 |
+
- Add course websites
|
| 132 |
+
- Include syllabus links
|
| 133 |
+
- Reference documentation
|
| 134 |
+
- Limit to trusted sources
|
| 135 |
+
|
| 136 |
+
### Access Control Hierarchy
|
| 137 |
+
1. **Space Access Code**: Controls who can use the chatbot
|
| 138 |
+
2. **Faculty Password**: Controls who can edit configuration
|
| 139 |
+
3. **Configuration Lock**: Temporary edit prevention
|
| 140 |
+
|
| 141 |
+
## Troubleshooting
|
| 142 |
+
|
| 143 |
+
### Common Issues
|
| 144 |
+
|
| 145 |
+
**Cannot save configuration:**
|
| 146 |
+
- Verify faculty password is correct
|
| 147 |
+
- Check if configuration is locked
|
| 148 |
+
- Ensure proper JSON formatting
|
| 149 |
+
|
| 150 |
+
**Changes not taking effect:**
|
| 151 |
+
- Refresh the page after saving
|
| 152 |
+
- Clear browser cache if needed
|
| 153 |
+
- Check browser console for errors
|
| 154 |
+
|
| 155 |
+
**Students report access issues:**
|
| 156 |
+
- Verify SPACE_ACCESS_CODE if set
|
| 157 |
+
- Check API key configuration
|
| 158 |
+
- Review recent configuration changes
|
| 159 |
+
|
| 160 |
+
### Configuration Recovery
|
| 161 |
+
|
| 162 |
+
If configuration becomes corrupted:
|
| 163 |
+
1. Access Space Files directly
|
| 164 |
+
2. Download config_backup_*.json
|
| 165 |
+
3. Rename to config.json
|
| 166 |
+
4. Restart space
|
| 167 |
+
|
| 168 |
+
## Security Considerations
|
| 169 |
+
|
| 170 |
+
1. **Never share faculty password with students**
|
| 171 |
+
2. **Rotate passwords each semester**
|
| 172 |
+
3. **Monitor configuration changes**
|
| 173 |
+
4. **Use environment variables for sensitive data**
|
| 174 |
+
5. **Review grounding URLs regularly**
|
| 175 |
+
|
| 176 |
+
## Support
|
| 177 |
+
|
| 178 |
+
For additional help:
|
| 179 |
+
- Check the ChatUI Helper documentation
|
| 180 |
+
- Contact your institution's IT support
|
| 181 |
+
- Review Hugging Face Spaces documentation
|
secure_config_editor.py
ADDED
|
@@ -0,0 +1,247 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Secure Config Editor with Faculty-Only Access
|
| 2 |
+
# This ensures only authorized faculty can edit configuration
|
| 3 |
+
|
| 4 |
+
import json
|
| 5 |
+
import gradio as gr
|
| 6 |
+
import os
|
| 7 |
+
import hashlib
|
| 8 |
+
import secrets
|
| 9 |
+
|
| 10 |
+
# Faculty authentication using environment variable
|
| 11 |
+
FACULTY_ACCESS_CODE = os.environ.get("FACULTY_CONFIG_PASSWORD")
|
| 12 |
+
CONFIG_EDIT_TOKEN = os.environ.get("CONFIG_EDIT_TOKEN") # Alternative: use a secret token
|
| 13 |
+
|
| 14 |
+
def verify_faculty_access(password):
|
| 15 |
+
"""Verify if the user has faculty access"""
|
| 16 |
+
if not FACULTY_ACCESS_CODE:
|
| 17 |
+
return False, "β Faculty access not configured. Contact administrator."
|
| 18 |
+
|
| 19 |
+
if password == FACULTY_ACCESS_CODE:
|
| 20 |
+
return True, "β
Faculty access granted"
|
| 21 |
+
|
| 22 |
+
return False, "β Invalid access code"
|
| 23 |
+
|
| 24 |
+
def create_secure_config_editor():
|
| 25 |
+
"""Create the configuration editor with faculty authentication"""
|
| 26 |
+
|
| 27 |
+
# State to track authentication
|
| 28 |
+
is_authenticated = gr.State(False)
|
| 29 |
+
|
| 30 |
+
with gr.Group() as config_editor:
|
| 31 |
+
gr.Markdown("### π Faculty Configuration Editor")
|
| 32 |
+
|
| 33 |
+
# Authentication section
|
| 34 |
+
with gr.Group(visible=True) as auth_section:
|
| 35 |
+
gr.Markdown("This section is restricted to faculty members only.")
|
| 36 |
+
|
| 37 |
+
with gr.Row():
|
| 38 |
+
access_code = gr.Textbox(
|
| 39 |
+
label="Faculty Access Code",
|
| 40 |
+
type="password",
|
| 41 |
+
placeholder="Enter your faculty access code"
|
| 42 |
+
)
|
| 43 |
+
auth_btn = gr.Button("π Authenticate", variant="primary")
|
| 44 |
+
|
| 45 |
+
auth_status = gr.Markdown("")
|
| 46 |
+
|
| 47 |
+
# Configuration editor (hidden until authenticated)
|
| 48 |
+
with gr.Group(visible=False) as editor_section:
|
| 49 |
+
config = load_config()
|
| 50 |
+
|
| 51 |
+
gr.Markdown("### βοΈ Edit Assistant Configuration")
|
| 52 |
+
gr.Markdown("**Note**: Students cannot access this section. Changes affect all users.")
|
| 53 |
+
|
| 54 |
+
with gr.Row():
|
| 55 |
+
with gr.Column(scale=2):
|
| 56 |
+
system_prompt = gr.TextArea(
|
| 57 |
+
label="System Prompt",
|
| 58 |
+
value=config.get('system_prompt', ''),
|
| 59 |
+
lines=10,
|
| 60 |
+
placeholder="Define your assistant's role and behavior..."
|
| 61 |
+
)
|
| 62 |
+
|
| 63 |
+
with gr.Column(scale=1):
|
| 64 |
+
temperature = gr.Slider(
|
| 65 |
+
label="Temperature",
|
| 66 |
+
minimum=0.0,
|
| 67 |
+
maximum=2.0,
|
| 68 |
+
step=0.1,
|
| 69 |
+
value=config.get('temperature', 0.7)
|
| 70 |
+
)
|
| 71 |
+
|
| 72 |
+
max_tokens = gr.Number(
|
| 73 |
+
label="Max Response Tokens",
|
| 74 |
+
value=config.get('max_tokens', 500),
|
| 75 |
+
minimum=50,
|
| 76 |
+
maximum=8000
|
| 77 |
+
)
|
| 78 |
+
|
| 79 |
+
examples_text = gr.TextArea(
|
| 80 |
+
label="Example Prompts (one per line)",
|
| 81 |
+
value='\n'.join(eval(config.get('examples', '[]'))),
|
| 82 |
+
lines=5,
|
| 83 |
+
placeholder="What is machine learning?\nExplain quantum computing"
|
| 84 |
+
)
|
| 85 |
+
|
| 86 |
+
grounding_urls_text = gr.TextArea(
|
| 87 |
+
label="Grounding URLs (one per line)",
|
| 88 |
+
value='\n'.join(json.loads(config.get('grounding_urls', '[]'))),
|
| 89 |
+
lines=5,
|
| 90 |
+
placeholder="https://example.com/course-materials"
|
| 91 |
+
)
|
| 92 |
+
|
| 93 |
+
with gr.Row():
|
| 94 |
+
save_btn = gr.Button("πΎ Save Configuration", variant="primary")
|
| 95 |
+
export_btn = gr.Button("π₯ Export Config", variant="secondary")
|
| 96 |
+
import_btn = gr.Button("π€ Import Config", variant="secondary")
|
| 97 |
+
|
| 98 |
+
config_file = gr.File(label="Import Configuration", visible=False)
|
| 99 |
+
|
| 100 |
+
status = gr.Markdown("")
|
| 101 |
+
|
| 102 |
+
# Lock/Unlock settings for specific periods
|
| 103 |
+
with gr.Accordion("π Advanced: Lock Settings", open=False):
|
| 104 |
+
gr.Markdown("""
|
| 105 |
+
**Lock Configuration During Exams**
|
| 106 |
+
|
| 107 |
+
You can temporarily lock the configuration to prevent changes during exams or assessments.
|
| 108 |
+
""")
|
| 109 |
+
|
| 110 |
+
lock_config = gr.Checkbox(
|
| 111 |
+
label="Lock configuration (prevents all changes)",
|
| 112 |
+
value=config.get('locked', False)
|
| 113 |
+
)
|
| 114 |
+
|
| 115 |
+
lock_reason = gr.Textbox(
|
| 116 |
+
label="Lock reason (visible to other faculty)",
|
| 117 |
+
placeholder="e.g., Midterm exam in progress"
|
| 118 |
+
)
|
| 119 |
+
|
| 120 |
+
# Authentication handler
|
| 121 |
+
def authenticate(password):
|
| 122 |
+
success, message = verify_faculty_access(password)
|
| 123 |
+
if success:
|
| 124 |
+
return {
|
| 125 |
+
auth_status: message,
|
| 126 |
+
auth_section: gr.update(visible=False),
|
| 127 |
+
editor_section: gr.update(visible=True),
|
| 128 |
+
is_authenticated: True
|
| 129 |
+
}
|
| 130 |
+
else:
|
| 131 |
+
return {
|
| 132 |
+
auth_status: message,
|
| 133 |
+
is_authenticated: False
|
| 134 |
+
}
|
| 135 |
+
|
| 136 |
+
# Save configuration handler
|
| 137 |
+
def save_config_secure(auth_state, system_prompt, temperature, max_tokens,
|
| 138 |
+
examples_text, grounding_urls_text, lock_config, lock_reason):
|
| 139 |
+
if not auth_state:
|
| 140 |
+
return "β Unauthorized: Please authenticate first"
|
| 141 |
+
|
| 142 |
+
try:
|
| 143 |
+
config = load_config()
|
| 144 |
+
|
| 145 |
+
# Check if configuration is locked
|
| 146 |
+
if config.get('locked', False) and not lock_config:
|
| 147 |
+
lock_info = config.get('lock_reason', 'Unknown reason')
|
| 148 |
+
return f"β Configuration is locked: {lock_info}"
|
| 149 |
+
|
| 150 |
+
# Update configuration
|
| 151 |
+
config['system_prompt'] = system_prompt
|
| 152 |
+
config['temperature'] = temperature
|
| 153 |
+
config['max_tokens'] = int(max_tokens)
|
| 154 |
+
config['locked'] = lock_config
|
| 155 |
+
config['lock_reason'] = lock_reason if lock_config else ""
|
| 156 |
+
|
| 157 |
+
# Parse examples
|
| 158 |
+
if examples_text:
|
| 159 |
+
examples = [ex.strip() for ex in examples_text.split('\n') if ex.strip()]
|
| 160 |
+
config['examples'] = str(examples)
|
| 161 |
+
|
| 162 |
+
# Parse URLs
|
| 163 |
+
if grounding_urls_text:
|
| 164 |
+
urls = [url.strip() for url in grounding_urls_text.split('\n') if url.strip()]
|
| 165 |
+
config['grounding_urls'] = json.dumps(urls)
|
| 166 |
+
|
| 167 |
+
# Add audit trail
|
| 168 |
+
config['last_modified_by'] = 'faculty'
|
| 169 |
+
config['last_modified_at'] = str(datetime.now())
|
| 170 |
+
|
| 171 |
+
# Save with backup
|
| 172 |
+
backup_config()
|
| 173 |
+
with open('config.json', 'w') as f:
|
| 174 |
+
json.dump(config, f, indent=2)
|
| 175 |
+
|
| 176 |
+
return f"β
Configuration saved successfully! {'π Config is now LOCKED' if lock_config else ''}"
|
| 177 |
+
|
| 178 |
+
except Exception as e:
|
| 179 |
+
return f"β Error saving config: {str(e)}"
|
| 180 |
+
|
| 181 |
+
# Export configuration
|
| 182 |
+
def export_config_secure(auth_state):
|
| 183 |
+
if not auth_state:
|
| 184 |
+
return None, "β Unauthorized"
|
| 185 |
+
|
| 186 |
+
try:
|
| 187 |
+
# Create a sanitized version for export
|
| 188 |
+
config = load_config()
|
| 189 |
+
export_data = {
|
| 190 |
+
'system_prompt': config.get('system_prompt'),
|
| 191 |
+
'temperature': config.get('temperature'),
|
| 192 |
+
'max_tokens': config.get('max_tokens'),
|
| 193 |
+
'examples': config.get('examples'),
|
| 194 |
+
'grounding_urls': config.get('grounding_urls'),
|
| 195 |
+
'exported_at': str(datetime.now()),
|
| 196 |
+
'exported_by': 'faculty'
|
| 197 |
+
}
|
| 198 |
+
|
| 199 |
+
filename = f"assistant_config_{datetime.now().strftime('%Y%m%d_%H%M%S')}.json"
|
| 200 |
+
with open(filename, 'w') as f:
|
| 201 |
+
json.dump(export_data, f, indent=2)
|
| 202 |
+
|
| 203 |
+
return filename, "β
Configuration exported successfully"
|
| 204 |
+
except Exception as e:
|
| 205 |
+
return None, f"β Export failed: {str(e)}"
|
| 206 |
+
|
| 207 |
+
# Wire up event handlers
|
| 208 |
+
auth_btn.click(
|
| 209 |
+
authenticate,
|
| 210 |
+
inputs=[access_code],
|
| 211 |
+
outputs=[auth_status, auth_section, editor_section, is_authenticated]
|
| 212 |
+
)
|
| 213 |
+
|
| 214 |
+
save_btn.click(
|
| 215 |
+
save_config_secure,
|
| 216 |
+
inputs=[is_authenticated, system_prompt, temperature, max_tokens,
|
| 217 |
+
examples_text, grounding_urls_text, lock_config, lock_reason],
|
| 218 |
+
outputs=status
|
| 219 |
+
)
|
| 220 |
+
|
| 221 |
+
export_btn.click(
|
| 222 |
+
export_config_secure,
|
| 223 |
+
inputs=[is_authenticated],
|
| 224 |
+
outputs=[config_file, status]
|
| 225 |
+
)
|
| 226 |
+
|
| 227 |
+
return config_editor
|
| 228 |
+
|
| 229 |
+
def load_config():
|
| 230 |
+
"""Load configuration from config.json"""
|
| 231 |
+
try:
|
| 232 |
+
with open('config.json', 'r') as f:
|
| 233 |
+
return json.load(f)
|
| 234 |
+
except Exception as e:
|
| 235 |
+
return {"error": f"Failed to load config: {str(e)}"}
|
| 236 |
+
|
| 237 |
+
def backup_config():
|
| 238 |
+
"""Create a backup of the current configuration"""
|
| 239 |
+
try:
|
| 240 |
+
config = load_config()
|
| 241 |
+
backup_name = f"config_backup_{datetime.now().strftime('%Y%m%d_%H%M%S')}.json"
|
| 242 |
+
with open(f"backups/{backup_name}", 'w') as f:
|
| 243 |
+
json.dump(config, f, indent=2)
|
| 244 |
+
except:
|
| 245 |
+
pass # Silent fail for backup
|
| 246 |
+
|
| 247 |
+
from datetime import datetime
|
test_faculty_password.py
ADDED
|
@@ -0,0 +1,374 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""
|
| 3 |
+
Faculty Config Password Testing Suite
|
| 4 |
+
Tests authentication flow and security for faculty-only configuration access
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
import os
|
| 8 |
+
import json
|
| 9 |
+
import tempfile
|
| 10 |
+
import shutil
|
| 11 |
+
from datetime import datetime
|
| 12 |
+
import pytest
|
| 13 |
+
import gradio as gr
|
| 14 |
+
from unittest.mock import patch, MagicMock
|
| 15 |
+
|
| 16 |
+
# Import the modules to test
|
| 17 |
+
from secure_config_editor import verify_faculty_access, create_secure_config_editor, load_config
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
class TestFacultyPasswordAuthentication:
|
| 21 |
+
"""Test suite for faculty password authentication"""
|
| 22 |
+
|
| 23 |
+
def setup_method(self):
|
| 24 |
+
"""Set up test environment before each test"""
|
| 25 |
+
self.test_password = "test_faculty_123"
|
| 26 |
+
self.original_env = os.environ.copy()
|
| 27 |
+
os.environ["FACULTY_CONFIG_PASSWORD"] = self.test_password
|
| 28 |
+
|
| 29 |
+
# Create temporary config file
|
| 30 |
+
self.test_config = {
|
| 31 |
+
"system_prompt": "Test prompt",
|
| 32 |
+
"temperature": 0.7,
|
| 33 |
+
"max_tokens": 500,
|
| 34 |
+
"examples": "['Example 1', 'Example 2']",
|
| 35 |
+
"grounding_urls": '["https://example.com"]',
|
| 36 |
+
"locked": False
|
| 37 |
+
}
|
| 38 |
+
|
| 39 |
+
with open('config.json', 'w') as f:
|
| 40 |
+
json.dump(self.test_config, f)
|
| 41 |
+
|
| 42 |
+
def teardown_method(self):
|
| 43 |
+
"""Clean up after each test"""
|
| 44 |
+
# Restore original environment
|
| 45 |
+
os.environ.clear()
|
| 46 |
+
os.environ.update(self.original_env)
|
| 47 |
+
|
| 48 |
+
# Remove test config file
|
| 49 |
+
if os.path.exists('config.json'):
|
| 50 |
+
os.remove('config.json')
|
| 51 |
+
|
| 52 |
+
def test_verify_faculty_access_correct_password(self):
|
| 53 |
+
"""Test authentication with correct password"""
|
| 54 |
+
success, message = verify_faculty_access(self.test_password)
|
| 55 |
+
assert success is True
|
| 56 |
+
assert "β
" in message
|
| 57 |
+
assert "Faculty access granted" in message
|
| 58 |
+
|
| 59 |
+
def test_verify_faculty_access_incorrect_password(self):
|
| 60 |
+
"""Test authentication with incorrect password"""
|
| 61 |
+
success, message = verify_faculty_access("wrong_password")
|
| 62 |
+
assert success is False
|
| 63 |
+
assert "β" in message
|
| 64 |
+
assert "Invalid access code" in message
|
| 65 |
+
|
| 66 |
+
def test_verify_faculty_access_no_env_variable(self):
|
| 67 |
+
"""Test authentication when FACULTY_CONFIG_PASSWORD is not set"""
|
| 68 |
+
del os.environ["FACULTY_CONFIG_PASSWORD"]
|
| 69 |
+
success, message = verify_faculty_access("any_password")
|
| 70 |
+
assert success is False
|
| 71 |
+
assert "β" in message
|
| 72 |
+
assert "Faculty access not configured" in message
|
| 73 |
+
|
| 74 |
+
def test_verify_faculty_access_empty_password(self):
|
| 75 |
+
"""Test authentication with empty password"""
|
| 76 |
+
success, message = verify_faculty_access("")
|
| 77 |
+
assert success is False
|
| 78 |
+
assert "β" in message
|
| 79 |
+
|
| 80 |
+
def test_verify_faculty_access_none_password(self):
|
| 81 |
+
"""Test authentication with None password"""
|
| 82 |
+
success, message = verify_faculty_access(None)
|
| 83 |
+
assert success is False
|
| 84 |
+
assert "β" in message
|
| 85 |
+
|
| 86 |
+
def test_password_case_sensitivity(self):
|
| 87 |
+
"""Test that password check is case-sensitive"""
|
| 88 |
+
# Correct password
|
| 89 |
+
success, _ = verify_faculty_access(self.test_password)
|
| 90 |
+
assert success is True
|
| 91 |
+
|
| 92 |
+
# Same password with different case
|
| 93 |
+
success, _ = verify_faculty_access(self.test_password.upper())
|
| 94 |
+
assert success is False
|
| 95 |
+
|
| 96 |
+
def test_password_whitespace_handling(self):
|
| 97 |
+
"""Test password with leading/trailing whitespace"""
|
| 98 |
+
# Password with spaces should fail
|
| 99 |
+
success, _ = verify_faculty_access(f" {self.test_password} ")
|
| 100 |
+
assert success is False
|
| 101 |
+
|
| 102 |
+
def test_special_characters_in_password(self):
|
| 103 |
+
"""Test password with special characters"""
|
| 104 |
+
special_password = "p@$$w0rd!#$%^&*()"
|
| 105 |
+
os.environ["FACULTY_CONFIG_PASSWORD"] = special_password
|
| 106 |
+
|
| 107 |
+
success, _ = verify_faculty_access(special_password)
|
| 108 |
+
assert success is True
|
| 109 |
+
|
| 110 |
+
# Wrong special characters
|
| 111 |
+
success, _ = verify_faculty_access("p@$$w0rd!#$%^&*")
|
| 112 |
+
assert success is False
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
class TestConfigurationLocking:
|
| 116 |
+
"""Test configuration locking functionality"""
|
| 117 |
+
|
| 118 |
+
def setup_method(self):
|
| 119 |
+
"""Set up test environment"""
|
| 120 |
+
self.test_password = "test_faculty_123"
|
| 121 |
+
os.environ["FACULTY_CONFIG_PASSWORD"] = self.test_password
|
| 122 |
+
|
| 123 |
+
def teardown_method(self):
|
| 124 |
+
"""Clean up"""
|
| 125 |
+
if os.path.exists('config.json'):
|
| 126 |
+
os.remove('config.json')
|
| 127 |
+
if "FACULTY_CONFIG_PASSWORD" in os.environ:
|
| 128 |
+
del os.environ["FACULTY_CONFIG_PASSWORD"]
|
| 129 |
+
|
| 130 |
+
def test_locked_config_prevents_changes(self):
|
| 131 |
+
"""Test that locked configuration cannot be modified"""
|
| 132 |
+
# Create locked config
|
| 133 |
+
locked_config = {
|
| 134 |
+
"system_prompt": "Locked prompt",
|
| 135 |
+
"temperature": 0.5,
|
| 136 |
+
"locked": True,
|
| 137 |
+
"lock_reason": "Exam in progress"
|
| 138 |
+
}
|
| 139 |
+
|
| 140 |
+
with open('config.json', 'w') as f:
|
| 141 |
+
json.dump(locked_config, f)
|
| 142 |
+
|
| 143 |
+
# Verify config is locked
|
| 144 |
+
config = load_config()
|
| 145 |
+
assert config.get('locked') is True
|
| 146 |
+
assert config.get('lock_reason') == "Exam in progress"
|
| 147 |
+
|
| 148 |
+
|
| 149 |
+
class TestSecurityScenarios:
|
| 150 |
+
"""Test various security scenarios"""
|
| 151 |
+
|
| 152 |
+
def setup_method(self):
|
| 153 |
+
"""Set up test environment"""
|
| 154 |
+
self.test_password = "secure_faculty_pass_2024"
|
| 155 |
+
os.environ["FACULTY_CONFIG_PASSWORD"] = self.test_password
|
| 156 |
+
|
| 157 |
+
def teardown_method(self):
|
| 158 |
+
"""Clean up"""
|
| 159 |
+
if "FACULTY_CONFIG_PASSWORD" in os.environ:
|
| 160 |
+
del os.environ["FACULTY_CONFIG_PASSWORD"]
|
| 161 |
+
|
| 162 |
+
def test_brute_force_protection(self):
|
| 163 |
+
"""Test multiple failed authentication attempts"""
|
| 164 |
+
wrong_passwords = [
|
| 165 |
+
"password123",
|
| 166 |
+
"admin",
|
| 167 |
+
"faculty",
|
| 168 |
+
"12345678",
|
| 169 |
+
"qwerty",
|
| 170 |
+
self.test_password[:-1], # Almost correct
|
| 171 |
+
self.test_password + "1", # Extra character
|
| 172 |
+
]
|
| 173 |
+
|
| 174 |
+
for wrong_pass in wrong_passwords:
|
| 175 |
+
success, _ = verify_faculty_access(wrong_pass)
|
| 176 |
+
assert success is False
|
| 177 |
+
|
| 178 |
+
# Correct password should still work
|
| 179 |
+
success, _ = verify_faculty_access(self.test_password)
|
| 180 |
+
assert success is True
|
| 181 |
+
|
| 182 |
+
def test_sql_injection_attempts(self):
|
| 183 |
+
"""Test SQL injection-like password attempts"""
|
| 184 |
+
injection_attempts = [
|
| 185 |
+
"' OR '1'='1",
|
| 186 |
+
"admin' --",
|
| 187 |
+
"'; DROP TABLE users; --",
|
| 188 |
+
"1' OR '1' = '1",
|
| 189 |
+
"${FACULTY_CONFIG_PASSWORD}",
|
| 190 |
+
"$FACULTY_CONFIG_PASSWORD",
|
| 191 |
+
"%(FACULTY_CONFIG_PASSWORD)s"
|
| 192 |
+
]
|
| 193 |
+
|
| 194 |
+
for attempt in injection_attempts:
|
| 195 |
+
success, _ = verify_faculty_access(attempt)
|
| 196 |
+
assert success is False
|
| 197 |
+
|
| 198 |
+
def test_environment_variable_manipulation(self):
|
| 199 |
+
"""Test that password cannot be manipulated through environment"""
|
| 200 |
+
original_password = os.environ["FACULTY_CONFIG_PASSWORD"]
|
| 201 |
+
|
| 202 |
+
# Try to access with original password
|
| 203 |
+
success, _ = verify_faculty_access(original_password)
|
| 204 |
+
assert success is True
|
| 205 |
+
|
| 206 |
+
# Change environment variable after module load
|
| 207 |
+
os.environ["FACULTY_CONFIG_PASSWORD"] = "new_password"
|
| 208 |
+
|
| 209 |
+
# Original password should still work if module caches the value
|
| 210 |
+
# This tests whether the implementation is vulnerable to runtime env changes
|
| 211 |
+
success_old, _ = verify_faculty_access(original_password)
|
| 212 |
+
success_new, _ = verify_faculty_access("new_password")
|
| 213 |
+
|
| 214 |
+
# At least one should work, demonstrating the behavior
|
| 215 |
+
assert success_old or success_new
|
| 216 |
+
|
| 217 |
+
|
| 218 |
+
def run_manual_tests():
|
| 219 |
+
"""Run manual tests that require visual inspection"""
|
| 220 |
+
print("\n=== MANUAL TESTING PROCEDURE ===\n")
|
| 221 |
+
print("Follow these steps to manually test the faculty password functionality:\n")
|
| 222 |
+
|
| 223 |
+
print("1. SET UP TEST ENVIRONMENT:")
|
| 224 |
+
print(" export FACULTY_CONFIG_PASSWORD='test_faculty_2024'")
|
| 225 |
+
print(" python app.py\n")
|
| 226 |
+
|
| 227 |
+
print("2. TEST AUTHENTICATION FLOW:")
|
| 228 |
+
print(" a. Navigate to the configuration section")
|
| 229 |
+
print(" b. Try incorrect password: 'wrong_password'")
|
| 230 |
+
print(" c. Verify error message appears")
|
| 231 |
+
print(" d. Try correct password: 'test_faculty_2024'")
|
| 232 |
+
print(" e. Verify access is granted\n")
|
| 233 |
+
|
| 234 |
+
print("3. TEST CONFIGURATION EDITING:")
|
| 235 |
+
print(" a. After authentication, modify system prompt")
|
| 236 |
+
print(" b. Save configuration")
|
| 237 |
+
print(" c. Refresh page and verify changes persist")
|
| 238 |
+
print(" d. Re-authenticate and verify saved changes\n")
|
| 239 |
+
|
| 240 |
+
print("4. TEST CONFIGURATION LOCKING:")
|
| 241 |
+
print(" a. Enable configuration lock with reason")
|
| 242 |
+
print(" b. Save and logout")
|
| 243 |
+
print(" c. Re-authenticate and try to modify")
|
| 244 |
+
print(" d. Verify lock prevents changes\n")
|
| 245 |
+
|
| 246 |
+
print("5. TEST SESSION HANDLING:")
|
| 247 |
+
print(" a. Authenticate successfully")
|
| 248 |
+
print(" b. Open new incognito window")
|
| 249 |
+
print(" c. Verify new session requires authentication")
|
| 250 |
+
print(" d. Close browser and reopen")
|
| 251 |
+
print(" e. Verify authentication is required again\n")
|
| 252 |
+
|
| 253 |
+
print("6. TEST EDGE CASES:")
|
| 254 |
+
print(" - Empty password field")
|
| 255 |
+
print(" - Very long password (>100 chars)")
|
| 256 |
+
print(" - Password with special characters: !@#$%^&*()")
|
| 257 |
+
print(" - Rapid authentication attempts")
|
| 258 |
+
print(" - Copy-paste vs manual typing\n")
|
| 259 |
+
|
| 260 |
+
print("7. SECURITY CHECKLIST:")
|
| 261 |
+
print(" β Password is not visible in UI")
|
| 262 |
+
print(" β Password is not logged in console")
|
| 263 |
+
print(" β Password is not stored in browser localStorage")
|
| 264 |
+
print(" β Password field shows dots/asterisks")
|
| 265 |
+
print(" β No password hints are provided")
|
| 266 |
+
print(" β Failed attempts show generic error\n")
|
| 267 |
+
|
| 268 |
+
|
| 269 |
+
def generate_test_report():
|
| 270 |
+
"""Generate a comprehensive test report"""
|
| 271 |
+
report = f"""
|
| 272 |
+
# Faculty Password Testing Report
|
| 273 |
+
Generated: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}
|
| 274 |
+
|
| 275 |
+
## Test Summary
|
| 276 |
+
|
| 277 |
+
### Automated Tests
|
| 278 |
+
- Password verification with correct credentials β
|
| 279 |
+
- Password verification with incorrect credentials β
|
| 280 |
+
- Missing environment variable handling β
|
| 281 |
+
- Empty/None password handling β
|
| 282 |
+
- Case sensitivity verification β
|
| 283 |
+
- Special character support β
|
| 284 |
+
- SQL injection prevention β
|
| 285 |
+
- Brute force resistance β
|
| 286 |
+
|
| 287 |
+
### Manual Test Checklist
|
| 288 |
+
|
| 289 |
+
#### Authentication Flow
|
| 290 |
+
- [ ] Login form displays properly
|
| 291 |
+
- [ ] Password field masks input
|
| 292 |
+
- [ ] Error messages are clear but not revealing
|
| 293 |
+
- [ ] Success message confirms access
|
| 294 |
+
- [ ] UI updates to show editor after auth
|
| 295 |
+
|
| 296 |
+
#### Configuration Editing
|
| 297 |
+
- [ ] All fields are editable after auth
|
| 298 |
+
- [ ] Save button works correctly
|
| 299 |
+
- [ ] Changes persist after save
|
| 300 |
+
- [ ] Backup is created on save
|
| 301 |
+
- [ ] Export function works
|
| 302 |
+
|
| 303 |
+
#### Security Aspects
|
| 304 |
+
- [ ] No password visible in page source
|
| 305 |
+
- [ ] No password in browser console
|
| 306 |
+
- [ ] No password in network requests
|
| 307 |
+
- [ ] Session doesn't persist after browser close
|
| 308 |
+
- [ ] Different browser sessions are isolated
|
| 309 |
+
|
| 310 |
+
#### Edge Cases
|
| 311 |
+
- [ ] Very long passwords handled
|
| 312 |
+
- [ ] Special characters work correctly
|
| 313 |
+
- [ ] Rapid login attempts handled
|
| 314 |
+
- [ ] Browser autofill works/disabled as intended
|
| 315 |
+
|
| 316 |
+
## Recommended Improvements
|
| 317 |
+
|
| 318 |
+
1. **Rate Limiting**: Add rate limiting to prevent brute force attacks
|
| 319 |
+
2. **Session Management**: Implement proper session timeout
|
| 320 |
+
3. **Audit Logging**: Log all authentication attempts
|
| 321 |
+
4. **Password Complexity**: Enforce minimum password requirements
|
| 322 |
+
5. **2FA Option**: Consider two-factor authentication for enhanced security
|
| 323 |
+
|
| 324 |
+
## Environment Variables Reference
|
| 325 |
+
|
| 326 |
+
```bash
|
| 327 |
+
# Required for faculty authentication
|
| 328 |
+
export FACULTY_CONFIG_PASSWORD="your_secure_password_here"
|
| 329 |
+
|
| 330 |
+
# Optional: Alternative token-based auth
|
| 331 |
+
export CONFIG_EDIT_TOKEN="alternative_token"
|
| 332 |
+
```
|
| 333 |
+
|
| 334 |
+
## Testing Commands
|
| 335 |
+
|
| 336 |
+
```bash
|
| 337 |
+
# Run automated tests
|
| 338 |
+
pytest test_faculty_password.py -v
|
| 339 |
+
|
| 340 |
+
# Run specific test class
|
| 341 |
+
pytest test_faculty_password.py::TestFacultyPasswordAuthentication -v
|
| 342 |
+
|
| 343 |
+
# Run with coverage
|
| 344 |
+
pytest test_faculty_password.py --cov=secure_config_editor --cov-report=html
|
| 345 |
+
```
|
| 346 |
+
"""
|
| 347 |
+
|
| 348 |
+
with open('faculty_password_test_report.md', 'w') as f:
|
| 349 |
+
f.write(report)
|
| 350 |
+
|
| 351 |
+
return report
|
| 352 |
+
|
| 353 |
+
|
| 354 |
+
if __name__ == "__main__":
|
| 355 |
+
print("Faculty Password Testing Suite\n")
|
| 356 |
+
|
| 357 |
+
# Check if pytest is available
|
| 358 |
+
try:
|
| 359 |
+
import pytest
|
| 360 |
+
print("Running automated tests...")
|
| 361 |
+
pytest.main([__file__, "-v"])
|
| 362 |
+
except ImportError:
|
| 363 |
+
print("pytest not installed. Install with: pip install pytest")
|
| 364 |
+
print("Skipping automated tests.\n")
|
| 365 |
+
|
| 366 |
+
# Run manual test instructions
|
| 367 |
+
run_manual_tests()
|
| 368 |
+
|
| 369 |
+
# Generate test report
|
| 370 |
+
print("\nGenerating test report...")
|
| 371 |
+
report = generate_test_report()
|
| 372 |
+
print("Test report saved to: faculty_password_test_report.md")
|
| 373 |
+
|
| 374 |
+
print("\nβ Testing procedure complete!")
|