Normalize copied API keys and show explicit setup validation errors
This commit is contained in:
parent
a44d45f431
commit
8739a521bf
4 changed files with 43 additions and 11 deletions
|
|
@ -2,4 +2,4 @@
|
||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
__version__ = "0.3.0b7"
|
__version__ = "0.3.0b8"
|
||||||
|
|
|
||||||
|
|
@ -4,6 +4,7 @@ from __future__ import annotations
|
||||||
|
|
||||||
import json
|
import json
|
||||||
import os
|
import os
|
||||||
|
import re
|
||||||
import tempfile
|
import tempfile
|
||||||
from io import StringIO
|
from io import StringIO
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
|
@ -23,16 +24,31 @@ def read_api_key(root: Path) -> str:
|
||||||
|
|
||||||
def normalize_api_key(value: str) -> str:
|
def normalize_api_key(value: str) -> str:
|
||||||
"""Accept a key or one OPENAI_API_KEY assignment pasted from dotenv."""
|
"""Accept a key or one OPENAI_API_KEY assignment pasted from dotenv."""
|
||||||
candidate = value.strip()
|
candidate = value.strip().lstrip("\ufeff")
|
||||||
if candidate.startswith(("OPENAI_API_KEY=", "OPENAI_API_KEY =", "export OPENAI_API_KEY=")):
|
assignment = re.match(r"^(?:export\s+)?OPENAI_API_KEY\s*=", candidate)
|
||||||
|
if assignment:
|
||||||
|
candidate = "OPENAI_API_KEY=" + candidate[assignment.end() :]
|
||||||
parsed = dotenv_values(stream=StringIO(candidate), interpolate=False)
|
parsed = dotenv_values(stream=StringIO(candidate), interpolate=False)
|
||||||
if set(parsed) != {"OPENAI_API_KEY"}:
|
if set(parsed) != {"OPENAI_API_KEY"}:
|
||||||
raise ValueError("Вставьте только строку OPENAI_API_KEY или значение ключа")
|
raise ValueError("Скопировано несколько настроек. Нужна только строка OPENAI_API_KEY.")
|
||||||
candidate = (parsed.get("OPENAI_API_KEY") or "").strip()
|
candidate = (parsed.get("OPENAI_API_KEY") or "").strip()
|
||||||
elif len(candidate) >= 2 and candidate[0] == candidate[-1] and candidate[0] in "\"'":
|
quote_pairs = {'"': '"', "'": "'", "“": "”", "«": "»"}
|
||||||
|
if len(candidate) >= 2 and quote_pairs.get(candidate[0]) == candidate[-1]:
|
||||||
candidate = candidate[1:-1].strip()
|
candidate = candidate[1:-1].strip()
|
||||||
if not candidate or any(char.isspace() for char in candidate) or "=" in candidate:
|
if not candidate:
|
||||||
raise ValueError("Введите ключ без пробелов и переносов строк")
|
raise ValueError("Поле ключа пустое. Вставьте значение OPENAI_API_KEY из .env.")
|
||||||
|
# Long keys are sometimes copied with visual line wrapping or invisible separators.
|
||||||
|
compact = "".join(
|
||||||
|
char for char in candidate if not char.isspace() and char not in "\u200b\ufeff"
|
||||||
|
)
|
||||||
|
if compact.startswith("sk-") and re.fullmatch(r"[A-Za-z0-9_-]+", compact):
|
||||||
|
candidate = compact
|
||||||
|
if any(char.isspace() for char in candidate):
|
||||||
|
raise ValueError(
|
||||||
|
"В ключе остались пробелы или лишние строки. Скопируйте только значение после =."
|
||||||
|
)
|
||||||
|
if "=" in candidate:
|
||||||
|
raise ValueError("Не удалось разобрать строку. Ожидается OPENAI_API_KEY=значение.")
|
||||||
return candidate
|
return candidate
|
||||||
|
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -5,6 +5,7 @@ from __future__ import annotations
|
||||||
import subprocess
|
import subprocess
|
||||||
import sys
|
import sys
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
from tkinter import messagebox
|
||||||
|
|
||||||
import customtkinter as ctk
|
import customtkinter as ctk
|
||||||
|
|
||||||
|
|
@ -123,10 +124,10 @@ def run_setup(root: Path, store: ConfigStore, *, smoke_test: bool = False) -> bo
|
||||||
try:
|
try:
|
||||||
if key.get().strip():
|
if key.get().strip():
|
||||||
save_api_key(root, key.get())
|
save_api_key(root, key.get())
|
||||||
except ValueError:
|
except ValueError as exc:
|
||||||
message.configure(
|
message.configure(text=str(exc))
|
||||||
text="Вставьте значение ключа или одну строку OPENAI_API_KEY=… из .env."
|
messagebox.showerror("Ключ не сохранён", str(exc), parent=window)
|
||||||
)
|
key.focus_set()
|
||||||
return
|
return
|
||||||
except OSError:
|
except OSError:
|
||||||
message.configure(
|
message.configure(
|
||||||
|
|
|
||||||
|
|
@ -53,3 +53,18 @@ def test_multiple_env_values_rejected(tmp_path: Path) -> None:
|
||||||
with pytest.raises(ValueError):
|
with pytest.raises(ValueError):
|
||||||
save_api_key(tmp_path, "OPENAI_API_KEY=sk-test\nOTHER_KEY=test")
|
save_api_key(tmp_path, "OPENAI_API_KEY=sk-test\nOTHER_KEY=test")
|
||||||
assert not (tmp_path / "credentials.json").exists()
|
assert not (tmp_path / "credentials.json").exists()
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize(
|
||||||
|
"value",
|
||||||
|
[
|
||||||
|
"OPENAI_API_KEY\t=sk-test-not-real",
|
||||||
|
"export OPENAI_API_KEY = sk-test-not-real",
|
||||||
|
"sk-test-\nnot-real",
|
||||||
|
"“sk-test-not-real”",
|
||||||
|
"sk-test-\u200bnot-real",
|
||||||
|
],
|
||||||
|
)
|
||||||
|
def test_copy_formatting_is_normalized(tmp_path: Path, value: str) -> None:
|
||||||
|
save_api_key(tmp_path, value)
|
||||||
|
assert read_api_key(tmp_path) == "sk-test-not-real"
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue