Self-hosted workflows for coding-agent delivery. Orchestrate CodeBuddy, Codex and Claude Code with scripts and human approval gates. Includes Local workflows for coding assistants.
JavaScript agent-orchestrationagentic-workflowai-agentsai-codingclaude-codecode-reviewcodebuddycodexcoding-agentscursordeveloper-toolshuman-on-the-loopllmmcpmulti-agentsdlcself-hostedsopworkflow-automationworkflow-engine
feat(engine): let nodes request platform credentials as env vars (#1043)
jason zhangf8dcd1eb315c
diff --git a/internal/domain/workflow.go b/internal/domain/workflow.goindex 57607475..59175e63 100644--- a/internal/domain/workflow.go+++ b/internal/domain/workflow.go@@ -59,7 +59,14 @@ type WorkflowNode struct {RunOnWorkspaceRebuild bool `json:"runOnWorkspaceRebuild,omitempty"`ScriptLanguage string `json:"scriptLanguage,omitempty"` // shell, pythonScript string `json:"script,omitempty"`- ExecutionScope string `json:"executionScope,omitempty"` // run, repositories; empty = run+ // CredentialEnv requests platform-managed credentials as environment+ // variables for script and verification commands: each entry maps an+ // environment variable name to a credential kind (a RunCredentials.Extra+ // key registered by the deployment). A declared credential the+ // responsible user has not saved fails the node up front; the secret+ // itself never appears in workflow definitions, node configs or logs.+ CredentialEnv map[string]string `json:"credentialEnv,omitempty"`+ ExecutionScope string `json:"executionScope,omitempty"` // run, repositories; empty = runCommand string `json:"command,omitempty"` // legacy command-node payloadArtifactOutputs []ArtifactContract `json:"artifactOutputs,omitempty"`RejectTo string `json:"rejectTo,omitempty"`diff --git a/internal/engine/node_execute.go b/internal/engine/node_execute.goindex 74c29b5d..cafa1b8a 100644--- a/internal/engine/node_execute.go+++ b/internal/engine/node_execute.go@@ -461,7 +461,11 @@ func (e *Engine) executeNode(ctx context.Context, runID string, wf domain.Workfl// (执行器) it is dispatched to that machine so gates run next to the CLI// output in the runner-side task workspace.gateExec := func(command string, target executionTarget, gateSink runtime.EventSink) (string, error) {- return sb.Exec(ctx, runtime.CommandSpec{Argv: []string{"sh", "-lc", bindExecutionTarget(command, target)}, Provider: "verification", CredentialBindings: []runtime.CredentialBinding{runtime.BindGit, runtime.BindMCP}}, gateSink)+ spec, err := runtime.CommandSpecWithCredentialEnv(runtime.CommandSpec{Argv: []string{"sh", "-lc", bindExecutionTarget(command, target)}, Provider: "verification", CredentialBindings: []runtime.CredentialBinding{runtime.BindGit, runtime.BindMCP}}, node.CredentialEnv, sb.credentialSnapshot())+ if err != nil {+ return "", err+ }+ return sb.Exec(ctx, spec, gateSink)}current, _ = e.repo.RunState(runID)gitCredentials := sb.credentialSnapshot()@@ -610,7 +614,11 @@ func (e *Engine) executeNode(ctx context.Context, runID string, wf domain.Workflif err := runtime.ProvisionMCPAssets(ctx, sb, sb.Workspace(), scriptAssets, targetSink); err != nil {return "", err}- return sb.Exec(ctx, runtime.CommandSpec{Argv: []string{"sh", "-lc", bound}, Provider: "script", CredentialBindings: []runtime.CredentialBinding{runtime.BindGit, runtime.BindMCP}}, targetSink)+ scriptSpec, err := runtime.CommandSpecWithCredentialEnv(runtime.CommandSpec{Argv: []string{"sh", "-lc", bound}, Provider: "script", CredentialBindings: []runtime.CredentialBinding{runtime.BindGit, runtime.BindMCP}}, effectiveNode.CredentialEnv, sb.credentialSnapshot())+ if err != nil {+ return "", err+ }+ return sb.Exec(ctx, scriptSpec, targetSink)})if execMachine := e.defaultExecutionRunner(current); execMachine != "" {workspace := runnerWorkspaceRel(current, node.ID)diff --git a/internal/runtime/run_credentials_extra.go b/internal/runtime/run_credentials_extra.goindex c183af19..badf0ebb 100644--- a/internal/runtime/run_credentials_extra.go+++ b/internal/runtime/run_credentials_extra.go@@ -1,6 +1,11 @@package runtime-import "sync"+import (+ "fmt"+ "sort"+ "strings"+ "sync"+)// ExtraCredentialSource returns deployment-specific run credentials for a// user (credential name → secret). The open-source build registers none; a@@ -49,3 +54,43 @@ func ExtraRunCredentials(userID int64) map[string]string {}return merged}++// MissingExtraCredentialKinds returns the sorted credential kinds requested by+// env (variable name → credential kind) that are absent or empty in extra.+// Callers use it to fail a declared credential up front with the kind named,+// instead of running a command with a silently empty variable.+func MissingExtraCredentialKinds(env, extra map[string]string) []string {+ var missing []string+ for _, kind := range env {+ kind = strings.TrimSpace(kind)+ if kind == "" {+ continue+ }+ if strings.TrimSpace(extra[kind]) == "" {+ missing = append(missing, kind)+ }+ }+ sort.Strings(missing)+ return missing+}++// CommandSpecWithCredentialEnv applies a node's CredentialEnv declaration to a+// command spec: it appends the BindExtra binding so the responsible user's+// platform-managed credentials are exported as the mapped environment+// variables. A declared credential the user has not saved fails the node up+// front with the kind named — the same contract as the CodeBuddy key binding —+// instead of running a command whose authentication silently falls back to the+// execution machine's own login. Both the engine's script/verification paths+// and workspace preparation replays share it, so a rebuilt environment binds+// exactly what a normal execution bound.+func CommandSpecWithCredentialEnv(spec CommandSpec, credentialEnv map[string]string, credentials RunCredentials) (CommandSpec, error) {+ if len(credentialEnv) == 0 {+ return spec, nil+ }+ if missing := MissingExtraCredentialKinds(credentialEnv, credentials.Extra); len(missing) > 0 {+ return spec, fmt.Errorf("需求责任人未配置凭证 %s,请先在个人配置中保存", strings.Join(missing, "、"))+ }+ spec.CredentialBindings = append(append([]CredentialBinding(nil), spec.CredentialBindings...), BindExtra)+ spec.ExtraCredentialEnv = credentialEnv+ return spec, nil+}diff --git a/internal/runtime/run_credentials_extra_test.go b/internal/runtime/run_credentials_extra_test.goindex 0a52a574..8c065ed6 100644--- a/internal/runtime/run_credentials_extra_test.go+++ b/internal/runtime/run_credentials_extra_test.go@@ -163,3 +163,47 @@ func TestConversationPathBindsExtraCredentialEnv(t *testing.T) {t.Errorf("MY_ABSENT_TOKEN: got %q, want empty (host value must be cleared)", got)}}++func TestCommandSpecWithCredentialEnvNoopWithoutDeclaration(t *testing.T) {+ spec := CommandSpec{Argv: []string{"sh", "-c", "exit 0"}, CredentialBindings: []CredentialBinding{BindGit}}+ out, err := CommandSpecWithCredentialEnv(spec, nil, RunCredentials{})+ if err != nil {+ t.Fatalf("CommandSpecWithCredentialEnv: %v", err)+ }+ if len(out.CredentialBindings) != 1 || out.CredentialBindings[0] != BindGit {+ t.Fatalf("bindings changed without declaration: %v", out.CredentialBindings)+ }+ if out.ExtraCredentialEnv != nil {+ t.Fatalf("ExtraCredentialEnv set without declaration: %v", out.ExtraCredentialEnv)+ }+}++func TestCommandSpecWithCredentialEnvAppendsBinding(t *testing.T) {+ spec := CommandSpec{Argv: []string{"sh", "-c", "exit 0"}, CredentialBindings: []CredentialBinding{BindGit, BindMCP}}+ env := map[string]string{"BG_USER_TOKEN": "knotToken"}+ out, err := CommandSpecWithCredentialEnv(spec, env, RunCredentials{Extra: map[string]string{"knotToken": "tok-1"}})+ if err != nil {+ t.Fatalf("CommandSpecWithCredentialEnv: %v", err)+ }+ if len(out.CredentialBindings) != 3 || out.CredentialBindings[2] != BindExtra {+ t.Fatalf("BindExtra not appended: %v", out.CredentialBindings)+ }+ if out.ExtraCredentialEnv["BG_USER_TOKEN"] != "knotToken" {+ t.Fatalf("ExtraCredentialEnv not mapped: %v", out.ExtraCredentialEnv)+ }+ if len(spec.CredentialBindings) != 2 {+ t.Fatal("input spec bindings mutated")+ }+}++func TestCommandSpecWithCredentialEnvFailsOnMissingCredential(t *testing.T) {+ spec := CommandSpec{Argv: []string{"sh", "-c", "exit 0"}}+ env := map[string]string{"BG_USER_TOKEN": "knotToken"}+ _, err := CommandSpecWithCredentialEnv(spec, env, RunCredentials{})+ if err == nil {+ t.Fatal("missing declared credential must fail")+ }+ if !strings.Contains(err.Error(), "knotToken") {+ t.Fatalf("error must name the credential kind: %v", err)+ }+}diff --git a/internal/runtime/sandbox_manager.go b/internal/runtime/sandbox_manager.goindex 64cfff9d..8cc40561 100644--- a/internal/runtime/sandbox_manager.go+++ b/internal/runtime/sandbox_manager.go@@ -406,6 +406,18 @@ func (s *managedSandbox) SetCredentials(credentials RunCredentials) {s.credentials = credentials}+// CredentialSnapshot returns the current credential snapshot. Read-only use:+// preparation code validating a node's declared credentials up front.+func (s *managedSandbox) CredentialSnapshot() RunCredentials {+ s.credentialsMu.RLock()+ defer s.credentialsMu.RUnlock()+ return s.credentials+}++// sandboxCredentialSnapshot lets runtime preparation code read a sandbox's+// credentials without widening the public Sandbox interface.+type sandboxCredentialSnapshot interface{ CredentialSnapshot() RunCredentials }+func (s *managedSandbox) Exec(ctx context.Context, command CommandSpec, sink EventSink) (string, error) {select {case s.slots <- struct{}{}:diff --git a/internal/runtime/workspace_preparation.go b/internal/runtime/workspace_preparation.goindex 0455b87a..485d0b6c 100644--- a/internal/runtime/workspace_preparation.go+++ b/internal/runtime/workspace_preparation.go@@ -357,7 +357,25 @@ func EnsureWorkspacePreparation(ctx context.Context, sb Sandbox, wf domain.Workfemit(node, "started", "正在恢复工作区环境:"+node.Name)var output stringexecute := func(repo *domain.RepositoryContext) error {- raw, execErr := sb.Exec(ctx, CommandSpec{Argv: []string{"sh", "-lc", preparationCommand(node, repo)}, Provider: "script", CredentialBindings: []CredentialBinding{BindGit, BindMCP}}, nil)+ spec := CommandSpec{Argv: []string{"sh", "-lc", preparationCommand(node, repo)}, Provider: "script", CredentialBindings: []CredentialBinding{BindGit, BindMCP}}+ // A rebuilt environment binds exactly what a normal execution+ // bound: the node's declared credentials are validated up front+ // (where the sandbox exposes its snapshot) and injected through+ // the same BindExtra path, so a replay never falls back to the+ // host process's own variables.+ if len(node.CredentialEnv) > 0 {+ if snapshot, ok := sb.(sandboxCredentialSnapshot); ok {+ var err error+ spec, err = CommandSpecWithCredentialEnv(spec, node.CredentialEnv, snapshot.CredentialSnapshot())+ if err != nil {+ return err+ }+ } else {+ spec.CredentialBindings = append(append([]CredentialBinding(nil), spec.CredentialBindings...), BindExtra)+ spec.ExtraCredentialEnv = node.CredentialEnv+ }+ }+ raw, execErr := sb.Exec(ctx, spec, nil)output = tailAtRuneBoundary(output+redactPreparationOutput(sb, raw), preparationOutputLimit)return execErr}diff --git a/internal/runtime/workspace_preparation_test.go b/internal/runtime/workspace_preparation_test.goindex d47943e6..08d022bd 100644--- a/internal/runtime/workspace_preparation_test.go+++ b/internal/runtime/workspace_preparation_test.go@@ -364,3 +364,75 @@ func TestPreparationScopedReadNeverFallsBackToLegacyOrUnsafeScopePath(t *testing}}}++// TestPreparationReplayBindsDeclaredCredentialEnv covers the rebuild path for+// node CredentialEnv: a replayed script must see the rebuilt environment's+// responsible-user credential and never the host process's own variable, and a+// missing declared credential must fail the preparation up front.+func TestPreparationReplayBindsDeclaredCredentialEnv(t *testing.T) {+ credentialWorkflow := func(script string) domain.WorkflowDefinition {+ return domain.WorkflowDefinition{Nodes: []domain.WorkflowNode{{+ ID: "env", Name: "带凭证的环境脚本", Type: "script", RunOnWorkspaceRebuild: true,+ Script: script, CredentialEnv: map[string]string{"MY_TOOL_TOKEN": "gateway"},+ }}}+ }+ ctx := context.Background()++ firstRoot := t.TempDir()+ sb := &managedSandbox{+ Sandbox: &localSandbox{id: "prep-cred", workspace: firstRoot},+ slots: make(chan struct{}, 1),+ workspace: firstRoot,+ credentials: RunCredentials{Extra: map[string]string{"gateway": "user-first"}},+ }+ wf := credentialWorkflow("mkdir -p .agentflow/prep; printf '%s' \"$MY_TOOL_TOKEN\" > .agentflow/prep/token")+ if _, err := EnsureWorkspacePreparation(ctx, sb, wf, nil, nil); err != nil {+ t.Fatal(err)+ }+ first, err := os.ReadFile(filepath.Join(sb.Workspace(), ".agentflow", "prep", "token"))+ if err != nil || string(first) != "user-first" {+ t.Fatalf("first run token = %q (err %v), want user-first", first, err)+ }++ archive, err := CreateWorkspaceCheckpoint(sb.Workspace())+ if err != nil {+ t.Fatal(err)+ }+ root := filepath.Join(t.TempDir(), "restored")+ if err = RestoreWorkspaceCheckpoint(root, archive); err != nil {+ t.Fatal(err)+ }+ // The host process carries its own MY_TOOL_TOKEN; the replay must neither+ // leak it into the script nor let it stand in for the user credential.+ t.Setenv("MY_TOOL_TOKEN", "host-owned-value")+ restored := &managedSandbox{+ Sandbox: &localSandbox{id: "restored", workspace: root},+ slots: make(chan struct{}, 1),+ workspace: root,+ credentials: RunCredentials{Extra: map[string]string{"gateway": "user-second"}},+ }+ if _, err = EnsureWorkspacePreparation(ctx, restored, wf, nil, nil); err != nil {+ t.Fatal(err)+ }+ second, err := os.ReadFile(filepath.Join(root, ".agentflow", "prep", "token"))+ if err != nil || string(second) != "user-second" {+ t.Fatalf("replay token = %q (err %v), want user-second", second, err)+ }++ // A rebuilt environment whose user has not saved the declared credential+ // fails the preparation with the kind named instead of replaying with an+ // empty or host-owned variable.+ missingRoot := filepath.Join(t.TempDir(), "missing")+ if err := os.MkdirAll(missingRoot, 0o755); err != nil {+ t.Fatal(err)+ }+ missing := &managedSandbox{+ Sandbox: &localSandbox{id: "missing", workspace: missingRoot},+ slots: make(chan struct{}, 1),+ workspace: missingRoot,+ credentials: RunCredentials{},+ }+ if _, err = EnsureWorkspacePreparation(ctx, missing, wf, nil, nil); err == nil || !strings.Contains(err.Error(), "gateway") {+ t.Fatalf("missing credential error = %v, want failure naming gateway", err)+ }+}