1module cli23import os4import compress.zlib5import crypto.sha2566import json27import src.exchange8import src.release9import src.remote10import src.events11import src.history12import src.machine13import src.snapshot14import src.storage1516fn testsuite_begin() {17 os.setenv('HOME', os.join_path(os.temp_dir(), 'koh3-test-home-${os.getpid()}'), true)18}1920fn test_doctor_checks_cycles_and_missing_heads_without_walking_forever() {21 saves := [history.Save{ id: 'aaaaaaaaaaaa', parent: 'bbbbbbbbbbbb' },22 history.Save{ id: 'bbbbbbbbbbbb', parent: 'aaaaaaaaaaaa' }]23 assert doctor_history(saves, 'cccccccccccc').any(it.contains('head'))24 assert doctor_history(saves, 'aaaaaaaaaaaa').any(it.contains('cycle'))25 assert doctor_history([history.Save{ id: 'aaaaaaaaaaaa', parent: 'cccccccccccc' }],26 'aaaaaaaaaaaa').any(it.contains('missing parent'))27 assert doctor_history([]history.Save{}, '').len == 028 assert doctor_history([history.Save{ id: 'aaaaaaaaaaaa' }], '').any(it.contains('no head'))29}3031fn test_doctor_checks_off_line_paths_and_file_directory_collisions() {32 mut report := DoctorJson{}33 doctor_files('aaaaaaaaaaaa', [snapshot.FileEntry{ path: '../unsafe' },34 snapshot.FileEntry{ path: 'a' }, snapshot.FileEntry{ path: 'a/b' }], []events.Event{},35 mut report)36 assert report.problems.any(it.contains('unsafe path'))37 assert report.problems.any(it.contains('file and a directory'))38}3940fn test_doctor_reports_unsafe_save_paths_with_a_quoted_strip_command() {41 dir := os.join_path(os.temp_dir(), 'koh3_doctor_paths_${os.getpid()}')42 os.rmdir_all(dir) or {}43 os.mkdir_all(dir)!44 defer {45 os.rmdir_all(dir) or {}46 }47 store := storage.create(dir)!48 defer {49 store.close()50 }51 hash := store.put_object('unsafe'.bytes())!52 store.begin()!53 history.import_save(store, history.Save{54 id: 'badbadbadbad'55 }, [snapshot.FileEntry{56 path: "../June's file"57 hash: hash58 }])!59 history.set_head(store, 'badbadbadbad')!60 store.end()!61 mut report := DoctorJson{}62 doctor_files('badbadbadbad', history.files_of(store, 'badbadbadbad')!, []events.Event{}, mut report)63 assert report.problems == [64 "save [badbadbadbad] has unsafe path ../June's file — koh strip '../June'\\''s file'",65 ]66}6768struct DoctorReadOnly {69mut:70 items map[string][]u871}7273fn (mut backend DoctorReadOnly) get(key string) !remote.Object {74 if body := backend.items[key] {75 return remote.Object{ found: true, body: body }76 }77 return remote.Object{}78}7980fn (mut backend DoctorReadOnly) list(prefix string) ![]string {81 return backend.items.keys().filter(it.starts_with('${prefix}/'))82}8384fn (mut backend DoctorReadOnly) list_dirs(prefix string) ![]string {85 return dirs_of(backend.list(prefix)!, prefix)86}8788fn dirs_of(keys []string, prefix string) []string {89 mut names := map[string]bool{}90 for key in keys {91 rest := key[prefix.len..].trim_left('/')92 if rest.contains('/') {93 names[rest.all_before('/')] = true94 }95 }96 return names.keys()97}9899fn (mut backend DoctorReadOnly) put_if_absent(key string, body []u8) !bool {100 panic('Doctor attempted a remote write')101}102103fn (mut backend DoctorReadOnly) put_if_match(key string, body []u8, tag string) !bool {104 panic('Doctor attempted a remote write')105}106107fn (mut backend DoctorReadOnly) delete(key string) ! {108 panic('Doctor attempted a remote delete')109}110111fn test_doctor_remote_audits_unreferenced_objects_and_release_checksums_without_writes() {112 data := 'file'.bytes()113 hash := storage.hash_hex(data)114 mut backend := DoctorReadOnly{115 items: {116 'repo/head': 'aaaaaaaaaaaa'.bytes()117 'repo/saves/aaaaaaaaaaaa': json2.encode(exchange.SaveRecord{118 id: 'aaaaaaaaaaaa'119 files: [exchange.FileRecord{ path: 'file', hash: hash }]120 }).bytes()121 'repo/objects/${hash}': zlib.compress(data)!122 'repo/releases/latest': '1.0.0'.bytes()123 'repo/releases/1.0.0/release.json': json2.encode(release.Record{124 repo: 'repo'125 version: '1.0.0'126 save: 'aaaaaaaaaaaa'127 files: [release.File{128 platform: 'linux-aarch64'129 name: 'app'130 size: data.len131 blake3: hash132 sha256: sha256.sum256(data).hex()133 }]134 }).bytes()135 'repo/releases/1.0.0/linux-aarch64/app': data136 }137 }138 mut report := DoctorJson{ head_id: 'aaaaaaaaaaaa' }139 doctor_remote_content(mut backend, 'repo', mut report)!140 assert report.problems.len == 0141 assert report.remote_saves == 1142 assert report.remote_releases == 1143 backend.items['repo/objects/${storage.hash_hex('unreferenced'.bytes())}'] = 'bad zlib'.bytes()144 backend.items['repo/releases/1.0.0/linux-aarch64/app'] = 'corrupt'.bytes()145 mut damaged := DoctorJson{}146 doctor_remote_content(mut backend, 'repo', mut damaged)!147 assert damaged.problems.any(it.contains('damaged remote object'))148 assert damaged.problems.any(it.contains('checksum verification'))149}150151fn test_doctor_remote_keeps_a_complete_report_for_invalid_records() {152 mut backend := DoctorReadOnly{153 items: {154 'repo/head': 'aaaaaaaaaaaa'.bytes()155 'repo/saves/aaaaaaaaaaaa': json2.encode(exchange.SaveRecord{156 id: 'aaaaaaaaaaaa'157 created_at: -1158 }).bytes()159 'repo/events/bad': json2.encode(exchange.EventRecord{160 id: 'bad'161 kind: 'unknown'162 created_at: 1163 }).bytes()164 }165 }166 mut report := DoctorJson{}167 doctor_remote_content(mut backend, 'repo', mut report)!168 assert report.problems.any(it.contains('invalid metadata'))169 assert report.problems.any(it.contains('invalid ID'))170 assert report.problems.any(it.contains('unknown kind'))171}172173fn test_doctor_remote_binds_a_save_to_its_exact_key() {174 mut backend := DoctorReadOnly{175 items: {176 'repo/head': 'aaaaaaaaaaaa'.bytes()177 'repo/saves/nested/aaaaaaaaaaaa': json2.encode(exchange.SaveRecord{178 id: 'aaaaaaaaaaaa'179 }).bytes()180 }181 }182 mut report := DoctorJson{}183 if _ := doctor_remote_content(mut backend, 'repo', mut report) {184 assert false, 'a nested save key must not stand in for the canonical key'185 } else {186 assert err.msg().contains('disagrees with key'), err.msg()187 }188}189190fn test_doctor_reports_event_errors_strip_residue_and_flags() {191 mut report := DoctorJson{}192 saves := [history.Save{ id: 'aaaaaaaaaaaa' }]193 event_list := [events.Event{ id: 'strip', kind: 'strip', path: 'private' },194 events.Event{ id: 'flag', kind: 'flag', save_id: 'aaaaaaaaaaaa' },195 events.Event{ id: 'bad', kind: 'unknown' }]196 doctor_events(event_list, saves, mut report)197 doctor_files(saves[0].id, [snapshot.FileEntry{ path: 'private/file' }], event_list, mut report)198 assert report.flagged_saves == 1199 assert report.problems.any(it.contains('invalid ID'))200 assert report.problems.any(it.contains('unknown kind'))201 assert report.problems.any(it.contains('stripped path'))202 assert report.strip_residue_paths == ['private']203}204205struct DoctorMemory {206mut:207 items map[string][]u8208}209210fn (mut backend DoctorMemory) get(key string) !remote.Object {211 if body := backend.items[key] {212 return remote.Object{ found: true, body: body }213 }214 return remote.Object{}215}216217fn (mut backend DoctorMemory) list(prefix string) ![]string {218 return backend.items.keys().filter(it.starts_with('${prefix}/'))219}220221fn (mut backend DoctorMemory) list_dirs(prefix string) ![]string {222 return dirs_of(backend.list(prefix)!, prefix)223}224225fn (mut backend DoctorMemory) put_if_absent(key string, body []u8) !bool {226 if key in backend.items {227 return false228 }229 backend.items[key] = body230 return true231}232233fn (mut backend DoctorMemory) put_if_match(key string, body []u8, tag string) !bool {234 return false235}236237fn (mut backend DoctorMemory) delete(key string) ! {238 backend.items.delete(key)239}240241fn doctor_store(name string) !(storage.Store, string) {242 dir := os.join_path(os.temp_dir(), 'koh3_doctor_${name}_${os.getpid()}')243 os.rmdir_all(dir) or {}244 os.mkdir_all(dir)!245 return storage.create(dir)!, dir246}247248fn test_doctor_fetches_missing_parents_from_the_remote_without_writing_to_it() {249 store, dir := doctor_store('fetch')!250 defer {251 store.close()252 os.rmdir_all(dir) or {}253 }254 data := 'parent'.bytes()255 hash := storage.hash_hex(data)256 mut backend := DoctorReadOnly{257 items: {258 'repo/saves/aaaaaaaaaaaa': json2.encode(exchange.SaveRecord{259 id: 'aaaaaaaaaaaa'260 files: [exchange.FileRecord{ path: 'file', hash: hash }]261 }).bytes()262 'repo/objects/${hash}': zlib.compress(data)!263 }264 }265 store.db.exec('PRAGMA foreign_keys=OFF')!266 store.begin()!267 history.import_save(store, history.Save{ id: 'bbbbbbbbbbbb', parent: 'aaaaaaaaaaaa' },268 []snapshot.FileEntry{})!269 history.set_head(store, 'bbbbbbbbbbbb')!270 store.end()!271 store.db.exec('PRAGMA foreign_keys=ON')!272 missing := missing_saves(history.all_saves(store)!, 'bbbbbbbbbbbb')273 assert missing == ['aaaaaaaaaaaa']274 assert exchange.fetch_missing(store, mut backend, 'repo', missing)! == 1275 assert missing_saves(history.all_saves(store)!, 'bbbbbbbbbbbb').len == 0276 assert store.get_object(hash)! == data277 assert exchange.fetch_missing(store, mut backend, 'repo', ['cccccccccccc']) or {278 assert err.msg().contains('does not have save')279 0280 } == 0281}282283fn test_doctor_reapplies_recorded_strips_and_finds_the_only_tip() {284 store, dir := doctor_store('strip')!285 defer {286 store.close()287 os.rmdir_all(dir) or {}288 }289 secret := store.put_object('secret'.bytes())!290 kept := store.put_object('kept'.bytes())!291 store.begin()!292 history.import_save(store, history.Save{ id: 'aaaaaaaaaaaa' }, [293 snapshot.FileEntry{ path: 'keep', hash: kept },294 snapshot.FileEntry{ path: 'private/key', hash: secret },295 ])!296 history.import_save(store, history.Save{ id: 'bbbbbbbbbbbb', parent: 'aaaaaaaaaaaa' },297 [snapshot.FileEntry{ path: 'keep', hash: kept }])!298 events.strip(store, '', 'private')!299 store.end()!300 assert only_tip(store) or { '' } == 'bbbbbbbbbbbb'301 mut report := DoctorJson{}302 doctor_files('aaaaaaaaaaaa', history.files_of(store, 'aaaaaaaaaaaa')!, events.all(store)!, mut303 report)304 assert report.strip_residue305 assert exchange.reapply_strips(store)! == 1306 assert history.files_of(store, 'aaaaaaaaaaaa')!.map(it.path) == ['keep']307 assert !store.has_object(secret)!308 assert events.strip_events(store)!.len == 1309}310311fn test_doctor_restores_objects_from_working_files_and_resends_them_to_the_remote() {312 store, dir := doctor_store('objects')!313 defer {314 store.close()315 os.rmdir_all(dir) or {}316 }317 data := 'content'.bytes()318 hash := store.put_object(data)!319 store.begin()!320 history.import_save(store, history.Save{ id: 'aaaaaaaaaaaa' }, [321 snapshot.FileEntry{ path: 'app', hash: hash },322 ])!323 history.set_head(store, 'aaaaaaaaaaaa')!324 store.end()!325 store.db.exec("UPDATE objects SET data = x'00'")!326 problems := store.check_objects()!327 assert problems.map(it.hash) == [hash]328 assert local_copy(store, hash) == none329 os.write_file(os.join_path(dir, 'app'), 'content')!330 store.repair_object(hash, local_copy(store, hash) or { panic('no working copy') })!331 assert store.check_objects()!.len == 0332 store.repair_object(hash, 'other'.bytes()) or {333 assert err.msg().contains('does not match')334 }335 mut backend := DoctorMemory{336 items: {337 'repo/objects/${hash}': 'damaged'.bytes()338 }339 }340 assert exchange.resend(store, mut backend, 'repo', [hash], ['aaaaaaaaaaaa'])! == 2341 assert zlib.decompress(backend.items['repo/objects/${hash}'])! == data342 assert exchange.decode_save(backend.items['repo/saves/aaaaaaaaaaaa'])!.files[0].hash == hash343}344345346347fn test_doctor_strip_repair_ignores_invalid_events_and_keeps_unrelated_objects() {348 store, dir := doctor_store('strip_safety')!349 defer {350 store.close()351 os.rmdir_all(dir) or {}352 }353 app := store.put_object('app'.bytes())!354 secret := store.put_object('secret'.bytes())!355 orphan := store.put_object('orphan'.bytes())!356 store.begin()!357 history.import_save(store, history.Save{ id: 'aaaaaaaaaaaa' }, [358 snapshot.FileEntry{ path: 'app', hash: app },359 snapshot.FileEntry{ path: 'secret', hash: secret },360 ])!361 events.receive(store, events.Event{362 id: 'invalidstrip'363 kind: events.kind_strip364 path: 'app'365 created_at: -1366 machine: 'test'367 })!368 events.strip(store, '', 'secret')!369 store.end()!370 mut report := DoctorJson{}371 doctor_files('aaaaaaaaaaaa', [snapshot.FileEntry{ path: 'app' }], events.all(store)!, mut372 report)373 assert !report.strip_residue374 assert exchange.reapply_strips(store)! == 1375 assert history.files_of(store, 'aaaaaaaaaaaa')!.map(it.path) == ['app']376 assert store.has_object(app)!377 assert store.has_object(orphan)!378 assert !store.has_object(secret)!379}380381382383fn test_doctor_guesses_head_only_when_nothing_knows_better() {384 store, dir := doctor_store('only_tip')!385 defer {386 store.close()387 os.rmdir_all(dir) or {}388 }389 store.begin()!390 history.import_save(store, history.Save{ id: 'aaaaaaaaaaaa' }, []snapshot.FileEntry{})!391 store.end()!392 mut report := DoctorJson{393 metadata_available: true394 saves: 1395 source: 'folder/repo'396 remote_head: 'bbbbbbbbbbbb'397 }398 assert !plan_repairs(store, report).any(it.action.contains('point head'))399 report.remote_head = ''400 report.checks << DoctorCheck{'remote audit', 'skipped', '--fast requested', ''}401 assert !plan_repairs(store, report).any(it.action.contains('point head'))402 report.checks = [DoctorCheck{'remote stability', 'fail', 'remote head changed during audit', ''}]403 assert !plan_repairs(store, report).any(it.action.contains('point head'))404 report.checks = []405 assert plan_repairs(store, report).any(it.action.contains('point head'))406 report.source = ''407 repairs := plan_repairs(store, report).filter(it.action.contains('point head'))408 assert repairs.len == 1409 history.set_head(store, 'cccccccccccc')!410 if _ := repairs[0].run() {411 assert false, 'a head another command set must not be replaced'412 } else {413 assert err.msg().contains('changed'), err.msg()414 }415 assert store.state(storage.head_key) or { '' } == 'cccccccccccc'416 store.remove_state(storage.head_key)!417 repairs[0].run()!418 assert store.state(storage.head_key) or { '' } == 'aaaaaaaaaaaa'419}420421fn test_doctor_reports_objects_it_restored_before_one_it_could_not() {422 store, dir := doctor_store('partial')!423 defer {424 store.close()425 os.rmdir_all(dir) or {}426 }427 kept := store.put_object('kept'.bytes())!428 lost := store.put_object('lost'.bytes())!429 store.begin()!430 history.import_save(store, history.Save{ id: 'aaaaaaaaaaaa' }, [431 snapshot.FileEntry{ path: 'kept', hash: kept },432 snapshot.FileEntry{ path: 'lost', hash: lost },433 ])!434 store.end()!435 store.db.exec("UPDATE objects SET data = x'00'")!436 os.write_file(os.join_path(dir, 'kept'), 'kept')!437 if _ := repair_objects(store, [kept, lost], '', '') {438 assert false, 'an object with no verified copy must fail its repair'439 } else {440 assert err is exchange.Partway441 assert (err as exchange.Partway).done == 'restored 1 damaged or missing object'442 assert err.msg().contains(lost)443 }444 assert store.get_object(kept)! == 'kept'.bytes()445}446447fn test_doctor_refuses_a_remote_save_with_invalid_metadata() {448 store, dir := doctor_store('invalid_fetch')!449 defer {450 store.close()451 os.rmdir_all(dir) or {}452 }453 mut backend := DoctorReadOnly{454 items: {455 'repo/saves/aaaaaaaaaaaa': json2.encode(exchange.SaveRecord{456 id: 'aaaaaaaaaaaa'457 created_at: -1458 }).bytes()459 }460 }461 if _ := exchange.fetch_missing(store, mut backend, 'repo', ['aaaaaaaaaaaa']) {462 assert false, 'a record with invalid metadata must not be imported'463 } else {464 assert err.msg().contains('invalid metadata')465 }466 assert history.all_saves(store)!.len == 0467}468469470471fn test_doctor_replaces_a_damaged_remote_copy_of_an_empty_file() {472 store, dir := doctor_store('empty_object')!473 defer {474 store.close()475 os.rmdir_all(dir) or {}476 }477 hash := store.put_object([]u8{})!478 mut backend := DoctorMemory{479 items: {480 'repo/objects/${hash}': 'not zlib'.bytes()481 }482 }483 assert exchange.resend(store, mut backend, 'repo', [hash], [])! == 1484 assert zlib.decompress(backend.items['repo/objects/${hash}'])!.len == 0485}486487488489fn test_doctor_rechecks_the_remote_head_before_guessing() {490 store, dir := doctor_store('remote_tip')!491 remote_dir := os.join_path(dir, 'remote')492 defer {493 store.close()494 machine.forget_remote() or {}495 os.rmdir_all(dir) or {}496 }497 store.begin()!498 history.import_save(store, history.Save{ id: 'aaaaaaaaaaaa' }, []snapshot.FileEntry{})!499 store.end()!500 mut folder := remote.new_folder(remote_dir)!501 machine.save_remote(machine.RemoteSettings{ kind: machine.kind_folder, path: remote_dir })!502 report := DoctorJson{503 metadata_available: true504 saves: 1505 remote_repo: 'repo'506 }507 repairs := plan_repairs(store, report).filter(it.action.contains('point head'))508 assert repairs.len == 1509 folder.put_if_absent(exchange.head_key('repo'), 'bbbbbbbbbbbb'.bytes())!510 if _ := repairs[0].run() {511 assert false, 'a head offered since the audit must stop the guess'512 } else {513 assert err.msg().contains('another head'), err.msg()514 }515 assert store.state(storage.head_key) == none516}517518519fn test_doctor_reports_restored_objects_when_the_remote_then_fails() {520 store, dir := doctor_store('partial_remote')!521 defer {522 store.close()523 machine.forget_remote() or {}524 os.rmdir_all(dir) or {}525 }526 kept := store.put_object('kept'.bytes())!527 lost := store.put_object('lost'.bytes())!528 store.begin()!529 history.import_save(store, history.Save{ id: 'aaaaaaaaaaaa' }, [530 snapshot.FileEntry{ path: 'kept', hash: kept },531 snapshot.FileEntry{ path: 'lost', hash: lost },532 ])!533 store.end()!534 store.db.exec("UPDATE objects SET data = x'00'")!535 os.write_file(os.join_path(dir, 'kept'), 'kept')!536 machine.save_remote(machine.RemoteSettings{537 kind: machine.kind_folder538 path: os.join_path(dir, 'unmounted')539 })!540 if _ := repair_objects(store, [kept, lost], '', '') {541 assert false, 'an unreachable remote must fail the repair'542 } else {543 assert err is exchange.Partway544 assert (err as exchange.Partway).done == 'restored 1 damaged or missing object'545 assert err.msg().contains('not there'), err.msg()546 }547}548549550fn test_doctor_fetch_ignores_invalid_strip_events() {551 store, dir := doctor_store('fetch_invalid_strip')!552 defer {553 store.close()554 os.rmdir_all(dir) or {}555 }556 data := 'app'.bytes()557 hash := storage.hash_hex(data)558 mut backend := DoctorReadOnly{559 items: {560 'repo/saves/aaaaaaaaaaaa': json2.encode(exchange.SaveRecord{561 id: 'aaaaaaaaaaaa'562 files: [exchange.FileRecord{ path: 'app', hash: hash }]563 }).bytes()564 'repo/objects/${hash}': zlib.compress(data)!565 }566 }567 events.receive(store, events.Event{568 id: 'invalidstrip'569 kind: events.kind_strip570 path: 'app'571 created_at: -1572 machine: 'test'573 })!574 assert exchange.fetch_missing(store, mut backend, 'repo', ['aaaaaaaaaaaa'])! == 1575 assert history.files_of(store, 'aaaaaaaaaaaa')!.map(it.path) == ['app']576}577578579580581fn test_doctor_sends_a_recorded_strip_again_for_remote_residue() {582 store, dir := doctor_store('remote_residue')!583 remote_dir := os.join_path(dir, 'remote')584 defer {585 store.close()586 machine.forget_remote() or {}587 os.rmdir_all(dir) or {}588 }589 secret := 'secret'.bytes()590 hash := storage.hash_hex(secret)591 mut folder := remote.new_folder(remote_dir)!592 folder.put_if_absent(exchange.save_key('repo', 'aaaaaaaaaaaa'), json2.encode(exchange.SaveRecord{593 id: 'aaaaaaaaaaaa'594 files: [exchange.FileRecord{ path: 'app', hash: hash }]595 }).bytes())!596 folder.put_if_absent(exchange.object_key('repo', hash), zlib.compress(secret)!)!597 machine.save_remote(machine.RemoteSettings{ kind: machine.kind_folder, path: remote_dir })!598 store.set_state('remote_repo', 'repo')!599 events.strip(store, '', 'app')!600 store.set_state('strip_pending:bad', 'not JSON')!601 report := DoctorJson{602 remote_repo: 'repo'603 remote_strip_residue: ['app', 'bad']604 upload_unsettled: true605 }606 assert plan_repairs(store, report).any(it.action.contains('interrupted upload'))607 repairs := plan_repairs(store, report).filter(it.action.contains('remote still holds'))608 assert repairs.len == 1609 if _ := repairs[0].run() {610 assert false, 'an untrusted note must stop the second path'611 } else {612 assert err is exchange.Partway613 assert (err as exchange.Partway).done == 'sent 1 strip', (err as exchange.Partway).done614 }615 record := exchange.decode_save(folder.get(exchange.save_key('repo', 'aaaaaaaaaaaa'))!.body)!616 assert record.files.len == 0617 assert !folder.get(exchange.object_key('repo', hash))!.found618 assert !exchange.strip_pending(store, 'app')619}