fd-line-auth 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,214 @@
1
+ """Offline verification of FindData per-line (gate K) tokens.
2
+
3
+ One implementation for every line. A line only injects configuration (its name,
4
+ its issuer, its public key source); the security surface — TTL ceiling, reason
5
+ codes, accepted algorithms, verification order — lives here and cannot drift
6
+ per line.
7
+
8
+ Gate K token shape (minted by the registry gateway):
9
+ iss = gateway, aud = source = <line>, exp - iat <= 600s, sub = billing principal.
10
+
11
+ Differences from the member-level (gate A) assertion are deliberate: gate K is
12
+ reusable within its TTL (no one-time jti), and it carries `source` as both the
13
+ metering attribution and the cross-line-reuse guard.
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ import os
19
+ from dataclasses import dataclass
20
+ from typing import Any, Callable
21
+
22
+ __all__ = [
23
+ "MAX_TTL_SECONDS",
24
+ "LineTokenIdentity",
25
+ "LineTokenRejected",
26
+ "LineTokenSettings",
27
+ "env_names",
28
+ "settings_from_env",
29
+ "verify_line_token",
30
+ ]
31
+
32
+ #: Gate K token lifetime ceiling (seconds). The gateway clamps at 600 too.
33
+ MAX_TTL_SECONDS = 600
34
+
35
+
36
+ def env_names(prefix: str) -> dict[str, str]:
37
+ """Environment variable names for a line prefix, e.g. ``FD_INFO``.
38
+
39
+ Kept as a function so each line wrapper exports the same four names it used
40
+ before (``FD_<LINE>_LINE_TOKEN_*``) without hard-coding the mapping here.
41
+ """
42
+ p = prefix.rstrip("_").upper()
43
+ return {
44
+ "issuer": f"{p}_LINE_TOKEN_ISSUER",
45
+ "line": f"{p}_LINE_TOKEN_LINE",
46
+ "pem": f"{p}_LINE_TOKEN_PUBLIC_KEY_PEM",
47
+ "jwks_uri": f"{p}_LINE_TOKEN_JWKS_URI",
48
+ }
49
+
50
+
51
+ class LineTokenRejected(Exception):
52
+ """Verification failed. ``reason`` is a stable code (assert on it, not text)."""
53
+
54
+ NOT_CONFIGURED = "not_configured"
55
+ TOKEN_MALFORMED = "token_malformed"
56
+ BAD_SIGNATURE = "bad_signature"
57
+ WRONG_ISSUER = "wrong_issuer"
58
+ WRONG_AUDIENCE = "wrong_audience"
59
+ WRONG_SOURCE = "wrong_source"
60
+ EXPIRED = "expired"
61
+ TTL_TOO_LONG = "ttl_too_long"
62
+ MISSING_CLAIM = "missing_claim"
63
+
64
+ def __init__(self, reason: str, detail: str = "") -> None:
65
+ super().__init__(f"{reason}: {detail}" if detail else reason)
66
+ self.reason = reason
67
+ self.detail = detail
68
+
69
+
70
+ @dataclass(frozen=True)
71
+ class LineTokenIdentity:
72
+ """Verified gate K identity.
73
+
74
+ ``subject`` is the gateway's billing-side principal (sub2api user id as a
75
+ string), not a Logto username and not a line tenant id. Do not build a
76
+ customer record from it.
77
+ """
78
+
79
+ subject: str
80
+ email: str | None
81
+ scope: tuple[str, ...]
82
+ source: str
83
+ expires_at: int
84
+ jti: str
85
+
86
+ @property
87
+ def can_write(self) -> bool:
88
+ return "line:write" in self.scope
89
+
90
+
91
+ @dataclass(frozen=True)
92
+ class LineTokenSettings:
93
+ issuer: str
94
+ line: str
95
+ public_key_pem: str = ""
96
+ jwks_uri: str = ""
97
+ algorithms: tuple[str, ...] = ("ES256", "RS256", "EdDSA")
98
+ max_ttl_seconds: int = MAX_TTL_SECONDS
99
+
100
+ @property
101
+ def configured(self) -> bool:
102
+ return bool(self.issuer and self.line and (self.jwks_uri or self.public_key_pem))
103
+
104
+
105
+ def settings_from_env(
106
+ env: dict[str, str] | None = None,
107
+ *,
108
+ prefix: str,
109
+ default_line: str,
110
+ ) -> LineTokenSettings:
111
+ """Read settings from the environment on every call (public-key rotation needs no restart)."""
112
+ e = os.environ if env is None else env
113
+ names = env_names(prefix)
114
+ return LineTokenSettings(
115
+ issuer=(e.get(names["issuer"]) or "").strip(),
116
+ line=(e.get(names["line"]) or default_line).strip() or default_line,
117
+ public_key_pem=(e.get(names["pem"]) or "").strip(),
118
+ jwks_uri=(e.get(names["jwks_uri"]) or "").strip(),
119
+ )
120
+
121
+
122
+ def verify_line_token(
123
+ token: str,
124
+ *,
125
+ settings: LineTokenSettings,
126
+ jwks_client_factory: Callable[[str], Any] | None = None,
127
+ ) -> LineTokenIdentity:
128
+ """Verify a gate K token offline. The only failure mode is ``LineTokenRejected``.
129
+
130
+ Order is part of the contract: verify signature first (most expensive),
131
+ then iss/aud, then TTL window, then source. No state is written — gate K
132
+ tokens are reusable within their TTL, so there is no replay ledger here.
133
+ """
134
+ if not settings.configured:
135
+ raise LineTokenRejected(LineTokenRejected.NOT_CONFIGURED, "issuer/line/key incomplete")
136
+ if not isinstance(token, str) or not token.strip():
137
+ raise LineTokenRejected(LineTokenRejected.TOKEN_MALFORMED, "empty token")
138
+
139
+ try:
140
+ import jwt as pyjwt
141
+ except ImportError as exc: # pragma: no cover - deployment error
142
+ raise LineTokenRejected(LineTokenRejected.NOT_CONFIGURED, "PyJWT not installed") from exc
143
+
144
+ key: Any
145
+ if settings.public_key_pem:
146
+ key = settings.public_key_pem
147
+ elif settings.jwks_uri and jwks_client_factory is not None:
148
+ try:
149
+ key = jwks_client_factory(settings.jwks_uri).get_signing_key_from_jwt(token).key
150
+ except Exception as exc:
151
+ raise LineTokenRejected(
152
+ LineTokenRejected.BAD_SIGNATURE, f"jwks lookup failed: {type(exc).__name__}"
153
+ ) from exc
154
+ else:
155
+ raise LineTokenRejected(LineTokenRejected.NOT_CONFIGURED, "no verification key source")
156
+
157
+ try:
158
+ claims = pyjwt.decode(
159
+ token,
160
+ key,
161
+ algorithms=list(settings.algorithms),
162
+ issuer=settings.issuer,
163
+ audience=settings.line,
164
+ options={"verify_exp": True, "verify_aud": True, "verify_iss": True},
165
+ )
166
+ except pyjwt.ExpiredSignatureError as exc:
167
+ raise LineTokenRejected(LineTokenRejected.EXPIRED) from exc
168
+ except pyjwt.InvalidAudienceError as exc:
169
+ raise LineTokenRejected(LineTokenRejected.WRONG_AUDIENCE, f"expected {settings.line}") from exc
170
+ except pyjwt.InvalidIssuerError as exc:
171
+ raise LineTokenRejected(LineTokenRejected.WRONG_ISSUER, f"expected {settings.issuer}") from exc
172
+ except pyjwt.InvalidSignatureError as exc:
173
+ # Must precede DecodeError: InvalidSignatureError is a DecodeError
174
+ # subclass, and reporting it as token_malformed points the investigation
175
+ # at the token format instead of the signing key.
176
+ raise LineTokenRejected(LineTokenRejected.BAD_SIGNATURE, type(exc).__name__) from exc
177
+ except pyjwt.DecodeError as exc:
178
+ raise LineTokenRejected(LineTokenRejected.TOKEN_MALFORMED) from exc
179
+ except Exception as exc: # algorithm mismatch, etc.
180
+ raise LineTokenRejected(LineTokenRejected.BAD_SIGNATURE, type(exc).__name__) from exc
181
+
182
+ subject = claims.get("sub")
183
+ if not isinstance(subject, str) or not subject.strip():
184
+ raise LineTokenRejected(LineTokenRejected.MISSING_CLAIM, "sub")
185
+ jti = claims.get("jti")
186
+ if not isinstance(jti, str) or not jti.strip():
187
+ raise LineTokenRejected(LineTokenRejected.MISSING_CLAIM, "jti")
188
+ exp = claims.get("exp")
189
+ iat = claims.get("iat")
190
+ if not isinstance(exp, int):
191
+ raise LineTokenRejected(LineTokenRejected.MISSING_CLAIM, "exp")
192
+
193
+ if isinstance(iat, int) and exp - iat > settings.max_ttl_seconds:
194
+ raise LineTokenRejected(
195
+ LineTokenRejected.TTL_TOO_LONG, f"{exp - iat}s > {settings.max_ttl_seconds}s"
196
+ )
197
+
198
+ source = claims.get("source")
199
+ if not isinstance(source, str) or not source.strip():
200
+ raise LineTokenRejected(LineTokenRejected.MISSING_CLAIM, "source")
201
+ if source.strip() != settings.line:
202
+ raise LineTokenRejected(LineTokenRejected.WRONG_SOURCE, f"expected {settings.line}")
203
+
204
+ scope_value = claims.get("scope") or ""
205
+ scope = tuple(str(scope_value).split()) if scope_value else ()
206
+ email = claims.get("email")
207
+ return LineTokenIdentity(
208
+ subject=subject.strip(),
209
+ email=str(email) if isinstance(email, str) and email else None,
210
+ scope=scope,
211
+ source=source.strip(),
212
+ expires_at=exp,
213
+ jti=jti.strip(),
214
+ )
@@ -0,0 +1,64 @@
1
+ Metadata-Version: 2.4
2
+ Name: fd-line-auth
3
+ Version: 0.1.0
4
+ Summary: Offline verification of FindData per-line (gate K) tokens, shared by every line
5
+ License: MIT
6
+ Requires-Python: >=3.11
7
+ Description-Content-Type: text/markdown
8
+ License-File: LICENSE
9
+ Requires-Dist: PyJWT>=2.0
10
+ Provides-Extra: jwks
11
+ Requires-Dist: PyJWT[crypto]>=2.0; extra == "jwks"
12
+ Provides-Extra: test
13
+ Requires-Dist: pytest>=8; extra == "test"
14
+ Requires-Dist: PyJWT[crypto]>=2.0; extra == "test"
15
+ Dynamic: license-file
16
+
17
+ # fd-line-auth
18
+
19
+ 门 K(per-line)短命令牌的**线侧离线校验**,全系各线共用一份。
20
+
21
+ 此前每个线仓各存一份 `line_token.py`(wire / info / sentiment / text-core /
22
+ zhengxin / lex / erp),靠文件头注「逻辑逐条对齐」维持一致;一份的安全面漂移
23
+ (TTL 上限、原因码集合、算法集合、校验顺序)不会让任何东西变红。本包把它变成
24
+ 一个可依赖的版本化实现。
25
+
26
+ ## 用法
27
+
28
+ 显式配置(线自己从 pydantic/settings 取配置时):
29
+
30
+ ```python
31
+ from fd_line_auth import LineTokenSettings, verify_line_token
32
+
33
+ settings = LineTokenSettings(
34
+ issuer="https://mcp.finddatatech.cloud",
35
+ line="wire",
36
+ public_key_pem=...,
37
+ )
38
+ identity = verify_line_token(token, settings=settings)
39
+ ```
40
+
41
+ 环境变量配置(线按约定前缀读):
42
+
43
+ ```python
44
+ from fd_line_auth import settings_from_env
45
+
46
+ settings = settings_from_env(prefix="FD_INFO", default_line="info")
47
+ # 读 FD_INFO_LINE_TOKEN_ISSUER / _LINE / _PUBLIC_KEY_PEM / _JWKS_URI
48
+ ```
49
+
50
+ 失败一律抛 `LineTokenRejected`,原因码是稳定契约(见 `LineTokenRejected.*`)。
51
+
52
+ ## 安全面(不可逐线分叉)
53
+
54
+ - TTL 上限 600 秒(与网关一致,两边各守一次)
55
+ - 原因码集合固定;`wrong_audience` 与 `wrong_source` 对外同码
56
+ - 可接受算法集合固定(ES256 / RS256 / EdDSA)
57
+ - 校验顺序:验签 → iss/aud → TTL → source
58
+ - 缺公钥 = 失败关闭,不回退放行
59
+
60
+ ## 测试
61
+
62
+ ```bash
63
+ python -m pytest tests -q
64
+ ```
@@ -0,0 +1,6 @@
1
+ fd_line_auth/__init__.py,sha256=4R53tZ6GT9s-49lCueOL5wYhRxHxAwnyXA0K_HqmJ5c,7865
2
+ fd_line_auth-0.1.0.dist-info/licenses/LICENSE,sha256=2rN_-pxX7F3pkb54QX03XBLWDQalOcwvG4QbZ9UhTgY,1069
3
+ fd_line_auth-0.1.0.dist-info/METADATA,sha256=1UPA10K25nPXFerdaTC0oMbR7f2j8umEvcxQ7vNiQKc,1982
4
+ fd_line_auth-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
5
+ fd_line_auth-0.1.0.dist-info/top_level.txt,sha256=gxcEcFrA6_6xl-xHNCDvXcm0RGqPd9lUMok4JZqoGQc,13
6
+ fd_line_auth-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 cli-anything
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1 @@
1
+ fd_line_auth