skyplatform-iam 1.0.0__tar.gz → 1.0.1__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.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: skyplatform-iam
3
- Version: 1.0.0
3
+ Version: 1.0.1
4
4
  Summary: SkyPlatform IAM认证SDK,提供FastAPI中间件和认证路由
5
5
  Project-URL: Homepage, https://github.com/xinmayoujiang12621/agenterra_iam
6
6
  Project-URL: Documentation, https://skyplatform-iam.readthedocs.io/
@@ -24,7 +24,7 @@ Classifier: Programming Language :: Python :: 3.12
24
24
  Classifier: Topic :: Internet :: WWW/HTTP :: HTTP Servers
25
25
  Classifier: Topic :: Security
26
26
  Classifier: Topic :: Software Development :: Libraries :: Python Modules
27
- Requires-Python: >=3.8
27
+ Requires-Python: >=3.9
28
28
  Requires-Dist: fastapi>=0.68.0
29
29
  Requires-Dist: pydantic>=1.8.0
30
30
  Requires-Dist: python-dotenv>=0.19.0
@@ -4,13 +4,13 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "skyplatform-iam"
7
- version = "1.0.0"
7
+ version = "1.0.1"
8
8
  authors = [
9
9
  { name="x9", email="xuanxienanxunmobao@gmail.com" },
10
10
  ]
11
11
  description = "SkyPlatform IAM认证SDK,提供FastAPI中间件和认证路由"
12
12
  readme = "README.md"
13
- requires-python = ">=3.8"
13
+ requires-python = ">=3.9"
14
14
  license = { text = "MIT" }
15
15
  keywords = ["fastapi", "authentication", "middleware", "iam", "skyplatform"]
16
16
  classifiers = [
@@ -6,6 +6,7 @@ SkyPlatform IAM SDK
6
6
  from .config import AuthConfig
7
7
  from .middleware import AuthMiddleware
8
8
  from .connect_agenterra_iam import ConnectAgenterraIam
9
+ from .auth_middleware import setup_auth_middleware
9
10
  from .exceptions import (
10
11
  SkyPlatformAuthException,
11
12
  AuthenticationError,
@@ -28,6 +29,7 @@ __all__ = [
28
29
 
29
30
  # 中间件
30
31
  "AuthMiddleware",
32
+ "setup_auth_middleware",
31
33
 
32
34
  # 客户端
33
35
  "ConnectAgenterraIam",
@@ -4,20 +4,36 @@ from typing import Optional, Dict
4
4
  import jwt
5
5
 
6
6
  from .connect_agenterra_iam import ConnectAgenterraIam
7
+ from .config import AuthConfig
7
8
  import logging
8
9
 
9
10
  logger = logging.getLogger(__name__)
10
11
 
11
12
 
12
13
  class AuthMiddleware:
13
- def __init__(self):
14
+ def __init__(self, auth_config: Optional[AuthConfig] = None):
14
15
  self.security = HTTPBearer(auto_error=False)
15
16
  self.iam_client = ConnectAgenterraIam()
17
+ self.auth_config = auth_config
18
+
19
+ def is_path_whitelisted(self, path: str) -> bool:
20
+ """
21
+ 检查路径是否在白名单中
22
+ """
23
+ if not self.auth_config:
24
+ return False
25
+ return self.auth_config.is_path_whitelisted(path)
16
26
 
17
27
  async def verify_token(self, request: Request):
18
28
  # 通过token, server_ak, server_sk判断是否有权限
19
- credentials: HTTPAuthorizationCredentials = await self.security(request)
20
29
  api_path = request.url.path
30
+
31
+ # 首先检查路径是否在白名单中
32
+ if self.is_path_whitelisted(api_path):
33
+ logger.info(f"路径 {api_path} 在白名单中,跳过IAM鉴权")
34
+ return True
35
+
36
+ credentials: HTTPAuthorizationCredentials = await self.security(request)
21
37
  method = request.method
22
38
 
23
39
  server_ak = request.headers.get("SERVER-AK", "")
@@ -162,6 +178,18 @@ class AuthMiddleware:
162
178
  auth_middleware = AuthMiddleware()
163
179
 
164
180
 
181
+ def setup_auth_middleware(auth_config: AuthConfig) -> None:
182
+ """
183
+ 设置认证中间件配置
184
+
185
+ Args:
186
+ auth_config: 认证配置实例,包含白名单路径等配置
187
+ """
188
+ global auth_middleware
189
+ auth_middleware = AuthMiddleware(auth_config)
190
+ logger.info(f"认证中间件已配置,白名单路径数量: {len(auth_config.get_whitelist_paths())}")
191
+
192
+
165
193
  # 便捷的依赖函数
166
194
  async def get_current_user(request: Request) -> Dict:
167
195
  """获取当前用户的依赖函数"""
@@ -0,0 +1,132 @@
1
+ """
2
+ SkyPlatform IAM SDK 配置模块
3
+ """
4
+ import os
5
+ import fnmatch
6
+ from typing import Optional, List
7
+ from pydantic import BaseModel, Field
8
+ from dotenv import load_dotenv
9
+
10
+ # 加载环境变量
11
+ load_dotenv()
12
+
13
+
14
+ class AuthConfig(BaseModel):
15
+ """
16
+ 认证配置类
17
+ 支持环境变量和代码配置
18
+ """
19
+ # IAM服务配置
20
+ agenterra_iam_host: str
21
+ server_name: str
22
+ access_key: str
23
+
24
+ # Token配置
25
+ token_header: str = "Authorization"
26
+ token_prefix: str = "Bearer "
27
+
28
+ # 错误处理配置
29
+ enable_debug: bool = False
30
+
31
+ # 白名单路径配置(实例变量)
32
+ whitelist_paths: List[str] = Field(default_factory=list)
33
+
34
+ class Config:
35
+ env_prefix = "AGENTERRA_"
36
+
37
+ @classmethod
38
+ def from_env(cls) -> "AuthConfig":
39
+ """
40
+ 从环境变量创建配置
41
+ """
42
+ return cls(
43
+ agenterra_iam_host=os.environ.get('AGENTERRA_IAM_HOST', ''),
44
+ server_name=os.environ.get('AGENTERRA_SERVER_NAME', ''),
45
+ access_key=os.environ.get('AGENTERRA_ACCESS_KEY', ''),
46
+ enable_debug=os.environ.get('AGENTERRA_ENABLE_DEBUG', 'false').lower() == 'true',
47
+ whitelist_paths=[] # 初始化空的白名单路径列表
48
+ )
49
+
50
+ def validate_config(self) -> bool:
51
+ """
52
+ 验证配置是否完整
53
+ """
54
+ required_fields = ['agenterra_iam_host', 'server_name', 'access_key']
55
+ for field in required_fields:
56
+ if not getattr(self, field):
57
+ raise ValueError(f"配置项 {field} 不能为空")
58
+ return True
59
+
60
+ def _normalize_path(self, path: str) -> str:
61
+ """
62
+ 标准化路径格式
63
+ """
64
+ if not path:
65
+ return path
66
+
67
+ # 确保路径以 / 开头
68
+ if not path.startswith('/'):
69
+ path = '/' + path
70
+
71
+ # 移除重复的斜杠
72
+ while '//' in path:
73
+ path = path.replace('//', '/')
74
+
75
+ return path
76
+
77
+ def add_whitelist_path(self, path: str) -> None:
78
+ """
79
+ 添加白名单路径
80
+ """
81
+ if not path:
82
+ return
83
+
84
+ normalized_path = self._normalize_path(path)
85
+ if normalized_path not in self.whitelist_paths:
86
+ self.whitelist_paths.append(normalized_path)
87
+
88
+ def add_whitelist_paths(self, paths: List[str]) -> None:
89
+ """
90
+ 批量添加白名单路径
91
+ """
92
+ for path in paths:
93
+ self.add_whitelist_path(path)
94
+
95
+ def remove_whitelist_path(self, path: str) -> None:
96
+ """
97
+ 移除白名单路径
98
+ """
99
+ if not path:
100
+ return
101
+
102
+ normalized_path = self._normalize_path(path)
103
+ if normalized_path in self.whitelist_paths:
104
+ self.whitelist_paths.remove(normalized_path)
105
+
106
+ def clear_whitelist_paths(self) -> None:
107
+ """
108
+ 清空所有白名单路径
109
+ """
110
+ self.whitelist_paths.clear()
111
+
112
+ def get_whitelist_paths(self) -> List[str]:
113
+ """
114
+ 获取所有白名单路径
115
+ """
116
+ return self.whitelist_paths.copy()
117
+
118
+ def is_path_whitelisted(self, path: str) -> bool:
119
+ """
120
+ 检查路径是否在白名单中(支持通配符匹配)
121
+ """
122
+ if not path:
123
+ return False
124
+
125
+ normalized_path = self._normalize_path(path)
126
+
127
+ for whitelist_path in self.whitelist_paths:
128
+ # 支持通配符匹配
129
+ if fnmatch.fnmatch(normalized_path, whitelist_path):
130
+ return True
131
+
132
+ return False
@@ -1,68 +0,0 @@
1
- """
2
- SkyPlatform IAM SDK 配置模块
3
- """
4
- import os
5
- from typing import Optional, List
6
- from pydantic import BaseModel
7
- from dotenv import load_dotenv
8
-
9
- # 加载环境变量
10
- load_dotenv()
11
-
12
-
13
- class AuthConfig(BaseModel):
14
- """
15
- 认证配置类
16
- 支持环境变量和代码配置
17
- """
18
- # IAM服务配置
19
- agenterra_iam_host: str
20
- server_name: str
21
- access_key: str
22
-
23
-
24
- # Token配置
25
- token_header: str = "Authorization"
26
- token_prefix: str = "Bearer "
27
-
28
- # 错误处理配置
29
- enable_debug: bool = False
30
-
31
- class Config:
32
- env_prefix = "AGENTERRA_"
33
-
34
- @classmethod
35
- def from_env(cls) -> "AuthConfig":
36
- """
37
- 从环境变量创建配置
38
- """
39
- return cls(
40
- agenterra_iam_host=os.environ.get('AGENTERRA_IAM_HOST', ''),
41
- server_name=os.environ.get('AGENTERRA_SERVER_NAME', ''),
42
- access_key=os.environ.get('AGENTERRA_ACCESS_KEY', ''),
43
- enable_debug=os.environ.get('AGENTERRA_ENABLE_DEBUG', 'false').lower() == 'true'
44
- )
45
-
46
- def validate_config(self) -> bool:
47
- """
48
- 验证配置是否完整
49
- """
50
- required_fields = ['agenterra_iam_host', 'server_name', 'access_key']
51
- for field in required_fields:
52
- if not getattr(self, field):
53
- raise ValueError(f"配置项 {field} 不能为空")
54
- return True
55
-
56
- def add_whitelist_path(self, path: str) -> None:
57
- """
58
- 添加白名单路径
59
- """
60
- if path not in self.whitelist_paths:
61
- self.whitelist_paths.append(path)
62
-
63
- def remove_whitelist_path(self, path: str) -> None:
64
- """
65
- 移除白名单路径
66
- """
67
- if path in self.whitelist_paths:
68
- self.whitelist_paths.remove(path)