File size: 5,780 Bytes
fc0f952
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# app.py
import streamlit as st
import time
from typing import Dict, List
import random

class HarbormasterDemo:
    def __init__(self):
        self.security_checks = {
            "prompt_injection": self.check_prompt_injection,
            "data_leakage": self.check_data_leakage,
            "rate_limiting": self.check_rate_limiting,
            "token_validation": self.check_token_validation
        }
        
    def check_prompt_injection(self, text: str) -> Dict:
        """Simulates prompt injection detection"""
        suspicious_patterns = ["system.execute", "ignore previous", "sudo", "override"]
        threats = [p for p in suspicious_patterns if p in text.lower()]
        return {
            "status": "failed" if threats else "passed",
            "threats": threats,
            "risk_score": len(threats) * 25
        }
    
    def check_data_leakage(self, text: str) -> Dict:
        """Simulates data leakage detection"""
        sensitive_patterns = ["password", "api_key", "secret", "token"]
        leaks = [p for p in sensitive_patterns if p in text.lower()]
        return {
            "status": "failed" if leaks else "passed",
            "leaks": leaks,
            "risk_score": len(leaks) * 30
        }
    
    def check_rate_limiting(self) -> Dict:
        """Simulates rate limiting check"""
        current_rate = random.randint(1, 120)
        limit = 100
        return {
            "status": "failed" if current_rate > limit else "passed",
            "current_rate": current_rate,
            "limit": limit,
            "risk_score": max(0, (current_rate - limit))
        }
    
    def check_token_validation(self) -> Dict:
        """Simulates token validation"""
        valid = random.choice([True, True, True, False])  # 75% chance of valid token
        return {
            "status": "passed" if valid else "failed",
            "valid": valid,
            "risk_score": 0 if valid else 100
        }

def main():
    st.set_page_config(
        page_title="Harbormaster Demo",
        page_icon="πŸ›‘οΈ",
        layout="wide"
    )
    
    st.title("πŸ›‘οΈ Harbormaster Security Demo")
    st.markdown("""
    Harbormaster provides real-time protection for your Hugging Face models.
    This demo showcases key security features and how they protect your model from various threats.
    """)
    
    demo = HarbormasterDemo()
    
    # Model selection
    st.sidebar.header("Configuration")
    model_id = st.sidebar.text_input(
        "Model ID",
        value="gpt2",
        help="Enter a Hugging Face model ID"
    )
    
    # Main interface
    col1, col2 = st.columns([2, 1])
    
    with col1:
        st.subheader("Model Interface")
        user_input = st.text_area(
            "Enter your prompt:",
            height=100,
            help="Enter text to test Harbormaster's security features"
        )
        
        if st.button("πŸš€ Run with Protection"):
            if user_input:
                with st.spinner("Running security checks..."):
                    # Run security checks
                    results = {}
                    
                    # Animate security checks
                    progress_bar = st.progress(0)
                    for i, (check_name, check_func) in enumerate(demo.security_checks.items()):
                        time.sleep(0.5)  # Simulate processing
                        progress_bar.progress((i + 1) * 25)
                        
                        if check_name in ["prompt_injection", "data_leakage"]:
                            results[check_name] = check_func(user_input)
                        else:
                            results[check_name] = check_func()
                    
                    progress_bar.empty()
                    
                    # Display overall security status
                    total_risk = sum(r["risk_score"] for r in results.values())
                    status = "βœ… Secure" if total_risk < 50 else "⚠️ Warning" if total_risk < 100 else "❌ Blocked"
                    
                    st.header(f"Security Status: {status}")
                    
                    # Display detailed results
                    for check_name, result in results.items():
                        with st.expander(f"{check_name.replace('_', ' ').title()} Check"):
                            st.json(result)
                    
                    # Show model response if secure
                    if total_risk < 100:
                        st.success("Model response would be shown here")
                    else:
                        st.error("Request blocked due to security concerns")
            else:
                st.warning("Please enter a prompt to test")
    
    with col2:
        st.subheader("Security Dashboard")
        
        # Real-time metrics
        st.metric(
            label="Active Protection",
            value="Enabled",
            delta="Real-time"
        )
        
        st.metric(
            label="Request Rate",
            value=f"{random.randint(60, 90)}/min",
            delta="Within limits"
        )
        
        st.metric(
            label="Threats Blocked",
            value=random.randint(100, 999),
            delta="24h"
        )
        
        # Protection status
        st.subheader("Protection Status")
        protections = {
            "Prompt Injection Shield": True,
            "Data Leakage Prevention": True,
            "Rate Limiting": True,
            "Token Validation": True,
            "Output Sanitization": True
        }
        
        for protection, status in protections.items():
            st.write(f"{'βœ…' if status else '❌'} {protection}")

if __name__ == "__main__":
    main()