#!/bin/bash # issue-comment.sh - Add a comment to an issue on GitHub or Gitea # Usage: issue-comment.sh -i -c [--login ] # # tea v0.11.1 defines no `comment` subcommand under `tea issue` (or `tea pr`); # the non-existent `tea issue comment ...` form does not error — tea silently # no-ops and still exits 0, so a caller trusting the exit code believes a # comment was posted when it was not (#865). tea 0.11.1 also cannot reliably # emit the id of a record it created, so an exit code is the ONLY signal it # offers — and that signal is untrustworthy. This script therefore does not # write via tea at all: it POSTs the comment through the Gitea REST API (which # returns the created comment object, including its id), then GETs that exact # id back and fails closed unless it matches. Keying verification to the # provider-returned created id means a concurrent comment cannot masquerade as # this write and a no-op create simply yields no id to verify. # # --login override: the default login is resolved from the local `tea` login # list for this repo's host (get_gitea_login). Pass --login to override # it for this invocation only. The REST write, the /user identity read, and the # read-back are ALL performed with the token of the EFFECTIVE login (the # override when given), so the write and its verification bind to the same # identity — a --login override is never written under one credential and # verified under a different default one. set -e SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" source "$SCRIPT_DIR/detect-platform.sh" # Parse arguments ISSUE_NUMBER="" COMMENT="" LOGIN_OVERRIDE="" while [[ $# -gt 0 ]]; do case $1 in -i|--issue) ISSUE_NUMBER="$2" shift 2 ;; -c|--comment) COMMENT="$2" shift 2 ;; -l|--login) LOGIN_OVERRIDE="$2" shift 2 ;; -h|--help) echo "Usage: issue-comment.sh -i -c [--login ]" echo "" echo "Options:" echo " -i, --issue Issue number (required)" echo " -c, --comment Comment text (required)" echo " -l, --login Override the detected Gitea tea login for this call" echo " -h, --help Show this help" exit 0 ;; *) echo "Unknown option: $1" exit 1 ;; esac done if [[ -z "$ISSUE_NUMBER" ]]; then echo "Error: Issue number is required (-i)" exit 1 fi if [[ -z "$COMMENT" ]]; then echo "Error: Comment is required (-c)" exit 1 fi detect_platform >/dev/null # Resolve and cache the Gitea REST endpoint + token for the current remote, # bound to a SPECIFIC login identity ($1). Populates GITEA_API_ROOT (…/api/v1), # GITEA_API_BASE (…/api/v1/repos/), and GITEA_API_TOKEN. # # The token is resolved for the EFFECTIVE login (the --login override when # given, otherwise the detected default) so that the single credential used for # the write ALSO drives the /user identity read and the read-back — write token # and read-back token are the same identity by construction (this is the # credential-ordering fix: a --login override is no longer written under one # credential and verified under a different default one). Falls back to the # host-scoped credential ONLY when NO --login override was supplied (the # best-effort default path). When $2 is "explicit" the login came from a # caller-supplied --login: that exact login's token MUST resolve, and we FAIL # CLOSED rather than silently downgrading the write to the host default # identity — otherwise a caller relying on a dedicated per-role credential would # be told the write succeeded as requested while it was attributed to the shared # default. Returns non-zero (clear stderr) on any resolution failure. gitea_resolve_api_for_login() { local effective_login="$1" override_explicit="${2:-}" host configured_url repo host=$(get_remote_host) if [[ -n "$override_explicit" ]]; then GITEA_API_TOKEN=$(get_gitea_token_for_login "$effective_login" "$host") || { echo "Error: could not resolve a host-matched Gitea token for --login '$effective_login' on host '$host'; refusing to fall back to the host default identity or a cross-host credential (comment write/read-back)" >&2 return 1 } else GITEA_API_TOKEN=$(get_gitea_token_for_login "$effective_login" "$host") \ || GITEA_API_TOKEN=$(get_gitea_token "$host") || { echo "Error: Gitea token not found for login '$effective_login' (comment write/read-back)" >&2 return 1 } fi configured_url=$(get_gitea_url_for_host "$host") || { echo "Error: Configured Gitea URL not found for comment read-back verification" >&2 return 1 } repo=$(get_gitea_repo_slug_for_url "$configured_url") || { echo "Error: Could not resolve Gitea owner/repository relative to configured URL" >&2 return 1 } GITEA_API_ROOT="${configured_url%/}/api/v1" GITEA_API_BASE="$GITEA_API_ROOT/repos/$repo" return 0 } # Resolve the login of the identity the API token authenticates as (GET # /user). Used to attribute a read-back record to THIS invocation's writer so # a concurrent write from a DIFFERENT identity cannot satisfy verification. # Prints the login on success. gitea_authenticated_login() { local response_file status response_file=$(mktemp "${TMPDIR:-/tmp}/mosaic-issue-comment-whoami.XXXXXX") trap 'rm -f "$response_file"' RETURN if ! status=$(curl -sS -o "$response_file" -w '%{http_code}' \ -H "Authorization: token $GITEA_API_TOKEN" \ "$GITEA_API_ROOT/user"); then echo "Error: Gitea authenticated-identity read transport failed" >&2 return 1 fi if [[ "$status" != "200" ]]; then echo "Error: Gitea authenticated-identity read failed with HTTP $status" >&2 return 1 fi python3 - "$response_file" <<'PY' import json import sys try: with open(sys.argv[1], encoding="utf-8") as response: user = json.load(response) login = user.get("login") if isinstance(user, dict) else None if not isinstance(login, str) or not login: raise ValueError("missing authenticated login") except (OSError, json.JSONDecodeError, TypeError, ValueError) as error: print(f"Error: could not resolve authenticated Gitea identity: {error}", file=sys.stderr) raise SystemExit(1) print(login) PY } # Post a comment to a Gitea issue via the supported REST API and verify it # durably against a PROVIDER-RETURNED created id — never trust an exit code # (#865 defect class: tea's non-existent `tea issue comment` no-ops yet exits # 0). The write is a direct POST that returns the created comment object, so we # learn the exact id of THIS write; we then GET that exact id and require # id == created id AND author == acting identity AND exact body AND that it # belongs to this issue. Because verification is keyed to the id the create # returned, a concurrent comment (even same identity, same body) CANNOT # masquerade as this write, and a suppressed/no-op write yields no created id # and fails closed — there is no fallback list scan that a concurrent record # could satisfy. Prints the created comment id on success. # # Args: $1 = issue number, $2 = comment body, $3 = acting identity login. gitea_create_comment_verified() { local issue_number="$1" comment_body="$2" acting_login="$3" local payload write_file readback_file write_status readback_status created_id payload=$(COMMENT_BODY="$comment_body" python3 -c ' import json import os print(json.dumps({"body": os.environ["COMMENT_BODY"]})) ') write_file=$(mktemp "${TMPDIR:-/tmp}/mosaic-issue-comment-write.XXXXXX") readback_file=$(mktemp "${TMPDIR:-/tmp}/mosaic-issue-comment-getid.XXXXXX") trap 'rm -f "$write_file" "$readback_file"' RETURN if ! write_status=$(curl -sS -o "$write_file" -w '%{http_code}' \ -X POST \ -H "Authorization: token $GITEA_API_TOKEN" \ -H 'Content-Type: application/json' \ -d "$payload" \ "$GITEA_API_BASE/issues/$issue_number/comments"); then echo "Error: Gitea comment write transport failed" >&2 return 1 fi if [[ "$write_status" != "201" ]]; then echo "Error: Gitea comment write failed with HTTP $write_status (#865: no durable comment created)" >&2 return 1 fi created_id=$(python3 - "$write_file" <<'PY' import json import sys try: with open(sys.argv[1], encoding="utf-8") as response: comment = json.load(response) created_id = comment.get("id") if isinstance(comment, dict) else None if not isinstance(created_id, int) or created_id <= 0: raise ValueError("create response carried no positive comment id") except (OSError, json.JSONDecodeError, ValueError) as error: print(f"Error: could not identify created Gitea comment: {error}", file=sys.stderr) raise SystemExit(1) print(created_id) PY ) || return 1 if ! readback_status=$(curl -sS -o "$readback_file" -w '%{http_code}' \ -H "Authorization: token $GITEA_API_TOKEN" \ "$GITEA_API_BASE/issues/comments/$created_id"); then echo "Error: Gitea comment read-back transport failed" >&2 return 1 fi if [[ "$readback_status" != "200" ]]; then echo "Error: Gitea comment read-back failed with HTTP $readback_status" >&2 return 1 fi EXPECTED_COMMENT_ID="$created_id" EXPECTED_COMMENT_BODY="$comment_body" \ ACTING_LOGIN="$acting_login" EXPECTED_REPO_SLUG="${GITEA_API_BASE##*/repos/}" \ EXPECTED_NUMBER="$issue_number" \ python3 - "$readback_file" <<'PY' || return 1 import json import os import sys from urllib.parse import urlparse try: with open(sys.argv[1], encoding="utf-8") as response: comment = json.load(response) if not isinstance(comment, dict): raise ValueError("response is not a comment object") expected_id = int(os.environ["EXPECTED_COMMENT_ID"]) expected_body = os.environ["EXPECTED_COMMENT_BODY"] acting_login = os.environ["ACTING_LOGIN"] slug = os.environ["EXPECTED_REPO_SLUG"] number = os.environ["EXPECTED_NUMBER"] # Gitea populates WEB (html) URLs here, not API paths. A plain issue comment # carries issue_url = ///issues/ (pull_request_url # empty); a comment posted to a PR's conversation carries # pull_request_url = ///pulls/ (issue_url empty). # Accept whichever the provider populated — scoped to THIS repo slug and # number — so a genuine write is never rejected merely for URL shape. issue_suffix = f"/{slug}/issues/{number}" pr_suffix = f"/{slug}/pulls/{number}" issue_path = urlparse(comment.get("issue_url") or "").path.rstrip("/") pr_path = urlparse(comment.get("pull_request_url") or "").path.rstrip("/") if comment.get("id") != expected_id: raise ValueError("read-back id does not match the created id") if (comment.get("user") or {}).get("login") != acting_login: raise ValueError("created comment is not authored by the acting identity") if comment.get("body") != expected_body: raise ValueError("created comment body does not match") if not (issue_path.endswith(issue_suffix) or pr_path.endswith(pr_suffix)): raise ValueError("created comment does not belong to this issue") except (OSError, json.JSONDecodeError, KeyError, TypeError, ValueError) as error: print(f"Error: Gitea comment persistence verification failed: {error}", file=sys.stderr) raise SystemExit(1) PY echo "$created_id" return 0 } if [[ "$PLATFORM" == "github" ]]; then gh issue comment "$ISSUE_NUMBER" --body "$COMMENT" echo "Added comment to GitHub issue #$ISSUE_NUMBER" elif [[ "$PLATFORM" == "gitea" ]]; then # Resolve the login this comment should be attributed to: the --login # override when given, otherwise the detected default for this repo's host. # A --login override always wins. Otherwise name this repo host's login only # as a best effort: the login name merely selects a per-login token, and # gitea_resolve_api_for_login falls back to the host credential # (get_gitea_token) when no tea login is named, so the default credential # still resolves even when the host tea has no matching login entry. EFFECTIVE_LOGIN="$LOGIN_OVERRIDE" [[ -n "$EFFECTIVE_LOGIN" ]] || EFFECTIVE_LOGIN=$(get_gitea_login 2>/dev/null || true) # Bind the REST endpoint + token to the effective login, then derive the # acting identity from that SAME credential (GET /user). The write below and # its read-back both use this credential, so the write is verified against # the identity that actually performed it. Passing "explicit" when --login # was supplied forbids the host-default fallback: an unresolvable explicit # override fails closed instead of writing under the default identity. gitea_resolve_api_for_login "$EFFECTIVE_LOGIN" "${LOGIN_OVERRIDE:+explicit}" || exit 1 ACTING_LOGIN=$(gitea_authenticated_login) || exit 1 comment_id=$(gitea_create_comment_verified "$ISSUE_NUMBER" "$COMMENT" "$ACTING_LOGIN") || { echo "Error: could not create and verify a comment on Gitea issue #$ISSUE_NUMBER via a provider-returned created id (#865)." >&2 exit 1 } echo "Added and verified comment on Gitea issue #$ISSUE_NUMBER (comment ID $comment_id)" else echo "Error: Unknown platform" exit 1 fi