From 5e474fb608b5fb23152e6cdc5d6186cd8ffdb286 Mon Sep 17 00:00:00 2001 From: Will Mobley Date: Fri, 20 Nov 2026 15:52:03 -0600 Subject: [PATCH] Credentials: show a typed value on request and save values trimmed A pasted key with a space at either end reached the model server as a key that does not start with sk-, and was refused with a 401 though it looked right. The Saved credentials form now has a show/hide button for each typed value and warns when a value starts or ends with a space or a quote mark. The adapter stores every field with spaces at either end removed, and the form trims too. Stored values are still never read back. --- svo-adapter-service/app/secrets.py | 17 +++++-- .../tests/test_secrets_store.py | 10 +++- ui-react/src/lib/user-secrets.ts | 18 ++++++- .../src/pages/account/CredentialsPage.tsx | 50 +++++++++++++++---- .../__tests__/CredentialsPage.test.tsx | 30 +++++++++++ 5 files changed, 110 insertions(+), 15 deletions(-) diff --git a/svo-adapter-service/app/secrets.py b/svo-adapter-service/app/secrets.py index b40be962..7e9b54d6 100644 --- a/svo-adapter-service/app/secrets.py +++ b/svo-adapter-service/app/secrets.py @@ -110,23 +110,32 @@ def validate_name(name: str) -> str: def validate_fields(fields: dict[str, str]) -> dict[str, str]: - """Field names ``[a-z0-9_]{1,32}``, at most 16, 4 KiB total, no NUL/newline.""" + """Field names ``[a-z0-9_]{1,32}``, at most 16, 4 KiB total, no NUL/newline. + + Returns the fields with spaces at either end of each value removed: they are + never part of a key or an address, and sent along they make a server reject a + key that looks right (a pasted " sk-..."). Store what this returns.""" if not isinstance(fields, dict) or not fields: raise SecretValidationError("fields must be a non-empty object") if len(fields) > MAX_FIELDS: raise SecretValidationError(f"at most {MAX_FIELDS} fields are allowed") total = 0 + cleaned: dict[str, str] = {} for key, value in fields.items(): if not isinstance(key, str) or not FIELD_RE.match(key): raise SecretValidationError("field names must match [a-z0-9_]{1,32}") - if not isinstance(value, str) or not value: + if not isinstance(value, str): raise SecretValidationError(f"field {key!r} must be a non-empty string") if "\x00" in value or "\n" in value or "\r" in value: raise SecretValidationError(f"field {key!r} must not contain NUL or newlines") + value = value.strip() + if not value: + raise SecretValidationError(f"field {key!r} must be a non-empty string") + cleaned[key] = value total += len(key.encode()) + len(value.encode()) if total > MAX_TOTAL_BYTES: raise SecretValidationError(f"fields exceed {MAX_TOTAL_BYTES} bytes in total") - return fields + return cleaned # -------------------------------------------------------------------------- @@ -215,7 +224,7 @@ async def find(self, scope: str, owner: str, name: str, configuration_id: str) - async def put(self, *, scope, owner, name, configuration_id, pinned_app_id, pinned_app_version, fields, actor) -> dict[str, Any]: validate_name(name) - validate_fields(fields) + fields = validate_fields(fields) existing = await self.find(scope, owner, name, configuration_id) now = datetime.now(tz=timezone.utc).isoformat() row = { diff --git a/svo-adapter-service/tests/test_secrets_store.py b/svo-adapter-service/tests/test_secrets_store.py index 29618ef8..9ae698be 100644 --- a/svo-adapter-service/tests/test_secrets_store.py +++ b/svo-adapter-service/tests/test_secrets_store.py @@ -124,13 +124,21 @@ def test_bad_secret_names_are_rejected(name): @pytest.mark.parametrize("fields", [ - {}, {"Bad": "x"}, {"a" * 33: "x"}, {"a": ""}, {"a": "x\ny"}, {"a": "x\x00y"}, + {}, {"Bad": "x"}, {"a" * 33: "x"}, {"a": ""}, {"a": " "}, {"a": "x\ny"}, {"a": "x\x00y"}, {f"f{i}": "v" for i in range(17)}, {"a": "x" * 4097}]) def test_bad_field_sets_are_rejected(fields): with pytest.raises(secrets_store.SecretValidationError): secrets_store.validate_fields(fields) +def test_values_are_stored_without_spaces_at_either_end(): + # A pasted " sk-abc " reaches the model server as the key it is, not with the spaces. + assert secrets_store.validate_fields({"api_key": " sk-abc\t", "url": "https://x "}) == { + "api_key": "sk-abc", "url": "https://x"} + # Spaces inside a value are kept. + assert secrets_store.validate_fields({"note": " a b "}) == {"note": "a b"} + + def test_rotation_reencrypts_under_the_new_key_and_the_old_key_can_go(monkeypatch): old = Fernet.generate_key().decode() new = Fernet.generate_key().decode() diff --git a/ui-react/src/lib/user-secrets.ts b/ui-react/src/lib/user-secrets.ts index 56326d99..1d69b545 100644 --- a/ui-react/src/lib/user-secrets.ts +++ b/ui-react/src/lib/user-secrets.ts @@ -107,6 +107,22 @@ export async function deleteUserSecret(name: string): Promise { } /** The first rule a credential breaks, as a sentence, or null when it is fine. */ +/** + * What may be wrong with a typed value, shown under its box, or null. Spaces at + * either end are removed when the value is saved; quote marks are kept (a value + * may hold them), but usually come from copying a key out of a config file. + */ +export function credentialValueWarning(value: string): string | null { + if (value === '') return null; + if (value !== value.trim()) { + return 'This value starts or ends with a space. Spaces at either end are removed when it is saved.'; + } + if (/^["'`]|["'`]$/.test(value)) { + return 'This value starts or ends with a quote mark. Remove it unless the quote is part of the value.'; + } + return null; +} + export function validateUserSecret( name: string, fields: Array<{ name: string; value: string }>, @@ -123,7 +139,7 @@ export function validateUserSecret( } if (seen.has(f.name)) return 'Each field name can be used only once.'; seen.add(f.name); - if (f.value === '') return `Enter a value for "${f.name}".`; + if (f.value.trim() === '') return `Enter a value for "${f.name}".`; } const bytes = fields.reduce( (n, f) => diff --git a/ui-react/src/pages/account/CredentialsPage.tsx b/ui-react/src/pages/account/CredentialsPage.tsx index e1fcaea4..cf08bfd2 100644 --- a/ui-react/src/pages/account/CredentialsPage.tsx +++ b/ui-react/src/pages/account/CredentialsPage.tsx @@ -3,8 +3,11 @@ * * A value is typed into a password field, sent once and never shown again, so * replacing a credential means entering every field again. Values live only in - * this form's state and are dropped as soon as the save succeeds. + * this form's state and are dropped as soon as the save succeeds. "Show" reveals + * only what is typed in the form, so the person can check it before saving; a + * stored value is never read back. */ +import { Eye, EyeOff } from 'lucide-react'; import { useCallback, useEffect, useState } from 'react'; import { ConfirmDialog } from '@/components/common/ConfirmDialog'; @@ -12,6 +15,7 @@ import { Button } from '@/components/ui/button'; import { Input } from '@/components/ui/input'; import { Label } from '@/components/ui/label'; import { + credentialValueWarning, deleteUserSecret, listUserSecrets, MODEL_SERVER_PRESET, @@ -53,6 +57,8 @@ export function CredentialsPage() { const [notice, setNotice] = useState(null); const [saving, setSaving] = useState(false); const [toDelete, setToDelete] = useState(null); + // Which typed values are shown in clear, by field key. Reset with the form. + const [shown, setShown] = useState>({}); const reload = useCallback(async () => { try { @@ -69,6 +75,7 @@ export function CredentialsPage() { const open = (next: FormState) => { setForm(next); + setShown({}); setFormError(null); setNotice(null); }; @@ -85,6 +92,7 @@ export function CredentialsPage() { const close = () => { setForm(null); + setShown({}); setFormError(null); }; @@ -104,11 +112,14 @@ export function CredentialsPage() { setFormError(null); try { const fields: Record = {}; - for (const f of form.fields) fields[f.name] = f.value; + // Spaces at either end are never part of a key or an address; sent, they make + // a server reject a key that looks right. + for (const f of form.fields) fields[f.name] = f.value.trim(); await saveUserSecret(form.name, fields); const verb = form.mode === 'replace' ? 'replaced' : 'saved'; // Drop every typed value from state before anything else happens. setForm(null); + setShown({}); setNotice(`Credential "${form.name}" ${verb}.`); await reload(); } catch (error) { @@ -237,13 +248,34 @@ export function CredentialsPage() {
- patchField(f.key, { value: e.target.value })} - /> +
+ patchField(f.key, { value: e.target.value })} + /> + +
+ {credentialValueWarning(f.value) && ( +

+ {credentialValueWarning(f.value)} +

+ )}
{form.mode === 'add' && form.fields.length > 1 && (