diff --git a/scripts/test_queue_dart.py b/scripts/test_queue_dart.py index 7cdea71..481d55b 100644 --- a/scripts/test_queue_dart.py +++ b/scripts/test_queue_dart.py @@ -12,7 +12,7 @@ def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('--flutter', default='flutter') parser.add_argument('--widgets', action='store_true', help='Also render production GPU monitor widgets on the CPU Flutter test engine') - parser.add_argument('--ssh-bundle', action='store_true', help='Verify ZIP parsing, private key matching and protected SSH configuration') + parser.add_argument('--ssh-bundle', action='store_true', help='Verify ZIP parsing, private key matching, protected SSH configuration and device leases') parser.add_argument('--offline', action='store_true', help='Use already cached pub dependencies') args = parser.parse_args() build = ROOT/'build' @@ -22,7 +22,7 @@ def main(): (harness/'test').mkdir() ui = ' material_ui: 1.5.0\n cupertino_ui: 1.1.1\n url_launcher: 6.3.2\n clock: ^1.1.3\n' if args.widgets else '' if args.ssh_bundle: - ui += f' archive: ^4.3.0\n crypto: ^3.0.0\n pointycastle: ^4.0.0\n pinenacl: ^0.6.0\n dartssh2:\n path: "{ROOT / "serverbox/packages/dartssh2"}"\n' + ui += f' archive: ^4.3.0\n crypto: ^3.0.0\n path: ^1.9.1\n pointycastle: ^4.0.0\n pinenacl: ^0.6.0\n dartssh2:\n path: "{ROOT / "serverbox/packages/dartssh2"}"\n' (harness/'pubspec.yaml').write_text("name: queue_protocol_checks\nenvironment:\n sdk: '>=3.11.0 <4.0.0'\ndependencies:\n flutter:\n sdk: flutter\n"+ui+"dev_dependencies:\n flutter_test:\n sdk: flutter\nflutter:\n uses-material-design: true\n") names = ['queue_protocol_test.dart', 'queue_session_test.dart', 'queue_presentation_test.dart', 'mac_update_release_test.dart', 'mac_update_bridge_test.dart', 'local_calendar_test.dart', 'result_preview_test.dart'] if args.widgets: @@ -31,8 +31,9 @@ def main(): source = (ROOT/'serverbox/test/unit/app'/name).read_text() (harness/'test'/name).write_text(source) if args.ssh_bundle: - (harness/'test/client_bundle_test.dart').write_text((ROOT/'serverbox/test/unit/ssh/client_bundle_test.dart').read_text()) - (harness/'test/device_login_test.dart').write_text((ROOT/'serverbox/test/unit/ssh/device_login_test.dart').read_text()) + for name in ['client_bundle_test.dart', 'device_login_test.dart', 'device_lease_test.dart']: + source = (ROOT/'serverbox/test/unit/ssh'/name).read_text() + (harness/'test'/name).write_text(source) subprocess.run([args.flutter, 'pub', 'get', *(['--offline'] if args.offline else [])], cwd=harness, check=True) # Resolve the real production library; no copies, mocks, or native app # hooks. Only the small declared dependency graph is built by this harness. diff --git a/serverbox/lib/core/ssh_bundle/device_lease.dart b/serverbox/lib/core/ssh_bundle/device_lease.dart new file mode 100644 index 0000000..0132c39 --- /dev/null +++ b/serverbox/lib/core/ssh_bundle/device_lease.dart @@ -0,0 +1,84 @@ +import 'dart:convert'; +import 'dart:io'; + +import 'package:path/path.dart' as p; + +enum DeviceLeaseState { valid, expired, revoked } + +/// The displayable part of a locally installed Feishu device record. +class DeviceLease { + const DeviceLease._(this.state, this.expiresAt); + + final DeviceLeaseState state; + final DateTime? expiresAt; + + static const _maxFileBytes = 8192; + static const _maxEpochSeconds = 8640000000000; // DateTime's range. + + /// Returns null when the SSH key has no recognizable device lease. + static DeviceLease? read( + String keyPath, { + required String bundlesRoot, + DateTime? now, + }) { + final root = p.normalize(bundlesRoot); + final device = p.dirname(keyPath); + final name = p.basename(device); + if (!p.isAbsolute(root) || + keyPath.contains('\u0000') || + !name.startsWith('device-') || + name == 'device-' || + keyPath != p.join(root, name, 'identity')) { + return null; + } + final session = p.join(device, 'session.json'); + try { + if (FileSystemEntity.typeSync(root, followLinks: false) != + FileSystemEntityType.directory || + FileSystemEntity.typeSync(device, followLinks: false) != + FileSystemEntityType.directory || + FileSystemEntity.typeSync(keyPath, followLinks: false) != + FileSystemEntityType.file || + FileSystemEntity.typeSync(session, followLinks: false) != + FileSystemEntityType.file || + File(keyPath).lengthSync() > _maxFileBytes) { + return null; + } + + final record = File(session).openSync(); + try { + if (record.lengthSync() > _maxFileBytes) return null; + final bytes = record.readSync(_maxFileBytes + 1); + if (bytes.length > _maxFileBytes) return null; + final data = jsonDecode(utf8.decode(bytes)); + if (data is! Map) return null; + + final seconds = data['lease_expires_at']; + final expiresAt = + seconds is int && + seconds >= -_maxEpochSeconds && + seconds <= _maxEpochSeconds + ? DateTime.fromMillisecondsSinceEpoch(seconds * 1000) + : null; + final revoked = data['revoked']; + if (revoked == true) { + return DeviceLease._(DeviceLeaseState.revoked, expiresAt); + } + if (expiresAt == null || (revoked != null && revoked is! bool)) { + return null; + } + + final state = expiresAt.isAfter(now ?? DateTime.now()) + ? DeviceLeaseState.valid + : DeviceLeaseState.expired; + return DeviceLease._(state, expiresAt); + } finally { + record.closeSync(); + } + } on FileSystemException { + return null; + } on FormatException { + return null; + } + } +} diff --git a/serverbox/lib/view/page/server/card/notices.dart b/serverbox/lib/view/page/server/card/notices.dart index 01d0c0b..881ab60 100644 --- a/serverbox/lib/view/page/server/card/notices.dart +++ b/serverbox/lib/view/page/server/card/notices.dart @@ -1,10 +1,15 @@ +import 'dart:async'; import 'dart:ui' show lerpDouble; import 'package:fl_lib/fl_lib.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:intl/intl.dart' show DateFormat; import 'package:material_ui/material_ui.dart'; import 'package:server_box/core/extension/context/locale.dart'; import 'package:server_box/core/extension/server.dart'; +import 'package:server_box/core/ssh_bundle/device_lease.dart'; +import 'package:server_box/data/model/app/error.dart'; +import 'package:server_box/data/model/server/server.dart'; import 'package:server_box/data/model/server/server_private_info.dart'; import 'package:server_box/data/model/server/try_limiter.dart'; import 'package:server_box/data/provider/server/all.dart'; @@ -15,6 +20,7 @@ import 'package:server_box/view/page/server/card/metric.dart'; import 'package:server_box/view/page/server/card/sizes.dart'; import 'package:server_box/view/page/server/metric_row.dart'; import 'package:server_box/view/page/server/reading_text.dart'; +import 'package:server_box/view/widget/feishu_server_setup.dart'; // --- The states that are not a body --- // @@ -37,6 +43,9 @@ enum ServerNoticeKind { /// Reaching it failed, and the machine said why. failed, + /// The SSH device authorization has expired or was revoked. + feishuLease, + /// Nothing yet, and something on its way. connecting, @@ -49,8 +58,7 @@ enum ServerNoticeKind { /// /// One set of words for the card in the list and for the page it opens /// into, because the block that says them is one widget at two sizes — see -/// [ServerCardNotice]. The actions are the page's alone: they act on the -/// machine, and a card has nowhere to put them. +/// [ServerCardNotice]. class ServerNotice { const ServerNotice({ required this.kind, @@ -59,17 +67,18 @@ class ServerNotice { this.text = '', this.mono = '', this.hint = '', - }); + bool feishuAuthFailed = false, + }) : _feishuAuthFailed = feishuAuthFailed; final ServerNoticeKind kind; + final bool _feishuAuthFailed; final IconData glyph; /// What went wrong, in this app's words. final String title; - /// A sentence under the title, which the page has room for and a card has - /// not. + /// A sentence under the title. final String text; /// What the machine said, as it said it — the only part a search engine @@ -79,8 +88,12 @@ class ServerNotice { /// A line under the page's actions. final String hint; + bool canReloginFeishu({bool? onMacOS}) => + (onMacOS ?? isMacOS) && + (kind == ServerNoticeKind.feishuLease || _feishuAuthFailed); + /// Which state this machine is in, and what to say about it. - static ServerNotice of(ServerState srv) { + static ServerNotice of(ServerState srv, {String? deviceBundlesRoot}) { // Asked before the error is read: a connection this app has not been // allowed to make has not been tried, so whatever else is on `err` is // about an earlier address or an earlier setting. @@ -103,12 +116,37 @@ class ServerNotice { ); } final err = srv.status.err; + final keyPath = srv.spi.sshOn?.keyPath; + final lease = + keyPath != null && (err != null || srv.conn < ServerConn.connected) + ? DeviceLease.read( + keyPath, + bundlesRoot: deviceBundlesRoot ?? '${Paths.doc}/ssh-client-bundles', + ) + : null; + if (lease != null && lease.state != DeviceLeaseState.valid) { + final revoked = lease.state == DeviceLeaseState.revoked; + final expiresAt = lease.expiresAt; + final expiry = expiresAt == null + ? '' + : '${revoked ? '原授权' : '授权'}到期时间:' + '${DateFormat('yyyy-MM-dd HH:mm').format(expiresAt.toLocal())}。'; + return ServerNotice( + kind: ServerNoticeKind.feishuLease, + glyph: Icons.lock_outline, + title: revoked ? '此设备的飞书授权已退出' : '飞书登录授权已过期', + text: '$expiry重新通过飞书登录可恢复服务器状态监控。', + mono: err?.message ?? '', + ); + } if (err != null) { return ServerNotice( kind: ServerNoticeKind.failed, glyph: Icons.link_off, title: err.solution ?? libL10n.fail, mono: err.message ?? '', + feishuAuthFailed: + lease != null && err is SSHErr && err.type == SSHErrType.auth, ); } // `connected` counts as busy: the SSH path sits there through system @@ -138,21 +176,37 @@ class ServerNotice { /// What the card in the list says about this machine, or null when it says /// nothing. /// - /// Only a failure it has seen. Waiting is said by the spinner beside the - /// name, and a machine that answered with nothing is a name with nothing - /// under it. A prompt from the far end is not a failure to report either: - /// the card offers a lock rather than a retry — see - /// `ServerStateUi.needsInteractiveAuth`. + /// A recorded failure or a device lease that needs attention. Other + /// interactive authentication prompts use the lock beside the name. /// /// The page asks this too, of the block it holds room for: what the card /// draws, the page paints only at the handover; what the card does not, /// the page brings in itself — see `ServerDetailPage.readingsShowing`. - static ServerNotice? onCard(ServerState srv) { - if (srv.status.err == null || srv.needsInteractiveAuth) return null; - return of(srv); + static ServerNotice? onCard(ServerState srv, {String? deviceBundlesRoot}) { + if (srv.status.err == null && + (!(srv.conn < ServerConn.connected) || + srv.spi.sshOn?.keyPath == null)) { + return null; + } + final notice = of(srv, deviceBundlesRoot: deviceBundlesRoot); + if (notice.kind == ServerNoticeKind.feishuLease || + (srv.status.err != null && !srv.needsInteractiveAuth)) { + return notice; + } + return null; } } +Widget feishuReloginButton(BuildContext context, {bool inErrorDialog = false}) { + return TextButton( + onPressed: () { + if (inErrorDialog) context.popDialog(); + unawaited(FeishuServerSetup.open(context)); + }, + child: const Text('重新飞书登录'), + ); +} + /// What the page draws a notice as, which is where a card's block is going. /// /// Decided from where the card is going rather than from where it is, the @@ -201,7 +255,7 @@ class ServerCardNotice extends StatelessWidget { /// What a press does once this is the page's, in the /// [ServerNoticeForm.card] form: the whole error, with what the app was /// doing and the copy button a bug report needs. Null on a card, where the - /// card's own tap is the one that counts. + /// parent handles navigation and the Feishu button opens sign-in directly. final VoidCallback? onTap; /// Around the block at rest. @@ -245,6 +299,7 @@ class ServerCardNotice extends StatelessWidget { /// own. Widget _page(BuildContext context, double t) { final scheme = Theme.of(context).colorScheme; + final feishuLease = notice.kind == ServerNoticeKind.feishuLease; // From the left of a card's block to the middle of the page. The lines // of a title that wraps follow at the halfway point, by which the card is // wide enough that none does. @@ -334,25 +389,32 @@ class ServerCardNotice extends StatelessWidget { crossAxisAlignment: CrossAxisAlignment.stretch, children: [ title, - // The page's sentence under the title, which a card has no room - // for: it grows in from nothing, so what is under it travels - // rather than arriving lower by its height. + // A device lease explanation is visible at both sizes. if (notice.text.isNotEmpty) ServerCardReveal( - shown: t, + shown: feishuLease ? 1 : t, child: Padding( - padding: const EdgeInsets.only(top: 13), + padding: EdgeInsets.only( + top: feishuLease ? lerpDouble(3, 13, t)! : 13, + ), child: Text( notice.text, textAlign: textAlign, style: UIs.textGrey, + maxLines: feishuLease && t < 1 ? 3 : null, + overflow: feishuLease && t < 1 ? TextOverflow.ellipsis : null, ), ), ), - if (mono != null) ...[ - SizedBox(height: lerpDouble(3, 13, t)), - mono, - ], + if (mono != null) ...[SizedBox(height: lerpDouble(3, 13, t)), mono], + if (notice.canReloginFeishu() && t < 1) + ServerCardReveal( + shown: 1 - t, + child: Align( + alignment: AlignmentDirectional.centerStart, + child: feishuReloginButton(context), + ), + ), ], ), ); @@ -408,6 +470,10 @@ class ServerCardNotice extends StatelessWidget { maxLines: 2, overflow: TextOverflow.ellipsis, ), + if (notice.kind == ServerNoticeKind.feishuLease) ...[ + const SizedBox(height: 3), + Text(notice.text, style: UIs.textGrey), + ], if (notice.mono.isNotEmpty) ...[ const SizedBox(height: 3), Text( @@ -421,24 +487,33 @@ class ServerCardNotice extends StatelessWidget { ); final body = Padding( padding: EdgeInsets.lerp(_pad, ServerCardSizes.focusPad, t)!, - child: Row( + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, children: [ - Expanded(child: words), - // The page's card is a way in as well as a line, and says so. On - // a card there is no room to say it and nothing it would lead to - // that tapping the card does not. - SizedBox(width: 9 * t), - SizedBox( - width: 17 * t, - child: Opacity( - opacity: t, - child: const Icon( - Icons.chevron_right, - size: 17, - color: Colors.grey, - ), - ), + Row( + children: [ + Expanded(child: words), + // The page's card is a way in as well as a line, and says so. + if (notice.kind != ServerNoticeKind.feishuLease || + notice.mono.isNotEmpty || + onTap != null) ...[ + SizedBox(width: 9 * t), + SizedBox( + width: 17 * t, + child: Opacity( + opacity: t, + child: const Icon( + Icons.chevron_right, + size: 17, + color: Colors.grey, + ), + ), + ), + ], + ], ), + if (notice.canReloginFeishu()) feishuReloginButton(context), ], ), ); diff --git a/serverbox/lib/view/page/server/detail/notices.dart b/serverbox/lib/view/page/server/detail/notices.dart index 044ef60..a4dc659 100644 --- a/serverbox/lib/view/page/server/detail/notices.dart +++ b/serverbox/lib/view/page/server/detail/notices.dart @@ -35,7 +35,9 @@ extension on _ServerDetailPageState { form: ServerNoticeForm.page, openness: 1, ), - byCard: ServerNotice.onCard(si) != null, + byCard: + notice.kind == ServerNoticeKind.feishuLease || + ServerNotice.onCard(si) != null, from: const Offset(0, 24), ), _entering( @@ -117,7 +119,8 @@ extension on _ServerDetailPageState { ), edit, ], - ServerNoticeKind.failed => [ + ServerNoticeKind.failed || ServerNoticeKind.feishuLease => [ + if (notice.canReloginFeishu()) feishuReloginButton(context), retry, // The title above is the error's own line; this is everything // around it — what the app was doing, and the copy button a bug @@ -125,7 +128,7 @@ extension on _ServerDetailPageState { if (si.status.err case final err?) Btn.text( text: l10n.viewError, - onTap: () => _showErrDetail(si, err), + onTap: () => _showErrDetail(si, err, notice), ), edit, ], @@ -136,9 +139,12 @@ extension on _ServerDetailPageState { } /// The error as markdown: what to do about it, then what was actually said. - String _errMarkdown(Err err) { + String _errMarkdown(Err err, ServerNotice notice) { + final solution = notice.kind == ServerNoticeKind.feishuLease + ? notice.text + : err.solution ?? libL10n.unknown; return ''' -${err.solution ?? libL10n.unknown} +$solution ```sh ${err.message ?? 'null'} @@ -220,27 +226,33 @@ ${err.message ?? 'null'} /// showing the last successful one — stale data with a visible reason /// beats a blank page. /// - /// The block the card in the list draws, at the far end of its movement — - /// see [ServerNoticeForm.card]. Pressing it is the way to the whole error. + /// The block the card in the list draws, at the far end of its movement. + /// An error opens the full diagnostics. A disconnected device can still + /// explain its lease and offer to sign in again. Widget? _buildErrCard(ServerState si) { final err = si.status.err; - if (err == null) return null; + final notice = err == null ? ServerNotice.onCard(si) : ServerNotice.of(si); + if (notice == null) return null; return ServerCardNotice( - notice: ServerNotice.of(si), + notice: notice, form: ServerNoticeForm.card, openness: 1, - onTap: () => _showErrDetail(si, err), + onTap: err == null ? null : () => _showErrDetail(si, err, notice), ); } /// A server that has reported before shows its failure here rather than on /// the empty page, so the same one-tap answer has to be offered in both. - void _showErrDetail(ServerState si, Err err) { - final md = _errMarkdown(err); + void _showErrDetail(ServerState si, Err err, ServerNotice notice) { + final md = _errMarkdown(err, notice); context.showRoundDialog( - title: libL10n.error, + title: notice.kind == ServerNoticeKind.feishuLease + ? notice.title + : libL10n.error, child: SingleChildScrollView(child: SimpleMarkdown(data: md)), actions: [ + if (notice.canReloginFeishu()) + feishuReloginButton(context, inErrorDialog: true), if (si.spi.monitorHttp?.needsInsecureOptIn == true) TextButton( // Closes the dialog itself and leaves the work to the page: an diff --git a/serverbox/test/unit/server/server_notice_test.dart b/serverbox/test/unit/server/server_notice_test.dart new file mode 100644 index 0000000..4e9ec8c --- /dev/null +++ b/serverbox/test/unit/server/server_notice_test.dart @@ -0,0 +1,141 @@ +import 'dart:convert'; +import 'dart:io'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:path/path.dart' as p; +import 'package:server_box/core/extension/context/locale.dart'; +import 'package:server_box/data/model/app/error.dart'; +import 'package:server_box/data/model/server/server.dart'; +import 'package:server_box/data/provider/server/single.dart'; +import 'package:server_box/data/res/status.dart'; +import 'package:server_box/view/page/server/card/notices.dart'; + +import '../../helpers/spi_fixture.dart'; + +void main() { + late Directory scratch; + late File identity; + late File session; + const authError = SSHErr( + type: SSHErrType.auth, + message: 'Synthetic SSH authentication error', + ); + const connectError = SSHErr( + type: SSHErrType.connect, + message: 'Synthetic SSH connection error', + ); + + setUp(() { + scratch = Directory.systemTemp.createTempSync('server-notice-'); + final device = Directory(p.join(scratch.path, 'device-example')) + ..createSync(); + identity = File(p.join(device.path, 'identity'))..createSync(); + session = File(p.join(device.path, 'session.json')); + }); + + tearDown(() => scratch.deleteSync(recursive: true)); + + void writeLease(DateTime expiresAt, {bool revoked = false}) { + session.writeAsStringSync( + jsonEncode({ + 'lease_expires_at': expiresAt.millisecondsSinceEpoch ~/ 1000, + 'revoked': revoked, + }), + ); + } + + ServerState server({ + String? keyPath, + SSHErr? err, + ServerConn conn = ServerConn.disconnected, + bool sshEnabled = true, + }) => ServerState( + spi: spiFixture( + name: 'Example Server', + ip: 'server.example.test', + user: 'example-user', + keyPath: keyPath ?? identity.path, + ).copyWith(sshEnabled: sshEnabled), + status: InitStatus.status..err = err, + conn: conn, + ); + + test('expired device notice explains recovery and keeps SSH diagnostics', () { + writeLease(DateTime.utc(2000)); + final srv = server(err: connectError, conn: ServerConn.failed); + final notice = ServerNotice.of(srv, deviceBundlesRoot: scratch.path); + final card = ServerNotice.onCard(srv, deviceBundlesRoot: scratch.path); + + expect(notice.kind, ServerNoticeKind.feishuLease); + expect(notice.title, '飞书登录授权已过期'); + expect(notice.text, contains('授权到期时间')); + expect(notice.text, contains('重新通过飞书登录可恢复服务器状态监控')); + expect(notice.mono, connectError.message); + expect(card?.title, notice.title); + expect(notice.canReloginFeishu(onMacOS: true), isTrue); + expect(notice.canReloginFeishu(onMacOS: false), isFalse); + }); + + test('device logout is visible on the card even before an SSH error', () { + writeLease(DateTime.utc(2100), revoked: true); + final srv = server(); + final notice = ServerNotice.of(srv, deviceBundlesRoot: scratch.path); + final card = ServerNotice.onCard(srv, deviceBundlesRoot: scratch.path); + + expect(notice.title, '此设备的飞书授权已退出'); + expect(notice.mono, isEmpty); + expect(card?.title, notice.title); + expect(notice.canReloginFeishu(onMacOS: true), isTrue); + }); + + test('still-authorized devices offer sign-in only for SSH auth errors', () { + writeLease(DateTime.utc(2100)); + final authFailure = ServerNotice.of( + server(err: authError), + deviceBundlesRoot: scratch.path, + ); + final connectionFailure = ServerNotice.of( + server(err: connectError), + deviceBundlesRoot: scratch.path, + ); + + expect(authFailure.kind, ServerNoticeKind.failed); + expect(authFailure.title, l10n.authFailTip); + expect(authFailure.canReloginFeishu(onMacOS: true), isTrue); + expect(authFailure.canReloginFeishu(onMacOS: false), isFalse); + expect(connectionFailure.canReloginFeishu(onMacOS: true), isFalse); + }); + + test('ordinary SSH auth errors keep their existing text and diagnostics', () { + final ordinary = p.join(scratch.path, 'id_example'); + final notice = ServerNotice.onCard( + server(keyPath: ordinary, err: authError), + deviceBundlesRoot: scratch.path, + )!; + + expect(notice.kind, ServerNoticeKind.failed); + expect(notice.title, l10n.authFailTip); + expect(notice.mono, authError.message); + expect(notice.canReloginFeishu(onMacOS: true), isFalse); + }); + + test( + 'a ready connection or disabled SSH does not report lease expiration', + () { + writeLease(DateTime.utc(2000)); + expect( + ServerNotice.onCard( + server(conn: ServerConn.finished), + deviceBundlesRoot: scratch.path, + ), + isNull, + ); + final disabled = ServerNotice.of( + server(err: connectError, sshEnabled: false), + deviceBundlesRoot: scratch.path, + ); + expect(disabled.kind, ServerNoticeKind.failed); + expect(disabled.canReloginFeishu(onMacOS: true), isFalse); + }, + ); +} diff --git a/serverbox/test/unit/ssh/device_lease_test.dart b/serverbox/test/unit/ssh/device_lease_test.dart new file mode 100644 index 0000000..068a419 --- /dev/null +++ b/serverbox/test/unit/ssh/device_lease_test.dart @@ -0,0 +1,158 @@ +import 'dart:convert'; +import 'dart:io'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:path/path.dart' as p; +import 'package:server_box/core/ssh_bundle/device_lease.dart'; + +void main() { + late Directory scratch; + late String root; + late Directory device; + late File identity; + late File session; + final expiresAt = DateTime.utc(2030, 1, 2, 3, 4); + final expiresAtSeconds = expiresAt.millisecondsSinceEpoch ~/ 1000; + + setUp(() { + scratch = Directory.systemTemp.createTempSync('device-lease-'); + root = p.join(scratch.path, 'ssh-client-bundles'); + device = Directory(p.join(root, 'device-example')) + ..createSync(recursive: true); + identity = File(p.join(device.path, 'identity'))..createSync(); + session = File(p.join(device.path, 'session.json')); + }); + + tearDown(() => scratch.deleteSync(recursive: true)); + + DeviceLease? read({String? keyPath, DateTime? now}) => DeviceLease.read( + keyPath ?? identity.path, + bundlesRoot: root, + now: now ?? expiresAt, + ); + + test('lease exposes its expiration and expires at the exact boundary', () { + session.writeAsStringSync( + jsonEncode({ + 'lease_expires_at': expiresAtSeconds, + 'server_id': 'server-example', + 'username': 'example-user', + 'code_verifier': 'synthetic-verifier', + }), + ); + final lease = read( + now: expiresAt.subtract(const Duration(milliseconds: 1)), + )!; + + expect(lease.state, DeviceLeaseState.valid); + expect(lease.expiresAt!.toUtc(), expiresAt); + expect(lease.toString(), isNot(contains('synthetic-verifier'))); + expect(read()!.state, DeviceLeaseState.expired); + expect( + read(now: expiresAt.add(const Duration(milliseconds: 1)))!.state, + DeviceLeaseState.expired, + ); + }); + + test('explicit revocation takes precedence and can stand on its own', () { + session.writeAsStringSync( + jsonEncode({'lease_expires_at': expiresAtSeconds, 'revoked': true}), + ); + final afterExpiry = read()!; + expect(afterExpiry.state, DeviceLeaseState.revoked); + expect(afterExpiry.expiresAt!.toUtc(), expiresAt); + expect( + read(now: expiresAt.subtract(const Duration(days: 1)))!.state, + DeviceLeaseState.revoked, + ); + + session.writeAsStringSync('{"revoked":true}'); + expect(read()!.state, DeviceLeaseState.revoked); + expect(read()!.expiresAt, isNull); + }); + + test('ordinary keys and paths outside the expected layout are ignored', () { + session.writeAsStringSync('{"revoked":true}'); + final ordinary = Directory(p.join(root, 'ordinary-ssh'))..createSync(); + final nonDeviceKey = File(p.join(ordinary.path, 'identity'))..createSync(); + File(p.join(ordinary.path, 'session.json')) + .writeAsStringSync('{"revoked":true}'); + + final sibling = Directory(p.join('$root-other', 'device-example')) + ..createSync(recursive: true); + final siblingKey = File(p.join(sibling.path, 'identity'))..createSync(); + File(p.join(sibling.path, 'session.json')) + .writeAsStringSync('{"revoked":true}'); + final traversingKey = p.join( + ordinary.path, + '..', + 'device-example', + 'identity', + ); + + expect(read(keyPath: nonDeviceKey.path), isNull); + expect(read(keyPath: siblingKey.path), isNull); + expect(read(keyPath: traversingKey), isNull); + }); + + test('missing, malformed and unsafe lease records are ignored', () { + expect(read(), isNull); + for (final contents in [ + '{', + '[]', + '{"expires_at":$expiresAtSeconds}', + '{"lease_expires_at":"$expiresAtSeconds"}', + '{"lease_expires_at":9223372036854775807}', + '{"lease_expires_at":$expiresAtSeconds,"revoked":"true"}', + ]) { + session.writeAsStringSync(contents); + expect(read(), isNull, reason: contents); + } + session.writeAsBytesSync([0xff]); + expect(read(), isNull); + }); + + test('files are limited to 8192 bytes', () { + session.writeAsStringSync('{"revoked":true}'.padRight(8192)); + expect(read()!.state, DeviceLeaseState.revoked); + session.writeAsStringSync('{"revoked":true}'.padRight(8193)); + expect(read(), isNull); + + session.writeAsStringSync('{"revoked":true}'); + identity.writeAsStringSync(' '.padRight(8193)); + expect(read(), isNull); + }); + + test( + 'links are ignored at every level of the bundle', + () { + session.writeAsStringSync('{"revoked":true}'); + final target = session.renameSync('${session.path}.other'); + final sessionLink = Link(session.path)..createSync(target.path); + expect(read(), isNull); + sessionLink.deleteSync(); + target.renameSync(session.path); + + final key = identity.renameSync('${identity.path}.other'); + final keyLink = Link(identity.path)..createSync(key.path); + expect(read(), isNull); + keyLink.deleteSync(); + key.renameSync(identity.path); + + final movedDevice = device.renameSync( + p.join(scratch.path, 'device-other'), + ); + final deviceLink = Link(device.path)..createSync(movedDevice.path); + expect(read(), isNull); + deviceLink.deleteSync(); + movedDevice.renameSync(device.path); + + final movedRoot = Directory(root).renameSync('$root-other'); + Link(root).createSync(movedRoot.path); + expect(read(), isNull); + }, + skip: Platform.isWindows + ? 'Windows link creation requires extra privileges' + : false, + ); +}