From bee03094f3bf2fa0c2dab80313d2f4bd15452c3d Mon Sep 17 00:00:00 2001 From: Anya Tokugawa Date: Sun, 8 Nov 2026 20:29:10 +0900 Subject: [PATCH] feat(auth): support explicit trusted login and expired session recovery --- Dockerfile.release | 2 +- README.md | 16 +++++++++++++- VERSION | 2 +- pages | 22 +++++++++++-------- test_remember.py | 55 ++++++++++++++++++++++++++++++++++++++++++++++ 5 files changed, 85 insertions(+), 12 deletions(-) create mode 100644 test_remember.py diff --git a/Dockerfile.release b/Dockerfile.release index 7e6cf34..5c215ff 100644 --- a/Dockerfile.release +++ b/Dockerfile.release @@ -6,6 +6,6 @@ ENV SOURCE_REVISION=$SOURCE_REVISION COPY requirements-build.txt . RUN pip install --no-cache-dir -r requirements-build.txt COPY . . -RUN python -m unittest test_pages test_productivity test_distribution test_tls && python tools/build.py && python tools/smoke_binary.py dist/pages && PAGES_CLI_TEST_BINARY=/src/dist/pages python -m unittest test_tls +RUN python -m unittest test_pages test_productivity test_distribution test_tls test_remember && python tools/build.py && python tools/smoke_binary.py dist/pages && PAGES_CLI_TEST_BINARY=/src/dist/pages python -m unittest test_tls FROM scratch AS artifacts COPY --from=build /src/release/ / diff --git a/README.md b/README.md index adf4db6..4b7cf29 100644 --- a/README.md +++ b/README.md @@ -55,7 +55,21 @@ pages -k logout OIDCでは `pages -k login --oidc --no-browser` のように指定できます。ただし、スキップするのはCLIのHTTPS要求のみです。開いたブラウザやOIDCプロバイダーの証明書検証は変更しません。 -### OIDCでログインする +### 信頼できる端末でログインを維持する + +開発版(未リリース)では、対応サーバーと組み合わせて最長30日のログインを選択できます。 + +```sh +pages login --remember +pages login --oidc --no-browser --remember +``` + +実際の期限はサーバー管理者の設定に従います。旧サーバーでは通常の期限になる場合があります。 +パスワード認証のTOTP、ログアウト、管理者による失効、アカウント停止は従来どおり有効です。 +共有端末では使用しないでください。アクセスによる期限の自動延長は行いません。 +期限切れ後はlogoutなしで再ログインでき、同じアカウントの作業パスと未送信タスク下書きを保持します。 + +### OIDC認証の手順 OIDC連携を有効にしたDomainで利用します。サーバーは **v0.3.0以降** が必要です。独立版CLI v0.1.0は対応済みです(分離前のCLIではサーバー同梱版v0.3.0以降)。 CLIのファイルだけを更新しても、v0.2.xのサーバーでは利用できません。 diff --git a/VERSION b/VERSION index 2b7c5ae..8f0916f 100644 --- a/VERSION +++ b/VERSION @@ -1 +1 @@ -0.4.2 +0.5.0 diff --git a/pages b/pages index 2aa70fb..9d4175e 100755 --- a/pages +++ b/pages @@ -32,7 +32,7 @@ import urllib.parse as url import urllib.request as http import webbrowser -VERSION = '0.4.2' +VERSION = '0.5.0' class Failure(Exception): def __init__(self, message, status=0, payload=None): @@ -144,9 +144,11 @@ class Client: except (ValueError, UnicodeError): raise Failure('Invalid JSON response.') from None - def login(self, username, password, otp=getpass.getpass): + def login(self, username, password, otp=getpass.getpass, *, remember=False): + form={'username':username,'password':password} + if remember:form['remember']='1' try: - result = self.json('/_/auth/login', method='POST', form={'username': username, 'password': password}) + result = self.json('/_/auth/login', method='POST', form=form) except Failure as e: if e.status != 401 or not e.payload.get('mfa_required') or not e.payload.get('challenge_token'): raise @@ -164,12 +166,13 @@ class Client: self.token = token return time.time() + duration - def login_oidc(self, no_browser=False, expected_username='', *, sleep=time.sleep, clock=time.monotonic): + def login_oidc(self, no_browser=False, expected_username='', *, remember=False, sleep=time.sleep, clock=time.monotonic): verifier = secrets.token_urlsafe(32) challenge = base64.urlsafe_b64encode(hashlib.sha256(verifier.encode()).digest()).decode().rstrip('=') try: - started = self.json('/_/auth/cli/start', method='POST', form={ - 'code_challenge': challenge, 'code_challenge_method': 'S256'}) + form={'code_challenge':challenge,'code_challenge_method':'S256'} + if remember:form['remember']='1' + started = self.json('/_/auth/cli/start', method='POST', form=form) except Failure as e: if e.status in (404, 405, 501): raise Failure('CLI OIDC login is unavailable on this server. Check the configured server URL and deploy a server version supporting /_/auth/cli/start.', e.status) from None @@ -856,6 +859,7 @@ def main(argv=None): login = argparse.ArgumentParser(prog='pages login', description='Log into the configured connection. Password and TOTP are prompted privately.') login.add_argument('--oidc', action='store_true', help='Authenticate and approve in a browser; no local password required') login.add_argument('--no-browser', action='store_true', help='Print the browser login URL without opening it (requires --oidc)') + login.add_argument('--remember', action='store_true', help='Keep this trusted device signed in for up to 30 days, subject to server policy') login_args = login.parse_args(args.args) if login_args.no_browser and not login_args.oidc: login.error('--no-browser requires --oidc') elif '--help' in args.args: @@ -874,13 +878,13 @@ def main(argv=None): print('WARNING: --insecure disables TLS certificate and hostname verification for this invocation. Credentials and data can be intercepted; this option is not saved.', file=sys.stderr) if args.command == 'login': if not login_args.oidc and not spec.get('username'): raise Failure('Set your account with pages configure --username NAME, or use pages login --oidc.') - if profile.data.get('token'): raise Failure('Log out this profile before replacing its session.') + if profile.data.get('token') and profile.data.get('expires',0)>time.time(): raise Failure('Log out this profile before replacing its active session.') client = Client(spec['origin'], lang=lang, insecure=args.insecure) if login_args.oidc: - expires, username = client.login_oidc(login_args.no_browser, spec.get('username', '')) + expires, username = client.login_oidc(login_args.no_browser, spec.get('username', ''), remember=login_args.remember) else: username = spec['username'] - expires = client.login(username, getpass.getpass('Password: ')) + expires = client.login(username, getpass.getpass('Password: '), remember=login_args.remember) same_identity = profile.data.get('origin') == client.base and profile.data.get('username') == username pending = profile.data.get('task_outbox', {}) if pending and not same_identity: diff --git a/test_remember.py b/test_remember.py new file mode 100644 index 0000000..48bee90 --- /dev/null +++ b/test_remember.py @@ -0,0 +1,55 @@ +import contextlib +import io +import os +from pathlib import Path +import runpy +import time +import tempfile +import unittest +from unittest.mock import patch + +m = runpy.run_path(str(Path(__file__).with_name('pages'))) + + +class RememberTests(unittest.TestCase): + def test_expired_login_retains_same_account_drafts_and_path(self): + with tempfile.TemporaryDirectory() as root, patch.dict(os.environ, {'XDG_CONFIG_HOME': root}), contextlib.redirect_stdout(io.StringIO()): + with m['Configuration']().locked() as config: + config.data = {'version': 1, 'default_profile': 'default', 'profiles': {'default': {'origin': 'https://wiki.example', 'username': 'anya', 'lang': 'auto'}}} + config.save() + with m['Profile']('default').locked() as profile: + profile.data = {'origin': 'https://wiki.example', 'username': 'anya', 'token': 'expired', 'expires': 1, + 'cwd': '/projects/demo', 'task_outbox': {'request': {'title': 'synthetic draft'}}} + profile.save() + def login(client, username, password, *, remember=False): + self.assertTrue(remember) + client.token = 'pw_api_'+'x'*43 + return time.time()+2592000 + with patch.object(m['Client'], 'login', login), patch.object(m['getpass'], 'getpass', return_value='synthetic'): + m['main'](['login', '--remember']) + with m['Profile']('default').locked() as profile: + self.assertEqual(profile.data['cwd'], '/projects/demo') + self.assertEqual(profile.data['task_outbox']['request']['title'], 'synthetic draft') + self.assertTrue(profile.data['token'].startswith('pw_api_')) + + def test_password_choice_is_explicit_and_bound_before_totp(self): + for remember in (False, True): + client = m['Client']('https://wiki.example') + challenge = m['Failure']('MFA', 401, {'mfa_required': True, 'challenge_token': 'challenge'}) + result = {'access_token': 'pw_api_' + 'x'*43, 'token_type': 'Bearer', 'expires_in': 2592000} + with patch.object(client, 'json', side_effect=[challenge, result]) as api: + expiry = client.login('anya', 'synthetic-password', lambda _: '123456', remember=remember) + self.assertEqual(api.call_args_list[0].kwargs['form'].get('remember'), '1' if remember else None) + self.assertNotIn('remember', api.call_args_list[1].kwargs['form']) + self.assertAlmostEqual(expiry - time.time(), 2592000, delta=2) + + def test_oidc_choice_is_bound_at_start(self): + for remember in (False, True): + client = m['Client']('https://wiki.example') + start = {'device_code': 'd'*43, 'verification_uri': '/_/auth/cli/verify?request='+'r'*43, + 'user_code': 'ABCD-1234', 'expires_in': 300, 'interval': 5} + result = {'access_token': 'pw_api_'+'x'*43, 'token_type': 'Bearer', 'expires_in': 2592000, 'username': 'anya'} + with patch.object(client, 'json', side_effect=[start, result]) as api, contextlib.redirect_stdout(io.StringIO()): + client.login_oidc(True, remember=remember, sleep=lambda _: None, clock=lambda: 0) + self.assertEqual(api.call_args_list[0].kwargs['form'].get('remember'), '1' if remember else None) + self.assertNotIn('remember', api.call_args_list[1].kwargs['form'])