Repository navigation
Expand file tree
/
Copy pathapp.py
More file actions
140 lines (112 loc) · 5.31 KB
/
Copy pathapp.py
File metadata and controls
140 lines (112 loc) · 5.31 KB
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
import streamlit as st
from src.guardrail import NeuroGuardrail
import os
import json
from dotenv import load_dotenv
# Page config
st.set_page_config(page_title="NeuroGuard AI", page_icon="brain", layout="wide")
# Load environment variables
load_dotenv()
# Initialize Guardrail in Session State to maintain persistence
if 'guardrail' not in st.session_state:
schema_path = "src/metta/logic_rules.metta"
data_path = "src/metta/atomspace.metta"
st.session_state.guardrail = NeuroGuardrail(schema_path, data_path)
# Sidebar for configuration
st.sidebar.title("Configuration")
use_mock = st.sidebar.toggle("Use Mock Extractor", value=True)
st.session_state.guardrail.extractor.use_mock = use_mock
st.sidebar.divider()
st.sidebar.info("""
**Roles in AtomSpace:**
- Admin (alice)
- Manager (charlie)
- Developer (david)
- Support (eve)
- Intern (bob)
""")
# Main UI
st.title("Neuro-Symbolic AI Guardrail")
# Custom function to capture prints from the guardrail for display in Streamlit
def process_with_ui(request):
# Capture the flow diagram by overriding the internal print for a moment or using a custom collector
# For simplicity, we'll let process_request return the data and we'll rebuild the UI components
# 1. Neural Extraction
intents = st.session_state.guardrail.extractor.extract(request)
with st.expander("Step 1: Intent Extraction", expanded=True):
st.write("Decomposition of the User Request into a structured JSON Plan:")
st.json([i.model_dump() for i in intents])
# 2. Symbolic Verification
verdicts = []
final_status = "ALLOWED"
with st.expander("Step 2: Symbolic Verification (MeTTa)", expanded=True):
cols = st.columns(len(intents) if len(intents) > 0 else 1)
for i, intent in enumerate(intents):
with cols[i]:
st.subheader(f"Intent {i+1}")
st.write(f"**Action:** {intent.action}")
st.write(f"**Target:** {intent.target}")
st.write(f"**Subject:** {intent.subject}")
# Pre-flight check
res_check = st.session_state.guardrail.verifier.metta.run(f"!(match &self (has-tier {intent.target} $t) $t)")
if not res_check or not res_check[0] or str(res_check[0][0]) == "[]":
v = {"allowed": False, "proof": "None", "reasoning": f"Security Alert: Unrecognized resource '{intent.target}'"}
final_status = "DENIED"
else:
v = st.session_state.guardrail.verifier.verify(intent.subject, intent.action, intent.target)
if not v["allowed"]:
final_status = "DENIED"
verdicts.append((intent, v))
if v["allowed"]:
st.success("Authorized")
st.markdown("**Symbolic Proof:**")
st.code(v["proof"], language="lisp")
st.info(f"**Reasoning:** {v['reasoning']}")
else:
st.error("Denied")
st.warning(f"**Reasoning:** {v['reasoning']}")
if final_status == "DENIED":
break
# 3. Final Execution Gate
st.divider()
if final_status == "ALLOWED":
st.header("Execution Authorized")
for intent, v in verdicts:
st.write(f"- Successfully performed **{intent.action}** on **{intent.target}**")
else:
st.header("Execution Blocked")
st.error(f"Atomic Rollback triggered. The entire transaction was cancelled.")
st.write(f"**Reason:** {verdicts[-1][1]['reasoning']}")
# User Input
user_input = st.chat_input("Ask a security request (e.g., 'David, read source_code')")
if user_input:
with st.chat_message("user"):
st.write(user_input)
with st.chat_message("assistant"):
process_with_ui(user_input)
# Examples section
st.sidebar.divider()
st.sidebar.subheader("Elite Test Cases")
if st.sidebar.button("Admin: Deep Inheritance"):
process_with_ui("I am alice, read news")
st.sidebar.caption("Showcases Admin inheriting through Manager -> Developer -> Intern.")
if st.sidebar.button("Developer: Write Permission"):
process_with_ui("I am david, write news")
st.sidebar.caption("Developer can write to Tier-1, but Intern cannot.")
if st.sidebar.button("Support: Tier-2 Access"):
process_with_ui("I am eve, read source_code")
st.sidebar.caption("Support role specifically allowed for Tier-2 read.")
if st.sidebar.button("Bob: Unauthorized Delete"):
process_with_ui("I am bob, delete budget")
st.sidebar.caption("Bob (Intern) blocked from Tier-3 delete.")
st.sidebar.divider()
st.sidebar.subheader("Multi-Step Planning")
if st.sidebar.button("Complex Plan: 3 Steps"):
process_with_ui("David, read source_code, write news, and delete budget")
st.sidebar.caption("Decomposes into 3 distinct actions. Fails at the final 'delete' step.")
if st.sidebar.button("Atomic Rollback Demo"):
process_with_ui("Alice, read news then Bob, delete budget")
st.sidebar.caption("Blocks the WHOLE request because one part is unauthorized.")
if st.sidebar.button("Identity Spoof Check"):
process_with_ui("I am hacker_man, read budget")
st.sidebar.caption("Zero-Trust check catches unregistered identities.")