users: added SSH key management for user admin pages
This commit is contained in:
parent
15272baace
commit
35cefa9b2d
16 changed files with 4822 additions and 21 deletions
|
|
@ -653,13 +653,13 @@
|
|||
};
|
||||
};
|
||||
ecdsa = super.buildPythonPackage {
|
||||
name = "ecdsa-0.11";
|
||||
name = "ecdsa-0.13";
|
||||
buildInputs = with self; [];
|
||||
doCheck = false;
|
||||
propagatedBuildInputs = with self; [];
|
||||
src = fetchurl {
|
||||
url = "https://pypi.python.org/packages/6c/3f/92fe5dcdcaa7bd117be21e5520c9a54375112b66ec000d209e9e9519fad1/ecdsa-0.11.tar.gz";
|
||||
md5 = "8ef586fe4dbb156697d756900cb41d7c";
|
||||
url = "https://pypi.python.org/packages/f9/e5/99ebb176e47f150ac115ffeda5fedb6a3dbb3c00c74a59fd84ddf12f5857/ecdsa-0.13.tar.gz";
|
||||
md5 = "1f60eda9cb5c46722856db41a3ae6670";
|
||||
};
|
||||
meta = {
|
||||
license = [ pkgs.lib.licenses.mit ];
|
||||
|
|
@ -1172,19 +1172,6 @@
|
|||
license = [ pkgs.lib.licenses.bsdOriginal ];
|
||||
};
|
||||
};
|
||||
paramiko = super.buildPythonPackage {
|
||||
name = "paramiko-1.15.1";
|
||||
buildInputs = with self; [];
|
||||
doCheck = false;
|
||||
propagatedBuildInputs = with self; [pycrypto ecdsa];
|
||||
src = fetchurl {
|
||||
url = "https://pypi.python.org/packages/04/2b/a22d2a560c1951abbbf95a0628e245945565f70dc082d9e784666887222c/paramiko-1.15.1.tar.gz";
|
||||
md5 = "48c274c3f9b1282932567b21f6acf3b5";
|
||||
};
|
||||
meta = {
|
||||
license = [ { fullName = "LGPL"; } { fullName = "GNU Library or Lesser General Public License (LGPL)"; } ];
|
||||
};
|
||||
};
|
||||
pathlib2 = super.buildPythonPackage {
|
||||
name = "pathlib2-2.3.0";
|
||||
buildInputs = with self; [];
|
||||
|
|
@ -1722,7 +1709,7 @@
|
|||
name = "rhodecode-enterprise-ce-4.9.0";
|
||||
buildInputs = with self; [pytest py pytest-cov pytest-sugar pytest-runner pytest-catchlog pytest-profiling gprof2dot pytest-timeout mock WebTest cov-core coverage configobj];
|
||||
doCheck = true;
|
||||
propagatedBuildInputs = with self; [Babel Beaker FormEncode Mako Markdown MarkupSafe MySQL-python Paste PasteDeploy PasteScript Pygments pygments-markdown-lexer Pylons Routes SQLAlchemy Tempita URLObject WebError WebHelpers WebHelpers2 WebOb WebTest Whoosh alembic amqplib anyjson appenlight-client authomatic cssselect celery channelstream colander decorator deform docutils gevent gunicorn infrae.cache ipython iso8601 kombu lxml msgpack-python nbconvert packaging psycopg2 py-gfm pycrypto pycurl pyparsing pyramid pyramid-debugtoolbar pyramid-mako pyramid-beaker pysqlite python-dateutil python-ldap python-memcached python-pam recaptcha-client repoze.lru requests simplejson subprocess32 waitress zope.cachedescriptors dogpile.cache dogpile.core psutil py-bcrypt];
|
||||
propagatedBuildInputs = with self; [Babel Beaker FormEncode Mako Markdown MarkupSafe MySQL-python Paste PasteDeploy PasteScript Pygments pygments-markdown-lexer Pylons Routes SQLAlchemy Tempita URLObject WebError WebHelpers WebHelpers2 WebOb WebTest Whoosh alembic amqplib anyjson appenlight-client authomatic cssselect celery channelstream colander decorator deform docutils gevent gunicorn infrae.cache ipython iso8601 kombu lxml msgpack-python nbconvert packaging psycopg2 py-gfm pycrypto pycurl pyparsing pyramid pyramid-debugtoolbar pyramid-mako pyramid-beaker pysqlite python-dateutil python-ldap python-memcached python-pam recaptcha-client repoze.lru requests simplejson sshpubkeys subprocess32 waitress zope.cachedescriptors dogpile.cache dogpile.core psutil py-bcrypt];
|
||||
src = ./.;
|
||||
meta = {
|
||||
license = [ { fullName = "Affero GNU General Public License v3 or later (AGPLv3+)"; } { fullName = "AGPLv3, and Commercial License"; } ];
|
||||
|
|
@ -1832,6 +1819,19 @@
|
|||
license = [ pkgs.lib.licenses.mit ];
|
||||
};
|
||||
};
|
||||
sshpubkeys = super.buildPythonPackage {
|
||||
name = "sshpubkeys-2.2.0";
|
||||
buildInputs = with self; [];
|
||||
doCheck = false;
|
||||
propagatedBuildInputs = with self; [pycrypto ecdsa];
|
||||
src = fetchurl {
|
||||
url = "https://pypi.python.org/packages/27/da/337fabeb3dca6b62039a93ceaa636f25065e0ae92b575b1235342076cf0a/sshpubkeys-2.2.0.tar.gz";
|
||||
md5 = "458e45f6b92b1afa84f0ffe1f1c90935";
|
||||
};
|
||||
meta = {
|
||||
license = [ pkgs.lib.licenses.bsdOriginal ];
|
||||
};
|
||||
};
|
||||
subprocess32 = super.buildPythonPackage {
|
||||
name = "subprocess32-3.2.7";
|
||||
buildInputs = with self; [];
|
||||
|
|
|
|||
|
|
@ -19,7 +19,7 @@ deform==2.0.4
|
|||
docutils==0.13.1
|
||||
dogpile.cache==0.6.4
|
||||
dogpile.core==0.4.1
|
||||
ecdsa==0.11
|
||||
ecdsa==0.13
|
||||
FormEncode==1.2.4
|
||||
future==0.14.3
|
||||
futures==3.0.2
|
||||
|
|
@ -39,7 +39,6 @@ MySQL-python==1.2.5
|
|||
nose==1.3.6
|
||||
objgraph==3.1.0
|
||||
packaging==15.2
|
||||
paramiko==1.15.1
|
||||
Paste==2.0.3
|
||||
PasteDeploy==1.5.2
|
||||
PasteScript==1.7.5
|
||||
|
|
@ -74,6 +73,7 @@ simplejson==3.11.1
|
|||
six==1.9.0
|
||||
Sphinx==1.2.2
|
||||
SQLAlchemy==1.1.11
|
||||
sshpubkeys==2.2.0
|
||||
subprocess32==3.2.7
|
||||
supervisor==3.3.2
|
||||
Tempita==0.5.2
|
||||
|
|
|
|||
|
|
@ -51,7 +51,7 @@ PYRAMID_SETTINGS = {}
|
|||
EXTENSIONS = {}
|
||||
|
||||
__version__ = ('.'.join((str(each) for each in VERSION[:3])))
|
||||
__dbversion__ = 79 # defines current db version for migrations
|
||||
__dbversion__ = 80 # defines current db version for migrations
|
||||
__platform__ = platform.system()
|
||||
__license__ = 'AGPLv3, and Commercial License'
|
||||
__author__ = 'RhodeCode GmbH'
|
||||
|
|
|
|||
|
|
@ -126,6 +126,20 @@ def admin_routes(config):
|
|||
name='edit_user_auth_tokens_delete',
|
||||
pattern='/users/{user_id:\d+}/edit/auth_tokens/delete')
|
||||
|
||||
# user ssh keys
|
||||
config.add_route(
|
||||
name='edit_user_ssh_keys',
|
||||
pattern='/users/{user_id:\d+}/edit/ssh_keys')
|
||||
config.add_route(
|
||||
name='edit_user_ssh_keys_generate_keypair',
|
||||
pattern='/users/{user_id:\d+}/edit/ssh_keys/generate')
|
||||
config.add_route(
|
||||
name='edit_user_ssh_keys_add',
|
||||
pattern='/users/{user_id:\d+}/edit/ssh_keys/new')
|
||||
config.add_route(
|
||||
name='edit_user_ssh_keys_delete',
|
||||
pattern='/users/{user_id:\d+}/edit/ssh_keys/delete')
|
||||
|
||||
# user emails
|
||||
config.add_route(
|
||||
name='edit_user_emails',
|
||||
|
|
|
|||
173
rhodecode/apps/admin/tests/test_admin_users_ssh_keys.py
Normal file
173
rhodecode/apps/admin/tests/test_admin_users_ssh_keys.py
Normal file
|
|
@ -0,0 +1,173 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
|
||||
# Copyright (C) 2010-2017 RhodeCode GmbH
|
||||
#
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU Affero General Public License, version 3
|
||||
# (only), as published by the Free Software Foundation.
|
||||
#
|
||||
# This program is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# GNU General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU Affero General Public License
|
||||
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
#
|
||||
# This program is dual-licensed. If you wish to learn more about the
|
||||
# RhodeCode Enterprise Edition, including its added features, Support services,
|
||||
# and proprietary license terms, please see https://rhodecode.com/licenses/
|
||||
|
||||
import pytest
|
||||
|
||||
from rhodecode.model.db import User, UserSshKeys
|
||||
|
||||
from rhodecode.tests import TestController, assert_session_flash
|
||||
from rhodecode.tests.fixture import Fixture
|
||||
|
||||
fixture = Fixture()
|
||||
|
||||
|
||||
def route_path(name, params=None, **kwargs):
|
||||
import urllib
|
||||
from rhodecode.apps._base import ADMIN_PREFIX
|
||||
|
||||
base_url = {
|
||||
'edit_user_ssh_keys':
|
||||
ADMIN_PREFIX + '/users/{user_id}/edit/ssh_keys',
|
||||
'edit_user_ssh_keys_generate_keypair':
|
||||
ADMIN_PREFIX + '/users/{user_id}/edit/ssh_keys/generate',
|
||||
'edit_user_ssh_keys_add':
|
||||
ADMIN_PREFIX + '/users/{user_id}/edit/ssh_keys/new',
|
||||
'edit_user_ssh_keys_delete':
|
||||
ADMIN_PREFIX + '/users/{user_id}/edit/ssh_keys/delete',
|
||||
|
||||
}[name].format(**kwargs)
|
||||
|
||||
if params:
|
||||
base_url = '{}?{}'.format(base_url, urllib.urlencode(params))
|
||||
return base_url
|
||||
|
||||
|
||||
class TestAdminUsersSshKeysView(TestController):
|
||||
INVALID_KEY = """\
|
||||
ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDk+77sjDzVeB6vevJsuZds1iNU5
|
||||
LANOa5CU5G/9JYIA6RYsWWMO7mbsR82IUckdqOHmxSykfR1D1TdluyIpQLrwgH5kb
|
||||
n8FkVI8zBMCKakxowvN67B0R7b1BT4PPzW2JlOXei/m9W12ZY484VTow6/B+kf2Q8
|
||||
cP8tmCJmKWZma5Em7OTUhvjyQVNz3v7HfeY5Hq0Ci4ECJ59hepFDabJvtAXg9XrI6
|
||||
jvdphZTc30I4fG8+hBHzpeFxUGvSGNtXPUbwaAY8j/oHYrTpMgkj6pUEFsiKfC5zP
|
||||
qPFR5HyKTCHW0nFUJnZsbyFT5hMiF/hZkJc9A0ZbdSvJwCRQ/g3bmdL
|
||||
your_email@example.com
|
||||
"""
|
||||
VALID_KEY = 'ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDk+77sjDzVeB6vev' \
|
||||
'JsuZds1iNU5LANOa5CU5G/9JYIA6RYsWWMO7mbsR82IUckdqOHmxSy' \
|
||||
'kfR1D1TdluyIpQLrwgH5kbn8FkVI8zBMCKakxowvN67B0R7b1BT4PP' \
|
||||
'zW2JlOXei/m9W12ZY484VTow6/B+kf2Q8cP8tmCJmKWZma5Em7OTUh' \
|
||||
'vjyQVNz3v7HfeY5Hq0Ci4ECJ59hepFDabJvtAXg9XrI6jvdphZTc30' \
|
||||
'I4fG8+hBHzpeFxUGvSGNtXPUbwaAY8j/oHYrTpMgkj6pUEFsiKfC5zPq' \
|
||||
'PFR5HyKTCHW0nFUJnZsbyFT5hMiF/hZkJc9A0ZbdSvJwCRQ/g3bmdL ' \
|
||||
'your_email@example.com'
|
||||
|
||||
def test_ssh_keys_default_user(self):
|
||||
self.log_user()
|
||||
user = User.get_default_user()
|
||||
self.app.get(
|
||||
route_path('edit_user_ssh_keys', user_id=user.user_id),
|
||||
status=302)
|
||||
|
||||
def test_add_ssh_key_error(self, user_util):
|
||||
self.log_user()
|
||||
user = user_util.create_user()
|
||||
user_id = user.user_id
|
||||
|
||||
key_data = self.INVALID_KEY
|
||||
|
||||
desc = 'MY SSH KEY'
|
||||
response = self.app.post(
|
||||
route_path('edit_user_ssh_keys_add', user_id=user_id),
|
||||
{'description': desc, 'key_data': key_data,
|
||||
'csrf_token': self.csrf_token})
|
||||
assert_session_flash(response, 'An error occurred during ssh '
|
||||
'key saving: Unable to decode the key')
|
||||
|
||||
def test_ssh_key_duplicate(self, user_util):
|
||||
self.log_user()
|
||||
user = user_util.create_user()
|
||||
user_id = user.user_id
|
||||
|
||||
key_data = self.VALID_KEY
|
||||
|
||||
desc = 'MY SSH KEY'
|
||||
response = self.app.post(
|
||||
route_path('edit_user_ssh_keys_add', user_id=user_id),
|
||||
{'description': desc, 'key_data': key_data,
|
||||
'csrf_token': self.csrf_token})
|
||||
assert_session_flash(response, 'Ssh Key successfully created')
|
||||
response.follow() # flush session flash
|
||||
|
||||
# add the same key AGAIN
|
||||
desc = 'MY SSH KEY'
|
||||
response = self.app.post(
|
||||
route_path('edit_user_ssh_keys_add', user_id=user_id),
|
||||
{'description': desc, 'key_data': key_data,
|
||||
'csrf_token': self.csrf_token})
|
||||
assert_session_flash(response, 'An error occurred during ssh key '
|
||||
'saving: Such key already exists, '
|
||||
'please use a different one')
|
||||
|
||||
def test_add_ssh_key(self, user_util):
|
||||
self.log_user()
|
||||
user = user_util.create_user()
|
||||
user_id = user.user_id
|
||||
|
||||
key_data = self.VALID_KEY
|
||||
|
||||
desc = 'MY SSH KEY'
|
||||
response = self.app.post(
|
||||
route_path('edit_user_ssh_keys_add', user_id=user_id),
|
||||
{'description': desc, 'key_data': key_data,
|
||||
'csrf_token': self.csrf_token})
|
||||
assert_session_flash(response, 'Ssh Key successfully created')
|
||||
|
||||
response = response.follow()
|
||||
response.mustcontain(desc)
|
||||
|
||||
def test_delete_ssh_key(self, user_util):
|
||||
self.log_user()
|
||||
user = user_util.create_user()
|
||||
user_id = user.user_id
|
||||
|
||||
key_data = self.VALID_KEY
|
||||
|
||||
desc = 'MY SSH KEY'
|
||||
response = self.app.post(
|
||||
route_path('edit_user_ssh_keys_add', user_id=user_id),
|
||||
{'description': desc, 'key_data': key_data,
|
||||
'csrf_token': self.csrf_token})
|
||||
assert_session_flash(response, 'Ssh Key successfully created')
|
||||
response = response.follow() # flush the Session flash
|
||||
|
||||
# now delete our key
|
||||
keys = UserSshKeys.query().filter(UserSshKeys.user_id == user_id).all()
|
||||
assert 1 == len(keys)
|
||||
|
||||
response = self.app.post(
|
||||
route_path('edit_user_ssh_keys_delete', user_id=user_id),
|
||||
{'del_ssh_key': keys[0].ssh_key_id,
|
||||
'csrf_token': self.csrf_token})
|
||||
|
||||
assert_session_flash(response, 'Ssh key successfully deleted')
|
||||
keys = UserSshKeys.query().filter(UserSshKeys.user_id == user_id).all()
|
||||
assert 0 == len(keys)
|
||||
|
||||
def test_generate_keypair(self, user_util):
|
||||
self.log_user()
|
||||
user = user_util.create_user()
|
||||
user_id = user.user_id
|
||||
|
||||
response = self.app.get(
|
||||
route_path('edit_user_ssh_keys_generate_keypair', user_id=user_id))
|
||||
|
||||
response.mustcontain('Private key')
|
||||
response.mustcontain('Public key')
|
||||
response.mustcontain('-----BEGIN RSA PRIVATE KEY-----')
|
||||
|
|
@ -25,6 +25,7 @@ import formencode
|
|||
from pyramid.httpexceptions import HTTPFound
|
||||
from pyramid.view import view_config
|
||||
from sqlalchemy.sql.functions import coalesce
|
||||
from sqlalchemy.exc import IntegrityError
|
||||
|
||||
from rhodecode.apps._base import BaseAppView, DataGridAppView
|
||||
|
||||
|
|
@ -35,9 +36,11 @@ from rhodecode.lib.auth import (
|
|||
from rhodecode.lib import helpers as h
|
||||
from rhodecode.lib.utils2 import safe_int, safe_unicode
|
||||
from rhodecode.model.auth_token import AuthTokenModel
|
||||
from rhodecode.model.ssh_key import SshKeyModel
|
||||
from rhodecode.model.user import UserModel
|
||||
from rhodecode.model.user_group import UserGroupModel
|
||||
from rhodecode.model.db import User, or_, UserIpMap, UserEmailMap, UserApiKeys
|
||||
from rhodecode.model.db import (
|
||||
or_, User, UserIpMap, UserEmailMap, UserApiKeys, UserSshKeys)
|
||||
from rhodecode.model.meta import Session
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
|
@ -252,6 +255,123 @@ class AdminUsersView(BaseAppView, DataGridAppView):
|
|||
|
||||
return HTTPFound(h.route_path('edit_user_auth_tokens', user_id=user_id))
|
||||
|
||||
@LoginRequired()
|
||||
@HasPermissionAllDecorator('hg.admin')
|
||||
@view_config(
|
||||
route_name='edit_user_ssh_keys', request_method='GET',
|
||||
renderer='rhodecode:templates/admin/users/user_edit.mako')
|
||||
def ssh_keys(self):
|
||||
_ = self.request.translate
|
||||
c = self.load_default_context()
|
||||
|
||||
user_id = self.request.matchdict.get('user_id')
|
||||
c.user = User.get_or_404(user_id)
|
||||
self._redirect_for_default_user(c.user.username)
|
||||
|
||||
c.active = 'ssh_keys'
|
||||
c.default_key = self.request.GET.get('default_key')
|
||||
c.user_ssh_keys = SshKeyModel().get_ssh_keys(c.user.user_id)
|
||||
return self._get_template_context(c)
|
||||
|
||||
@LoginRequired()
|
||||
@HasPermissionAllDecorator('hg.admin')
|
||||
@view_config(
|
||||
route_name='edit_user_ssh_keys_generate_keypair', request_method='GET',
|
||||
renderer='rhodecode:templates/admin/users/user_edit.mako')
|
||||
def ssh_keys_generate_keypair(self):
|
||||
_ = self.request.translate
|
||||
c = self.load_default_context()
|
||||
|
||||
user_id = self.request.matchdict.get('user_id')
|
||||
c.user = User.get_or_404(user_id)
|
||||
self._redirect_for_default_user(c.user.username)
|
||||
|
||||
c.active = 'ssh_keys_generate'
|
||||
comment = 'RhodeCode-SSH {}'.format(c.user.email or '')
|
||||
c.private, c.public = SshKeyModel().generate_keypair(comment=comment)
|
||||
|
||||
return self._get_template_context(c)
|
||||
|
||||
@LoginRequired()
|
||||
@HasPermissionAllDecorator('hg.admin')
|
||||
@CSRFRequired()
|
||||
@view_config(
|
||||
route_name='edit_user_ssh_keys_add', request_method='POST')
|
||||
def ssh_keys_add(self):
|
||||
_ = self.request.translate
|
||||
c = self.load_default_context()
|
||||
|
||||
user_id = self.request.matchdict.get('user_id')
|
||||
c.user = User.get_or_404(user_id)
|
||||
|
||||
self._redirect_for_default_user(c.user.username)
|
||||
|
||||
user_data = c.user.get_api_data()
|
||||
key_data = self.request.POST.get('key_data')
|
||||
description = self.request.POST.get('description')
|
||||
|
||||
try:
|
||||
if not key_data:
|
||||
raise ValueError('Please add a valid public key')
|
||||
|
||||
key = SshKeyModel().parse_key(key_data.strip())
|
||||
fingerprint = key.hash_md5()
|
||||
|
||||
ssh_key = SshKeyModel().create(
|
||||
c.user.user_id, fingerprint, key_data, description)
|
||||
ssh_key_data = ssh_key.get_api_data()
|
||||
|
||||
audit_logger.store_web(
|
||||
'user.edit.ssh_key.add', action_data={
|
||||
'data': {'ssh_key': ssh_key_data, 'user': user_data}},
|
||||
user=self._rhodecode_user, )
|
||||
Session().commit()
|
||||
|
||||
h.flash(_("Ssh Key successfully created"), category='success')
|
||||
|
||||
except IntegrityError:
|
||||
log.exception("Exception during ssh key saving")
|
||||
h.flash(_('An error occurred during ssh key saving: {}').format(
|
||||
'Such key already exists, please use a different one'),
|
||||
category='error')
|
||||
except Exception as e:
|
||||
log.exception("Exception during ssh key saving")
|
||||
h.flash(_('An error occurred during ssh key saving: {}').format(e),
|
||||
category='error')
|
||||
|
||||
return HTTPFound(
|
||||
h.route_path('edit_user_ssh_keys', user_id=user_id))
|
||||
|
||||
@LoginRequired()
|
||||
@HasPermissionAllDecorator('hg.admin')
|
||||
@CSRFRequired()
|
||||
@view_config(
|
||||
route_name='edit_user_ssh_keys_delete', request_method='POST')
|
||||
def ssh_keys_delete(self):
|
||||
_ = self.request.translate
|
||||
c = self.load_default_context()
|
||||
|
||||
user_id = self.request.matchdict.get('user_id')
|
||||
c.user = User.get_or_404(user_id)
|
||||
self._redirect_for_default_user(c.user.username)
|
||||
user_data = c.user.get_api_data()
|
||||
|
||||
del_ssh_key = self.request.POST.get('del_ssh_key')
|
||||
|
||||
if del_ssh_key:
|
||||
ssh_key = UserSshKeys.get_or_404(del_ssh_key)
|
||||
ssh_key_data = ssh_key.get_api_data()
|
||||
|
||||
SshKeyModel().delete(del_ssh_key, c.user.user_id)
|
||||
audit_logger.store_web(
|
||||
'user.edit.ssh_key.delete', action_data={
|
||||
'data': {'ssh_key': ssh_key_data, 'user': user_data}},
|
||||
user=self._rhodecode_user,)
|
||||
Session().commit()
|
||||
h.flash(_("Ssh key successfully deleted"), category='success')
|
||||
|
||||
return HTTPFound(h.route_path('edit_user_ssh_keys', user_id=user_id))
|
||||
|
||||
@LoginRequired()
|
||||
@HasPermissionAllDecorator('hg.admin')
|
||||
@view_config(
|
||||
|
|
|
|||
|
|
@ -46,6 +46,8 @@ ACTIONS_V1 = {
|
|||
'user.edit.token.delete': {'token': {}, 'user': {}},
|
||||
'user.edit.email.add': {'email': ''},
|
||||
'user.edit.email.delete': {'email': ''},
|
||||
'user.edit.ssh_key.add': {'token': {}, 'user': {}},
|
||||
'user.edit.ssh_key.delete': {'token': {}, 'user': {}},
|
||||
'user.edit.password_reset.enabled': {},
|
||||
'user.edit.password_reset.disabled': {},
|
||||
|
||||
|
|
|
|||
4172
rhodecode/lib/dbmigrate/schema/db_4_9_0_0.py
Normal file
4172
rhodecode/lib/dbmigrate/schema/db_4_9_0_0.py
Normal file
File diff suppressed because it is too large
Load diff
29
rhodecode/lib/dbmigrate/versions/080_version_4_9_0.py
Normal file
29
rhodecode/lib/dbmigrate/versions/080_version_4_9_0.py
Normal file
|
|
@ -0,0 +1,29 @@
|
|||
import logging
|
||||
|
||||
from sqlalchemy import *
|
||||
from rhodecode.model import meta
|
||||
from rhodecode.lib.dbmigrate.versions import _reset_base, notify
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def upgrade(migrate_engine):
|
||||
"""
|
||||
Upgrade operations go here.
|
||||
Don't create your own engine; bind migrate_engine to your metadata
|
||||
"""
|
||||
_reset_base(migrate_engine)
|
||||
from rhodecode.lib.dbmigrate.schema import db_4_9_0_0 as db
|
||||
|
||||
db.UserSshKeys.__table__.create()
|
||||
|
||||
fixups(db, meta.Session)
|
||||
|
||||
|
||||
def downgrade(migrate_engine):
|
||||
meta = MetaData()
|
||||
meta.bind = migrate_engine
|
||||
|
||||
|
||||
def fixups(models, _SESSION):
|
||||
pass
|
||||
|
|
@ -545,6 +545,8 @@ class User(Base, BaseModel):
|
|||
user_emails = relationship('UserEmailMap', cascade='all')
|
||||
user_ip_map = relationship('UserIpMap', cascade='all')
|
||||
user_auth_tokens = relationship('UserApiKeys', cascade='all')
|
||||
user_ssh_keys = relationship('UserSshKeys', cascade='all')
|
||||
|
||||
# gists
|
||||
user_gists = relationship('Gist', cascade='all')
|
||||
# user pull requests
|
||||
|
|
@ -1143,6 +1145,43 @@ class UserIpMap(Base, BaseModel):
|
|||
self.user_id, self.ip_addr)
|
||||
|
||||
|
||||
class UserSshKeys(Base, BaseModel):
|
||||
__tablename__ = 'user_ssh_keys'
|
||||
__table_args__ = (
|
||||
Index('usk_ssh_key_fingerprint_idx', 'ssh_key_fingerprint'),
|
||||
|
||||
UniqueConstraint('ssh_key_fingerprint'),
|
||||
|
||||
{'extend_existing': True, 'mysql_engine': 'InnoDB',
|
||||
'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
|
||||
)
|
||||
__mapper_args__ = {}
|
||||
|
||||
ssh_key_id = Column('ssh_key_id', Integer(), nullable=False, unique=True, default=None, primary_key=True)
|
||||
ssh_key_data = Column('ssh_key_data', String(10240), nullable=False, unique=None, default=None)
|
||||
ssh_key_fingerprint = Column('ssh_key_fingerprint', String(1024), nullable=False, unique=None, default=None)
|
||||
|
||||
description = Column('description', UnicodeText().with_variant(UnicodeText(1024), 'mysql'))
|
||||
|
||||
created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
|
||||
accessed_on = Column('accessed_on', DateTime(timezone=False), nullable=True, default=None)
|
||||
user_id = Column('user_id', Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
|
||||
|
||||
user = relationship('User', lazy='joined')
|
||||
|
||||
def __json__(self):
|
||||
data = {
|
||||
'ssh_fingerprint': self.ssh_key_fingerprint,
|
||||
'description': self.description,
|
||||
'created_on': self.created_on
|
||||
}
|
||||
return data
|
||||
|
||||
def get_api_data(self):
|
||||
data = self.__json__()
|
||||
return data
|
||||
|
||||
|
||||
class UserLog(Base, BaseModel):
|
||||
__tablename__ = 'user_logs'
|
||||
__table_args__ = (
|
||||
|
|
|
|||
123
rhodecode/model/ssh_key.py
Normal file
123
rhodecode/model/ssh_key.py
Normal file
|
|
@ -0,0 +1,123 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
|
||||
# Copyright (C) 2013-2017 RhodeCode GmbH
|
||||
#
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU Affero General Public License, version 3
|
||||
# (only), as published by the Free Software Foundation.
|
||||
#
|
||||
# This program is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# GNU General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU Affero General Public License
|
||||
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
#
|
||||
# This program is dual-licensed. If you wish to learn more about the
|
||||
# RhodeCode Enterprise Edition, including its added features, Support services,
|
||||
# and proprietary license terms, please see https://rhodecode.com/licenses/
|
||||
|
||||
import logging
|
||||
import traceback
|
||||
|
||||
import sshpubkeys
|
||||
import sshpubkeys.exceptions
|
||||
|
||||
from rhodecode.model import BaseModel
|
||||
from rhodecode.model.db import UserSshKeys
|
||||
from rhodecode.model.meta import Session
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class SshKeyModel(BaseModel):
|
||||
cls = UserSshKeys
|
||||
|
||||
def parse_key(self, key_data):
|
||||
"""
|
||||
print(ssh.bits) # 768
|
||||
print(ssh.hash_md5()) # 56:84:1e:90:08:3b:60:c7:29:70:5f:5e:25:a6:3b:86
|
||||
print(ssh.hash_sha256()) # SHA256:xk3IEJIdIoR9MmSRXTP98rjDdZocmXJje/28ohMQEwM
|
||||
print(ssh.hash_sha512()) # SHA512:1C3lNBhjpDVQe39hnyy+xvlZYU3IPwzqK1rVneGavy6O3/ebjEQSFvmeWoyMTplIanmUK1hmr9nA8Skmj516HA
|
||||
print(ssh.comment) # ojar@ojar-laptop
|
||||
print(ssh.options_raw) # None (string of optional options at the beginning of public key)
|
||||
print(ssh.options) # None (options as a dictionary, parsed and validated)
|
||||
|
||||
:param key_data:
|
||||
:return:
|
||||
"""
|
||||
ssh = sshpubkeys.SSHKey(strict_mode=True)
|
||||
try:
|
||||
ssh.parse(key_data)
|
||||
return ssh
|
||||
except sshpubkeys.exceptions.InvalidKeyException as err:
|
||||
log.error("Invalid key: %s", err)
|
||||
raise
|
||||
except NotImplementedError as err:
|
||||
log.error("Invalid key type: %s", err)
|
||||
raise
|
||||
except Exception as err:
|
||||
log.error("Key Parse error: %s", err)
|
||||
raise
|
||||
|
||||
def generate_keypair(self, comment=None):
|
||||
from Crypto.PublicKey import RSA
|
||||
|
||||
key = RSA.generate(2048)
|
||||
private = key.exportKey('PEM')
|
||||
|
||||
pubkey = key.publickey()
|
||||
public = pubkey.exportKey('OpenSSH')
|
||||
if comment:
|
||||
public = public + " " + comment
|
||||
return private, public
|
||||
|
||||
def create(self, user, fingerprint, key_data, description):
|
||||
"""
|
||||
"""
|
||||
user = self._get_user(user)
|
||||
|
||||
new_ssh_key = UserSshKeys()
|
||||
new_ssh_key.ssh_key_fingerprint = fingerprint
|
||||
new_ssh_key.ssh_key_data = key_data
|
||||
new_ssh_key.user_id = user.user_id
|
||||
new_ssh_key.description = description
|
||||
|
||||
Session().add(new_ssh_key)
|
||||
|
||||
return new_ssh_key
|
||||
|
||||
def delete(self, ssh_key_id, user=None):
|
||||
"""
|
||||
Deletes given api_key, if user is set it also filters the object for
|
||||
deletion by given user.
|
||||
"""
|
||||
ssh_key = UserSshKeys.query().filter(
|
||||
UserSshKeys.ssh_key_id == ssh_key_id)
|
||||
|
||||
if user:
|
||||
user = self._get_user(user)
|
||||
ssh_key = ssh_key.filter(UserSshKeys.user_id == user.user_id)
|
||||
ssh_key = ssh_key.scalar()
|
||||
|
||||
if ssh_key:
|
||||
try:
|
||||
Session().delete(ssh_key)
|
||||
except Exception:
|
||||
log.error(traceback.format_exc())
|
||||
raise
|
||||
|
||||
def get_ssh_keys(self, user):
|
||||
user = self._get_user(user)
|
||||
user_ssh_keys = UserSshKeys.query()\
|
||||
.filter(UserSshKeys.user_id == user.user_id)
|
||||
user_ssh_keys = user_ssh_keys.order_by(UserSshKeys.ssh_key_id)
|
||||
return user_ssh_keys
|
||||
|
||||
def get_ssh_key_by_fingerprint(self, ssh_key_fingerprint):
|
||||
user_ssh_key = UserSshKeys.query()\
|
||||
.filter(UserSshKeys.ssh_key_fingerprint == ssh_key_fingerprint)\
|
||||
.first()
|
||||
|
||||
return user_ssh_key
|
||||
|
|
@ -62,6 +62,10 @@ function registerRCRoutes() {
|
|||
pyroutes.register('edit_user_auth_tokens', '/_admin/users/%(user_id)s/edit/auth_tokens', ['user_id']);
|
||||
pyroutes.register('edit_user_auth_tokens_add', '/_admin/users/%(user_id)s/edit/auth_tokens/new', ['user_id']);
|
||||
pyroutes.register('edit_user_auth_tokens_delete', '/_admin/users/%(user_id)s/edit/auth_tokens/delete', ['user_id']);
|
||||
pyroutes.register('edit_user_ssh_keys', '/_admin/users/%(user_id)s/edit/ssh_keys', ['user_id']);
|
||||
pyroutes.register('edit_user_ssh_keys_generate_keypair', '/_admin/users/%(user_id)s/edit/ssh_keys/generate', ['user_id']);
|
||||
pyroutes.register('edit_user_ssh_keys_add', '/_admin/users/%(user_id)s/edit/ssh_keys/new', ['user_id']);
|
||||
pyroutes.register('edit_user_ssh_keys_delete', '/_admin/users/%(user_id)s/edit/ssh_keys/delete', ['user_id']);
|
||||
pyroutes.register('edit_user_emails', '/_admin/users/%(user_id)s/edit/emails', ['user_id']);
|
||||
pyroutes.register('edit_user_emails_add', '/_admin/users/%(user_id)s/edit/emails/new', ['user_id']);
|
||||
pyroutes.register('edit_user_emails_delete', '/_admin/users/%(user_id)s/edit/emails/delete', ['user_id']);
|
||||
|
|
|
|||
|
|
@ -37,6 +37,7 @@
|
|||
<ul class="nav nav-pills nav-stacked">
|
||||
<li class="${'active' if c.active=='profile' else ''}"><a href="${h.url('edit_user', user_id=c.user.user_id)}">${_('User Profile')}</a></li>
|
||||
<li class="${'active' if c.active=='auth_tokens' else ''}"><a href="${h.route_path('edit_user_auth_tokens', user_id=c.user.user_id)}">${_('Auth tokens')}</a></li>
|
||||
<li class="${'active' if c.active in ['ssh_keys','ssh_keys_generate'] else ''}"><a href="${h.route_path('edit_user_ssh_keys', user_id=c.user.user_id)}">${_('SSH Keys')}</a></li>
|
||||
<li class="${'active' if c.active=='advanced' else ''}"><a href="${h.url('edit_user_advanced', user_id=c.user.user_id)}">${_('Advanced')}</a></li>
|
||||
<li class="${'active' if c.active=='global_perms' else ''}"><a href="${h.url('edit_user_global_perms', user_id=c.user.user_id)}">${_('Global permissions')}</a></li>
|
||||
<li class="${'active' if c.active=='perms_summary' else ''}"><a href="${h.url('edit_user_perms_summary', user_id=c.user.user_id)}">${_('Permissions summary')}</a></li>
|
||||
|
|
|
|||
78
rhodecode/templates/admin/users/user_edit_ssh_keys.mako
Normal file
78
rhodecode/templates/admin/users/user_edit_ssh_keys.mako
Normal file
|
|
@ -0,0 +1,78 @@
|
|||
<div class="panel panel-default">
|
||||
<div class="panel-heading">
|
||||
<h3 class="panel-title">${_('SSH Keys')}</h3>
|
||||
</div>
|
||||
<div class="panel-body">
|
||||
<div class="sshkeys_wrap">
|
||||
<table class="rctable ssh_keys">
|
||||
<tr>
|
||||
<th>${_('Fingerprint')}</th>
|
||||
<th>${_('Description')}</th>
|
||||
<th>${_('Created')}</th>
|
||||
<th>${_('Action')}</th>
|
||||
</tr>
|
||||
%if c.user_ssh_keys:
|
||||
%for ssh_key in c.user_ssh_keys:
|
||||
<tr class="">
|
||||
<td class="">
|
||||
<code>${ssh_key.ssh_key_fingerprint}</code>
|
||||
</td>
|
||||
<td class="td-wrap">${ssh_key.description}</td>
|
||||
<td class="td-tags">${h.format_date(ssh_key.created_on)}</td>
|
||||
|
||||
<td class="td-action">
|
||||
${h.secure_form(h.route_path('edit_user_ssh_keys_delete', user_id=c.user.user_id), method='POST', request=request)}
|
||||
${h.hidden('del_ssh_key', ssh_key.ssh_key_id)}
|
||||
<button class="btn btn-link btn-danger" type="submit"
|
||||
onclick="return confirm('${_('Confirm to remove ssh key %s') % ssh_key.ssh_key_fingerprint}');">
|
||||
${_('Delete')}
|
||||
</button>
|
||||
${h.end_form()}
|
||||
</td>
|
||||
</tr>
|
||||
%endfor
|
||||
%else:
|
||||
<tr><td><div class="ip">${_('No additional ssh keys specified')}</div></td></tr>
|
||||
%endif
|
||||
</table>
|
||||
</div>
|
||||
|
||||
<div class="user_ssh_keys">
|
||||
${h.secure_form(h.route_path('edit_user_ssh_keys_add', user_id=c.user.user_id), method='POST', request=request)}
|
||||
<div class="form form-vertical">
|
||||
<!-- fields -->
|
||||
<div class="fields">
|
||||
<div class="field">
|
||||
<div class="label">
|
||||
<label for="new_email">${_('New ssh key')}:</label>
|
||||
</div>
|
||||
<div class="input">
|
||||
${h.text('description', class_='medium', placeholder=_('Description'))}
|
||||
<a href="${h.route_path('edit_user_ssh_keys_generate_keypair', user_id=c.user.user_id)}">${_('Generate random RSA key')}</a>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="field">
|
||||
<div class="textarea text-area editor">
|
||||
${h.textarea('key_data',c.default_key, size=30, placeholder=_("Public key, begins with 'ssh-rsa', 'ssh-dss', 'ssh-ed25519', 'ecdsa-sha2-nistp256', 'ecdsa-sha2-nistp384', or 'ecdsa-sha2-nistp521'"))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="buttons">
|
||||
${h.submit('save',_('Add'),class_="btn")}
|
||||
${h.reset('reset',_('Reset'),class_="btn")}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
${h.end_form()}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
|
||||
$(document).ready(function(){
|
||||
|
||||
|
||||
});
|
||||
</script>
|
||||
|
|
@ -0,0 +1,45 @@
|
|||
<div class="panel panel-default">
|
||||
<div class="panel-heading">
|
||||
<h3 class="panel-title">${_('New SSH Key generated')}</h3>
|
||||
</div>
|
||||
<div class="panel-body">
|
||||
<p>
|
||||
${_('Below is a 2048 bit generated SSH RSA key. You can use it to access RhodeCode via the SSH wrapper.')}
|
||||
</p>
|
||||
<h4>${_('Private key')}</h4>
|
||||
<pre>
|
||||
# Save the content as
|
||||
~/.ssh/id_rsa_rhodecode_access_priv.key
|
||||
# Change permissions
|
||||
chmod 0600 ~/.ssh/id_rsa_rhodecode_access_priv.key
|
||||
</pre>
|
||||
|
||||
<div>
|
||||
<textarea style="height: 300px">${c.private}</textarea>
|
||||
</div>
|
||||
<br/>
|
||||
|
||||
|
||||
<h4>${_('Public key')}</h4>
|
||||
<pre>
|
||||
# Save the content as
|
||||
~/.ssh/id_rsa_rhodecode_access_pub.key
|
||||
# Change permissions
|
||||
chmod 0600 ~/.ssh/id_rsa_rhodecode_access_pub.key
|
||||
</pre>
|
||||
|
||||
<input type="text" value="${c.public}" class="large text" size="100"/>
|
||||
<p>
|
||||
<a href="${h.route_path('edit_user_ssh_keys', user_id=c.user.user_id, _query=dict(default_key=c.public))}">${_('Add this generated key')}</a>
|
||||
</p>
|
||||
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
|
||||
$(document).ready(function(){
|
||||
|
||||
|
||||
});
|
||||
</script>
|
||||
1
setup.py
1
setup.py
|
|
@ -134,6 +134,7 @@ install_requirements = [
|
|||
'repoze.lru',
|
||||
'requests',
|
||||
'simplejson',
|
||||
'sshpubkeys',
|
||||
'subprocess32',
|
||||
'waitress',
|
||||
'zope.cachedescriptors',
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue