feat(ssh): add multi-organization support for certificate signing

Add support for users who belong to multiple organizations to select
which organization's CA should sign their SSH certificates.

Changes:
- CLI: Add --org-id and --list-orgs options for organization selection
- API: Return MULTIPLE_ORGS_AMBIGUOUS error when org selection needed
- API: Add /users/me/organizations/simple endpoint for CLI org listing
- DB: Add organization_id to certificate_audit_logs for better tracking
- Include organization_name in certificate response for clarity
This commit is contained in:
2026-04-24 22:27:24 +09:30
parent 015c622016
commit cec04f3cb2
8 changed files with 314 additions and 46 deletions
+75 -5
View File
@@ -253,7 +253,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,23 +272,54 @@ 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:
f.write(json_result['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."""
@@ -393,6 +424,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."""
@@ -465,11 +528,13 @@ if __name__ == "__main__":
parser.add_argument("--clear-cache", action='store_true', default=False, help="Remove the cached authentication token")
parser.add_argument("--remove-key", nargs='?', const='', metavar='KEY_ID', help="Remove an SSH key from your profile. Omit KEY_ID to pick interactively.")
parser.add_argument("--list-keys", action='store_true', default=False, help="List SSH keys in your profile")
parser.add_argument("--list-orgs", action='store_true', default=False, help="List all organizations you are a member of")
parser.add_argument("--org-id", metavar='ORG_ID', help="Specify organization ID for certificate signing (required if member of multiple orgs)")
args = parser.parse_args()
if not (args.check_cert or args.request_cert or args.add_key or args.clear_cache
or args.remove_key is not None or args.list_keys):
parser.error("At least one of --check-cert, --request-cert, --add-key, --list-keys, --remove-key, or --clear-cache must be provided.")
or args.remove_key is not None or args.list_keys or args.list_orgs):
parser.error("At least one of --check-cert, --request-cert, --add-key, --list-keys, --remove-key, --list-orgs, or --clear-cache must be provided.")
# Retrieve SSH key from environment variables if not provided via CLI
@@ -488,6 +553,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())
@@ -524,5 +594,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)