Coverage for app / services / system_resources / rules.py: 100%

25 statements  

« prev     ^ index     » next       coverage.py v7.13.5, created at 2026-10-31 11:21 +0000

1""" 

2Built-in governance rules — the controls most deployments want, written once 

3by CHAIN-R so nobody has to work out the regular expression for an AWS key. 

4 

5A built-in rule governs nobody. The engine loads only the rules a user owns, 

6so a user adopts one by creating a rule of their own from it (Governance → 

7Rules → Built-in → *Use this rule*): the builder opens with the definition 

8filled in, the user scopes and tunes it, and the rule they create records the 

9built-in and its release (``based_on_rule_id`` / ``based_on_version``). That 

10is deliberate. A rule carries decisions only its owner can make — what it 

11covers, how much spend is too much, whether it is switched on — and a change 

12to what governs a user's invocations should be theirs, not a release's. 

13 

14Each definition is held to the checks a generated rule is, and its patterns 

15to known true and false positives, by ``tests/test_built_in_rules.py``. 

16 

17Rules that were considered and left out, because they would not do what 

18their name says today: 

19 

20- **A rate limit.** Evaluation runs are concurrent and write the same ledger 

21 a limit counts, so any default low enough to stop a runaway loop refuses 

22 chats while an evaluation runs. 

23- **Flag expensive or slow invocations.** Left out while no audit call site 

24 passed ``estimated_cost_usd`` or ``latency_ms``, so a condition on either 

25 never matched. Every audit path now passes both (``usage.audit_figures``), 

26 so a user can write one; a built-in waits on what thresholds a deployment 

27 would want by default. 

28 

29Ids are fixed, ``…000000000401`` onwards (#11, the trusted regulators, came 

30with the Tools layer; #12, withholding leaked credentials, with ``withhold``; 

31#13, the publishers CHAINR Bot puts first, with its preferred sources). A 

32released built-in is corrected in place, never removed: users' rules point at 

33it. The one exception is #8, *Route long prompts*, which went with routing 

34rules themselves: migration 104 deleted it with every routing rule, so nothing 

35points at it. 

36""" 

37 

38from __future__ import annotations 

39 

40from uuid import UUID 

41 

42from app.db.postgres.enums import RuleEnum 

43from app.services import quality_check 

44from app.services.rules import pii 

45 

46from . import web_sources 

47from .definition import CHAINR_BOT, SystemRuleSpec 

48 

49_ID_PREFIX = "c4a1b0e7-0000-4000-8000-" 

50 

51 

52def _rule_id(number: int) -> UUID: 

53 return UUID(f"{_ID_PREFIX}{400 + number:012d}") 

54 

55 

56#: Credentials with a recognisable shape: PEM private keys, AWS access key 

57#: ids, GitHub, Slack, OpenAI / Anthropic, Stripe and Google API keys, JSON 

58#: Web Tokens, and database URLs carrying a password. Matched ignoring case, 

59#: like every ``matches`` condition. ``sk-`` keys must contain a digit, so 

60#: hyphenated prose ("sk-learn-compatible-…") is not mistaken for one. 

61CREDENTIAL_PATTERN = "|".join( 

62 ( 

63 r"-----BEGIN (?:[A-Z]+ )*PRIVATE KEY-----", 

64 r"\b(?:AKIA|ASIA)[0-9A-Z]{16}\b", 

65 r"\bgh[pousr]_[A-Za-z0-9]{36,}", 

66 r"\bgithub_pat_\w{40,}", 

67 r"\bxox[abposr]-[\w-]{10,}", 

68 r"\bsk-(?=[\w-]*\d)[\w-]{24,}", 

69 r"\b[rs]k_live_\w{20,}", 

70 r"\bAIza[\w-]{35}", 

71 r"\beyJ[\w-]{8,}\.eyJ[\w-]{8,}\.[\w-]{8,}", 

72 r"\b(?:postgres(?:ql)?|mysql|mongodb(?:\+srv)?|redis|amqps?)" 

73 r"://[^\s:/@]+:[^\s@/]+@", 

74 ) 

75) 

76 

77#: The commonest prompt-injection phrasings. Aimed at instructions to the 

78#: model about *its* instructions, so a person correcting themselves ("ignore 

79#: my previous instructions") or asking about a prompt ("show me the system 

80#: prompt for my agent") is not refused. 

81INJECTION_PATTERN = "|".join( 

82 ( 

83 r"\b(?:ignore|disregard|forget)\s+(?:(?:all|any)\s+)?(?:of\s+)?" 

84 r"(?:the\s+|your\s+)?(?:previous|prior|above|earlier|system)\s+" 

85 r"(?:instructions|prompts?|rules|guidelines)", 

86 r"\b(?:reveal|print|repeat|show\s+me)\s+your\s+" 

87 r"(?:system|hidden|initial|developer)\s+(?:prompt|instructions)", 

88 r"\byou\s+are\s+now\s+(?:in\s+)?" 

89 r"(?:DAN|developer\s+mode|jailbroken|unrestricted)", 

90 r"\b(?:pretend|act\s+as\s+if)\s+you\s+have\s+no\s+" 

91 r"(?:restrictions|rules|guidelines|limits)", 

92 r"\bdo\s+anything\s+now\b", 

93 ) 

94) 

95 

96 

97REDACT_PROMPTS = SystemRuleSpec( 

98 id=_rule_id(1), 

99 name="Redact PII in prompts", 

100 description=( 

101 "Replaces personal data in every prompt — and in the conversation " 

102 "history, attached documents and answers sent with it — with " 

103 f"placeholders before a model sees it: {pii.summary()}. Governance → " 

104 "Activity records which kinds were removed and how many, never the " 

105 "values." 

106 ), 

107 layer=RuleEnum.Layer.input, 

108 actions=({"type": "redact_pii"},), 

109) 

110 

111BLOCK_CREDENTIALS = SystemRuleSpec( 

112 id=_rule_id(2), 

113 name="Block credentials in prompts", 

114 description=( 

115 "Refuses a prompt containing a recognisable secret — a private key; " 

116 "an AWS, GitHub, Slack, OpenAI, Anthropic, Stripe or Google API key; " 

117 "a JSON Web Token; or a database URL with a password in it — so it " 

118 "never reaches a model provider. Known formats only: a bare password " 

119 "is not detected." 

120 ), 

121 layer=RuleEnum.Layer.input, 

122 conditions=( 

123 {"field": "prompt", "operator": "matches", "value": CREDENTIAL_PATTERN}, 

124 ), 

125 actions=( 

126 { 

127 "type": "block", 

128 "message": ( 

129 "This prompt appears to contain a credential — a key, a token " 

130 "or a connection string with a password. Remove it and try " 

131 "again: credentials should never be sent to a model." 

132 ), 

133 }, 

134 ), 

135) 

136 

137BLOCK_INJECTION = SystemRuleSpec( 

138 id=_rule_id(3), 

139 name="Block prompt injection", 

140 description=( 

141 "Refuses prompts using the commonest injection phrasings: telling the " 

142 "model to ignore its previous instructions, asking it to reveal its " 

143 "system prompt, or declaring it unrestricted (“DAN”, “developer " 

144 "mode”). A first line of defence on the user's message — it does not " 

145 "see knowledge or tool results. The Prompt injection gold dataset " 

146 "tests how your agents hold up." 

147 ), 

148 layer=RuleEnum.Layer.input, 

149 conditions=( 

150 {"field": "prompt", "operator": "matches", "value": INJECTION_PATTERN}, 

151 ), 

152 actions=( 

153 { 

154 "type": "block", 

155 "message": ( 

156 "This request looks like an attempt to override the " 

157 "assistant's instructions, so it was not sent." 

158 ), 

159 }, 

160 ), 

161) 

162 

163DAILY_SPEND_CAP = SystemRuleSpec( 

164 id=_rule_id(4), 

165 name="Daily spend cap", 

166 description=( 

167 "Refuses invocations once estimated spend reaches $10 in the trailing " 

168 "24 hours, across everything the rule covers — narrow its scope to " 

169 "cap one agent or project. Evaluation runs count toward the cap and " 

170 "are refused at it too. Set the amount to your budget before you " 

171 "create the rule." 

172 ), 

173 layer=RuleEnum.Layer.access, 

174 actions=( 

175 { 

176 "type": "cost_cap", 

177 "max_usd": 10, 

178 "window_seconds": 86_400, 

179 "message": ( 

180 "The daily spending limit has been reached. It frees up as " 

181 "the 24-hour window moves on." 

182 ), 

183 }, 

184 ), 

185) 

186 

187MONTHLY_BUDGET = SystemRuleSpec( 

188 id=_rule_id(10), 

189 name="Monthly budget", 

190 description=( 

191 "Refuses invocations once spend this calendar month (UTC) reaches " 

192 "$100, across everything the rule covers, and starts again on the " 

193 "1st. Made in an organisation, it is one budget for the organisation " 

194 "and every project in it; mark it Required for all projects so it " 

195 'applies inside them. Choose "each member" for an allowance per ' 

196 'person, or "let calls through" to be told rather than stopped. ' 

197 "Set the amount to your budget before you create the rule." 

198 ), 

199 layer=RuleEnum.Layer.access, 

200 actions=( 

201 { 

202 "type": "cost_cap", 

203 "max_usd": 100, 

204 "period": "month", 

205 "share": "shared", 

206 "on_reach": "block", 

207 "message": ( 

208 "This month's AI budget has been reached. It starts again on " 

209 "the 1st (UTC); an administrator can raise it." 

210 ), 

211 }, 

212 ), 

213) 

214 

215REQUIRE_EVALUATION = SystemRuleSpec( 

216 id=_rule_id(5), 

217 name="Require passing evaluations", 

218 description=( 

219 "Lets an agent answer only when its version in force has passed an " 

220 "evaluation: a completed, scored run of the agent as configured that " 

221 "reaches each dataset's pass mark without regressing. Evaluation runs " 

222 "are never refused, so a new version can earn its evidence. CHAINR " 

223 "Bot is left out by the condition on its id; remove it to gate the " 

224 "bot too." 

225 ), 

226 layer=RuleEnum.Layer.access, 

227 conditions=({"field": "agent_id", "operator": "neq", "value": str(CHAINR_BOT.id)},), 

228 actions=( 

229 { 

230 "type": "require_evaluation", 

231 "message": "This agent version has not passed its evaluation.", 

232 }, 

233 ), 

234) 

235 

236REDACT_RESPONSES = SystemRuleSpec( 

237 id=_rule_id(6), 

238 name="Redact PII in responses", 

239 description=( 

240 "Replaces personal data in every response — as it streams, in its " 

241 "trace and in what is stored — including personal data a model draws " 

242 f"from knowledge, tools or memory, which redacting the prompt cannot " 

243 f"catch: {pii.summary()}." 

244 ), 

245 layer=RuleEnum.Layer.output, 

246 actions=({"type": "redact_pii"},), 

247) 

248 

249FLAG_LEAKED_CREDENTIALS = SystemRuleSpec( 

250 id=_rule_id(7), 

251 name="Flag leaked credentials", 

252 description=( 

253 "Flags a response containing a recognisable secret — the formats " 

254 "“Block credentials in prompts” looks for — for a person to review " 

255 "under Governance → Rules → Reviews: a model repeating a key from a " 

256 "document or a tool result is a leak to investigate. The response is " 

257 "still returned, so revoke the credential. Flags are kept for 90 days." 

258 ), 

259 layer=RuleEnum.Layer.output, 

260 conditions=( 

261 {"field": "response", "operator": "matches", "value": CREDENTIAL_PATTERN}, 

262 ), 

263 actions=( 

264 {"type": "flag_for_review", "reviewer": "security", "retention_days": 90}, 

265 ), 

266) 

267 

268TRUSTED_REGULATORS = SystemRuleSpec( 

269 id=_rule_id(11), 

270 name="Trusted sources: UK & EU regulators", 

271 description=( 

272 "Puts official UK and EU sources first whenever an agent searches the " 

273 "web — GOV.UK and legislation.gov.uk, the Information Commissioner's " 

274 "Office, and the EU's institutions (EUR-Lex, the EDPB) — and tells it " 

275 "to read and cite them first. Other sources stay usable: turn on " 

276 "“Use only these” to search and read nothing else." 

277 ), 

278 layer=RuleEnum.Layer.tools, 

279 actions=( 

280 { 

281 "type": "trusted_sources", 

282 "domains": [ 

283 "gov.uk", 

284 "legislation.gov.uk", 

285 "ico.org.uk", 

286 "europa.eu", 

287 "eur-lex.europa.eu", 

288 "edpb.europa.eu", 

289 ], 

290 "only": False, 

291 }, 

292 ), 

293) 

294 

295TRUSTED_NEWS = SystemRuleSpec( 

296 id=_rule_id(13), 

297 name="Trusted sources: wire services & public broadcasters", 

298 description=( 

299 "Puts the publishers CHAINR Bot's searches put first ahead of the rest " 

300 "whenever an agent searches the web — Reuters and the Associated " 

301 "Press, public-service broadcasters (the BBC, Deutsche Welle, CBC, " 

302 "ABC, RTÉ, France 24) and the Office for National Statistics — and " 

303 "tells it to read and cite them first. Other sources stay usable. " 

304 "Pinned to CHAINR Bot, a rule of your own made from this replaces the " 

305 "bot's list with yours." 

306 ), 

307 layer=RuleEnum.Layer.tools, 

308 actions=( 

309 { 

310 "type": "trusted_sources", 

311 # The bot's own list, so the two cannot drift (``web_sources``). 

312 "domains": web_sources.domains(), 

313 "only": False, 

314 }, 

315 ), 

316) 

317 

318WITHHOLD_LEAKED_CREDENTIALS = SystemRuleSpec( 

319 id=_rule_id(12), 

320 name="Withhold answers that leak credentials", 

321 description=( 

322 "Withholds a response containing a recognisable secret — the formats " 

323 "“Block credentials in prompts” looks for — and sends it to review " 

324 "under Governance → Rules → Reviews, so the key never reaches the " 

325 "person who asked. The backstop for a customer-facing agent: while it " 

326 "covers an agent, answers appear once they have been checked, not as " 

327 "they are written. Still revoke the credential." 

328 ), 

329 layer=RuleEnum.Layer.output, 

330 conditions=( 

331 {"field": "response", "operator": "matches", "value": CREDENTIAL_PATTERN}, 

332 ), 

333 actions=( 

334 { 

335 "type": "withhold", 

336 "message": ( 

337 "This answer was withheld: it appeared to contain a credential. " 

338 "It has been sent for review." 

339 ), 

340 "review": True, 

341 }, 

342 ), 

343) 

344 

345UNCHECKED_ANSWERS = SystemRuleSpec( 

346 id=_rule_id(9), 

347 name="Review answers the quality check could not stand behind", 

348 description=( 

349 "Flags an agent's answer for a person to review under Governance → " 

350 "Reviews when its quality check failed and nothing fixed it, or when " 

351 "no check could run. The answer is still returned: this is bounded " 

352 "autonomy — the agent answers within your rules, and what it cannot " 

353 "stand behind reaches a person. Add “revised” to also review answers " 

354 "the check rewrote. Flags are kept for 90 days." 

355 ), 

356 layer=RuleEnum.Layer.output, 

357 conditions=( 

358 { 

359 "field": "quality_check", 

360 "operator": "in", 

361 "value": [ 

362 quality_check.Outcome.failed.value, 

363 quality_check.Outcome.unavailable.value, 

364 ], 

365 }, 

366 ), 

367 actions=({"type": "flag_for_review", "reviewer": "quality", "retention_days": 90},), 

368) 

369 

370#: In flow order, as the Rules page lists them: whether a request runs, what 

371#: reaches the model, where it may look things up, then what comes back. 

372SYSTEM_RULES: tuple[SystemRuleSpec, ...] = ( 

373 # Access 

374 MONTHLY_BUDGET, 

375 DAILY_SPEND_CAP, 

376 REQUIRE_EVALUATION, 

377 # Input 

378 REDACT_PROMPTS, 

379 BLOCK_CREDENTIALS, 

380 BLOCK_INJECTION, 

381 # Tools 

382 TRUSTED_REGULATORS, 

383 TRUSTED_NEWS, 

384 # Output 

385 REDACT_RESPONSES, 

386 FLAG_LEAKED_CREDENTIALS, 

387 WITHHOLD_LEAKED_CREDENTIALS, 

388 UNCHECKED_ANSWERS, 

389)