Coverage for src/copytrading_engine/backup/configuration.py: 54%

102 statements  

« prev     ^ index     » next       coverage.py v7.16.2, created at 2026-11-16 16:55 +0000

1"""What an installation's saved identity, configuration, and credential references say.""" 

2 

3from __future__ import annotations 

4 

5import re 

6import uuid 

7from pathlib import Path 

8 

9from copytrading_engine.backup.archive import open_archive, read_limited 

10from copytrading_engine.backup.files import require_regular_file 

11from copytrading_engine.backup.manifest import BackupManifest, BackupManifestError, json_object 

12from copytrading_engine.shared.configuration_version import ( 

13 CONFIGURATION_VERSION, 

14 EARLIEST_UPGRADABLE_VERSION, 

15) 

16 

17 

18def read_installation_id(data_dir: Path) -> str: 

19 path = data_dir / "installation-id" 

20 require_regular_file(path, "installation identity is unavailable") 

21 value = path.read_text(encoding="ascii").strip() 

22 try: 

23 canonical = str(uuid.UUID(value)) 

24 except (ValueError, TypeError, AttributeError) as exc: 

25 raise BackupManifestError("installation identity is invalid") from exc 

26 if value.lower() != canonical: 26 ↛ 27line 26 didn't jump to line 27 because the condition on line 26 was never true

27 raise BackupManifestError("installation identity is invalid") 

28 return canonical 

29 

30 

31# The fields the app's TradingConfigurationStore writes; its persistence test pins the same set. 

32SAVED_CONFIGURATION_FIELDS = frozenset( 

33 {"version", "configuration", "revision", "secretRevision", "pendingActivation"} 

34) 

35 

36 

37def read_configuration_identities(content: bytes) -> tuple[str, ...]: 

38 raw = json_object(content) 

39 if set(raw) - SAVED_CONFIGURATION_FIELDS: 39 ↛ 40line 39 didn't jump to line 40 because the condition on line 39 was never true

40 raise BackupManifestError("saved configuration has unsupported fields") 

41 if type(raw.get("version")) is not int or raw.get("version") != 1: 41 ↛ 42line 41 didn't jump to line 42 because the condition on line 41 was never true

42 raise BackupManifestError("saved configuration schema is unsupported") 

43 revision = raw.get("revision") 

44 if revision is not None and ( 44 ↛ 47line 44 didn't jump to line 47 because the condition on line 44 was never true

45 not isinstance(revision, str) or not re.fullmatch(r"[0-9a-f]{64}", revision) 

46 ): 

47 raise BackupManifestError("saved configuration revision is invalid") 

48 if raw.get("pendingActivation") is not None: 48 ↛ 49line 48 didn't jump to line 49 because the condition on line 48 was never true

49 raise BackupManifestError("saved configuration activation is incomplete") 

50 configuration = raw.get("configuration") 

51 # An earlier setup is restored as it was; the app upgrades it when it next loads it. 

52 version = configuration.get("version") if isinstance(configuration, dict) else None 

53 if ( 

54 not isinstance(configuration, dict) 

55 or type(version) is not int 

56 or not EARLIEST_UPGRADABLE_VERSION <= version <= CONFIGURATION_VERSION 

57 ): 

58 raise BackupManifestError("saved trading configuration is unsupported") 

59 accounts = configuration.get("accounts") 

60 if not isinstance(accounts, list): 60 ↛ 61line 60 didn't jump to line 61 because the condition on line 60 was never true

61 raise BackupManifestError("saved trading account identities are invalid") 

62 identities: list[str] = [] 

63 for account in accounts: 

64 if not isinstance(account, dict) or set(account) - {"id", "environment", "policy"}: 64 ↛ 65line 64 didn't jump to line 65 because the condition on line 64 was never true

65 raise BackupManifestError("saved trading account identity is invalid") 

66 account_id, environment = account.get("id"), account.get("environment") 

67 if ( 67 ↛ 72line 67 didn't jump to line 72 because the condition on line 67 was never true

68 not isinstance(account_id, str) 

69 or not re.fullmatch(r"[A-Za-z0-9_-]{1,64}", account_id) 

70 or environment not in {"paper", "live"} 

71 ): 

72 raise BackupManifestError("saved trading account identity is invalid") 

73 identities.append(f"{environment}:{account_id}") 

74 if len({identity.split(":", 1)[1] for identity in identities}) != len(identities): 74 ↛ 75line 74 didn't jump to line 75 because the condition on line 74 was never true

75 raise BackupManifestError("saved trading account identities are duplicated") 

76 reference = raw.get("secretRevision") 

77 if reference is not None: 

78 try: 

79 canonical_reference = str(uuid.UUID(reference)) 

80 except (ValueError, TypeError, AttributeError) as exc: 

81 raise BackupManifestError("saved credential reference is invalid") from exc 

82 if reference.lower() != canonical_reference: 82 ↛ 83line 82 didn't jump to line 83 because the condition on line 82 was never true

83 raise BackupManifestError("saved credential reference is invalid") 

84 return tuple(sorted(identities)) 

85 

86 

87def validate_activation_json(content: bytes) -> None: 

88 raw = json_object(content) 

89 if ( 

90 set(raw) != {"version", "record"} 

91 or type(raw.get("version")) is not int 

92 or raw.get("version") != 1 

93 ): 

94 raise BackupManifestError("trading activation journal is unsupported") 

95 record = raw["record"] 

96 required = { 

97 "activation_id", 

98 "candidate_revision", 

99 "committed_revision", 

100 "committed_activation_id", 

101 "phase", 

102 "error_code", 

103 } 

104 if not isinstance(record, dict) or set(record) != required: 

105 raise BackupManifestError("trading activation journal is invalid") 

106 try: 

107 activation_id = record["activation_id"] 

108 committed_activation_id = record["committed_activation_id"] 

109 if ( 

110 not isinstance(activation_id, str) 

111 or str(uuid.UUID(activation_id)) != activation_id 

112 or ( 

113 committed_activation_id is not None 

114 and ( 

115 not isinstance(committed_activation_id, str) 

116 or str(uuid.UUID(committed_activation_id)) != committed_activation_id 

117 ) 

118 ) 

119 ): 

120 raise ValueError("invalid activation identity") 

121 except (ValueError, TypeError, AttributeError) as exc: 

122 raise BackupManifestError("trading activation journal is invalid") from exc 

123 candidate_revision = record["candidate_revision"] 

124 committed_revision = record["committed_revision"] 

125 error_code = record["error_code"] 

126 if ( 

127 not isinstance(candidate_revision, str) 

128 or not re.fullmatch(r"[0-9a-f]{64}", candidate_revision) 

129 or ( 

130 committed_revision is not None 

131 and ( 

132 not isinstance(committed_revision, str) 

133 or not re.fullmatch(r"[0-9a-f]{64}", committed_revision) 

134 ) 

135 ) 

136 or not isinstance(record["phase"], str) 

137 or record["phase"] not in {"starting", "ready", "failed", "stopped", "interrupted"} 

138 or (error_code is not None and (not isinstance(error_code, str) or len(error_code) > 64)) 

139 ): 

140 raise BackupManifestError("trading activation journal is invalid") 

141 

142 

143def archive_credential_references(archive_path: Path, manifest: BackupManifest) -> tuple[str, ...]: 

144 config_member = next( 

145 (member for member in manifest.members if member.path == "trading-configuration.json"), 

146 None, 

147 ) 

148 if config_member is None: 

149 return () 

150 with open_archive(archive_path) as archive: 

151 raw = json_object( 

152 read_limited(archive, archive.getinfo(config_member.path), config_member.size) 

153 ) 

154 reference = raw.get("secretRevision") 

155 if reference is None: 155 ↛ 156line 155 didn't jump to line 156 because the condition on line 155 was never true

156 return () 

157 try: 

158 return (str(uuid.UUID(reference)),) 

159 except (ValueError, TypeError, AttributeError) as exc: 

160 raise BackupManifestError("saved credential reference is invalid") from exc 

161 

162 

163def candidate_credential_references( 

164 candidate: Path, 

165 manifest: BackupManifest, 

166) -> tuple[str, ...]: 

167 config_member = next( 

168 (member for member in manifest.members if member.path == "trading-configuration.json"), 

169 None, 

170 ) 

171 if config_member is None: 171 ↛ 173line 171 didn't jump to line 173 because the condition on line 171 was always true

172 return () 

173 raw = json_object((candidate / config_member.path).read_bytes()) 

174 reference = raw.get("secretRevision") 

175 if reference is None: 

176 return () 

177 try: 

178 return (str(uuid.UUID(reference)),) 

179 except (ValueError, TypeError, AttributeError) as exc: 

180 raise BackupManifestError("saved credential reference is invalid") from exc