def post(self): """ Login """ request = self.validate_message(self.request.body, requests.AuthDesc) username = request['username'] password = request['password'] delay = random_login_delay() if delay: yield deferred_sleep(delay) using_tor2web = self.check_tor2web() try: user_id, status, role, pcn = yield login(username, password, using_tor2web) finally: yield self.uniform_answers_delay() session = GLSession(user_id, role, status) self.write({ 'session_id': session.id, 'role': session.user_role, 'user_id': session.user_id, 'session_expiration': int(session.getTime()), 'status': session.user_status, 'password_change_needed': pcn })
def post(self): """ Receipt login handler used by whistleblowers """ request = self.validate_message(self.request.body, requests.ReceiptAuthDesc) receipt = request['receipt'] delay = random_login_delay() if delay: yield deferred_sleep(delay) using_tor2web = self.check_tor2web() try: user_id = yield login_whistleblower(receipt, using_tor2web) finally: yield self.uniform_answers_delay() session = GLSession(user_id, 'whistleblower', 'Enabled') self.write({ 'session_id': session.id, 'role': session.user_role, 'user_id': session.user_id, 'session_expiration': int(session.getTime()) })
def post(self): """ Receipt login handler used by whistleblowers """ request = self.validate_message(self.request.content.read(), requests.ReceiptAuthDesc) receipt = request['receipt'] delay = random_login_delay() if delay: yield deferred_sleep(delay) user_id = yield login_whistleblower(receipt, self.request.client_using_tor) GLSessions.revoke_all_sessions(user_id) session = GLSession(user_id, 'whistleblower', 'Enabled') returnValue({ 'session_id': session.id, 'role': session.user_role, 'user_id': session.user_id, 'session_expiration': int(session.getTime()) })
def post(self): """ Login """ request = self.validate_message(self.request.content.read(), requests.AuthDesc) username = request['username'] password = request['password'] user_id, status, role, pcn = yield login(username, password, self.request.client_using_tor) # Revoke all other sessions for the newly authenticated user GLSessions.revoke_all_sessions(user_id) session = GLSession(user_id, role, status) returnValue({ 'session_id': session.id, 'role': session.user_role, 'user_id': session.user_id, 'session_expiration': int(session.getTime()), 'status': session.user_status, 'password_change_needed': pcn })
def test_successful_session_update_on_auth_request(self): session = GLSession('admin', 'admin', 'enabled') date1 = session.getTime() self.test_reactor.pump([1] * FUTURE) handler = self.request({}, headers={'X-Session': session.id}) yield handler.get_authenticated() date2 = GLSessions.get(session.id).getTime() self.assertEqual(date1 + FUTURE, date2)
def test_session_management_sched(self): GLSession('admin', 'admin', 'enabled') # 1! GLSession('admin', 'admin', 'enabled') # 2! GLSession('admin', 'admin', 'enabled') # 3! self.assertEqual(len(GLSessions), 3) self.test_reactor.pump([1] * (GLSettings.authentication_lifetime - 1)) self.assertEqual(len(GLSessions), 3) self.test_reactor.advance(1) self.assertEqual(len(GLSessions), 0) yield session_management_sched.SessionManagementSchedule().run()
def db_refresh_memory_variables(store): """ This routine loads in memory few variables of node and notification tables that are subject to high usage. """ node_ro = ObjectDict(models.config.NodeFactory(store).admin_export()) GLSettings.memory_copy = node_ro GLSettings.memory_copy.accept_tor2web_access = { 'admin': node_ro.tor2web_admin, 'custodian': node_ro.tor2web_custodian, 'whistleblower': node_ro.tor2web_whistleblower, 'receiver': node_ro.tor2web_receiver } enabled_langs = models.l10n.EnabledLanguage.list(store) GLSettings.memory_copy.languages_enabled = enabled_langs notif_fact = models.config.NotificationFactory(store) notif_ro = ObjectDict(notif_fact.admin_export()) GLSettings.memory_copy.notif = notif_ro if GLSettings.developer_name: GLSettings.memory_copy.notif.source_name = GLSettings.developer_name db_refresh_exception_delivery_list(store) GLSettings.memory_copy.private = ObjectDict(models.config.PrivateFactory(store).mem_copy_export()) if GLSettings.memory_copy.private.admin_api_token_digest: api_id = store.find(models.User.id, models.User.role==u'admin').order_by(models.User.creation_date).first() if api_id is not None: GLSettings.appstate.api_token_session = GLSession(api_id, 'admin', 'enabled')
def request(self, jbody=None, user_id=None, role=None, headers=None, body='', path=None, remote_ip='0.0.0.0', method='MOCK', handler_cls=None, attached_file={}, kwargs={}): """ Constructs a handler for preforming mock requests using the bag of params described below. Args: jbody: The body of the request as a dict (it will be automatically converted to string) body: The body of the request as a string user_id: when simulating authentication the session should be bound to a certain user_id. role: when simulating authentication the session should be bound to a certain role. method: HTTP method, e.g. "GET" or "POST" headers: Dict of headers to pass on the request remote_ip: If a particular remote_ip should be set. handler_cls: The type of handler that will respond to the request. If this is not set self._handler is used. attached_file: A dict to place in the request.args.files obj """ if jbody and not body: body = json.dumps(jbody) elif body and jbody: raise ValueError('jbody and body in conflict') if handler_cls is None: handler_cls = self._handler request = DummyRequest(['']) def getResponseBody(): return ''.join(request.written) request.path = '' request.code = 200 request.language = 'en' request.client_ip = '127.0.0.1' request.client_proto = 'https' request.client_using_tor = False request.getResponseBody = getResponseBody request.client = IPv4Address('TCP', '1.2.3.4', 12345) request.args = {} if attached_file is not None: request.args = {'file': [attached_file]} if headers is not None: for k, v in headers.iteritems(): request.requestHeaders.setRawHeaders(bytes(k), [bytes(v)]) request.headers = request.getAllHeaders() from globaleaks.rest import api x = api.APIResourceWrapper() x.preprocess(request) if path is not None: if not path.startswith('/'): raise ValueError('Must pass a valid url path') request.path = path class fakeBody(object): def read(self): return body def close(self): pass request.content = fakeBody() from globaleaks.rest.api import decorate_method if not getattr(handler_cls, 'decorated', False): for method in ['get', 'post', 'put', 'delete']: if getattr(handler_cls, method, None) is not None: decorate_method(handler_cls, method) handler_cls.decorated = True handler = handler_cls(request, **kwargs) if user_id is None and role is not None: if role == 'admin': user_id = self.dummyAdminUser['id'] elif role == 'receiver': user_id = self.dummyReceiverUser_1['id'] elif role == 'custodian': user_id = self.dummyCustodianUser['id'] if role is not None: session = GLSession(user_id, role, 'enabled') handler.request.headers['x-session'] = session.id return handler
def request(self, jbody=None, user_id=None, role=None, headers=None, body='', remote_ip='0.0.0.0', method='MOCK', kwargs={}): """ Function userful for performing mock requests. Args: jbody: The body of the request as a dict (it will be automatically converted to string) body: The body of the request as a string user_id: when simulating authentication the session should be bound to a certain user_id. role: when simulating authentication the session should be bound to a certain role. method: HTTP method, e.g. "GET" or "POST" headers: (dict or :class:`cyclone.httputil.HTTPHeaders` instance) HTTP headers to pass on the request remote_ip: If a particular remote_ip should be set. """ if jbody and not body: body = json.dumps(jbody) elif body and jbody: raise ValueError('jbody and body in conflict') application = Application([]) tr = proto_helpers.StringTransport() connection = GLHTTPConnection() connection.factory = application connection.makeConnection(tr) request = httpserver.HTTPRequest(uri='mock', method=method, headers=headers, body=body, remote_ip=remote_ip, connection=connection) handler = self._handler(application, request, **kwargs) if user_id is None and role is not None: if role == 'admin': user_id = self.dummyAdminUser['id'] elif role == 'receiver': user_id = self.dummyReceiverUser_1['id'] elif role == 'custodian': user_id = self.dummyCustodianUser['id'] if role is not None: session = GLSession(user_id, role, 'enabled') handler.request.headers['X-Session'] = session.id return handler
def request(self, jbody=None, user_id=None, role=None, headers=None, body='', remote_ip='0.0.0.0', method='MOCK', attached_file={}, kwargs={}): """ Function userful for performing mock requests. Args: jbody: The body of the request as a dict (it will be automatically converted to string) body: The body of the request as a string user_id: when simulating authentication the session should be bound to a certain user_id. role: when simulating authentication the session should be bound to a certain role. method: HTTP method, e.g. "GET" or "POST" headers: (dict or :class:`cyclone.httputil.HTTPHeaders` instance) HTTP headers to pass on the request remote_ip: If a particular remote_ip should be set. attached_file: A cyclone.httputil.HTTPFiles or a dict to place in the request.files obj """ if jbody and not body: body = json.dumps(jbody) elif body and jbody: raise ValueError('jbody and body in conflict') if attached_file is None: fake_files = {} else: fake_files = { 'file': [attached_file] } # Yes this is ugly, but it's the format application = Application([]) tr = proto_helpers.StringTransport() connection = GLHTTPConnection() connection.factory = application connection.makeConnection(tr) request = httpserver.HTTPRequest(uri='mock', method=method, headers=headers, body=body, remote_ip=remote_ip, connection=connection, files=fake_files) def mock_write(cls, response=None): if response: self.responses.append(response) self._handler.write = mock_write def mock_finish(cls): pass self._handler.finish = mock_finish handler = self._handler(application, request, **kwargs) # pylint: disable=not-callable if user_id is None and role is not None: if role == 'admin': user_id = self.dummyAdminUser['id'] elif role == 'receiver': user_id = self.dummyReceiverUser_1['id'] elif role == 'custodian': user_id = self.dummyCustodianUser['id'] if role is not None: session = GLSession(user_id, role, 'enabled') handler.request.headers['X-Session'] = session.id return handler