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 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWXgrX1QxVjqMiz6KFs
This commit is contained in:
Krzysztof Rudnicki 2026-11-16 07:59:31 +01:00
parent de5ad7d2dd
commit 0ce9c42ff6
7 changed files with 234 additions and 33 deletions

View File

@ -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<void> _tail = Future.value();

View File

@ -1,3 +1,4 @@
import 'dart:async';
import 'dart:io';
import 'package:mcp_dart/mcp_dart.dart';
@ -34,26 +35,43 @@ class TodoMcpServer {
/// `http://<host>:<bound port>/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<TodoMcpServer> 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<void> 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'),

View File

@ -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<String> _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 `<sha256> <name>` lines, `#` comments allowed.
final File file;
/// Receives read errors, one line each.
final void Function(String) log;
Set<String>? _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<String> _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));
}

View File

@ -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

View File

@ -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 {

View File

@ -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)!;

View File

@ -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<String> 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);
});
}