Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -409,7 +409,7 @@ curl -X POST http://127.0.0.1:8000/v1/fetch \
- **限额护栏**(行内「设置限额」,四项独立,全空 = 不受限,判定在选号前):保留积分(剩余 ≤ 值 → 整号停用,余额未知不猜)、每日 token 上限、每日积分上限、按模型 token 上限(`{模型: 上限}`,只停该模型)。当日 = 北京时间自然日。写入 `PUT /api/credentials/{id}/limits`(整体替换,即时生效,审计 `credential.limits`)。
- **凭证级模型白名单**(同一对话框):`allowed_models` = fnmatch glob、逗号分隔,`''` = 不限制,语法与 API Key 的模型白名单一致。**只作用于对话 / 推理选号**:不在列表里的模型不选这个号,但不硬禁用、不写冷却,换个模型立即可用;签到 / 刷新 / 探活 / 额度探测 / 模型列表等后台路径不受限。模型名无法判定(空 / `auto`)时放行,避免把池子摘空。
- **账号级模型黑名单**(`blocked_models`,同语法同语义,与白名单取**交集**、黑名单优先):某号被某模型封了(`11102` 负缓存 / `6004` 模型限流)时只摘掉那一个模型,不必整号停用。同样只影响选号、不硬禁用、不写冷却;模型名无法判定时**不摘号**(黑名单 fail open —— 摘错号会直接减少可用容量)。
- **不可续期标注**:凭证行在剩余时间后追加「不可续期」——该凭证**没有刷新凭据**(手工粘贴的 bearer-only token),到期只能重新粘贴。判定在写入口按凭证结构派生(`refresh_token` / `wps_sid` / `access_token` 任一存在即算可续期),**只在有到期时间时**判定;读路径对老库行按需派生一次。与「刷新令牌已失效」(需重新登录,`disabled_reason`)是两回事:前者是结构性的、重试无意义。
- **不可续期标注**:凭证行在剩余时间后追加「不可续期」——该凭证**没有刷新凭据**(手工粘贴的 bearer-only token),到期只能重新粘贴。判定在写入口按凭证结构派生(`refresh_token` / `wps_sid` / `access_token` 任一存在即算可续期),**只在有到期时间时**判定;读路径对老库行按需派生一次。与「刷新令牌已失效」(需重新登录,`disabled_reason`)是两回事:前者是结构性的、重试无意义。升级时自动回填老库 `refreshable`:对「token 两列已写、`refreshable` 未判定」的行按凭证结构解密判定一次,可续期的行保持未判定(下次启动重试解不开的行)。
- **凭证批量导出** `POST /api/credentials/export`(`{ids: [...]}`,≤200 条):输出 `{credentials: [...], failed: [...]}`,条目与「批量导入」同形,可原样回灌;逐条隔离(解密失败 / 不存在只进 `failed`,带受控原因),与单条 `/export` 同一脱敏(去 `web_cookie` / `password`)、同一 `credential.export` 审计、`no-store`。
- **并发编辑冲突**:编辑端点带 `expected_updated_at`(列表每行已返回),不匹配回 `409 credential_conflict` 并附当前行快照;管理台提示「已被他人修改,请刷新」。版本号只在**人工编辑**时推进,后台轮询/冷却写入不推进,所以打开着的编辑页不会被自己刷成过期。
- **在途上限** `MAX_INFLIGHT_PER_CREDENTIAL`(默认 0 = 不限,可热更):同一凭证并发达到该值后不再参与选号;计数进程内,租约在请求结束时释放,另有 600s TTL 兜底。**兼作负载键**:插在「免费优先」之后、到期额度之前 → 并发自动摊到空闲号。
Expand Down
28 changes: 28 additions & 0 deletions src/db/migrate.py
Original file line number Diff line number Diff line change
Expand Up @@ -310,3 +310,31 @@ def apply_schema(conn) -> None:
# PRAGMA 不支持参数绑定,版本号来自本模块常量(非外部输入)
conn.execute(f"PRAGMA user_version = {SCHEMA_VERSION}")
conn.commit()


def backfill_refreshable(conn, cipher) -> None:
"""v42 老库 `refreshable` 回填(幂等,随启动执行一次)。

v42 只补列不判定,而派生触发器(`repo._resolve_token_facts`)只认
`token_expires_at IS NULL`:升级前就已写回 token 两列的行永远不会再被派生,
「不可续期」标记就此永久丢失,写路径也都与新列同时写、不会自我修复。

**必须解密才能判定**:有刷新凭据(可续期)与结构性不可续期在列上都表现为
NULL,纯 SQL 条件会把可续期的 OAuth 行全部误标成「不可续期」。所以只补
派生结果为 1 的行;可续期行保持 NULL(与新库写路径一致),解不开的行不写、
留待下次启动重试。`WHERE ... refreshable IS NULL` 自带条件,重复执行结果一致。
"""
# 延迟导入:repo 依赖较重(调度 / 上游),而本模块被建用户脚本直接引用。
from .repo import _legacy_token_facts

rows = conn.execute(
"SELECT id, data_enc FROM credentials"
" WHERE token_expires_at > 0 AND refreshable IS NULL").fetchall()
for credential_id, data_enc in rows:
facts = _legacy_token_facts(data_enc, cipher)
if facts is None or facts[2] is None:
continue
conn.execute(
"UPDATE credentials SET refreshable = ?"
" WHERE id = ? AND refreshable IS NULL", (facts[2], credential_id))
conn.commit()
5 changes: 4 additions & 1 deletion src/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,7 @@
from .db.key_usage import KeyUsageRepository
from .db.limits import LimitsRepository, day_usage
from .db.log_repo import LogRepository
from .db.migrate import apply_schema
from .db.migrate import apply_schema, backfill_refreshable
from .db.paid_models import PaidModelRepository
from .db.repo import (
AccessFreezeRepository,
Expand Down Expand Up @@ -516,6 +516,9 @@ def build_app(settings: Settings | None = None, *, providers: dict | None = None
# 必须在 apply_schema 之后构造——新库的 runtime_settings 表由上面建好。
runtime = load_runtime_settings(config, RuntimeSettingsRepository(db))
cipher = CredentialCipher(config.app_secret)
# v42 老库 refreshable 回填:需要解密判定,故放在 cipher 建好之后、
# 首次读凭证之前(幂等,每次启动重试解不开的行)。
backfill_refreshable(db.connect(), cipher)
credentials = CredentialRepository(db, cipher)
growth_events = GrowthRepository(db)
credit_events = CreditEventRepository(db)
Expand Down
74 changes: 64 additions & 10 deletions tests/db/test_repo_token.py
Original file line number Diff line number Diff line change
Expand Up @@ -265,12 +265,17 @@ def decrypt(self, ciphertext: bytes) -> bytes:
return self._inner.decrypt(ciphertext)


def _legacy_row(tmp_path, token):
"""建库并造一行老库凭证:token 两列与 refreshable 全为 NULL。"""
def _legacy_row(tmp_path, token, now=None):
"""建库并造一行老库凭证:token 两列与 refreshable 全为 NULL。

`now` 由调用方给定:测试要用同一个时刻造 token 和断言列值,若这里再取一次
`time.time()`,跨秒(CI 上建库 + 加密可能跨 1 秒)就会让 `iat`/`exp` 与断言
差 1 秒而随机失败。
"""
db = Database(tmp_path / "t.sqlite3")
apply_schema(db.connect())
credentials = CredentialRepository(db, CountingCipher(CredentialCipher(SECRET)))
now = int(time.time())
now = int(time.time()) if now is None else now
cid = credentials.add(provider="codebuddy", credential_data={"bearer_token": token},
now=now)
db.connect().execute(
Expand Down Expand Up @@ -309,7 +314,7 @@ def test_legacy_token_facts_tolerates_bad_ciphertext():
def test_legacy_row_read_is_read_only_and_derives_per_read(tmp_path):
"""老库行:读路径只派生展示值、**不写库**(不再有 UPDATE)。"""
now = int(time.time())
credentials, db, cid, now = _legacy_row(tmp_path, _jwt(now + 5 * 86400, iat=now))
credentials, db, cid, now = _legacy_row(tmp_path, _jwt(now + 5 * 86400, iat=now), now=now)
cols = ("token_expires_at", "token_issued_at", "refreshable", "updated_at",
"enabled", "disabled", "pinned")
before = _columns(db, cid, cols)
Expand All @@ -336,7 +341,7 @@ def test_legacy_row_read_is_read_only_and_derives_per_read(tmp_path):
def test_backfill_token_columns_writes_once_and_is_idempotent(tmp_path):
"""一次性回填:写回三列、可重复执行、之后读路径零解密。"""
now = int(time.time())
credentials, db, cid, now = _legacy_row(tmp_path, _jwt(now + 5 * 86400, iat=now))
credentials, db, cid, now = _legacy_row(tmp_path, _jwt(now + 5 * 86400, iat=now), now=now)
cols = ("token_expires_at", "token_issued_at", "refreshable", "updated_at",
"enabled", "disabled", "pinned")
before = _columns(db, cid, cols)
Expand Down Expand Up @@ -379,7 +384,7 @@ def test_expiring_tokens_reads_legacy_row_without_writing(tmp_path):
now = int(time.time())
# 寿命 20 天、还剩 1 天:落进 3 天窗口,且不会被「寿命短于窗口」静音
credentials, db, cid, now = _legacy_row(
tmp_path, _jwt(now + 86400, iat=now - 19 * 86400))
tmp_path, _jwt(now + 86400, iat=now - 19 * 86400), now=now)
hits = credentials.expiring_tokens(within_seconds=3 * 86400, now=now)
assert [item["id"] for item in hits] == [cid]
assert _columns(db, cid, ("token_expires_at", "token_issued_at")) == {
Expand All @@ -396,7 +401,7 @@ def test_expiring_tokens_reads_legacy_row_without_writing(tmp_path):
def test_backfill_skips_undecryptable_rows(tmp_path):
"""密文坏掉的行不回填半成品,留着下次启动重试;返回 0。"""
now = int(time.time())
credentials, db, cid, now = _legacy_row(tmp_path, _jwt(now + 86400, iat=now))
credentials, db, cid, now = _legacy_row(tmp_path, _jwt(now + 86400, iat=now), now=now)
db.connect().execute("UPDATE credentials SET data_enc = ? WHERE id = ?",
(b"not-a-fernet-token", cid))
db.connect().commit()
Expand All @@ -409,7 +414,7 @@ def test_backfill_skips_undecryptable_rows(tmp_path):
def test_read_path_survives_read_only_connection(tmp_path):
"""只读副本 / PRAGMA query_only:读接口字段完整、不因写而失败。"""
now = int(time.time())
credentials, db, cid, now = _legacy_row(tmp_path, _jwt(now + 5 * 86400, iat=now))
credentials, db, cid, now = _legacy_row(tmp_path, _jwt(now + 5 * 86400, iat=now), now=now)
db.close()
ro = Database(tmp_path / "t.sqlite3", read_only=True)
ro_credentials = CredentialRepository(ro, CountingCipher(CredentialCipher(SECRET)))
Expand All @@ -427,7 +432,7 @@ def test_read_path_survives_read_only_connection(tmp_path):
def test_read_path_logs_and_degrades_when_cipher_raises(tmp_path):
"""派生抛非预期异常:只记 WARNING,GET 不会 500,字段退化成未知。"""
now = int(time.time())
credentials, db, cid, now = _legacy_row(tmp_path, _jwt(now + 86400, iat=now))
credentials, db, cid, now = _legacy_row(tmp_path, _jwt(now + 86400, iat=now), now=now)

class BombCipher:
calls = 0
Expand Down Expand Up @@ -466,7 +471,7 @@ def test_known_expiry_row_never_decrypts_even_with_null_refreshable(tmp_path):
def test_undecryptable_legacy_row_keeps_columns_untouched(tmp_path):
"""密文坏掉:展示值退化、列表不抛异常,且不回写半成品。"""
now = int(time.time())
credentials, db, cid, now = _legacy_row(tmp_path, _jwt(now + 86400, iat=now))
credentials, db, cid, now = _legacy_row(tmp_path, _jwt(now + 86400, iat=now), now=now)
db.connect().execute("UPDATE credentials SET data_enc = ? WHERE id = ?",
(b"not-a-fernet-token", cid))
db.connect().commit()
Expand All @@ -479,3 +484,52 @@ def test_undecryptable_legacy_row_keeps_columns_untouched(tmp_path):
"token_issued_at": None,
"refreshable": None}
db.close()


def test_backfill_refreshable_marks_legacy_rows_only(tmp_path):
"""v42 老库回填:token 两列已写、refreshable 仍 NULL 的老行补回「不可续期」。

反向约束:有刷新凭据(可续期)的行同样是 NULL,不能被误标;已非 NULL 的
行不被改写;密文坏掉的行不写、留待重试;连续执行两次结果一致。
"""
from src.db.migrate import backfill_refreshable

db = Database(tmp_path / "t.sqlite3")
apply_schema(db.connect())
cipher = CredentialCipher(SECRET)
credentials = CredentialRepository(db, cipher)
now = int(time.time())
legacy = credentials.add(
provider="codebuddy",
credential_data={"bearer_token": _jwt(now + 3600, iat=now)}, now=now)
renewable = credentials.add(
provider="codebuddy",
credential_data={"bearer_token": _jwt(now + 3600, iat=now),
"refresh_token": "r"}, now=now)
decided = credentials.add(
provider="codebuddy",
credential_data={"bearer_token": _jwt(now + 3600, iat=now)}, now=now)
broken = credentials.add(provider="codebuddy",
credential_data={"bearer_token": "t"}, now=now)
db.connect().execute("UPDATE credentials SET refreshable = NULL WHERE id = ?",
(legacy,))
db.connect().execute("UPDATE credentials SET refreshable = 7 WHERE id = ?",
(decided,))
# 坏密文那行也造出「token 已写回」的形态,才能落进回填范围
db.connect().execute(
"UPDATE credentials SET token_expires_at = ?, data_enc = ? WHERE id = ?",
(now + 3600, b"not-a-fernet-token", broken))
db.connect().commit()

backfill_refreshable(db.connect(), cipher)
assert _columns(db, legacy, ("refreshable",)) == {"refreshable": 1}
assert _columns(db, renewable, ("refreshable",)) == {"refreshable": None}
assert _columns(db, decided, ("refreshable",)) == {"refreshable": 7}
assert _columns(db, broken, ("refreshable",)) == {"refreshable": None}

# 幂等:再跑一次结果一致(已非 NULL 的行不进范围)
backfill_refreshable(db.connect(), cipher)
assert _columns(db, legacy, ("refreshable",)) == {"refreshable": 1}
assert _columns(db, renewable, ("refreshable",)) == {"refreshable": None}
assert _columns(db, decided, ("refreshable",)) == {"refreshable": 7}
db.close()