/* * gh_api.c - the one outbound HTTP call and the five REST mappings of * plugin_github. * * Every request goes through gh_api_call(): the api base and token are * resolved by gh_config.c (env > config.json > default), the URL is parsed * by the transport (no hand-rolled splitting), the credential rides in * "Authorization: Bearer " exactly as GitHub documents, and TLS is * verified by the vendored BearSSL stack - hostname check on, no downgrade, * the only skip switch being the documented SX_TLS_INSECURE env var. * http:// is accepted because the offline suite and self-hosted GitHub * Enterprise instances use it; there is no special-cased host. * * Retry policy (from the connector spec): a 429 or 5xx is retried exactly * once, sleeping min(Retry-After, GH_RETRY_MAX_MS). One, not a loop: a CGI * request or an MCP tool call must not turn into an unbounded wait. * * Output policy: tool results are human-readable text built in a growable * buffer and hard-capped at GH_OUT_CAP; every string taken from GitHub's * JSON is copied BEFORE the document is freed (this fleet has already paid * for that bug once) and JSON-escaped through gh_json_str() when it lands * inside a structured section. An upstream refusal is relayed with GitHub's * own {"message":...} - the user's one actionable fact is never replaced by * a generic error. * * MIT License. Copyright (c) 2026 SCORPIOX INC. */ #if defined(_WIN32) && !defined(_WIN32_WINNT) # define _WIN32_WINNT 0x0601 #endif #if !defined(_WIN32) # if !defined(_POSIX_C_SOURCE) || _POSIX_C_SOURCE < 200809L # undef _POSIX_C_SOURCE # define _POSIX_C_SOURCE 200809L # endif # ifndef _DEFAULT_SOURCE # define _DEFAULT_SOURCE 1 # endif #endif #include "gh.h" #include #include #include #include #include #if defined(_WIN32) # include #else # include #endif /* ---------------------------------------------------------------- sleep */ static void gh_sleep_ms(long ms) { if (ms <= 0) return; if (ms > GH_RETRY_MAX_MS) ms = GH_RETRY_MAX_MS; #if defined(_WIN32) Sleep((DWORD)ms); #else { struct timespec ts; ts.tv_sec = ms / 1000; ts.tv_nsec = (ms % 1000) * 1000000L; while (nanosleep(&ts, &ts) != 0) { /* EINTR: resume */ } } #endif } /* ------------------------------------------------------------ args read */ int gh_arg_str(const char *args_json, const char *key, char *out, size_t capsz, int required, char *err, size_t errsz) { yyjson_doc *d; yyjson_val *v; int found = 0; if (out && capsz) out[0] = '\0'; if (!args_json || !*args_json) args_json = "{}"; d = yyjson_read(args_json, strlen(args_json), 0); if (!d) { if (err && errsz) gh_copy(err, errsz, "arguments are not valid JSON"); return -1; } v = yyjson_obj_get(yyjson_doc_get_root(d), key); if (v && yyjson_is_str(v) && yyjson_get_str(v)[0]) { gh_copy(out, capsz, yyjson_get_str(v)); found = 1; } else if (v && yyjson_is_uint(v)) { char tmp[32]; snprintf(tmp, sizeof tmp, "%llu", (unsigned long long)yyjson_get_uint(v)); gh_copy(out, capsz, tmp); found = 1; } else if (v && yyjson_is_sint(v)) { char tmp[32]; snprintf(tmp, sizeof tmp, "%lld", (long long)yyjson_get_sint(v)); gh_copy(out, capsz, tmp); found = 1; } yyjson_doc_free(d); if (!found && required && err && errsz) { gh_copy(err, errsz, "missing required argument"); /* name the key without any format-string risk: append it verbatim */ { char full[160]; snprintf(full, sizeof full, "missing required argument '%s'", key); gh_copy(err, errsz, full); } } return found; } int gh_arg_int(const char *args_json, const char *key, long *out_val, int required, char *err, size_t errsz) { yyjson_doc *d; yyjson_val *v; int found = 0; if (out_val) *out_val = 0; if (!args_json || !*args_json) args_json = "{}"; d = yyjson_read(args_json, strlen(args_json), 0); if (!d) { if (err && errsz) gh_copy(err, errsz, "arguments are not valid JSON"); return -1; } v = yyjson_obj_get(yyjson_doc_get_root(d), key); if (v && yyjson_is_uint(v)) { if (out_val) *out_val = (long)yyjson_get_uint(v); found = 1; } else if (v && yyjson_is_sint(v)) { if (out_val) *out_val = (long)yyjson_get_sint(v); found = 1; } else if (v && yyjson_is_str(v)) { char *end = NULL; long x = strtol(yyjson_get_str(v), &end, 10); if (end && *end == '\0' && end != yyjson_get_str(v)) { if (out_val) *out_val = x; found = 1; } } yyjson_doc_free(d); if (!found && required && err && errsz) { char full[160]; snprintf(full, sizeof full, "missing required argument '%s'", key); gh_copy(err, errsz, full); } return found; } /* ------------------------------------------------------------- one call */ /* Join api base + path into one URL string. Both are already validated * pieces; sx_url_parse then re-validates the whole thing before a byte * leaves the process. */ static void join_url(const gh_config *cfg, const char *path, char *url, size_t urlsz) { if (!path || path[0] != '/') snprintf(url, urlsz, "%s/", cfg->api_base); else snprintf(url, urlsz, "%s%s", cfg->api_base, path); } static int one_request(const gh_config *cfg, const char *method, const char *path, const char *body, sx_conn *c, char **resp, char *err, size_t errsz) { char url[1536]; char headers[1024]; sx_url u; *resp = NULL; join_url(cfg, path, url, sizeof url); if (sx_url_parse(url, &u, err, errsz) != 0) return -1; if (sx_conn_open(c, &u, GH_HTTP_TIMEOUT_MS, err, errsz) != 0) return -1; snprintf(headers, sizeof headers, "Accept: application/vnd.github+json\r\n" "X-GitHub-Api-Version: %s\r\n" "User-Agent: %s\r\n" "Content-Type: application/json\r\n", GH_API_VERSION, GH_UA); if (sx_http_request(c, method, u.path[0] ? u.path : "/", headers, cfg->has_token ? cfg->token : NULL, body, body ? strlen(body) : 0, GH_HTTP_TIMEOUT_MS, err, errsz) != 0) { sx_conn_close(c); return -1; } { char *buf = NULL; if (sx_read_all(c, &buf, NULL, GH_HTTP_TIMEOUT_MS) != 1) { free(buf); sx_conn_close(c); gh_copy(err, errsz, "response body read failed"); return -1; } *resp = buf ? buf : strdup(""); } sx_conn_close(c); return 0; } int gh_api_call(const gh_config *cfg, const char *method, const char *path, const char *body, long *status, char **resp, char *err, size_t errsz) { sx_conn c; long st = 0; char *text = NULL; int attempt; *status = 0; *resp = NULL; err[0] = '\0'; for (attempt = 0; attempt < 2; attempt++) { memset(&c, 0, sizeof c); if (one_request(cfg, method, path, body, &c, &text, err, errsz) != 0) { free(text); return -1; } st = c.status; if (attempt == 0 && (st == 429 || st >= 500)) { char ra[32]; long wait_ms = 1000; /* one second by default */ if (sx_http_header(&c, "Retry-After", ra, sizeof ra)) { long secs = strtol(ra, NULL, 10); if (secs > 0) wait_ms = secs * 1000; } free(text); text = NULL; gh_sleep_ms(wait_ms); continue; } break; } /* secondary rate-limit bodies ask to wait too, but a 200 with a * rate_limit structure is a success, not a retry */ *status = st; *resp = text ? text : strdup(""); return 0; } void gh_upstream_error(const char *resp, long status, char *err, size_t errsz) { yyjson_doc *d = NULL; const char *msg = NULL; if (resp && *resp) d = yyjson_read(resp, strlen(resp), 0); if (d) { yyjson_val *root = yyjson_doc_get_root(d); yyjson_val *m; /* {"message":"..."} is the documented REST shape; GraphQL errors * arrive as {"errors":[{"message":...}]} - relay either, verbatim */ m = root ? yyjson_obj_get(root, "message") : NULL; if (m && yyjson_is_str(m)) msg = yyjson_get_str(m); else if (root && yyjson_is_obj(root)) { yyjson_val *errs = yyjson_obj_get(root, "errors"); if (errs && yyjson_is_arr(errs) && yyjson_arr_size(errs) > 0) { yyjson_val *e0 = yyjson_arr_get(errs, 0); yyjson_val *em = e0 ? yyjson_obj_get(e0, "message") : NULL; if (em && yyjson_is_str(em)) msg = yyjson_get_str(em); } } } if (msg && *msg) { /* copy BEFORE freeing: yyjson strings point into the document */ char safe[512]; gh_copy(safe, sizeof safe, msg); snprintf(err, errsz, "GitHub HTTP %ld: %s", status, safe); } else { snprintf(err, errsz, "GitHub HTTP %ld", status); } if (d) yyjson_doc_free(d); } /* ------------------------------------------------------- shared helpers */ /* Reject anything that could break a URL path segment or JSON. The rule is * allow-list, not block-list: repo names cannot contain spaces, quotes, or * control characters in the first place. */ static int safe_name(const char *s, char *err, size_t errsz) { size_t i; if (!s || !*s) { gh_copy(err, errsz, "empty name argument"); return -1; } for (i = 0; s[i]; i++) { unsigned char c = (unsigned char)s[i]; if (c <= 0x20 || c >= 0x7f || c == '"' || c == '\'' || c == '\\' || c == '%' || c == '?' || c == '#' || c == '&' || c == '<' || c == '>') { gh_copy(err, errsz, "name contains characters not allowed by GitHub"); return -1; } } return 0; } /* GET a path, treat 2xx as success, otherwise emit the upstream message. * Returns the parsed document (caller frees) or NULL with err filled. */ static yyjson_doc *api_get_json(const gh_config *cfg, const char *path, long *status_out, char *err, size_t errsz) { long status = 0; char *resp = NULL; if (gh_api_call(cfg, "GET", path, NULL, &status, &resp, err, errsz) != 0) return NULL; if (status < 200 || status >= 300) { gh_upstream_error(resp, status, err, errsz); free(resp); return NULL; } if (status_out) *status_out = status; { yyjson_doc *d = yyjson_read(resp, strlen(resp), 0); free(resp); if (!d) { gh_copy(err, errsz, "GitHub returned a body that is not JSON"); return NULL; } return d; } } static const char *jstr(yyjson_val *obj, const char *key) { yyjson_val *v = obj ? yyjson_obj_get(obj, key) : NULL; return (v && yyjson_is_str(v)) ? yyjson_get_str(v) : ""; } static long long jint(yyjson_val *obj, const char *key, long long dflt) { yyjson_val *v = obj ? yyjson_obj_get(obj, key) : NULL; if (v && yyjson_is_uint(v)) return (long long)yyjson_get_uint(v); if (v && yyjson_is_sint(v)) return (long long)yyjson_get_sint(v); return dflt; } /* Copy a possibly-long string from a document into a bounded buffer, then * append a labelled line to the buffer. All copies happen while the doc is * alive (cw2). */ static void put_field(gh_buf *b, yyjson_val *obj, const char *key, const char *label) { char val[512]; gh_copy(val, sizeof val, jstr(obj, key)); if (!val[0]) return; gh_buf_printf(b, "%s: ", label); gh_buf_puts(b, val); gh_buf_puts(b, "\n"); } /* ---------------------------------------------------------------- tools */ int gh_tool_get_repo(const char *args_json, char *out, size_t outsz, char *err, size_t errsz) { gh_config cfg; char owner[128], repo[128], path[320]; yyjson_doc *d; yyjson_val *root; gh_buf b; owner[0] = repo[0] = '\0'; if (gh_arg_str(args_json, "owner", owner, sizeof owner, 1, err, errsz) <= 0) return 1; if (gh_arg_str(args_json, "repo", repo, sizeof repo, 1, err, errsz) <= 0) return 1; if (safe_name(owner, err, errsz) != 0 || safe_name(repo, err, errsz) != 0) return 1; gh_config_load(&cfg); snprintf(path, sizeof path, "/repos/%s/%s", owner, repo); d = api_get_json(&cfg, path, NULL, err, errsz); if (!d) return 1; root = yyjson_doc_get_root(d); gh_buf_init(&b); gh_buf_printf(&b, "repository %s/%s\n", owner, repo); put_field(&b, root, "full_name", "full_name"); put_field(&b, root, "description", "description"); put_field(&b, root, "html_url", "html_url"); put_field(&b, root, "default_branch", "default_branch"); put_field(&b, root, "language", "language"); put_field(&b, yyjson_obj_get(root, "license"), "spdx_id", "license"); put_field(&b, root, "visibility", "visibility"); gh_buf_printf(&b, "stars: %lld\n", jint(root, "stargazers_count", 0)); gh_buf_printf(&b, "forks: %lld\n", jint(root, "forks_count", 0)); gh_buf_printf(&b, "open_issues: %lld\n", jint(root, "open_issues_count", 0)); gh_buf_printf(&b, "archived: %s\n", yyjson_is_true(yyjson_obj_get(root, "archived")) ? "yes" : "no"); gh_buf_printf(&b, "pushed_at: %s\n", jstr(root, "pushed_at")); if (b.n > GH_OUT_CAP) { /* descriptions are user data; hard cap stands */ out[0] = '\0'; } gh_copy(out, outsz, gh_buf_str(&b)); gh_buf_free(&b); yyjson_doc_free(d); return 0; } int gh_tool_list_issues(const char *args_json, char *out, size_t outsz, char *err, size_t errsz) { gh_config cfg; char owner[128], repo[128], state[16], path[384]; yyjson_doc *d; yyjson_val *root, *it; gh_buf b; size_t idx, maxv, shown = 0; owner[0] = repo[0] = '\0'; if (gh_arg_str(args_json, "owner", owner, sizeof owner, 1, err, errsz) <= 0) return 1; if (gh_arg_str(args_json, "repo", repo, sizeof repo, 1, err, errsz) <= 0) return 1; if (gh_arg_str(args_json, "state", state, sizeof state, 0, err, errsz) < 0) return 1; if (!state[0]) gh_copy(state, sizeof state, "open"); if (strcmp(state, "open") != 0 && strcmp(state, "closed") != 0 && strcmp(state, "all") != 0) { gh_copy(err, errsz, "state must be open, closed or all"); return 1; } if (safe_name(owner, err, errsz) != 0 || safe_name(repo, err, errsz) != 0) return 1; gh_config_load(&cfg); snprintf(path, sizeof path, "/repos/%s/%s/issues?state=%s&per_page=%d&sort=created&direction=desc", owner, repo, state, GH_PER_PAGE); d = api_get_json(&cfg, path, NULL, err, errsz); if (!d) return 1; root = yyjson_doc_get_root(d); if (!yyjson_is_arr(root)) { yyjson_doc_free(d); gh_copy(err, errsz, "GitHub returned a body that is not an array"); return 1; } gh_buf_init(&b); gh_buf_printf(&b, "issues (%s) in %s/%s\n", state, owner, repo); /* upstream parity: /issues also returns pull requests; a PR carries a * pull_request key, and skipping it here is exactly what the reference * implementations do */ yyjson_arr_foreach(root, idx, maxv, it) { long long num; char title[300]; if (yyjson_obj_get(it, "pull_request") != NULL) continue; num = jint(it, "number", 0); gh_copy(title, sizeof title, jstr(it, "title")); gh_buf_printf(&b, "#%lld", num); /* a title is arbitrary user text: put it on its own escaped-safe * line with control bytes replaced so nothing can forge a row */ { size_t k; for (k = 0; title[k]; k++) { unsigned char ch = (unsigned char)title[k]; if (ch < 0x20 || ch == 0x7f) title[k] = ' '; } gh_buf_printf(&b, "\t%s", title); } gh_buf_printf(&b, "\t%s\t%s\n", jstr(it, "state"), jstr(it, "html_url")); shown++; if (b.n > GH_OUT_CAP) break; } if (shown == 0) gh_buf_puts(&b, "(none)\n"); gh_copy(out, outsz, gh_buf_str(&b)); gh_buf_free(&b); yyjson_doc_free(d); return 0; } int gh_tool_create_issue(const char *args_json, char *out, size_t outsz, char *err, size_t errsz) { gh_config cfg; char owner[128], repo[128], title[257], body_txt[4097], path[320]; long status = 0; char *resp = NULL; yyjson_doc *d; gh_buf req, b; owner[0] = repo[0] = title[0] = body_txt[0] = '\0'; if (gh_arg_str(args_json, "owner", owner, sizeof owner, 1, err, errsz) <= 0) return 1; if (gh_arg_str(args_json, "repo", repo, sizeof repo, 1, err, errsz) <= 0) return 1; if (gh_arg_str(args_json, "title", title, sizeof title, 1, err, errsz) <= 0) return 1; if (gh_arg_str(args_json, "body", body_txt, sizeof body_txt, 0, err, errsz) < 0) return 1; if (safe_name(owner, err, errsz) != 0 || safe_name(repo, err, errsz) != 0) return 1; if (!title[0]) { gh_copy(err, errsz, "title must not be empty"); return 1; } gh_config_load(&cfg); if (!cfg.has_token) { gh_copy(err, errsz, "no credential configured - create_issue needs a PAT; " "open the plugin page and save one"); return 1; } /* build {"title":"...","body":"..."} with the escaper, never a format */ gh_buf_init(&req); gh_buf_puts(&req, "{\"title\":"); gh_json_str(&req, title); if (body_txt[0]) { gh_buf_puts(&req, ",\"body\":"); gh_json_str(&req, body_txt); } gh_buf_puts(&req, "}"); snprintf(path, sizeof path, "/repos/%s/%s/issues", owner, repo); if (gh_api_call(&cfg, "POST", path, gh_buf_str(&req), &status, &resp, err, errsz) != 0) { gh_buf_free(&req); return 1; } gh_buf_free(&req); if (status < 200 || status >= 300) { gh_upstream_error(resp, status, err, errsz); free(resp); return 1; } d = yyjson_read(resp, strlen(resp), 0); free(resp); gh_buf_init(&b); if (d) { yyjson_val *root = yyjson_doc_get_root(d); gh_buf_printf(&b, "created issue #%lld in %s/%s\n", jint(root, "number", 0), owner, repo); put_field(&b, root, "html_url", "html_url"); put_field(&b, root, "state", "state"); gh_copy(out, outsz, gh_buf_str(&b)); yyjson_doc_free(d); } else { snprintf(out, outsz, "created issue in %s/%s (HTTP %ld)", owner, repo, status); } gh_buf_free(&b); return 0; } int gh_tool_get_pull_request(const char *args_json, char *out, size_t outsz, char *err, size_t errsz) { gh_config cfg; char owner[128], repo[128], path[320]; long number = 0; yyjson_doc *d; yyjson_val *root; gh_buf b; owner[0] = repo[0] = '\0'; if (gh_arg_str(args_json, "owner", owner, sizeof owner, 1, err, errsz) <= 0) return 1; if (gh_arg_str(args_json, "repo", repo, sizeof repo, 1, err, errsz) <= 0) return 1; if (gh_arg_int(args_json, "number", &number, 1, err, errsz) <= 0) return 1; if (number <= 0) { gh_copy(err, errsz, "number must be a positive integer"); return 1; } if (safe_name(owner, err, errsz) != 0 || safe_name(repo, err, errsz) != 0) return 1; gh_config_load(&cfg); snprintf(path, sizeof path, "/repos/%s/%s/pulls/%ld", owner, repo, number); d = api_get_json(&cfg, path, NULL, err, errsz); if (!d) return 1; root = yyjson_doc_get_root(d); gh_buf_init(&b); gh_buf_printf(&b, "pull request #%ld in %s/%s\n", number, owner, repo); put_field(&b, root, "title", "title"); put_field(&b, root, "state", "state"); put_field(&b, root, "html_url", "html_url"); put_field(&b, yyjson_obj_get(root, "user"), "login", "author"); put_field(&b, yyjson_obj_get(root, "head"), "label", "head"); put_field(&b, yyjson_obj_get(root, "base"), "label", "base"); gh_buf_printf(&b, "draft: %s\n", yyjson_is_true(yyjson_obj_get(root, "draft")) ? "yes" : "no"); gh_buf_printf(&b, "merged: %s\n", yyjson_obj_get(root, "merged_at") && !yyjson_is_null(yyjson_obj_get(root, "merged_at")) ? "yes" : "no"); gh_buf_printf(&b, "commits: %lld comments: %lld additions: %lld deletions: %lld\n", jint(root, "commits", 0), jint(root, "comments", 0), jint(root, "additions", 0), jint(root, "deletions", 0)); put_field(&b, root, "merged_at", "merged_at"); put_field(&b, root, "created_at", "created_at"); gh_copy(out, outsz, gh_buf_str(&b)); gh_buf_free(&b); yyjson_doc_free(d); return 0; } int gh_tool_search_code(const char *args_json, char *out, size_t outsz, char *err, size_t errsz) { gh_config cfg; char query[512]; yyjson_doc *d; yyjson_val *root, *items, *it; gh_buf q, pathb, b; size_t idx, maxv, shown = 0; query[0] = '\0'; if (gh_arg_str(args_json, "query", query, sizeof query, 1, err, errsz) <= 0) return 1; if (!query[0]) { gh_copy(err, errsz, "query must not be empty"); return 1; } gh_buf_init(&q); gh_url_encode(query, &q); gh_config_load(&cfg); gh_buf_init(&pathb); gh_buf_printf(&pathb, "/search/code?q=%s&per_page=%d", gh_buf_str(&q), GH_SEARCH_MAX_ITEMS); gh_buf_free(&q); d = api_get_json(&cfg, gh_buf_str(&pathb), NULL, err, errsz); gh_buf_free(&pathb); if (!d) return 1; root = yyjson_doc_get_root(d); items = yyjson_obj_get(root, "items"); gh_buf_init(&b); gh_buf_printf(&b, "code search: %s\n", query); gh_buf_printf(&b, "total_count: %lld\n", jint(root, "total_count", 0)); if (!items || !yyjson_is_arr(items)) { gh_buf_puts(&b, "(no results)\n"); } else { gh_buf_puts(&b, "results (path @ repo):\n"); yyjson_arr_foreach(items, idx, maxv, it) { char name[256], pth[400], html[400]; yyjson_val *r = yyjson_obj_get(it, "repository"); gh_copy(name, sizeof name, jstr(it, "name")); gh_copy(pth, sizeof pth, jstr(it, "path")); gh_copy(html, sizeof html, jstr(it, "html_url")); { /* every field is user data: strip control bytes so one * result row cannot forge another row or a fake header */ size_t k; for (k = 0; name[k]; k++) if ((unsigned char)name[k] < 0x20) name[k] = ' '; for (k = 0; pth[k]; k++) if ((unsigned char)pth[k] < 0x20) pth[k] = ' '; } gh_buf_printf(&b, "%s @ %s\t%s\n", pth, jstr(r, "full_name"), html); shown++; if (b.n > GH_OUT_CAP) break; } if (shown == 0) gh_buf_puts(&b, "(none)\n"); } gh_copy(out, outsz, gh_buf_str(&b)); gh_buf_free(&b); yyjson_doc_free(d); return 0; }