Let a Core keep a token for one owner's apps on a host

coreapp login <host>/<owner> saves a token used for that owner's
repositories and images before the host's token, so apps from different
accounts on one host can use different tokens. git sends it only under
https://<host>/<owner>/; docker gets it for that pull only. Errors name
the token that was tried.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-12-03 20:51:41 -07:00
co-authored by Claude Opus 5.5
parent c337ba2530
commit f0468c43f2
6 changed files with 114 additions and 48 deletions
+58 -30
View File
@@ -22,9 +22,12 @@ coreapps update [--addon-ok] <name> update an app installed from a
repository to its newest release
coreapps remove <name> uninstall an app installed by coreapps
coreapps list the apps installed by coreapps
coreapps login <host> <user> keep a token (read from stdin) for
coreapps login <host>[/<owner>] <user>
keep a token (read from stdin) for
installing private apps from host
coreapps logout <host> forget host's token
(with /<owner>: that owner's apps only,
used before the host's token)
coreapps logout <host>[/<owner>] forget that token
coreapps logins the hosts this Core has tokens for
coreapps mail <name> what the Core's mail server did with the
mail the app sent in the last day
@@ -136,10 +139,14 @@ GIT_ENV = {"PATH": "/usr/bin:/bin", "GIT_TERMINAL_PROMPT": "0",
"GIT_CONFIG_GLOBAL": "/dev/null", "HOME": "/nonexistent",
"LC_ALL": "C"}
GIT_TIMEOUT = 120
# Tokens for private repositories and registries, by host (root only)
# Tokens for private repositories and registries (root only), by host, or
# by host/owner for one account or organization's apps on a host where
# others need another token
CREDENTIALS = "/etc/coreapps/credentials"
HOST = r"[a-z0-9](?:[a-z0-9.-]{0,251}[a-z0-9])?(?::[0-9]{1,5})?"
LOGIN_USER = r"[A-Za-z0-9][A-Za-z0-9._-]{0,63}"
OWNER = r"[a-z0-9][a-z0-9._-]{0,63}"
LOGIN_KEY = HOST + r"(?:/" + OWNER + r")?"
TOKEN = r"[A-Za-z0-9._~+/=-]{8,512}"
@@ -358,16 +365,17 @@ def read_credentials():
return {}
except tomllib.TOMLDecodeError as e:
raise Refused(f"{CREDENTIALS} isn't valid: {e}")
return {host: c for host, c in data.items()
if isinstance(c, dict) and re.fullmatch(LOGIN_USER, str(c.get("user", "")))
return {key: c for key, c in data.items()
if re.fullmatch(LOGIN_KEY, key) and isinstance(c, dict)
and re.fullmatch(LOGIN_USER, str(c.get("user", "")))
and re.fullmatch(TOKEN, str(c.get("token", "")))}
def write_credentials(creds):
os.makedirs(os.path.dirname(CREDENTIALS), mode=0o700, exist_ok=True)
os.chmod(os.path.dirname(CREDENTIALS), 0o700)
text = ("# Tokens coreapps uses to install private apps, by host. Manage with\n"
"# coreapps login / logout.\n")
text = ("# Tokens coreapps uses to install private apps, by host or host/owner\n"
"# (used first for that owner's apps). Manage with coreapps login / logout.\n")
for host in sorted(creds):
text += f'\n["{host}"]\nuser = "{creds[host]["user"]}"\ntoken = "{creds[host]["token"]}"\n'
new = CREDENTIALS + ".new"
@@ -377,12 +385,24 @@ def write_credentials(creds):
os.rename(new, CREDENTIALS)
def basic_auth(host):
"""'user:token' in base64 for host, or None."""
c = read_credentials().get(host)
if not c:
return None
return base64.b64encode(f"{c['user']}:{c['token']}".encode()).decode()
def basic_auth(host, owner=""):
"""(the login's key, 'user:token' in base64) for owner's apps on host:
host/owner's token, else host's; or (None, None)."""
creds = read_credentials()
for key in ([f"{host}/{owner.lower()}"] if owner else []) + [host]:
c = creds.get(key)
if c:
return key, base64.b64encode(f"{c['user']}:{c['token']}".encode()).decode()
return None, None
def login_key(arg):
"""host or host/owner, checked and in lowercase."""
key = arg.lower().rstrip("/")
if not re.fullmatch(LOGIN_KEY, key):
raise Refused(f"'{arg}' isn't a host name (like gitea.example.com) or a host and "
"owner (gitea.example.com/my-team).")
return key
def url_host(url):
@@ -420,10 +440,9 @@ def check_token(host, user, token):
return False if status in (401, 403) else None
def login(host, user):
host = host.lower()
if not re.fullmatch(HOST, host):
raise Refused(f"'{host}' isn't a host name (like gitea.example.com).")
def login(arg, user):
key = login_key(arg)
host = key.split("/", 1)[0]
if not re.fullmatch(LOGIN_USER, user):
raise Refused(f"'{user}' isn't a user name.")
token = sys.stdin.readline().strip()
@@ -433,20 +452,22 @@ def login(host, user):
if ok is False:
raise Refused(f"{host} rejected the token for {user}. Nothing was saved.")
creds = read_credentials()
creds[host] = {"user": user, "token": token}
creds[key] = {"user": user, "token": token}
write_credentials(creds)
say(f"Saved a token for {user}@{host}"
+ (f", for {key.split('/', 1)[1]}'s apps there" if "/" in key else "")
+ (" (its registry accepts it)." if ok else " (couldn't check it with its registry)."))
return 0
def logout(host):
def logout(arg):
key = login_key(arg)
creds = read_credentials()
if creds.pop(host.lower(), None) is None:
say(f"No token for {host}.")
if creds.pop(key, None) is None:
say(f"No token for {key}.")
return 0
write_credentials(creds)
say(f"Forgot the token for {host}.")
say(f"Forgot the token for {key}.")
return 0
@@ -454,8 +475,9 @@ def list_logins():
creds = read_credentials()
if not creds:
say("No tokens: this Core installs public apps only.")
for host in sorted(creds):
say(f"{host} (user {creds[host]['user']})")
for key in sorted(creds):
say(f"{key} (user {creds[key]['user']}"
+ (f"; for {key.split('/', 1)[1]}'s apps)" if "/" in key else ")"))
return 0
@@ -519,10 +541,16 @@ def fetch_repo(arg, staging):
"https://host/owner/repo (no user or password in it).")
url = normalize_url(url)
host = url_host(url)
token = basic_auth(host)
auth = (f"https://{host}", token) if token else None
no_access = ("" if token else
f" If it's private, give this Core a token for {host}: coreapp login {host}.")
owner = url.split("://", 1)[1].split("/")[1]
key, token = basic_auth(host, owner)
# git sends it only under the login's address: the owner's (as the URL
# spells it; git compares paths exactly), or the host's
auth = ((f"https://{host}/{owner}" if "/" in key else f"https://{host}"), token) \
if token else None
no_access = (f" If it's private, give this Core a token for {host}: coreapp login {host} "
f"(or coreapp login {host}/{owner.lower()} for {owner}'s apps only)."
if not token else
f" (It used the token for {key}: check it can read this repository.)")
if tag and not re.fullmatch(TAG, tag):
raise Refused(f"'{tag}' isn't a release tag (v and a version, like v1.2.0).")
if not tag:
@@ -834,8 +862,8 @@ def ensure_image(m, pull=False):
raise Refused(f"The image {ref} isn't on this Core, and localhost/ images "
"can't be pulled. coreapp deploy copies it here.")
say(f"Pulling {ref}...")
registry = m["image"].split("/", 1)[0]
token = basic_auth(registry)
registry, owner = m["image"].split("/")[:2]
_, token = basic_auth(registry, owner)
# The token goes in a docker config just for this pull, so the Core
# keeps no docker login
with tempfile.TemporaryDirectory(prefix="coreapps-docker-") as config: