def test_generate_unsigned(self) -> None: token = generate_jwt_token(generate_session_id(), signed=False) assert '.' not in token assert 123 == len(token) assert "session_id" in json.loads(_b64_to_utf8(token)) another_token = generate_jwt_token(generate_session_id(), signed=False) assert '.' not in another_token assert 123 == len(another_token) assert "session_id" in json.loads(_b64_to_utf8(another_token)) assert token != another_token
def test_generate_unsigned(self) -> None: token = generate_jwt_token(generate_session_id(), signed=False) assert '.' not in token assert 123 == len(token) assert "session_id" in json.loads(_base64_decode(token, encoding='utf-8')) another_token = generate_jwt_token(generate_session_id(), signed=False) assert '.' not in another_token assert 123 == len(another_token) assert "session_id" in json.loads(_base64_decode(another_token, encoding='utf-8')) assert token != another_token
def getDataLoaderModule(request, editMode=True): template = None endPoint = 'studio-pipeline/dataloader/' # on récupère l'url de l'application du Board du serveur Bokeh bokeh_server_url = "%s" % (request.build_absolute_uri( location='/')) + endPoint session_id = request.COOKIES.get('session_id') if session_id == None: session_id = token.generate_session_id() headers = request.headers headers = dict(headers) if headers else {} headers['session'] = request.COOKIES.get('crsftoken') server_script = server_session(None, session_id=session_id, url=bokeh_server_url, headers=headers) # Création du context pour le template Jinja context = {"dataloader": server_script} template = render(request, 'data/data_loader.html', context) return template
def get_event_plot(): """ Connects the frontend to the Bokeh Server by pulling and returning a sesssion which generates Bokeh plots displaying all the events for a given run Returns: str: A script tag that embeds content from a specific existing session on a Bokeh server. """ if request.is_json: token = request.args.get("token") req = request.get_json() run_id = None user = None try: run_id = req["run_id"] user = req["user"] except: return make_response(jsonify({"error": "Bad Request"}), 400) if not authenticate(user, token): return make_response(jsonify({"error": "Unauthorized API request"}), 403) print("RUN ID IS: ", run_id) threading.Thread(target=cache_events_request, args=[run_id]).start() session_id = generate_session_id() my_sessions.insert_one({session_id: run_id}) script = server_session(url=BOKEH_SERVER_URL, session_id=session_id) # use the script in the rendered page return script else: return make_response(jsonify({"error": "Bad Request"}), 400)
def test_payload_unsigned(self): token = generate_jwt_token(generate_session_id(), signed=False, extra_payload=dict(foo=10)) assert '.' not in token payload = json.loads(_base64_decode(token, encoding='utf-8')) assert payload['foo'] == 10
async def get_session(self): token = self.get_argument("bokeh-token", default=None) session_id = self.get_argument("bokeh-session-id", default=None) if 'Bokeh-Session-Id' in self.request.headers: if session_id is not None: log.debug("Server received session ID in request argument and header, expected only one") raise HTTPError(status_code=403, reason="session ID was provided as an argument and header") session_id = self.request.headers.get('Bokeh-Session-Id') if token is not None: if session_id is not None: log.debug("Server received both token and session ID, expected only one") raise HTTPError(status_code=403, reason="Both token and session ID were provided") session_id = get_session_id(token) elif session_id is None: if self.application.generate_session_ids: session_id = generate_session_id(secret_key=self.application.secret_key, signed=self.application.sign_sessions) else: log.debug("Server configured not to generate session IDs and none was provided") raise HTTPError(status_code=403, reason="No bokeh-session-id provided") if token is None: if self.application.include_headers is None: excluded_headers = (self.application.exclude_headers or []) allowed_headers = [header for header in self.request.headers if header not in excluded_headers] else: allowed_headers = self.application.include_headers headers = {k: v for k, v in self.request.headers.items() if k in allowed_headers} if self.application.include_cookies is None: excluded_cookies = (self.application.exclude_cookies or []) allowed_cookies = [cookie for cookie in self.request.cookies if cookie not in excluded_cookies] else: allowed_cookies = self.application.include_cookies cookies = {k: v.value for k, v in self.request.cookies.items() if k in allowed_cookies} payload = {'headers': headers, 'cookies': cookies} payload.update(self.application_context.application.process_request(self.request)) token = generate_jwt_token(session_id, secret_key=self.application.secret_key, signed=self.application.sign_sessions, expiration=self.application.session_token_expiration, extra_payload=payload) if not check_token_signature(token, secret_key=self.application.secret_key, signed=self.application.sign_sessions): log.error("Session id had invalid signature: %r", session_id) raise HTTPError(status_code=403, reason="Invalid token or session ID") session = await self.application_context.create_session_if_needed(session_id, self.request, token) return session
def test_payload_with_zlib_key(self): token = generate_jwt_token(generate_session_id(), signed=False, extra_payload=dict([(_TOKEN_ZLIB_KEY, 10)])) assert '.' not in token assert _TOKEN_ZLIB_KEY in json.loads(_b64_to_utf8(token)) payload = get_token_payload(token) assert _TOKEN_ZLIB_KEY in payload assert payload[_TOKEN_ZLIB_KEY] == 10
def test_payload_unsigned(self): token = generate_jwt_token(generate_session_id(), signed=False, extra_payload=dict(foo=10)) assert '.' not in token assert _TOKEN_ZLIB_KEY in json.loads(_b64_to_utf8(token)) payload = get_token_payload(token) assert _TOKEN_ZLIB_KEY not in payload assert payload['foo'] == 10
def test_generate_signed(self) -> None: session_id = generate_session_id(signed=True, secret_key="abc") token = generate_jwt_token(session_id, signed=True, secret_key="abc") assert '.' in token decoded = json.loads(_base64_decode(token.split('.')[0], encoding='utf-8')) assert "session_id" in decoded assert decoded['session_id'] == session_id assert check_token_signature(token, secret_key="abc", signed=True) assert not check_token_signature(token, secret_key="qrs", signed=True)
def test_payload_signed(self): session_id = generate_session_id(signed=True, secret_key="abc") token = generate_jwt_token(session_id, signed=True, secret_key="abc", extra_payload=dict(foo=10)) assert '.' in token decoded = json.loads(_base64_decode(token.split('.')[0], encoding='utf-8')) assert 'session_id' in decoded session_id = get_session_id(token) assert check_token_signature(token, secret_key="abc", signed=True) assert not check_token_signature(token, secret_key="qrs", signed=True) assert decoded['foo'] == 10
def wik(): """App route for wik application.""" if 'auth' in session.keys(): if session['auth'] == 1: script1 = server_session(url=f'{BOKEH_URL}', session_id=generate_session_id()) return render_template("app.html", script1=script1, relative_urls=True) return redirect(f"{WIK_URL}/login")
async def _get_session(self) -> ServerSession: session_id = self.arguments.get('bokeh-session-id', generate_session_id(secret_key=None, signed=False)) payload = {'headers': {k.decode('utf-8'): v.decode('utf-8') for k, v in self.request.headers}, 'cookies': dict(self.request.cookies)} token = generate_jwt_token(session_id, secret_key=None, signed=False, expiration=300, extra_payload=payload) session = await self.application_context.create_session_if_needed(session_id, self.request, token) return session
def get_context_data(self, *args, **kwargs): context = super().get_context_data(**kwargs) helper_image = None app_ID = self.kwargs['app_ID'] if app_ID == 'flood_msmt': header_info = 'Flood Measurement Explorer' elif app_ID == 'ndimensions': header_info = 'N-Dimensional Space' elif app_ID == 'sliders': header_info = 'Bokeh Demo App' elif app_ID == 'recognition_heuristic': header_info = 'Recognition Heuristic Visualization' helper_image = 'static/gigenrenzer_fn.jpg' try: if settings.DEBUG: bk_url = 'http://127.0.0.1:5006/' + app_ID bk_script = server_session(url=bk_url, relative_urls=False, session_id=generate_session_id(),) else: bk_script = server_session(url='/bokeh/' + app_ID, relative_urls=True, resources=None, session_id=generate_session_id(), ) context['bk_script'] = bk_script context['header_info'] = header_info context['helper_image'] = helper_image except Exception as e: msg = "Uh oh. Richard, whatja do??: {}".format(e) logger.error(msg) return context
def test_payload_signed(self): session_id = generate_session_id(signed=True, secret_key="abc") token = generate_jwt_token(session_id, signed=True, secret_key="abc", extra_payload=dict(foo=10)) assert '.' in token decoded = json.loads(_b64_to_utf8(token.split('.')[0])) assert _TOKEN_ZLIB_KEY in decoded assert 'session_id' in decoded session_id = get_session_id(token) assert check_token_signature(token, secret_key="abc", signed=True) assert not check_token_signature(token, secret_key="qrs", signed=True) payload = get_token_payload(token) assert _TOKEN_ZLIB_KEY not in payload assert payload['foo'] == 10
def getBoardVizElementFromSlug(request, boardSlug, vizSlug): bokeh_server_url = "%s" % (request.build_absolute_uri( location='/')) + 'board/' + boardSlug + '/vizentity/' + vizSlug vizElement = VizEntity.objects.get(slug=vizSlug) headers = request.headers headers = dict(headers) if headers else {} headers['viz-element-id'] = vizElement.id session_id = token.generate_session_id() server_script = server_session(None, session_id=session_id, url=bokeh_server_url, headers=headers) context = { "script": server_script, "vizName": vizElement.title, } response = render(request, 'board/board_edit.html', context) response.set_cookie('session_id', session_id, 'SameSite', 'Lax') return response
def test_string_encoding_does_not_affect_session_id_check(self) -> None: # originates from #6653 session_id = generate_session_id(signed=True, secret_key="abc") token = generate_jwt_token(session_id, signed=True, secret_key="abc") assert check_token_signature(token, secret_key="abc", signed=True)
def test_check_signature_of_unsigned(self) -> None: # secret shouldn't be used token = generate_jwt_token(generate_session_id(), signed=False, secret_key="abc") assert not check_token_signature(token, secret_key="abc", signed=True)
def test_payload_error(self): session_id = generate_session_id() with pytest.raises(RuntimeError): generate_jwt_token(session_id, extra_payload=dict(session_id=10))
def getBoardAppFromBoardSlug(*args, **kwargs): params = kwargs.get('params') slug = kwargs.get('slug') message = kwargs.get('message') request = kwargs.get('request') base_uri = request.build_absolute_uri(location='/') edit = params['editMode'] # on cherche l'identifiant de l'objet BoardEntity à partir du Slug board = BoardEntity.objects.get(slug=slug) targets = board.targetentity_set.all() # Création du context pour le template Jinja context = { "message": message, "boardName": board.name, "boardSlug": board.slug, "board": board, "targets": targets, "extraParams": request.GET } headers = request.headers headers = dict(headers) if headers else {} # on ajoute dans le header l'id du board (il sera utiliser par la suite dans le service de création du document Bokeh) headers['board-id'] = board.id session_id = request.COOKIES.get('session_id') if session_id == None: session_id = token.generate_session_id() headers['session'] = request.COOKIES.get('crsftoken') # On regarde si on est en mode edition #todo faire le controle des droits edit = request.GET.get('edit') # on récupère les variables du templates pour les injecter dans le template Django ## on instancie un lumenDashboard si besoin #lumenDashBord = LumenDashboard.getinstancesBySessionId(sessionId=session_id+str(board.id)) # #if lumenDashBord: # lumenDashBord = lumenDashBord.pop() #else: # lumenDashBord = LumenDashboard(board=board.id, sessionId=session_id) template = lumen.Dashboard( specification= "specYamlFile/default/nouveau_dashboard_default_config.yml" )._template template.header_background = psud_branding['header_background'] doc = template._init_doc() template_variables = doc.template_variables root = [obj for obj in doc.roots] listeOfBokehModel = [obj for obj in root if len(obj.tags) > 0] # on va chercher les composants Panels qui ont des tags définis nav = BoardController.getBokehModelByTag(listeOfBokehModel, 'nav') modal = BoardController.getBokehModelByTag(listeOfBokehModel, 'modal') header = BoardController.getBokehModelByTag(listeOfBokehModel, 'header') main = BoardController.getBokehModelByTag(listeOfBokehModel, 'main') listeOfBokehModelWithNoTags = [ obj for obj in root if len(obj.tags) == 0 ] # on va chercher les autres composants Panels qui n'ont de tags définis js_area = [ obj for obj in listeOfBokehModelWithNoTags if obj.name == 'js_area' ] busy_indicator = [ obj for obj in listeOfBokehModelWithNoTags if obj.name == 'busy_indicator' ] location = [ obj for obj in listeOfBokehModelWithNoTags if obj.name == 'location' ] # génération des scripts server_script_Dict = {} listeScriptToCreate = [('sidebar', nav), ('modal', modal), ('header', header), ('js_area', js_area), ('busy_indicator', busy_indicator), ('main', main)] for scriptName in listeScriptToCreate: model = scriptName[1] if len(model) == 0: pass else: model = model.pop() bokeh_server_url = BoardController.endPointConstructor( None, slug, scriptName[0], base_uri, **params) script = BoardController.createBokehScript( model, session_id, headers, bokeh_server_url) server_script_Dict[scriptName[0]] = script contextWithlumenDashboard = { **context, **template_variables, **server_script_Dict } if (edit == 'True'): template = render(request, 'board/board_edit.html', contextWithlumenDashboard) else: template = render(request, 'board/board_view.html', context) response = template # on set les cookies car on en aura besoin dans le service qui sera exectué par le script bokeh (qui est en passe d'être injecté dans le template) response.set_cookie('session_id', session_id) response.set_cookie('board_id', board.id) return response
def createAllContextWithScript(request, **kwargs): base_uri = request.build_absolute_uri(location='/') moduleName = kwargs.get('moduleName') serviceName = kwargs.get('serviceName') endPoint = f'{moduleName}/{serviceName}/' slug = kwargs.get('slug') template = None session_id = request.COOKIES.get('session_id') if session_id == None: session_id = token.generate_session_id() headers = request.headers headers = dict(headers) if headers else {} headers['session'] = request.COOKIES.get('crsftoken') board_id = request.COOKIES.get('board_id') board = BoardEntity.objects.get(id=board_id) lumenDashBord = LumenDashboard.getinstancesBySessionId( sessionId=session_id + board_id) if lumenDashBord: lumenDashBord = lumenDashBord.pop() else: lumenDashBord = LumenDashboard(board=board.id, sessionId=session_id) template = lumenDashBord.dashBoard._template template.header_background = psud_branding['header_background'] doc = template._init_doc() template_variables = doc.template_variables root = [obj for obj in doc.roots] listeOfBokehModel = [obj for obj in root if len(obj.tags) > 0] # on va chercher les composants Panels qui ont des tags définis nav = BoardController.getBokehModelByTag(listeOfBokehModel, 'nav').pop() header = BoardController.getBokehModelByTag(listeOfBokehModel, 'header').pop() listeOfBokehModelWithNoTags = [ obj for obj in root if len(obj.tags) == 0 ] # on va chercher les autres composants Panels qui n'ont pas de tags définis js_area = [ obj for obj in listeOfBokehModelWithNoTags if obj.name == 'js_area' ].pop() busy_indicator = [ obj for obj in listeOfBokehModelWithNoTags if obj.name == 'busy_indicator' ].pop() location = [ obj for obj in listeOfBokehModelWithNoTags if obj.name == 'location' ].pop() # génération des scripts server_script_Dict = {} listeScriptToCreate = [('sidebar', nav), ('header', header), ('js_area', js_area), ('busy_indicator', busy_indicator)] for scriptName in listeScriptToCreate: model = scriptName[1] bokeh_server_url = BoardController.endPointConstructor( None, slug, scriptName[0], base_uri, editMode=True, lumenMode=True) script = BoardController.createBokehScript(model, session_id, headers, bokeh_server_url) server_script_Dict[scriptName[0]] = script # on ajoute le script de la pipeline bokeh_server_url = "%s" % (request.build_absolute_uri( location='/')) + endPoint pipeline = server_session(None, session_id=session_id, url=bokeh_server_url, headers=headers) server_script_Dict['main'] = pipeline context = { "boardName": board.name, "boardSlug": board.slug, "board": board, "traces": TraceEntity.objects.filter(board=board), "targets": TargetEntity.objects.filter(board=board), "extraParams": request.GET } # Création du context pour le template Jinja return {**context, **template_variables, **server_script_Dict}