Coverage for app/backend/src/tests/fixtures/sessions.py: 99%

305 statements  

« prev     ^ index     » next       coverage.py v7.17.2, created at 2026-11-10 09:48 +0000

1from collections.abc import Generator 

2from concurrent import futures 

3from contextlib import contextmanager 

4from typing import Any, NoReturn 

5from zoneinfo import ZoneInfo 

6 

7import grpc 

8from grpc._server import _validate_generic_rpc_handlers 

9 

10from couchers.context import make_interactive_context 

11from couchers.db import session_scope 

12from couchers.i18n import LocalizationContext 

13from couchers.i18n.locales import DEFAULT_LOCALE 

14from couchers.middleware.interceptors import ( 

15 CouchersMiddlewareInterceptor, 

16 _try_get_and_update_user_details, 

17 check_permissions, 

18) 

19from couchers.middleware.proto_annotations import get_proto_annotations 

20from couchers.proto import ( 

21 account_pb2_grpc, 

22 admin_pb2_grpc, 

23 api_pb2_grpc, 

24 auth_pb2_grpc, 

25 blocking_pb2_grpc, 

26 bugs_pb2_grpc, 

27 communities_pb2_grpc, 

28 conversations_pb2_grpc, 

29 discussions_pb2_grpc, 

30 donations_pb2_grpc, 

31 editor_pb2_grpc, 

32 galleries_pb2_grpc, 

33 gis_pb2_grpc, 

34 groups_pb2_grpc, 

35 iris_pb2_grpc, 

36 jail_pb2_grpc, 

37 media_pb2_grpc, 

38 moderation_pb2_grpc, 

39 notifications_pb2_grpc, 

40 pages_pb2_grpc, 

41 postal_verification_pb2_grpc, 

42 public_pb2_grpc, 

43 public_trips_pb2_grpc, 

44 references_pb2_grpc, 

45 reporting_pb2_grpc, 

46 resources_pb2_grpc, 

47 screens_pb2_grpc, 

48 search_pb2_grpc, 

49 stripe_pb2_grpc, 

50 threads_pb2_grpc, 

51) 

52from couchers.servicers.account import Account, Iris 

53from couchers.servicers.admin import Admin 

54from couchers.servicers.api import API 

55from couchers.servicers.auth import Auth 

56from couchers.servicers.blocking import Blocking 

57from couchers.servicers.bugs import Bugs 

58from couchers.servicers.communities import Communities 

59from couchers.servicers.conversations import Conversations 

60from couchers.servicers.discussions import Discussions 

61from couchers.servicers.donations import Donations, Stripe 

62from couchers.servicers.editor import Editor 

63from couchers.servicers.galleries import Galleries 

64from couchers.servicers.gis import GIS 

65from couchers.servicers.groups import Groups 

66from couchers.servicers.jail import Jail 

67from couchers.servicers.media import Media, get_media_auth_interceptor 

68from couchers.servicers.moderation import Moderation 

69from couchers.servicers.notifications import Notifications 

70from couchers.servicers.pages import Pages 

71from couchers.servicers.postal_verification import PostalVerification 

72from couchers.servicers.public import Public 

73from couchers.servicers.public_trips import PublicTrips 

74from couchers.servicers.references import References 

75from couchers.servicers.reporting import Reporting 

76from couchers.servicers.resources import Resources 

77from couchers.servicers.screens import Screens 

78from couchers.servicers.search import Search 

79from couchers.servicers.threads import Threads 

80from tests.fixtures import query_log 

81 

82 

83class _MockCouchersContext: 

84 @property 

85 def headers(self): 

86 return {} 

87 

88 def get_header(self, name): 

89 return None 

90 

91 def set_cookies(self, cookies): 

92 pass 

93 

94 

95class CookieMetadataPlugin(grpc.AuthMetadataPlugin): 

96 """ 

97 Injects the right `cookie: couchers-sesh=...` header into the metadata 

98 """ 

99 

100 def __init__(self, token: str): 

101 self.token = token 

102 

103 def __call__(self, context, callback) -> None: 

104 callback((("cookie", f"couchers-sesh={self.token}"),), None) 

105 

106 

107class MetadataKeeperInterceptor(grpc.UnaryUnaryClientInterceptor): 

108 def __init__(self): 

109 self.latest_headers = {} 

110 

111 def intercept_unary_unary(self, continuation, client_call_details, request): 

112 call = continuation(client_call_details, request) 

113 self.latest_headers = dict(call.initial_metadata()) 

114 self.latest_header_raw = call.initial_metadata() 

115 return call 

116 

117 

118class QuerySpanInterceptor(grpc.ServerInterceptor): 

119 """Attributes the queries a handler issues to the RPC being served. 

120 

121 Wraps only the returned handler, not the continuation, so the downstream middleware's auth lookups stay out of 

122 the span. The wrapper runs on the thread that services the call, which is what query_log's thread-local needs. 

123 """ 

124 

125 def intercept_service(self, continuation, handler_call_details): 

126 method = handler_call_details.method 

127 # The downstream middleware authenticates inside its own intercept_service, so this span covers the auth 

128 # lookups. They're a real per-call cost and worth seeing, just not conflated with the handler's own work. 

129 with query_log.span("auth", method): 

130 handler = continuation(handler_call_details) 

131 if handler is None or handler.unary_unary is None: 131 ↛ 132line 131 didn't jump to line 132 because the condition on line 131 was never true

132 return handler 

133 

134 inner = handler.unary_unary 

135 

136 def wrapper(request, context): 

137 with query_log.span("rpc", method): 

138 return inner(request, context) 

139 

140 return grpc.unary_unary_rpc_method_handler( 

141 wrapper, 

142 request_deserializer=handler.request_deserializer, 

143 response_serializer=handler.response_serializer, 

144 ) 

145 

146 

147class FakeRpcError(grpc.RpcError): 

148 def __init__(self, code: grpc.StatusCode, details: str): 

149 self._code = code 

150 self._details = details 

151 

152 def code(self) -> grpc.StatusCode: 

153 return self._code 

154 

155 def details(self) -> str: 

156 return self._details 

157 

158 

159class MockGrpcContext: 

160 """ 

161 Pure mock of grpc.ServicerContext for testing. 

162 """ 

163 

164 def __init__(self): 

165 self._initial_metadata = [] 

166 self._invocation_metadata: list[tuple[str, str]] = [] 

167 

168 def abort(self, code: grpc.StatusCode, details: str) -> NoReturn: 

169 raise FakeRpcError(code, details) 

170 

171 def invocation_metadata(self) -> list[tuple[str, str]]: 

172 return self._invocation_metadata 

173 

174 def send_initial_metadata(self, metadata): 

175 self._initial_metadata.extend(metadata) 

176 

177 

178class FakeChannel: 

179 """ 

180 Mock gRPC channel for testing that orchestrates context creation. 

181 

182 This holds the test state (token) and creates proper CouchersContext 

183 instances when handlers are invoked. 

184 """ 

185 

186 def __init__(self, token: str | None = None, *, locale: str | None = None): 

187 self.handlers: dict[str, Any] = {} 

188 self._token = token 

189 self._locale = locale or DEFAULT_LOCALE 

190 

191 def add_generic_rpc_handlers(self, generic_rpc_handlers: Any): 

192 _validate_generic_rpc_handlers(generic_rpc_handlers) 

193 self.handlers.update(generic_rpc_handlers[0]._method_handlers) 

194 

195 def unary_unary(self, method, request_serializer, response_deserializer): 

196 handler = self.handlers[method] 

197 

198 def fake_handler(request): 

199 with query_log.span("auth", method): 

200 auth_info = _try_get_and_update_user_details( 

201 self._token, 

202 is_api_key=False, 

203 ip_address="127.0.0.1", 

204 user_agent="Testing User-Agent", 

205 sofa=None, 

206 client_platform=None, 

207 ) 

208 auth_level = get_proto_annotations().auth_level(method) 

209 check_permissions(auth_info, auth_level) 

210 

211 # Do a full serialization cycle on the request and the 

212 # response to catch accidental use of unserializable data. 

213 request = handler.request_deserializer(request_serializer(request)) 

214 

215 # Span covers the handler and its session but not the auth lookup above, matching the boundary 

216 # couchers.middleware.perf uses in prod and the real-server sessions below. 

217 with query_log.span("rpc", method), session_scope() as session: 

218 context = make_interactive_context( 

219 grpc_context=MockGrpcContext(), 

220 user_id=auth_info.user_id if auth_info else None, 

221 is_api_key=False, 

222 token=self._token if auth_info else None, 

223 localization=LocalizationContext( 

224 locale=(auth_info and auth_info.ui_language_preference) or self._locale, 

225 timezone=ZoneInfo((auth_info and auth_info.timezone) or "Etc/UTC"), 

226 ), 

227 sofa="test_sofa_cookie_value", 

228 ) 

229 

230 response = handler.unary_unary(request, context, session) 

231 

232 return response_deserializer(handler.response_serializer(response)) 

233 

234 return fake_handler 

235 

236 

237@contextmanager 

238def run_server(grpc_channel_options=(), token: str | None = None): 

239 with futures.ThreadPoolExecutor(1) as executor: 

240 if token: 

241 call_creds = grpc.metadata_call_credentials(CookieMetadataPlugin(token)) 

242 creds = grpc.composite_channel_credentials(grpc.local_channel_credentials(), call_creds) 

243 else: 

244 creds = grpc.local_channel_credentials() 

245 

246 srv = grpc.server(executor, interceptors=[QuerySpanInterceptor(), CouchersMiddlewareInterceptor()]) 

247 port = srv.add_secure_port("localhost:0", grpc.local_server_credentials()) 

248 srv.start() 

249 

250 try: 

251 with grpc.secure_channel(f"localhost:{port}", creds, options=grpc_channel_options) as channel: 

252 metadata_interceptor = MetadataKeeperInterceptor() 

253 channel = grpc.intercept_channel(channel, metadata_interceptor) 

254 yield srv, channel, metadata_interceptor 

255 finally: 

256 srv.stop(None).wait() 

257 

258 

259# Sessions that start a real GRPC server. 

260@contextmanager 

261def auth_api_session( 

262 grpc_channel_options=(), 

263) -> Generator[tuple[auth_pb2_grpc.AuthStub, MetadataKeeperInterceptor]]: 

264 """ 

265 Create an Auth API for testing 

266 

267 This needs to use the real server since it plays around with headers 

268 """ 

269 with run_server(grpc_channel_options) as (server, channel, metadata_interceptor): 

270 auth_pb2_grpc.add_AuthServicer_to_server(Auth(), server) 

271 yield auth_pb2_grpc.AuthStub(channel), metadata_interceptor 

272 

273 

274@contextmanager 

275def real_api_session(token: str): 

276 """ 

277 Create an API for testing, using TCP sockets, uses the token for auth 

278 """ 

279 with run_server(token=token) as (server, channel, metadata_interceptor): 

280 api_pb2_grpc.add_APIServicer_to_server(API(), server) 

281 yield api_pb2_grpc.APIStub(channel) 

282 

283 

284@contextmanager 

285def real_admin_session(token: str): 

286 """ 

287 Create an Admin service for testing, using TCP sockets, uses the token for auth 

288 """ 

289 with run_server(token=token) as (server, channel, metadata_interceptor): 

290 admin_pb2_grpc.add_AdminServicer_to_server(Admin(), server) 

291 yield admin_pb2_grpc.AdminStub(channel) 

292 

293 

294@contextmanager 

295def real_editor_session(token: str): 

296 """ 

297 Create an Editor service for testing, using TCP sockets, uses the token for auth 

298 """ 

299 with run_server(token=token) as (server, channel, metadata_interceptor): 

300 editor_pb2_grpc.add_EditorServicer_to_server(Editor(), server) 

301 yield editor_pb2_grpc.EditorStub(channel) 

302 

303 

304@contextmanager 

305def real_moderation_session(token: str): 

306 """ 

307 Create a Moderation service for testing, using TCP sockets, uses the token for auth 

308 """ 

309 with run_server(token=token) as (server, channel, metadata_interceptor): 

310 moderation_pb2_grpc.add_ModerationServicer_to_server(Moderation(), server) 

311 yield moderation_pb2_grpc.ModerationStub(channel) 

312 

313 

314@contextmanager 

315def real_account_session(token: str): 

316 """ 

317 Create an Account service for testing, using TCP sockets, uses the token for auth 

318 """ 

319 with run_server(token=token) as (server, channel, metadata_interceptor): 

320 account_pb2_grpc.add_AccountServicer_to_server(Account(), server) 

321 yield account_pb2_grpc.AccountStub(channel) 

322 

323 

324@contextmanager 

325def real_jail_session(token: str): 

326 """ 

327 Create a Jail service for testing, using TCP sockets, uses the token for auth 

328 """ 

329 with run_server(token=token) as (server, channel, metadata_interceptor): 

330 jail_pb2_grpc.add_JailServicer_to_server(Jail(), server) 

331 yield jail_pb2_grpc.JailStub(channel) 

332 

333 

334@contextmanager 

335def real_stripe_session(): 

336 """ 

337 Create a Stripe service for testing, using TCP sockets 

338 """ 

339 with run_server() as (server, channel, metadata_interceptor): 

340 stripe_pb2_grpc.add_StripeServicer_to_server(Stripe(), server) 

341 yield stripe_pb2_grpc.StripeStub(channel) 

342 

343 

344@contextmanager 

345def real_iris_session(): 

346 with run_server() as (server, channel, metadata_interceptor): 

347 iris_pb2_grpc.add_IrisServicer_to_server(Iris(), server) 

348 yield iris_pb2_grpc.IrisStub(channel) 

349 

350 

351@contextmanager 

352def real_bugs_session(): 

353 """ 

354 Bugs over a real server so requests can carry metadata (HTTP request headers) 

355 and the response's initial metadata (HTTP response headers) can be asserted. 

356 """ 

357 with run_server() as (server, channel, metadata_interceptor): 

358 bugs_pb2_grpc.add_BugsServicer_to_server(Bugs(), server) 

359 yield bugs_pb2_grpc.BugsStub(channel), metadata_interceptor 

360 

361 

362@contextmanager 

363def media_session(bearer_token: str): 

364 """ 

365 Create a fresh Media API for testing, uses the bearer token for media auth 

366 """ 

367 media_auth_interceptor = get_media_auth_interceptor(bearer_token) 

368 

369 with futures.ThreadPoolExecutor(1) as executor: 

370 server = grpc.server(executor, interceptors=[media_auth_interceptor]) 

371 port = server.add_secure_port("localhost:0", grpc.local_server_credentials()) 

372 media_pb2_grpc.add_MediaServicer_to_server(Media(), server) 

373 server.start() 

374 

375 call_creds = grpc.access_token_call_credentials(bearer_token) 

376 comp_creds = grpc.composite_channel_credentials(grpc.local_channel_credentials(), call_creds) 

377 

378 try: 

379 with grpc.secure_channel(f"localhost:{port}", comp_creds) as channel: 

380 yield media_pb2_grpc.MediaStub(channel) 

381 finally: 

382 server.stop(None).wait() 

383 

384 

385# Sessions that don't need to start a real GRPC server. 

386# Note: these don't need to be context managers, but they are so that 

387# we can switch to a real implementation if needed. 

388@contextmanager 

389def api_session(token: str): 

390 """ 

391 Create an API for testing, uses the token for auth 

392 """ 

393 channel = FakeChannel(token) 

394 api_pb2_grpc.add_APIServicer_to_server(API(), channel) 

395 yield api_pb2_grpc.APIStub(channel) 

396 

397 

398@contextmanager 

399def gis_session(token: str): 

400 channel = FakeChannel(token) 

401 gis_pb2_grpc.add_GISServicer_to_server(GIS(), channel) 

402 yield gis_pb2_grpc.GISStub(channel) 

403 

404 

405@contextmanager 

406def public_session(token: str | None = None): 

407 channel = FakeChannel(token) 

408 public_pb2_grpc.add_PublicServicer_to_server(Public(), channel) 

409 yield public_pb2_grpc.PublicStub(channel) 

410 

411 

412@contextmanager 

413def public_trips_session(token: str): 

414 channel = FakeChannel(token) 

415 public_trips_pb2_grpc.add_PublicTripsServicer_to_server(PublicTrips(), channel) 

416 yield public_trips_pb2_grpc.PublicTripsStub(channel) 

417 

418 

419@contextmanager 

420def conversations_session(token: str): 

421 """ 

422 Create a Conversations API for testing, uses the token for auth 

423 """ 

424 channel = FakeChannel(token) 

425 conversations_pb2_grpc.add_ConversationsServicer_to_server(Conversations(), channel) 

426 yield conversations_pb2_grpc.ConversationsStub(channel) 

427 

428 

429@contextmanager 

430def threads_session(token: str): 

431 channel = FakeChannel(token) 

432 threads_pb2_grpc.add_ThreadsServicer_to_server(Threads(), channel) 

433 yield threads_pb2_grpc.ThreadsStub(channel) 

434 

435 

436@contextmanager 

437def discussions_session(token: str): 

438 channel = FakeChannel(token) 

439 discussions_pb2_grpc.add_DiscussionsServicer_to_server(Discussions(), channel) 

440 yield discussions_pb2_grpc.DiscussionsStub(channel) 

441 

442 

443@contextmanager 

444def screens_session(token: str): 

445 channel = FakeChannel(token) 

446 screens_pb2_grpc.add_ScreensServicer_to_server(Screens(), channel) 

447 yield screens_pb2_grpc.ScreensStub(channel) 

448 

449 

450@contextmanager 

451def donations_session(token: str): 

452 channel = FakeChannel(token) 

453 donations_pb2_grpc.add_DonationsServicer_to_server(Donations(), channel) 

454 yield donations_pb2_grpc.DonationsStub(channel) 

455 

456 

457@contextmanager 

458def pages_session(token: str): 

459 channel = FakeChannel(token) 

460 pages_pb2_grpc.add_PagesServicer_to_server(Pages(), channel) 

461 yield pages_pb2_grpc.PagesStub(channel) 

462 

463 

464@contextmanager 

465def communities_session(token: str): 

466 channel = FakeChannel(token) 

467 communities_pb2_grpc.add_CommunitiesServicer_to_server(Communities(), channel) 

468 yield communities_pb2_grpc.CommunitiesStub(channel) 

469 

470 

471@contextmanager 

472def groups_session(token: str): 

473 channel = FakeChannel(token) 

474 groups_pb2_grpc.add_GroupsServicer_to_server(Groups(), channel) 

475 yield groups_pb2_grpc.GroupsStub(channel) 

476 

477 

478@contextmanager 

479def blocking_session(token: str): 

480 channel = FakeChannel(token) 

481 blocking_pb2_grpc.add_BlockingServicer_to_server(Blocking(), channel) 

482 yield blocking_pb2_grpc.BlockingStub(channel) 

483 

484 

485@contextmanager 

486def notifications_session(token: str): 

487 channel = FakeChannel(token) 

488 notifications_pb2_grpc.add_NotificationsServicer_to_server(Notifications(), channel) 

489 yield notifications_pb2_grpc.NotificationsStub(channel) 

490 

491 

492@contextmanager 

493def account_session(token: str): 

494 """ 

495 Create a Account API for testing, uses the token for auth 

496 """ 

497 channel = FakeChannel(token) 

498 account_pb2_grpc.add_AccountServicer_to_server(Account(), channel) 

499 yield account_pb2_grpc.AccountStub(channel) 

500 

501 

502@contextmanager 

503def search_session(token: str): 

504 """ 

505 Create a Search API for testing, uses the token for auth 

506 """ 

507 channel = FakeChannel(token) 

508 search_pb2_grpc.add_SearchServicer_to_server(Search(), channel) 

509 yield search_pb2_grpc.SearchStub(channel) 

510 

511 

512@contextmanager 

513def references_session(token: str): 

514 """ 

515 Create a References API for testing, uses the token for auth 

516 """ 

517 channel = FakeChannel(token) 

518 references_pb2_grpc.add_ReferencesServicer_to_server(References(), channel) 

519 yield references_pb2_grpc.ReferencesStub(channel) 

520 

521 

522@contextmanager 

523def galleries_session(token: str): 

524 """ 

525 Create a Galleries API for testing, uses the token for auth 

526 """ 

527 channel = FakeChannel(token) 

528 galleries_pb2_grpc.add_GalleriesServicer_to_server(Galleries(), channel) 

529 yield galleries_pb2_grpc.GalleriesStub(channel) 

530 

531 

532@contextmanager 

533def reporting_session(token: str): 

534 channel = FakeChannel(token) 

535 reporting_pb2_grpc.add_ReportingServicer_to_server(Reporting(), channel) 

536 yield reporting_pb2_grpc.ReportingStub(channel) 

537 

538 

539@contextmanager 

540def postal_verification_session(token: str): 

541 channel = FakeChannel(token) 

542 postal_verification_pb2_grpc.add_PostalVerificationServicer_to_server(PostalVerification(), channel) 

543 yield postal_verification_pb2_grpc.PostalVerificationStub(channel) 

544 

545 

546@contextmanager 

547def bugs_session(token: str | None = None): 

548 channel = FakeChannel(token) 

549 bugs_pb2_grpc.add_BugsServicer_to_server(Bugs(), channel) 

550 yield bugs_pb2_grpc.BugsStub(channel) 

551 

552 

553@contextmanager 

554def resources_session(*, locale: str | None = None): 

555 channel = FakeChannel(locale=locale) 

556 resources_pb2_grpc.add_ResourcesServicer_to_server(Resources(), channel) 

557 yield resources_pb2_grpc.ResourcesStub(channel)