From b8ba5f798039a83d8c4926349564cd505fe7a5fc Mon Sep 17 00:00:00 2001 From: Florent Xicluna Date: Fri, 27 Nov 2026 00:48:56 +0100 Subject: [PATCH] feat: reuse browser session with session_id cookie Add argument session_id to Client and Client.login, and option --session-id, to reuse an authenticated Web session when password login is disabled (e.g. OAuth sign-in). The Web session of each user is cached and reused when switching user or environment. session_destroy() terminates the session of its own environment. sudo() on a browser session warns that it becomes Superuser; the Superuser session is reused, never another session. --- CHANGES.rst | 20 +++ README.rst | 11 ++ docs/index.rst | 8 ++ odooly/client.py | 88 ++++++++++-- odooly/environment.py | 110 +++++++++++---- odooly/http.py | 34 ++++- odooly/run.py | 39 +++++- tests/test_client.py | 302 +++++++++++++++++++++++++++++++++++++++++- 8 files changed, 566 insertions(+), 46 deletions(-) diff --git a/CHANGES.rst b/CHANGES.rst index 5428e46..8c8c9b9 100644 --- a/CHANGES.rst +++ b/CHANGES.rst @@ -2,6 +2,26 @@ Changelog --------- +3.0.x (unreleased) +~~~~~~~~~~~~~~~~~~ + +* Add argument ``session_id`` to :class:`Client` and :meth:`Client.login` + to reuse an authenticated browser session, with its ``session_id`` + cookie. It is useful when password login is disabled, for example with + OAuth sign-in. Command line option ``--session-id``. + +* Reuse the Webclient session of each user, when switching user or + environment, instead of authenticating again. When switching database, + the previous session is not terminated anymore. + +* :meth:`Env.session_destroy` terminates the session of its environment, + instead of the current session. + +* The Superuser environment reuses its session. When this session is + terminated, it raises an error, instead of switching another session to + Superuser. Call :meth:`Env.sudo` again. + + 3.0.6 (2026-11-18) ~~~~~~~~~~~~~~~~~~ diff --git a/README.rst b/README.rst index afa9d7e..73c41bd 100644 --- a/README.rst +++ b/README.rst @@ -87,6 +87,17 @@ Connect to the Odoo server:: ~$ odooly --env devel +When password login is disabled (e.g. OAuth sign-in), login in the browser +and reuse the value of its ``session_id`` cookie (in the browser developer +tools, under *Application > Cookies* or *Storage > Cookies*):: + + ~$ odooly --env devel --session-id 0123456789abcdef + +The browser session is shared: Odooly does not log out, unless +``env.session_destroy()`` is called. Note that ``env.sudo()`` turns +the browser session into a Superuser session, until it is terminated. + + This is a sample session:: >>> env['res.users'] diff --git a/docs/index.rst b/docs/index.rst index 739924e..aec81ae 100644 --- a/docs/index.rst +++ b/docs/index.rst @@ -9,6 +9,7 @@ Odooly - client for Odoo The Odooly library communicates with any `Odoo server`_ using the Webclient API. If an ``api_key`` is configured, it will use the JSON-2 endpoint with Odoo 19. +If a ``session_id`` is provided, it will reuse this browser session (e.g. OAuth sign-in). It can also connect through the `deprecated external RPC interface`_ (JSON-RPC). It provides both a :ref:`fully featured low-level API `, @@ -50,6 +51,13 @@ Authentication methods per Odoo version, and per API: example ``/web/webclient/version_info``. The ``/web/database/*`` endpoints are public, although they require the Master password as argument. +.. note:: As an alternative to Login, the Webclient API accepts the ``session_id`` + cookie of a browser session, with :meth:`Client.login` or the + ``--session-id`` command line option. It is useful when password login is + disabled, for example with OAuth sign-in. The session is shared: Odooly + does not log out, unless :meth:`Env.session_destroy` is called. + :meth:`Env.sudo` turns the browser session into a Superuser session. + Contents: diff --git a/odooly/client.py b/odooly/client.py index 6c11ef4..1033ae7 100644 --- a/odooly/client.py +++ b/odooly/client.py @@ -34,17 +34,20 @@ class Client: The `db` is the name of the database and the `user` should exist in the table ``res.users``. If the `password` is not provided, it will be asked on login. + + As an alternative, the `session_id` of an authenticated Webclient + session can be provided. """ _use_call_button = False _printer = None - def __init__(self, server, db=None, user=None, password=None, api_key=None): + def __init__(self, server, db=None, user=None, password=None, api_key=None, session_id=None): self._http = HTTPSession() - self._session_uid = None + self._session_uid = self._session_info = None self._set_services(server, db) self.env = Env(self) - if user: # Try to login - self.login(user, password=password, api_key=api_key, database=db) + if user or session_id: # Try to login + self.login(user, password=password, api_key=api_key, database=db, session_id=session_id) def _set_services(self, server, db): if isinstance(server, list): @@ -153,6 +156,37 @@ def dispatch_web(method, params): def __repr__(self): return f"" + def _set_session(self, session_info, session_id=None): + """Set the ``session_id`` HTTP cookie and the uid of the current session.""" + self._http.set_cookie(self._server, 'session_id', session_id) + self._session_uid = session_info and session_info['uid'] + self._session_info = session_info + + def _get_session_id(self): + """Return the ``session_id`` HTTP cookie of the current session.""" + return self._http.get_cookie(self._server, 'session_id') + + def _load_session(self, session_id): + """Attach an authenticated Webclient session, and return its info. + + The `session_id` is the value of the ``session_id`` cookie. + Return None if the session is invalid or expired. + """ + if not self.web: + return + if self._session_info and session_id == self._get_session_id(): + session_info = self._session_info + self._session_info = None + return session_info + self._http.set_cookie(self._server, 'session_id', session_id) + try: + session_info = self.web_session.get_session_info() + except ServerError: # odoo.http.SessionExpiredException + self._set_session(None) + return + self._set_session(session_info, session_id) + return session_info + def _authenticate(self, db, login, password, api_key): if api_key and not password and self.version_info >= 19.0: json2_api = Json2(self, db, api_key) @@ -165,6 +199,7 @@ def _authenticate(self, db, login, password, api_key): return info def _authenticate_session(self, db, login, password): + self._set_session(None) # Do not authenticate on the shared session info = {'uid': None} try: if db: @@ -210,20 +245,53 @@ def _authenticate_web(self, **kw): def _authenticate_system(self): __, session_info = self._request_parse('/web/become') self._session_uid = session_info.get('uid') + self._session_info = None # The session has changed if self._session_uid != 1: raise Error("Cannot become Superuser") return session_info + def _authenticate_rpc(self, db, uid, login, password): + # The password is asked by Env._check_user_password, which caches it + if not uid: + uid = self.common.login(db, login, password) + session_info = {'uid': uid} + if uid: + args = db, uid, password, 'res.users', 'context_get', () + session_info['user_context'] = self._object.execute_kw(*args) + return session_info + def _select_database(self, db_list): return db_list[0] if len(db_list) == 1 else None - def login(self, user, password=None, database=None, api_key=None): + def login(self, user, password=None, database=None, api_key=None, session_id=None): """Switch `user` and (optionally) `database`. If the `password` is not available, it will be asked. + + As an alternative, the `session_id` of an authenticated Webclient + session can be provided: it is the value of the ``session_id`` + cookie of a browser session. Use it when the password login is + disabled, for example when the user signs in with OAuth. + The session is shared with the browser: Odooly does not authenticate + again on this session, and it does not log out, unless + :meth:`Env.session_destroy` is called. Note that :meth:`Env.sudo` + turns the browser session into a Superuser session. + The `user` and the `database` are optional: if provided, they must + match the session. """ env = self.env - if not env.db_name or (database and env.db_name != database): + session_info = None + if session_id: # Reuse a Webclient session + if not (session_info := self._load_session(session_id)): + raise Error("Error: Invalid or expired session") + if database and database != session_info['db']: + self._set_session(None) + raise Error(f"Error: Session is bound to database {session_info['db']!r}") + if user and user != session_info['username']: + self._set_session(None) + raise Error(f"Error: Session is bound to user {session_info['username']!r}") + (user, database) = (session_info['username'], session_info['db']) + if not session_id and (not env.db_name or (database and env.db_name != database)): try: dbs = self.database.list() except Exception: @@ -235,9 +303,13 @@ def login(self, user, password=None, database=None, api_key=None): if dbs and database not in dbs: raise Error(f"Database {database!r} does not exist: {dbs}") if database and env.db_name != database: - if self._session_uid: - env.session_destroy() + if env.db_name and self._session_uid and not session_info: + self._set_session(None) # Do not reuse the session on another database env = Env(self, database) + if session_info: + # Saved like any other session: Env._check_user_password reuses it + auth_cache = env._cache_get('auth', dict) + auth_cache[user] = (session_info['uid'], None, session_id) try: self.env = env(user=user, password=password, api_key=api_key) except Exception: diff --git a/odooly/environment.py b/odooly/environment.py index d7b8fb7..c7429c3 100644 --- a/odooly/environment.py +++ b/odooly/environment.py @@ -97,20 +97,56 @@ def __bool__(self): def __repr__(self): return f"" + @classmethod + def _ask_password(cls, user): + return getpass(f"Password for '{color_bold(user)}': ") + + def _reuse_session(self, login, session_id, password=None): + """Attach the session `session_id`, if it is still valid for `login`.""" + info = self.client._load_session(session_id) + if info and ( + info['username'] != login or + (self.db_name and info['db'] != self.db_name) + ): + # The session has changed, e.g. with /web/become + self.client._set_session(None) + if info['username'] == SYSTEM_USER and not password: + # A browser session cannot be restored without a new sign-in + raise Error(f"Error: Session of {login!r} is now Superuser. " + "Log out with session_destroy()") + info = None + return info + def _check_user_password(self, user, password, api_key): if self.client._object and not self.db_name: raise Error('Error: Not connected') assert isinstance(user, str) and user - if user == SYSTEM_USER and self.uid and not password: - info = self.client._authenticate_system() - return info['uid'], password, info # Read from cache auth_cache = self._cache_get('auth', dict) - (uid, pwcache) = auth_cache.get(user) or (None, None) + (uid, pwcache, session_id) = auth_cache.get(user) or (None, None, None) password = password or pwcache + if session_id: + # Saved session: attach again, if it is still valid + if session_info := self._reuse_session(user, session_id, password): + auth_cache[user] = (session_info['uid'], password, session_id) + return session_info['uid'], password, session_info + if not password and user != SYSTEM_USER: + print(f"Session expired for {user!r}") + if user == SYSTEM_USER and self.uid and not password: + # Become Superuser from the session of this environment + self._ensure_session() + session_id = self.client._get_session_id() + info = self.client._authenticate_system() + if session_id: + # Cache the Superuser session, for reuse and session_destroy() + auth_cache[SYSTEM_USER] = (info['uid'], None, session_id) + (__, pw, sid) = auth_cache.get(self.user.login) or (None, None, None) + if sid == session_id and not pw: + print("Session is now Superuser. To undo: env.session_destroy()") + return info['uid'], password, info # Ask for password if not password and not api_key: - password = getpass(f"Password for '{color_bold(user)}': ") + password = self._ask_password(user) if not self.client._object: try: # Standard Web or JSON-2 authentication info = self.client._authenticate(self.db_name, user, password, api_key) @@ -120,11 +156,8 @@ def _check_user_password(self, user, password, api_key): raise Error('Error: Database does not exist') raise else: # Login through RPC Service (deprecated) - if not uid: - uid = self.client.common.login(self.db_name, user, api_key or password) - if uid: - args = self.db_name, uid, api_key or password, 'res.users', 'context_get', () - info = {'uid': uid, 'user_context': self.client._object.execute_kw(*args)} + info = self.client._authenticate_rpc(self.db_name, uid, user, api_key or password) + uid = info['uid'] if not uid: # Failed if user in auth_cache: del auth_cache[user] @@ -138,8 +171,10 @@ def _check_user_password(self, user, password, api_key): if not self.uid: # Cache the unauthenticated Env and the client self._cache_set(Env, self) - # Update credentials in cache - auth_cache[user] = uid, password + # Update credentials in cache, with the Webclient session if any + # (after JSON-2 or JSON-RPC login, the cookie can belong to another user) + session_id = self.client._get_session_id() if uid == self.client._session_uid else None + auth_cache[user] = uid, password, session_id return uid, password, info def set_api_key(self, api_key, store=True): @@ -282,7 +317,7 @@ def _identitycheck(self, result): result = None while not result: try: - password = password or getpass(f"Password for '{color_bold(self.user.login)}': ") + password = password or self._ask_password(self.user.login) except (KeyboardInterrupt, EOFError): print() raise Error("Security Control - FAILED") @@ -306,11 +341,14 @@ def _identitycheck(self, result): def _ensure_session(self): if self.uid != self.client._session_uid: - password = self._cache_get('auth')[self.user.login][1] + auth_cache = self._cache_get('auth') + (__, password, session_id) = auth_cache.get(self.user.login) or (None, None, None) if self.user.login == SYSTEM_USER and not password: - self.client._authenticate_system() + if not (session_id and self._reuse_session(SYSTEM_USER, session_id)): + self.client._set_session(None) + raise Error("Error: Superuser session is terminated") else: - self.session_authenticate(password=password) + self.session_authenticate(password=password, session_id=session_id) return self def _call_kw(self, model, method, args, kw=None): @@ -548,16 +586,25 @@ def upgrade_cancel(self): """Press button ``Cancel Upgrade/Install/Uninstall``.""" return self._upgrade((), button='cancel', quiet=True) - def session_authenticate(self, login=None, password=None): + def session_authenticate(self, login=None, password=None, session_id=None): """Create a Webclient session for current user.""" if not login: login = self.user.login - params = { - 'db': self.db_name, - 'login': login, - 'password': password or getpass(f"Password for '{color_bold(login)}': "), - } - self.session_info = self.client._authenticate_session(**params) + # Reuse the session, if it is still valid + info = session_id and self._reuse_session(login, session_id, password) + if not info: + params = { + 'db': self.db_name, + 'login': login, + 'password': password or self._ask_password(login), + } + info = self.client._authenticate_session(**params) + # Update the session in cache + auth_cache = self._cache_get('auth', dict) + if info.get('uid') and login in auth_cache: + (uid, pw) = auth_cache[login][:2] + auth_cache[login] = (uid, pw, self.client._get_session_id()) + self.session_info = info # When database name is discovered, copy cached data if ( not self.db_name and @@ -572,14 +619,27 @@ def session_authenticate(self, login=None, password=None): print(f'Session authenticated for {login!r}' if self.session_info['uid'] else 'Failed') def session_destroy(self): - """Terminate current Webclient session.""" - self.client._session_uid = None + """Terminate the Webclient session of this environment. + + A browser session is terminated too: the browser is logged out. + """ + auth = self.uid and self._cache_get('auth', dict).get(self.user.login) + session_id = auth and auth[2] + if session_id: + if session_id != self.client._get_session_id(): + # Attach the session of this environment, even if it changed (/web/become) + if not self.client._load_session(session_id): + return # Already terminated + elif self.uid != self.client._session_uid: + return # The current session belongs to another environment try: return self.client.web_session.destroy() except ServerError as exc: # Ignore: odoo.http.SessionExpiredException if exc.args[0]['code'] != 100: raise + finally: + self.client._set_session(None) def generate_api_key(self, expiration_date=DEFAULT): """Generate an API Key and configure environment to use it. diff --git a/odooly/http.py b/odooly/http.py index 6f28efd..5844865 100644 --- a/odooly/http.py +++ b/odooly/http.py @@ -3,7 +3,8 @@ import json import os import re -from urllib.parse import unquote, urlencode +from http.cookiejar import Cookie, CookieJar +from urllib.parse import unquote, urlencode, urlsplit from . import __version__ from .exceptions import ServerError @@ -37,6 +38,13 @@ def extract_filename(response, default=None): return unquote(found.group(1)) if found else default +def extract_domain(url): + host = urlsplit(url).hostname or '' + if '.' not in host: + host += '.local' # Like http.cookiejar.eff_request_host + return host + + def unescape(text): # When /report/download hits an AccessError, it can return JSON encoded with HTML entities return html.unescape(text) if text[:3] == '{&#' else text @@ -47,6 +55,7 @@ class HTTPSession: def __init__(self): self._session = requests.Session() self._session.headers.update({'User-Agent': USER_AGENT, 'Accept': 'application/json'}) + self._cookies = self._session.cookies def set_auth(self, uri, username, password): self._session.auth = (username, password) @@ -71,7 +80,9 @@ def _parse_error(self, err): else: # urllib.request def __init__(self): - self._session = build_opener(HTTPCookieProcessor(), HTTPSHandler(context=http_context)) + self._cookies = CookieJar() + self._session = build_opener(HTTPCookieProcessor(self._cookies), + HTTPSHandler(context=http_context)) self._session.addheaders = [('User-Agent', USER_AGENT), ('Accept', 'application/json')] def set_auth(self, uri, username, password): @@ -103,6 +114,25 @@ def _parse_response(self, resp): def _parse_error(self, err): return (err.code, self._parse_response(err)) if hasattr(err, 'code') else (0, 0) + def set_cookie(self, url, name, value): + """Set the cookie `name` for the host of `url`, or remove it if `value` is None.""" + host = extract_domain(url) + try: + self._cookies.clear(host, '/', name) + except KeyError: + pass + if value is not None: + self._cookies.set_cookie(Cookie( + 0, name, value, None, False, host, False, False, '/', True, + False, None, True, None, None, {})) + + def get_cookie(self, url, name): + """Get the cookie `name` for the host of `url`.""" + host = extract_domain(url) + values = (ck.value for ck in self._cookies + if (ck.domain, ck.path, ck.name) == (host, '/', name)) + return next(values, None) + def request(self, url, *, method='POST', data=None, json=None, headers=None): try: with self._request(url, method=method, data=data, json=json, headers=headers) as resp: diff --git a/odooly/run.py b/odooly/run.py index 3f4dc63..52af810 100644 --- a/odooly/run.py +++ b/odooly/run.py @@ -51,10 +51,12 @@ class InteractiveClient(Client): _saved_config_demo = {} _globals = None - def __init__(self, server, db=None, user=None, password=None, api_key=None, verbose=False): + def __init__(self, server, db=None, user=None, password=None, api_key=None, session_id=None, + verbose=False): self._printer = Printer() self.verbose = verbose - super().__init__(server, db=db, user=user, password=password, api_key=api_key) + super().__init__(server, db=db, user=user, password=password, api_key=api_key, + session_id=session_id) @property def verbose(self): @@ -99,13 +101,17 @@ def get_config(cls, environment): return cls._saved_config[environment] @classmethod - def from_config(cls, environment, *, user=None, database=None, verbose=False): + def from_config(cls, environment, *, user=None, database=None, session_id=None, + verbose=False): """Create a connection to a defined environment. See :meth:`InteractiveClient.get_config` Return a connected :class:`InteractiveClient`. """ (server, db, conf_user, password, api_key) = cls.get_config(environment) + if session_id: # Reuse a Webclient session + client = cls(server, database or db or None, session_id=session_id, verbose=verbose) + return client.save(environment) if skip_save := user and user != conf_user: password = None try: @@ -178,12 +184,24 @@ def _select_database(self, db_list, limit=20): except Exception: pass - def login(self, user, password=None, database=None, api_key=None): + def login(self, user, password=None, database=None, api_key=None, session_id=None): """Switch `user` and (optionally) `database`.""" if not self._is_interactive(): - return super().login(user, password=password, database=database, api_key=api_key) + return super().login( + user, + password=password, + database=database, + api_key=api_key, + session_id=session_id, + ) try: - register = super().login(user, password=password, database=database, api_key=api_key) + register = super().login( + user, + password=password, + database=database, + api_key=api_key, + session_id=session_id, + ) except (Error, EOFError, KeyboardInterrupt) as exc: print(exc) register = 'client' not in self._globals @@ -329,6 +347,9 @@ def get_parser(): parser.add_argument( '--api-key', dest='api_key', default=None, help='API Key for JSON-2 or JSON-RPC') + parser.add_argument( + '--session-id', dest='session_id', default=None, + help='reuse the "session_id" cookie of a browser session (e.g. OAuth login)') parser.add_argument( '--demo', dest='demo', nargs='?', const="demo", help='connect to demo or runbot server (default: demo, demo.odoo.com)') @@ -350,6 +371,7 @@ def connect_client(args): kwargs = { "user": args.user, "database": args.db, + "session_id": args.session_id, "verbose": args.verbose, } with except_handler(): @@ -366,10 +388,13 @@ def connect_client(args): kwargs = { "password": args.password, "api_key": args.api_key, + "session_id": args.session_id, "verbose": args.verbose, } with except_handler(): - client = InteractiveClient(server, args.db, args.user or ADMIN_USER, **kwargs) + # With a session_id, the user is optional: it must match the session + user = args.user or (None if args.session_id else ADMIN_USER) + client = InteractiveClient(server, args.db, user, **kwargs) return client diff --git a/tests/test_client.py b/tests/test_client.py index 3c7f4ee..21e5408 100644 --- a/tests/test_client.py +++ b/tests/test_client.py @@ -1,8 +1,9 @@ -from unittest import mock +from http.cookiejar import Cookie +from unittest import mock, TestCase from unittest.mock import call, sentinel, ANY import odooly.run -from ._common import JsonRpcTestCase, OBJ +from ._common import JsonRpcTestCase, OdooTestCase, OBJ AUTH = sentinel.AUTH ID1, ID2 = 4001, 4002 @@ -170,7 +171,7 @@ def test_create(self): {(odooly.Env, 'newdb', self.server): odooly.Env(client, 'newdb'), (key_1, 'newdb', self.server): client.env(context={}), (key_2, 'newdb', self.server): client.env, - ('auth', 'newdb', self.server): {'usr': (1, 'pss')}, + ('auth', 'newdb', self.server): {'usr': (1, 'pss', None)}, ('model_names', 'newdb', self.server): {'res.users': False}}) self.assertOutput('') @@ -203,7 +204,7 @@ def test_create_with_cache(self): self.service.database.list.return_value = ['database'] self.assertFalse(odooly.Env._cache) mock.patch.dict(odooly.Env._cache, - {('auth', 'database', self.server): {'usr': (1, 'password')}}).start() + {('auth', 'database', self.server): {'usr': (1, 'password', None)}}).start() client = odooly.Client(self.server, 'database', 'usr') self.assertIsInstance(client, odooly.Client) @@ -626,3 +627,296 @@ class TestClientApi18(TestClientApi): class TestClientApi19(TestClientApi): """Test the Client API for Odoo 19.""" server_version = '19.0' + + +class TestSharedSession(OdooTestCase): + """Test the Client with the session_id of a browser session.""" + server = f'{OdooTestCase.server}/' + database, user, uid = 'prod', 'jdoe@example.com', 7 + session_info = {'uid': uid, 'username': user, 'db': database, + 'user_context': {'lang': 'en_US'}, 'is_system': True} + + def _patch_http_request(self): + self.requests = [] + self.sessions = {'BROWSER': self.session_info} + return mock.patch('odooly.http.HTTPSession.request', autospec=True, + side_effect=self._fake_odoo).start() + + def _fake_odoo(self, http, url, *, method='POST', data=None, json=None, headers=None): + path = url[len(self.server) - 1:] + cookies = {c.name: c.value for c in http._cookies} + self.requests.append((path, cookies.get('session_id'))) + session = self.sessions.get(cookies.get('session_id')) + expired = {'code': 100, 'message': 'Odoo Session Expired', 'data': {}} + if method == 'HEAD': + return mock.Mock(url=url) + if path == '/web/become': + # Like Odoo 17: the session itself becomes Superuser + if session.get('is_system'): + self.sessions[cookies['session_id']] = { + 'uid': 1, 'username': '__system__', 'db': self.database} + return 'odoo.__session_info__ = {"uid": 1};' + if path == '/web/webclient/version_info': + return {'result': {'server_version': '17.0+e'}} + if path == '/web/database/list': + return {'error': {'code': 200, 'message': 'Access Denied', 'data': {}}} + if path == '/web/session/get_session_info': + return {'result': session} if session else {'error': expired} + if path == '/web/session/authenticate': + assert json['params']['password'] == 'admin' + self.sessions['OWN'] = {'uid': 2, 'username': 'admin', 'db': self.database, + 'is_system': True} + http.set_cookie(url, 'session_id', 'OWN') + return {'result': {'uid': 2, 'user_context': {}}} + if path == '/web/session/destroy': + self.sessions.pop(cookies.get('session_id'), None) + return {'result': None} + if path.startswith('/web/dataset/call_kw/'): + if not session: + return {'error': expired} + results = { + 'ir.model/fields_get': {}, + 'ir.model/search_read': [{'model': 'res.partner'}], + 'res.partner/search': [session['uid']], + } + return {'result': results[path[21:]]} + raise AssertionError(f'Unexpected request {path}') + + def test_login_session(self): + client = odooly.Client(self.server, session_id='BROWSER') + + self.assertEqual(client.env.uid, self.uid) + self.assertEqual(client.env.user.login, self.user) + self.assertEqual(client.env.db_name, self.database) + self.assertEqual(client.env.context, {'lang': 'en_US'}) + self.assertEqual(client.env.session_info, self.session_info) + self.assertEqual(client.env._cache_get('auth')[self.user], (self.uid, None, 'BROWSER')) + self.assertEqual(self.requests, [ + ('', None), # HEAD request + ('/web/webclient/version_info', None), + ('/web/session/get_session_info', 'BROWSER'), + ]) + self.assertEqual(client.env['res.partner'].search([]).ids, [self.uid]) + self.assertEqual(self.requests[-1], ('/web/dataset/call_kw/res.partner/search', 'BROWSER')) + self.assertOutput('') + + def test_login_session_invalid(self): + with self.assertRaisesRegex(odooly.Error, 'Invalid or expired session'): + odooly.Client(self.server, session_id='WRONG') + self.assertEqual(self.requests[-1], ('/web/session/get_session_info', 'WRONG')) + + client = odooly.Client(self.server) + with self.assertRaisesRegex(odooly.Error, "bound to database 'prod'"): + client.login(None, session_id='BROWSER', database='other') + self.assertFalse([*client._http._cookies]) + self.assertIsNone(client.env.uid) + + with self.assertRaisesRegex(odooly.Error, "bound to user 'jdoe@example.com'"): + client.login('admin', session_id='BROWSER') + self.assertFalse([*client._http._cookies]) + self.assertIsNone(client.env.uid) + self.assertOutput('') + + def test_switch_user(self): + client = odooly.Client(self.server, self.database, session_id='BROWSER') + shared_env = client.env + + # Password login does not reuse the shared session + client.login('admin', 'admin') + self.assertEqual(self.requests[-1], ('/web/session/authenticate', None)) + self.assertEqual(client.env['res.partner'].search([]).ids, [2]) + self.assertEqual(self.requests[-1][1], 'OWN') + + # Back to the shared session + self.assertEqual(shared_env['res.partner'].search([]).ids, [self.uid]) + self.assertEqual(self.requests[-1][1], 'BROWSER') + self.assertEqual(client.login(self.user), self.uid) + # Attached again through Env.session_authenticate + self.assertOutput(f"Session authenticated for {self.user!r}\n") + + # Back to the password user: its session is reused + self.requests.clear() + self.assertEqual(client.login('admin'), 2) + self.assertEqual(client.env['res.partner'].search([]).ids, [2]) + self.assertEqual(self.requests, [ + ('/web/session/get_session_info', 'OWN'), + ('/web/dataset/call_kw/res.partner/search', 'OWN'), + ]) + self.assertOutput('') + + def test_destroy_own_session(self): + client = odooly.Client(self.server, self.database, 'admin', 'admin') + env = client.env + self.assertEqual(env.context, {}) + self.assertEqual(env['res.partner'].search([]).ids, [2]) + env.session_destroy() + self.assertNotIn('OWN', self.sessions) + self.assertOutput('') + + # Authenticate again with the password, the destroyed session is not reused + self.requests.clear() + self.assertEqual(env['res.partner'].search([]).ids, [2]) + self.assertEqual(self.requests, [ + ('/web/session/get_session_info', 'OWN'), + ('/web/session/authenticate', None), + ('/web/dataset/call_kw/res.partner/search', 'OWN'), + ]) + self.assertEqual(env._cache_get('auth')['admin'], (2, 'admin', 'OWN')) + self.assertNotIn('__session_id', env.session_info) + self.assertOutput("Session authenticated for 'admin'\n") + + def test_sudo_own_session(self): + client = odooly.Client(self.server, self.database, 'admin', 'admin') + admin_env = client.env + self.assertEqual(client.env.sudo('__system__').uid, 1) + self.assertEqual(self.sessions['OWN']['username'], '__system__') + + # The environment authenticates again with the password + self.requests.clear() + self.assertEqual(admin_env['res.partner'].search([]).ids, [2]) + self.assertEqual(self.requests[:2], [ + ('/web/session/get_session_info', 'OWN'), + ('/web/session/authenticate', None), + ]) + self.assertEqual(self.requests[-1], ('/web/dataset/call_kw/res.partner/search', 'OWN')) + self.assertOutput("Session authenticated for 'admin'\n") + # Become Superuser again: the fake server reuses the id 'OWN' for the + # new session, so the saved Superuser session id is stale + self.sessions['OWN']['is_system'] = True + self.assertEqual(client.env.sudo('__system__').uid, 1) + self.assertOutput("Session authenticated for 'admin'\n") + + # The session is now Superuser: authenticate again with the password + self.requests.clear() + self.assertEqual(client.login('admin'), 2) + self.assertEqual(self.requests, [ + ('/web/session/get_session_info', 'OWN'), + ('/web/session/authenticate', None), + ]) + self.assertEqual(self.sessions['OWN']['username'], 'admin') + self.assertOutput('') + + def test_sudo_shared_session(self): + client = odooly.Client(self.server, self.database, session_id='BROWSER') + shared_env = client.env + client.login('admin', 'admin') + self.assertEqual(client.env['res.partner'].search([]).ids, [2]) + + # sudo() starts from the session of shared_env, and warns about the browser + system_env = shared_env.sudo() + self.assertEqual(system_env.uid, 1) + self.assertIn(('/web/become', 'BROWSER'), self.requests) + self.assertEqual(self.sessions['BROWSER']['username'], '__system__') + self.assertEqual(self.sessions['OWN']['username'], 'admin') + self.assertOutput(f"Session authenticated for {self.user!r}\n" + "Session is now Superuser. To undo: env.session_destroy()\n") + + # The Superuser session is reused, without /web/become again + self.assertEqual(client.env['res.partner'].search([]).ids, [2]) + self.requests.clear() + self.assertEqual(system_env['res.partner'].search([]).ids, [1]) + self.assertEqual(self.requests, [ + ('/web/session/get_session_info', 'BROWSER'), + ('/web/dataset/call_kw/res.partner/search', 'BROWSER'), + ]) + + # The shared user cannot go back to its session + with self.assertRaisesRegex(odooly.Error, "Session of 'jdoe@example.com' is now Superuser"): + client.login(self.user) + + # Undo: terminate the session + shared_env.session_destroy() + self.assertNotIn('BROWSER', self.sessions) + self.assertIn('OWN', self.sessions) + with self.assertRaisesRegex(odooly.Error, 'Superuser session is terminated'): + system_env['res.partner'].search([]).ids + self.assertOutput("Session authenticated for 'admin'\n") + + def test_destroy_session_of_env(self): + client = odooly.Client(self.server, self.database, session_id='BROWSER') + shared_env = client.env + client.login('admin', 'admin') + admin_env = client.env + self.assertEqual(shared_env['res.partner'].search([]).ids, [self.uid]) + + # The BROWSER session is attached, but OWN is terminated + admin_env.session_destroy() + self.assertEqual(set(self.sessions), {'BROWSER'}) + self.assertEqual(self.requests[-2:], [ + ('/web/session/get_session_info', 'OWN'), + ('/web/session/destroy', 'OWN'), + ]) + admin_env.session_destroy() # Already terminated + self.assertEqual(set(self.sessions), {'BROWSER'}) + self.assertOutput(f"Session authenticated for {self.user!r}\n") + + def test_destroy_shared_session(self): + mock.patch('odooly.environment.getpass', side_effect=EOFError).start() + client = odooly.Client(self.server, self.database, session_id='BROWSER') + env = client.env + + self.assertIsNone(env.session_destroy()) + self.assertNotIn('BROWSER', self.sessions) + self.assertFalse([*client._http._cookies]) + self.assertOutput('') + + # The browser is logged out: a password is needed + self.assertRaises(EOFError, env._get, 'res.partner') + self.assertEqual(self.requests[-1], ('/web/session/get_session_info', 'BROWSER')) + paths = {path for (path, sid) in self.requests} + self.assertFalse(paths & {'/web/session/authenticate', '/web/login', '/web/become'}) + + def test_connect_client(self): + args = odooly.run.get_parser().parse_args([self.server, '--session-id', 'BROWSER']) + client = odooly.run.connect_client(args) + self.assertEqual(client.env.uid, self.uid) + self.assertEqual(client.env.user.login, self.user) + + args = odooly.run.get_parser().parse_args( + [self.server, '-u', 'admin', '--session-id', 'BROWSER']) + with self.assertRaises(SystemExit): + odooly.run.connect_client(args) + self.assertIn("Session is bound to user 'jdoe@example.com'", self.stdout.popvalue()) + self.assertOutput('') + + def test_from_config(self): + env_tuple = (self.server, self.database, 'jdoe', None, None) + mock.patch('odooly.run.InteractiveClient.get_config', return_value=env_tuple).start() + + client = odooly.run.InteractiveClient.from_config('prod', session_id='BROWSER') + self.assertEqual(client.env.uid, self.uid) + self.assertEqual(client.env.name, 'prod') + self.assertEqual(client._saved_config['prod'][2], self.user) + self.assertOutput('') + + +class TestHTTPSessionCookie(TestCase): + + def test_set_cookie(self): + http = odooly.http.HTTPSession() + http.set_cookie('https://odoo.example.com/web', 'session_id', 'abc') + http.set_cookie('https://odoo.example.com/web', 'session_id', 'xyz') + http.set_cookie('http://localhost:8069/web', 'session_id', 'loc') + self.assertEqual(sorted((c.domain, c.value) for c in http._cookies), + [('localhost.local', 'loc'), ('odoo.example.com', 'xyz')]) + + http.set_cookie('https://odoo.example.com/web', 'session_id', None) + http.set_cookie('https://odoo.example.com/web', 'session_id', None) + self.assertEqual([c.value for c in http._cookies], ['loc']) + + def test_get_cookie(self): + http = odooly.http.HTTPSession() + self.assertIsNone(http.get_cookie('https://odoo.example.com/web', 'session_id')) + + # A cookie with another path is ignored, like in set_cookie + http._cookies.set_cookie(Cookie( + 0, 'session_id', 'other', None, False, 'odoo.example.com', False, False, + '/odoo', True, False, None, True, None, None, {})) + self.assertIsNone(http.get_cookie('https://odoo.example.com/web', 'session_id')) + + http.set_cookie('https://odoo.example.com/web', 'session_id', 'abc') + http.set_cookie('http://localhost:8069/web', 'session_id', 'loc') + self.assertEqual(http.get_cookie('https://odoo.example.com/', 'session_id'), 'abc') + self.assertEqual(http.get_cookie('http://localhost:8069/', 'session_id'), 'loc') + self.assertIsNone(http.get_cookie('https://odoo.example.com/', 'other')) + self.assertIsNone(http.get_cookie('https://example.com/', 'session_id'))