Skip to content

Commit db5c641

Browse files
gh-aw-botCopilot
andauthored
Track computed secret references safely
Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
1 parent 3c4e3c9 commit db5c641

17 files changed

Lines changed: 303 additions & 9 deletions

‎actions/setup/js/redact_secrets.cjs‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -748,6 +748,11 @@ async function main({ prepareForCustomMasking = false, additionalDirectories = [
748748
secretValues.push(secretValue.trim());
749749
}
750750
}
751+
for (const [name, value] of Object.entries(process.env)) {
752+
if (name.startsWith("GH_AW_DYNAMIC_SECRET_VALUE_") && value && value.trim() !== "") {
753+
secretValues.push(value.trim());
754+
}
755+
}
751756

752757
// Extract MCP gateway bearer tokens from known config files and add them to
753758
// the redaction list. The gateway token has no fixed prefix so it cannot be

‎actions/setup/js/redact_secrets.test.cjs‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,22 @@ const { persistDetectionMasks } = require("./detection_mask_state.cjs");
3131
const redactScript = fs.readFileSync(path.join(__dirname, "redact_secrets.cjs"), "utf8");
3232
describe("redact_secrets.cjs", () => {
3333
let tempDir, ambientPathsSpy;
34+
it("redacts dynamically selected secret values from artifacts", async () => {
35+
const { main } = require("./redact_secrets.cjs");
36+
const secret = "synthetic-dynamic-secret-value";
37+
vi.stubEnv("GH_AW_DYNAMIC_SECRET_VALUE_0", secret);
38+
const directory = path.join(process.env.RUNNER_TEMP, "gh-aw");
39+
fs.mkdirSync(directory, { recursive: true });
40+
const file = path.join(directory, "dynamic-secret.json");
41+
fs.writeFileSync(file, JSON.stringify({ token: secret }));
42+
43+
await main();
44+
45+
expect(fs.readFileSync(file, "utf8")).not.toContain(secret);
46+
expect(JSON.parse(fs.readFileSync(file, "utf8"))).toEqual({ token: "***REDACTED***" });
47+
expect(mockCore.setFailed).not.toHaveBeenCalled();
48+
});
49+
3450
it("sanitizes detection results, copied firewall logs and late-created accounting files", async () => {
3551
const { main } = require("./redact_secrets.cjs");
3652
const secret = "synthetic-detection-private-value";

‎pkg/workflow/compiler.go‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -688,6 +688,7 @@ func (c *Compiler) CompileWorkflowData(workflowData *WorkflowData, markdownPath
688688
if enforceErr := EnforceSafeUpdate(SafeUpdateOptions{
689689
Manifest: oldManifest,
690690
SecretNames: bodySecrets,
691+
DynamicSecretReferences: workflowData.dynamicSecretReferences,
691692
ActionRefs: bodyActions,
692693
CurrentRedirect: workflowData.Redirect,
693694
PullRequestTransition: prTransition,

‎pkg/workflow/compiler_workflow_call.go‎

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -227,6 +227,31 @@ type workflowCallSecretEntry struct {
227227
Required bool `yaml:"required"`
228228
}
229229

230+
func workflowCallSecretNames(onSection string) []string {
231+
var onData map[string]any
232+
if err := yaml.Unmarshal([]byte(onSection), &onData); err != nil {
233+
return nil
234+
}
235+
on, ok := onData["on"].(map[string]any)
236+
if !ok {
237+
return nil
238+
}
239+
workflowCall, ok := on["workflow_call"].(map[string]any)
240+
if !ok {
241+
return nil
242+
}
243+
secrets, ok := workflowCall["secrets"].(map[string]any)
244+
if !ok {
245+
return nil
246+
}
247+
names := make([]string, 0, len(secrets))
248+
for name := range secrets {
249+
names = append(names, name)
250+
}
251+
sort.Strings(names)
252+
return names
253+
}
254+
230255
// injectWorkflowCallSecretsSection adds on.workflow_call.secrets declarations for secrets
231256
// used by the workflow, so that callers can pass them explicitly instead of using
232257
// secrets: inherit. GITHUB_TOKEN is excluded because it is automatically provided by

‎pkg/workflow/compiler_workflow_call_test.go‎

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -473,3 +473,60 @@ func TestInjectWorkflowCallSecretsSection(t *testing.T) {
473473
})
474474
}
475475
}
476+
477+
func TestWorkflowCallDynamicSecretSelectionRequiresExplicitBoundedNames(t *testing.T) {
478+
t.Parallel()
479+
directory := testutil.TempDir(t, "workflow-call-dynamic-secret-test")
480+
workflow := `---
481+
on:
482+
workflow_call:
483+
engine: copilot
484+
steps:
485+
- name: Use computed secret
486+
env:
487+
SELECTED_SECRET: "${{ secrets[vars.SECRET_NAME] }}"
488+
run: echo "using secret"
489+
---
490+
Run the workflow.
491+
`
492+
path := filepath.Join(directory, "dynamic-secret.md")
493+
require.NoError(t, os.WriteFile(path, []byte(workflow), 0644))
494+
compiler := NewCompiler()
495+
data, err := compiler.ParseWorkflowFile(path)
496+
require.NoError(t, err)
497+
498+
_, _, _, err = compiler.generateYAML(data, path)
499+
require.ErrorContains(t, err, "explicitly declared on.workflow_call.secrets names")
500+
}
501+
502+
func TestWorkflowCallDynamicSecretSelectionIsInventoriedAndRedacted(t *testing.T) {
503+
t.Parallel()
504+
directory := testutil.TempDir(t, "workflow-call-dynamic-secret-inventory-test")
505+
workflow := `---
506+
on:
507+
workflow_call:
508+
secrets:
509+
DEPLOY_TOKEN:
510+
required: false
511+
engine: copilot
512+
steps:
513+
- name: Use computed secret
514+
env:
515+
SELECTED_SECRET: "${{ secrets[vars.SECRET_NAME] }}"
516+
run: echo "using secret"
517+
---
518+
Run the workflow.
519+
`
520+
path := filepath.Join(directory, "dynamic-secret.md")
521+
require.NoError(t, os.WriteFile(path, []byte(workflow), 0644))
522+
compiler := NewCompiler()
523+
data, err := compiler.ParseWorkflowFile(path)
524+
require.NoError(t, err)
525+
526+
yamlOutput, secrets, _, err := compiler.generateYAML(data, path)
527+
require.NoError(t, err)
528+
require.Contains(t, secrets, "DEPLOY_TOKEN")
529+
require.Contains(t, yamlOutput, `GH_AW_DYNAMIC_SECRET_VALUE_0: "${{ secrets[vars.SECRET_NAME] }}"`)
530+
require.Contains(t, yamlOutput, "SECRET_DEPLOY_TOKEN: ${{ secrets.DEPLOY_TOKEN }}")
531+
require.Contains(t, yamlOutput, `"dynamic_secret_references":["sha256:`)
532+
}

‎pkg/workflow/compiler_yaml.go‎

Lines changed: 19 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -227,6 +227,10 @@ func (c *Compiler) generateWorkflowBody(yaml *strings.Builder, data *WorkflowDat
227227

228228
func (c *Compiler) generateYAML(data *WorkflowData, markdownPath string) (string, []string, []string, error) { //nolint:largefunc // Existing workflow YAML assembly keeps generation steps in order.
229229
compilerYamlLog.Printf("Generating YAML for workflow: %s", data.Name)
230+
data.dynamicSecretReferences = CollectDynamicSecretReferences(data.FrontmatterYAML)
231+
if len(data.dynamicSecretReferences) > 0 && hasWorkflowCallTrigger(data.On) && len(workflowCallSecretNames(data.On)) == 0 {
232+
return "", nil, nil, errors.New("computed secret selection in a workflow_call requires explicitly declared on.workflow_call.secrets names to bound the secret inventory")
233+
}
230234

231235
repoConfig, err := c.loadRepoConfig()
232236
if err != nil {
@@ -303,7 +307,10 @@ func (c *Compiler) generateYAML(data *WorkflowData, markdownPath string) (string
303307
}
304308
// Appending failures can replace a slice's backing array; generatedActionRefs
305309
// is a shared map and needs no copy-back.
306-
defer func() { sourceData.ActionResolutionFailures = data.ActionResolutionFailures }()
310+
defer func() {
311+
sourceData.ActionResolutionFailures = data.ActionResolutionFailures
312+
sourceData.dynamicSecretReferences = data.dynamicSecretReferences
313+
}()
307314

308315
// Build all jobs and validate dependencies
309316
if err := c.buildJobsAndValidate(data, markdownPath); err != nil {
@@ -348,6 +355,17 @@ func (c *Compiler) generateYAML(data *WorkflowData, markdownPath string) (string
348355
// These are returned to the caller so they can be used for safe update enforcement
349356
// without requiring a second scan of the full YAML content.
350357
secrets := CollectSecretReferences(bodyContent)
358+
data.dynamicSecretReferences = append(data.dynamicSecretReferences, CollectDynamicSecretReferences(bodyContent)...)
359+
slices.Sort(data.dynamicSecretReferences)
360+
data.dynamicSecretReferences = slices.Compact(data.dynamicSecretReferences)
361+
if len(data.dynamicSecretReferences) > 0 && hasWorkflowCallTrigger(data.On) && len(workflowCallSecretNames(data.On)) == 0 {
362+
return "", nil, nil, errors.New("computed secret selection in a workflow_call requires explicitly declared on.workflow_call.secrets names to bound the secret inventory")
363+
}
364+
if hasWorkflowCallTrigger(data.On) {
365+
secrets = append(secrets, workflowCallSecretNames(data.On)...)
366+
slices.Sort(secrets)
367+
secrets = slices.Compact(secrets)
368+
}
351369

352370
// If this workflow has a workflow_call trigger, inject on.workflow_call.secrets:
353371
// declarations so callers can map secrets explicitly instead of using secrets: inherit.

‎pkg/workflow/compiler_yaml_header.go‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -95,6 +95,7 @@ func (c *Compiler) generateManifestHeader(yaml *strings.Builder, data *WorkflowD
9595
// The manifest records safe-update inventory and normalized webhook declarations
9696
// for CAO discovery without interpreting generated workflow steps.
9797
manifest := NewGHAWManifest(secrets, actions, data.ActionResolutionFailures, data.DockerImagePins, data.Redirect, data.Skills, data.Plugins, data.RawFrontmatter["on"])
98+
manifest.DynamicSecretReferences = normalizeDynamicSecretReferences(data.dynamicSecretReferences)
9899
metadata := data.compiledMarkdownMetadata
99100
if metadata == nil {
100101
metadata = c.collectMarkdownMetadata(data)

‎pkg/workflow/redact_secrets.go‎

Lines changed: 32 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ package workflow
33
import (
44
"fmt"
55
"maps"
6+
"slices"
67
"strings"
78
"unicode/utf8"
89

@@ -71,6 +72,12 @@ func CollectSecretReferences(yamlContent string) []string {
7172
rest = rest[end:]
7273
}
7374

75+
for name := range ExtractSecretsFromValue(yamlContent) {
76+
if name == strings.ToUpper(name) {
77+
secretsMap[name] = struct{}{}
78+
}
79+
}
80+
7481
// Convert map to sorted slice for consistent ordering
7582
secrets := sliceutil.SortedKeys(secretsMap)
7683

@@ -79,6 +86,14 @@ func CollectSecretReferences(yamlContent string) []string {
7986
return secrets
8087
}
8188

89+
func CollectDynamicSecretReferences(yamlContent string) []string {
90+
references := make(map[string]struct{})
91+
for _, reference := range ExtractDynamicSecretReferencesFromValue(yamlContent) {
92+
references[reference] = struct{}{}
93+
}
94+
return sliceutil.SortedKeys(references)
95+
}
96+
8297
// CollectActionReferences extracts all external GitHub Action references from the workflow YAML.
8398
// It returns a sorted, deduplicated list of "uses:" values, excluding local and
8499
// self-repository references that start with "./" or "$/".
@@ -139,6 +154,12 @@ func actionReferenceFromLine(line string) (string, bool) {
139154
func (c *Compiler) generateSecretRedactionStep(yaml *strings.Builder, yamlContent string, data *WorkflowData, stagedDurableFiles bool) {
140155
// Extract secret references from the generated YAML
141156
secretReferences := CollectSecretReferences(yamlContent)
157+
secretReferences = append(secretReferences, workflowCallSecretNames(data.On)...)
158+
secretReferences = sliceutil.Deduplicate(secretReferences)
159+
dynamicSecretReferences := CollectDynamicSecretReferences(yamlContent)
160+
dynamicSecretReferences = append(dynamicSecretReferences, data.dynamicSecretReferences...)
161+
slices.Sort(dynamicSecretReferences)
162+
dynamicSecretReferences = slices.Compact(dynamicSecretReferences)
142163

143164
// Always record that we're adding a secret redaction step, even if no secrets found
144165
// This is important for validation to ensure the step ordering is correct
@@ -153,14 +174,16 @@ func (c *Compiler) generateSecretRedactionStep(yaml *strings.Builder, yamlConten
153174
durableCopilot := stagedDurableFiles && data.durableExecutionPlan != nil && data.EngineConfig != nil && data.EngineConfig.ID == "copilot"
154175
writeSecretRedactionScript(yaml, data, durableCopilot)
155176

156-
if durableCopilot || len(secretReferences) > 0 {
177+
if durableCopilot || len(secretReferences) > 0 || len(dynamicSecretReferences) > 0 {
157178
yaml.WriteString(" env:\n")
158179
}
159180
if durableCopilot {
160181
generateCopilotCheckpointRedactionEnv(yaml, data)
161182
}
162183
if len(secretReferences) > 0 {
163-
writeSecretRedactionEnvironment(yaml, secretReferences)
184+
writeSecretRedactionEnvironment(yaml, secretReferences, dynamicSecretReferences)
185+
} else if len(dynamicSecretReferences) > 0 {
186+
writeSecretRedactionEnvironment(yaml, nil, dynamicSecretReferences)
164187
}
165188

166189
// Inject custom secret masking steps if configured
@@ -195,17 +218,22 @@ func writeSecretRedactionScript(yaml *strings.Builder, data *WorkflowData, durab
195218
yaml.WriteString(" await main();\n")
196219
}
197220

198-
func writeSecretRedactionEnvironment(yaml *strings.Builder, secretReferences []string) {
221+
func writeSecretRedactionEnvironment(yaml *strings.Builder, secretReferences, dynamicSecretReferences []string) {
199222
escapedRefs := make([]string, 0, len(secretReferences))
200223
for _, ref := range secretReferences {
201224
escapedRefs = append(escapedRefs, escapeSingleQuoteBackslash(ref))
202225
}
203-
yaml.WriteString(" GH_AW_SECRET_NAMES: '" + strings.Join(escapedRefs, ",") + "'\n")
226+
if len(escapedRefs) > 0 {
227+
yaml.WriteString(" GH_AW_SECRET_NAMES: '" + strings.Join(escapedRefs, ",") + "'\n")
228+
}
204229

205230
for _, secretName := range secretReferences {
206231
escapedSecretName := escapeSingleQuoteBackslash(secretName)
207232
yaml.WriteString(" SECRET_" + escapedSecretName + ": ${{ secrets." + secretName + " }}\n")
208233
}
234+
for index, reference := range dynamicSecretReferences {
235+
fmt.Fprintf(yaml, " GH_AW_DYNAMIC_SECRET_VALUE_%d: %q\n", index, reference) //nolint:fprintferrorunchecked // strings.Builder writes cannot fail.
236+
}
209237
}
210238

211239
// customSecretMaskingStepIDs preserves explicit IDs and assigns stable, non-conflicting

‎pkg/workflow/redact_secrets_test.go‎

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,12 @@ func TestCollectSecretReferences(t *testing.T) {
2727
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}`,
2828
expected: []string{"GITHUB_TOKEN"},
2929
},
30+
{
31+
name: "Static bracket secret reference",
32+
yaml: `env:
33+
TOKEN: ${{ secrets['MY_TOKEN'] }}`,
34+
expected: []string{"MY_TOKEN"},
35+
},
3036
{
3137
name: "Multiple secret references",
3238
yaml: `env:
@@ -392,7 +398,7 @@ func TestSecretRedactionEmitsEnvMappingWithWorkflowSecrets(t *testing.T) {
392398
var builder strings.Builder
393399
compiler := NewCompiler()
394400

395-
compiler.generateSecretRedactionStep(&builder, "${{ secrets.MY_TOKEN }}", &WorkflowData{}, false)
401+
compiler.generateSecretRedactionStep(&builder, "${{ secrets.MY_TOKEN }} and ${{ secrets[vars.SECRET_NAME] }}", &WorkflowData{}, false)
396402

397403
steps := parseGeneratedSteps(t, builder.String())
398404
if len(steps) != 1 {
@@ -408,6 +414,9 @@ func TestSecretRedactionEmitsEnvMappingWithWorkflowSecrets(t *testing.T) {
408414
if _, ok := env["SECRET_MY_TOKEN"]; !ok {
409415
t.Errorf("Expected the secret value to be passed as SECRET_MY_TOKEN, got %#v", env)
410416
}
417+
if env["GH_AW_DYNAMIC_SECRET_VALUE_0"] != "${{ secrets[vars.SECRET_NAME] }}" {
418+
t.Errorf("Expected the computed secret value to be passed for redaction, got %#v", env["GH_AW_DYNAMIC_SECRET_VALUE_0"])
419+
}
411420
}
412421

413422
func TestSecretRedactionPreparesFilesOnlyForCustomMasking(t *testing.T) {

‎pkg/workflow/safe_update_enforcement.go‎

Lines changed: 27 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,7 @@ type PullRequestEventTransition struct {
4848
type SafeUpdateOptions struct {
4949
Manifest *GHAWManifest
5050
SecretNames []string
51+
DynamicSecretReferences []string
5152
ActionRefs []string
5253
CurrentRedirect string
5354
PullRequestTransition PullRequestEventTransition
@@ -84,12 +85,13 @@ func EnforceSafeUpdate(options SafeUpdateOptions) error {
8485
}
8586

8687
secretViolations := collectSecretViolations(options.Manifest, options.SecretNames)
88+
dynamicSecretViolations := collectDynamicSecretViolations(options.Manifest, options.DynamicSecretReferences)
8789
addedActions, removedActions := collectActionViolations(options.Manifest, options.ActionRefs)
8890
addedRedirect, removedRedirect := collectRedirectViolations(options.Manifest, options.CurrentRedirect)
8991
memoryValidationScriptChanges := collectMemoryValidationScriptChanges(options.Manifest, options.MemoryValidationScripts)
9092
pullRequestTargetEscalation := hasPullRequestTargetEscalation(options.PullRequestTransition.OldHasPullRequest, options.PullRequestTransition.OldHasPullRequestTarget, options.PullRequestTransition.CurrentHasPullRequest, options.PullRequestTransition.CurrentHasPullRequestTarget)
9193

92-
if len(secretViolations) == 0 && len(addedActions) == 0 && len(removedActions) == 0 && addedRedirect == "" && removedRedirect == "" && len(memoryValidationScriptChanges) == 0 && !pullRequestTargetEscalation {
94+
if len(secretViolations) == 0 && len(dynamicSecretViolations) == 0 && len(addedActions) == 0 && len(removedActions) == 0 && addedRedirect == "" && removedRedirect == "" && len(memoryValidationScriptChanges) == 0 && !pullRequestTargetEscalation {
9395
safeUpdateLog.Printf("Safe update check passed (%d secret(s), %d action(s) verified)",
9496
len(options.SecretNames), len(options.ActionRefs))
9597
return nil
@@ -121,7 +123,7 @@ func EnforceSafeUpdate(options SafeUpdateOptions) error {
121123
safeUpdateLog.Print("Safe update violation: pull_request event converted to pull_request_target")
122124
}
123125

124-
return buildSafeUpdateError(secretViolations, addedActions, removedActions, addedRedirect, removedRedirect, pullRequestTargetEscalation, memoryValidationScriptChanges)
126+
return buildSafeUpdateError(secretViolations, addedActions, removedActions, addedRedirect, removedRedirect, pullRequestTargetEscalation, memoryValidationScriptChanges, dynamicSecretViolations)
125127
}
126128

127129
func hasPullRequestTargetEscalation(oldHasPullRequest bool, oldHasPullRequestTarget bool, currentHasPullRequest bool, currentHasPullRequestTarget bool) bool {
@@ -193,6 +195,20 @@ func collectSecretViolations(manifest *GHAWManifest, secretNames []string) []str
193195
return violations
194196
}
195197

198+
func collectDynamicSecretViolations(manifest *GHAWManifest, references []string) []string {
199+
known := make(map[string]struct{}, len(manifest.DynamicSecretReferences))
200+
for _, reference := range manifest.DynamicSecretReferences {
201+
known[reference] = struct{}{}
202+
}
203+
var violations []string
204+
for _, reference := range normalizeDynamicSecretReferences(references) {
205+
if !setutil.Contains(known, reference) {
206+
violations = append(violations, reference)
207+
}
208+
}
209+
return violations
210+
}
211+
196212
// githubActionsOrg is the owner whose actions are always trusted and never flagged
197213
// as unapproved additions, regardless of what was recorded in the manifest.
198214
const githubActionsOrg = "actions"
@@ -328,14 +344,22 @@ func collectMemoryValidationScriptChanges(manifest *GHAWManifest, current []GHAW
328344

329345
// buildSafeUpdateError creates a clear, structured error message that names the
330346
// offending secrets, actions, and redirects and tells the user how to remediate.
331-
func buildSafeUpdateError(secretViolations, addedActions, removedActions []string, addedRedirect, removedRedirect string, hasPullRequestTargetEscalation bool, memoryValidationScriptChanges []string) error {
347+
func buildSafeUpdateError(secretViolations, addedActions, removedActions []string, addedRedirect, removedRedirect string, hasPullRequestTargetEscalation bool, memoryValidationScriptChanges []string, dynamicSecretViolations ...[]string) error {
332348
var sb strings.Builder
333349
sb.WriteString("safe update mode detected unapproved changes\n")
350+
var computedSecretViolations []string
351+
if len(dynamicSecretViolations) > 0 {
352+
computedSecretViolations = dynamicSecretViolations[0]
353+
}
334354

335355
if len(secretViolations) > 0 {
336356
sb.WriteString("\nNew restricted secret(s):\n - ")
337357
sb.WriteString(strings.Join(secretViolations, "\n - "))
338358
}
359+
if len(computedSecretViolations) > 0 {
360+
sb.WriteString("\nNew computed secret selector(s) (SHA-256):\n - ")
361+
sb.WriteString(strings.Join(computedSecretViolations, "\n - "))
362+
}
339363
if len(addedActions) > 0 {
340364
sb.WriteString("\nNew unapproved action(s):\n - ")
341365
sb.WriteString(strings.Join(addedActions, "\n - "))

0 commit comments

Comments
 (0)