Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 15 additions & 2 deletions rust/contracts/github.md
Original file line number Diff line number Diff line change
Expand Up @@ -88,8 +88,21 @@ Supported operations are `deviceCode`, `deviceToken`, `currentUser`,
`listBranches`, `compareBranches`, `listPullRequests`, `getPullRequest`, `createPullRequest`, `updatePullRequest`,
`listPullRequestFiles`, `listPullRequestComments`,
`createPullRequestComment`, `createPullRequestReview`, `mergePullRequest`,
`updatePullRequestMetadata`, `listReviewComments`, `listCheckRuns`, and
`getCombinedStatus`.
`updatePullRequestMetadata`, `listReviewComments`, `listCheckRuns`,
`getCombinedStatus`, `latestCommit`, and `listReleases`.

`latestCommit` and `listReleases` read public data, so their plans set
`requiresAuthentication: false` and work without a signed-in account.
`latestCommit` (`GET /repos/{owner}/{name}/commits?sha={ref}&per_page=1`) needs
`ref` (`HEAD`, a branch or tag name, or a `refs/...` name; whitespace, `..`, a
leading `-` and the revision operators `~ ^ : ? * [ \` are refused) and returns
`{ sha }`, the ref's newest commit as a full lowercase SHA-1 or SHA-256 name.
Hosts use it to pin a marketplace index to a commit, because raw file URLs of a
branch are cached for minutes (see `plugins.marketplace.resolveSource`).
`listReleases` (`GET /repos/{owner}/{name}/releases`, first page of 20) returns
`[{ tagName, name, body, publishedAt, prerelease, url }]` newest publication
first, ties ordered by tag; drafts are dropped, an empty title is `null` and
missing notes are `""`.

`listReviewComments` (`GET /repos/{owner}/{name}/pulls/{number}/comments`, first
page of 100) needs `pullNumber` and returns a flat array of
Expand Down
7 changes: 5 additions & 2 deletions rust/contracts/rust-core-api.md
Original file line number Diff line number Diff line change
Expand Up @@ -5438,8 +5438,11 @@ archives and pass the parsed JSON. `validateIndex` accepts
`{ index, sourceKind: "official" | "thirdParty", platform, hostCapabilities? }`
and returns `{ status: "ok", index: { plugins, rejected } }` with per-entry
`availability`; a listed version is available only when its `pluginAPIVersion`
is one Core supports and every capability it requires is in `hostCapabilities`; `resolveSource` accepts `{ url }` and returns
`{ status: "ok", source: { indexURL, recommendationsURL, repository, displayName } }`;
is one Core supports and every capability it requires is in `hostCapabilities`; `resolveSource` accepts `{ url, commit? }` and returns
`{ status: "ok", source: { indexURL, recommendationsURL, repository, displayName, revision, pinned? } }`,
where `revision` names the GitHub repository and ref a host may look the newest commit of
(`github.latestCommit`) and `pinned` holds the same URLs at the `commit` passed back;
`indexURL` remains the source identity;
`installReview` accepts `{ manifest, expectedID?, expectedVersion?,
approvedPrograms?, hostCapabilities? }` and returns `{ status: "ok", review: { id, version,
permissions, programs, newPrograms } }`;
Expand Down
124 changes: 124 additions & 0 deletions rust/crates/core/src/tests/github.rs
Original file line number Diff line number Diff line change
Expand Up @@ -394,3 +394,127 @@ fn request_plan_and_normalize_review_comment_threads() {
assert!(response["data"][1]["line"].is_null());
assert_eq!(response["data"][1]["createdAt"], "2026-11-01T00:05:00Z");
}

#[test]
fn request_plan_reads_the_newest_commit_and_releases_without_credentials() {
let response = execute(
"github.requestPlan",
json!({
"operation": "latestCommit",
"repository": {"owner": "example", "name": "lithe-plugins"},
"ref": "refs/heads/release"
}),
);
assert_eq!(response["ok"], true, "{response:?}");
assert_eq!(response["data"]["host"], "api");
assert_eq!(response["data"]["method"], "GET");
assert_eq!(
response["data"]["path"],
"/repos/example/lithe-plugins/commits"
);
assert_eq!(
response["data"]["query"],
json!({"per_page": "1", "sha": "refs/heads/release"})
);
assert_eq!(response["data"]["requiresAuthentication"], false);

let response = execute(
"github.requestPlan",
json!({
"operation": "listReleases",
"repository": {"owner": "example", "name": "lithe-plugin-rust"}
}),
);
assert_eq!(response["ok"], true, "{response:?}");
assert_eq!(
response["data"]["path"],
"/repos/example/lithe-plugin-rust/releases"
);
assert_eq!(response["data"]["query"], json!({"per_page": "20"}));
assert_eq!(response["data"]["requiresAuthentication"], false);

for git_ref in ["", "main..x", "-x", "main x", "HEAD~1", "a:b"] {
let response = execute(
"github.requestPlan",
json!({
"operation": "latestCommit",
"repository": {"owner": "example", "name": "lithe-plugins"},
"ref": git_ref
}),
);
assert_eq!(response["ok"], false, "{git_ref}: {response:?}");
assert_eq!(response["error"]["code"], "invalid_request");
}
}

#[test]
fn normalizes_the_newest_commit_to_a_full_lowercase_object_name() {
let sha = "0123456789ABCDEF0123456789ABCDEF01234567";
let response = execute(
"github.normalizeResponse",
json!({
"operation": "latestCommit",
"status": 200,
"body": json!([{"sha": sha, "commit": {"message": "x"}}]).to_string()
}),
);
assert_eq!(response["ok"], true, "{response:?}");
assert_eq!(response["data"], json!({"sha": sha.to_ascii_lowercase()}));

for body in [json!([]), json!([{"sha": "0123abc"}]), json!({"sha": sha})] {
let response = execute(
"github.normalizeResponse",
json!({"operation": "latestCommit", "status": 200, "body": body.to_string()}),
);
assert_eq!(response["ok"], false, "{body}: {response:?}");
assert_eq!(response["error"]["code"], "parse_failed");
}
}

#[test]
fn normalizes_releases_newest_first_without_drafts() {
let body = json!([
{
"tag_name": "v0.1.0", "name": "v0.1.0", "body": "First.", "draft": false,
"prerelease": true, "published_at": "2026-11-21T08:00:00Z",
"html_url": "https://github.com/example/p/releases/tag/v0.1.0"
},
{
"tag_name": "v0.2.0", "name": null, "body": null, "draft": true,
"prerelease": false, "published_at": null,
"html_url": "https://github.com/example/p/releases/tag/untagged"
},
{
"tag_name": "v0.1.1", "name": " ", "body": "## Fixes\n- One.", "draft": false,
"prerelease": false, "published_at": "2026-11-22T13:31:49Z",
"html_url": "https://github.com/example/p/releases/tag/v0.1.1"
}
]);
let response = execute(
"github.normalizeResponse",
json!({"operation": "listReleases", "status": 200, "body": body.to_string()}),
);
assert_eq!(response["ok"], true, "{response:?}");
assert_eq!(
response["data"],
json!([
{
"tagName": "v0.1.1", "name": null, "body": "## Fixes\n- One.",
"publishedAt": "2026-11-22T13:31:49Z", "prerelease": false,
"url": "https://github.com/example/p/releases/tag/v0.1.1"
},
{
"tagName": "v0.1.0", "name": "v0.1.0", "body": "First.",
"publishedAt": "2026-11-21T08:00:00Z", "prerelease": true,
"url": "https://github.com/example/p/releases/tag/v0.1.0"
}
])
);

let response = execute(
"github.normalizeResponse",
json!({"operation": "listReleases", "status": 404, "body": "{\"message\":\"Not Found\"}"}),
);
assert_eq!(response["ok"], false, "{response:?}");
assert_eq!(response["error"]["code"], "invalid_request");
}
6 changes: 5 additions & 1 deletion rust/crates/core/src/tests/marketplace_plugins.rs
Original file line number Diff line number Diff line change
Expand Up @@ -197,7 +197,11 @@ fn source_url_fixtures_resolve_to_expected_index_urls() {
let cases = json_file(SOURCE_URLS);
for case in cases["cases"].as_array().unwrap() {
let input = case["input"].as_str().unwrap();
let outcome = resolve_source_command(json!({ "url": input })).unwrap();
let mut payload = json!({ "url": input });
if let Some(commit) = case.get("commit") {
payload["commit"] = commit.clone();
}
let outcome = resolve_source_command(payload).unwrap();
if let Some(code) = case.get("expectedCode") {
assert_eq!(outcome["status"], "rejected", "{input}: {outcome}");
assert_eq!(&outcome["error"]["code"], code, "{input}: {outcome}");
Expand Down
125 changes: 125 additions & 0 deletions rust/crates/github/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,11 @@ const DEVICE_EXPIRATION_MAX_SECONDS: u64 = 86_400;
// Once an interval reaches the maximum lifetime, no further poll can occur.
const DEVICE_INTERVAL_MAX_SECONDS: u64 = DEVICE_EXPIRATION_MAX_SECONDS;
const DEVICE_SLOW_DOWN_SECONDS: u64 = 5;
// The changelog shows the newest releases; one bounded page keeps the
// anonymous request small.
const RELEASE_PAGE_SIZE: u64 = 20;
// A Git ref name is bounded like a file name; GitHub refuses longer ones.
const GIT_REF_MAX_BYTES: usize = 255;

#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
Expand Down Expand Up @@ -200,6 +205,9 @@ pub struct RequestPlanRequest {
/// Full commit SHA required by commit-status operations.
#[serde(default)]
pub commit: Option<String>,
/// Branch, tag or `HEAD` whose newest commit `latestCommit` looks up.
#[serde(default, rename = "ref")]
pub git_ref: Option<String>,
/// OAuth application's public client identifier.
#[serde(default)]
pub client_id: Option<String>,
Expand Down Expand Up @@ -452,6 +460,24 @@ pub struct GitHubComparison {
pub files: Vec<GitHubPullRequestFile>,
}

#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
/// Normalized published release of a repository, as a changelog lists it.
pub struct GitHubRelease {
/// Git tag the release was published from.
pub tag_name: String,
/// Release title; null when the author left it empty.
pub name: Option<String>,
/// Markdown release notes; empty when the author wrote none.
pub body: String,
/// ISO-8601 publication timestamp.
pub published_at: Option<String>,
/// Whether the author marked the release as a pre-release.
pub prerelease: bool,
/// Browser URL of the release page.
pub url: String,
}

/// Parses one supported GitHub remote URL.
pub fn parse_remote(request: ParseRemoteRequest) -> Result<GitHubRepository, CoreError> {
let value = request.remote_url.trim().trim_end_matches('/');
Expand Down Expand Up @@ -634,6 +660,32 @@ pub fn request_plan(request: RequestPlanRequest) -> Result<GitHubRequestPlan, Co
true,
)
}
// Public reads: an anonymous request works on any public repository,
// so a signed-out user gets the same answer.
"latestCommit" => {
let repository = repository_path(&request)?;
let git_ref = git_ref(&request)?;
query.insert("sha".to_string(), git_ref.to_string());
query.insert("per_page".to_string(), "1".to_string());
(
GitHubHost::Api,
"GET",
format!("/repos/{repository}/commits"),
None,
false,
)
}
"listReleases" => {
let repository = repository_path(&request)?;
query.insert("per_page".to_string(), RELEASE_PAGE_SIZE.to_string());
(
GitHubHost::Api,
"GET",
format!("/repos/{repository}/releases"),
None,
false,
)
}
"listPullRequestComments" => {
let repository = repository_path(&request)?;
let number = pull_number(&request)?;
Expand Down Expand Up @@ -744,6 +796,8 @@ pub fn normalize_response(request: NormalizeResponseRequest) -> Result<Value, Co
"listReviewComments" => normalize_review_comment_list(value),
"listCheckRuns" => normalize_check_run_list(value),
"getCombinedStatus" => normalize_combined_status(value),
"latestCommit" => normalize_latest_commit(value),
"listReleases" => normalize_release_list(value),
"createPullRequestComment" => {
Ok(serde_json::to_value(normalize_comment(&value)?).expect("comment encodes"))
}
Expand All @@ -766,6 +820,24 @@ fn commit_path(request: &RequestPlanRequest) -> Result<(String, String), CoreErr
Ok((repository, commit.to_string()))
}

/// The ref travels as a query value, so it is only bounded here; GitHub
/// answers an unknown ref with an error.
fn git_ref(request: &RequestPlanRequest) -> Result<&str, CoreError> {
let value = required_text(request.git_ref.as_deref(), "ref")?;
let valid = value.len() <= GIT_REF_MAX_BYTES
&& !value.contains("..")
&& !value.starts_with('-')
&& value.chars().all(|character| {
character.is_ascii_graphic()
&& !matches!(character, '~' | '^' | ':' | '?' | '*' | '[' | '\\')
});
if valid {
Ok(value)
} else {
Err(invalid_field("ref"))
}
}

fn repository_path(request: &RequestPlanRequest) -> Result<String, CoreError> {
request
.repository
Expand Down Expand Up @@ -1097,6 +1169,59 @@ fn normalize_combined_status(value: Value) -> Result<Value, CoreError> {
Ok(serde_json::to_value(checks).expect("combined status encodes"))
}

/// The commit list is asked for one entry: the ref's newest commit. A full
/// SHA-1 or SHA-256 object name is required, because the caller builds an
/// immutable file URL from it.
fn normalize_latest_commit(value: Value) -> Result<Value, CoreError> {
let first = value
.as_array()
.and_then(|commits| commits.first())
.ok_or_else(parse_shape_error)?;
let sha = text(object(first)?, "sha")?;
if !matches!(sha.len(), 40 | 64) || !sha.bytes().all(|byte| byte.is_ascii_hexdigit()) {
return Err(parse_shape_error());
}
Ok(json!({ "sha": sha.to_ascii_lowercase() }))
}

/// Drafts are dropped (an anonymous reader never sees them). The newest
/// publication comes first; equal timestamps fall back to the tag so the
/// order does not depend on GitHub's.
fn normalize_release_list(value: Value) -> Result<Value, CoreError> {
let mut releases = Vec::new();
for value in value.as_array().ok_or_else(parse_shape_error)? {
let object = object(value)?;
if object.get("draft").and_then(Value::as_bool) == Some(true) {
continue;
}
let optional = |key: &str| {
object
.get(key)
.and_then(Value::as_str)
.filter(|value| !value.trim().is_empty())
.map(str::to_string)
};
releases.push(GitHubRelease {
tag_name: text(object, "tag_name")?.to_string(),
name: optional("name"),
body: optional("body").unwrap_or_default(),
published_at: optional("published_at"),
prerelease: object
.get("prerelease")
.and_then(Value::as_bool)
.unwrap_or(false),
url: text(object, "html_url")?.to_string(),
});
}
releases.sort_by(|left, right| {
right
.published_at
.cmp(&left.published_at)
.then_with(|| right.tag_name.cmp(&left.tag_name))
});
Ok(serde_json::to_value(releases).expect("release list encodes"))
}

fn normalize_file_list(value: Value) -> Result<Value, CoreError> {
let array = value.as_array().ok_or_else(parse_shape_error)?;
let mut files = array
Expand Down
Loading
Loading