Add private registry credentials, and stop update checks lying (0.56.0)
CI / check (push) Successful in 12m33s
CI / build-and-push (push) Successful in 2m1s

This was on the gap list as a missing feature, but it was a bug first. The
update checker asks the registry for a tag's digest over HTTP itself, and could
only do it anonymously. A private repository answers 401, remote_digest returned
None, and None already meant "could not reach registry" — so a private image was
indistinguishable from a network blip. The Images page showed nothing and a
stack pinned to a six-month-old image looked up to date indefinitely.

So AuthRequired is now its own exception, separate from unreachable, and the
error names the registry and which of the two problems it is: "ghcr.io needs
credentials" when there are none, "ghcr.io rejected the stored credentials" when
there are and they are wrong. Those are different fixes, and the message should
say which one you need. The plain unreachable message survives unchanged, with a
test pinning it, because not every failure is an auth failure.

Two consumers need the credentials and they need them in completely different
shapes, which is why this is its own service rather than a field on something
else. StackPilot's own checker wants (user, password) inside async code that has
no database session, so the rows are mirrored into an in-memory cache that
reload() refills on startup and after every write. The Docker CLI wants a
config.json, so reload() writes one into ${DATA_DIR}/docker and compose runs with
DOCKER_CONFIG pointed at it. Generating it from the database every time is what
makes deletion real: removing a registry in the UI revokes the CLI's login
instead of leaving a stale one in ~/.docker.

Host normalization is the join that makes any of it work, and it is easy to
underestimate. parse_ref only ever produces registry-1.docker.io, nobody types
that, and the CLI wants the whole thing under https://index.docker.io/v1/ — three
spellings of one registry across three layers. canonical_host settles on what
parse_ref produces, the config writer translates on the way out, and a bare
nginx:alpine finds credentials entered as "docker.io". Verified end to end:
typed as the v1 URL, stored as registry-1.docker.io, written as the v1 URL.

The password is encrypted at rest with the same key as backup destinations and
never leaves the server, not even masked — the API returns has_password, which
is all the form needs to offer "leave blank to keep". A row that cannot be
decrypted after a SECRET_KEY change is skipped with a warning rather than taking
every other registry down with it. Everything here is admin-only including the
reads, because even masked the rows say which registries this install talks to
and under what account.

The Test button asks the registry rather than validating a string, following the
Bearer challenge with credentials attached the way a real client does. Only an
outright 401 counts as wrong credentials; anything else means reachable and
talking, which is as much as a credentials check can honestly claim. Checked
against the live Docker Hub token endpoint with deliberately wrong credentials.

33 tests: the normalization table, the cache, the generated config.json down to
its 0600 mode and the Docker Hub key, encryption at rest, that no password field
appears in any response, and the 401-is-reported behaviour that started this.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
menzelj
2026-09-18 00:42:27 +02:00
co-authored by Claude Opus 5
parent a2adb59526
commit 95e03f031f
13 changed files with 1277 additions and 14 deletions
+1 -1
View File
@@ -1,7 +1,7 @@
{
"name": "stackpilot-frontend",
"private": true,
"version": "0.55.0",
"version": "0.56.0",
"type": "module",
"scripts": {
"dev": "vite",
+36
View File
@@ -0,0 +1,36 @@
import api from "./client";
const base = "/api/registries";
export interface RegistryCredentials {
id: number;
name: string;
/** Canonical host, as the server normalized it (e.g. registry-1.docker.io). */
host: string;
username: string;
/** The password itself is never sent to the browser — only whether one is set. */
has_password: boolean;
created_at: string;
updated_at: string;
}
export interface RegistryInput {
name?: string;
host?: string;
username?: string;
/** Omit when editing to keep the stored password. */
password?: string;
}
export const registriesApi = {
list: () => api.get<RegistryCredentials[]>(base).then((r) => r.data),
create: (body: RegistryInput) =>
api.post<RegistryCredentials>(base, body).then((r) => r.data),
update: (id: number, body: RegistryInput) =>
api.put<RegistryCredentials>(`${base}/${id}`, body).then((r) => r.data),
remove: (id: number) => api.delete(`${base}/${id}`).then((r) => r.data),
/** Try credentials against the registry. Without a password, the stored one
* is used — which is how a saved row can be re-tested. */
test: (body: { host: string; username: string; password?: string }) =>
api.post<{ ok: boolean; host: string }>(`${base}/test`, body).then((r) => r.data),
};
+244
View File
@@ -13,6 +13,7 @@ import {
HardDrive,
CalendarClock,
Play,
KeyRound,
} from "lucide-react";
import { toast } from "sonner";
import { Badge, Button, Card, Input, Spinner } from "@/components/ui";
@@ -23,6 +24,11 @@ import {
type WebhookInput,
} from "@/api/settings";
import { destinationsApi, type BackupDestination } from "@/api/backups";
import {
registriesApi,
type RegistryCredentials,
type RegistryInput,
} from "@/api/registries";
import { schedulesApi, type BackupSchedule } from "@/api/schedules";
import { stacksApi } from "@/api/stacks";
import { apiErrorMessage } from "@/api/client";
@@ -48,6 +54,7 @@ export function Settings() {
return (
<div className="mx-auto max-w-3xl space-y-6">
<GeneralSection />
<RegistriesSection />
<DestinationsSection />
<SchedulesSection />
<NotificationsSection />
@@ -318,6 +325,243 @@ const FIELDS: Record<string, { key: string; label: string; secret?: boolean; are
],
};
/* -------------------------------------------------------------------------- */
/* Private registries */
/* -------------------------------------------------------------------------- */
function RegistriesSection() {
const qc = useQueryClient();
const { data, isLoading } = useQuery({
queryKey: ["registries"],
queryFn: registriesApi.list,
});
const [adding, setAdding] = useState(false);
const invalidate = () => {
qc.invalidateQueries({ queryKey: ["registries"] });
// Update availability is computed from these, so a new login can change
// what the Images page has to say.
qc.invalidateQueries({ queryKey: ["images"] });
qc.invalidateQueries({ queryKey: ["stack-updates"] });
};
return (
<section>
<SectionTitle icon={<KeyRound className="h-4 w-4" />}>Private registries</SectionTitle>
<div className="space-y-3">
{isLoading ? (
<Spinner />
) : (
data?.map((r) => <RegistryRow key={r.id} registry={r} onChange={invalidate} />)
)}
{data?.length === 0 && !adding && (
<Card>
<p className="text-sm text-slate-500">
No registry logins. Add one for Docker Hub, ghcr.io or your own
registry so StackPilot can pull private images and so update
checks stop reporting needs credentials for them.
</p>
</Card>
)}
{adding ? (
<RegistryForm
onDone={() => {
setAdding(false);
invalidate();
}}
onCancel={() => setAdding(false)}
/>
) : (
<Button variant="outline" onClick={() => setAdding(true)}>
<Plus className="h-4 w-4" /> Add registry
</Button>
)}
</div>
</section>
);
}
function RegistryRow({
registry,
onChange,
}: {
registry: RegistryCredentials;
onChange: () => void;
}) {
const [editing, setEditing] = useState(false);
const test = useMutation({
// No password: the server falls back to the stored one, which the browser
// has never seen.
mutationFn: () => registriesApi.test({ host: registry.host, username: registry.username }),
onSuccess: () => toast.success(`${registry.host} accepted the credentials`),
onError: (e) => toast.error(apiErrorMessage(e)),
});
const remove = useMutation({
mutationFn: () => registriesApi.remove(registry.id),
onSuccess: () => {
toast.success("Registry removed");
onChange();
},
onError: (e) => toast.error(apiErrorMessage(e)),
});
if (editing) {
return (
<RegistryForm
registry={registry}
onDone={() => {
setEditing(false);
onChange();
}}
onCancel={() => setEditing(false)}
/>
);
}
return (
<Card className="flex flex-wrap items-center justify-between gap-2">
<div className="min-w-0">
<div className="flex items-center gap-2">
<span className="font-medium">{registry.name}</span>
<Badge>{registry.host}</Badge>
</div>
<p className="break-all font-mono text-xs text-slate-500">
{registry.username} · password stored
</p>
</div>
<div className="flex gap-2">
<Button variant="ghost" onClick={() => test.mutate()} loading={test.isPending}>
<RefreshCw className="h-4 w-4" /> Test
</Button>
<Button variant="ghost" onClick={() => setEditing(true)}>
Edit
</Button>
<Button variant="ghost" onClick={() => remove.mutate()} loading={remove.isPending}>
<Trash2 className="h-4 w-4 text-red-500" />
</Button>
</div>
</Card>
);
}
function RegistryForm({
registry,
onDone,
onCancel,
}: {
registry?: RegistryCredentials;
onDone: () => void;
onCancel: () => void;
}) {
const editing = Boolean(registry);
const [name, setName] = useState(registry?.name ?? "");
const [host, setHost] = useState(registry?.host ?? "");
const [username, setUsername] = useState(registry?.username ?? "");
const [password, setPassword] = useState("");
const [testing, setTesting] = useState(false);
const body = (): RegistryInput => ({
name: name.trim() || undefined,
host: host.trim(),
username: username.trim(),
// Editing with the field left blank keeps whatever is stored.
password: password || undefined,
});
const save = useMutation({
mutationFn: () =>
registry ? registriesApi.update(registry.id, body()) : registriesApi.create(body()),
onSuccess: () => {
toast.success(editing ? "Registry updated" : "Registry added");
onDone();
},
onError: (e) => toast.error(apiErrorMessage(e)),
});
const test = async () => {
setTesting(true);
try {
await registriesApi.test({
host: host.trim(),
username: username.trim(),
password: password || undefined,
});
toast.success("The registry accepted these credentials");
} catch (e) {
toast.error(apiErrorMessage(e));
} finally {
setTesting(false);
}
};
const ready = host.trim() && username.trim() && (editing || password);
return (
<Card className="space-y-3">
<div className="grid gap-3 sm:grid-cols-2">
<label className="space-y-1">
<span className="sp-label">Registry</span>
<Input
placeholder="ghcr.io"
value={host}
onChange={(e) => setHost(e.target.value)}
/>
<span className="block text-[11px] text-slate-400">
Host only. Use <code>docker.io</code> for Docker Hub.
</span>
</label>
<label className="space-y-1">
<span className="sp-label">Label (optional)</span>
<Input
placeholder="Defaults to the host"
value={name}
onChange={(e) => setName(e.target.value)}
/>
</label>
<label className="space-y-1">
<span className="sp-label">Username</span>
<Input value={username} onChange={(e) => setUsername(e.target.value)} />
</label>
<label className="space-y-1">
<span className="sp-label">
{editing ? "New password / token" : "Password or access token"}
</span>
<Input
type="password"
autoComplete="new-password"
placeholder={editing ? "Leave blank to keep the stored one" : ""}
value={password}
onChange={(e) => setPassword(e.target.value)}
/>
<span className="block text-[11px] text-slate-400">
A token with read access is enough, and safer than your account
password.
</span>
</label>
</div>
<div className="flex flex-wrap justify-end gap-2">
<Button variant="ghost" onClick={onCancel}>
Cancel
</Button>
<Button
variant="outline"
onClick={test}
loading={testing}
disabled={!host.trim() || !username.trim()}
>
<RefreshCw className="h-4 w-4" /> Test
</Button>
<Button onClick={() => save.mutate()} loading={save.isPending} disabled={!ready}>
{editing ? "Save" : "Add registry"}
</Button>
</div>
</Card>
);
}
/* -------------------------------------------------------------------------- */
/* Backup destinations */
/* -------------------------------------------------------------------------- */
function DestinationsSection() {
const qc = useQueryClient();
const { data, isLoading } = useQuery({ queryKey: ["destinations"], queryFn: destinationsApi.list });