(bugfix) Normalize pasted OpenSSH private keys
Canonicalize uploaded OpenSSH private keys before validation by normalizing line endings, removing whitespace from the base64 body, and re-wrapping it between the BEGIN and END markers. Add SSH credential tests that generate a real ed25519 key, damage its wrapping, and verify that validation succeeds after normalization. Return a clearer validation error for PEM private keys, which are not supported by the current credential flow.
This commit is contained in:
@@ -1,6 +1,7 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import textwrap
|
||||
import subprocess
|
||||
from pathlib import Path
|
||||
from tempfile import TemporaryDirectory
|
||||
@@ -238,7 +239,20 @@ class ScheduleConfigForm(forms.ModelForm):
|
||||
|
||||
|
||||
def normalize_private_key(private_key: str) -> str:
|
||||
return private_key.replace("\r\n", "\n").replace("\r", "\n").strip().lstrip("\ufeff")
|
||||
normalized = private_key.replace("\r\n", "\n").replace("\r", "\n").strip().lstrip("\ufeff")
|
||||
|
||||
begin_marker = "-----BEGIN OPENSSH PRIVATE KEY-----"
|
||||
end_marker = "-----END OPENSSH PRIVATE KEY-----"
|
||||
if begin_marker in normalized and end_marker in normalized:
|
||||
before_body, after_begin = normalized.split(begin_marker, 1)
|
||||
body, after_end = after_begin.split(end_marker, 1)
|
||||
if before_body.strip() or after_end.strip():
|
||||
return normalized
|
||||
compact_body = "".join(body.split())
|
||||
wrapped_body = "\n".join(textwrap.wrap(compact_body, width=70))
|
||||
return f"{begin_marker}\n{wrapped_body}\n{end_marker}"
|
||||
|
||||
return normalized
|
||||
|
||||
|
||||
def normalize_public_key(public_key: str) -> str:
|
||||
@@ -254,8 +268,13 @@ def public_key_identity(public_key: str) -> str:
|
||||
|
||||
def validate_ssh_private_key(private_key: str) -> str:
|
||||
if "BEGIN OPENSSH PRIVATE KEY" not in private_key:
|
||||
if private_key.strip().startswith(("ssh-ed25519 ", "ssh-rsa ", "ecdsa-sha2-", "sk-")):
|
||||
stripped = private_key.strip()
|
||||
if stripped.startswith(("ssh-ed25519 ", "ssh-rsa ", "ecdsa-sha2-", "sk-")):
|
||||
raise forms.ValidationError("This looks like a public key. Paste the private key in this field.")
|
||||
if "BEGIN RSA PRIVATE KEY" in stripped or "BEGIN EC PRIVATE KEY" in stripped:
|
||||
raise forms.ValidationError(
|
||||
"PEM private keys are not supported here yet. Convert it to an unencrypted OpenSSH key first."
|
||||
)
|
||||
raise forms.ValidationError("Invalid SSH private key: missing OpenSSH private key header.")
|
||||
|
||||
with TemporaryDirectory() as tmp:
|
||||
|
||||
Reference in New Issue
Block a user