fd-line-auth 0.1.0__tar.gz
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.
- fd_line_auth-0.1.0/LICENSE +21 -0
- fd_line_auth-0.1.0/PKG-INFO +64 -0
- fd_line_auth-0.1.0/README.md +48 -0
- fd_line_auth-0.1.0/fd_line_auth/__init__.py +214 -0
- fd_line_auth-0.1.0/fd_line_auth.egg-info/PKG-INFO +64 -0
- fd_line_auth-0.1.0/fd_line_auth.egg-info/SOURCES.txt +10 -0
- fd_line_auth-0.1.0/fd_line_auth.egg-info/dependency_links.txt +1 -0
- fd_line_auth-0.1.0/fd_line_auth.egg-info/requires.txt +8 -0
- fd_line_auth-0.1.0/fd_line_auth.egg-info/top_level.txt +1 -0
- fd_line_auth-0.1.0/pyproject.toml +22 -0
- fd_line_auth-0.1.0/setup.cfg +4 -0
- fd_line_auth-0.1.0/tests/test_line_token.py +161 -0
|
@@ -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,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,48 @@
|
|
|
1
|
+
# fd-line-auth
|
|
2
|
+
|
|
3
|
+
门 K(per-line)短命令牌的**线侧离线校验**,全系各线共用一份。
|
|
4
|
+
|
|
5
|
+
此前每个线仓各存一份 `line_token.py`(wire / info / sentiment / text-core /
|
|
6
|
+
zhengxin / lex / erp),靠文件头注「逻辑逐条对齐」维持一致;一份的安全面漂移
|
|
7
|
+
(TTL 上限、原因码集合、算法集合、校验顺序)不会让任何东西变红。本包把它变成
|
|
8
|
+
一个可依赖的版本化实现。
|
|
9
|
+
|
|
10
|
+
## 用法
|
|
11
|
+
|
|
12
|
+
显式配置(线自己从 pydantic/settings 取配置时):
|
|
13
|
+
|
|
14
|
+
```python
|
|
15
|
+
from fd_line_auth import LineTokenSettings, verify_line_token
|
|
16
|
+
|
|
17
|
+
settings = LineTokenSettings(
|
|
18
|
+
issuer="https://mcp.finddatatech.cloud",
|
|
19
|
+
line="wire",
|
|
20
|
+
public_key_pem=...,
|
|
21
|
+
)
|
|
22
|
+
identity = verify_line_token(token, settings=settings)
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
环境变量配置(线按约定前缀读):
|
|
26
|
+
|
|
27
|
+
```python
|
|
28
|
+
from fd_line_auth import settings_from_env
|
|
29
|
+
|
|
30
|
+
settings = settings_from_env(prefix="FD_INFO", default_line="info")
|
|
31
|
+
# 读 FD_INFO_LINE_TOKEN_ISSUER / _LINE / _PUBLIC_KEY_PEM / _JWKS_URI
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
失败一律抛 `LineTokenRejected`,原因码是稳定契约(见 `LineTokenRejected.*`)。
|
|
35
|
+
|
|
36
|
+
## 安全面(不可逐线分叉)
|
|
37
|
+
|
|
38
|
+
- TTL 上限 600 秒(与网关一致,两边各守一次)
|
|
39
|
+
- 原因码集合固定;`wrong_audience` 与 `wrong_source` 对外同码
|
|
40
|
+
- 可接受算法集合固定(ES256 / RS256 / EdDSA)
|
|
41
|
+
- 校验顺序:验签 → iss/aud → TTL → source
|
|
42
|
+
- 缺公钥 = 失败关闭,不回退放行
|
|
43
|
+
|
|
44
|
+
## 测试
|
|
45
|
+
|
|
46
|
+
```bash
|
|
47
|
+
python -m pytest tests -q
|
|
48
|
+
```
|
|
@@ -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,10 @@
|
|
|
1
|
+
LICENSE
|
|
2
|
+
README.md
|
|
3
|
+
pyproject.toml
|
|
4
|
+
fd_line_auth/__init__.py
|
|
5
|
+
fd_line_auth.egg-info/PKG-INFO
|
|
6
|
+
fd_line_auth.egg-info/SOURCES.txt
|
|
7
|
+
fd_line_auth.egg-info/dependency_links.txt
|
|
8
|
+
fd_line_auth.egg-info/requires.txt
|
|
9
|
+
fd_line_auth.egg-info/top_level.txt
|
|
10
|
+
tests/test_line_token.py
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
fd_line_auth
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=68", "wheel"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "fd-line-auth"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "Offline verification of FindData per-line (gate K) tokens, shared by every line"
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.11"
|
|
11
|
+
license = { text = "MIT" }
|
|
12
|
+
dependencies = ["PyJWT>=2.0"]
|
|
13
|
+
|
|
14
|
+
[project.optional-dependencies]
|
|
15
|
+
jwks = ["PyJWT[crypto]>=2.0"]
|
|
16
|
+
test = ["pytest>=8", "PyJWT[crypto]>=2.0"]
|
|
17
|
+
|
|
18
|
+
[tool.setuptools]
|
|
19
|
+
packages = ["fd_line_auth"]
|
|
20
|
+
|
|
21
|
+
[tool.pytest.ini_options]
|
|
22
|
+
testpaths = ["tests"]
|
|
@@ -0,0 +1,161 @@
|
|
|
1
|
+
"""Security surface of the shared gate K verifier.
|
|
2
|
+
|
|
3
|
+
Each test names the behaviour a line must not fork: TTL ceiling, reason codes,
|
|
4
|
+
accepted algorithms, verification order, cross-line rejection, fail-closed.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import time
|
|
10
|
+
|
|
11
|
+
import jwt as pyjwt
|
|
12
|
+
import pytest
|
|
13
|
+
from cryptography.hazmat.primitives import serialization
|
|
14
|
+
from cryptography.hazmat.primitives.asymmetric import rsa
|
|
15
|
+
|
|
16
|
+
from fd_line_auth import (
|
|
17
|
+
MAX_TTL_SECONDS,
|
|
18
|
+
LineTokenRejected,
|
|
19
|
+
LineTokenSettings,
|
|
20
|
+
settings_from_env,
|
|
21
|
+
verify_line_token,
|
|
22
|
+
)
|
|
23
|
+
|
|
24
|
+
ISSUER = "https://mcp.finddatatech.cloud"
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
@pytest.fixture(scope="module")
|
|
28
|
+
def keypair():
|
|
29
|
+
key = rsa.generate_private_key(public_exponent=65537, key_size=2048)
|
|
30
|
+
priv = key.private_bytes(
|
|
31
|
+
serialization.Encoding.PEM,
|
|
32
|
+
serialization.PrivateFormat.PKCS8,
|
|
33
|
+
serialization.NoEncryption(),
|
|
34
|
+
).decode()
|
|
35
|
+
pub = key.public_key().public_bytes(
|
|
36
|
+
serialization.Encoding.PEM,
|
|
37
|
+
serialization.PublicFormat.SubjectPublicKeyInfo,
|
|
38
|
+
).decode()
|
|
39
|
+
return priv, pub
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def mint(priv: str, *, line: str = "info", ttl: int = 300, **overrides) -> str:
|
|
43
|
+
now = int(time.time()) - 1
|
|
44
|
+
claims = {
|
|
45
|
+
"iss": ISSUER,
|
|
46
|
+
"aud": line,
|
|
47
|
+
"source": line,
|
|
48
|
+
"sub": "cust-1",
|
|
49
|
+
"jti": "j-1",
|
|
50
|
+
"scope": "line:read",
|
|
51
|
+
"iat": now,
|
|
52
|
+
"exp": now + ttl,
|
|
53
|
+
}
|
|
54
|
+
claims.update(overrides)
|
|
55
|
+
return pyjwt.encode(claims, priv, algorithm="RS256")
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def settings(pub: str, line: str = "info") -> LineTokenSettings:
|
|
59
|
+
return LineTokenSettings(issuer=ISSUER, line=line, public_key_pem=pub)
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def test_valid_token(keypair):
|
|
63
|
+
priv, pub = keypair
|
|
64
|
+
identity = verify_line_token(mint(priv), settings=settings(pub))
|
|
65
|
+
assert identity.subject == "cust-1"
|
|
66
|
+
assert identity.source == "info"
|
|
67
|
+
assert identity.can_write is False
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def test_write_scope(keypair):
|
|
71
|
+
priv, pub = keypair
|
|
72
|
+
identity = verify_line_token(mint(priv, scope="line:read line:write"), settings=settings(pub))
|
|
73
|
+
assert identity.can_write is True
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def test_cross_line_token_rejected(keypair):
|
|
77
|
+
priv, pub = keypair
|
|
78
|
+
token = mint(priv, line="wire") # aud and source both say wire
|
|
79
|
+
with pytest.raises(LineTokenRejected) as exc:
|
|
80
|
+
verify_line_token(token, settings=settings(pub, line="info"))
|
|
81
|
+
assert exc.value.reason in {
|
|
82
|
+
LineTokenRejected.WRONG_AUDIENCE,
|
|
83
|
+
LineTokenRejected.WRONG_SOURCE,
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def test_source_mismatch_rejected(keypair):
|
|
88
|
+
priv, pub = keypair
|
|
89
|
+
token = mint(priv, source="wire")
|
|
90
|
+
with pytest.raises(LineTokenRejected) as exc:
|
|
91
|
+
verify_line_token(token, settings=settings(pub))
|
|
92
|
+
assert exc.value.reason == LineTokenRejected.WRONG_SOURCE
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def test_expired_rejected(keypair):
|
|
96
|
+
priv, pub = keypair
|
|
97
|
+
now = int(time.time())
|
|
98
|
+
token = mint(priv, iat=now - 1200, exp=now - 600)
|
|
99
|
+
with pytest.raises(LineTokenRejected) as exc:
|
|
100
|
+
verify_line_token(token, settings=settings(pub))
|
|
101
|
+
assert exc.value.reason == LineTokenRejected.EXPIRED
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def test_ttl_ceiling(keypair):
|
|
105
|
+
priv, pub = keypair
|
|
106
|
+
token = mint(priv, ttl=MAX_TTL_SECONDS + 1)
|
|
107
|
+
with pytest.raises(LineTokenRejected) as exc:
|
|
108
|
+
verify_line_token(token, settings=settings(pub))
|
|
109
|
+
assert exc.value.reason == LineTokenRejected.TTL_TOO_LONG
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def test_missing_jti_rejected(keypair):
|
|
113
|
+
priv, pub = keypair
|
|
114
|
+
token = mint(priv, jti="")
|
|
115
|
+
with pytest.raises(LineTokenRejected) as exc:
|
|
116
|
+
verify_line_token(token, settings=settings(pub))
|
|
117
|
+
assert exc.value.reason == LineTokenRejected.MISSING_CLAIM
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def test_bad_signature(keypair):
|
|
121
|
+
_, pub = keypair
|
|
122
|
+
other = rsa.generate_private_key(public_exponent=65537, key_size=2048)
|
|
123
|
+
priv2 = other.private_bytes(
|
|
124
|
+
serialization.Encoding.PEM,
|
|
125
|
+
serialization.PrivateFormat.PKCS8,
|
|
126
|
+
serialization.NoEncryption(),
|
|
127
|
+
).decode()
|
|
128
|
+
with pytest.raises(LineTokenRejected) as exc:
|
|
129
|
+
verify_line_token(mint(priv2), settings=settings(pub))
|
|
130
|
+
assert exc.value.reason == LineTokenRejected.BAD_SIGNATURE
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
def test_not_configured_fails_closed():
|
|
134
|
+
with pytest.raises(LineTokenRejected) as exc:
|
|
135
|
+
verify_line_token("anything", settings=LineTokenSettings(issuer="", line="info"))
|
|
136
|
+
assert exc.value.reason == LineTokenRejected.NOT_CONFIGURED
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def test_empty_token_malformed(keypair):
|
|
140
|
+
_, pub = keypair
|
|
141
|
+
with pytest.raises(LineTokenRejected) as exc:
|
|
142
|
+
verify_line_token(" ", settings=settings(pub))
|
|
143
|
+
assert exc.value.reason == LineTokenRejected.TOKEN_MALFORMED
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
def test_settings_from_env_prefix():
|
|
147
|
+
env = {
|
|
148
|
+
"FD_INFO_LINE_TOKEN_ISSUER": ISSUER,
|
|
149
|
+
"FD_INFO_LINE_TOKEN_LINE": "info",
|
|
150
|
+
"FD_INFO_LINE_TOKEN_PUBLIC_KEY_PEM": "pem",
|
|
151
|
+
}
|
|
152
|
+
s = settings_from_env(env, prefix="FD_INFO", default_line="info")
|
|
153
|
+
assert s.configured
|
|
154
|
+
assert s.line == "info"
|
|
155
|
+
assert s.issuer == ISSUER
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
def test_settings_default_line_is_not_configurable_by_env_absence():
|
|
159
|
+
s = settings_from_env({}, prefix="FD_INFO", default_line="info")
|
|
160
|
+
assert s.line == "info"
|
|
161
|
+
assert not s.configured
|