-
Notifications
You must be signed in to change notification settings - Fork 445
Expand file tree
/
Copy pathaction_resolver.go
More file actions
301 lines (266 loc) · 12.4 KB
/
Copy pathaction_resolver.go
File metadata and controls
301 lines (266 loc) · 12.4 KB
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
297
298
299
300
301
package workflow
import (
"context"
"fmt"
"maps"
"strings"
"time"
"github.com/github/gh-aw/pkg/actionpins"
"github.com/github/gh-aw/pkg/gitutil"
"github.com/github/gh-aw/pkg/logger"
"github.com/github/gh-aw/pkg/semverutil"
)
var resolverLog = logger.New("workflow:action_resolver")
// ActionResolver handles resolving action SHAs using GitHub CLI
type ActionResolver struct {
cache *ActionCache
failedResolutions map[string]bool // tracks failed resolution attempts in current run (key: "repo@version")
usedCacheKeys map[string]bool // tracks cache keys that were hit or newly set during this run
}
// NewActionResolver creates a new action resolver
func NewActionResolver(cache *ActionCache) *ActionResolver {
return &ActionResolver{
cache: cache,
failedResolutions: make(map[string]bool),
usedCacheKeys: make(map[string]bool),
}
}
// GetUsedCacheKeys returns the set of cache keys (in "repo@version" format) that
// were successfully resolved from the cache or written to the cache during this run.
// These represent the action pins actually referenced by the compiled workflows.
func (r *ActionResolver) GetUsedCacheKeys() map[string]bool {
keys := make(map[string]bool, len(r.usedCacheKeys))
maps.Copy(keys, r.usedCacheKeys)
return keys
}
// MarkCacheKeyAsUsed explicitly marks a cache key as used during this compilation run.
// This is useful for compiler-generated actions that aren't resolved through ResolveSHA.
func (r *ActionResolver) MarkCacheKeyAsUsed(cacheKey string) {
r.usedCacheKeys[cacheKey] = true
resolverLog.Printf("Marked cache key as used: %s", cacheKey)
}
// MarkCompilerGeneratedActionsAsUsed scans the cache for any entries matching
// compiler-generated action repos and marks them as used. This ensures that actions
// embedded in generated YAML (e.g., actions/cache, actions/checkout) aren't pruned
// as orphaned entries even if they weren't resolved through ResolveSHA.
//
// This is called after workflow compilation to handle actions that are hardcoded
// in code generators (cache.go, checkout_step_generator.go, etc.) rather than
// resolved from markdown workflows.
func (r *ActionResolver) MarkCompilerGeneratedActionsAsUsed() {
if r.cache == nil {
return
}
// List of action repos that are commonly generated by the compiler
compilerGeneratedRepos := []string{
"actions/cache",
"actions/cache/restore",
"actions/cache/save",
"actions/checkout",
"actions/github-script",
"actions/upload-artifact",
"actions/download-artifact",
"actions/create-github-app-token",
"github/codeql-action/upload-sarif",
}
marked := 0
for _, repo := range compilerGeneratedRepos {
if cacheKey, _, found := r.cache.FindAnyEntryForRepo(repo); found {
if !r.usedCacheKeys[cacheKey] {
r.usedCacheKeys[cacheKey] = true
marked++
resolverLog.Printf("Marked compiler-generated action as used: %s", cacheKey)
}
}
}
if marked > 0 {
resolverLog.Printf("Marked %d compiler-generated action(s) as used", marked)
}
}
// ResolveSHA resolves the SHA for a given action@version using GitHub CLI
// Returns the SHA and an error if resolution fails
func (r *ActionResolver) ResolveSHA(ctx context.Context, repo, version string) (string, error) {
resolverLog.Printf("Resolving SHA for action: %s@%s", repo, version)
// Create a cache key for tracking failed resolutions and cache lookups.
// Computed once here and reused below to avoid duplicate allocation.
cacheKey := formatActionCacheKey(repo, version)
r.usedCacheKeys[cacheKey] = true
// Check if we've already failed to resolve this action in this run
if r.failedResolutions[cacheKey] {
resolverLog.Printf("Skipping resolution for %s@%s: already failed in this run", repo, version)
return "", fmt.Errorf("previously failed to resolve %s@%s in this compilation run", repo, version)
}
// Check cache first using the pre-computed key to avoid a second key allocation.
if sha, found := r.cache.GetByCacheKey(cacheKey); found {
resolverLog.Printf("Cache hit for %s@%s: %s", repo, version, sha)
return sha, nil
}
resolverLog.Printf("Cache miss for %s@%s, checking embedded action pins", repo, version)
// Check embedded action pins for a semver-compatible version before making
// a network call. Note: we intentionally do NOT call r.cache.Set() for
// embedded pins — they are always available in memory, and writing to the
// on-disk cache would create root-owned files inside Docker containers
// (e.g. the Alpine CI test), preventing cleanup by the host.
if sha, found := lookupEmbeddedActionPin(repo, version); found {
return sha, nil
}
resolverLog.Printf("No embedded pin for %s@%s, querying GitHub API", repo, version)
resolverLog.Printf("This may take a moment as we query GitHub API at /repos/%s/git/ref/tags/%s", gitutil.ExtractBaseRepo(repo), version)
// Resolve using GitHub CLI
sha, err := r.resolveFromGitHub(ctx, repo, version)
if err != nil {
resolverLog.Printf("Failed to resolve %s@%s: %v", repo, version, err)
// Mark this resolution as failed for this compilation run
r.failedResolutions[cacheKey] = true
resolverLog.Printf("Marked %s as failed, will not retry in this run", cacheKey)
return "", err
}
resolverLog.Printf("Successfully resolved %s@%s to SHA: %s", repo, version, sha)
// Cache the result
resolverLog.Printf("Caching result: %s@%s → %s", repo, version, sha)
r.cache.Set(repo, version, sha)
return sha, nil
}
// lookupEmbeddedActionPin returns the pinned SHA for repo@version from the
// embedded action pin set. It returns ("", false) if no matching pin is found.
// The embedded pins are the source-of-truth for known versions and are always
// available without network access, avoiding a ~1s gh-api subprocess for any
// action covered by the embedded pin set.
func lookupEmbeddedActionPin(repo, version string) (string, bool) {
requested := semverutil.EnsureVPrefix(version)
requestedVer := semverutil.ParseVersion(requested)
requestedIsPrecise := requestedVer != nil && requestedVer.IsPreciseVersion()
for _, pin := range actionpins.GetActionPinsByRepo(repo) {
pinVersion := semverutil.EnsureVPrefix(pin.Version)
if requestedIsPrecise {
if pinVersion != requested {
continue
}
} else if !semverutil.IsCompatible(pinVersion, requested) {
continue
}
resolverLog.Printf("Embedded pin hit for %s@%s → %s (%s)", repo, version, pin.SHA, pin.Version)
return pin.SHA, true
}
return "", false
}
// ParseTagRefTSV parses the tab-separated output from the GitHub API
// `[.object.sha, .object.type] | @tsv` jq expression.
// It returns the object SHA and type, or an error if the output is malformed.
// This is a standalone helper so that the parsing logic can be unit-tested
// independently of network calls.
func ParseTagRefTSV(line string) (sha, objType string, err error) {
line = strings.TrimSpace(line)
parts := strings.SplitN(line, "\t", 2)
if len(parts) != 2 || parts[0] == "" || parts[1] == "" {
return "", "", fmt.Errorf("unexpected format: %q", line)
}
sha = parts[0]
objType = parts[1]
if len(sha) != 40 || !gitutil.IsHexString(sha) {
return "", "", fmt.Errorf("invalid SHA format: expected 40 hex characters, got %d (%s)", len(sha), sha)
}
return sha, objType, nil
}
// resolveFromGitHub uses gh CLI to resolve the SHA for an action@version
func (r *ActionResolver) resolveFromGitHub(ctx context.Context, repo, version string) (string, error) {
// Extract base repository (for actions like "github/codeql-action/upload-sarif")
baseRepo := gitutil.ExtractBaseRepo(repo)
resolverLog.Printf("Extracted base repository: %s from %s", baseRepo, repo)
// Use gh api to get the git ref for the tag
// API endpoint: GET /repos/{owner}/{repo}/git/ref/tags/{tag}
apiPath := fmt.Sprintf("/repos/%s/git/ref/tags/%s", baseRepo, version)
resolverLog.Printf("Querying GitHub API: %s", apiPath)
// Derive a timeout context from the caller's context for the initial tag lookup.
// The caller's ctx is preserved separately so that each annotated-tag peel
// operation can also derive a fresh 30-second timeout from it (rather than from
// the already-running callCtx, which may have far less than 30 seconds remaining).
callCtx, cancel := context.WithTimeout(ctx, 30*time.Second)
defer cancel()
// Fetch both SHA and object type to detect annotated tags.
// Annotated tags have type "tag" and their SHA points to the tag object,
// not the underlying commit. We must peel to get the commit SHA.
cmd := ExecGHContext(callCtx, "api", apiPath, "--jq", "[.object.sha, .object.type] | @tsv")
ForceGHHostEnv(cmd, "github.com")
output, err := cmd.Output()
if err != nil {
return "", fmt.Errorf("failed to resolve %s@%s: %w", repo, version, err)
}
sha, objType, err := ParseTagRefTSV(string(output))
if err != nil {
return "", fmt.Errorf("failed to parse API response for %s@%s: %w", repo, version, err)
}
// Annotated tags (and chained tag objects) point to a tag object rather than
// directly to a commit. Iteratively peel until we reach a non-tag object so
// that emitted action pins use the stable underlying commit SHA rather than a
// mutable tag object SHA (which changes when the tag is re-created).
const maxTagPeelDepth = 10
for depth := 0; objType == "tag"; depth++ {
if depth >= maxTagPeelDepth {
return "", fmt.Errorf("failed to resolve %s@%s: exceeded max tag peel depth %d", repo, version, maxTagPeelDepth)
}
resolverLog.Printf("Detected annotated tag for %s@%s (depth %d, tag object SHA: %s), peeling to underlying object", repo, version, depth, sha)
// Each peel gets its own fresh 30-second timeout derived from the original
// caller context (ctx), not from callCtx, so we don't accidentally shrink
// the budget for subsequent peels. peelTagObject defers cancel within its
// own function scope to satisfy resource-lifecycle lint rules.
sha, objType, err = peelTagObject(ctx, baseRepo, repo, version, sha)
if err != nil {
return "", err
}
}
resolverLog.Printf("Resolved %s@%s to %s SHA: %s", repo, version, objType, sha)
return sha, nil
}
// peelTagObject resolves a single annotated-tag object to its underlying object by
// querying the GitHub API. It is called iteratively for chained tag objects.
// The timeout context is created and immediately deferred within this function so
// that cancel is always called when the function returns (not deferred inside a loop).
func peelTagObject(ctx context.Context, baseRepo, repo, version, sha string) (newSHA, objType string, err error) {
tagPath := fmt.Sprintf("/repos/%s/git/tags/%s", baseRepo, sha)
// Each peel gets a fresh 30-second timeout derived from the original caller
// context so we don't accidentally shrink the budget across iterations.
peelCtx, peelCancel := context.WithTimeout(ctx, 30*time.Second)
defer peelCancel()
cmd := ExecGHContext(peelCtx, "api", tagPath, "--jq", "[.object.sha, .object.type] | @tsv")
ForceGHHostEnv(cmd, "github.com")
output, peelErr := cmd.Output()
if peelErr != nil {
return "", "", fmt.Errorf("failed to peel annotated tag %s@%s: %w", repo, version, peelErr)
}
newSHA, objType, err = ParseTagRefTSV(string(output))
if err != nil {
return "", "", fmt.Errorf("failed to parse peeled tag API response for %s@%s: %w", repo, version, err)
}
return newSHA, objType, nil
}
// ResolveGhAwRef resolves a branch, tag, or SHA ref in the github/gh-aw
// repository to its full 40-character commit SHA.
// If ref is already a valid full SHA it is returned unchanged.
// Otherwise the GitHub API commits endpoint is queried, which accepts
// branch names, tag names, and SHAs.
func ResolveGhAwRef(ctx context.Context, ref string) (string, error) {
if gitutil.IsValidFullSHA(ref) {
resolverLog.Printf("--gh-aw-ref %q is already a full SHA, no resolution needed", ref)
return ref, nil
}
resolverLog.Printf("Resolving --gh-aw-ref %q to commit SHA via GitHub API", ref)
apiPath := "/repos/github/gh-aw/commits/" + ref
callCtx, cancel := context.WithTimeout(ctx, 30*time.Second)
defer cancel()
cmd := ExecGHContext(callCtx, "api", apiPath, "--jq", ".sha")
output, err := cmd.CombinedOutput()
if err != nil {
msg := strings.TrimSpace(string(output))
if msg != "" {
return "", fmt.Errorf("failed to resolve gh-aw ref %q to SHA: %s: %w", ref, msg, err)
}
return "", fmt.Errorf("failed to resolve gh-aw ref %q to SHA: %w", ref, err)
}
sha := strings.TrimSpace(string(output))
if !gitutil.IsValidFullSHA(sha) {
return "", fmt.Errorf("unexpected response resolving gh-aw ref %q: got %q (expected 40-char hex SHA)", ref, sha)
}
resolverLog.Printf("Resolved --gh-aw-ref %q to commit SHA %s", ref, sha)
return sha, nil
}