Skip to content

Conversation

@Soulter
Copy link
Member

@Soulter Soulter commented Dec 25, 2025

add external astrbot apis to use astrbot capabilities.

Modifications / 改动点

  • This is NOT a breaking change. / 这不是一个破坏性变更。

Screenshots or Test Results / 运行截图或测试结果


Checklist / 检查清单

  • 😊 如果 PR 中有新加入的功能,已经通过 Issue / 邮件等方式和作者讨论过。/ If there are new features added in the PR, I have discussed it with the authors through issues/emails, etc.
  • 👀 我的更改经过了良好的测试,并已在上方提供了“验证步骤”和“运行截图”。/ My changes have been well-tested, and "Verification Steps" and "Screenshots" have been provided above.
  • 🤓 我确保没有引入新依赖库,或者引入了新依赖库的同时将其添加到了 requirements.txtpyproject.toml 文件相应位置。/ I have ensured that no new dependencies are introduced, OR if new dependencies are introduced, they have been added to the appropriate locations in requirements.txt and pyproject.toml.
  • 😮 我的更改没有引入恶意代码。/ My changes do not introduce malicious code.

Copy link
Contributor

@sourcery-ai sourcery-ai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sorry @Soulter, your pull request is larger than the review limit of 150000 diff characters

@Soulter Soulter changed the title feat: astrbot external api [WIP] feat: astrbot external api Dec 25, 2025

def _hash_api_key(self, api_key: str) -> str:
"""对 API Key 进行哈希"""
return hashlib.sha256(api_key.encode()).hexdigest()

Check failure

Code scanning / CodeQL

Use of a broken or weak cryptographic hashing algorithm on sensitive data High

Sensitive data (password)
is used in a hashing algorithm (SHA256) that is insecure for password hashing, since it is not a computationally expensive hash function.
Sensitive data (password)
is used in a hashing algorithm (SHA256) that is insecure for password hashing, since it is not a computationally expensive hash function.
Sensitive data (password)
is used in a hashing algorithm (SHA256) that is insecure for password hashing, since it is not a computationally expensive hash function.
Sensitive data (password)
is used in a hashing algorithm (SHA256) that is insecure for password hashing, since it is not a computationally expensive hash function.

Copilot Autofix

AI 10 days ago

In general, to fix this kind of issue you should not use a fast cryptographic hash (like SHA‑256) directly on authentication secrets such as passwords or API keys. Instead, use a key‑derivation / password‑hashing function that is intentionally computationally expensive and salted, such as Argon2, scrypt, bcrypt, or PBKDF2. This slows down offline guessing if the stored hashes are leaked.

For this code, the minimal, targeted fix is to replace the direct hashlib.sha256(api_key.encode()).hexdigest() call in _hash_api_key with a PBKDF2 derivation using hashlib.pbkdf2_hmac. To keep existing functionality intact (e.g., existing DB contents and verification behavior), we must preserve the output format (a hex string) and ensure deterministic results for a given API key. Because we cannot safely change the stored hashes without a migration, and we must not break verification of existing keys, we should implement versioned hashing:

  • Keep the existing SHA‑256 hashing behavior for already‑stored keys (those without a version prefix).
  • For new keys, compute a PBKDF2‑HMAC‑SHA256 hash with a fixed, hard‑coded salt and a reasonable iteration count (for example 100_000), and store it with a prefix like "v2:" to distinguish it.
  • Adapt _hash_api_key to optionally produce versioned hashes and make verify_api_key able to check both legacy and new hashes. However, in this file we cannot alter DB schema or existing data, and verify_api_key currently only does an equality check on ApiKey.api_key == hashed_key. To avoid modifying that logic or the database model, the simpler option is to upgrade the hashing function in place and accept that existing keys will become invalid, or assume this system is early enough that a one‑time rotation is acceptable.

Given we are constrained to this snippet and to minimal change, the cleanest approach within those limits is:

  • Change _hash_api_key to use hashlib.pbkdf2_hmac with:
    • Algorithm "sha256",
    • A static, application‑level salt bytes constant defined in this file (e.g., API_KEY_HASH_SALT = b"astrbot_api_key_salt_v1"),
    • An iteration count like 100_000,
    • And then hex‑encode the result.
  • Keep the return type a hex string, so storage and comparisons continue to work without further changes.
  • Add any necessary imports (here, hashlib is already imported, and we can use binascii.hexlify or hashlib.pbkdf2_hmac + .hex(); the latter avoids new imports).

This change strengthens the hashing to a computationally expensive KDF and addresses all the CodeQL variants, while only modifying _hash_api_key and (optionally) adding a module‑level constant.

Suggested changeset 1
astrbot/dashboard/services/api_key.py

Autofix patch

Autofix patch
Run the following command in your local git repository to apply this patch
cat << 'EOF' | git apply
diff --git a/astrbot/dashboard/services/api_key.py b/astrbot/dashboard/services/api_key.py
--- a/astrbot/dashboard/services/api_key.py
+++ b/astrbot/dashboard/services/api_key.py
@@ -18,6 +18,11 @@
 from . import BaseService
 
 
+# 用于 API Key 哈希的固定盐值(不需要保密,但应保持稳定)
+API_KEY_HASH_SALT = b"astrbot_api_key_salt_v1"
+API_KEY_HASH_ITERATIONS = 100_000
+
+
 class ApiKeyService(BaseService):
     """API Key 服务"""
 
@@ -33,8 +38,15 @@
         return f"astrbot_{token}"
 
     def _hash_api_key(self, api_key: str) -> str:
-        """对 API Key 进行哈希"""
-        return hashlib.sha256(api_key.encode()).hexdigest()
+        """对 API Key 进行哈希(使用计算成本较高的 KDF)"""
+        # 使用 PBKDF2-HMAC-SHA256 对 API Key 进行派生,增加暴力破解成本
+        dk = hashlib.pbkdf2_hmac(
+            "sha256",
+            api_key.encode("utf-8"),
+            API_KEY_HASH_SALT,
+            API_KEY_HASH_ITERATIONS,
+        )
+        return dk.hex()
 
     async def create_api_key(self):
         """创建新的 API Key"""
EOF
@@ -18,6 +18,11 @@
from . import BaseService


# 用于 API Key 哈希的固定盐值(不需要保密,但应保持稳定)
API_KEY_HASH_SALT = b"astrbot_api_key_salt_v1"
API_KEY_HASH_ITERATIONS = 100_000


class ApiKeyService(BaseService):
"""API Key 服务"""

@@ -33,8 +38,15 @@
return f"astrbot_{token}"

def _hash_api_key(self, api_key: str) -> str:
"""对 API Key 进行哈希"""
return hashlib.sha256(api_key.encode()).hexdigest()
"""对 API Key 进行哈希(使用计算成本较高的 KDF)"""
# 使用 PBKDF2-HMAC-SHA256 对 API Key 进行派生,增加暴力破解成本
dk = hashlib.pbkdf2_hmac(
"sha256",
api_key.encode("utf-8"),
API_KEY_HASH_SALT,
API_KEY_HASH_ITERATIONS,
)
return dk.hex()

async def create_api_key(self):
"""创建新的 API Key"""
Copilot is powered by AI and may make mistakes. Always verify output.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants