Skip to content
Closed
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
90 changes: 90 additions & 0 deletions remediation/workflow/maintainedactions/getlatestrelease.go
Original file line number Diff line number Diff line change
Expand Up @@ -64,3 +64,93 @@ func GetLatestRelease(ownerRepo string) (string, error) {

return getMajorVersion(release.GetTagName()), nil
}

// GetMajorTagFromSHA finds the major version tag (e.g., "v5") on ownerRepo
// whose commit matches the given SHA, by listing all tags with prefix "tags/v".
// Returns ("", nil) if no matching tag is found.
func GetMajorTagFromSHA(ownerRepo, sha string) (string, error) {
splitOnSlash := strings.Split(ownerRepo, "/")
if len(splitOnSlash) < 2 {
return "", fmt.Errorf("invalid owner/repo format: %s", ownerRepo)
}
owner := splitOnSlash[0]
repo := splitOnSlash[1]

ctx := context.Background()
client := github.NewClient(nil)

token := os.Getenv("PAT")
if token != "" {
ts := oauth2.StaticTokenSource(&oauth2.Token{AccessToken: token})
client = github.NewClient(oauth2.NewClient(ctx, ts))
}

refs, _, err := client.Git.ListMatchingRefs(ctx, owner, repo, &github.ReferenceListOptions{
Ref: "tags/v",
})
if err != nil {
return "", err
}

fmt.Println("len refs:", len(refs))

for _, ref := range refs {
var refSHA string
if ref.GetObject().GetType() == "commit" {
refSHA = ref.GetObject().GetSHA()
} else {
// annotated tag — dereference to get the commit SHA
refSHA, _, err = client.Repositories.GetCommitSHA1(ctx, owner, repo, ref.GetRef(), "")
if err != nil {
continue
}
}
if refSHA == sha {
tag := strings.TrimPrefix(ref.GetRef(), "refs/tags/")
return getMajorVersion(tag), nil
}
}
return "", nil
}

// GetMajorTagIfExists checks whether ownerRepo has a tag exactly matching
// majorVersion (e.g., "v5"). Returns (majorVersion, true, nil) when the tag
// exists, ("", false, nil) when it is absent (404), and ("", false, err) for
// unexpected API failures.
func GetMajorTagIfExists(ownerRepo, majorVersion string) (string, bool, error) {
splitOnSlash := strings.Split(ownerRepo, "/")
if len(splitOnSlash) < 2 {
return "", false, fmt.Errorf("invalid owner/repo format: %s", ownerRepo)
}
owner := splitOnSlash[0]
repo := splitOnSlash[1]

ctx := context.Background()
client := github.NewClient(nil)

_, resp, err := client.Git.GetRef(ctx, owner, repo, "refs/tags/"+majorVersion)
if err == nil {
return majorVersion, true, nil
}
if resp != nil && resp.StatusCode == 404 {
return "", false, nil
}

// First attempt failed for a non-404 reason — retry with token.
token := os.Getenv("PAT")
if token == "" {
return "", false, nil
}
ts := oauth2.StaticTokenSource(&oauth2.Token{AccessToken: token})
tc := oauth2.NewClient(ctx, ts)
client = github.NewClient(tc)

_, resp, err = client.Git.GetRef(ctx, owner, repo, "refs/tags/"+majorVersion)
if err == nil {
return majorVersion, true, nil
}
if resp != nil && resp.StatusCode == 404 {
return "", false, nil
}
return "", false, fmt.Errorf("failed to check tag %s on %s: %w", majorVersion, ownerRepo, err)
}
50 changes: 40 additions & 10 deletions remediation/workflow/maintainedactions/maintainedActions.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (

"github.com/step-security/secure-repo/remediation/workflow/metadata"
"github.com/step-security/secure-repo/remediation/workflow/permissions"
"github.com/step-security/secure-repo/remediation/workflow/pin"
"gopkg.in/yaml.v3"
)

Expand Down Expand Up @@ -76,19 +77,33 @@ func ReplaceActions(inputYaml string, customerMaintainedActions map[string]strin
continue
}
for stepIdx, step := range job.Steps {
// fmt.Println("step ", step.Uses)
actionName := strings.Split(step.Uses, "@")[0]
if newAction, ok := actionMap[actionName]; ok {
latestVersion, err := GetLatestRelease(newAction)
if err != nil {
return inputYaml, updated, fmt.Errorf("unable to get latest release: %v", err)
parts := strings.SplitN(step.Uses, "@", 2)
if len(parts) < 2 || parts[1] == "" {
continue
}
ref := parts[1]
var version string
if len(ref) == 40 && pin.IsAllHex(ref) {
version, err = GetMajorTagFromSHA(actionName, ref)
if err != nil || version == "" {
continue
}
} else {
version = ref
}
majorVersion := getMajorVersion(version)
tag, exists, err := GetMajorTagIfExists(newAction, majorVersion)
if err != nil || !exists {
continue
}
replacements = append(replacements, replacement{
jobName: jobName,
stepIdx: stepIdx,
newAction: newAction,
originalAction: step.Uses,
latestVersion: latestVersion,
latestVersion: tag,
})
}
}
Expand All @@ -100,16 +115,31 @@ func ReplaceActions(inputYaml string, customerMaintainedActions map[string]strin
if len(step.Uses) > 0 {
actionName := strings.Split(step.Uses, "@")[0]
if newAction, ok := actionMap[actionName]; ok {
latestVersion, err := GetLatestRelease(newAction)
if err != nil {
return inputYaml, updated, fmt.Errorf("unable to get latest release: %v", err)
parts := strings.SplitN(step.Uses, "@", 2)
if len(parts) < 2 || parts[1] == "" {
continue
}
ref := parts[1]
var version string
if len(ref) == 40 && pin.IsAllHex(ref) {
version, err = GetMajorTagFromSHA(actionName, ref)
if err != nil || version == "" {
continue
}
} else {
version = ref
}
majorVersion := getMajorVersion(version)
tag, exists, err := GetMajorTagIfExists(newAction, majorVersion)
if err != nil || !exists {
continue
}
replacements = append(replacements, replacement{
jobName: "composite", // special marker for composite actions
jobName: "composite",
stepIdx: stepIdx,
newAction: newAction,
originalAction: step.Uses,
latestVersion: latestVersion,
latestVersion: tag,
})
}
}
Expand Down
63 changes: 31 additions & 32 deletions remediation/workflow/maintainedactions/maintainedactions_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,38 +16,21 @@ func TestReplaceActions(t *testing.T) {
httpmock.Activate()
defer httpmock.DeactivateAndReset()

// Mock GitHub API responses for getting latest releases
httpmock.RegisterResponder("GET", "https://api.github.com/repos/step-security/action-semantic-pull-request/releases/latest",
httpmock.NewStringResponder(200, `{
"tag_name": "v5.5.5",
"name": "v5.5.5",
"body": "Release notes",
"created_at": "2023-01-01T00:00:00Z"
}`))

httpmock.RegisterResponder("GET", "https://api.github.com/repos/step-security/skip-duplicate-actions/releases/latest",
httpmock.NewStringResponder(200, `{
"tag_name": "v5.3.2",
"name": "v5.3.2",
"body": "Release notes",
"created_at": "2023-01-01T00:00:00Z"
}`))

httpmock.RegisterResponder("GET", "https://api.github.com/repos/step-security/git-restore-mtime-action/releases/latest",
httpmock.NewStringResponder(200, `{
"tag_name": "v2.1.0",
"name": "v2.1.0",
"body": "Release notes",
"created_at": "2023-01-01T00:00:00Z"
}`))

httpmock.RegisterResponder("GET", "https://api.github.com/repos/step-security/actions-cache/releases/latest",
httpmock.NewStringResponder(200, `{
"tag_name": "v1.0.0",
"name": "v1.0.0",
"body": "Release notes",
"created_at": "2023-01-01T00:00:00Z"
}`))
// Mock GitHub API responses for checking major version tags on forks
httpmock.RegisterResponder("GET", "https://api.github.com/repos/step-security/action-semantic-pull-request/git/ref/tags/v5",
httpmock.NewStringResponder(200, `{"ref":"refs/tags/v5","object":{"sha":"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa","type":"commit"}}`))

httpmock.RegisterResponder("GET", "https://api.github.com/repos/step-security/action-semantic-pull-request/git/ref/tags/v3",
httpmock.NewStringResponder(404, `{"message":"Not Found"}`))

httpmock.RegisterResponder("GET", "https://api.github.com/repos/step-security/skip-duplicate-actions/git/ref/tags/v5",
httpmock.NewStringResponder(200, `{"ref":"refs/tags/v5","object":{"sha":"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb","type":"commit"}}`))

httpmock.RegisterResponder("GET", "https://api.github.com/repos/step-security/git-restore-mtime-action/git/ref/tags/v1",
httpmock.NewStringResponder(200, `{"ref":"refs/tags/v1","object":{"sha":"cccccccccccccccccccccccccccccccccccccccc","type":"commit"}}`))

httpmock.RegisterResponder("GET", "https://api.github.com/repos/step-security/actions-cache/git/ref/tags/v1",
httpmock.NewStringResponder(200, `{"ref":"refs/tags/v1","object":{"sha":"dddddddddddddddddddddddddddddddddddddddd","type":"commit"}}`))

tests := []struct {
name string
Expand Down Expand Up @@ -84,6 +67,13 @@ func TestReplaceActions(t *testing.T) {
wantUpdated: true,
wantErr: false,
},
{
name: "no replacement when fork does not have matching major version",
inputFile: "noMatchingMajorVersion.yml",
outputFile: "noMatchingMajorVersion.yml",
wantUpdated: false,
wantErr: false,
},
}

for _, tt := range tests {
Expand Down Expand Up @@ -125,3 +115,12 @@ func TestReplaceActions(t *testing.T) {
})
}
}

func TestSome(t *testing.T) {

version, err := GetMajorTagFromSHA("tj-actions/changed-files", "00f80efd45353091691a96565de08f4f50c685f8")
if err != nil {
t.Errorf("GetMajorTagFromSHA() error = %v", err)
}
t.Logf("GetMajorTagFromSHA() version = %v", version)
}
8 changes: 4 additions & 4 deletions remediation/workflow/pin/pinactions.go
Original file line number Diff line number Diff line change
Expand Up @@ -228,20 +228,20 @@ func isAbsolute(ref string) bool {
parts := strings.Split(ref, "@")
last := parts[len(parts)-1]

if len(last) == 40 && isAllHex(last) {
if len(last) == 40 && IsAllHex(last) {
return true
}

if len(last) == 71 && last[:6] == "sha256" && isAllHex(last[7:]) {
if len(last) == 71 && last[:6] == "sha256" && IsAllHex(last[7:]) {
return true
}

return false
}

// isAllHex returns true if the given string is all hex characters, false
// IsAllHex returns true if the given string is all hex characters, false
// otherwise.
func isAllHex(s string) bool {
func IsAllHex(s string) bool {
for _, ch := range s {
if (ch < '0' || ch > '9') && (ch < 'a' || ch > 'f') && (ch < 'A' || ch > 'F') {
return false
Expand Down
Loading
Loading