Add OIDC browser approval and PKCE session handoff for pages CLI

This commit is contained in:
Anya Tokugawa committed 2026-11-01 20:26:45 +09:00
1 parent 336c5790e9
commit f188e7eac1
3 files changed
+224 -9

No files matched your search

+29 -1
View File
@@ -34,6 +34,34 @@ pages[default]:/manual> exit
`exit` はシェルを閉じるだけです。セッションを失効させる場合は `pages logout`。
### OIDCでログインする
OIDC連携を有効にしたDomainで利用します。サーバーとCLIの両方に **v0.3.0以降** が必要です。
CLIのファイルだけを更新しても、v0.2.xのサーバーでは利用できません。
```sh
pages configure --origin https://pages.example.test
pages login --oidc
# SSH先など、ブラウザを自動で開かない場合
pages login --oidc --no-browser
```
CLIに表示されたURLを手元のPC/スマホで開き、OIDCでログインします。
続いてアカウント・接続先を確認し、ターミナルの確認コードを入力して承認します。
ローカルTOTPを設定済みならTOTPも必要です。承認後はCLIが専用セッションを受け取ります。
OIDCプロバイダーのパスワードやトークンをターミナルに入力する必要はありません。
ユーザー名の指定は省略できます。指定済みならブラウザで認証したユーザーとの一致を確認し、
不一致時は発行セッションの失効を試みて保存しません。`pages logout` 後に設定を変更できます。
リクエストは5分で失効します。Ctrl+Cはローカルの待機を終了し、未交換リクエストは期限で失効します。
他人から送られたURL・コードでは承認しないでください。通信断で交換結果が不明な場合は自動再送せず、
サーバのセッション管理で不要なセッションを確認・失効してからログインし直します。
`CLI OIDC login is unavailable on this server` は開始APIが利用できない場合の表示です。
configureの接続先URLを確認し、サーバーも対応版へ更新してください。
`OIDC login is not enabled for this domain` の場合は、対象DomainのOIDC設定を確認してください。
`--no-browser` はブラウザーの自動起動だけを抑止し、承認待ちとセッション取得は通常どおり行います。
## 設定する
```sh
@@ -94,7 +122,7 @@ pages edit /guide
`pages --help`、`pages configure --help`、`pages edit --help` で引数を確認できます。
Tab補完、上下キーのプロセス内履歴に対応。複雑な引用位置の補完、Ctrl+Pのfuzzy UIは後続です。
初期版は既存Page・既存言語の更新まで。新規作成、OIDC引き継ぎ、バイナリ更新は未実装です。
初期版は既存Page・既存言語の更新まで。新規作成、バイナリ更新は未実装です。
競合や通信断で自動上書きせず、ローカル原稿を保持します。HTTPS必須(開発用loopbackのみHTTP可)。
詳しいURI・保存・安全性の契約は[設計書](../docs/design/ja/remote-cli.md)を参照してください。
+75 -8
View File
@@ -1,6 +1,7 @@
#!/usr/bin/env python3
"""pages — navigate and edit PagesWiki from your terminal (pages-cli)."""
import argparse
import base64
import contextlib
import difflib
import fcntl
@@ -11,6 +12,7 @@ import os
from pathlib import Path
import posixpath
import re
import secrets
import shlex
import stat
import subprocess
@@ -130,11 +132,69 @@ class Client:
raise
result = self.json('/_/auth/totp', method='POST', form={
'challenge_token': e.payload['challenge_token'], 'code': otp('TOTP: ')})
return self.accept_session(result)
def accept_session(self, result):
token = result.get('access_token')
if not isinstance(token, str) or not re.fullmatch(r'[A-Za-z0-9_.~-]{16,1024}', token) or result.get('token_type') != 'Bearer':
raise Failure('Server did not issue a Bearer session.')
duration = result.get('expires_in')
if not isinstance(duration, int) or isinstance(duration, bool) or not 1 <= duration <= 30*24*60*60:
raise Failure('Invalid session lifetime.')
self.token = token
return time.time() + int(result['expires_in'])
return time.time() + duration
def login_oidc(self, no_browser=False, expected_username='', *, 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'})
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
if e.status == 403 and e.payload.get('error') == 'oidc_disabled':
raise Failure('OIDC login is not enabled for this domain. Ask your administrator to enable it.', e.status) from None
raise
device, route, code = (started.get(k) for k in ('device_code', 'verification_uri', 'user_code'))
if (not isinstance(device, str) or not re.fullmatch(r'[A-Za-z0-9_-]{43}', device)
or not isinstance(route, str) or not re.fullmatch(r'/_/auth/cli/verify\?request=[A-Za-z0-9_-]{43}', route)
or not isinstance(code, str) or not re.fullmatch(r'[A-F0-9]{4}-[A-F0-9]{4}', code)):
raise Failure('Invalid browser login response; no browser was opened.')
lifetime, interval = int(started.get('expires_in', 0)), int(started.get('interval', 0))
if not 1 <= lifetime <= 300 or not 5 <= interval <= 30:
raise Failure('Invalid browser login lifetime or polling interval.')
deadline = clock() + lifetime
print('Open this URL and approve only the request you started:')
print(self.base + route)
print('Confirmation code:', code)
print('Waiting for approval (up to 5 minutes). Ctrl+C cancels locally.', flush=True)
if not no_browser:
try: webbrowser.open(self.base + route, new=2)
except (webbrowser.Error, OSError): pass # URL remains usable on another device.
while clock() + interval < deadline:
sleep(interval)
try:
result = self.json('/_/auth/cli/token', method='POST', form={
'device_code': device, 'code_verifier': verifier})
except Failure as e:
reason = e.payload.get('error')
if e.status == 400 and reason == 'authorization_pending': continue
if e.status == 400 and reason == 'slow_down':
interval = min(30, interval + 5); continue
if reason in ('access_denied', 'expired_token', 'oidc_disabled'):
raise Failure('Browser login denied, expired or disabled. Restart pages login --oidc.') from None
raise # Never retry an ambiguous token exchange or a network failure.
name = result.get('username')
expires = self.accept_session(result)
if (not isinstance(name, str) or not name or any(unicodedata.category(c).startswith('C') for c in name)
or (expected_username and name.lower() != expected_username.lower())):
try: self.json('/_/auth/logout', method='POST')
except Failure: pass
self.token = ''
raise Failure('The browser account differs from the configured username; attempted to revoke the new session.')
return expires, name
raise Failure('Browser login expired. Restart pages login --oidc.')
def listing(self, path, prefix=''):
return self.json('/_/api/v1/path-picker?' + url.urlencode({'path': path, 'mode': 'children', 'prefix': prefix}))
@@ -304,7 +364,7 @@ def configure(words, root=None):
# Configuration and session locks use this order. Never retarget an
# active credential to a different Domain or account.
with Profile(name, root).locked() as session:
if session.data.get('token') and (spec['origin'] != session.data.get('origin') or spec.get('username', '') != session.data.get('username')):
if session.data.get('token') and (spec['origin'] != session.data.get('origin') or spec.get('username', '') != session.data.get('configured_username', session.data.get('username'))):
raise Failure('Log out this profile before changing its origin or username.')
data['profiles'][name] = spec
if len(data['profiles']) == 1: data['default_profile'] = name
@@ -480,7 +540,10 @@ def main(argv=None):
parser.print_help(); return
if args.command == 'login':
login = argparse.ArgumentParser(prog='pages login', description='Log into the configured connection. Password and TOTP are prompted privately.')
login.parse_args(args.args)
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_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:
execute(None, None, [args.command] + args.args); return
with contextlib.ExitStack() as stack:
@@ -494,13 +557,17 @@ def main(argv=None):
# Hold the profile lock before releasing the configuration lock.
profile = stack.enter_context(Profile(name).locked())
if args.command == 'login':
if not spec.get('username'): raise Failure('Set your account with pages configure --username NAME.')
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.')
client = Client(spec['origin'], lang=lang)
expires = client.login(spec['username'], getpass.getpass('Password: '))
same_identity = profile.data.get('origin') == client.base and profile.data.get('username') == spec['username']
if login_args.oidc:
expires, username = client.login_oidc(login_args.no_browser, spec.get('username', ''))
else:
username = spec['username']
expires = client.login(username, getpass.getpass('Password: '))
same_identity = profile.data.get('origin') == client.base and profile.data.get('username') == username
cwd = profile.data.get('cwd', '/') if same_identity else '/'
profile.data = {'origin': client.base, 'username': spec['username'], 'token': client.token, 'expires': expires, 'cwd': cwd}
profile.data = {'origin': client.base, 'username': username, 'configured_username': spec.get('username', ''), 'token': client.token, 'expires': expires, 'cwd': cwd}
try:
profile.save()
except OSError:
@@ -512,7 +579,7 @@ def main(argv=None):
raise Failure('Could not save credentials; attempted to revoke the new session.') from None
print('Logged in. Session saved privately.'); return
if not profile.data.get('token'): raise Failure('Log in first.')
if args.command != 'logout' and (profile.data.get('origin') != spec['origin'] or profile.data.get('username') != spec.get('username')):
if args.command != 'logout' and (profile.data.get('origin') != spec['origin'] or profile.data.get('configured_username', profile.data.get('username')) != spec.get('username', '')):
raise Failure('Session and configured identity differ. Log out before reconnecting.')
if args.command not in ('logout', 'status') and profile.data.get('expires', 0) <= time.time(): raise Failure('Session expired; log out and log in again.')
client = Client(profile.data['origin'], profile.data['token'], lang)
+120
View File
@@ -1,4 +1,5 @@
import contextlib
import base64
from email.message import Message
import hashlib
import io
@@ -38,6 +39,94 @@ def reply(h, status, body, mime='application/json'):
class RemoteTests(unittest.TestCase):
def test_oidc_polling_pkce_and_no_secret_output(self):
now = [0]
waits, calls = [], []
started = {'device_code': 'D'*43, 'verification_uri': '/_/auth/cli/verify?request='+'R'*43,
'user_code': 'ABCD-1234', 'expires_in': 300, 'interval': 5}
client = Client('https://wiki.example')
def sleep(seconds): waits.append(seconds); now[0] += seconds
def request(route, **kwargs):
calls.append((route, kwargs))
if route.endswith('/start'): return started
polls = len(calls)-1
if polls == 1: raise Failure('pending',400,{'error':'authorization_pending'})
if polls == 2: raise Failure('slow',400,{'error':'slow_down'})
return {'access_token':'pw_api_'+'S'*43,'token_type':'Bearer','expires_in':3600,'username':'anya'}
with patch.object(client,'json',side_effect=request), patch.object(m['webbrowser'],'open') as browser, contextlib.redirect_stdout(io.StringIO()) as out:
expires, name = client.login_oidc(True,sleep=sleep,clock=lambda:now[0])
self.assertEqual(name,'anya'); self.assertGreater(expires,time.time())
self.assertEqual(waits,[5,5,10]); browser.assert_not_called()
proof = calls[1][1]['form']['code_verifier']
expected=base64.urlsafe_b64encode(hashlib.sha256(proof.encode()).digest()).decode().rstrip('=')
self.assertEqual(calls[0][1]['form']['code_challenge'],expected)
self.assertNotIn(proof,out.getvalue()); self.assertNotIn(started['device_code'],out.getvalue()); self.assertNotIn(client.token,out.getvalue())
self.assertIn('ABCD-1234',out.getvalue())
def test_oidc_unavailable_server_explained_without_retry(self):
for status in (404, 405, 501):
with self.subTest(status=status):
client = Client('https://wiki.example')
with patch.object(client, 'json', side_effect=Failure('Not found or not readable.', status)) as api, patch.object(m['webbrowser'], 'open') as browser, contextlib.redirect_stdout(io.StringIO()) as out:
with self.assertRaisesRegex(Failure, 'CLI OIDC login is unavailable') as caught:
client.login_oidc(True)
self.assertEqual(caught.exception.status, status)
api.assert_called_once()
browser.assert_not_called()
self.assertEqual(out.getvalue(), '')
self.assertEqual(client.token, '')
def test_oidc_disabled_and_other_start_errors(self):
client = Client('https://wiki.example')
with patch.object(client, 'json', side_effect=Failure('Access denied.', 403, {'error': 'oidc_disabled'})):
with self.assertRaisesRegex(Failure, 'not enabled for this domain'):
client.login_oidc(True)
for error in (Failure('Connection/TLS failure.'), Failure('Access denied.', 403), Failure('Unavailable.', 503)):
with patch.object(client, 'json', side_effect=error) as api:
with self.assertRaises(Failure) as caught:
client.login_oidc(True)
self.assertIs(caught.exception, error)
api.assert_called_once()
def test_oidc_rejects_external_url_and_wrong_account(self):
client=Client('https://wiki.example')
started={'device_code':'D'*43,'verification_uri':'https://evil.example/','user_code':'ABCD-1234','expires_in':300,'interval':5}
with patch.object(client,'json',return_value=started),patch.object(m['webbrowser'],'open') as browser:
with self.assertRaises(Failure): client.login_oidc()
browser.assert_not_called()
started['verification_uri']='/_/auth/cli/verify?request='+'R'*43
token={'access_token':'pw_api_'+'S'*43,'token_type':'Bearer','expires_in':3600,'username':'other'}
with patch.object(client,'json',side_effect=[started,token,{}]) as api, contextlib.redirect_stdout(io.StringIO()):
with self.assertRaises(Failure): client.login_oidc(True,'anya',sleep=lambda _:None,clock=lambda:0)
self.assertEqual(api.call_args.args[0],'/_/auth/logout')
self.assertEqual(client.token,'')
def test_oidc_cancellation_denial_and_ambiguous_exchange(self):
started={'device_code':'D'*43,'verification_uri':'/_/auth/cli/verify?request='+'R'*43,'user_code':'ABCD-1234','expires_in':300,'interval':5}
for error in [Failure('denied',403,{'error':'access_denied'}),Failure('expired',400,{'error':'expired_token'}),Failure('network failure')]:
client=Client('https://wiki.example')
with patch.object(client,'json',side_effect=[started,error]) as api,contextlib.redirect_stdout(io.StringIO()):
with self.assertRaises(Failure): client.login_oidc(True,sleep=lambda _:None,clock=lambda:0)
self.assertEqual(api.call_count,2)
client=Client('https://wiki.example')
with patch.object(client,'json',return_value=started) as api,contextlib.redirect_stdout(io.StringIO()):
def interrupt(_): raise KeyboardInterrupt()
with self.assertRaises(KeyboardInterrupt): client.login_oidc(True,sleep=interrupt,clock=lambda:0)
self.assertEqual(api.call_count,1)
def test_oidc_main_without_configured_username(self):
with tempfile.TemporaryDirectory() as root, patch.dict(os.environ,{'XDG_CONFIG_HOME':root}):
self.configure(None,'--origin','https://wiki.example')
def login(client,*args,**kwargs): client.token='pw_api_'+'s'*43; return time.time()+600,'anya'
with patch.object(Client,'login_oidc',login),contextlib.redirect_stdout(io.StringIO()):
m['main'](['login','--oidc','--no-browser'])
m['main'](['status'])
self.configure(None,'--lang','ja')
with Profile('default').locked() as profile:
self.assertEqual(profile.data['username'],'anya')
self.assertEqual(profile.data['configured_username'],'')
with self.assertRaises(Failure): self.configure(None,'--username','other')
def configure(self, root, *args):
with contextlib.redirect_stdout(io.StringIO()) as output:
m['configure'](list(args), root)
@@ -204,6 +293,36 @@ class RemoteTests(unittest.TestCase):
self.assertEqual(stat.S_IMODE((directory/'recovery.json').stat().st_mode),0o600)
def oidc_integration():
fixture=json.load(sys.stdin)
original=Client.json
grant={}
def capture(client,route,**kwargs):
result=original(client,route,**kwargs)
if route=='/_/auth/cli/start': grant.update(result)
return result
def browser(target,**kwargs):
ident=m['url'].parse_qs(m['url'].urlsplit(target).query)['request'][0]
original(Client(fixture['origin']),'/__test/cli-approve',method='POST',form={'request':ident,'code':grant['user_code']})
return True
with tempfile.TemporaryDirectory() as root,patch.dict(os.environ,{'XDG_CONFIG_HOME':root}),contextlib.redirect_stdout(io.StringIO()) as output:
m['main'](['configure','--origin',fixture['origin']])
with patch.object(Client,'json',capture),patch.object(m['webbrowser'],'open',browser): m['main'](['login','--oidc'])
with Profile('default',root).locked() as session:
token=session.data['token']; assert session.data['username']=='admin'
m['main'](['ls']); m['main'](['status'])
client=Client(fixture['origin'],token)
state=client.snapshot('path:/editor-fixture')
client.save(state,'# OIDC edit\n\n{{children}}\n',True)
assert '{{children}}' in client.snapshot('path:/editor-fixture')['markdown']
m['main'](['logout'])
assert token not in output.getvalue()
try: client.snapshot('path:/editor-fixture')
except Failure as e: assert e.status in (401,403,303)
else: raise AssertionError('revoked CLI session accepted')
print('OIDC CLI configure/login/list/authoring/logout integration passed')
def integration():
fixture=json.load(sys.stdin)
# Exercise the public entry point with persisted defaults, not only Client.
@@ -261,4 +380,5 @@ def integration():
if __name__=='__main__':
if sys.argv[1:] == ['--integration']: integration()
elif sys.argv[1:] == ['--oidc-integration']: oidc_integration()
else: unittest.main()