Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 0 additions & 1 deletion lib/src/archive_extractor.dart
Original file line number Diff line number Diff line change
Expand Up @@ -174,7 +174,6 @@ class ArchiveExtractionGuard {
static bool _looksAbsolute(String path) {
final normalized = path.replaceAll(r'\', '/');
return normalized.startsWith('/') ||
normalized.startsWith('//') ||
RegExp(r'^[A-Za-z]:/').hasMatch(normalized);
}

Expand Down
36 changes: 30 additions & 6 deletions lib/src/backup_models.dart
Original file line number Diff line number Diff line change
Expand Up @@ -58,12 +58,12 @@ class BackupRecord {

static BackupRecord fromJson(Map<String, Object?> json) {
return BackupRecord(
id: json['id'] as String,
notebookName: json['notebookName'] as String,
createdAt: DateTime.parse(json['createdAt'] as String),
archivePath: json['archivePath'] as String,
renderPath: json['renderPath'] as String,
pageCount: json['pageCount'] as int,
id: _requiredString(json, 'id'),
notebookName: _requiredString(json, 'notebookName'),
createdAt: _requiredDateTime(json, 'createdAt'),
archivePath: _requiredString(json, 'archivePath'),
renderPath: _requiredString(json, 'renderPath'),
pageCount: _requiredInt(json, 'pageCount'),
readablePath: json['readablePath'] as String?,
searchIndexPath: json['searchIndexPath'] as String?,
integrityManifestPath: json['integrityManifestPath'] as String?,
Expand All @@ -75,6 +75,30 @@ class BackupRecord {
);
}

static String _requiredString(Map<String, Object?> json, String key) {
final value = json[key];
if (value is String && value.trim().isNotEmpty) {
return value;
}
throw FormatException('Backup record missing required string "$key".');
}

static DateTime _requiredDateTime(Map<String, Object?> json, String key) {
final value = json[key];
if (value is String) {
return DateTime.parse(value);
}
throw FormatException('Backup record missing required date "$key".');
}

static int _requiredInt(Map<String, Object?> json, String key) {
final value = json[key];
if (value is int) {
return value;
}
throw FormatException('Backup record missing required integer "$key".');
}

BackupRecord copyWith({
String? id,
String? notebookName,
Expand Down
9 changes: 9 additions & 0 deletions lib/src/backup_parser.dart
Original file line number Diff line number Diff line change
Expand Up @@ -565,7 +565,16 @@ class BackupParser {
);
}

static const _allowedTables = {
'entry_parts',
'entry_part_versions',
'tree_nodes',
};

Future<Set<String>> _sqliteColumns(File db, String table) async {
if (!_allowedTables.contains(table)) {
throw ArgumentError.value(table, 'table', 'Table name not in allowlist');
}
final rows = await _sqliteRows(db, "PRAGMA table_info('$table')");
return rows
.map((row) => _stringValue(row['name']))
Expand Down
21 changes: 17 additions & 4 deletions lib/src/backup_service.dart
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,9 @@ class _ZipEntry {
class BackupService {
BackupService({Directory? root, SecureSecretStore? secretStore})
: root = root ?? _findProjectRoot(),
// Only read from the Keychain when using the default project root.
// A custom `root` means a test/debug environment where the Keychain
// should not be touched; fall back to DisabledSecretStore in that case.
_secretStore =
secretStore ??
(root == null && MacOSKeychainReadOnlySecretStore.isSupported
Expand Down Expand Up @@ -2367,6 +2370,7 @@ class BackupService {
onProgress: (receivedBytes, totalBytes) {
final shouldEmit =
receivedBytes == totalBytes ||
lastDownloadProgress == 0 ||
receivedBytes - lastDownloadProgress >= 25 * 1024 * 1024;
if (!shouldEmit) {
return;
Expand Down Expand Up @@ -3566,9 +3570,16 @@ class BackupService {
return;
}
try {
await Process.run('chmod', ['600', file.path]);
} catch (_) {
return;
final result = await Process.run('chmod', ['600', file.path]);
if (result.exitCode != 0) {
stderr.writeln(
'Warning: could not restrict permissions on ${file.path}: ${result.stderr}',
);
}
} catch (e) {
stderr.writeln(
'Warning: could not restrict permissions on ${file.path}: $e',
);
}
}

Expand Down Expand Up @@ -3743,7 +3754,9 @@ String _oneLine(String value) {
}

String _csv(String value) {
final escaped = value.replaceAll('"', '""');
final escaped = value
.replaceAll(RegExp(r'[\r\n]+'), ' ')
.replaceAll('"', '""');
return '"$escaped"';
}

Expand Down
1 change: 1 addition & 0 deletions lib/src/labarchives_client.dart
Original file line number Diff line number Diff line change
Expand Up @@ -246,6 +246,7 @@ class LabArchivesClient {
String _signatureFor(String method, String expires) {
final key = utf8.encode(accessKey);
final message = utf8.encode('$accessId$method$expires');
// SHA-1 is required by the LabArchives API signature scheme; not a free choice.
return base64Encode(Hmac(sha1, key).convert(message).bytes);
}

Expand Down
6 changes: 5 additions & 1 deletion lib/src/notebook_search_service.dart
Original file line number Diff line number Diff line change
Expand Up @@ -523,7 +523,11 @@ class NotebookSearchService {
final response = await request.close().timeout(
const Duration(seconds: 90),
);
final responseBody = await utf8.decoder.bind(response).join();
// Timeout the body read independently; response.close() only covers headers.
final responseBody = await utf8.decoder
.bind(response)
.join()
.timeout(const Duration(seconds: 120));
if (response.statusCode < 200 || response.statusCode >= 300) {
throw AiApiHttpException(response.statusCode, responseBody);
}
Expand Down
2 changes: 1 addition & 1 deletion lib/src/readable_notebook_exporter.dart
Original file line number Diff line number Diff line change
Expand Up @@ -240,7 +240,7 @@ class ReadableNotebookExporter {
List<String> _splitText(String text, {required int maxChars}) {
final clean = text.trim();
if (clean.isEmpty) {
return const [''];
return const [];
}
if (clean.length <= maxChars) {
return [clean];
Expand Down
3 changes: 3 additions & 0 deletions lib/src/secure_secret_store.dart
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,9 @@ class DisabledSecretStore implements SecureSecretStore {
}) async {}
}

// "ReadOnly" refers to write operations from the CLI: secrets must be written
// via the BenchVault app. The delete() method is intentionally included because
// removing a stale credential from the Keychain is a safe CLI operation.
class MacOSKeychainReadOnlySecretStore implements SecureSecretStore {
const MacOSKeychainReadOnlySecretStore();

Expand Down
2 changes: 1 addition & 1 deletion scripts/labarchives_auth_flow.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ def load_env(path: Path) -> Dict[str, str]:

def sign(access_id: str, access_key: str, method: str, expires_ms: str) -> str:
message = f"{access_id}{method}{expires_ms}".encode("utf-8")
digest = hmac.new(access_key.encode("utf-8"), message, hashlib.sha1).digest()
digest = hmac.digest(access_key.encode("utf-8"), message, hashlib.sha1)
return base64.b64encode(digest).decode("ascii")


Expand Down
76 changes: 76 additions & 0 deletions test/backup_models_test.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
import 'dart:convert';
import 'dart:io';

import 'package:benchvault/src/backup_models.dart';
import 'package:benchvault/src/backup_service.dart';
import 'package:flutter_test/flutter_test.dart';

void main() {
test('backup records reject missing required fields', () {
final valid = <String, Object?>{
'id': 'run_001_demo_lab',
'notebookName': 'Demo Lab Notebook',
'createdAt': '2026-05-14T12:00:00.000Z',
'archivePath': 'notebooks/demo_lab/2026/05/14/run_001/notebook.7z',
'renderPath':
'notebooks/demo_lab/2026/05/14/run_001/render_notebook.json',
'pageCount': 3,
};

for (final key in [
'id',
'notebookName',
'createdAt',
'archivePath',
'renderPath',
'pageCount',
]) {
final malformed = Map<String, Object?>.of(valid)..remove(key);

expect(
() => BackupRecord.fromJson(malformed),
throwsA(isA<FormatException>()),
reason: 'missing $key should not be accepted as a blank/default value',
);
}
});

test('loadBackups skips malformed backup records', () async {
final root = await Directory.systemTemp.createTemp(
'benchvault_bad_record_test_',
);
addTearDown(() => root.delete(recursive: true));

final service = BackupService(root: root);
final goodRun = Directory('${root.path}/backups/good');
final badRun = Directory('${root.path}/backups/bad');
await goodRun.create(recursive: true);
await badRun.create(recursive: true);

final record = BackupRecord(
id: 'run_001_demo_lab',
notebookName: 'Demo Lab Notebook',
createdAt: DateTime.utc(2026, 5, 14),
archivePath: 'good/notebook.7z',
renderPath: 'good/render_notebook.json',
pageCount: 1,
);
await File('${goodRun.path}/backup_record.json').writeAsString(
const JsonEncoder.withIndent(' ').convert(record.toJson()),
);
await File('${badRun.path}/backup_record.json').writeAsString(
jsonEncode({
'id': 'run_002_corrupt',
'notebookName': 'Corrupt record',
'createdAt': '2026-05-14T12:00:00.000Z',
'archivePath': 'bad/notebook.7z',
'pageCount': 1,
}),
);

final records = await service.loadBackups();

expect(records, hasLength(1));
expect(records.single.id, 'run_001_demo_lab');
});
}
Loading