Skip to content
Merged
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
5 changes: 5 additions & 0 deletions actions/setup/js/redact_secrets.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -748,6 +748,11 @@ async function main({ prepareForCustomMasking = false, additionalDirectories = [
secretValues.push(secretValue.trim());
}
}
for (const [name, value] of Object.entries(process.env)) {
if (name.startsWith("GH_AW_DYNAMIC_SECRET_VALUE_") && value && value.trim() !== "") {
secretValues.push(value.trim());
}
}

// Extract MCP gateway bearer tokens from known config files and add them to
// the redaction list. The gateway token has no fixed prefix so it cannot be
Expand Down
16 changes: 16 additions & 0 deletions actions/setup/js/redact_secrets.test.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,22 @@ const { persistDetectionMasks } = require("./detection_mask_state.cjs");
const redactScript = fs.readFileSync(path.join(__dirname, "redact_secrets.cjs"), "utf8");
describe("redact_secrets.cjs", () => {
let tempDir, ambientPathsSpy;
it("redacts dynamically selected secret values from artifacts", async () => {
const { main } = require("./redact_secrets.cjs");
const secret = "synthetic-dynamic-secret-value";
vi.stubEnv("GH_AW_DYNAMIC_SECRET_VALUE_0", secret);
const directory = path.join(process.env.RUNNER_TEMP, "gh-aw");
fs.mkdirSync(directory, { recursive: true });
const file = path.join(directory, "dynamic-secret.json");
fs.writeFileSync(file, JSON.stringify({ token: secret }));

await main();

expect(fs.readFileSync(file, "utf8")).not.toContain(secret);
expect(JSON.parse(fs.readFileSync(file, "utf8"))).toEqual({ token: "***REDACTED***" });
expect(mockCore.setFailed).not.toHaveBeenCalled();
});

it("sanitizes detection results, copied firewall logs and late-created accounting files", async () => {
const { main } = require("./redact_secrets.cjs");
const secret = "synthetic-detection-private-value";
Expand Down
1 change: 1 addition & 0 deletions docs/src/content/docs/reference/workflow-linters.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ Threat IDs refer to the [Compiler Threat Detection Specification](https://github
| `workflow-run-scope` | `CTR-021` | AW, Actions | `workflow_run` selects workflows and has a positive branch scope, not only wildcard, negated, or empty filters. |
| `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. |
| `secret-leak` | `CTR-017` | AW, Actions | Symbolic secrets do not reach modeled disclosure sinks. AW-only checks report missing generated execution coverage. |
| `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. |
| `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. |
| `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. |
| `version-check` | `CTR-018` | AW | Authored source does not disable `check-for-updates`. |
Expand Down
1 change: 1 addition & 0 deletions pkg/workflow/compiler.go
Original file line number Diff line number Diff line change
Expand Up @@ -688,6 +688,7 @@ func (c *Compiler) CompileWorkflowData(workflowData *WorkflowData, markdownPath
if enforceErr := EnforceSafeUpdate(SafeUpdateOptions{
Manifest: oldManifest,
SecretNames: bodySecrets,
DynamicSecretReferences: workflowData.dynamicSecretReferences,
ActionRefs: bodyActions,
CurrentRedirect: workflowData.Redirect,
PullRequestTransition: prTransition,
Expand Down
3 changes: 2 additions & 1 deletion pkg/workflow/compiler_lint.go
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,8 @@ func (c *Compiler) lintCompiledWorkflow(data *WorkflowData, content, sourcePath
if data.ParsedFrontmatter != nil {
suppressions = data.ParsedFrontmatter.ThreatDetectionSuppressions
}
if isThreatDetectionRuleSuppressed(suppressions, diagnostic.ThreatRuleID, time.Now()) {
if diagnostic.RuleID != "overprovisioned-secrets" &&
isThreatDetectionRuleSuppressed(suppressions, diagnostic.ThreatRuleID, time.Now()) {
continue
}
}
Expand Down
17 changes: 17 additions & 0 deletions pkg/workflow/compiler_lint_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -482,6 +482,23 @@ func TestCompilerLintPreservesThreatSuppressions(t *testing.T) {
require.ErrorContains(t, err, "[template-injection]")
}
}

}

func TestCompilerLintCTR017SuppressionDoesNotHideOverprovisionedSecrets(t *testing.T) {
t.Parallel()
expires := time.Now().UTC().AddDate(0, 0, 1).Format("2006-01-02")
document, err := aw.Parse("---\nstrict: true\non: workflow_dispatch\n---\nReview.\n")
require.NoError(t, err)
data := &WorkflowData{SourceDocument: document, RawFrontmatter: document.Frontmatter, ParsedFrontmatter: &FrontmatterConfig{
ThreatDetectionSuppressions: []ThreatDetectionSuppression{{
Rule: "CTR-017", Reason: "Reviewed secret leak", Expires: expires,
}},
}}
content := "jobs:\n call:\n uses: octo/shared/.github/workflows/deploy.yml@0123456789abcdef0123456789abcdef01234567\n secrets: inherit\n"

err = NewCompiler(WithLint(true)).lintCompiledWorkflow(data, content, "test.md")
require.ErrorContains(t, err, "[overprovisioned-secrets]")
}

func TestCompilerLintWarningsRemainAdvisory(t *testing.T) {
Expand Down
25 changes: 25 additions & 0 deletions pkg/workflow/compiler_workflow_call.go
Original file line number Diff line number Diff line change
Expand Up @@ -227,6 +227,31 @@ type workflowCallSecretEntry struct {
Required bool `yaml:"required"`
}

func workflowCallSecretNames(onSection string) []string {
var onData map[string]any
if err := yaml.Unmarshal([]byte(onSection), &onData); err != nil {
return nil
}
on, ok := onData["on"].(map[string]any)
if !ok {
return nil
}
workflowCall, ok := on["workflow_call"].(map[string]any)
if !ok {
return nil
}
secrets, ok := workflowCall["secrets"].(map[string]any)
if !ok {
return nil
}
names := make([]string, 0, len(secrets))
for name := range secrets {
names = append(names, name)
}
sort.Strings(names)
return names
}

// injectWorkflowCallSecretsSection adds on.workflow_call.secrets declarations for secrets
// used by the workflow, so that callers can pass them explicitly instead of using
// secrets: inherit. GITHUB_TOKEN is excluded because it is automatically provided by
Expand Down
57 changes: 57 additions & 0 deletions pkg/workflow/compiler_workflow_call_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -473,3 +473,60 @@ func TestInjectWorkflowCallSecretsSection(t *testing.T) {
})
}
}

func TestWorkflowCallDynamicSecretSelectionRequiresExplicitBoundedNames(t *testing.T) {
t.Parallel()
directory := testutil.TempDir(t, "workflow-call-dynamic-secret-test")
workflow := `---
on:
workflow_call:
engine: copilot
steps:
- name: Use computed secret
env:
SELECTED_SECRET: "${{ secrets[vars.SECRET_NAME] }}"
run: echo "using secret"
---
Run the workflow.
`
path := filepath.Join(directory, "dynamic-secret.md")
require.NoError(t, os.WriteFile(path, []byte(workflow), 0644))
compiler := NewCompiler()
data, err := compiler.ParseWorkflowFile(path)
require.NoError(t, err)

_, _, _, err = compiler.generateYAML(data, path)
require.ErrorContains(t, err, "explicitly declared on.workflow_call.secrets names")
}

func TestWorkflowCallDynamicSecretSelectionIsInventoriedAndRedacted(t *testing.T) {
t.Parallel()
directory := testutil.TempDir(t, "workflow-call-dynamic-secret-inventory-test")
workflow := `---
on:
workflow_call:
secrets:
DEPLOY_TOKEN:
required: false
engine: copilot
steps:
- name: Use computed secret
env:
SELECTED_SECRET: "${{ secrets[vars.SECRET_NAME] }}"
run: echo "using secret"
---
Run the workflow.
`
path := filepath.Join(directory, "dynamic-secret.md")
require.NoError(t, os.WriteFile(path, []byte(workflow), 0644))
compiler := NewCompiler()
data, err := compiler.ParseWorkflowFile(path)
require.NoError(t, err)

yamlOutput, secrets, _, err := compiler.generateYAML(data, path)
require.NoError(t, err)
require.Contains(t, secrets, "DEPLOY_TOKEN")
require.Contains(t, yamlOutput, `GH_AW_DYNAMIC_SECRET_VALUE_0: "${{ secrets[vars.SECRET_NAME] }}"`)
require.Contains(t, yamlOutput, "SECRET_DEPLOY_TOKEN: ${{ secrets.DEPLOY_TOKEN }}")
require.Contains(t, yamlOutput, `"dynamic_secret_references":["sha256:`)
}
20 changes: 19 additions & 1 deletion pkg/workflow/compiler_yaml.go
Original file line number Diff line number Diff line change
Expand Up @@ -227,6 +227,10 @@ func (c *Compiler) generateWorkflowBody(yaml *strings.Builder, data *WorkflowDat

func (c *Compiler) generateYAML(data *WorkflowData, markdownPath string) (string, []string, []string, error) { //nolint:largefunc // Existing workflow YAML assembly keeps generation steps in order.
compilerYamlLog.Printf("Generating YAML for workflow: %s", data.Name)
data.dynamicSecretReferences = CollectDynamicSecretReferences(data.FrontmatterYAML)
if len(data.dynamicSecretReferences) > 0 && hasWorkflowCallTrigger(data.On) && len(workflowCallSecretNames(data.On)) == 0 {
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")
}

repoConfig, err := c.loadRepoConfig()
if err != nil {
Expand Down Expand Up @@ -303,7 +307,10 @@ func (c *Compiler) generateYAML(data *WorkflowData, markdownPath string) (string
}
// Appending failures can replace a slice's backing array; generatedActionRefs
// is a shared map and needs no copy-back.
defer func() { sourceData.ActionResolutionFailures = data.ActionResolutionFailures }()
defer func() {
sourceData.ActionResolutionFailures = data.ActionResolutionFailures
sourceData.dynamicSecretReferences = data.dynamicSecretReferences
}()

// Build all jobs and validate dependencies
if err := c.buildJobsAndValidate(data, markdownPath); err != nil {
Expand Down Expand Up @@ -348,6 +355,17 @@ func (c *Compiler) generateYAML(data *WorkflowData, markdownPath string) (string
// These are returned to the caller so they can be used for safe update enforcement
// without requiring a second scan of the full YAML content.
secrets := CollectSecretReferences(bodyContent)
data.dynamicSecretReferences = append(data.dynamicSecretReferences, CollectDynamicSecretReferences(bodyContent)...)
slices.Sort(data.dynamicSecretReferences)
data.dynamicSecretReferences = slices.Compact(data.dynamicSecretReferences)
if len(data.dynamicSecretReferences) > 0 && hasWorkflowCallTrigger(data.On) && len(workflowCallSecretNames(data.On)) == 0 {
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")
}
if hasWorkflowCallTrigger(data.On) {
secrets = append(secrets, workflowCallSecretNames(data.On)...)
slices.Sort(secrets)
secrets = slices.Compact(secrets)
}

// If this workflow has a workflow_call trigger, inject on.workflow_call.secrets:
// declarations so callers can map secrets explicitly instead of using secrets: inherit.
Expand Down
1 change: 1 addition & 0 deletions pkg/workflow/compiler_yaml_header.go
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,7 @@ func (c *Compiler) generateManifestHeader(yaml *strings.Builder, data *WorkflowD
// The manifest records safe-update inventory and normalized webhook declarations
// for CAO discovery without interpreting generated workflow steps.
manifest := NewGHAWManifest(secrets, actions, data.ActionResolutionFailures, data.DockerImagePins, data.Redirect, data.Skills, data.Plugins, data.RawFrontmatter["on"])
manifest.DynamicSecretReferences = normalizeDynamicSecretReferences(data.dynamicSecretReferences)
metadata := data.compiledMarkdownMetadata
if metadata == nil {
metadata = c.collectMarkdownMetadata(data)
Expand Down
47 changes: 27 additions & 20 deletions pkg/workflow/lint/overprovisioned_secrets.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,11 +16,12 @@ import (
// secrets context instead of the named secrets a job or step actually needs.
func OverprovisionedSecretsRule() Rule {
return Rule{
ID: "overprovisioned-secrets",
Description: "Detect secrets: inherit and expressions that materialize the whole secrets context",
Severity: Error,
Targets: ActionsAST | AWAST,
Check: checkOverprovisionedSecrets,
ID: "overprovisioned-secrets",
ThreatRuleID: "CTR-017",

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

CTR-017 suppressions no longer suppress overprovisioned-secrets; added strict-mode regression coverage in 3c4e3c96.

Description: "Detect secrets: inherit and expressions that materialize the whole secrets context",
Severity: Error,
Targets: ActionsAST | AWAST,
Check: checkOverprovisionedSecrets,
}
}

Expand Down Expand Up @@ -93,19 +94,7 @@ func overprovisionedSecretsDiagnostics(ctx context.Context, input Input) ([]Diag
}

blocks, err := aw.ExecutionBlocks(ctx, input.Document)
failures := []error{err}
// engine.env and sandbox.agent.env are copied into the agent execution step
// environment but are not execution blocks.
if input.Document != nil {
if engine, ok := input.Document.Frontmatter["engine"].(map[string]any); ok {
failures = append(failures, walkExpressionScalars(ctx, engine["env"], "engine.env", visit))
}
if sandbox, ok := input.Document.Frontmatter["sandbox"].(map[string]any); ok {
if agent, ok := sandbox["agent"].(map[string]any); ok {
failures = append(failures, walkExpressionScalars(ctx, agent["env"], "sandbox.agent.env", visit))
}
}
}
failures := []error{err, walkOverprovisionedSecretsEnv(ctx, input.Document, visit)}
for _, block := range blocks {
if secrets, ok := block.Fields["secrets"].(string); ok && strings.EqualFold(strings.TrimSpace(secrets), "inherit") {
if uses, ok := block.Fields["uses"].(string); ok {
Expand All @@ -124,6 +113,23 @@ func overprovisionedSecretsDiagnostics(ctx context.Context, input Input) ([]Diag
return diagnostics, errors.Join(failures...)
}

func walkOverprovisionedSecretsEnv(ctx context.Context, document *aw.Document, visit func(string, string) error) error {
// engine.env and sandbox.agent.env are copied into the agent execution step
// environment but are not execution blocks.
var failures []error
if document != nil {
if engine, ok := document.Frontmatter["engine"].(map[string]any); ok {
failures = append(failures, walkExpressionScalars(ctx, engine["env"], "engine.env", visit))
}
if sandbox, ok := document.Frontmatter["sandbox"].(map[string]any); ok {
if agent, ok := sandbox["agent"].(map[string]any); ok {
failures = append(failures, walkExpressionScalars(ctx, agent["env"], "sandbox.agent.env", visit))
}
}
}
return errors.Join(failures...)
}

// isCompilerCallWorkflowFallback reports whether job has the exact shape of a
// compiler-generated call-workflow fan-out job: call-<worker> needing
// safe_outputs, gated on call_workflow_name, and calling the local worker file.
Expand Down Expand Up @@ -174,7 +180,8 @@ func inheritDiagnostic(path, uses string) Diagnostic {
}

// materializesSecretsContext reports whether node evaluates the secrets
// context as a whole: any reference other than secrets.NAME or secrets['NAME'].
// context as a whole rather than selecting one property. Dynamic indexes select
// one secret too, but their expressions are still visited for whole-context use.
func materializesSecretsContext(node actionlint.ExprNode) bool {
found := false
actionlint.VisitExprNode(node, func(child, parent actionlint.ExprNode, entering bool) {
Expand All @@ -191,7 +198,7 @@ func materializesSecretsContext(node actionlint.ExprNode) bool {
return
}
case *actionlint.IndexAccessNode:
if _, literal := parent.Index.(*actionlint.StringNode); literal && parent.Operand == child {
if parent.Operand == child {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Computed selectors are now fingerprinted for safe-update checks, redacted, and bounded by explicit workflow_call secret names. Added generated-workflow regression coverage in db5c641e.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Computed secret references are now included in step secret classification, so env bindings are rejected when the step writes to GITHUB_ENV; added a regression in db5c641e.

return
}
}
Expand Down
Loading
Loading