broadfield-dev commited on
Commit
b04a886
Β·
verified Β·
1 Parent(s): ed6e61e

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +35 -46
app.py CHANGED
@@ -18,9 +18,8 @@ logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(level
18
  logger = logging.getLogger(__name__)
19
 
20
  # ==============================================================================
21
- # CONFIGURATION: URL to the public list of services
22
  # ==============================================================================
23
- # This can be any publicly accessible raw JSON file.
24
  ENDPOINTS_JSON_URL = "https://huggingface.co/spaces/broadfield-dev/KeyLock-Auth-Creator/raw/main/endpoints.json"
25
 
26
  # ==============================================================================
@@ -29,13 +28,8 @@ ENDPOINTS_JSON_URL = "https://huggingface.co/spaces/broadfield-dev/KeyLock-Auth-
29
  def generate_rsa_keys():
30
  """Generates a new 2048-bit RSA key pair LOCALLY."""
31
  private_key = rsa.generate_private_key(public_exponent=65537, key_size=2048)
32
- private_pem = private_key.private_bytes(
33
- encoding=serialization.Encoding.PEM, format=serialization.PrivateFormat.PKCS8,
34
- encryption_algorithm=serialization.NoEncryption()
35
- ).decode('utf-8')
36
- public_pem = private_key.public_key().public_bytes(
37
- encoding=serialization.Encoding.PEM, format=serialization.PublicFormat.SubjectPublicKeyInfo
38
- ).decode('utf-8')
39
  return private_pem, public_pem
40
 
41
  def create_encrypted_image(secret_data_str: str, public_key_pem: str) -> Image.Image:
@@ -43,22 +37,15 @@ def create_encrypted_image(secret_data_str: str, public_key_pem: str) -> Image.I
43
  if not secret_data_str.strip(): raise ValueError("Secret data cannot be empty.")
44
  if not public_key_pem.strip(): raise ValueError("Public Key cannot be empty.")
45
 
46
- data_dict = {}
47
- for line in secret_data_str.splitlines():
48
- if not line.strip() or line.strip().startswith('#'): continue
49
- parts = line.split(':', 1) if ':' in line else line.split('=', 1)
50
- if len(parts) != 2: continue
51
- data_dict[parts[0].strip()] = parts[1].strip().strip("'\"")
52
  if not data_dict: raise ValueError("No valid key-value pairs found.")
53
 
54
  json_bytes = json.dumps(data_dict).encode('utf-8')
55
  public_key = serialization.load_pem_public_key(public_key_pem.encode('utf-8'))
56
  aes_key, nonce = os.urandom(32), os.urandom(12)
57
- ciphertext_with_tag = AESGCM(aes_key).encrypt(nonce, json_bytes, None)
58
- rsa_encrypted_aes_key = public_key.encrypt(
59
- aes_key, padding.OAEP(mgf=padding.MGF1(hashes.SHA256()), algorithm=hashes.SHA256(), label=None)
60
- )
61
- encrypted_payload = struct.pack('>I', len(rsa_encrypted_aes_key)) + rsa_encrypted_aes_key + nonce + ciphertext_with_tag
62
 
63
  img = Image.new('RGB', (800, 600), color=(45, 52, 54))
64
  draw = ImageDraw.Draw(img)
@@ -67,9 +54,10 @@ def create_encrypted_image(secret_data_str: str, public_key_pem: str) -> Image.I
67
  draw.text((400, 300), "KeyLock Secure Data", fill=(223, 230, 233), font=font, anchor="ms")
68
 
69
  pixel_data = np.array(img.convert("RGB")).ravel()
70
- binary_payload = ''.join(format(byte, '08b') for byte in struct.pack('>I', len(encrypted_payload)) + encrypted_payload)
71
- if len(binary_payload) > pixel_data.size: raise ValueError("Data too large for image capacity.")
72
- for i in range(len(binary_payload)): pixel_data[i] = (pixel_data[i] & 0xFE) | int(binary_payload[i])
 
73
  stego_pixels = pixel_data.reshape((600, 800, 3))
74
  return Image.fromarray(stego_pixels, 'RGB')
75
 
@@ -79,18 +67,19 @@ def create_encrypted_image(secret_data_str: str, public_key_pem: str) -> Image.I
79
 
80
  def get_server_list():
81
  """Fetches the list of servers from the public JSON file."""
82
- status = f"Fetching server list from remote config..."
83
- yield gr.Dropdown(choices=[], value=None, label="⏳ Fetching..."), status, []
84
  try:
85
  response = requests.get(ENDPOINTS_JSON_URL, timeout=10)
86
  response.raise_for_status()
87
  endpoints = response.json()
 
 
 
88
  endpoint_names = [e['name'] for e in endpoints]
89
  status = f"βœ… Success! Found {len(endpoint_names)} servers."
90
- yield gr.Dropdown(choices=endpoint_names, value=endpoint_names[0] if endpoint_names else None, label="Target Server"), status, endpoints
91
  except Exception as e:
92
  status = f"❌ Error fetching configuration: {e}"
93
- yield gr.Dropdown(choices=[], value=None, label="Error fetching servers"), status, []
94
 
95
  def create_keylock_wrapper(service_name: str, secret_data: str, available_endpoints: list):
96
  """UI wrapper for creating an image for a selected service."""
@@ -108,13 +97,14 @@ def send_keylock_wrapper(service_name: str, image: Image.Image, available_endpoi
108
  if not service_name: raise gr.Error("Please select a target server.")
109
  if image is None: raise gr.Error("Please upload an image to send.")
110
 
111
- server = next((e for e in available_endpoints if e['name'] == service_name), None)
112
- if not server: raise gr.Error(f"Could not find server configuration for '{service_name}'.")
113
-
114
- server_space_id = server.get('link', '').split('/spaces/')[-1]
115
- api_endpoint = f"https://{server_space_id.replace('/', '-')}.hf.space/run/keylock-auth-decoder"
116
- status = f"Connecting to server: {server_space_id}..."
117
- yield None, status
 
118
 
119
  try:
120
  with io.BytesIO() as buffer:
@@ -153,7 +143,7 @@ with gr.Blocks(theme=theme, title="KeyLock Operations Dashboard") as demo:
153
  endpoints_state = gr.State([])
154
 
155
  gr.Markdown("# πŸ”‘ KeyLock Operations Dashboard")
156
- gr.Markdown("A self-contained dashboard to demonstrate the KeyLock ecosystem. Key/Image creation is performed locally, while decryption is handled by a **live, remote API call** to a secure server.")
157
 
158
  with gr.Tabs() as tabs:
159
  with gr.TabItem("β‘  Create KeyLock", id=0):
@@ -163,7 +153,7 @@ with gr.Blocks(theme=theme, title="KeyLock Operations Dashboard") as demo:
163
  with gr.Column(scale=2):
164
  with gr.Row():
165
  creator_service_dropdown = gr.Dropdown(label="Target Server", interactive=True, info="Select the API server to encrypt data for.")
166
- refresh_button = gr.Button("πŸ”„", scale=0, size="sm")
167
  creator_secret_input = gr.Textbox(lines=8, label="Secret Data to Encrypt", placeholder="API_KEY: sk-123...\nUSER: demo-user")
168
  creator_button = gr.Button("✨ Create Auth Image", variant="primary")
169
  with gr.Column(scale=1):
@@ -172,12 +162,12 @@ with gr.Blocks(theme=theme, title="KeyLock Operations Dashboard") as demo:
172
 
173
  with gr.TabItem("β‘‘ Send KeyLock", id=1):
174
  gr.Markdown("## Step 2: Decrypt via Live API Call")
175
- gr.Markdown("This tool acts as the **Client**. It sends the encrypted image you created in Step 1 to the live, remote **Decoder Server** you select. The server uses its securely stored private key to decrypt the data and sends the result back.")
176
  with gr.Row(variant="panel"):
177
  with gr.Column(scale=1):
178
- gr.Markdown("### Select Server to Call")
179
  send_service_dropdown = gr.Dropdown(label="Target Server", interactive=True, info="Select the API server to send the image to.")
180
- gr.Markdown("### Upload Image")
181
  client_image_input = gr.Image(type="pil", label="Upload or Drag Encrypted Image Here", sources=["upload", "clipboard"])
182
  client_button = gr.Button("πŸ”“ Decrypt via Remote Server", variant="primary")
183
  with gr.Column(scale=1):
@@ -185,11 +175,11 @@ with gr.Blocks(theme=theme, title="KeyLock Operations Dashboard") as demo:
185
  client_status = gr.Textbox(label="Status", interactive=False, lines=2)
186
  client_json_output = gr.JSON(label="Decrypted Data")
187
 
188
- with gr.TabItem("ℹ️ Key Generation & Info", id=2):
189
- gr.Markdown("## Ecosystem Information")
190
- gr.Markdown("This dashboard coordinates with live Hugging Face Spaces to demonstrate a secure, decoupled workflow.")
191
  with gr.Accordion("πŸ”‘ RSA Key Pair Generator", open=False):
192
- gr.Markdown("Create a new public/private key pair. In a real scenario, you would add the **Public Key** to the public `endpoints.json` configuration file, and set the **Private Key** as a secret variable in the corresponding server space.")
193
  with gr.Row():
194
  with gr.Column():
195
  output_public_key = gr.Textbox(lines=10, label="Generated Public Key", interactive=False, show_copy_button=True)
@@ -201,9 +191,8 @@ with gr.Blocks(theme=theme, title="KeyLock Operations Dashboard") as demo:
201
  gen_keys_button.click(fn=generate_rsa_keys, inputs=None, outputs=[output_private_key, output_public_key])
202
 
203
  def refresh_and_update_all():
204
- *_, last_yield = get_server_list()
205
- dropdown_update, status_update, state_update = last_yield
206
- # Update both dropdowns simultaneously
207
  return dropdown_update, dropdown_update, status_update, state_update
208
 
209
  refresh_button.click(fn=refresh_and_update_all, outputs=[creator_service_dropdown, send_service_dropdown, creator_status, endpoints_state])
 
18
  logger = logging.getLogger(__name__)
19
 
20
  # ==============================================================================
21
+ # CONFIGURATION
22
  # ==============================================================================
 
23
  ENDPOINTS_JSON_URL = "https://huggingface.co/spaces/broadfield-dev/KeyLock-Auth-Creator/raw/main/endpoints.json"
24
 
25
  # ==============================================================================
 
28
  def generate_rsa_keys():
29
  """Generates a new 2048-bit RSA key pair LOCALLY."""
30
  private_key = rsa.generate_private_key(public_exponent=65537, key_size=2048)
31
+ private_pem = private_key.private_bytes(encoding=serialization.Encoding.PEM, format=serialization.PrivateFormat.PKCS8, encryption_algorithm=serialization.NoEncryption()).decode('utf-8')
32
+ public_pem = private_key.public_key().public_bytes(encoding=serialization.Encoding.PEM, format=serialization.PublicFormat.SubjectPublicKeyInfo).decode('utf-8')
 
 
 
 
 
33
  return private_pem, public_pem
34
 
35
  def create_encrypted_image(secret_data_str: str, public_key_pem: str) -> Image.Image:
 
37
  if not secret_data_str.strip(): raise ValueError("Secret data cannot be empty.")
38
  if not public_key_pem.strip(): raise ValueError("Public Key cannot be empty.")
39
 
40
+ data_dict = {parts[0].strip(): parts[1].strip().strip("'\"") for line in secret_data_str.splitlines() if (line := line.strip()) and not line.startswith('#') and (parts := (line.split(':', 1) if ':' in line else line.split('=', 1))) and len(parts) == 2}
 
 
 
 
 
41
  if not data_dict: raise ValueError("No valid key-value pairs found.")
42
 
43
  json_bytes = json.dumps(data_dict).encode('utf-8')
44
  public_key = serialization.load_pem_public_key(public_key_pem.encode('utf-8'))
45
  aes_key, nonce = os.urandom(32), os.urandom(12)
46
+ ciphertext = AESGCM(aes_key).encrypt(nonce, json_bytes, None)
47
+ rsa_encrypted_key = public_key.encrypt(aes_key, padding.OAEP(mgf=padding.MGF1(hashes.SHA256()), algorithm=hashes.SHA256(), label=None))
48
+ encrypted_payload = struct.pack('>I', len(rsa_encrypted_key)) + rsa_encrypted_key + nonce + ciphertext
 
 
49
 
50
  img = Image.new('RGB', (800, 600), color=(45, 52, 54))
51
  draw = ImageDraw.Draw(img)
 
54
  draw.text((400, 300), "KeyLock Secure Data", fill=(223, 230, 233), font=font, anchor="ms")
55
 
56
  pixel_data = np.array(img.convert("RGB")).ravel()
57
+ binary_payload = ''.join(format(b, '08b') for b in struct.pack('>I', len(encrypted_payload)) + encrypted_payload)
58
+ if len(binary_payload) > pixel_data.size: raise ValueError("Data too large for image.")
59
+ pixel_data[:len(binary_payload)] = (pixel_data[:len(binary_payload)] & 0xFE) | np.array(list(binary_payload), dtype=np.uint8)
60
+
61
  stego_pixels = pixel_data.reshape((600, 800, 3))
62
  return Image.fromarray(stego_pixels, 'RGB')
63
 
 
67
 
68
  def get_server_list():
69
  """Fetches the list of servers from the public JSON file."""
 
 
70
  try:
71
  response = requests.get(ENDPOINTS_JSON_URL, timeout=10)
72
  response.raise_for_status()
73
  endpoints = response.json()
74
+ # Validate the new structure
75
+ for e in endpoints:
76
+ if "api_endpoint" not in e: raise ValueError("Configuration Error: Entry is missing the required 'api_endpoint' field.")
77
  endpoint_names = [e['name'] for e in endpoints]
78
  status = f"βœ… Success! Found {len(endpoint_names)} servers."
79
+ return gr.Dropdown(choices=endpoint_names, value=endpoint_names[0] if endpoint_names else None, label="Target Server"), status, endpoints
80
  except Exception as e:
81
  status = f"❌ Error fetching configuration: {e}"
82
+ return gr.Dropdown(choices=[], value=None, label="Error fetching servers"), status, []
83
 
84
  def create_keylock_wrapper(service_name: str, secret_data: str, available_endpoints: list):
85
  """UI wrapper for creating an image for a selected service."""
 
97
  if not service_name: raise gr.Error("Please select a target server.")
98
  if image is None: raise gr.Error("Please upload an image to send.")
99
 
100
+ # --- THIS IS THE FIX ---
101
+ # Look up the correct, full API endpoint from the configuration. No more guesswork!
102
+ api_endpoint = next((e['api_endpoint'] for e in available_endpoints if e['name'] == service_name), None)
103
+ if not api_endpoint:
104
+ raise gr.Error(f"Configuration Error: Could not find 'api_endpoint' for '{service_name}'.")
105
+
106
+ status = f"Connecting to endpoint: {api_endpoint}"
107
+ logger.info(status)
108
 
109
  try:
110
  with io.BytesIO() as buffer:
 
143
  endpoints_state = gr.State([])
144
 
145
  gr.Markdown("# πŸ”‘ KeyLock Operations Dashboard")
146
+ gr.Markdown("A centralized dashboard to manage and demonstrate the entire KeyLock ecosystem. Key/Image creation is performed locally, while decryption is handled by a **live, remote API call** to a secure server.")
147
 
148
  with gr.Tabs() as tabs:
149
  with gr.TabItem("β‘  Create KeyLock", id=0):
 
153
  with gr.Column(scale=2):
154
  with gr.Row():
155
  creator_service_dropdown = gr.Dropdown(label="Target Server", interactive=True, info="Select the API server to encrypt data for.")
156
+ refresh_button = gr.Button("πŸ”„", scale=0, size="sm", tooltip="Refresh Server List from Config File")
157
  creator_secret_input = gr.Textbox(lines=8, label="Secret Data to Encrypt", placeholder="API_KEY: sk-123...\nUSER: demo-user")
158
  creator_button = gr.Button("✨ Create Auth Image", variant="primary")
159
  with gr.Column(scale=1):
 
162
 
163
  with gr.TabItem("β‘‘ Send KeyLock", id=1):
164
  gr.Markdown("## Step 2: Decrypt via Live API Call")
165
+ gr.Markdown("This tool acts as the **Client**. It sends the encrypted image you created in Step 1 to the live, remote **Decoder Server** you select from the same configuration list. The server uses its securely stored private key to decrypt the data and sends the result back.")
166
  with gr.Row(variant="panel"):
167
  with gr.Column(scale=1):
168
+ gr.Markdown("### Configuration")
169
  send_service_dropdown = gr.Dropdown(label="Target Server", interactive=True, info="Select the API server to send the image to.")
170
+ gr.Markdown("### Image to Send")
171
  client_image_input = gr.Image(type="pil", label="Upload or Drag Encrypted Image Here", sources=["upload", "clipboard"])
172
  client_button = gr.Button("πŸ”“ Decrypt via Remote Server", variant="primary")
173
  with gr.Column(scale=1):
 
175
  client_status = gr.Textbox(label="Status", interactive=False, lines=2)
176
  client_json_output = gr.JSON(label="Decrypted Data")
177
 
178
+ with gr.TabItem("ℹ️ Info & Key Generation", id=2):
179
+ gr.Markdown("## Ecosystem Architecture")
180
+ gr.Markdown(f"This dashboard uses a public [configuration file]({ENDPOINTS_JSON_URL}) to dynamically discover and interact with live services. It demonstrates a secure, decoupled workflow.")
181
  with gr.Accordion("πŸ”‘ RSA Key Pair Generator", open=False):
182
+ gr.Markdown("Create a new key pair. In a real scenario, you would add the **Public Key** and the server's **API Endpoint URL** to the `endpoints.json` configuration file, and set the **Private Key** as a secret variable in the corresponding server space.")
183
  with gr.Row():
184
  with gr.Column():
185
  output_public_key = gr.Textbox(lines=10, label="Generated Public Key", interactive=False, show_copy_button=True)
 
191
  gen_keys_button.click(fn=generate_rsa_keys, inputs=None, outputs=[output_private_key, output_public_key])
192
 
193
  def refresh_and_update_all():
194
+ dropdown_update, status_update, state_update = get_server_list()
195
+ # Update both dropdowns simultaneously from the same source of truth
 
196
  return dropdown_update, dropdown_update, status_update, state_update
197
 
198
  refresh_button.click(fn=refresh_and_update_all, outputs=[creator_service_dropdown, send_service_dropdown, creator_status, endpoints_state])