Coverage for app / dependency / resource_access.py: 91%

138 statements  

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

1from uuid import UUID 

2 

3from fastapi import HTTPException, status 

4from sqlalchemy.orm import Session 

5 

6#: Returned when something tries to change a built-in resource — CHAINR Bot, 

7#: its guide, or a built-in skillset or skill. 

8SYSTEM_READ_ONLY_DETAIL = ( 

9 "Built-in resources are managed by the platform and cannot be changed." 

10) 

11 

12 

13def _is_system(resource) -> bool: 

14 # ``is True`` rather than truthiness: an unconfigured mock's attribute is 

15 # a truthy mock, and a check that guesses "system" would turn every such 

16 # test fixture read-only. 

17 return getattr(resource, "is_system", False) is True 

18 

19 

20def verify_resource_access(resource, current_user, db: Session) -> None: 

21 """Raise 403 if current_user does not own or have membership for the given resource. 

22 

23 This is the check for **changing** a resource (and for any path that has 

24 not said otherwise), so a platform-managed row is refused outright — 

25 superusers included, because the row's content is defined in code and an 

26 edit would be overwritten at the next startup anyway. Paths that only 

27 read — or reference — a resource use :func:`verify_resource_read`, which 

28 admits system rows. Opting in per path keeps the default closed: a route 

29 nobody thought about cannot edit CHAINR Bot. 

30 """ 

31 if _is_system(resource): 

32 raise HTTPException( 

33 status_code=status.HTTP_403_FORBIDDEN, detail=SYSTEM_READ_ONLY_DETAIL 

34 ) 

35 if current_user.is_superuser: 

36 return 

37 

38 if resource.owner_user_id is not None: 

39 if resource.owner_user_id != current_user.id: 

40 raise HTTPException( 

41 status_code=status.HTTP_403_FORBIDDEN, detail="Forbidden" 

42 ) 

43 return 

44 

45 # An organisation's or project's: what the caller's role lets them change 

46 # in the resource's area (``app/services/access.py``). 

47 _require_level( 

48 db, 

49 current_user, 

50 organisation_id=resource.owner_organisation_id, 

51 project_id=resource.owner_project_id, 

52 model=type(resource), 

53 resource=resource, 

54 ) 

55 

56 

57def _require_level( 

58 db: Session, 

59 current_user, 

60 *, 

61 organisation_id, 

62 project_id, 

63 model, 

64 resource=None, 

65 creating: bool = False, 

66) -> None: 

67 """403 unless the caller's level in ``model``'s area, in the owning 

68 organisation or project, lets them create (``creating``) or change 

69 ``resource``. 

70 

71 Changing needs editor, or — for its creator — the kind's 

72 ``change_own_level`` (writer for most kinds, editor for rules). A kind in 

73 no area (a project inside an organisation) is the admins' to change. 

74 """ 

75 if organisation_id is None and project_id is None: 

76 return 

77 from app.services import access, membership 

78 

79 scope = ( 

80 membership.ORGANISATION if organisation_id is not None else membership.PROJECT 

81 ) 

82 scope_id = organisation_id if organisation_id is not None else project_id 

83 m = membership.effective_membership(db, scope, scope_id, current_user.id) 

84 if m is None: 

85 raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Forbidden") 

86 

87 kind = access.kind_of(model) 

88 if kind is None: 

89 if membership.role_of(m) is not membership.MemberRole.admin: 

90 raise HTTPException( 

91 status_code=status.HTTP_403_FORBIDDEN, 

92 detail=f"Only an admin of this {scope.label} can do that.", 

93 ) 

94 return 

95 

96 level = access.effective(m)[kind.area] 

97 needed = kind.create_level if creating else access.AccessLevel.editor 

98 if level >= needed: 

99 return 

100 if ( 

101 not creating 

102 and resource is not None 

103 and level >= kind.change_own_level 

104 and creator_of(db, kind, resource) == current_user.id 

105 ): 

106 return 

107 area = access.AREA_LABELS[kind.area] 

108 raise HTTPException( 

109 status_code=status.HTTP_403_FORBIDDEN, 

110 detail=( 

111 f"You are a {access.LEVEL_LABELS[level].lower()} of {area} in this " 

112 f"{scope.label}; that needs " 

113 + ( 

114 f"{access.LEVEL_LABELS[needed].lower()}." 

115 if creating or kind.change_own_level >= access.AccessLevel.editor 

116 else "an editor, or a writer who created it." 

117 ) 

118 ), 

119 ) 

120 

121 

122def verify_change_here(resource, current_user, db: Session) -> None: 

123 """:func:`verify_resource_access`, and the resource is the request 

124 workspace's own: what a project inherits from its parent, or is required 

125 to apply, is read-only there (``WorkspaceGuard``) — changed in its own 

126 workspace, never from another's page.""" 

127 verify_resource_access(resource, current_user, db) 

128 from app.dependency.workspace import request_workspace 

129 

130 ws = request_workspace(db, current_user) 

131 if ws is not None and not ws.owns_row(resource): 

132 raise HTTPException( 

133 status_code=status.HTTP_403_FORBIDDEN, 

134 detail="This belongs to another workspace; change it there.", 

135 ) 

136 

137 

138def may_change_here(resource, current_user, db: Session) -> bool: 

139 """Whether :func:`verify_change_here` would let the caller through — what 

140 a detail page asks before it offers edit or delete. A read: it raises 

141 nothing.""" 

142 try: 

143 verify_change_here(resource, current_user, db) 

144 except HTTPException: 

145 return False 

146 return True 

147 

148 

149def creator_of(db: Session, kind, resource): 

150 """Who created ``resource``: the actor on its first edit-history version.""" 

151 from app.db.postgres.models import ResourceVersion 

152 

153 row = ( 

154 db.query(ResourceVersion.actor_user_id) 

155 .filter( 

156 ResourceVersion.resource_type == kind.history_type, 

157 ResourceVersion.resource_id == resource.id, 

158 ) 

159 .order_by(ResourceVersion.version_number.asc()) 

160 .first() 

161 ) 

162 return row[0] if row else None 

163 

164 

165def verify_resource_read(resource, current_user, db: Session) -> None: 

166 """Raise 403 unless current_user may **read** the given resource. 

167 

168 Platform-managed rows (``is_system``) are readable by every user: CHAINR 

169 Bot, its guide repository and the knowledge base in it. Referencing a 

170 resource — chatting with an agent, pointing a dashboard tile or an 

171 evaluation at it — is a read. An organisation's or project's resource is 

172 readable by any member, whatever their level in its area: reading and 

173 using is what a reader is for (``app/services/access.py``). A person's 

174 resource is readable by them, and by the members of a personal project 

175 of theirs that inherits it. 

176 """ 

177 if _is_system(resource): 

178 return 

179 if current_user.is_superuser: 

180 return 

181 if resource.owner_user_id is not None: 

182 if resource.owner_user_id == current_user.id: 

183 return 

184 # A person's work is readable by the members of their personal 

185 # projects that inherit it (``app/services/inheritance.py``). 

186 from app.services import inheritance 

187 

188 if inheritance.readable_through_a_project(db, resource, current_user): 

189 return 

190 raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Forbidden") 

191 if resource.owner_organisation_id is not None: 

192 verify_list_scope( 

193 resource.owner_organisation_id, "organisation", current_user, db 

194 ) 

195 elif resource.owner_project_id is not None: 

196 verify_list_scope(resource.owner_project_id, "project", current_user, db) 

197 

198 

199def verify_list_scope( 

200 scope_id: UUID, scope_type: str, current_user, db: Session 

201) -> None: 

202 """Raise 403 if current_user is not a member of the given org or project.""" 

203 if current_user.is_superuser: 

204 return 

205 

206 if scope_type == "organisation": 

207 from app.db.postgres.models import UserOrganisation 

208 

209 membership = ( 

210 db.query(UserOrganisation) 

211 .filter( 

212 UserOrganisation.user_id == current_user.id, 

213 UserOrganisation.organisation_id == scope_id, 

214 ) 

215 .first() 

216 ) 

217 if not membership: 

218 raise HTTPException( 

219 status_code=status.HTTP_403_FORBIDDEN, detail="Forbidden" 

220 ) 

221 

222 elif scope_type == "project": 

223 # A member, or an admin by position: an admin of the organisation 

224 # that owns it, or the owner of a personal project. 

225 from app.services import membership as membership_service 

226 

227 if ( 

228 membership_service.effective_membership( 

229 db, membership_service.PROJECT, scope_id, current_user.id 

230 ) 

231 is None 

232 ): 

233 raise HTTPException( 

234 status_code=status.HTTP_403_FORBIDDEN, detail="Forbidden" 

235 ) 

236 

237 

238_OWNER_COLUMNS = ("owner_user_id", "owner_organisation_id", "owner_project_id") 

239 

240 

241def verify_owner_scope(owner, current_user, db: Session, *, model) -> None: 

242 """Raise 403 unless current_user may create or move a ``model`` into 

243 the owner that ``owner`` names: a member at the kind's create level in 

244 its area (``app/services/access.py``). 

245 

246 ``owner`` is a request body dict or an unsaved model. The owner columns 

247 arrive from the client, so without this a resource can be planted in 

248 another user's account, organisation or project — where it then shows up 

249 in their lists and, for a knowledge base or agent, in what their agents 

250 retrieve. Every column that is set is checked, rather than the first, 

251 so the check does not lean on the one-owner DB constraint to be sound. 

252 """ 

253 if current_user.is_superuser: 

254 return 

255 

256 def _get(column): 

257 if isinstance(owner, dict): 

258 return owner.get(column) 

259 return getattr(owner, column, None) 

260 

261 user_id, organisation_id, project_id = (_get(c) for c in _OWNER_COLUMNS) 

262 if user_id is not None and str(user_id) != str(current_user.id): 

263 raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Forbidden") 

264 if organisation_id is not None: 

265 verify_list_scope(organisation_id, "organisation", current_user, db) 

266 if project_id is not None: 

267 verify_list_scope(project_id, "project", current_user, db) 

268 _require_level( 

269 db, 

270 current_user, 

271 organisation_id=organisation_id, 

272 project_id=project_id, 

273 model=model, 

274 creating=True, 

275 ) 

276 

277 

278def verify_organisation_access(resource, current_user, db: Session) -> None: 

279 """Access check for organisations, which are membership- not owner-scoped. 

280 

281 ``Organisation`` carries no ``owner_*`` columns at all — it *is* an owner 

282 scope — so the default check would allow everyone. Membership is the only 

283 meaningful predicate. 

284 """ 

285 if current_user.is_superuser: 

286 return 

287 

288 from app.db.postgres.models import UserOrganisation 

289 

290 membership = ( 

291 db.query(UserOrganisation) 

292 .filter( 

293 UserOrganisation.user_id == current_user.id, 

294 UserOrganisation.organisation_id == resource.id, 

295 ) 

296 .first() 

297 ) 

298 if not membership: 

299 raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Forbidden") 

300 

301 

302def verify_conversation_access(conversation_id, current_user, db: Session) -> None: 

303 """403 when ``conversation_id`` names somebody else's conversation. 

304 

305 The prompt paths load a conversation's history into the model's context 

306 and append the new turn to it, so continuing a conversation the caller 

307 cannot read would disclose it and write into it. An unknown id is left 

308 alone — the prompt paths already treat it as the start of a new one. 

309 """ 

310 if conversation_id is None: 

311 return 

312 from app.db.postgres.models import Conversation 

313 

314 conversation = db.get(Conversation, conversation_id) 

315 if conversation is not None: 

316 verify_resource_access(conversation, current_user, db) 

317 

318 

319def shared_with(model, user, *, include_system: bool = False): 

320 """The rows of ``model`` that ``user`` sees in a list without naming an 

321 owner: their own, and those of every organisation and project they 

322 belong to. ``include_system`` adds the platform's built-ins. 

323 

324 Lists used to show only what the caller owned personally, so work an 

325 organisation owned appeared on none of the main pages — a shared rule or 

326 dataset was reachable by id and visible nowhere. Each row still says who 

327 owns it (the ``owner_*`` columns on every Read schema), which is how a 

328 page labels it. 

329 """ 

330 from sqlalchemy import or_, select 

331 

332 from app.db.postgres.models import UserOrganisation, UserProject 

333 

334 clauses = [ 

335 model.owner_user_id == user.id, 

336 model.owner_organisation_id.in_( 

337 select(UserOrganisation.organisation_id).where( 

338 UserOrganisation.user_id == user.id 

339 ) 

340 ), 

341 model.owner_project_id.in_( 

342 select(UserProject.project_id).where(UserProject.user_id == user.id) 

343 ), 

344 ] 

345 if include_system and hasattr(model, "is_system"): 

346 clauses.append(model.is_system.is_(True)) 

347 return or_(*clauses) 

348 

349 

350def scoped( 

351 model, 

352 user, 

353 db: Session, 

354 *, 

355 workspace: str | None = None, 

356 owner_organisation_id: UUID | None = None, 

357 owner_project_id: UUID | None = None, 

358 include_system: bool = False, 

359): 

360 """``(filter, workspace)`` for a list endpoint, from what the request 

361 names. 

362 

363 ``workspace`` (``personal`` / ``organisation:<id>`` / ``project:<id>``) 

364 lists exactly that workspace's rows — its own, what a project inherits 

365 from its parent, and built-ins (``app/services/workspace.py``); the 

366 workspace comes back so the endpoint can say why each row is there 

367 (``inheritance.annotate``). The ``owner_*`` parameters are an older 

368 spelling of an organisation or project. Naming neither is Personal: 

369 there is no mixed listing any more — every page shows one workspace. 

370 """ 

371 from app.services import workspace as workspace_service 

372 

373 if not workspace and not owner_organisation_id and not owner_project_id: 

374 workspace = workspace_service.PERSONAL 

375 if workspace: 

376 ws = workspace_service.resolve(db, workspace, user) 

377 return workspace_service.in_scope(model, ws, system=include_system), ws 

378 if owner_organisation_id: 

379 verify_list_scope(owner_organisation_id, "organisation", user, db) 

380 return model.owner_organisation_id == owner_organisation_id, None 

381 verify_list_scope(owner_project_id, "project", user, db) 

382 return model.owner_project_id == owner_project_id, None 

383 

384 

385def list_scope(model, user, db: Session, **names): 

386 """The filter of :func:`scoped`, for a list that doesn't annotate.""" 

387 return scoped(model, user, db, **names)[0] 

388 

389 

390def annotated(rows: list, ws) -> list: 

391 """``rows`` with ``origin`` / ``home_workspace`` set when the listing 

392 named a workspace (``ws``); unchanged otherwise.""" 

393 if ws is None: 

394 return rows 

395 from app.services import inheritance 

396 

397 return inheritance.annotate(rows, ws)