Update app.py
Browse files
app.py
CHANGED
@@ -1,134 +1,27 @@
|
|
1 |
import gradio as gr
|
2 |
-
|
3 |
-
from PIL import Image
|
4 |
-
import base64
|
5 |
-
import io
|
6 |
-
import json
|
7 |
-
import logging
|
8 |
-
import requests
|
9 |
-
import tempfile
|
10 |
-
from cryptography.hazmat.primitives import serialization
|
11 |
-
from cryptography.hazmat.primitives.asymmetric import rsa
|
12 |
-
|
13 |
-
# --- Configure Logging ---
|
14 |
-
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
|
15 |
-
logger = logging.getLogger(__name__)
|
16 |
-
|
17 |
-
# ==============================================================================
|
18 |
-
# CONFIGURATION: IDs AND URLs OF THE REMOTE SERVICES
|
19 |
-
# ==============================================================================
|
20 |
-
CREATOR_SPACE_ID = "broadfield-dev/KeyLock-Auth-Creator"
|
21 |
-
SERVER_SPACE_ID = "broadfield-dev/KeyLock-Auth-Server"
|
22 |
-
CREATOR_ENDPOINTS_JSON_URL = "https://huggingface.co/spaces/broadfield-dev/KeyLock-Auth-Creator/raw/main/endpoints.json"
|
23 |
-
|
24 |
-
BASE_HF_URL = "https://huggingface.co/spaces/"
|
25 |
-
CREATOR_URL = f"{BASE_HF_URL}{CREATOR_SPACE_ID}"
|
26 |
-
SERVER_URL = f"{BASE_HF_URL}{SERVER_SPACE_ID}"
|
27 |
-
CREATOR_APP_PY_URL = f"{CREATOR_URL}/blob/main/app.py"
|
28 |
-
SERVER_APP_PY_URL = f"{SERVER_URL}/blob/main/app.py"
|
29 |
|
30 |
# ==============================================================================
|
31 |
-
#
|
32 |
# ==============================================================================
|
33 |
-
|
34 |
-
|
35 |
-
"""Fetches the list of supported endpoints by making an HTTP request to the Creator's JSON file."""
|
36 |
-
status = f"Fetching endpoint list from {CREATOR_ENDPOINTS_JSON_URL}..."
|
37 |
-
# Using yield for streaming status updates
|
38 |
-
yield gr.Dropdown(choices=[], value=None, label="β³ Fetching..."), status, []
|
39 |
try:
|
40 |
-
|
41 |
-
|
42 |
-
endpoints = response.json()
|
43 |
-
endpoint_names = [e['name'] for e in endpoints]
|
44 |
-
status = f"β
Success! Found {len(endpoint_names)} endpoints."
|
45 |
-
yield gr.Dropdown(choices=endpoint_names, value=endpoint_names[0] if endpoint_names else None, label="Target Service"), status, endpoints
|
46 |
except Exception as e:
|
47 |
-
|
48 |
-
status = f"β Error: Could not fetch configuration. Check the URL and if the 'endpoints.json' file is public. Details: {e}"
|
49 |
-
yield gr.Dropdown(choices=[], value=None, label="Error fetching services"), status, []
|
50 |
-
|
51 |
-
def create_image_via_api(service_name: str, secret_data: str, available_endpoints: list):
|
52 |
-
"""Calls the Creator Space API to generate an encrypted image for a selected service."""
|
53 |
-
if not all([service_name, secret_data]):
|
54 |
-
raise gr.Error("Please select a service and provide secret data.")
|
55 |
-
|
56 |
-
status = f"Looking up public key for '{service_name}'..."
|
57 |
-
# No yield here, we'll return everything at the end.
|
58 |
|
|
|
|
|
59 |
try:
|
60 |
-
|
61 |
-
|
62 |
-
raise gr.Error(f"Could not find public key for '{service_name}' in the fetched configuration.")
|
63 |
-
|
64 |
-
status = f"Connecting to Creator: {CREATOR_SPACE_ID}..."
|
65 |
-
logger.info(status)
|
66 |
-
|
67 |
-
client = Client(src=CREATOR_SPACE_ID)
|
68 |
-
temp_filepath = client.predict(secret_data, public_key, api_name="/create_image")
|
69 |
-
|
70 |
-
if not temp_filepath:
|
71 |
-
raise gr.Error("Creator API did not return an image.")
|
72 |
-
|
73 |
-
# --- PNG FIX ---
|
74 |
-
# Load the image from the temp path and return the PIL Image object directly.
|
75 |
-
# The gr.Image component's `format="png"` will handle the rest.
|
76 |
-
created_image = Image.open(temp_filepath)
|
77 |
-
|
78 |
-
status = f"β
Success! Image created for '{service_name}'."
|
79 |
-
return created_image, status
|
80 |
-
|
81 |
except Exception as e:
|
82 |
-
|
83 |
-
# On error, return an empty image and the error status.
|
84 |
-
return None, f"β Error calling Creator API: {e}"
|
85 |
-
|
86 |
-
def decrypt_image_via_api(image: Image.Image):
|
87 |
-
"""Calls the Server Space API to decrypt an image."""
|
88 |
-
if image is None:
|
89 |
-
raise gr.Error("Please upload an image to decrypt.")
|
90 |
-
|
91 |
-
status = f"Connecting to Server: {SERVER_SPACE_ID}..."
|
92 |
-
logger.info(status)
|
93 |
-
|
94 |
-
try:
|
95 |
-
client = Client(src=SERVER_SPACE_ID)
|
96 |
-
with io.BytesIO() as buffer:
|
97 |
-
# Explicitly save as PNG to ensure format is correct before base64 encoding
|
98 |
-
image.save(buffer, format="PNG")
|
99 |
-
b64_string = base64.b64encode(buffer.getvalue()).decode("utf-8")
|
100 |
-
|
101 |
-
status = f"Calling API on {SERVER_SPACE_ID}..."
|
102 |
-
logger.info(status)
|
103 |
-
|
104 |
-
decrypted_json = client.predict(b64_string, api_name="/keylock-auth-decoder")
|
105 |
-
|
106 |
-
status = "β
Success! Data decrypted by the Server."
|
107 |
-
logger.info(f"Decryption successful. Data: {decrypted_json}")
|
108 |
-
|
109 |
-
# --- DECRYPTED DATA FIX ---
|
110 |
-
# Use a single, final return statement. This is more robust.
|
111 |
-
return decrypted_json, status
|
112 |
-
|
113 |
-
except Exception as e:
|
114 |
-
logger.error(f"Server API call failed: {e}", exc_info=True)
|
115 |
-
# Return an empty dict and the error message for a clean UI update.
|
116 |
-
return {}, f"β Error calling Server API: {e}"
|
117 |
-
|
118 |
-
def generate_rsa_keys():
|
119 |
-
"""Generates a new RSA key pair."""
|
120 |
-
private_key = rsa.generate_private_key(public_exponent=65537, key_size=2048)
|
121 |
-
private_pem = private_key.private_bytes(
|
122 |
-
encoding=serialization.Encoding.PEM, format=serialization.PrivateFormat.PKCS8,
|
123 |
-
encryption_algorithm=serialization.NoEncryption()
|
124 |
-
).decode('utf-8')
|
125 |
-
public_pem = private_key.public_key().public_bytes(
|
126 |
-
encoding=serialization.Encoding.PEM, format=serialization.PublicFormat.SubjectPublicKeyInfo
|
127 |
-
).decode('utf-8')
|
128 |
-
return private_pem, public_pem
|
129 |
|
130 |
# ==============================================================================
|
131 |
-
# GRADIO DASHBOARD INTERFACE
|
132 |
# ==============================================================================
|
133 |
theme = gr.themes.Base(
|
134 |
primary_hue=gr.themes.colors.blue, secondary_hue=gr.themes.colors.sky, neutral_hue=gr.themes.colors.slate,
|
@@ -140,77 +33,70 @@ theme = gr.themes.Base(
|
|
140 |
)
|
141 |
|
142 |
with gr.Blocks(theme=theme, title="KeyLock Operations Dashboard") as demo:
|
143 |
-
endpoints_state = gr.State([])
|
144 |
-
|
145 |
gr.Markdown("# π KeyLock Operations Dashboard")
|
146 |
-
gr.Markdown("A
|
147 |
|
148 |
with gr.Tabs() as tabs:
|
149 |
-
with gr.TabItem("β
|
150 |
-
gr.Markdown("## Create
|
151 |
-
gr.Markdown(
|
|
|
|
|
|
|
|
|
|
|
|
|
152 |
with gr.Row(variant="panel"):
|
|
|
|
|
|
|
|
|
153 |
with gr.Column(scale=2):
|
154 |
-
|
155 |
-
|
156 |
-
|
157 |
-
|
158 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
159 |
with gr.Column(scale=1):
|
|
|
160 |
creator_status = gr.Textbox(label="Status", interactive=False, lines=2)
|
161 |
-
#
|
162 |
-
|
163 |
-
creator_image_output = gr.Image(label="Image from Creator Service", type="pil", show_download_button=True, format="png")
|
164 |
|
165 |
-
with gr.TabItem("
|
166 |
-
gr.Markdown("## Decrypt
|
167 |
-
gr.Markdown(
|
168 |
with gr.Row(variant="panel"):
|
169 |
with gr.Column(scale=1):
|
170 |
-
|
171 |
-
|
|
|
|
|
172 |
with gr.Column(scale=1):
|
|
|
173 |
client_status = gr.Textbox(label="Status", interactive=False, lines=2)
|
174 |
-
client_json_output = gr.JSON(label="
|
175 |
-
|
176 |
-
with gr.TabItem("βΉοΈ Service Information", id=2):
|
177 |
-
gr.Markdown("## Ecosystem Architecture")
|
178 |
-
gr.Markdown("This dashboard coordinates separate Hugging Face Spaces to demonstrate a secure, decoupled workflow. Each service has a specific role.")
|
179 |
-
with gr.Row():
|
180 |
-
with gr.Column():
|
181 |
-
gr.Markdown(f"### π Auth Creator Service\n- **Space:** [{CREATOR_SPACE_ID}]({CREATOR_URL})\n- **Role:** Provides an API to encrypt data for various targets defined in its `endpoints.json` file.\n- **Source Code:** [app.py]({CREATOR_APP_PY_URL})")
|
182 |
-
with gr.Column():
|
183 |
-
gr.Markdown(f"### π‘ Decoder Server\n- **Space:** [{SERVER_SPACE_ID}]({SERVER_URL})\n- **Role:** The trusted authority. It holds a secret private key and provides a secure API to decrypt images.\n- **Source Code:** [app.py]({SERVER_APP_PY_URL})")
|
184 |
-
|
185 |
-
# --- Generate Keys moved to a closed Accordion ---
|
186 |
-
with gr.Accordion("π RSA Key Pair Generator", open=False):
|
187 |
-
gr.Markdown("Create a new public/private key pair. The public key can be added to a service's configuration to allow it to be a target for the Auth Creator.")
|
188 |
-
with gr.Row():
|
189 |
-
with gr.Column():
|
190 |
-
output_public_key = gr.Textbox(lines=10, label="Generated Public Key (Share This)", interactive=False, show_copy_button=True)
|
191 |
-
with gr.Column():
|
192 |
-
output_private_key = gr.Textbox(lines=10, label="Generated Private Key (Keep Secret!)", interactive=False, show_copy_button=True)
|
193 |
-
gen_keys_button = gr.Button("Generate New 2048-bit Key Pair", variant="secondary")
|
194 |
|
195 |
# --- Wire up the component logic ---
|
196 |
-
gen_keys_button.click(fn=generate_rsa_keys, inputs=None, outputs=[output_private_key, output_public_key])
|
197 |
|
198 |
-
def refresh_endpoints():
|
199 |
-
# This is a generator function, so we need to iterate to get the last value.
|
200 |
-
*_, last_yield = get_creator_endpoints()
|
201 |
-
return last_yield
|
202 |
-
|
203 |
-
refresh_button.click(fn=refresh_endpoints, outputs=[creator_service_dropdown, creator_status, endpoints_state])
|
204 |
-
demo.load(fn=refresh_endpoints, outputs=[creator_service_dropdown, creator_status, endpoints_state])
|
205 |
-
|
206 |
creator_button.click(
|
207 |
-
fn=
|
208 |
-
inputs=[
|
209 |
-
outputs=[creator_image_output, creator_status]
|
210 |
)
|
|
|
211 |
client_button.click(
|
212 |
-
fn=
|
213 |
-
inputs=[client_image_input],
|
214 |
outputs=[client_json_output, client_status]
|
215 |
)
|
216 |
|
|
|
1 |
import gradio as gr
|
2 |
+
import core # Import all our local logic
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
3 |
|
4 |
# ==============================================================================
|
5 |
+
# GRADIO UI HELPER FUNCTIONS
|
6 |
# ==============================================================================
|
7 |
+
def creator_wrapper(public_key: str, secret_data: str):
|
8 |
+
"""UI wrapper for the image creation logic."""
|
|
|
|
|
|
|
|
|
9 |
try:
|
10 |
+
created_image = core.create_encrypted_image(secret_data, public_key)
|
11 |
+
return created_image, f"β
Success! Image created. You can now go to the 'Send KeyLock' tab to test it."
|
|
|
|
|
|
|
|
|
12 |
except Exception as e:
|
13 |
+
return None, f"β Error: {e}"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
14 |
|
15 |
+
def decoder_wrapper(image: gr.Image, private_key: str):
|
16 |
+
"""UI wrapper for the image decryption logic."""
|
17 |
try:
|
18 |
+
decrypted_data = core.decode_data_from_image(image, private_key)
|
19 |
+
return decrypted_data, "β
Success! Data decrypted from image."
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
20 |
except Exception as e:
|
21 |
+
return None, f"β Error: {e}"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
22 |
|
23 |
# ==============================================================================
|
24 |
+
# GRADIO DASHBOARD INTERFACE
|
25 |
# ==============================================================================
|
26 |
theme = gr.themes.Base(
|
27 |
primary_hue=gr.themes.colors.blue, secondary_hue=gr.themes.colors.sky, neutral_hue=gr.themes.colors.slate,
|
|
|
33 |
)
|
34 |
|
35 |
with gr.Blocks(theme=theme, title="KeyLock Operations Dashboard") as demo:
|
|
|
|
|
36 |
gr.Markdown("# π KeyLock Operations Dashboard")
|
37 |
+
gr.Markdown("A self-contained demonstration of the entire KeyLock workflow: Key Generation, Image Creation, and Decryption.")
|
38 |
|
39 |
with gr.Tabs() as tabs:
|
40 |
+
with gr.TabItem("β Generate Keys", id=0):
|
41 |
+
gr.Markdown("## Step 1: Create a Secure Key Pair")
|
42 |
+
gr.Markdown(
|
43 |
+
"""
|
44 |
+
Every secure system starts with a key pair. This consists of a **Public Key** and a **Private Key**.
|
45 |
+
- **Public Key π:** You can share this with anyone. It's used only for *encrypting* data. In a real system, you would add this key to a server's configuration file (like an `endpoints.json`) so that clients know how to encrypt data for it.
|
46 |
+
- **Private Key π:** This must be kept **absolutely secret**. It is the only key that can *decrypt* data encrypted with its corresponding public key. In a real system, this would be stored as a secure environment variable or secret on the server.
|
47 |
+
"""
|
48 |
+
)
|
49 |
with gr.Row(variant="panel"):
|
50 |
+
with gr.Column(scale=1):
|
51 |
+
gr.Markdown("### Your New Keys")
|
52 |
+
gen_keys_button = gr.Button("Generate New 2048-bit Key Pair", variant="secondary")
|
53 |
+
gr.Markdown("β¬οΈ **Copy these keys for the next steps!**")
|
54 |
with gr.Column(scale=2):
|
55 |
+
with gr.Row():
|
56 |
+
output_public_key = gr.Textbox(lines=11, label="Generated Public Key (For Creator)", interactive=False, show_copy_button=True)
|
57 |
+
output_private_key = gr.Textbox(lines=11, label="Generated Private Key (For Decoder)", interactive=False, show_copy_button=True)
|
58 |
+
|
59 |
+
with gr.TabItem("β‘ Create KeyLock", id=1):
|
60 |
+
gr.Markdown("## Step 2: Create an Encrypted Auth Image")
|
61 |
+
gr.Markdown("This tool acts as the **Auth Creator**. It takes your secret data and uses the **Public Key** from Step 1 to encrypt it into a new PNG image. This simulates a user preparing their credentials to send to a secure service.")
|
62 |
+
with gr.Row(variant="panel"):
|
63 |
+
with gr.Column(scale=1):
|
64 |
+
gr.Markdown("### Configuration")
|
65 |
+
creator_pubkey_input = gr.Textbox(lines=8, label="Paste the Public Key Here", placeholder="Copy the public key generated in Step 1...")
|
66 |
+
creator_secret_input = gr.Textbox(lines=5, label="Secret Data to Encrypt", placeholder="API_KEY: sk-123...\nUSER: demo-user")
|
67 |
+
creator_button = gr.Button("β¨ Create Auth Image", variant="primary")
|
68 |
with gr.Column(scale=1):
|
69 |
+
gr.Markdown("### Output")
|
70 |
creator_status = gr.Textbox(label="Status", interactive=False, lines=2)
|
71 |
+
# format="png" is the key to ensuring the download button creates a proper PNG file.
|
72 |
+
creator_image_output = gr.Image(label="Generated Encrypted Image", type="pil", show_download_button=True, format="png", show_share_button=False)
|
|
|
73 |
|
74 |
+
with gr.TabItem("β’ Send KeyLock", id=2):
|
75 |
+
gr.Markdown("## Step 3: Decrypt the Image (Client Simulation)")
|
76 |
+
gr.Markdown("This tool acts as the **Client** sending the image to a secure **Server**. To prove it can decrypt the data, the 'Server' needs the corresponding **Private Key** from Step 1. In a real application, you would only send the image; the server would already have its private key.")
|
77 |
with gr.Row(variant="panel"):
|
78 |
with gr.Column(scale=1):
|
79 |
+
gr.Markdown("### Input")
|
80 |
+
client_image_input = gr.Image(type="pil", label="Upload or Drag Encrypted Image Here", sources=["upload", "clipboard"])
|
81 |
+
client_private_key_input = gr.Textbox(lines=8, label="Paste the Private Key Here", placeholder="Copy the private key generated in Step 1...")
|
82 |
+
client_button = gr.Button("π Decrypt Image", variant="primary")
|
83 |
with gr.Column(scale=1):
|
84 |
+
gr.Markdown("### Decrypted Data")
|
85 |
client_status = gr.Textbox(label="Status", interactive=False, lines=2)
|
86 |
+
client_json_output = gr.JSON(label="Result from 'Server'")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
87 |
|
88 |
# --- Wire up the component logic ---
|
89 |
+
gen_keys_button.click(fn=core.generate_rsa_keys, inputs=None, outputs=[output_private_key, output_public_key])
|
90 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
91 |
creator_button.click(
|
92 |
+
fn=creator_wrapper,
|
93 |
+
inputs=[creator_pubkey_input, creator_secret_input],
|
94 |
+
outputs=[creator_image_output, creator_status]
|
95 |
)
|
96 |
+
|
97 |
client_button.click(
|
98 |
+
fn=decoder_wrapper,
|
99 |
+
inputs=[client_image_input, client_private_key_input],
|
100 |
outputs=[client_json_output, client_status]
|
101 |
)
|
102 |
|