fix(tools): write Gitea reviews/comments via REST POST and verify by exact created id (#865)
All checks were successful
ci/woodpecker/pr/ci Pipeline was successful
All checks were successful
ci/woodpecker/pr/ci Pipeline was successful
Replace the tea-based write + boundary/author read-back with a direct Gitea
REST POST that returns the created record's id, and verify that exact record.
BLOCKER 2 (credential ordering): resolve the acting identity, the write token,
and the read-back token from the SAME effective login. A --login override now
selects the credential used for the POST, GET /user, and the GET-by-id
read-back, so an overridden write is verified against the identity that
performed it -- not the host default. Login-name resolution is best-effort and
non-fatal (the override always wins; otherwise fall back to the host
credential), so exotic/ported hosts still resolve a token.
BLOCKER 1+3 (attribution + tautological tests): the write is now
POST /issues/{n}/comments or POST /pulls/{n}/reviews (event + body + commit_id
== PR head), parsing the provider-returned created id. Verification GETs that
exact id and checks author == acting identity and body (comments) or state +
commit_id (reviews). Keying on the created id closes the concurrency window:
a no-op create yields no id and fails closed with no list-scan fallback, and a
concurrent same-identity record has a different id. The review body travels in
the review submit, removing the separate detached comment.
Tests: the curl stub now models a real server with persistent on-disk
review/comment state -- a POST actually creates+persists a record and returns
its id, and the read-back reads that same state (no fabricated record for the
wrapper to find). Adds same-identity no-op-concurrent and author-mismatch
fail-closed cases for both comments and reviews, and >page-1 pagination
coverage for both. README "Durable review provenance" refreshed for the REST
mechanism.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
@@ -3,21 +3,24 @@
|
||||
# Usage: issue-comment.sh -i <issue_number> -c <comment> [--login <name>]
|
||||
#
|
||||
# tea v0.11.1 defines no `comment` subcommand under `tea issue` (or `tea pr`);
|
||||
# the correct invocation is the TOP-LEVEL `tea comment <index> <body>` form.
|
||||
# Calling the non-existent `tea issue comment ...` form does not error — tea
|
||||
# silently falls through to a no-op and still exits 0, so a caller trusting
|
||||
# the exit code alone believes a comment was posted when it was not (#865).
|
||||
# Because that failure mode is silent, this script never trusts tea's exit
|
||||
# code alone: after posting, it independently re-fetches the issue's comments
|
||||
# via the Gitea REST API (curl — urllib is blocked by Cloudflare on this
|
||||
# host) and fails closed if the posted body cannot be found.
|
||||
# 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 <name> to
|
||||
# override that default for this invocation only. The override is appended
|
||||
# to the tea command line AFTER the detected default, because tea honors
|
||||
# only the LAST `--login` flag on the command line — a flag placed before
|
||||
# the default would be silently clobbered by it.
|
||||
# --login override: the default login is resolved from the local `tea` login
|
||||
# list for this repo's host (get_gitea_login). Pass --login <name> 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
|
||||
|
||||
@@ -72,16 +75,25 @@ fi
|
||||
|
||||
detect_platform >/dev/null
|
||||
|
||||
# Resolve and cache the Gitea REST endpoint + token for the current remote.
|
||||
# Populates GITEA_API_ROOT (…/api/v1), GITEA_API_BASE (…/api/v1/repos/<slug>),
|
||||
# and GITEA_API_TOKEN. Returns non-zero (with a clear stderr message) if any
|
||||
# part of the resolution fails.
|
||||
gitea_resolve_api() {
|
||||
local host configured_url repo
|
||||
# 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/<slug>), 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 the login has no token in tea's own config.
|
||||
# Returns non-zero (clear stderr) on any resolution failure.
|
||||
gitea_resolve_api_for_login() {
|
||||
local effective_login="$1" host configured_url repo
|
||||
|
||||
host=$(get_remote_host)
|
||||
GITEA_API_TOKEN=$(get_gitea_token "$host") || {
|
||||
echo "Error: Gitea token not found for comment read-back verification" >&2
|
||||
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
|
||||
}
|
||||
configured_url=$(get_gitea_url_for_host "$host") || {
|
||||
@@ -192,54 +204,22 @@ print(login)
|
||||
PY
|
||||
}
|
||||
|
||||
# Print the maximum existing comment id on an issue (0 if none). This is the
|
||||
# pre-write BOUNDARY: Gitea comment ids are monotonic, so any comment created
|
||||
# by a subsequent write has an id strictly greater than this value.
|
||||
gitea_max_comment_id() {
|
||||
local issue_number="$1" merged_file
|
||||
|
||||
merged_file=$(mktemp "${TMPDIR:-/tmp}/mosaic-issue-comment-boundary.XXXXXX")
|
||||
trap 'rm -f "$merged_file"' RETURN
|
||||
|
||||
gitea_fetch_all "$GITEA_API_BASE/issues/$issue_number/comments" "$merged_file" || return 1
|
||||
|
||||
python3 - "$merged_file" <<'PY'
|
||||
import json
|
||||
import sys
|
||||
|
||||
try:
|
||||
with open(sys.argv[1], encoding="utf-8") as response:
|
||||
comments = json.load(response)
|
||||
ids = [c.get("id") for c in comments if isinstance(c, dict) and isinstance(c.get("id"), int)]
|
||||
print(max(ids) if ids else 0)
|
||||
except (OSError, json.JSONDecodeError, TypeError, ValueError) as error:
|
||||
print(f"Error: could not compute Gitea comment boundary: {error}", file=sys.stderr)
|
||||
raise SystemExit(1)
|
||||
PY
|
||||
}
|
||||
|
||||
# Independently re-fetch (all pages of) the issue's comments and require a
|
||||
# comment attributable to THIS invocation: id strictly greater than the
|
||||
# pre-write boundary AND author login equal to the acting identity AND exact
|
||||
# body match. tea's exit code is not trustworthy evidence of a durable write
|
||||
# on its own (#865); id-above-boundary alone is only temporal ordering, so the
|
||||
# author-login check is what excludes a concurrent write by a DIFFERENT
|
||||
# identity. Prints the matched comment ID on success.
|
||||
#
|
||||
# Residual (documented, not eliminable without a tea-emitted created-record
|
||||
# id, which tea 0.11.1 does not reliably provide): a concurrent write by the
|
||||
# SAME identity with an identical body inside the boundary window could still
|
||||
# be accepted. That is a strictly narrower window than temporal-only matching.
|
||||
gitea_verify_comment_posted() {
|
||||
local issue_number="$1" comment_body="$2" boundary="$3" acting_login="$4"
|
||||
local merged_file
|
||||
# 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
|
||||
|
||||
EXPECTED_COMMENT_BODY="$comment_body" BOUNDARY_COMMENT_ID="$boundary" ACTING_LOGIN="$acting_login" \
|
||||
CREATED_COMMENT_ID="$created_id" ACTING_LOGIN="$acting_login" \
|
||||
python3 - "$merged_file" <<'PY'
|
||||
import json
|
||||
import os
|
||||
@@ -250,65 +230,161 @@ try:
|
||||
comments = json.load(response)
|
||||
if not isinstance(comments, list):
|
||||
raise ValueError("response is not a comment list")
|
||||
expected_body = os.environ["EXPECTED_COMMENT_BODY"]
|
||||
boundary = int(os.environ["BOUNDARY_COMMENT_ID"])
|
||||
created_id = int(os.environ["CREATED_COMMENT_ID"])
|
||||
acting_login = os.environ["ACTING_LOGIN"]
|
||||
# Attribution to THIS write: created-after-boundary AND authored by the
|
||||
# acting identity AND exact body match. The author check excludes a
|
||||
# concurrent DIFFERENT-identity writer that id+body alone would admit.
|
||||
matches = [
|
||||
c for c in comments
|
||||
if isinstance(c, dict)
|
||||
and isinstance(c.get("id"), int)
|
||||
and c.get("id") > boundary
|
||||
and (c.get("user") or {}).get("login") == acting_login
|
||||
and c.get("body") == expected_body
|
||||
]
|
||||
if not matches:
|
||||
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(
|
||||
"no comment attributable to this write matched "
|
||||
"(id > boundary, acting identity, exact body); "
|
||||
"tea may have silently no-opped (#865)"
|
||||
f"created comment id {created_id} is not enumerable in the issue's "
|
||||
"paginated comment list under the acting identity"
|
||||
)
|
||||
comment_id = max(c["id"] for c in matches)
|
||||
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)
|
||||
print(comment_id)
|
||||
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
|
||||
# Build the invocation as an argv array (not unquoted $(get_gitea_repo_args)
|
||||
# word-splitting) so the comment body — including Markdown backticks, $(...),
|
||||
# and quotes — is passed verbatim and never re-split or shell-evaluated.
|
||||
REPO_SLUG=$(get_repo_slug)
|
||||
GITEA_LOGIN_NAME=$(get_gitea_login) || {
|
||||
echo "Error: could not resolve a Gitea login for this repo; cannot comment on issue #$ISSUE_NUMBER." >&2
|
||||
exit 1
|
||||
}
|
||||
# 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)
|
||||
|
||||
# Resolve the REST endpoint, the acting identity, and the pre-write
|
||||
# boundary BEFORE the write, so the read-back can require a strictly-newer
|
||||
# comment id authored by this identity.
|
||||
gitea_resolve_api || exit 1
|
||||
# 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.
|
||||
gitea_resolve_api_for_login "$EFFECTIVE_LOGIN" || exit 1
|
||||
ACTING_LOGIN=$(gitea_authenticated_login) || exit 1
|
||||
boundary=$(gitea_max_comment_id "$ISSUE_NUMBER") || exit 1
|
||||
|
||||
TEA_ARGS=(comment "$ISSUE_NUMBER" "$COMMENT" --repo "$REPO_SLUG" --login "$GITEA_LOGIN_NAME")
|
||||
# --login override goes LAST: tea honors only the final --login on its
|
||||
# command line, so an override placed before the detected default above
|
||||
# would be silently clobbered by it.
|
||||
if [[ -n "$LOGIN_OVERRIDE" ]]; then
|
||||
TEA_ARGS+=(--login "$LOGIN_OVERRIDE")
|
||||
fi
|
||||
tea "${TEA_ARGS[@]}"
|
||||
|
||||
comment_id=$(gitea_verify_comment_posted "$ISSUE_NUMBER" "$COMMENT" "$boundary" "$ACTING_LOGIN") || {
|
||||
echo "Error: could not verify comment landed on Gitea issue #$ISSUE_NUMBER via bounded read-back; treating tea's exit code as untrustworthy (#865)." >&2
|
||||
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)"
|
||||
|
||||
Reference in New Issue
Block a user