Skip to content

Commit fe13bb2

Browse files
authored
feat(oauth): add StatelessOAuthStateStore using JWT (#1916)
1 parent 99f4fed commit fe13bb2

3 files changed

Lines changed: 148 additions & 0 deletions

File tree

‎slack_sdk/oauth/state_store/__init__.py‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,8 +6,10 @@
66
# from .amazon_s3_state_store import AmazonS3OAuthStateStore
77
from .file import FileOAuthStateStore
88
from .state_store import OAuthStateStore
9+
from .stateless import StatelessOAuthStateStore
910

1011
__all__ = [
1112
"FileOAuthStateStore",
1213
"OAuthStateStore",
14+
"StatelessOAuthStateStore",
1315
]
Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
1+
import base64
2+
import hashlib
3+
import hmac
4+
import json
5+
import logging
6+
import time
7+
from logging import Logger
8+
9+
from ..async_state_store import AsyncOAuthStateStore
10+
from ..state_store import OAuthStateStore
11+
12+
13+
class StatelessOAuthStateStore(OAuthStateStore, AsyncOAuthStateStore):
14+
def __init__(
15+
self,
16+
*,
17+
expiration_seconds: int,
18+
signing_secret: str,
19+
logger: Logger = logging.getLogger(__name__),
20+
):
21+
self.expiration_seconds = expiration_seconds
22+
self.signing_secret = signing_secret
23+
self._logger = logger
24+
25+
@property
26+
def logger(self) -> Logger:
27+
if self._logger is None:
28+
self._logger = logging.getLogger(__name__)
29+
return self._logger
30+
31+
@staticmethod
32+
def _b64url_encode(data: bytes) -> str:
33+
return base64.urlsafe_b64encode(data).rstrip(b"=").decode("utf-8")
34+
35+
@staticmethod
36+
def _b64url_decode(data: str) -> bytes:
37+
padded = data + "=" * (4 - len(data) % 4)
38+
return base64.urlsafe_b64decode(padded)
39+
40+
def _sign(self, message: str) -> str:
41+
return self._b64url_encode(
42+
hmac.new(
43+
self.signing_secret.encode("utf-8"),
44+
message.encode("utf-8"),
45+
hashlib.sha256,
46+
).digest()
47+
)
48+
49+
def issue(self, *args, **kwargs) -> str:
50+
header = self._b64url_encode(json.dumps({"alg": "HS256", "typ": "JWT"}, separators=(",", ":")).encode())
51+
payload = self._b64url_encode(
52+
json.dumps({"exp": int(time.time()) + self.expiration_seconds}, separators=(",", ":")).encode()
53+
)
54+
signature = self._sign(f"{header}.{payload}")
55+
return f"{header}.{payload}.{signature}"
56+
57+
def consume(self, state: str) -> bool:
58+
try:
59+
parts = state.split(".")
60+
if len(parts) != 3:
61+
return False
62+
header, payload, signature = parts
63+
expected_signature = self._sign(f"{header}.{payload}")
64+
if not hmac.compare_digest(signature, expected_signature):
65+
self.logger.warning("Invalid JWT signature for state parameter")
66+
return False
67+
claims = json.loads(self._b64url_decode(payload))
68+
exp = claims.get("exp")
69+
if exp is None or time.time() > exp:
70+
self.logger.warning("Expired or missing exp claim in state JWT")
71+
return False
72+
return True
73+
except Exception as e:
74+
self.logger.warning(f"Failed to validate state JWT: {e}")
75+
return False
76+
77+
async def async_issue(self, *args, **kwargs) -> str:
78+
return self.issue(*args, **kwargs)
79+
80+
async def async_consume(self, state: str) -> bool:
81+
return self.consume(state)
Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
import unittest
2+
3+
from slack_sdk.oauth.state_store import StatelessOAuthStateStore
4+
5+
6+
class TestStateless(unittest.TestCase):
7+
def setUp(self):
8+
self.store = StatelessOAuthStateStore(
9+
expiration_seconds=10,
10+
signing_secret="test-signing-secret",
11+
)
12+
13+
def tearDown(self):
14+
pass
15+
16+
def test_instance(self):
17+
self.assertIsNotNone(self.store)
18+
19+
def test_issue_returns_jwt_format(self):
20+
state = self.store.issue()
21+
self.assertEqual(len(state.split(".")), 3)
22+
23+
def test_issue_and_consume(self):
24+
state = self.store.issue()
25+
result = self.store.consume(state)
26+
self.assertTrue(result)
27+
28+
def test_consume_is_repeatable(self):
29+
state = self.store.issue()
30+
self.assertTrue(self.store.consume(state))
31+
self.assertTrue(self.store.consume(state))
32+
33+
def test_invalid_state_format(self):
34+
self.assertFalse(self.store.consume("not-a-jwt"))
35+
36+
def test_tampered_signature(self):
37+
state = self.store.issue()
38+
parts = state.split(".")
39+
parts[2] = "invalidsignature"
40+
self.assertFalse(self.store.consume(".".join(parts)))
41+
42+
def test_tampered_payload(self):
43+
state = self.store.issue()
44+
parts = state.split(".")
45+
parts[1] = parts[1][:-2] + "AA"
46+
self.assertFalse(self.store.consume(".".join(parts)))
47+
48+
def test_wrong_signing_secret(self):
49+
store2 = StatelessOAuthStateStore(
50+
expiration_seconds=10,
51+
signing_secret="different-secret",
52+
)
53+
state = self.store.issue()
54+
self.assertFalse(store2.consume(state))
55+
56+
def test_expired_state(self):
57+
expired_store = StatelessOAuthStateStore(
58+
expiration_seconds=-1,
59+
signing_secret="test-signing-secret",
60+
)
61+
state = expired_store.issue()
62+
self.assertFalse(self.store.consume(state))
63+
64+
def test_kwargs(self):
65+
self.store.issue(foo=123, bar="baz")

0 commit comments

Comments
 (0)