This is an automated email from the ASF dual-hosted git repository.

sbp pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/tooling-trusted-release.git


The following commit(s) were added to refs/heads/main by this push:
     new 40af197  Add a form to add public keys from an uploaded KEYS file
40af197 is described below

commit 40af197dc4b650c9aa9afe75ab0d35d55de96403
Author: Sean B. Palmer <[email protected]>
AuthorDate: Wed Mar 26 14:57:21 2025 +0200

    Add a form to add public keys from an uploaded KEYS file
---
 atr/routes/keys.py                  | 156 +++++++++++++++++++++++++++++++++---
 atr/templates/includes/sidebar.html |   6 +-
 atr/templates/keys-upload.html      | 106 ++++++++++++++++++++++++
 3 files changed, 255 insertions(+), 13 deletions(-)

diff --git a/atr/routes/keys.py b/atr/routes/keys.py
index ab0e0f4..dfbd4810 100644
--- a/atr/routes/keys.py
+++ b/atr/routes/keys.py
@@ -25,6 +25,7 @@ import hashlib
 import logging
 import logging.handlers
 import pprint
+import re
 import shutil
 import tempfile
 from collections.abc import AsyncGenerator, Sequence
@@ -36,6 +37,7 @@ import asfquart.session as session
 import cryptography.hazmat.primitives.serialization as serialization
 import gnupg
 import quart
+import werkzeug.datastructures as datastructures
 import werkzeug.wrappers.response as response
 import wtforms
 
@@ -84,7 +86,7 @@ async def key_add_post(
     if invalid_committees:
         raise routes.FlashError(f"Invalid PMC selection: {', 
'.join(invalid_committees)}")
 
-    return await key_user_add(web_session, public_key, selected_committees)
+    return await key_user_add(util.unwrap(web_session.uid), public_key, 
selected_committees)
 
 
 def key_ssh_fingerprint(ssh_key_string: str) -> str:
@@ -114,9 +116,7 @@ def key_ssh_fingerprint(ssh_key_string: str) -> str:
     raise ValueError("Invalid SSH key format")
 
 
-async def key_user_add(
-    web_session: session.ClientSession, public_key: str, selected_committees: 
list[str]
-) -> dict | None:
+async def key_user_add(asf_uid: str | None, public_key: str, 
selected_committees: list[str]) -> dict | None:
     if not public_key:
         raise routes.FlashError("Public key is required")
 
@@ -148,14 +148,25 @@ async def key_user_add(
         # https://infra.apache.org/release-signing.html#note
         # Says that keys must be at least 2048 bits
         raise routes.FlashError("Key is not long enough; must be at least 2048 
bits")
+    if asf_uid is None:
+        for uid in key["uids"]:
+            match = re.search(r"([A-Za-z0-9]+)@apache.org", uid)
+            if match:
+                asf_uid = match.group(1).lower()
+                break
+        else:
+            logging.warning(f"key_user_add called with no ASF UID: {keys}")
+    if asf_uid is None:
+        # We place this here to make it easier on the type checkers
+        raise routes.FlashError("No Apache UID found in the key UIDs")
 
     # Store key in database
     async with db.session() as data:
-        return await key_user_session_add(web_session, public_key, key, 
selected_committees, data)
+        return await key_user_session_add(asf_uid, public_key, key, 
selected_committees, data)
 
 
 async def key_user_session_add(
-    web_session: session.ClientSession,
+    asf_uid: str,
     public_key: str,
     key: dict,
     selected_committees: list[str],
@@ -169,15 +180,15 @@ async def key_user_session_add(
     # if existing_key:
     #     return ("You already have a key registered", None)
 
-    if not web_session.uid:
-        raise routes.FlashError("You must be signed in to add a key")
-
     fingerprint = key.get("fingerprint")
     if not isinstance(fingerprint, str):
         raise routes.FlashError("Invalid key fingerprint")
     fingerprint = fingerprint.lower()
     uids = key.get("uids")
     async with data.begin():
+        if existing := await data.public_signing_key(fingerprint=fingerprint, 
apache_uid=asf_uid).get():
+            raise routes.FlashError(f"Key already exists: 
{existing.fingerprint}")
+
         # Create new key record
         key_record = models.PublicSigningKey(
             fingerprint=fingerprint,
@@ -186,7 +197,7 @@ async def key_user_session_add(
             created=datetime.datetime.fromtimestamp(int(key["date"])),
             expires=datetime.datetime.fromtimestamp(int(key["expires"])) if 
key.get("expires") else None,
             declared_uid=uids[0] if uids else None,
-            apache_uid=web_session.uid,
+            apache_uid=asf_uid,
             ascii_armored_key=public_key,
         )
         data.add(key_record)
@@ -221,7 +232,7 @@ async def root_keys_add() -> str:
 
     key_info = None
 
-    # Get PMC objects for all projects the user is a member of
+    # Get committees for all projects the user is a member of
     async with db.session() as data:
         project_list = web_session.committees + web_session.projects
         user_committees = await data.committee(name_in=project_list).all()
@@ -324,6 +335,7 @@ async def root_keys_ssh_add() -> response.Response | str:
     web_session = await session.read()
     if web_session is None:
         raise base.ASFQuartException("Not authenticated", errorcode=401)
+    uid = util.unwrap(web_session.uid)
 
     form = await AddSSHKeyForm.create_form()
     fingerprint = None
@@ -332,7 +344,7 @@ async def root_keys_ssh_add() -> response.Response | str:
         fingerprint = await asyncio.to_thread(key_ssh_fingerprint, key)
         async with db.session() as data:
             async with data.begin():
-                data.add(models.SSHKey(fingerprint=fingerprint, key=key, 
asf_uid=util.unwrap(web_session.uid)))
+                data.add(models.SSHKey(fingerprint=fingerprint, key=key, 
asf_uid=uid))
         await quart.flash(f"SSH key added successfully: {fingerprint}", 
"success")
         return quart.redirect(quart.url_for("root_keys_review"))
 
@@ -342,3 +354,123 @@ async def root_keys_ssh_add() -> response.Response | str:
         form=form,
         fingerprint=fingerprint,
     )
+
+
[email protected]_route("/keys/upload", methods=["GET", "POST"])
[email protected](auth.Requirements.committer)
+async def root_keys_upload() -> str:
+    """Upload a KEYS file containing multiple GPG keys."""
+    web_session = await session.read()
+    if web_session is None:
+        raise base.ASFQuartException("Not authenticated", errorcode=401)
+
+    # Get committees for all projects the user is a member of
+    async with db.session() as data:
+        project_list = web_session.committees + web_session.projects
+        user_committees = await data.committee(name_in=project_list).all()
+
+    class UploadKeyForm(util.QuartFormTyped):
+        key = wtforms.FileField("KEYS file")
+        submit = wtforms.SubmitField("Upload KEYS file")
+        selected_committee = wtforms.SelectField("PMCs", choices=[(c.name, 
c.name) for c in user_committees])
+
+    form = await UploadKeyForm.create_form()
+    results: list[dict] = []
+
+    async def render(error: str | None = None) -> str:
+        # For easier happy pathing
+        if error is not None:
+            await quart.flash(error, "error")
+        return await quart.render_template(
+            "keys-upload.html",
+            asf_id=web_session.uid,
+            user_committees=user_committees,
+            form=form,
+            results=results,
+            algorithms=routes.algorithms,
+        )
+
+    if await form.validate_on_submit():
+        key_file = form.key.data
+        if not isinstance(key_file, datastructures.FileStorage):
+            return await render(error="Invalid file upload")
+
+        # This is a KEYS file of multiple GPG keys
+        # We need to parse it and add each key to the user's account
+        key_blocks = await _upload_key_blocks(key_file)
+        if not key_blocks:
+            return await render(error="No valid GPG keys found in the uploaded 
file")
+
+        # Get selected committee from the form
+        selected_committee = form.selected_committee.data
+        if not selected_committee:
+            return await render(error="You must select at least one committee")
+
+        # Ensure that the selected committee is one of which the user is 
actually a member
+        if selected_committee not in (web_session.committees + 
web_session.projects):
+            return await render(error=f"You are not a member of 
{selected_committee}")
+
+        # Process each key block
+        results = await _upload_process_key_blocks(key_blocks, 
selected_committee)
+        if not results:
+            return await render(error="No keys were added")
+
+        success_count = sum(1 for r in results if r["status"] == "success")
+        error_count = len(results) - success_count
+        await quart.flash(
+            f"Processed {len(results)} keys: {success_count} successful, 
{error_count} failed",
+            "success" if success_count > 0 else "error",
+        )
+    return await render()
+
+
+async def _upload_key_blocks(key_file: datastructures.FileStorage) -> 
list[str]:
+    """Extract GPG key blocks from a KEYS file."""
+    # Read the file content
+    keys_content = await asyncio.to_thread(key_file.read)
+    keys_text = keys_content.decode("utf-8", errors="replace")
+
+    # Extract GPG key blocks
+    key_blocks = []
+    current_block = []
+    in_key_block = False
+
+    for line in keys_text.splitlines():
+        if line.strip() == "-----BEGIN PGP PUBLIC KEY BLOCK-----":
+            in_key_block = True
+            current_block = [line]
+        elif (line.strip() == "-----END PGP PUBLIC KEY BLOCK-----") and 
in_key_block:
+            current_block.append(line)
+            key_blocks.append("\n".join(current_block))
+            in_key_block = False
+        elif in_key_block:
+            current_block.append(line)
+
+    return key_blocks
+
+
+async def _upload_process_key_blocks(key_blocks: list[str], 
selected_committee: str) -> list[dict]:
+    """Process GPG key blocks and add them to the user's account."""
+    results: list[dict] = []
+
+    # Process each key block
+    for i, key_block in enumerate(key_blocks):
+        try:
+            key_info = await key_user_add(None, key_block, 
[selected_committee])
+            if key_info:
+                key_info["status"] = "success"
+                key_info["message"] = "Key added successfully"
+                results.append(key_info)
+        except Exception as e:
+            logging.exception("Exception adding key:")
+            results.append(
+                {
+                    "status": "error",
+                    "message": f"Exception: {e}",
+                    "key_id": f"Key #{i + 1}",
+                    "fingerprint": "Error",
+                    "user_id": "Unknown",
+                }
+            )
+
+    return results
diff --git a/atr/templates/includes/sidebar.html 
b/atr/templates/includes/sidebar.html
index 637030a..411e1b1 100644
--- a/atr/templates/includes/sidebar.html
+++ b/atr/templates/includes/sidebar.html
@@ -69,7 +69,11 @@
         </li>
         <li>
           <a href="{{ url_for('root_keys_add') }}"
-             {% if request.endpoint == 'root_keys_add' %}class="active"{% 
endif %}>Add signing key</a>
+             {% if request.endpoint == 'root_keys_add' %}class="active"{% 
endif %}>Add your signing key</a>
+        </li>
+        <li>
+          <a href="{{ url_for('root_keys_upload') }}"
+             {% if request.endpoint == 'root_keys_upload' %}class="active"{% 
endif %}>Upload a KEYS file</a>
         </li>
         <li>
           <a href="{{ url_for('root_keys_ssh_add') }}"
diff --git a/atr/templates/keys-upload.html b/atr/templates/keys-upload.html
new file mode 100644
index 0000000..6c5d839
--- /dev/null
+++ b/atr/templates/keys-upload.html
@@ -0,0 +1,106 @@
+{% extends "layouts/base.html" %}
+
+{% block title %}
+  Upload KEYS file ~ ATR
+{% endblock title %}
+
+{% block description %}
+  Upload a KEYS file containing multiple GPG public keys.
+{% endblock description %}
+
+{% block content %}
+  <h1>Upload KEYS file</h1>
+  <p class="intro">Upload a KEYS file containing multiple GPG public keys.</p>
+
+  {% if form.errors %}
+    <h2 class="text-danger">Form errors</h2>
+    <div class="error-message mt-3 mb-3">
+      {% for field, errors in form.errors.items() %}
+        {% for error in errors %}<p class="text-danger mb-1">{{ field }}: {{ 
error }}</p>{% endfor %}
+      {% endfor %}
+    </div>
+  {% endif %}
+
+  {% if results %}
+    <h2>KEYS processing results</h2>
+    <p>The following keys were found in your KEYS file:</p>
+
+    {% for key_info in results %}
+      <div class="my-3 p-3 rounded {% if key_info.status == 'success' 
%}bg-light{% else %}bg-danger-subtle{% endif %}">
+        <h3 class="mt-0">
+          {% if key_info.status == 'success' %}
+            Success: Added Key
+          {% else %}
+            Error: Failed to add key
+          {% endif %}
+        </h3>
+        <dl class="row mb-0">
+          <dt class="col-sm-3 fw-bold">Key ID</dt>
+          <dd class="col-sm-9 mb-2">
+            {{ key_info.key_id }}
+          </dd>
+          <dt class="col-sm-3 fw-bold">Fingerprint</dt>
+          <dd class="col-sm-9 mb-2">
+            {{ key_info.fingerprint }}
+          </dd>
+          <dt class="col-sm-3 fw-bold">User ID</dt>
+          <dd class="col-sm-9 mb-2">
+            {{ key_info.user_id }}
+          </dd>
+          {% if key_info.status == 'success' %}
+            <dt class="col-sm-3 fw-bold">Created</dt>
+            <dd class="col-sm-9 mb-2">
+              {{ key_info.creation_date }}
+            </dd>
+            <dt class="col-sm-3 fw-bold">Expires</dt>
+            <dd class="col-sm-9 mb-2">
+              {{ key_info.expiration_date or 'Never' }}
+            </dd>
+          {% endif %}
+          <dt class="col-sm-3 fw-bold">Status</dt>
+          <dd class="col-sm-9 mb-2">
+            {{ key_info.message }}
+          </dd>
+          {% if key_info.status == 'success' and key_info.data %}
+            <details>
+              <summary>Key Data</summary>
+              <pre class="mb-0">{{ key_info.data }}</pre>
+            </details>
+          {% endif %}
+        </dl>
+      </div>
+    {% endfor %}
+  {% endif %}
+
+  <form method="post" class="striking" enctype="multipart/form-data">
+    {{ form.csrf_token }}
+
+    <div class="mb-4">
+      <div class="mb-3">
+        <label for="key" class="form-label">KEYS file:</label>
+      </div>
+      {{ form.key(class="form-control mb-2", aria_describedby="keys-help") }}
+      <small id="keys-help" class="form-text text-muted">
+        Upload a KEYS file containing multiple PGP public keys. The file 
should contain keys in ASCII-armored format, starting with "-----BEGIN PGP 
PUBLIC KEY BLOCK-----".
+      </small>
+    </div>
+
+    {% if user_committees %}
+      <div class="mb-4">
+        <div class="mb-3">
+          <label for="selected_committee" class="form-label">Associate with 
project:</label>
+        </div>
+        {{ form.selected_committee(class="form-select", 
aria_describedby="committees-help") }}
+        <small id="committees-help" class="form-text text-muted mt-2">
+          Select the committee to associate these keys with. You must be a 
member of the selected committee.
+        </small>
+      </div>
+    {% else %}
+      <div class="text-danger mt-1">
+        <p>You must be a member of at least one committee to add signing 
keys.</p>
+      </div>
+    {% endif %}
+
+    {{ form.submit(class="btn btn-primary") }}
+  </form>
+{% endblock content %}


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to