From 0ce9c42ff6aff7a55caffcb6857ab56423aeb30f Mon Sep 17 00:00:00 2001 From: Krzysztof kuhy Rudnicki Date: Mon, 16 Nov 2026 07:59:31 +0100 Subject: [PATCH] MCP tokens load once, keep last good set A read error no longer clears the accepted tokens; with no good load the answer is 503, not 403. A request costs one stat. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01WzxdWXgrX1QxVjqMiz6KFs --- lib/mcp/task_service.dart | 2 + lib/mcp/todo_mcp_server.dart | 45 ++++++++++++--- lib/mcp/token_file.dart | 87 ++++++++++++++++++++++------ pubspec.yaml | 2 +- test/mcp/mcp_auth_test.dart | 27 +++++++-- test/mcp/mcp_harness.dart | 4 +- test/mcp/token_store_test.dart | 100 +++++++++++++++++++++++++++++++++ 7 files changed, 234 insertions(+), 33 deletions(-) create mode 100644 test/mcp/token_store_test.dart diff --git a/lib/mcp/task_service.dart b/lib/mcp/task_service.dart index ad4fde8..18ee0f1 100644 --- a/lib/mcp/task_service.dart +++ b/lib/mcp/task_service.dart @@ -25,6 +25,8 @@ class TaskService { final CliSession _session; final BoardClient? _board; + + /// Longest one call may run before it fails with a TimeoutException. final Duration callTimeout; Future _tail = Future.value(); diff --git a/lib/mcp/todo_mcp_server.dart b/lib/mcp/todo_mcp_server.dart index 6e9a6d5..6a14c4a 100644 --- a/lib/mcp/todo_mcp_server.dart +++ b/lib/mcp/todo_mcp_server.dart @@ -1,3 +1,4 @@ +import 'dart:async'; import 'dart:io'; import 'package:mcp_dart/mcp_dart.dart'; @@ -34,26 +35,43 @@ class TodoMcpServer { /// `http://:/mcp`. Uri get uri => Uri.parse('http://${_http.host}:${_http.boundPort}/mcp'); - /// Binds [host]:[port] (0 = any free port); [tokens] is read per request. + /// Binds [host]:[port] (0 = any free port); [tokens] is loaded once and + /// re-read when its mtime changes, errors going to [log] (default stderr). + /// static Future start({ required TaskService tasks, required File tokens, String host = '127.0.0.1', int port = kTodoMcpPort, + void Function(String)? log, }) async { + final out = log ?? (String line) => stderr.writeln(line); + final store = TokenStore(tokens, log: out); final http = StreamableMcpServer( serverFactory: (_) => _server(tasks), host: host, port: port, - authenticator: (request) => tokenAccepted( - tokens, - request is HttpRequest - ? request.headers.value(HttpHeaders.authorizationHeader) - : null, - ), + authenticator: (request) { + if (request is! HttpRequest) return false; + return switch (store.verdict( + request.headers.value(HttpHeaders.authorizationHeader), + )) { + TokenVerdict.accepted => true, + TokenVerdict.rejected => false, + TokenVerdict.unavailable => _answerUnavailable(request), + }; + }, allowedHosts: const {'localhost', '127.0.0.1', '::1', _publicHost}, ); - await http.start(); + // The library runs each request as an unawaited future in the zone that + // called start(): without a guard, one failed write (a response we closed + // first) would be an uncaught error and kill the process. + await runZonedGuarded(http.start, (error, stack) { + if (error is StateError && '$error'.contains('Header already sent')) { + return; // the library answering a request we already answered + } + out('todo-mcp: request error: $error'); + }); return TodoMcpServer._(http); } @@ -61,6 +79,17 @@ class TodoMcpServer { Future close() => _http.stop(); } +/// Answers 503 here because the library can only say 403 for a refusal; it +/// then fails to write its own 403 ("Header already sent", swallowed by the +/// zone guard in [TodoMcpServer.start]) and the request stays refused. +bool _answerUnavailable(HttpRequest request) { + request.response + ..statusCode = HttpStatus.serviceUnavailable + ..write('Service Unavailable') + ..close().ignore(); + return false; +} + McpServer _server(TaskService tasks) { final server = McpServer( const Implementation(name: 'todo', version: '1.0.0'), diff --git a/lib/mcp/token_file.dart b/lib/mcp/token_file.dart index 0988d29..15cbb4d 100644 --- a/lib/mcp/token_file.dart +++ b/lib/mcp/token_file.dart @@ -5,27 +5,78 @@ import 'package:crdt_sync/crdt_sync.dart'; /// sha256 hex of [token] (crdt_sync's `revisionOf` is exactly that). String tokenHash(String token) => revisionOf(token); -Set _hashes(File tokens) { - final String text; - try { - text = tokens.readAsStringSync(); - } on FileSystemException { - return const {}; +/// What the tokens file says about one `Authorization` header. +enum TokenVerdict { + /// A listed token: let the request in. + accepted, + + /// Missing, malformed or unlisted: HTTP 403. + rejected, + + /// No token set has ever loaded, so nothing can be judged: HTTP 503. + unavailable, +} + +/// The sha256-hashed bearer tokens of [file], loaded once. +/// +/// A request costs one `stat`; the file is re-read only when its mtime or +/// size changed. A failed read keeps the last good set (an exhausted fd table +/// once made every valid token read as "no tokens", i.e. 403) and is logged +/// once per distinct error. Until a first good load every well-formed bearer +/// is [TokenVerdict.unavailable], never a refusal. +class TokenStore { + /// Watches [file]; [log] gets read errors. + TokenStore(this.file, {required this.log}); + + /// The ` ` lines, `#` comments allowed. + final File file; + + /// Receives read errors, one line each. + final void Function(String) log; + + Set? _hashes; + (DateTime, int)? _seen; + String? _lastError; + + /// Judges [authorization] (an `Authorization` header value or null). + TokenVerdict verdict(String? authorization) { + const scheme = 'bearer '; + if (authorization == null || + !authorization.toLowerCase().startsWith(scheme)) { + return TokenVerdict.rejected; + } + final token = authorization.substring(scheme.length).trim(); + if (token.isEmpty) return TokenVerdict.rejected; + _refresh(); + final hashes = _hashes; + if (hashes == null) return TokenVerdict.unavailable; + return hashes.contains(tokenHash(token)) + ? TokenVerdict.accepted + : TokenVerdict.rejected; } - return { + + void _refresh() { + try { + final stat = file.statSync(); + if (stat.type == FileSystemEntityType.notFound) { + throw FileSystemException('no such file', file.path); + } + final key = (stat.modified, stat.size); + if (key == _seen) return; + _hashes = _parse(file.readAsStringSync()); + _seen = key; + _lastError = null; + } on FileSystemException catch (e) { + // Keep the last good set; `_seen` stays, so the next request retries. + final message = '${e.message} ${e.path} ${e.osError?.errorCode}'; + if (message != _lastError) log('tokens: keeping last set: $message'); + _lastError = message; + } + } + + static Set _parse(String text) => { for (final line in text.split('\n')) if (line.trim() case final t when t.isNotEmpty && !t.startsWith('#')) t.split(RegExp(r'\s+')).first.toLowerCase(), }; } - -/// Whether [authorization] bears a token hashed in [tokens], read per call. -bool tokenAccepted(File tokens, String? authorization) { - const scheme = 'bearer '; - if (authorization == null || - !authorization.toLowerCase().startsWith(scheme)) { - return false; - } - final token = authorization.substring(scheme.length).trim(); - return token.isNotEmpty && _hashes(tokens).contains(tokenHash(token)); -} diff --git a/pubspec.yaml b/pubspec.yaml index da9e80f..e909dee 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -16,7 +16,7 @@ publish_to: 'none' # Remove this line if you wish to publish to pub.dev # https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html # In Windows, build-name is used as the major, minor, and patch parts # of the product and file versions while build-number is used as the build suffix. -version: 1.0.89+1 +version: 1.0.90+1 environment: sdk: ^3.12.2 diff --git a/test/mcp/mcp_auth_test.dart b/test/mcp/mcp_auth_test.dart index d531438..5bd994a 100644 --- a/test/mcp/mcp_auth_test.dart +++ b/test/mcp/mcp_auth_test.dart @@ -1,6 +1,9 @@ // Bearer tokens are checked against sha256 hashes in the tokens file, re-read -// per request so revoking a line takes effect without a restart; the Host -// check admits loopback and the public proxy name only. +// when it changes so revoking a line takes effect without a restart; a read +// error keeps the last good set, and with none loaded the answer is 503. The +// Host check admits loopback and the public proxy name only. +import 'dart:io'; + import 'package:flutter_test/flutter_test.dart'; import 'mcp_harness.dart'; @@ -33,9 +36,25 @@ void main() { expect(await h.rawInitialize({'authorization': ok}), anyOf(401, 403)); }); - test('a missing tokens file admits nobody', () async { + test('a vanished tokens file keeps the tokens already loaded', () async { + expect(await h.rawInitialize({'authorization': ok}), 200); h.tokens.deleteSync(); - expect(await h.rawInitialize({'authorization': ok}), anyOf(401, 403)); + expect(await h.rawInitialize({'authorization': ok}), 200); + }); + + test('[T-tokens-keep] an unreadable file keeps the loaded tokens', () async { + expect(await h.rawInitialize({'authorization': ok}), 200); + h.tokens.writeAsStringSync('# rewritten, then locked\n'); + Process.runSync('chmod', ['000', h.tokens.path]); + expect(await h.rawInitialize({'authorization': ok}), 200); + }); + + test('[T-tokens-503] no good load yet answers 503, not 403', () async { + Process.runSync('chmod', ['000', h.tokens.path]); + expect(await h.rawInitialize({'authorization': ok}), 503); + expect(await h.rawInitialize({}), 403, reason: 'no bearer: plain refusal'); + Process.runSync('chmod', ['600', h.tokens.path]); + expect(await h.rawInitialize({'authorization': ok}), 200); }); test('the proxy host is admitted, a foreign host is not', () async { diff --git a/test/mcp/mcp_harness.dart b/test/mcp/mcp_harness.dart index f779477..7f393df 100644 --- a/test/mcp/mcp_harness.dart +++ b/test/mcp/mcp_harness.dart @@ -24,7 +24,7 @@ class McpHarness { final BoardClient? board; static const token = 'test-token-for-pc'; - final tmp = Directory.systemTemp.createTempSync('mcp_harness'); + final Directory tmp = Directory.systemTemp.createTempSync('mcp_harness'); final db = FakeRtdb(); late final File tokens = File('${tmp.path}/tokens'); late final CliSession session; @@ -135,4 +135,4 @@ class McpHarness { /// The first full uuid in [text]. String idIn(String text) => - RegExp(r'[0-9a-f]{8}-[0-9a-f-]{27}').firstMatch(text)!.group(0)!; + RegExp('[0-9a-f]{8}-[0-9a-f-]{27}').firstMatch(text)!.group(0)!; diff --git a/test/mcp/token_store_test.dart b/test/mcp/token_store_test.dart new file mode 100644 index 0000000..93f8d5f --- /dev/null +++ b/test/mcp/token_store_test.dart @@ -0,0 +1,100 @@ +// The tokens file is read once and again only when its mtime or size changes. +// A read error keeps the last good set (an exhausted fd table once made every +// valid token read as 403); with no good load yet the answer is "unavailable". +import 'dart:io'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:todo/mcp/token_file.dart'; + +void main() { + late Directory tmp; + late File file; + late List logged; + late TokenStore store; + + setUp(() { + tmp = Directory.systemTemp.createTempSync('token_store'); + file = File('${tmp.path}/tokens') + ..writeAsStringSync('${tokenHash('good')} pc\n# note\n'); + logged = []; + store = TokenStore(file, log: logged.add); + }); + tearDown(() { + if (file.existsSync()) Process.runSync('chmod', ['600', file.path]); + tmp.deleteSync(recursive: true); + }); + + TokenVerdict check(String token) => store.verdict('Bearer $token'); + + /// Rewrites [file] and moves its mtime on, so the change is always seen. + void rewrite(String text) { + final before = file.lastModifiedSync(); + file + ..writeAsStringSync(text) + ..setLastModifiedSync(before.add(const Duration(seconds: 5))); + } + + test('a listed token is accepted, others and malformed headers rejected', () { + expect(check('good'), TokenVerdict.accepted); + expect(check('bad'), TokenVerdict.rejected); + expect(store.verdict(null), TokenVerdict.rejected); + expect(store.verdict('Basic good'), TokenVerdict.rejected); + expect(store.verdict('Bearer '), TokenVerdict.rejected); + }); + + test('[T-tokens-mtime] the file is not re-read while its mtime holds', () { + expect(check('good'), TokenVerdict.accepted); + final mtime = file.lastModifiedSync(); + // Same length, same mtime: only a re-read could notice the new hash. + file + ..writeAsStringSync('${tokenHash('other')} pc\n# note\n') + ..setLastModifiedSync(mtime); + expect(check('good'), TokenVerdict.accepted); + expect(check('other'), TokenVerdict.rejected); + }); + + test('a changed mtime reloads, so deleting a line revokes it', () { + expect(check('good'), TokenVerdict.accepted); + rewrite('# revoked\n'); + expect(check('good'), TokenVerdict.rejected); + }); + + test('[T-tokens-keep] an unreadable file after a good load keeps tokens', () { + expect(check('good'), TokenVerdict.accepted); + rewrite('${tokenHash('good')} pc\n${tokenHash('new')} pc2\n'); + Process.runSync('chmod', ['000', file.path]); + expect(check('good'), TokenVerdict.accepted); + expect(check('new'), TokenVerdict.rejected); + expect(logged, isNotEmpty); + }); + + test('a vanished file after a good load keeps the last set', () { + expect(check('good'), TokenVerdict.accepted); + file.deleteSync(); + expect(check('good'), TokenVerdict.accepted); + }); + + test('the file coming back readable is picked up again', () { + expect(check('good'), TokenVerdict.accepted); + rewrite('${tokenHash('new')} pc\n'); + Process.runSync('chmod', ['000', file.path]); + expect(check('new'), TokenVerdict.rejected); + Process.runSync('chmod', ['600', file.path]); + expect(check('new'), TokenVerdict.accepted); + expect(check('good'), TokenVerdict.rejected); + }); + + test('[T-tokens-503] no good load yet is unavailable, not rejected', () { + Process.runSync('chmod', ['000', file.path]); + expect(check('good'), TokenVerdict.unavailable); + expect(check('bad'), TokenVerdict.unavailable); + expect(logged, hasLength(1), reason: 'the same error is logged once'); + Process.runSync('chmod', ['600', file.path]); + expect(check('good'), TokenVerdict.accepted); + }); + + test('a missing file with no good load is unavailable', () { + file.deleteSync(); + expect(check('good'), TokenVerdict.unavailable); + }); +}