#!/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") || { echo "Error: could not resolve a Gitea token for --login '$effective_login'; refusing to fall back to the host default identity (comment write/read-back)" >&2 return 1 } else GITEA_API_TOKEN=$(get_gitea_token_for_login "$effective_login") \ || 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 } # Fetch every page of a Gitea list endpoint into $2 (merged into one JSON # array). Gitea paginates list responses, so a single-page read would # false-negative once a newly created record lands beyond page 1. Walks # page=1,2,… until a short page (fewer than the requested limit) or an empty # page is returned, so the merged array is exhaustive. $1 is the endpoint URL # with NO query string. Returns non-zero (clear stderr) on any transport / # HTTP / parse failure. gitea_fetch_all() { local base_url="$1" dest="$2" page=1 limit=50 status page_file count printf '[]' > "$dest" while :; do page_file=$(mktemp "${TMPDIR:-/tmp}/mosaic-issue-comment-page.XXXXXX") if ! status=$(curl -sS -o "$page_file" -w '%{http_code}' \ -H "Authorization: token $GITEA_API_TOKEN" \ "${base_url}?limit=${limit}&page=${page}"); then rm -f "$page_file" echo "Error: Gitea list read transport failed" >&2 return 1 fi if [[ "$status" != "200" ]]; then rm -f "$page_file" echo "Error: Gitea list read failed with HTTP $status" >&2 return 1 fi count=$(DEST="$dest" python3 - "$page_file" <<'PY' import json import os import sys try: with open(os.environ["DEST"], encoding="utf-8") as merged_file: merged = json.load(merged_file) with open(sys.argv[1], encoding="utf-8") as page_file: page = json.load(page_file) if not isinstance(page, list): raise ValueError("page response is not a list") merged.extend(item for item in page if isinstance(item, dict)) with open(os.environ["DEST"], "w", encoding="utf-8") as merged_file: json.dump(merged, merged_file) except (OSError, json.JSONDecodeError, TypeError, ValueError) as error: print(f"Error: could not merge Gitea list page: {error}", file=sys.stderr) raise SystemExit(1) print(len(page)) PY ) || { rm -f "$page_file"; return 1; } rm -f "$page_file" [[ "$count" -lt "$limit" ]] && break page=$((page + 1)) if [[ "$page" -gt 1000 ]]; then echo "Error: Gitea list pagination exceeded 1000 pages" >&2 return 1 fi done 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 } # Confirm that the comment CREATED by this invocation ($2 = its provider id) is # enumerable in the issue's full, paginated comment listing and is authored by # the acting identity. Gitea paginates list responses, so a comment created # beyond page 1 must still be found; walking every page also proves the created # id is durably indexed against THIS issue rather than merely retrievable by id. # Returns non-zero (clear stderr) if the exact created id is not present with a # matching author. gitea_confirm_comment_enumerable() { local issue_number="$1" created_id="$2" acting_login="$3" merged_file merged_file=$(mktemp "${TMPDIR:-/tmp}/mosaic-issue-comment-readback.XXXXXX") trap 'rm -f "$merged_file"' RETURN gitea_fetch_all "$GITEA_API_BASE/issues/$issue_number/comments" "$merged_file" || return 1 CREATED_COMMENT_ID="$created_id" ACTING_LOGIN="$acting_login" \ python3 - "$merged_file" <<'PY' import json import os import sys try: with open(sys.argv[1], encoding="utf-8") as response: comments = json.load(response) if not isinstance(comments, list): raise ValueError("response is not a comment list") created_id = int(os.environ["CREATED_COMMENT_ID"]) acting_login = os.environ["ACTING_LOGIN"] match = next( ( c for c in comments if isinstance(c, dict) and c.get("id") == created_id and (c.get("user") or {}).get("login") == acting_login ), None, ) if match is None: raise ValueError( f"created comment id {created_id} is not enumerable in the issue's " "paginated comment list under the acting identity" ) except (OSError, json.JSONDecodeError, KeyError, TypeError, ValueError) as error: print(f"Error: Gitea comment enumeration check failed: {error}", file=sys.stderr) raise SystemExit(1) 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_ISSUE_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"] expected_suffix = ( f"/repos/{os.environ['EXPECTED_REPO_SLUG']}" f"/issues/{os.environ['EXPECTED_ISSUE_NUMBER']}" ) issue_path = urlparse(comment.get("issue_url", "")).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(expected_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 gitea_confirm_comment_enumerable "$issue_number" "$created_id" "$acting_login" || return 1 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