Merge branch 'main' into v1.01/stable

This commit is contained in:
2026-04-26 22:54:54 +08:00
committed by GitHub
135 changed files with 13567 additions and 307 deletions
+163 -7
View File
@@ -49,10 +49,96 @@ class MyServer(BaseHTTPRequestHandler):
self.send_response(200)
self.send_header("Content-type", "text/html")
self.end_headers()
self.wfile.write(bytes("<html><head><title>OIDC Workflow Tool</title></head>", "utf-8"))
self.wfile.write(bytes("<body><p>The token has been received</p>", "utf-8"))
self.wfile.write(bytes("<p>You may now close this window.</p>", "utf-8"))
self.wfile.write(bytes("</body></html>", "utf-8"))
html_content = """<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Authentication Successful - Gatehouse</title>
<!-- Best-effort CSS load from primary site -->
<link rel="stylesheet" href="{SIGN_URL}/static/css/main.css">
<style>
* {{
margin: 0;
padding: 0;
box-sizing: border-box;
}}
body {{
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
background-color: #f0f4f8;
min-height: 100vh;
display: flex;
align-items: center;
justify-content: center;
}}
.card {{
background: white;
border-radius: 12px;
box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
padding: 48px 40px;
text-align: center;
max-width: 400px;
width: 90%;
}}
.checkmark {{
width: 64px;
height: 64px;
background: #10b981;
border-radius: 50%;
display: flex;
align-items: center;
justify-content: center;
margin: 0 auto 24px;
}}
.checkmark svg {{
width: 32px;
height: 32px;
stroke: white;
stroke-width: 3;
fill: none;
}}
h1 {{
color: #1f2937;
font-size: 24px;
font-weight: 600;
margin-bottom: 12px;
}}
p {{
color: #6b7280;
font-size: 16px;
line-height: 1.5;
}}
.fallback {{
margin-top: 24px;
padding-top: 24px;
border-top: 1px solid #e5e7eb;
color: #9ca3af;
font-size: 14px;
}}
</style>
</head>
<body>
<div class="card">
<div class="checkmark">
<svg viewBox="0 0 24 24">
<polyline points="20 6 9 17 4 12"></polyline>
</svg>
</div>
<h1>Authentication Complete</h1>
<p>You can now return to the terminal.</p>
<p class="fallback">If this window doesn't close automatically, you can close it manually.</p>
</div>
<script>
setTimeout(function() {{
window.close();
if (window.innerHeight > 0) {{
document.querySelector('.fallback').textContent = 'Window refused to close. You may close this tab manually.';
}}
}}, 2000);
</script>
</body>
</html>""".format(SIGN_URL=SIGN_URL)
self.wfile.write(bytes(html_content, "utf-8"))
parsed_url = urlparse(self.path)
query_data = dict(parse_qsl(parsed_url.query))
@@ -253,7 +339,7 @@ def fetch_my_principals():
return principal_names
def request_certificate():
def request_certificate(org_id=None):
CERT_ID = os.getenv("CERT_ID") or get_activated_ssh_key()
principals = fetch_my_principals()
@@ -272,9 +358,13 @@ def request_certificate():
'principals': principals,
}
# Add organization_id if specified
if org_id:
payload['organization_id'] = org_id
try:
response = requests.post(f"{SIGN_URL}/api/v1/ssh/sign", json=payload, headers=headers)
if response.status_code == 201:
json_result = response.json().get('data', response.json())
with open(CERT_FILE_PATH, 'w') as f:
@@ -287,14 +377,41 @@ def request_certificate():
logger.info(f"Certificate signed successfully, located at {CERT_FILE_PATH}")
logger.info(f"Valid for principals: {', '.join(json_result.get('principals', principals))}")
# Show which org issued the cert
org_name = json_result.get('organization_name', 'Unknown')
logger.info(f"Issued by organization: {org_name}")
logger.info("You can login to your destination server with the following command")
logger.info(f"\tssh user@server -o CertificateFile={CERT_FILE_PATH}")
elif response.status_code == 400:
error_data = response.json()
if error_data.get('error', {}).get('type') == 'MULTIPLE_ORGS_AMBIGUOUS':
logger.error("You are a member of multiple organizations. Please specify one with --org-id")
logger.error("\nYour organizations:")
for org in error_data.get('error', {}).get('details', {}).get('organizations', []):
logger.error(f" - {org['name']} (ID: {org['id']}, Role: {org['role']})")
logger.error("\nRun: secuird --list-orgs to see all your organizations")
logger.error("Then run: secuird -r --org-id <organization_id>")
else:
logger.error(f"Error: {error_data.get('message', 'Unknown error')}")
exit(1)
elif response.status_code == 403:
error_data = response.json()
logger.error(f"Permission denied: {error_data.get('message', 'Unknown error')}")
exit(1)
else:
logger.error("Error in response from server")
logger.error(f"Status code: {response.status_code}")
logger.error(f"Response text: {response.text}")
exit(1)
except Exception as e:
logger.error(f"Error during certificate signing: {e}")
exit(1)
def generate_and_sign_challenge(ssh_key_file, key_id):
"""Fetch a challenge from the server, sign it with the SSH key, and submit the signature."""
@@ -321,11 +438,13 @@ def generate_and_sign_challenge(ssh_key_file, key_id):
with open(CHALLENGE_FILE_PATH, 'w') as f:
f.write(challenge_text)
os.chmod(CHALLENGE_FILE_PATH, 0o600)
subprocess.run(
["ssh-keygen", "-Y", "sign", "-f", ssh_key_file, "-n", "file", CHALLENGE_FILE_PATH],
check=True,
)
os.chmod(CHALLENGE_SIG_FILE_PATH, 0o600)
with open(CHALLENGE_SIG_FILE_PATH, 'rb') as f:
signature = base64.b64encode(f.read()).decode('utf-8')
@@ -399,6 +518,38 @@ def remove_ssh_key(key_id=None):
else:
logger.error(f"Failed to remove key {k['id']}: {del_response.status_code} - {del_response.text}")
def list_organizations():
"""List all organizations the user is a member of."""
response = requests.get(
f"{SIGN_URL}/api/v1/users/me/organizations/simple",
headers=auth_headers()
)
if response.status_code != 200:
logger.error(f"Failed to list organizations: {response.status_code} - {response.text}")
exit(1)
data = response.json().get('data', {})
orgs = data.get('organizations', [])
if not orgs:
print("You are not a member of any organizations.")
return
print("\nYour Organizations:")
print("-" * 80)
for org in orgs:
ca_status = []
if org.get('has_user_ca'):
ca_status.append("User CA ✓")
if org.get('has_host_ca'):
ca_status.append("Host CA ✓")
ca_str = f" ({', '.join(ca_status)})" if ca_status else " (No CAs configured)"
print(f" ID: {org['id']}")
print(f" Name: {org['name']}{ca_str}")
print(f" Role: {org['role']}")
print("-" * 80)
def add_ssh_key(ssh_key_file):
"""Add an SSH key to the server and auto-verify it."""
@@ -540,6 +691,11 @@ if __name__ == "__main__":
remove_ssh_key(args.remove_key if args.remove_key else None)
exit(0)
if args.list_orgs:
request_token()
list_organizations()
exit(0)
if args.list_keys:
request_token()
response = requests.get(f"{SIGN_URL}/api/v1/ssh/keys", headers=auth_headers())
@@ -580,5 +736,5 @@ if __name__ == "__main__":
if args.force:
logger.info("Forcing renewal of certificate")
if args.force or checkCert() == 1:
request_certificate()
request_certificate(org_id=args.org_id)
exit(0)