-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathtest_slack_dynamic_token_and_verifier.py
More file actions
1416 lines (1178 loc) · 60.2 KB
/
Copy pathtest_slack_dynamic_token_and_verifier.py
File metadata and controls
1416 lines (1178 loc) · 60.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Tests for the dynamic ``bot_token`` resolver and custom ``webhook_verifier``.
Port of upstream ``vercel/chat#421`` (commit ``2531e9c``) — adds the
``SlackBotToken`` resolver shape and the ``SlackWebhookVerifier`` escape
hatch that bypasses HMAC signature verification.
The custom verifier path is security-sensitive: the default verifier uses
``hmac.compare_digest`` and a 5-minute timestamp tolerance check. A custom
verifier replaces both — these tests assert that the verifier is called,
that throws/falsy returns reject with 401, that string returns substitute
the body for downstream parsing, and that an explicit verifier opts out of
the ``SLACK_SIGNING_SECRET`` env fallback.
"""
from __future__ import annotations
import asyncio
import hashlib
import hmac
import json
import os
import time
from typing import Any
from unittest.mock import AsyncMock, MagicMock
import pytest
try:
from chat_sdk.adapters.slack.adapter import SlackAdapter, create_slack_adapter
from chat_sdk.adapters.slack.types import (
SlackAdapterConfig,
SlackInstallation,
)
from chat_sdk.shared.errors import AuthenticationError, ValidationError
_SLACK_AVAILABLE = True
except ImportError:
_SLACK_AVAILABLE = False
pytestmark = pytest.mark.skipif(not _SLACK_AVAILABLE, reason="Slack adapter import failed")
# ---------------------------------------------------------------------------
# Helpers
# ---------------------------------------------------------------------------
class _FakeRequest:
def __init__(self, body: str, headers: dict[str, str] | None = None):
self.body = body.encode("utf-8")
self.headers = headers or {}
async def text(self) -> str:
return self.body.decode("utf-8")
def _slack_signature(body: str, secret: str, timestamp: int | None = None) -> tuple[str, str]:
ts = str(timestamp or int(time.time()))
sig_base = f"v0:{ts}:{body}"
sig = "v0=" + hmac.new(secret.encode(), sig_base.encode(), hashlib.sha256).hexdigest()
return ts, sig
def _signed_request(body: str, secret: str = "test-signing-secret") -> _FakeRequest:
ts, sig = _slack_signature(body, secret)
return _FakeRequest(
body,
{
"x-slack-request-timestamp": ts,
"x-slack-signature": sig,
"content-type": "application/json",
},
)
def _unsigned_request(body: str, content_type: str = "application/json") -> _FakeRequest:
return _FakeRequest(body, {"content-type": content_type})
def _make_mock_state() -> MagicMock:
cache: dict[str, Any] = {}
state = MagicMock()
state.get = AsyncMock(side_effect=lambda k: cache.get(k))
state.set = AsyncMock(side_effect=lambda k, v, *a, **kw: cache.__setitem__(k, v))
state.delete = AsyncMock(side_effect=lambda k: cache.pop(k, None))
state.append_to_list = AsyncMock()
state.get_list = AsyncMock(return_value=[])
state._cache = cache
return state
def _make_mock_chat(state: MagicMock) -> MagicMock:
chat = MagicMock()
chat.process_message = MagicMock()
chat.handle_incoming_message = AsyncMock()
chat.process_reaction = MagicMock()
chat.process_action = MagicMock()
chat.process_modal_submit = AsyncMock()
chat.process_modal_close = MagicMock()
chat.process_slash_command = MagicMock()
chat.get_state = MagicMock(return_value=state)
chat.get_user_name = MagicMock(return_value="test-bot")
chat.get_logger = MagicMock(return_value=MagicMock())
return chat
# ---------------------------------------------------------------------------
# Constructor: bot_token as a callable resolver
# ---------------------------------------------------------------------------
class TestBotTokenResolverConstruction:
"""``bot_token`` accepts both a static string and a callable resolver."""
def test_accepts_static_string(self):
adapter = SlackAdapter(SlackAdapterConfig(signing_secret="s", bot_token="xoxb-static"))
# current_token is sync — works for static config without ever invoking a resolver.
assert adapter.current_token == "xoxb-static"
def test_accepts_sync_callable(self):
calls: list[int] = []
def resolver() -> str:
calls.append(1)
return "xoxb-from-sync-resolver"
# Construction must not invoke the resolver — verifier-only modes need
# to defer all token resolution to per-request flow.
adapter = SlackAdapter(SlackAdapterConfig(signing_secret="s", bot_token=resolver))
assert isinstance(adapter, SlackAdapter)
assert calls == []
def test_accepts_async_callable(self):
async def resolver() -> str:
return "xoxb-from-async-resolver"
adapter = SlackAdapter(SlackAdapterConfig(signing_secret="s", bot_token=resolver))
# No exception — resolver isn't invoked yet.
assert adapter.name == "slack"
@pytest.mark.asyncio
async def test_sync_resolver_invoked_via_current_token_async(self):
calls: list[int] = []
def resolver() -> str:
calls.append(1)
return "xoxb-from-sync-resolver"
adapter = SlackAdapter(SlackAdapterConfig(signing_secret="s", bot_token=resolver))
token = await adapter.current_token_async()
assert token == "xoxb-from-sync-resolver"
assert calls == [1]
@pytest.mark.asyncio
async def test_async_resolver_invoked_via_current_token_async(self):
calls: list[int] = []
async def resolver() -> str:
calls.append(1)
await asyncio.sleep(0)
return "xoxb-from-async-resolver"
adapter = SlackAdapter(SlackAdapterConfig(signing_secret="s", bot_token=resolver))
token = await adapter.current_token_async()
assert token == "xoxb-from-async-resolver"
assert calls == [1]
@pytest.mark.asyncio
async def test_resolver_invoked_per_call_supports_rotation(self):
tokens = ["xoxb-token-1", "xoxb-token-2", "xoxb-token-3"]
i = [0]
def resolver() -> str:
t = tokens[i[0]]
i[0] += 1
return t
adapter = SlackAdapter(SlackAdapterConfig(signing_secret="s", bot_token=resolver))
assert await adapter.current_token_async() == "xoxb-token-1"
assert await adapter.current_token_async() == "xoxb-token-2"
assert await adapter.current_token_async() == "xoxb-token-3"
assert i[0] == 3
def test_sync_current_token_with_resolver_before_resolution_raises(self):
"""Sync ``current_token`` access before the resolver has run raises a clear error."""
def resolver() -> str:
return "xoxb-resolved"
adapter = SlackAdapter(SlackAdapterConfig(signing_secret="s", bot_token=resolver))
# Tightened: error message must mention ``current_token_async`` so
# callers know the right async accessor to use, not just that "the
# resolver hasn't run". Substring check on "current_token_async"
# is escaped via ``re.escape`` so the underscore isn't treated as a
# regex token (it isn't, but be explicit).
with pytest.raises(AuthenticationError, match=r"current_token_async"):
_ = adapter.current_token
@pytest.mark.asyncio
async def test_resolver_returning_empty_string_raises(self):
def resolver() -> str:
return ""
adapter = SlackAdapter(SlackAdapterConfig(signing_secret="s", bot_token=resolver))
with pytest.raises(AuthenticationError, match="empty or non-string"):
await adapter.current_token_async()
@pytest.mark.asyncio
async def test_resolver_returning_none_raises(self):
"""Non-string ``None`` return must be rejected, not silently used."""
def resolver() -> Any:
return None
adapter = SlackAdapter(SlackAdapterConfig(signing_secret="s", bot_token=resolver))
with pytest.raises(AuthenticationError, match="empty or non-string"):
await adapter.current_token_async()
@pytest.mark.asyncio
async def test_resolver_returning_int_raises(self):
"""Non-string ``int`` (e.g. accidental ``return 0``) must be rejected."""
def resolver() -> Any:
return 12345
adapter = SlackAdapter(SlackAdapterConfig(signing_secret="s", bot_token=resolver))
with pytest.raises(AuthenticationError, match="empty or non-string"):
await adapter.current_token_async()
@pytest.mark.asyncio
async def test_resolver_returning_dict_raises(self):
"""Non-string ``dict`` (e.g. returning the secret-manager response object) must be rejected."""
def resolver() -> Any:
return {"token": "xoxb-buried-in-dict"}
adapter = SlackAdapter(SlackAdapterConfig(signing_secret="s", bot_token=resolver))
with pytest.raises(AuthenticationError, match="empty or non-string"):
await adapter.current_token_async()
@pytest.mark.asyncio
async def test_resolver_propagates_user_exceptions(self):
def resolver() -> str:
raise RuntimeError("token fetch failed")
adapter = SlackAdapter(SlackAdapterConfig(signing_secret="s", bot_token=resolver))
with pytest.raises(RuntimeError, match="token fetch failed"):
await adapter.current_token_async()
@pytest.mark.asyncio
async def test_async_resolver_exception_is_logged_and_propagated(self):
"""Async resolver exceptions raise during ``await``, not at call time.
What to fix if this fails: in ``_resolve_default_token``
(``adapters/slack/adapter.py``), make sure the ``await result`` is
inside the ``try`` block alongside ``provider()`` — otherwise async
resolver failures bypass the logger and the rotation-safety
invariants documented in the PR.
"""
log_calls: list[tuple[str, dict[str, object]]] = []
async def resolver() -> str:
raise RuntimeError("async fetch failed")
adapter = SlackAdapter(SlackAdapterConfig(signing_secret="s", bot_token=resolver))
adapter._logger.error = lambda msg, ctx=None: log_calls.append((msg, ctx or {})) # type: ignore[assignment]
with pytest.raises(RuntimeError, match="async fetch failed"):
await adapter.current_token_async()
assert any(msg == "Bot token resolver raised" for msg, _ in log_calls), (
"_resolve_default_token must log async resolver failures via "
"self._logger.error('Bot token resolver raised'); "
"ensure 'await result' is inside the try block"
)
@pytest.mark.asyncio
async def test_url_verification_bypasses_broken_resolver(self):
"""A broken bot-token resolver must not break Slack's URL verification.
URL verification is a one-time setup ping at app-install / event-
subscription time and only needs the ``challenge`` echo back. No API
call (and thus no token) is required.
What to fix if this fails: in
``src/chat_sdk/adapters/slack/adapter.py`` ``handle_webhook``, the
``url_verification`` short-circuit must run BEFORE
``_resolve_default_token()``. Otherwise a flaky/down secret-manager
keeps Slack from re-subscribing the webhook, which blocks app
installation. Mirrors upstream where ``getToken`` is only called at
per-API-call sites, never at webhook entry.
"""
def resolver() -> str:
raise RuntimeError("secret manager is down")
adapter = SlackAdapter(SlackAdapterConfig(signing_secret="s", bot_token=resolver))
body = json.dumps({"type": "url_verification", "challenge": "abc-123"})
response = await adapter.handle_webhook(_signed_request(body, "s"))
assert response["status"] == 200, (
"URL verification must succeed even when the bot-token resolver is broken; "
"the resolver call must be deferred until after the url_verification short-circuit"
)
assert json.loads(response["body"]) == {"challenge": "abc-123"}
@pytest.mark.asyncio
async def test_resolver_refreshes_sync_token_cache(self):
"""After the resolver runs, sync ``current_token`` sees the resolved token.
Regression for CodeRabbit r3285672709: ``_resolve_default_token``
previously only wrote the per-request ContextVar, so callers reading
``current_token`` *outside* that ContextVar scope (e.g. from a sync
helper invoked from a different task) still saw the pre-resolution
state and raised ``AuthenticationError``. The resolver must also
refresh the process-wide ``_default_bot_token_cache`` so the sync
path returns the freshly resolved value.
What to fix if this fails: in ``_resolve_default_token``
(``adapters/slack/adapter.py``), after the
``isinstance(token, str)`` / non-empty validation and before
``self._resolved_default_token.set(token)``, assign
``self._default_bot_token_cache = token``.
"""
def resolver() -> str:
return "xoxb-resolved-token"
adapter = SlackAdapter(SlackAdapterConfig(signing_secret="s", bot_token=resolver))
# Sanity: before the resolver runs, sync ``current_token`` must raise
# (matches ``test_sync_current_token_with_resolver_before_resolution_raises``).
with pytest.raises(AuthenticationError, match=r"current_token_async"):
_ = adapter.current_token
# Invoke the resolver via the documented async entry point.
token = await adapter.current_token_async()
assert token == "xoxb-resolved-token"
# Now read sync ``current_token`` from a context *without* the
# ContextVar set by the resolver — running the read inside a fresh
# ``asyncio.to_thread`` would copy the ContextVar, so use a brand-new
# asyncio task with the default (empty) ContextVar state by spawning
# a new task and clearing the per-request var.
#
# Simpler equivalent: directly clear the ContextVar and read. The
# per-request var being reset back to ``None`` mirrors the "different
# task, no ContextVar copy" scenario described in the finding.
adapter._resolved_default_token.set(None)
assert adapter.current_token == "xoxb-resolved-token", (
"sync current_token must read from the refreshed "
"_default_bot_token_cache after the resolver succeeds; the "
"ContextVar-only cache breaks sync access outside the request scope"
)
# ---------------------------------------------------------------------------
# Constructor: webhook_verifier
# ---------------------------------------------------------------------------
class TestWebhookVerifierConstruction:
"""Webhook verifier replaces signing_secret as the auth requirement."""
def test_signing_secret_or_verifier_required(self):
old = os.environ.pop("SLACK_SIGNING_SECRET", None)
try:
with pytest.raises(ValidationError, match="signingSecret or webhookVerifier"):
SlackAdapter(SlackAdapterConfig(bot_token="xoxb-x"))
finally:
if old is not None:
os.environ["SLACK_SIGNING_SECRET"] = old
def test_webhook_verifier_alone_is_sufficient(self):
old = os.environ.pop("SLACK_SIGNING_SECRET", None)
try:
adapter = SlackAdapter(
SlackAdapterConfig(
bot_token="xoxb-x",
webhook_verifier=lambda req, body: True,
)
)
assert isinstance(adapter, SlackAdapter)
finally:
if old is not None:
os.environ["SLACK_SIGNING_SECRET"] = old
def test_webhook_verifier_takes_precedence_over_signing_secret(self):
"""When both are set, ``webhook_verifier`` wins.
Port of upstream vercel/chat#468 (commit ``0f0c203``): the original
Python port (PR #87) and upstream both used to prefer
``signing_secret``; upstream has since reversed itself and this port
follows. Callers wiring up a verifier no longer have it silently
shadowed by a present ``signing_secret`` (or ``SLACK_SIGNING_SECRET``
env var; see :meth:`test_verifier_opts_out_of_env_signing_secret`).
"""
verifier_called: list[int] = []
def verifier(req: Any, body: str) -> bool:
verifier_called.append(1)
return True
adapter = SlackAdapter(
SlackAdapterConfig(
signing_secret="s",
bot_token="xoxb-x",
webhook_verifier=verifier,
)
)
# The verifier wins; the explicit signing_secret is dropped so the
# built-in HMAC path is never taken.
assert adapter._webhook_verifier is verifier
assert adapter._signing_secret is None
def test_verifier_opts_out_of_env_signing_secret(self):
"""An explicit verifier suppresses the SLACK_SIGNING_SECRET env fallback.
Regression: a deployment with SLACK_SIGNING_SECRET set in env would
otherwise silently shadow the verifier the caller intended to use.
"""
old = os.environ.get("SLACK_SIGNING_SECRET")
os.environ["SLACK_SIGNING_SECRET"] = "env-secret-should-not-be-used"
try:
adapter = SlackAdapter(
SlackAdapterConfig(
bot_token="xoxb-x",
webhook_verifier=lambda req, body: True,
)
)
assert adapter._signing_secret is None
assert adapter._webhook_verifier is not None
finally:
if old is None:
os.environ.pop("SLACK_SIGNING_SECRET", None)
else:
os.environ["SLACK_SIGNING_SECRET"] = old
def test_empty_signing_secret_rejected_at_construction(self):
"""Explicit ``signing_secret=""`` must fail validation at adapter init.
Regression for Codex P1 on PR #87: the ``is not None`` cascade in
commit ``5a648ec`` over-corrected the truthiness trap — it correctly
stopped empty strings from silently falling through to the env
fallback, but then *accepted* the empty string as a valid signing
secret. ``_verify_signature`` short-circuits with
``if not self._signing_secret`` and returns ``False`` for every
webhook, leaving the adapter responding ``401`` to Slack on every
request rather than failing fast at construction. An explicit empty
string is now rejected outright by a dedicated construction guard
(see :meth:`test_empty_signing_secret_rejected_even_with_verifier`),
so the misconfiguration surfaces here, not on the production webhook
path.
"""
old = os.environ.pop("SLACK_SIGNING_SECRET", None)
try:
with pytest.raises(ValidationError, match="signing_secret must be a non-empty string"):
SlackAdapter(SlackAdapterConfig(signing_secret=""))
# Also fails when an otherwise-valid bot_token is set: the
# signing_secret value is what matters, not the rest of the
# config.
with pytest.raises(ValidationError, match="signing_secret must be a non-empty string"):
SlackAdapter(SlackAdapterConfig(signing_secret="", bot_token="xoxb-test"))
finally:
if old is not None:
os.environ["SLACK_SIGNING_SECRET"] = old
def test_empty_signing_secret_does_not_fall_back_to_env(self):
"""Empty-string ``signing_secret`` is rejected even with SLACK_SIGNING_SECRET set.
Pairs with :meth:`test_empty_signing_secret_rejected_at_construction`:
an explicit empty string is a hard error at construction (the
dedicated guard fires before the env-fallback cascade), so a
deployment-set ``SLACK_SIGNING_SECRET`` cannot rescue the typo. The
user's explicit (if empty) config loses to nothing — it fails fast.
"""
old = os.environ.get("SLACK_SIGNING_SECRET")
os.environ["SLACK_SIGNING_SECRET"] = "env-secret-should-not-be-used"
try:
with pytest.raises(ValidationError, match="signing_secret must be a non-empty string"):
SlackAdapter(SlackAdapterConfig(signing_secret="", bot_token="xoxb-test"))
finally:
if old is None:
os.environ.pop("SLACK_SIGNING_SECRET", None)
else:
os.environ["SLACK_SIGNING_SECRET"] = old
def test_empty_signing_secret_rejected_even_with_verifier(self):
"""``signing_secret=""`` is rejected at construction even with a verifier.
Regression for CodeRabbit Major on PR #87. An explicit empty-string
``signing_secret`` is a config typo (e.g. an unset env var
interpolated into the field). Previously it normalized to ``None`` and,
when a ``webhook_verifier`` was also set, the guard passed and the
adapter silently switched from the built-in HMAC check to the custom
verifier — without the caller's knowledge. The explicit empty string
must now fail fast at construction regardless of whether a verifier is
provided, so the typo surfaces at init rather than silently altering
which verification path runs in production.
"""
old = os.environ.pop("SLACK_SIGNING_SECRET", None)
try:
with pytest.raises(ValidationError, match="signing_secret must be a non-empty string"):
SlackAdapter(
SlackAdapterConfig(
signing_secret="",
bot_token="xoxb-test",
webhook_verifier=lambda req, body: True,
)
)
finally:
if old is not None:
os.environ["SLACK_SIGNING_SECRET"] = old
def test_non_callable_webhook_verifier_rejected_at_construction(self):
"""A non-callable ``webhook_verifier`` must fail validation at init.
Regression for Codex P2 on PR #87. A typo such as
``webhook_verifier=""`` / ``False`` / ``123`` passed the ``is not
None`` guard, then ``handle_webhook`` tried to *call* it, the
resulting ``TypeError`` was caught and reported as an invalid
signature, and every webhook failed closed with 401 — an opaque
production outage from a one-character mistake. Reject any non-None,
non-callable value at construction so the typo surfaces immediately.
"""
old = os.environ.get("SLACK_SIGNING_SECRET")
os.environ["SLACK_SIGNING_SECRET"] = "valid-signing-secret"
try:
for bad in ("", False, 123):
with pytest.raises(ValidationError, match="webhook_verifier must be callable"):
SlackAdapter(
SlackAdapterConfig(
bot_token="xoxb-test",
webhook_verifier=bad, # type: ignore[arg-type]
)
)
finally:
if old is None:
os.environ.pop("SLACK_SIGNING_SECRET", None)
else:
os.environ["SLACK_SIGNING_SECRET"] = old
def test_empty_env_slack_bot_token_does_not_become_static_token(self):
"""``SLACK_BOT_TOKEN=""`` must not be cached as the default bot token.
Regression companion to the empty-signing_secret fix: the env
fallback for ``SLACK_BOT_TOKEN`` was updated in ``5a648ec`` to
use ``if env_token is not None`` to match the
"explicit-empty-is-config" rule. But unlike user config, an empty
env var is the system telling us "no token here" — caching
``""`` as the default bot token would propagate to every Slack
API call as ``Authorization: Bearer `` and surface as opaque
``invalid_auth`` errors. Treat env ``""`` as unset.
"""
old_token = os.environ.get("SLACK_BOT_TOKEN")
old_secret = os.environ.get("SLACK_SIGNING_SECRET")
os.environ["SLACK_BOT_TOKEN"] = ""
os.environ["SLACK_SIGNING_SECRET"] = "valid-signing-secret"
try:
# Zero-config path is what triggers the env fallback.
adapter = SlackAdapter()
assert adapter._default_bot_token_cache is None
assert adapter._default_bot_token_provider is None
finally:
if old_token is None:
os.environ.pop("SLACK_BOT_TOKEN", None)
else:
os.environ["SLACK_BOT_TOKEN"] = old_token
if old_secret is None:
os.environ.pop("SLACK_SIGNING_SECRET", None)
else:
os.environ["SLACK_SIGNING_SECRET"] = old_secret
def test_empty_string_bot_token_rejected_at_construction(self):
"""Explicit ``bot_token=""`` must fail validation at adapter init.
Companion to :meth:`test_empty_signing_secret_rejected_at_construction`
— the same hazard for ``signing_secret=""`` exists for a
user-configured ``bot_token=""``: ``_default_bot_token_cache`` would
be primed with ``""`` and the sync ``_get_token`` path would happily
return it, producing ``Authorization: Bearer `` API calls and
opaque ``invalid_auth`` errors from Slack. The async resolver path
catches this later, but failing fast at construction is strictly
better than failing on every Slack API call in production.
Callable resolvers are unaffected: they may return any string at
resolve time and the empty-result case is already validated in
``_resolve_default_token``.
"""
old_secret = os.environ.pop("SLACK_SIGNING_SECRET", None)
old_token = os.environ.pop("SLACK_BOT_TOKEN", None)
try:
with pytest.raises(ValidationError, match="bot_token"):
SlackAdapter(SlackAdapterConfig(signing_secret="ok", bot_token=""))
finally:
if old_secret is not None:
os.environ["SLACK_SIGNING_SECRET"] = old_secret
if old_token is not None:
os.environ["SLACK_BOT_TOKEN"] = old_token
def test_empty_client_id_does_not_fall_back_to_env(self):
"""Explicit ``client_id=""`` is honored as "not configured", not env-shadowed.
Regression for hazard #1 (truthiness trap) in the OAuth field
cascade. The previous ``config.client_id or env`` pattern silently
converted ``client_id=""`` into the env value when ``zero_config``
was true, and into ``None`` when it wasn't — neither matches the
user's intent. Using ``is not None`` makes the behavior explicit:
an explicit (even empty) user config value wins over env.
"""
old_id = os.environ.get("SLACK_CLIENT_ID")
old_secret = os.environ.get("SLACK_CLIENT_SECRET")
os.environ["SLACK_CLIENT_ID"] = "env-id-should-not-be-used"
os.environ["SLACK_CLIENT_SECRET"] = "env-secret-should-not-be-used"
try:
# Explicit empty user config — env must NOT shadow it. With a
# bot_token set, zero_config is False anyway, so env wouldn't be
# read; this test exercises the multi-workspace zero_config path
# to confirm the per-field ``is not None`` gate also rejects env
# when the user passed an explicit empty value.
adapter = SlackAdapter(SlackAdapterConfig(signing_secret="ok", client_id="", client_secret=""))
assert adapter._client_id == ""
assert adapter._client_secret == ""
finally:
if old_id is None:
os.environ.pop("SLACK_CLIENT_ID", None)
else:
os.environ["SLACK_CLIENT_ID"] = old_id
if old_secret is None:
os.environ.pop("SLACK_CLIENT_SECRET", None)
else:
os.environ["SLACK_CLIENT_SECRET"] = old_secret
def test_empty_env_client_id_treated_as_unset(self):
"""``SLACK_CLIENT_ID=""`` env must not become the resolved client_id.
Mirrors the SLACK_BOT_TOKEN-empty rule from ``2ecd451``: an empty
env value is the system telling us "nothing here", not a valid
configured value. Empty env client_id would surface as opaque
OAuth ``invalid_client`` errors mid-flow rather than a clear "OAuth
not configured" state.
"""
old_token = os.environ.get("SLACK_BOT_TOKEN")
old_secret = os.environ.get("SLACK_SIGNING_SECRET")
old_id = os.environ.get("SLACK_CLIENT_ID")
old_csecret = os.environ.get("SLACK_CLIENT_SECRET")
os.environ.pop("SLACK_BOT_TOKEN", None)
os.environ["SLACK_SIGNING_SECRET"] = "valid-signing-secret"
os.environ["SLACK_CLIENT_ID"] = ""
os.environ["SLACK_CLIENT_SECRET"] = ""
try:
adapter = SlackAdapter()
assert adapter._client_id is None
assert adapter._client_secret is None
finally:
if old_token is None:
os.environ.pop("SLACK_BOT_TOKEN", None)
else:
os.environ["SLACK_BOT_TOKEN"] = old_token
if old_secret is None:
os.environ.pop("SLACK_SIGNING_SECRET", None)
else:
os.environ["SLACK_SIGNING_SECRET"] = old_secret
if old_id is None:
os.environ.pop("SLACK_CLIENT_ID", None)
else:
os.environ["SLACK_CLIENT_ID"] = old_id
if old_csecret is None:
os.environ.pop("SLACK_CLIENT_SECRET", None)
else:
os.environ["SLACK_CLIENT_SECRET"] = old_csecret
def test_empty_encryption_key_does_not_fall_back_to_env(self):
"""Explicit ``encryption_key=""`` is honored as "user opted out", not env-shadowed.
Companion to the ``client_id=""`` / ``client_secret=""`` fix in
``7c30c13``: the previous ``config.encryption_key or env`` pattern
silently substituted ``SLACK_ENCRYPTION_KEY`` whenever the user
explicitly passed an empty string. That violates hazard #1 — an
explicit user config value (even ``""``) must win over env.
Functional impact is narrower than the client_id case because the
end result is gated by ``if encryption_key_raw``, so an empty user
config eventually becomes ``self._encryption_key = None``. But with
env set, env would *replace* the user's explicit "off" intent and
downstream installation tokens would be encrypted with a key the
user didn't ask for — surprising at minimum, and load-bearing for
callers who rotate keys by clearing the explicit config.
"""
import base64
old_key = os.environ.get("SLACK_ENCRYPTION_KEY")
# 32 bytes of `x`, base64-encoded — a valid key shape.
os.environ["SLACK_ENCRYPTION_KEY"] = base64.b64encode(b"x" * 32).decode()
try:
adapter = SlackAdapter(SlackAdapterConfig(signing_secret="s", encryption_key=""))
assert adapter._encryption_key is None, (
"explicit encryption_key='' must opt out of encryption, not "
"silently fall back to SLACK_ENCRYPTION_KEY from env"
)
finally:
if old_key is None:
os.environ.pop("SLACK_ENCRYPTION_KEY", None)
else:
os.environ["SLACK_ENCRYPTION_KEY"] = old_key
# ---------------------------------------------------------------------------
# handle_webhook with custom verifier
# ---------------------------------------------------------------------------
class TestHandleWebhookCustomVerifier:
@pytest.mark.asyncio
async def test_verifier_truthy_accepts_request(self):
adapter = SlackAdapter(
SlackAdapterConfig(
bot_token="xoxb-x",
webhook_verifier=lambda req, body: True,
)
)
body = json.dumps({"type": "url_verification", "challenge": "verifier-challenge"})
response = await adapter.handle_webhook(_unsigned_request(body))
assert response["status"] == 200
assert json.loads(response["body"]) == {"challenge": "verifier-challenge"}
@pytest.mark.asyncio
async def test_verifier_throws_returns_401(self):
def verifier(req: Any, body: str) -> bool:
raise RuntimeError("bad signature")
adapter = SlackAdapter(SlackAdapterConfig(bot_token="xoxb-x", webhook_verifier=verifier))
body = json.dumps({"type": "url_verification"})
response = await adapter.handle_webhook(_unsigned_request(body))
assert response["status"] == 401
@pytest.mark.asyncio
async def test_verifier_returns_false_returns_401(self):
adapter = SlackAdapter(
SlackAdapterConfig(
bot_token="xoxb-x",
webhook_verifier=lambda req, body: False,
)
)
body = json.dumps({"type": "url_verification"})
response = await adapter.handle_webhook(_unsigned_request(body))
assert response["status"] == 401
@pytest.mark.asyncio
async def test_verifier_returns_none_returns_401(self):
adapter = SlackAdapter(
SlackAdapterConfig(
bot_token="xoxb-x",
webhook_verifier=lambda req, body: None,
)
)
body = json.dumps({"type": "url_verification"})
response = await adapter.handle_webhook(_unsigned_request(body))
assert response["status"] == 401
@pytest.mark.asyncio
async def test_verifier_receives_request_and_body(self):
captured: list[tuple[Any, str]] = []
def verifier(req: Any, body: str) -> bool:
captured.append((req, body))
return True
adapter = SlackAdapter(SlackAdapterConfig(bot_token="xoxb-x", webhook_verifier=verifier))
body = json.dumps({"type": "url_verification", "challenge": "x"})
request = _unsigned_request(body)
await adapter.handle_webhook(request)
assert len(captured) == 1
assert captured[0][0] is request
assert captured[0][1] == body
@pytest.mark.asyncio
async def test_async_verifier_is_awaited(self):
async def verifier(req: Any, body: str) -> bool:
await asyncio.sleep(0)
return True
adapter = SlackAdapter(SlackAdapterConfig(bot_token="xoxb-x", webhook_verifier=verifier))
body = json.dumps({"type": "url_verification", "challenge": "async-challenge"})
response = await adapter.handle_webhook(_unsigned_request(body))
assert response["status"] == 200
assert json.loads(response["body"]) == {"challenge": "async-challenge"}
@pytest.mark.asyncio
async def test_verifier_returning_string_substitutes_body(self):
# Verifier swaps the body so the parser sees a different challenge
canonical_body = json.dumps({"type": "url_verification", "challenge": "canonical"})
def verifier(req: Any, body: str) -> str:
return canonical_body
adapter = SlackAdapter(SlackAdapterConfig(bot_token="xoxb-x", webhook_verifier=verifier))
# Original body has a *different* challenge; the verifier's return
# should win for downstream parsing.
original_body = json.dumps({"type": "url_verification", "challenge": "original"})
response = await adapter.handle_webhook(_unsigned_request(original_body))
assert response["status"] == 200
assert json.loads(response["body"]) == {"challenge": "canonical"}
@pytest.mark.asyncio
async def test_verifier_runs_even_when_signing_secret_is_configured(self):
"""``webhook_verifier`` wins over a configured ``signing_secret``.
Port of upstream vercel/chat#468 — the upstream test was previously
titled "prefers signingSecret over webhookVerifier" and asserted
``verifier`` was *not* called when both were set. Upstream reversed
that behavior; this Python port mirrors the new direction: with no
signing headers (which would fail the built-in HMAC check), the
verifier still runs and the request succeeds.
"""
verifier_calls: list[tuple[Any, str]] = []
def verifier(req: Any, body: str) -> bool:
verifier_calls.append((req, body))
return True
adapter = SlackAdapter(
SlackAdapterConfig(
signing_secret="test-signing-secret",
bot_token="xoxb-x",
webhook_verifier=verifier,
)
)
body = json.dumps({"type": "url_verification", "challenge": "test-challenge"})
# No signing headers — only the verifier should run.
response = await adapter.handle_webhook(_FakeRequest(body, {"content-type": "application/json"}))
assert response["status"] == 200
assert json.loads(response["body"]) == {"challenge": "test-challenge"}
assert len(verifier_calls) == 1
@pytest.mark.asyncio
async def test_verifier_path_does_not_invoke_default_signature_check(self):
"""When verifier is configured, the built-in HMAC + timestamp check is skipped.
SECURITY note: this is the documented escape hatch. The implementer
is responsible for replay protection (timestamp freshness) since the
default 5-minute tolerance is bypassed.
"""
# No timestamp/signature headers — would fail the default check —
# but the verifier accepts.
adapter = SlackAdapter(
SlackAdapterConfig(
bot_token="xoxb-x",
webhook_verifier=lambda req, body: True,
)
)
body = json.dumps({"type": "url_verification", "challenge": "no-headers"})
response = await adapter.handle_webhook(_FakeRequest(body, {"content-type": "application/json"}))
assert response["status"] == 200
# ---------------------------------------------------------------------------
# Resolver runs at webhook entry — sync _get_token sees the resolved value
# ---------------------------------------------------------------------------
class TestResolverIntegratedWithWebhookFlow:
@pytest.mark.asyncio
async def test_handle_webhook_invokes_resolver_before_dispatch(self):
"""For real event payloads, the resolver is invoked at handle_webhook
entry so downstream sync ``_get_token`` callers see the resolved
value.
Note: url_verification is now special-cased and short-circuits
BEFORE the resolver runs (see test_url_verification_bypasses_broken_resolver
above) — so this test uses a regular ``event_callback`` payload to
exercise the resolver-before-dispatch invariant.
"""
calls: list[int] = []
def resolver() -> str:
calls.append(1)
return "xoxb-from-resolver"
adapter = SlackAdapter(
SlackAdapterConfig(
signing_secret="test-signing-secret",
bot_token=resolver,
)
)
# Use an event_callback (a real Slack event) — this is the path that
# actually needs a token in dispatch. URL verification doesn't.
body = json.dumps(
{
"type": "event_callback",
"team_id": "T123",
"event": {"type": "app_mention", "user": "U1", "channel": "C1", "ts": "1.0", "text": "hi"},
}
)
response = await adapter.handle_webhook(_signed_request(body))
# event_callback returns 200 even if no handlers fire.
assert response["status"] == 200
assert calls == [1], "resolver must be invoked at handle_webhook entry for real events"
@pytest.mark.asyncio
async def test_resolver_result_visible_to_sync_get_token_during_dispatch(self):
"""During webhook processing, sync ``_get_token`` returns the freshly resolved value."""
resolved: list[str | None] = []
def resolver() -> str:
return "xoxb-rotated"
adapter = SlackAdapter(
SlackAdapterConfig(
signing_secret="test-signing-secret",
bot_token=resolver,
)
)
# Custom verifier captures the sync token visible from inside dispatch.
# The verifier runs BEFORE the resolver primes the per-request cache,
# so we instead patch _process_event_payload to capture mid-dispatch.
original = adapter._process_event_payload
def capture(payload: Any, options: Any = None) -> None:
try:
resolved.append(adapter._get_token())
except Exception as exc: # pragma: no cover - debug aid
resolved.append(f"ERR: {exc!r}")
original(payload, options)
adapter._process_event_payload = capture # type: ignore[method-assign]
body = json.dumps(
{
"type": "event_callback",
"event": {"type": "user_change", "user": {"id": "U1"}},
"team_id": "T1",
}
)
await adapter.handle_webhook(_signed_request(body))
assert resolved == ["xoxb-rotated"]
# ---------------------------------------------------------------------------
# Per-request isolation: concurrent webhooks see their own resolved token
# ---------------------------------------------------------------------------
class TestConcurrentRequestIsolation:
@pytest.mark.asyncio
async def test_concurrent_resolver_invocations_do_not_leak_across_requests(self):
"""Two concurrent ``_resolve_default_token`` calls each see their own token.
Regression guard for hazard #6 (ContextVar boundaries): the
per-request resolved token cache must use ContextVar, not a shared
instance attribute. We force the second call to await BEFORE its
``_get_token()`` read so that, if the cache were a shared instance
attribute, the first task's overwrite would leak into the second
task's read.
"""
i = [0]
# Both tasks enter the resolver and obtain their own token. Then the
# FIRST task gates on this event before reading _get_token, so that
# the SECOND task can run its full resolve+set+read cycle in
# between. With a per-request ContextVar the first task's read
# still returns its own resolved token; with a shared attribute it
# would be clobbered by the second task's set.
first_task_can_read = asyncio.Event()
second_task_done = asyncio.Event()
async def resolver() -> str:
n = i[0]
i[0] += 1
return f"xoxb-call-{n}"
adapter = SlackAdapter(
SlackAdapterConfig(
signing_secret="test-signing-secret",
bot_token=resolver,
)
)
async def call(label: str, is_first: bool) -> tuple[str, str]:
await adapter._resolve_default_token()
if is_first:
# Wait for the second task to fully run its resolve cycle.
await first_task_can_read.wait()
else:
# Yield so the first task already passed _resolve_default_token.
await asyncio.sleep(0)
await adapter._resolve_default_token()
second_task_done.set()
first_task_can_read.set()
token = adapter._get_token()
return label, token
async def first() -> tuple[str, str]:
return await call("first", is_first=True)
async def second() -> tuple[str, str]:
# Let the first task enter call() and pass its first await.
await asyncio.sleep(0)
return await call("second", is_first=False)