1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
use super::Error as GithubError;
use super::Registry;
use super::responses::{CommitResponse, GitRef, GitTagResponse};
use crate::domain::action::identity::{ActionId, CommitSha};
use crate::domain::action::uses_ref::RefType;
/// Base URL for the GitHub REST API.
pub(super) const GITHUB_API_BASE: &str = "https://api.github.com";
/// The ref endpoint for `tag` in `base_repo`, an `owner/repo` slug.
fn tag_ref_url(base_repo: &str, tag: &str) -> String {
format!("{GITHUB_API_BASE}/repos/{base_repo}/git/ref/tags/{tag}")
}
#[expect(
clippy::multiple_inherent_impl,
reason = "Registry's impl is split across files to stay within the per-file size budget"
)]
impl Registry {
/// Resolve a ref (tag, branch, or commit) to a full commit SHA and detect the ref type.
///
/// Returns a tuple of (`sha`, `ref_type`) by tracking which API path succeeded.
///
/// # Examples
///
/// - `resolve_ref("actions/checkout", "v4") -> ("abc123...", RefType::Tag)`
/// - `resolve_ref("actions/checkout", "main") -> ("def456...", RefType::Branch)`
/// - `resolve_ref("actions/checkout", "abc123") -> ("abc123...", RefType::Commit)`
/// - `resolve_ref("github/codeql-action/upload-sarif", "v4") -> ("abc123...", RefType::Tag)`
///
/// # Errors
///
/// Returns an error if the API request fails or returns a non-success status.
pub fn resolve_ref(
&self,
owner_repo: &str,
ref_name: &str,
) -> Result<(String, Option<RefType>), GithubError> {
// If it already looks like a full SHA (40 hex chars), return it as a Commit
if CommitSha::is_valid(ref_name) {
return Ok((ref_name.to_owned(), Some(RefType::Commit)));
}
// Handle subpath actions (e.g., "github/codeql-action/upload-sarif")
// Extract just the owner/repo part (first two path segments)
let base_repo = owner_repo.split('/').take(2).collect::<Vec<_>>().join("/");
// Try to resolve as a tag first
if let Ok(sha) = self.fetch_ref_commit(&tag_ref_url(&base_repo, ref_name)) {
// Check if this tag has a GitHub Release
if self
.fetch_release_date(&base_repo, ref_name)
.ok()
.flatten()
.is_some()
{
return Ok((sha, Some(RefType::Release)));
}
return Ok((sha, Some(RefType::Tag)));
}
// Try to resolve as a branch
let branch_url = format!("{GITHUB_API_BASE}/repos/{base_repo}/git/ref/heads/{ref_name}");
if let Ok(sha) = self.fetch_ref_commit(&branch_url) {
return Ok((sha, Some(RefType::Branch)));
}
// Try to resolve as a direct commit
let commit_url = format!("{GITHUB_API_BASE}/repos/{base_repo}/commits/{ref_name}");
self.fetch_commit_sha(&commit_url)
.map(|sha| (sha, Some(RefType::Commit)))
}
/// Fetch the commit SHA for a git ref, dereferencing annotated tags if needed.
pub(super) fn fetch_ref_commit(&self, url: &str) -> Result<String, GithubError> {
let git_ref: GitRef = self.get_json(url, "ref")?;
// For annotated tags, the object is a tag object, not a commit.
// Dereference via the git tags API to get the underlying commit SHA.
if git_ref.object.object_type == "tag" {
let tag_url = format!(
"{GITHUB_API_BASE}/repos/{}/git/tags/{}",
// Extract owner/repo from the ref URL
url.strip_prefix(&format!("{GITHUB_API_BASE}/repos/"))
.and_then(|s| {
let mut split = s.splitn(3, '/');
let owner = split.next()?;
let repo = split.next()?;
Some(format!("{owner}/{repo}"))
})
.unwrap_or_default(),
git_ref.object.sha
);
let tag_data: GitTagResponse = self.get_json(&tag_url, "tag dereference")?;
return Ok(tag_data.object.sha);
}
Ok(git_ref.object.sha)
}
/// Fetch the SHA from a commit endpoint URL.
pub(super) fn fetch_commit_sha(&self, url: &str) -> Result<String, GithubError> {
let commit: CommitResponse = self.get_json(url, "commit")?;
Ok(commit.sha)
}
}
/// Resolves a tag to the commit it currently points at.
///
/// Implemented by [`GitTags`] (real) and `FakeTags` (tests).
pub trait TagResolver {
/// The commit `tag` points at in `action`'s repository, following annotated tags
/// through to their target.
///
/// An `Err` means the tag's target could not be established — never a guess, because a
/// caller that mistook "could not look" for "unchanged" would report a false clean.
///
/// # Errors
///
/// Returns [`GithubError`] if the request fails, is rejected, or the tag does not exist.
fn tag_commit(&self, action: &ActionId, tag: &str) -> Result<CommitSha, GithubError>;
}
/// Resolves tags against the live GitHub API.
pub struct GitTags {
/// The client carrying the token and HTTP configuration.
registry: Registry,
}
impl GitTags {
/// Wrap a registry as a tag resolver.
#[must_use]
pub const fn new(registry: Registry) -> Self {
Self { registry }
}
}
impl TagResolver for GitTags {
fn tag_commit(&self, action: &ActionId, tag: &str) -> Result<CommitSha, GithubError> {
// Tags belong to the repository, so a subpath action resolves against its root.
self.registry
.fetch_ref_commit(&tag_ref_url(action.base_repo().as_str(), tag))
.map(CommitSha::from)
}
}
/// The [`TagResolver`] test double.
///
/// Inline because `src/infra/github/` is at its 8-file budget.
#[cfg(test)]
pub(crate) mod fake {
use super::{ActionId, CommitSha, GithubError, TagResolver, tag_ref_url};
use std::cell::RefCell;
use std::collections::HashMap;
/// Answers tag lookups from memory without issuing any request.
pub struct FakeTags {
/// What an unseeded lookup returns; `None` fails it.
fallback: Option<String>,
/// Commit each `(repository, tag)` resolves to, overriding `fallback`.
targets: HashMap<(String, String), String>,
/// Every `(repository, tag)` asked for, in call order, so a test can prove a
/// skipped entry was never looked up.
seen: RefCell<Vec<(String, String)>>,
}
impl FakeTags {
/// A resolver whose every tag points at `sha` — no tag has moved.
#[must_use]
pub fn resolving(sha: &str) -> Self {
Self::from_fallback(Some(sha.to_owned()))
}
/// A resolver whose every lookup fails.
#[must_use]
pub fn failing() -> Self {
Self::from_fallback(None)
}
/// Shared constructor.
fn from_fallback(fallback: Option<String>) -> Self {
Self {
fallback,
targets: HashMap::new(),
seen: RefCell::new(Vec::new()),
}
}
/// Seed the commit `tag` resolves to in `repo`.
#[must_use]
pub fn with(mut self, repo: &str, tag: &str, sha: &str) -> Self {
self.targets
.insert((repo.to_owned(), tag.to_owned()), sha.to_owned());
self
}
/// Every `(repository, tag)` lookup this resolver was asked for.
#[must_use]
pub fn lookups(&self) -> Vec<(String, String)> {
self.seen.borrow().clone()
}
}
impl TagResolver for FakeTags {
fn tag_commit(&self, action: &ActionId, tag: &str) -> Result<CommitSha, GithubError> {
// Keyed on the repository root, as the real adapter is.
let key = (action.base_repo().as_str().to_owned(), tag.to_owned());
self.seen.borrow_mut().push(key.clone());
self.targets
.get(&key)
.or(self.fallback.as_ref())
.map(|sha| CommitSha::from(sha.as_str()))
.ok_or_else(|| GithubError::NotFound {
url: tag_ref_url(&key.0, tag),
})
}
}
}
#[cfg(test)]
#[expect(
clippy::unwrap_used,
reason = "tests use unwrap, indexing, and other patterns freely"
)]
mod tests {
use super::Registry as GithubRegistry;
use super::tag_ref_url;
use crate::domain::action::uses_ref::RefType;
use crate::domain::resolution::VersionRegistry as _;
#[test]
fn full_sha_passthrough() {
let client = GithubRegistry::new(None).unwrap();
let sha = "a1b2c3d4e5f6789012345678901234567890abcd";
let (result_sha, result_type) = client.resolve_ref("actions/checkout", sha).unwrap();
assert_eq!(result_sha, sha);
assert_eq!(result_type, Some(RefType::Commit));
}
#[test]
fn subpath_action_extracts_base_repo() {
let client = GithubRegistry::new(None).unwrap();
let sha = "a1b2c3d4e5f6789012345678901234567890abcd";
// Should work with subpath actions
let (result_sha, result_type) = client
.resolve_ref("github/codeql-action/upload-sarif", sha)
.unwrap();
assert_eq!(result_sha, sha);
assert_eq!(result_type, Some(RefType::Commit));
}
#[test]
fn version_resolver_preserves_commit_when_date_is_unavailable() {
// Port zero refuses connections; the explicit proxy prevents the optional date
// lookup from reaching GitHub or depending on this machine's proxy settings.
let client = GithubRegistry {
client: reqwest::blocking::Client::builder()
.no_proxy()
.proxy(reqwest::Proxy::all("http://127.0.0.1:0").unwrap())
.timeout(std::time::Duration::from_secs(1))
.build()
.unwrap(),
token: None,
};
let id = crate::domain::action::identity::ActionId::from("actions/checkout");
let sha_version = crate::domain::action::identity::Version::from(
"a1b2c3d4e5f6789012345678901234567890abcd",
);
let result = client.lookup_sha(&id, &sha_version).unwrap();
assert_eq!(result.sha.as_str(), sha_version.as_str());
assert_eq!(result.ref_type, Some(RefType::Commit));
assert!(result.date.as_str().is_empty());
}
#[test]
fn tag_url_targets_the_repository_root() {
for (action, tag, url) in [
(
"actions/checkout",
"v4.2.1",
"https://api.github.com/repos/actions/checkout/git/ref/tags/v4.2.1",
),
(
"github/codeql-action/upload-sarif",
"v3",
"https://api.github.com/repos/github/codeql-action/git/ref/tags/v3",
),
] {
let id = crate::domain::action::identity::ActionId::from(action);
assert_eq!(tag_ref_url(id.base_repo().as_str(), tag), url);
}
}
}