Update app.py
Browse files
app.py
CHANGED
@@ -5,7 +5,8 @@ import base64
|
|
5 |
import io
|
6 |
import json
|
7 |
import logging
|
8 |
-
import requests
|
|
|
9 |
from cryptography.hazmat.primitives import serialization
|
10 |
from cryptography.hazmat.primitives.asymmetric import rsa
|
11 |
|
@@ -18,12 +19,8 @@ logger = logging.getLogger(__name__)
|
|
18 |
# ==============================================================================
|
19 |
CREATOR_SPACE_ID = "broadfield-dev/KeyLock-Auth-Creator"
|
20 |
SERVER_SPACE_ID = "broadfield-dev/KeyLock-Auth-Server"
|
21 |
-
|
22 |
-
# URL to the raw JSON file containing the list of public keys and services.
|
23 |
-
# This makes the Creator's configuration publicly readable.
|
24 |
CREATOR_ENDPOINTS_JSON_URL = "https://huggingface.co/spaces/broadfield-dev/KeyLock-Auth-Creator/raw/main/endpoints.json"
|
25 |
|
26 |
-
# Construct URLs for linking in documentation
|
27 |
BASE_HF_URL = "https://huggingface.co/spaces/"
|
28 |
CREATOR_URL = f"{BASE_HF_URL}{CREATOR_SPACE_ID}"
|
29 |
SERVER_URL = f"{BASE_HF_URL}{SERVER_SPACE_ID}"
|
@@ -31,7 +28,7 @@ CREATOR_APP_PY_URL = f"{CREATOR_URL}/blob/main/app.py"
|
|
31 |
SERVER_APP_PY_URL = f"{SERVER_URL}/blob/main/app.py"
|
32 |
|
33 |
# ==============================================================================
|
34 |
-
# API CALL WRAPPER FUNCTIONS
|
35 |
# ==============================================================================
|
36 |
|
37 |
def get_creator_endpoints():
|
@@ -40,13 +37,10 @@ def get_creator_endpoints():
|
|
40 |
yield gr.Dropdown(choices=[], value=None, label="β³ Fetching..."), status, [] # Initial state
|
41 |
try:
|
42 |
response = requests.get(CREATOR_ENDPOINTS_JSON_URL, timeout=10)
|
43 |
-
response.raise_for_status()
|
44 |
-
|
45 |
endpoints = response.json()
|
46 |
endpoint_names = [e['name'] for e in endpoints]
|
47 |
-
|
48 |
status = f"β
Success! Found {len(endpoint_names)} endpoints."
|
49 |
-
# Return the full list to the state, and the updated dropdown
|
50 |
yield gr.Dropdown(choices=endpoint_names, value=endpoint_names[0] if endpoint_names else None, label="Target Service"), status, endpoints
|
51 |
except Exception as e:
|
52 |
logger.error(f"Failed to get endpoints from creator's JSON file: {e}", exc_info=True)
|
@@ -74,9 +68,18 @@ def create_image_via_api(service_name: str, secret_data: str, available_endpoint
|
|
74 |
|
75 |
if not temp_filepath: raise gr.Error("Creator API did not return an image.")
|
76 |
|
|
|
|
|
|
|
77 |
created_image = Image.open(temp_filepath)
|
|
|
|
|
|
|
|
|
|
|
78 |
status = f"β
Success! Image created for '{service_name}'."
|
79 |
-
yield created_image,
|
|
|
80 |
except Exception as e:
|
81 |
logger.error(f"Creator API call failed: {e}", exc_info=True)
|
82 |
yield None, None, f"β Error calling Creator API: {e}"
|
@@ -105,13 +108,11 @@ def generate_rsa_keys():
|
|
105 |
"""Generates a new RSA key pair."""
|
106 |
private_key = rsa.generate_private_key(public_exponent=65537, key_size=2048)
|
107 |
private_pem = private_key.private_bytes(
|
108 |
-
encoding=serialization.Encoding.PEM,
|
109 |
-
format=serialization.PrivateFormat.PKCS8,
|
110 |
encryption_algorithm=serialization.NoEncryption()
|
111 |
).decode('utf-8')
|
112 |
public_pem = private_key.public_key().public_bytes(
|
113 |
-
encoding=serialization.Encoding.PEM,
|
114 |
-
format=serialization.PublicFormat.SubjectPublicKeyInfo
|
115 |
).decode('utf-8')
|
116 |
return private_pem, public_pem
|
117 |
|
@@ -119,18 +120,12 @@ def generate_rsa_keys():
|
|
119 |
# GRADIO DASHBOARD INTERFACE
|
120 |
# ==============================================================================
|
121 |
theme = gr.themes.Base(
|
122 |
-
primary_hue=gr.themes.colors.blue,
|
123 |
-
secondary_hue=gr.themes.colors.sky,
|
124 |
-
neutral_hue=gr.themes.colors.slate,
|
125 |
font=(gr.themes.GoogleFont("Inter"), "system-ui", "sans-serif"),
|
126 |
).set(
|
127 |
-
body_background_fill="#F1F5F9",
|
128 |
-
|
129 |
-
|
130 |
-
block_border_width="1px",
|
131 |
-
block_shadow="*shadow_drop_lg",
|
132 |
-
button_primary_background_fill="*primary_600",
|
133 |
-
button_primary_background_fill_hover="*primary_700",
|
134 |
)
|
135 |
|
136 |
with gr.Blocks(theme=theme, title="KeyLock Operations Dashboard") as demo:
|
@@ -140,31 +135,24 @@ with gr.Blocks(theme=theme, title="KeyLock Operations Dashboard") as demo:
|
|
140 |
gr.Markdown("A centralized dashboard to manage and demonstrate the entire KeyLock ecosystem, powered by live API calls to dedicated services.")
|
141 |
|
142 |
with gr.Tabs() as tabs:
|
143 |
-
with gr.TabItem("β
|
144 |
-
gr.Markdown("## RSA Key Pair Generator")
|
145 |
-
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.")
|
146 |
-
with gr.Row(variant="panel"):
|
147 |
-
with gr.Group():
|
148 |
-
gen_keys_button = gr.Button("π Generate New 2048-bit Key Pair", variant="secondary")
|
149 |
-
with gr.Row():
|
150 |
-
output_public_key = gr.Textbox(lines=10, label="Generated Public Key (Share This)", interactive=False, show_copy_button=True)
|
151 |
-
output_private_key = gr.Textbox(lines=10, label="Generated Private Key (Keep Secret!)", interactive=False, show_copy_button=True)
|
152 |
-
|
153 |
-
with gr.TabItem("β‘ Auth Creator", id=1):
|
154 |
gr.Markdown("## Create an Encrypted Authentication Image")
|
155 |
gr.Markdown(f"This tool calls the **[{CREATOR_SPACE_ID}]({CREATOR_URL})** service to encrypt data for a chosen target. The list of targets is fetched live from the Creator's configuration.")
|
156 |
with gr.Row(variant="panel"):
|
157 |
with gr.Column(scale=2):
|
158 |
with gr.Row():
|
159 |
creator_service_dropdown = gr.Dropdown(label="Target Service", interactive=True, info="Select the API server you want to encrypt data for.")
|
160 |
-
refresh_button = gr.Button("π
|
161 |
creator_secret_input = gr.Textbox(lines=8, label="Secret Data to Encrypt", placeholder="API_KEY: sk-123...\nUSER: demo-user")
|
162 |
creator_button = gr.Button("β¨ Create Auth Image via API", variant="primary")
|
163 |
with gr.Column(scale=1):
|
164 |
creator_status = gr.Textbox(label="Status", interactive=False, lines=2)
|
165 |
-
creator_image_output = gr.Image(label="Image from Creator Service", type="pil", show_download_button=
|
|
|
|
|
|
|
166 |
|
167 |
-
with gr.TabItem("
|
168 |
gr.Markdown("## Decrypt an Authentication Image")
|
169 |
gr.Markdown(f"This tool acts as a client, calling the **[{SERVER_SPACE_ID}]({SERVER_URL})** service to decrypt an image using its securely stored private key.")
|
170 |
with gr.Row(variant="panel"):
|
@@ -175,7 +163,7 @@ with gr.Blocks(theme=theme, title="KeyLock Operations Dashboard") as demo:
|
|
175 |
client_status = gr.Textbox(label="Status", interactive=False, lines=2)
|
176 |
client_json_output = gr.JSON(label="Decrypted Data from Server")
|
177 |
|
178 |
-
with gr.TabItem("βΉοΈ Service Information", id=
|
179 |
gr.Markdown("## Ecosystem Architecture")
|
180 |
gr.Markdown("This dashboard coordinates separate Hugging Face Spaces to demonstrate a secure, decoupled workflow. Each service has a specific role.")
|
181 |
with gr.Row():
|
@@ -183,21 +171,32 @@ with gr.Blocks(theme=theme, title="KeyLock Operations Dashboard") as demo:
|
|
183 |
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})")
|
184 |
with gr.Column():
|
185 |
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})")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
186 |
|
187 |
# --- Wire up the component logic ---
|
188 |
gen_keys_button.click(fn=generate_rsa_keys, inputs=None, outputs=[output_private_key, output_public_key])
|
189 |
|
190 |
-
# Event handler for loading the page or refreshing the endpoint list
|
191 |
def refresh_endpoints():
|
192 |
-
# This is a generator function, so we need to iterate to get the last value.
|
193 |
*_, last_yield = get_creator_endpoints()
|
194 |
return last_yield
|
195 |
|
196 |
refresh_button.click(fn=refresh_endpoints, outputs=[creator_service_dropdown, creator_status, endpoints_state])
|
197 |
demo.load(fn=refresh_endpoints, outputs=[creator_service_dropdown, creator_status, endpoints_state])
|
198 |
|
199 |
-
|
200 |
-
|
|
|
|
|
|
|
201 |
client_button.click(fn=decrypt_image_via_api, inputs=[client_image_input], outputs=[client_json_output, client_status])
|
202 |
|
203 |
if __name__ == "__main__":
|
|
|
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 |
|
|
|
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}"
|
|
|
28 |
SERVER_APP_PY_URL = f"{SERVER_URL}/blob/main/app.py"
|
29 |
|
30 |
# ==============================================================================
|
31 |
+
# API CALL WRAPPER FUNCTIONS (Your working versions)
|
32 |
# ==============================================================================
|
33 |
|
34 |
def get_creator_endpoints():
|
|
|
37 |
yield gr.Dropdown(choices=[], value=None, label="β³ Fetching..."), status, [] # Initial state
|
38 |
try:
|
39 |
response = requests.get(CREATOR_ENDPOINTS_JSON_URL, timeout=10)
|
40 |
+
response.raise_for_status()
|
|
|
41 |
endpoints = response.json()
|
42 |
endpoint_names = [e['name'] for e in endpoints]
|
|
|
43 |
status = f"β
Success! Found {len(endpoint_names)} endpoints."
|
|
|
44 |
yield gr.Dropdown(choices=endpoint_names, value=endpoint_names[0] if endpoint_names else None, label="Target Service"), status, endpoints
|
45 |
except Exception as e:
|
46 |
logger.error(f"Failed to get endpoints from creator's JSON file: {e}", exc_info=True)
|
|
|
68 |
|
69 |
if not temp_filepath: raise gr.Error("Creator API did not return an image.")
|
70 |
|
71 |
+
# --- PNG FIX ---
|
72 |
+
# The API returns a path to a temp file which could be any format.
|
73 |
+
# We open it, ensure it's saved as PNG, and return that path.
|
74 |
created_image = Image.open(temp_filepath)
|
75 |
+
|
76 |
+
with tempfile.NamedTemporaryFile(suffix=".png", delete=False) as png_file:
|
77 |
+
created_image.save(png_file.name, "PNG")
|
78 |
+
png_filepath = png_file.name
|
79 |
+
|
80 |
status = f"β
Success! Image created for '{service_name}'."
|
81 |
+
yield created_image, png_filepath, status
|
82 |
+
|
83 |
except Exception as e:
|
84 |
logger.error(f"Creator API call failed: {e}", exc_info=True)
|
85 |
yield None, None, f"β Error calling Creator API: {e}"
|
|
|
108 |
"""Generates a new RSA key pair."""
|
109 |
private_key = rsa.generate_private_key(public_exponent=65537, key_size=2048)
|
110 |
private_pem = private_key.private_bytes(
|
111 |
+
encoding=serialization.Encoding.PEM, format=serialization.PrivateFormat.PKCS8,
|
|
|
112 |
encryption_algorithm=serialization.NoEncryption()
|
113 |
).decode('utf-8')
|
114 |
public_pem = private_key.public_key().public_bytes(
|
115 |
+
encoding=serialization.Encoding.PEM, format=serialization.PublicFormat.SubjectPublicKeyInfo
|
|
|
116 |
).decode('utf-8')
|
117 |
return private_pem, public_pem
|
118 |
|
|
|
120 |
# GRADIO DASHBOARD INTERFACE
|
121 |
# ==============================================================================
|
122 |
theme = gr.themes.Base(
|
123 |
+
primary_hue=gr.themes.colors.blue, secondary_hue=gr.themes.colors.sky, neutral_hue=gr.themes.colors.slate,
|
|
|
|
|
124 |
font=(gr.themes.GoogleFont("Inter"), "system-ui", "sans-serif"),
|
125 |
).set(
|
126 |
+
body_background_fill="#F1F5F9", panel_background_fill="white", block_background_fill="white",
|
127 |
+
block_border_width="1px", block_shadow="*shadow_drop_lg",
|
128 |
+
button_primary_background_fill="*primary_600", button_primary_background_fill_hover="*primary_700",
|
|
|
|
|
|
|
|
|
129 |
)
|
130 |
|
131 |
with gr.Blocks(theme=theme, title="KeyLock Operations Dashboard") as demo:
|
|
|
135 |
gr.Markdown("A centralized dashboard to manage and demonstrate the entire KeyLock ecosystem, powered by live API calls to dedicated services.")
|
136 |
|
137 |
with gr.Tabs() as tabs:
|
138 |
+
with gr.TabItem("β Auth Creator", id=0):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
139 |
gr.Markdown("## Create an Encrypted Authentication Image")
|
140 |
gr.Markdown(f"This tool calls the **[{CREATOR_SPACE_ID}]({CREATOR_URL})** service to encrypt data for a chosen target. The list of targets is fetched live from the Creator's configuration.")
|
141 |
with gr.Row(variant="panel"):
|
142 |
with gr.Column(scale=2):
|
143 |
with gr.Row():
|
144 |
creator_service_dropdown = gr.Dropdown(label="Target Service", interactive=True, info="Select the API server you want to encrypt data for.")
|
145 |
+
refresh_button = gr.Button("π", scale=0, size="sm", tooltip="Refresh Target Service List")
|
146 |
creator_secret_input = gr.Textbox(lines=8, label="Secret Data to Encrypt", placeholder="API_KEY: sk-123...\nUSER: demo-user")
|
147 |
creator_button = gr.Button("β¨ Create Auth Image via API", variant="primary")
|
148 |
with gr.Column(scale=1):
|
149 |
creator_status = gr.Textbox(label="Status", interactive=False, lines=2)
|
150 |
+
creator_image_output = gr.Image(label="Image from Creator Service", type="pil", show_download_button=False) # Download handled by gr.File
|
151 |
+
# --- PNG FIX ---
|
152 |
+
# Use a dedicated, visible File component for reliable PNG downloads.
|
153 |
+
creator_download_output = gr.File(label="Download Image as PNG", interactive=False)
|
154 |
|
155 |
+
with gr.TabItem("β‘ Client / Decoder", id=1):
|
156 |
gr.Markdown("## Decrypt an Authentication Image")
|
157 |
gr.Markdown(f"This tool acts as a client, calling the **[{SERVER_SPACE_ID}]({SERVER_URL})** service to decrypt an image using its securely stored private key.")
|
158 |
with gr.Row(variant="panel"):
|
|
|
163 |
client_status = gr.Textbox(label="Status", interactive=False, lines=2)
|
164 |
client_json_output = gr.JSON(label="Decrypted Data from Server")
|
165 |
|
166 |
+
with gr.TabItem("βΉοΈ Service Information", id=2):
|
167 |
gr.Markdown("## Ecosystem Architecture")
|
168 |
gr.Markdown("This dashboard coordinates separate Hugging Face Spaces to demonstrate a secure, decoupled workflow. Each service has a specific role.")
|
169 |
with gr.Row():
|
|
|
171 |
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})")
|
172 |
with gr.Column():
|
173 |
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})")
|
174 |
+
|
175 |
+
# --- Generate Keys moved to a closed Accordion ---
|
176 |
+
with gr.Accordion("π RSA Key Pair Generator", open=False):
|
177 |
+
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.")
|
178 |
+
with gr.Row():
|
179 |
+
with gr.Column():
|
180 |
+
output_public_key = gr.Textbox(lines=10, label="Generated Public Key (Share This)", interactive=False, show_copy_button=True)
|
181 |
+
with gr.Column():
|
182 |
+
output_private_key = gr.Textbox(lines=10, label="Generated Private Key (Keep Secret!)", interactive=False, show_copy_button=True)
|
183 |
+
gen_keys_button = gr.Button("Generate New 2048-bit Key Pair", variant="secondary")
|
184 |
|
185 |
# --- Wire up the component logic ---
|
186 |
gen_keys_button.click(fn=generate_rsa_keys, inputs=None, outputs=[output_private_key, output_public_key])
|
187 |
|
|
|
188 |
def refresh_endpoints():
|
|
|
189 |
*_, last_yield = get_creator_endpoints()
|
190 |
return last_yield
|
191 |
|
192 |
refresh_button.click(fn=refresh_endpoints, outputs=[creator_service_dropdown, creator_status, endpoints_state])
|
193 |
demo.load(fn=refresh_endpoints, outputs=[creator_service_dropdown, creator_status, endpoints_state])
|
194 |
|
195 |
+
creator_button.click(
|
196 |
+
fn=create_image_via_api,
|
197 |
+
inputs=[creator_service_dropdown, creator_secret_input, endpoints_state],
|
198 |
+
outputs=[creator_image_output, creator_download_output, creator_status] # Now outputs to the gr.File component
|
199 |
+
)
|
200 |
client_button.click(fn=decrypt_image_via_api, inputs=[client_image_input], outputs=[client_json_output, client_status])
|
201 |
|
202 |
if __name__ == "__main__":
|