Skip to content

Commit 6493817

Browse files
authored
Fix dynamic secret selection false positives in strict linting (#80581)
1 parent 599f6db commit 6493817

25 files changed

Lines changed: 428 additions & 41 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";

‎docs/src/content/docs/reference/workflow-linters.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ Threat IDs refer to the [Compiler Threat Detection Specification](https://github
1919
| `workflow-run-scope` | `CTR-021` | AW, Actions | `workflow_run` selects workflows and has a positive branch scope, not only wildcard, negated, or empty filters. |
2020
| `dangerous-triggers` | `CTR-008`, `CTR-039` | AW, Actions | Target-trigger warnings and comment-trigger warnings correlated with actor admission and GitHub integrity filtering, including AW commands. Trusted roles, approved/merged filtering without lockdown override, or explicit GitHub disablement suppress the comment finding; literal AW target-risk acknowledgment suppresses only the target warning. |
2121
| `secret-leak` | `CTR-017` | AW, Actions | Symbolic secrets do not reach modeled disclosure sinks. AW-only checks report missing generated execution coverage. |
22+
| `overprovisioned-secrets` | `CTR-017` | AW, Actions | Whole-context secrets expressions, including `toJSON(secrets)` and wildcard projections, are rejected under strict AW policy. Selecting one secret with a literal or dynamic index is not whole-context exposure; nested selector expressions are still checked. This distinction does not establish selector trust or authorize disclosure. Remote `secrets: inherit` is rejected under strict AW policy; local inheritance warns. Actions-only and non-strict findings warn. |
2223
| `otlp-secret-leak` | `CTR-017` | AW, Actions | Secret-tainted expressions are not exported through OTLP span or resource attributes. Hard-coded credentials and runtime values are not detected. |
2324
| `permission-scope` | `CTR-001` | AW, Actions | Permissions avoid blanket `write-all`; OIDC does not use invalid `id-token: read`. Scoped writes and `id-token: write` are not violations. |
2425
| `version-check` | `CTR-018` | AW | Authored source does not disable `check-for-updates`. |

‎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_lint.go‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -53,7 +53,8 @@ func (c *Compiler) lintCompiledWorkflow(data *WorkflowData, content, sourcePath
5353
if data.ParsedFrontmatter != nil {
5454
suppressions = data.ParsedFrontmatter.ThreatDetectionSuppressions
5555
}
56-
if isThreatDetectionRuleSuppressed(suppressions, diagnostic.ThreatRuleID, time.Now()) {
56+
if diagnostic.RuleID != "overprovisioned-secrets" &&
57+
isThreatDetectionRuleSuppressed(suppressions, diagnostic.ThreatRuleID, time.Now()) {
5758
continue
5859
}
5960
}

‎pkg/workflow/compiler_lint_test.go‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -482,6 +482,23 @@ func TestCompilerLintPreservesThreatSuppressions(t *testing.T) {
482482
require.ErrorContains(t, err, "[template-injection]")
483483
}
484484
}
485+
486+
}
487+
488+
func TestCompilerLintCTR017SuppressionDoesNotHideOverprovisionedSecrets(t *testing.T) {
489+
t.Parallel()
490+
expires := time.Now().UTC().AddDate(0, 0, 1).Format("2006-01-02")
491+
document, err := aw.Parse("---\nstrict: true\non: workflow_dispatch\n---\nReview.\n")
492+
require.NoError(t, err)
493+
data := &WorkflowData{SourceDocument: document, RawFrontmatter: document.Frontmatter, ParsedFrontmatter: &FrontmatterConfig{
494+
ThreatDetectionSuppressions: []ThreatDetectionSuppression{{
495+
Rule: "CTR-017", Reason: "Reviewed secret leak", Expires: expires,
496+
}},
497+
}}
498+
content := "jobs:\n call:\n uses: octo/shared/.github/workflows/deploy.yml@0123456789abcdef0123456789abcdef01234567\n secrets: inherit\n"
499+
500+
err = NewCompiler(WithLint(true)).lintCompiledWorkflow(data, content, "test.md")
501+
require.ErrorContains(t, err, "[overprovisioned-secrets]")
485502
}
486503

487504
func TestCompilerLintWarningsRemainAdvisory(t *testing.T) {

‎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)

0 commit comments

Comments
 (0)