ddns 4.0.2__py2.py3-none-any.whl → 4.1.0b2__py2.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.
ddns/provider/_base.py ADDED
@@ -0,0 +1,539 @@
1
+ # coding=utf-8
2
+ """
3
+ ## SimpleProvider 简单DNS抽象基类
4
+ * set_record()
5
+
6
+ ## BaseProvider 标准DNS抽象基类
7
+ 定义所有 DNS 服务商 API 类应继承的抽象基类,统一接口,便于扩展适配多服务商。
8
+ Defines a unified interface to support extension and adaptation across providers.
9
+ * _query_zone_id
10
+ * _query_record
11
+ * _update_record
12
+ * _create_record
13
+
14
+ ┌──────────────────────────────────────────────────┐
15
+ │ 调用 set_record(domain, value...) │
16
+ └──────────────────────────────────────────────────┘
17
+
18
+
19
+ ┌──────────────────────────────────────┐
20
+ │ 快速解析 是否包含 ~ 或 + 分隔符? │
21
+ └──────────────────────────────────────┘
22
+ │ │
23
+ [是,拆解成功] [否,无法拆解]
24
+ sub 和 main│ │ domain
25
+ ▼ ▼
26
+ ┌────────────────────────┐ ┌──────────────────────────┐
27
+ │ 查询 zone_id │ │ 自动循环解析 while: │
28
+ │ _query_zone_id(main) │ │ _query_zone_id(...) │
29
+ └────────────────────────┘ └──────────────────────────┘
30
+ │ │
31
+ ▼ ▼
32
+ zone_id ←──────────────┬─── sub
33
+
34
+ ┌─────────────────────────────────────┐
35
+ │ 查询 record: │
36
+ │ _query_record(zone_id, sub, ...) │
37
+ └─────────────────────────────────────┘
38
+
39
+ ┌─────────────┴────────────────┐
40
+ │ record_id 是否存在? │
41
+ └────────────┬─────────────────┘
42
+
43
+ ┌──────────────┴─────────────┐
44
+ │ │
45
+ ▼ ▼
46
+ ┌─────────────────────┐ ┌─────────────────────┐
47
+ │ 更新记录 │ │ 创建记录 │
48
+ │ _update_record(...) │ │ _create_record(...) │
49
+ └─────────────────────┘ └─────────────────────┘
50
+ │ │
51
+ ▼ ▼
52
+ ┌───────────────────────────────┐
53
+ │ 返回操作结果 │
54
+ └───────────────────────────────┘
55
+ @author: NewFuture
56
+ """
57
+
58
+ from abc import ABCMeta, abstractmethod
59
+ from json import loads as jsondecode, dumps as jsonencode
60
+ from logging import Logger, getLogger # noqa:F401 # type: ignore[no-redef]
61
+ from ..util.http import send_http_request, quote, urlencode
62
+
63
+ TYPE_FORM = "application/x-www-form-urlencoded"
64
+ TYPE_JSON = "application/json"
65
+
66
+
67
+ def encode_params(params):
68
+ # type: (dict|list|str|bytes|None) -> str
69
+ """
70
+ 编码参数为 URL 查询字符串,参数顺序会排序
71
+
72
+ Args:
73
+ params (dict|list|str|bytes|None): 参数字典、列表或字符串
74
+ Returns:
75
+ str: 编码后的查询字符串
76
+ """
77
+ if not params:
78
+ return ""
79
+ elif isinstance(params, (str, bytes)):
80
+ return params # type: ignore[return-value]
81
+ items = params.items() if isinstance(params, dict) else params
82
+ return urlencode(sorted(items), doseq=True)
83
+
84
+
85
+ class SimpleProvider(object):
86
+ """
87
+ 简单DNS服务商接口的抽象基类, 必须实现 `set_record` 方法。
88
+
89
+ Abstract base class for all simple DNS provider APIs.
90
+ Subclasses must implement `set_record`.
91
+
92
+ * set_record(domain, value, record_type="A", ttl=None, line=None, **extra)
93
+ """
94
+
95
+ __metaclass__ = ABCMeta
96
+
97
+ # API endpoint domain (to be defined in subclass)
98
+ endpoint = "" # type: str # https://exampledns.com
99
+ # Content-Type for requests (to be defined in subclass)
100
+ content_type = TYPE_FORM # type: Literal["application/x-www-form-urlencoded"] | Literal["application/json"]
101
+ # 默认 accept 头部, 空则不设置
102
+ accept = TYPE_JSON # type: str | None
103
+ # Decode Response as JSON by default
104
+ decode_response = True # type: bool
105
+ # UA 可自定义, 可在子类中覆盖,空则不设置
106
+ user_agent = "DDNS/{version} (ddns@newfuture.cc)"
107
+ # Description
108
+ remark = "Managed by [DDNS](https://ddns.newfuture.cc)"
109
+
110
+ def __init__(self, id, token, logger=None, verify_ssl="auto", proxy=None, endpoint=None, **options):
111
+ # type: (str, str, Logger | None, bool|str, Sequence[str|None]|None, str|None, **object) -> None
112
+ """
113
+ 初始化服务商对象
114
+
115
+ Initialize provider instance.
116
+
117
+ Args:
118
+ id (str): 身份认证 ID / Authentication ID
119
+ token (str): 密钥 / Authentication Token
120
+ options (dict): 其它参数 / Additional options
121
+ """
122
+ self.id = id
123
+ self.token = token
124
+ if endpoint:
125
+ self.endpoint = endpoint
126
+ self._proxy = proxy if proxy and len(proxy) else [None]
127
+ self._ssl = verify_ssl
128
+
129
+ self.options = options
130
+ name = self.__class__.__name__
131
+ self.logger = (logger or getLogger()).getChild(name)
132
+
133
+ self._zone_map = {} # type: dict[str, str]
134
+ self.logger.debug("%s initialized with: %s", self.__class__.__name__, id)
135
+ self._validate() # 验证身份认证信息
136
+
137
+ @abstractmethod
138
+ def set_record(self, domain, value, record_type="A", ttl=None, line=None, **extra):
139
+ # type: (str, str, str, str | int | None, str | None, **object) -> bool
140
+ """
141
+ 设置 DNS 记录(创建或更新)
142
+
143
+ Set or update DNS record.
144
+
145
+ Args:
146
+ domain (str): 完整域名
147
+ value (str): 新记录值
148
+ record_type (str): 记录类型
149
+ ttl (int | None): TTL 值,可选
150
+ line (str | None): 线路信息
151
+ extra (dict): 额外参数
152
+
153
+ Returns:
154
+ Any: 执行结果
155
+ """
156
+ raise NotImplementedError("This set_record should be implemented by subclasses")
157
+
158
+ def _validate(self):
159
+ # type: () -> None
160
+ """
161
+ 验证身份认证信息是否填写
162
+
163
+ Validate authentication credentials.
164
+ """
165
+ if not self.id:
166
+ raise ValueError("id must be configured")
167
+ if not self.token:
168
+ raise ValueError("token must be configured")
169
+ if not self.endpoint:
170
+ raise ValueError("API endpoint must be defined in {}".format(self.__class__.__name__))
171
+
172
+ def _http(self, method, url, params=None, body=None, queries=None, headers=None): # noqa: C901
173
+ # type: (str, str, dict[str,Any]|str|None, dict[str,Any]|str|None, dict[str,Any]|None, dict|None) -> Any
174
+ """
175
+ 发送 HTTP/HTTPS 请求,自动根据 API/url 选择协议。
176
+
177
+ Args:
178
+ method (str): 请求方法,如 GET、POST
179
+ url (str): 请求路径
180
+ params (dict[str, Any] | None): 请求参数,自动处理 query string 或者body
181
+ body (dict[str, Any] | str | None): 请求体内容
182
+ queries (dict[str, Any] | None): 查询参数,自动处理为 URL 查询字符串
183
+ headers (dict): 头部,可选
184
+
185
+ Returns:
186
+ Any: 解析后的响应内容
187
+
188
+ Raises:
189
+ RuntimeError: 当响应状态码为400/401或5xx(服务器错误)时抛出异常
190
+ """
191
+ method = method.upper()
192
+
193
+ # 简化参数处理逻辑
194
+ query_params = queries or {}
195
+ if params:
196
+ if method in ("GET", "DELETE"):
197
+ if isinstance(params, dict):
198
+ query_params.update(params)
199
+ else:
200
+ # params是字符串,直接作为查询字符串
201
+ url += ("&" if "?" in url else "?") + str(params)
202
+ params = None
203
+ elif body is None:
204
+ body = params
205
+
206
+ # 构建查询字符串
207
+ if len(query_params) > 0:
208
+ url += ("&" if "?" in url else "?") + encode_params(query_params)
209
+
210
+ # 构建完整URL
211
+ if not url.startswith("http://") and not url.startswith("https://"):
212
+ if not url.startswith("/") and self.endpoint.endswith("/"):
213
+ url = "/" + url
214
+ url = self.endpoint + url
215
+
216
+ # 记录请求日志
217
+ self.logger.info("%s %s", method, self._mask_sensitive_data(url))
218
+
219
+ # 处理请求体
220
+ body_data, headers = None, headers or {}
221
+ if body:
222
+ if "content-type" not in headers:
223
+ headers["content-type"] = self.content_type
224
+ body_data = self._encode_body(body)
225
+ self.logger.debug("body:\n%s", self._mask_sensitive_data(body_data))
226
+
227
+ # 处理headers
228
+ if self.accept and "accept" not in headers and "Accept" not in headers:
229
+ headers["accept"] = self.accept
230
+ if "user-agent" not in headers and "User-Agent" not in headers and self.user_agent:
231
+ headers["user-agent"] = self.user_agent
232
+ if len(headers) > 3:
233
+ self.logger.debug("headers:\n%s", {k: self._mask_sensitive_data(v) for k, v in headers.items()})
234
+
235
+ response = None # type: Any
236
+ for p in self._proxy:
237
+ if p:
238
+ self.logger.debug("Using proxy: %s", p)
239
+ try:
240
+ response = send_http_request(
241
+ method, url, body=body_data, headers=headers, proxy=p, verify_ssl=self._ssl
242
+ )
243
+ break # 成功发送请求,跳出循环
244
+ except Exception as e:
245
+ self.logger.warning("Failed to send request: %s", e)
246
+ if not response:
247
+ if len(self._proxy) > 1:
248
+ self.logger.error("Failed to send request via all proxies: %s", self._proxy)
249
+ raise RuntimeError("Failed to send request to {}".format(url))
250
+ # 处理响应
251
+ status_code = response.status
252
+ if not (200 <= status_code < 300):
253
+ self.logger.warning("response status: %s %s", status_code, response.reason)
254
+
255
+ res = response.body
256
+ # 针对客户端错误、认证/授权错误和服务器错误直接抛出异常
257
+ if status_code >= 500 or status_code in (400, 401, 403):
258
+ self.logger.error("HTTP error:\n%s", res)
259
+ if status_code == 400:
260
+ raise RuntimeError("请求参数错误 [400]: " + response.reason)
261
+ elif status_code == 401:
262
+ raise RuntimeError("认证失败 [401]: " + response.reason)
263
+ elif status_code == 403:
264
+ raise RuntimeError("禁止访问 [403]: " + response.reason)
265
+ else:
266
+ raise RuntimeError("服务器错误 [{}]: {}".format(status_code, response.reason))
267
+
268
+ self.logger.debug("response:\n%s", res)
269
+ if not self.decode_response:
270
+ return res
271
+
272
+ try:
273
+ return jsondecode(res)
274
+ except Exception as e:
275
+ self.logger.error("fail to decode response: %s", e)
276
+ return res
277
+
278
+ def _encode_body(self, data):
279
+ # type: (dict | list | str | bytes | None) -> str
280
+ """
281
+ 自动编码数据为字符串或字节, 根据 content_type 选择编码方式。
282
+ Args:
283
+ data (dict | list | str | bytes | None): 待编码数据
284
+
285
+ Returns:
286
+ str | bytes | None: 编码后的数据
287
+ """
288
+ if isinstance(data, (str, bytes)):
289
+ return data # type: ignore[return-value]
290
+ if not data:
291
+ return ""
292
+ if self.content_type == TYPE_FORM:
293
+ return encode_params(data)
294
+ return jsonencode(data)
295
+
296
+ def _mask_sensitive_data(self, data):
297
+ # type: (str | bytes | None) -> str | bytes | None
298
+ """
299
+ 对敏感数据进行打码处理,用于日志输出,支持URL编码的敏感信息
300
+
301
+ Args:
302
+ data (str | bytes | None): 需要处理的数据
303
+ Returns:
304
+ str | bytes | None: 打码后的字符串
305
+ """
306
+ if not data or not self.token:
307
+ return data
308
+
309
+ # 生成打码后的token
310
+ token_masked = self.token[:2] + "***" + self.token[-2:] if len(self.token) > 4 else "***"
311
+ token_encoded = quote(self.token, safe="")
312
+
313
+ if isinstance(data, bytes): # 处理字节数据
314
+ return data.replace(self.token.encode(), token_masked.encode()).replace(
315
+ token_encoded.encode(), token_masked.encode()
316
+ )
317
+ if hasattr(data, "replace"): # 处理字符串数据
318
+ return data.replace(self.token, token_masked).replace(token_encoded, token_masked)
319
+ return data
320
+
321
+
322
+ class BaseProvider(SimpleProvider):
323
+ """
324
+ 标准DNS服务商接口的抽象基类
325
+
326
+ Abstract base class for all standard DNS provider APIs.
327
+ Subclasses must implement the abstract methods to support various providers.
328
+
329
+ * _query_zone_id()
330
+ * _query_record_id()
331
+ * _update_record()
332
+ * _create_record()
333
+ """
334
+
335
+ def set_record(self, domain, value, record_type="A", ttl=None, line=None, **extra):
336
+ # type: (str, str, str, str | int | None, str | None, **Any) -> bool
337
+ """
338
+ 设置 DNS 记录(创建或更新)
339
+
340
+ Set or update DNS record.
341
+
342
+ Args:
343
+ domain (str): 完整域名
344
+ value (str): 新记录值
345
+ record_type (str): 记录类型
346
+ ttl (int | None): TTL 值,可选
347
+ line (str | None): 线路信息
348
+ extra (dict): 额外参数
349
+
350
+ Returns:
351
+ bool: 执行结果
352
+ """
353
+ domain = domain.lower()
354
+ self.logger.info("%s => %s(%s)", domain, value, record_type)
355
+ sub, main = _split_custom_domain(domain)
356
+ try:
357
+ if sub is not None:
358
+ # 使用自定义分隔符格式
359
+ zone_id = self.get_zone_id(main)
360
+ else:
361
+ # 自动分析域名
362
+ zone_id, sub, main = self._split_zone_and_sub(domain)
363
+
364
+ self.logger.info("sub: %s, main: %s(id=%s)", sub, main, zone_id)
365
+ if not zone_id or sub is None:
366
+ self.logger.critical("找不到 zone_id 或 subdomain: %s", domain)
367
+ return False
368
+
369
+ # 查询现有记录
370
+ record = self._query_record(zone_id, sub, main, record_type=record_type, line=line, extra=extra)
371
+
372
+ # 更新或创建记录
373
+ if record:
374
+ self.logger.info("Found existing record: %s", record)
375
+ return self._update_record(zone_id, record, value, record_type, ttl=ttl, line=line, extra=extra)
376
+ else:
377
+ self.logger.warning("No existing record found, creating new one")
378
+ return self._create_record(zone_id, sub, main, value, record_type, ttl=ttl, line=line, extra=extra)
379
+ except Exception as e:
380
+ self.logger.exception("Error setting record for %s: %s", domain, e)
381
+ return False
382
+
383
+ def get_zone_id(self, domain):
384
+ # type: (str) -> str | None
385
+ """
386
+ 查询指定域名对应的 zone_id
387
+
388
+ Get zone_id for the domain.
389
+
390
+ Args:
391
+ domain (str): 主域名 / main name
392
+
393
+ Returns:
394
+ str | None: 区域 ID / Zone identifier
395
+ """
396
+ if domain in self._zone_map:
397
+ return self._zone_map[domain]
398
+ zone_id = self._query_zone_id(domain)
399
+ if zone_id:
400
+ self._zone_map[domain] = zone_id
401
+ return zone_id
402
+
403
+ @abstractmethod
404
+ def _query_zone_id(self, domain):
405
+ # type: (str) -> str | None
406
+ """
407
+ 查询主域名的 zone ID
408
+
409
+ Args:
410
+ domain (str): 主域名
411
+
412
+ Returns:
413
+ str | None: Zone ID
414
+ """
415
+ return domain
416
+
417
+ @abstractmethod
418
+ def _query_record(self, zone_id, subdomain, main_domain, record_type, line, extra):
419
+ # type: (str, str, str, str, str | None, dict) -> Any
420
+ """
421
+ 查询 DNS 记录 ID
422
+
423
+ Args:
424
+ zone_id (str): 区域 ID
425
+ subdomain (str): 子域名
426
+ main_domain (str): 主域名
427
+ record_type (str): 记录类型,例如 A、AAAA
428
+ line (str | None): 线路选项,可选
429
+ extra (dict): 额外参数
430
+ Returns:
431
+ Any | None: 记录
432
+ """
433
+ raise NotImplementedError("This _query_record should be implemented by subclasses")
434
+
435
+ @abstractmethod
436
+ def _create_record(self, zone_id, subdomain, main_domain, value, record_type, ttl, line, extra):
437
+ # type: (str, str, str, str, str, int | str | None, str | None, dict) -> bool
438
+ """
439
+ 创建新 DNS 记录
440
+
441
+ Args:
442
+ zone_id (str): 区域 ID
443
+ subdomain (str): 子域名
444
+ main_domain (str): 主域名
445
+ value (str): 记录值
446
+ record_type (str): 类型,如 A
447
+ ttl (int | None): TTL 可选
448
+ line (str | None): 线路选项
449
+ extra (dict | None): 额外字段
450
+
451
+ Returns:
452
+ Any: 操作结果
453
+ """
454
+ raise NotImplementedError("This _create_record should be implemented by subclasses")
455
+
456
+ @abstractmethod
457
+ def _update_record(self, zone_id, old_record, value, record_type, ttl, line, extra):
458
+ # type: (str, dict, str, str, int | str | None, str | None, dict) -> bool
459
+ """
460
+ 更新已有 DNS 记录
461
+
462
+ Args:
463
+ zone_id (str): 区域 ID
464
+ old_record (dict): 旧记录信息
465
+ value (str): 新的记录值
466
+ record_type (str): 类型
467
+ ttl (int | None): TTL
468
+ line (str | None): 线路
469
+ extra (dict | None): 额外参数
470
+
471
+ Returns:
472
+ bool: 操作结果
473
+ """
474
+ raise NotImplementedError("This _update_record should be implemented by subclasses")
475
+
476
+ def _split_zone_and_sub(self, domain):
477
+ # type: (str) -> tuple[str | None, str | None, str ]
478
+ """
479
+ 从完整域名拆分主域名和子域名
480
+
481
+ Args:
482
+ domain (str): 完整域名
483
+
484
+ Returns:
485
+ (zone_id, sub): 元组
486
+ """
487
+ domain_split = domain.split(".")
488
+ zone_id = None
489
+ index = 2
490
+ main = ""
491
+ while not zone_id and index <= len(domain_split):
492
+ main = ".".join(domain_split[-index:])
493
+ zone_id = self.get_zone_id(main)
494
+ index += 1
495
+ if zone_id:
496
+ sub = ".".join(domain_split[: -index + 1]) or "@"
497
+ self.logger.debug("zone_id: %s, sub: %s", zone_id, sub)
498
+ return zone_id, sub, main
499
+ return None, None, main
500
+
501
+
502
+ def _split_custom_domain(domain):
503
+ # type: (str) -> tuple[str | None, str]
504
+ """
505
+ 拆分支持 ~ 或 + 的自定义格式域名为 (子域, 主域)
506
+
507
+ 如 sub~example.com => ('sub', 'example.com')
508
+
509
+ Returns:
510
+ (sub, main): 子域 + 主域
511
+ """
512
+ for sep in ("~", "+"):
513
+ if sep in domain:
514
+ sub, main = domain.split(sep, 1)
515
+ return sub, main
516
+ return None, domain
517
+
518
+
519
+ def join_domain(sub, main):
520
+ # type: (str | None, str) -> str
521
+ """
522
+ 合并子域名和主域名为完整域名
523
+
524
+ Args:
525
+ sub (str | None): 子域名
526
+ main (str): 主域名
527
+
528
+ Returns:
529
+ str: 完整域名
530
+ """
531
+ sub = sub and sub.strip(".").strip().lower()
532
+ main = main and main.strip(".").strip().lower()
533
+ if not sub or sub == "@":
534
+ if not main:
535
+ raise ValueError("Both sub and main cannot be empty")
536
+ return main
537
+ if not main:
538
+ return sub
539
+ return "{}.{}".format(sub, main)
@@ -0,0 +1,113 @@
1
+ # coding=utf-8
2
+ """
3
+ DNS Provider 签名和哈希算法模块
4
+
5
+ Signature and hash algorithms module for DNS providers.
6
+ Provides common cryptographic functions for cloud provider authentication.
7
+
8
+ @author: NewFuture
9
+ """
10
+
11
+ from hashlib import sha256
12
+ from hmac import HMAC
13
+
14
+
15
+ def hmac_sha256(key, message):
16
+ # type: (str | bytes, str | bytes) -> HMAC
17
+ """
18
+ 计算 HMAC-SHA256 签名对象
19
+
20
+ Compute HMAC-SHA256 signature object.
21
+
22
+ Args:
23
+ key (str | bytes): 签名密钥 / Signing key
24
+ message (str | bytes): 待签名消息 / Message to sign
25
+
26
+ Returns:
27
+ HMAC: HMAC签名对象,可调用.digest()获取字节或.hexdigest()获取十六进制字符串
28
+ HMAC signature object, call .digest() for bytes or .hexdigest() for hex string
29
+ """
30
+ # Python 2/3 compatible encoding - avoid double encoding in Python 2
31
+ if not isinstance(key, bytes):
32
+ key = key.encode("utf-8")
33
+ if not isinstance(message, bytes):
34
+ message = message.encode("utf-8")
35
+ return HMAC(key, message, sha256)
36
+
37
+
38
+ def sha256_hash(data):
39
+ # type: (str | bytes) -> str
40
+ """
41
+ 计算 SHA256 哈希值
42
+
43
+ Compute SHA256 hash.
44
+
45
+ Args:
46
+ data (str | bytes): 待哈希数据 / Data to hash
47
+
48
+ Returns:
49
+ str: 十六进制哈希字符串 / Hexadecimal hash string
50
+ """
51
+ # Python 2/3 compatible encoding - avoid double encoding in Python 2
52
+ if not isinstance(data, bytes):
53
+ data = data.encode("utf-8")
54
+ return sha256(data).hexdigest()
55
+
56
+
57
+ def hmac_sha256_authorization(
58
+ secret_key, # type: str | bytes
59
+ method, # type: str
60
+ path, # type: str
61
+ query, # type: str
62
+ headers, # type: dict[str, str]
63
+ body_hash, # type: str
64
+ signing_string_format, # type: str
65
+ authorization_format, # type: str
66
+ ):
67
+ # type: (...) -> str
68
+ """
69
+ HMAC-SHA256 云服务商通用认证签名生成器
70
+
71
+ Universal cloud provider authentication signature generator using HMAC-SHA256.
72
+
73
+ 通用的云服务商API认证签名生成函数,使用HMAC-SHA256算法生成符合各云服务商规范的Authorization头部。
74
+
75
+ 模板变量格式:{HashedCanonicalRequest}, {SignedHeaders}, {Signature}
76
+
77
+ Args:
78
+ secret_key (str | bytes): 签名密钥,已经过密钥派生处理 / Signing key (already derived if needed)
79
+ method (str): HTTP请求方法 / HTTP request method (GET, POST, etc.)
80
+ path (str): API请求路径 / API request path
81
+ query (str): URL查询字符串 / URL query string
82
+ headers (dict[str, str]): HTTP请求头部 / HTTP request headers
83
+ body_hash (str): 请求体的SHA256哈希值 / SHA256 hash of request payload
84
+ signing_string_format (str): 待签名字符串模板,包含 {HashedCanonicalRequest} 占位符
85
+ authorization_format (str): Authorization头部模板,包含 {SignedHeaders}, {Signature} 占位符
86
+
87
+ Returns:
88
+ str: 完整的Authorization头部值 / Complete Authorization header value
89
+ """
90
+ # 1. 构建规范化头部 - 所有传入的头部都参与签名
91
+ headers_to_sign = {k.lower(): str(v).strip() for k, v in headers.items()}
92
+ signed_headers_list = sorted(headers_to_sign.keys())
93
+
94
+ # 2. 构建规范请求字符串
95
+ canonical_headers = ""
96
+ for header_name in signed_headers_list:
97
+ canonical_headers += "{}:{}\n".format(header_name, headers_to_sign[header_name])
98
+
99
+ # 构建完整的规范请求字符串
100
+ signed_headers = ";".join(signed_headers_list)
101
+ canonical_request = "\n".join([method.upper(), path, query, canonical_headers, signed_headers, body_hash])
102
+
103
+ # 3. 构建待签名字符串 - 只需要替换 HashedCanonicalRequest
104
+ hashed_canonical_request = sha256_hash(canonical_request)
105
+ string_to_sign = signing_string_format.format(HashedCanonicalRequest=hashed_canonical_request)
106
+
107
+ # 4. 计算最终签名
108
+ signature = hmac_sha256(secret_key, string_to_sign).hexdigest()
109
+
110
+ # 5. 构建Authorization头部 - 只需要替换 SignedHeaders 和 Signature
111
+ authorization = authorization_format.format(SignedHeaders=signed_headers, Signature=signature)
112
+
113
+ return authorization