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
+58 -11
View File
@@ -17,7 +17,7 @@ import httpx
from docker_client import DockerError, get_client, safe_call
from models.setting import EVENT_UPDATE_AVAILABLE
from services import notify_service, settings_service
from services import notify_service, registry_service, settings_service
logger = logging.getLogger("stackpilot.update")
@@ -145,7 +145,16 @@ def _local_digest(image: str) -> Optional[str]:
# --------------------------------------------------------------------------- #
async def _get_token(client: httpx.AsyncClient, www_auth: str) -> Optional[str]:
async def _get_token(
client: httpx.AsyncClient,
www_auth: str,
auth: Optional[tuple[str, str]] = None,
) -> Optional[str]:
"""Follow a Bearer challenge, with credentials when we have them.
A public image gets an anonymous token; a private one only gets a token at
all if the request to the token realm is authenticated.
"""
# Parse: Bearer realm="...",service="...",scope="..."
params = {}
if not www_auth.lower().startswith("bearer"):
@@ -158,7 +167,7 @@ async def _get_token(client: httpx.AsyncClient, www_auth: str) -> Optional[str]:
if not realm:
return None
try:
resp = await client.get(realm, params=params, timeout=10)
resp = await client.get(realm, params=params, auth=auth, timeout=10)
resp.raise_for_status()
data = resp.json()
return data.get("token") or data.get("access_token")
@@ -166,25 +175,54 @@ async def _get_token(client: httpx.AsyncClient, www_auth: str) -> Optional[str]:
return None
class AuthRequired(Exception):
"""The registry wants credentials we do not have (or rejected ours).
Distinct from "could not reach the registry" on purpose: a private image
with no configured credentials used to be indistinguishable from a network
blip, so the UI said nothing and the stack looked up to date forever.
"""
async def remote_digest(image: str) -> Optional[str]:
"""The digest the registry currently serves for this tag.
Raises :class:`AuthRequired` when the registry refuses us; returns None when
it could not be reached or answered without a digest.
"""
registry, repo, tag = parse_ref(image)
if tag.startswith("sha256:"):
return tag
scheme = "https"
url = f"{scheme}://{registry}/v2/{repo}/manifests/{tag}"
headers = {"Accept": _MANIFEST_ACCEPT}
auth = registry_service.credentials_for(registry)
async with httpx.AsyncClient(follow_redirects=True) as client:
try:
resp = await client.head(url, headers=headers, timeout=10)
if resp.status_code == 401:
token = await _get_token(client, resp.headers.get("WWW-Authenticate", ""))
if not token:
return None
headers["Authorization"] = f"Bearer {token}"
resp = await client.head(url, headers=headers, timeout=10)
challenge = resp.headers.get("WWW-Authenticate", "")
if challenge.lower().startswith("basic"):
# A plain htpasswd-protected registry: no token dance.
if not auth:
raise AuthRequired(registry)
resp = await client.head(url, headers=headers, auth=auth, timeout=10)
else:
token = await _get_token(client, challenge, auth)
if not token:
raise AuthRequired(registry)
headers["Authorization"] = f"Bearer {token}"
resp = await client.head(url, headers=headers, timeout=10)
if resp.status_code in (401, 403):
raise AuthRequired(registry)
if resp.status_code == 405 or "Docker-Content-Digest" not in resp.headers:
# Some registries don't support HEAD; fall back to GET.
resp = await client.get(url, headers=headers, timeout=10)
resp = await client.get(
url, headers=headers, auth=auth if "Authorization" not in headers else None,
timeout=10,
)
if resp.status_code in (401, 403):
raise AuthRequired(registry)
digest = resp.headers.get("Docker-Content-Digest")
return digest
except httpx.HTTPError as exc:
@@ -199,9 +237,18 @@ async def remote_digest(image: str) -> Optional[str]:
async def check_image(image: str) -> UpdateStatus:
local = _local_digest(image)
remote = await remote_digest(image)
error = None
if remote is None:
try:
remote = await remote_digest(image)
except AuthRequired as exc:
# Say which registry, because the fix is to add credentials for it.
remote = None
error = (
f"{exc} needs credentials"
if not registry_service.credentials_for(str(exc))
else f"{exc} rejected the stored credentials"
)
if remote is None and error is None:
error = "could not reach registry"
update_available = bool(local and remote and local != remote)
status = UpdateStatus(