All checks were successful
ci/woodpecker/pr/ci Pipeline was successful
CI-red root cause (classification a: my round-4 change fails in the clean/cold CI env): get_gitea_token_for_login hard-required PyYAML (`import yaml`), which is absent on CI's node:24-alpine (python3 without py3-yaml). Round-4's --login override cases were the first to exercise that path, turning the mosaic package test (test:framework-shell -> test-pr-review-gitea-comment.sh) RED. Fix: add an indentation-aware line-parser fallback that resolves the SAME per-name token PyYAML would from tea's flat `logins:` list; PyYAML stays the fast path. This also repairs a latent production defect (--login overrides were silently unusable on any PyYAML-less host). Auditor blockers folded into the same round-5: 1. issue_url vs pull_request_url shape (correctness): Gitea populates WEB (html) URLs in issue_url/pull_request_url, not API paths, and a PR-conversation comment carries pull_request_url (issue_url empty). Verification now accepts either web shape scoped to the repo slug + number, so a durable write is never rejected for URL shape. Test stubs now emit the REAL Gitea web shapes. 2. Cross-host credential binding (security): get_gitea_token_for_login now takes the repo host and requires the matched login's configured URL host to equal it; an override login configured for a different host FAILS CLOSED instead of sending a cross-host credential. Regression tests added to both suites. 3. Non-exhaustive enumeration (false-fail): removed the redundant, non-exhaustive post-verification list enumeration (gitea_fetch_all + confirm_*_enumerable) from both wrappers; the exact-id GET is authoritative. Pagination cases dropped; a guard asserts no list enumeration is performed. 4. Trap clobbering / temp-file leak (security/hygiene): removing the nested enumeration eliminates the RETURN-trap nesting that clobbered caller cleanup; remaining RETURN traps are single/non-nested and clean up on all exit paths. Temp-file leak regression tests (success + failure paths) added to both suites. 5. README: corrected the exhaustive-pagination claim and documented host-bound --login selection. Preserves every round-2/3/4 fix (explicit --login fail-closed at all write sites, token->identity attribution seam). Gates: cold `pnpm turbo run test --filter=@mosaicstack/mosaic` green (14/14); full test-*.sh suite green with AND without PyYAML; bash -n, shellcheck -x -S warning, prettier --check README clean. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
742 lines
23 KiB
Bash
Executable File
742 lines
23 KiB
Bash
Executable File
#!/bin/bash
|
|
# detect-platform.sh - Detect git platform (Gitea or GitHub) for current repo
|
|
# Usage: source detect-platform.sh && detect_platform
|
|
# or: ./detect-platform.sh (prints platform name)
|
|
|
|
detect_platform() {
|
|
local remote_url
|
|
remote_url=$(git remote get-url origin 2>/dev/null)
|
|
|
|
if [[ -z "$remote_url" ]]; then
|
|
echo "error: not a git repository or no origin remote" >&2
|
|
return 1
|
|
fi
|
|
|
|
# Check for GitHub
|
|
if [[ "$remote_url" == *"github.com"* ]]; then
|
|
PLATFORM="github"
|
|
export PLATFORM
|
|
echo "github"
|
|
return 0
|
|
fi
|
|
|
|
# Check for common Gitea indicators
|
|
# Gitea URLs typically don't contain github.com, gitlab.com, bitbucket.org
|
|
if [[ "$remote_url" != *"gitlab.com"* ]] && \
|
|
[[ "$remote_url" != *"bitbucket.org"* ]]; then
|
|
# Assume Gitea for self-hosted repos
|
|
PLATFORM="gitea"
|
|
export PLATFORM
|
|
echo "gitea"
|
|
return 0
|
|
fi
|
|
|
|
PLATFORM="unknown"
|
|
export PLATFORM
|
|
echo "unknown"
|
|
return 1
|
|
}
|
|
|
|
get_repo_info() {
|
|
local remote_url
|
|
remote_url=$(git remote get-url origin 2>/dev/null)
|
|
|
|
if [[ -z "$remote_url" ]]; then
|
|
echo "error: not a git repository or no origin remote" >&2
|
|
return 1
|
|
fi
|
|
|
|
# Extract owner/repo from URL
|
|
# Handles: git@host:owner/repo.git, https://host/owner/repo.git, https://host/owner/repo
|
|
local repo_path
|
|
if [[ "$remote_url" == git@* ]]; then
|
|
repo_path="${remote_url#*:}"
|
|
else
|
|
repo_path="${remote_url#*://}"
|
|
repo_path="${repo_path#*/}"
|
|
fi
|
|
|
|
# Remove .git suffix if present
|
|
repo_path="${repo_path%.git}"
|
|
|
|
echo "$repo_path"
|
|
}
|
|
|
|
get_repo_owner() {
|
|
local repo_info
|
|
repo_info=$(get_repo_info)
|
|
echo "${repo_info%%/*}"
|
|
}
|
|
|
|
get_repo_name() {
|
|
local repo_info
|
|
repo_info=$(get_repo_info)
|
|
echo "${repo_info##*/}"
|
|
}
|
|
|
|
get_repo_slug() {
|
|
get_repo_info
|
|
}
|
|
|
|
gitea_url_matches_host() {
|
|
local url="${1:-}" host="${2:-}"
|
|
[[ -n "$url" && -n "$host" ]] || return 1
|
|
python3 - "$url" "$host" <<'PY'
|
|
import sys
|
|
from urllib.parse import urlparse
|
|
|
|
url, remote_host = sys.argv[1:]
|
|
configured = urlparse(url)
|
|
remote = urlparse(f"//{remote_host}")
|
|
if configured.scheme not in {"http", "https"} or configured.hostname != remote.hostname:
|
|
raise SystemExit(1)
|
|
|
|
# Normalize by scheme: an implicit (portless) HTTP(S) URL and its explicit
|
|
# default-port form (":80" for http, ":443" for https) name the same
|
|
# provider endpoint. Apply that equivalence symmetrically -- whichever side
|
|
# omits the port is treated as carrying the scheme's default port -- so
|
|
# "configured implicit vs. remote explicit" and "configured explicit vs.
|
|
# remote implicit" both match. (The remote side here is always an HTTP(S)
|
|
# authority; an SSH remote's transport port is stripped by get_remote_host
|
|
# before reaching this comparison, since it identifies an unrelated
|
|
# service on the same host, not the HTTP(S) provider port.)
|
|
default_port = 80 if configured.scheme == "http" else 443
|
|
normalized_configured = configured.port if configured.port is not None else default_port
|
|
normalized_remote = remote.port if remote.port is not None else default_port
|
|
if normalized_configured != normalized_remote:
|
|
raise SystemExit(1)
|
|
raise SystemExit(0)
|
|
PY
|
|
}
|
|
|
|
get_gitea_service_for_host() {
|
|
local host="$1"
|
|
local cred_file="${MOSAIC_CREDENTIALS_FILE:-}"
|
|
if [[ -z "$cred_file" ]]; then
|
|
# Same resolution chain as _lib/credentials.sh: profile HOME, then
|
|
# host-level /etc only if it exists; neither existing keeps the
|
|
# $HOME default (matches the lib's final := fallback).
|
|
cred_file="$HOME/.config/mosaic/credentials.json"
|
|
if [[ ! -f "$cred_file" && -f /etc/mosaic/credentials.json ]]; then
|
|
cred_file="/etc/mosaic/credentials.json"
|
|
fi
|
|
fi
|
|
|
|
case "$host" in
|
|
git.mosaicstack.dev)
|
|
echo "mosaicstack"
|
|
return 0
|
|
;;
|
|
git.uscllc.com)
|
|
echo "usc"
|
|
return 0
|
|
;;
|
|
esac
|
|
|
|
[[ -f "$cred_file" ]] || return 1
|
|
command -v jq >/dev/null 2>&1 || return 1
|
|
|
|
jq -r --arg host "$host" '
|
|
.gitea // {}
|
|
| to_entries[]
|
|
| select((.value.url // "" | sub("/+$"; "")) | test("https?://" + $host + "$"))
|
|
| .key
|
|
' "$cred_file" | head -n 1
|
|
}
|
|
|
|
find_tea_login_for_host() {
|
|
local host="$1"
|
|
local logins_json
|
|
|
|
command -v tea >/dev/null 2>&1 || return 1
|
|
logins_json=$(tea login list --output json 2>/dev/null) || return 1
|
|
TEA_LOGINS_JSON="$logins_json" python3 - "$host" <<'PY'
|
|
import json
|
|
import os
|
|
import sys
|
|
from urllib.parse import urlparse
|
|
|
|
host = sys.argv[1]
|
|
try:
|
|
logins = json.loads(os.environ.get("TEA_LOGINS_JSON", "[]"))
|
|
except Exception:
|
|
raise SystemExit(1)
|
|
|
|
for login in logins if isinstance(logins, list) else []:
|
|
url = str(login.get("url") or login.get("URL") or "")
|
|
name = str(login.get("name") or login.get("Name") or "")
|
|
parsed = urlparse(url)
|
|
if parsed.hostname == host and name:
|
|
print(name)
|
|
raise SystemExit(0)
|
|
|
|
raise SystemExit(1)
|
|
PY
|
|
}
|
|
|
|
tea_login_matches_host() {
|
|
local login_name="$1" host="$2"
|
|
local logins_json
|
|
|
|
command -v tea >/dev/null 2>&1 || return 1
|
|
logins_json=$(tea login list --output json 2>/dev/null) || return 1
|
|
TEA_LOGINS_JSON="$logins_json" python3 - "$login_name" "$host" <<'PY'
|
|
import json
|
|
import os
|
|
import sys
|
|
from urllib.parse import urlparse
|
|
|
|
login_name, host = sys.argv[1], sys.argv[2]
|
|
try:
|
|
logins = json.loads(os.environ.get("TEA_LOGINS_JSON", "[]"))
|
|
except Exception:
|
|
raise SystemExit(1)
|
|
|
|
for login in logins if isinstance(logins, list) else []:
|
|
url = str(login.get("url") or login.get("URL") or "")
|
|
name = str(login.get("name") or login.get("Name") or "")
|
|
parsed = urlparse(url)
|
|
if name == login_name and parsed.hostname == host:
|
|
raise SystemExit(0)
|
|
|
|
raise SystemExit(1)
|
|
PY
|
|
}
|
|
|
|
# Emit an actionable diagnostic to stderr when no tea login resolves for a host.
|
|
# Callers that have a working API fallback may ignore the non-zero return of
|
|
# get_gitea_login_for_host; this turns the previously SILENT failure into a loud,
|
|
# greppable hint (available logins + override + add-login instructions). Printed to
|
|
# stderr only, so it never contaminates stdout (the resolved login name) or log
|
|
# assertions that capture tea/curl invocations.
|
|
print_gitea_login_diagnostic() {
|
|
local host="${1:-<unknown>}"
|
|
local available
|
|
available=$(
|
|
command -v tea >/dev/null 2>&1 || { echo "(tea CLI not installed)"; exit 0; }
|
|
logins_json=$(tea login list --output json 2>/dev/null) || { echo "(could not query tea login list)"; exit 0; }
|
|
TEA_LOGINS_JSON="$logins_json" python3 - <<'PY'
|
|
import json, os
|
|
from urllib.parse import urlparse
|
|
try:
|
|
logins = json.loads(os.environ.get("TEA_LOGINS_JSON", "[]"))
|
|
except Exception:
|
|
logins = []
|
|
rows = []
|
|
for login in logins if isinstance(logins, list) else []:
|
|
name = str(login.get("name") or login.get("Name") or "")
|
|
url = str(login.get("url") or login.get("URL") or "")
|
|
host = urlparse(url).hostname or "?"
|
|
if name:
|
|
rows.append(f"{name} (host: {host})")
|
|
print("; ".join(rows) if rows else "(none configured)")
|
|
PY
|
|
)
|
|
{
|
|
echo "Error: no Gitea tea login matches host '$host'."
|
|
echo " Available tea logins: ${available}"
|
|
echo " Fix: set GITEA_LOGIN to a login whose URL host is '$host',"
|
|
echo " or add one: tea login add --name <name> --url https://$host --token <token>"
|
|
} >&2
|
|
}
|
|
|
|
get_gitea_login_for_host() {
|
|
local host="${1:-}"
|
|
local login
|
|
|
|
if [[ -z "$host" ]]; then
|
|
host=$(get_remote_host) || return 1
|
|
fi
|
|
|
|
if [[ -n "${GITEA_LOGIN:-}" ]]; then
|
|
if tea_login_matches_host "$GITEA_LOGIN" "$host"; then
|
|
echo "$GITEA_LOGIN"
|
|
return 0
|
|
fi
|
|
fi
|
|
|
|
login=$(find_tea_login_for_host "$host" || true)
|
|
if [[ -n "$login" ]]; then
|
|
echo "$login"
|
|
return 0
|
|
fi
|
|
|
|
print_gitea_login_diagnostic "$host"
|
|
return 1
|
|
}
|
|
|
|
# Validate the current authenticated Gitea user for a resolved Tea login.
|
|
# Tea stores a user name with each login which can become stale after user rename,
|
|
# token rotation, or server migration. Querying /user derives the identity from the
|
|
# active credential instead of trusting that saved name. Callers fall back to the
|
|
# host-scoped API path when this validation fails.
|
|
get_gitea_authenticated_user() {
|
|
local login_name="$1" response
|
|
|
|
command -v tea >/dev/null 2>&1 || return 1
|
|
response=$(tea api --login "$login_name" /user 2>/dev/null) || return 1
|
|
TEA_AUTHENTICATED_USER_JSON="$response" python3 - <<'PY'
|
|
import json
|
|
import os
|
|
|
|
try:
|
|
user = json.loads(os.environ["TEA_AUTHENTICATED_USER_JSON"])
|
|
except (KeyError, json.JSONDecodeError):
|
|
raise SystemExit(1)
|
|
|
|
login = user.get("login") if isinstance(user, dict) else None
|
|
if isinstance(login, str) and login:
|
|
print(login)
|
|
raise SystemExit(0)
|
|
raise SystemExit(1)
|
|
PY
|
|
}
|
|
|
|
get_default_tea_login() {
|
|
local logins_json
|
|
|
|
command -v tea >/dev/null 2>&1 || return 1
|
|
logins_json=$(tea login list --output json 2>/dev/null) || return 1
|
|
TEA_LOGINS_JSON="$logins_json" python3 - <<'PY'
|
|
import json
|
|
import os
|
|
|
|
try:
|
|
logins = json.loads(os.environ.get("TEA_LOGINS_JSON", "[]"))
|
|
except Exception:
|
|
raise SystemExit(1)
|
|
|
|
if not isinstance(logins, list) or not logins:
|
|
raise SystemExit(1)
|
|
|
|
for login in logins:
|
|
if not isinstance(login, dict):
|
|
continue
|
|
is_default = str(login.get("default") or login.get("Default") or "").lower()
|
|
name = str(login.get("name") or login.get("Name") or "")
|
|
if name and is_default == "true":
|
|
print(name)
|
|
raise SystemExit(0)
|
|
|
|
for login in logins:
|
|
if not isinstance(login, dict):
|
|
continue
|
|
name = str(login.get("name") or login.get("Name") or "")
|
|
if name:
|
|
print(name)
|
|
raise SystemExit(0)
|
|
|
|
raise SystemExit(1)
|
|
PY
|
|
}
|
|
|
|
get_gitea_login_for_repo_override() {
|
|
local login
|
|
|
|
if [[ -n "${GITEA_LOGIN:-}" ]]; then
|
|
echo "$GITEA_LOGIN"
|
|
return 0
|
|
fi
|
|
|
|
login=$(get_default_tea_login || true)
|
|
if [[ -n "$login" ]]; then
|
|
echo "$login"
|
|
return 0
|
|
fi
|
|
|
|
return 1
|
|
}
|
|
|
|
get_host_from_url() {
|
|
local url="${1:-}"
|
|
[[ -n "$url" ]] || return 1
|
|
|
|
python3 - "$url" <<'PY'
|
|
import sys
|
|
from urllib.parse import urlparse
|
|
|
|
parsed = urlparse(sys.argv[1])
|
|
if parsed.hostname:
|
|
print(parsed.hostname)
|
|
raise SystemExit(0)
|
|
raise SystemExit(1)
|
|
PY
|
|
}
|
|
|
|
get_gitea_api_host_for_repo_override() {
|
|
if [[ -n "${GITEA_HOST:-}" ]]; then
|
|
echo "$GITEA_HOST"
|
|
return 0
|
|
fi
|
|
|
|
get_host_from_url "${GITEA_URL:-}"
|
|
}
|
|
|
|
# Resolve owner/repo relative to a configured Gitea base URL. HTTP(S) clone
|
|
# URLs can include the deployment prefix (for example /gitea/owner/repo.git),
|
|
# but Gitea's /repos API expects only owner/repo. Root-mounted and SSH clone
|
|
# forms retain their existing owner/repo behavior.
|
|
get_gitea_repo_slug_for_url() {
|
|
local configured_url="$1" remote_url
|
|
remote_url=$(git remote get-url origin 2>/dev/null) || return 1
|
|
|
|
if [[ "$remote_url" =~ ^https?:// ]]; then
|
|
python3 - "$remote_url" "$configured_url" <<'PY'
|
|
import sys
|
|
from urllib.parse import urlparse
|
|
|
|
remote = urlparse(sys.argv[1])
|
|
base = urlparse(sys.argv[2])
|
|
remote_path = remote.path.strip("/")
|
|
if remote_path.endswith(".git"):
|
|
remote_path = remote_path[:-4]
|
|
base_path = base.path.strip("/")
|
|
remote_parts = [part for part in remote_path.split("/") if part]
|
|
base_parts = [part for part in base_path.split("/") if part]
|
|
|
|
if base_parts and remote_parts[:len(base_parts)] == base_parts:
|
|
repo_parts = remote_parts[len(base_parts):]
|
|
elif len(remote_parts) == 2:
|
|
# Preserve a root-shaped clone URL when provider API configuration carries
|
|
# a reverse-proxy prefix separately.
|
|
repo_parts = remote_parts
|
|
else:
|
|
raise SystemExit(1)
|
|
|
|
if len(repo_parts) != 2:
|
|
raise SystemExit(1)
|
|
print("/".join(repo_parts))
|
|
PY
|
|
return
|
|
fi
|
|
|
|
get_repo_slug
|
|
}
|
|
|
|
get_gitea_repo_args() {
|
|
local repo host login
|
|
repo=$(get_repo_slug) || return 1
|
|
host=$(get_remote_host) || return 1
|
|
login=$(get_gitea_login_for_host "$host") || return 1
|
|
printf -- '--repo %q --login %q' "$repo" "$login"
|
|
}
|
|
|
|
get_gitea_login() {
|
|
get_gitea_login_for_host "$(get_remote_host)"
|
|
}
|
|
|
|
get_remote_host() {
|
|
local remote_url
|
|
remote_url=$(git remote get-url origin 2>/dev/null || true)
|
|
if [[ -z "$remote_url" ]]; then
|
|
return 1
|
|
fi
|
|
if [[ "$remote_url" =~ ^https?://([^/]+)/ ]]; then
|
|
local host="${BASH_REMATCH[1]}"
|
|
echo "${host##*@}"
|
|
return 0
|
|
fi
|
|
if [[ "$remote_url" =~ ^ssh://([^/]+)/ ]]; then
|
|
local host="${BASH_REMATCH[1]}"
|
|
host="${host##*@}"
|
|
# Strip an SSH transport port (e.g. "git.example:2222"): it names the
|
|
# SSH daemon port, not the HTTP(S) provider API port, and must not
|
|
# feed gitea_url_matches_host's port comparison (#850).
|
|
echo "${host%%:*}"
|
|
return 0
|
|
fi
|
|
if [[ "$remote_url" =~ ^git@([^:]+): ]]; then
|
|
echo "${BASH_REMATCH[1]}"
|
|
return 0
|
|
fi
|
|
return 1
|
|
}
|
|
|
|
# Resolve the configured Gitea base URL for a host from the same credential
|
|
# source used by get_gitea_token. The scheme and any deployment path prefix are
|
|
# provider configuration and must not be reconstructed from the git remote.
|
|
get_gitea_url_for_host() {
|
|
local host="$1" script_dir cred_loader url
|
|
script_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
|
cred_loader="$script_dir/../_lib/credentials.sh"
|
|
|
|
if [[ -f "$cred_loader" ]]; then
|
|
url=$(
|
|
# shellcheck source=/dev/null
|
|
source "$cred_loader"
|
|
unset GITEA_TOKEN GITEA_URL
|
|
case "$host" in
|
|
git.mosaicstack.dev) load_credentials gitea-mosaicstack 2>/dev/null ;;
|
|
git.uscllc.com) load_credentials gitea-usc 2>/dev/null ;;
|
|
*)
|
|
for svc in gitea-mosaicstack gitea-usc; do
|
|
unset GITEA_TOKEN GITEA_URL
|
|
load_credentials "$svc" 2>/dev/null || continue
|
|
if gitea_url_matches_host "${GITEA_URL:-}" "$host"; then
|
|
break
|
|
fi
|
|
unset GITEA_TOKEN GITEA_URL
|
|
done
|
|
;;
|
|
esac
|
|
if gitea_url_matches_host "${GITEA_URL:-}" "$host"; then
|
|
printf '%s' "${GITEA_URL%/}"
|
|
fi
|
|
)
|
|
if [[ -n "$url" ]]; then
|
|
printf '%s\n' "$url"
|
|
return 0
|
|
fi
|
|
fi
|
|
|
|
if gitea_url_matches_host "${GITEA_URL:-}" "$host"; then
|
|
printf '%s\n' "${GITEA_URL%/}"
|
|
return 0
|
|
fi
|
|
|
|
return 1
|
|
}
|
|
|
|
# Resolve a Gitea API token for the given host.
|
|
# Priority: Mosaic credential loader → GITEA_TOKEN env → ~/.git-credentials
|
|
get_gitea_token() {
|
|
local host="$1"
|
|
local script_dir
|
|
script_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
|
local cred_loader="$script_dir/../_lib/credentials.sh"
|
|
|
|
# 1. Mosaic credential loader (host → service mapping, run in subshell to avoid polluting env)
|
|
if [[ -f "$cred_loader" ]]; then
|
|
local token
|
|
token=$(
|
|
# shellcheck source=/dev/null
|
|
source "$cred_loader"
|
|
# Host-specific wrapper resolution must not inherit caller/global GITEA_*.
|
|
# load_credentials intentionally preserves existing env vars for interactive use,
|
|
# but metadata/merge wrappers need credentials matching the remote host.
|
|
unset GITEA_TOKEN GITEA_URL
|
|
case "$host" in
|
|
git.mosaicstack.dev) load_credentials gitea-mosaicstack 2>/dev/null ;;
|
|
git.uscllc.com) load_credentials gitea-usc 2>/dev/null ;;
|
|
*)
|
|
local matched=false
|
|
for svc in gitea-mosaicstack gitea-usc; do
|
|
unset GITEA_TOKEN GITEA_URL
|
|
load_credentials "$svc" 2>/dev/null || continue
|
|
if gitea_url_matches_host "${GITEA_URL:-}" "$host"; then
|
|
matched=true
|
|
break
|
|
fi
|
|
done
|
|
if [[ "$matched" != true ]]; then
|
|
unset GITEA_TOKEN GITEA_URL
|
|
fi
|
|
;;
|
|
esac
|
|
echo "${GITEA_TOKEN:-}"
|
|
)
|
|
if [[ -n "$token" ]]; then
|
|
echo "$token"
|
|
return 0
|
|
fi
|
|
fi
|
|
|
|
# 2. GITEA_TOKEN env var (only when GITEA_URL, if present, matches the remote host)
|
|
if [[ -n "${GITEA_TOKEN:-}" ]]; then
|
|
if [[ -z "${GITEA_URL:-}" ]] || gitea_url_matches_host "$GITEA_URL" "$host"; then
|
|
echo "$GITEA_TOKEN"
|
|
return 0
|
|
fi
|
|
fi
|
|
|
|
# 3. ~/.git-credentials file
|
|
local creds="$HOME/.git-credentials"
|
|
if [[ -f "$creds" ]]; then
|
|
local token
|
|
token=$(grep -F "$host" "$creds" 2>/dev/null | sed -n 's#https\?://[^@]*:\([^@/]*\)@.*#\1#p' | head -n 1)
|
|
if [[ -n "$token" ]]; then
|
|
echo "$token"
|
|
return 0
|
|
fi
|
|
fi
|
|
|
|
return 1
|
|
}
|
|
|
|
# Resolve the API token for a SPECIFIC tea login name from tea's own config
|
|
# (the same store tea itself writes/reads for `--login <name>`). This is what
|
|
# lets a REST write be performed AS the selected --login identity: tea keys its
|
|
# per-login tokens by `name` in $XDG_CONFIG_HOME/tea/config.yml (default
|
|
# ~/.config/tea/config.yml), exactly as the `tea` CLI resolves them, so a
|
|
# --login override and its REST read-back bind to the SAME credential/identity.
|
|
#
|
|
# $2 (repo host) binds the selected credential to the TARGET host: a tea login
|
|
# also records the `url` it authenticates against, and the matched login's URL
|
|
# host MUST equal the repo host. This fails closed when an override login is
|
|
# configured for a DIFFERENT host than the repo remote, so a login name shared
|
|
# across hosts (or a mistargeted override) can never send one host's credential
|
|
# to another host (cross-host credential leak). When $2 is empty the host bind
|
|
# is skipped (host-agnostic lookup) — callers that write should always pass it.
|
|
#
|
|
# Prints the token on success; returns non-zero (no output) if the config, a
|
|
# matching login token, or the host bind cannot be satisfied. Callers must not
|
|
# log the result.
|
|
get_gitea_token_for_login() {
|
|
local login_name="$1" repo_host="${2:-}" config_file
|
|
[[ -n "$login_name" ]] || return 1
|
|
config_file="${XDG_CONFIG_HOME:-$HOME/.config}/tea/config.yml"
|
|
[[ -f "$config_file" ]] || return 1
|
|
|
|
LOGIN_NAME="$login_name" REPO_HOST="$repo_host" python3 - "$config_file" <<'PY'
|
|
import os
|
|
import re
|
|
import sys
|
|
from urllib.parse import urlparse
|
|
|
|
wanted = os.environ["LOGIN_NAME"]
|
|
repo_host = os.environ.get("REPO_HOST", "").strip().lower()
|
|
config_path = sys.argv[1]
|
|
|
|
|
|
def _strip_scalar(value):
|
|
value = value.strip()
|
|
if len(value) >= 2 and value[0] == value[-1] and value[0] in ("'", '"'):
|
|
value = value[1:-1]
|
|
return value
|
|
|
|
|
|
def _host_of(url):
|
|
if not isinstance(url, str) or not url:
|
|
return None
|
|
parsed = urlparse(url if "//" in url else f"//{url}")
|
|
host = parsed.hostname
|
|
return host.lower() if host else None
|
|
|
|
|
|
def _accept(token, url):
|
|
# Enforce the host bind before surfacing a token. When a repo host is given,
|
|
# the login's recorded URL host must match it exactly; a login with no
|
|
# usable URL (or a mismatched one) is rejected (fail closed) so a cross-host
|
|
# credential is never emitted.
|
|
if not isinstance(token, str) or not token:
|
|
return None
|
|
if repo_host:
|
|
if _host_of(url) != repo_host:
|
|
return None
|
|
return token
|
|
|
|
|
|
def _token_via_pyyaml():
|
|
# Preferred, fully general path when PyYAML is installed. Raises ImportError
|
|
# (caught by the caller) when the module is unavailable so the environment
|
|
# -robust fallback can take over instead of failing closed on every host
|
|
# that lacks PyYAML.
|
|
import yaml
|
|
|
|
with open(config_path, encoding="utf-8") as handle:
|
|
config = yaml.safe_load(handle)
|
|
logins = config.get("logins") if isinstance(config, dict) else None
|
|
if not isinstance(logins, list):
|
|
return None
|
|
for login in logins:
|
|
if isinstance(login, dict) and str(login.get("name") or "") == wanted:
|
|
return _accept(login.get("token"), login.get("url"))
|
|
return None
|
|
|
|
|
|
def _token_via_lines():
|
|
# Conservative fallback for hosts without PyYAML. tea writes config.yml in a
|
|
# fixed, flat shape (a `logins:` list of maps with scalar name/url/token
|
|
# fields), so a small indentation-aware scan resolves the SAME token PyYAML
|
|
# would. It only ever returns the `token` of the entry whose `name` EXACTLY
|
|
# equals the requested login AND whose url host matches the repo host, so it
|
|
# cannot misattribute to another identity or host; anything it cannot parse
|
|
# yields None (fail closed).
|
|
with open(config_path, encoding="utf-8") as handle:
|
|
lines = handle.read().splitlines()
|
|
|
|
logins_indent = None
|
|
start = len(lines)
|
|
for index, line in enumerate(lines):
|
|
match = re.match(r"^(\s*)logins\s*:\s*$", line)
|
|
if match:
|
|
logins_indent = len(match.group(1))
|
|
start = index + 1
|
|
break
|
|
if logins_indent is None:
|
|
return None
|
|
|
|
entries = []
|
|
current = None
|
|
for line in lines[start:]:
|
|
if not line.strip() or line.lstrip().startswith("#"):
|
|
continue
|
|
indent = len(line) - len(line.lstrip(" "))
|
|
if indent <= logins_indent:
|
|
break
|
|
item = re.match(r"^\s*-\s*(.*)$", line)
|
|
rest = item.group(1) if item else line
|
|
if item:
|
|
current = {}
|
|
entries.append(current)
|
|
pair = re.match(r"^([A-Za-z0-9_]+)\s*:\s*(.*)$", rest.strip())
|
|
if pair and current is not None:
|
|
current[pair.group(1)] = _strip_scalar(pair.group(2))
|
|
|
|
for entry in entries:
|
|
if str(entry.get("name") or "") == wanted:
|
|
return _accept(entry.get("token"), entry.get("url"))
|
|
return None
|
|
|
|
|
|
try:
|
|
try:
|
|
token = _token_via_pyyaml()
|
|
except ImportError:
|
|
token = _token_via_lines()
|
|
except Exception:
|
|
raise SystemExit(1)
|
|
|
|
if isinstance(token, str) and token:
|
|
print(token)
|
|
raise SystemExit(0)
|
|
raise SystemExit(1)
|
|
PY
|
|
}
|
|
|
|
# Resolve HTTPS basic auth credentials for a Gitea host from ~/.git-credentials.
|
|
# Prints "username:password" for direct curl -u consumption. Callers must not log it.
|
|
get_gitea_basic_auth() {
|
|
local host="$1"
|
|
local creds="$HOME/.git-credentials"
|
|
if [[ ! -f "$creds" ]]; then
|
|
return 1
|
|
fi
|
|
|
|
python3 - "$host" "$creds" <<'PY'
|
|
import sys
|
|
from pathlib import Path
|
|
from urllib.parse import unquote, urlparse
|
|
|
|
host = sys.argv[1]
|
|
creds = Path(sys.argv[2])
|
|
|
|
for line in creds.read_text(encoding="utf-8").splitlines():
|
|
parsed = urlparse(line.strip())
|
|
if parsed.hostname != host:
|
|
continue
|
|
username = unquote(parsed.username or "")
|
|
password = unquote(parsed.password or "")
|
|
if username and password:
|
|
print(f"{username}:{password}")
|
|
raise SystemExit(0)
|
|
|
|
raise SystemExit(1)
|
|
PY
|
|
}
|
|
|
|
# If script is run directly (not sourced), output the platform
|
|
if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then
|
|
detect_platform
|
|
fi
|