Skip to content
Closed
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
17 changes: 13 additions & 4 deletions svo-adapter-service/app/secrets.py
Original file line number Diff line number Diff line change
Expand Up @@ -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


# --------------------------------------------------------------------------
Expand Down Expand Up @@ -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 = {
Expand Down
10 changes: 9 additions & 1 deletion svo-adapter-service/tests/test_secrets_store.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down
18 changes: 17 additions & 1 deletion ui-react/src/lib/user-secrets.ts
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,22 @@ export async function deleteUserSecret(name: string): Promise<void> {
}

/** 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 }>,
Expand All @@ -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) =>
Expand Down
50 changes: 41 additions & 9 deletions ui-react/src/pages/account/CredentialsPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,19 @@
*
* 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';
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,
Expand Down Expand Up @@ -53,6 +57,8 @@ export function CredentialsPage() {
const [notice, setNotice] = useState<string | null>(null);
const [saving, setSaving] = useState(false);
const [toDelete, setToDelete] = useState<string | null>(null);
// Which typed values are shown in clear, by field key. Reset with the form.
const [shown, setShown] = useState<Record<number, boolean>>({});

const reload = useCallback(async () => {
try {
Expand All @@ -69,6 +75,7 @@ export function CredentialsPage() {

const open = (next: FormState) => {
setForm(next);
setShown({});
setFormError(null);
setNotice(null);
};
Expand All @@ -85,6 +92,7 @@ export function CredentialsPage() {

const close = () => {
setForm(null);
setShown({});
setFormError(null);
};

Expand All @@ -104,11 +112,14 @@ export function CredentialsPage() {
setFormError(null);
try {
const fields: Record<string, string> = {};
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) {
Expand Down Expand Up @@ -237,13 +248,34 @@ export function CredentialsPage() {
</div>
<div className="flex-1 space-y-1">
<Label htmlFor={`field-value-${f.key}`}>Value {index + 1}</Label>
<Input
id={`field-value-${f.key}`}
type="password"
value={f.value}
autoComplete="off"
onChange={(e) => patchField(f.key, { value: e.target.value })}
/>
<div className="flex gap-1">
<Input
id={`field-value-${f.key}`}
type={shown[f.key] ? 'text' : 'password'}
value={f.value}
autoComplete="off"
spellCheck={false}
aria-describedby={
credentialValueWarning(f.value) ? `field-warning-${f.key}` : undefined
}
onChange={(e) => patchField(f.key, { value: e.target.value })}
/>
<Button
type="button"
variant="outline"
size="sm"
aria-label={`${shown[f.key] ? 'Hide' : 'Show'} value ${index + 1}`}
aria-pressed={Boolean(shown[f.key])}
onClick={() => setShown((s) => ({ ...s, [f.key]: !s[f.key] }))}
>
{shown[f.key] ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />}
</Button>
</div>
{credentialValueWarning(f.value) && (
<p id={`field-warning-${f.key}`} className="text-xs text-amber-700">
{credentialValueWarning(f.value)}
</p>
)}
</div>
{form.mode === 'add' && form.fields.length > 1 && (
<Button
Expand Down
30 changes: 30 additions & 0 deletions ui-react/src/pages/account/__tests__/CredentialsPage.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,36 @@ describe('CredentialsPage', () => {
expect(screen.getByRole('status')).toHaveTextContent(/saved/i);
});

it('shows a typed value on request, warns about spaces and quotes, and saves it trimmed', async () => {
const fetchMock = stubAdapter();
renderWithProviders(<CredentialsPage />);
fireEvent.click(await screen.findByRole('button', { name: /add a model server/i }));
const key = screen.getByLabelText('Value 1');
fireEvent.change(key, { target: { value: ' sk-abc ' } });
expect(screen.getByText(/starts or ends with a space/i)).toBeInTheDocument();

fireEvent.click(screen.getByRole('button', { name: 'Show value 1' }));
expect(key).toHaveAttribute('type', 'text');
expect(screen.getByRole('button', { name: 'Hide value 1' })).toHaveAttribute(
'aria-pressed',
'true',
);
fireEvent.click(screen.getByRole('button', { name: 'Hide value 1' }));
expect(key).toHaveAttribute('type', 'password');
// The other values stay hidden.
expect(screen.getByLabelText('Value 2')).toHaveAttribute('type', 'password');

fireEvent.change(screen.getByLabelText('Value 2'), { target: { value: '"https://chat"' } });
expect(screen.getByText(/starts or ends with a quote mark/i)).toBeInTheDocument();
fireEvent.change(screen.getByLabelText('Value 2'), { target: { value: 'https://chat' } });
fireEvent.change(screen.getByLabelText('Value 3'), { target: { value: 'https://embed' } });
fireEvent.click(screen.getByRole('button', { name: /^save$/i }));

await waitFor(() => expect(calls(fetchMock, 'PUT')).toHaveLength(1));
const [, init] = calls(fetchMock, 'PUT')[0] as unknown as [string, RequestInit];
expect(JSON.parse(String(init.body)).fields.api_key).toBe('sk-abc');
});

it('checks the rules before sending', async () => {
const fetchMock = stubAdapter();
renderWithProviders(<CredentialsPage />);
Expand Down
Loading