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 fb20f52 Allow users to upload their public SSH keys
fb20f52 is described below
commit fb20f52f7800b105e9e85e4449ee05734a9943b8
Author: Sean B. Palmer <[email protected]>
AuthorDate: Wed Mar 19 15:24:36 2025 +0200
Allow users to upload their public SSH keys
---
atr/blueprints/admin/admin.py | 1 +
atr/db/__init__.py | 17 +++++++
atr/db/models.py | 6 +++
atr/routes/keys.py | 95 ++++++++++++++++++++++++++++++++++---
atr/templates/includes/sidebar.html | 4 ++
atr/templates/keys-review.html | 47 ++++++++++++++++--
atr/templates/keys-ssh-add.html | 44 +++++++++++++++++
7 files changed, 204 insertions(+), 10 deletions(-)
diff --git a/atr/blueprints/admin/admin.py b/atr/blueprints/admin/admin.py
index 0556e7c..9a439a9 100644
--- a/atr/blueprints/admin/admin.py
+++ b/atr/blueprints/admin/admin.py
@@ -128,6 +128,7 @@ async def admin_data(model: str = "Committee") -> str:
"Project": data.project,
"PublicSigningKey": data.public_signing_key,
"Release": data.release,
+ "SSHKey": data.ssh_key,
"Task": data.task,
"VotePolicy": data.vote_policy,
}
diff --git a/atr/db/__init__.py b/atr/db/__init__.py
index 22d133b..67eb157 100644
--- a/atr/db/__init__.py
+++ b/atr/db/__init__.py
@@ -303,6 +303,23 @@ class Session(sqlalchemy.ext.asyncio.AsyncSession):
return Query(self, query)
+ def ssh_key(
+ self,
+ fingerprint: Any = _DEFAULT,
+ key: Any = _DEFAULT,
+ asf_uid: Any = _DEFAULT,
+ ) -> Query[models.SSHKey]:
+ query = sqlmodel.select(models.SSHKey)
+
+ if fingerprint is not _DEFAULT:
+ query = query.where(models.SSHKey.fingerprint == fingerprint)
+ if key is not _DEFAULT:
+ query = query.where(models.SSHKey.key == key)
+ if asf_uid is not _DEFAULT:
+ query = query.where(models.SSHKey.asf_uid == asf_uid)
+
+ return Query(self, query)
+
def task(
self,
id: Any = _DEFAULT,
diff --git a/atr/db/models.py b/atr/db/models.py
index 1776156..df2ff89 100644
--- a/atr/db/models.py
+++ b/atr/db/models.py
@@ -300,3 +300,9 @@ class Release(sqlmodel.SQLModel, table=True):
if project is None:
return None
return project.committee
+
+
+class SSHKey(sqlmodel.SQLModel, table=True):
+ fingerprint: str = sqlmodel.Field(primary_key=True)
+ key: str
+ asf_uid: str
diff --git a/atr/routes/keys.py b/atr/routes/keys.py
index 7831335..7438cd0 100644
--- a/atr/routes/keys.py
+++ b/atr/routes/keys.py
@@ -18,8 +18,10 @@
"""keys.py"""
import asyncio
+import base64
import contextlib
import datetime
+import hashlib
import logging
import logging.handlers
import pprint
@@ -27,9 +29,11 @@ import shutil
import tempfile
from collections.abc import AsyncGenerator, Sequence
+import cryptography.hazmat.primitives.serialization as serialization
import gnupg
import quart
import werkzeug.wrappers.response as response
+import wtforms
import asfquart as asfquart
import asfquart.auth as auth
@@ -38,6 +42,12 @@ import asfquart.session as session
import atr.db as db
import atr.db.models as models
import atr.routes as routes
+import atr.util as util
+
+
+class AddSSHKeyForm(util.QuartFormTyped):
+ key = wtforms.StringField("SSH key", widget=wtforms.widgets.TextArea())
+ submit = wtforms.SubmitField("Add SSH key")
@contextlib.asynccontextmanager
@@ -77,6 +87,33 @@ async def key_add_post(
return await key_user_add(web_session, public_key, selected_committees)
+def key_ssh_fingerprint(ssh_key_string: str) -> str:
+ # The format should be as in *.pub or authorized_keys files
+ # I.e. TYPE DATA COMMENT
+ ssh_key_parts = ssh_key_string.strip().split()
+ if len(ssh_key_parts) >= 2:
+ key_type = ssh_key_parts[0]
+ key_data = ssh_key_parts[1]
+ # We discard the comment, which is ssh_key_parts[2]
+
+ # Parse the key
+ key = serialization.load_ssh_public_key(f"{key_type}
{key_data}".encode())
+
+ # Get raw public key bytes
+ public_bytes = key.public_bytes(
+ encoding=serialization.Encoding.DER,
format=serialization.PublicFormat.SubjectPublicKeyInfo
+ )
+
+ # Calculate SHA256 hash
+ digest = hashlib.sha256(public_bytes).digest()
+ fingerprint = base64.b64encode(digest).decode("utf-8").rstrip("=")
+
+ # TODO: Do we really want to use a prefix?
+ return f"SHA256:{fingerprint}"
+
+ raise ValueError("Invalid SSH key format")
+
+
async def key_user_add(
web_session: session.ClientSession, public_key: str, selected_committees:
list[str]
) -> dict | None:
@@ -208,6 +245,40 @@ async def root_keys_add() -> str:
)
[email protected]_route("/keys/ssh/add", methods=["GET", "POST"])
[email protected](auth.Requirements.committer)
+async def root_keys_ssh_add() -> response.Response | str:
+ """Add a new SSH key to the user's account."""
+ # TODO: Make an auth.require wrapper that gives the session automatically
+ # And the form if it's a POST handler? Might be hard to type
+ # But we can use variants of the function
+ # GET, POST, GET_POST are all we need
+ # We could even include auth in the function names
+ web_session = await session.read()
+ if web_session is None:
+ raise base.ASFQuartException("Not authenticated", errorcode=401)
+
+ form = await AddSSHKeyForm.create_form()
+ fingerprint = None
+ if await form.validate_on_submit():
+ key: str = util.unwrap(form.key.data)
+ fingerprint = await asyncio.to_thread(key_ssh_fingerprint, key)
+ logging.info("Fingerprint: %s", fingerprint)
+ async with db.session() as data:
+ logging.info("Adding SSH key to database")
+ data.add(models.SSHKey(fingerprint=fingerprint, key=key,
asf_uid=util.unwrap(web_session.uid)))
+ await data.commit()
+ await quart.flash(f"SSH key added successfully: {fingerprint}",
"success")
+ return quart.redirect(quart.url_for("root_keys_review"))
+
+ return await quart.render_template(
+ "keys-ssh-add.html",
+ asf_id=web_session.uid,
+ form=form,
+ fingerprint=fingerprint,
+ )
+
+
@routes.app_route("/keys/delete", methods=["POST"])
@auth.require(auth.Requirements.committer)
async def root_keys_delete() -> response.Response:
@@ -224,17 +295,25 @@ async def root_keys_delete() -> response.Response:
async with db.session() as data:
async with data.begin():
- # Get the key and verify ownership
+ # Try to get a GPG key first
key = await data.public_signing_key(fingerprint=fingerprint,
apache_uid=web_session.uid).get()
- if not key:
- await quart.flash("Key not found or not owned by you", "error")
+ if key:
+ # Delete the GPG key
+ await data.delete(key)
+ await quart.flash("GPG key deleted successfully", "success")
return quart.redirect(quart.url_for("root_keys_review"))
- # Delete the key
- await data.delete(key)
+ # If not a GPG key, try to get an SSH key
+ ssh_key = await data.ssh_key(fingerprint=fingerprint,
asf_uid=web_session.uid).get()
+ if ssh_key:
+ # Delete the SSH key
+ await data.delete(ssh_key)
+ await quart.flash("SSH key deleted successfully", "success")
+ return quart.redirect(quart.url_for("root_keys_review"))
- await quart.flash("Key deleted successfully", "success")
- return quart.redirect(quart.url_for("root_keys_review"))
+ # No key was found
+ await quart.flash("Key not found or not owned by you", "error")
+ return quart.redirect(quart.url_for("root_keys_review"))
@routes.app_route("/keys/review")
@@ -248,6 +327,7 @@ async def root_keys_review() -> str:
# Get all existing keys for the user
async with db.session() as data:
user_keys = await data.public_signing_key(apache_uid=web_session.uid,
_committees=True).all()
+ user_ssh_keys = await data.ssh_key(asf_uid=web_session.uid).all()
status_message = quart.request.args.get("status_message")
status_type = quart.request.args.get("status_type")
@@ -256,6 +336,7 @@ async def root_keys_review() -> str:
"keys-review.html",
asf_id=web_session.uid,
user_keys=user_keys,
+ user_ssh_keys=user_ssh_keys,
algorithms=routes.algorithms,
status_message=status_message,
status_type=status_type,
diff --git a/atr/templates/includes/sidebar.html
b/atr/templates/includes/sidebar.html
index 9c9cabc..ead4f99 100644
--- a/atr/templates/includes/sidebar.html
+++ b/atr/templates/includes/sidebar.html
@@ -70,6 +70,10 @@
<a href="{{ url_for('root_keys_add') }}"
{% if request.endpoint == 'root_keys_add' %}class="active"{%
endif %}>Add signing key</a>
</li>
+ <li>
+ <a href="{{ url_for('root_keys_ssh_add') }}"
+ {% if request.endpoint == 'root_keys_ssh_add' %}class="active"{%
endif %}>Add SSH key</a>
+ </li>
</ul>
{% if is_admin(current_user.uid) %}
diff --git a/atr/templates/keys-review.html b/atr/templates/keys-review.html
index 9196611..610cd58 100644
--- a/atr/templates/keys-review.html
+++ b/atr/templates/keys-review.html
@@ -1,15 +1,15 @@
{% extends "layouts/base.html" %}
{% block title %}
- Your signing keys ~ ATR
+ Your keys ~ ATR
{% endblock title %}
{% block description %}
- Review your signing keys.
+ Review your keys.
{% endblock description %}
{% block content %}
- <h1>Your signing keys</h1>
+ <h1>Your keys</h1>
<p class="intro">Review your public keys used for signing release
artifacts.</p>
<div class="user-info">
@@ -100,4 +100,45 @@
<a href="{{ url_for('root_keys_add') }}">Add a key</a>
</p>
{% endif %}
+
+ <h2>SSH keys</h2>
+ {% if user_ssh_keys %}
+ <div class="mb-5 p-4 bg-light rounded">
+ <div class="d-grid gap-4">
+ {% for key in user_ssh_keys %}
+ <div class="card p-3 border">
+ <table class="mb-0">
+ <tbody>
+ <tr>
+ <th class="p-2 text-dark">Fingerprint</th>
+ <td class="text-break">{{ key.fingerprint }}</td>
+ </tr>
+ <tr>
+ <th class="p-2 text-dark">Type</th>
+ <td class="text-break">{{ key.key.split()[0] }}</td>
+ </tr>
+ </tbody>
+ </table>
+
+ <details class="mt-3 p-3 bg-light rounded">
+ <summary class="fw-bold">View whole key</summary>
+ <pre class="mt-3">{{ key.key }}</pre>
+ </details>
+
+ <form method="post" action="{{ url_for('root_keys_delete') }}"
class="mt-3">
+ <input type="hidden" name="fingerprint" value="{{
key.fingerprint }}" />
+ <button type="submit" class="btn btn-danger">Delete key</button>
+ </form>
+ </div>
+ {% endfor %}
+ </div>
+ </div>
+ {% else %}
+ <p>
+ <strong>You haven't added any SSH keys yet.</strong>
+ </p>
+ <p>
+ <a href="{{ url_for('root_keys_ssh_add') }}">Add an SSH key</a>
+ </p>
+ {% endif %}
{% endblock content %}
diff --git a/atr/templates/keys-ssh-add.html b/atr/templates/keys-ssh-add.html
new file mode 100644
index 0000000..26db6ed
--- /dev/null
+++ b/atr/templates/keys-ssh-add.html
@@ -0,0 +1,44 @@
+{% extends "layouts/base.html" %}
+
+{% block title %}
+ Add SSH key ~ ATR
+{% endblock title %}
+
+{% block description %}
+ Add an SSH public key to your account.
+{% endblock description %}
+
+{% block content %}
+ <h1>Add SSH key</h1>
+ <p class="intro">Add your SSH public key to use for rsync authentication.</p>
+
+ <div class="user-info">
+ <p>
+ Welcome, <strong>{{ asf_id }}</strong>! You are authenticated as an ASF
committer.
+ </p>
+ </div>
+
+ {% 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 %}
+
+ <form method="post" class="striking">
+ {{ form.csrf_token }}
+ <div class="mb-4">
+ <div class="mb-3">
+ <label for="key" class="form-label">SSH public key:</label>
+ </div>
+ {{ form.key(class="form-control mb-2", rows=4, placeholder="Paste your
SSH public key here (in the format used in authorized_keys files)",
aria_describedby="key-help") }}
+ <small id="key-help" class="form-text text-muted">
+ Your SSH public key should be in the standard format, starting with a
key type (like "ssh-rsa" or "ssh-ed25519") followed by the key data.
+ </small>
+ </div>
+
+ {{ form.submit(class="btn btn-primary") }}
+ </form>
+{% endblock content %}
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]